@open-spreadsheet/core 0.1.1 → 0.2.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/app/book.ts CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  parseFormula,
19
19
  type Node as FormulaNode,
20
20
  } from '@open-spreadsheet/engine';
21
- import { BLANK, columnValues, conditionalLook, type CellLook, DEFAULT_HIGHLIGHT, filteredRows, shiftRange, validationAt } from './features.ts';
21
+ import { isProtectedCell, touchesProtected, BLANK, columnValues, conditionalLook, type CellLook, DEFAULT_HIGHLIGHT, filteredRows, shiftRange, validationAt } from './features.ts';
22
22
  import { chartData, chartSvg } from './charts.ts';
23
23
  import { printHtml } from './print.ts';
24
24
  import { api } from './home.ts';
@@ -526,7 +526,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
526
526
  }
527
527
  const input = wb.inputAt(name, r, c);
528
528
  const style = styleAt(r, c);
529
- if (!input && !style?.bg && !style?.border && !style?.check && !noteAt(r, c) && !isFilterHead(r, c)) continue;
529
+ if (!input && !style?.bg && !style?.border && !style?.check && !noteAt(r, c) && !isFilterHead(r, c) && !isProtectedCell(sheet(), r, c)) continue;
530
530
  let w = colX[c + 1]! - colX[c]!;
531
531
  const s = input ? show(r, c) : null;
532
532
  const isText = s && (typeof s.v === 'string' || s.v === null) && !style?.wrap && (style?.align ?? 'left') === 'left';
@@ -617,6 +617,11 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
617
617
  if (look.bg) d.style.background = look.bg;
618
618
  if (look.color) d.style.color = look.color;
619
619
  if (look.b) d.classList.add('b');
620
+ if (look.icon) {
621
+ const ic = el('span', 'cf-icon', look.icon.glyph);
622
+ ic.style.color = look.icon.color;
623
+ d.prepend(ic);
624
+ }
620
625
  if (look.bar) {
621
626
  const bar = el('span', 'data-bar');
622
627
  bar.style.width = `${Math.round(look.bar.pct * 100)}%`;
@@ -632,6 +637,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
632
637
  d.classList.add('filter-head');
633
638
  }
634
639
  if (merged || spills) d.classList.add('solid');
640
+ if (isProtectedCell(sheet(), row, col)) d.classList.add('locked');
635
641
  if (noteAt(row, col)) {
636
642
  const mark = el('span', 'note-mark');
637
643
  // On a spilling cell the mark belongs to the cell's own corner, not the spill's.
@@ -1057,6 +1063,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1057
1063
  if (s.hiddenRows?.length) out.hiddenRows = s.hiddenRows;
1058
1064
  if (s.hiddenCols?.length) out.hiddenCols = s.hiddenCols;
1059
1065
  if (s.charts?.length) out.charts = s.charts;
1066
+ if (s.protected?.length) out.protected = s.protected;
1060
1067
  return out;
1061
1068
  }),
1062
1069
  };
@@ -1132,9 +1139,21 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1132
1139
  }
1133
1140
  }
1134
1141
  /** Every change: undo point, the change, then layout, paint and save. */
1142
+ /** Thrown by a write into a protected range; `change` undoes the whole step and says why. */
1143
+ class LockedError extends Error {}
1135
1144
  function change(fn: () => void, opts: { relayout?: boolean } = {}) {
1136
1145
  checkpoint();
1137
- fn();
1146
+ try {
1147
+ fn();
1148
+ } catch (e) {
1149
+ if (!(e instanceof LockedError)) throw e;
1150
+ const before = undoStack.pop();
1151
+ if (before) restore(before);
1152
+ layout();
1153
+ render();
1154
+ toast(T.protectedRefused);
1155
+ return;
1156
+ }
1138
1157
  if (opts.relayout !== false) layout();
1139
1158
  render();
1140
1159
  save();
@@ -1143,6 +1162,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1143
1162
  // ---------- cell edits ----------
1144
1163
  const name = () => sname();
1145
1164
  function setInputs(cells: { row: number; col: number; input: string }[]) {
1165
+ if (cells.some((c) => isProtectedCell(sheet(), c.row, c.col))) throw new LockedError();
1146
1166
  wb.setCells(name(), cells);
1147
1167
  }
1148
1168
  function forEachCell(r: Rect, fn: (row: number, col: number) => void) {
@@ -1152,6 +1172,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1152
1172
  for (let row = r.r0; row <= r1; row++) for (let col = r.c0; col <= c1; col++) fn(row, col);
1153
1173
  }
1154
1174
  function setStyle(r: Rect, patch: Partial<CellStyle> | null) {
1175
+ if (touchesProtected(sheet(), r)) throw new LockedError();
1155
1176
  const sh = sheet();
1156
1177
  sh.styles ??= {};
1157
1178
  for (let row = r.r0; row <= r.r1; row++) {
@@ -1178,6 +1199,38 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1178
1199
  const on = !styleAt(active.row, active.col)?.[k];
1179
1200
  change(() => setStyle(styleRect(), { [k]: on }), { relayout: false });
1180
1201
  }
1202
+ // ---------- protection ----------
1203
+ /** Protects the selection: one range added, the ones it covers folded in. */
1204
+ function protectSelection() {
1205
+ const s = selection();
1206
+ const text = rangeText(s);
1207
+ checkpoint();
1208
+ const sh = sheet();
1209
+ const rest = (sh.protected ?? []).filter((t) => {
1210
+ const r = parseRange(t);
1211
+ return !(r && r.r0 >= s.r0 && r.r1 <= s.r1 && r.c0 >= s.c0 && r.c1 <= s.c1);
1212
+ });
1213
+ sh.protected = [...rest, text];
1214
+ render();
1215
+ save();
1216
+ toast(T.protectedOn(text));
1217
+ }
1218
+ /** Removes every protected range that touches the selection. */
1219
+ function unprotectSelection() {
1220
+ const s = selection();
1221
+ const sh = sheet();
1222
+ const keep = (sh.protected ?? []).filter((t) => {
1223
+ const r = parseRange(t);
1224
+ return !(r && r.r0 <= s.r1 && s.r0 <= r.r1 && r.c0 <= s.c1 && s.c0 <= r.c1);
1225
+ });
1226
+ if (keep.length === (sh.protected ?? []).length) return;
1227
+ checkpoint();
1228
+ sh.protected = keep.length ? keep : undefined;
1229
+ render();
1230
+ save();
1231
+ toast(T.protectedOff);
1232
+ }
1233
+
1181
1234
  // ---------- checkboxes ----------
1182
1235
  const isCheck = (row: number, col: number) => Boolean(styleAt(row, col)?.check);
1183
1236
  /**
@@ -1255,6 +1308,11 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1255
1308
  // ---------- editing ----------
1256
1309
  const draft = () => (editing?.source === 'bar' ? finput.value : editor.value);
1257
1310
  function beginEdit(mode: 'enter' | 'edit', initial?: string, source: 'cell' | 'bar' = 'cell') {
1311
+ if (isProtectedCell(sheet(), active.row, active.col)) {
1312
+ // The key that tried to start the edit is already in the editor; drop it so it cannot reach a later edit.
1313
+ editor.value = '';
1314
+ return void toast(T.protectedRefused);
1315
+ }
1258
1316
  const m = mergeOf(active.row, active.col);
1259
1317
  if (m) {
1260
1318
  active = { row: m.r0, col: m.c0 };
@@ -1756,6 +1814,13 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1756
1814
  const range = shiftRange(r.range, axis, at, count);
1757
1815
  return range ? [{ ...r, range }] : [];
1758
1816
  });
1817
+ if (sh.protected) {
1818
+ sh.protected = sh.protected.flatMap((t) => {
1819
+ const range = shiftRange(t, axis, at, count);
1820
+ return range ? [range] : [];
1821
+ });
1822
+ if (!sh.protected.length) sh.protected = undefined;
1823
+ }
1759
1824
  if (sh.validation) sh.validation = sh.validation.flatMap((v) => {
1760
1825
  const range = shiftRange(v.range, axis, at, count);
1761
1826
  return range ? [{ ...v, range }] : [];
@@ -1811,6 +1876,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1811
1876
  });
1812
1877
  }
1813
1878
  function deleteRows(r0: number, r1: number) {
1879
+ if (touchesProtected(sheet(), { r0, c0: 0, r1, c1: MAX_COLS })) return toast(T.protectedRefused);
1814
1880
  change(() => {
1815
1881
  wb.insertRows(name(), r0, -(r1 - r0 + 1));
1816
1882
  shiftMeta('row', r0, -(r1 - r0 + 1));
@@ -1818,6 +1884,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
1818
1884
  moveTo({ row: r0, col: active.col });
1819
1885
  }
1820
1886
  function deleteCols(c0: number, c1: number) {
1887
+ if (touchesProtected(sheet(), { r0: 0, c0, r1: MAX_ROWS, c1 })) return toast(T.protectedRefused);
1821
1888
  change(() => {
1822
1889
  wb.insertColumns(name(), c0, -(c1 - c0 + 1));
1823
1890
  shiftMeta('col', c0, -(c1 - c0 + 1));
@@ -2251,6 +2318,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
2251
2318
  { label: T.validation, icon: 'listCheck', action: () => void editValidation() },
2252
2319
  isCheck(active.row, active.col) ? { label: T.removeCheckbox, icon: 'check', action: removeCheckboxes } : { label: T.insertCheckbox, icon: 'check', action: insertCheckboxes },
2253
2320
  { label: T.defineName, icon: 'pencil', action: () => void defineName() },
2321
+ touchesProtected(sheet(), selection()) ? { label: T.unprotectRange, icon: 'eye', action: unprotectSelection } : { label: T.protectRange, icon: 'eyeOff', action: protectSelection },
2254
2322
  ...(linkAt(active.row, active.col) ? [{ label: T.openLink, icon: 'arrowRight', action: () => openLink(linkAt(active.row, active.col)!) }] : []),
2255
2323
  { label: T.tracePrecedents, icon: 'arrowRight', disabled: !wb.inputAt(sname(), active.row, active.col).startsWith('='), action: () => traceCells('pre') },
2256
2324
  { label: T.traceDependents, icon: 'arrowLeft', action: () => traceCells('dep') },
@@ -3341,6 +3409,8 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
3341
3409
  ...['SUM', 'AVERAGE', 'COUNT', 'MAX', 'MIN'].map((f) => cmd(T.autosum, `${f}( )`, () => autosum(f), 'sigma', undefined, `autosum ${f.toLowerCase()}`)),
3342
3410
  cmd(T.gFormat, T.bold, () => toggleStyle('b'), 'bold', `${MOD}B`, 'bold'),
3343
3411
  cmd(T.gEdit, T.insertCheckbox, insertCheckboxes, 'check', undefined, 'checkbox tick box todo'),
3412
+ cmd(T.gEdit, T.protectRange, protectSelection, 'eyeOff', undefined, 'protect lock range read only'),
3413
+ cmd(T.gEdit, T.unprotectRange, unprotectSelection, 'eye', undefined, 'unprotect unlock range'),
3344
3414
  cmd(T.gEdit, T.removeCheckbox, removeCheckboxes, 'check', undefined, 'checkbox remove'),
3345
3415
  ...(['top', 'middle', 'bottom'] as const).map((v) => cmd(T.gFormat, `${T.valign}:${T[`valign_${v}`]}`, () => setValign(v), 'alignCenter', undefined, `vertical align ${v}`)),
3346
3416
  cmd(T.gFormat, T.italic, () => toggleStyle('i'), 'italic', `${MOD}I`, 'italic'),
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { Scalar } from '../../engine/src/index.ts';
3
+ import { conditionalLook, iconCount, iconGlyph } from './features.ts';
4
+ import type { ConditionalRule, SheetData } from './types.ts';
5
+
6
+ // A1:A5 = 10, 20, 30, 40, 50
7
+ const values: Scalar[] = [10, 20, 30, 40, 50];
8
+ const lookFor = (rule: ConditionalRule) => {
9
+ const sheet: SheetData = { name: 'S', cells: {}, conditional: [rule] };
10
+ const look = conditionalLook(sheet, (row) => values[row] ?? null, { rows: 5, cols: 1 });
11
+ return values.map((_, row) => look(row, 0));
12
+ };
13
+
14
+ describe('Excel conditional formats from xlsx', () => {
15
+ it('Top and Bottom N, by count and by percent', () => {
16
+ expect(lookFor({ range: 'A1:A5', type: 'top', rank: 2 }).map(Boolean)).toEqual([false, false, false, true, true]);
17
+ expect(lookFor({ range: 'A1:A5', type: 'top', rank: 2, bottom: true }).map(Boolean)).toEqual([true, true, false, false, false]);
18
+ expect(lookFor({ range: 'A1:A5', type: 'top', rank: 40, percent: true }).map(Boolean)).toEqual([false, false, false, true, true]);
19
+ });
20
+
21
+ it('above and below the average, with or without it', () => {
22
+ expect(lookFor({ range: 'A1:A5', type: 'average' }).map(Boolean)).toEqual([false, false, false, true, true]);
23
+ expect(lookFor({ range: 'A1:A5', type: 'average', below: true, equal: true }).map(Boolean)).toEqual([true, true, true, false, false]);
24
+ });
25
+
26
+ it('icon sets pick a level by percent of the range, reversible', () => {
27
+ const arrows = lookFor({ range: 'A1:A5', type: 'iconSet', set: '3Arrows' }).map((l) => l?.icon?.glyph);
28
+ // 10..50 sit at 0, 25, 50, 75 and 100 percent; Excel's 3-icon cuts are 33 and 67.
29
+ expect(arrows).toEqual(['↓', '↓', '→', '↑', '↑']);
30
+ const reversed = lookFor({ range: 'A1:A5', type: 'iconSet', set: '3Arrows', reverse: true }).map((l) => l?.icon?.glyph);
31
+ expect(reversed).toEqual(['↑', '↑', '→', '↓', '↓']);
32
+ expect(lookFor({ range: 'A1:A5', type: 'iconSet', set: '3TrafficLights1', thresholds: [50, 90] }).map((l) => l?.icon?.color)).toEqual([
33
+ '#d93025',
34
+ '#d93025',
35
+ '#f9ab00',
36
+ '#f9ab00',
37
+ '#1e8e3e',
38
+ ]);
39
+ expect(iconCount('5Rating')).toBe(5);
40
+ expect(iconGlyph('4Arrows', 3, 4).glyph).toBe('↑');
41
+ });
42
+ });
package/app/features.ts CHANGED
@@ -27,6 +27,22 @@ export const inRect = (r: Rect, row: number, col: number) => row >= r.r0 && row
27
27
  * A range after `count` rows or columns are inserted before `at` (negative:
28
28
  * deleted): it grows, shrinks or moves; null when every cell of it is gone.
29
29
  */
30
+ /** Whether a cell lies in one of the sheet's protected ranges. */
31
+ export function isProtectedCell(sheet: SheetData, row: number, col: number): boolean {
32
+ return (sheet.protected ?? []).some((t) => {
33
+ const r = parseRange(t);
34
+ return r !== null && row >= r.r0 && row <= r.r1 && col >= r.c0 && col <= r.c1;
35
+ });
36
+ }
37
+
38
+ /** Whether any cell of a rectangle is protected. */
39
+ export function touchesProtected(sheet: SheetData, rect: { r0: number; c0: number; r1: number; c1: number }): boolean {
40
+ return (sheet.protected ?? []).some((t) => {
41
+ const r = parseRange(t);
42
+ return r !== null && r.r0 <= rect.r1 && rect.r0 <= r.r1 && r.c0 <= rect.c1 && rect.c0 <= r.c1;
43
+ });
44
+ }
45
+
30
46
  export function shiftRange(text: string, axis: 'row' | 'col', at: number, count: number): string | null {
31
47
  const m = parseRange(text);
32
48
  if (!m) return null;
@@ -57,6 +73,35 @@ export interface CellLook {
57
73
  b?: boolean;
58
74
  /** A data bar: how far it reaches (0–1) and its colour. */
59
75
  bar?: { pct: number; color: string };
76
+ /** An icon-set icon: the glyph and its colour. */
77
+ icon?: { glyph: string; color: string };
78
+ }
79
+
80
+ /** How many icons a set has: "3Arrows" → 3. */
81
+ export const iconCount = (set: string) => Math.min(5, Math.max(3, Number(/^(\d)/.exec(set)?.[1] ?? 3)));
82
+
83
+ /**
84
+ * The glyph for level `i` (0 = lowest) of an icon set, drawn as text so it needs
85
+ * no image: arrows, lights, symbols, flags, ratings and the rest by family.
86
+ */
87
+ export function iconGlyph(set: string, i: number, n: number): { glyph: string; color: string } {
88
+ const red = '#d93025';
89
+ const amber = '#f9ab00';
90
+ const green = '#1e8e3e';
91
+ const grey = '#80868b';
92
+ const traffic = n === 3 ? [red, amber, green] : n === 4 ? ['#202124', red, amber, green] : [red, '#e37400', amber, '#7cb342', green];
93
+ const name = set.replace(/^\d/, '');
94
+ if (/Arrows/.test(name)) {
95
+ const glyphs = n === 3 ? ['↓', '→', '↑'] : n === 4 ? ['↓', '↘', '↗', '↑'] : ['↓', '↘', '→', '↗', '↑'];
96
+ return { glyph: glyphs[i]!, color: /Gray/.test(name) ? grey : traffic[i]! };
97
+ }
98
+ if (/Traffic|Signs/.test(name)) return { glyph: '●', color: traffic[i]! };
99
+ if (/Symbols/.test(name)) return { glyph: ['✖', '!', '✔'][Math.min(2, Math.round((i * 2) / (n - 1)))]!, color: [red, amber, green][Math.min(2, Math.round((i * 2) / (n - 1)))]! };
100
+ if (/Flags/.test(name)) return { glyph: '⚑', color: [red, amber, green][Math.min(2, Math.round((i * 2) / (n - 1)))]! };
101
+ if (/Stars/.test(name)) return { glyph: ['☆', '⯪', '★'][Math.min(2, i)]!, color: amber };
102
+ if (/Rating|Quarters|Boxes|Triangles/.test(name)) return { glyph: ['○', '◔', '◑', '◕', '●'][Math.round((i * 4) / (n - 1))]!, color: '#1a73e8' };
103
+ if (/RedToBlack/.test(name)) return { glyph: '●', color: ['#202124', grey, '#f28b82', red][Math.min(3, i)]! };
104
+ return { glyph: '●', color: traffic[i]! };
60
105
  }
61
106
 
62
107
  const hex = (c: string) => {
@@ -88,7 +133,7 @@ export function conditionalLook(sheet: SheetData, value: (row: number, col: numb
88
133
  let max = -Infinity;
89
134
  const nums: number[] = [];
90
135
  const counts = new Map<string, number>();
91
- if (rule.type === 'colorScale' || rule.type === 'dataBar' || rule.type === 'duplicate') {
136
+ if (rule.type === 'colorScale' || rule.type === 'dataBar' || rule.type === 'duplicate' || rule.type === 'top' || rule.type === 'average' || rule.type === 'iconSet') {
92
137
  for (let row = rect.r0; row <= rect.r1; row++) {
93
138
  for (let col = rect.c0; col <= rect.c1; col++) {
94
139
  const v = value(row, col);
@@ -107,17 +152,38 @@ export function conditionalLook(sheet: SheetData, value: (row: number, col: numb
107
152
  }
108
153
  nums.sort((a, b) => a - b);
109
154
  const mid = nums.length ? nums[Math.floor((nums.length - 1) / 2)]! : 0;
110
- return { rule, rect, min, max, mid, counts };
155
+ const mean = nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : 0;
156
+ // The value a Top/Bottom rule cuts at: the rank-th from the top (or bottom).
157
+ let cut = Number.NaN;
158
+ if (rule.type === 'top' && nums.length) {
159
+ const k = Math.max(1, rule.percent ? Math.floor((nums.length * rule.rank) / 100) : Math.floor(rule.rank));
160
+ cut = rule.bottom ? nums[Math.min(k, nums.length) - 1]! : nums[Math.max(0, nums.length - k)]!;
161
+ }
162
+ return { rule, rect, min, max, mid, counts, mean, cut };
111
163
  })
112
164
  .filter((x) => x !== null);
113
165
  if (!rules.length) return () => null;
114
166
 
115
167
  return (row, col) => {
116
168
  let look: CellLook | null = null;
117
- for (const { rule, rect, min, max, mid, counts } of rules) {
169
+ for (const { rule, rect, min, max, mid, counts, mean, cut } of rules) {
118
170
  if (!inRect(rect, row, col)) continue;
119
171
  const v = value(row, col);
120
172
  if (v === null || v === '') continue;
173
+ const n = asNumber(v);
174
+ if (rule.type === 'top' && (n === null || Number.isNaN(cut) || (rule.bottom ? n > cut : n < cut))) continue;
175
+ if (rule.type === 'average' && (n === null || (rule.below ? (rule.equal ? n > mean : n >= mean) : rule.equal ? n < mean : n <= mean))) continue;
176
+ if (rule.type === 'iconSet') {
177
+ if (n === null || !Number.isFinite(min)) continue;
178
+ const count = iconCount(rule.set);
179
+ const cuts = rule.thresholds?.length === count - 1 ? rule.thresholds : Array.from({ length: count - 1 }, (_, i) => Math.round(((i + 1) * 100) / count));
180
+ const pct = max === min ? 100 : ((n - min) / (max - min)) * 100;
181
+ let level = cuts.filter((c) => pct >= c).length;
182
+ if (rule.reverse) level = count - 1 - level;
183
+ look ??= {};
184
+ look.icon = iconGlyph(rule.set, level, count);
185
+ continue;
186
+ }
121
187
  const hit = test(rule, v, counts);
122
188
  if (hit === false) continue;
123
189
  look ??= {};
package/app/i18n-more.ts CHANGED
@@ -211,6 +211,11 @@ export const zhCN: Dict = {
211
211
  openLinkHint: '⌘+点击打开',
212
212
  insertCheckbox: '插入复选框',
213
213
  removeCheckbox: '删除复选框',
214
+ protectRange: '保护区域',
215
+ unprotectRange: '取消保护',
216
+ protectedOn: (r: string) => `已保护 ${r}:取消保护前不能修改。`,
217
+ protectedOff: '已取消保护。',
218
+ protectedRefused: '这个区域受保护。请先取消保护(右键 → 取消保护)。',
214
219
  fontSize: '字号',
215
220
  fontSizeOther: '其他字号…',
216
221
  customSort: '自定义排序…',
@@ -474,6 +479,11 @@ export const ja: Dict = {
474
479
  openLinkHint: '⌘+クリックで開く',
475
480
  insertCheckbox: 'チェックボックスを挿入',
476
481
  removeCheckbox: 'チェックボックスを削除',
482
+ protectRange: '範囲を保護',
483
+ unprotectRange: '範囲の保護を解除',
484
+ protectedOn: (r: string) => `${r} を保護しました。解除するまで変更できません。`,
485
+ protectedOff: '保護を解除しました。',
486
+ protectedRefused: 'この範囲は保護されています。先に保護を解除してください(右クリック → 範囲の保護を解除)。',
477
487
  fontSize: 'フォント サイズ',
478
488
  fontSizeOther: 'その他のサイズ…',
479
489
  customSort: 'ユーザー設定の並べ替え…',
@@ -737,6 +747,11 @@ export const ko: Dict = {
737
747
  openLinkHint: '⌘+클릭으로 열기',
738
748
  insertCheckbox: '확인란 삽입',
739
749
  removeCheckbox: '확인란 제거',
750
+ protectRange: '범위 보호',
751
+ unprotectRange: '범위 보호 해제',
752
+ protectedOn: (r: string) => `${r}을(를) 보호했습니다. 해제하기 전에는 변경할 수 없습니다.`,
753
+ protectedOff: '보호를 해제했습니다.',
754
+ protectedRefused: '이 범위는 보호되어 있습니다. 먼저 보호를 해제하세요(오른쪽 클릭 → 범위 보호 해제).',
740
755
  fontSize: '글꼴 크기',
741
756
  fontSizeOther: '다른 크기…',
742
757
  customSort: '사용자 지정 정렬…',
package/app/i18n.ts CHANGED
@@ -211,6 +211,11 @@ export const en = {
211
211
  openLinkHint: '⌘-click to open',
212
212
  insertCheckbox: 'Insert checkbox',
213
213
  removeCheckbox: 'Remove checkbox',
214
+ protectRange: 'Protect range',
215
+ unprotectRange: 'Unprotect range',
216
+ protectedOn: (r: string) => `Protected: ${r}. Its cells cannot be changed until unprotected.`,
217
+ protectedOff: 'Protection removed.',
218
+ protectedRefused: 'This range is protected. Unprotect it first (right-click → Unprotect range).',
214
219
  fontSize: 'Font size',
215
220
  fontSizeOther: 'Other size…',
216
221
  customSort: 'Custom sort…',
@@ -474,6 +479,11 @@ const zh: Dict = {
474
479
  openLinkHint: '⌘+點擊開啟',
475
480
  insertCheckbox: '插入核取方塊',
476
481
  removeCheckbox: '移除核取方塊',
482
+ protectRange: '保護範圍',
483
+ unprotectRange: '取消保護',
484
+ protectedOn: (r: string) => `已保護 ${r}:取消保護前不能修改。`,
485
+ protectedOff: '已取消保護。',
486
+ protectedRefused: '這個範圍受保護。請先取消保護(右鍵 → 取消保護)。',
477
487
  fontSize: '字型大小',
478
488
  fontSizeOther: '其他大小…',
479
489
  customSort: '自訂排序…',
package/app/io.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { CellError, columnIndex, columnName, formatA1, formatValue, impliedFormat, offsetFormula, parseA1, type Scalar, Workbook } from '@open-spreadsheet/engine';
7
7
  import { chartShape } from './charts.ts';
8
- import { BLANK, columnValues, filteredRows, parseRange } from './features.ts';
8
+ import { BLANK, columnValues, filteredRows, parseRange, iconCount } from './features.ts';
9
9
  import type { CellStyle, ChartSpec, ChartType, ConditionalRule, HighlightStyle, SheetData, WorkbookData } from './types.ts';
10
10
 
11
11
  // ---------- CSV ----------
@@ -255,6 +255,16 @@ export function exportXlsx(data: WorkbookData, wb: Workbook): Blob {
255
255
  }
256
256
  case 'dataBar':
257
257
  return `<cfRule type="dataBar" priority="${priority}"><dataBar><cfvo type="min"/><cfvo type="max"/><color rgb="${argb(r.color ?? '#638ec6')}"/></dataBar></cfRule>`;
258
+ case 'top':
259
+ return `<cfRule type="top10" dxfId="${dxfId(r.style)}" priority="${priority}" rank="${Math.max(1, Math.floor(r.rank))}"${r.percent ? ' percent="1"' : ''}${r.bottom ? ' bottom="1"' : ''}/>`;
260
+ case 'average':
261
+ return `<cfRule type="aboveAverage" dxfId="${dxfId(r.style)}" priority="${priority}"${r.below ? ' aboveAverage="0"' : ''}${r.equal ? ' equalAverage="1"' : ''}/>`;
262
+ case 'iconSet': {
263
+ const count = iconCount(r.set);
264
+ const cuts = r.thresholds?.length === count - 1 ? r.thresholds : Array.from({ length: count - 1 }, (_, i) => Math.round(((i + 1) * 100) / count));
265
+ const set = /^[3-5][A-Za-z0-9]+$/.test(r.set) ? r.set : '3TrafficLights1';
266
+ return `<cfRule type="iconSet" priority="${priority}"><iconSet iconSet="${set}"${r.reverse ? ' reverse="1"' : ''}><cfvo type="percent" val="0"/>${cuts.map((c) => `<cfvo type="percent" val="${c}"/>`).join('')}</iconSet></cfRule>`;
267
+ }
258
268
  default:
259
269
  return `<cfRule type="cellIs" dxfId="${dxfId(r.style)}" priority="${priority}" operator="${OPS[r.type]}"><formula>${xml(literal(r.value))}</formula></cfRule>`;
260
270
  }
@@ -713,6 +723,36 @@ function readRules(doc: Document, sheet: SheetData, dxfs: HighlightStyle[]): voi
713
723
  if (colors.length >= 2) conditional.push({ range, type: 'colorScale', colors });
714
724
  } else if (type === 'dataBar') {
715
725
  conditional.push({ range, type: 'dataBar', color: rgbOf(first(rule, 'color')) ?? '#638ec6' });
726
+ } else if (type === 'top10') {
727
+ conditional.push({
728
+ range,
729
+ type: 'top',
730
+ rank: Number(rule.getAttribute('rank') ?? 10) || 10,
731
+ ...(rule.getAttribute('percent') === '1' ? { percent: true } : {}),
732
+ ...(rule.getAttribute('bottom') === '1' ? { bottom: true } : {}),
733
+ style,
734
+ });
735
+ } else if (type === 'aboveAverage') {
736
+ conditional.push({
737
+ range,
738
+ type: 'average',
739
+ ...(rule.getAttribute('aboveAverage') === '0' ? { below: true } : {}),
740
+ ...(rule.getAttribute('equalAverage') === '1' ? { equal: true } : {}),
741
+ style,
742
+ });
743
+ } else if (type === 'iconSet') {
744
+ const is = first(rule, 'iconSet');
745
+ const set = is?.getAttribute('iconSet') ?? '3TrafficLights1';
746
+ // Only percent thresholds carry over; other kinds fall back to even steps.
747
+ const cfvos = is ? tags(is, 'cfvo') : [];
748
+ const thresholds = cfvos.slice(1).map((c) => (c.getAttribute('type') === 'percent' ? Number(c.getAttribute('val')) : Number.NaN));
749
+ conditional.push({
750
+ range,
751
+ type: 'iconSet',
752
+ set,
753
+ ...(thresholds.length === iconCount(set) - 1 && thresholds.every(Number.isFinite) ? { thresholds } : {}),
754
+ ...(is?.getAttribute('reverse') === '1' ? { reverse: true } : {}),
755
+ });
716
756
  }
717
757
  }
718
758
  }
package/app/style.css CHANGED
@@ -229,6 +229,9 @@ kbd { font: 10.5px var(--mono); color: var(--muted-foreground); border: 1px soli
229
229
  .cell.i { font-style: italic; }
230
230
  .cell.err { color: var(--error); }
231
231
  .cell.link { color: var(--link, #1a73e8); }
232
+ .cell .cf-icon { flex: none; margin-right: auto; padding-right: calc(4px * var(--z)); font-size: 0.95em; line-height: 1; }
233
+ .cell.a-left .cf-icon { margin-right: calc(4px * var(--z)); }
234
+ .cell.locked { background-image: repeating-linear-gradient(135deg, transparent 0 6px, color-mix(in srgb, var(--cell-fg) 6%, transparent) 6px 7px); }
232
235
  .cell .cb { width: calc(14px * var(--z)); height: calc(14px * var(--z)); border: 1.5px solid var(--muted-foreground); border-radius: 3px; display: inline-grid; place-items: center; cursor: pointer; flex: none; }
233
236
  .cell .cb.on { background: var(--link, #1a73e8); border-color: var(--link, #1a73e8); color: #fff; }
234
237
  .cell .cb svg { width: 100%; height: 100%; }
package/app/types.ts CHANGED
@@ -24,6 +24,11 @@ export interface SheetData {
24
24
  name: string;
25
25
  /** What was typed, by A1 address: "120", "=SUM(B2:B3)". */
26
26
  cells: Record<string, string>;
27
+ /**
28
+ * Protected ranges ("A1:D1"): their contents and formats cannot be changed
29
+ * from the editor or by an agent through MCP until a person unprotects them.
30
+ */
31
+ protected?: string[];
27
32
  /** Column widths in px by column letter. */
28
33
  cols?: Record<string, number>;
29
34
  /** Row heights in px by 1-based row number. */
@@ -59,7 +64,17 @@ export type ConditionalRule =
59
64
  | { range: string; type: 'duplicate'; style?: HighlightStyle }
60
65
  /** Two or three colours, from the smallest number to the largest. */
61
66
  | { range: string; type: 'colorScale'; colors: string[] }
62
- | { range: string; type: 'dataBar'; color?: string };
67
+ | { range: string; type: 'dataBar'; color?: string }
68
+ /** Excel's Top/Bottom N (or N percent) items. */
69
+ | { range: string; type: 'top'; rank: number; percent?: boolean; bottom?: boolean; style?: HighlightStyle }
70
+ /** Above (or below) the range's average; `equal` counts the average itself. */
71
+ | { range: string; type: 'average'; below?: boolean; equal?: boolean; style?: HighlightStyle }
72
+ /**
73
+ * An icon per cell by where its number falls between the range's smallest and
74
+ * largest: Excel's icon sets, e.g. "3Arrows", "3TrafficLights1", "4Rating", "5Arrows".
75
+ * `thresholds` are the percents between icons (3 icons → [33, 67]).
76
+ */
77
+ | { range: string; type: 'iconSet'; set: string; thresholds?: number[]; reverse?: boolean };
63
78
 
64
79
  export interface Validation {
65
80
  range: string;
package/mcp.js CHANGED
@@ -197,6 +197,34 @@ const TOOLS = [
197
197
 
198
198
  // ---------- tools ----------
199
199
 
200
+ /** Whether a cell lies in a protected range of the sheet. */
201
+ const isProtected = (sheet, row, col) =>
202
+ (sheet.protected ?? []).some((t) => {
203
+ const r = parseRange(t);
204
+ return row >= r.r0 && row <= r.r1 && col >= r.c0 && col <= r.c1;
205
+ });
206
+ const refuseProtected = (sheet, cells) => {
207
+ const hit = cells.find((c) => isProtected(sheet, c.row, c.col));
208
+ if (hit)
209
+ throw new OpsError(
210
+ 'protected',
211
+ `${formatA1(hit.row, hit.col)} on ${sheet.name} is in a protected range (${sheet.protected.join(', ')}). Ask the person to unprotect it in the editor; agents cannot change protected cells or remove protection.`,
212
+ );
213
+ };
214
+
215
+ /** Refuses a style change on a rectangle that overlaps a protected range. */
216
+ const refuseProtectedRect = (sheet, r) => {
217
+ const hit = (sheet.protected ?? []).find((t) => {
218
+ const p = parseRange(t);
219
+ return p.r0 <= r.r1 && r.r0 <= p.r1 && p.c0 <= r.c1 && r.c0 <= p.c1;
220
+ });
221
+ if (hit)
222
+ throw new OpsError(
223
+ 'protected',
224
+ `${hit} on ${sheet.name} is protected. Ask the person to unprotect it in the editor; agents cannot change protected cells or remove protection.`,
225
+ );
226
+ };
227
+
200
228
  const sheetOf = (data, name) => {
201
229
  const s = data.sheets.find((x) => x.name === name);
202
230
  if (!s) throw new OpsError('no_sheet', `No sheet "${name}". Sheets: ${data.sheets.map((x) => x.name).join(', ')}`);
@@ -248,6 +276,20 @@ function shiftMeta(sheet, axis, at, count) {
248
276
  }
249
277
  if (axis === 'col' && sheet.cols) sheet.cols = Object.fromEntries(Object.entries(sheet.cols).flatMap(([k, v]) => (move(columnIndex(k)) === null ? [] : [[columnName(move(columnIndex(k))), v]])));
250
278
  if (axis === 'row' && sheet.rows) sheet.rows = Object.fromEntries(Object.entries(sheet.rows).flatMap(([k, v]) => (move(Number(k) - 1) === null ? [] : [[String(move(Number(k) - 1) + 1), v]])));
279
+ if (sheet.protected) {
280
+ sheet.protected = sheet.protected.flatMap((t) => {
281
+ const r = parseRange(t);
282
+ const lo = axis === 'row' ? r.r0 : r.c0;
283
+ const hi = axis === 'row' ? r.r1 : r.c1;
284
+ const a = move(lo);
285
+ const b = move(hi);
286
+ if (a === null && b === null) return [];
287
+ const n = axis === 'row' ? { ...r, r0: a ?? at, r1: b ?? at - 1 } : { ...r, c0: a ?? at, c1: b ?? at - 1 };
288
+ if (n.r1 < n.r0 || n.c1 < n.c0) return [];
289
+ return [n.r0 === n.r1 && n.c0 === n.c1 ? formatA1(n.r0, n.c0) : `${formatA1(n.r0, n.c0)}:${formatA1(n.r1, n.c1)}`];
290
+ });
291
+ if (!sheet.protected.length) delete sheet.protected;
292
+ }
251
293
  if (sheet.merges) {
252
294
  sheet.merges = sheet.merges.flatMap((m) => {
253
295
  const r = parseRange(m);
@@ -275,13 +317,14 @@ async function callTool(root, name, a) {
275
317
  return traceCell(readWorkbook(root, a.workbook).data, a.sheet, a.address);
276
318
  case 'write_cells':
277
319
  return mutate(root, a.workbook, a.expected_hash, (data, wb) => {
278
- sheetOf(data, a.sheet);
320
+ const target = sheetOf(data, a.sheet);
279
321
  const cells = Object.entries(a.cells ?? {}).map(([addr, input]) => {
280
322
  const p = parseA1(addr);
281
323
  if (!p) throw new OpsError('bad_address', `Not an A1 address: ${addr}`);
282
324
  if (input !== null && typeof input !== 'string') throw new OpsError('bad_input', `${addr}: inputs are strings, e.g. "${input}"`);
283
325
  return { ...p, input: input ?? '' };
284
326
  });
327
+ refuseProtected(target, cells);
285
328
  wb.setCells(a.sheet, cells);
286
329
  const values = Object.fromEntries(cells.map((c) => [formatA1(c.row, c.col), wb.value(a.sheet, c.row, c.col)?.toString?.() ?? null]));
287
330
  return { written: cells.length, values };
@@ -290,6 +333,7 @@ async function callTool(root, name, a) {
290
333
  return mutate(root, a.workbook, a.expected_hash, (data) => {
291
334
  const sheet = sheetOf(data, a.sheet);
292
335
  const r = parseRange(a.range);
336
+ refuseProtectedRect(sheet, r);
293
337
  sheet.styles ??= {};
294
338
  for (let row = r.r0; row <= r.r1; row++) {
295
339
  for (let col = r.c0; col <= r.c1; col++) {
@@ -391,8 +435,10 @@ async function callTool(root, name, a) {
391
435
  });
392
436
  case 'delete_sheet':
393
437
  return mutate(root, a.workbook, a.expected_hash, (data, wb) => {
394
- sheetOf(data, a.sheet);
438
+ const doomed = sheetOf(data, a.sheet);
395
439
  if (data.sheets.length === 1) throw new OpsError('last_sheet', 'A workbook needs at least one sheet.');
440
+ if (doomed.protected?.length)
441
+ throw new OpsError('protected', `${a.sheet} has protected ranges (${doomed.protected.join(', ')}). Ask the person to unprotect them in the editor before it can be deleted.`);
396
442
  wb.removeSheet(a.sheet);
397
443
  data.sheets = data.sheets.filter((s) => s.name !== a.sheet);
398
444
  });
package/ops.js CHANGED
@@ -271,7 +271,9 @@ export function checkWorkbook(data) {
271
271
  for (const a of Object.keys(s.styles ?? {})) if (!parseA1(a)) add('warning', s.name, a, 'Style on something that is not an A1 address.');
272
272
  for (const rule of s.conditional ?? []) {
273
273
  if (!parseRange(rule.range ?? '')) add('error', s.name, rule.range ?? '', 'A conditional format needs a range like B2:B20.');
274
- if (!['gt', 'lt', 'ge', 'le', 'eq', 'ne', 'between', 'contains', 'duplicate', 'colorScale', 'dataBar'].includes(rule.type)) add('error', s.name, rule.range ?? '', `Unknown conditional format type "${rule.type}".`);
274
+ if (!['gt', 'lt', 'ge', 'le', 'eq', 'ne', 'between', 'contains', 'duplicate', 'colorScale', 'dataBar', 'top', 'average', 'iconSet'].includes(rule.type)) add('error', s.name, rule.range ?? '', `Unknown conditional format type "${rule.type}".`);
275
+ if (rule.type === 'top' && !(Number(rule.rank) >= 1)) add('error', s.name, rule.range ?? '', 'A top/bottom rule needs a rank of 1 or more.');
276
+ if (rule.type === 'iconSet' && !/^[3-5][A-Za-z0-9]+$/.test(rule.set ?? '')) add('error', s.name, rule.range ?? '', 'An icon set is named like Excel\'s: "3Arrows", "3TrafficLights1", "5Rating".');
275
277
  }
276
278
  for (const v of s.validation ?? []) {
277
279
  if (!parseRange(v.range ?? '')) add('error', s.name, v.range ?? '', 'A validation rule needs a range.');
@@ -287,6 +289,7 @@ export function checkWorkbook(data) {
287
289
  if (!parseA1(a)) add('warning', s.name, a, 'Note on something that is not an A1 address.');
288
290
  else if (typeof t !== 'string') add('error', s.name, a, 'A note is a string.');
289
291
  }
292
+ for (const t of s.protected ?? []) if (!parseRange(t)) add('error', s.name, t, 'Not a protected range like A1:D1 or B2.');
290
293
  const merges = (s.merges ?? []).map((m) => ({ m, r: parseRange(m) }));
291
294
  for (const { m, r } of merges) if (!r || !m.includes(':')) add('error', s.name, m, 'Not a merge range like A1:C1.');
292
295
  for (let i = 0; i < merges.length; i++)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-spreadsheet/core",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "open-spreadsheet: an Excel-like spreadsheet for agents and people. The dev server, the grid editor and the CLI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,10 +34,11 @@ Each workbook is `sheets/<id>/workbook.json`. The grid editor at `pnpm dev` relo
34
34
  | `freeze` | `{ rows, cols }` frozen at the top and left |
35
35
  | `hiddenRows` / `hiddenCols` | Rows (1-based numbers) and columns (letters) hidden by hand |
36
36
  | `names` (top level, beside `sheets`) | Defined names: `{ "Sales": "Orders!$F$2:$F$200" }`, used in formulas as `=SUM(Sales)`; each points at a cell or range with its sheet |
37
+ | `protected` | Ranges a person locked, `["A1:D1", "F2"]`. The editor and MCP refuse to change them; never edit or remove them yourself — ask the person |
37
38
  | `charts` | Charts over the grid: `[{ "id": "sales", "type": "bar", "range": "A1:C13", "title": "Sales by month", "x": 520, "y": 0, "w": 440, "h": 270 }]` — `type` is `bar`, `line` or `pie`; the range's first column holds the categories and its first row the series names; `x`/`y`/`w`/`h` are px at 100% zoom from the sheet's top-left |
38
39
  | `color` | The sheet tab's colour |
39
40
  | `notes` | A1 address → a note left on the cell (see the `apply-notes` skill) |
40
- | `conditional` | Conditional formats, later ones win: `{ "range": "D2:D50", "type": "gt", "value": 10000, "style": { "bg": "#ffc7ce", "color": "#9c0006" } }`; types `gt lt ge le eq ne` (value), `between` (value, value2), `contains` (text), `duplicate`, `colorScale` (`colors`: 2 or 3 hex, low → high), `dataBar` (`color`) |
41
+ | `conditional` | Conditional formats, later ones win: `{ "range": "D2:D50", "type": "gt", "value": 10000, "style": { "bg": "#ffc7ce", "color": "#9c0006" } }`; types `gt lt ge le eq ne` (value), `between` (value, value2), `contains` (text), `duplicate`, `colorScale` (`colors`: 2 or 3 hex, low → high), `dataBar` (`color`), `top` (`rank`, optional `percent`, `bottom`), `average` (optional `below`, `equal`), `iconSet` (`set` as Excel names it — `3Arrows`, `3TrafficLights1`, `4Rating`, `5Arrows`…; optional `thresholds` in percent, `reverse`). All of them go to and from .xlsx |
41
42
  | `validation` | Dropdown lists: `[{ "range": "C2:C100", "list": ["Open", "In progress", "Done"] }]`; other input is refused in the editor |
42
43
  | `filter` | An autofilter: `{ "range": "A1:F200" }` (header row first); `hidden` maps a column letter to the shown values it hides |
43
44
 
@@ -45,6 +45,7 @@ npx open-spreadsheet export <id> --range A1:F200 --out data.csv # computed val
45
45
  - Sizes are pixels: `cols` by letter, `rows` by 1-based row number.
46
46
  - **Defined names** sit at the top level: `"names": { "Sales": "Orders!$F$2:$F$200" }`, then `=SUM(Sales)`.
47
47
  - **Conditional formats, dropdown lists and filters** live beside the cells too (`conditional`, `validation`, `filter`); see the `sheet-authoring` skill.
48
+ - **Protected ranges** (`"protected": ["A1:D1"]` on a sheet) are cells a person locked. Do not change them, by MCP or by editing the JSON; if a task needs them changed, ask the person to unprotect them in the editor.
48
49
  - **Notes** are comments people leave on cells, often requests for you. "Apply the notes" means: do what each asks, then remove it (the `apply-notes` skill).
49
50
 
50
51
  ## Working rules