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