@yudaocode/univer-docs 1.6.210 → 1.6.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ # Word Template Protocol Specification (v1)
2
+
3
+ This document defines the canonical cross-language (`TypeScript` & `Java`) contract for **Univer Docs `IDocumentData` Word templates**: character stream layout, structural index invariants, inline field tokens, `<w:sdt>` Structured Document Tag (SDT) controls, single-level detail table row loops (`tableRowLoops`), idempotent filled-snapshot reuse in read-only viewers and `.docx` encoding, and OOXML `.docx` round-trip metadata.
4
+
5
+ Golden cross-language test vectors conforming to this specification are published in [`fixtures/word-template-protocol-v1.json`](./fixtures/word-template-protocol-v1.json).
6
+
7
+ ---
8
+
9
+ ## 1. `IDocumentData` Core Layout & Structural Invariants
10
+
11
+ A Univer Docs document (`IDocumentData`) stores rich content across a primary `body` story plus optional `headers[segmentId]` and `footers[segmentId]` stories, paired with top-level `tableSource`, `drawings`, `documentStyle`, and `resources`.
12
+
13
+ ### 1.1 `dataStream` Control Characters (`DataStreamTreeTokenType`)
14
+
15
+ Every story (`body`, `headers[id].body`, `footers[id].body`) encodes text and structural sentinels in a single UTF-16 `dataStream` string:
16
+
17
+ | Token | Escape / Hex | Code Point | Meaning |
18
+ | :--- | :--- | :--- | :--- |
19
+ | `TAB` | `\t` (`\u0009`) | `0x09` | Inline horizontal tab (`<w:tab/>`) |
20
+ | `SECTION_BREAK` | `\n` (`\u000A`) | `0x0A` | Story / cell section sentinel (always paired with `sectionBreaks[]`) |
21
+ | `PAGE_BREAK` | `\f` (`\u000C`) | `0x0C` | Hard page break (`<w:br w:type="page"/>`) |
22
+ | `PARAGRAPH` | `\r` (`\u000D`) | `0x0D` | Paragraph break sentinel (always paired 1:1 with `paragraphs[]`) |
23
+ | `CUSTOM_BLOCK` | `\u0016` | `0x16` | Inline drawing / image / note anchor (`customBlocks[]`) |
24
+ | `TABLE_START` | `\u001A` | `0x1A` | Start of table block |
25
+ | `TABLE_ROW_START` | `\u001B` | `0x1B` | Start of table row (`<w:tr>`) |
26
+ | `TABLE_CELL_START` | `\u001C` | `0x1C` | Start of table cell (`<w:tc>`) |
27
+ | `TABLE_CELL_END` | `\u001D` | `0x1D` | End of table cell (`</w:tc>`) |
28
+ | `TABLE_ROW_END` | `\u001E` | `0x1E` | End of table row (`</w:tr>`) |
29
+ | `TABLE_END` | `\u001F` | `0x1F` | End of table block (`</w:tbl>`) |
30
+
31
+ ### 1.2 Mandatory Offset & Structural Invariants
32
+
33
+ Both TypeScript (`fillDatasetIntoDocSnapshot`) and Java template compilers MUST preserve the following invariants on every story (`body`, `headers[*]`, `footers[*]`):
34
+
35
+ 1. **Story Termination**: The main `body.dataStream` ends with `\r\n` (at least one `\r` paragraph break followed by the trailing `\n` section break).
36
+ 2. **Strict 1:1 `\r` <-> `paragraphs[]` Mapping**:
37
+ - Every `\r` (`0x0D`) character in `dataStream` MUST have **exactly one** corresponding `IParagraph` entry in `paragraphs[]` whose `startIndex` equals the exact UTF-16 index of that `\r`, sorted in strictly ascending `startIndex` order.
38
+ - Multi-line text inside a paragraph or table cell MUST normalize `\r\n` and `\n` to `\r` (never raw `\n`, which is reserved for `SECTION_BREAK`) and MUST emit an `IParagraph` entry for **every** `\r`.
39
+ 3. **Strict 1:1 `\n` <-> `sectionBreaks[]` Mapping**:
40
+ - Every `\n` (`0x0A`) character in `dataStream` MUST have a corresponding `ISectionBreak` entry in `sectionBreaks[]` at `startIndex`, sorted in ascending order.
41
+ - Every table cell closes with `\r\n\u001D` (`PARAGRAPH` + `SECTION_BREAK` + `TABLE_CELL_END`).
42
+ 4. **Table Spans & `tableSource` Synchronization**:
43
+ - Each entry in `body.tables[]` has `{ tableId, startIndex, endIndex }` where `dataStream[startIndex] === '\u001A'` (`TABLE_START`) and `endIndex` is **exclusive** (`dataStream[endIndex - 1] === '\u001F'`, `TABLE_END`).
44
+ - `snapshot.tableSource[tableId]` holds column widths (`tableColumns`) and row/cell layout (`tableRows`), where `tableSource[tableId].tableRows.length` MUST equal the number of `\u001B...\u001E` rows in `body.dataStream` for that table, and every `<w:tbl>` MUST have **at least 1 row** (`rowCount >= 1`).
45
+ 5. **Custom Ranges (`customRanges[]`) & Text Runs (`textRuns[]`)**:
46
+ - `ICustomRange` uses **inclusive** bounds `[startIndex, endIndex]` (`dataStream.slice(startIndex, endIndex + 1)`).
47
+ - `ITextRun` uses **half-open** bounds `[st, ed)` (`ed > st`, sorted by `st` ascending).
48
+ - Any splice at `[oldStart, oldEndExclusive)` with delta `newLen - oldLen` MUST shift all downstream `paragraphs`, `sectionBreaks`, `textRuns`, `customRanges`, `customBlocks`, and `tables` at `>= oldEndExclusive` by `+delta` (and adjust enclosing ranges whose `startIndex < oldStart && endIndex >= oldEndExclusive`).
49
+ 6. **Template Metadata Resource (`YUDAO_DOCS_TEMPLATE_RESOURCE`)**:
50
+ - Template metadata is stored in `IDocumentData.resources[]` under `{ id: "YUDAO_DOCS_TEMPLATE_RESOURCE", name: "YUDAO_DOCS_TEMPLATE_RESOURCE", data: JSON.stringify(metadata) }`.
51
+
52
+ ---
53
+
54
+ ## 2. Field Bindings: Inline Tokens & SDT Controls
55
+
56
+ Data payloads are JSON objects (`Record<string, unknown>`). Nested property paths (`a.b.c` and bracket indices `a[0].b`) are resolved via `resolvePathValue(source, path)`, checking exact literal keys on `source` first before dot/index traversal.
57
+
58
+ ### 2.1 Inline Value Tokens
59
+
60
+ Inline expressions are supported across `body`, `headers`, `footers`, and table cells:
61
+
62
+ - **Dollar syntax**: `${field}`, `${set.field}`, `${nested.path.field}`
63
+ - **Hash syntax**: `#{field}`, `#{set.field}`, `#{nested.path.field}`
64
+ - **Explicit list-item syntax** (inside detail table rows or paragraph loops): `${#listKey.field}`, `#{#listKey.field}`
65
+ - **1-based row sequence token** (inside detail table rows or paragraph loops): `${listKey._index}`, `#{listKey._index}`, `${#listKey._index}`, `#{#listKey._index}`, and (when explicit `listKey` is bound on the row) `${_index}`, `#{_index}`
66
+
67
+ Outside loop rows, scalar values (`string | number | boolean`) replace the token span while preserving surrounding run styles; unresolved scalar tokens outside explicit loop rows remain untouched.
68
+
69
+ ### 2.2 Structured Document Tag (`<w:sdt>`) Controls
70
+
71
+ SDT controls live in `story.customRanges[]` with `rangeType = 7` (`CustomRangeType.SDT`):
72
+
73
+ ```json
74
+ {
75
+ "rangeId": "sdt_contract_no",
76
+ "rangeType": 7,
77
+ "startIndex": 5,
78
+ "endIndex": 14,
79
+ "wholeEntity": false,
80
+ "properties": {
81
+ "kind": "text",
82
+ "yudaoKind": "text",
83
+ "placement": "inline",
84
+ "alias": "合同编号",
85
+ "tag": "contractNo",
86
+ "lock": "sdtLocked",
87
+ "showingPlaceholder": true,
88
+ "placeholder": "【请输入合同编号】",
89
+ "required": true,
90
+ "bindingPath": "contract.no",
91
+ "sdtValue": "",
92
+ "dataBinding": {
93
+ "storeItemID": "yudao-dataset-store",
94
+ "xpath": "contract.no"
95
+ }
96
+ }
97
+ }
98
+ ```
99
+
100
+ - **Binding Resolution Order**: `properties.bindingPath` -> `properties.dataBinding.xpath` -> `properties.tag` (`resolvePathValue(data, key) ?? data[tag]`).
101
+ - **Clean Filled Chrome Rule**:
102
+ - In template design mode (`showingPlaceholder: true`), unset `visualChrome` displays soft editor placeholder shading (`#f3f5ff` / `#eeeff1` background, `#7d8698` placeholder text) so authors can locate empty slots.
103
+ - When `fillDatasetIntoDocSnapshot` fills an SDT with a non-empty value (`showingPlaceholder: false`), editor placeholder shading MUST be stripped unless `properties.visualChrome === "highlight"` was explicitly configured. `visualChrome: "underline"` renders a bottom border (`ul: { s: 1 }`), `"brackets"` wraps with `prefix` / `postfix` (`【...】`), and `"clean"` (or unset `visualChrome` once filled) renders clean body typography without background shading in both read-only Univer preview and exported `.docx`.
104
+
105
+ ---
106
+
107
+ ## 3. Single-Level `tableRowLoops` Expansion Protocol
108
+
109
+ ### 3.1 Configuration Schema
110
+
111
+ Row loop bindings are stored in `YUDAO_DOCS_TEMPLATE_RESOURCE` under `metadata.tableRowLoops`, keyed by `"${tableId}:${rowIndex}"`:
112
+
113
+ ```ts
114
+ export type DocEmptyRowStrategy = 'keep-blank' | 'remove' | 'placeholder';
115
+
116
+ export interface IDocTableRowLoopConfig {
117
+ tableId: string;
118
+ /** 0-based template row index in the table */
119
+ rowIndex: number;
120
+ /** Top-level or dotted array path in `data`, e.g. `"items"` or `"order.items"` */
121
+ listKey: string;
122
+ /** Repeat header rows `0 .. rowIndex - 1` across pages (`<w:tblHeader/>`). Default: `true` */
123
+ repeatHeaderRow?: boolean;
124
+ /** Behavior when resolved list has 0 items. Default: `'keep-blank'` */
125
+ emptyStrategy?: DocEmptyRowStrategy;
126
+ /** Cell 0 text when `emptyStrategy === 'placeholder'`. Default: `'暂无明细数据'` */
127
+ emptyPlaceholderText?: string;
128
+ }
129
+ ```
130
+
131
+ ### 3.2 Deterministic Processing Order & Rules
132
+
133
+ 1. **Bottom-to-Top Traversal**:
134
+ - Tables in `body.tables` are processed from `tables.length - 1` down to `0`.
135
+ - Within each table, rows are processed from `parsedRows.length - 1` down to `0`, tracking `remainingRowCount` initialized to `parsedRows.length`.
136
+ 2. **`listKey` Detection & Nested Resolution**:
137
+ - Use `explicitCfg.listKey` if configured on `${tableId}:${rIdx}`.
138
+ - Otherwise auto-detect from `${#listKey.field}` / `#{#listKey.field}` tokens, dotted `${set.field}` / `#{set.field}` tokens where `Array.isArray(resolvePathValue(data, set))`, or SDT `bindingPath` / `tag` prefixes inside the row where `Array.isArray(resolvePathValue(data, candidatePrefix))` is `true`.
139
+ - Resolve list items via `rawItems = resolvePathValue(data, detectedListKey) ?? data[detectedListKey]`. Any `null`, `undefined`, or non-array value is treated as `[]`.
140
+ 3. **`repeatHeaderRow` Semantics**:
141
+ - When `explicitCfg?.repeatHeaderRow === false`: set `tableSource[tableId].tableRows[h].repeatHeaderRow = 0` (`BooleanNumber.FALSE`) for `0 <= h < Math.max(1, rIdx)`, and delete `metadata.tableRepeatHeaders[tableId]`. Exported `.docx` MUST NOT emit `<w:tblHeader/>` on that table.
142
+ - When `repeatHeader` is `true` (`explicitCfg?.repeatHeaderRow ?? true`) and `rIdx > 0`: set `tableSource[tableId].tableRows[h].repeatHeaderRow = 1` (`BooleanNumber.TRUE`) for all header rows `0 <= h < rIdx` (and `isFirstRow = 1` on row `0`).
143
+ 4. **Empty List Strategies (`items.length === 0`)**:
144
+ - `'remove'`: If `remainingRowCount > 1`, splice out the row from `body.dataStream` and `tableSource[tableId].tableRows`, shift all downstream offsets by `-removedLen`, and decrement `remainingRowCount`. **Safety fallback**: if `remainingRowCount <= 1` (e.g., a 1-row table or all rows in the table are empty `'remove'` loop rows), fall back to `'keep-blank'` (1 blank row) so `<w:tbl>` never ends up with 0 rows.
145
+ - `'placeholder'`: Render 1 row (`itemObj = null`) where cell `0` contains `explicitCfg.emptyPlaceholderText || "暂无明细数据"` and cells `1 .. colCount - 1` contain `""`.
146
+ - `'keep-blank'`: Render 1 row (`itemObj = null`) where all loop tokens and loop SDTs resolve to `""`.
147
+ 5. **Cell Rendering (Inline Tokens + Nested SDTs)**:
148
+ - Inspect all SDTs (`CustomRangeType.SDT`) inside each template cell `[contentStart, textEndExclusive)` prior to expansion.
149
+ - Replace SDT spans whose `bindingPath` or `tag` starts with `${detectedListKey}.` (stripping `${detectedListKey}.`, resolving `_index` -> `String(rowSeqIndex + 1)` or `resolvePathValue(itemObj, subPath)`) or resolves directly on `itemObj` (falling back to scalar `resolvePathValue(rootData, ...)` or `""` when `itemObj === null`), formatted via `formatSdtDisplayText` and flattened into plain cell text (preserving cell typography while stripping `#f3f5ff` / `#eeeff1` / `#7d8698` / `#9ca3af` editor chrome).
150
+ - Replace inline tokens via `replaceRowCellTokens`, supporting `${listKey.field}`, `#{listKey.field}`, `${#listKey.field}`, `#{#listKey.field}`, `${listKey._index}`, `#{listKey._index}`, and — when explicit `listKey` is configured — unqualified `${field}`, `#{field}`, `${_index}`, `#{_index}` (falling back to scalar `resolvePathValue(rootData, ...)` when not found on `itemObj`, or `""` when `itemObj === null`).
151
+ 6. **Deterministic Paragraph & Section IDs**:
152
+ - For `cloneIdx === 0`, preserve the template cell's existing `paragraphId` and `sectionId` when single-line.
153
+ - For `cloneIdx > 0` (or additional multi-line `\r` splits), emit deterministic IDs:
154
+ - Single-line cell paragraph: `p_loop_${tableId}_r${rIdx}_${cloneIdx}_c${cIdx}`
155
+ - Multi-line cell paragraphs: `p_loop_${tableId}_r${rIdx}_${cloneIdx}_c${cIdx}_m${lineIdx}`
156
+ - Cell section break: `s_loop_${tableId}_r${rIdx}_${cloneIdx}_c${cIdx}`
157
+ - Cloned `tableSource[tableId].tableRows` entries set `repeatHeaderRow = 0` and `isFirstRow = (rIdx === 0 && cloneIdx === 0) ? 1 : 0`.
158
+
159
+ ---
160
+
161
+ ## 4. Idempotency, Read-Only Viewer Reuse, & `.docx` Round-Trip
162
+
163
+ ### 4.1 Idempotent Filled Snapshot & Direct `exportDocxBytes(filledSnapshot)`
164
+
165
+ After `fillDatasetIntoDocSnapshot(templateSnapshot, data)` expands `tableRowLoops`, all consumed `"${tableId}:${rowIndex}"` entries are **removed** from `YUDAO_DOCS_TEMPLATE_RESOURCE.tableRowLoops` on the returned `filledSnapshot`:
166
+
167
+ - **Read-Only Viewer**: `filledSnapshot` can be mounted directly into Univer Docs with `mode: 'view'` (`disabled: true`) — displaying clean filled values and expanded rows with zero placeholder shading.
168
+ - **Zero-Refill `.docx` Export**: Passing `filledSnapshot` directly to `exportDocxBytes(filledSnapshot)` (with **no** second `data` argument) encodes the already-filled document into a standard `.docx` archive without re-running dataset fill or double-expanding row 1.
169
+ - **Idempotency**: Calling `fillDatasetIntoDocSnapshot(filledSnapshot, data)` a second time is a deterministic no-op (`deepEqual(filledSnapshot)`).
170
+
171
+ ### 4.2 `.docx` Template Metadata Round-Trip (`docProps/yudao-meta.json`)
172
+
173
+ When exporting an **unfilled template** `IDocumentData` to `.docx` via `exportDocxBytes(templateSnapshot)`:
174
+
175
+ - `docProps/yudao-meta.json` persists `tableOrder` (`body.tables.map(t => t.tableId)`), `tableRowLoops`, and `tableRepeatHeaders` alongside `<w:sdt>` OOXML tags (`<w:alias>`, `<w:tag>`, `<w:lock>`, `<w:dataBinding w:xpath="..."/>`) and `<w:tblHeader/>`.
176
+ - On `parseDocxBytesWithReport(docxBytes)`, `oldTableOrder[idx]` is mapped to the newly parsed `docData.body.tables[idx].tableId` (`oldToNewTblId`), remapping `"${oldTblId}:${rowIndex}"` -> `"${newTblId}:${rowIndex}"` in `tableRowLoops` and `"${oldTblId}"` -> `"${newTblId}"` in `tableRepeatHeaders` inside `YUDAO_DOCS_TEMPLATE_RESOURCE`.