@xlsx-editor.dev/react 0.0.0-stage → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2597 @@
1
+ // src/XlsxEditor.tsx
2
+ import { forwardRef as forwardRef2 } from "react";
3
+
4
+ // src/XlsxEditorRoot.tsx
5
+ import {
6
+ forwardRef,
7
+ useEffect as useEffect2,
8
+ useImperativeHandle,
9
+ useLayoutEffect,
10
+ useRef,
11
+ useState
12
+ } from "react";
13
+ import {
14
+ createXlsxEditor,
15
+ cycleRegion,
16
+ emptySnapshotOf as emptySnapshotOf2,
17
+ followModeProp,
18
+ relabelEditor,
19
+ reportFontError,
20
+ sameFontSource,
21
+ sameNumberLocale,
22
+ watchFontErrors,
23
+ watchGridSetup,
24
+ whenOpenSettles
25
+ } from "@xlsx-editor.dev/core/editor";
26
+
27
+ // src/context.ts
28
+ import {
29
+ createContext,
30
+ useCallback,
31
+ useContext,
32
+ useEffect,
33
+ useMemo,
34
+ useSyncExternalStore
35
+ } from "react";
36
+ import {
37
+ createT,
38
+ deepMerge,
39
+ en
40
+ } from "@xlsx-editor.dev/i18n";
41
+ import {
42
+ emptySnapshotOf
43
+ } from "@xlsx-editor.dev/core/editor";
44
+ var XlsxEditorContext = createContext(null);
45
+ function translatorFor(locale) {
46
+ const merged = deepMerge(
47
+ en,
48
+ locale
49
+ );
50
+ return createT(merged, typeof locale?._lang === "string" ? locale._lang : "en");
51
+ }
52
+ var TranslationContext = createContext(translatorFor(void 0));
53
+ function useXlsxEditor() {
54
+ return useContext(XlsxEditorContext);
55
+ }
56
+ function useTranslation() {
57
+ return { t: useContext(TranslationContext) };
58
+ }
59
+ var RootModeContext = createContext("edit");
60
+ var ModeWaitsContext = createContext(false);
61
+ function useViewModeWaits() {
62
+ return useContext(ModeWaitsContext);
63
+ }
64
+ var LayoutPartsContext = createContext(null);
65
+ function useLayoutPart(part) {
66
+ const parts = useContext(LayoutPartsContext);
67
+ useEffect(() => {
68
+ if (!parts) return;
69
+ parts[part] += 1;
70
+ return () => {
71
+ parts[part] -= 1;
72
+ };
73
+ }, [parts, part]);
74
+ }
75
+ function useEditorState(selector, isEqual = Object.is) {
76
+ const editor = useXlsxEditor();
77
+ const empty = emptySnapshotOf(useContext(RootModeContext));
78
+ const subscribe = useCallback(
79
+ (onChange) => editor ? editor.subscribe(onChange) : () => void 0,
80
+ [editor]
81
+ );
82
+ const read = useMemo(() => {
83
+ let last = null;
84
+ return () => {
85
+ const snapshot = editor ? editor.snapshot() : empty;
86
+ if (last && last.snapshot === snapshot) return last.slice;
87
+ const slice = selector(snapshot);
88
+ const kept = last && isEqual(last.slice, slice) ? last.slice : slice;
89
+ last = { snapshot, slice: kept };
90
+ return kept;
91
+ };
92
+ }, [editor, empty, selector, isEqual]);
93
+ return useSyncExternalStore(subscribe, read, read);
94
+ }
95
+ var whole = (snapshot) => snapshot;
96
+ function useEditorSnapshot() {
97
+ return useEditorState(whole);
98
+ }
99
+
100
+ // src/is-development.ts
101
+ function developmentFrom(signals) {
102
+ const dev = signals.viteEnv?.DEV;
103
+ if (typeof dev === "boolean") return dev;
104
+ return signals.hasProcess && signals.nodeEnv !== "production";
105
+ }
106
+ function viteEnv() {
107
+ try {
108
+ return import.meta.env;
109
+ } catch {
110
+ return void 0;
111
+ }
112
+ }
113
+ function isDevelopment() {
114
+ const hasProcess = typeof process !== "undefined";
115
+ return developmentFrom({
116
+ viteEnv: viteEnv(),
117
+ nodeEnv: hasProcess ? process.env.NODE_ENV : void 0,
118
+ hasProcess
119
+ });
120
+ }
121
+
122
+ // src/color-mode.ts
123
+ import { createContext as createContext2, useContext as useContext2, useSyncExternalStore as useSyncExternalStore2 } from "react";
124
+ import {
125
+ resolveDarkChrome,
126
+ subscribeSystemDark,
127
+ systemPrefersDark
128
+ } from "@xlsx-editor.dev/core/editor";
129
+ var light = () => false;
130
+ var nothing = () => () => {
131
+ };
132
+ function useResolvedDark(mode) {
133
+ const following = mode === "system";
134
+ const systemDark = useSyncExternalStore2(
135
+ following ? subscribeSystemDark : nothing,
136
+ following ? systemPrefersDark : light,
137
+ light
138
+ );
139
+ return resolveDarkChrome(mode, systemDark);
140
+ }
141
+ var ScopedByAncestorContext = createContext2(false);
142
+ var ChromeDarkContext = createContext2(false);
143
+ function useChromeDark() {
144
+ return useContext2(ChromeDarkContext);
145
+ }
146
+ var LIGHT = Object.freeze({ colorMode: "light" });
147
+ var DARK = Object.freeze({ colorMode: "dark" });
148
+ function useEditorColorMode() {
149
+ return useContext2(ChromeDarkContext) ? DARK : LIGHT;
150
+ }
151
+ function useScopeClassName() {
152
+ const scoped = useContext2(ScopedByAncestorContext);
153
+ const dark = useContext2(ChromeDarkContext);
154
+ if (scoped) return "";
155
+ return dark ? "xlsx-editor dark " : "xlsx-editor ";
156
+ }
157
+
158
+ // src/XlsxEditorRoot.tsx
159
+ import { jsx } from "react/jsx-runtime";
160
+ var XlsxEditorRoot = forwardRef(
161
+ function XlsxEditorRoot2(props, ref) {
162
+ const { document: bytes, locale, mode = "edit", colorMode, children } = props;
163
+ const dark = useResolvedDark(colorMode);
164
+ const [editor, setEditorState] = useState(null);
165
+ const live = useRef(null);
166
+ const callbacks = useRef({
167
+ onReady: props.onReady,
168
+ onChange: props.onChange,
169
+ onFontError: props.onFontError
170
+ });
171
+ callbacks.current = {
172
+ onReady: props.onReady,
173
+ onChange: props.onChange,
174
+ onFontError: props.onFontError
175
+ };
176
+ const created = useRef({ fonts: props.fonts, numberLocale: props.numberLocale, mode });
177
+ const t = useTranslatorOf(locale);
178
+ const tRef = useRef(t);
179
+ tRef.current = t;
180
+ const modeRef = useRef(mode);
181
+ modeRef.current = mode;
182
+ const labeled = useRef(t);
183
+ useEffect2(() => {
184
+ if (!editor || labeled.current === t) return;
185
+ labeled.current = t;
186
+ relabelEditor(editor);
187
+ }, [editor, t]);
188
+ useImperativeHandle(
189
+ ref,
190
+ () => ({
191
+ load: async (b) => live.current ? live.current.load(b) : null,
192
+ save: () => live.current?.save() ?? null,
193
+ saveInTasks: async () => live.current ? live.current.saveInTasks() : null,
194
+ getEditor: () => live.current,
195
+ focus: () => live.current?.focus(),
196
+ snapshot: () => live.current?.snapshot() ?? emptySnapshotOf2(modeRef.current)
197
+ }),
198
+ []
199
+ );
200
+ useEffect2(() => {
201
+ const { fonts: fonts2, numberLocale: numberLocale2, mode: initialMode } = created.current;
202
+ const instance = createXlsxEditor({
203
+ // Omitted, the engine loads the packaged substitute faces and keeps their failures.
204
+ ...fonts2 ? { fonts: fonts2 } : {},
205
+ mode: initialMode,
206
+ ...numberLocale2 ? { numberLocale: numberLocale2 } : {},
207
+ // The engine's keys are keys of the shared catalog.
208
+ translate: (key, params) => tRef.current(key, params ? { ...params } : void 0)
209
+ });
210
+ live.current = instance;
211
+ setEditorState(instance);
212
+ const offFonts = watchFontErrors(
213
+ instance,
214
+ (f) => reportFontError(f, callbacks.current.onFontError)
215
+ );
216
+ const off = instance.subscribe(() => callbacks.current.onChange?.(instance.snapshot()));
217
+ return () => {
218
+ offFonts();
219
+ off();
220
+ if (live.current === instance) live.current = null;
221
+ instance.destroy();
222
+ };
223
+ }, []);
224
+ const opened = useRef(false);
225
+ useEffect2(() => {
226
+ if (!editor) return;
227
+ if (bytes) void editor.load(bytes);
228
+ else if (opened.current) editor.close();
229
+ opened.current = bytes !== void 0;
230
+ }, [editor, bytes]);
231
+ useEffect2(() => {
232
+ if (!editor) return void 0;
233
+ return whenOpenSettles(editor, () => callbacks.current.onReady?.(editor));
234
+ }, [editor]);
235
+ const { fonts, numberLocale } = props;
236
+ useEffect2(() => {
237
+ if (!editor || sameFontSource(fonts, created.current.fonts)) return;
238
+ created.current = { ...created.current, fonts };
239
+ void editor.setFonts(fonts).then((failure) => {
240
+ if (failure) reportFontError(failure, callbacks.current.onFontError);
241
+ });
242
+ }, [editor, fonts]);
243
+ useEffect2(() => {
244
+ if (!editor || sameNumberLocale(numberLocale, created.current.numberLocale)) return;
245
+ created.current = { ...created.current, numberLocale };
246
+ editor.setNumberLocale(numberLocale);
247
+ }, [editor, numberLocale]);
248
+ const modeProp = useRef(null);
249
+ const [modeWaits, setModeWaits] = useState(false);
250
+ useEffect2(() => {
251
+ if (!editor) return void 0;
252
+ const follow = followModeProp(editor, setModeWaits);
253
+ modeProp.current = follow;
254
+ return () => {
255
+ follow.dispose();
256
+ if (modeProp.current === follow) modeProp.current = null;
257
+ };
258
+ }, [editor]);
259
+ useEffect2(() => {
260
+ modeProp.current?.apply(mode);
261
+ }, [editor, mode]);
262
+ const parts = useRef({ grids: 0, statusMessages: 0 });
263
+ useEffect2(() => {
264
+ const { grids, statusMessages } = parts.current;
265
+ if (!editor || grids === 0 || statusMessages > 0 || !isDevelopment()) return;
266
+ console.warn(
267
+ "XlsxEditor.Root: the layout has no XlsxEditor.StatusMessage, so edit refusals and the stale-value notice are not shown. Add <XlsxEditor.StatusMessage /> to the layout."
268
+ );
269
+ }, [editor]);
270
+ return /* @__PURE__ */ jsx(XlsxEditorContext.Provider, { value: editor, children: /* @__PURE__ */ jsx(RootModeContext.Provider, { value: mode, children: /* @__PURE__ */ jsx(ModeWaitsContext.Provider, { value: modeWaits, children: /* @__PURE__ */ jsx(TranslationContext.Provider, { value: t, children: /* @__PURE__ */ jsx(LayoutPartsContext.Provider, { value: parts.current, children: /* @__PURE__ */ jsx(ChromeDarkContext.Provider, { value: dark, children }) }) }) }) }) });
271
+ }
272
+ );
273
+ function useTranslatorOf(locale) {
274
+ const key = locale ? JSON.stringify(locale) : "";
275
+ const memo = useRef(null);
276
+ if (memo.current?.key !== key) memo.current = { key, t: translatorFor(locale) };
277
+ return memo.current.t;
278
+ }
279
+ function XlsxEditorViewport({ className, label, style, children }) {
280
+ const { t } = useTranslation();
281
+ const editor = useXlsxEditor();
282
+ const dark = useChromeDark();
283
+ const region = label === false ? {} : { role: "region", "aria-label": label ?? t("viewport.ariaLabel") };
284
+ return /* @__PURE__ */ jsx(
285
+ "div",
286
+ {
287
+ className: ["xlsx-editor", dark ? "dark" : "", "xlsx-editor-viewport", className].filter(Boolean).join(" "),
288
+ ...style ? { style } : {},
289
+ ...region,
290
+ onKeyDown: (e) => void cycleRegion(e, e.currentTarget, editor),
291
+ children: /* @__PURE__ */ jsx(ScopedByAncestorContext.Provider, { value: true, children })
292
+ }
293
+ );
294
+ }
295
+ function XlsxEditorContent({ className }) {
296
+ const editor = useXlsxEditor();
297
+ useLayoutPart("grids");
298
+ const host = useRef(null);
299
+ useLayoutEffect(() => {
300
+ if (!editor || !host.current) return;
301
+ editor.attach(host.current);
302
+ return () => editor.detach();
303
+ }, [editor]);
304
+ useEffect2(() => {
305
+ const element = host.current;
306
+ if (!editor || !element || !isDevelopment()) return void 0;
307
+ return watchGridSetup(element, "XlsxEditor.Content", "@xlsx-editor.dev/react/styles.css");
308
+ }, [editor]);
309
+ return /* @__PURE__ */ jsx("div", { ref: host, className: `xlsx-canvas${className ? ` ${className}` : ""}` });
310
+ }
311
+
312
+ // src/chrome.tsx
313
+ import { useContext as useContext3 } from "react";
314
+ import {
315
+ MAX_ZOOM,
316
+ MIN_ZOOM,
317
+ keepGridFocus,
318
+ sameSlice,
319
+ statusSlice,
320
+ statusView,
321
+ zoomSlice
322
+ } from "@xlsx-editor.dev/core/editor";
323
+
324
+ // src/icons.tsx
325
+ import { jsx as jsx2 } from "react/jsx-runtime";
326
+ var ADD = "M440-440H200v-80h240v-240h80v240h240v80H520v240h-80v-240Z";
327
+ var REMOVE = "M200-440v-80h560v80H200Z";
328
+ function Icon({ d }) {
329
+ return /* @__PURE__ */ jsx2("svg", { viewBox: "0 -960 960 960", "aria-hidden": "true", focusable: "false", children: /* @__PURE__ */ jsx2("path", { d }) });
330
+ }
331
+ var ZoomInIcon = () => /* @__PURE__ */ jsx2(Icon, { d: ADD });
332
+ var ZoomOutIcon = () => /* @__PURE__ */ jsx2(Icon, { d: REMOVE });
333
+ var AddIcon = () => /* @__PURE__ */ jsx2(Icon, { d: ADD });
334
+
335
+ // src/chrome.tsx
336
+ import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
337
+ function ZoomControl() {
338
+ const { t } = useTranslation();
339
+ const editor = useXlsxEditor();
340
+ const snap = useEditorState(zoomSlice, sameSlice);
341
+ if (snap.status !== "ready") return null;
342
+ const level = `${Math.round(snap.zoom * 100)}%`;
343
+ const atMin = snap.zoom <= MIN_ZOOM;
344
+ const atMax = snap.zoom >= MAX_ZOOM;
345
+ return /* @__PURE__ */ jsxs(
346
+ "div",
347
+ {
348
+ className: "xlsx-zoom",
349
+ role: "group",
350
+ "aria-label": t("zoom.zoomLevel"),
351
+ onMouseDown: keepGridFocus,
352
+ children: [
353
+ /* @__PURE__ */ jsx3(
354
+ "button",
355
+ {
356
+ type: "button",
357
+ "aria-label": t("zoom.zoomOut"),
358
+ title: t("zoom.zoomOut"),
359
+ "aria-disabled": atMin,
360
+ onClick: () => {
361
+ if (!atMin) editor?.zoomStep(-1);
362
+ },
363
+ children: /* @__PURE__ */ jsx3(ZoomOutIcon, {})
364
+ }
365
+ ),
366
+ /* @__PURE__ */ jsx3(
367
+ "button",
368
+ {
369
+ type: "button",
370
+ className: "xlsx-zoom-level",
371
+ "aria-label": t("zoom.resetAt", { level }),
372
+ title: t("zoom.reset"),
373
+ onClick: () => editor?.setZoom(1),
374
+ children: level
375
+ }
376
+ ),
377
+ /* @__PURE__ */ jsx3(
378
+ "button",
379
+ {
380
+ type: "button",
381
+ "aria-label": t("zoom.zoomIn"),
382
+ title: t("zoom.zoomIn"),
383
+ "aria-disabled": atMax,
384
+ onClick: () => {
385
+ if (!atMax) editor?.zoomStep(1);
386
+ },
387
+ children: /* @__PURE__ */ jsx3(ZoomInIcon, {})
388
+ }
389
+ )
390
+ ]
391
+ }
392
+ );
393
+ }
394
+ function Notice(props) {
395
+ const { on, short, text, brief } = props;
396
+ return /* @__PURE__ */ jsx3(
397
+ "div",
398
+ {
399
+ className: "xlsx-notice",
400
+ role: "status",
401
+ ...on ? { title: text } : {},
402
+ ...on && short ? { "data-short": "" } : {},
403
+ children: on ? /* @__PURE__ */ jsxs(Fragment, { children: [
404
+ /* @__PURE__ */ jsx3("span", { className: "xlsx-notice-full", children: text }),
405
+ /* @__PURE__ */ jsx3("span", { className: "xlsx-notice-brief", "aria-hidden": "true", children: brief })
406
+ ] }) : null
407
+ }
408
+ );
409
+ }
410
+ function StatusMessage() {
411
+ const { t } = useTranslation();
412
+ const snap = useEditorState(statusSlice, sameSlice);
413
+ const modeWaits = useContext3(ModeWaitsContext);
414
+ useLayoutPart("statusMessages");
415
+ const view = statusView(snap, modeWaits, t);
416
+ if (view.kind === "strip")
417
+ return /* @__PURE__ */ jsxs("div", { className: "xlsx-status-strip", children: [
418
+ view.refusal ? /* @__PURE__ */ jsx3("div", { className: "xlsx-refusal", children: view.refusal }) : null,
419
+ view.notices.map((n) => /* @__PURE__ */ jsx3(Notice, { on: n.on, short: n.short, text: n.text, brief: n.brief }, n.id))
420
+ ] });
421
+ return /* @__PURE__ */ jsxs("div", { className: "xlsx-message", children: [
422
+ /* @__PURE__ */ jsx3("div", { role: view.role, children: view.text }),
423
+ view.refusals.map((text) => /* @__PURE__ */ jsx3("div", { className: "xlsx-message-refusal", children: text }, text))
424
+ ] });
425
+ }
426
+
427
+ // src/FormulaBar.tsx
428
+ import { useCallback as useCallback2, useId, useLayoutEffect as useLayoutEffect2, useRef as useRef2, useState as useState2 } from "react";
429
+ import {
430
+ MAX_GO_TO_LENGTH,
431
+ composesKey,
432
+ contentFieldText,
433
+ editMoveOf,
434
+ formulaSlice,
435
+ insertFieldText,
436
+ keepGridFocus as keepGridFocus2,
437
+ pressFieldBox,
438
+ refusalText,
439
+ refusesEditText,
440
+ refusesReference,
441
+ sameSlice as sameSlice2,
442
+ showCaretLine,
443
+ stepFieldHistory
444
+ } from "@xlsx-editor.dev/core/editor";
445
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
446
+ function FormulaBar() {
447
+ const { t } = useTranslation();
448
+ const editor = useXlsxEditor();
449
+ const snap = useEditorState(formulaSlice, sameSlice2);
450
+ const composing = useRef2(false);
451
+ const field = useRef2(null);
452
+ const caret = useRef2(null);
453
+ const [refusedText, setRefusedText] = useState2(null);
454
+ const hintId = useId();
455
+ const reasonId = useId();
456
+ const shortenedId = useId();
457
+ const { editing, refusal, text } = snap;
458
+ const seen = useRef2(null);
459
+ useLayoutEffect2(() => {
460
+ if (!editing) setRefusedText(null);
461
+ else if (refusal !== seen.current)
462
+ setRefusedText(refusal && refusesEditText(refusal.code) ? text : null);
463
+ seen.current = refusal;
464
+ }, [refusal, editing, text]);
465
+ useLayoutEffect2(() => {
466
+ const at = caret.current;
467
+ caret.current = null;
468
+ if (at !== null) field.current?.setSelectionRange(at, at);
469
+ showCaretLine(field.current);
470
+ });
471
+ const bindField = useCallback2(
472
+ (el) => {
473
+ field.current = el;
474
+ if (el || !composing.current) return;
475
+ composing.current = false;
476
+ const s = editor?.snapshot();
477
+ if (s?.editing) editor?.setEditText(s.editText ?? "", { composing: false });
478
+ },
479
+ [editor]
480
+ );
481
+ if (snap.status !== "ready") return null;
482
+ const type = (value, composes) => editor?.setEditText(value, { composing: composes }).ok === true;
483
+ const shown = contentFieldText(text);
484
+ const shortened = shown.length < text.length;
485
+ const readOnly = snap.view || shortened;
486
+ const shortenedNote = `${t("formulaBar.shortened")}${snap.view ? "" : ` ${t("formulaBar.shortenedEdit")}`}`;
487
+ const endComposition = (value) => {
488
+ if (!composing.current) return;
489
+ composing.current = false;
490
+ const open = editor?.snapshot();
491
+ if (open?.editing) type(shortened ? open.editText ?? "" : value, false);
492
+ };
493
+ const invalid = editing && refusal !== null && refusedText === text;
494
+ const onKeyDown = (e) => {
495
+ if (!editor || composesKey(e.nativeEvent, composing.current)) return;
496
+ if (stepFieldHistory(e, editor, editing)) return;
497
+ const move = editMoveOf(e);
498
+ if (move) {
499
+ e.preventDefault();
500
+ editor.commitEdit(move);
501
+ } else if (e.key === "Enter" && e.altKey && !readOnly) {
502
+ e.preventDefault();
503
+ if (insertFieldText(e.currentTarget, "\n")) return;
504
+ const { value, selectionStart, selectionEnd } = e.currentTarget;
505
+ const next = `${value.slice(0, selectionStart)}
506
+ ${value.slice(selectionEnd)}`;
507
+ if (type(next, false)) caret.current = selectionStart + 1;
508
+ } else if (e.key === "Escape") {
509
+ e.preventDefault();
510
+ e.stopPropagation();
511
+ if (editor.snapshot().editing) editor.cancelEdit();
512
+ else editor.focus();
513
+ }
514
+ };
515
+ const lines = shortened ? 1 : text.split("\n").length;
516
+ const reason = invalid && refusal ? refusalText(refusal, t, snap.numberLocale) : "";
517
+ return /* @__PURE__ */ jsxs2("div", { className: "xlsx-formula-bar", onMouseDown: keepGridFocus2, children: [
518
+ /* @__PURE__ */ jsx4(NameBox, { reference: snap.ref ?? "", contentField: field }),
519
+ /* @__PURE__ */ jsxs2(
520
+ "div",
521
+ {
522
+ className: "xlsx-cell-content-box",
523
+ "data-lines": lines > 1 ? "" : void 0,
524
+ onMouseDown: (e) => pressFieldBox(field.current, e),
525
+ children: [
526
+ /* @__PURE__ */ jsx4(
527
+ "textarea",
528
+ {
529
+ ref: bindField,
530
+ className: "xlsx-cell-content",
531
+ name: "xlsx-cell-content",
532
+ rows: 1,
533
+ wrap: "off",
534
+ spellCheck: false,
535
+ autoComplete: "off",
536
+ autoCapitalize: "off",
537
+ "aria-label": t("formulaBar.content"),
538
+ "aria-describedby": shortened ? shortenedId : snap.view ? void 0 : invalid ? `${reasonId} ${hintId}` : hintId,
539
+ readOnly,
540
+ "aria-invalid": invalid || void 0,
541
+ value: shown,
542
+ onChange: (e) => {
543
+ if (shortened) return;
544
+ const event = e.nativeEvent;
545
+ type(e.currentTarget.value, composing.current || event.isComposing === true);
546
+ },
547
+ onCompositionStart: () => {
548
+ composing.current = true;
549
+ },
550
+ onCompositionEnd: (e) => endComposition(e.currentTarget.value),
551
+ onBlur: (e) => endComposition(e.currentTarget.value),
552
+ onKeyDown,
553
+ onSelect: (e) => showCaretLine(e.currentTarget)
554
+ }
555
+ ),
556
+ shortened ? /* @__PURE__ */ jsx4(
557
+ "span",
558
+ {
559
+ id: shortenedId,
560
+ className: "xlsx-cell-content-lines xlsx-cell-content-note",
561
+ title: shortenedNote,
562
+ children: shortenedNote
563
+ }
564
+ ) : lines > 1 ? /* @__PURE__ */ jsx4("span", { className: "xlsx-cell-content-lines", "aria-hidden": "true", children: t("formulaBar.lines", { count: lines }) }) : null
565
+ ]
566
+ }
567
+ ),
568
+ /* @__PURE__ */ jsx4("span", { id: hintId, hidden: true, children: t("formulaBar.contentHint") }),
569
+ /* @__PURE__ */ jsx4("span", { id: reasonId, hidden: true, children: reason })
570
+ ] });
571
+ }
572
+ function NameBox(props) {
573
+ const { t } = useTranslation();
574
+ const editor = useXlsxEditor();
575
+ const reason = useEditorState(
576
+ (s) => s.refusal ? refusalText(s.refusal, t, s.numberLocale) : "",
577
+ Object.is
578
+ );
579
+ const [draft, setDraft] = useState2(null);
580
+ const [refused, setRefused] = useState2(false);
581
+ const composing = useRef2(false);
582
+ const hintId = useId();
583
+ const reasonId = useId();
584
+ const raised = useRef2(false);
585
+ const reset = () => {
586
+ setDraft(null);
587
+ setRefused(false);
588
+ raised.current = false;
589
+ };
590
+ const drop = (editor2) => {
591
+ if (raised.current && refusesReference(editor2.snapshot().refusal?.code ?? "loading"))
592
+ editor2.dismissRefusal();
593
+ reset();
594
+ };
595
+ const go = (editor2, text) => {
596
+ if (text.trim() === "") {
597
+ drop(editor2);
598
+ editor2.focus();
599
+ return;
600
+ }
601
+ const r = editor2.selectReference(text);
602
+ if (r.ok) {
603
+ reset();
604
+ editor2.focus();
605
+ } else if (refusesReference(r.refusal.code)) {
606
+ setDraft(text);
607
+ setRefused(true);
608
+ raised.current = true;
609
+ } else {
610
+ reset();
611
+ props.contentField.current?.focus();
612
+ }
613
+ };
614
+ return /* @__PURE__ */ jsxs2(Fragment2, { children: [
615
+ /* @__PURE__ */ jsx4(
616
+ "input",
617
+ {
618
+ className: "xlsx-name-box",
619
+ name: "xlsx-name-box",
620
+ type: "text",
621
+ spellCheck: false,
622
+ autoComplete: "off",
623
+ autoCapitalize: "off",
624
+ maxLength: MAX_GO_TO_LENGTH,
625
+ "aria-label": t("formulaBar.nameBox"),
626
+ "aria-describedby": refused ? `${reasonId} ${hintId}` : hintId,
627
+ "aria-invalid": refused || void 0,
628
+ value: draft ?? props.reference,
629
+ onFocus: (e) => e.currentTarget.select(),
630
+ onChange: (e) => {
631
+ setDraft(e.currentTarget.value);
632
+ setRefused(false);
633
+ },
634
+ onBlur: () => {
635
+ if (editor) drop(editor);
636
+ else reset();
637
+ },
638
+ onCompositionStart: () => {
639
+ composing.current = true;
640
+ },
641
+ onCompositionEnd: () => {
642
+ composing.current = false;
643
+ },
644
+ onKeyDown: (e) => {
645
+ if (!editor || composesKey(e.nativeEvent, composing.current)) return;
646
+ if (stepFieldHistory(e, editor, draft !== null || editor.snapshot().editing)) return;
647
+ if (e.key === "Enter") {
648
+ e.preventDefault();
649
+ go(editor, e.currentTarget.value);
650
+ } else if (e.key === "Escape") {
651
+ e.preventDefault();
652
+ e.stopPropagation();
653
+ drop(editor);
654
+ editor.focus();
655
+ }
656
+ }
657
+ }
658
+ ),
659
+ /* @__PURE__ */ jsx4("span", { id: hintId, hidden: true, children: t("formulaBar.nameBoxHint") }),
660
+ /* @__PURE__ */ jsx4("span", { id: reasonId, hidden: true, children: refused ? reason : "" })
661
+ ] });
662
+ }
663
+
664
+ // src/SheetTabs.tsx
665
+ import {
666
+ Fragment as Fragment3,
667
+ useEffect as useEffect3,
668
+ useId as useId2,
669
+ useLayoutEffect as useLayoutEffect3,
670
+ useRef as useRef3,
671
+ useState as useState3
672
+ } from "react";
673
+ import {
674
+ RENAME_COMMIT_EVENT,
675
+ disabledReasonText,
676
+ focusAfterRelease,
677
+ historyShortcutOf,
678
+ keepGridFocus as keepGridFocus3,
679
+ listenSheetMenuDismiss,
680
+ moveInSheetMenu,
681
+ openSheetMenu,
682
+ refusalText as refusalText2,
683
+ sameSlice as sameSlice3,
684
+ scrollIntoNearestScroller,
685
+ sheetCommandState,
686
+ sheetListKey,
687
+ sheetMenuLeft,
688
+ sheetRenameBox,
689
+ tabKey,
690
+ tabsSlice
691
+ } from "@xlsx-editor.dev/core/editor";
692
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
693
+ function SheetTabs() {
694
+ const { t } = useTranslation();
695
+ const editor = useXlsxEditor();
696
+ const snap = useEditorState(tabsSlice, sameSlice3);
697
+ const bar = useRef3(null);
698
+ const list = useRef3(null);
699
+ const menuRef = useRef3(null);
700
+ const addRef = useRef3(null);
701
+ const [menu, setMenu] = useState3(null);
702
+ const [renaming, setRenaming] = useState3(null);
703
+ const [focusSheet, setFocusSheet] = useState3(null);
704
+ const reasonId = useId2();
705
+ const viewReasonId = useId2();
706
+ const renameReasonId = useId2();
707
+ const tabReasonId = useId2();
708
+ const stateOf = (command, sheet2 = -1) => sheetCommandState(snap, command, sheet2);
709
+ const addState = stateOf("add");
710
+ const sheetLock = addState.disabledReason ? disabledReasonText(addState.disabledReason, t) : null;
711
+ const blocked = !addState.enabled;
712
+ useEffect3(() => {
713
+ if (focusSheet === null) return;
714
+ setFocusSheet(null);
715
+ list.current?.querySelector(`[data-sheet-index="${focusSheet}"]`)?.focus();
716
+ }, [focusSheet]);
717
+ const active = snap.activeSheet;
718
+ const listKey = sheetListKey(snap.sheets);
719
+ useEffect3(() => {
720
+ const tab = list.current?.querySelector(`[data-sheet-index="${active}"]`);
721
+ if (tab) scrollIntoNearestScroller(tab, list.current);
722
+ }, [active, listKey]);
723
+ const renameField = useRef3(null);
724
+ const refusedPress = useRef3(false);
725
+ const listFocused = useRef3(false);
726
+ const renameRefused = useRef3(false);
727
+ const renameRefusal = useRef3(null);
728
+ useEffect3(() => {
729
+ renameField.current?.drop();
730
+ const field = bar.current?.ownerDocument.activeElement;
731
+ if (field && bar.current?.contains(field) && field.classList.contains("xlsx-sheet-rename"))
732
+ editor?.focus();
733
+ setRenaming(null);
734
+ }, [listKey, editor]);
735
+ useEffect3(() => {
736
+ const el = bar.current;
737
+ if (!menu || !el) return;
738
+ return listenSheetMenuDismiss(
739
+ el,
740
+ (node) => menuRef.current?.contains(node) ?? false,
741
+ () => setMenu(null)
742
+ );
743
+ }, [menu]);
744
+ useLayoutEffect3(() => {
745
+ const el = menuRef.current;
746
+ if (!menu || !el) return;
747
+ return openSheetMenu(el, bar.current, menu.left, menu, editor);
748
+ }, [menu, editor]);
749
+ const tabs = snap.sheets.filter((s) => s.visible);
750
+ if (snap.status !== "ready" || tabs.length === 0) return null;
751
+ const choose = (index) => editor?.setActiveSheet(index) ?? false;
752
+ const openMenu = (sheet2, tab, clientX) => {
753
+ const had = tab.ownerDocument.activeElement;
754
+ const inList = !!had && !!list.current?.contains(had);
755
+ const back = clientX === void 0 || inList ? tab : had;
756
+ if (!choose(sheet2)) return;
757
+ setMenu({
758
+ sheet: sheet2,
759
+ left: sheetMenuLeft(bar.current, tab, clientX),
760
+ back,
761
+ keyboard: clientX === void 0
762
+ });
763
+ };
764
+ const renameBox = (name) => sheetRenameBox(
765
+ { bar: bar.current, list: list.current, add: addRef.current },
766
+ snap.sheets,
767
+ name
768
+ );
769
+ const commitRename = (press) => {
770
+ const open = renameField.current;
771
+ if (!renaming || !open) return true;
772
+ const written = open.commit();
773
+ if (!press || !written) editor?.focus();
774
+ else focusAfterRelease(press, () => editor?.focus());
775
+ return written;
776
+ };
777
+ const startRename = (sheet2) => {
778
+ if (!stateOf("rename", sheet2).enabled) return;
779
+ if (editor && !editor.commitEdit().ok) return;
780
+ const shown = editor?.snapshot().refusal;
781
+ if (shown && shown === renameRefusal.current) editor?.dismissRefusal();
782
+ renameRefusal.current = null;
783
+ const name = snap.sheets[sheet2]?.name;
784
+ renameRefused.current = false;
785
+ if (name !== void 0) setRenaming(renameBox(name));
786
+ };
787
+ const onTabKeyDown = (e, sheet2) => {
788
+ const history = historyShortcutOf(e);
789
+ if (history) {
790
+ e.preventDefault();
791
+ if (history === "undo") editor?.undo();
792
+ else editor?.redo();
793
+ const shown = editor?.snapshot().activeSheet;
794
+ if (shown !== void 0 && shown >= 0) setFocusSheet(shown);
795
+ return;
796
+ }
797
+ if (e.key === "F10" && e.shiftKey || e.key === "ContextMenu") {
798
+ e.preventDefault();
799
+ openMenu(sheet2, e.currentTarget);
800
+ return;
801
+ }
802
+ if (e.key === "F2") {
803
+ e.preventDefault();
804
+ startRename(sheet2);
805
+ return;
806
+ }
807
+ const sheets = tabs.filter((s) => s.worksheet);
808
+ const position = sheets.findIndex((s) => s.index === sheet2);
809
+ const step = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
810
+ const next = e.key === "Home" ? 0 : e.key === "End" ? sheets.length - 1 : step ? position + step : -1;
811
+ if (position < 0 || next < 0 || next >= sheets.length) return;
812
+ e.preventDefault();
813
+ const target = sheets[next];
814
+ if (!choose(target.index)) return;
815
+ list.current?.querySelector(`[data-sheet-index="${target.index}"]`)?.focus();
816
+ };
817
+ const onMenuKeyDown = (e) => {
818
+ const history = historyShortcutOf(e);
819
+ if (history) {
820
+ e.preventDefault();
821
+ e.stopPropagation();
822
+ setMenu(null);
823
+ if (history === "undo") editor?.undo();
824
+ else editor?.redo();
825
+ const shown = editor?.snapshot().activeSheet;
826
+ if (shown !== void 0 && shown >= 0) setFocusSheet(shown);
827
+ return;
828
+ }
829
+ if (e.key === "Escape" || e.key === "Tab") {
830
+ e.preventDefault();
831
+ e.stopPropagation();
832
+ setMenu(null);
833
+ return;
834
+ }
835
+ if (menuRef.current && moveInSheetMenu(menuRef.current, e.key)) {
836
+ e.preventDefault();
837
+ e.stopPropagation();
838
+ }
839
+ };
840
+ const item = (command, label, state, run) => {
841
+ const disabled = !state.enabled;
842
+ const reason = disabled && state.disabledReason ? disabledReasonText(state.disabledReason, t) : null;
843
+ const id = `${reasonId}-${command}`;
844
+ return /* @__PURE__ */ jsxs3(Fragment3, { children: [
845
+ /* @__PURE__ */ jsx5(
846
+ "button",
847
+ {
848
+ type: "button",
849
+ role: "menuitem",
850
+ className: "xlsx-sheet-menu-item",
851
+ tabIndex: -1,
852
+ "aria-disabled": disabled || void 0,
853
+ ...reason ? { title: t("toolbar.disabledTitle", { label, reason }), "aria-describedby": id } : {},
854
+ onMouseDown: keepGridFocus3,
855
+ onClick: () => {
856
+ if (!disabled) run();
857
+ },
858
+ children: label
859
+ }
860
+ ),
861
+ reason ? /* @__PURE__ */ jsx5("span", { id, hidden: true, children: reason }) : null
862
+ ] }, command);
863
+ };
864
+ const sheet = menu?.sheet ?? -1;
865
+ const renameState = stateOf("rename", sheet);
866
+ const deleteState = stateOf("delete", sheet);
867
+ const leftState = stateOf("moveLeft", sheet);
868
+ const rightState = stateOf("moveRight", sheet);
869
+ const keyboardMenu = menu?.keyboard ?? false;
870
+ const moveTo = (to) => {
871
+ setMenu(null);
872
+ const r = editor?.moveSheet(sheet, to);
873
+ if (keyboardMenu) setFocusSheet(r?.ok ? to : sheet);
874
+ };
875
+ const renameReason = renaming && renameRefused.current && snap.refusal ? refusalText2(snap.refusal, t, snap.numberLocale) : null;
876
+ const viewReason = { id: viewReasonId, text: sheetLock ?? "" };
877
+ const notWorksheet = disabledReasonText({ key: "disabledReason.notWorksheet" }, t);
878
+ const tabReasons = /* @__PURE__ */ new Map();
879
+ const tabReason = (s) => {
880
+ const state = stateOf("rename", s.index);
881
+ const text = !s.worksheet ? notWorksheet : !state.enabled && state.disabledReason ? disabledReasonText(state.disabledReason, t) : null;
882
+ if (text === null) return null;
883
+ let id = tabReasons.get(text);
884
+ if (id === void 0) tabReasons.set(text, id = `${tabReasonId}-${tabReasons.size}`);
885
+ return { text, id };
886
+ };
887
+ const reasonOfTab = tabs.map(tabReason);
888
+ const addLabel = t("sheetTabs.add");
889
+ return /* @__PURE__ */ jsxs3("div", { className: "xlsx-sheet-bar", ref: bar, onMouseDown: keepGridFocus3, children: [
890
+ /* @__PURE__ */ jsx5(
891
+ "div",
892
+ {
893
+ className: "xlsx-sheet-tabs",
894
+ role: "tablist",
895
+ "aria-label": t("sheetTabs.ariaLabel"),
896
+ ref: list,
897
+ onScroll: () => {
898
+ if (renaming) setRenaming(renameBox(renaming.name));
899
+ },
900
+ children: tabs.map((s, i) => /* @__PURE__ */ jsx5(
901
+ "button",
902
+ {
903
+ type: "button",
904
+ role: "tab",
905
+ className: `xlsx-sheet-tab${renaming?.name === s.name ? " xlsx-sheet-tab-renaming" : ""}`,
906
+ "data-sheet-index": s.index,
907
+ "aria-selected": s.index === snap.activeSheet,
908
+ ...s.worksheet ? { "aria-haspopup": "menu", "aria-expanded": menu?.sheet === s.index } : { "aria-disabled": true },
909
+ tabIndex: s.worksheet && s.index === snap.activeSheet ? 0 : -1,
910
+ "aria-describedby": reasonOfTab[i]?.id,
911
+ title: reasonOfTab[i] ? t("toolbar.disabledTitle", { label: s.name, reason: reasonOfTab[i].text }) : s.name,
912
+ onMouseDown: (e) => {
913
+ keepGridFocus3(e);
914
+ const doc = e.currentTarget.ownerDocument;
915
+ listFocused.current = list.current?.contains(doc.activeElement) ?? false;
916
+ if (e.detail <= 1) refusedPress.current = !commitRename(doc);
917
+ },
918
+ onClick: (e) => {
919
+ if (refusedPress.current || !s.worksheet) return;
920
+ choose(s.index);
921
+ if (listFocused.current) e.currentTarget.focus();
922
+ else if (!renaming) editor?.focus();
923
+ },
924
+ onDoubleClick: () => {
925
+ if (!refusedPress.current && s.worksheet) startRename(s.index);
926
+ },
927
+ onContextMenu: (e) => {
928
+ e.preventDefault();
929
+ if (refusedPress.current || !s.worksheet) return;
930
+ openMenu(s.index, e.currentTarget, e.clientX);
931
+ },
932
+ onKeyDown: (e) => {
933
+ if (s.worksheet) onTabKeyDown(e, s.index);
934
+ },
935
+ children: s.name
936
+ },
937
+ tabKey(tabs, i)
938
+ ))
939
+ }
940
+ ),
941
+ renaming ? /* @__PURE__ */ jsx5(
942
+ RenameField,
943
+ {
944
+ name: renaming.name,
945
+ label: t("sheetTabs.renameInput"),
946
+ box: renaming,
947
+ reasonId: renameReason ? renameReasonId : void 0,
948
+ handle: renameField,
949
+ focusGrid: () => editor?.focus(),
950
+ onDone: (name, keyboard) => {
951
+ const sheet2 = editor?.snapshot().sheets.find((s) => s.name === renaming.name);
952
+ let written = true;
953
+ if (name !== null && sheet2) {
954
+ const r = editor?.renameSheet(sheet2.index, name);
955
+ written = r?.ok ?? false;
956
+ renameRefused.current = !written;
957
+ renameRefusal.current = written ? null : editor?.snapshot().refusal ?? null;
958
+ if (!written && keyboard) return false;
959
+ }
960
+ setRenaming(null);
961
+ if (keyboard && sheet2) setFocusSheet(sheet2.index);
962
+ return written;
963
+ },
964
+ onCancel: () => {
965
+ if (renameRefused.current) editor?.dismissRefusal();
966
+ renameRefused.current = false;
967
+ }
968
+ },
969
+ renaming.name
970
+ ) : null,
971
+ blocked ? /* @__PURE__ */ jsx5("span", { id: viewReasonId, hidden: true, children: viewReason.text }) : null,
972
+ [...tabReasons].map(([text, id]) => /* @__PURE__ */ jsx5("span", { id, hidden: true, children: text }, id)),
973
+ renameReason ? /* @__PURE__ */ jsx5("span", { id: renameReasonId, hidden: true, children: renameReason }) : null,
974
+ /* @__PURE__ */ jsx5(
975
+ "button",
976
+ {
977
+ ref: addRef,
978
+ type: "button",
979
+ className: "xlsx-sheet-add",
980
+ "aria-label": addLabel,
981
+ title: blocked ? t("toolbar.disabledTitle", { label: addLabel, reason: viewReason.text }) : addLabel,
982
+ "aria-disabled": blocked || void 0,
983
+ "aria-describedby": blocked ? viewReasonId : void 0,
984
+ onMouseDown: keepGridFocus3,
985
+ onKeyDown: (e) => {
986
+ const history = historyShortcutOf(e);
987
+ if (!history) return;
988
+ e.preventDefault();
989
+ if (history === "undo") editor?.undo();
990
+ else editor?.redo();
991
+ },
992
+ onClick: (e) => {
993
+ if (blocked) return;
994
+ const doc = e.currentTarget.ownerDocument;
995
+ const fromList = list.current?.contains(doc.activeElement) ?? false;
996
+ if (commitRename() && editor?.addSheet().ok && fromList)
997
+ setFocusSheet(editor.snapshot().activeSheet);
998
+ },
999
+ children: /* @__PURE__ */ jsx5(AddIcon, {})
1000
+ }
1001
+ ),
1002
+ menu ? /* @__PURE__ */ jsxs3(
1003
+ "div",
1004
+ {
1005
+ ref: menuRef,
1006
+ className: "xlsx-sheet-menu",
1007
+ role: "menu",
1008
+ "aria-label": t("sheetTabs.menu"),
1009
+ style: { left: menu.left },
1010
+ onMouseDown: keepGridFocus3,
1011
+ onContextMenu: (e) => e.preventDefault(),
1012
+ onKeyDown: onMenuKeyDown,
1013
+ children: [
1014
+ item("rename", t("sheetTabs.rename"), renameState, () => {
1015
+ setMenu(null);
1016
+ startRename(sheet);
1017
+ }),
1018
+ item("delete", t("sheetTabs.delete"), deleteState, () => {
1019
+ setMenu(null);
1020
+ editor?.deleteSheet(sheet);
1021
+ const shown = editor?.snapshot().activeSheet;
1022
+ if (keyboardMenu && shown !== void 0 && shown >= 0) setFocusSheet(shown);
1023
+ }),
1024
+ item("moveLeft", t("sheetTabs.moveLeft"), leftState, () => moveTo(leftState.to)),
1025
+ item("moveRight", t("sheetTabs.moveRight"), rightState, () => moveTo(rightState.to))
1026
+ ]
1027
+ }
1028
+ ) : null
1029
+ ] });
1030
+ }
1031
+ function RenameField({
1032
+ name,
1033
+ label,
1034
+ box,
1035
+ reasonId,
1036
+ handle,
1037
+ focusGrid,
1038
+ onDone,
1039
+ onCancel
1040
+ }) {
1041
+ const [value, setValue] = useState3(name);
1042
+ const field = useRef3(null);
1043
+ const ended = useRef3(false);
1044
+ useLayoutEffect3(() => {
1045
+ field.current?.focus();
1046
+ field.current?.select();
1047
+ }, []);
1048
+ const finish = (write, keyboard) => {
1049
+ if (ended.current) return true;
1050
+ ended.current = true;
1051
+ const next = value.trim();
1052
+ const written = onDone(write && next !== "" && next !== name ? next : null, keyboard);
1053
+ if (!written && keyboard) {
1054
+ ended.current = false;
1055
+ field.current?.focus();
1056
+ }
1057
+ return written;
1058
+ };
1059
+ useLayoutEffect3(() => {
1060
+ handle.current = {
1061
+ commit: () => finish(true, false),
1062
+ drop: () => {
1063
+ ended.current = true;
1064
+ }
1065
+ };
1066
+ const el = field.current;
1067
+ const onCommit = (e) => {
1068
+ e.detail.written = finish(true, false);
1069
+ focusGrid();
1070
+ };
1071
+ el?.addEventListener(RENAME_COMMIT_EVENT, onCommit);
1072
+ return () => {
1073
+ handle.current = null;
1074
+ el?.removeEventListener(RENAME_COMMIT_EVENT, onCommit);
1075
+ };
1076
+ });
1077
+ return /* @__PURE__ */ jsx5(
1078
+ "input",
1079
+ {
1080
+ ref: field,
1081
+ className: "xlsx-sheet-rename",
1082
+ "aria-label": label,
1083
+ "aria-invalid": reasonId ? true : void 0,
1084
+ "aria-describedby": reasonId,
1085
+ value,
1086
+ style: { left: box.left, minWidth: box.width, maxWidth: box.maxWidth },
1087
+ size: Math.max(4, Math.min(value.length + 1, 31)),
1088
+ onChange: (e) => setValue(e.target.value),
1089
+ onBlur: () => finish(true, false),
1090
+ onKeyDown: (e) => {
1091
+ e.stopPropagation();
1092
+ if (e.nativeEvent.isComposing || e.keyCode === 229) return;
1093
+ if (e.key === "Enter") {
1094
+ e.preventDefault();
1095
+ finish(true, true);
1096
+ } else if (e.key === "Escape") {
1097
+ e.preventDefault();
1098
+ finish(false, true);
1099
+ onCancel();
1100
+ }
1101
+ }
1102
+ }
1103
+ );
1104
+ }
1105
+
1106
+ // src/toolbar/Toolbar.tsx
1107
+ import {
1108
+ Fragment as Fragment6,
1109
+ useCallback as useCallback5,
1110
+ useEffect as useEffect8,
1111
+ useLayoutEffect as useLayoutEffect7,
1112
+ useMemo as useMemo5,
1113
+ useRef as useRef7,
1114
+ useState as useState7
1115
+ } from "react";
1116
+ import {
1117
+ TOOLBAR_FIXED_ATTRIBUTE,
1118
+ arrangeToolbar,
1119
+ chromeSlotId as chromeSlotId2,
1120
+ guardToolbarMousedown as guardToolbarMousedown2,
1121
+ listenSaveKey,
1122
+ measureToolbar,
1123
+ moveBarFocus,
1124
+ observeToolbar,
1125
+ toolbarGroupHeading as toolbarGroupHeading2,
1126
+ runToolbarCommand as runToolbarCommand2
1127
+ } from "@xlsx-editor.dev/core/editor";
1128
+
1129
+ // src/toolbar/slot.tsx
1130
+ import {
1131
+ chromeControlForSlot,
1132
+ slotWords
1133
+ } from "@xlsx-editor.dev/core/editor";
1134
+
1135
+ // src/useEditorCommand.ts
1136
+ import { createContext as createContext3, useCallback as useCallback3, useContext as useContext4, useMemo as useMemo2 } from "react";
1137
+ import {
1138
+ editorCommandSlice,
1139
+ runToolbarCommand,
1140
+ sameEditorCommandSlice
1141
+ } from "@xlsx-editor.dev/core/editor";
1142
+ var ToolbarHostContext = createContext3({});
1143
+ function translateKey(t, key, params) {
1144
+ return t(key, params ? { ...params } : void 0);
1145
+ }
1146
+ function useEditorCommand(slot) {
1147
+ const editor = useXlsxEditor();
1148
+ const host = useContext4(ToolbarHostContext);
1149
+ const { t } = useTranslation();
1150
+ const select = useCallback3(
1151
+ (snapshot) => editorCommandSlice(snapshot, slot, host, t),
1152
+ [slot, host, t]
1153
+ );
1154
+ const slice = useEditorState(select, sameEditorCommandSlice);
1155
+ const execute = useCallback3(
1156
+ (value) => editor ? runToolbarCommand(editor, slot, value, host).ok : false,
1157
+ [editor, slot, host]
1158
+ );
1159
+ return useMemo2(
1160
+ () => ({
1161
+ execute,
1162
+ isActive: slice.active,
1163
+ isEnabled: slice.enabled,
1164
+ disabledReason: slice.disabledReason,
1165
+ hint: slice.hint,
1166
+ value: slice.value
1167
+ }),
1168
+ [execute, slice]
1169
+ );
1170
+ }
1171
+
1172
+ // src/toolbar/slot.tsx
1173
+ import { jsx as jsx6 } from "react/jsx-runtime";
1174
+ function useToolbarSlot(slot) {
1175
+ const editor = useXlsxEditor();
1176
+ const { t } = useTranslation();
1177
+ const command = useEditorCommand(slot);
1178
+ const control = chromeControlForSlot(slot);
1179
+ return {
1180
+ ...command,
1181
+ ...slotWords(control.labelKey, command, t),
1182
+ slot,
1183
+ control,
1184
+ focusGrid: () => editor?.focus()
1185
+ };
1186
+ }
1187
+ function ChromeIcon({
1188
+ paths,
1189
+ className
1190
+ }) {
1191
+ if (!paths) return null;
1192
+ return /* @__PURE__ */ jsx6("svg", { className, viewBox: "0 -960 960 960", "aria-hidden": "true", focusable: "false", children: paths.map((d) => /* @__PURE__ */ jsx6("path", { d }, d)) });
1193
+ }
1194
+
1195
+ // src/toolbar/parts.tsx
1196
+ import {
1197
+ useEffect as useEffect6,
1198
+ useId as useId4,
1199
+ useLayoutEffect as useLayoutEffect6,
1200
+ useRef as useRef6,
1201
+ useMemo as useMemo4,
1202
+ useState as useState6
1203
+ } from "react";
1204
+ import {
1205
+ COLOR_CHOICES,
1206
+ FONT_FAMILY_CHOICES,
1207
+ FONT_SIZE_CHOICES,
1208
+ NO_FILL,
1209
+ focusPopupItem,
1210
+ guardToolbarMousedown,
1211
+ isHexColor,
1212
+ movePopupFocus,
1213
+ numberFormatListView,
1214
+ parseFontSize,
1215
+ placePopup,
1216
+ popupTriggerAction
1217
+ } from "@xlsx-editor.dev/core/editor";
1218
+
1219
+ // src/toolbar/useDropdownClose.ts
1220
+ import { useEffect as useEffect4 } from "react";
1221
+ import {
1222
+ hasOpenNestedPopup,
1223
+ listenForOutsidePress,
1224
+ listenForPopupEscape,
1225
+ listenForPopupFocusLeave
1226
+ } from "@xlsx-editor.dev/core/editor";
1227
+ function useDropdownClose(open, setOpen, rootRef, hidden = false, nested = false) {
1228
+ useEffect4(() => {
1229
+ if (open && hidden) setOpen(false);
1230
+ }, [open, hidden, setOpen]);
1231
+ useEffect4(() => {
1232
+ const root = rootRef.current;
1233
+ if (!open || hidden || !root) return void 0;
1234
+ const contains = (node) => root.contains(node);
1235
+ const stopEscape = listenForPopupEscape({
1236
+ popup: root,
1237
+ contains,
1238
+ chromeRoot: () => root.closest(".xlsx-toolbar"),
1239
+ ...nested ? { skip: () => hasOpenNestedPopup(root.querySelector("[data-popup]")) } : {},
1240
+ close: (fromInside) => {
1241
+ setOpen(false);
1242
+ if (fromInside) root.querySelector("[aria-haspopup]")?.focus();
1243
+ }
1244
+ });
1245
+ const stopFocus = listenForPopupFocusLeave({
1246
+ popup: root,
1247
+ contains,
1248
+ close: () => setOpen(false)
1249
+ });
1250
+ const stopPress = listenForOutsidePress({ popup: root, contains, close: () => setOpen(false) });
1251
+ return () => {
1252
+ stopPress();
1253
+ stopEscape();
1254
+ stopFocus();
1255
+ };
1256
+ }, [open, hidden, setOpen, rootRef, nested]);
1257
+ }
1258
+
1259
+ // src/toolbar/NumberFormatDialog.tsx
1260
+ import {
1261
+ createContext as createContext4,
1262
+ useCallback as useCallback4,
1263
+ useContext as useContext5,
1264
+ useEffect as useEffect5,
1265
+ useId as useId3,
1266
+ useMemo as useMemo3,
1267
+ useLayoutEffect as useLayoutEffect5,
1268
+ useRef as useRef5,
1269
+ useState as useState5
1270
+ } from "react";
1271
+ import {
1272
+ numberFormatDialogApplyStep,
1273
+ numberFormatDialogCurrent,
1274
+ numberFormatDialogStart,
1275
+ previewNumberFormat,
1276
+ refusalText as refusalText3,
1277
+ workbookNumberFormatCodes
1278
+ } from "@xlsx-editor.dev/core/editor";
1279
+
1280
+ // src/dialog-frame.tsx
1281
+ import { useLayoutEffect as useLayoutEffect4, useRef as useRef4, useState as useState4 } from "react";
1282
+ import { isDialogBackdropPoint, trapTabWithin } from "@xlsx-editor.dev/core/editor";
1283
+ import { jsx as jsx7 } from "react/jsx-runtime";
1284
+ function DialogFrame({
1285
+ kind,
1286
+ label,
1287
+ onClose,
1288
+ onRestoreFocus,
1289
+ onKeyDown,
1290
+ children
1291
+ }) {
1292
+ const ref = useRef4(null);
1293
+ const closeRef = useRef4(onClose);
1294
+ closeRef.current = onClose;
1295
+ const restoreRef = useRef4(onRestoreFocus);
1296
+ restoreRef.current = onRestoreFocus;
1297
+ const pressedOutside = useRef4(false);
1298
+ const [ownScope, setOwnScope] = useState4(false);
1299
+ const dark = useChromeDark();
1300
+ useLayoutEffect4(() => {
1301
+ const panel = ref.current;
1302
+ if (!panel) return void 0;
1303
+ setOwnScope(!panel.parentElement?.closest(".xlsx-editor"));
1304
+ const active = panel.ownerDocument.activeElement;
1305
+ const opener = active === panel.ownerDocument.body ? null : active;
1306
+ if (typeof panel.showModal === "function") panel.showModal();
1307
+ else panel.setAttribute("open", "");
1308
+ panel.querySelector(
1309
+ 'input:not([disabled]),select:not([disabled]),button:not([disabled]),[tabindex="0"]'
1310
+ )?.focus({ preventScroll: true });
1311
+ return () => {
1312
+ const active2 = panel.ownerDocument.activeElement;
1313
+ if (active2 && panel.contains(active2)) active2.blur?.();
1314
+ if (typeof panel.close === "function" && panel.open) panel.close();
1315
+ else panel.removeAttribute("open");
1316
+ if (restoreRef.current?.()) return;
1317
+ if (opener?.isConnected) opener.focus({ preventScroll: true });
1318
+ };
1319
+ }, []);
1320
+ return /* @__PURE__ */ jsx7(
1321
+ "dialog",
1322
+ {
1323
+ ref,
1324
+ "aria-modal": "true",
1325
+ "aria-label": label,
1326
+ "data-xlsx-dialog": kind,
1327
+ className: ownScope ? `xlsx-dialog xlsx-editor${dark ? " dark" : ""}` : "xlsx-dialog",
1328
+ onCancel: (event) => {
1329
+ event.preventDefault();
1330
+ closeRef.current();
1331
+ },
1332
+ onMouseDown: (event) => {
1333
+ pressedOutside.current = isDialogBackdropPoint(event.currentTarget, event);
1334
+ event.stopPropagation();
1335
+ },
1336
+ onClick: (event) => {
1337
+ const close = pressedOutside.current && isDialogBackdropPoint(event.currentTarget, event);
1338
+ pressedOutside.current = false;
1339
+ if (close) closeRef.current();
1340
+ event.stopPropagation();
1341
+ },
1342
+ onKeyDown: (event) => {
1343
+ const composing = event.nativeEvent.isComposing || event.keyCode === 229;
1344
+ if (event.key === "Escape" && !composing) {
1345
+ event.preventDefault();
1346
+ closeRef.current();
1347
+ } else if (trapTabWithin(event.currentTarget, event.nativeEvent)) event.preventDefault();
1348
+ else if (!composing && !event.defaultPrevented) onKeyDown?.(event);
1349
+ event.stopPropagation();
1350
+ },
1351
+ children
1352
+ }
1353
+ );
1354
+ }
1355
+
1356
+ // src/toolbar/NumberFormatDialog.tsx
1357
+ import { jsx as jsx8, jsxs as jsxs4 } from "react/jsx-runtime";
1358
+ var OpenerContext = createContext4(null);
1359
+ var PanelCloseContext = createContext4(null);
1360
+ function useNumberFormatDialogOpener() {
1361
+ const opener = useContext5(OpenerContext);
1362
+ const closePanel = useContext5(PanelCloseContext);
1363
+ return useMemo3(
1364
+ () => opener && closePanel ? {
1365
+ open(returnTo) {
1366
+ const opened = opener.open(returnTo);
1367
+ if (opened && !returnTo) closePanel();
1368
+ return opened;
1369
+ }
1370
+ } : opener,
1371
+ [opener, closePanel]
1372
+ );
1373
+ }
1374
+ function NumberFormatDialogHost({ children }) {
1375
+ const editor = useXlsxEditor();
1376
+ const [open, setOpen] = useState5(null);
1377
+ const opener = useMemo3(
1378
+ () => ({
1379
+ open: (returnTo) => {
1380
+ const start = editor ? numberFormatDialogStart(editor) : null;
1381
+ if (start) setOpen({ returnTo, start });
1382
+ return start !== null;
1383
+ }
1384
+ }),
1385
+ [editor]
1386
+ );
1387
+ const close = useCallback4(() => setOpen(null), []);
1388
+ return /* @__PURE__ */ jsxs4(OpenerContext.Provider, { value: opener, children: [
1389
+ children,
1390
+ open ? /* @__PURE__ */ jsx8(NumberFormatDialog, { returnTo: open.returnTo, start: open.start, onClose: close }) : null
1391
+ ] });
1392
+ }
1393
+ var HEX6 = /^[0-9A-Fa-f]{6}$/;
1394
+ function NumberFormatDialog({
1395
+ returnTo,
1396
+ start,
1397
+ onClose
1398
+ }) {
1399
+ const editor = useXlsxEditor();
1400
+ const { t } = useTranslation();
1401
+ const s = useToolbarSlot("number.custom");
1402
+ const initial = start.initial;
1403
+ const [code, setCode] = useState5(initial);
1404
+ const [error, setError] = useState5(null);
1405
+ const [errorCount, setErrorCount] = useState5(0);
1406
+ const applied = useRef5(false);
1407
+ const [attempted, setAttempted] = useState5(false);
1408
+ const field = useRef5(null);
1409
+ const list = useRef5(null);
1410
+ const id = useId3();
1411
+ const ids = {
1412
+ field: `${id}-code`,
1413
+ hint: `${id}-hint`,
1414
+ preview: `${id}-preview`,
1415
+ error: `${id}-error`,
1416
+ list: `${id}-list`,
1417
+ sample: `${id}-sample`,
1418
+ blank: `${id}-blank`,
1419
+ previewLabel: `${id}-preview-label`
1420
+ };
1421
+ useEffect5(() => field.current?.select(), []);
1422
+ const snapshot = useEditorSnapshot();
1423
+ const codes = useMemo3(
1424
+ () => editor && snapshot ? workbookNumberFormatCodes(editor) : [],
1425
+ [editor, snapshot]
1426
+ );
1427
+ const current = useEditorState(
1428
+ useCallback4(() => !!editor && numberFormatDialogCurrent(editor, start), [editor, start])
1429
+ );
1430
+ useEffect5(() => {
1431
+ if (!current) onClose();
1432
+ }, [current, onClose]);
1433
+ const preview = editor ? previewNumberFormat(editor, code) : null;
1434
+ const problem = preview && !preview.ok ? translateKey(t, preview.problem.key, preview.problem.params) : null;
1435
+ if (attempted && problem === null) setAttempted(false);
1436
+ const invalid = problem !== null && (attempted || code !== "");
1437
+ useLayoutEffect5(() => {
1438
+ const el = list.current;
1439
+ if (!el) return;
1440
+ if (codes.includes(code)) el.value = code;
1441
+ else el.selectedIndex = -1;
1442
+ }, [code, codes]);
1443
+ const apply = () => {
1444
+ if (!editor) return;
1445
+ const step = numberFormatDialogApplyStep(editor, start, code);
1446
+ if (step.kind === "closed" || step.kind === "unchanged") {
1447
+ if (step.kind === "unchanged") applied.current = true;
1448
+ onClose();
1449
+ return;
1450
+ }
1451
+ if (step.kind === "problem") {
1452
+ setAttempted(true);
1453
+ setError(translateKey(t, step.problem.key, step.problem.params));
1454
+ setErrorCount((n) => n + 1);
1455
+ field.current?.focus();
1456
+ return;
1457
+ }
1458
+ if (s.execute(code)) {
1459
+ applied.current = true;
1460
+ onClose();
1461
+ return;
1462
+ }
1463
+ const after = editor.snapshot();
1464
+ setError(
1465
+ after.refusal ? refusalText3(after.refusal, t, after.numberLocale) : t("dialogs.numberFormat.notApplied")
1466
+ );
1467
+ setErrorCount((n) => n + 1);
1468
+ };
1469
+ const sample = !!preview?.ok && preview.sample;
1470
+ const blank = !!preview?.ok && preview.text === "";
1471
+ const shownColor = preview?.ok && preview.color && HEX6.test(preview.color) ? preview.color : null;
1472
+ return /* @__PURE__ */ jsxs4(
1473
+ DialogFrame,
1474
+ {
1475
+ kind: "numberFormat",
1476
+ label: t("dialogs.numberFormat.title"),
1477
+ onClose,
1478
+ onRestoreFocus: () => {
1479
+ if (applied.current && editor) {
1480
+ editor.focus();
1481
+ return true;
1482
+ }
1483
+ if (!returnTo?.isConnected) return false;
1484
+ returnTo.focus({ preventScroll: true });
1485
+ return true;
1486
+ },
1487
+ onKeyDown: (event) => {
1488
+ const tag = event.target.tagName;
1489
+ if (event.key !== "Enter" || tag !== "INPUT" && tag !== "SELECT") return;
1490
+ event.preventDefault();
1491
+ apply();
1492
+ },
1493
+ children: [
1494
+ /* @__PURE__ */ jsx8("div", { className: "xlsx-dialog__header", children: /* @__PURE__ */ jsx8("h2", { className: "xlsx-dialog__title", children: t("dialogs.numberFormat.title") }) }),
1495
+ /* @__PURE__ */ jsxs4("div", { className: "xlsx-dialog__body", children: [
1496
+ /* @__PURE__ */ jsx8("label", { className: "xlsx-dialog__label", htmlFor: ids.field, children: t("dialogs.numberFormat.code") }),
1497
+ /* @__PURE__ */ jsx8(
1498
+ "input",
1499
+ {
1500
+ ref: field,
1501
+ id: ids.field,
1502
+ name: "xlsx-number-format-code",
1503
+ type: "text",
1504
+ dir: "ltr",
1505
+ autoComplete: "off",
1506
+ spellCheck: false,
1507
+ className: "xlsx-dialog__input",
1508
+ value: code,
1509
+ "aria-invalid": invalid,
1510
+ "aria-describedby": [
1511
+ ids.hint,
1512
+ ...error ? [ids.error] : [ids.previewLabel, ids.preview],
1513
+ sample ? ids.sample : "",
1514
+ blank && !error ? ids.blank : ""
1515
+ ].filter(Boolean).join(" "),
1516
+ onChange: (e) => {
1517
+ setCode(e.currentTarget.value);
1518
+ setError(null);
1519
+ }
1520
+ }
1521
+ ),
1522
+ /* @__PURE__ */ jsx8("p", { id: ids.error, role: "alert", className: "xlsx-dialog__error", children: error }, errorCount),
1523
+ /* @__PURE__ */ jsx8("p", { id: ids.hint, className: "xlsx-dialog__hint", children: t(
1524
+ codes.length > 0 ? "dialogs.numberFormat.codeHint" : "dialogs.numberFormat.codeHintNoList"
1525
+ ) }),
1526
+ /* @__PURE__ */ jsxs4("div", { className: "xlsx-dialog__preview", hidden: error !== null, children: [
1527
+ /* @__PURE__ */ jsx8("span", { id: ids.previewLabel, className: "xlsx-dialog__preview-label", children: t("dialogs.numberFormat.preview") }),
1528
+ /* @__PURE__ */ jsx8(
1529
+ "output",
1530
+ {
1531
+ id: ids.preview,
1532
+ htmlFor: ids.field,
1533
+ "aria-labelledby": ids.previewLabel,
1534
+ "aria-live": "off",
1535
+ className: "xlsx-dialog__preview-value",
1536
+ "data-problem": problem ? "" : void 0,
1537
+ style: shownColor ? { color: `#${shownColor}` } : void 0,
1538
+ children: preview?.ok ? preview.stale ? t("grid.staleResult", { text: preview.text }) : preview.text : problem ?? ""
1539
+ }
1540
+ )
1541
+ ] }),
1542
+ blank && error === null ? /* @__PURE__ */ jsx8("p", { id: ids.blank, className: "xlsx-dialog__hint", children: t("dialogs.numberFormat.previewBlank") }) : null,
1543
+ sample ? /* @__PURE__ */ jsx8("p", { id: ids.sample, className: "xlsx-dialog__hint", children: t("dialogs.numberFormat.previewSample") }) : null,
1544
+ codes.length > 0 ? /* @__PURE__ */ jsx8("label", { className: "xlsx-dialog__label", htmlFor: ids.list, children: t("dialogs.numberFormat.existing") }) : /* @__PURE__ */ jsx8("span", { className: "xlsx-dialog__label", children: t("dialogs.numberFormat.existing") }),
1545
+ codes.length > 0 ? /* @__PURE__ */ jsx8(
1546
+ "select",
1547
+ {
1548
+ id: ids.list,
1549
+ name: "xlsx-number-format-existing",
1550
+ size: Math.min(6, Math.max(2, codes.length)),
1551
+ dir: "ltr",
1552
+ className: "xlsx-dialog__list",
1553
+ ref: list,
1554
+ onChange: (e) => {
1555
+ setCode(e.currentTarget.value);
1556
+ setError(null);
1557
+ },
1558
+ onKeyDown: (e) => {
1559
+ const el = e.currentTarget;
1560
+ const down = e.key === "ArrowDown";
1561
+ if (el.selectedIndex !== -1 || !down && e.key !== "ArrowUp") return;
1562
+ e.preventDefault();
1563
+ const option = el.options[down ? 0 : el.options.length - 1];
1564
+ if (!option) return;
1565
+ setCode(option.value);
1566
+ setError(null);
1567
+ },
1568
+ onDoubleClick: (e) => {
1569
+ if (e.target.tagName === "OPTION") apply();
1570
+ },
1571
+ children: codes.map((c) => /* @__PURE__ */ jsx8("option", { value: c, title: c, children: c }, c))
1572
+ }
1573
+ ) : /* @__PURE__ */ jsx8("p", { className: "xlsx-dialog__hint", children: t("dialogs.numberFormat.noExisting") })
1574
+ ] }),
1575
+ /* @__PURE__ */ jsxs4("div", { className: "xlsx-dialog__footer", children: [
1576
+ /* @__PURE__ */ jsx8("button", { type: "button", className: "xlsx-dialog__button", onClick: onClose, children: t("common.cancel") }),
1577
+ /* @__PURE__ */ jsx8(
1578
+ "button",
1579
+ {
1580
+ type: "button",
1581
+ className: "xlsx-dialog__button xlsx-dialog__button--primary",
1582
+ "data-slot": "number.custom",
1583
+ onClick: apply,
1584
+ children: t("common.apply")
1585
+ }
1586
+ )
1587
+ ] })
1588
+ ]
1589
+ }
1590
+ );
1591
+ }
1592
+
1593
+ // src/toolbar/icons.ts
1594
+ import { CHROME_ICON_PATHS } from "@xlsx-editor.dev/core/editor";
1595
+ var ICON_MORE = CHROME_ICON_PATHS.more_horiz;
1596
+ var ICON_FIELD_CARET = CHROME_ICON_PATHS.expand_more;
1597
+ var ICON_MENU_CARET = CHROME_ICON_PATHS.arrow_drop_down;
1598
+ var ICON_CHECK = CHROME_ICON_PATHS.check;
1599
+
1600
+ // src/toolbar/parts.tsx
1601
+ import { jsx as jsx9, jsxs as jsxs5 } from "react/jsx-runtime";
1602
+ function slotAttributes(s, reasonId) {
1603
+ return {
1604
+ "data-slot": s.slot,
1605
+ "aria-disabled": s.isEnabled ? void 0 : "true",
1606
+ ...s.description ? { "aria-describedby": reasonId } : {},
1607
+ title: s.title,
1608
+ onMouseDown: guardToolbarMousedown,
1609
+ ...s.isActive ? { "data-active": "" } : {},
1610
+ ...s.isEnabled ? {} : { "data-disabled": "" }
1611
+ };
1612
+ }
1613
+ function ReasonText({ id, reason }) {
1614
+ return reason ? /* @__PURE__ */ jsx9("span", { id, hidden: true, children: reason }) : null;
1615
+ }
1616
+ function ToolbarButton({
1617
+ slot,
1618
+ layout = "bar"
1619
+ }) {
1620
+ const s = useToolbarSlot(slot);
1621
+ const reasonId = useId4();
1622
+ return /* @__PURE__ */ jsxs5(
1623
+ "button",
1624
+ {
1625
+ type: "button",
1626
+ className: layout === "row" ? "xlsx-toolbar-row" : "xlsx-toolbar-button",
1627
+ "aria-label": s.label,
1628
+ ...s.control.toggle ? { "aria-pressed": s.isActive } : {},
1629
+ ...slotAttributes(s, reasonId),
1630
+ onKeyDown: (e) => {
1631
+ if (e.key === "Enter" && e.repeat) e.preventDefault();
1632
+ },
1633
+ onClick: () => {
1634
+ if (s.isEnabled) s.execute();
1635
+ },
1636
+ children: [
1637
+ /* @__PURE__ */ jsx9(ChromeIcon, { paths: s.control.paths }),
1638
+ layout === "row" ? /* @__PURE__ */ jsx9("span", { children: s.label }) : null,
1639
+ /* @__PURE__ */ jsx9(ReasonText, { id: reasonId, reason: s.description })
1640
+ ]
1641
+ }
1642
+ );
1643
+ }
1644
+ function usePopup(selector, options = {}) {
1645
+ const { inline = false, closed = false, nested = false } = options;
1646
+ const [open, setOpen] = useState6(false);
1647
+ const root = useRef6(null);
1648
+ const focusOnOpen = useRef6(false);
1649
+ const id = useId4();
1650
+ useDropdownClose(open, setOpen, root, closed, nested);
1651
+ useLayoutEffect6(() => {
1652
+ if (open && root.current) placePopup(root.current, inline, selector);
1653
+ }, [open, inline, selector]);
1654
+ const focusIn = () => focusPopupItem(root.current, selector);
1655
+ useEffect6(() => {
1656
+ if (!open || !focusOnOpen.current) return;
1657
+ focusOnOpen.current = false;
1658
+ focusIn();
1659
+ });
1660
+ const openWithKeyboard = () => {
1661
+ focusOnOpen.current = true;
1662
+ setOpen(true);
1663
+ };
1664
+ return { open, setOpen, root, id, openWithKeyboard, focusIn };
1665
+ }
1666
+ function popupTriggerKeys(popup, enabled) {
1667
+ return {
1668
+ onKeyDown: (e) => {
1669
+ const action = popupTriggerAction(e.key, popup.open);
1670
+ if (!action) return;
1671
+ e.preventDefault();
1672
+ if (!enabled) return;
1673
+ if (action === "open") popup.openWithKeyboard();
1674
+ else if (action === "focusIn") popup.focusIn();
1675
+ else popup.setOpen(false);
1676
+ },
1677
+ // Space activates a button on key up in some browsers: the key down already acted.
1678
+ onKeyUp: (e) => {
1679
+ if (e.key === " ") e.preventDefault();
1680
+ }
1681
+ };
1682
+ }
1683
+ function Trigger({
1684
+ s,
1685
+ popup,
1686
+ kind,
1687
+ className,
1688
+ caret,
1689
+ name,
1690
+ children,
1691
+ label
1692
+ }) {
1693
+ const { t } = useTranslation();
1694
+ const reasonId = useId4();
1695
+ const attributes = slotAttributes(s, reasonId);
1696
+ const after = s.description;
1697
+ const title = label === void 0 ? attributes.title : after ? t("toolbar.hintTitle", { label, hint: after }) : label;
1698
+ return /* @__PURE__ */ jsxs5(
1699
+ "button",
1700
+ {
1701
+ type: "button",
1702
+ className,
1703
+ "aria-haspopup": kind,
1704
+ "aria-expanded": popup.open,
1705
+ "aria-controls": popup.open ? popup.id : void 0,
1706
+ "aria-label": name,
1707
+ ...attributes,
1708
+ title,
1709
+ onClick: () => {
1710
+ if (s.isEnabled) popup.setOpen(!popup.open);
1711
+ },
1712
+ ...popupTriggerKeys(popup, s.isEnabled),
1713
+ children: [
1714
+ children,
1715
+ /* @__PURE__ */ jsx9(
1716
+ ChromeIcon,
1717
+ {
1718
+ paths: caret === "field" ? ICON_FIELD_CARET : ICON_MENU_CARET,
1719
+ className: "xlsx-toolbar-caret"
1720
+ }
1721
+ ),
1722
+ /* @__PURE__ */ jsx9(ReasonText, { id: reasonId, reason: s.description })
1723
+ ]
1724
+ }
1725
+ );
1726
+ }
1727
+ function popupAttributes(layout, className) {
1728
+ return {
1729
+ className: `xlsx-toolbar-popup ${className}`,
1730
+ "data-popup": "",
1731
+ ...layout === "row" ? { "data-inline": "" } : {}
1732
+ };
1733
+ }
1734
+ function ToolbarList({
1735
+ slot,
1736
+ options,
1737
+ text,
1738
+ layout,
1739
+ width,
1740
+ entry,
1741
+ more,
1742
+ name,
1743
+ active
1744
+ }) {
1745
+ const s = useToolbarSlot(slot);
1746
+ const items = `${entry ? "input, " : ""}[role="option"]${more ? ", [data-list-more]" : ""}`;
1747
+ const popup = usePopup(items, {
1748
+ inline: layout === "row",
1749
+ closed: !s.isEnabled
1750
+ });
1751
+ const [invalid, setInvalid] = useState6(false);
1752
+ const pick = (value) => {
1753
+ popup.setOpen(false);
1754
+ s.execute(value);
1755
+ s.focusGrid();
1756
+ };
1757
+ return /* @__PURE__ */ jsxs5(
1758
+ "div",
1759
+ {
1760
+ ref: popup.root,
1761
+ className: `xlsx-toolbar-dropdown${layout === "row" ? " xlsx-toolbar-labelled" : ""}`,
1762
+ children: [
1763
+ layout === "row" ? /* @__PURE__ */ jsx9("span", { className: "xlsx-toolbar-row-label", children: s.label }) : null,
1764
+ /* @__PURE__ */ jsx9(
1765
+ Trigger,
1766
+ {
1767
+ s,
1768
+ popup,
1769
+ kind: "listbox",
1770
+ className: `xlsx-toolbar-select xlsx-toolbar-select-${width}`,
1771
+ caret: "field",
1772
+ name: `${s.label}: ${name ?? text}`,
1773
+ ...name !== void 0 ? { label: `${s.label}: ${name}` } : {},
1774
+ children: /* @__PURE__ */ jsx9("span", { className: "xlsx-toolbar-select-text", children: text })
1775
+ }
1776
+ ),
1777
+ popup.open ? /* @__PURE__ */ jsxs5(
1778
+ "div",
1779
+ {
1780
+ ...popupAttributes(layout, "xlsx-toolbar-list-popup"),
1781
+ onKeyDown: (e) => movePopupFocus(e, items),
1782
+ children: [
1783
+ entry ? /* @__PURE__ */ jsx9(
1784
+ "input",
1785
+ {
1786
+ type: "text",
1787
+ inputMode: "decimal",
1788
+ autoComplete: "off",
1789
+ className: "xlsx-toolbar-entry",
1790
+ "aria-label": entry.label,
1791
+ "aria-invalid": invalid,
1792
+ ...invalid ? { "aria-describedby": `${popup.id}-entry-error` } : {},
1793
+ placeholder: text,
1794
+ onChange: () => setInvalid(false),
1795
+ onKeyDown: (e) => {
1796
+ if (e.key !== "Enter") return;
1797
+ e.preventDefault();
1798
+ const value = entry.parse(e.currentTarget.value);
1799
+ if (value === null) setInvalid(true);
1800
+ else pick(value);
1801
+ }
1802
+ }
1803
+ ) : null,
1804
+ entry && invalid ? /* @__PURE__ */ jsx9("div", { id: `${popup.id}-entry-error`, role: "alert", className: "xlsx-toolbar-entry-error", children: entry.invalid }) : null,
1805
+ /* @__PURE__ */ jsx9("ul", { id: popup.id, role: "listbox", "aria-label": s.label, className: "xlsx-toolbar-list", children: options.map((o) => /* @__PURE__ */ jsxs5(
1806
+ "li",
1807
+ {
1808
+ role: "option",
1809
+ tabIndex: -1,
1810
+ "aria-selected": o.value === s.value,
1811
+ ...o.value === active ? { "aria-current": "true" } : {},
1812
+ onMouseDown: guardToolbarMousedown,
1813
+ onClick: () => pick(o.value),
1814
+ onKeyDown: (e) => {
1815
+ if (e.key !== "Enter" && e.key !== " ") return;
1816
+ e.preventDefault();
1817
+ pick(o.value);
1818
+ },
1819
+ children: [
1820
+ o.label,
1821
+ o.value === s.value ? /* @__PURE__ */ jsx9(ChromeIcon, { paths: ICON_CHECK, className: "xlsx-toolbar-check" }) : null
1822
+ ]
1823
+ },
1824
+ o.value
1825
+ )) }),
1826
+ more?.(() => popup.setOpen(false))
1827
+ ]
1828
+ }
1829
+ ) : null
1830
+ ]
1831
+ }
1832
+ );
1833
+ }
1834
+ function FontFamilyList({ layout = "bar" }) {
1835
+ const s = useToolbarSlot("font.family");
1836
+ const current = s.value ?? "";
1837
+ const names = current && !FONT_FAMILY_CHOICES.includes(current) ? [current] : [];
1838
+ const options = [...names, ...FONT_FAMILY_CHOICES].map((n) => ({ value: n, label: n }));
1839
+ return /* @__PURE__ */ jsx9(ToolbarList, { slot: "font.family", options, text: current, layout, width: "wide" });
1840
+ }
1841
+ function FontSizeList({ layout = "bar" }) {
1842
+ const { t } = useTranslation();
1843
+ const s = useToolbarSlot("font.size");
1844
+ const current = Number(s.value);
1845
+ const sizes = [...FONT_SIZE_CHOICES];
1846
+ if (Number.isFinite(current) && current > 0 && !sizes.includes(current)) sizes.push(current);
1847
+ sizes.sort((a, b) => a - b);
1848
+ const options = sizes.map((n) => ({ value: String(n), label: String(n) }));
1849
+ return /* @__PURE__ */ jsx9(
1850
+ ToolbarList,
1851
+ {
1852
+ slot: "font.size",
1853
+ options,
1854
+ text: s.value ?? "",
1855
+ layout,
1856
+ width: "narrow",
1857
+ entry: {
1858
+ label: t("fontSize.typeSize"),
1859
+ invalid: t("fontSize.invalid"),
1860
+ parse: parseFontSize
1861
+ }
1862
+ }
1863
+ );
1864
+ }
1865
+ var numberLocaleOf = (snapshot) => snapshot.numberLocale;
1866
+ function NumberFormatList({
1867
+ layout = "bar",
1868
+ more = false
1869
+ }) {
1870
+ const { t } = useTranslation();
1871
+ const s = useToolbarSlot("number.format");
1872
+ const locale = useEditorState(numberLocaleOf);
1873
+ const view = useMemo4(
1874
+ () => numberFormatListView(
1875
+ s.value ?? void 0,
1876
+ (key, params) => translateKey(t, key, params),
1877
+ locale
1878
+ ),
1879
+ [s.value, t, locale]
1880
+ );
1881
+ return /* @__PURE__ */ jsx9(
1882
+ ToolbarList,
1883
+ {
1884
+ slot: "number.format",
1885
+ options: view.entries,
1886
+ text: view.text,
1887
+ ...view.name ? { name: view.name } : {},
1888
+ ...view.current !== void 0 ? { active: view.current } : {},
1889
+ layout,
1890
+ width: "wide",
1891
+ ...more ? { more: (close) => /* @__PURE__ */ jsx9(MoreFormatsItem, { close }) } : {}
1892
+ }
1893
+ );
1894
+ }
1895
+ function MoreFormatsItem({ close }) {
1896
+ const s = useToolbarSlot("number.custom");
1897
+ const dialog = useNumberFormatDialogOpener();
1898
+ const reasonId = useId4();
1899
+ if (!dialog) return null;
1900
+ return /* @__PURE__ */ jsxs5(
1901
+ "button",
1902
+ {
1903
+ type: "button",
1904
+ className: "xlsx-toolbar-list-more",
1905
+ tabIndex: -1,
1906
+ "data-list-more": "",
1907
+ "aria-haspopup": "dialog",
1908
+ ...slotAttributes(s, reasonId),
1909
+ onClick: (e) => {
1910
+ if (!s.isEnabled) return;
1911
+ const item = e.currentTarget;
1912
+ const root = item.closest(".xlsx-toolbar-dropdown");
1913
+ const fromKeyboard = item.ownerDocument.activeElement === item;
1914
+ const trigger = root?.querySelector('[aria-haspopup="listbox"]') ?? null;
1915
+ close();
1916
+ if (!dialog.open(fromKeyboard ? trigger : null) && fromKeyboard) s.focusGrid();
1917
+ },
1918
+ children: [
1919
+ s.label,
1920
+ /* @__PURE__ */ jsx9(ReasonText, { id: reasonId, reason: s.description })
1921
+ ]
1922
+ }
1923
+ );
1924
+ }
1925
+ function NumberFormatDialogButton({ layout = "bar" }) {
1926
+ const s = useToolbarSlot("number.custom");
1927
+ const dialog = useNumberFormatDialogOpener();
1928
+ const reasonId = useId4();
1929
+ if (!dialog) return null;
1930
+ return /* @__PURE__ */ jsxs5(
1931
+ "button",
1932
+ {
1933
+ type: "button",
1934
+ className: layout === "row" ? "xlsx-toolbar-row" : "xlsx-toolbar-button",
1935
+ "aria-label": s.label,
1936
+ "aria-haspopup": "dialog",
1937
+ ...slotAttributes(s, reasonId),
1938
+ onClick: (e) => {
1939
+ if (!s.isEnabled) return;
1940
+ const self = e.currentTarget;
1941
+ dialog.open(self.ownerDocument.activeElement === self ? self : null);
1942
+ },
1943
+ children: [
1944
+ /* @__PURE__ */ jsx9(ChromeIcon, { paths: s.control.paths }),
1945
+ layout === "row" ? /* @__PURE__ */ jsx9("span", { children: s.label }) : null,
1946
+ /* @__PURE__ */ jsx9(ReasonText, { id: reasonId, reason: s.description })
1947
+ ]
1948
+ }
1949
+ );
1950
+ }
1951
+ function ColorPalette({
1952
+ slot,
1953
+ layout = "bar"
1954
+ }) {
1955
+ const { t } = useTranslation();
1956
+ const s = useToolbarSlot(slot);
1957
+ const popup = usePopup("[data-color]", { inline: layout === "row", closed: !s.isEnabled });
1958
+ const pick = (value) => {
1959
+ popup.setOpen(false);
1960
+ s.execute(value);
1961
+ s.focusGrid();
1962
+ };
1963
+ const current = s.value ?? void 0;
1964
+ const colors = [
1965
+ ...slot === "fill.color" ? [{ value: NO_FILL, label: t("colorPicker.noFill") }] : [],
1966
+ ...COLOR_CHOICES.map((c) => ({ value: c.value, label: translateKey(t, c.labelKey) }))
1967
+ ];
1968
+ return /* @__PURE__ */ jsxs5(
1969
+ "div",
1970
+ {
1971
+ ref: popup.root,
1972
+ className: `xlsx-toolbar-dropdown${layout === "row" ? " xlsx-toolbar-labelled" : ""}`,
1973
+ children: [
1974
+ layout === "row" ? /* @__PURE__ */ jsx9("span", { className: "xlsx-toolbar-row-label", children: s.label }) : null,
1975
+ /* @__PURE__ */ jsx9(
1976
+ Trigger,
1977
+ {
1978
+ s,
1979
+ popup,
1980
+ kind: "listbox",
1981
+ className: "xlsx-toolbar-color",
1982
+ caret: "menu",
1983
+ name: s.label,
1984
+ children: /* @__PURE__ */ jsxs5("span", { className: "xlsx-toolbar-color-icon", children: [
1985
+ /* @__PURE__ */ jsx9(ChromeIcon, { paths: s.control.paths }),
1986
+ /* @__PURE__ */ jsx9(
1987
+ "span",
1988
+ {
1989
+ className: "xlsx-toolbar-color-bar",
1990
+ "data-none": isHexColor(current) ? void 0 : "",
1991
+ style: isHexColor(current) ? { backgroundColor: `#${current}` } : void 0
1992
+ }
1993
+ )
1994
+ ] })
1995
+ }
1996
+ ),
1997
+ popup.open ? /* @__PURE__ */ jsx9(
1998
+ "div",
1999
+ {
2000
+ id: popup.id,
2001
+ role: "listbox",
2002
+ "aria-label": s.label,
2003
+ "aria-orientation": "horizontal",
2004
+ ...popupAttributes(layout, "xlsx-toolbar-palette"),
2005
+ onKeyDown: (e) => movePopupFocus(e, "[data-color]", true),
2006
+ children: colors.map((c) => /* @__PURE__ */ jsx9(
2007
+ "button",
2008
+ {
2009
+ type: "button",
2010
+ role: "option",
2011
+ tabIndex: -1,
2012
+ "data-color": c.value,
2013
+ "aria-label": c.label,
2014
+ title: c.label,
2015
+ "aria-selected": c.value === current,
2016
+ className: c.value === NO_FILL ? "xlsx-toolbar-no-fill" : "xlsx-toolbar-swatch",
2017
+ style: c.value === NO_FILL ? void 0 : { backgroundColor: `#${c.value}` },
2018
+ onMouseDown: guardToolbarMousedown,
2019
+ onClick: () => pick(c.value),
2020
+ children: c.value === NO_FILL ? c.label : null
2021
+ },
2022
+ c.value
2023
+ ))
2024
+ }
2025
+ ) : null
2026
+ ]
2027
+ }
2028
+ );
2029
+ }
2030
+ function MenuItem({ slot, close }) {
2031
+ const s = useToolbarSlot(slot);
2032
+ const reasonId = useId4();
2033
+ return (
2034
+ // A disabled menu item stays focusable (`aria-disabled`), so the keyboard reaches its reason.
2035
+ /* @__PURE__ */ jsxs5(
2036
+ "button",
2037
+ {
2038
+ type: "button",
2039
+ role: "menuitem",
2040
+ className: "xlsx-toolbar-row",
2041
+ tabIndex: -1,
2042
+ "data-slot": s.slot,
2043
+ "aria-disabled": !s.isEnabled,
2044
+ ...s.disabledReason ? { "aria-describedby": reasonId } : {},
2045
+ title: s.title,
2046
+ onMouseDown: guardToolbarMousedown,
2047
+ onClick: () => {
2048
+ if (!s.isEnabled) return;
2049
+ close();
2050
+ s.execute();
2051
+ s.focusGrid();
2052
+ },
2053
+ children: [
2054
+ /* @__PURE__ */ jsx9(ChromeIcon, { paths: s.control.paths }),
2055
+ /* @__PURE__ */ jsx9("span", { children: s.label }),
2056
+ s.disabledReason ? /* @__PURE__ */ jsx9("span", { id: reasonId, className: "xlsx-toolbar-reason", children: s.disabledReason }) : null
2057
+ ]
2058
+ }
2059
+ )
2060
+ );
2061
+ }
2062
+ function GroupMenu({ group }) {
2063
+ const { t } = useTranslation();
2064
+ const popup = usePopup('[role="menuitem"]');
2065
+ const name = translateKey(t, group.labelKey);
2066
+ return /* @__PURE__ */ jsxs5("div", { ref: popup.root, className: "xlsx-toolbar-dropdown", children: [
2067
+ /* @__PURE__ */ jsxs5(
2068
+ "button",
2069
+ {
2070
+ type: "button",
2071
+ className: "xlsx-toolbar-button xlsx-toolbar-menu-button",
2072
+ "data-group-menu": group.id,
2073
+ "aria-haspopup": "menu",
2074
+ "aria-expanded": popup.open,
2075
+ "aria-controls": popup.open ? popup.id : void 0,
2076
+ "aria-label": name,
2077
+ title: name,
2078
+ onMouseDown: guardToolbarMousedown,
2079
+ onClick: () => popup.setOpen(!popup.open),
2080
+ ...popupTriggerKeys(popup, true),
2081
+ children: [
2082
+ /* @__PURE__ */ jsx9(ChromeIcon, { paths: group.menu?.paths ?? null }),
2083
+ /* @__PURE__ */ jsx9(ChromeIcon, { paths: ICON_MENU_CARET, className: "xlsx-toolbar-caret" })
2084
+ ]
2085
+ }
2086
+ ),
2087
+ popup.open ? /* @__PURE__ */ jsx9(
2088
+ "div",
2089
+ {
2090
+ id: popup.id,
2091
+ role: "menu",
2092
+ "aria-label": name,
2093
+ className: "xlsx-toolbar-popup xlsx-toolbar-menu",
2094
+ "data-popup": "",
2095
+ onKeyDown: (e) => movePopupFocus(e, '[role="menuitem"]'),
2096
+ children: group.controls.map((c) => /* @__PURE__ */ jsx9(
2097
+ MenuItem,
2098
+ {
2099
+ slot: `${group.id}.${c.id}`,
2100
+ close: () => popup.setOpen(false)
2101
+ },
2102
+ c.id
2103
+ ))
2104
+ }
2105
+ ) : null
2106
+ ] });
2107
+ }
2108
+
2109
+ // src/toolbar/host-parts.tsx
2110
+ import {
2111
+ Children,
2112
+ Fragment as Fragment4,
2113
+ cloneElement,
2114
+ createContext as createContext5,
2115
+ isValidElement,
2116
+ useContext as useContext6,
2117
+ useEffect as useEffect7
2118
+ } from "react";
2119
+ import {
2120
+ CHROME_GROUPS,
2121
+ chromeSlotId,
2122
+ toolbarGroupHeading
2123
+ } from "@xlsx-editor.dev/core/editor";
2124
+ import { Fragment as Fragment5, jsx as jsx10 } from "react/jsx-runtime";
2125
+ function markPart(part, marker) {
2126
+ part[marker] = true;
2127
+ }
2128
+ var PartLayoutContext = createContext5("bar");
2129
+ function Control({
2130
+ group,
2131
+ control,
2132
+ layout,
2133
+ replaced
2134
+ }) {
2135
+ const slot = chromeSlotId(group, control);
2136
+ if (slot === "font.family") return /* @__PURE__ */ jsx10(FontFamilyList, { layout });
2137
+ if (slot === "font.size") return /* @__PURE__ */ jsx10(FontSizeList, { layout });
2138
+ const listed = (id) => group.controls.some((c) => c.id === id) && !replaced?.has(`${group.id}.${id}`);
2139
+ if (slot === "number.format") return /* @__PURE__ */ jsx10(NumberFormatList, { layout, more: listed("custom") });
2140
+ if (control.shape === "dialog" && slot === "number.custom")
2141
+ return listed("format") ? null : /* @__PURE__ */ jsx10(NumberFormatDialogButton, { layout });
2142
+ if (slot === "font.color" || slot === "fill.color")
2143
+ return /* @__PURE__ */ jsx10(ColorPalette, { slot, layout });
2144
+ return /* @__PURE__ */ jsx10(ToolbarButton, { slot, layout });
2145
+ }
2146
+ function groupOfSlot(slot) {
2147
+ for (const g of CHROME_GROUPS)
2148
+ for (const c of g.controls)
2149
+ if (chromeSlotId(g, c) === slot) return { group: { ...g, controls: [c] }, control: c };
2150
+ return null;
2151
+ }
2152
+ function XlsxEditorToolbarSlot({ slotId, hidden, children }) {
2153
+ const layout = useContext6(PartLayoutContext);
2154
+ const content = hasContent(children);
2155
+ const found = hidden || content ? null : groupOfSlot(slotId);
2156
+ const unknown = !hidden && !content && !found;
2157
+ useEffect7(() => {
2158
+ if (unknown) warnToolbarProblems([unknownSlotProblem(slotId, "XlsxEditor.Toolbar.Slot")]);
2159
+ }, [unknown, slotId]);
2160
+ if (hidden) return null;
2161
+ if (content) return /* @__PURE__ */ jsx10(Fragment5, { children });
2162
+ return found ? /* @__PURE__ */ jsx10(Control, { group: found.group, control: found.control, layout }) : null;
2163
+ }
2164
+ markPart(XlsxEditorToolbarSlot, "xlsxToolbarSlot");
2165
+ function XlsxEditorToolbarGroup(props) {
2166
+ const { t } = useTranslation();
2167
+ if (props.hidden || !hasContent(props.children)) return null;
2168
+ return /* @__PURE__ */ jsx10(
2169
+ "div",
2170
+ {
2171
+ role: "group",
2172
+ "aria-label": toolbarGroupHeading(props, (key) => translateKey(t, key)),
2173
+ className: `xlsx-toolbar-group${props.className ? ` ${props.className}` : ""}`,
2174
+ "data-host-group": props.id,
2175
+ children: props.children
2176
+ }
2177
+ );
2178
+ }
2179
+ markPart(XlsxEditorToolbarGroup, "xlsxToolbarGroup");
2180
+ function flatChildren(children, prefix = "") {
2181
+ return Children.toArray(children).flatMap((child) => {
2182
+ if (!isValidElement(child)) return [child];
2183
+ if (child.type === Fragment4)
2184
+ return flatChildren(
2185
+ child.props.children,
2186
+ `${prefix}${String(child.key)}/`
2187
+ );
2188
+ return [prefix ? cloneElement(child, { key: `${prefix}${String(child.key)}` }) : child];
2189
+ });
2190
+ }
2191
+ function hasContent(children) {
2192
+ return flatChildren(children).some((child) => child !== "");
2193
+ }
2194
+ var isPart = (child, marker) => isValidElement(child) && (typeof child.type === "function" || typeof child.type === "object") && child.type[marker] === true;
2195
+ function partOf(child) {
2196
+ return isPart(child, "xlsxToolbarSlot") || isPart(child, "xlsxToolbarGroup") ? child : null;
2197
+ }
2198
+ function readToolbarChildren(children) {
2199
+ const slots = /* @__PURE__ */ new Map();
2200
+ const groups = /* @__PURE__ */ new Map();
2201
+ const slotRequests = [];
2202
+ const groupRequests = [];
2203
+ const appended = [];
2204
+ for (const child of flatChildren(children)) {
2205
+ const part = partOf(child);
2206
+ if (part && isPart(part, "xlsxToolbarGroup")) {
2207
+ const props = part.props;
2208
+ const id = String(props.id);
2209
+ groups.set(id, props);
2210
+ groupRequests.push({
2211
+ id,
2212
+ after: props.after,
2213
+ hidden: props.hidden === true,
2214
+ label: props.label,
2215
+ labelKey: props.labelKey,
2216
+ content: hasContent(props.children)
2217
+ });
2218
+ } else if (part) {
2219
+ const props = part.props;
2220
+ const slotId = String(props.slotId);
2221
+ slots.set(slotId, props);
2222
+ slotRequests.push({
2223
+ slotId,
2224
+ hidden: props.hidden === true,
2225
+ content: hasContent(props.children)
2226
+ });
2227
+ } else appended.push(child);
2228
+ }
2229
+ return { slots, groups, appended, slotRequests, groupRequests };
2230
+ }
2231
+ function unknownSlotProblem(slotId, part) {
2232
+ return `"${slotId}" is not a toolbar slot id, so its ${part} renders nothing. Use a ChromeSlotId, such as "font.bold".`;
2233
+ }
2234
+ var printed = /* @__PURE__ */ new Set();
2235
+ function warnToolbarProblems(problems) {
2236
+ if (problems.length === 0 || !isDevelopment()) return;
2237
+ for (const problem of problems) {
2238
+ if (printed.has(problem)) continue;
2239
+ printed.add(problem);
2240
+ console.warn(`[xlsx-editor] ${problem}`);
2241
+ }
2242
+ }
2243
+
2244
+ // src/toolbar/Toolbar.tsx
2245
+ import { Fragment as Fragment7, jsx as jsx11, jsxs as jsxs6 } from "react/jsx-runtime";
2246
+ function groupHeading(t, group) {
2247
+ const translate = (key) => translateKey(t, key);
2248
+ return group.chrome ? translate(group.chrome.labelKey) : toolbarGroupHeading2(group, translate);
2249
+ }
2250
+ function GroupContent({ group, parts, replaced, layout }) {
2251
+ const chrome = group.chrome;
2252
+ const content = (slot) => parts.slots.get(slot)?.children;
2253
+ const controls = chrome?.controls ?? [];
2254
+ const own = chrome?.menu && layout === "bar";
2255
+ const menu = own ? controls.filter((c) => !replaced.has(chromeSlotId2(chrome, c))) : [];
2256
+ return /* @__PURE__ */ jsxs6(Fragment7, { children: [
2257
+ chrome && menu.length > 0 ? /* @__PURE__ */ jsx11(GroupMenu, { group: { ...chrome, controls: menu } }) : null,
2258
+ chrome ? controls.map((c) => {
2259
+ const slot = chromeSlotId2(chrome, c);
2260
+ if (replaced.has(slot)) return /* @__PURE__ */ jsx11(Fragment6, { children: content(slot) }, c.id);
2261
+ if (own) return null;
2262
+ return /* @__PURE__ */ jsx11(Control, { group: chrome, control: c, layout, replaced }, c.id);
2263
+ }) : null,
2264
+ parts.groups.get(group.id)?.children
2265
+ ] });
2266
+ }
2267
+ function BarGroup(props) {
2268
+ const { t } = useTranslation();
2269
+ const own = props.parts.groups.get(props.group.id)?.className;
2270
+ return /* @__PURE__ */ jsx11(
2271
+ "div",
2272
+ {
2273
+ className: `xlsx-toolbar-group${own ? ` ${own}` : ""}`,
2274
+ role: "group",
2275
+ "aria-label": groupHeading(t, props.group),
2276
+ "data-group": props.group.id,
2277
+ children: /* @__PURE__ */ jsx11(GroupContent, { ...props, layout: "bar" })
2278
+ }
2279
+ );
2280
+ }
2281
+ var isLoading = (s) => s.status === "loading";
2282
+ function MorePanel({
2283
+ groups,
2284
+ parts,
2285
+ replaced
2286
+ }) {
2287
+ const { t } = useTranslation();
2288
+ const popup = usePopup("button, input", { nested: true });
2289
+ const text = t("formattingBar.more");
2290
+ const loading = useEditorState(isLoading);
2291
+ const { setOpen } = popup;
2292
+ useEffect8(() => {
2293
+ if (loading) setOpen(false);
2294
+ }, [loading, setOpen]);
2295
+ const closePanel = useCallback5(() => setOpen(false), [setOpen]);
2296
+ return /* @__PURE__ */ jsxs6("div", { ref: popup.root, className: "xlsx-toolbar-more", children: [
2297
+ /* @__PURE__ */ jsx11(
2298
+ "button",
2299
+ {
2300
+ type: "button",
2301
+ className: "xlsx-toolbar-button",
2302
+ "aria-haspopup": "dialog",
2303
+ "aria-expanded": popup.open,
2304
+ "aria-controls": popup.open ? popup.id : void 0,
2305
+ "aria-label": text,
2306
+ title: text,
2307
+ onMouseDown: guardToolbarMousedown2,
2308
+ onClick: () => popup.setOpen(!popup.open),
2309
+ ...popupTriggerKeys(popup, true),
2310
+ children: /* @__PURE__ */ jsx11(ChromeIcon, { paths: ICON_MORE })
2311
+ }
2312
+ ),
2313
+ popup.open ? /* @__PURE__ */ jsx11(
2314
+ "div",
2315
+ {
2316
+ id: popup.id,
2317
+ role: "dialog",
2318
+ "aria-label": text,
2319
+ className: "xlsx-toolbar-panel",
2320
+ "data-popup": "",
2321
+ children: /* @__PURE__ */ jsx11(PanelCloseContext.Provider, { value: closePanel, children: /* @__PURE__ */ jsx11(PartLayoutContext.Provider, { value: "row", children: groups.map((g) => /* @__PURE__ */ jsxs6(
2322
+ "div",
2323
+ {
2324
+ role: "group",
2325
+ "aria-label": groupHeading(t, g),
2326
+ className: "xlsx-toolbar-section",
2327
+ children: [
2328
+ /* @__PURE__ */ jsx11("span", { className: "xlsx-toolbar-heading", "aria-hidden": "true", children: groupHeading(t, g) }),
2329
+ /* @__PURE__ */ jsx11(GroupContent, { group: g, parts, replaced, layout: "row" })
2330
+ ]
2331
+ },
2332
+ `group:${g.id}`
2333
+ )) }) })
2334
+ }
2335
+ ) : null
2336
+ ] });
2337
+ }
2338
+ var NO_PARTS = readToolbarChildren(null);
2339
+ function XlsxEditorToolbarRoot({
2340
+ onSave,
2341
+ onSaveStart,
2342
+ opening,
2343
+ overflow = true,
2344
+ className,
2345
+ hidden,
2346
+ preset = true,
2347
+ children
2348
+ }) {
2349
+ const { t } = useTranslation();
2350
+ const openingNow = useRef7(opening ?? false);
2351
+ openingNow.current = opening ?? false;
2352
+ const host = useMemo5(
2353
+ () => ({
2354
+ ...onSave ? { save: onSave } : {},
2355
+ ...onSaveStart ? { saveStart: onSaveStart } : {},
2356
+ ...opening === void 0 ? {} : { opening: () => openingNow.current }
2357
+ }),
2358
+ [onSave, onSaveStart, opening]
2359
+ );
2360
+ const parts = preset ? readToolbarChildren(children) : NO_PARTS;
2361
+ const requestKey = JSON.stringify([
2362
+ [...hidden ?? []].sort(),
2363
+ parts.slotRequests,
2364
+ parts.groupRequests
2365
+ ]);
2366
+ const arrangement = useMemo5(() => {
2367
+ const [h, slots, groups2] = JSON.parse(requestKey);
2368
+ return arrangeToolbar({ hidden: h, slots, groups: groups2 });
2369
+ }, [requestKey]);
2370
+ useEffect8(() => warnToolbarProblems(arrangement.problems), [arrangement]);
2371
+ const groups = arrangement.groups;
2372
+ const fixed = preset ? [
2373
+ ...parts.appended.filter((child) => child !== ""),
2374
+ ...arrangement.outside.map((slot) => /* @__PURE__ */ jsx11(Fragment6, { children: parts.slots.get(slot)?.children }, `slot:${slot}`))
2375
+ ] : [];
2376
+ const hasFixed = fixed.length > 0;
2377
+ const measuring = preset && overflow;
2378
+ const bar = useRef7(null);
2379
+ const editor = useXlsxEditor();
2380
+ const wasOpening = useRef7(false);
2381
+ useEffect8(() => {
2382
+ const ended = wasOpening.current && !opening;
2383
+ wasOpening.current = !!opening;
2384
+ if (!ended || !editor) return;
2385
+ const refusal = editor.snapshot().refusal;
2386
+ if (refusal?.code === "loading" && refusal.command === "save") editor.dismissRefusal();
2387
+ }, [opening, editor]);
2388
+ const saves = !!onSave;
2389
+ useEffect8(() => {
2390
+ const el = bar.current;
2391
+ if (!el || !editor || !saves) return void 0;
2392
+ return listenSaveKey(el, () => runToolbarCommand2(editor, "file.save", void 0, host));
2393
+ }, [editor, saves, host]);
2394
+ const widths = useRef7(/* @__PURE__ */ new Map());
2395
+ const [shown, setShown] = useState7(groups.length);
2396
+ useLayoutEffect7(() => {
2397
+ widths.current.clear();
2398
+ }, [t, groups]);
2399
+ useLayoutEffect7(() => {
2400
+ const el = bar.current;
2401
+ if (!el || !measuring) {
2402
+ setShown(groups.length);
2403
+ return void 0;
2404
+ }
2405
+ const measure = () => {
2406
+ const next = measureToolbar(el, groups, widths.current);
2407
+ setShown((current) => current === next ? current : next);
2408
+ };
2409
+ measure();
2410
+ return observeToolbar(el, measure);
2411
+ }, [measuring, groups, shown, t, hasFixed]);
2412
+ const replaced = arrangement.replaced;
2413
+ let body;
2414
+ if (!preset) body = children;
2415
+ else {
2416
+ const rest = groups.slice(shown);
2417
+ const items = groups.slice(0, shown).map((g) => /* @__PURE__ */ jsx11(BarGroup, { group: g, parts, replaced }, `group:${g.id}`));
2418
+ if (rest.length > 0)
2419
+ items.push(/* @__PURE__ */ jsx11(MorePanel, { groups: rest, parts, replaced }, "more"));
2420
+ if (hasFixed)
2421
+ items.push(
2422
+ /* @__PURE__ */ jsx11("div", { className: "xlsx-toolbar-group", ...{ [TOOLBAR_FIXED_ATTRIBUTE]: "" }, children: fixed }, "fixed")
2423
+ );
2424
+ body = items;
2425
+ }
2426
+ return /* @__PURE__ */ jsx11(ToolbarHostContext.Provider, { value: host, children: /* @__PURE__ */ jsx11(NumberFormatDialogHost, { children: /* @__PURE__ */ jsx11(
2427
+ "div",
2428
+ {
2429
+ ref: bar,
2430
+ role: "toolbar",
2431
+ "aria-label": t("formattingBar.label"),
2432
+ className: `xlsx-toolbar${className ? ` ${className}` : ""}`,
2433
+ ...measuring ? { "data-overflow": "" } : {},
2434
+ onMouseDown: guardToolbarMousedown2,
2435
+ onKeyDown: moveBarFocus,
2436
+ children: body
2437
+ }
2438
+ ) }) });
2439
+ }
2440
+ var XlsxEditorToolbar = Object.assign(XlsxEditorToolbarRoot, {
2441
+ Slot: XlsxEditorToolbarSlot,
2442
+ Group: XlsxEditorToolbarGroup
2443
+ });
2444
+
2445
+ // src/XlsxEditor.tsx
2446
+ import { Fragment as Fragment8, jsx as jsx12, jsxs as jsxs7 } from "react/jsx-runtime";
2447
+ var statusOf = (snapshot) => snapshot.status;
2448
+ function Body({
2449
+ onSave,
2450
+ onSaveStart,
2451
+ opening
2452
+ }) {
2453
+ const status = useEditorState(statusOf);
2454
+ return /* @__PURE__ */ jsxs7(Fragment8, { children: [
2455
+ /* @__PURE__ */ jsx12(
2456
+ XlsxEditorToolbar,
2457
+ {
2458
+ ...onSave ? { onSave } : {},
2459
+ ...onSaveStart ? { onSaveStart } : {},
2460
+ ...opening === void 0 ? {} : { opening }
2461
+ }
2462
+ ),
2463
+ /* @__PURE__ */ jsx12(FormulaBar, {}),
2464
+ /* @__PURE__ */ jsx12(StatusMessage, {}),
2465
+ /* @__PURE__ */ jsx12(XlsxEditorContent, { className: status === "ready" ? void 0 : "xlsx-canvas-idle" }),
2466
+ /* @__PURE__ */ jsxs7("div", { className: "xlsx-footer", children: [
2467
+ /* @__PURE__ */ jsx12(SheetTabs, {}),
2468
+ /* @__PURE__ */ jsx12(ZoomControl, {})
2469
+ ] })
2470
+ ] });
2471
+ }
2472
+ var XlsxEditor = forwardRef2(function XlsxEditor2({ className, style, onSave, onSaveStart, opening, ...props }, ref) {
2473
+ return /* @__PURE__ */ jsx12(XlsxEditorRoot, { ref, ...props, children: /* @__PURE__ */ jsx12(XlsxEditorViewport, { ...className ? { className } : {}, ...style ? { style } : {}, children: /* @__PURE__ */ jsx12(
2474
+ Body,
2475
+ {
2476
+ ...onSave ? { onSave } : {},
2477
+ ...onSaveStart ? { onSaveStart } : {},
2478
+ ...opening === void 0 ? {} : { opening }
2479
+ }
2480
+ ) }) });
2481
+ });
2482
+
2483
+ // src/index.ts
2484
+ import {
2485
+ CLIPBOARD_TYPE,
2486
+ composesKey as composesKey2,
2487
+ contentFieldText as contentFieldText2,
2488
+ CUSTOM_NUMBER_FORMAT_PREFIX,
2489
+ editMoveOf as editMoveOf2,
2490
+ fieldHistoryKey,
2491
+ MAX_COLUMN_WIDTH,
2492
+ MAX_CONTENT_FIELD_CHARS,
2493
+ MAX_GO_TO_LENGTH as MAX_GO_TO_LENGTH2,
2494
+ MAX_LISTED_NUMBER_FORMATS,
2495
+ MAX_RESIZE_NEW_ROWS,
2496
+ MAX_ROW_HEIGHT,
2497
+ mergeCommandState,
2498
+ NUMBER_FORMAT_CODE_PROBLEM_KEYS,
2499
+ NUMBER_FORMAT_SAMPLE,
2500
+ numberFormatChoiceCode,
2501
+ numberFormatChoices,
2502
+ numberFormatCodeProblem,
2503
+ numberFormatDialogApplyStep as numberFormatDialogApplyStep2,
2504
+ numberFormatDialogCurrent as numberFormatDialogCurrent2,
2505
+ numberFormatDialogStart as numberFormatDialogStart2,
2506
+ numberFormatListView as numberFormatListView2,
2507
+ numberFormatValue,
2508
+ previewNumberFormat as previewNumberFormat2,
2509
+ refusalText as refusalText4,
2510
+ refusesEditText as refusesEditText2,
2511
+ refusesReference as refusesReference2,
2512
+ sheetCommandState as sheetCommandState2,
2513
+ trapTabWithin as trapTabWithin2,
2514
+ workbookNumberFormatCodes as workbookNumberFormatCodes2
2515
+ } from "@xlsx-editor.dev/core/editor";
2516
+
2517
+ // src/customization-hooks.ts
2518
+ import { useEffect as useEffect9, useRef as useRef8 } from "react";
2519
+ function useEditorEvent(event, handler) {
2520
+ const editor = useXlsxEditor();
2521
+ const handlerRef = useRef8(handler);
2522
+ useEffect9(() => {
2523
+ handlerRef.current = handler;
2524
+ });
2525
+ useEffect9(() => {
2526
+ if (!editor) return void 0;
2527
+ const forward = ((...args) => handlerRef.current(...args));
2528
+ return editor.on(event, forward);
2529
+ }, [editor, event]);
2530
+ }
2531
+
2532
+ // src/index.ts
2533
+ var XlsxEditor3 = Object.assign(XlsxEditor, {
2534
+ Root: XlsxEditorRoot,
2535
+ Viewport: XlsxEditorViewport,
2536
+ Content: XlsxEditorContent,
2537
+ Toolbar: XlsxEditorToolbar,
2538
+ FormulaBar,
2539
+ SheetTabs,
2540
+ ZoomControl,
2541
+ StatusMessage
2542
+ });
2543
+ export {
2544
+ CLIPBOARD_TYPE,
2545
+ CUSTOM_NUMBER_FORMAT_PREFIX,
2546
+ FormulaBar,
2547
+ MAX_COLUMN_WIDTH,
2548
+ MAX_CONTENT_FIELD_CHARS,
2549
+ MAX_GO_TO_LENGTH2 as MAX_GO_TO_LENGTH,
2550
+ MAX_LISTED_NUMBER_FORMATS,
2551
+ MAX_RESIZE_NEW_ROWS,
2552
+ MAX_ROW_HEIGHT,
2553
+ NUMBER_FORMAT_CODE_PROBLEM_KEYS,
2554
+ NUMBER_FORMAT_SAMPLE,
2555
+ SheetTabs,
2556
+ StatusMessage,
2557
+ TranslationContext,
2558
+ XlsxEditor3 as XlsxEditor,
2559
+ XlsxEditorContent,
2560
+ XlsxEditorContext,
2561
+ XlsxEditorRoot,
2562
+ XlsxEditorToolbar,
2563
+ XlsxEditorToolbarGroup,
2564
+ XlsxEditorToolbarSlot,
2565
+ XlsxEditorViewport,
2566
+ ZoomControl,
2567
+ composesKey2 as composesKey,
2568
+ contentFieldText2 as contentFieldText,
2569
+ editMoveOf2 as editMoveOf,
2570
+ fieldHistoryKey,
2571
+ mergeCommandState,
2572
+ numberFormatChoiceCode,
2573
+ numberFormatChoices,
2574
+ numberFormatCodeProblem,
2575
+ numberFormatDialogApplyStep2 as numberFormatDialogApplyStep,
2576
+ numberFormatDialogCurrent2 as numberFormatDialogCurrent,
2577
+ numberFormatDialogStart2 as numberFormatDialogStart,
2578
+ numberFormatListView2 as numberFormatListView,
2579
+ numberFormatValue,
2580
+ previewNumberFormat2 as previewNumberFormat,
2581
+ refusalText4 as refusalText,
2582
+ refusesEditText2 as refusesEditText,
2583
+ refusesReference2 as refusesReference,
2584
+ sheetCommandState2 as sheetCommandState,
2585
+ translatorFor,
2586
+ trapTabWithin2 as trapTabWithin,
2587
+ useEditorColorMode,
2588
+ useEditorCommand,
2589
+ useEditorEvent,
2590
+ useEditorSnapshot,
2591
+ useEditorState,
2592
+ useScopeClassName,
2593
+ useTranslation,
2594
+ useViewModeWaits,
2595
+ useXlsxEditor,
2596
+ workbookNumberFormatCodes2 as workbookNumberFormatCodes
2597
+ };