@8sheets/react 0.0.0-stage → 1.0.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/LICENSE.md ADDED
@@ -0,0 +1,36 @@
1
+ # 8sheets npm Package Licence
2
+
3
+ > Version 1.0, 17 November 2026. It covers the packages published on npm (`8sheets`, `@8sheets/core`, `@8sheets/react`, `@8sheets/vue`, `@8sheets/angular`). The full terms of the paid licence, the 8sheets Source Licence, are at https://8sheets.com/docs/licence/; prices are at https://8sheets.com/pricing/.
4
+
5
+ Copyright (c) 2026 8cells Jarosław Kaczmarski. All rights reserved. This is commercial software. It is not open source.
6
+
7
+ ## 1. Evaluation
8
+
9
+ You may install this package and use it free of charge to evaluate 8sheets: in development, in tests, in prototypes and in demos that you do not offer to anyone as a product or service.
10
+
11
+ ## 2. Use in a product
12
+
13
+ Any other use needs a paid licence, bought at https://8sheets.com/pricing/. This includes using the package in an application, website, service or system that you deploy or make available to its users, including your own employees. The licence you buy decides who may use your product:
14
+
15
+ - **Internal** (999 USD, once per company): your product is used only inside your company.
16
+ - **SaaS / OEM** (2,999 USD, once per company): your product is offered to people outside your company.
17
+ - **Enterprise** (priced in a separate agreement): any use, under that agreement.
18
+
19
+ Each licence covers every developer and every deployment of the company that holds it. There is no licence key. Once you hold a licence, the 8sheets Source Licence (https://8sheets.com/docs/licence/) governs your use of this package and replaces sections 1 and 3 of this file.
20
+
21
+ ## 3. Restrictions
22
+
23
+ Without a licence that allows it, you may not:
24
+
25
+ 1. use the package in production, in a product or for a customer;
26
+ 2. publish, sell, sublicense or redistribute the package or any part of it on its own, or as a component, SDK or library for other developers;
27
+ 3. reverse engineer, decompile or de-minify the package, except as far as the law allows despite this restriction;
28
+ 4. remove or change copyright and licence notices.
29
+
30
+ ## 4. Third-party components
31
+
32
+ The package includes data and artwork under their own licences (icons, map data, dictionaries and thesauri). Their notices are in the files next to that data (`*.NOTICE.txt`, `*.LICENSE.txt`, `charts/geo/NOTICE`) and listed at https://8sheets.com/docs/notices/. Those terms apply to those parts.
33
+
34
+ ## 5. No warranty
35
+
36
+ The package is provided "as is", without warranty of any kind. To the extent the law allows, 8cells Jarosław Kaczmarski is not liable for any damages arising from its use.
package/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # 8sheets for React
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
+ `<Sheet>` puts an [8sheets](https://8sheets.com) workbook, an Excel-compatible spreadsheet, in a React app. It works with React 18 and 19, StrictMode included, and with server rendering. Props, events and the ref are typed.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm i @8sheets/react @8sheets/core
9
+ ```
10
+
11
+ ## Use
12
+
13
+ ```jsx
14
+ import { useRef } from 'react';
15
+ import { Sheet } from '@8sheets/react';
16
+
17
+ export function Budget() {
18
+ const sheet = useRef(null);
19
+ return (
20
+ <div style={{ height: 480 }}>
21
+ <Sheet
22
+ ref={sheet}
23
+ options={{ chrome: 'light', parts: { titleBar: false } }}
24
+ onReady={(wb) => { wb.activeSheet.range('A1').values = [['Item', 'Cost']]; }}
25
+ onCellsChanged={(e) => console.log(e.count, 'cells changed')}
26
+ onBeforeSheetRemove={(e) => e.cancel()}
27
+ />
28
+ </div>
29
+ );
30
+ }
31
+ ```
32
+
33
+ The component renders one `<div>` that fills its container, so the container needs a height.
34
+
35
+ - **`options`** goes to `mountWorkbook`: `parts`, `chrome`, `theme`, `fileName`, `language`, `data`, `sheets` and every option in the API reference. After mount it is compared by value, and only the changed keys go to `wb.setOptions`, with no remount. `data` and `sheets` act only at mount.
36
+ - **Events** are props: `on` plus the event name in camel case (`onCellsChanged`, `onSelectionChanged`, `onBeforeSheetRemove`). Call `e.cancel()` in a `before…` handler to stop the action. Only the events you pass a handler for are subscribed.
37
+ - **`onReady(wb)`** gives the workbook once it is mounted; **`onError(err)`** reports a failed mount or an option `setOptions` refused.
38
+ - **The ref** (`SheetRef`) has `workbook`, `openFile(file)` and `saveXlsx(sink)`.
39
+ - On unmount the workbook is destroyed, with its listeners and Worker.
40
+
41
+ ## Next.js
42
+
43
+ `sheet.js` is marked `'use client'` and mounts in an effect, so a server component can render `<Sheet>` and the server sends an empty `<div>`. Handler props are functions, so pass them from a client component. To keep 8sheets out of the server bundle entirely, load it with `dynamic(() => import('@8sheets/react').then((m) => m.Sheet), { ssr: false })` in a client component; `dynamic()` doesn't forward refs, so use `onReady` there. Both Turbopack and webpack build it with no configuration.
44
+
45
+ ## Vite
46
+
47
+ ```js
48
+ // vite.config.js
49
+ export default defineConfig({
50
+ worker: { format: 'es' },
51
+ optimizeDeps: { exclude: ['@8sheets/core', '@8sheets/react'] },
52
+ });
53
+ ```
54
+
55
+ The Workers are ES modules. `optimizeDeps.exclude` is needed only before Vite 8: the older dependency pre-bundling moves the 8sheets modules away from their Workers, so files can't be opened or saved in `vite` dev. On Vite 8 you can leave it out.
56
+
57
+ ## Documentation
58
+
59
+ [React, Vue and Angular](https://8sheets.com/docs/frameworks/), [For developers](https://8sheets.com/docs/developers/) and the [API reference](https://8sheets.com/docs/api/) for everything on the workbook.
60
+
61
+ ## Licence
62
+
63
+ 8sheets is commercial software, not open source. You may install it and try it for free, to evaluate it. Using it in a product, or deploying it for your users or your own staff, needs a licence from [8sheets.com/pricing](https://8sheets.com/pricing/): **Internal** 999 USD or **SaaS / OEM** 2,999 USD, each paid once per company and covering every developer and every deployment, or **Enterprise**, quoted. There is no licence key and nothing in the package checks for one. The terms are in `LICENSE.md` and, once you hold a licence, the [8sheets Source Licence](https://8sheets.com/docs/licence/).
package/index.d.ts ADDED
@@ -0,0 +1,182 @@
1
+ // Types for <Sheet>.
2
+ import type { CSSProperties, ForwardRefExoticComponent, RefAttributes } from 'react';
3
+ import type { SheetEvent, SheetsWorkbook, mountWorkbook } from '@8sheets/core';
4
+
5
+ type MountOptions = NonNullable<Parameters<typeof mountWorkbook>[1]>;
6
+
7
+ /** An event from the workbook: `type`, `workbook`, `cancelled`, `cancel()` and the fields of that event. */
8
+ export type SheetsEvent = SheetEvent & { workbook: SheetsWorkbook; [field: string]: any };
9
+ export type SheetEventHandler = (event: SheetsEvent) => void;
10
+
11
+ /**
12
+ * Options for `mountWorkbook`: the mount options (`parts`, `chrome`, `fileName`, `theme`, `data`, `language`)
13
+ * plus any option from the "All options" table in docs/api.md. After mount, changed keys go to
14
+ * `wb.setOptions`; a value `setOptions` refuses is reported through `onError`. `data` and `sheets` act only
15
+ * at mount, like React's `defaultValue`, and later changes to them are ignored.
16
+ */
17
+ export type SheetOptions = MountOptions & Record<string, any>;
18
+
19
+ /** One handler prop per workbook event, named `on` + the camel-cased event name. */
20
+ export interface SheetEventProps {
21
+ /** `before-change` (cancellable): An undoable edit is about to run. Fields: label, sheet. */
22
+ onBeforeChange?: SheetEventHandler;
23
+ /** `cells-changed`: Cells changed through any path: typing, paste, fill, API, undo or redo. `cells()` lists them lazily. Fields: sheet, label, reason, count, bounds, cells(). */
24
+ onCellsChanged?: SheetEventHandler;
25
+ /** `step-done`: Any undoable step finished or was undone or redone, including ones that touch no cell, such as a format or a theme. Fields: sheet, label, reason. */
26
+ onStepDone?: SheetEventHandler;
27
+ /** `bulk-written`: A typed-array bulk write finished. It reports bounds instead of cells. Fields: sheet, bounds, count. */
28
+ onBulkWritten?: SheetEventHandler;
29
+ /** `before-selection` (cancellable): The selection is about to change. Fields: sheet, from, to. */
30
+ onBeforeSelection?: SheetEventHandler;
31
+ /** `selection-changed`: The selection changed. Fields: sheet, from, to. */
32
+ onSelectionChanged?: SheetEventHandler;
33
+ /** `cell-enter`: The active cell moved onto a cell. Fields: sheet, row, col. */
34
+ onCellEnter?: SheetEventHandler;
35
+ /** `cell-leave`: The active cell left a cell. Fields: sheet, row, col. */
36
+ onCellLeave?: SheetEventHandler;
37
+ /** `cell-click`: A click landed on a cell or header. The hit test is included. Fields: sheet, hit, originalEvent. */
38
+ onCellClick?: SheetEventHandler;
39
+ /** `cell-double-click` (cancellable): A double click landed on the grid. Cancelling stops the edit it would start. Fields: sheet, hit, originalEvent. */
40
+ onCellDoubleClick?: SheetEventHandler;
41
+ /** `tab-click`: A sheet tab was clicked. Fields: sheet, index. */
42
+ onTabClick?: SheetEventHandler;
43
+ /** `tab-double-click`: A sheet tab was double clicked. Fields: sheet, index. */
44
+ onTabDoubleClick?: SheetEventHandler;
45
+ /** `before-edit` (cancellable): A cell editor is about to open. Fields: sheet, row, col, initial, origin. */
46
+ onBeforeEdit?: SheetEventHandler;
47
+ /** `edit-started`: The cell editor opened. Fields: sheet, row, col, text, origin. */
48
+ onEditStarted?: SheetEventHandler;
49
+ /** `edit-input`: The text in the editor changed. Fields: sheet, row, col, text. */
50
+ onEditInput?: SheetEventHandler;
51
+ /** `before-commit` (cancellable): The editor is about to store its text. Set `text` to replace it; cancelling keeps the editor open. Fields: sheet, row, col, text. */
52
+ onBeforeCommit?: SheetEventHandler;
53
+ /** `edit-ended`: The editor closed. Fields: sheet, row, col, committed. */
54
+ onEditEnded?: SheetEventHandler;
55
+ /** `editor-status`: Editor status moved between ready, enter and edit. Fields: from, to. */
56
+ onEditorStatus?: SheetEventHandler;
57
+ /** `before-comment-change` (cancellable): A threaded comment is about to change. Fields: sheet. */
58
+ onBeforeCommentChange?: SheetEventHandler;
59
+ /** `comment-changed`: A threaded comment changed. Fields: sheet. */
60
+ onCommentChanged?: SheetEventHandler;
61
+ /** `before-mention` (cancellable): The list of people to mention is about to open. Cancel it and @ stays plain text. Fields: query. */
62
+ onBeforeMention?: SheetEventHandler;
63
+ /** `mentioned`: A person was mentioned. Fields: person. */
64
+ onMentioned?: SheetEventHandler;
65
+ /** `before-copy` (cancellable): Copy or cut is about to run. Fields: sheet, ranges, cut. */
66
+ onBeforeCopy?: SheetEventHandler;
67
+ /** `after-copy`: Copy or cut finished. Fields: sheet, ranges, cut. */
68
+ onAfterCopy?: SheetEventHandler;
69
+ /** `before-paste` (cancellable): Paste is about to run. `text` is the plain text on the clipboard. Fields: sheet, ranges, text. */
70
+ onBeforePaste?: SheetEventHandler;
71
+ /** `after-paste`: Paste finished. Fields: sheet, ranges, text. */
72
+ onAfterPaste?: SheetEventHandler;
73
+ /** `before-active-sheet` (cancellable): The active sheet is about to change. Fields: from, to. */
74
+ onBeforeActiveSheet?: SheetEventHandler;
75
+ /** `active-sheet-changed`: The active sheet changed. Fields: from, to. */
76
+ onActiveSheetChanged?: SheetEventHandler;
77
+ /** `sheet-added`: A sheet was added or duplicated. Fields: sheet. */
78
+ onSheetAdded?: SheetEventHandler;
79
+ /** `before-sheet-remove` (cancellable): A sheet is about to be deleted. Fields: sheet. */
80
+ onBeforeSheetRemove?: SheetEventHandler;
81
+ /** `sheet-removed`: A sheet was deleted. Fields: name. */
82
+ onSheetRemoved?: SheetEventHandler;
83
+ /** `before-sheet-rename` (cancellable): A sheet is about to be renamed. Fields: sheet, from, to. */
84
+ onBeforeSheetRename?: SheetEventHandler;
85
+ /** `sheet-renamed`: A sheet was renamed. Fields: sheet, from, to. */
86
+ onSheetRenamed?: SheetEventHandler;
87
+ /** `before-sheet-move` (cancellable): A sheet is about to move. Fields: sheet, from, to. */
88
+ onBeforeSheetMove?: SheetEventHandler;
89
+ /** `sheet-moved`: A sheet moved. Fields: sheet, from, to. */
90
+ onSheetMoved?: SheetEventHandler;
91
+ /** `before-structure` (cancellable): Rows or columns are about to be inserted or deleted. Fields: sheet, label. */
92
+ onBeforeStructure?: SheetEventHandler;
93
+ /** `structure-changed`: Rows or columns were inserted or deleted. Fields: sheet, label, reason. */
94
+ onStructureChanged?: SheetEventHandler;
95
+ /** `axis-resized`: Row or column sizes or hidden state changed. Fields: sheet, axis, indexes. */
96
+ onAxisResized?: SheetEventHandler;
97
+ /** `before-sort` (cancellable): A sort is about to run. Fields: sheet. */
98
+ onBeforeSort?: SheetEventHandler;
99
+ /** `range-sorting`: A sort is working out its order; set `info.compareFunction` to compare two cell values your own way. Fields: sheet, range, info. */
100
+ onRangeSorting?: SheetEventHandler;
101
+ /** `sorted`: A sort finished. Fields: sheet, reason. */
102
+ onSorted?: SheetEventHandler;
103
+ /** `before-filter` (cancellable): A filter is about to change, from the API or a filter menu. Fields: sheet. */
104
+ onBeforeFilter?: SheetEventHandler;
105
+ /** `filtered`: A filter was applied or cleared. Fields: sheet, reason. */
106
+ onFiltered?: SheetEventHandler;
107
+ /** `before-fill` (cancellable): A fill drag is about to write its cells. Fields: sheet, from, to, mode. */
108
+ onBeforeFill?: SheetEventHandler;
109
+ /** `filled`: A fill drag finished. Fields: sheet, from, to, mode. */
110
+ onFilled?: SheetEventHandler;
111
+ /** `before-drag-merge` (cancellable): A drag on the merge grip is about to merge cells. Fields: sheet, range. */
112
+ onBeforeDragMerge?: SheetEventHandler;
113
+ /** `drag-merged`: A drag on the merge grip merged cells. Fields: sheet, range. */
114
+ onDragMerged?: SheetEventHandler;
115
+ /** `before-move` (cancellable): Dragging the selection border is about to move or copy cells. Fields: sheet, drag. */
116
+ onBeforeMove?: SheetEventHandler;
117
+ /** `cells-moved`: A drag moved or copied cells. Fields: sheet, drag. */
118
+ onCellsMoved?: SheetEventHandler;
119
+ /** `validation-failed`: Text entered in the editor breaks the cell's data validation rule. Fields: sheet, row, col, text, rule. */
120
+ onValidationFailed?: SheetEventHandler;
121
+ /** `calc-progress`: A calculation slice finished on a large workbook. Fields: remaining, total. */
122
+ onCalcProgress?: SheetEventHandler;
123
+ /** `calc-end`: Calculation finished and all values are current. */
124
+ onCalcEnd?: SheetEventHandler;
125
+ /** `before-zoom` (cancellable): The zoom is about to change. Set `zoom` to clamp it, or cancel. Fields: from, zoom. */
126
+ onBeforeZoom?: SheetEventHandler;
127
+ /** `view-changed`: The zoom changed. Fields: zoom. */
128
+ onViewChanged?: SheetEventHandler;
129
+ /** `scrolled`: The grid scrolled. Fields: x, y, topRow, leftCol. */
130
+ onScrolled?: SheetEventHandler;
131
+ /** `object-selected`: The selected chart, shape or picture changed. Fields: object. */
132
+ onObjectSelected?: SheetEventHandler;
133
+ /** `menu-opening` (cancellable): A context menu is about to open. `items` can be edited in place. Fields: area, items, x, y, hit. */
134
+ onMenuOpening?: SheetEventHandler;
135
+ /** `command-executed`: A named command ran. Fields: name, args, result. */
136
+ onCommandExecuted?: SheetEventHandler;
137
+ /** `invalid-operation`: An action was refused, for example by protection or a listener. Fields: action, reason. */
138
+ onInvalidOperation?: SheetEventHandler;
139
+ /** `before-print` (cancellable): A print or PDF job started through the API is about to run. Fields: sheets. */
140
+ onBeforePrint?: SheetEventHandler;
141
+ /** `theme-changed`: The workbook theme changed. Fields: theme. */
142
+ onThemeChanged?: SheetEventHandler;
143
+ /** `user-changed`: The current user changed. Fields: user. */
144
+ onUserChanged?: SheetEventHandler;
145
+ /** `presence-changed`: Someone started or stopped editing a range. Fields: userId, presence. */
146
+ onPresenceChanged?: SheetEventHandler;
147
+ /** `workbook-loaded`: A JSON model or document replaced the workbook contents. Fields: source. */
148
+ onWorkbookLoaded?: SheetEventHandler;
149
+ }
150
+
151
+ export interface SheetProps extends SheetEventProps {
152
+ /**
153
+ * Given to `mountWorkbook`. After mount it is compared by value and only the changed keys go to
154
+ * `wb.setOptions`; a removed key goes back to its default. `data` and `sheets` are initial values only.
155
+ */
156
+ options?: SheetOptions;
157
+ /** Called once with the workbook after it mounted and the event props are subscribed. */
158
+ onReady?: (workbook: SheetsWorkbook) => void;
159
+ /** A mount that failed, or an option `setOptions` refused. Without it the error goes to console.error. */
160
+ onError?: (error: unknown) => void;
161
+ /** Class of the element the workbook fills. */
162
+ className?: string;
163
+ /** Style of that element. It is 100% wide and high by default, so its container needs a height. */
164
+ style?: CSSProperties;
165
+ }
166
+
167
+ /** What a ref on <Sheet> gives. */
168
+ export interface SheetRef {
169
+ /** The mounted workbook, or null before onReady and after unmount. */
170
+ readonly workbook: SheetsWorkbook | null;
171
+ /** `workbook.openFile`: opens an xlsx or csv file. Throws before mount. */
172
+ openFile(file: File | Blob): Promise<void>;
173
+ /** `workbook.saveXlsx`: writes the workbook as xlsx to a sink. Throws before mount. */
174
+ saveXlsx(sink: { write: (bytes: Uint8Array) => Promise<any> }): Promise<void>;
175
+ }
176
+
177
+ export const Sheet: ForwardRefExoticComponent<SheetProps & RefAttributes<SheetRef>>;
178
+
179
+ /** 'cells-changed' -> 'onCellsChanged'. */
180
+ export function eventProp(name: string): string;
181
+ /** Prop name to event name, for every event in the catalog. */
182
+ export const EVENT_PROPS: Record<string, string>;
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@8sheets/react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "license": "SEE LICENSE IN LICENSE.md",
5
+ "homepage": "https://8sheets.com",
6
+ "author": "8cells",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "keywords": [
11
+ "spreadsheet",
12
+ "excel",
13
+ "xlsx",
14
+ "grid",
15
+ "data-grid",
16
+ "spreadsheet-component",
17
+ "workbook",
18
+ "formulas",
19
+ "csv",
20
+ "pivot-table",
21
+ "charts",
22
+ "react",
23
+ "react-component"
24
+ ],
25
+ "type": "module",
26
+ "sideEffects": false,
27
+ "description": "React component for 8sheets, the Excel-compatible spreadsheet: <Sheet> with typed props, events and ref.",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./index.d.ts",
31
+ "default": "./sheet.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "main": "./sheet.js",
36
+ "types": "./index.d.ts",
37
+ "files": [
38
+ "sheet.js",
39
+ "index.d.ts"
40
+ ],
41
+ "peerDependencies": {
42
+ "react": ">=18",
43
+ "@8sheets/core": "1.0.0"
44
+ }
45
+ }
package/sheet.js ADDED
@@ -0,0 +1,184 @@
1
+ 'use client';
2
+ // <Sheet>: an 8sheets workbook as a React component (React 18 and 19). See README.md.
3
+ import { createElement, forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef } from 'react';
4
+ import { EVENTS, mountWorkbook } from '@8sheets/core';
5
+
6
+ /** Event name to prop name: 'cells-changed' -> 'onCellsChanged'. */
7
+ export const eventProp = (name) => 'on' + name.replace(/(^|-)([a-z])/g, (_, __, ch) => ch.toUpperCase());
8
+
9
+ /** Prop name to event name, for every event in the 8sheets catalog. */
10
+ export const EVENT_PROPS = Object.fromEntries(Object.keys(EVENTS).map((name) => [eventProp(name), name]));
11
+
12
+ // useLayoutEffect warns during server rendering in React 18; neither runs there.
13
+ const useClientLayoutEffect = typeof document === 'undefined' ? useEffect : useLayoutEffect;
14
+
15
+ const isPlain = (v) => v !== null && typeof v === 'object' && (Array.isArray(v) || Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
16
+
17
+ /** Equal by value through plain objects and arrays, by identity otherwise (elements, functions, typed arrays). */
18
+ function same(a, b) {
19
+ if (Object.is(a, b)) return true;
20
+ if (!isPlain(a) || !isPlain(b) || Array.isArray(a) !== Array.isArray(b)) return false;
21
+ const ka = Object.keys(a);
22
+ if (ka.length !== Object.keys(b).length) return false;
23
+ return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && same(a[k], b[k]));
24
+ }
25
+
26
+ // Act only when the workbook is made, like React's defaultValue: later values are ignored, and `data`,
27
+ // which can be large, is never compared.
28
+ const INITIAL_ONLY = new Set(['data', 'sheets']);
29
+
30
+ /** A copy of plain objects and arrays, so a value changed in place later still compares as changed. */
31
+ const snapshot = (v) => (Array.isArray(v) ? v.map(snapshot) : isPlain(v) ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, snapshot(x)])) : v);
32
+
33
+ /** The options that can change after mount, as copies. */
34
+ const liveOptions = (options) => Object.fromEntries(Object.entries(options ?? {}).filter(([key]) => !INITIAL_ONLY.has(key)).map(([key, v]) => [key, snapshot(v)]));
35
+
36
+ /**
37
+ * Sends the options that differ from what the workbook has (`state.applied`). A key left out of `next` goes
38
+ * as undefined, which `setOptions` takes as its default; `setOptions` merges `parts` name by name, so a part
39
+ * left out of a `parts` that is still given goes as undefined too, and shows again. When `setOptions` refuses
40
+ * the patch, each key goes on its own, so the others still apply. A refused key is reported once and left
41
+ * out (`state.refused`) until its value changes.
42
+ */
43
+ function syncOptionsTo(wb, next, state, report) {
44
+ const patch = {};
45
+ for (const key of new Set([...Object.keys(state.applied), ...Object.keys(next)])) {
46
+ if (INITIAL_ONLY.has(key)) continue;
47
+ if (same(state.applied[key], next[key])) state.refused.delete(key);
48
+ else if (!(state.refused.has(key) && same(state.refused.get(key), next[key]))) patch[key] = next[key];
49
+ }
50
+ const keys = Object.keys(patch);
51
+ if (keys.length === 0) return;
52
+ if (isPlain(patch.parts) && isPlain(state.applied.parts)) {
53
+ const parts = { ...patch.parts };
54
+ for (const name of Object.keys(state.applied.parts)) if (!(name in parts)) parts[name] = undefined;
55
+ patch.parts = parts;
56
+ }
57
+ const took = (key) => {
58
+ if (next[key] === undefined) delete state.applied[key];
59
+ else state.applied[key] = snapshot(next[key]);
60
+ state.refused.delete(key);
61
+ };
62
+ try {
63
+ wb.setOptions(patch);
64
+ keys.forEach(took);
65
+ } catch {
66
+ // setOptions applies nothing when one key is refused: send each key on its own.
67
+ for (const key of keys) {
68
+ try {
69
+ wb.setOptions({ [key]: patch[key] });
70
+ took(key);
71
+ } catch (err) {
72
+ state.refused.set(key, snapshot(next[key]));
73
+ report(err);
74
+ }
75
+ }
76
+ }
77
+ }
78
+
79
+ const report = (props, err) => {
80
+ if (props.onError) props.onError(err);
81
+ else console.error(err);
82
+ };
83
+
84
+ /**
85
+ * An 8sheets workbook that fills its container. See README.md for props, events and the ref handle.
86
+ */
87
+ export const Sheet = forwardRef(function Sheet(props, ref) {
88
+ const elRef = useRef(null);
89
+ const wbRef = useRef(null);
90
+ const propsRef = useRef(props);
91
+ const optionsRef = useRef({ applied: {}, refused: new Map() }); // the options the workbook has, and those it refused
92
+ const subsRef = useRef(new Map()); // event name -> unsubscribe
93
+ const chainRef = useRef(Promise.resolve()); // mounts on this element run one after another
94
+
95
+ // Handlers are read through this ref, so a new function each render needs no re-subscription.
96
+ useClientLayoutEffect(() => {
97
+ propsRef.current = props;
98
+ });
99
+
100
+ /** Subscribes to the events that have a handler prop now, and drops the rest. */
101
+ const syncEvents = (wb) => {
102
+ const p = propsRef.current;
103
+ const subs = subsRef.current;
104
+ for (const [prop, name] of Object.entries(EVENT_PROPS)) {
105
+ const wanted = typeof p[prop] === 'function';
106
+ if (wanted && !subs.has(name)) subs.set(name, wb.events.on(name, (e) => propsRef.current[prop]?.(e)));
107
+ else if (!wanted && subs.has(name)) {
108
+ subs.get(name)();
109
+ subs.delete(name);
110
+ }
111
+ }
112
+ };
113
+
114
+ /** Sends the options that changed since the workbook last took them. */
115
+ const syncOptions = (wb) => syncOptionsTo(wb, propsRef.current.options ?? {}, optionsRef.current, (err) => report(propsRef.current, err));
116
+
117
+ useEffect(() => {
118
+ const el = elRef.current;
119
+ let cancelled = false;
120
+ let wb = null;
121
+ const run = chainRef.current.then(async () => {
122
+ if (cancelled) return;
123
+ const given = propsRef.current.options ?? {};
124
+ const applied = liveOptions(given); // what the mount takes, copied before it starts
125
+ let mounted;
126
+ try {
127
+ mounted = await mountWorkbook(el, given);
128
+ } catch (err) {
129
+ if (!cancelled) report(propsRef.current, err);
130
+ return;
131
+ }
132
+ if (cancelled) {
133
+ mounted.destroy();
134
+ return;
135
+ }
136
+ wb = mounted;
137
+ wbRef.current = wb;
138
+ optionsRef.current = { applied, refused: new Map() };
139
+ syncEvents(wb);
140
+ syncOptions(wb); // options that changed while the mount was pending
141
+ propsRef.current.onReady?.(wb);
142
+ });
143
+ chainRef.current = run;
144
+ return () => {
145
+ cancelled = true;
146
+ for (const off of subsRef.current.values()) off();
147
+ subsRef.current.clear();
148
+ if (wb) {
149
+ wbRef.current = null;
150
+ wb.destroy();
151
+ }
152
+ };
153
+ }, []);
154
+
155
+ // After every render: follow handler props that appeared or went, and options that changed.
156
+ useEffect(() => {
157
+ const wb = wbRef.current;
158
+ if (!wb) return;
159
+ syncEvents(wb);
160
+ syncOptions(wb);
161
+ });
162
+
163
+ useImperativeHandle(ref, () => {
164
+ const need = () => {
165
+ if (!wbRef.current) throw new Error('The workbook is not mounted yet; wait for onReady');
166
+ return wbRef.current;
167
+ };
168
+ return {
169
+ get workbook() {
170
+ return wbRef.current;
171
+ },
172
+ openFile: (file) => need().openFile(file),
173
+ saveXlsx: (sink) => need().saveXlsx(sink),
174
+ };
175
+ }, []);
176
+
177
+ return createElement('div', {
178
+ ref: elRef,
179
+ className: props.className,
180
+ style: { display: 'block', width: '100%', height: '100%', minHeight: 0, ...props.style },
181
+ });
182
+ });
183
+
184
+ Sheet.displayName = 'Sheet';