@kivacore/ui-pro-sheets 0.0.0-stage → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,380 @@
1
- # Temporary Holding Version
1
+ # @kivacore/ui-pro-sheets
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Native Kiva spreadsheet for React 19: a canvas grid, an Excel-compatible
4
+ formula engine and a complete file layer, in one package with no runtime
5
+ dependency on UniverJS.
6
+
7
+ The package has three layers:
8
+
9
+ - **Core** (`src/core`): the document model and file layer, forked from
10
+ [hucre](https://github.com/productdevbook/hucre) (MIT) and vendored into
11
+ this package. It reads and writes XLSX, XLS, XLSB, ODS, CSV, JSON, NDJSON,
12
+ XML, HTML and Markdown, models styles, merges, validations, conditional
13
+ rules, tables, images, sparklines, charts, pivots, protection and outlines,
14
+ formats numbers with Excel patterns, and provides row/column operations that
15
+ keep formulas, merges and rules consistent. See `src/core/README.md` for the
16
+ fork notes.
17
+ - **Engine** (`src/engine`): the editable `Workbook`/`Worksheet` facades over
18
+ the core model, undo/redo, the formula engine (tokenizer, parser, evaluator,
19
+ dependency graph, spills) with ~370 function bodies from
20
+ [`@formulajs/formulajs`](https://github.com/formulajs/formulajs) plus native
21
+ implementations where Excel semantics differ, clipboard and fill helpers.
22
+ - **React** (`src/react`): the canvas grid and the chrome around it.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ pnpm add @kivacore/ui-pro-sheets
28
+ ```
29
+
30
+ ```tsx
31
+ import { Sheets, type SheetsHandle } from '@kivacore/ui-pro-sheets';
32
+ import '@kivacore/ui-pro-sheets/styles.css';
33
+
34
+ function Page() {
35
+ const ref = useRef<SheetsHandle>(null);
36
+
37
+ return (
38
+ <div style={{ height: 600 }}>
39
+ <Sheets ref={ref} initialData={doc} locale="tr" onChange={wb => save(wb.serialize())} />
40
+ </div>
41
+ );
42
+ }
43
+ ```
44
+
45
+ The component fills its parent, so give the parent a bounded height.
46
+
47
+ ## Entry points
48
+
49
+ | Import | Contents |
50
+ | --- | --- |
51
+ | `@kivacore/ui-pro-sheets` | `Sheets` component, toolbar/formula bar/tabs parts, hooks, everything below |
52
+ | `@kivacore/ui-pro-sheets/engine` | `Workbook`, `Worksheet`, formula engine, clipboard and fill helpers, charts, pivot tables, filters, outlines, collaboration (no React) |
53
+ | `@kivacore/ui-pro-sheets/io` | `importFile`, `exportBlob`, `importXlsx`/`exportXlsx`, `importOds`/`exportOds`, `importCsv`/`exportCsv`, `importJson`/`exportJson`, `exportHtml`/`exportMarkdown`, `printWorkbook`/`buildPrintDocument`, Univer adapters |
54
+ | `@kivacore/ui-pro-sheets/styles.css` | Component styles (prefix `dsh-`, light and dark palettes) |
55
+
56
+ The raw core is also re-exported as `core` from the main entry.
57
+
58
+ ## `<Sheets>` props
59
+
60
+ | Prop | Description |
61
+ | --- | --- |
62
+ | `workbook` | A `Workbook` instance to control externally |
63
+ | `initialData` | A core document, `{ name, sheets }`, the core's serialised JSON, or Univer JSON |
64
+ | `onChange(workbook)` | Debounced after every change |
65
+ | `onSelectionChange(selection, sheet)` | Selection updates |
66
+ | `readOnly` | Disables editing, keeps navigation and copy |
67
+ | `locale` | `en` (default) or `tr`; add more with `registerSheetsLocale` |
68
+ | `theme` | `light`, `dark` or `auto` (follows a `.dark` ancestor) |
69
+ | `showToolbar`, `showFormulaBar`, `showSheetTabs`, `showStatusBar` | Chrome toggles |
70
+ | `toolbarExtra` | Extra controls rendered at the end of the toolbar |
71
+ | `dayFirst` | Parse `01/02/2024` as 1 February |
72
+ | `collaboration` | A `CollaborationSession` you manage yourself |
73
+ | `kivaCollaboration` | `{ url, room, token, name?, color?, onStatusChange? }`: live collaboration through Kiva Collaboration, fully managed by the component (see below) |
74
+
75
+ The `ref` exposes `workbook`, `toJSON()` (core serialisation), `toUniver()`,
76
+ `importFile(file)`, `load(source)`, `exportBlob(format)` for `xlsx`, `ods`,
77
+ `csv`, `tsv`, `json`, `html`, `md`, `focus()`, `getSelection()` and
78
+ `setSelection(range)`.
79
+
80
+ ## Workbook API (engine)
81
+
82
+ ```ts
83
+ import { Workbook, createSheet } from '@kivacore/ui-pro-sheets/engine';
84
+
85
+ const wb = new Workbook({ name: 'Budget', sheets: [createSheet('Q3')] });
86
+ const sheet = wb.getActiveSheet();
87
+
88
+ sheet.setCellInput(0, 0, 'Planned'); // parses numbers, dates, booleans, formulas
89
+ sheet.setValues(1, 0, [[100, '=A2*2']]);
90
+ sheet.applyStyle({ startRow: 0, startCol: 0, endRow: 0, endCol: 1 }, { font: { bold: true }, fill: { type: 'pattern', pattern: 'solid', fgColor: { rgb: 'E0E7FF' } } });
91
+ sheet.merge({ startRow: 3, startCol: 0, endRow: 3, endCol: 3 });
92
+ sheet.setFreeze(1, 0);
93
+ sheet.insertRows(1, 2); // formulas across the workbook are rewritten
94
+ sheet.addTable({ name: 'T1', range: 'A1:D10', style: 'TableStyleMedium2', columns: [] });
95
+ sheet.setSparklines([{ location: 'F2', dataRange: 'B2:E2', type: 'line' }]);
96
+ sheet.setProtection({ sheet: true });
97
+ wb.setDefinedName({ name: 'Rate', range: 'Q3!$B$1' });
98
+ wb.undo();
99
+ sheet.getValue(1, 1); // computed value, FormulaError for errors
100
+ wb.serialize(); // lossless JSON
101
+ ```
102
+
103
+ Every mutation is undoable. `wb.transact(label, fn)` groups several writes into
104
+ one history step. `wb.on(listener)` reports `cells`, `structure`,
105
+ `active-sheet`, `history` and `commit` events. `wb.doc` is the underlying core
106
+ document.
107
+
108
+ ### Charts, pivot tables, filters, outlines
109
+
110
+ ```ts
111
+ import {
112
+ buildChart, chartData, writePivot, refreshPivots, applyAutoFilter, clearAutoFilter
113
+ } from '@kivacore/ui-pro-sheets/engine';
114
+
115
+ sheet.addChart(buildChart({
116
+ type: 'column', title: 'Revenue', sheetName: 'Q3',
117
+ dataRange: { startRow: 0, startCol: 0, endRow: 4, endCol: 3 },
118
+ anchor: { from: { row: 7, col: 0 }, to: { row: 22, col: 6 } }, grouping: 'stacked'
119
+ }));
120
+ chartData(wb, sheet.id, sheet.getCharts()[0]); // resolved series for rendering
121
+
122
+ writePivot(wb, {
123
+ name: 'ByRegion', sourceSheet: 'Sales', sourceRange: { startRow: 0, startCol: 0, endRow: 48, endCol: 4 },
124
+ targetSheet: 'Summary', targetCell: { row: 0, col: 7 },
125
+ rows: ['Region'], columns: ['Product'], pages: [], values: [{ field: 'Revenue', function: 'sum' }]
126
+ });
127
+ refreshPivots(wb); // recompute after the source changed
128
+
129
+ sheet.setAutoFilter({ range: 'A1:E49' }); // header buttons appear
130
+ applyAutoFilter(sheet, range, [{ colIndex: 0, filters: ['EMEA'] }], format);
131
+ sheet.groupRows(1, 4); sheet.collapseGroup('row', sheet.getOutline('row').groups[0]);
132
+ sheet.setPageSetup({ orientation: 'landscape', printArea: '$A$1:$F$40' });
133
+ ```
134
+
135
+ Charts are stored in the file model (`sheet.charts`) and written to XLSX
136
+ through the authoring writer; pivot definitions become `PivotTable` +
137
+ `PivotCache` records and the computed cells are written as values, so Excel
138
+ shows the result and can refresh the pivot. Filters hide rows and persist as
139
+ the sheet `autoFilter`; outline levels persist per row/column.
140
+
141
+ ### Collaboration
142
+
143
+ ```ts
144
+ import { CollaborationSession, BroadcastChannelTransport } from '@kivacore/ui-pro-sheets/engine';
145
+
146
+ const session = new CollaborationSession(wb, new BroadcastChannelTransport('doc-42'), { name: 'Erhan' });
147
+ <Sheets workbook={wb} collaboration={session} />
148
+ ```
149
+
150
+ Every transaction becomes a `commit` (cell writes plus replayable structural
151
+ operations, or a document snapshot when an operation has no descriptor);
152
+ peers apply commits without touching their undo history, newcomers receive
153
+ the document from the first peer that answers, and selections travel as
154
+ presence. Transports: `BroadcastChannelTransport` (tabs of one origin),
155
+ `WebSocketTransport` (any socket-like object) and `MemoryCollabHub` (same
156
+ realm, used by the playground demo).
157
+
158
+ #### Kiva Collaboration
159
+
160
+ In a Kiva app, pass where to connect and who the user is; the component
161
+ connects, reconnects with backoff (fetching a fresh token each time), queues
162
+ edits made while offline and re-syncs the workbook after a reconnect.
163
+
164
+ ```tsx
165
+ <Sheets
166
+ workbook={wb}
167
+ kivaCollaboration={{
168
+ url: import.meta.env.VITE_COLLAB_URL, // wss://collab.docyrus.app (alpha: wss://alpha-collab.docyrus.app)
169
+ room: `t#${tenantId}/sheet#${sheetId}`, // tenant-scoped room name
170
+ token: getKivaToken, // () => the signed-in user's Kiva token
171
+ name: user.name
172
+ }} />
173
+ ```
174
+
175
+ Outside React: `connectKivaCollaboration(wb, options)` returns the
176
+ `CollaborationSession`; call `dispose()` to leave. The server only relays
177
+ messages: the workbook still loads from and saves to your own storage.
178
+
179
+ ### Printing
180
+
181
+ `printWorkbook(wb, { sheetId, range, gridlines, headings })` builds an HTML
182
+ document from the sheet (styles, merges, hidden rows, print area, repeated
183
+ title rows, page breaks, charts as SVG, `@page` size and margins from the
184
+ sheet's page setup) and opens the browser's print dialog; `openPrintPreview`
185
+ opens it in a tab and `buildPrintDocument` returns the HTML.
186
+
187
+ Custom functions:
188
+
189
+ ```ts
190
+ import { registerFunction } from '@kivacore/ui-pro-sheets/engine';
191
+
192
+ registerFunction('DOUBLE', { impl: ([x]) => 2 * Number(x) });
193
+ ```
194
+
195
+ ## Formula support
196
+
197
+ Operators with Excel precedence and coercion, A1 references (relative,
198
+ absolute, whole rows/columns, cross-sheet), array literals, dynamic array
199
+ spilling (`=SEQUENCE(3,3)`, `=FILTER(...)`), defined names, `LET`, lazy
200
+ `IF`/`IFS`/`IFERROR`/`CHOOSE`/`SWITCH`, the `SUMIF` family with Excel criteria
201
+ strings and wildcards, `XLOOKUP`/`XMATCH`, `OFFSET`/`INDIRECT`/`INDEX`
202
+ returning references, volatile functions, cycle detection (`#CYCLE!`) and all
203
+ Excel error values. Shared formulas from files are expanded per cell.
204
+
205
+ Function bodies come from formulajs plus native implementations for what it
206
+ lacks: `LAMBDA` (inline `LAMBDA(x, x*2)(3)` and defined-name lambdas called as
207
+ `=MyFn(A1)`), `MAP`/`BYROW`/`BYCOL`/`SCAN`/`REDUCE`/`MAKEARRAY`/`ISOMITTED`,
208
+ `TEXTBEFORE`/`TEXTAFTER`/`TEXTSPLIT`, `TOCOL`/`TOROW`, `ARRAYTOTEXT`/`VALUETOTEXT`,
209
+ byte functions (`LENB`, `LEFTB`, `MIDB`, `FINDB`, …), `ASC`/`JIS`/`DBCS`,
210
+ `BAHTTEXT`, `ENCODEURL`, `MDETERM`/`MINVERSE`/`AREAS`, `CELL`/`INFO`, the bond
211
+ functions (`PRICE`, `YIELD`, `DURATION`, `MDURATION`, `COUP*`, `PRICEMAT`,
212
+ `YIELDMAT`, `RECEIVED`, `INTRATE`, `ACCRINTM`, `YIELDDISC`), `VDB`,
213
+ `AMORLINC`/`AMORDEGRC` and the statistical aliases (`CONFIDENCE`, `POISSON`,
214
+ `WEIBULL`, `PERCENTRANK`, `FORECAST.LINEAR`, `CHISQ.DIST.RT`, `T.DIST.2T`, …).
215
+ About 480 names in total; `listFunctions()` returns them with category,
216
+ argument list and description for the Insert Function dialog (Shift+F3).
217
+
218
+ `GETPIVOTDATA` reads the pivot tables this package lays out; `FORECAST.ETS`,
219
+ `.CONFINT`, `.SEASONALITY` and `.STAT` use additive Holt-Winters with a
220
+ parameter search (close to, not identical with, Excel's AAA model); the
221
+ odd-coupon bonds (`ODDFPRICE`, `ODDFYIELD`, `ODDLPRICE`, `ODDLYIELD`) follow
222
+ Excel's published formulas. Not implemented: the external-data functions
223
+ `RTD`, `WEBSERVICE`, `FILTERXML` (they return `#NAME?`).
224
+
225
+ Dates are `Date` values in the document and serial numbers inside formulas;
226
+ number formats use Excel patterns (`#,##0.00`, `0%`, `yyyy-mm-dd`, …).
227
+
228
+ ## Rendering
229
+
230
+ Canvas grid with virtualisation, frozen panes, merged cells, text overflow and
231
+ wrap, rich text runs, borders, number formats, conditional formatting (cell
232
+ rules, expressions, colour scales, data bars, icon sets, top/bottom, above
233
+ average, duplicates, text rules), data validation (lists with a dropdown,
234
+ checkboxes, numeric and custom rules), table styles with banding, sparklines,
235
+ images and text boxes anchored to cells, charts (column, bar, line, area, pie,
236
+ doughnut, scatter, radar; movable and resizable overlays), pivot tables,
237
+ autofilter buttons with sort/search/value dropdowns, outline gutters with
238
+ collapse buttons and level buttons, hyperlinks, comments, sheet protection
239
+ with locked cells, hidden rows, zoom, collaborator cursors, light and dark
240
+ themes.
241
+
242
+ ## Comments, rich text, Univer facade
243
+
244
+ Comment threads: root note plus replies, resolve/reopen, an anchored popover
245
+ (context menu or the Comments toolbar button) and a side panel listing every
246
+ thread; the `author` prop names the writer. Rich text inside a cell: F2 on a
247
+ rich cell opens the rich editor, selecting text and pressing Bold/Italic/
248
+ Underline/colour/size/family in the toolbar formats only the selection (a
249
+ plain edit switches to the rich editor on the first such click); runs are
250
+ stored as `richText` and exported. `crosshair` highlights the active row and
251
+ column, `watermark` tiles a diagonal text over the grid. Locales: en, tr, es,
252
+ fr (`registerSheetsLocale` for more).
253
+
254
+ Comment notifications: every comment change emits a `comment` workbook event
255
+ (`CommentEvent`: created, edited, replied, replyDeleted, resolved, reopened,
256
+ deleted, with sheet, cell, author, text and the `@name` / `@[Full Name]`
257
+ mentions parsed from the text). `<Sheets onCommentEvent>` receives them so the
258
+ host can call its notification service; `people` feeds the `@` mention picker
259
+ and `unreadComments` (thread ids) draws unread markers in the accent colour,
260
+ shows a badge on the toolbar button and an "unread only" filter in the panel.
261
+ The package stores no read state itself.
262
+
263
+ Hosting comments in your own service: the package knows nothing about any
264
+ backend, it only gives you the pieces. `currentUser` (a `CommentPerson`)
265
+ names the writer and stores its `id` as `authorId` on notes and replies;
266
+ `canEditComment({ thread, reply? })` lets you hide edit/delete/resolve for
267
+ other people's comments; `CommentEvent` carries `authorId` and `mentionIds`
268
+ (mention names resolved against `people`) so notifications go to the right
269
+ users. To replay threads you already store, call
270
+ `workbook.loadComments([{ sheetId | sheetName, row, col, thread }])` — one
271
+ silent step with no undo entry and no `comment` events — or pass
272
+ `{ silent: true }` to `setComment` / `addCommentReply` / `setCommentResolved` /
273
+ `removeCommentReply`; ids and `createdAt` you pass are kept, so the thread
274
+ round-trips with your identifiers. `workbook.findComment(id)` locates a
275
+ thread across sheets and `handle.openComment(id)` activates its sheet,
276
+ selects the cell and opens the popover — the target of a "view comment" link.
277
+
278
+ `useSheetComments(workbook, store)` wires those pieces to any backend for
279
+ you: implement `CommentStore` — `list`, `create`, `reply`, `update`,
280
+ `remove` — and the hook loads stored threads into the cells on mount, turns
281
+ every comment event into one store call, serialises the calls per thread and
282
+ adopts the id your service returns (`adoptCommentId` does that step alone for
283
+ hosts that keep their own sync loop). It returns `{ loading, error, pending,
284
+ reload }`; pass `{ people }` so the store also receives `mentionIds`, and
285
+ `{ onError }` to surface failures. The package ships no HTTP client and
286
+ depends on nothing but React — the store is where your service lives:
287
+
288
+ ```tsx
289
+ const [handle, setHandle] = useState<SheetsHandle | null>(null);
290
+ const store = useMemo<CommentStore>(() => ({
291
+ list: async () => (await api.get(`/docs/${docId}/comments`)).map(toLoadedComment),
292
+ create: async e => ({ id: (await api.post(`/docs/${docId}/comments`, toRecord(e))).id }),
293
+ reply: async e => ({ id: (await api.post(`/docs/${docId}/comments`, toRecord(e))).id }),
294
+ update: async e => { await api.patch(`/docs/${docId}/comments/${e.replyId ?? e.commentId}`, toRecord(e)); },
295
+ remove: async e => { await api.delete(`/docs/${docId}/comments/${e.replyId ?? e.commentId}`); }
296
+ }), [docId]);
297
+
298
+ const comments = useSheetComments(handle?.workbook, store, { people });
299
+
300
+ <Sheets ref={setHandle} people={people} currentUser={me} canEditComment={mine} />
301
+ ```
302
+
303
+ `canComment` decides whether notes and replies may be written at all; it
304
+ defaults to `!readOnly`, so pass `canComment` with `readOnly` for a commenter
305
+ who may not touch the cells. `CommentPerson.avatar`, when given, is shown
306
+ next to the author in the thread and in the mention picker.
307
+
308
+ `handle.facade` is a Univer-style API (`getActiveWorkbook().getActiveSheet()
309
+ .getRange('A1:B2').setValues(...)`, `setFontWeight`, `setBorder`, `merge`,
310
+ `insertRowsAfter`, `setFrozenRows`, `zoom`, …) and `handle.executeApiCall({
311
+ method: 'range:A1:B2:setValues', args })` runs the `api:call` payloads host
312
+ applications already send to Univer, so the integration code does not change.
313
+
314
+ ## Opening documents saved by Univer
315
+
316
+ `workbookFromUniver` (and so `initialData`, `load` and `importJson`) reads a
317
+ real `workbook.save()` snapshot, not only the AI-shaped JSON: conditional
318
+ formatting, data validation, filters, comment threads with replies, defined
319
+ names and embedded images come from the snapshot's plugin `resources`, cell
320
+ hyperlinks from the rich text custom ranges. Images Univer references by URL
321
+ or upload id, range protection and the watermark are not carried over.
322
+
323
+ ## Storage envelope
324
+
325
+ ```ts
326
+ import { packWorkbook, unpackWorkbook } from '@kivacore/ui-pro-sheets/io';
327
+
328
+ const stored = await packWorkbook(handle.workbook); // { format: 'docyrus-sheets', version: 1, encoding: 'gzip-base64', data }
329
+ const workbook = await unpackWorkbook(stored); // also accepts serialised JSON, Univer JSON, rows
330
+ ```
331
+
332
+ The lossless serialisation is about 2.5 times the size of the same data as
333
+ Univer JSON; the envelope is about a third of it. Store the envelope, not
334
+ `toUniver()`, which cannot carry charts, pivots, tables or sparklines.
335
+
336
+ ## Text to columns
337
+
338
+ Data › Text to columns, the cell context menu and the command palette split
339
+ the first column of the selection at a comma, semicolon, tab or space; Custom
340
+ opens a dialog for any delimiter. `splitTextToColumns(sheet, range, {
341
+ delimiters, treatConsecutiveAsOne })` is the engine call; one undo step.
342
+
343
+ ## Slicers, tables, sparklines, names, combo charts
344
+
345
+ Slicers live in a side panel (Data › Slicers): one button group per slicer,
346
+ bound to a table column or a pivot field; clicking items filters the table
347
+ or recomputes the pivot, Ctrl+click selects several. "Format as table"
348
+ offers the 60 built-in table styles with banding, filter buttons and a total
349
+ row. Sparklines (line, column, win/loss) and the name manager have their own
350
+ dialogs. Charts can mix column, line and area series, put series on a
351
+ secondary axis and use a pseudo-3D look; those settings live in the chart's
352
+ `kiva` extras and combo charts export with their per-series kinds.
353
+
354
+ ## Dialogs and commands
355
+
356
+ Conditional formatting (highlight rules, top/bottom, duplicates, formula
357
+ rules, colour scales, data bars, icon sets, with a list of existing rules),
358
+ data validation (list, whole, decimal, date, time, text length, custom),
359
+ Insert Function (Shift+F3, searchable catalogue with signatures), a command
360
+ palette (Ctrl+Shift+P) listing every action with its shortcut, Remove
361
+ Duplicates (Data menu, `removeDuplicateRows` in the engine), Ctrl+Shift+L
362
+ toggles the autofilter. Pivot report filters show a dropdown on the page-field
363
+ cell; the selected item is stored with the pivot definition.
364
+
365
+ ## Not included yet
366
+
367
+ Timelines (preserved on round trip, not rendered), slicer positions (the
368
+ file model carries no drawing anchor, so slicers live in the side panel),
369
+ printing of chart sheets, and the external-data formulas listed above.
370
+
371
+ ## Development
372
+
373
+ ```bash
374
+ pnpm --filter @kivacore/ui-pro-sheets build
375
+ pnpm --filter @kivacore/ui-pro-sheets lint
376
+ ```
377
+
378
+ The playground page `/components/sheets` exercises the component with sample
379
+ workbooks, import and export in every format, locale switching and a 10,000
380
+ row dataset.