@open-document/core 0.10.0 → 0.12.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 (86) hide show
  1. package/dist/{build-DJMLK50m.js → build-DfUfpeTR.js} +1 -1
  2. package/dist/{check-CUKuufBm.js → check-CHxiOkQG.js} +3 -3
  3. package/dist/cli/bin.js +20 -33
  4. package/dist/{config-CvzpyAUA.js → config-9IdbhVuT.js} +2015 -725
  5. package/dist/{context-B4ip7SoI.js → context-BLI1-64_.js} +2 -2
  6. package/dist/{dev-dnH7DTlD.js → dev-yNYKv5mm.js} +1 -1
  7. package/dist/{diff-QTo0A5Rx.js → diff-Bs205mOx.js} +2 -2
  8. package/dist/{export-BrRFrexj.js → export-tkquS5O5.js} +11 -4
  9. package/dist/{import-C14Vn9ER.js → import-D1hIKIr3.js} +3 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +63 -28
  12. package/dist/ops/index.d.ts +111 -2
  13. package/dist/ops/index.js +3 -3
  14. package/dist/{ops-DKidjLXP.js → ops-Dgqujq5a.js} +85 -164
  15. package/dist/package-version-C89gtYSk.js +36 -0
  16. package/dist/{preview-wKM4C6Uk.js → preview-BImdTH6K.js} +1 -1
  17. package/dist/{sdk-CpDEGRIo.d.ts → sdk-CHEGeINh.d.ts} +46 -1
  18. package/dist/templates-DT5zzqHq.js +34 -0
  19. package/dist/vite/index.js +1 -1
  20. package/package.json +2 -1
  21. package/skills/apply-comments/SKILL.md +3 -1
  22. package/skills/create-doc/SKILL.md +2 -0
  23. package/skills/doc-authoring/SKILL.md +2 -0
  24. package/src/app/components/browser/browser-ui.tsx +21 -0
  25. package/src/app/components/browser/new-document-dialog.tsx +208 -0
  26. package/src/app/components/changes/changes-overlay.tsx +68 -0
  27. package/src/app/components/changes/changes-panel.tsx +341 -0
  28. package/src/app/components/changes/use-changes.ts +85 -0
  29. package/src/app/components/comments/comments-overlay.tsx +50 -0
  30. package/src/app/components/comments/comments-panel.tsx +272 -0
  31. package/src/app/components/comments/use-comments.ts +61 -0
  32. package/src/app/components/doc-sidebar.tsx +32 -2
  33. package/src/app/components/inspector/field-source.tsx +41 -0
  34. package/src/app/components/inspector/format-section.tsx +434 -0
  35. package/src/app/components/inspector/inspector.tsx +311 -118
  36. package/src/app/components/inspector/use-style-edits.ts +210 -0
  37. package/src/app/components/overlay-frame.tsx +79 -0
  38. package/src/app/components/page-frame.tsx +4 -0
  39. package/src/app/components/page-placement.ts +68 -0
  40. package/src/app/components/panel/fields.tsx +95 -7
  41. package/src/app/components/record-picker.tsx +79 -0
  42. package/src/app/components/themes/theme-preview.tsx +5 -4
  43. package/src/app/lib/agent-bridge.ts +29 -1
  44. package/src/app/lib/docx/ooxml.test.ts +24 -1
  45. package/src/app/lib/docx/ooxml.ts +27 -1
  46. package/src/app/lib/export-docx.ts +3 -1
  47. package/src/app/lib/export-dom.ts +2 -1
  48. package/src/app/lib/export-html.ts +4 -2
  49. package/src/app/lib/export-image.ts +2 -1
  50. package/src/app/lib/flow-measure.test.ts +30 -0
  51. package/src/app/lib/flow-measure.ts +35 -10
  52. package/src/app/lib/i18n-ja/browser.ts +10 -0
  53. package/src/app/lib/i18n-ja/doc.ts +4 -0
  54. package/src/app/lib/i18n-ja/panels.ts +92 -5
  55. package/src/app/lib/i18n-ko/browser.ts +10 -0
  56. package/src/app/lib/i18n-ko/doc.ts +4 -0
  57. package/src/app/lib/i18n-ko/panels.ts +90 -5
  58. package/src/app/lib/i18n-zh-cn/browser.ts +10 -0
  59. package/src/app/lib/i18n-zh-cn/doc.ts +4 -0
  60. package/src/app/lib/i18n-zh-cn/panels.ts +88 -5
  61. package/src/app/lib/i18n-zh-tw/browser.ts +10 -0
  62. package/src/app/lib/i18n-zh-tw/doc.ts +4 -0
  63. package/src/app/lib/i18n-zh-tw/panels.ts +88 -5
  64. package/src/app/lib/inspector/format.ts +156 -0
  65. package/src/app/lib/records.test.ts +38 -0
  66. package/src/app/lib/records.ts +127 -0
  67. package/src/app/lib/sdk.ts +29 -0
  68. package/src/app/lib/use-doc-module.ts +7 -0
  69. package/src/app/lib/use-doc-pages.ts +15 -9
  70. package/src/app/routes/doc.tsx +274 -11
  71. package/src/app/routes/home.tsx +30 -5
  72. package/src/app/styles.css +23 -0
  73. package/templates/blank/index.tsx +63 -0
  74. package/templates/blank/template.json +6 -0
  75. package/templates/certificate/data/recipients.csv +4 -0
  76. package/templates/certificate/index.tsx +128 -0
  77. package/templates/certificate/template.json +6 -0
  78. package/templates/letter/index.tsx +106 -0
  79. package/templates/letter/template.json +5 -0
  80. package/templates/meeting-notes/index.tsx +194 -0
  81. package/templates/meeting-notes/template.json +6 -0
  82. package/templates/proposal/index.tsx +264 -0
  83. package/templates/proposal/template.json +6 -0
  84. package/templates/report/data/metrics.csv +5 -0
  85. package/templates/report/index.tsx +224 -0
  86. package/templates/report/template.json +6 -0
@@ -61,4 +61,8 @@ export const DOC: Record<string, string> = {
61
61
  'Actual size (100%)': '实际大小 (100%)',
62
62
  'Link copied': '已复制链接',
63
63
  'Copy link': '复制链接',
64
+ Record: '数据行',
65
+ 'Previous record': '上一条数据',
66
+ 'Next record': '下一条数据',
67
+ Certificate: '证书',
64
68
  };
@@ -86,13 +86,96 @@ export const PANELS: Record<string, string> = {
86
86
  'Click to select · double-click to edit · Esc to leave': '单击选中 · 双击编辑 · Esc 退出',
87
87
  Element: '元素',
88
88
  Close: '关闭',
89
- 'Editing on the page. Enter keeps the change, Shift+Enter starts a new line, Esc reverts it.':
90
- '正在页面上编辑。按 Enter 保留更改,Shift+Enter 换行,Esc 还原。',
91
- 'Double-click the text on the page, or press Enter, to edit it where it is printed.':
92
- '在页面上双击文字或按 Enter,即可在其打印位置直接编辑。',
93
- 'Inline markup stays as written.': '行内标记会保持原样。',
94
89
  'Not editable here.': '无法在此编辑。',
95
90
  'Comment for the agent': '给 agent 的注释',
96
91
  'make this bold, shorten to one line…': '改为粗体、缩短为一行…',
97
92
  'Mark comment': '标记注释',
93
+ Typography: '字体排印',
94
+ Color: '颜色',
95
+ Font: '字体',
96
+ Size: '大小',
97
+ 'Size in pixels': '大小(像素)',
98
+ Weight: '粗细',
99
+ 'Line height': '行高',
100
+ 'Letter spacing in pixels': '字距(像素)',
101
+ Fill: '填色',
102
+ Background: '背景',
103
+ None: '无',
104
+ Inherited: '继承',
105
+ 'From {name}': '来自 {name}',
106
+ 'from {name}': '来自 {name}',
107
+ 'set in code: {code}': '由代码设置:{code}',
108
+ Custom: '自定义',
109
+ 'Align left': '左对齐',
110
+ 'Align center': '居中对齐',
111
+ 'Align right': '右对齐',
112
+ Justify: '两端对齐',
113
+ 'This is a component — its styles are set inside it, not here.':
114
+ '这是组件,它的样式在组件内部设置,不在这里。',
115
+ 'This element’s style is not written as an object.': '这个元素的 style 不是以对象编写的。',
116
+ 'source does not match this element': '源码与这个元素不符',
117
+ 'element not found': '找不到元素',
118
+ 'Light 300': '细 300',
119
+ 'Regular 400': '常规 400',
120
+ 'Medium 500': '中等 500',
121
+ 'Semibold 600': '半粗 600',
122
+ 'Bold 700': '粗 700',
123
+ 'Extrabold 800': '特粗 800',
124
+ 'Heading {level}': '标题 {level}',
125
+ Paragraph: '段落',
126
+ List: '列表',
127
+ Table: '表格',
128
+ Image: '图片',
129
+ Box: '区块',
130
+ Alignment: '对齐',
131
+ Emphasis: '强调',
132
+ 'Edit on page': '在页面上编辑',
133
+ Source: '源码',
134
+ Location: '位置',
135
+ 'Letter spacing': '字距',
136
+ 'Text color': '文字颜色',
137
+ '{label} token': '{label} token',
138
+ 'Inherited font': '继承的字体',
139
+ '{name} font': '{name}字体',
140
+ 'Custom font': '自定义字体',
141
+ Done: '完成',
142
+ '{count} elements print from this line of source': '这一行源码输出 {count} 个元素',
143
+ Changes: '变更',
144
+ 'Changes ({count})': '变更({count})',
145
+ 'Changes since the last commit': '上次 commit 之后的变更',
146
+ 'Close the changes panel': '关闭变更面板',
147
+ 'Show changes since the last commit': '显示上次 commit 之后的变更',
148
+ 'Previous change': '上一个变更',
149
+ 'Next change': '下一个变更',
150
+ Since: '比较',
151
+ 'Compare with': '比较对象',
152
+ 'Last commit': '上次 commit',
153
+ 'git is not installed': '没有安装 git',
154
+ 'Not a git repository': '不是 git 仓库',
155
+ 'No changes': '没有变更',
156
+ 'Page {page}, changed': '第 {page} 页,有变更',
157
+ Files: '文件',
158
+ 'Revert this change': '还原这个变更',
159
+ 'that change is no longer there — reload the changes': '这个变更已经不在了,请重新加载变更',
160
+ 'the file changed since the diff was read': '读取差异之后文件又被改过了',
161
+ 'reverting this change alone would break the source — revert the changes around it too':
162
+ '单独还原这个变更会让源码出错,请连同周围的变更一起还原',
163
+ 'a binary file cannot be reverted here': '二进制文件无法在这里还原',
164
+ 'this workspace is not under git': '这个工作区没有使用 git',
165
+ Comments: '评论',
166
+ 'Comments ({count})': '评论({count})',
167
+ 'Close the comments panel': '关闭评论面板',
168
+ 'Show comments': '显示评论',
169
+ 'New comment': '新建评论',
170
+ Resolve: '标为已解决',
171
+ 'Copy request for the agent': '复制给 Agent 的指令',
172
+ 'No comments': '没有评论',
173
+ 'p.{page}': '第 {page} 页',
174
+ 'Page {page}, with comments': '第 {page} 页,有评论',
175
+ 'Could not resolve the comment': '无法标为已解决',
176
+ 'Pick an element on the page': '在页面上点选元素',
177
+ 'Click the element to comment on · Esc to cancel': '点选要评论的元素 · Esc 取消',
178
+ Records: '数据',
179
+ 'Row {row} of {count}': '第 {row} 行,共 {count} 行',
180
+ 'Esc to deselect': 'Esc 取消选取',
98
181
  };
@@ -81,4 +81,14 @@ export const BROWSER: Record<string, string> = {
81
81
  'Light theme': '淺色主題',
82
82
  'Dark theme': '深色主題',
83
83
  'System theme': '系統主題',
84
+ 'New document': '新增文件',
85
+ Template: '範本',
86
+ 'This workspace': '這個工作區',
87
+ Create: '建立',
88
+ 'Could not create the document': '無法建立文件',
89
+ Blank: '空白',
90
+ Report: '報告',
91
+ Proposal: '提案',
92
+ 'Meeting notes': '會議紀錄',
93
+ Letter: '信函',
84
94
  };
@@ -61,4 +61,8 @@ export const DOC: Record<string, string> = {
61
61
  'Actual size (100%)': '實際大小 (100%)',
62
62
  'Link copied': '已複製連結',
63
63
  'Copy link': '複製連結',
64
+ Record: '資料列',
65
+ 'Previous record': '上一筆資料',
66
+ 'Next record': '下一筆資料',
67
+ Certificate: '證書',
64
68
  };
@@ -87,13 +87,96 @@ export const PANELS: Record<string, string> = {
87
87
  'Click to select · double-click to edit · Esc to leave': '按一下選取 · 按兩下編輯 · Esc 離開',
88
88
  Element: '元素',
89
89
  Close: '關閉',
90
- 'Editing on the page. Enter keeps the change, Shift+Enter starts a new line, Esc reverts it.':
91
- '正在頁面上編輯。按 Enter 保留變更,Shift+Enter 換行,Esc 還原。',
92
- 'Double-click the text on the page, or press Enter, to edit it where it is printed.':
93
- '在頁面上按兩下文字或按 Enter,即可直接在印出的位置編輯。',
94
- 'Inline markup stays as written.': '行內標記會維持原樣。',
95
90
  'Not editable here.': '無法在這裡編輯。',
96
91
  'Comment for the agent': '給 agent 的註解',
97
92
  'make this bold, shorten to one line…': '改成粗體、縮短成一行…',
98
93
  'Mark comment': '標記註解',
94
+ Typography: '字體排印',
95
+ Color: '顏色',
96
+ Font: '字型',
97
+ Size: '大小',
98
+ 'Size in pixels': '大小(像素)',
99
+ Weight: '粗細',
100
+ 'Line height': '行高',
101
+ 'Letter spacing in pixels': '字距(像素)',
102
+ Fill: '填色',
103
+ Background: '背景',
104
+ None: '無',
105
+ Inherited: '繼承',
106
+ 'From {name}': '來自 {name}',
107
+ 'from {name}': '來自 {name}',
108
+ 'set in code: {code}': '由程式碼設定:{code}',
109
+ Custom: '自訂',
110
+ 'Align left': '靠左對齊',
111
+ 'Align center': '置中對齊',
112
+ 'Align right': '靠右對齊',
113
+ Justify: '左右對齊',
114
+ 'This is a component — its styles are set inside it, not here.':
115
+ '這是元件,它的樣式在元件內部設定,不在這裡。',
116
+ 'This element’s style is not written as an object.': '這個元素的 style 不是以物件撰寫的。',
117
+ 'source does not match this element': '原始碼與這個元素不符',
118
+ 'element not found': '找不到元素',
119
+ 'Light 300': '細 300',
120
+ 'Regular 400': '一般 400',
121
+ 'Medium 500': '中等 500',
122
+ 'Semibold 600': '半粗 600',
123
+ 'Bold 700': '粗 700',
124
+ 'Extrabold 800': '特粗 800',
125
+ 'Heading {level}': '標題 {level}',
126
+ Paragraph: '段落',
127
+ List: '清單',
128
+ Table: '表格',
129
+ Image: '圖片',
130
+ Box: '區塊',
131
+ Alignment: '對齊',
132
+ Emphasis: '強調',
133
+ 'Edit on page': '在頁面上編輯',
134
+ Source: '原始碼',
135
+ Location: '位置',
136
+ 'Letter spacing': '字距',
137
+ 'Text color': '文字顏色',
138
+ '{label} token': '{label} token',
139
+ 'Inherited font': '繼承的字型',
140
+ '{name} font': '{name}字型',
141
+ 'Custom font': '自訂字型',
142
+ Done: '完成',
143
+ '{count} elements print from this line of source': '這一行原始碼印出 {count} 個元素',
144
+ Changes: '變更',
145
+ 'Changes ({count})': '變更({count})',
146
+ 'Changes since the last commit': '上次 commit 之後的變更',
147
+ 'Close the changes panel': '關閉變更面板',
148
+ 'Show changes since the last commit': '顯示上次 commit 之後的變更',
149
+ 'Previous change': '上一個變更',
150
+ 'Next change': '下一個變更',
151
+ Since: '比較',
152
+ 'Compare with': '比較對象',
153
+ 'Last commit': '上次 commit',
154
+ 'git is not installed': '沒有安裝 git',
155
+ 'Not a git repository': '不是 git 儲存庫',
156
+ 'No changes': '沒有變更',
157
+ 'Page {page}, changed': '第 {page} 頁,有變更',
158
+ Files: '檔案',
159
+ 'Revert this change': '還原這個變更',
160
+ 'that change is no longer there — reload the changes': '這個變更已經不在了,請重新載入變更',
161
+ 'the file changed since the diff was read': '讀取差異之後檔案又被改過了',
162
+ 'reverting this change alone would break the source — revert the changes around it too':
163
+ '單獨還原這個變更會讓原始碼出錯,請連同周圍的變更一起還原',
164
+ 'a binary file cannot be reverted here': '二進位檔無法在這裡還原',
165
+ 'this workspace is not under git': '這個工作區沒有使用 git',
166
+ Comments: '留言',
167
+ 'Comments ({count})': '留言({count})',
168
+ 'Close the comments panel': '關閉留言面板',
169
+ 'Show comments': '顯示留言',
170
+ 'New comment': '新增留言',
171
+ Resolve: '標為已解決',
172
+ 'Copy request for the agent': '複製給 Agent 的指令',
173
+ 'No comments': '沒有留言',
174
+ 'p.{page}': '第 {page} 頁',
175
+ 'Page {page}, with comments': '第 {page} 頁,有留言',
176
+ 'Could not resolve the comment': '無法標為已解決',
177
+ 'Pick an element on the page': '在頁面上點選元素',
178
+ 'Click the element to comment on · Esc to cancel': '點選要留言的元素 · Esc 取消',
179
+ Records: '資料',
180
+ 'Row {row} of {count}': '第 {row} 列,共 {count} 列',
181
+ 'Esc to deselect': 'Esc 取消選取',
99
182
  };
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The element panel's Format section, shared by the viewer and the dev server:
3
+ * which style keys it may write, which design tokens each one offers, and what
4
+ * a value has to look like before it is spliced into a document's source.
5
+ */
6
+
7
+ export const STYLE_PROPS = [
8
+ 'fontFamily',
9
+ 'fontSize',
10
+ 'fontWeight',
11
+ 'fontStyle',
12
+ 'textAlign',
13
+ 'lineHeight',
14
+ 'letterSpacing',
15
+ 'color',
16
+ 'background',
17
+ ] as const;
18
+
19
+ export type StyleProp = (typeof STYLE_PROPS)[number];
20
+
21
+ /** `null` takes the key off the element, so the value comes from wherever it did before. */
22
+ export type StyleValue = string | number | null;
23
+ export type StyleChanges = Partial<Record<StyleProp, StyleValue>>;
24
+
25
+ /** What the source says about one key: a literal, a design token, or code the panel can only show. */
26
+ export type StyleSource =
27
+ | { kind: 'literal'; value: string | number }
28
+ | { kind: 'token'; token: string }
29
+ | { kind: 'code'; code: string };
30
+
31
+ /** `from` names the shared style object the key comes from, when it is not the element's own. */
32
+ export type StyleOrigin = StyleSource & { from?: string };
33
+
34
+ export type StyleInfo =
35
+ | { editable: true; props: Partial<Record<StyleProp, StyleOrigin>> }
36
+ | { editable: false; reason: string; props?: undefined };
37
+
38
+ export function isStyleProp(value: unknown): value is StyleProp {
39
+ return typeof value === 'string' && (STYLE_PROPS as readonly string[]).includes(value);
40
+ }
41
+
42
+ export type TokenGroup = 'font' | 'size' | 'color' | 'leading';
43
+
44
+ /** The `--od-*` variables a document's design const defines, by what they can stand for. */
45
+ export const TOKENS: Record<TokenGroup, Array<{ token: string; label: string }>> = {
46
+ font: [
47
+ { token: 'font-heading', label: 'Heading' },
48
+ { token: 'font-body', label: 'Body' },
49
+ { token: 'font-mono', label: 'Mono' },
50
+ ],
51
+ size: [
52
+ { token: 'size-title', label: 'Title' },
53
+ { token: 'size-h1', label: 'H1' },
54
+ { token: 'size-h2', label: 'H2' },
55
+ { token: 'size-h3', label: 'H3' },
56
+ { token: 'size-body', label: 'Body' },
57
+ { token: 'size-caption', label: 'Caption' },
58
+ ],
59
+ color: [
60
+ { token: 'text', label: 'Text' },
61
+ { token: 'muted', label: 'Muted' },
62
+ { token: 'accent', label: 'Accent' },
63
+ { token: 'rule', label: 'Rule' },
64
+ { token: 'bg', label: 'Background' },
65
+ ],
66
+ leading: [{ token: 'leading', label: 'Leading' }],
67
+ };
68
+
69
+ export const PROP_TOKENS: Partial<Record<StyleProp, TokenGroup>> = {
70
+ fontFamily: 'font',
71
+ fontSize: 'size',
72
+ color: 'color',
73
+ background: 'color',
74
+ lineHeight: 'leading',
75
+ };
76
+
77
+ const TOKEN_VALUE = /^var\(\s*--od-([a-z0-9-]+)\s*\)$/;
78
+
79
+ /** `var(--od-accent)` → `accent`; anything else is not a token reference. */
80
+ export function tokenOf(value: string): string | null {
81
+ return TOKEN_VALUE.exec(value.trim())?.[1] ?? null;
82
+ }
83
+
84
+ export function tokenValue(token: string): string {
85
+ return `var(--od-${token})`;
86
+ }
87
+
88
+ function isToken(prop: StyleProp, value: string): boolean {
89
+ const group = PROP_TOKENS[prop];
90
+ const token = tokenOf(value);
91
+ return group !== undefined && token !== null && TOKENS[group].some((t) => t.token === token);
92
+ }
93
+
94
+ const LENGTH = /^-?\d+(\.\d+)?(px|em|rem)$/;
95
+ const HEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
96
+ // Everything written is a quoted string literal, so nothing here can become
97
+ // code; this keeps out what would end a declaration in exported CSS instead.
98
+ const PLAIN = /^[^;{}<>\\\n\r]{1,200}$/;
99
+
100
+ /** Whether the panel may write this value for this key — the server's check, run again in the viewer. */
101
+ export function isValidStyleValue(prop: StyleProp, value: StyleValue): boolean {
102
+ if (value === null) return true;
103
+ if (typeof value === 'number') {
104
+ if (!Number.isFinite(value)) return false;
105
+ if (prop === 'fontWeight') return value >= 100 && value <= 900 && value % 100 === 0;
106
+ if (prop === 'lineHeight') return value > 0 && value <= 10;
107
+ return false;
108
+ }
109
+ if (!PLAIN.test(value)) return false;
110
+ if (isToken(prop, value)) return true;
111
+ switch (prop) {
112
+ case 'fontFamily':
113
+ return tokenOf(value) === null;
114
+ case 'fontSize':
115
+ return LENGTH.test(value) && !value.startsWith('-');
116
+ case 'letterSpacing':
117
+ return LENGTH.test(value) || value === 'normal';
118
+ case 'fontWeight':
119
+ return value === 'normal' || value === 'bold';
120
+ case 'fontStyle':
121
+ return value === 'normal' || value === 'italic';
122
+ case 'textAlign':
123
+ return ['left', 'center', 'right', 'justify', 'start', 'end'].includes(value);
124
+ case 'lineHeight':
125
+ return value === 'normal';
126
+ case 'color':
127
+ case 'background':
128
+ return HEX.test(value) || value === 'transparent';
129
+ }
130
+ }
131
+
132
+ /** `fontSize` → `font-size`, for `style.setProperty`. */
133
+ export function cssName(prop: StyleProp): string {
134
+ return prop.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);
135
+ }
136
+
137
+ /** A value as CSS, the way React would render it onto the element. */
138
+ export function cssValue(prop: StyleProp, value: string | number): string {
139
+ return typeof value === 'number' && prop !== 'fontWeight' && prop !== 'lineHeight'
140
+ ? `${value}px`
141
+ : String(value);
142
+ }
143
+
144
+ /** `rgb(29, 78, 216)` → `#1d4ed8`; a translucent or unparseable colour is `null`. */
145
+ export function rgbToHex(value: string): string | null {
146
+ const match = /^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)(?:[\s,/]+([\d.]+%?))?\s*\)$/.exec(value);
147
+ if (!match) return HEX.test(value) ? value.toLowerCase() : null;
148
+ const alpha = match[4];
149
+ if (alpha !== undefined) {
150
+ const a = alpha.endsWith('%') ? Number.parseFloat(alpha) / 100 : Number.parseFloat(alpha);
151
+ if (a < 1) return null;
152
+ }
153
+ return `#${[match[1], match[2], match[3]]
154
+ .map((part) => Number(part).toString(16).padStart(2, '0'))
155
+ .join('')}`;
156
+ }
@@ -0,0 +1,38 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { getRecordState, recordFileName, recordLabel, setRecordIndex, setRecords } from './records';
3
+
4
+ describe('recordFileName', () => {
5
+ const row = { name: 'Lin Mei', company: 'Acme / Asia', score: 92 };
6
+
7
+ it('fills columns and the row number', () => {
8
+ expect(recordFileName('certificate-{name}', row, 2, 120)).toBe('certificate-Lin Mei');
9
+ expect(recordFileName('{#}-{company}', row, 2, 120)).toBe('003-Acme - Asia');
10
+ });
11
+
12
+ it('numbers a pattern without placeholders, so each row gets its own file', () => {
13
+ expect(recordFileName('awards', row, 0, 9)).toBe('awards-1');
14
+ });
15
+
16
+ it('falls back to the number when the pattern fills to nothing', () => {
17
+ expect(recordFileName('{missing}', row, 4, 12)).toBe('05');
18
+ });
19
+ });
20
+
21
+ describe('recordLabel', () => {
22
+ it('uses the named column, else the first value', () => {
23
+ expect(recordLabel({ id: '', name: 'Ada' }, 0)).toBe('Ada');
24
+ expect(recordLabel({ id: 'x7', name: 'Ada' }, 0, 'name')).toBe('Ada');
25
+ expect(recordLabel(undefined, 3)).toBe('4');
26
+ });
27
+ });
28
+
29
+ describe('the record store', () => {
30
+ it('keeps the index inside the rows', () => {
31
+ setRecords([{ a: 1 }, { a: 2 }], 5);
32
+ expect(getRecordState().index).toBe(1);
33
+ setRecordIndex(-3);
34
+ expect(getRecordState().index).toBe(0);
35
+ setRecords(undefined);
36
+ expect(getRecordState()).toEqual({ records: [], index: 0 });
37
+ });
38
+ });
@@ -0,0 +1,127 @@
1
+ import { createElement, type ReactNode, useSyncExternalStore } from 'react';
2
+
3
+ /** One row of a document's `records` — usually a line of an imported `.csv`. */
4
+ export type DataRecord = Record<string, unknown>;
5
+
6
+ // Shared through globalThis for the same reason as the outline store: the
7
+ // viewer and the exporters set the record from the source copy of this module,
8
+ // while a document's `useRecord()` and `<Field>` read it from the published
9
+ // bundle. Two stores would mean pages that never change record.
10
+ const GLOBAL_KEY = '__open_doc_record_store__';
11
+ type RecordStore = {
12
+ records: DataRecord[];
13
+ index: number;
14
+ listeners: Set<() => void>;
15
+ };
16
+ type GlobalWithStore = typeof globalThis & { [GLOBAL_KEY]?: RecordStore };
17
+ const g = globalThis as GlobalWithStore;
18
+ if (!g[GLOBAL_KEY]) g[GLOBAL_KEY] = { records: [], index: 0, listeners: new Set() };
19
+ const store = g[GLOBAL_KEY];
20
+
21
+ const notify = () => {
22
+ for (const listener of store.listeners) listener();
23
+ };
24
+
25
+ /** The rows the open document prints from, or none — the viewer sets this as a document loads. */
26
+ export function setRecords(records: DataRecord[] | undefined, index = 0): void {
27
+ const next = Array.isArray(records) ? records : [];
28
+ const at = Math.min(Math.max(0, index), Math.max(0, next.length - 1));
29
+ if (store.records === next && store.index === at) return;
30
+ store.records = next;
31
+ store.index = at;
32
+ notify();
33
+ }
34
+
35
+ export function setRecordIndex(index: number): void {
36
+ const at = Math.min(Math.max(0, index), Math.max(0, store.records.length - 1));
37
+ if (store.index === at) return;
38
+ store.index = at;
39
+ notify();
40
+ }
41
+
42
+ export function getRecordState(): { records: DataRecord[]; index: number } {
43
+ return { records: store.records, index: store.index };
44
+ }
45
+
46
+ function subscribe(listener: () => void): () => void {
47
+ store.listeners.add(listener);
48
+ return () => store.listeners.delete(listener);
49
+ }
50
+
51
+ const getIndex = () => store.index;
52
+ const getCount = () => store.records.length;
53
+ const getCurrent = (): DataRecord | undefined => store.records[store.index];
54
+
55
+ export function useRecordIndex(): number {
56
+ return useSyncExternalStore(subscribe, getIndex, getIndex);
57
+ }
58
+
59
+ export function useRecordCount(): number {
60
+ return useSyncExternalStore(subscribe, getCount, getCount);
61
+ }
62
+
63
+ /**
64
+ * The row this copy of the document is printed for. A document that exports
65
+ * `records` is laid out once per row; every page reads the same one. Outside a
66
+ * document with records — a card in the document list — it is `undefined`.
67
+ */
68
+ export function useRecord<T extends DataRecord = DataRecord>(): T | undefined {
69
+ return useSyncExternalStore(subscribe, getCurrent, getCurrent) as T | undefined;
70
+ }
71
+
72
+ export type FieldProps = {
73
+ /** The column to print. */
74
+ name: string;
75
+ /** Printed when the row has no value for it. */
76
+ fallback?: ReactNode;
77
+ };
78
+
79
+ /**
80
+ * One value of the current row, as text. Where no row is set — a document
81
+ * card, a theme preview — it prints the column's name in guillemets, so the
82
+ * layout still shows what goes where.
83
+ */
84
+ export function Field({ name, fallback }: FieldProps) {
85
+ const record = useRecord();
86
+ if (!record) return createElement('span', { style: { opacity: 0.55 } }, `‹${name}›`);
87
+ const value = record[name];
88
+ if (value === null || value === undefined || value === '') {
89
+ return fallback === undefined ? null : createElement('span', null, fallback);
90
+ }
91
+ return createElement('span', null, String(value));
92
+ }
93
+
94
+ /** How a row is named in the viewer's picker: the chosen column, else the first non-empty one. */
95
+ export function recordLabel(record: DataRecord | undefined, index: number, key?: string): string {
96
+ if (!record) return String(index + 1);
97
+ const value = key ? record[key] : Object.values(record).find((v) => v !== '' && v != null);
98
+ return value === undefined || value === null || value === '' ? String(index + 1) : String(value);
99
+ }
100
+
101
+ // Characters no file system takes in a name, and the separators.
102
+ const UNSAFE = /[\\/:*?"<>|\p{Cc}]+/gu;
103
+
104
+ /**
105
+ * A file name for one row: `{column}` takes the row's value and `{#}` its
106
+ * 1-based number, padded to the width of the count. A pattern-free name gets
107
+ * the number appended, so every row still lands in its own file.
108
+ */
109
+ export function recordFileName(
110
+ pattern: string,
111
+ record: DataRecord | undefined,
112
+ index: number,
113
+ count: number,
114
+ ): string {
115
+ const number = String(index + 1).padStart(String(count).length, '0');
116
+ const filled = pattern.replace(/\{([^{}]+)\}/g, (_, key: string) =>
117
+ key === '#' ? number : String(record?.[key.trim()] ?? ''),
118
+ );
119
+ const named = /\{[^{}]+\}/.test(pattern) ? filled : `${filled}-${number}`;
120
+ return (
121
+ named
122
+ .replace(UNSAFE, '-')
123
+ .replace(/\s+/g, ' ')
124
+ .replace(/^[\s.-]+|[\s.-]+$/g, '')
125
+ .slice(0, 120) || number
126
+ );
127
+ }
@@ -1,6 +1,7 @@
1
1
  import type { ComponentType, ReactNode } from 'react';
2
2
  import type { DesignSystem } from './design.ts';
3
3
  import type { LabelVocabulary } from './labels.ts';
4
+ import type { DataRecord } from './records.ts';
4
5
 
5
6
  /** The only sheets a document may be laid out on. */
6
7
  export const PAGE_SIZE_NAMES = ['A4', 'B4', 'A3'] as const;
@@ -86,8 +87,31 @@ export type DocMeta = {
86
87
  createdAt?: string;
87
88
  /** What numbered items are called — `圖`/`表` instead of `Figure`/`Table`. */
88
89
  labels?: Partial<LabelVocabulary>;
90
+ /**
91
+ * The language the document is written in, as a BCP 47 tag — `zh-Hant-TW`,
92
+ * `ja`, `ko`, `en-GB`. It decides glyph shapes for shared Han characters,
93
+ * which line-breaking rules apply, and the language an exported file
94
+ * declares. English when unset.
95
+ */
96
+ lang?: string;
97
+ /**
98
+ * With `records`: the file name for each row's copy — `{column}` takes the
99
+ * row's value, `{#}` its number. `<id>-{#}` when unset.
100
+ */
101
+ recordName?: string;
102
+ /** With `records`: the column that names a row in the viewer's picker. */
103
+ recordLabel?: string;
89
104
  };
90
105
 
106
+ /**
107
+ * The `lang` every sheet carries. Always set, never inherited: a sheet that
108
+ * took its language from the viewer would break lines and pick glyphs by the
109
+ * reader's interface language, and print differently for each reader.
110
+ */
111
+ export function pageLang(meta?: DocMeta): string {
112
+ return meta?.lang?.trim() || 'en';
113
+ }
114
+
91
115
  export type FolderIcon = { type: 'emoji'; value: string } | { type: 'color'; value: string };
92
116
 
93
117
  export type Folder = {
@@ -105,6 +129,11 @@ export type DocModule = {
105
129
  default: DocEntry[];
106
130
  meta?: DocMeta;
107
131
  design?: DesignSystem;
132
+ /**
133
+ * Rows to print the document for, one copy each — usually an imported
134
+ * `.csv`. Pages read the current row with `useRecord()` or `<Field>`.
135
+ */
136
+ records?: DataRecord[];
108
137
  };
109
138
 
110
139
  export function resolvePageGeometry(meta?: DocMeta): PageGeometry {
@@ -15,6 +15,7 @@ export function useDocModule(docId: string | undefined): DocState {
15
15
  useEffect(() => {
16
16
  if (!docId) return;
17
17
  let cancelled = false;
18
+ let rescanned = false;
18
19
 
19
20
  const read = () => {
20
21
  loadDoc(docId)
@@ -23,6 +24,12 @@ export function useDocModule(docId: string | undefined): DocState {
23
24
  })
24
25
  .catch((err: unknown) => {
25
26
  if (cancelled) return;
27
+ // A document created a moment ago may not be in the list yet; the
28
+ // dev server rescans and reloads the page if it is on disk.
29
+ if (import.meta.env.DEV && !rescanned) {
30
+ rescanned = true;
31
+ void fetch('/__docs-rescan').catch(() => {});
32
+ }
26
33
  setState({
27
34
  status: 'error',
28
35
  doc: null,