@kivacore/ui-pro-sheets
v0.5.4
Published
Native Kiva spreadsheet: hucre data model, canvas grid, Excel-compatible formula engine, and XLSX/ODS/CSV/JSON import-export.
Readme
@kivacore/ui-pro-sheets
Native Kiva spreadsheet for React 19: a canvas grid, an Excel-compatible formula engine and a complete file layer, in one package with no runtime dependency on UniverJS.
The package has three layers:
- Core (
src/core): the document model and file layer, forked from hucre (MIT) and vendored into this package. It reads and writes XLSX, XLS, XLSB, ODS, CSV, JSON, NDJSON, XML, HTML and Markdown, models styles, merges, validations, conditional rules, tables, images, sparklines, charts, pivots, protection and outlines, formats numbers with Excel patterns, and provides row/column operations that keep formulas, merges and rules consistent. Seesrc/core/README.mdfor the fork notes. - Engine (
src/engine): the editableWorkbook/Worksheetfacades over the core model, undo/redo, the formula engine (tokenizer, parser, evaluator, dependency graph, spills) with ~370 function bodies from@formulajs/formulajsplus native implementations where Excel semantics differ, clipboard and fill helpers. - React (
src/react): the canvas grid and the chrome around it.
Install
pnpm add @kivacore/ui-pro-sheetsimport { Sheets, type SheetsHandle } from '@kivacore/ui-pro-sheets';
import '@kivacore/ui-pro-sheets/styles.css';
function Page() {
const ref = useRef<SheetsHandle>(null);
return (
<div style={{ height: 600 }}>
<Sheets ref={ref} initialData={doc} locale="tr" onChange={wb => save(wb.serialize())} />
</div>
);
}The component fills its parent, so give the parent a bounded height.
Entry points
| Import | Contents |
| --- | --- |
| @kivacore/ui-pro-sheets | Sheets component, toolbar/formula bar/tabs parts, hooks, everything below |
| @kivacore/ui-pro-sheets/engine | Workbook, Worksheet, formula engine, clipboard and fill helpers, charts, pivot tables, filters, outlines, collaboration (no React) |
| @kivacore/ui-pro-sheets/io | importFile, exportBlob, importXlsx/exportXlsx, importOds/exportOds, importCsv/exportCsv, importJson/exportJson, exportHtml/exportMarkdown, printWorkbook/buildPrintDocument, Univer adapters |
| @kivacore/ui-pro-sheets/styles.css | Component styles (prefix dsh-, light and dark palettes) |
The raw core is also re-exported as core from the main entry.
<Sheets> props
| Prop | Description |
| --- | --- |
| workbook | A Workbook instance to control externally |
| initialData | A core document, { name, sheets }, the core's serialised JSON, or Univer JSON |
| onChange(workbook) | Debounced after every change |
| onSelectionChange(selection, sheet) | Selection updates |
| readOnly | Disables editing, keeps navigation and copy |
| locale | en (default) or tr; add more with registerSheetsLocale |
| theme | light, dark or auto (follows a .dark ancestor) |
| showToolbar, showFormulaBar, showSheetTabs, showStatusBar | Chrome toggles |
| toolbarExtra | Extra controls rendered at the end of the toolbar |
| dayFirst | Parse 01/02/2024 as 1 February |
| collaboration | A CollaborationSession you manage yourself |
| kivaCollaboration | { url, room, token, name?, color?, onStatusChange? }: live collaboration through Kiva Collaboration, fully managed by the component (see below) |
The ref exposes workbook, toJSON() (core serialisation), toUniver(),
importFile(file), load(source), exportBlob(format) for xlsx, ods,
csv, tsv, json, html, md, focus(), getSelection() and
setSelection(range).
Workbook API (engine)
import { Workbook, createSheet } from '@kivacore/ui-pro-sheets/engine';
const wb = new Workbook({ name: 'Budget', sheets: [createSheet('Q3')] });
const sheet = wb.getActiveSheet();
sheet.setCellInput(0, 0, 'Planned'); // parses numbers, dates, booleans, formulas
sheet.setValues(1, 0, [[100, '=A2*2']]);
sheet.applyStyle({ startRow: 0, startCol: 0, endRow: 0, endCol: 1 }, { font: { bold: true }, fill: { type: 'pattern', pattern: 'solid', fgColor: { rgb: 'E0E7FF' } } });
sheet.merge({ startRow: 3, startCol: 0, endRow: 3, endCol: 3 });
sheet.setFreeze(1, 0);
sheet.insertRows(1, 2); // formulas across the workbook are rewritten
sheet.addTable({ name: 'T1', range: 'A1:D10', style: 'TableStyleMedium2', columns: [] });
sheet.setSparklines([{ location: 'F2', dataRange: 'B2:E2', type: 'line' }]);
sheet.setProtection({ sheet: true });
wb.setDefinedName({ name: 'Rate', range: 'Q3!$B$1' });
wb.undo();
sheet.getValue(1, 1); // computed value, FormulaError for errors
wb.serialize(); // lossless JSONEvery mutation is undoable. wb.transact(label, fn) groups several writes into
one history step. wb.on(listener) reports cells, structure,
active-sheet, history and commit events. wb.doc is the underlying core
document.
Charts, pivot tables, filters, outlines
import {
buildChart, chartData, writePivot, refreshPivots, applyAutoFilter, clearAutoFilter
} from '@kivacore/ui-pro-sheets/engine';
sheet.addChart(buildChart({
type: 'column', title: 'Revenue', sheetName: 'Q3',
dataRange: { startRow: 0, startCol: 0, endRow: 4, endCol: 3 },
anchor: { from: { row: 7, col: 0 }, to: { row: 22, col: 6 } }, grouping: 'stacked'
}));
chartData(wb, sheet.id, sheet.getCharts()[0]); // resolved series for rendering
writePivot(wb, {
name: 'ByRegion', sourceSheet: 'Sales', sourceRange: { startRow: 0, startCol: 0, endRow: 48, endCol: 4 },
targetSheet: 'Summary', targetCell: { row: 0, col: 7 },
rows: ['Region'], columns: ['Product'], pages: [], values: [{ field: 'Revenue', function: 'sum' }]
});
refreshPivots(wb); // recompute after the source changed
sheet.setAutoFilter({ range: 'A1:E49' }); // header buttons appear
applyAutoFilter(sheet, range, [{ colIndex: 0, filters: ['EMEA'] }], format);
sheet.groupRows(1, 4); sheet.collapseGroup('row', sheet.getOutline('row').groups[0]);
sheet.setPageSetup({ orientation: 'landscape', printArea: '$A$1:$F$40' });Charts are stored in the file model (sheet.charts) and written to XLSX
through the authoring writer; pivot definitions become PivotTable +
PivotCache records and the computed cells are written as values, so Excel
shows the result and can refresh the pivot. Filters hide rows and persist as
the sheet autoFilter; outline levels persist per row/column.
Collaboration
import { CollaborationSession, BroadcastChannelTransport } from '@kivacore/ui-pro-sheets/engine';
const session = new CollaborationSession(wb, new BroadcastChannelTransport('doc-42'), { name: 'Erhan' });
<Sheets workbook={wb} collaboration={session} />Every transaction becomes a commit (cell writes plus replayable structural
operations, or a document snapshot when an operation has no descriptor);
peers apply commits without touching their undo history, newcomers receive
the document from the first peer that answers, and selections travel as
presence. Transports: BroadcastChannelTransport (tabs of one origin),
WebSocketTransport (any socket-like object) and MemoryCollabHub (same
realm, used by the playground demo).
Kiva Collaboration
In a Kiva app, pass where to connect and who the user is; the component connects, reconnects with backoff (fetching a fresh token each time), queues edits made while offline and re-syncs the workbook after a reconnect.
<Sheets
workbook={wb}
kivaCollaboration={{
url: import.meta.env.VITE_COLLAB_URL, // wss://collab.docyrus.app (alpha: wss://alpha-collab.docyrus.app)
room: `t#${tenantId}/sheet#${sheetId}`, // tenant-scoped room name
token: getKivaToken, // () => the signed-in user's Kiva token
name: user.name
}} />Outside React: connectKivaCollaboration(wb, options) returns the
CollaborationSession; call dispose() to leave. The server only relays
messages: the workbook still loads from and saves to your own storage.
Printing
printWorkbook(wb, { sheetId, range, gridlines, headings }) builds an HTML
document from the sheet (styles, merges, hidden rows, print area, repeated
title rows, page breaks, charts as SVG, @page size and margins from the
sheet's page setup) and opens the browser's print dialog; openPrintPreview
opens it in a tab and buildPrintDocument returns the HTML.
Custom functions:
import { registerFunction } from '@kivacore/ui-pro-sheets/engine';
registerFunction('DOUBLE', { impl: ([x]) => 2 * Number(x) });Formula support
Operators with Excel precedence and coercion, A1 references (relative,
absolute, whole rows/columns, cross-sheet), array literals, dynamic array
spilling (=SEQUENCE(3,3), =FILTER(...)), defined names, LET, lazy
IF/IFS/IFERROR/CHOOSE/SWITCH, the SUMIF family with Excel criteria
strings and wildcards, XLOOKUP/XMATCH, OFFSET/INDIRECT/INDEX
returning references, volatile functions, cycle detection (#CYCLE!) and all
Excel error values. Shared formulas from files are expanded per cell.
Function bodies come from formulajs plus native implementations for what it
lacks: LAMBDA (inline LAMBDA(x, x*2)(3) and defined-name lambdas called as
=MyFn(A1)), MAP/BYROW/BYCOL/SCAN/REDUCE/MAKEARRAY/ISOMITTED,
TEXTBEFORE/TEXTAFTER/TEXTSPLIT, TOCOL/TOROW, ARRAYTOTEXT/VALUETOTEXT,
byte functions (LENB, LEFTB, MIDB, FINDB, …), ASC/JIS/DBCS,
BAHTTEXT, ENCODEURL, MDETERM/MINVERSE/AREAS, CELL/INFO, the bond
functions (PRICE, YIELD, DURATION, MDURATION, COUP*, PRICEMAT,
YIELDMAT, RECEIVED, INTRATE, ACCRINTM, YIELDDISC), VDB,
AMORLINC/AMORDEGRC and the statistical aliases (CONFIDENCE, POISSON,
WEIBULL, PERCENTRANK, FORECAST.LINEAR, CHISQ.DIST.RT, T.DIST.2T, …).
About 480 names in total; listFunctions() returns them with category,
argument list and description for the Insert Function dialog (Shift+F3).
GETPIVOTDATA reads the pivot tables this package lays out; FORECAST.ETS,
.CONFINT, .SEASONALITY and .STAT use additive Holt-Winters with a
parameter search (close to, not identical with, Excel's AAA model); the
odd-coupon bonds (ODDFPRICE, ODDFYIELD, ODDLPRICE, ODDLYIELD) follow
Excel's published formulas. Not implemented: the external-data functions
RTD, WEBSERVICE, FILTERXML (they return #NAME?).
Dates are Date values in the document and serial numbers inside formulas;
number formats use Excel patterns (#,##0.00, 0%, yyyy-mm-dd, …).
Rendering
Canvas grid with virtualisation, frozen panes, merged cells, text overflow and wrap, rich text runs, borders, number formats, conditional formatting (cell rules, expressions, colour scales, data bars, icon sets, top/bottom, above average, duplicates, text rules), data validation (lists with a dropdown, checkboxes, numeric and custom rules), table styles with banding, sparklines, images and text boxes anchored to cells, charts (column, bar, line, area, pie, doughnut, scatter, radar; movable and resizable overlays), pivot tables, autofilter buttons with sort/search/value dropdowns, outline gutters with collapse buttons and level buttons, hyperlinks, comments, sheet protection with locked cells, hidden rows, zoom, collaborator cursors, light and dark themes.
Comments, rich text, Univer facade
Comment threads: root note plus replies, resolve/reopen, an anchored popover
(context menu or the Comments toolbar button) and a side panel listing every
thread; the author prop names the writer. Rich text inside a cell: F2 on a
rich cell opens the rich editor, selecting text and pressing Bold/Italic/
Underline/colour/size/family in the toolbar formats only the selection (a
plain edit switches to the rich editor on the first such click); runs are
stored as richText and exported. crosshair highlights the active row and
column, watermark tiles a diagonal text over the grid. Locales: en, tr, es,
fr (registerSheetsLocale for more).
Comment notifications: every comment change emits a comment workbook event
(CommentEvent: created, edited, replied, replyDeleted, resolved, reopened,
deleted, with sheet, cell, author, text and the @name / @[Full Name]
mentions parsed from the text). <Sheets onCommentEvent> receives them so the
host can call its notification service; people feeds the @ mention picker
and unreadComments (thread ids) draws unread markers in the accent colour,
shows a badge on the toolbar button and an "unread only" filter in the panel.
The package stores no read state itself.
Hosting comments in your own service: the package knows nothing about any
backend, it only gives you the pieces. currentUser (a CommentPerson)
names the writer and stores its id as authorId on notes and replies;
canEditComment({ thread, reply? }) lets you hide edit/delete/resolve for
other people's comments; CommentEvent carries authorId and mentionIds
(mention names resolved against people) so notifications go to the right
users. To replay threads you already store, call
workbook.loadComments([{ sheetId | sheetName, row, col, thread }]) — one
silent step with no undo entry and no comment events — or pass
{ silent: true } to setComment / addCommentReply / setCommentResolved /
removeCommentReply; ids and createdAt you pass are kept, so the thread
round-trips with your identifiers. workbook.findComment(id) locates a
thread across sheets and handle.openComment(id) activates its sheet,
selects the cell and opens the popover — the target of a "view comment" link.
useSheetComments(workbook, store) wires those pieces to any backend for
you: implement CommentStore — list, create, reply, update,
remove — and the hook loads stored threads into the cells on mount, turns
every comment event into one store call, serialises the calls per thread and
adopts the id your service returns (adoptCommentId does that step alone for
hosts that keep their own sync loop). It returns { loading, error, pending,
reload }; pass { people } so the store also receives mentionIds, and
{ onError } to surface failures. The package ships no HTTP client and
depends on nothing but React — the store is where your service lives:
const [handle, setHandle] = useState<SheetsHandle | null>(null);
const store = useMemo<CommentStore>(() => ({
list: async () => (await api.get(`/docs/${docId}/comments`)).map(toLoadedComment),
create: async e => ({ id: (await api.post(`/docs/${docId}/comments`, toRecord(e))).id }),
reply: async e => ({ id: (await api.post(`/docs/${docId}/comments`, toRecord(e))).id }),
update: async e => { await api.patch(`/docs/${docId}/comments/${e.replyId ?? e.commentId}`, toRecord(e)); },
remove: async e => { await api.delete(`/docs/${docId}/comments/${e.replyId ?? e.commentId}`); }
}), [docId]);
const comments = useSheetComments(handle?.workbook, store, { people });
<Sheets ref={setHandle} people={people} currentUser={me} canEditComment={mine} />canComment decides whether notes and replies may be written at all; it
defaults to !readOnly, so pass canComment with readOnly for a commenter
who may not touch the cells. CommentPerson.avatar, when given, is shown
next to the author in the thread and in the mention picker.
handle.facade is a Univer-style API (getActiveWorkbook().getActiveSheet()
.getRange('A1:B2').setValues(...), setFontWeight, setBorder, merge,
insertRowsAfter, setFrozenRows, zoom, …) and handle.executeApiCall({
method: 'range:A1:B2:setValues', args }) runs the api:call payloads host
applications already send to Univer, so the integration code does not change.
Opening documents saved by Univer
workbookFromUniver (and so initialData, load and importJson) reads a
real workbook.save() snapshot, not only the AI-shaped JSON: conditional
formatting, data validation, filters, comment threads with replies, defined
names and embedded images come from the snapshot's plugin resources, cell
hyperlinks from the rich text custom ranges. Images Univer references by URL
or upload id, range protection and the watermark are not carried over.
Storage envelope
import { packWorkbook, unpackWorkbook } from '@kivacore/ui-pro-sheets/io';
const stored = await packWorkbook(handle.workbook); // { format: 'docyrus-sheets', version: 1, encoding: 'gzip-base64', data }
const workbook = await unpackWorkbook(stored); // also accepts serialised JSON, Univer JSON, rowsThe lossless serialisation is about 2.5 times the size of the same data as
Univer JSON; the envelope is about a third of it. Store the envelope, not
toUniver(), which cannot carry charts, pivots, tables or sparklines.
Text to columns
Data › Text to columns, the cell context menu and the command palette split
the first column of the selection at a comma, semicolon, tab or space; Custom
opens a dialog for any delimiter. splitTextToColumns(sheet, range, {
delimiters, treatConsecutiveAsOne }) is the engine call; one undo step.
Slicers, tables, sparklines, names, combo charts
Slicers live in a side panel (Data › Slicers): one button group per slicer,
bound to a table column or a pivot field; clicking items filters the table
or recomputes the pivot, Ctrl+click selects several. "Format as table"
offers the 60 built-in table styles with banding, filter buttons and a total
row. Sparklines (line, column, win/loss) and the name manager have their own
dialogs. Charts can mix column, line and area series, put series on a
secondary axis and use a pseudo-3D look; those settings live in the chart's
kiva extras and combo charts export with their per-series kinds.
Dialogs and commands
Conditional formatting (highlight rules, top/bottom, duplicates, formula
rules, colour scales, data bars, icon sets, with a list of existing rules),
data validation (list, whole, decimal, date, time, text length, custom),
Insert Function (Shift+F3, searchable catalogue with signatures), a command
palette (Ctrl+Shift+P) listing every action with its shortcut, Remove
Duplicates (Data menu, removeDuplicateRows in the engine), Ctrl+Shift+L
toggles the autofilter. Pivot report filters show a dropdown on the page-field
cell; the selected item is stored with the pivot definition.
Not included yet
Timelines (preserved on round trip, not rendered), slicer positions (the file model carries no drawing anchor, so slicers live in the side panel), printing of chart sheets, and the external-data formulas listed above.
Development
pnpm --filter @kivacore/ui-pro-sheets build
pnpm --filter @kivacore/ui-pro-sheets lintThe playground page /components/sheets exercises the component with sample
workbooks, import and export in every format, locale switching and a 10,000
row dataset.
