@casualoffice/sheets 0.9.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.
Files changed (92) hide show
  1. package/LICENSE +200 -0
  2. package/dist/embed/embed-runtime.js +537 -0
  3. package/dist/embed/embed.html +29 -0
  4. package/dist/embed/parser.worker.js +48474 -0
  5. package/dist/embed.cjs +225 -0
  6. package/dist/embed.cjs.map +1 -0
  7. package/dist/embed.d.cts +100 -0
  8. package/dist/embed.d.ts +100 -0
  9. package/dist/embed.js +204 -0
  10. package/dist/embed.js.map +1 -0
  11. package/dist/index.cjs +1549 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +9 -0
  14. package/dist/index.d.ts +9 -0
  15. package/dist/index.js +1530 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/parser.worker.cjs +48469 -0
  18. package/dist/parser.worker.cjs.map +1 -0
  19. package/dist/parser.worker.js +48474 -0
  20. package/dist/parser.worker.js.map +1 -0
  21. package/dist/protocol--KyBQUjU.d.cts +171 -0
  22. package/dist/protocol-cEzy7S0i.d.ts +171 -0
  23. package/dist/sheets.cjs +677 -0
  24. package/dist/sheets.cjs.map +1 -0
  25. package/dist/sheets.d.cts +177 -0
  26. package/dist/sheets.d.ts +177 -0
  27. package/dist/sheets.js +658 -0
  28. package/dist/sheets.js.map +1 -0
  29. package/dist/signing.cjs +706 -0
  30. package/dist/signing.cjs.map +1 -0
  31. package/dist/signing.d.cts +141 -0
  32. package/dist/signing.d.ts +141 -0
  33. package/dist/signing.js +683 -0
  34. package/dist/signing.js.map +1 -0
  35. package/dist/styles.cjs +10 -0
  36. package/dist/styles.cjs.map +1 -0
  37. package/dist/styles.d.cts +2 -0
  38. package/dist/styles.d.ts +2 -0
  39. package/dist/styles.js +8 -0
  40. package/dist/styles.js.map +1 -0
  41. package/dist/types-s_O0u6Cg.d.cts +90 -0
  42. package/dist/types-s_O0u6Cg.d.ts +90 -0
  43. package/dist/univer.cjs +220 -0
  44. package/dist/univer.cjs.map +1 -0
  45. package/dist/univer.d.cts +60 -0
  46. package/dist/univer.d.ts +60 -0
  47. package/dist/univer.js +187 -0
  48. package/dist/univer.js.map +1 -0
  49. package/dist/xlsx.cjs +3388 -0
  50. package/dist/xlsx.cjs.map +1 -0
  51. package/dist/xlsx.d.cts +383 -0
  52. package/dist/xlsx.d.ts +383 -0
  53. package/dist/xlsx.js +3383 -0
  54. package/dist/xlsx.js.map +1 -0
  55. package/package.json +293 -0
  56. package/src/embed/EmbedHostTransport.ts +226 -0
  57. package/src/embed/EmbedTransport.ts +323 -0
  58. package/src/embed/EmbedTransport.unit.test.ts +161 -0
  59. package/src/embed/index.ts +40 -0
  60. package/src/embed/protocol.ts +258 -0
  61. package/src/embed-runtime/embed.html +29 -0
  62. package/src/embed-runtime/index.tsx +440 -0
  63. package/src/index.ts +16 -0
  64. package/src/sheets/CasualSheets.tsx +319 -0
  65. package/src/sheets/CasualSheetsIframe.tsx +220 -0
  66. package/src/sheets/api.ts +108 -0
  67. package/src/sheets/index.ts +11 -0
  68. package/src/signing/SigningPane.tsx +374 -0
  69. package/src/signing/SigningProvider.tsx +126 -0
  70. package/src/signing/captures.tsx +316 -0
  71. package/src/signing/controller.ts +151 -0
  72. package/src/signing/controller.unit.test.ts +133 -0
  73. package/src/signing/index.ts +44 -0
  74. package/src/signing/types.ts +89 -0
  75. package/src/styles.ts +16 -0
  76. package/src/univer/index.ts +17 -0
  77. package/src/univer/lazy-plugins.ts +280 -0
  78. package/src/xlsx/_perf.ts +14 -0
  79. package/src/xlsx/_snapshot-constants.ts +15 -0
  80. package/src/xlsx/comments-resource.ts +209 -0
  81. package/src/xlsx/constants.ts +9 -0
  82. package/src/xlsx/data-validation-resource.ts +219 -0
  83. package/src/xlsx/import.ts +35 -0
  84. package/src/xlsx/index.ts +40 -0
  85. package/src/xlsx/page-setup-resource.ts +205 -0
  86. package/src/xlsx/parse-impl.ts +418 -0
  87. package/src/xlsx/parse-in-worker.ts +82 -0
  88. package/src/xlsx/parser.worker.ts +39 -0
  89. package/src/xlsx/passthrough-resource.ts +175 -0
  90. package/src/xlsx/pivot-passthrough.ts +359 -0
  91. package/src/xlsx/style-mapping.ts +171 -0
  92. package/src/xlsx/tables-resource.ts +211 -0
package/dist/sheets.js ADDED
@@ -0,0 +1,658 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // src/sheets/CasualSheets.tsx
6
+ import { useEffect, useRef } from "react";
7
+ import {
8
+ ICommandService,
9
+ LocaleType,
10
+ LogLevel,
11
+ ThemeService as ThemeService2,
12
+ Univer,
13
+ UniverInstanceType
14
+ } from "@univerjs/core";
15
+ import { FUniver } from "@univerjs/core/facade";
16
+ import { defaultTheme } from "@univerjs/themes";
17
+ import { UniverRenderEnginePlugin } from "@univerjs/engine-render";
18
+ import { UniverFormulaEnginePlugin } from "@univerjs/engine-formula";
19
+ import { UniverUIPlugin } from "@univerjs/ui";
20
+ import { UniverDocsPlugin } from "@univerjs/docs";
21
+ import { UniverDocsUIPlugin } from "@univerjs/docs-ui";
22
+ import { UniverSheetsPlugin } from "@univerjs/sheets";
23
+ import { UniverSheetsUIPlugin } from "@univerjs/sheets-ui";
24
+ import { UniverSheetsFormulaPlugin } from "@univerjs/sheets-formula";
25
+ import { UniverSheetsFormulaUIPlugin } from "@univerjs/sheets-formula-ui";
26
+ import { UniverSheetsNumfmtPlugin } from "@univerjs/sheets-numfmt";
27
+ import { UniverSheetsNumfmtUIPlugin } from "@univerjs/sheets-numfmt-ui";
28
+
29
+ // src/sheets/api.ts
30
+ import "@univerjs/sheets/facade";
31
+ import { ThemeService } from "@univerjs/core";
32
+ function createCasualSheetsAPI(univerAPI) {
33
+ return {
34
+ univer: univerAPI,
35
+ getSnapshot() {
36
+ return univerAPI.getActiveWorkbook()?.save() ?? null;
37
+ },
38
+ loadSnapshot(data) {
39
+ const current = univerAPI.getActiveWorkbook();
40
+ if (current) univerAPI.disposeUnit(current.getId());
41
+ univerAPI.createWorkbook(data);
42
+ },
43
+ getSelection() {
44
+ const wb = univerAPI.getActiveWorkbook();
45
+ const range = wb?.getActiveRange();
46
+ if (!wb || !range) return null;
47
+ return {
48
+ unitId: wb.getId(),
49
+ sheetId: wb.getActiveSheet().getSheetId(),
50
+ range: range.getRange()
51
+ };
52
+ },
53
+ executeCommand(id, params) {
54
+ return univerAPI.executeCommand(id, params);
55
+ },
56
+ setTheme(appearance) {
57
+ const dark = appearance === "dark";
58
+ const injector = univerAPI._injector;
59
+ const themeService = injector?.get(ThemeService);
60
+ if (themeService && themeService.darkMode !== dark) themeService.setDarkMode(dark);
61
+ }
62
+ };
63
+ }
64
+
65
+ // src/univer/lazy-plugins.ts
66
+ var LOADERS = {
67
+ cf: async () => {
68
+ const [base, ui] = await Promise.all([
69
+ import("@univerjs/sheets-conditional-formatting"),
70
+ import("@univerjs/sheets-conditional-formatting-ui")
71
+ ]);
72
+ return [
73
+ [base.UniverSheetsConditionalFormattingPlugin],
74
+ [ui.UniverSheetsConditionalFormattingUIPlugin]
75
+ ];
76
+ },
77
+ dv: async () => {
78
+ const [base, ui] = await Promise.all([
79
+ import("@univerjs/sheets-data-validation"),
80
+ import("@univerjs/sheets-data-validation-ui")
81
+ ]);
82
+ return [
83
+ [base.UniverSheetsDataValidationPlugin],
84
+ [ui.UniverSheetsDataValidationUIPlugin]
85
+ ];
86
+ },
87
+ hyperlink: async () => {
88
+ const [base, ui] = await Promise.all([
89
+ import("@univerjs/sheets-hyper-link"),
90
+ import("@univerjs/sheets-hyper-link-ui")
91
+ ]);
92
+ return [
93
+ [base.UniverSheetsHyperLinkPlugin],
94
+ [ui.UniverSheetsHyperLinkUIPlugin]
95
+ ];
96
+ },
97
+ note: async () => {
98
+ const [base, ui] = await Promise.all([
99
+ import("@univerjs/sheets-note"),
100
+ import("@univerjs/sheets-note-ui")
101
+ ]);
102
+ return [[base.UniverSheetsNotePlugin], [ui.UniverSheetsNoteUIPlugin]];
103
+ },
104
+ table: async () => {
105
+ const [base, ui] = await Promise.all([
106
+ import("@univerjs/sheets-table"),
107
+ import("@univerjs/sheets-table-ui")
108
+ ]);
109
+ return [[base.UniverSheetsTablePlugin], [ui.UniverSheetsTableUIPlugin]];
110
+ },
111
+ threadComment: async () => {
112
+ const [tc, tcUi, sheetsTc, sheetsTcUi] = await Promise.all([
113
+ import("@univerjs/thread-comment"),
114
+ import("@univerjs/thread-comment-ui"),
115
+ import("@univerjs/sheets-thread-comment"),
116
+ import("@univerjs/sheets-thread-comment-ui")
117
+ ]);
118
+ return [
119
+ [tc.UniverThreadCommentPlugin],
120
+ [tcUi.UniverThreadCommentUIPlugin],
121
+ [sheetsTc.UniverSheetsThreadCommentPlugin],
122
+ [sheetsTcUi.UniverSheetsThreadCommentUIPlugin]
123
+ ];
124
+ },
125
+ drawing: async () => {
126
+ const [d, dUi, sd, sdUi] = await Promise.all([
127
+ import("@univerjs/drawing"),
128
+ import("@univerjs/drawing-ui"),
129
+ import("@univerjs/sheets-drawing"),
130
+ import("@univerjs/sheets-drawing-ui"),
131
+ // Side-effect imports: install FWorksheet.insertImage / getImages /
132
+ // updateImages on the facade prototype. Without these, code that
133
+ // reaches in via the FUniver facade (e2e specs, future shell glue)
134
+ // sees an undefined method even though the plugin is registered.
135
+ import("@univerjs/sheets-drawing/facade"),
136
+ import("@univerjs/sheets-drawing-ui/facade")
137
+ ]);
138
+ return [
139
+ [d.UniverDrawingPlugin],
140
+ [dUi.UniverDrawingUIPlugin],
141
+ [sd.UniverSheetsDrawingPlugin],
142
+ [sdUi.UniverSheetsDrawingUIPlugin]
143
+ ];
144
+ },
145
+ sort: async () => {
146
+ const [base, ui] = await Promise.all([
147
+ import("@univerjs/sheets-sort"),
148
+ import("@univerjs/sheets-sort-ui")
149
+ ]);
150
+ return [[base.UniverSheetsSortPlugin], [ui.UniverSheetsSortUIPlugin]];
151
+ },
152
+ filter: async () => {
153
+ const [base, ui] = await Promise.all([
154
+ import("@univerjs/sheets-filter"),
155
+ import("@univerjs/sheets-filter-ui")
156
+ ]);
157
+ return [[base.UniverSheetsFilterPlugin], [ui.UniverSheetsFilterUIPlugin]];
158
+ },
159
+ findReplace: async () => {
160
+ const [base, sheets] = await Promise.all([
161
+ import("@univerjs/find-replace"),
162
+ import("@univerjs/sheets-find-replace")
163
+ ]);
164
+ return [[base.UniverFindReplacePlugin], [sheets.UniverSheetsFindReplacePlugin]];
165
+ }
166
+ };
167
+ var RESOURCE_NAME_TO_GROUP = {
168
+ SHEET_CONDITIONAL_FORMATTING_PLUGIN: "cf",
169
+ SHEET_DATA_VALIDATION_PLUGIN: "dv",
170
+ SHEET_HYPER_LINK_PLUGIN: "hyperlink",
171
+ SHEET_NOTE_PLUGIN: "note",
172
+ SHEET_TABLE_PLUGIN: "table",
173
+ SHEET_THREAD_COMMENT_BASE_PLUGIN: "threadComment",
174
+ SHEET_DRAWING_PLUGIN: "drawing",
175
+ SHEET_SORT_PLUGIN: "sort",
176
+ SHEET_FILTER_PLUGIN: "filter"
177
+ };
178
+ var loaded = /* @__PURE__ */ new Set();
179
+ var inflight = /* @__PURE__ */ new Map();
180
+ var currentUniver = null;
181
+ function setUniverForLazyLoad(univer) {
182
+ currentUniver = univer;
183
+ }
184
+ function ensurePlugin(univer, group) {
185
+ if (loaded.has(group)) return Promise.resolve();
186
+ const existing = inflight.get(group);
187
+ if (existing) return existing;
188
+ const loader = LOADERS[group];
189
+ if (!loader) return Promise.resolve();
190
+ const p = loader().then((plugins) => {
191
+ for (const [PluginCtor, config] of plugins) {
192
+ univer.registerPlugin(PluginCtor, config);
193
+ }
194
+ loaded.add(group);
195
+ inflight.delete(group);
196
+ });
197
+ inflight.set(group, p);
198
+ return p;
199
+ }
200
+ async function eagerLoadForSnapshot(univer, snapshot) {
201
+ const groups = /* @__PURE__ */ new Set();
202
+ const resources = snapshot.resources ?? [];
203
+ for (const r of resources) {
204
+ const g = RESOURCE_NAME_TO_GROUP[r.name];
205
+ if (g) groups.add(g);
206
+ }
207
+ if (snapshotHasHyperlinks(snapshot)) groups.add("hyperlink");
208
+ await Promise.all(Array.from(groups).map((g) => ensurePlugin(univer, g)));
209
+ }
210
+ function idleLoadAll(univer) {
211
+ const groups = Object.keys(LOADERS);
212
+ schedule(() => {
213
+ for (const g of groups) {
214
+ void ensurePlugin(univer, g);
215
+ }
216
+ });
217
+ }
218
+ function schedule(fn) {
219
+ const ric = globalThis.requestIdleCallback;
220
+ if (ric) ric(fn, { timeout: 500 });
221
+ else setTimeout(fn, 0);
222
+ }
223
+ function snapshotHasHyperlinks(snapshot) {
224
+ const sheetOrder = snapshot.sheetOrder ?? [];
225
+ for (const sid of sheetOrder) {
226
+ const sheet = snapshot.sheets?.[sid];
227
+ if (!sheet?.cellData) continue;
228
+ const cellData = sheet.cellData;
229
+ for (const r of Object.keys(cellData)) {
230
+ const row = cellData[r];
231
+ for (const c of Object.keys(row)) {
232
+ const ranges = row[c]?.p?.body?.customRanges ?? [];
233
+ if (ranges.some((cr) => cr.rangeType === 0)) return true;
234
+ }
235
+ }
236
+ }
237
+ return false;
238
+ }
239
+
240
+ // src/sheets/CasualSheets.tsx
241
+ import { jsx } from "react/jsx-runtime";
242
+ var DEFAULT_STYLE = {
243
+ width: "100%",
244
+ height: "100%",
245
+ position: "relative"
246
+ };
247
+ var DEFAULT_UI = {
248
+ header: false,
249
+ toolbar: false,
250
+ footer: false,
251
+ contextMenu: true
252
+ };
253
+ function CasualSheets({
254
+ initialData,
255
+ onReady,
256
+ onChange,
257
+ onChangeDebounceMs = 400,
258
+ lazyPlugins = true,
259
+ locale = LocaleType.EN_US,
260
+ locales,
261
+ logLevel = LogLevel.WARN,
262
+ ui,
263
+ theme = defaultTheme,
264
+ appearance = "light",
265
+ style,
266
+ className,
267
+ testId = "casual-sheets"
268
+ }) {
269
+ const hostRef = useRef(null);
270
+ const onChangeRef = useRef(onChange);
271
+ onChangeRef.current = onChange;
272
+ const hasOnChange = useRef(!!onChange).current;
273
+ const apiRef = useRef(null);
274
+ useEffect(() => {
275
+ const container = hostRef.current;
276
+ if (!container) return;
277
+ const univer = new Univer({
278
+ theme,
279
+ locale,
280
+ locales,
281
+ logLevel
282
+ });
283
+ const uiOpts = { ...DEFAULT_UI, ...ui, container };
284
+ univer.registerPlugin(UniverRenderEnginePlugin);
285
+ univer.registerPlugin(UniverFormulaEnginePlugin);
286
+ univer.registerPlugin(UniverUIPlugin, uiOpts);
287
+ univer.registerPlugin(UniverDocsPlugin);
288
+ univer.registerPlugin(UniverDocsUIPlugin);
289
+ univer.registerPlugin(UniverSheetsPlugin);
290
+ univer.registerPlugin(UniverSheetsUIPlugin);
291
+ univer.registerPlugin(UniverSheetsFormulaPlugin);
292
+ univer.registerPlugin(UniverSheetsFormulaUIPlugin);
293
+ univer.registerPlugin(UniverSheetsNumfmtPlugin);
294
+ univer.registerPlugin(UniverSheetsNumfmtUIPlugin);
295
+ if (lazyPlugins) setUniverForLazyLoad(univer);
296
+ let cancelled = false;
297
+ let changeTimer = null;
298
+ let changeSub;
299
+ void (async () => {
300
+ if (lazyPlugins) {
301
+ await eagerLoadForSnapshot(univer, initialData);
302
+ if (cancelled) return;
303
+ }
304
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, initialData);
305
+ const api = createCasualSheetsAPI(FUniver.newAPI(univer));
306
+ apiRef.current = api;
307
+ applyAppearance(api, container, appearance);
308
+ onReady?.(api);
309
+ if (hasOnChange) {
310
+ const injector = api.univer._injector;
311
+ const cmdSvc = injector?.get(ICommandService);
312
+ changeSub = cmdSvc?.onMutationExecutedForCollab(() => {
313
+ if (changeTimer) clearTimeout(changeTimer);
314
+ changeTimer = setTimeout(() => {
315
+ const snap = api.getSnapshot();
316
+ if (snap) onChangeRef.current?.(snap);
317
+ }, onChangeDebounceMs);
318
+ });
319
+ if (cancelled) changeSub?.dispose();
320
+ }
321
+ if (lazyPlugins) idleLoadAll(univer);
322
+ })();
323
+ return () => {
324
+ cancelled = true;
325
+ if (changeTimer) clearTimeout(changeTimer);
326
+ changeSub?.dispose();
327
+ apiRef.current = null;
328
+ if (lazyPlugins) setUniverForLazyLoad(null);
329
+ const toDispose = univer;
330
+ queueMicrotask(() => toDispose.dispose());
331
+ };
332
+ }, []);
333
+ useEffect(() => {
334
+ const api = apiRef.current;
335
+ const container = hostRef.current;
336
+ if (!api || !container) return;
337
+ applyAppearance(api, container, appearance);
338
+ }, [appearance]);
339
+ return /* @__PURE__ */ jsx(
340
+ "div",
341
+ {
342
+ ref: hostRef,
343
+ style: { ...DEFAULT_STYLE, ...style },
344
+ className,
345
+ "data-testid": testId
346
+ }
347
+ );
348
+ }
349
+ function applyAppearance(api, container, appearance) {
350
+ const dark = appearance === "dark";
351
+ container.classList.toggle("univer-dark", dark);
352
+ try {
353
+ const injector = api.univer._injector;
354
+ const themeService = injector?.get(ThemeService2);
355
+ if (themeService && themeService.darkMode !== dark) themeService.setDarkMode(dark);
356
+ } catch {
357
+ }
358
+ }
359
+
360
+ // src/sheets/CasualSheetsIframe.tsx
361
+ import {
362
+ forwardRef,
363
+ useCallback,
364
+ useEffect as useEffect2,
365
+ useRef as useRef2
366
+ } from "react";
367
+
368
+ // src/embed/protocol.ts
369
+ function isCasualEnvelope(value) {
370
+ if (!value || typeof value !== "object") return false;
371
+ const v = value;
372
+ return typeof v.type === "string" && v.type.startsWith("casual.") && (v.app === "docs" || v.app === "sheet") && v.v === 1 && "data" in v;
373
+ }
374
+
375
+ // src/embed/EmbedHostTransport.ts
376
+ var EmbedHostTransport = class {
377
+ constructor(opts) {
378
+ __publicField(this, "opts");
379
+ __publicField(this, "handlers", {});
380
+ __publicField(this, "boundOnMessage");
381
+ __publicField(this, "destroyed", false);
382
+ this.opts = opts;
383
+ this.boundOnMessage = this.onMessage.bind(this);
384
+ const target = opts.hostWindow ?? window;
385
+ target.addEventListener("message", this.boundOnMessage);
386
+ }
387
+ on(handlers) {
388
+ this.handlers = { ...this.handlers, ...handlers };
389
+ }
390
+ destroy() {
391
+ if (this.destroyed) return;
392
+ this.destroyed = true;
393
+ const target = this.opts.hostWindow ?? window;
394
+ target.removeEventListener("message", this.boundOnMessage);
395
+ }
396
+ sendHostHello(data) {
397
+ this.post("casual.hello", data);
398
+ }
399
+ sendSetViewMode(data) {
400
+ this.post("casual.command.set.viewmode", data);
401
+ }
402
+ sendSetReadOnly(data) {
403
+ this.post("casual.command.set.readonly", data);
404
+ }
405
+ sendSetTheme(data) {
406
+ this.post("casual.command.set.theme", data);
407
+ }
408
+ sendSetLocale(data) {
409
+ this.post("casual.command.set.locale", data);
410
+ }
411
+ sendCommandSave() {
412
+ this.post("casual.command.save", null);
413
+ }
414
+ sendCommandFocus() {
415
+ this.post("casual.command.focus", null);
416
+ }
417
+ /** Host → Editor: run a formatting / navigation command (bold,
418
+ * italic, undo, …) against the active selection. v0.6+. */
419
+ sendCommandExecute(data) {
420
+ this.post("casual.command.execute", data);
421
+ }
422
+ sendSignatureRequest(id, data) {
423
+ this.post("casual.signature.request", data, id);
424
+ }
425
+ sendSignatureCancel(data) {
426
+ this.post("casual.signature.cancel", data);
427
+ }
428
+ onMessage(ev) {
429
+ if (this.destroyed) return;
430
+ if (ev.origin !== this.opts.embedOrigin) return;
431
+ if (ev.source !== this.opts.iframeWindow) return;
432
+ if (!isCasualEnvelope(ev.data)) return;
433
+ if (ev.data.app !== this.opts.app) return;
434
+ void this.dispatch(ev.data);
435
+ }
436
+ async dispatch(env) {
437
+ switch (env.type) {
438
+ case "casual.ready":
439
+ this.handlers.onEditorReady?.(env.data);
440
+ return;
441
+ case "casual.load.request": {
442
+ if (!this.handlers.onLoadRequest) return;
443
+ const id = env.id ?? "";
444
+ try {
445
+ const resp = await this.handlers.onLoadRequest(env.data);
446
+ const transfer = resp.ok ? [resp.bytes] : [];
447
+ this.post("casual.load.response", resp, id, transfer);
448
+ } catch (err) {
449
+ this.post(
450
+ "casual.load.response",
451
+ {
452
+ ok: false,
453
+ code: "host_error",
454
+ message: err instanceof Error ? err.message : String(err)
455
+ },
456
+ id
457
+ );
458
+ }
459
+ return;
460
+ }
461
+ case "casual.save.request": {
462
+ if (!this.handlers.onSaveRequest) return;
463
+ const id = env.id ?? "";
464
+ try {
465
+ const resp = await this.handlers.onSaveRequest(env.data);
466
+ this.post("casual.save.response", resp, id);
467
+ } catch (err) {
468
+ this.post(
469
+ "casual.save.response",
470
+ {
471
+ ok: false,
472
+ code: "host_error",
473
+ message: err instanceof Error ? err.message : String(err)
474
+ },
475
+ id
476
+ );
477
+ }
478
+ return;
479
+ }
480
+ case "casual.selection.changed":
481
+ this.handlers.onSelectionChanged?.(env.data);
482
+ return;
483
+ case "casual.selection.format-state":
484
+ this.handlers.onSelectionFormatState?.(env.data);
485
+ return;
486
+ case "casual.telemetry.event":
487
+ this.handlers.onTelemetry?.(env.data);
488
+ return;
489
+ case "casual.signature.field.signed":
490
+ this.handlers.onSignatureFieldSigned?.(env.data);
491
+ return;
492
+ case "casual.signature.complete":
493
+ this.handlers.onSignatureComplete?.(env.data);
494
+ return;
495
+ case "casual.signature.cancel":
496
+ this.handlers.onSignatureCancel?.(env.data);
497
+ return;
498
+ case "casual.signature.request.ack":
499
+ return;
500
+ case "casual.error":
501
+ this.handlers.onError?.(env.data);
502
+ return;
503
+ default:
504
+ return;
505
+ }
506
+ }
507
+ post(type, data, id, transfer) {
508
+ const env = {
509
+ type,
510
+ app: this.opts.app,
511
+ v: 1,
512
+ data,
513
+ ...id ? { id } : {}
514
+ };
515
+ const send = this.opts.iframeWindow.postMessage.bind(
516
+ this.opts.iframeWindow
517
+ );
518
+ send(env, this.opts.embedOrigin, transfer);
519
+ }
520
+ };
521
+
522
+ // src/sheets/CasualSheetsIframe.tsx
523
+ import { jsx as jsx2 } from "react/jsx-runtime";
524
+ var DEFAULT_STYLE2 = {
525
+ width: "100%",
526
+ height: "100%",
527
+ border: "none",
528
+ display: "block"
529
+ };
530
+ var CasualSheetsIframe = forwardRef(
531
+ function CasualSheetsIframe2(props, ref) {
532
+ const {
533
+ fileSource,
534
+ docId,
535
+ viewMode = "editor",
536
+ embedBasePath = "/embed/sheets",
537
+ onSelectionChanged,
538
+ onSelectionFormatState,
539
+ onTelemetry,
540
+ onError,
541
+ style,
542
+ className,
543
+ testId = "casual-sheets-iframe"
544
+ } = props;
545
+ const iframeRef = useRef2(null);
546
+ const transportRef = useRef2(null);
547
+ const fileSourceRef = useRef2(fileSource);
548
+ fileSourceRef.current = fileSource;
549
+ const onLoad = useCallback(async (req) => {
550
+ try {
551
+ const { bytes, name, etag } = await fileSourceRef.current.open(req.docId);
552
+ return {
553
+ ok: true,
554
+ bytes,
555
+ fileName: name,
556
+ ...etag !== void 0 ? { etag } : {}
557
+ };
558
+ } catch (err) {
559
+ return {
560
+ ok: false,
561
+ code: "open_failed",
562
+ message: err instanceof Error ? err.message : String(err)
563
+ };
564
+ }
565
+ }, []);
566
+ const onSave = useCallback(
567
+ async (req) => {
568
+ try {
569
+ if (!fileSourceRef.current.save) {
570
+ return {
571
+ ok: false,
572
+ code: "save_unsupported",
573
+ message: "host fileSource does not implement save"
574
+ };
575
+ }
576
+ const opts = req.baseEtag !== void 0 ? { etag: req.baseEtag } : void 0;
577
+ const { etag } = await fileSourceRef.current.save(req.docId, req.bytes, opts);
578
+ return { ok: true, etag };
579
+ } catch (err) {
580
+ return {
581
+ ok: false,
582
+ code: "save_failed",
583
+ message: err instanceof Error ? err.message : String(err)
584
+ };
585
+ }
586
+ },
587
+ []
588
+ );
589
+ const onIframeLoad = useCallback(() => {
590
+ const iframe = iframeRef.current;
591
+ if (!iframe?.contentWindow) return;
592
+ transportRef.current?.destroy();
593
+ const transport = new EmbedHostTransport({
594
+ app: "sheet",
595
+ iframeWindow: iframe.contentWindow,
596
+ embedOrigin: window.location.origin
597
+ });
598
+ transport.on({
599
+ onLoadRequest: onLoad,
600
+ onSaveRequest: onSave,
601
+ ...onSelectionChanged ? { onSelectionChanged } : {},
602
+ ...onSelectionFormatState ? { onSelectionFormatState } : {},
603
+ ...onTelemetry ? { onTelemetry } : {},
604
+ ...onError ? { onError } : {},
605
+ onEditorReady: () => {
606
+ transport.sendHostHello({ capabilities: ["load", "save"] });
607
+ transport.sendSetViewMode({ viewMode });
608
+ }
609
+ });
610
+ transportRef.current = transport;
611
+ }, [
612
+ onLoad,
613
+ onSave,
614
+ onSelectionChanged,
615
+ onSelectionFormatState,
616
+ onTelemetry,
617
+ onError,
618
+ viewMode
619
+ ]);
620
+ useEffect2(() => {
621
+ transportRef.current?.sendSetViewMode({ viewMode });
622
+ }, [viewMode]);
623
+ useEffect2(() => {
624
+ return () => {
625
+ transportRef.current?.destroy();
626
+ transportRef.current = null;
627
+ };
628
+ }, []);
629
+ if (ref) {
630
+ const apiRef = ref;
631
+ apiRef.current = {
632
+ setViewMode: (mode) => transportRef.current?.sendSetViewMode({ viewMode: mode }),
633
+ iframe: () => iframeRef.current,
634
+ executeCommand: (command) => transportRef.current?.sendCommandExecute({ command })
635
+ };
636
+ }
637
+ const url = `${embedBasePath}/embed.html?app=sheet&docId=${encodeURIComponent(docId)}&viewMode=${viewMode}`;
638
+ return /* @__PURE__ */ jsx2(
639
+ "iframe",
640
+ {
641
+ ref: iframeRef,
642
+ src: url,
643
+ onLoad: onIframeLoad,
644
+ title: "Casual Sheets",
645
+ sandbox: "allow-scripts allow-same-origin allow-downloads allow-modals",
646
+ style: { ...DEFAULT_STYLE2, ...style },
647
+ className,
648
+ "data-testid": testId
649
+ }
650
+ );
651
+ }
652
+ );
653
+ export {
654
+ CasualSheets,
655
+ CasualSheetsIframe,
656
+ createCasualSheetsAPI
657
+ };
658
+ //# sourceMappingURL=sheets.js.map