@nextgensoftwares/folio-model
Document model: ProseMirror-shaped JSON, schemas, validation. DOM-free, no dependencies. Guide: Document model & schema.
Node types
type Attrs = Record<string, unknown>;
interface Mark { type: string; attrs?: Attrs }
interface FolioNode { type: string; attrs?: Attrs; content?: FolioNode[]; text?: string; marks?: Mark[] }
interface FolioDocument extends FolioNode { type: 'doc'; content: FolioNode[] }
type NodePath = readonly number[];| Export | Signature | Description |
|---|---|---|
isTextNode | (node: FolioNode) => boolean | node.type === 'text' |
attr | <T>(node: FolioNode, name: string, fallback: T) => T | attribute value, or fallback when undefined/null |
nodeAt | (root: FolioNode, path: NodePath) => FolioNode | undefined | follow a child-index path |
textContent | (node: FolioNode) => string | concatenated text; inline atoms and hard breaks contribute nothing |
marksEqual | (a?: readonly Mark[], b?: readonly Mark[]) => boolean | same mark types and attrs, in order |
Schema
interface AttrSpec { default?: unknown; validate?: (value: unknown) => boolean } // no default = required
interface NodeSpec {
group?: string; content?: string; inline?: boolean; atom?: boolean;
marks?: string; // '_' all (textblock default), '' none, or space-separated names
code?: boolean; // preformatted, no marks
ownSelection?: boolean; // a plugin draws this node's selection (views paint no node highlight)
attrs?: Record<string, AttrSpec>;
}
interface MarkSpec { attrs?: Record<string, AttrSpec>; excludes?: string }
interface GlobalAttrs { types: string[]; attrs: Record<string, AttrSpec> }
interface SchemaSpec { nodes: Record<string, NodeSpec>; marks: Record<string, MarkSpec>; globalAttrs?: GlobalAttrs[]; topNode?: string }
interface ResolvedNodeSpec extends NodeSpec { name: string; attrs: Record<string, AttrSpec>; contentExpr: ContentExpr; isTextblock: boolean }class Schema
| Member | Description |
|---|---|
new Schema(spec: SchemaSpec) | resolves global attrs into each node, parses content expressions, computes isTextblock; throws if topNode (default 'doc') is missing |
spec, nodes: Map<string, ResolvedNodeSpec>, marks: ReadonlyMap<string, MarkSpec>, topNode | the resolved schema |
extend(extra: Partial<SchemaSpec>): Schema | a new schema with extra nodes, marks and global attrs (host extensions) |
node(name) | resolved node spec or undefined |
fits(childType, name) | does a node of childType satisfy the name-or-group name? |
matches(parentType, childTypes) | { ok, failedAt } against the parent's content expression |
allowsMark(parentType, markType) | mark allowed inside this parent (never in code nodes) |
withDefaults(specAttrs?, attrs?) | default-filled attrs; unknown attrs kept untouched |
standardSchema
The built-in node and mark set (StarterKit + tables + code + math + media + text styles, plus Word pagination attrs). See the full list.
ListLevel, isListLevel(value): a list's own marker definition (the listLevel attr on bulletList/orderedList: format, template text, font, colour, size, bold, picture bullet, indent, hanging, align, suffix (tab: text a marker overruns moves to the next tab stop, Word's default; nothing: it starts right after the marker, as PowerPoint draws bullets); see the schema) and its validator (rejects unknown keys and javascript: images).
LIST_STYLE_TYPES: the accepted listStyleType values (disc, circle, square, decimal, decimal-leading-zero, lower-alpha, upper-alpha, lower-latin, upper-latin, lower-roman, upper-roman, lower-greek, none).
FONT_VARIANTS: the accepted textStyle fontVariant values (small-caps, all-small-caps); see caps and letter spacing.
FONT_WEIGHTS, FONT_STYLES: the accepted textStyle fontWeight (100…900 in steps of 100, numbers) and fontStyle (normal, italic) values. They set a run's weight and slant against its block's, e.g. a regular run in a bold heading; bold / italic marks win over them.
LEADINGS: the accepted paragraph/heading leading values (split, below, above), the block's own line model over the theme's (see document model).
TAB_ALIGNS, TAB_LEADERS, tabStopsAttr: the accepted tabStops alignments (left, center, right, decimal) and leaders (none, dot, hyphen, underscore, middleDot), and the attr spec validating paragraph/heading tabStops ([{ pos, align?, leader? }], at most 64). Tabs themselves are \t characters in text.
Paragraph borders and shading (Word's w:pBdr / w:shd): paragraphs and headings declare borders ({ top?, bottom?, left?, right?, between? }, each { style: 'single' | 'double' | 'dashed' | 'dotted' | 'none', width, color, space } with px lengths) and shading ({ fill?, pattern?: 'solid' | 'pctNN' | 'clear', color? }). Plain JSON. Consecutive paragraphs with equal borders, shading, indents and direction share one box: the top border on the first, between rules between them, the bottom border on the last; a box cut by a page break has no rule at the cut. Borders sit space px outside the text, which keeps its width.
resizableMedia declares naturalWidth/naturalHeight (intrinsic px, so layout needs no image fetch) and name (file name), which imports write; Folio's own import output passes validate and fromProseMirrorJson with onUnknown: 'reject'.
WRAP_MODES: the accepted media wrap values (inline, square, topBottom, behind, front). resizableMedia also declares distT, distB, distL, distR (px, 0–480), offsetX, offsetY (px, ±4000) and anchor (paragraph | margin); see Media ▸ Size and placement.
Content expressions
interface ContentTerm { names: string[]; min: number; max: number }
type ContentExpr = ContentTerm[];| Export | Signature | Description |
|---|---|---|
parseContentExpr | (source: string) => ContentExpr | "paragraph block*", "(tableCell|tableHeader)*"; throws on bad syntax |
matchContent | (expr, childTypes, fits) => { ok: boolean; failedAt: number } | greedy, non-backtracking match; failedAt is the first child that doesn't fit (-1 if all match) |
Validation
interface ValidationIssue { path: NodePath; message: string }| Export | Signature | Description |
|---|---|---|
validate | (root: FolioNode, schema: Schema) => ValidationIssue[] | unknown types and marks, missing/invalid attrs, content mismatches, disallowed marks, empty text nodes. Never throws |
normalize | <T extends FolioNode>(node: T, schema: Schema) => T | cleaned copy: defaults filled, empty text dropped, equal-mark text merged, disallowed marks removed |
omitDefaults | <T extends FolioNode>(node: T, schema: Schema) => T | the opposite, for storage: attrs that are null or equal to their schema default removed from nodes and marks (the editor and plugins write every declared attr). Unknown attrs kept; unchanged subtrees keep their identity. canonicalJson(json, { schema }) also ignores defaults when comparing |
sanitizeDocTheme, isDocTheme, DOC_THEME_ATTR | (raw: unknown) => DocTheme | null, (v) => boolean, 'theme' | a document's own theme (doc.attrs.theme): known Theme fields only, numbers clamped, colours and font stacks checked; isDocTheme is the schema validator (null, or exactly what the sanitizer stores) |
Block ids
Every block type (not inline, not the top node) declares an optional id (BLOCK_ID_ATTR, spec BLOCK_ID_SPEC: null or a non-empty string), host types from schema.extend() included, so ids survive the editor, sync and exports. Heading ids are also PDF named destinations (#id links, outline).
| Export | Signature | Description |
|---|---|---|
blockIdOf | (node) => string | null | a node's id |
hasBlockId | (schema, type) => boolean | can this type carry an id |
blockById | (doc, id) => { node, path } | null | first block with this id (O(blocks)) |
pathOfBlockId / blockIdAt | (doc, id) => number[] | null / (doc, path) => string | null | path ↔ id |
indexBlockIds | (doc) => Map<string, number[]> | every id → path of its first occurrence |
ensureBlockIds | <T>(doc: T, { seed, schema?, generate? }: EnsureBlockIdsOptions) => T | gives every id-capable block an id: existing ids kept (later duplicates renamed), missing ones generate(path, seed, attempt) (default defaultBlockId: hashId(seed/path)). Pure, deterministic per seed, idempotent (returns the same object), unchanged subtrees keep their identity |
hashId | (s: string) => string | 12-character base32 id (60 bits) from a string; same on every platform |
randomBlockId | (length = 12) => string | a fresh random id (editor-minted) |
Text effects
The text outline and text shadow of a run live in its textStyle mark, as CSS-like strings:
textOutline:"1.5px #c00000", optionally with a DrawingML preset dash after the colour ("1.5px #c00000 sysDot";textOutlineCssdrops it for CSS's-webkit-text-stroke);textShadow:"2px 2px 3px #00000066".
The DOM, canvas and PDF painters draw the shadow under the glyphs and the outline over their fill.
| Export | Description |
|---|---|
textEffectsOf(marks) | { outline: TextOutline | null, shadow: TextShadow | null } of a run's marks |
TextOutline, TextShadow | { width, color, dash? }; { dx, dy, blur, color } (px, CSS colours) |
textOutlineDash(outline) | the dash pattern in px (a:prstDash lengths × width), or null for solid; canvas and PDF painters stroke with it |
parseTextOutline(v), parseTextShadow(v), formatTextOutline(o), formatTextShadow(s) | to and from the attribute strings |
Text search
The matching every Folio search shares (the reader's find, the editors' find and replace, slides, host server search), DOM-free. Arabic-aware by default: diacritics (tashkeel), tatweel and Quranic marks are ignored and letter variants fold (أ إ آ ٱ → ا, ى → ي, ة → ه, ؤ → و, ئ → ي); matches map back to offsets in the original text, and a match takes the marks on its last letter.
| Export | Signature | Description |
|---|---|---|
TextSearchOptions | { caseSensitive?, loose?, wholeWord?, regex? } | loose (default true) is the Arabic folding; wholeWord: no letter, digit or mark right before or after; regex: a JavaScript regular expression (letters in it fold too when loose) |
compileTextQuery | (query, opts?) => TextMatcher | null | compile once, match many texts; null for an empty query; throws TextQueryError for a regex that doesn't parse |
TextMatcher | { query, options, find(text, limit?) => [from, to][] } | non-overlapping matches in order (empty regex matches are skipped) |
TextQueryError | class extends Error | the regex's parse error message |
findInText | (text, query, opts?, limit?) => [from, to][] | one-off search (invalid regex → no matches) |
normalizeSearchText | (text, { caseSensitive?, loose? }) => { text, map } | the folded text and, per folded char, its source index (plus the source length) |
searchSnippet | (text, from, to, radius = 40) => string | a one-line context for result lists (… at cut ends; U+FFFC objects as spaces) |
searchContext | (text, from, to, radius = 40) => { before, match, after } | the same, split so lists can bold the match |
Spelling (shared by the document and slide editors)
| Export | Signature | Description |
|---|---|---|
SpellChecker | (words, lang) => (string[] | null)[] | Promise<…> | the host's checker: per word (in lang, BCP 47; '' when the text says none) null when right, else suggestions |
spellWords, SpellToken | (text, lang?) => { from, to, word }[] | the words worth checking, segmented the way the language breaks words (Intl.Segmenter); one-letter words, words with digits, words in capitals (caseless scripts always checked), identifiers (camelCase, snake_case) and anything in a link or email address left out |
SpellCache | class | one per document or deck: the checker's answers per language and word (get), ignored (Ignore All: ignore(word)), dictionary (setDictionary(words)), accepts(word), on (setOn), subscribe, emit, gen (counts changes) |
SpellDictionary | { words, onAdd?, onRemove? } | a host's own dictionary, controlled: its words are right (a lowercase entry matches any case); Add to Dictionary calls onAdd, the Spelling pane's Remove onRemove |
checkSpellWords | (words: { word, lang }[], check, cache) => Promise<(T & { suggestions })[]> | asks the checker only about words the cache hasn't seen; returns the misspelled ones |
squiggleRect | (rect, thickness = 4) => rect | the squiggle band under a word's box, keeping its matrix (rotated text) |
Suggestion marks
| Export | Type | Description |
|---|---|---|
SUGGEST_INSERT, SUGGEST_DELETE | 'suggestInsert', 'suggestDelete' | track-changes marks (@nextgensoftwares/folio-plugin-suggest adds them to the schema) |
SuggestionAttrs, SuggestionKind | { id, author, authorName, time }, 'insert' | 'delete' | their attrs (time: ms since the epoch) |
suggestColor | (author) => string | the author's stable #rrggbb |
suggestionLook | (marks) => { insert, delete, color } | null | how painters draw a run: underlined (insert), struck through (delete), in the latest author's colour (a deletion's over an insertion's) |
Word count
| Export | Type | Description |
|---|---|---|
numberEquations | (doc, numbering?: EquationNumbering | false) => FolioDocument | the document with its display equations numbered, for drawing (layout and exportDocx call it): numbered LaTeX environments without a \tag get (1), (2)… in reading order, written as \tag*{…} in a copy of their mathBlock node. Blocks whose numbers didn't change are the same objects as on the last call (layout caches by identity), a document without numbered equations is returned as it is, and an already numbered document is unchanged. EquationNumbering: start? (default 1), within? (restart after headings of that level or above), format?(n, { section }); false: rows are told \notag |
equationCount | (doc | blocks) => number | how many automatic numbers a document takes: the next chapter of a book numbered through starts at start + equationCount(doc) |
countEquationNumbers, numberLatex | (latex) => number, (latex, label: (k) => string | null) => string | one equation's LaTeX: how many numbers it takes as LaTeX counts them, and the same source with row k's number written as \tag*{label(k)} (\notag for null; a blank last row after a trailing \\ takes none) |
countWords | (doc, { textBoxes?, headerFooter? }?) => WordCount | Word's statistics of a document, pure (no DOM): { words, characters, charactersNoSpaces, paragraphs } |
countNode | (node, opts?) => WordCount | the same for one node (a top-level block: hosts cache per block, nodes being immutable) |
countText | (text) => WordCount | one paragraph's text |
addCounts, ZERO_COUNT | summing counts |
Rules (Word's):
- Words split on whitespace only: "a/b", "self-management", "word—word" and URLs are one word each. A no-break space (U+00A0, U+202F, U+2007) joins, as in Word. Each Han ideograph or kana is a word; Arabic, Hebrew and Hangul split on spaces like Latin. Runs of one paragraph join (a bold suffix stays part of its word); paragraphs and table cells never join.
- Included: body text, tables, notes (Folio keeps footnotes and endnotes in the body), and with
textBoxes(default true, Word's "Include textboxes, footnotes and endnotes") the text of text boxes and shapes, through groups. - Left out: list numbers and bullets (generated, never text), headers and footers (unless
headerFooter: true), suggested deletions (insertions count), comments (kept outside the document). - Characters are counted in code points (an emoji is one), with spaces and without whitespace; paragraph marks, line breaks, pictures and equations aren't characters. Paragraphs are those holding text.