@quirekit/mind-map-docx 0.0.0-stage → 0.0.1-alpha.0

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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wang Yishuai (王一帅) and QuireKit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @quirekit/mind-map-docx
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](./README.zh-CN.md)
4
+
5
+ Includes mind maps in Word exports while preserving the data needed to edit them again in QuireKit.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @quirekit/mind-map-docx@alpha
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Register the conversion rules returned by `createMindMapDocxCodec()` in the DOCX conversion pipeline. Export needs object data and a displayable preview; import attempts to recover the data saved in the file.
16
+
17
+ ## Things to know
18
+
19
+ - The preview shown in Word is not a native editable Word object of the same kind. Other applications may discard attached data when resaving the file.
20
+ - This package handles one document object. Use Lit DOCX or Classic DOCX to read or generate a complete DOCX file.
21
+
22
+ ## Related documentation
23
+
24
+ - [Source data](../mind-map/README.md)
25
+ - [DOCX file I/O](../lit-docx/README.md)
26
+
27
+ ## License
28
+
29
+ [MIT](./LICENSE.md). Third-party notices: [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,29 @@
1
+ # @quirekit/mind-map-docx
2
+
3
+ [English](./README.md) | 简体中文
4
+
5
+ 让 思维导图可以随 Word 文档导出,并保留回到 QuireKit 后继续编辑所需的数据。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ npm install @quirekit/mind-map-docx@alpha
11
+ ```
12
+
13
+ ## 使用方式
14
+
15
+ 把 `createMindMapDocxCodec()` 创建的转换规则注册到 DOCX 转换流程。导出时需要对象数据和可显示的预览;导入时尝试恢复随文件保存的数据。
16
+
17
+ ## 使用时注意
18
+
19
+ - Word 里显示的预览不等于 Word 原生可编辑的同类对象。第三方软件重新保存文件后,也可能丢失附带的数据。
20
+ - 本包处理一种文档对象;读取或生成整个 DOCX 文件使用 Lit DOCX 或 Classic DOCX。
21
+
22
+ ## 相关说明
23
+
24
+ - [原始数据](../mind-map/README.zh-CN.md)
25
+ - [DOCX 文件读写](../lit-docx/README.zh-CN.md)
26
+
27
+ ## 许可
28
+
29
+ [MIT](./LICENSE.md);第三方声明见 [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md)。
@@ -0,0 +1,143 @@
1
+ # 第三方声明 / Third-party notices
2
+
3
+ QuireKit 的分层授权只适用于相应权利人有权授权的原创部分,不替代或限制以下上游
4
+ 材料的授权。独立第三方依赖及资源还可能有其自己的许可,分发包含它们的产物时必须
5
+ 继续履行相关义务。本文件不声称是全部运行时依赖或所有构建产物的完整 SBOM。
6
+
7
+ The project license does not replace or restrict the licenses of upstream code.
8
+ Third-party dependencies and resources retain their own terms. This file covers
9
+ recorded upstream foundations and is not a complete dependency or artifact SBOM.
10
+ A license below applies to its identified material, not to all QuireKit code.
11
+
12
+ ## QuireKit 原创部分 / Original work
13
+
14
+ Copyright (c) 2026 Wang Yishuai (王一帅) and QuireKit contributors
15
+
16
+ QuireKit 原创部分按包分为三层:MIT 生态层、GNU AGPL 第 3 版(仅此版本,`AGPL-3.0-only`)
17
+ 引擎层,以及 QuireKit 商业组件。每个包的许可以其包内 `LICENSE.md` 为准。以下第三方材料
18
+ 继续遵循其原有许可,不受上述任何一层影响。
19
+
20
+ QuireKit original work is licensed per package in three tiers: MIT, GNU AGPL
21
+ version 3 only (`AGPL-3.0-only`) and the QuireKit Commercial License. Each
22
+ package's `LICENSE.md` is authoritative. Third-party materials below retain their
23
+ own terms regardless of tier.
24
+
25
+ ## ProseMirror
26
+
27
+ The vendored ProseMirror packages retain their original MIT license files.
28
+ The following notices cover the respective upstream portions, including when
29
+ those portions are incorporated into a derived or bundled artifact.
30
+
31
+ ### @quirekit/pm-collab, @quirekit/pm-commands, @quirekit/pm-decoration, @quirekit/pm-gapcursor, @quirekit/pm-history, @quirekit/pm-inputrules, @quirekit/pm-keymap, @quirekit/pm-model, @quirekit/pm-schema-list, @quirekit/pm-state, @quirekit/pm-transform, @quirekit/pm-view
32
+
33
+ Copyright (C) 2015-2017 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
34
+
35
+ Permission is hereby granted, free of charge, to any person obtaining a copy
36
+ of this software and associated documentation files (the "Software"), to deal
37
+ in the Software without restriction, including without limitation the rights
38
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
39
+ copies of the Software, and to permit persons to whom the Software is
40
+ furnished to do so, subject to the following conditions:
41
+
42
+ The above copyright notice and this permission notice shall be included in
43
+ all copies or substantial portions of the Software.
44
+
45
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
48
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
50
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
51
+ THE SOFTWARE.
52
+
53
+ ## Tiptap
54
+
55
+ Upstream: https://github.com/ueberdosis/tiptap
56
+
57
+ The following notice applies to Tiptap-derived portions of the compatibility
58
+ layer and extensions, where present. It does not relicense QuireKit additions.
59
+
60
+ MIT License
61
+
62
+ Copyright (c) 2025, Tiptap GmbH
63
+
64
+ Permission is hereby granted, free of charge, to any person obtaining a copy
65
+ of this software and associated documentation files (the "Software"), to deal
66
+ in the Software without restriction, including without limitation the rights
67
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
68
+ copies of the Software, and to permit persons to whom the Software is
69
+ furnished to do so, subject to the following conditions:
70
+
71
+ The above copyright notice and this permission notice shall be included in all
72
+ copies or substantial portions of the Software.
73
+
74
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
75
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
76
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
77
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
78
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
79
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
80
+ SOFTWARE.
81
+
82
+ ## bidi-js
83
+
84
+ Upstream: https://github.com/lojjic/bidi-js
85
+
86
+ The renderer uses bidi-js; its code retains the following license.
87
+
88
+ Copyright (c) 2021 Jason Johnston
89
+
90
+ MIT License
91
+
92
+ Permission is hereby granted, free of charge, to any person obtaining
93
+ a copy of this software and associated documentation files (the
94
+ "Software"), to deal in the Software without restriction, including
95
+ without limitation the rights to use, copy, modify, merge, publish,
96
+ distribute, sublicense, and/or sell copies of the Software, and to
97
+ permit persons to whom the Software is furnished to do so, subject to
98
+ the following conditions:
99
+
100
+ The above copyright notice and this permission notice shall be
101
+ included in all copies or substantial portions of the Software.
102
+
103
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
104
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
105
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
106
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
107
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
108
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
109
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
110
+
111
+ ## Fonts and other resources
112
+
113
+ The font-pack wrapper has its own MIT license. Distributed font assets retain
114
+ their individual OFL or other license files under the font package's licenses
115
+ and dist/licenses directories. The wrapper license does not replace font terms.
116
+ Local system fonts served by development tooling receive no new redistribution
117
+ rights. Other dependencies, bundled resources and license comments retain their
118
+ own notices; those obligations must be checked against the actual artifact.
119
+
120
+ ## RevoGrid Community
121
+
122
+ The optional chart data editor loads `@revolist/revogrid` 4.28.2, MIT licensed.
123
+ Upstream: https://github.com/revolist/revogrid
124
+
125
+ Copyright (c) 2024 Revolist OU
126
+
127
+ Permission is hereby granted, free of charge, to any person obtaining a copy
128
+ of this software and associated documentation files (the "Software"), to deal
129
+ in the Software without restriction, including without limitation the rights
130
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
131
+ copies of the Software, and to permit persons to whom the Software is
132
+ furnished to do so, subject to the following conditions:
133
+
134
+ The above copyright notice and this permission notice shall be included in
135
+ all copies or substantial portions of the Software.
136
+
137
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
138
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
139
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
140
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
141
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
142
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
143
+ THE SOFTWARE.
@@ -0,0 +1,28 @@
1
+ import { DocxAuthoringApi, DocxCodecDiagnosticInput, LitAstNode } from "@quirekit/lit-docx-contract";
2
+ import { MindMapEmbed } from "@quirekit/mind-map";
3
+ import { DocxJsonMark, DocxJsonNode } from "@quirekit/docx";
4
+
5
+ //#region src/types.d.ts
6
+ /** Optional source policy; saved images always remain visible in Word. */
7
+ interface MindMapDocxOptions {
8
+ /** Retain source when it fits the existing metadata budget; default true. */
9
+ readonly metadata?: boolean;
10
+ }
11
+ //#endregion
12
+ //#region src/codec.d.ts
13
+ /** @param options - Optional source recovery. @returns One feature codec shared by Classic and Core/Block document managers. */
14
+ declare function createMindMapDocxCodec<ModelNode extends Pick<DocxJsonNode, "attrs"> = DocxJsonNode, ModelMark = DocxJsonMark>(options?: MindMapDocxOptions): import("@quirekit/lit-docx-contract").DocxNodeCodec<ModelNode, ModelMark>;
15
+ //#endregion
16
+ //#region src/projection.d.ts
17
+ /** One versioned tag shared by PM and Markdown consumers. */
18
+ declare const mindMapDocxTag = "quirekit:mind-map:1";
19
+ /** @param input - Saved source and matching preview. @param api - Central Word authoring facade.
20
+ * @param report - Operation-local diagnostics. @param options - Optional recovery policy.
21
+ * @returns Visible Word content with bounded optional source recovery. */
22
+ declare function projectMindMap(input: unknown, api: DocxAuthoringApi, report: (diagnostic: DocxCodecDiagnosticInput) => void, options: MindMapDocxOptions): LitAstNode;
23
+ /** @param node - Current tagged control. @param api - Fingerprint-aware metadata reader.
24
+ * @returns Valid editable source, or null to retain current Word content. */
25
+ declare function recoverMindMap(node: LitAstNode, api: DocxAuthoringApi): MindMapEmbed | null;
26
+ //#endregion
27
+ export { type MindMapDocxOptions, createMindMapDocxCodec, mindMapDocxTag, projectMindMap, recoverMindMap };
28
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/codec.ts","../src/projection.ts"],"mappings":";;;;;;UACiB,kBAAA;;WACwE,QAAQ;AAAA;;;;iBCIjF,sBAAA,mBAAyC,IAAA,CAAK,YAAA,aAAyB,YAAA,cAA0B,YAAA,EAAc,OAAA,GAAS,kBAAA,yCAAuB,aAAA,CAAA,SAAA,EAAA,SAAA;;;;cCClJ,cAAA;AFNb;;;AAAA,iBEiBgB,cAAA,CAAe,KAAA,WAAgB,GAAA,EAAK,gBAAA,EAAkB,MAAA,GAAS,UAAA,EAAY,wBAAA,WACzF,OAAA,EAAS,kBAAA,GAAqB,UAAA;AFjBiE;;AAAA,iBEoDjF,cAAA,CAAe,IAAA,EAAM,UAAA,EAAY,GAAA,EAAK,gBAAA,GAAmB,YAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,180 @@
1
+ import { docx } from "@quirekit/lit-docx-contract";
2
+ import { createQuireInlineImageResolver } from "@quirekit/media";
3
+ import { mindMapAnnotationTopics, parseMindMapEmbed, readMindMapEmbed, serializeMindMapEmbed } from "@quirekit/mind-map";
4
+ //#region src/outline.ts
5
+ /** @param mind - Validated source without a raster. @param api - Central Word authoring facade.
6
+ * @returns Complete topic text, including folded descendants and separate free trees. */
7
+ function projectMindMapOutline(mind, api) {
8
+ const blocks = [];
9
+ const names = /* @__PURE__ */ new Map();
10
+ /** @param text - Literal visible paragraph text. */
11
+ function paragraph(text) {
12
+ blocks.push(api.blocks.paragraph({ children: [api.inline.text(text)] }));
13
+ }
14
+ /** @param node - Current immutable topic. @param depth - Source hierarchy depth, bounded by the model. */
15
+ function visit(node, depth) {
16
+ names.set(node.id, node.text);
17
+ paragraph(`${" ".repeat(depth)}${depth ? "• " : ""}${node.text}`);
18
+ const details = node.details;
19
+ if (details?.link) paragraph(`链接:${details.link}`);
20
+ if (details?.note) paragraph(`备注:${details.note}`);
21
+ if (details?.marker) paragraph(`优先级:${details.marker.slice(-1)}`);
22
+ if (details?.image) paragraph(`图片:${details.image.alt || "主题图片"}`);
23
+ node.children.forEach((child) => visit(child, depth + 1));
24
+ }
25
+ paragraph(`思维导图:${mind.title}`);
26
+ visit(mind.document.root, 0);
27
+ for (const topic of mind.document.floatingTopics ?? []) {
28
+ paragraph("自由主题");
29
+ visit(topic.root, 0);
30
+ }
31
+ const labels = {
32
+ relation: "关联",
33
+ summary: "概要",
34
+ boundary: "外框"
35
+ };
36
+ for (const item of mind.document.annotations ?? []) {
37
+ const members = mindMapAnnotationTopics(item).map((id) => names.get(id)).join(item.kind === "relation" ? " → " : "、");
38
+ paragraph(`${labels[item.kind]}:${item.text}(${members})`);
39
+ }
40
+ return blocks;
41
+ }
42
+ //#endregion
43
+ //#region src/projection.ts
44
+ /** One versioned tag shared by PM and Markdown consumers. */
45
+ const mindMapDocxTag = "quirekit:mind-map:1";
46
+ /** @param value - Untrusted metadata. @returns Whether it is an inert record. */
47
+ function isRecord(value) {
48
+ return value !== null && typeof value === "object" && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value));
49
+ }
50
+ /** @param input - Saved source and matching preview. @param api - Central Word authoring facade.
51
+ * @param report - Operation-local diagnostics. @param options - Optional recovery policy.
52
+ * @returns Visible Word content with bounded optional source recovery. */
53
+ function projectMindMap(input, api, report, options) {
54
+ const mind = readMindMapEmbed(input), preview = mind.preview;
55
+ if (preview && !preview.dataUrl) throw new Error("思维导图预览图是外部地址,请先取回图片再导出");
56
+ if (preview?.dataUrl && !createQuireInlineImageResolver().resolve({
57
+ kind: "external",
58
+ href: preview.dataUrl
59
+ })) throw new Error("思维导图 PNG 数据无效,请重新保存脑图");
60
+ const scale = preview ? Math.min(560 / preview.width, 460 / preview.height, 1) : 1;
61
+ const children = preview ? [api.blocks.paragraph({ children: [{
62
+ type: "image",
63
+ attrs: {
64
+ src: preview.dataUrl,
65
+ alt: mind.title,
66
+ name: `${mind.title}.png`,
67
+ width: preview.width * scale,
68
+ height: preview.height * scale
69
+ }
70
+ }] })] : projectMindMapOutline(mind, api);
71
+ const metadata = {
72
+ version: 1,
73
+ data: {
74
+ source: serializeMindMapEmbed({
75
+ ...mind,
76
+ preview: null
77
+ }),
78
+ width: preview?.width ?? 0,
79
+ height: preview?.height ?? 0
80
+ }
81
+ };
82
+ const preserve = options.metadata !== false && new TextEncoder().encode(JSON.stringify(metadata)).length <= 65536;
83
+ report({
84
+ code: preview ? "mind-map-image-projected" : "mind-map-outline-projected",
85
+ severity: preview ? "info" : "warning",
86
+ disposition: preview ? "projected" : "approximated",
87
+ message: preview ? "思维导图以图片导出;可编辑源按元数据保留策略处理,可见内容未修改时可恢复。" : "思维导图尚无预览,已保留完整主题文字大纲;打开脑图并保存后可导出图像布局。"
88
+ });
89
+ if (!preserve) report({
90
+ code: "mind-map-source-not-retained",
91
+ severity: "warning",
92
+ disposition: "approximated",
93
+ message: "脑图可见内容已导出;源数据超过 Word 元数据预算或已关闭源保留。请保留原生 JSON 或 Markdown 以继续编辑。"
94
+ });
95
+ return api.roundTrip.taggedBlock({
96
+ tag: mindMapDocxTag,
97
+ alias: mind.title,
98
+ children,
99
+ ...preserve ? {
100
+ metadata,
101
+ metadataOptional: true
102
+ } : {}
103
+ });
104
+ }
105
+ /** @param node - Fingerprint-checked visible subtree. @returns All embedded images, so ambiguous projections cannot restore source. */
106
+ function imagesIn(node) {
107
+ const images = [];
108
+ /** @param current - Current visible content. */
109
+ function visit(current) {
110
+ if (current.type === "image") images.push(current);
111
+ (current.children ?? []).forEach(visit);
112
+ }
113
+ visit(node);
114
+ return images;
115
+ }
116
+ /** @param node - Current tagged control. @param api - Fingerprint-aware metadata reader.
117
+ * @returns Valid editable source, or null to retain current Word content. */
118
+ function recoverMindMap(node, api) {
119
+ const metadata = api.roundTrip.readMetadata(node), data = metadata?.data;
120
+ if (metadata?.version !== 1 || !isRecord(data) || typeof data.source !== "string") return null;
121
+ try {
122
+ if (Object.keys(data).some((key) => ![
123
+ "source",
124
+ "width",
125
+ "height"
126
+ ].includes(key))) return null;
127
+ const source = parseMindMapEmbed(data.source), images = imagesIn(node);
128
+ if (source.preview !== null) return null;
129
+ if (data.width === 0 && data.height === 0) return images.length === 0 ? source : null;
130
+ if (images.length !== 1) return null;
131
+ const restored = readMindMapEmbed({
132
+ ...source,
133
+ preview: {
134
+ dataUrl: images[0].attrs?.src,
135
+ width: data.width,
136
+ height: data.height
137
+ }
138
+ });
139
+ return createQuireInlineImageResolver().resolve({
140
+ kind: "external",
141
+ href: restored.preview.dataUrl
142
+ }) ? restored : null;
143
+ } catch {
144
+ return null;
145
+ }
146
+ }
147
+ //#endregion
148
+ //#region src/codec.ts
149
+ /** @param options - Optional source recovery. @returns One feature codec shared by Classic and Core/Block document managers. */
150
+ function createMindMapDocxCodec(options = {}) {
151
+ return docx.codec.node({
152
+ id: "mind-map.document",
153
+ modelType: "mindMap",
154
+ export: { convert: ({ node, docx: api, report }) => [projectMindMap(node.attrs?.mind, api, report, options)] },
155
+ import: {
156
+ from: docx.roundTrip.matchTag(mindMapDocxTag),
157
+ childContentKind: "block",
158
+ creates: ["mindMap", "paragraph"],
159
+ convert: ({ node, docx: api, convertChildren, report }) => {
160
+ const mind = recoverMindMap(node, api);
161
+ if (mind) return [{
162
+ type: "mindMap",
163
+ attrs: { mind }
164
+ }];
165
+ report({
166
+ code: "mind-map-source-unavailable",
167
+ severity: "warning",
168
+ disposition: "approximated",
169
+ message: "脑图源缺失、无效或可见内容已变化;保留当前 Word 内容,不恢复旧脑图。"
170
+ });
171
+ return convertChildren(node.children ?? []);
172
+ }
173
+ },
174
+ capabilities: { fields: ["mind"] }
175
+ });
176
+ }
177
+ //#endregion
178
+ export { createMindMapDocxCodec, mindMapDocxTag, projectMindMap, recoverMindMap };
179
+
180
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/outline.ts","../src/projection.ts","../src/codec.ts"],"sourcesContent":["import type { DocxAuthoringApi, LitAstNode } from \"@quirekit/lit-docx-contract\";\nimport { mindMapAnnotationTopics, type MindMapEmbed, type MindMapNode } from \"@quirekit/mind-map\";\n\n/** @param mind - Validated source without a raster. @param api - Central Word authoring facade.\n * @returns Complete topic text, including folded descendants and separate free trees. */\nexport function projectMindMapOutline(mind: MindMapEmbed, api: DocxAuthoringApi): LitAstNode[] {\n const blocks: LitAstNode[] = [];\n const names = new Map<string, string>();\n /** @param text - Literal visible paragraph text. */\n function paragraph(text: string): void { blocks.push(api.blocks.paragraph({ children: [api.inline.text(text)] })); }\n /** @param node - Current immutable topic. @param depth - Source hierarchy depth, bounded by the model. */\n function visit(node: MindMapNode, depth: number): void {\n names.set(node.id, node.text);\n paragraph(`${\" \".repeat(depth)}${depth ? \"• \" : \"\"}${node.text}`);\n const details = node.details;\n if (details?.link) paragraph(`链接:${details.link}`);\n if (details?.note) paragraph(`备注:${details.note}`);\n if (details?.marker) paragraph(`优先级:${details.marker.slice(-1)}`);\n if (details?.image) paragraph(`图片:${details.image.alt || \"主题图片\"}`);\n node.children.forEach(child => visit(child, depth + 1));\n }\n paragraph(`思维导图:${mind.title}`);\n visit(mind.document.root, 0);\n for (const topic of mind.document.floatingTopics ?? []) {\n paragraph(\"自由主题\"); visit(topic.root, 0);\n }\n const labels = { relation: \"关联\", summary: \"概要\", boundary: \"外框\" };\n for (const item of mind.document.annotations ?? []) {\n const members = mindMapAnnotationTopics(item).map(id => names.get(id)).join(item.kind === \"relation\" ? \" → \" : \"、\");\n paragraph(`${labels[item.kind]}:${item.text}(${members})`);\n }\n return blocks;\n}\n","import type { DocxAuthoringApi, DocxCodecDiagnosticInput, LitAstNode } from \"@quirekit/lit-docx-contract\";\nimport { createQuireInlineImageResolver } from \"@quirekit/media\";\nimport { parseMindMapEmbed, readMindMapEmbed, serializeMindMapEmbed, type MindMapEmbed } from \"@quirekit/mind-map\";\nimport { projectMindMapOutline } from \"./outline\";\nimport type { MindMapDocxOptions } from \"./types\";\n\n/** One versioned tag shared by PM and Markdown consumers. */\nexport const mindMapDocxTag = \"quirekit:mind-map:1\";\n\n/** @param value - Untrusted metadata. @returns Whether it is an inert record. */\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n && [Object.prototype, null].includes(Object.getPrototypeOf(value));\n}\n\n/** @param input - Saved source and matching preview. @param api - Central Word authoring facade.\n * @param report - Operation-local diagnostics. @param options - Optional recovery policy.\n * @returns Visible Word content with bounded optional source recovery. */\nexport function projectMindMap(input: unknown, api: DocxAuthoringApi, report: (diagnostic: DocxCodecDiagnosticInput) => void,\n options: MindMapDocxOptions): LitAstNode {\n const mind = readMindMapEmbed(input), preview = mind.preview;\n if (preview && !preview.dataUrl) throw new Error(\"思维导图预览图是外部地址,请先取回图片再导出\");\n if (preview?.dataUrl && !createQuireInlineImageResolver().resolve({ kind: \"external\", href: preview.dataUrl })) {\n throw new Error(\"思维导图 PNG 数据无效,请重新保存脑图\");\n }\n const scale = preview ? Math.min(560 / preview.width, 460 / preview.height, 1) : 1;\n const children = preview ? [api.blocks.paragraph({ children: [{ type: \"image\", attrs: {\n src: preview.dataUrl, alt: mind.title, name: `${mind.title}.png`, width: preview.width * scale, height: preview.height * scale,\n } }] })] : projectMindMapOutline(mind, api);\n\n // The central package already owns the PNG. Store only canonical source and\n // intrinsic dimensions; optional recovery must never prevent visible export.\n const source = serializeMindMapEmbed({ ...mind, preview: null });\n const metadata = { version: 1, data: { source, width: preview?.width ?? 0, height: preview?.height ?? 0 } };\n const preserve = options.metadata !== false && new TextEncoder().encode(JSON.stringify(metadata)).length <= 65_536;\n report({ code: preview ? \"mind-map-image-projected\" : \"mind-map-outline-projected\", severity: preview ? \"info\" : \"warning\", disposition: preview ? \"projected\" : \"approximated\",\n message: preview ? \"思维导图以图片导出;可编辑源按元数据保留策略处理,可见内容未修改时可恢复。\"\n : \"思维导图尚无预览,已保留完整主题文字大纲;打开脑图并保存后可导出图像布局。\" });\n if (!preserve) report({ code: \"mind-map-source-not-retained\", severity: \"warning\", disposition: \"approximated\",\n message: \"脑图可见内容已导出;源数据超过 Word 元数据预算或已关闭源保留。请保留原生 JSON 或 Markdown 以继续编辑。\" });\n return api.roundTrip.taggedBlock({ tag: mindMapDocxTag, alias: mind.title, children,\n ...(preserve ? { metadata, metadataOptional: true } : {}) });\n}\n\n/** @param node - Fingerprint-checked visible subtree. @returns All embedded images, so ambiguous projections cannot restore source. */\nfunction imagesIn(node: LitAstNode): LitAstNode[] {\n const images: LitAstNode[] = [];\n /** @param current - Current visible content. */\n function visit(current: LitAstNode): void { if (current.type === \"image\") images.push(current); (current.children ?? []).forEach(visit); }\n visit(node); return images;\n}\n\n/** @param node - Current tagged control. @param api - Fingerprint-aware metadata reader.\n * @returns Valid editable source, or null to retain current Word content. */\nexport function recoverMindMap(node: LitAstNode, api: DocxAuthoringApi): MindMapEmbed | null {\n const metadata = api.roundTrip.readMetadata(node), data = metadata?.data;\n if (metadata?.version !== 1 || !isRecord(data) || typeof data.source !== \"string\") return null;\n try {\n if (Object.keys(data).some(key => ![\"source\", \"width\", \"height\"].includes(key))) return null;\n const source = parseMindMapEmbed(data.source), images = imagesIn(node);\n if (source.preview !== null) return null;\n if (data.width === 0 && data.height === 0) return images.length === 0 ? source : null;\n if (images.length !== 1) return null;\n const restored = readMindMapEmbed({ ...source, preview: { dataUrl: images[0]!.attrs?.src, width: data.width, height: data.height } });\n return createQuireInlineImageResolver().resolve({ kind: \"external\", href: restored.preview!.dataUrl! }) ? restored : null;\n } catch { return null; }\n}\n","import { docx } from \"@quirekit/lit-docx-contract\";\nimport type { DocxJsonNode, DocxJsonMark } from \"@quirekit/docx\";\nimport { mindMapDocxTag, projectMindMap, recoverMindMap } from \"./projection\";\nimport type { MindMapDocxOptions } from \"./types\";\n\n/** @param options - Optional source recovery. @returns One feature codec shared by Classic and Core/Block document managers. */\nexport function createMindMapDocxCodec<ModelNode extends Pick<DocxJsonNode, \"attrs\"> = DocxJsonNode, ModelMark = DocxJsonMark>(options: MindMapDocxOptions = {}) {\n return docx.codec.node<ModelNode, ModelMark>({ id: \"mind-map.document\", modelType: \"mindMap\",\n export: { convert: ({ node, docx: api, report }) => [projectMindMap(node.attrs?.mind, api, report, options)] },\n import: { from: docx.roundTrip.matchTag(mindMapDocxTag), childContentKind: \"block\", creates: [\"mindMap\", \"paragraph\"],\n convert: ({ node, docx: api, convertChildren, report }) => {\n const mind = recoverMindMap(node, api);\n if (mind) return [{ type: \"mindMap\", attrs: { mind } } as unknown as ModelNode];\n report({ code: \"mind-map-source-unavailable\", severity: \"warning\", disposition: \"approximated\",\n message: \"脑图源缺失、无效或可见内容已变化;保留当前 Word 内容,不恢复旧脑图。\" });\n return convertChildren(node.children ?? []);\n } },\n capabilities: { fields: [\"mind\"] },\n });\n}\n"],"mappings":";;;;;;AAKA,SAAgB,sBAAsB,MAAoB,KAAqC;CAC7F,MAAM,SAAuB,CAAC;CAC9B,MAAM,wBAAQ,IAAI,IAAoB;;CAEtC,SAAS,UAAU,MAAoB;EAAE,OAAO,KAAK,IAAI,OAAO,UAAU,EAAE,UAAU,CAAC,IAAI,OAAO,KAAK,IAAI,CAAC,EAAE,CAAC,CAAC;CAAG;;CAEnH,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AC,eAAe,KAAK,OAAO,MAAM,KAAK,QAAQ,OAAO,CAAC,EAAE;EAC7G,QAAQ;GAAE,MAAM,KAAK,UAAU,SAAS,cAAc;GAAG,kBAAkB;GAAS,SAAS,CAAC,WAAW,WAAW;GAClH,UAAU,EAAE,MAAM,MAAM,KAAK,iBAAiB,aAAa;IACzD,MAAM,OAAO,eAAe,MAAM,GAAG;IACrC,IAAI,MAAM,OAAO,CAAC;KAAE,MAAM;KAAW,OAAO,EAAE,KAAK;IAAE,CAAyB;IAC9E,OAAO;KAAE,MAAM;KAA+B,UAAU;KAAW,aAAa;KAC9E,SAAS;IAAwC,CAAC;IACpD,OAAO,gBAAgB,KAAK,YAAY,CAAC,CAAC;GAC5C;EAAE;EACJ,cAAc,EAAE,QAAQ,CAAC,MAAM,EAAE;CACnC,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@quirekit/mind-map-docx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1-alpha.0",
4
+ "description": "Shared Mind Editor Word image projection and source recovery.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/quirekit/quirekit.git",
9
+ "directory": "packages/mind-map-docx"
10
+ },
11
+ "homepage": "https://github.com/quirekit/quirekit/tree/main/packages/mind-map-docx#readme",
12
+ "bugs": "https://github.com/quirekit/quirekit/issues",
13
+ "type": "module",
14
+ "sideEffects": false,
15
+ "files": [
16
+ "LICENSE.md",
17
+ "THIRD_PARTY_NOTICES.md",
18
+ "dist",
19
+ "src"
20
+ ],
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.mts",
24
+ "import": "./dist/index.mjs"
25
+ }
26
+ },
27
+ "types": "./dist/index.d.mts",
28
+ "dependencies": {
29
+ "@quirekit/mind-map": "0.0.1-alpha.0",
30
+ "@quirekit/lit-docx-contract": "0.0.1-alpha.0",
31
+ "@quirekit/media": "0.0.1-alpha.0",
32
+ "@quirekit/docx": "0.0.1-alpha.0"
33
+ },
34
+ "devDependencies": {
35
+ "tsdown": "0.22.3",
36
+ "typescript": "6.0.3",
37
+ "vitest": "4.1.9",
38
+ "jszip": "3.10.1"
39
+ },
40
+ "scripts": {
41
+ "build": "tsdown src/index.ts --format esm --dts --clean --out-dir dist",
42
+ "typecheck": "tsc --noEmit -p tsconfig.json",
43
+ "test": "vitest run src"
44
+ }
6
45
  }
package/src/codec.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { docx } from "@quirekit/lit-docx-contract";
2
+ import type { DocxJsonNode, DocxJsonMark } from "@quirekit/docx";
3
+ import { mindMapDocxTag, projectMindMap, recoverMindMap } from "./projection";
4
+ import type { MindMapDocxOptions } from "./types";
5
+
6
+ /** @param options - Optional source recovery. @returns One feature codec shared by Classic and Core/Block document managers. */
7
+ export function createMindMapDocxCodec<ModelNode extends Pick<DocxJsonNode, "attrs"> = DocxJsonNode, ModelMark = DocxJsonMark>(options: MindMapDocxOptions = {}) {
8
+ return docx.codec.node<ModelNode, ModelMark>({ id: "mind-map.document", modelType: "mindMap",
9
+ export: { convert: ({ node, docx: api, report }) => [projectMindMap(node.attrs?.mind, api, report, options)] },
10
+ import: { from: docx.roundTrip.matchTag(mindMapDocxTag), childContentKind: "block", creates: ["mindMap", "paragraph"],
11
+ convert: ({ node, docx: api, convertChildren, report }) => {
12
+ const mind = recoverMindMap(node, api);
13
+ if (mind) return [{ type: "mindMap", attrs: { mind } } as unknown as ModelNode];
14
+ report({ code: "mind-map-source-unavailable", severity: "warning", disposition: "approximated",
15
+ message: "脑图源缺失、无效或可见内容已变化;保留当前 Word 内容,不恢复旧脑图。" });
16
+ return convertChildren(node.children ?? []);
17
+ } },
18
+ capabilities: { fields: ["mind"] },
19
+ });
20
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { createMindMapDocxCodec } from "./codec";
2
+ export { projectMindMap, recoverMindMap, mindMapDocxTag } from "./projection";
3
+ export type { MindMapDocxOptions } from "./types";
package/src/outline.ts ADDED
@@ -0,0 +1,33 @@
1
+ import type { DocxAuthoringApi, LitAstNode } from "@quirekit/lit-docx-contract";
2
+ import { mindMapAnnotationTopics, type MindMapEmbed, type MindMapNode } from "@quirekit/mind-map";
3
+
4
+ /** @param mind - Validated source without a raster. @param api - Central Word authoring facade.
5
+ * @returns Complete topic text, including folded descendants and separate free trees. */
6
+ export function projectMindMapOutline(mind: MindMapEmbed, api: DocxAuthoringApi): LitAstNode[] {
7
+ const blocks: LitAstNode[] = [];
8
+ const names = new Map<string, string>();
9
+ /** @param text - Literal visible paragraph text. */
10
+ function paragraph(text: string): void { blocks.push(api.blocks.paragraph({ children: [api.inline.text(text)] })); }
11
+ /** @param node - Current immutable topic. @param depth - Source hierarchy depth, bounded by the model. */
12
+ function visit(node: MindMapNode, depth: number): void {
13
+ names.set(node.id, node.text);
14
+ paragraph(`${" ".repeat(depth)}${depth ? "• " : ""}${node.text}`);
15
+ const details = node.details;
16
+ if (details?.link) paragraph(`链接:${details.link}`);
17
+ if (details?.note) paragraph(`备注:${details.note}`);
18
+ if (details?.marker) paragraph(`优先级:${details.marker.slice(-1)}`);
19
+ if (details?.image) paragraph(`图片:${details.image.alt || "主题图片"}`);
20
+ node.children.forEach(child => visit(child, depth + 1));
21
+ }
22
+ paragraph(`思维导图:${mind.title}`);
23
+ visit(mind.document.root, 0);
24
+ for (const topic of mind.document.floatingTopics ?? []) {
25
+ paragraph("自由主题"); visit(topic.root, 0);
26
+ }
27
+ const labels = { relation: "关联", summary: "概要", boundary: "外框" };
28
+ for (const item of mind.document.annotations ?? []) {
29
+ const members = mindMapAnnotationTopics(item).map(id => names.get(id)).join(item.kind === "relation" ? " → " : "、");
30
+ paragraph(`${labels[item.kind]}:${item.text}(${members})`);
31
+ }
32
+ return blocks;
33
+ }
@@ -0,0 +1,41 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { docx, type DocxRoundTripMetadata, type LitAstNode } from "@quirekit/lit-docx-contract";
3
+ import { createMindMapEmbed, serializeMindMapEmbed } from "@quirekit/mind-map";
4
+ import { projectMindMap, recoverMindMap } from "./projection";
5
+
6
+ const png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII=";
7
+ const source = createMindMapEmbed("recovery", "保留源"), serialized = serializeMindMapEmbed(source);
8
+ const image: LitAstNode = { type: "image", attrs: { src: png } };
9
+ /** @param metadata - Untrusted semantic payload. @param children - Already decoded visible content.
10
+ * @returns Tagged projection through the public authoring API. */
11
+ function control(metadata: DocxRoundTripMetadata, children: readonly LitAstNode[] = [image]): LitAstNode {
12
+ return docx.roundTrip.taggedBlock({ tag: "quirekit:mind-map:1", metadata, children: [...children] });
13
+ }
14
+
15
+ describe("mind map metadata validation", () => {
16
+ it.each([
17
+ { version: 2, data: { source: serialized, width: 1, height: 1 } },
18
+ { version: 1, data: { source: "invalid", width: 1, height: 1 } },
19
+ { version: 1, data: { source: serialized, width: 1, height: 0 } },
20
+ { version: 1, data: { source: serialized, width: 1.5, height: 1 } },
21
+ { version: 1, data: { source: serialized, width: 4097, height: 1 } },
22
+ { version: 1, data: { source: serialized, width: 1, height: 1, extra: true } },
23
+ { version: 1, data: { source: JSON.stringify({ ...source, version: 99 }), width: 1, height: 1 } },
24
+ { version: 1, data: { source: JSON.stringify({ ...source, preview: { dataUrl: png, width: 1, height: 1 } }), width: 1, height: 1 } },
25
+ ])("declines unsupported or inconsistent metadata without restoring stale source", metadata => {
26
+ expect(recoverMindMap(control(metadata), docx)).toBeNull();
27
+ });
28
+ it("rejects absent or ambiguous images and does not mistake them for an outline", () => {
29
+ const metadata = { version: 1, data: { source: serialized, width: 1, height: 1 } };
30
+ expect(recoverMindMap(control(metadata, []), docx)).toBeNull();
31
+ expect(recoverMindMap(control(metadata, [image, image]), docx)).toBeNull();
32
+ expect(recoverMindMap(control({ ...metadata, data: { ...metadata.data, width: 0, height: 0 } }, [image, image]), docx)).toBeNull();
33
+ });
34
+ it("does not mutate the accepted model or duplicate PNG bytes in metadata", () => {
35
+ const saved = { ...source, preview: { dataUrl: png, width: 32, height: 24 } };
36
+ const before = JSON.stringify(saved), projection = projectMindMap(saved, docx, () => {}, {});
37
+ expect(JSON.stringify(saved)).toBe(before);
38
+ expect(JSON.stringify(docx.roundTrip.readMetadata(projection))).not.toContain("data:image");
39
+ expect(recoverMindMap(projection, docx)).toEqual(saved);
40
+ });
41
+ });
@@ -0,0 +1,67 @@
1
+ import type { DocxAuthoringApi, DocxCodecDiagnosticInput, LitAstNode } from "@quirekit/lit-docx-contract";
2
+ import { createQuireInlineImageResolver } from "@quirekit/media";
3
+ import { parseMindMapEmbed, readMindMapEmbed, serializeMindMapEmbed, type MindMapEmbed } from "@quirekit/mind-map";
4
+ import { projectMindMapOutline } from "./outline";
5
+ import type { MindMapDocxOptions } from "./types";
6
+
7
+ /** One versioned tag shared by PM and Markdown consumers. */
8
+ export const mindMapDocxTag = "quirekit:mind-map:1";
9
+
10
+ /** @param value - Untrusted metadata. @returns Whether it is an inert record. */
11
+ function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value)
13
+ && [Object.prototype, null].includes(Object.getPrototypeOf(value));
14
+ }
15
+
16
+ /** @param input - Saved source and matching preview. @param api - Central Word authoring facade.
17
+ * @param report - Operation-local diagnostics. @param options - Optional recovery policy.
18
+ * @returns Visible Word content with bounded optional source recovery. */
19
+ export function projectMindMap(input: unknown, api: DocxAuthoringApi, report: (diagnostic: DocxCodecDiagnosticInput) => void,
20
+ options: MindMapDocxOptions): LitAstNode {
21
+ const mind = readMindMapEmbed(input), preview = mind.preview;
22
+ if (preview && !preview.dataUrl) throw new Error("思维导图预览图是外部地址,请先取回图片再导出");
23
+ if (preview?.dataUrl && !createQuireInlineImageResolver().resolve({ kind: "external", href: preview.dataUrl })) {
24
+ throw new Error("思维导图 PNG 数据无效,请重新保存脑图");
25
+ }
26
+ const scale = preview ? Math.min(560 / preview.width, 460 / preview.height, 1) : 1;
27
+ const children = preview ? [api.blocks.paragraph({ children: [{ type: "image", attrs: {
28
+ src: preview.dataUrl, alt: mind.title, name: `${mind.title}.png`, width: preview.width * scale, height: preview.height * scale,
29
+ } }] })] : projectMindMapOutline(mind, api);
30
+
31
+ // The central package already owns the PNG. Store only canonical source and
32
+ // intrinsic dimensions; optional recovery must never prevent visible export.
33
+ const source = serializeMindMapEmbed({ ...mind, preview: null });
34
+ const metadata = { version: 1, data: { source, width: preview?.width ?? 0, height: preview?.height ?? 0 } };
35
+ const preserve = options.metadata !== false && new TextEncoder().encode(JSON.stringify(metadata)).length <= 65_536;
36
+ report({ code: preview ? "mind-map-image-projected" : "mind-map-outline-projected", severity: preview ? "info" : "warning", disposition: preview ? "projected" : "approximated",
37
+ message: preview ? "思维导图以图片导出;可编辑源按元数据保留策略处理,可见内容未修改时可恢复。"
38
+ : "思维导图尚无预览,已保留完整主题文字大纲;打开脑图并保存后可导出图像布局。" });
39
+ if (!preserve) report({ code: "mind-map-source-not-retained", severity: "warning", disposition: "approximated",
40
+ message: "脑图可见内容已导出;源数据超过 Word 元数据预算或已关闭源保留。请保留原生 JSON 或 Markdown 以继续编辑。" });
41
+ return api.roundTrip.taggedBlock({ tag: mindMapDocxTag, alias: mind.title, children,
42
+ ...(preserve ? { metadata, metadataOptional: true } : {}) });
43
+ }
44
+
45
+ /** @param node - Fingerprint-checked visible subtree. @returns All embedded images, so ambiguous projections cannot restore source. */
46
+ function imagesIn(node: LitAstNode): LitAstNode[] {
47
+ const images: LitAstNode[] = [];
48
+ /** @param current - Current visible content. */
49
+ function visit(current: LitAstNode): void { if (current.type === "image") images.push(current); (current.children ?? []).forEach(visit); }
50
+ visit(node); return images;
51
+ }
52
+
53
+ /** @param node - Current tagged control. @param api - Fingerprint-aware metadata reader.
54
+ * @returns Valid editable source, or null to retain current Word content. */
55
+ export function recoverMindMap(node: LitAstNode, api: DocxAuthoringApi): MindMapEmbed | null {
56
+ const metadata = api.roundTrip.readMetadata(node), data = metadata?.data;
57
+ if (metadata?.version !== 1 || !isRecord(data) || typeof data.source !== "string") return null;
58
+ try {
59
+ if (Object.keys(data).some(key => !["source", "width", "height"].includes(key))) return null;
60
+ const source = parseMindMapEmbed(data.source), images = imagesIn(node);
61
+ if (source.preview !== null) return null;
62
+ if (data.width === 0 && data.height === 0) return images.length === 0 ? source : null;
63
+ if (images.length !== 1) return null;
64
+ const restored = readMindMapEmbed({ ...source, preview: { dataUrl: images[0]!.attrs?.src, width: data.width, height: data.height } });
65
+ return createQuireInlineImageResolver().resolve({ kind: "external", href: restored.preview!.dataUrl! }) ? restored : null;
66
+ } catch { return null; }
67
+ }
package/src/types.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Optional source policy; saved images always remain visible in Word. */
2
+ export interface MindMapDocxOptions {
3
+ /** Retain source when it fits the existing metadata budget; default true. */ readonly metadata?: boolean;
4
+ }