@a200888213/gbdocx 0.0.0-stage → 0.4.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.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +206 -2
  3. package/index.html +25 -0
  4. package/package.json +48 -6
  5. package/serve.mjs +22 -0
  6. package/src/app/file-io.js +122 -0
  7. package/src/app/main.js +9 -0
  8. package/src/app/word/catalog.js +52 -0
  9. package/src/app/word/comments.js +112 -0
  10. package/src/app/word/doc.js +113 -0
  11. package/src/app/word/edit.js +72 -0
  12. package/src/app/word/file.js +162 -0
  13. package/src/app/word/hf.js +76 -0
  14. package/src/app/word/layout.js +155 -0
  15. package/src/app/word/menus.js +175 -0
  16. package/src/app/word/notes.js +110 -0
  17. package/src/app/word/shared.js +22 -0
  18. package/src/app/word/view.js +117 -0
  19. package/src/app/word-app.js +459 -0
  20. package/src/app/word-sheets.js +101 -0
  21. package/src/kernel/docx/catalog.js +41 -0
  22. package/src/kernel/docx/codec/blocks.js +123 -0
  23. package/src/kernel/docx/codec/carry.js +129 -0
  24. package/src/kernel/docx/codec/comments.js +25 -0
  25. package/src/kernel/docx/codec/docx.js +198 -0
  26. package/src/kernel/docx/codec/docxStyles.js +177 -0
  27. package/src/kernel/docx/codec/fonts.js +195 -0
  28. package/src/kernel/docx/codec/helpers.js +161 -0
  29. package/src/kernel/docx/codec/hfHtml.js +152 -0
  30. package/src/kernel/docx/codec/html.js +739 -0
  31. package/src/kernel/docx/codec/losses.js +420 -0
  32. package/src/kernel/docx/codec/markdown.js +170 -0
  33. package/src/kernel/docx/codec/parts.js +249 -0
  34. package/src/kernel/docx/codec/read.js +603 -0
  35. package/src/kernel/docx/codec/render.js +1156 -0
  36. package/src/kernel/docx/codec/roundtrip.js +236 -0
  37. package/src/kernel/docx/codec/write.js +833 -0
  38. package/src/kernel/docx/comments.js +14 -0
  39. package/src/kernel/docx/constants.js +63 -0
  40. package/src/kernel/docx/menus.js +211 -0
  41. package/src/kernel/docx/pageGeometry.js +123 -0
  42. package/src/kernel/docx/pagination.js +481 -0
  43. package/src/kernel/docx/watermark.js +45 -0
  44. package/src/kernel/docx/wordShortcuts.js +37 -0
  45. package/src/kernel/editor/constants.js +8 -0
  46. package/src/kernel/editor/engine/blocks.js +594 -0
  47. package/src/kernel/editor/engine/blocksEnter.js +109 -0
  48. package/src/kernel/editor/engine/blocksInsert.js +254 -0
  49. package/src/kernel/editor/engine/blocksStructure.js +226 -0
  50. package/src/kernel/editor/engine/commands.js +181 -0
  51. package/src/kernel/editor/engine/dom.js +646 -0
  52. package/src/kernel/editor/engine/editor.js +213 -0
  53. package/src/kernel/editor/engine/history.js +149 -0
  54. package/src/kernel/editor/engine/inline.js +656 -0
  55. package/src/kernel/editor/engine/input.js +554 -0
  56. package/src/kernel/editor/engine/interaction.js +137 -0
  57. package/src/kernel/editor/engine/pointer.js +39 -0
  58. package/src/kernel/editor/engine/revision.js +138 -0
  59. package/src/kernel/editor/engine/schema.js +417 -0
  60. package/src/kernel/editor/engine/search.js +113 -0
  61. package/src/kernel/editor/engine/selection.js +119 -0
  62. package/src/kernel/editor/engine/state.js +118 -0
  63. package/src/kernel/editor/engine/tableClip.js +154 -0
  64. package/src/kernel/editor/engine/tableGrid.js +55 -0
  65. package/src/kernel/editor/engine/tableInteraction.js +388 -0
  66. package/src/kernel/editor/engine/tableMenu.js +250 -0
  67. package/src/kernel/editor/engine/tableOps.js +174 -0
  68. package/src/kernel/editor/engine/tables.js +732 -0
  69. package/src/kernel/editor/overlayGeometry.js +20 -0
  70. package/src/kernel/editor/pasteClean.js +293 -0
  71. package/src/kernel/editor/utils.js +49 -0
  72. package/src/kernel/keyboard.js +114 -0
  73. package/src/kernel/notify.js +54 -0
  74. package/src/kernel/textStyles.js +84 -0
  75. package/src/kernel/util/clipboard.js +89 -0
  76. package/src/kernel/util/imageFile.js +91 -0
  77. package/src/kernel/util/safeValue.js +25 -0
  78. package/src/kernel/util/shortcutKey.js +33 -0
  79. package/src/surface/editor-surface.js +600 -0
  80. package/src/ui/color-panel.js +69 -0
  81. package/src/ui/context-menu.js +130 -0
  82. package/src/ui/dialogs.js +249 -0
  83. package/src/ui/find-bar.js +151 -0
  84. package/src/ui/icons.js +134 -0
  85. package/src/ui/menubar.js +28 -0
  86. package/src/ui/panels.js +115 -0
  87. package/src/ui/popup.js +79 -0
  88. package/src/ui/prompt.js +89 -0
  89. package/src/ui/ribbon.js +485 -0
  90. package/src/ui/special-chars.js +39 -0
  91. package/src/ui/statusbar.js +81 -0
  92. package/src/ui/toolbar.js +32 -0
  93. package/styles/app.css +944 -0
  94. package/styles/editor-content.css +440 -0
  95. package/styles/tokens.css +154 -0
  96. package/styles/word-panel.css +410 -0
@@ -0,0 +1,123 @@
1
+ // [文件] web·docx·codec·blocks —— 块模型:HTML 与 OOXML 双方归一到的中间结构(写出与读回只认它)
2
+
3
+ /** run 的类型。嵌套关系(修订标记包住一串 run、批注范围包住一串 run)用扁平序列
4
+ * 里的开闭标记表达,模型里不再嵌一层树——OOXML 侧本来就是 w:ins/w:commentRange 这种包夹元素 */
5
+ export const MARK = {
6
+ TEXT: 'text', // 普通文字
7
+ BREAK: 'break', // 软换行 <w:br/>
8
+ PAGE: 'page', // 分页符 <w:br w:type="page"/>
9
+ IMAGE: 'image', // 内嵌图片
10
+ NOTE: 'note', // 脚注/尾注引用 <w:footnoteReference>/<w:endnoteReference>
11
+ REV_OPEN: 'revOpen', // 修订标记起点
12
+ REV_CLOSE: 'revClose', // 修订标记终点
13
+ CMT_OPEN: 'cmtOpen', // 批注范围起点
14
+ CMT_CLOSE: 'cmtClose' // 批注范围终点
15
+ };
16
+
17
+ /**
18
+ * 行内格式。OOXML 的 rPr 是「显式开、显式关」的集合,故这里用布尔而非三态
19
+ * @returns {{bold:boolean, italic:boolean, underline:boolean, strike:boolean, superscript:boolean, subscript:boolean,
20
+ * mono:boolean, del:boolean, font:string, color:string, bg:string, size:number, link:string}}
21
+ */
22
+ export function makeForm(fields = {}) {
23
+ return {
24
+ bold: false,
25
+ italic: false,
26
+ underline: false,
27
+ strike: false,
28
+ superscript: false, // 上标(w:vertAlign superscript;与下标互斥)
29
+ subscript: false, // 下标(w:vertAlign subscript)
30
+ mono: false, // 等宽(代码)
31
+ del: false, // 删除建议内的文字,要写 w:delText 而不是 w:t
32
+ font: '', // 字体族名(拉丁字形,w:ascii/hAnsi)
33
+ fontEa: '', // 东亚字形字体名(w:eastAsia);空则按 font 的字体链反解
34
+ hint: '', // 歧义标点的字形归属('eastAsia' = 交给中文字体,对应 w:rFonts/@w:hint)
35
+ spacing: 0, // 字符间距(px,负数为收紧);0 = 不写
36
+ scale: 0, // 字符缩放(百分比);0/100 = 不缩放
37
+ color: '', // "#rrggbb"
38
+ colorTheme: '', // 主题色引用(w:themeColor 名;非空时按引用落盘,不摊平成 hex)
39
+ colorThemeTint: '', // 主题色调亮(w:themeTint,两位 hex 原样透传)
40
+ colorThemeShade: '', // 主题色调暗(w:themeShade)
41
+ bg: '', // "#rrggbb" 文字底色
42
+ size: 0, // px;0 = 跟随默认
43
+ link: '', // 处于超链接内时的 href
44
+ ...fields
45
+ };
46
+ }
47
+
48
+ /** 一段行内内容 */
49
+ export function makeRun(fields = {}) {
50
+ const { mark = MARK.TEXT, text = '', rev = '', cmt = 0, note = '', end = false, author = '', date = '', img = null, form = null } = fields;
51
+ return { mark, text, rev, cmt, note, end, author, date, img, form: form ?? makeForm() };
52
+ }
53
+
54
+ /** 造一段普通文字 run */
55
+ export const textRun = (text, form) => makeRun({ mark: MARK.TEXT, text, form: form ?? makeForm() });
56
+
57
+ /** 列表项编号引用。numId 1 是项目符号、2 是有序号、3/4 是已勾选/未勾选待办(对应 numbering.xml) */
58
+ export const numRef = (level, ordered, task = '') => ({ level, ordered, task });
59
+
60
+ /**
61
+ * 段落。列表项也是段落,只是多了编号引用
62
+ * @returns {{style:string, align:string, indent:number, firstLine:number, hanging:number, before:number, after:number,
63
+ * line:number, lineExact:number, shade:string, borders:Object|null,
64
+ * tabs:Array|null, num:null|{level:number,ordered:boolean}, runs:Array}}
65
+ */
66
+ export function makePara(fields = {}) {
67
+ return {
68
+ style: '', // pStyle 值(Heading1~6 / Title);"" = 正文
69
+ align: '', // "" | center | right | justify
70
+ indent: 0, // 左缩进(twips);0 = 不写
71
+ firstLine: 0, // 首行缩进(twips);0 = 不写
72
+ hanging: 0, // 悬挂缩进(twips);0 = 不写
73
+ before: 0, // 段前(twips);0 = 不写
74
+ after: 0, // 段后(twips);0 = 不写
75
+ line: 0, // 行距(240 分之一行;CSS 倍数的等价编码);0 = 不写
76
+ lineExact: 0, // 固定行距(twips;来自导入文档的 exact/atLeast);>0 优先于 line
77
+ shade: '', // 段落底色 "RRGGBB"(代码块靠它标记)
78
+ borders: null, // 段落边框 { top?: {size,color}, bottom?: {size,color}, left?, right? };size = 1/8 磅
79
+ tabs: null, // 自定义制表位 [{pos,align,leader}];null = 不写 w:tabs
80
+ keepNext: false, // 与下段同页(w:keepNext)
81
+ keepLines: false, // 整段不拆页(w:keepLines)
82
+ pageBreakBefore: false, // 段前分页(w:pageBreakBefore)
83
+ widowOff: false, // 关闭孤行控制(w:widowControl val=0;缺省即开启,只在显式关时写)
84
+ num: null, // 非 null 表示列表项
85
+ runs: [],
86
+ ...fields
87
+ };
88
+ }
89
+
90
+ /** 一张内嵌图片,尺寸已是最终显示值(像素) */
91
+ export function makeImageRef(fields = {}) {
92
+ return { data: new Uint8Array(0), ext: '', w: 0, h: 0, ...fields };
93
+ }
94
+
95
+ /** 一个网格格 */
96
+ export function makeCell(fields = {}) {
97
+ return {
98
+ span: 1, // 横向跨列
99
+ restart: false, // 纵向合并起点(w:vMerge restart)
100
+ cont: false, // 纵向合并续格(空 tc + 无值 w:vMerge)
101
+ shade: '', // "RRGGBB"
102
+ vAlign: '', // 垂直对齐 'top'|'center'|'bottom';'' = 未声明(Word 默认 top)
103
+ width: 0, // 占表格宽的百分比
104
+ blocks: [],
105
+ ...fields
106
+ };
107
+ }
108
+
109
+ /** 一个块级元素:段落与表格二选一;secBreak = 节边界标记块、toc = 目录块(TOC 域,缓存行在 tocBlocks) */
110
+ const makeBlock = (fields = {}) => ({ para: null, table: null, spanAll: false, secBreak: false, toc: false, tocBlocks: null, ...fields });
111
+
112
+ /** 段落块(spanAll 顶层块的跨栏标记:多栏文档里 col-span-all 的块自成单栏节,
113
+ * 与分栏正文之间要插连续分节符——HTML 侧的 class 与 OOXML 侧的单栏节是同一件事) */
114
+ export const paraBlock = (para, spanAll = false) => makeBlock({ para, spanAll });
115
+
116
+ /** 表格块 */
117
+ export const tableBlock = (table) => makeBlock({ table });
118
+
119
+ /** 节边界块(内嵌 sectPr 所在位置;写出端据此在正文流中落该节的 sectPr) */
120
+ export const secBreakBlock = () => makeBlock({ secBreak: true });
121
+
122
+ /** 目录块(TOC 域的缓存行序列;写出端包回域幕,读端把域跨度收成这一个块) */
123
+ export const tocBlock = (blocks) => makeBlock({ toc: true, tocBlocks: blocks });
@@ -0,0 +1,129 @@
1
+ // [文件] web·docx·codec·carry —— 整部件透传:编辑器不建模但 Word 按关系类型发现的部件(theme/glossary/customXml/扩展属性)原样带过往返
2
+ /*
3
+ [设计] 为什么不是「未建模元素也保留」:ooxml 的树只存元素/属性/文本三段、不存原始字节与命名空间
4
+ 前缀(那是它不被没见过的元素整篇解析失败的前提)。元素级原文保留需要序列化器,属引擎级改造;
5
+ 整部件透传是同一目标下最小可用的一步——这些部件 Word 按关系类型发现,内容与我们写的部件正交。
6
+
7
+ [设计] 只带「关系闭包完整」的候选:闭包里任何一个目标解析不了(包内没有、或没有 Override
8
+ 内容类型——二进制嵌入物与只按扩展名声明内容类型的部件都过不了),整个候选放弃。
9
+ 宁可回到「不带」的现状,也不写悬空引用让 Word 判文件损坏。
10
+ */
11
+ import { parseNode, relsPath, resolveTarget } from 'gbooxml';
12
+ import { PART_DOCUMENT, PART_NUMBERING, PART_STYLES } from './parts.js';
13
+
14
+ /** 可透传的关系类型(Word 按类型从 document 关系表 / 包根关系表发现这些部件,与正文内容无引用耦合) */
15
+ const CARRY_TYPES = new Set([
16
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
17
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable',
18
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings',
19
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument',
20
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml',
21
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
22
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties'
23
+ ]);
24
+
25
+ /** 我们按原路径重写的部件:闭包指向它们 = 指向写出后的包,有效 */
26
+ const OWN_PARTS = new Set([PART_DOCUMENT, PART_STYLES, PART_NUMBERING]);
27
+
28
+ /** [Content_Types].xml 的 Override 表(部件路径 → 内容类型;只有 Override 的部件才谈得上原样透传) */
29
+ const contentTypes = (pkg) => {
30
+ const out = new Map();
31
+ const raw = pkg.part('[Content_Types].xml');
32
+ if (!raw) return out;
33
+ let tree;
34
+ try {
35
+ tree = parseNode(raw);
36
+ } catch {
37
+ return out;
38
+ }
39
+ for (const o of tree.children('Override')) out.set(o.attr('PartName').replace(/^\//, ''), o.attr('ContentType'));
40
+ return out;
41
+ };
42
+
43
+ /** 候选部件的关系闭包:它自己的 rels 文件 + 闭包里要连带透传的部件;解析不了返回 ok=false */
44
+ const closureOf = (pkg, cts, path, seen) => {
45
+ const parts = [];
46
+ const relsName = relsPath(path);
47
+ const relsRaw = pkg.part(relsName);
48
+ if (!relsRaw) return { ok: true, parts };
49
+ parts.push({ path: relsName, ct: '' }); // .rels 内容类型由 Default 覆盖,写出侧走 addRaw
50
+ let tree;
51
+ try {
52
+ tree = parseNode(relsRaw);
53
+ } catch {
54
+ return { ok: false, parts };
55
+ }
56
+ for (const r of tree.children('Relationship')) {
57
+ if (r.attr('TargetMode').toLowerCase() === 'external') continue; // 包外目标不随包走,也不影响包完整性
58
+ const target = resolveTarget(path, r.attr('Target'));
59
+ if (OWN_PARTS.has(target)) continue; // 我们原路径重写
60
+ if (target === '' || seen.has(target)) continue;
61
+ const ct = cts.get(target);
62
+ if (!ct || !pkg.part(target)) return { ok: false, parts };
63
+ seen.add(target);
64
+ parts.push({ path: target, ct });
65
+ const sub = closureOf(pkg, cts, target, seen);
66
+ if (!sub.ok) return { ok: false, parts: [...parts, ...sub.parts] };
67
+ parts.push(...sub.parts);
68
+ }
69
+ return { ok: true, parts };
70
+ };
71
+
72
+ /**
73
+ * 读入时收集可透传部件(字节直接引用包内已解压数据,不复制)
74
+ * [设计] 两遍式:先收齐顶层候选(关系类型命中的),再逐个算闭包——同一个部件既被 document
75
+ * 关系直接引用、又可能被别的候选连带时,顶层注册优先(降级成闭包件会丢掉 document 级关系,
76
+ * Word 就按类型找不到它了)。遍历顺序因此不影响结果。
77
+ * @param {import('gbooxml').OpcReader} pkg
78
+ * @returns {Array<{path:string,bytes:Uint8Array,ct:string,from:string|null,type:string,target:string}>}
79
+ * from 非 null = 顶层候选(写出时注册关系);null = 闭包连带部件(只加字节,关系由透传的 rels 文件承载)
80
+ */
81
+ export const collectCarry = (pkg) => {
82
+ const cts = contentTypes(pkg);
83
+ const taken = new Set();
84
+ const candidates = [];
85
+ const sources = [
86
+ { from: PART_DOCUMENT, rels: pkg.rels(PART_DOCUMENT) },
87
+ { from: '', rels: pkg.rels('') }
88
+ ];
89
+ for (const { from, rels } of sources) {
90
+ for (const rel of rels.values()) {
91
+ if (rel.external || !CARRY_TYPES.has(rel.type)) continue;
92
+ const target = resolveTarget(from, rel.target);
93
+ if (target === '' || taken.has(target)) continue;
94
+ const ct = cts.get(target);
95
+ const bytes = pkg.part(target);
96
+ if (!ct || !bytes) continue;
97
+ taken.add(target);
98
+ candidates.push({ path: target, bytes, ct, from, type: rel.type, target: rel.target });
99
+ }
100
+ }
101
+ const out = [];
102
+ for (const c of candidates) {
103
+ const closure = closureOf(pkg, cts, c.path, new Set([c.path]));
104
+ if (!closure.ok) continue; // 闭包不全:候选整体放弃(见文件头 [设计])
105
+ out.push(c);
106
+ for (const part of closure.parts) {
107
+ if (taken.has(part.path)) continue;
108
+ const bytes = pkg.part(part.path);
109
+ if (!bytes) continue;
110
+ taken.add(part.path);
111
+ out.push({ path: part.path, bytes, ct: part.ct, from: null, type: '', target: '' });
112
+ }
113
+ }
114
+ return out;
115
+ };
116
+
117
+ /**
118
+ * 写出时把透传部件装回包(顶层候选顺带注册关系;rId 由 OpcPackage 自动分配,不与正文图片冲突)
119
+ * @param {import('gbooxml').OpcPackage} pkg
120
+ * @param {Array} carry collectCarry 的产物
121
+ */
122
+ export const writeCarry = (pkg, carry) => {
123
+ for (const c of carry || []) {
124
+ if (!c?.bytes) continue;
125
+ if (c.ct) pkg.add(c.path, c.ct, c.bytes);
126
+ else pkg.addRaw(c.path, c.bytes);
127
+ if (c.from !== null) pkg.rel(c.from, c.type, c.target);
128
+ }
129
+ };
@@ -0,0 +1,25 @@
1
+ // [文件] web·docx·codec·comments —— 批注回读:comments.xml → 批注清单(写出侧见 parts.js 的 commentsPart)
2
+ import { parseNode } from 'gbooxml';
3
+ import { PART_COMMENTS } from './parts.js';
4
+
5
+ /**
6
+ * 解析 word/comments.xml。
7
+ * Key 用 docx 里的数字 id 字符串,与正文回读出的 data-cmt 对齐;部件缺失或损坏一律当作没有批注
8
+ * @param {import('gbooxml').OpcReader} pkg
9
+ */
10
+ export const parseComments = (pkg) => {
11
+ const raw = pkg.part(PART_COMMENTS);
12
+ if (!raw) return [];
13
+ let tree;
14
+ try {
15
+ tree = parseNode(raw);
16
+ } catch {
17
+ return [];
18
+ }
19
+ return tree.children('comment').map((c) => ({
20
+ key: c.attr('id'),
21
+ text: c.texts().join(' '),
22
+ author: c.attr('author'),
23
+ date: c.attr('date')
24
+ }));
25
+ };
@@ -0,0 +1,198 @@
1
+ // [文件] web·docx·codec·docx —— Document 模型、页面几何、单位换算与读写编排(前端 .docx 唯一出入口)
2
+ /*
3
+ 本模块把编辑器内存态的正文 HTML 子集与 WordprocessingML 互转,是 Word 文档以 .docx 读写的唯一入口。
4
+ 转换分两段:先归一到中间的块模型(paragraph/run/table 一套结构,见 blocks.js),再由两个方向各自消费——
5
+ 写出走「块模型 → OOXML 部件」,读回走「OOXML 部件 → 块模型 → HTML」。中间层把 HTML 的
6
+ 语义翻译与 OOXML 的拼装拆开,顺带让两个方向共用同一套块概念。
7
+
8
+ 支持的子集:段落(对齐/缩进/行距)、标题 H1~H6、粗斜下划线删除线、字体颜色/字号/字体族与文字底色、
9
+ 等宽代码段、超链接、无序与有序列表、表格(列宽/单元格底色/横向与纵向合并)、内嵌图片(data URL)、
10
+ 分隔线、引用块、分页符、页眉页脚与页码、纸张尺寸/方向/页边距/分栏、批注、修订标记(含作者/日期)、
11
+ 脚注与尾注(锚点 + 纯文本)、文档属性(docProps 标题/作者等)、整部件透传(theme/glossary/customXml 等)。
12
+
13
+ 不支持(读时忽略、写时丢弃):文本框与形状、域代码、SmartArt 等。
14
+ 这些内容读入时盘点成 losses 清单,保存前弹确认告知用户;写出的字节另做一次读回自检(codec/roundtrip.js)。
15
+ 旧版二进制 .doc 是 OLE 复合文档,按魔数明确拒收。
16
+ */
17
+
18
+ import { readDocument } from './read.js';
19
+ import { writeDocument } from './write.js';
20
+ import { PAGE_SIZES, defaultPageConf } from '../constants.js';
21
+
22
+ /** 页眉页脚重复模式。空串等价 HF_MODE.ALL——早于该设置存在的文档读回来就是空串 */
23
+ export const HF_MODE = {
24
+ ALL: 'all', // 每页显示同一段文字
25
+ EXCEPT_FIRST: 'except-first', // 除首页外每页显示
26
+ ODD_EVEN: 'odd-even', // 奇数页/偶数页各一份
27
+ ODD_EVEN_FIRST: 'odd-even-first', // 奇偶页各一份,且首页再单独一份(Word 的 titlePg + evenAndOddHeaders)
28
+ NONE: 'none' // 完全不显示
29
+ };
30
+
31
+ /** 该重复模式是否使用偶数页部件 */
32
+ export const hfUsesEven = (mode) => mode === HF_MODE.ODD_EVEN || mode === HF_MODE.ODD_EVEN_FIRST;
33
+
34
+ /** 该重复模式是否使用首页部件 */
35
+ export const hfUsesFirst = (mode) => mode === HF_MODE.EXCEPT_FIRST || mode === HF_MODE.ODD_EVEN_FIRST;
36
+
37
+ /** 页码的中文编号(w:pgNumType 的 w:fmt 取值;其余取值与缺省都是阿拉伯数字) */
38
+ export const PAGE_NUM_CHINESE = 'chinese';
39
+
40
+ /** 页码的短横格式「- 1 -」(w:pgNumType w:fmt="numberInDash",公文页码的标准写法) */
41
+ export const PAGE_NUM_DASH = 'dash';
42
+
43
+ /** 段落样式 id。这些 id 同时是前端编辑器的样式名与 OOXML 的 pStyle 值,改动会同时影响两端渲染 */
44
+ export const STYLE_TITLE = 'Title';
45
+ /**
46
+ * 富文本文档:HTML 是编辑器正文,其余按节(w:sectPr)组织
47
+ * @typedef {Object} Document
48
+ * @property {string} html 编辑器正文 HTML 子集(节边界是 <div class="doc-sectionbreak"> 块)
49
+ * @property {SectionConf[]} [sections] 节序列(文档序、末节收尾;渲染几何与写出都以它为准)
50
+ * @property {Comment[]} [comments] 批注
51
+ * @property {Array<{id:string,text:string}>} [footnotes] 脚注(正文锚点是 <sup class="doc-footnote" data-fn="id">)
52
+ * @property {Array<{id:string,text:string}>} [endnotes] 尾注(锚点 class 为 doc-endnote)
53
+ * @property {object} [props] 文档属性(docProps/core.xml 的标题/主题/作者/备注/最后修改者)
54
+ * @property {number} [defaultTabStop] 默认制表位(twips;缺省 720,非缺省值随 settings.xml 往返)
55
+ * @property {boolean} [compressPunctuation] 标点挤压(settings 的 characterSpacingControl=compressPunctuation)
56
+ * @property {Array} [carry] 整部件透传清单(theme/glossary/customXml 等,字节 + 关系定义;见 codec/carry.js)
57
+ * @property {Array<{kind:string,count:number}>} [losses] 读入时盘点的保存必丢清单(kind 标签表见 codec/losses.js)
58
+ */
59
+
60
+ /**
61
+ * 一节的设置(w:sectPr):纸张几何 + 页眉页脚 + 页码 + 水印
62
+ * @typedef {Object} SectionConf
63
+ * @property {string} [type] 节切换类型(continuous/nextPage/evenPage/oddPage;空 = 缺省 nextPage)
64
+ * @property {PageConf} [page] 该节的页面几何
65
+ * @property {string} [hfMode] 该节的页眉页脚重复模式
66
+ * @property {string} [header] 该节页眉
67
+ * @property {string} [footer] 该节页脚
68
+ * @property {string} [headerEven] 该节偶数页页眉(仅奇偶模式写部件)
69
+ * @property {string} [footerEven] 该节偶数页页脚(仅奇偶模式写部件)
70
+ * @property {string} [headerFirst] 该节首页页眉(仅首页不同模式写部件)
71
+ * @property {string} [footerFirst] 该节首页页脚(仅首页不同模式写部件)
72
+ * @property {PageNumberConf} [pageNumbers] 该节页码设置
73
+ * @property {WatermarkConf} [watermark] 该节水印
74
+ */
75
+
76
+ /**
77
+ * @typedef {Object} Comment 一条批注。正文锚点是 <span class="doc-comment" data-cmt="键">,Key 进 docx 时映射为数字 id
78
+ * @property {string} key
79
+ * @property {string} text
80
+ * @property {string} [author]
81
+ * @property {string} [date]
82
+ */
83
+
84
+ /**
85
+ * 页码设置。落进页脚部件的 PAGE 域 + 节属性的 w:pgNumType
86
+ * @typedef {Object} PageNumberConf
87
+ * @property {boolean} enabled
88
+ * @property {string} [align] left | center | right;空串 = left
89
+ * @property {string} [format] arabic | chinese;空串 = arabic
90
+ * @property {number} [start] 起始页码;<=0 视为 1
91
+ */
92
+
93
+ /**
94
+ * 页面几何(页边距单位毫米)
95
+ * @typedef {Object} PageConf
96
+ * @property {string} [size] A4 | Letter | Legal
97
+ * @property {string} [orientation] portrait | landscape
98
+ * @property {{top:number,right:number,bottom:number,left:number}} [margins]
99
+ * @property {number} [columns] 分栏数(0/1 = 单栏)
100
+ * @property {number} [colGap] 栏间距,毫米
101
+ * @property {boolean} [colSeparator] 栏间分隔线(w:cols 的 w:sep)
102
+ * @property {number} [headerTop] 页眉距纸张上边缘,毫米(0 = Word 默认 12.7)
103
+ * @property {number} [footerBottom] 页脚距纸张下边缘,毫米(0 = Word 默认 12.7)
104
+ */
105
+
106
+ /**
107
+ * 页面水印(落进页眉部件的 VML 图形——Word 的水印就是页眉里的一张倾斜文字图)
108
+ * [设计] 不设「平铺」字段:Word 的水印靠页眉每页重复,一页就一个图形,OOXML 侧没有平铺表达,
109
+ * 留着它只能是一次会话内生效、存盘即丢的假开关。
110
+ * @typedef {Object} WatermarkConf
111
+ * @property {string} [data] 水印文字
112
+ * @property {string} [color] #rrggbb
113
+ * @property {number} [size] 字号(pt)
114
+ * @property {number} [opacity] 透明度与 Word 的 VML 口径一致(0~1)
115
+ */
116
+
117
+ /**
118
+ * 解析 .docx 为 Document(读回方向总入口,走 read.js)
119
+ * @param {Uint8Array|ArrayBuffer} data
120
+ * @returns {Promise<Document>}
121
+ */
122
+ export const parseDocx = (data) => readDocument(data);
123
+
124
+ /**
125
+ * 把 Document 打成 .docx(写出方向总入口,走 write.js)
126
+ * @param {Document} doc
127
+ * @returns {Promise<Uint8Array>}
128
+ */
129
+ export const buildDocx = (doc) => writeDocument(doc);
130
+
131
+ /* ---------- 单位换算 ---------- */
132
+
133
+ /** twips:二十分之一点。1 英寸 = 25.4mm = 1440 twips,这一串比例是换算的全部依据 */
134
+ const TWIPS_PER_MM = 1440 / 25.4;
135
+
136
+ /** 96dpi 下 1px = 1/96 英寸 */
137
+ const TWIPS_PER_PX = 15;
138
+
139
+ /** 保留一位小数(页面几何回读要毫米级的稳定值,多出来的浮点尾巴会让页面设置反复漂移) */
140
+ export const round1 = (v) => Math.round(v * 10) / 10;
141
+
142
+ export const mmToTwips = (mm) => Math.round(mm * TWIPS_PER_MM);
143
+ export const twipsToMM = (tw) => tw / TWIPS_PER_MM;
144
+
145
+ /** 纸张尺寸(twips,纵向)。Word 的 pgSz 就用这套数,回读时按最近者归名
146
+ * [设计] 由 constants.js 的 mm 表经 mmToTwips 派生,不另立一份 twips 表(同纸两套单位,改一处必漏一处) */
147
+ export const PAGE_SIZES_TWIPS = Object.fromEntries(
148
+ Object.entries(PAGE_SIZES).map(([name, { w, h }]) => [name, [mmToTwips(w), mmToTwips(h)]])
149
+ );
150
+ export const pxToTwips = (px) => Math.round(px * TWIPS_PER_PX);
151
+ export const twipsToPx = (tw) => tw / TWIPS_PER_PX;
152
+
153
+ /** 1px = 0.75pt,w:sz 以半点计 */
154
+ export const pxToHalfPoints = (px) => Math.round(px * 1.5);
155
+ export const halfPointsToPx = (hp) => hp / 1.5;
156
+
157
+ /**
158
+ * Word 单倍行高相对字号的倍数:Microsoft YaHei 10.5pt 的单倍行高实测 18pt(24px),即 24/14。
159
+ * 行距 auto 是「相对于单倍行高」的倍数,而 CSS 的 line-height 是「相对于字号」的倍数——
160
+ * 两侧换算必须过这个比值,否则编辑器里的 1.25 行会被 Word 当成 1.25 × 24px 排成两倍高。
161
+ * [约束] Word 的单倍行高随字体自带度量走:本值只对正文默认字体(导出侧写的就是 Microsoft YaHei)成立;
162
+ * 整篇换用其他字体后,Word 的行高会按该字体度量变化,编辑器则始终按字号 × 倍数排版。
163
+ */
164
+ const WORD_LINE_RATIO = 12 / 7;
165
+
166
+ /** CSS 行距倍数 → w:line(lineRule=auto):1.0 倍 = 140 */
167
+ export const cssLineToWord = (cssLine) => Math.round((cssLine * 240) / WORD_LINE_RATIO);
168
+
169
+ /** w:line(lineRule=auto)→ CSS 行距倍数 */
170
+ export const wordLineToCss = (wordLine) => (wordLine * WORD_LINE_RATIO) / 240;
171
+
172
+ /** 保留两位小数:twips 折 px、字号半点折 px 这类值取整会让整篇宽度/高度累积出可见误差 */
173
+ export const round2 = (v) => Math.round(v * 100) / 100;
174
+
175
+ /** 百分比写成 "25" 而不是 "25.00"(OOXML 的百分比属性对冗余小数不友好) */
176
+ export const pctText = (v) => String(round2(v));
177
+
178
+ /* ---------- 纸张几何 ---------- */
179
+
180
+ /** 纸张尺寸(毫米,纵向)——尺寸表唯一源是 constants.js 的 PAGE_SIZES(未知档回落 A4) */
181
+ const paperMM = (size, orientation) => {
182
+ const { w, h } = PAGE_SIZES[size] || PAGE_SIZES.A4;
183
+ return orientation === 'landscape' ? [h, w] : [w, h];
184
+ };
185
+
186
+ /** 正文栏宽(纸宽减左右页边距) */
187
+ export const textWidthMM = (pc) => {
188
+ const p = pc || defaultPageConf();
189
+ let left = 25.4;
190
+ let right = 25.4;
191
+ if (p.margins) {
192
+ left = p.margins.left;
193
+ right = p.margins.right;
194
+ }
195
+ const [w] = paperMM(p.size, p.orientation);
196
+ const width = w - left - right;
197
+ return width > 10 ? width : 210 - 50.8;
198
+ };
@@ -0,0 +1,177 @@
1
+ // [文件] web·docx·codec·docxStyles —— styles.xml 与 theme1.xml 的读数(主题调色板 / 表样式定义;渲染端据此摊平)
2
+ import { isHexColor, parseNode, resolveTarget } from 'gbooxml';
3
+ import { attrIntOf } from './helpers.js';
4
+ import { PART_DOCUMENT, PART_STYLES } from './parts.js';
5
+
6
+ /** themeColor 名 → clrScheme 元素名(OOXML 里同一批颜色有两套命名) */
7
+ const THEME_ALIAS = { dark1: 'dk1', light1: 'lt1', dark2: 'dk2', light2: 'lt2', hyperlink: 'hlink', followedHyperlink: 'folHlink' };
8
+
9
+ /** 十六进制颜色向目标色按比例混合(0 = 原色,1 = 全目标色) */
10
+ const mixHex = (hex, target, ratio) => {
11
+ let out = '';
12
+ for (let i = 0; i < 6; i += 2) {
13
+ const a = Number.parseInt(hex.slice(i, i + 2), 16);
14
+ const b = Number.parseInt(target.slice(i, i + 2), 16);
15
+ out += Math.round(a + (b - a) * ratio)
16
+ .toString(16)
17
+ .padStart(2, '0');
18
+ }
19
+ return out;
20
+ };
21
+
22
+ /** 主题调色板:theme1.xml 的 clrScheme(路径按 document 关系表找,不扫目录);解析不出返回 null */
23
+ export const themePalette = (pkg) => {
24
+ for (const rel of pkg.rels(PART_DOCUMENT).values()) {
25
+ if (rel.external || !rel.type.endsWith('/theme')) continue;
26
+ const raw = pkg.part(resolveTarget(PART_DOCUMENT, rel.target));
27
+ if (!raw) continue;
28
+ let scheme;
29
+ try {
30
+ scheme = parseNode(raw).find('themeElements', 'clrScheme');
31
+ } catch {
32
+ return null;
33
+ }
34
+ if (!scheme) return null;
35
+ const out = {};
36
+ for (const slot of scheme.kids) {
37
+ // srgbClr 的色值在 val;sysClr 的 val 是系统色名、实际色在 lastClr
38
+ const color = slot.child('srgbClr') || slot.child('sysClr');
39
+ if (!color) continue;
40
+ const v = color.attr('lastClr') || color.attr('val');
41
+ if (isHexColor(v)) out[slot.name] = v.toLowerCase();
42
+ }
43
+ return Object.keys(out).length ? out : null;
44
+ }
45
+ return null;
46
+ };
47
+
48
+ /**
49
+ * 主题色名 + tint/shade → 显示色 "#rrggbb"
50
+ * [口径] tint 向白混合、shade 向黑混合,比例是 OOXML 的两位 hex / 255;
51
+ * 无主题部件或名不识别返回 ''(调用方不写颜色样式)
52
+ */
53
+ export const themeColorOf = (rd, name, tint, shade) => {
54
+ if (!rd.theme) return '';
55
+ let hex = rd.theme[THEME_ALIAS[name] || name];
56
+ if (!hex) return '';
57
+ const ratio = (v) => {
58
+ const n = Number.parseInt(v, 16);
59
+ return Number.isInteger(n) && n >= 0 && n <= 255 ? n / 255 : 0;
60
+ };
61
+ if (tint !== '') hex = mixHex(hex, 'ffffff', ratio(tint));
62
+ else if (shade !== '') hex = mixHex(hex, '000000', ratio(shade));
63
+ return `#${hex}`;
64
+ };
65
+
66
+ /* ---------- 表样式(styles.xml 的 w:style type=table) ---------- */
67
+
68
+ /**
69
+ * 一个 tblPr 的边框/边距读数
70
+ * [口径] 表样式的 tblPr 与文档里表格自己的直接 tblPr 是同一套属性,读数只写这一份:
71
+ * bdr = '' 表示没声明(调用方才回退到表样式),'none' 是显式「不要框线」,不能被当成没声明。
72
+ */
73
+ export const tblPrFacts = (tblPr) => {
74
+ const facts = {};
75
+ if (!tblPr) return facts;
76
+ const bdrs = tblPr.child('tblBorders');
77
+ if (bdrs) {
78
+ const sides = ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']
79
+ .map((name) => bdrs.child(name))
80
+ .filter((n) => n !== null);
81
+ const drawn = sides.find((n) => {
82
+ const val = n.attr('val');
83
+ return val !== '' && val !== 'none' && val !== 'nil';
84
+ });
85
+ if (drawn) {
86
+ const sz = attrIntOf(drawn, 'sz');
87
+ const color = drawn.attr('color');
88
+ facts.bdr = `single:${sz > 0 ? sz : 4}:${isHexColor(color) ? color.toLowerCase() : 'd0d7de'}`;
89
+ } else if (sides.length) facts.bdr = 'none';
90
+ }
91
+ const mar = tblPr.child('tblCellMar');
92
+ if (mar) {
93
+ const side = (name) => attrIntOf(mar.child(name), 'w');
94
+ const t = side('top');
95
+ const l = side('left');
96
+ const b = side('bottom');
97
+ const r = side('right');
98
+ if (t > 0 || l > 0 || b > 0 || r > 0) facts.mar = `${t}:${l}:${b}:${r}`;
99
+ }
100
+ return facts;
101
+ };
102
+
103
+ /** 单个表样式节点自己的读数(边框线 / 单元格边距 / 首行与隔行条件) */
104
+ const styleFacts = (node) => {
105
+ const facts = tblPrFacts(node.find('tblPr'));
106
+ const cond = (type) => node.children('tblStylePr').find((c) => c.attr('type') === type);
107
+ const firstRow = cond('firstRow');
108
+ if (firstRow) {
109
+ const b = firstRow.find('rPr', 'b');
110
+ if (b && b.attr('val') !== '0' && b.attr('val') !== 'false') facts.firstRowBold = true;
111
+ const fill = firstRow.find('tcPr', 'shd')?.attr('fill');
112
+ if (isHexColor(fill) && fill.toLowerCase() !== 'auto') facts.firstRowShade = fill.toLowerCase();
113
+ }
114
+ const shadeOfCond = (type) => {
115
+ const fill = cond(type)?.find('tcPr', 'shd')?.attr('fill');
116
+ return isHexColor(fill) && fill.toLowerCase() !== 'auto' ? fill.toLowerCase() : '';
117
+ };
118
+ const b1 = shadeOfCond('band1Horz');
119
+ const b2 = shadeOfCond('band2Horz');
120
+ if (b1) facts.band1 = b1;
121
+ if (b2) facts.band2 = b2;
122
+ return facts;
123
+ };
124
+
125
+ /** 表样式定义表:styleId → 读数(basedOn 递归合并,父为底子覆盖) */
126
+ export const tableStylesOf = (pkg) => {
127
+ const out = new Map();
128
+ const raw = pkg.part(PART_STYLES);
129
+ if (!raw) return out;
130
+ let tree;
131
+ try {
132
+ tree = parseNode(raw);
133
+ } catch {
134
+ return out;
135
+ }
136
+ const defs = new Map();
137
+ for (const s of tree.children('style')) {
138
+ if (s.attr('type') === 'table') defs.set(s.attr('styleId'), s);
139
+ }
140
+ const resolve = (id, seen) => {
141
+ const node = defs.get(id);
142
+ if (!node || seen.has(id)) return {};
143
+ seen.add(id);
144
+ return { ...resolve(node.child('basedOn')?.attr('val') || '', seen), ...styleFacts(node) };
145
+ };
146
+ for (const id of defs.keys()) out.set(id, resolve(id, new Set()));
147
+ return out;
148
+ };
149
+
150
+ /**
151
+ * 表格的有效外观(tblStyle 定义 + tblLook 门控条件格式)
152
+ * [设计] 条件格式门控:无 tblLook 节点一律不应用(旧式表缺省);布尔属性优先,老式 val 位掩码兜底
153
+ * @returns {null|{bdr:string, mar:string, firstRowBold:boolean, firstRowShade:string, band1:string, band2:string}}
154
+ */
155
+ export const tableStyleOf = (rd, tbl) => {
156
+ const id = tbl.find('tblPr', 'tblStyle')?.attr('val') || '';
157
+ if (id === '' || !rd.tableStyles.has(id)) return null;
158
+ const facts = rd.tableStyles.get(id);
159
+ const look = tbl.find('tblPr', 'tblLook');
160
+ const on = (name, bit, dflt) => {
161
+ const v = look ? look.attr(name) : '';
162
+ if (v !== '') return v !== '0' && v !== 'false';
163
+ const mask = Number.parseInt(look?.attr('val') || '', 16);
164
+ if (!Number.isInteger(mask)) return dflt;
165
+ return (mask & bit) !== 0;
166
+ };
167
+ const firstRowOn = on('firstRow', 0x0020, false);
168
+ const hBandOff = on('noHBand', 0x0200, true);
169
+ return {
170
+ bdr: facts.bdr || '',
171
+ mar: facts.mar || '',
172
+ firstRowBold: firstRowOn && Boolean(facts.firstRowBold),
173
+ firstRowShade: firstRowOn ? facts.firstRowShade || '' : '',
174
+ band1: hBandOff ? '' : facts.band1 || '',
175
+ band2: hBandOff ? '' : facts.band2 || ''
176
+ };
177
+ };