gbxlxs 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -1,18 +1,19 @@
1
1
  # gbxlxs
2
2
 
3
- 独立电子表格引擎:**读写真正的 `.xlsx`、工作簿模型操作、CSV / HTML 导入导出**。
3
+ 独立电子表格引擎:**读写真正的 `.xlsx`、工作簿模型操作、CSV / HTML 导入导出,外加一个自包含的 HTML 表格编辑器**。
4
4
 
5
5
  它不是某个在线表格的封装,而是一层可以直接嵌进任何前端的表格内核:解析 OOXML 得到一个纯对象模型,用同步算子改这个模型,再序列化回 `.xlsx`,并在往返中尽量保住原文件的边角内容(图表、图片、透视表、条件格式、打印分节等)。ZIP 与 XML 这两个底层难题全部交给 [`gbooxml`](https://www.npmjs.com/package/gbooxml)。
6
6
 
7
- ## 三层结构
7
+ ## 四层结构
8
8
 
9
9
  | 层 | 入口 | 职责 |
10
10
  | --- | --- | --- |
11
11
  | 引擎 | `gbxlxs/workbook` | `.xlsx` 读写、CSV 导出、HTML 导入、数字格式、行列插删 |
12
12
  | 算子 | `gbxlxs/ops` | 对工作簿/分节对象做**同步就地修改**:取值、写值、公式、样式、合并、排序、筛选、冻结、分节增删改名 |
13
13
  | 会话 | `gbxlxs/session` | 托管一份文档:脏标记、自动序列化、失败上报、修订号握手 |
14
+ | 界面 | `web/` | 原生 HTML 表格编辑器:菜单、工具带、公式栏、窗口化网格、页签、右键菜单 |
14
15
 
15
- 根入口 `gbxlxs` 把三层的 68 个名字一次性全部导出,日常用 `import { openXlsx, setValue } from 'gbxlxs'` 就够了。
16
+ 根入口 `gbxlxs` 把引擎/算子/会话的 68 个名字一次性全部导出,日常用 `import { openXlsx, setValue } from 'gbxlxs'` 就够了。
16
17
 
17
18
  ## 安装
18
19
 
@@ -20,15 +21,59 @@
20
21
  npm install gbxlxs
21
22
  ```
22
23
 
24
+ ## 界面
25
+
26
+ `web/` 是一套不打包、不依赖框架的完整表格编辑器,引擎仍走本包:
27
+
28
+ ```bash
29
+ npm start # 等价于 node web/serve.mjs
30
+ # http://localhost:5275/web/
31
+ ```
32
+
33
+ 包含打开 / 保存 / 另存为 `.xlsx`、新建、CSV 导出、自动保存(浏览器文件句柄)、深色主题、缩放、冻结窗格、筛选、合并、排序、数字格式、条件格式、数据验证、批注、超链接、复选框、图片预览、拖放打开、撤销重做与剪贴板。`index.html` 通过 import map 把 `gbooxml` 指到 `/vendor/gbooxml/`,`serve.mjs` 负责静态供给,无需构建。
34
+
35
+ 也可以把编辑器嵌进现有前端(不依赖 Vue,导出路径为 `gbxlxs/web/*`):
36
+
37
+ ```js
38
+ import { SheetEditor } from 'gbxlxs/web/app/sheets-app.js';
39
+
40
+ const editor = new SheetEditor(mountEl, {
41
+ embedded: true, // 文件级动作交给宿主
42
+ host: {
43
+ getTitle: () => '销售.xlsx',
44
+ getPath: () => '文档/表格',
45
+ getStatus: () => ({ text: '已保存', kind: '' }),
46
+ getAutoSave: () => true,
47
+ setAutoSave: (on) => {},
48
+ canSave: () => true,
49
+ save: async () => true, // 宿主负责把 serializeNow() 的字节写回
50
+ saveAs: async () => true,
51
+ open: () => {},
52
+ create: () => {},
53
+ recentList: () => [],
54
+ openRecent: (doc) => {},
55
+ onChange: ({ dirty, error }) => {},
56
+ },
57
+ });
58
+
59
+ await editor.openBytes(bytes); // 或 await editor.createBlank()
60
+ const out = await editor.serializeNow();
61
+ editor.dispose();
62
+ ```
63
+
64
+ 不传 `host` / `embedded` 时即独立模式,编辑器自己处理文件选择、保存与未保存确认。
65
+
23
66
  ## 导入路径
24
67
 
25
- `exports` 只声明了五个键,**没有通配**,因此深层路径会被 Node 直接拒掉:
68
+ `exports` 声明了四个引擎入口与一个 `web/` 通配;`src/` 深层路径仍会被 Node 直接拒掉:
26
69
 
27
70
  ```js
28
71
  import { openXlsx } from 'gbxlxs'; // 根入口,全部 68 个名字
29
72
  import { openXlsx } from 'gbxlxs/workbook'; // 只要引擎层
30
73
  import { setValue } from 'gbxlxs/ops'; // 只要算子层
31
74
  import { createSheetSession } from 'gbxlxs/session';
75
+ import { SheetEditor } from 'gbxlxs/web/app/sheets-app.js';
76
+ import 'gbxlxs/web/styles/sheets.css';
32
77
  import version from 'gbxlxs/package.json' with { type: 'json' };
33
78
  ```
34
79
 
package/package.json CHANGED
@@ -1,23 +1,28 @@
1
1
  {
2
2
  "name": "gbxlxs",
3
- "version": "0.1.2",
4
- "description": "Standalone spreadsheet (XLSX) engine: read/write xlsx, workbook model ops and CSV/HTML import-export.",
3
+ "version": "0.1.3",
4
+ "description": "Standalone spreadsheet (XLSX) engine with a self-contained HTML editor: read/write xlsx, workbook model ops, CSV/HTML import-export and a full spreadsheet UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
- "sideEffects": false,
7
+ "sideEffects": [
8
+ "**/*.css"
9
+ ],
8
10
  "main": "./src/index.js",
9
11
  "exports": {
10
12
  ".": "./src/index.js",
11
13
  "./ops": "./src/ops.js",
12
14
  "./session": "./src/session.js",
13
15
  "./workbook": "./src/workbook/index.js",
16
+ "./web/*": "./web/*",
14
17
  "./package.json": "./package.json"
15
18
  },
16
19
  "files": [
17
20
  "src",
21
+ "web",
18
22
  "LICENSE"
19
23
  ],
20
24
  "scripts": {
25
+ "start": "node web/serve.mjs",
21
26
  "test": "node --test test/editing.test.js test/references.test.js test/session.test.js test/roundtrip.test.js"
22
27
  },
23
28
  "dependencies": {
@@ -28,7 +33,9 @@
28
33
  "excel",
29
34
  "spreadsheet",
30
35
  "ooxml",
31
- "workbook"
36
+ "workbook",
37
+ "editor",
38
+ "ui"
32
39
  ],
33
40
  "engines": {
34
41
  "node": ">=18"
@@ -0,0 +1,221 @@
1
+ import { fromHtml, letterToCol, colToLetter, replaceA1Refs } from '../../../src/index.js';
2
+ import { captureRegion, captureCell, applyCell, getDisplayText, parseInput } from '../../../src/ops.js';
3
+ import { notify } from '../ui/notify.js';
4
+ import { escapeHtml } from '../ui/dom.js';
5
+
6
+ let memory = null;
7
+
8
+ const escapeTsv = (text) => (/[\t\n\r"]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text);
9
+ const escapeCell = (text) => escapeHtml(text).replace(/\n/g, '<br>');
10
+
11
+ function regionToTsv(sheet, region) {
12
+ const lines = [];
13
+ for (let r = region.startRow; r <= region.endRow; r++) {
14
+ const cells = [];
15
+ for (let c = region.startCol; c <= region.endCol; c++) cells.push(escapeTsv(getDisplayText(sheet, r, c)));
16
+ lines.push(cells.join('\t'));
17
+ }
18
+ return lines.join('\n');
19
+ }
20
+
21
+ function regionToHtml(sheet, region) {
22
+ const rows = [];
23
+ for (let r = region.startRow; r <= region.endRow; r++) {
24
+ const cells = [];
25
+ for (let c = region.startCol; c <= region.endCol; c++) cells.push(`<td>${escapeCell(getDisplayText(sheet, r, c))}</td>`);
26
+ rows.push(`<tr>${cells.join('')}</tr>`);
27
+ }
28
+ return `<table>${rows.join('')}</table>`;
29
+ }
30
+
31
+ function parseTsv(text) {
32
+ const rows = [];
33
+ let row = [];
34
+ let cell = '';
35
+ let inQuotes = false;
36
+ for (let i = 0; i < text.length; i++) {
37
+ const ch = text[i];
38
+ if (inQuotes) {
39
+ if (ch === '"') {
40
+ if (text[i + 1] === '"') {
41
+ cell += '"';
42
+ i += 1;
43
+ } else inQuotes = false;
44
+ } else cell += ch;
45
+ } else if (ch === '"' && cell === '') inQuotes = true;
46
+ else if (ch === '\t') {
47
+ row.push(cell);
48
+ cell = '';
49
+ } else if (ch === '\n') {
50
+ row.push(cell);
51
+ rows.push(row);
52
+ row = [];
53
+ cell = '';
54
+ } else if (ch !== '\r') cell += ch;
55
+ }
56
+ if (cell !== '' || row.length) {
57
+ row.push(cell);
58
+ rows.push(row);
59
+ }
60
+ return rows;
61
+ }
62
+
63
+ async function writeClipboardText(text) {
64
+ if (navigator.clipboard?.writeText) return navigator.clipboard.writeText(text);
65
+ const area = document.createElement('textarea');
66
+ area.value = text;
67
+ area.readOnly = true;
68
+ area.style.cssText = 'position:fixed;top:0;left:0;opacity:0';
69
+ document.body.appendChild(area);
70
+ area.select();
71
+ const copied = document.execCommand('copy');
72
+ area.remove();
73
+ if (!copied) throw new Error('当前浏览器不支持自动复制,请手动选取复制');
74
+ }
75
+
76
+ async function copyRich(text, html) {
77
+ if (!text && !html) {
78
+ notify.error('没有可复制的内容');
79
+ return false;
80
+ }
81
+ try {
82
+ await navigator.clipboard.write([
83
+ new ClipboardItem({
84
+ 'text/plain': new Blob([text || ''], { type: 'text/plain' }),
85
+ 'text/html': new Blob([html || text || ''], { type: 'text/html' }),
86
+ }),
87
+ ]);
88
+ notify.success('已复制');
89
+ return true;
90
+ } catch {
91
+ try {
92
+ await writeClipboardText(text || '');
93
+ notify.success('已复制');
94
+ return true;
95
+ } catch (err) {
96
+ notify.error(`复制失败:${err?.message || err}`);
97
+ return false;
98
+ }
99
+ }
100
+ }
101
+
102
+ async function readRich() {
103
+ if (!navigator.clipboard?.read) throw new Error('当前访问方式不支持读取剪贴板,请手动粘贴');
104
+ const items = await navigator.clipboard.read();
105
+ let text = '';
106
+ let html = '';
107
+ for (const item of items) {
108
+ if (!html && item.types.includes('text/html')) html = await (await item.getType('text/html')).text();
109
+ if (!text && item.types.includes('text/plain')) text = await (await item.getType('text/plain')).text();
110
+ }
111
+ if (!text && !html) throw new Error('剪贴板没有可粘贴的内容');
112
+ return { text, html };
113
+ }
114
+
115
+ async function readExternalGrid() {
116
+ const { text, html } = await readRich();
117
+ if (html) {
118
+ try {
119
+ const sheet = fromHtml(html);
120
+ const rows = sheet.rows || [];
121
+ const grid = rows.map((row) =>
122
+ row.map((v) => (v === null || v === undefined || v === '' ? null : { value: v })),
123
+ );
124
+ if (grid.length) return { grid, origin: null };
125
+ } catch {
126
+ /* HTML 解析失败退 TSV */
127
+ }
128
+ }
129
+ if (text) {
130
+ const rows = parseTsv(text);
131
+ const grid = rows.map((row) =>
132
+ row.map((cellText) => {
133
+ if (cellText === '') return null;
134
+ const parsed = parseInput(cellText);
135
+ return parsed.formula != null
136
+ ? { value: null, formula: parsed.formula, formulaResult: null, style: null }
137
+ : { value: parsed.value, formula: null, formulaResult: null, style: null };
138
+ }),
139
+ );
140
+ if (grid.length) return { grid, origin: null };
141
+ }
142
+ return null;
143
+ }
144
+
145
+ const shiftRef = (ref, dRow, dCol) => {
146
+ const m = /^(\$?)([A-Za-z]+)(\$?)(\d+)$/.exec(ref);
147
+ if (!m) return ref;
148
+ const [, colAbs, colLetters, rowAbs, rowDigits] = m;
149
+ let col = letterToCol(colLetters);
150
+ let row = parseInt(rowDigits, 10) - 1;
151
+ if (!colAbs) col += dCol;
152
+ if (!rowAbs) row += dRow;
153
+ if (col < 0 || row < 0) return '#REF!';
154
+ return `${colAbs}${colToLetter(col)}${rowAbs}${row + 1}`;
155
+ };
156
+
157
+ const shiftFormulaText = (formula, dRow, dCol) =>
158
+ dRow === 0 && dCol === 0 ? formula : replaceA1Refs(formula, (ref) => shiftRef(ref, dRow, dCol));
159
+
160
+ export async function copyRegion(sheet, region) {
161
+ const grid = captureRegion(sheet, region);
162
+ memory = { grid, origin: { row: region.startRow, col: region.startCol }, cut: null };
163
+ return copyRich(regionToTsv(sheet, region), regionToHtml(sheet, region));
164
+ }
165
+
166
+ export async function cutRegion(workbook, sheet, region) {
167
+ const ok = await copyRegion(sheet, region);
168
+ if (ok) memory.cut = { workbook, sheet, region };
169
+ return ok;
170
+ }
171
+
172
+ export async function pasteAt(sheet, row, col, { mode = 'all' } = {}) {
173
+ let source;
174
+ let fromMemory = false;
175
+ if (memory?.grid?.length) {
176
+ source = { grid: memory.grid, origin: memory.origin };
177
+ fromMemory = true;
178
+ } else {
179
+ source = await readExternalGrid();
180
+ }
181
+ if (!source) return null;
182
+ const grid = source.grid;
183
+ const height = grid.length;
184
+ const width = Math.max(...grid.map((r) => r.length));
185
+ if (!height || !width) return null;
186
+
187
+ const region = { startRow: row, startCol: col, endRow: row + height - 1, endCol: col + width - 1 };
188
+ const before = captureRegion(sheet, region);
189
+ const dRow = source.origin ? row - source.origin.row : 0;
190
+ const dCol = source.origin ? col - source.origin.col : 0;
191
+
192
+ for (let i = 0; i < height; i++) {
193
+ for (let j = 0; j < grid[i].length; j++) {
194
+ const snap = grid[i][j];
195
+ if (!snap) continue;
196
+ const target = mode === 'all' ? null : captureCell(sheet, row + i, col + j);
197
+ let next;
198
+ if (mode === 'values') {
199
+ next = { value: snap.value, formula: snap.formula, formulaResult: snap.formulaResult, style: target?.style ?? null };
200
+ } else if (mode === 'formats') {
201
+ if (snap.style == null) continue;
202
+ next = { value: target?.value ?? null, formula: target?.formula ?? null, formulaResult: target?.formulaResult ?? null, style: snap.style };
203
+ } else {
204
+ next = { ...snap };
205
+ }
206
+ if (next.formula) next.formula = shiftFormulaText(next.formula, dRow, dCol);
207
+ applyCell(sheet, row + i, col + j, next);
208
+ }
209
+ }
210
+
211
+ if (fromMemory && memory.cut && mode !== 'formats') {
212
+ const { workbook: srcWorkbook, sheet: srcSheet, region: srcRegion } = memory.cut;
213
+ if (srcWorkbook?.sheets?.includes(srcSheet)) {
214
+ for (let r = srcRegion.startRow; r <= srcRegion.endRow; r++) {
215
+ for (let c = srcRegion.startCol; c <= srcRegion.endCol; c++) applyCell(srcSheet, r, c, null);
216
+ }
217
+ }
218
+ memory = null;
219
+ }
220
+ return { region, before };
221
+ }
@@ -0,0 +1,179 @@
1
+ import {
2
+ setFont,
3
+ setStyle,
4
+ setValue,
5
+ getEntry,
6
+ getStyle,
7
+ captureRegion,
8
+ currentNumfmt,
9
+ shiftedPattern,
10
+ currentRegion,
11
+ normalizeRegion,
12
+ sortRegion,
13
+ isProtected as isSheetProtected,
14
+ } from '../../../src/ops.js';
15
+ import { notify } from '../ui/notify.js';
16
+ import { diffRegion } from './history.js';
17
+ import { invalidateRuleCache } from './rules.js';
18
+
19
+ export function createSheetCmdCore({ session, selection, history, zoom, onChanged }) {
20
+ const getWorkbook = () => session.getWorkbook();
21
+ const getSheet = () => {
22
+ const workbook = getWorkbook();
23
+ return workbook ? workbook.sheets[session.getActiveSheetIndex()] || null : null;
24
+ };
25
+ const active = () => selection.active;
26
+
27
+ const changed = () => {
28
+ invalidateRuleCache(getSheet());
29
+ onChanged();
30
+ };
31
+
32
+ const hexToRgb = (hex) => String(hex).replace('#', '').slice(-6).toUpperCase();
33
+
34
+ const guard = () => {
35
+ if (!isSheetProtected(getSheet())) return true;
36
+ notify.warning('工作表已保护,无法编辑(在「开始 → 保护」中取消保护)');
37
+ return false;
38
+ };
39
+
40
+ const rangesEdit = (mutate) => {
41
+ if (!guard()) return false;
42
+ const sheet = getSheet();
43
+ if (!sheet || !selection.ranges.length) return false;
44
+ const changes = [];
45
+ for (const region of selection.ranges) {
46
+ const before = captureRegion(sheet, region);
47
+ mutate(sheet, region);
48
+ changes.push(...diffRegion(sheet, region, before).map((ch) => ({ ...ch, sheet })));
49
+ }
50
+ if (!changes.length) return false;
51
+ history.pushCellChanges(changes);
52
+ changed();
53
+ return true;
54
+ };
55
+
56
+ const structural = (doOp, { bypassProtection = false } = {}) => {
57
+ if (!bypassProtection && !guard()) return false;
58
+ const workbook = getWorkbook();
59
+ const index = session.getActiveSheetIndex();
60
+ const sheet = workbook?.sheets[index];
61
+ if (!sheet) return false;
62
+ const before = history.snapshotSheet(sheet);
63
+ if (doOp(sheet) === false) return false;
64
+ history.pushStructural(workbook, index, before, doOp);
65
+ changed();
66
+ return true;
67
+ };
68
+
69
+ const targetRegion = () => {
70
+ const sheet = getSheet();
71
+ const { row, col } = active();
72
+ const r = selection.primary;
73
+ if (r.endRow > r.startRow || r.endCol > r.startCol) {
74
+ return normalizeRegion(r.startRow, r.startCol, r.endRow, r.endCol);
75
+ }
76
+ return currentRegion(sheet, row, col);
77
+ };
78
+
79
+ const clearCells = (mutate) => {
80
+ if (!guard()) return false;
81
+ const sheet = getSheet();
82
+ if (!sheet) return false;
83
+ const changes = [];
84
+ for (const region of selection.ranges) {
85
+ for (let r = region.startRow; r <= region.endRow; r++) {
86
+ for (let c = region.startCol; c <= region.endCol; c++) {
87
+ const cell = { startRow: r, startCol: c, endRow: r, endCol: c };
88
+ const before = captureRegion(sheet, cell);
89
+ if (before[0][0] === null) continue;
90
+ setValue(sheet, r, c, null);
91
+ mutate?.(sheet, r, c);
92
+ changes.push(...diffRegion(sheet, cell, before).map((ch) => ({ ...ch, sheet })));
93
+ }
94
+ }
95
+ }
96
+ if (!changes.length) return false;
97
+ history.pushCellChanges(changes);
98
+ changed();
99
+ return true;
100
+ };
101
+
102
+ const fontEdit = (patch) =>
103
+ rangesEdit((sheet, region) => {
104
+ for (let r = region.startRow; r <= region.endRow; r++) {
105
+ for (let c = region.startCol; c <= region.endCol; c++) setFont(sheet, r, c, patch);
106
+ }
107
+ });
108
+
109
+ const alignEdit = (patchOf) =>
110
+ rangesEdit((sheet, region) => {
111
+ for (let r = region.startRow; r <= region.endRow; r++) {
112
+ for (let c = region.startCol; c <= region.endCol; c++) {
113
+ const cur = getEntry(sheet, r, c)?.style?.alignment;
114
+ const patch = { ...(cur || {}), ...patchOf(cur) };
115
+ for (const k of Object.keys(patch)) if (patch[k] === undefined) delete patch[k];
116
+ setStyle(sheet, r, c, { alignment: Object.keys(patch).length ? patch : undefined });
117
+ }
118
+ }
119
+ });
120
+
121
+ const activeEntryStyle = () => {
122
+ const sheet = getSheet();
123
+ return sheet ? getStyle(sheet, active().row, active().col) : null;
124
+ };
125
+
126
+ const toggleFont = (flag) => {
127
+ const on = activeEntryStyle()?.font?.[flag] === true;
128
+ return rangesEdit((sheet, region) => {
129
+ for (let r = region.startRow; r <= region.endRow; r++) {
130
+ for (let c = region.startCol; c <= region.endCol; c++) setFont(sheet, r, c, { [flag]: on ? undefined : true });
131
+ }
132
+ });
133
+ };
134
+
135
+ const stepDecimals = (delta) =>
136
+ rangesEdit((sheet, region) => {
137
+ for (let r = region.startRow; r <= region.endRow; r++) {
138
+ for (let c = region.startCol; c <= region.endCol; c++) {
139
+ setStyle(sheet, r, c, { numFmt: shiftedPattern(currentNumfmt(sheet, r, c), delta) });
140
+ }
141
+ }
142
+ });
143
+
144
+ const sortBy = (desc) => {
145
+ const sheet = getSheet();
146
+ if (!sheet) return false;
147
+ const region = targetRegion();
148
+ const col = active().col;
149
+ try {
150
+ return structural((s) => sortRegion(s, region, col, desc));
151
+ } catch (err) {
152
+ notify.warning(err.message);
153
+ return false;
154
+ }
155
+ };
156
+
157
+ return {
158
+ session,
159
+ selection,
160
+ history,
161
+ zoom,
162
+ getWorkbook,
163
+ getSheet,
164
+ active,
165
+ changed,
166
+ guard,
167
+ rangesEdit,
168
+ structural,
169
+ targetRegion,
170
+ clearCells,
171
+ fontEdit,
172
+ alignEdit,
173
+ activeEntryStyle,
174
+ toggleFont,
175
+ stepDecimals,
176
+ sortBy,
177
+ hexToRgb,
178
+ };
179
+ }
@@ -0,0 +1,167 @@
1
+ import {
2
+ getValue,
3
+ setValue,
4
+ setStyle,
5
+ setCellExtra,
6
+ getDisplayText,
7
+ captureRegion,
8
+ regionA1,
9
+ regionsOverlap,
10
+ } from '../../../src/ops.js';
11
+ import { parseSqref } from './rules.js';
12
+
13
+ const CF_HIGHLIGHT = {
14
+ gt: { type: 'cellIs', operator: 'greaterThan' },
15
+ lt: { type: 'cellIs', operator: 'lessThan' },
16
+ eq: { type: 'cellIs', operator: 'equal' },
17
+ contains: { type: 'containsText' },
18
+ };
19
+ const CF_HIGHLIGHT_STYLE = {
20
+ font: { color: { rgb: '9C0006' } },
21
+ fill: { type: 'pattern', pattern: 'solid', fgColor: { rgb: 'FFC7CE' } },
22
+ };
23
+
24
+ export function createSheetCmdData(core) {
25
+ const { getSheet, rangesEdit, guard, history, changed, structural, selection } = core;
26
+
27
+ return {
28
+ insertCheckbox: () =>
29
+ rangesEdit((sheet, region) => {
30
+ for (let r = region.startRow; r <= region.endRow; r++) {
31
+ for (let c = region.startCol; c <= region.endCol; c++) {
32
+ const cur = getValue(sheet, r, c);
33
+ setValue(sheet, r, c, typeof cur === 'boolean' ? cur : false);
34
+ setCellExtra(sheet, r, c, { checkbox: true });
35
+ }
36
+ }
37
+ }),
38
+ toggleCheckboxAt: (row, col) => {
39
+ if (!guard()) return false;
40
+ const sheet = getSheet();
41
+ if (!sheet) return false;
42
+ const region = { startRow: row, startCol: col, endRow: row, endCol: col };
43
+ const before = captureRegion(sheet, region);
44
+ setValue(sheet, row, col, getValue(sheet, row, col) === true ? false : true);
45
+ if (history.pushCells(sheet, region, before)) changed();
46
+ return true;
47
+ },
48
+ setCellValueAt: (row, col, value) => {
49
+ if (!guard()) return false;
50
+ const sheet = getSheet();
51
+ if (!sheet) return false;
52
+ const region = { startRow: row, startCol: col, endRow: row, endCol: col };
53
+ const before = captureRegion(sheet, region);
54
+ setValue(sheet, row, col, value);
55
+ if (history.pushCells(sheet, region, before)) changed();
56
+ return true;
57
+ },
58
+ insertDateAt: (row, col, isoDate) => {
59
+ if (!guard()) return false;
60
+ const sheet = getSheet();
61
+ if (!sheet) return false;
62
+ const [y, m, d] = String(isoDate).split('-').map(Number);
63
+ if (!Number.isInteger(y) || !Number.isInteger(m) || !Number.isInteger(d)) return false;
64
+ const region = { startRow: row, startCol: col, endRow: row, endCol: col };
65
+ const before = captureRegion(sheet, region);
66
+ setValue(sheet, row, col, new Date(Date.UTC(y, m - 1, d)));
67
+ setStyle(sheet, row, col, { numFmt: 'yyyy-mm-dd' });
68
+ if (history.pushCells(sheet, region, before)) changed();
69
+ return true;
70
+ },
71
+ setHyperlink: (target) =>
72
+ rangesEdit((sheet, region) => {
73
+ for (let r = region.startRow; r <= region.endRow; r++) {
74
+ for (let c = region.startCol; c <= region.endCol; c++) {
75
+ const display = getDisplayText(sheet, r, c);
76
+ setCellExtra(sheet, r, c, { hyperlink: { target, ...(display ? { display } : {}) } });
77
+ }
78
+ }
79
+ }),
80
+ clearHyperlink: () =>
81
+ rangesEdit((sheet, region) => {
82
+ for (let r = region.startRow; r <= region.endRow; r++) {
83
+ for (let c = region.startCol; c <= region.endCol; c++) setCellExtra(sheet, r, c, { hyperlink: null });
84
+ }
85
+ }),
86
+ setComment: (text) =>
87
+ rangesEdit((sheet, region) => {
88
+ for (let r = region.startRow; r <= region.endRow; r++) {
89
+ for (let c = region.startCol; c <= region.endCol; c++) setCellExtra(sheet, r, c, { comment: { text } });
90
+ }
91
+ }),
92
+ removeComment: () =>
93
+ rangesEdit((sheet, region) => {
94
+ for (let r = region.startRow; r <= region.endRow; r++) {
95
+ for (let c = region.startCol; c <= region.endCol; c++) setCellExtra(sheet, r, c, { comment: null });
96
+ }
97
+ }),
98
+ setListValidation: (values) => {
99
+ const sheet = getSheet();
100
+ if (!sheet) return false;
101
+ const range = regionA1(selection.primary);
102
+ return structural((s) => {
103
+ const kept = (s.dataValidations || []).filter((d) => d.range !== range);
104
+ s.dataValidations = [...kept, { type: 'list', range, values }];
105
+ return true;
106
+ });
107
+ },
108
+ clearValidation: () => {
109
+ const sheet = getSheet();
110
+ if (!sheet) return false;
111
+ const area = selection.primary;
112
+ return structural((s) => {
113
+ const list = s.dataValidations || [];
114
+ const kept = list.filter((d) => !parseSqref(d.range).some((b) => regionsOverlap(b, area)));
115
+ if (kept.length === list.length) return false;
116
+ if (kept.length) s.dataValidations = kept;
117
+ else delete s.dataValidations;
118
+ return true;
119
+ });
120
+ },
121
+ addHighlight: (kind, value) => {
122
+ const sheet = getSheet();
123
+ if (!sheet) return false;
124
+ const meta = CF_HIGHLIGHT[kind];
125
+ const text = String(value ?? '').trim();
126
+ if (!meta || !text) return false;
127
+ const range = regionA1(selection.primary);
128
+ return structural((s) => {
129
+ const rules = s.conditionalRules || [];
130
+ const priority = rules.reduce((n, rule) => Math.max(n, rule.priority || 0), 0) + 1;
131
+ const rule = { type: meta.type, priority, range, style: CF_HIGHLIGHT_STYLE };
132
+ if (meta.operator) rule.operator = meta.operator;
133
+ if (meta.type === 'cellIs') rule.formula = text;
134
+ else rule.text = text;
135
+ s.conditionalRules = [...rules, rule];
136
+ return true;
137
+ });
138
+ },
139
+ addDataBar: () => {
140
+ const sheet = getSheet();
141
+ if (!sheet) return false;
142
+ const range = regionA1(selection.primary);
143
+ return structural((s) => {
144
+ const rules = s.conditionalRules || [];
145
+ const priority = rules.reduce((n, rule) => Math.max(n, rule.priority || 0), 0) + 1;
146
+ s.conditionalRules = [
147
+ ...rules,
148
+ { type: 'dataBar', priority, range, dataBar: { cfvo: [{ type: 'min' }, { type: 'max' }], color: '#638EC6' } },
149
+ ];
150
+ return true;
151
+ });
152
+ },
153
+ clearCf: () => {
154
+ const sheet = getSheet();
155
+ if (!sheet) return false;
156
+ const area = selection.primary;
157
+ return structural((s) => {
158
+ const rules = s.conditionalRules || [];
159
+ const kept = rules.filter((rule) => !parseSqref(rule.range).some((b) => regionsOverlap(b, area)));
160
+ if (kept.length === rules.length) return false;
161
+ if (kept.length) s.conditionalRules = kept;
162
+ else delete s.conditionalRules;
163
+ return true;
164
+ });
165
+ },
166
+ };
167
+ }