@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/index.js ADDED
@@ -0,0 +1,1530 @@
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/signing/SigningProvider.tsx
6
+ import { createContext, useContext, useEffect, useMemo, useState } from "react";
7
+
8
+ // src/signing/controller.ts
9
+ function createSigningController(fields, mode) {
10
+ if (fields.length === 0) {
11
+ throw new Error("createSigningController: at least one field required");
12
+ }
13
+ const fieldIds = new Set(fields.map((f) => f.fieldId));
14
+ if (fieldIds.size !== fields.length) {
15
+ throw new Error("createSigningController: duplicate fieldId");
16
+ }
17
+ const signed = {};
18
+ let activeFieldIndex = nextRequiredIndex(fields, signed);
19
+ let isComplete = false;
20
+ let isCancelled = false;
21
+ const listeners = /* @__PURE__ */ new Set();
22
+ function emit() {
23
+ const snap = snapshotInternal();
24
+ for (const l of listeners) l(snap);
25
+ }
26
+ function snapshotInternal() {
27
+ return {
28
+ fields,
29
+ mode,
30
+ signed: { ...signed },
31
+ activeFieldIndex,
32
+ canComplete: allRequiredSigned(fields, signed),
33
+ isComplete,
34
+ isCancelled
35
+ };
36
+ }
37
+ return {
38
+ snapshot: snapshotInternal,
39
+ subscribe(listener) {
40
+ listeners.add(listener);
41
+ return () => {
42
+ listeners.delete(listener);
43
+ };
44
+ },
45
+ signField(payload) {
46
+ if (isComplete || isCancelled) return;
47
+ if (!fieldIds.has(payload.fieldId)) {
48
+ throw new Error(`signField: unknown fieldId ${payload.fieldId}`);
49
+ }
50
+ signed[payload.fieldId] = payload;
51
+ activeFieldIndex = nextRequiredIndex(fields, signed);
52
+ emit();
53
+ },
54
+ focusField(fieldId) {
55
+ if (isComplete || isCancelled) return;
56
+ const idx = fields.findIndex((f) => f.fieldId === fieldId);
57
+ if (idx < 0) return;
58
+ if (mode === "sequential") {
59
+ const next = nextRequiredIndex(fields, signed);
60
+ if (idx !== next) return;
61
+ }
62
+ activeFieldIndex = idx;
63
+ emit();
64
+ },
65
+ complete() {
66
+ if (!allRequiredSigned(fields, signed)) {
67
+ throw new Error("complete: required fields are still unsigned");
68
+ }
69
+ isComplete = true;
70
+ activeFieldIndex = -1;
71
+ emit();
72
+ return snapshotInternal();
73
+ },
74
+ cancel() {
75
+ if (isComplete || isCancelled) return;
76
+ isCancelled = true;
77
+ activeFieldIndex = -1;
78
+ emit();
79
+ }
80
+ };
81
+ }
82
+ function allRequiredSigned(fields, signed) {
83
+ return fields.every((f) => !f.required || signed[f.fieldId] !== void 0);
84
+ }
85
+ function nextRequiredIndex(fields, signed) {
86
+ for (let i = 0; i < fields.length; i++) {
87
+ if (fields[i].required && !signed[fields[i].fieldId]) return i;
88
+ }
89
+ for (let i = 0; i < fields.length; i++) {
90
+ if (!signed[fields[i].fieldId]) return i;
91
+ }
92
+ return -1;
93
+ }
94
+
95
+ // src/signing/SigningProvider.tsx
96
+ import { Fragment, jsx } from "react/jsx-runtime";
97
+ var SigningContext = createContext(null);
98
+ function SigningProvider({ session, documentBytes, children }) {
99
+ if (!session) {
100
+ return /* @__PURE__ */ jsx(Fragment, { children });
101
+ }
102
+ return /* @__PURE__ */ jsx(SigningProviderInner, { session, documentBytes, children });
103
+ }
104
+ function SigningProviderInner({
105
+ session,
106
+ documentBytes,
107
+ children
108
+ }) {
109
+ const controller = useMemo(
110
+ () => createSigningController(session.fields, session.mode),
111
+ // eslint-disable-next-line react-hooks/exhaustive-deps
112
+ [session.fields, session.mode]
113
+ );
114
+ const [snapshot, setSnapshot] = useState(() => controller.snapshot());
115
+ useEffect(() => {
116
+ const unsub = controller.subscribe(setSnapshot);
117
+ return unsub;
118
+ }, [controller]);
119
+ const value = useMemo(
120
+ () => ({
121
+ controller,
122
+ snapshot,
123
+ signField: async (payload) => {
124
+ controller.signField(payload);
125
+ await session.onFieldSigned?.(payload);
126
+ },
127
+ completeIfReady: async () => {
128
+ if (!controller.snapshot().canComplete) return;
129
+ const final = controller.complete();
130
+ const completePayload = {
131
+ fieldIds: final.fields.map((f) => f.fieldId).filter((id) => final.signed[id] !== void 0),
132
+ bytes: documentBytes ?? new ArrayBuffer(0),
133
+ fields: final.signed
134
+ };
135
+ await session.onComplete?.(completePayload);
136
+ },
137
+ cancel: (reason) => {
138
+ controller.cancel();
139
+ session.onCancel?.({ reason });
140
+ },
141
+ baseDocumentBytes: documentBytes
142
+ }),
143
+ [controller, snapshot, session, documentBytes]
144
+ );
145
+ return /* @__PURE__ */ jsx(SigningContext.Provider, { value, children });
146
+ }
147
+ function useSigning() {
148
+ return useContext(SigningContext);
149
+ }
150
+
151
+ // src/signing/SigningPane.tsx
152
+ import { useEffect as useEffect3, useState as useState3 } from "react";
153
+
154
+ // src/signing/captures.tsx
155
+ import { useEffect as useEffect2, useRef, useState as useState2 } from "react";
156
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
157
+ function DrawnSignaturePad({
158
+ onCapture,
159
+ clearLabel = "Clear",
160
+ saveLabel = "Use this signature",
161
+ width = 480,
162
+ height = 160
163
+ }) {
164
+ const canvasRef = useRef(null);
165
+ const drawingRef = useRef(false);
166
+ const [hasInk, setHasInk] = useState2(false);
167
+ useEffect2(() => {
168
+ const canvas = canvasRef.current;
169
+ if (!canvas) return;
170
+ const ctx = canvas.getContext("2d");
171
+ if (!ctx) return;
172
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
173
+ ctx.strokeStyle = "#0f172a";
174
+ ctx.lineWidth = 2;
175
+ ctx.lineCap = "round";
176
+ ctx.lineJoin = "round";
177
+ }, []);
178
+ const start = (e) => {
179
+ const canvas = canvasRef.current;
180
+ if (!canvas) return;
181
+ const ctx = canvas.getContext("2d");
182
+ if (!ctx) return;
183
+ const { x, y } = pointerPos(e, canvas);
184
+ ctx.beginPath();
185
+ ctx.moveTo(x, y);
186
+ drawingRef.current = true;
187
+ canvas.setPointerCapture(e.pointerId);
188
+ };
189
+ const move = (e) => {
190
+ if (!drawingRef.current) return;
191
+ const canvas = canvasRef.current;
192
+ if (!canvas) return;
193
+ const ctx = canvas.getContext("2d");
194
+ if (!ctx) return;
195
+ const { x, y } = pointerPos(e, canvas);
196
+ ctx.lineTo(x, y);
197
+ ctx.stroke();
198
+ if (!hasInk) setHasInk(true);
199
+ };
200
+ const end = (e) => {
201
+ drawingRef.current = false;
202
+ canvasRef.current?.releasePointerCapture(e.pointerId);
203
+ };
204
+ const clear = () => {
205
+ const canvas = canvasRef.current;
206
+ if (!canvas) return;
207
+ const ctx = canvas.getContext("2d");
208
+ if (!ctx) return;
209
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
210
+ setHasInk(false);
211
+ };
212
+ const save = async () => {
213
+ const canvas = canvasRef.current;
214
+ if (!canvas || !hasInk) return;
215
+ const blob = await new Promise((resolve) => {
216
+ canvas.toBlob((b) => resolve(b), "image/png");
217
+ });
218
+ if (!blob) return;
219
+ const bytes = await blob.arrayBuffer();
220
+ onCapture({ bytes, mime: "image/png" });
221
+ clear();
222
+ };
223
+ return /* @__PURE__ */ jsxs("div", { style: padWrapStyle, "data-testid": "drawn-signature-pad", children: [
224
+ /* @__PURE__ */ jsx2(
225
+ "canvas",
226
+ {
227
+ ref: canvasRef,
228
+ width,
229
+ height,
230
+ style: padCanvasStyle(width, height),
231
+ onPointerDown: start,
232
+ onPointerMove: move,
233
+ onPointerUp: end,
234
+ onPointerLeave: end,
235
+ "data-testid": "drawn-signature-canvas"
236
+ }
237
+ ),
238
+ /* @__PURE__ */ jsxs("div", { style: padActionsStyle, children: [
239
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: clear, style: secondaryBtnStyle(false), children: clearLabel }),
240
+ /* @__PURE__ */ jsx2(
241
+ "button",
242
+ {
243
+ type: "button",
244
+ onClick: save,
245
+ disabled: !hasInk,
246
+ style: primaryBtnStyle(!hasInk),
247
+ "data-testid": "drawn-signature-save",
248
+ children: saveLabel
249
+ }
250
+ )
251
+ ] })
252
+ ] });
253
+ }
254
+ function pointerPos(e, canvas) {
255
+ const rect = canvas.getBoundingClientRect();
256
+ const scaleX = canvas.width / rect.width;
257
+ const scaleY = canvas.height / rect.height;
258
+ return {
259
+ x: (e.clientX - rect.left) * scaleX,
260
+ y: (e.clientY - rect.top) * scaleY
261
+ };
262
+ }
263
+ function TypedSignatureField({
264
+ onCapture,
265
+ defaultText = "",
266
+ saveLabel = "Use this signature"
267
+ }) {
268
+ const [value, setValue] = useState2(defaultText);
269
+ const save = () => {
270
+ const trimmed = value.trim();
271
+ if (!trimmed) return;
272
+ const bytes = new TextEncoder().encode(trimmed).buffer;
273
+ onCapture({ bytes, mime: "text/plain" });
274
+ setValue("");
275
+ };
276
+ return /* @__PURE__ */ jsxs("div", { style: padWrapStyle, "data-testid": "typed-signature-field", children: [
277
+ /* @__PURE__ */ jsx2(
278
+ "input",
279
+ {
280
+ type: "text",
281
+ value,
282
+ onChange: (e) => setValue(e.target.value),
283
+ placeholder: "Type your full name",
284
+ style: typedInputStyle,
285
+ "data-testid": "typed-signature-input",
286
+ autoFocus: true
287
+ }
288
+ ),
289
+ /* @__PURE__ */ jsx2("div", { style: padActionsStyle, children: /* @__PURE__ */ jsx2(
290
+ "button",
291
+ {
292
+ type: "button",
293
+ onClick: save,
294
+ disabled: !value.trim(),
295
+ style: primaryBtnStyle(!value.trim()),
296
+ "data-testid": "typed-signature-save",
297
+ children: saveLabel
298
+ }
299
+ ) })
300
+ ] });
301
+ }
302
+ function UploadedSignatureField({
303
+ onCapture,
304
+ accept = "image/png,image/jpeg,image/svg+xml"
305
+ }) {
306
+ const inputRef = useRef(null);
307
+ const [fileName, setFileName] = useState2(null);
308
+ const onChange = async (e) => {
309
+ const file = e.target.files?.[0];
310
+ if (!file) return;
311
+ const bytes = await file.arrayBuffer();
312
+ onCapture({ bytes, mime: file.type || "application/octet-stream" });
313
+ setFileName(file.name);
314
+ if (inputRef.current) inputRef.current.value = "";
315
+ };
316
+ return /* @__PURE__ */ jsx2("div", { style: padWrapStyle, "data-testid": "uploaded-signature-field", children: /* @__PURE__ */ jsxs("label", { style: uploadLabelStyle, children: [
317
+ /* @__PURE__ */ jsx2(
318
+ "input",
319
+ {
320
+ ref: inputRef,
321
+ type: "file",
322
+ accept,
323
+ onChange,
324
+ style: { display: "none" },
325
+ "data-testid": "uploaded-signature-input"
326
+ }
327
+ ),
328
+ /* @__PURE__ */ jsx2("span", { children: fileName ?? "Choose image\u2026" })
329
+ ] }) });
330
+ }
331
+ var padWrapStyle = {
332
+ display: "flex",
333
+ flexDirection: "column",
334
+ gap: 10
335
+ };
336
+ var padCanvasStyle = (w, h) => ({
337
+ width: w,
338
+ height: h,
339
+ maxWidth: "100%",
340
+ border: "1px dashed var(--doc-border, #cbd5e1)",
341
+ borderRadius: 8,
342
+ background: "var(--doc-surface, #fff)",
343
+ cursor: "crosshair",
344
+ touchAction: "none"
345
+ });
346
+ var padActionsStyle = {
347
+ display: "flex",
348
+ justifyContent: "flex-end",
349
+ gap: 8
350
+ };
351
+ var typedInputStyle = {
352
+ width: "100%",
353
+ padding: "10px 12px",
354
+ border: "1px solid var(--doc-border, #cbd5e1)",
355
+ borderRadius: 6,
356
+ fontSize: 18,
357
+ fontFamily: '"Caveat", "Dancing Script", "Brush Script MT", cursive',
358
+ background: "var(--doc-surface, #fff)",
359
+ color: "var(--doc-text, #0f172a)"
360
+ };
361
+ var uploadLabelStyle = {
362
+ display: "inline-flex",
363
+ padding: "8px 14px",
364
+ border: "1px dashed var(--doc-border, #cbd5e1)",
365
+ borderRadius: 6,
366
+ background: "var(--doc-surface, #fff)",
367
+ color: "var(--doc-text, #0f172a)",
368
+ fontSize: 13,
369
+ cursor: "pointer",
370
+ alignSelf: "flex-start"
371
+ };
372
+ function primaryBtnStyle(disabled) {
373
+ return {
374
+ padding: "8px 16px",
375
+ borderRadius: 6,
376
+ border: "1px solid transparent",
377
+ background: disabled ? "var(--doc-border, #cbd5e1)" : "var(--doc-accent, #2563eb)",
378
+ color: disabled ? "var(--doc-text-muted, #64748b)" : "#fff",
379
+ fontSize: 13,
380
+ fontWeight: 600,
381
+ cursor: disabled ? "not-allowed" : "pointer",
382
+ fontFamily: "inherit"
383
+ };
384
+ }
385
+ function secondaryBtnStyle(disabled) {
386
+ return {
387
+ padding: "8px 16px",
388
+ borderRadius: 6,
389
+ border: "1px solid var(--doc-border, #cbd5e1)",
390
+ background: "transparent",
391
+ color: "var(--doc-text, #0f172a)",
392
+ fontSize: 13,
393
+ fontWeight: 500,
394
+ cursor: disabled ? "not-allowed" : "pointer",
395
+ fontFamily: "inherit"
396
+ };
397
+ }
398
+
399
+ // src/signing/SigningPane.tsx
400
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
401
+ function SigningPane({ banner, testId = "signing-pane" }) {
402
+ const ctx = useSigning();
403
+ if (!ctx) return null;
404
+ const { snapshot, signField, completeIfReady, cancel } = ctx;
405
+ if (snapshot.isComplete || snapshot.isCancelled) return null;
406
+ const active = snapshot.activeFieldIndex >= 0 ? snapshot.fields[snapshot.activeFieldIndex] : null;
407
+ return /* @__PURE__ */ jsxs2("aside", { style: paneStyle, role: "region", "aria-label": "Signing pane", "data-testid": testId, children: [
408
+ banner && /* @__PURE__ */ jsx3("div", { style: bannerStyle, "data-testid": `${testId}-banner`, children: banner }),
409
+ /* @__PURE__ */ jsx3("div", { style: listStyle, "data-testid": `${testId}-fields`, children: snapshot.fields.map((f, i) => {
410
+ const isSigned = !!snapshot.signed[f.fieldId];
411
+ const isActive = i === snapshot.activeFieldIndex;
412
+ return /* @__PURE__ */ jsxs2(
413
+ "div",
414
+ {
415
+ style: listItemStyle(isActive, isSigned),
416
+ "data-testid": `${testId}-field-${f.fieldId}`,
417
+ "data-state": isSigned ? "signed" : isActive ? "active" : "pending",
418
+ children: [
419
+ /* @__PURE__ */ jsx3("span", { style: listIconStyle(isSigned), "aria-hidden": "true", children: isSigned ? "\u2713" : i + 1 }),
420
+ /* @__PURE__ */ jsx3("span", { style: listLabelStyle, children: f.label }),
421
+ !f.required && /* @__PURE__ */ jsx3("span", { style: optionalChipStyle, "aria-label": "Optional", children: "optional" })
422
+ ]
423
+ },
424
+ f.fieldId
425
+ );
426
+ }) }),
427
+ active && /* @__PURE__ */ jsx3(
428
+ ActiveFieldEditor,
429
+ {
430
+ field: active,
431
+ testId,
432
+ onCapture: async (cap, method) => {
433
+ const payload = {
434
+ fieldId: active.fieldId,
435
+ method,
436
+ bytes: cap.bytes,
437
+ mime: cap.mime,
438
+ signedAt: (/* @__PURE__ */ new Date()).toISOString()
439
+ };
440
+ await signField(payload);
441
+ }
442
+ }
443
+ ),
444
+ !active && snapshot.canComplete && /* @__PURE__ */ jsx3("div", { style: completeBlockStyle, "data-testid": `${testId}-complete-block`, children: "All required signatures collected. Ready to finalise." }),
445
+ /* @__PURE__ */ jsxs2("footer", { style: footerStyle, children: [
446
+ /* @__PURE__ */ jsx3(
447
+ "button",
448
+ {
449
+ type: "button",
450
+ onClick: () => cancel("signer_cancelled"),
451
+ style: secondaryBtnStyle2(),
452
+ "data-testid": `${testId}-cancel`,
453
+ children: "Cancel"
454
+ }
455
+ ),
456
+ /* @__PURE__ */ jsx3(
457
+ "button",
458
+ {
459
+ type: "button",
460
+ onClick: () => void completeIfReady(),
461
+ disabled: !snapshot.canComplete,
462
+ style: primaryBtnStyle2(!snapshot.canComplete),
463
+ "data-testid": `${testId}-complete`,
464
+ children: "Complete"
465
+ }
466
+ )
467
+ ] })
468
+ ] });
469
+ }
470
+ function ActiveFieldEditor({
471
+ field,
472
+ testId,
473
+ onCapture
474
+ }) {
475
+ const [method, setMethod] = useState3(field.methods[0]);
476
+ useEffect3(() => {
477
+ setMethod(field.methods[0]);
478
+ }, [field]);
479
+ return /* @__PURE__ */ jsxs2("div", { style: editorStyle, "data-testid": `${testId}-editor`, children: [
480
+ /* @__PURE__ */ jsxs2("div", { style: editorHeaderStyle, children: [
481
+ /* @__PURE__ */ jsx3("div", { style: editorLabelStyle, children: field.label }),
482
+ field.signer?.name && /* @__PURE__ */ jsx3("div", { style: editorSignerStyle, children: field.signer.name })
483
+ ] }),
484
+ field.methods.length > 1 && /* @__PURE__ */ jsx3("div", { style: methodTabsStyle, role: "tablist", "data-testid": `${testId}-methods`, children: field.methods.map((m) => /* @__PURE__ */ jsx3(
485
+ "button",
486
+ {
487
+ type: "button",
488
+ role: "tab",
489
+ "aria-selected": method === m,
490
+ onClick: () => setMethod(m),
491
+ style: methodTabStyle(method === m),
492
+ "data-testid": `${testId}-method-${m}`,
493
+ children: methodLabel(m)
494
+ },
495
+ m
496
+ )) }),
497
+ /* @__PURE__ */ jsxs2("div", { style: captureWrapStyle, children: [
498
+ method === "drawn" && /* @__PURE__ */ jsx3(DrawnSignaturePad, { onCapture: (c) => onCapture(c, "drawn") }),
499
+ method === "typed" && /* @__PURE__ */ jsx3(
500
+ TypedSignatureField,
501
+ {
502
+ defaultText: field.signer?.name ?? "",
503
+ onCapture: (c) => onCapture(c, "typed")
504
+ }
505
+ ),
506
+ method === "uploaded" && /* @__PURE__ */ jsx3(UploadedSignatureField, { onCapture: (c) => onCapture(c, "uploaded") })
507
+ ] })
508
+ ] });
509
+ }
510
+ function methodLabel(m) {
511
+ switch (m) {
512
+ case "drawn":
513
+ return "Draw";
514
+ case "typed":
515
+ return "Type";
516
+ case "uploaded":
517
+ return "Upload";
518
+ }
519
+ }
520
+ var paneStyle = {
521
+ position: "fixed",
522
+ top: 16,
523
+ right: 16,
524
+ bottom: 16,
525
+ width: 360,
526
+ maxWidth: "100vw",
527
+ display: "flex",
528
+ flexDirection: "column",
529
+ gap: 14,
530
+ padding: 16,
531
+ background: "var(--doc-surface, #fff)",
532
+ border: "1px solid var(--doc-border, #cbd5e1)",
533
+ borderRadius: 12,
534
+ boxShadow: "0 1px 1px rgba(0, 0, 0, 0.04), 0 6px 24px rgba(15, 23, 42, 0.12)",
535
+ fontFamily: "inherit",
536
+ zIndex: 9e3
537
+ };
538
+ var bannerStyle = {
539
+ padding: "8px 10px",
540
+ background: "var(--doc-surface-2, #f1f5f9)",
541
+ border: "1px solid var(--doc-border-light, #e2e8f0)",
542
+ borderRadius: 6,
543
+ fontSize: 12,
544
+ color: "var(--doc-text-muted, #475569)"
545
+ };
546
+ var listStyle = {
547
+ display: "flex",
548
+ flexDirection: "column",
549
+ gap: 4
550
+ };
551
+ function listItemStyle(active, signed) {
552
+ return {
553
+ display: "flex",
554
+ alignItems: "center",
555
+ gap: 10,
556
+ padding: "8px 10px",
557
+ borderRadius: 6,
558
+ background: active ? "var(--doc-surface-2, #f1f5f9)" : signed ? "transparent" : "transparent",
559
+ border: active ? "1px solid var(--doc-border, #cbd5e1)" : "1px solid transparent",
560
+ opacity: signed && !active ? 0.7 : 1
561
+ };
562
+ }
563
+ function listIconStyle(signed) {
564
+ return {
565
+ display: "inline-flex",
566
+ alignItems: "center",
567
+ justifyContent: "center",
568
+ width: 22,
569
+ height: 22,
570
+ borderRadius: "50%",
571
+ background: signed ? "var(--doc-accent, #2563eb)" : "var(--doc-surface-2, #f1f5f9)",
572
+ color: signed ? "#fff" : "var(--doc-text-muted, #475569)",
573
+ fontSize: 12,
574
+ fontWeight: 600,
575
+ flexShrink: 0
576
+ };
577
+ }
578
+ var listLabelStyle = {
579
+ flex: 1,
580
+ fontSize: 13,
581
+ color: "var(--doc-text, #0f172a)",
582
+ fontWeight: 500
583
+ };
584
+ var optionalChipStyle = {
585
+ fontSize: 11,
586
+ color: "var(--doc-text-muted, #64748b)",
587
+ padding: "2px 6px",
588
+ background: "var(--doc-surface-2, #f1f5f9)",
589
+ borderRadius: 4
590
+ };
591
+ var editorStyle = {
592
+ display: "flex",
593
+ flexDirection: "column",
594
+ gap: 12
595
+ };
596
+ var editorHeaderStyle = {
597
+ display: "flex",
598
+ flexDirection: "column",
599
+ gap: 2
600
+ };
601
+ var editorLabelStyle = {
602
+ fontSize: 13,
603
+ fontWeight: 600,
604
+ color: "var(--doc-text, #0f172a)"
605
+ };
606
+ var editorSignerStyle = {
607
+ fontSize: 12,
608
+ color: "var(--doc-text-muted, #64748b)"
609
+ };
610
+ var methodTabsStyle = {
611
+ display: "flex",
612
+ gap: 4,
613
+ padding: 2,
614
+ background: "var(--doc-surface-2, #f1f5f9)",
615
+ borderRadius: 6
616
+ };
617
+ function methodTabStyle(selected) {
618
+ return {
619
+ flex: 1,
620
+ padding: "6px 10px",
621
+ background: selected ? "var(--doc-surface, #fff)" : "transparent",
622
+ border: "none",
623
+ borderRadius: 4,
624
+ fontSize: 12,
625
+ fontWeight: 500,
626
+ color: selected ? "var(--doc-text, #0f172a)" : "var(--doc-text-muted, #475569)",
627
+ cursor: "pointer",
628
+ fontFamily: "inherit"
629
+ };
630
+ }
631
+ var captureWrapStyle = {
632
+ display: "flex",
633
+ flexDirection: "column",
634
+ gap: 8
635
+ };
636
+ var completeBlockStyle = {
637
+ padding: "10px 12px",
638
+ background: "rgba(34, 197, 94, 0.08)",
639
+ border: "1px solid rgba(34, 197, 94, 0.28)",
640
+ borderRadius: 6,
641
+ fontSize: 12,
642
+ color: "rgb(20, 83, 45)"
643
+ };
644
+ var footerStyle = {
645
+ display: "flex",
646
+ justifyContent: "flex-end",
647
+ gap: 8,
648
+ marginTop: "auto",
649
+ paddingTop: 12,
650
+ borderTop: "1px solid var(--doc-border-light, #e2e8f0)"
651
+ };
652
+ function primaryBtnStyle2(disabled) {
653
+ return {
654
+ padding: "8px 16px",
655
+ borderRadius: 6,
656
+ border: "1px solid transparent",
657
+ background: disabled ? "var(--doc-border, #cbd5e1)" : "var(--doc-accent, #2563eb)",
658
+ color: disabled ? "var(--doc-text-muted, #64748b)" : "#fff",
659
+ fontSize: 13,
660
+ fontWeight: 600,
661
+ cursor: disabled ? "not-allowed" : "pointer",
662
+ fontFamily: "inherit"
663
+ };
664
+ }
665
+ function secondaryBtnStyle2() {
666
+ return {
667
+ padding: "8px 16px",
668
+ borderRadius: 6,
669
+ border: "1px solid var(--doc-border, #cbd5e1)",
670
+ background: "transparent",
671
+ color: "var(--doc-text, #0f172a)",
672
+ fontSize: 13,
673
+ fontWeight: 500,
674
+ cursor: "pointer",
675
+ fontFamily: "inherit"
676
+ };
677
+ }
678
+
679
+ // src/embed/protocol.ts
680
+ function isCasualEnvelope(value) {
681
+ if (!value || typeof value !== "object") return false;
682
+ const v = value;
683
+ return typeof v.type === "string" && v.type.startsWith("casual.") && (v.app === "docs" || v.app === "sheet") && v.v === 1 && "data" in v;
684
+ }
685
+
686
+ // src/embed/EmbedTransport.ts
687
+ var EmbedTransport = class {
688
+ constructor(opts) {
689
+ __publicField(this, "opts");
690
+ __publicField(this, "handlers", {});
691
+ __publicField(this, "destroyed", false);
692
+ __publicField(this, "pendingRequests", /* @__PURE__ */ new Map());
693
+ this.opts = {
694
+ ...opts,
695
+ parentWindow: opts.parentWindow ?? (typeof window !== "undefined" ? window.parent : { postMessage: () => void 0 }),
696
+ hostWindow: opts.hostWindow ?? (typeof window !== "undefined" ? window : {
697
+ addEventListener: () => void 0,
698
+ removeEventListener: () => void 0
699
+ })
700
+ };
701
+ this.boundMessage = this.boundMessage.bind(this);
702
+ this.opts.hostWindow.addEventListener("message", this.boundMessage);
703
+ }
704
+ /** Replaces the handler set. Idempotent — call multiple times. */
705
+ on(handlers) {
706
+ this.handlers = { ...this.handlers, ...handlers };
707
+ }
708
+ /** Editor → Host: announce ourselves. Call once after handlers are wired. */
709
+ sendHello() {
710
+ const data = {
711
+ capabilities: this.opts.capabilities,
712
+ version: this.opts.version,
713
+ commit: this.opts.commit
714
+ };
715
+ this.post("casual.hello", data);
716
+ }
717
+ /** Editor → Host: editor is ready to receive commands. */
718
+ sendReady() {
719
+ this.post("casual.ready", {});
720
+ }
721
+ /** Editor → Host: ask the host to supply document bytes for `docId`. */
722
+ async requestLoad(docId, timeoutMs = 3e4) {
723
+ return this.request(
724
+ "casual.load.request",
725
+ { docId },
726
+ timeoutMs
727
+ );
728
+ }
729
+ /** Editor → Host: ask the host to persist `bytes`. */
730
+ async requestSave(req, timeoutMs = 3e4) {
731
+ return this.request("casual.save.request", req, timeoutMs, [req.bytes]);
732
+ }
733
+ /** Editor → Host: selection moved. Fire-and-forget. */
734
+ sendSelectionChanged(data) {
735
+ this.post("casual.selection.changed", data);
736
+ }
737
+ /** Editor → Host: format flags on the active cell changed (bold,
738
+ * italic, …). Drive's custom toolbar mirrors this state in its
739
+ * "pressed" indicators. v0.6+. */
740
+ sendSelectionFormatState(data) {
741
+ this.post("casual.selection.format-state", data);
742
+ }
743
+ /** Editor → Host: a noteworthy event. */
744
+ sendTelemetry(data) {
745
+ this.post("casual.telemetry.event", data);
746
+ }
747
+ /** Editor → Host: per-field progress during a signing session. */
748
+ sendSignatureFieldSigned(data) {
749
+ this.post("casual.signature.field.signed", data, [data.bytes]);
750
+ }
751
+ /** Editor → Host: signing session is finished. */
752
+ sendSignatureComplete(data) {
753
+ this.post("casual.signature.complete", data, [data.bytes]);
754
+ }
755
+ /** Editor → Host: editor-side cancel of a signing session. */
756
+ sendSignatureCancel(reason) {
757
+ this.post("casual.signature.cancel", { reason });
758
+ }
759
+ /** Editor → Host: fatal boot / load error. Host surfaces via wrapper
760
+ * `onError` callback. Fire-and-forget. */
761
+ sendError(data) {
762
+ this.post("casual.error", data);
763
+ }
764
+ /** Tear down listeners. Idempotent. */
765
+ destroy() {
766
+ if (this.destroyed) return;
767
+ this.opts.hostWindow.removeEventListener("message", this.boundMessage);
768
+ this.pendingRequests.clear();
769
+ this.destroyed = true;
770
+ }
771
+ // ---------------------------------------------------------------
772
+ // Internals
773
+ // ---------------------------------------------------------------
774
+ boundMessage(ev) {
775
+ const msg = ev;
776
+ if (msg.origin && msg.origin !== this.opts.hostOrigin) return;
777
+ if (!isCasualEnvelope(msg.data)) return;
778
+ void this.dispatch(msg.data);
779
+ }
780
+ async dispatch(env) {
781
+ if (env.id && this.pendingRequests.has(env.id)) {
782
+ const resolve = this.pendingRequests.get(env.id);
783
+ this.pendingRequests.delete(env.id);
784
+ resolve(env);
785
+ return;
786
+ }
787
+ switch (env.type) {
788
+ case "casual.hello":
789
+ await this.handlers.onHostHello?.(env.data);
790
+ this.sendReady();
791
+ return;
792
+ case "casual.command.setReadOnly":
793
+ await this.handlers.onCommandSetReadOnly?.(env.data);
794
+ return;
795
+ case "casual.command.setTheme":
796
+ await this.handlers.onCommandSetTheme?.(env.data);
797
+ return;
798
+ case "casual.command.setLocale":
799
+ await this.handlers.onCommandSetLocale?.(env.data);
800
+ return;
801
+ case "casual.command.set.viewmode":
802
+ await this.handlers.onCommandSetViewMode?.(env.data);
803
+ return;
804
+ case "casual.command.execute":
805
+ await this.handlers.onCommandExecute?.(env.data);
806
+ return;
807
+ case "casual.command.focus":
808
+ await this.handlers.onCommandFocus?.();
809
+ return;
810
+ case "casual.command.save":
811
+ await this.handlers.onCommandSave?.();
812
+ return;
813
+ case "casual.command.load":
814
+ await this.handlers.onCommandLoad?.();
815
+ return;
816
+ case "casual.signature.request": {
817
+ const ack = await this.handlers.onSignatureRequest?.(
818
+ env.data
819
+ ) ?? {
820
+ ok: false,
821
+ code: "unhandled"
822
+ };
823
+ if (env.id) {
824
+ this.postReply(env.id, "casual.signature.request.ack", ack);
825
+ }
826
+ return;
827
+ }
828
+ case "casual.signature.cancel":
829
+ await this.handlers.onSignatureCancel?.(env.data);
830
+ return;
831
+ default:
832
+ return;
833
+ }
834
+ }
835
+ post(type, data, transfer) {
836
+ const env = { type, app: this.opts.app, v: 1, data };
837
+ try {
838
+ this.opts.parentWindow.postMessage(env, this.opts.hostOrigin, transfer);
839
+ } catch {
840
+ }
841
+ }
842
+ postReply(id, type, data) {
843
+ const env = { type, app: this.opts.app, id, v: 1, data };
844
+ try {
845
+ this.opts.parentWindow.postMessage(env, this.opts.hostOrigin);
846
+ } catch {
847
+ }
848
+ }
849
+ async request(type, data, timeoutMs, transfer) {
850
+ const id = newRequestId();
851
+ return new Promise((resolve, reject) => {
852
+ const timer = timeoutMs > 0 ? setTimeout(() => {
853
+ this.pendingRequests.delete(id);
854
+ reject(new Error(`Embed request ${type} timed out after ${timeoutMs}ms`));
855
+ }, timeoutMs) : null;
856
+ this.pendingRequests.set(id, (env2) => {
857
+ if (timer) clearTimeout(timer);
858
+ resolve(env2.data);
859
+ });
860
+ const env = { type, app: this.opts.app, id, v: 1, data };
861
+ try {
862
+ this.opts.parentWindow.postMessage(env, this.opts.hostOrigin, transfer);
863
+ } catch (err) {
864
+ if (timer) clearTimeout(timer);
865
+ this.pendingRequests.delete(id);
866
+ reject(err);
867
+ }
868
+ });
869
+ }
870
+ };
871
+ function newRequestId() {
872
+ return Math.random().toString(16).slice(2, 10);
873
+ }
874
+
875
+ // src/sheets/CasualSheets.tsx
876
+ import { useEffect as useEffect4, useRef as useRef2 } from "react";
877
+ import {
878
+ ICommandService,
879
+ LocaleType,
880
+ LogLevel,
881
+ ThemeService as ThemeService2,
882
+ Univer,
883
+ UniverInstanceType
884
+ } from "@univerjs/core";
885
+ import { FUniver } from "@univerjs/core/facade";
886
+ import { defaultTheme } from "@univerjs/themes";
887
+ import { UniverRenderEnginePlugin } from "@univerjs/engine-render";
888
+ import { UniverFormulaEnginePlugin } from "@univerjs/engine-formula";
889
+ import { UniverUIPlugin } from "@univerjs/ui";
890
+ import { UniverDocsPlugin } from "@univerjs/docs";
891
+ import { UniverDocsUIPlugin } from "@univerjs/docs-ui";
892
+ import { UniverSheetsPlugin } from "@univerjs/sheets";
893
+ import { UniverSheetsUIPlugin } from "@univerjs/sheets-ui";
894
+ import { UniverSheetsFormulaPlugin } from "@univerjs/sheets-formula";
895
+ import { UniverSheetsFormulaUIPlugin } from "@univerjs/sheets-formula-ui";
896
+ import { UniverSheetsNumfmtPlugin } from "@univerjs/sheets-numfmt";
897
+ import { UniverSheetsNumfmtUIPlugin } from "@univerjs/sheets-numfmt-ui";
898
+
899
+ // src/sheets/api.ts
900
+ import "@univerjs/sheets/facade";
901
+ import { ThemeService } from "@univerjs/core";
902
+ function createCasualSheetsAPI(univerAPI) {
903
+ return {
904
+ univer: univerAPI,
905
+ getSnapshot() {
906
+ return univerAPI.getActiveWorkbook()?.save() ?? null;
907
+ },
908
+ loadSnapshot(data) {
909
+ const current = univerAPI.getActiveWorkbook();
910
+ if (current) univerAPI.disposeUnit(current.getId());
911
+ univerAPI.createWorkbook(data);
912
+ },
913
+ getSelection() {
914
+ const wb = univerAPI.getActiveWorkbook();
915
+ const range = wb?.getActiveRange();
916
+ if (!wb || !range) return null;
917
+ return {
918
+ unitId: wb.getId(),
919
+ sheetId: wb.getActiveSheet().getSheetId(),
920
+ range: range.getRange()
921
+ };
922
+ },
923
+ executeCommand(id, params) {
924
+ return univerAPI.executeCommand(id, params);
925
+ },
926
+ setTheme(appearance) {
927
+ const dark = appearance === "dark";
928
+ const injector = univerAPI._injector;
929
+ const themeService = injector?.get(ThemeService);
930
+ if (themeService && themeService.darkMode !== dark) themeService.setDarkMode(dark);
931
+ }
932
+ };
933
+ }
934
+
935
+ // src/univer/lazy-plugins.ts
936
+ var LOADERS = {
937
+ cf: async () => {
938
+ const [base, ui] = await Promise.all([
939
+ import("@univerjs/sheets-conditional-formatting"),
940
+ import("@univerjs/sheets-conditional-formatting-ui")
941
+ ]);
942
+ return [
943
+ [base.UniverSheetsConditionalFormattingPlugin],
944
+ [ui.UniverSheetsConditionalFormattingUIPlugin]
945
+ ];
946
+ },
947
+ dv: async () => {
948
+ const [base, ui] = await Promise.all([
949
+ import("@univerjs/sheets-data-validation"),
950
+ import("@univerjs/sheets-data-validation-ui")
951
+ ]);
952
+ return [
953
+ [base.UniverSheetsDataValidationPlugin],
954
+ [ui.UniverSheetsDataValidationUIPlugin]
955
+ ];
956
+ },
957
+ hyperlink: async () => {
958
+ const [base, ui] = await Promise.all([
959
+ import("@univerjs/sheets-hyper-link"),
960
+ import("@univerjs/sheets-hyper-link-ui")
961
+ ]);
962
+ return [
963
+ [base.UniverSheetsHyperLinkPlugin],
964
+ [ui.UniverSheetsHyperLinkUIPlugin]
965
+ ];
966
+ },
967
+ note: async () => {
968
+ const [base, ui] = await Promise.all([
969
+ import("@univerjs/sheets-note"),
970
+ import("@univerjs/sheets-note-ui")
971
+ ]);
972
+ return [[base.UniverSheetsNotePlugin], [ui.UniverSheetsNoteUIPlugin]];
973
+ },
974
+ table: async () => {
975
+ const [base, ui] = await Promise.all([
976
+ import("@univerjs/sheets-table"),
977
+ import("@univerjs/sheets-table-ui")
978
+ ]);
979
+ return [[base.UniverSheetsTablePlugin], [ui.UniverSheetsTableUIPlugin]];
980
+ },
981
+ threadComment: async () => {
982
+ const [tc, tcUi, sheetsTc, sheetsTcUi] = await Promise.all([
983
+ import("@univerjs/thread-comment"),
984
+ import("@univerjs/thread-comment-ui"),
985
+ import("@univerjs/sheets-thread-comment"),
986
+ import("@univerjs/sheets-thread-comment-ui")
987
+ ]);
988
+ return [
989
+ [tc.UniverThreadCommentPlugin],
990
+ [tcUi.UniverThreadCommentUIPlugin],
991
+ [sheetsTc.UniverSheetsThreadCommentPlugin],
992
+ [sheetsTcUi.UniverSheetsThreadCommentUIPlugin]
993
+ ];
994
+ },
995
+ drawing: async () => {
996
+ const [d, dUi, sd, sdUi] = await Promise.all([
997
+ import("@univerjs/drawing"),
998
+ import("@univerjs/drawing-ui"),
999
+ import("@univerjs/sheets-drawing"),
1000
+ import("@univerjs/sheets-drawing-ui"),
1001
+ // Side-effect imports: install FWorksheet.insertImage / getImages /
1002
+ // updateImages on the facade prototype. Without these, code that
1003
+ // reaches in via the FUniver facade (e2e specs, future shell glue)
1004
+ // sees an undefined method even though the plugin is registered.
1005
+ import("@univerjs/sheets-drawing/facade"),
1006
+ import("@univerjs/sheets-drawing-ui/facade")
1007
+ ]);
1008
+ return [
1009
+ [d.UniverDrawingPlugin],
1010
+ [dUi.UniverDrawingUIPlugin],
1011
+ [sd.UniverSheetsDrawingPlugin],
1012
+ [sdUi.UniverSheetsDrawingUIPlugin]
1013
+ ];
1014
+ },
1015
+ sort: async () => {
1016
+ const [base, ui] = await Promise.all([
1017
+ import("@univerjs/sheets-sort"),
1018
+ import("@univerjs/sheets-sort-ui")
1019
+ ]);
1020
+ return [[base.UniverSheetsSortPlugin], [ui.UniverSheetsSortUIPlugin]];
1021
+ },
1022
+ filter: async () => {
1023
+ const [base, ui] = await Promise.all([
1024
+ import("@univerjs/sheets-filter"),
1025
+ import("@univerjs/sheets-filter-ui")
1026
+ ]);
1027
+ return [[base.UniverSheetsFilterPlugin], [ui.UniverSheetsFilterUIPlugin]];
1028
+ },
1029
+ findReplace: async () => {
1030
+ const [base, sheets] = await Promise.all([
1031
+ import("@univerjs/find-replace"),
1032
+ import("@univerjs/sheets-find-replace")
1033
+ ]);
1034
+ return [[base.UniverFindReplacePlugin], [sheets.UniverSheetsFindReplacePlugin]];
1035
+ }
1036
+ };
1037
+ var RESOURCE_NAME_TO_GROUP = {
1038
+ SHEET_CONDITIONAL_FORMATTING_PLUGIN: "cf",
1039
+ SHEET_DATA_VALIDATION_PLUGIN: "dv",
1040
+ SHEET_HYPER_LINK_PLUGIN: "hyperlink",
1041
+ SHEET_NOTE_PLUGIN: "note",
1042
+ SHEET_TABLE_PLUGIN: "table",
1043
+ SHEET_THREAD_COMMENT_BASE_PLUGIN: "threadComment",
1044
+ SHEET_DRAWING_PLUGIN: "drawing",
1045
+ SHEET_SORT_PLUGIN: "sort",
1046
+ SHEET_FILTER_PLUGIN: "filter"
1047
+ };
1048
+ var loaded = /* @__PURE__ */ new Set();
1049
+ var inflight = /* @__PURE__ */ new Map();
1050
+ var currentUniver = null;
1051
+ function setUniverForLazyLoad(univer) {
1052
+ currentUniver = univer;
1053
+ }
1054
+ function ensurePlugin(univer, group) {
1055
+ if (loaded.has(group)) return Promise.resolve();
1056
+ const existing = inflight.get(group);
1057
+ if (existing) return existing;
1058
+ const loader = LOADERS[group];
1059
+ if (!loader) return Promise.resolve();
1060
+ const p = loader().then((plugins) => {
1061
+ for (const [PluginCtor, config] of plugins) {
1062
+ univer.registerPlugin(PluginCtor, config);
1063
+ }
1064
+ loaded.add(group);
1065
+ inflight.delete(group);
1066
+ });
1067
+ inflight.set(group, p);
1068
+ return p;
1069
+ }
1070
+ async function eagerLoadForSnapshot(univer, snapshot) {
1071
+ const groups = /* @__PURE__ */ new Set();
1072
+ const resources = snapshot.resources ?? [];
1073
+ for (const r of resources) {
1074
+ const g = RESOURCE_NAME_TO_GROUP[r.name];
1075
+ if (g) groups.add(g);
1076
+ }
1077
+ if (snapshotHasHyperlinks(snapshot)) groups.add("hyperlink");
1078
+ await Promise.all(Array.from(groups).map((g) => ensurePlugin(univer, g)));
1079
+ }
1080
+ function idleLoadAll(univer) {
1081
+ const groups = Object.keys(LOADERS);
1082
+ schedule(() => {
1083
+ for (const g of groups) {
1084
+ void ensurePlugin(univer, g);
1085
+ }
1086
+ });
1087
+ }
1088
+ function schedule(fn) {
1089
+ const ric = globalThis.requestIdleCallback;
1090
+ if (ric) ric(fn, { timeout: 500 });
1091
+ else setTimeout(fn, 0);
1092
+ }
1093
+ function snapshotHasHyperlinks(snapshot) {
1094
+ const sheetOrder = snapshot.sheetOrder ?? [];
1095
+ for (const sid of sheetOrder) {
1096
+ const sheet = snapshot.sheets?.[sid];
1097
+ if (!sheet?.cellData) continue;
1098
+ const cellData = sheet.cellData;
1099
+ for (const r of Object.keys(cellData)) {
1100
+ const row = cellData[r];
1101
+ for (const c of Object.keys(row)) {
1102
+ const ranges = row[c]?.p?.body?.customRanges ?? [];
1103
+ if (ranges.some((cr) => cr.rangeType === 0)) return true;
1104
+ }
1105
+ }
1106
+ }
1107
+ return false;
1108
+ }
1109
+
1110
+ // src/sheets/CasualSheets.tsx
1111
+ import { jsx as jsx4 } from "react/jsx-runtime";
1112
+ var DEFAULT_STYLE = {
1113
+ width: "100%",
1114
+ height: "100%",
1115
+ position: "relative"
1116
+ };
1117
+ var DEFAULT_UI = {
1118
+ header: false,
1119
+ toolbar: false,
1120
+ footer: false,
1121
+ contextMenu: true
1122
+ };
1123
+ function CasualSheets({
1124
+ initialData,
1125
+ onReady,
1126
+ onChange,
1127
+ onChangeDebounceMs = 400,
1128
+ lazyPlugins = true,
1129
+ locale = LocaleType.EN_US,
1130
+ locales,
1131
+ logLevel = LogLevel.WARN,
1132
+ ui,
1133
+ theme = defaultTheme,
1134
+ appearance = "light",
1135
+ style,
1136
+ className,
1137
+ testId = "casual-sheets"
1138
+ }) {
1139
+ const hostRef = useRef2(null);
1140
+ const onChangeRef = useRef2(onChange);
1141
+ onChangeRef.current = onChange;
1142
+ const hasOnChange = useRef2(!!onChange).current;
1143
+ const apiRef = useRef2(null);
1144
+ useEffect4(() => {
1145
+ const container = hostRef.current;
1146
+ if (!container) return;
1147
+ const univer = new Univer({
1148
+ theme,
1149
+ locale,
1150
+ locales,
1151
+ logLevel
1152
+ });
1153
+ const uiOpts = { ...DEFAULT_UI, ...ui, container };
1154
+ univer.registerPlugin(UniverRenderEnginePlugin);
1155
+ univer.registerPlugin(UniverFormulaEnginePlugin);
1156
+ univer.registerPlugin(UniverUIPlugin, uiOpts);
1157
+ univer.registerPlugin(UniverDocsPlugin);
1158
+ univer.registerPlugin(UniverDocsUIPlugin);
1159
+ univer.registerPlugin(UniverSheetsPlugin);
1160
+ univer.registerPlugin(UniverSheetsUIPlugin);
1161
+ univer.registerPlugin(UniverSheetsFormulaPlugin);
1162
+ univer.registerPlugin(UniverSheetsFormulaUIPlugin);
1163
+ univer.registerPlugin(UniverSheetsNumfmtPlugin);
1164
+ univer.registerPlugin(UniverSheetsNumfmtUIPlugin);
1165
+ if (lazyPlugins) setUniverForLazyLoad(univer);
1166
+ let cancelled = false;
1167
+ let changeTimer = null;
1168
+ let changeSub;
1169
+ void (async () => {
1170
+ if (lazyPlugins) {
1171
+ await eagerLoadForSnapshot(univer, initialData);
1172
+ if (cancelled) return;
1173
+ }
1174
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, initialData);
1175
+ const api = createCasualSheetsAPI(FUniver.newAPI(univer));
1176
+ apiRef.current = api;
1177
+ applyAppearance(api, container, appearance);
1178
+ onReady?.(api);
1179
+ if (hasOnChange) {
1180
+ const injector = api.univer._injector;
1181
+ const cmdSvc = injector?.get(ICommandService);
1182
+ changeSub = cmdSvc?.onMutationExecutedForCollab(() => {
1183
+ if (changeTimer) clearTimeout(changeTimer);
1184
+ changeTimer = setTimeout(() => {
1185
+ const snap = api.getSnapshot();
1186
+ if (snap) onChangeRef.current?.(snap);
1187
+ }, onChangeDebounceMs);
1188
+ });
1189
+ if (cancelled) changeSub?.dispose();
1190
+ }
1191
+ if (lazyPlugins) idleLoadAll(univer);
1192
+ })();
1193
+ return () => {
1194
+ cancelled = true;
1195
+ if (changeTimer) clearTimeout(changeTimer);
1196
+ changeSub?.dispose();
1197
+ apiRef.current = null;
1198
+ if (lazyPlugins) setUniverForLazyLoad(null);
1199
+ const toDispose = univer;
1200
+ queueMicrotask(() => toDispose.dispose());
1201
+ };
1202
+ }, []);
1203
+ useEffect4(() => {
1204
+ const api = apiRef.current;
1205
+ const container = hostRef.current;
1206
+ if (!api || !container) return;
1207
+ applyAppearance(api, container, appearance);
1208
+ }, [appearance]);
1209
+ return /* @__PURE__ */ jsx4(
1210
+ "div",
1211
+ {
1212
+ ref: hostRef,
1213
+ style: { ...DEFAULT_STYLE, ...style },
1214
+ className,
1215
+ "data-testid": testId
1216
+ }
1217
+ );
1218
+ }
1219
+ function applyAppearance(api, container, appearance) {
1220
+ const dark = appearance === "dark";
1221
+ container.classList.toggle("univer-dark", dark);
1222
+ try {
1223
+ const injector = api.univer._injector;
1224
+ const themeService = injector?.get(ThemeService2);
1225
+ if (themeService && themeService.darkMode !== dark) themeService.setDarkMode(dark);
1226
+ } catch {
1227
+ }
1228
+ }
1229
+
1230
+ // src/sheets/CasualSheetsIframe.tsx
1231
+ import {
1232
+ forwardRef,
1233
+ useCallback,
1234
+ useEffect as useEffect5,
1235
+ useRef as useRef3
1236
+ } from "react";
1237
+
1238
+ // src/embed/EmbedHostTransport.ts
1239
+ var EmbedHostTransport = class {
1240
+ constructor(opts) {
1241
+ __publicField(this, "opts");
1242
+ __publicField(this, "handlers", {});
1243
+ __publicField(this, "boundOnMessage");
1244
+ __publicField(this, "destroyed", false);
1245
+ this.opts = opts;
1246
+ this.boundOnMessage = this.onMessage.bind(this);
1247
+ const target = opts.hostWindow ?? window;
1248
+ target.addEventListener("message", this.boundOnMessage);
1249
+ }
1250
+ on(handlers) {
1251
+ this.handlers = { ...this.handlers, ...handlers };
1252
+ }
1253
+ destroy() {
1254
+ if (this.destroyed) return;
1255
+ this.destroyed = true;
1256
+ const target = this.opts.hostWindow ?? window;
1257
+ target.removeEventListener("message", this.boundOnMessage);
1258
+ }
1259
+ sendHostHello(data) {
1260
+ this.post("casual.hello", data);
1261
+ }
1262
+ sendSetViewMode(data) {
1263
+ this.post("casual.command.set.viewmode", data);
1264
+ }
1265
+ sendSetReadOnly(data) {
1266
+ this.post("casual.command.set.readonly", data);
1267
+ }
1268
+ sendSetTheme(data) {
1269
+ this.post("casual.command.set.theme", data);
1270
+ }
1271
+ sendSetLocale(data) {
1272
+ this.post("casual.command.set.locale", data);
1273
+ }
1274
+ sendCommandSave() {
1275
+ this.post("casual.command.save", null);
1276
+ }
1277
+ sendCommandFocus() {
1278
+ this.post("casual.command.focus", null);
1279
+ }
1280
+ /** Host → Editor: run a formatting / navigation command (bold,
1281
+ * italic, undo, …) against the active selection. v0.6+. */
1282
+ sendCommandExecute(data) {
1283
+ this.post("casual.command.execute", data);
1284
+ }
1285
+ sendSignatureRequest(id, data) {
1286
+ this.post("casual.signature.request", data, id);
1287
+ }
1288
+ sendSignatureCancel(data) {
1289
+ this.post("casual.signature.cancel", data);
1290
+ }
1291
+ onMessage(ev) {
1292
+ if (this.destroyed) return;
1293
+ if (ev.origin !== this.opts.embedOrigin) return;
1294
+ if (ev.source !== this.opts.iframeWindow) return;
1295
+ if (!isCasualEnvelope(ev.data)) return;
1296
+ if (ev.data.app !== this.opts.app) return;
1297
+ void this.dispatch(ev.data);
1298
+ }
1299
+ async dispatch(env) {
1300
+ switch (env.type) {
1301
+ case "casual.ready":
1302
+ this.handlers.onEditorReady?.(env.data);
1303
+ return;
1304
+ case "casual.load.request": {
1305
+ if (!this.handlers.onLoadRequest) return;
1306
+ const id = env.id ?? "";
1307
+ try {
1308
+ const resp = await this.handlers.onLoadRequest(env.data);
1309
+ const transfer = resp.ok ? [resp.bytes] : [];
1310
+ this.post("casual.load.response", resp, id, transfer);
1311
+ } catch (err) {
1312
+ this.post(
1313
+ "casual.load.response",
1314
+ {
1315
+ ok: false,
1316
+ code: "host_error",
1317
+ message: err instanceof Error ? err.message : String(err)
1318
+ },
1319
+ id
1320
+ );
1321
+ }
1322
+ return;
1323
+ }
1324
+ case "casual.save.request": {
1325
+ if (!this.handlers.onSaveRequest) return;
1326
+ const id = env.id ?? "";
1327
+ try {
1328
+ const resp = await this.handlers.onSaveRequest(env.data);
1329
+ this.post("casual.save.response", resp, id);
1330
+ } catch (err) {
1331
+ this.post(
1332
+ "casual.save.response",
1333
+ {
1334
+ ok: false,
1335
+ code: "host_error",
1336
+ message: err instanceof Error ? err.message : String(err)
1337
+ },
1338
+ id
1339
+ );
1340
+ }
1341
+ return;
1342
+ }
1343
+ case "casual.selection.changed":
1344
+ this.handlers.onSelectionChanged?.(env.data);
1345
+ return;
1346
+ case "casual.selection.format-state":
1347
+ this.handlers.onSelectionFormatState?.(env.data);
1348
+ return;
1349
+ case "casual.telemetry.event":
1350
+ this.handlers.onTelemetry?.(env.data);
1351
+ return;
1352
+ case "casual.signature.field.signed":
1353
+ this.handlers.onSignatureFieldSigned?.(env.data);
1354
+ return;
1355
+ case "casual.signature.complete":
1356
+ this.handlers.onSignatureComplete?.(env.data);
1357
+ return;
1358
+ case "casual.signature.cancel":
1359
+ this.handlers.onSignatureCancel?.(env.data);
1360
+ return;
1361
+ case "casual.signature.request.ack":
1362
+ return;
1363
+ case "casual.error":
1364
+ this.handlers.onError?.(env.data);
1365
+ return;
1366
+ default:
1367
+ return;
1368
+ }
1369
+ }
1370
+ post(type, data, id, transfer) {
1371
+ const env = {
1372
+ type,
1373
+ app: this.opts.app,
1374
+ v: 1,
1375
+ data,
1376
+ ...id ? { id } : {}
1377
+ };
1378
+ const send = this.opts.iframeWindow.postMessage.bind(
1379
+ this.opts.iframeWindow
1380
+ );
1381
+ send(env, this.opts.embedOrigin, transfer);
1382
+ }
1383
+ };
1384
+
1385
+ // src/sheets/CasualSheetsIframe.tsx
1386
+ import { jsx as jsx5 } from "react/jsx-runtime";
1387
+ var DEFAULT_STYLE2 = {
1388
+ width: "100%",
1389
+ height: "100%",
1390
+ border: "none",
1391
+ display: "block"
1392
+ };
1393
+ var CasualSheetsIframe = forwardRef(
1394
+ function CasualSheetsIframe2(props, ref) {
1395
+ const {
1396
+ fileSource,
1397
+ docId,
1398
+ viewMode = "editor",
1399
+ embedBasePath = "/embed/sheets",
1400
+ onSelectionChanged,
1401
+ onSelectionFormatState,
1402
+ onTelemetry,
1403
+ onError,
1404
+ style,
1405
+ className,
1406
+ testId = "casual-sheets-iframe"
1407
+ } = props;
1408
+ const iframeRef = useRef3(null);
1409
+ const transportRef = useRef3(null);
1410
+ const fileSourceRef = useRef3(fileSource);
1411
+ fileSourceRef.current = fileSource;
1412
+ const onLoad = useCallback(async (req) => {
1413
+ try {
1414
+ const { bytes, name, etag } = await fileSourceRef.current.open(req.docId);
1415
+ return {
1416
+ ok: true,
1417
+ bytes,
1418
+ fileName: name,
1419
+ ...etag !== void 0 ? { etag } : {}
1420
+ };
1421
+ } catch (err) {
1422
+ return {
1423
+ ok: false,
1424
+ code: "open_failed",
1425
+ message: err instanceof Error ? err.message : String(err)
1426
+ };
1427
+ }
1428
+ }, []);
1429
+ const onSave = useCallback(
1430
+ async (req) => {
1431
+ try {
1432
+ if (!fileSourceRef.current.save) {
1433
+ return {
1434
+ ok: false,
1435
+ code: "save_unsupported",
1436
+ message: "host fileSource does not implement save"
1437
+ };
1438
+ }
1439
+ const opts = req.baseEtag !== void 0 ? { etag: req.baseEtag } : void 0;
1440
+ const { etag } = await fileSourceRef.current.save(req.docId, req.bytes, opts);
1441
+ return { ok: true, etag };
1442
+ } catch (err) {
1443
+ return {
1444
+ ok: false,
1445
+ code: "save_failed",
1446
+ message: err instanceof Error ? err.message : String(err)
1447
+ };
1448
+ }
1449
+ },
1450
+ []
1451
+ );
1452
+ const onIframeLoad = useCallback(() => {
1453
+ const iframe = iframeRef.current;
1454
+ if (!iframe?.contentWindow) return;
1455
+ transportRef.current?.destroy();
1456
+ const transport = new EmbedHostTransport({
1457
+ app: "sheet",
1458
+ iframeWindow: iframe.contentWindow,
1459
+ embedOrigin: window.location.origin
1460
+ });
1461
+ transport.on({
1462
+ onLoadRequest: onLoad,
1463
+ onSaveRequest: onSave,
1464
+ ...onSelectionChanged ? { onSelectionChanged } : {},
1465
+ ...onSelectionFormatState ? { onSelectionFormatState } : {},
1466
+ ...onTelemetry ? { onTelemetry } : {},
1467
+ ...onError ? { onError } : {},
1468
+ onEditorReady: () => {
1469
+ transport.sendHostHello({ capabilities: ["load", "save"] });
1470
+ transport.sendSetViewMode({ viewMode });
1471
+ }
1472
+ });
1473
+ transportRef.current = transport;
1474
+ }, [
1475
+ onLoad,
1476
+ onSave,
1477
+ onSelectionChanged,
1478
+ onSelectionFormatState,
1479
+ onTelemetry,
1480
+ onError,
1481
+ viewMode
1482
+ ]);
1483
+ useEffect5(() => {
1484
+ transportRef.current?.sendSetViewMode({ viewMode });
1485
+ }, [viewMode]);
1486
+ useEffect5(() => {
1487
+ return () => {
1488
+ transportRef.current?.destroy();
1489
+ transportRef.current = null;
1490
+ };
1491
+ }, []);
1492
+ if (ref) {
1493
+ const apiRef = ref;
1494
+ apiRef.current = {
1495
+ setViewMode: (mode) => transportRef.current?.sendSetViewMode({ viewMode: mode }),
1496
+ iframe: () => iframeRef.current,
1497
+ executeCommand: (command) => transportRef.current?.sendCommandExecute({ command })
1498
+ };
1499
+ }
1500
+ const url = `${embedBasePath}/embed.html?app=sheet&docId=${encodeURIComponent(docId)}&viewMode=${viewMode}`;
1501
+ return /* @__PURE__ */ jsx5(
1502
+ "iframe",
1503
+ {
1504
+ ref: iframeRef,
1505
+ src: url,
1506
+ onLoad: onIframeLoad,
1507
+ title: "Casual Sheets",
1508
+ sandbox: "allow-scripts allow-same-origin allow-downloads allow-modals",
1509
+ style: { ...DEFAULT_STYLE2, ...style },
1510
+ className,
1511
+ "data-testid": testId
1512
+ }
1513
+ );
1514
+ }
1515
+ );
1516
+ export {
1517
+ CasualSheets,
1518
+ CasualSheetsIframe,
1519
+ DrawnSignaturePad,
1520
+ EmbedTransport,
1521
+ SigningPane,
1522
+ SigningProvider,
1523
+ TypedSignatureField,
1524
+ UploadedSignatureField,
1525
+ createCasualSheetsAPI,
1526
+ createSigningController,
1527
+ isCasualEnvelope,
1528
+ useSigning
1529
+ };
1530
+ //# sourceMappingURL=index.js.map