@open-artifact/sheets-core 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-artifact/sheets-core",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "The Sheets type's model, free of DOM and React: the workbook engine's requests and answers, the page and server protocol, A1 addresses, the agent's reads and edits worked out into engine operations, charts and widgets, version history, xlsx export and the view context.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,8 +28,8 @@
28
28
  "NOTICE"
29
29
  ],
30
30
  "dependencies": {
31
- "@open-artifact/runtime": "0.10.0",
32
- "@open-artifact/wasm-sheets": "0.10.0",
31
+ "@open-artifact/runtime": "0.12.0",
32
+ "@open-artifact/wasm-sheets": "0.12.0",
33
33
  "acorn": "^8.19.0",
34
34
  "acorn-jsx": "^5.3.2"
35
35
  },
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Cell links and walkthroughs. A cell link is the part of the page's address after `#` that names a tab and some of
3
+ * its cells: `sheet-<sheetId>`, then each range after a `~`, its corners joined by `-` (`sheet-sht_ab.0~A2-D2~B1`).
4
+ * Opening it shows that tab, brings the first range into view and marks every range. A walkthrough is a list of stops,
5
+ * each a cell link and a short text, that the page steps the person through.
6
+ *
7
+ * A link's cells are places on the tab, as the agent reads them: rows and columns as they lie now, which is also how
8
+ * they lie while the person sorts the tab for themself alone.
9
+ */
10
+ import type { SheetWalkthrough } from '../protocol.ts';
11
+ import type { SheetView } from './workbook.ts';
12
+ /** A cell link read: the tab's id and its ranges, as A1 ranges (`A2:D2`, `B1`). */
13
+ export interface CellLink {
14
+ sheetId: string;
15
+ ranges: string[];
16
+ }
17
+ export declare const MAX_LINK_LENGTH = 128;
18
+ export declare const MAX_GUIDE_STOPS = 30;
19
+ export declare const MAX_STOP_TEXT = 600;
20
+ /** The fragment that names a tab in a cell link. */
21
+ export declare const linkFragmentOf: (sheetId: string) => string;
22
+ /** A cell link read, or null when the text is none. A link that names a tab and no cells is read with no ranges. */
23
+ export declare function parseCellLink(text: unknown): CellLink | null;
24
+ /**
25
+ * A walkthrough as showGuide gives it, checked against the workbook: each stop's tab must be one of `sheets` and its
26
+ * ranges must lie within it. A walkthrough that is not well made is refused as unreadableRead.
27
+ */
28
+ export declare function checkWalkthrough(guide: unknown, sheets: SheetView[]): SheetWalkthrough;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Cell links and walkthroughs. A cell link is the part of the page's address after `#` that names a tab and some of
3
+ * its cells: `sheet-<sheetId>`, then each range after a `~`, its corners joined by `-` (`sheet-sht_ab.0~A2-D2~B1`).
4
+ * Opening it shows that tab, brings the first range into view and marks every range. A walkthrough is a list of stops,
5
+ * each a cell link and a short text, that the page steps the person through.
6
+ *
7
+ * A link's cells are places on the tab, as the agent reads them: rows and columns as they lie now, which is also how
8
+ * they lie while the person sorts the tab for themself alone.
9
+ */
10
+ import { AgentError } from "./errors.js";
11
+ export const MAX_LINK_LENGTH = 128;
12
+ export const MAX_GUIDE_STOPS = 30;
13
+ export const MAX_STOP_TEXT = 600;
14
+ const LINK_PREFIX = 'sheet-';
15
+ const SHEET_ID = /^[A-Za-z0-9._-]+$/;
16
+ const CELL = '[A-Za-z]{1,3}[1-9][0-9]{0,6}';
17
+ const LINK_RANGE = new RegExp(`^(${CELL})(?:-(${CELL}))?$`);
18
+ /** The fragment that names a tab in a cell link. */
19
+ export const linkFragmentOf = (sheetId) => `${LINK_PREFIX}${sheetId}`;
20
+ /** A cell link read, or null when the text is none. A link that names a tab and no cells is read with no ranges. */
21
+ export function parseCellLink(text) {
22
+ if (typeof text !== 'string')
23
+ return null;
24
+ const fragment = text.startsWith('#') ? text.slice(1) : text;
25
+ if (fragment.length > MAX_LINK_LENGTH)
26
+ return null;
27
+ const [tab = '', ...parts] = fragment.split('~');
28
+ if (!tab.startsWith(LINK_PREFIX))
29
+ return null;
30
+ const sheetId = tab.slice(LINK_PREFIX.length);
31
+ if (!SHEET_ID.test(sheetId))
32
+ return null;
33
+ const ranges = [];
34
+ for (const part of parts) {
35
+ const corners = LINK_RANGE.exec(part);
36
+ if (!corners)
37
+ return null;
38
+ ranges.push(corners[2] ? `${corners[1]}:${corners[2]}`.toUpperCase() : corners[1].toUpperCase());
39
+ }
40
+ return { sheetId, ranges };
41
+ }
42
+ const GUIDE_SHAPE = `guide is {"stops": [{"at": "#sheet-<id>~A2-D2", "say": "…"}]}: from 1 to ${MAX_GUIDE_STOPS} stops, each a cell link with at least one range and a text of up to ${MAX_STOP_TEXT} characters.`;
43
+ /**
44
+ * A walkthrough as showGuide gives it, checked against the workbook: each stop's tab must be one of `sheets` and its
45
+ * ranges must lie within it. A walkthrough that is not well made is refused as unreadableRead.
46
+ */
47
+ export function checkWalkthrough(guide, sheets) {
48
+ if (typeof guide !== 'object' || guide === null || Array.isArray(guide))
49
+ throw new AgentError('unreadableRead', GUIDE_SHAPE);
50
+ const { stops } = guide;
51
+ const keys = Object.keys(guide).filter((key) => key !== 'stops');
52
+ if (keys.length)
53
+ throw new AgentError('unreadableRead', `guide takes no "${keys[0]}": ${GUIDE_SHAPE}`, { key: keys[0] });
54
+ if (!Array.isArray(stops) || stops.length < 1 || stops.length > MAX_GUIDE_STOPS)
55
+ throw new AgentError('unreadableRead', GUIDE_SHAPE);
56
+ return {
57
+ stops: stops.map((stop, i) => {
58
+ if (typeof stop !== 'object' || stop === null)
59
+ throw new AgentError('unreadableRead', `stops[${i}] is {"at", "say"}.`);
60
+ const { at, say } = stop;
61
+ const extra = Object.keys(stop).find((key) => key !== 'at' && key !== 'say');
62
+ if (extra)
63
+ throw new AgentError('unreadableRead', `stops[${i}] takes no "${extra}": its keys are at, say.`, { key: extra });
64
+ const link = parseCellLink(at);
65
+ if (typeof at !== 'string' || !link || link.ranges.length === 0) {
66
+ throw new AgentError('unreadableRead', `stops[${i}].at is a cell link of at most ${MAX_LINK_LENGTH} characters with at least one range: "#sheet-<id>~A2-D2~B1", the id being the tab's linkFragment from readSheets.`);
67
+ }
68
+ if (typeof say !== 'string' || say.trim() === '' || say.length > MAX_STOP_TEXT) {
69
+ throw new AgentError('unreadableRead', `stops[${i}].say is some plain text, of at most ${MAX_STOP_TEXT} characters.`);
70
+ }
71
+ const tab = sheets.find((s) => s.sheetId === link.sheetId);
72
+ if (!tab)
73
+ throw new AgentError('unknownSheetName', `stops[${i}].at names no tab of this Sheet: readSheets gives each tab's linkFragment.`, { linkFragment: linkFragmentOf(link.sheetId) });
74
+ for (const range of link.ranges)
75
+ tab.range(range, `stops[${i}].at`);
76
+ return { at, say };
77
+ }),
78
+ };
79
+ }
@@ -13,6 +13,11 @@
13
13
  * deletes it), and the engine's load checks them. They are logged in the format version the engine records them in
14
14
  * itself: 30, or 33 when a placement has an offset (what the page's own moves record).
15
15
  *
16
+ * An interactive panel is a view too, with one element of kind "interactive" and no placement: it fills a tab of its
17
+ * own, which names it in its settings (`interactive`). Its element lists the inputs the panel's controls may write
18
+ * (`writes`), each with the values its cells held when the panel was made, which a reset brings back. addInteractive
19
+ * writes it (setViews, then setSheetSettings), logged in format version 47; the agent's chart edits leave it alone.
20
+ *
16
21
  * An input keeps the ids of the corners it was given. A read gives where it lies now: as it lies between its corners,
17
22
  * or, when a corner's row or column was deleted, between where the corners were, worked out in a session that applied
18
23
  * every edit (a load leaves deleted cells out) and then brought those rows and columns back.
@@ -29,12 +34,21 @@ export interface WidgetLookup {
29
34
  /** The format version the engine records views and placements in; with an offset, the newer one. */
30
35
  export declare const CHART_FORMAT_VERSION = 30;
31
36
  export declare const OFFSET_FORMAT_VERSION = 33;
37
+ /** The format version the engine records an interactive panel's view and its tab's setting in. */
38
+ export declare const INTERACTIVE_FORMAT_VERSION = 47;
39
+ /** The most views a workbook holds: charts and interactive panels together. */
32
40
  export declare const MAX_CHARTS = 200;
41
+ /** The most cells one interactive panel may write, over all its writable inputs. */
42
+ export declare const MAX_WRITABLE_CELLS = 1000;
43
+ /** The data source the page fills for a panel's controls: no input may take its name. */
44
+ export declare const INTERACTIVE_SOURCE = "interactive";
33
45
  type ViewEntry = {
34
46
  viewId: string;
35
47
  view: ChartView;
36
48
  };
37
49
  type PlacementEntry = NonNullable<SheetContents['placements']>[number];
50
+ type ViewElement = ChartView['elements'][number];
51
+ type ViewInput = ViewElement['inputs'][number];
38
52
  /** The workbook with some deleted rows and columns brought back (null when that can't be done): see the header. */
39
53
  export type Undeleted = (ops: EngineMessage[]) => WorkbookContents | null;
40
54
  /** Reads charts: each view's live ranges, worked out once per read. */
@@ -45,6 +59,8 @@ export declare class ChartReader {
45
59
  private readonly brought;
46
60
  constructor(workbook: WorkbookContents, sheets: SheetView[], undeleted: Undeleted);
47
61
  views(): ViewEntry[];
62
+ /** The interactive panel a tab shows, as readInteractive gives it, or null when the tab is not one. */
63
+ interactiveOf(sheet: SheetView): EngineMessage | null;
48
64
  /** Each chart that lies over a sheet, in the order of its placements: {chartId, chart}. */
49
65
  chartsOf(view: SheetView): EngineMessage[];
50
66
  /** Where the view with this id lies: its placement and sheet, or null. */
@@ -54,7 +70,7 @@ export declare class ChartReader {
54
70
  } | null;
55
71
  chart(shown: ChartView, sheet: SheetView, entry: PlacementEntry): EngineMessage;
56
72
  /** Where an input lies now, as {sheet, range}; null when all its cells are deleted. */
57
- cellsOf(range: ChartView['elements'][number]['inputs'][number]['range']): {
73
+ cellsOf(range: ViewInput['range']): {
58
74
  sheet: string;
59
75
  range: string;
60
76
  } | null;
@@ -71,6 +87,6 @@ export interface ChartHost {
71
87
  undeleted: Undeleted;
72
88
  newIdCode(): string;
73
89
  }
74
- /** addChart, setChart and deleteChart (applyEdits calls them for its chart edits). */
90
+ /** addChart, setChart, deleteChart and addInteractive (applyEdits calls them for its chart edits). */
75
91
  export declare function chartEdits(host: ChartHost): ChartEdits;
76
92
  export {};
@@ -13,6 +13,11 @@
13
13
  * deletes it), and the engine's load checks them. They are logged in the format version the engine records them in
14
14
  * itself: 30, or 33 when a placement has an offset (what the page's own moves record).
15
15
  *
16
+ * An interactive panel is a view too, with one element of kind "interactive" and no placement: it fills a tab of its
17
+ * own, which names it in its settings (`interactive`). Its element lists the inputs the panel's controls may write
18
+ * (`writes`), each with the values its cells held when the panel was made, which a reset brings back. addInteractive
19
+ * writes it (setViews, then setSheetSettings), logged in format version 47; the agent's chart edits leave it alone.
20
+ *
16
21
  * An input keeps the ids of the corners it was given. A read gives where it lies now: as it lies between its corners,
17
22
  * or, when a corner's row or column was deleted, between where the corners were, worked out in a session that applied
18
23
  * every edit (a load leaves deleted cells out) and then brought those rows and columns back.
@@ -24,7 +29,17 @@ import { checkKeys, pickSheet, SheetView } from "./workbook.js";
24
29
  /** The format version the engine records views and placements in; with an offset, the newer one. */
25
30
  export const CHART_FORMAT_VERSION = 30;
26
31
  export const OFFSET_FORMAT_VERSION = 33;
32
+ /** The format version the engine records an interactive panel's view and its tab's setting in. */
33
+ export const INTERACTIVE_FORMAT_VERSION = 47;
34
+ /** The most views a workbook holds: charts and interactive panels together. */
27
35
  export const MAX_CHARTS = 200;
36
+ /** The most cells one interactive panel may write, over all its writable inputs. */
37
+ export const MAX_WRITABLE_CELLS = 1000;
38
+ /** The data source the page fills for a panel's controls: no input may take its name. */
39
+ export const INTERACTIVE_SOURCE = 'interactive';
40
+ const INTERACTIVE_KEYS = ['sheet', 'name', 'caption', 'widget', 'inputs', 'writable'];
41
+ /** What a writable cell may hold besides nothing: a value typed in, not a formula, a date or a person. */
42
+ const WRITABLE_KINDS = new Set(['number', 'text', 'boolean']);
28
43
  const MAX_INPUTS = 32;
29
44
  /** The engine's limits (describeSharedCode): a placement's sides and its offset from its cell. */
30
45
  const MIN_SIDE = 40;
@@ -59,6 +74,22 @@ export class ChartReader {
59
74
  views() {
60
75
  return this.workbook.views ?? [];
61
76
  }
77
+ /** The interactive panel a tab shows, as readInteractive gives it, or null when the tab is not one. */
78
+ interactiveOf(sheet) {
79
+ const viewId = sheet.contents.interactive;
80
+ const entry = viewId ? this.views().find((v) => v.viewId === viewId) : undefined;
81
+ const element = entry?.view.elements.find((e) => e.kind === 'interactive');
82
+ if (!entry || !element)
83
+ return null;
84
+ return {
85
+ interactiveId: entry.viewId,
86
+ name: entry.view.name,
87
+ caption: element.embed.caption,
88
+ widget: widgetOf(element.embed.ref),
89
+ inputs: element.inputs.map((input) => ({ name: input.name, cells: this.cellsOf(input.range) })),
90
+ writable: (element.writes ?? []).map((w) => w.input),
91
+ };
92
+ }
62
93
  /** Each chart that lies over a sheet, in the order of its placements: {chartId, chart}. */
63
94
  chartsOf(view) {
64
95
  const views = new Map(this.views().map((v) => [v.viewId, v.view]));
@@ -138,15 +169,15 @@ export class ChartReader {
138
169
  return this.brought.get(key) ?? null;
139
170
  }
140
171
  }
141
- /** addChart, setChart and deleteChart (applyEdits calls them for its chart edits). */
172
+ /** addChart, setChart, deleteChart and addInteractive (applyEdits calls them for its chart edits). */
142
173
  export function chartEdits(host) {
143
174
  const reader = (sheets) => new ChartReader(host.context.read(), sheets, host.undeleted);
144
175
  const versionOf = (placement) => (placement?.offsetFromAnchorCell ? OFFSET_FORMAT_VERSION : CHART_FORMAT_VERSION);
145
- /** The chart as it is given, checked, in the engine's terms; `now` is the chart it replaces (setChart). */
146
- function made(chart, sheets, now) {
147
- if (!isObject(chart))
148
- throw new AgentError('unreadableEdit', `chart is {${CHART_KEYS.join(', ')}, offsetFromAnchorCell?}.`);
149
- checkKeys({ ...chart, kind: 'chart' }, CHART_KEYS, ['offsetFromAnchorCell']);
176
+ /**
177
+ * What a chart and an interactive panel both give: the name and caption, the widget and the inputs, checked, in the
178
+ * engine's terms. `now` is the view they replace (setChart); its inputs given as the read gave them keep their corners.
179
+ */
180
+ function parts(chart, sheets, now) {
150
181
  const { name, caption } = chart;
151
182
  if (typeof name !== 'string' || name.trim() === '')
152
183
  throw new AgentError('viewHasNoName', 'name is what a screen reader calls the chart: some words, not "".');
@@ -195,6 +226,14 @@ export function chartEdits(host) {
195
226
  const b = of.range(input.cells.range, `inputs[${i}].cells.range`);
196
227
  return { name: inputName, range: { sheetId: of.sheetId, topLeft: { r: of.rowIds[b.top], c: of.columnIds[b.left] }, bottomRight: { r: of.rowIds[b.bottom], c: of.columnIds[b.right] } } };
197
228
  });
229
+ return { name, caption, widget, inputs };
230
+ }
231
+ /** The chart as it is given, checked, in the engine's terms; `now` is the chart it replaces (setChart). */
232
+ function made(chart, sheets, now) {
233
+ if (!isObject(chart))
234
+ throw new AgentError('unreadableEdit', `chart is {${CHART_KEYS.join(', ')}, offsetFromAnchorCell?}.`);
235
+ checkKeys({ ...chart, kind: 'chart' }, CHART_KEYS, ['offsetFromAnchorCell']);
236
+ const { name, caption, widget, inputs } = parts(chart, sheets, now);
198
237
  const sheet = pickSheet(sheets, chart.sheet);
199
238
  const corner = sheet.range(chart.topLeft, 'topLeft');
200
239
  if (corner.top !== corner.bottom || corner.left !== corner.right)
@@ -241,7 +280,77 @@ export function chartEdits(host) {
241
280
  const at = read.placementOf(view.viewId);
242
281
  return { ...view, at, reader: read };
243
282
  }
283
+ /**
284
+ * The cells a panel may write, input by input, each with what it holds now (the values a reset brings back). Only a
285
+ * blank cell or a plain number, text or boolean typed in is writable.
286
+ */
287
+ function writesOf(writable, inputs, sheets) {
288
+ if (!Array.isArray(writable) || new Set(writable).size !== writable.length) {
289
+ throw new AgentError('unreadableEdit', 'writable is a list of input names, each named once: [] when the controls only read.');
290
+ }
291
+ const byName = new Map(inputs.map((input) => [input.name, input]));
292
+ const filledOf = new Map();
293
+ let total = 0;
294
+ return writable.map((given) => {
295
+ const input = typeof given === 'string' ? byName.get(given) : undefined;
296
+ if (!input)
297
+ throw new AgentError('unknownInput', `writable names ${JSON.stringify(given)}, which is none of this panel's inputs.`);
298
+ const { sheetId, topLeft, bottomRight } = input.range;
299
+ const source = sheets.find((s) => s.sheetId === sheetId);
300
+ const [top, bottom] = [source.rowIndex(topLeft.r), source.rowIndex(bottomRight.r)];
301
+ const [left, right] = [source.columnIndex(topLeft.c), source.columnIndex(bottomRight.c)];
302
+ total += (bottom - top + 1) * (right - left + 1);
303
+ if (total > MAX_WRITABLE_CELLS)
304
+ throw new AgentError('tooManyCells', `The writable inputs of one panel cover at most ${MAX_WRITABLE_CELLS.toLocaleString('en-US')} cells together.`);
305
+ let filled = filledOf.get(sheetId);
306
+ if (!filled) {
307
+ filled = new Map(source.filled().map((f) => [`${f.row},${f.column}`, f]));
308
+ filledOf.set(sheetId, filled);
309
+ }
310
+ const saved = [];
311
+ for (let row = top; row <= bottom; row++) {
312
+ for (let column = left; column <= right; column++) {
313
+ const f = filled.get(`${row},${column}`);
314
+ const held = f?.cell.input;
315
+ if (f && (f.spilled || !isObject(held) || !WRITABLE_KINDS.has(String(held.kind)))) {
316
+ throw new AgentError('cannotWriteInteractiveCell', `${source.name}!${a1(row, column)} holds a formula, a spilled value or a value of another kind: a writable cell is blank or holds a plain number, text or boolean.`, { cell: `${source.name}!${a1(row, column)}` });
317
+ }
318
+ const value = f && isObject(held) ? { kind: String(held.kind), value: held.value } : null;
319
+ saved.push({ r: source.rowIds[row], c: source.columnIds[column], value });
320
+ }
321
+ }
322
+ return { input: input.name, saved };
323
+ });
324
+ }
244
325
  return {
326
+ addInteractive(panel, sheets) {
327
+ if (!isObject(panel))
328
+ throw new AgentError('unreadableEdit', `interactive is {${INTERACTIVE_KEYS.join(', ')}}.`);
329
+ checkKeys({ ...panel, kind: 'interactive' }, INTERACTIVE_KEYS);
330
+ const tab = pickSheet(sheets, panel.sheet);
331
+ if (tab.contents.interactive || tab.filledBlock() || tab.contents.placements?.length) {
332
+ throw new AgentError('sheetNotBlank', `Sheet "${tab.name}" already holds cells, charts or a panel: an interactive panel takes a blank tab of its own (addSheet one first).`);
333
+ }
334
+ if (reader(sheets).views().length >= MAX_CHARTS)
335
+ throw new AgentError('tooManyViews', `A workbook holds ${MAX_CHARTS} views, charts and interactive panels together.`);
336
+ const { name, caption, widget, inputs } = parts(panel, sheets, null);
337
+ if (inputs.some((input) => input.name === INTERACTIVE_SOURCE)) {
338
+ throw new AgentError('inputNameNotAllowed', `"${INTERACTIVE_SOURCE}" is the name of the source the page gives the panel's controls: name the input otherwise.`);
339
+ }
340
+ for (const input of inputs) {
341
+ const source = sheets.find((s) => s.sheetId === input.range.sheetId);
342
+ if (input.range.sheetId === tab.sheetId || source?.contents.interactive) {
343
+ throw new AgentError('sheetIsAnInteractive', `Input "${input.name}" lies on an interactive panel's tab: a panel's inputs are cells of the tabs that hold the data.`);
344
+ }
345
+ }
346
+ const writes = writesOf(panel.writable, inputs, sheets);
347
+ const viewId = `viw_${host.newIdCode()}.0`;
348
+ const elementId = `vel_${host.newIdCode()}.0`;
349
+ host.apply([
350
+ { kind: 'setViews', views: [{ viewId, view: { name, elements: [{ kind: 'interactive', elementId, embed: { ref: `node/${widget}`, caption }, inputs, writes }] } }] },
351
+ { kind: 'setSheetSettings', sheets: [{ sheetId: tab.sheetId, settings: { interactive: viewId } }] },
352
+ ], INTERACTIVE_FORMAT_VERSION);
353
+ },
245
354
  add(chart, sheets) {
246
355
  const charts = reader(sheets).views().length;
247
356
  if (charts >= MAX_CHARTS)
@@ -257,6 +366,9 @@ export function chartEdits(host) {
257
366
  },
258
367
  set(chartId, chart, sheets) {
259
368
  const found = find(chartId, sheets);
369
+ if (found.view.elements.some((e) => e.kind === 'interactive')) {
370
+ throw new AgentError('unknownChart', `${found.viewId} is an interactive panel, not a chart: setChart leaves it alone.`);
371
+ }
260
372
  if (!found.at)
261
373
  throw new AgentError('unknownChart', `Chart ${String(chartId)} lies over no sheet.`);
262
374
  const { sheet, entry } = found.at;
@@ -280,6 +392,9 @@ export function chartEdits(host) {
280
392
  },
281
393
  remove(chartId, sheets) {
282
394
  const found = find(chartId, sheets);
395
+ if (found.view.elements.some((e) => e.kind === 'interactive')) {
396
+ throw new AgentError('unknownChart', `${found.viewId} is an interactive panel, not a chart: deleteChart leaves it, and the person removes it in the page.`);
397
+ }
283
398
  const ops = [];
284
399
  if (found.at)
285
400
  ops.push({ kind: 'setPlacements', sheetId: found.at.sheet.sheetId, placements: [{ placementId: found.at.entry.placementId, placement: null }] });
@@ -32,6 +32,8 @@ export interface ChartEdits {
32
32
  add(chart: unknown, sheets: SheetView[]): void;
33
33
  set(chartId: unknown, chart: unknown, sheets: SheetView[]): boolean;
34
34
  remove(chartId: unknown, sheets: SheetView[]): void;
35
+ /** An interactive panel on a blank tab of its own (charts.ts). */
36
+ addInteractive(panel: unknown, sheets: SheetView[]): void;
35
37
  }
36
38
  export declare const EDIT_KINDS: string[];
37
39
  /**
@@ -17,7 +17,7 @@ export const EDIT_KINDS = [
17
17
  'writeCells', 'addSheet', 'renameSheet', 'restoreSheet', 'moveSheets', 'formatCells', 'groupRows', 'groupColumns', 'ungroupRows', 'ungroupColumns',
18
18
  'mergeCells', 'unmergeCells', 'setBorders', 'setColumnWidths', 'fitColumns', 'setRowHeights', 'insertRows', 'insertColumns', 'moveRows', 'moveColumns',
19
19
  'sortRows', 'sortCells', 'deleteRows', 'deleteColumns', 'deleteSheet', 'setSheetSettings', 'makeDropdown', 'setDropdownOptions', 'setCellTable',
20
- 'replaceConditionalFormats', 'addChart', 'setChart', 'deleteChart', 'setTimeZone', 'setLocale',
20
+ 'replaceConditionalFormats', 'addChart', 'setChart', 'deleteChart', 'addInteractive', 'setTimeZone', 'setLocale',
21
21
  ];
22
22
  /**
23
23
  * The edits of an applyEdits, made in order in `context`. A refusal throws an AgentError whose `extra` has the edit's
@@ -323,6 +323,12 @@ function applyEdit(edit, context) {
323
323
  context.charts.remove(edit.chartId, sheets);
324
324
  return true;
325
325
  }
326
+ case 'addInteractive':
327
+ checkKeys(edit, ['interactive']);
328
+ if (!context.charts)
329
+ throw new AgentError('interactiveNotAvailable', 'Interactive panels are made only by an update of the Sheet itself.');
330
+ context.charts.addInteractive(edit.interactive, sheets);
331
+ return true;
326
332
  case 'setTimeZone': {
327
333
  checkKeys(edit, ['timeZone']);
328
334
  const zone = edit.timeZone;
@@ -4,6 +4,7 @@
4
4
  * CSV text.
5
5
  */
6
6
  export * from './addresses.ts';
7
+ export * from './cell-links.ts';
7
8
  export * from './cells.ts';
8
9
  export * from './chart-code.ts';
9
10
  export * from './chart-descriptions.ts';
@@ -4,6 +4,7 @@
4
4
  * CSV text.
5
5
  */
6
6
  export * from "./addresses.js";
7
+ export * from "./cell-links.js";
7
8
  export * from "./cells.js";
8
9
  export * from "./chart-code.js";
9
10
  export * from "./chart-descriptions.js";
@@ -1,6 +1,7 @@
1
1
  /**
2
- * The agent's reads: readSheets, readCells, readCellFormats, readConditionalFormats and readCharts, answered from the
3
- * workbook at a revision, by the same names and keys as the agent's skill describes.
2
+ * The agent's reads: readSheets, readCells, readCellFormats, readConditionalFormats, readCharts and readInteractive,
3
+ * answered from the workbook at a revision, by the same names and keys as the agent's skill describes. showGuide goes
4
+ * through the same command but is no read of the workbook: the host answers it (cell-links.ts checks it).
4
5
  */
5
6
  import { type Block } from './addresses.ts';
6
7
  import { type EngineMessage } from './engine.ts';
@@ -18,7 +19,12 @@ export interface ReadContext {
18
19
  calculationTookTooLong?: boolean;
19
20
  timeZone: string | null;
20
21
  charts?: (view: SheetView, sheets: SheetView[]) => EngineMessage[];
22
+ /** The interactive panel a tab shows, or null (charts.ts, ChartReader.interactiveOf). */
23
+ interactive?: (view: SheetView, sheets: SheetView[]) => EngineMessage | null;
21
24
  }
25
+ export declare const READ_KINDS: string[];
26
+ /** What the read command takes besides the reads: a walkthrough the host shows the person. */
27
+ export declare const GUIDE_KIND = "showGuide";
22
28
  export declare function readWorkbook(payload: unknown, context: ReadContext): EngineMessage;
23
29
  /** A sheet's cell formats as blocks, later entries over earlier ones. */
24
30
  export declare function formatBlocks(view: SheetView): {
@@ -1,21 +1,26 @@
1
1
  /**
2
- * The agent's reads: readSheets, readCells, readCellFormats, readConditionalFormats and readCharts, answered from the
3
- * workbook at a revision, by the same names and keys as the agent's skill describes.
2
+ * The agent's reads: readSheets, readCells, readCellFormats, readConditionalFormats, readCharts and readInteractive,
3
+ * answered from the workbook at a revision, by the same names and keys as the agent's skill describes. showGuide goes
4
+ * through the same command but is no read of the workbook: the host answers it (cell-links.ts checks it).
4
5
  */
5
6
  import { a1, blockA1, columnLetters, columnsText, overlap, rowsText } from "./addresses.js";
6
7
  import { encodeCell, shownText, usFormulaText } from "./cells.js";
7
8
  import { isObject } from "./engine.js";
8
9
  import { AgentError } from "./errors.js";
9
10
  import { sha256Hex } from "./sha256.js";
11
+ import { linkFragmentOf } from "./cell-links.js";
10
12
  import { checkKeys, expand, pickSheet, sheetsOf } from "./workbook.js";
11
13
  /** The most cells one readCells answers. */
12
14
  export const MAX_READ_CELLS = 10_000;
13
15
  /** About the most JSON one read answers. */
14
16
  export const MAX_READ_BYTES = 190_000;
15
- const READ_KINDS = ['readSheets', 'readCells', 'readCellFormats', 'readConditionalFormats', 'readCharts'];
17
+ export const READ_KINDS = ['readSheets', 'readCells', 'readCellFormats', 'readConditionalFormats', 'readCharts', 'readInteractive'];
18
+ /** What the read command takes besides the reads: a walkthrough the host shows the person. */
19
+ export const GUIDE_KIND = 'showGuide';
20
+ const KINDS_TEXT = [...READ_KINDS, GUIDE_KIND].join(', ');
16
21
  export function readWorkbook(payload, context) {
17
22
  if (!isObject(payload) || typeof payload.kind !== 'string')
18
- throw new AgentError('unknownReadKind', `A read's payload is {"kind": …}: ${READ_KINDS.join(', ')}.`);
23
+ throw new AgentError('unknownReadKind', `A read's payload is {"kind": …}: ${KINDS_TEXT}.`);
19
24
  const sheets = sheetsOf(context.workbook);
20
25
  const revision = context.workbook.revision;
21
26
  const keys = (required) => {
@@ -52,15 +57,22 @@ export function readWorkbook(payload, context) {
52
57
  const view = pickSheet(sheets, payload.sheet);
53
58
  return { revision, sheet: view.name, charts: context.charts?.(view, sheets) ?? [] };
54
59
  }
60
+ case 'readInteractive': {
61
+ keys(['sheet']);
62
+ const view = pickSheet(sheets, payload.sheet);
63
+ return { revision, sheet: view.name, interactive: context.interactive?.(view, sheets) ?? null };
64
+ }
55
65
  default:
56
- throw new AgentError('unknownReadKind', `"${payload.kind}" is not a read: ${READ_KINDS.join(', ')}.`);
66
+ throw new AgentError('unknownReadKind', `"${payload.kind}" is not a read: ${KINDS_TEXT}.`);
57
67
  }
58
68
  }
59
69
  function readSheets(context, sheets) {
60
70
  const out = sheets.map((view) => {
61
71
  const c = view.contents;
62
72
  const filled = view.filledBlock();
63
- const sheet = { name: view.name, rowCount: view.rowIds.length, columnCount: view.columnIds.length };
73
+ const sheet = { name: view.name, linkFragment: linkFragmentOf(view.sheetId), rowCount: view.rowIds.length, columnCount: view.columnIds.length };
74
+ if (c.interactive)
75
+ sheet.interactiveId = c.interactive;
64
76
  if (filled)
65
77
  sheet.filledRange = blockA1(filled);
66
78
  const frozenRow = c.lastFrozenRow ? view.rowIndex(c.lastFrozenRow) : undefined;
@@ -89,6 +89,8 @@ export interface SheetContents {
89
89
  placement: Placement;
90
90
  liveTopLeft?: CellIds | null;
91
91
  }[];
92
+ /** The view this sheet shows as an interactive panel (charts.ts), when the whole tab is one. */
93
+ interactive?: string | null;
92
94
  }
93
95
  export interface CellIds {
94
96
  r: string;
@@ -107,7 +109,20 @@ export interface Placement {
107
109
  widthInPixels: number;
108
110
  heightInPixels: number;
109
111
  }
110
- /** A view (a chart): its name and its one element, the widget it draws and the cells each input stands for. */
112
+ /** A cell an interactive panel may write, with the value it held when the panel was made (null: blank). */
113
+ export interface WritableCell {
114
+ r: string;
115
+ c: string;
116
+ value: {
117
+ kind: string;
118
+ value: unknown;
119
+ } | null;
120
+ }
121
+ /**
122
+ * A view (a chart, or an interactive panel): its name and its one element, the widget it draws and the cells each
123
+ * input stands for. A panel's element (kind "interactive") also lists the inputs its controls may write, each with the
124
+ * values its cells go back to on a reset.
125
+ */
111
126
  export interface ChartView {
112
127
  name: string;
113
128
  elements: {
@@ -125,6 +140,10 @@ export interface ChartView {
125
140
  bottomRight: CellIds;
126
141
  };
127
142
  }[];
143
+ writes?: {
144
+ input: string;
145
+ saved: WritableCell[];
146
+ }[];
128
147
  }[];
129
148
  }
130
149
  export interface CellTable {
@@ -3,7 +3,8 @@
3
3
  * parsed, typed by the request's `kind`. Nothing here depends on where the
4
4
  * engine runs.
5
5
  */
6
- import type { EngineSession, SheetsEngine } from '@open-artifact/wasm-sheets';
6
+ import type { EngineSession, PackedCellBlock, SheetsEngine } from '@open-artifact/wasm-sheets';
7
+ import type { PackedReadRequest } from './packed.ts';
7
8
  import type { Refused } from './refusals.ts';
8
9
  import type { SessionKind, SessionKinds, SessionRequest } from './sync.ts';
9
10
  import type { FunctionDescriptions, UtilityKind, UtilityKinds, UtilityRequest } from './utility.ts';
@@ -17,6 +18,8 @@ export declare class EngineClient {
17
18
  constructor(session: EngineSession);
18
19
  /** A request about the workbook, and its answer. */
19
20
  request<R extends SessionRequest>(request: R): AnswerOf<R>;
21
+ /** A packed read, and its answer; the answer's blocks go to `take`, in their order, before it returns. */
22
+ requestWithCells<R extends PackedReadRequest>(request: R, take: (block: PackedCellBlock) => void): AnswerOf<R>;
20
23
  /** Frees the workbook; the client cannot be used afterwards. */
21
24
  free(): void;
22
25
  }
@@ -13,6 +13,10 @@ export class EngineClient {
13
13
  request(request) {
14
14
  return JSON.parse(this.session.answerJson(JSON.stringify(request)));
15
15
  }
16
+ /** A packed read, and its answer; the answer's blocks go to `take`, in their order, before it returns. */
17
+ requestWithCells(request, take) {
18
+ return JSON.parse(this.session.answerWithCells(JSON.stringify(request), take));
19
+ }
16
20
  /** Frees the workbook; the client cannot be used afterwards. */
17
21
  free() {
18
22
  this.session.free();