@open-spreadsheet/core 0.1.1 → 0.3.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/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,28 @@ 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: '这个区域受保护。请先取消保护(右键 → 取消保护)。',
219
+ assets: 'Assets',
220
+ assetsHint: '这个工作簿的图片和笔记;笔记也是 agent 处理时的背景资料。',
221
+ assetsThisBook: '这个工作簿',
222
+ assetsShared: '共享',
223
+ newChartImage: '图表图片',
224
+ newNote: '新建笔记',
225
+ uploadImage: '上传图片',
226
+ noAssets: '还没有内容。',
227
+ saveIn: '保存在',
228
+ noteContextHint: 'Markdown 格式。Agent 处理这个工作簿前会先读这些笔记:数字的含义、来源、要遵守的规则。',
229
+ deleteAssetTitle: (n: string) => `删除 ${n}?`,
230
+ deleteAssetBody: '会移到 assets 的 .trash 文件夹。',
231
+ chartSaved: (n: string) => `已保存到 Assets:${n}`,
232
+ chartsMoved: (k: number) => `已把 ${k} 个图表移到 Assets`,
233
+ chartsOnGrid: (k: number) => `这个工作簿的单元格上有 ${k} 个图表;图表现在改以图片放在 Assets。`,
234
+ moveChartsToAssets: '移到 Assets',
235
+ close: '关闭',
214
236
  fontSize: '字号',
215
237
  fontSizeOther: '其他字号…',
216
238
  customSort: '自定义排序…',
@@ -474,6 +496,28 @@ export const ja: Dict = {
474
496
  openLinkHint: '⌘+クリックで開く',
475
497
  insertCheckbox: 'チェックボックスを挿入',
476
498
  removeCheckbox: 'チェックボックスを削除',
499
+ protectRange: '範囲を保護',
500
+ unprotectRange: '範囲の保護を解除',
501
+ protectedOn: (r: string) => `${r} を保護しました。解除するまで変更できません。`,
502
+ protectedOff: '保護を解除しました。',
503
+ protectedRefused: 'この範囲は保護されています。先に保護を解除してください(右クリック → 範囲の保護を解除)。',
504
+ assets: 'Assets',
505
+ assetsHint: 'このブックの画像とメモ。メモはエージェントの作業時の前提情報にもなります。',
506
+ assetsThisBook: 'このブック',
507
+ assetsShared: '共有',
508
+ newChartImage: 'グラフ画像',
509
+ close: '閉じる',
510
+ newNote: '新しいメモ',
511
+ uploadImage: '画像をアップロード',
512
+ noAssets: 'まだありません。',
513
+ saveIn: '保存先',
514
+ noteContextHint: 'Markdown。エージェントはブックを扱う前にこれらのメモを読みます:数字の意味、出典、守るべきルール。',
515
+ deleteAssetTitle: (n: string) => `${n} を削除しますか?`,
516
+ deleteAssetBody: 'assets の .trash フォルダーに移動します。',
517
+ chartSaved: (n: string) => `Assets に保存しました:${n}`,
518
+ chartsMoved: (k: number) => `${k} 個のグラフを Assets に移動しました`,
519
+ chartsOnGrid: (k: number) => `このブックのセル上に ${k} 個のグラフがあります。グラフは画像として Assets に置くようになりました。`,
520
+ moveChartsToAssets: 'Assets へ移動',
477
521
  fontSize: 'フォント サイズ',
478
522
  fontSizeOther: 'その他のサイズ…',
479
523
  customSort: 'ユーザー設定の並べ替え…',
@@ -737,6 +781,28 @@ export const ko: Dict = {
737
781
  openLinkHint: '⌘+클릭으로 열기',
738
782
  insertCheckbox: '확인란 삽입',
739
783
  removeCheckbox: '확인란 제거',
784
+ protectRange: '범위 보호',
785
+ unprotectRange: '범위 보호 해제',
786
+ protectedOn: (r: string) => `${r}을(를) 보호했습니다. 해제하기 전에는 변경할 수 없습니다.`,
787
+ protectedOff: '보호를 해제했습니다.',
788
+ protectedRefused: '이 범위는 보호되어 있습니다. 먼저 보호를 해제하세요(오른쪽 클릭 → 범위 보호 해제).',
789
+ assets: 'Assets',
790
+ assetsHint: '이 통합 문서의 이미지와 메모입니다. 메모는 에이전트 작업의 배경 정보가 됩니다.',
791
+ assetsThisBook: '이 통합 문서',
792
+ assetsShared: '공유',
793
+ newChartImage: '차트 이미지',
794
+ close: '닫기',
795
+ newNote: '새 메모',
796
+ uploadImage: '이미지 업로드',
797
+ noAssets: '아직 없습니다.',
798
+ saveIn: '저장 위치',
799
+ noteContextHint: 'Markdown 형식입니다. 에이전트는 통합 문서를 다루기 전에 이 메모를 읽습니다: 숫자의 의미, 출처, 지킬 규칙.',
800
+ deleteAssetTitle: (n: string) => `${n}을(를) 삭제할까요?`,
801
+ deleteAssetBody: 'assets의 .trash 폴더로 이동합니다.',
802
+ chartSaved: (n: string) => `Assets에 저장했습니다: ${n}`,
803
+ chartsMoved: (k: number) => `차트 ${k}개를 Assets로 옮겼습니다`,
804
+ chartsOnGrid: (k: number) => `이 통합 문서의 셀 위에 차트가 ${k}개 있습니다. 차트는 이제 이미지로 Assets에 둡니다.`,
805
+ moveChartsToAssets: 'Assets로 이동',
740
806
  fontSize: '글꼴 크기',
741
807
  fontSizeOther: '다른 크기…',
742
808
  customSort: '사용자 지정 정렬…',
package/app/i18n.ts CHANGED
@@ -211,6 +211,28 @@ 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).',
219
+ assets: 'Assets',
220
+ assetsHint: "This workbook's images and notes. Notes are context for agents.",
221
+ assetsThisBook: 'This workbook',
222
+ assetsShared: 'Shared',
223
+ newChartImage: 'Chart image',
224
+ newNote: 'New note',
225
+ uploadImage: 'Upload image',
226
+ noAssets: 'Nothing here yet.',
227
+ saveIn: 'Save in',
228
+ noteContextHint: 'Markdown. Agents read these notes before working on the workbook: what the numbers mean, where they come from, what to keep.',
229
+ deleteAssetTitle: (n: string) => `Delete ${n}?`,
230
+ deleteAssetBody: 'It moves to the assets .trash folder.',
231
+ chartSaved: (n: string) => `Saved ${n} in Assets`,
232
+ chartsMoved: (k: number) => `Moved ${k} chart${k === 1 ? '' : 's'} to Assets`,
233
+ chartsOnGrid: (k: number) => `This workbook has ${k} chart${k === 1 ? '' : 's'} on the grid. Charts now live in Assets as images.`,
234
+ moveChartsToAssets: 'Move to Assets',
235
+ close: 'Close',
214
236
  fontSize: 'Font size',
215
237
  fontSizeOther: 'Other size…',
216
238
  customSort: 'Custom sort…',
@@ -474,6 +496,28 @@ const zh: Dict = {
474
496
  openLinkHint: '⌘+點擊開啟',
475
497
  insertCheckbox: '插入核取方塊',
476
498
  removeCheckbox: '移除核取方塊',
499
+ protectRange: '保護範圍',
500
+ unprotectRange: '取消保護',
501
+ protectedOn: (r: string) => `已保護 ${r}:取消保護前不能修改。`,
502
+ protectedOff: '已取消保護。',
503
+ protectedRefused: '這個範圍受保護。請先取消保護(右鍵 → 取消保護)。',
504
+ assets: 'Assets',
505
+ assetsHint: '這本活頁簿的圖片和筆記;筆記也是 agent 處理時的背景資料。',
506
+ assetsThisBook: '這本活頁簿',
507
+ assetsShared: '共用',
508
+ newChartImage: '圖表圖片',
509
+ close: '關閉',
510
+ newNote: '新增筆記',
511
+ uploadImage: '上傳圖片',
512
+ noAssets: '還沒有內容。',
513
+ saveIn: '存放在',
514
+ noteContextHint: 'Markdown 格式。Agent 處理這本活頁簿前會先讀這些筆記:數字的意思、來源、要遵守的規則。',
515
+ deleteAssetTitle: (n: string) => `刪除 ${n}?`,
516
+ deleteAssetBody: '會移到 assets 的 .trash 資料夾。',
517
+ chartSaved: (n: string) => `已存到 Assets:${n}`,
518
+ chartsMoved: (k: number) => `已把 ${k} 個圖表移到 Assets`,
519
+ chartsOnGrid: (k: number) => `這本活頁簿的格子上有 ${k} 個圖表;圖表現在改以圖片放在 Assets。`,
520
+ moveChartsToAssets: '移到 Assets',
477
521
  fontSize: '字型大小',
478
522
  fontSizeOther: '其他大小…',
479
523
  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
@@ -189,6 +189,32 @@ kbd { font: 10.5px var(--mono); color: var(--muted-foreground); border: 1px soli
189
189
  .finput { flex: 1; min-width: 0; border: 0; outline: none; padding: 0 12px; background: transparent; font: 13px var(--mono); }
190
190
 
191
191
  .grid-wrap { flex: 1; min-height: 0; position: relative; }
192
+
193
+ /* Assets: a drawer over the grid's right side. */
194
+ .assets-panel { position: absolute; top: 0; right: 0; bottom: 0; width: min(360px, 92vw); z-index: 30; display: flex; flex-direction: column; background: var(--background); border-left: 1px solid var(--border); box-shadow: -12px 0 24px -16px rgb(0 0 0 / 0.25); }
195
+ .assets-panel[hidden] { display: none; }
196
+ .assets-head { display: flex; align-items: center; gap: 8px; padding: 12px 12px 4px 16px; }
197
+ .assets-head h2 { margin: 0; font-size: 15px; font-weight: 600; }
198
+ .assets-hint { margin: 0 16px 10px; font-size: 12px; line-height: 1.5; color: var(--muted-foreground); }
199
+ .assets-actions { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 16px 12px; border-bottom: 1px solid var(--border); }
200
+ .assets-actions .btn { height: 30px; padding: 0 10px; font-size: 12.5px; }
201
+ .assets-list { flex: 1; overflow: auto; padding: 4px 16px 20px; }
202
+ .assets-section h3 { margin: 14px 0 8px; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted-foreground); }
203
+ .assets-empty { margin: 0; font-size: 12.5px; color: var(--muted-foreground); }
204
+ .asset-card { margin-bottom: 10px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: var(--background); }
205
+ .asset-card.fresh { border-color: var(--select); box-shadow: 0 0 0 2px color-mix(in srgb, var(--select) 25%, transparent); }
206
+ .asset-preview { display: block; background: #fff; }
207
+ .asset-preview img { display: block; width: 100%; height: auto; }
208
+ .asset-note { display: flex; align-items: center; gap: 8px; width: 100%; padding: 10px 12px; border: 0; background: none; color: var(--foreground); font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
209
+ .asset-note:hover { background: var(--muted); }
210
+ .asset-note-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
211
+ .asset-foot { display: flex; align-items: center; gap: 4px; padding: 4px 6px 4px 12px; border-top: 1px solid var(--border); }
212
+ .asset-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11.5px; color: var(--muted-foreground); }
213
+ .asset-foot .icon-link { display: inline-grid; place-items: center; width: 28px; height: 28px; border-radius: 6px; color: var(--muted-foreground); }
214
+ .asset-foot .icon-link:hover { background: var(--muted); color: var(--foreground); }
215
+ .legacy-charts { display: flex; align-items: center; gap: 10px; padding: 6px 12px; font-size: 12.5px; background: color-mix(in srgb, var(--select) 8%, var(--background)); border-bottom: 1px solid var(--border); }
216
+ .legacy-charts[hidden] { display: none; }
217
+ .legacy-charts .btn { height: 26px; padding: 0 10px; font-size: 12px; }
192
218
  .grid { position: absolute; inset: 0; overflow: hidden; background: var(--sheet); color: var(--cell-fg); --z: 1; user-select: none; -webkit-user-select: none; }
193
219
  .corner { position: absolute; left: 0; top: 0; width: 46px; height: 24px; z-index: 6; background: var(--head); border-right: 1px solid var(--grid); border-bottom: 1px solid var(--grid); }
194
220
  .corner.picked { background: var(--head-picked); }
@@ -229,6 +255,9 @@ kbd { font: 10.5px var(--mono); color: var(--muted-foreground); border: 1px soli
229
255
  .cell.i { font-style: italic; }
230
256
  .cell.err { color: var(--error); }
231
257
  .cell.link { color: var(--link, #1a73e8); }
258
+ .cell .cf-icon { flex: none; margin-right: auto; padding-right: calc(4px * var(--z)); font-size: 0.95em; line-height: 1; }
259
+ .cell.a-left .cf-icon { margin-right: calc(4px * var(--z)); }
260
+ .cell.locked { background-image: repeating-linear-gradient(135deg, transparent 0 6px, color-mix(in srgb, var(--cell-fg) 6%, transparent) 6px 7px); }
232
261
  .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
262
  .cell .cb.on { background: var(--link, #1a73e8); border-color: var(--link, #1a73e8); color: #fff; }
234
263
  .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/assets.js ADDED
@@ -0,0 +1,138 @@
1
+ // Assets: images and Markdown notes that sit beside a workbook
2
+ // (sheets/<id>/assets/) or are shared by the whole workspace (assets/).
3
+ // Charts are drawn here from a range — the editor's renderer — so a person, an
4
+ // agent and `apply-notes` all get the same picture. Notes are context: agents
5
+ // read them before working on a workbook.
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { Workbook } from '@open-spreadsheet/engine';
9
+ import { ID, OpsError, parseRangeText, readWorkbook, workbookFile } from './ops.js';
10
+
11
+ export const SHARED = 'shared';
12
+ /** One file name, no folders: letters (any script), digits, space, _ . ( ) -, and a kind we serve. */
13
+ const NAME = /^[\p{L}\p{N}_][\p{L}\p{N}_ .()-]{0,118}\.(svg|png|jpe?g|gif|webp|md)$/iu;
14
+ export const IMAGE = /\.(svg|png|jpe?g|gif|webp)$/i;
15
+ export const MIME = { svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', md: 'text/markdown; charset=utf-8' };
16
+
17
+ // The editor's renderer: its source in this repo, the stripped copy once installed.
18
+ const charts = () => import(new URL(import.meta.url.includes('/node_modules/') ? './dist/charts.js' : './app/charts.ts', import.meta.url).href);
19
+
20
+ /** Where a scope's assets live: a workbook's folder, or the workspace's shared one. */
21
+ export function assetsDir(root, scope) {
22
+ if (scope === SHARED) return path.join(root, 'assets');
23
+ if (!ID.test(String(scope ?? '')) || !existsSync(workbookFile(root, scope))) throw new OpsError('not_found', `No workbook ${scope} (or use scope "${SHARED}")`);
24
+ return path.join(path.dirname(workbookFile(root, scope)), 'assets');
25
+ }
26
+
27
+ export function assetPath(root, scope, name) {
28
+ if (!NAME.test(String(name ?? '')) || name.includes('..')) {
29
+ throw new OpsError('bad_name', `"${name}" is not an asset name: one file name ending in .md, .svg, .png, .jpg, .gif or .webp`);
30
+ }
31
+ return path.join(assetsDir(root, scope), name);
32
+ }
33
+
34
+ const firstLine = (text) => (text.split('\n').find((l) => l.trim()) ?? '').replace(/^#+\s*/, '').slice(0, 120);
35
+
36
+ /** A scope's images and notes, newest first; a note carries its first line as a title. */
37
+ export function listAssets(root, scope) {
38
+ const dir = assetsDir(root, scope);
39
+ if (!existsSync(dir)) return [];
40
+ return readdirSync(dir)
41
+ .filter((n) => NAME.test(n))
42
+ .map((name) => {
43
+ const st = statSync(path.join(dir, name));
44
+ const kind = IMAGE.test(name) ? 'image' : 'note';
45
+ return { name, kind, size: st.size, updatedAt: st.mtime.toISOString(), ...(kind === 'note' ? { title: firstLine(readFileSync(path.join(dir, name), 'utf8')) } : {}) };
46
+ })
47
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
48
+ }
49
+
50
+ /** A note's text, or an image's bytes. */
51
+ export function readAsset(root, scope, name) {
52
+ const file = assetPath(root, scope, name);
53
+ if (!existsSync(file)) throw new OpsError('not_found', `No asset ${name} in ${scope}`);
54
+ return IMAGE.test(name) ? readFileSync(file) : readFileSync(file, 'utf8');
55
+ }
56
+
57
+ function writeAtomic(file, content) {
58
+ mkdirSync(path.dirname(file), { recursive: true });
59
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
60
+ writeFileSync(tmp, content);
61
+ renameSync(tmp, file);
62
+ }
63
+
64
+ /** The name itself when free, else name-2, name-3… before the extension. */
65
+ function freeName(root, scope, name) {
66
+ const dir = assetsDir(root, scope);
67
+ const dot = name.lastIndexOf('.');
68
+ const stem = name.slice(0, dot);
69
+ const ext = name.slice(dot);
70
+ let candidate = name;
71
+ for (let n = 2; existsSync(path.join(dir, candidate)); n++) candidate = `${stem}-${n}${ext}`;
72
+ return candidate;
73
+ }
74
+
75
+ export function writeNote(root, scope, name, text) {
76
+ if (!/\.md$/i.test(String(name ?? ''))) throw new OpsError('bad_name', 'A note is a .md file');
77
+ const file = assetPath(root, scope, name);
78
+ writeAtomic(file, String(text ?? ''));
79
+ return { scope, name };
80
+ }
81
+
82
+ /** Stores an image (an upload); a taken name gets a number rather than replacing the file. */
83
+ export function saveImage(root, scope, name, bytes) {
84
+ if (!IMAGE.test(String(name ?? ''))) throw new OpsError('bad_name', 'An image is a .svg, .png, .jpg, .gif or .webp file');
85
+ assetPath(root, scope, name);
86
+ const free = freeName(root, scope, name);
87
+ writeAtomic(assetPath(root, scope, free), bytes);
88
+ return { scope, name: free };
89
+ }
90
+
91
+ /** Moves an asset to the scope's .trash folder; nothing is erased. */
92
+ export function trashAsset(root, scope, name) {
93
+ const file = assetPath(root, scope, name);
94
+ if (!existsSync(file)) throw new OpsError('not_found', `No asset ${name} in ${scope}`);
95
+ const trash = path.join(path.dirname(file), '.trash');
96
+ mkdirSync(trash, { recursive: true });
97
+ const to = path.join(trash, `${Date.now()}-${name}`);
98
+ renameSync(file, to);
99
+ return { scope, name, trashedTo: path.relative(root, to) };
100
+ }
101
+
102
+ const slug = (text) =>
103
+ String(text)
104
+ .normalize('NFKC')
105
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
106
+ .replace(/^-+|-+$/g, '')
107
+ .slice(0, 60);
108
+
109
+ /**
110
+ * Draws a chart from a workbook range and saves it as an SVG in the workbook's
111
+ * assets (or the shared ones): the same picture the editor shows.
112
+ */
113
+ export async function renderChart(root, workbook, opts) {
114
+ const { data } = readWorkbook(root, workbook);
115
+ const sheet = opts.sheet ? data.sheets.find((s) => s.name.toLowerCase() === String(opts.sheet).toLowerCase()) : data.sheets[0];
116
+ if (!sheet) throw new OpsError('no_sheet', `No sheet "${opts.sheet}". Sheets: ${data.sheets.map((s) => s.name).join(', ')}`);
117
+ const type = opts.type ?? 'bar';
118
+ if (!['bar', 'line', 'pie'].includes(type)) throw new OpsError('bad_type', 'type is bar, line or pie');
119
+ const r = parseRangeText(opts.range);
120
+ if (!r) throw new OpsError('bad_range', `Not a range: ${opts.range}`);
121
+ if ((r.r1 - r.r0 + 1) * (r.c1 - r.c0 + 1) > 5000) throw new OpsError('too_big', 'Chart at most 5,000 cells; pass a smaller range.');
122
+ const wb = Workbook.fromJSON(data);
123
+ const cells = [];
124
+ for (let row = r.r0; row <= r.r1; row++) {
125
+ const line = [];
126
+ for (let col = r.c0; col <= r.c1; col++) line.push(wb.value(sheet.name, row, col));
127
+ cells.push(line);
128
+ }
129
+ const { chartData, chartFile } = await charts();
130
+ const spec = { id: 'asset', type, range: opts.range, title: opts.title ?? '', x: 0, y: 0, w: 720, h: 405 };
131
+ const svg = chartFile(spec, chartData(cells), Number(opts.width) || 720, Number(opts.height) || 405);
132
+ const scope = opts.scope ?? workbook;
133
+ const wanted = opts.name ? (/\.svg$/i.test(opts.name) ? opts.name : `${opts.name}.svg`) : `${slug(opts.title || `${sheet.name}-${opts.range}`) || 'chart'}.svg`;
134
+ assetPath(root, scope, wanted);
135
+ const name = opts.replace ? wanted : freeName(root, scope, wanted);
136
+ writeAtomic(assetPath(root, scope, name), svg);
137
+ return { scope, name, sheet: sheet.name, range: opts.range, type, bytes: Buffer.byteLength(svg) };
138
+ }