@hussmartinez/image-sdk 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1617 @@
1
+ import { D as createImageReducer, F as DEVELOP_ADJUSTMENTS, G as placement, I as FILTER_PRESETS, K as createImageProcessor, M as MAX_METADATA_LENGTH, P as longerThan, V as createImageRenderer, _ as outputSize, a as compositionDeltaToSource, c as fitAspect, d as nudgeCropOnScreen, f as wholeCrop, i as aspectRatio, l as handleInSource, n as createImageSession, o as cropInComposition, p as compositionSize, q as createImageEngine, r as ASPECT_PRESETS, s as dragHandle, t as imageMessages, tt as isImageError, u as moveCrop } from "./core-cKo2m54U.js";
2
+ import { applyCommands, createMessages, createShortcutRegistry, createStore, createToolRegistry, defineTool } from "@hussmartinez/sdk-core";
3
+ import { AnnouncerProvider, Button, CropIcon, Dialog, DownloadIcon, Field, FileDropZone, FitIcon, FlipHorizontalIcon, FlipVerticalIcon, IconButton, NumberField, OpenIcon, ProgressBar, RedoIcon, RotateLeftIcon, RotateRightIcon, SearchIcon, SegmentedControl, Slider, Spinner, TextField, Toolbar, ToolbarGroup, UiMessagesProvider, UndoIcon, ZoomInIcon, ZoomOutIcon, useAnnounce, usePlatform } from "@hussmartinez/ui/react";
4
+ import { createContext, forwardRef, useContext, useEffect, useId, useImperativeHandle, useMemo, useRef, useState, useSyncExternalStore } from "react";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+ // src/features/tool-types.ts
7
+ var hasDocument = ({ snapshot }) => snapshot.plan !== null;
8
+ // src/features/crop/crop-tools.ts
9
+ function startCrop({ session, editor }) {
10
+ const { plan, source } = session.getSnapshot();
11
+ if (!plan || !source) return;
12
+ editor.set((state) => ({
13
+ ...state,
14
+ tool: "crop",
15
+ crop: {
16
+ pending: plan.base.crop ?? wholeCrop(source),
17
+ aspect: "free"
18
+ }
19
+ }));
20
+ }
21
+ var cropTool = /* @__PURE__ */ defineTool({
22
+ id: "image.crop",
23
+ label: "tools.crop",
24
+ icon: "crop",
25
+ group: "crop",
26
+ isEnabled: hasDocument,
27
+ isActive: ({ editor }) => editor.tool === "crop",
28
+ run: (context) => {
29
+ if (context.editor.getSnapshot().tool === "crop") return;
30
+ startCrop(context);
31
+ },
32
+ shortcuts: ["C"]
33
+ });
34
+ function flip({ session }, axis) {
35
+ const plan = session.getSnapshot().plan;
36
+ if (!plan) return;
37
+ const orientation = {
38
+ ...plan.base.orientation,
39
+ [axis]: !plan.base.orientation[axis]
40
+ };
41
+ session.execute({
42
+ type: "image.setOrientation",
43
+ orientation
44
+ });
45
+ }
46
+ var flipHorizontalTool = /* @__PURE__ */ defineTool({
47
+ id: "image.flip-horizontal",
48
+ label: "tools.flip-horizontal",
49
+ icon: "flip-horizontal",
50
+ group: "orientation",
51
+ isEnabled: hasDocument,
52
+ run: (context) => flip(context, "flipX")
53
+ });
54
+ var flipVerticalTool = /* @__PURE__ */ defineTool({
55
+ id: "image.flip-vertical",
56
+ label: "tools.flip-vertical",
57
+ icon: "flip-vertical",
58
+ group: "orientation",
59
+ isEnabled: hasDocument,
60
+ run: (context) => flip(context, "flipY")
61
+ });
62
+ // src/features/export/export-tool.ts
63
+ var exportTool = /* @__PURE__ */ defineTool({
64
+ id: "image.export",
65
+ label: "tools.export",
66
+ icon: "export",
67
+ group: "export",
68
+ isEnabled: ({ snapshot, editor }) => snapshot.plan !== null && editor.tool === null,
69
+ run: ({ editor }) => editor.set((state) => ({
70
+ ...state,
71
+ dialog: "export"
72
+ }))
73
+ });
74
+ // src/features/history/history-tools.ts
75
+ var undoTool = /* @__PURE__ */ defineTool({
76
+ id: "image.undo",
77
+ label: "tools.undo",
78
+ icon: "undo",
79
+ group: "history",
80
+ isEnabled: ({ snapshot }) => snapshot.canUndo,
81
+ run: ({ session }) => {
82
+ session.undo();
83
+ },
84
+ shortcuts: "undo"
85
+ });
86
+ var redoTool = /* @__PURE__ */ defineTool({
87
+ id: "image.redo",
88
+ label: "tools.redo",
89
+ icon: "redo",
90
+ group: "history",
91
+ isEnabled: ({ snapshot }) => snapshot.canRedo,
92
+ run: ({ session }) => {
93
+ session.redo();
94
+ },
95
+ shortcuts: "redo"
96
+ });
97
+ // src/features/open/open-tool.ts
98
+ var openTool = /* @__PURE__ */ defineTool({
99
+ id: "image.open",
100
+ label: "tools.open",
101
+ icon: "open",
102
+ group: "file",
103
+ run: ({ chooseFile }) => chooseFile()
104
+ });
105
+ // src/features/orientation/orientation-tools.ts
106
+ function turned(orientation, direction) {
107
+ const mirrored = orientation.flipX !== orientation.flipY;
108
+ const clockwise = direction === "right" !== mirrored;
109
+ const rotate = (orientation.rotate + (clockwise ? 90 : 270)) % 360;
110
+ return {
111
+ ...orientation,
112
+ rotate
113
+ };
114
+ }
115
+ function turn({ session }, direction) {
116
+ const plan = session.getSnapshot().plan;
117
+ if (!plan) return;
118
+ session.execute({
119
+ type: "image.setOrientation",
120
+ orientation: turned(plan.base.orientation, direction)
121
+ });
122
+ }
123
+ var rotateLeftTool = /* @__PURE__ */ defineTool({
124
+ id: "image.rotate-left",
125
+ label: "tools.rotate-left",
126
+ icon: "rotate-left",
127
+ group: "orientation",
128
+ isEnabled: hasDocument,
129
+ run: (context) => turn(context, "left"),
130
+ shortcuts: ["["]
131
+ });
132
+ var rotateRightTool = /* @__PURE__ */ defineTool({
133
+ id: "image.rotate-right",
134
+ label: "tools.rotate-right",
135
+ icon: "rotate-right",
136
+ group: "orientation",
137
+ isEnabled: hasDocument,
138
+ run: (context) => turn(context, "right"),
139
+ shortcuts: ["]"]
140
+ });
141
+ // src/features/zoom/zoom-tools.ts
142
+ var STEP = 1.25;
143
+ var clamp = (zoom) => Math.min(16, Math.max(.1, zoom));
144
+ // src/features/tools.ts
145
+ var imageTools = [
146
+ openTool,
147
+ undoTool,
148
+ redoTool,
149
+ rotateLeftTool,
150
+ rotateRightTool,
151
+ flipHorizontalTool,
152
+ flipVerticalTool,
153
+ cropTool,
154
+ /* @__PURE__ */ defineTool({
155
+ id: "image.zoom-in",
156
+ label: "tools.zoom-in",
157
+ icon: "zoom-in",
158
+ group: "zoom",
159
+ isEnabled: hasDocument,
160
+ run: ({ view }) => view.set((v) => ({
161
+ ...v,
162
+ zoom: clamp(v.zoom * STEP)
163
+ })),
164
+ shortcuts: "zoom-in"
165
+ }),
166
+ /* @__PURE__ */ defineTool({
167
+ id: "image.zoom-out",
168
+ label: "tools.zoom-out",
169
+ icon: "zoom-out",
170
+ group: "zoom",
171
+ isEnabled: hasDocument,
172
+ run: ({ view }) => view.set((v) => ({
173
+ ...v,
174
+ zoom: clamp(v.zoom / STEP)
175
+ })),
176
+ shortcuts: "zoom-out"
177
+ }),
178
+ /* @__PURE__ */ defineTool({
179
+ id: "image.zoom-fit",
180
+ label: "tools.zoom-fit",
181
+ icon: "fit",
182
+ group: "zoom",
183
+ isEnabled: hasDocument,
184
+ run: ({ view }) => view.set({
185
+ zoom: 1,
186
+ pan: {
187
+ x: 0,
188
+ y: 0
189
+ }
190
+ }),
191
+ shortcuts: "zoom-reset"
192
+ }),
193
+ exportTool
194
+ ];
195
+ var DEFAULT_TOOLBAR = [
196
+ ["image.open"],
197
+ ["image.undo", "image.redo"],
198
+ [
199
+ "image.rotate-left",
200
+ "image.rotate-right",
201
+ "image.flip-horizontal",
202
+ "image.flip-vertical"
203
+ ],
204
+ ["image.crop"],
205
+ [
206
+ "image.zoom-in",
207
+ "image.zoom-out",
208
+ "image.zoom-fit"
209
+ ],
210
+ ["image.export"]
211
+ ];
212
+ // src/react/context.ts
213
+ function createOpener(session) {
214
+ let controller;
215
+ return {
216
+ async open(file) {
217
+ controller?.abort();
218
+ const current = new AbortController();
219
+ controller = current;
220
+ try {
221
+ await session.open(file, { signal: current.signal });
222
+ } catch {} finally {
223
+ if (controller === current) controller = void 0;
224
+ }
225
+ },
226
+ cancel() {
227
+ controller?.abort();
228
+ controller = void 0;
229
+ }
230
+ };
231
+ }
232
+ var ImageContext = /* @__PURE__ */ createContext(void 0);
233
+ // src/react/hooks.ts
234
+ function useImageContext(hook) {
235
+ const value = useContext(ImageContext);
236
+ if (!value) throw new Error(`${hook}() must be used inside an ImageEditorProvider.`);
237
+ return value;
238
+ }
239
+ function useImageSession() {
240
+ return useImageContext("useImageSession").session;
241
+ }
242
+ function useImageDocument() {
243
+ const { session } = useImageContext("useImageDocument");
244
+ return useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot);
245
+ }
246
+ function useImageView() {
247
+ const { view } = useImageContext("useImageView");
248
+ return [useSyncExternalStore(view.subscribe, view.getSnapshot, view.getSnapshot), view];
249
+ }
250
+ function useImageEditorState() {
251
+ const { editor } = useImageContext("useImageEditorState");
252
+ return [useSyncExternalStore(editor.subscribe, editor.getSnapshot, editor.getSnapshot), editor];
253
+ }
254
+ function useImageMessages() {
255
+ return useImageContext("useImageMessages").messages;
256
+ }
257
+ function useImageInternals() {
258
+ return useImageContext("useImageInternals");
259
+ }
260
+ // src/react/crop/use-crop.ts
261
+ function useCropActions() {
262
+ const { session, editor, messages } = useImageInternals();
263
+ const announce = useAnnounce();
264
+ return useMemo(() => {
265
+ const pendingCrop = () => editor.getSnapshot().crop;
266
+ return {
267
+ update(crop) {
268
+ const current = pendingCrop();
269
+ if (!current) return;
270
+ editor.set((state) => ({
271
+ ...state,
272
+ crop: {
273
+ ...current,
274
+ pending: crop
275
+ }
276
+ }));
277
+ },
278
+ setAspect(aspect) {
279
+ const current = pendingCrop();
280
+ const source = session.getSnapshot().source;
281
+ if (!current || !source) return;
282
+ const pending = fitAspect(current.pending, aspectRatio(aspect, source));
283
+ editor.set((state) => ({
284
+ ...state,
285
+ crop: {
286
+ aspect,
287
+ pending
288
+ }
289
+ }));
290
+ },
291
+ apply() {
292
+ const current = pendingCrop();
293
+ const { plan, source } = session.getSnapshot();
294
+ editor.set((state) => ({
295
+ ...state,
296
+ tool: null,
297
+ crop: null
298
+ }));
299
+ if (!current || !plan || !source) return;
300
+ const whole = wholeCrop(source);
301
+ const crop = current.pending.x === 0 && current.pending.y === 0 && current.pending.width === whole.width && current.pending.height === whole.height ? null : current.pending;
302
+ if (JSON.stringify(crop) !== JSON.stringify(plan.base.crop)) session.execute({
303
+ type: "image.setCrop",
304
+ crop
305
+ });
306
+ announce(messages.t("crop.applied", {
307
+ width: current.pending.width,
308
+ height: current.pending.height
309
+ }));
310
+ },
311
+ cancel() {
312
+ editor.set((state) => ({
313
+ ...state,
314
+ tool: null,
315
+ crop: null
316
+ }));
317
+ }
318
+ };
319
+ }, [
320
+ announce,
321
+ editor,
322
+ messages,
323
+ session
324
+ ]);
325
+ }
326
+ // src/react/crop/CropPanel.tsx
327
+ var aspectKey = (aspect) => typeof aspect === "string" ? aspect : `${aspect[0]}:${aspect[1]}`;
328
+ function ImageCropPanel(props) {
329
+ const [state] = useImageEditorState();
330
+ const { source } = useImageDocument();
331
+ const messages = useImageMessages();
332
+ const actions = useCropActions();
333
+ const crop = state.crop;
334
+ if (state.tool !== "crop" || !crop || !source) return null;
335
+ const { pending } = crop;
336
+ const field = (name) => {
337
+ const max = name === "x" ? source.width - pending.width : name === "y" ? source.height - pending.height : name === "width" ? source.width - pending.x : source.height - pending.y;
338
+ return /* @__PURE__ */ jsx(Field, {
339
+ label: messages.t(`crop.${name}`),
340
+ children: /* @__PURE__ */ jsx(NumberField, {
341
+ value: pending[name],
342
+ min: name === "width" || name === "height" ? 1 : 0,
343
+ max,
344
+ step: 1,
345
+ largeStep: 10,
346
+ onValueChange: (value) => {
347
+ const next = {
348
+ ...pending,
349
+ [name]: Math.round(value)
350
+ };
351
+ actions.update(name === "x" || name === "y" ? moveCrop(next, 0, 0, source) : next);
352
+ }
353
+ })
354
+ }, name);
355
+ };
356
+ const options = ASPECT_PRESETS.map((aspect) => ({
357
+ value: aspectKey(aspect),
358
+ label: typeof aspect === "string" ? messages.t(`crop.aspects.${aspect}`) : messages.t("crop.aspects.ratio", {
359
+ width: aspect[0],
360
+ height: aspect[1]
361
+ })
362
+ }));
363
+ return /* @__PURE__ */ jsxs("section", {
364
+ className: ["hm-image-crop-panel", props.className].filter(Boolean).join(" "),
365
+ "aria-label": messages.t("crop.panel"),
366
+ children: [
367
+ /* @__PURE__ */ jsx("div", {
368
+ className: "hm-image-crop-fields",
369
+ children: [
370
+ "x",
371
+ "y",
372
+ "width",
373
+ "height"
374
+ ].map(field)
375
+ }),
376
+ /* @__PURE__ */ jsx(SegmentedControl, {
377
+ label: messages.t("crop.aspect"),
378
+ value: aspectKey(crop.aspect),
379
+ options,
380
+ size: "small",
381
+ onValueChange: (value) => {
382
+ const aspect = ASPECT_PRESETS.find((a) => aspectKey(a) === value);
383
+ if (aspect) actions.setAspect(aspect);
384
+ }
385
+ }),
386
+ /* @__PURE__ */ jsxs("div", {
387
+ className: "hm-image-crop-actions",
388
+ children: [
389
+ /* @__PURE__ */ jsx(Button, {
390
+ variant: "secondary",
391
+ onClick: () => actions.update(wholeCrop(source)),
392
+ children: messages.t("crop.reset")
393
+ }),
394
+ /* @__PURE__ */ jsx(Button, {
395
+ variant: "secondary",
396
+ onClick: () => actions.cancel(),
397
+ children: messages.t("crop.cancel")
398
+ }),
399
+ /* @__PURE__ */ jsx(Button, {
400
+ variant: "primary",
401
+ onClick: () => actions.apply(),
402
+ children: messages.t("crop.apply")
403
+ })
404
+ ]
405
+ })
406
+ ]
407
+ });
408
+ }
409
+ // src/react/export/export-listener.ts
410
+ var ExportListenerContext = createContext(null);
411
+ // src/react/export/ExportDialog.tsx
412
+ var FORMATS = [
413
+ "png",
414
+ "jpeg",
415
+ "webp"
416
+ ];
417
+ var EXTENSIONS = {
418
+ png: "png",
419
+ jpeg: "jpg",
420
+ webp: "webp"
421
+ };
422
+ var FIELDS = [
423
+ "title",
424
+ "description",
425
+ "artist",
426
+ "copyright"
427
+ ];
428
+ var KINDS = [
429
+ "location",
430
+ "camera",
431
+ "timestamps",
432
+ "thumbnail",
433
+ "colourProfile",
434
+ "other"
435
+ ];
436
+ var DEFAULT_QUALITY = 92;
437
+ var keepable = (text) => longerThan(text, 2e3) ? [...text].slice(0, MAX_METADATA_LENGTH).join("") : text;
438
+ function initialDraft(plan, source) {
439
+ return {
440
+ format: FORMATS.includes(source.format) ? source.format : "png",
441
+ quality: DEFAULT_QUALITY,
442
+ output: plan.output,
443
+ metadata: plan.metadata
444
+ };
445
+ }
446
+ var sameOutput = (a, b) => a.kind === "scale" && b.kind === "scale" ? a.scale === b.scale : a.kind === "fit" && b.kind === "fit" && a.width === b.width && a.height === b.height;
447
+ function changes(plan, draft) {
448
+ const commands = [];
449
+ if (!sameOutput(plan.output, draft.output)) commands.push({
450
+ type: "image.setOutput",
451
+ output: draft.output
452
+ });
453
+ for (const field of FIELDS) if (plan.metadata[field] !== draft.metadata[field]) commands.push({
454
+ type: "image.setMetadata",
455
+ field,
456
+ value: draft.metadata[field]
457
+ });
458
+ return commands;
459
+ }
460
+ var formatOf = (draft) => draft.format === "png" ? { type: "png" } : {
461
+ type: draft.format,
462
+ quality: draft.quality / 100
463
+ };
464
+ function ImageExportDialog(props) {
465
+ const { onExport, fileName = "image" } = props;
466
+ const session = useImageSession();
467
+ const { plan, source } = useImageDocument();
468
+ const [editor, editorStore] = useImageEditorState();
469
+ const messages = useImageMessages();
470
+ const announce = useAnnounce();
471
+ const listener = useContext(ExportListenerContext);
472
+ const [draft, setDraft] = useState(null);
473
+ const [phase, setPhase] = useState({ kind: "choose" });
474
+ const [error, setError] = useState(null);
475
+ const controller = useRef(null);
476
+ const objectUrl = useRef(null);
477
+ const downloadButton = useRef(null);
478
+ const open = editor.dialog === "export" && plan !== null && source !== null;
479
+ const current = draft ?? (plan && source ? initialDraft(plan, source) : null);
480
+ const revoke = () => {
481
+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
482
+ objectUrl.current = null;
483
+ };
484
+ useEffect(() => {
485
+ if (open) return;
486
+ const running = controller.current;
487
+ controller.current = null;
488
+ running?.abort();
489
+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
490
+ objectUrl.current = null;
491
+ setDraft(null);
492
+ setPhase((now) => now.kind === "choose" ? now : { kind: "choose" });
493
+ setError(null);
494
+ }, [open]);
495
+ useEffect(() => () => {
496
+ controller.current?.abort();
497
+ controller.current = null;
498
+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
499
+ }, []);
500
+ const done = phase.kind === "done";
501
+ useEffect(() => {
502
+ if (done) downloadButton.current?.focus();
503
+ }, [done]);
504
+ const close = () => {
505
+ editorStore.set((state) => state.dialog === null ? state : {
506
+ ...state,
507
+ dialog: null
508
+ });
509
+ };
510
+ if (!plan || !source || !current) return null;
511
+ const update = (patch) => setDraft({
512
+ ...current,
513
+ ...patch
514
+ });
515
+ const formatName = (format) => messages.t(`export.formats.${format}`);
516
+ const run = async () => {
517
+ setError(null);
518
+ try {
519
+ const commands = changes(plan, current);
520
+ if (commands.length > 0) session.execute(commands);
521
+ } catch (reason) {
522
+ setError(reason);
523
+ return;
524
+ }
525
+ const running = new AbortController();
526
+ controller.current = running;
527
+ setPhase({
528
+ kind: "exporting",
529
+ progress: 0
530
+ });
531
+ try {
532
+ const result = await session.export(formatOf(current), {
533
+ signal: running.signal,
534
+ onProgress: (progress) => setPhase((now) => now.kind === "exporting" ? {
535
+ kind: "exporting",
536
+ progress
537
+ } : now)
538
+ });
539
+ if (controller.current !== running) return;
540
+ controller.current = null;
541
+ announce(messages.t("export.done", {
542
+ format: formatName(current.format),
543
+ size: result.blob.size
544
+ }));
545
+ listener?.({
546
+ format: current.format,
547
+ width: result.width,
548
+ height: result.height,
549
+ size: result.blob.size,
550
+ removed: result.removed,
551
+ kept: result.kept
552
+ });
553
+ if (onExport) {
554
+ onExport(result.blob, result);
555
+ close();
556
+ return;
557
+ }
558
+ setPhase({
559
+ kind: "done",
560
+ result,
561
+ format: current.format
562
+ });
563
+ } catch (reason) {
564
+ if (controller.current !== running) return;
565
+ controller.current = null;
566
+ setPhase({ kind: "choose" });
567
+ if (isImageError(reason) && reason.code === "ABORTED") {
568
+ announce(messages.t("export.cancelled"));
569
+ return;
570
+ }
571
+ setError(reason);
572
+ }
573
+ };
574
+ const stop = () => controller.current?.abort();
575
+ const download = () => {
576
+ if (phase.kind !== "done") return;
577
+ revoke();
578
+ objectUrl.current = URL.createObjectURL(phase.result.blob);
579
+ const link = document.createElement("a");
580
+ link.href = objectUrl.current;
581
+ link.download = `${fileName}.${EXTENSIONS[phase.format]}`;
582
+ link.click();
583
+ };
584
+ const composition = compositionSize(plan, source);
585
+ const size = outputSize(current.output, composition);
586
+ const removed = KINDS.filter((kind) => source.metadata[kind]);
587
+ const kept = FIELDS.filter((field) => current.metadata[field] !== "");
588
+ const exporting = phase.kind === "exporting";
589
+ const footer = phase.kind === "done" ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
590
+ variant: "secondary",
591
+ onClick: close,
592
+ children: messages.t("export.close")
593
+ }), /* @__PURE__ */ jsx(Button, {
594
+ ref: downloadButton,
595
+ variant: "primary",
596
+ onClick: download,
597
+ children: messages.t("export.download")
598
+ })] }) : exporting ? /* @__PURE__ */ jsx(Button, {
599
+ variant: "secondary",
600
+ onClick: stop,
601
+ children: messages.t("export.stop")
602
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
603
+ variant: "secondary",
604
+ onClick: close,
605
+ children: messages.t("export.cancel")
606
+ }), /* @__PURE__ */ jsx(Button, {
607
+ variant: "primary",
608
+ onClick: () => void run(),
609
+ children: messages.t("export.confirm")
610
+ })] });
611
+ return /* @__PURE__ */ jsx(Dialog, {
612
+ open,
613
+ onOpenChange: (next) => {
614
+ if (!next) close();
615
+ },
616
+ title: messages.t("export.title"),
617
+ description: messages.t("export.description"),
618
+ footer,
619
+ className: ["hm-image-export", props.className].filter(Boolean).join(" "),
620
+ children: phase.kind === "done" ? /* @__PURE__ */ jsx("p", {
621
+ className: "hm-image-export-result",
622
+ children: messages.t("export.ready", {
623
+ width: phase.result.width,
624
+ height: phase.result.height,
625
+ format: formatName(phase.format),
626
+ size: phase.result.blob.size
627
+ })
628
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
629
+ /* @__PURE__ */ jsxs("fieldset", {
630
+ className: "hm-image-export-choices",
631
+ disabled: exporting,
632
+ children: [
633
+ /* @__PURE__ */ jsx(SegmentedControl, {
634
+ label: messages.t("export.format"),
635
+ value: current.format,
636
+ size: "small",
637
+ options: FORMATS.map((format) => ({
638
+ value: format,
639
+ label: formatName(format)
640
+ })),
641
+ onValueChange: (format) => update({ format })
642
+ }),
643
+ current.format === "png" ? null : /* @__PURE__ */ jsx(Field, {
644
+ label: messages.t("export.quality"),
645
+ className: "hm-image-slider-field",
646
+ children: /* @__PURE__ */ jsx(Slider, {
647
+ min: 1,
648
+ max: 100,
649
+ step: 1,
650
+ largeStep: 10,
651
+ value: current.quality,
652
+ onValueChange: (quality) => update({ quality: Math.round(quality) })
653
+ })
654
+ }),
655
+ /* @__PURE__ */ jsx(SegmentedControl, {
656
+ label: messages.t("export.size"),
657
+ value: current.output.kind,
658
+ size: "small",
659
+ options: [{
660
+ value: "scale",
661
+ label: messages.t("export.sizes.scale")
662
+ }, {
663
+ value: "fit",
664
+ label: messages.t("export.sizes.fit")
665
+ }],
666
+ onValueChange: (kind) => update({ output: kind === "fit" ? {
667
+ kind: "fit",
668
+ width: composition.width,
669
+ height: composition.height
670
+ } : {
671
+ kind: "scale",
672
+ scale: 1
673
+ } })
674
+ }),
675
+ /* @__PURE__ */ jsx("div", {
676
+ className: "hm-image-export-fields",
677
+ children: current.output.kind === "scale" ? /* @__PURE__ */ jsx(Field, {
678
+ label: messages.t("export.scale"),
679
+ children: /* @__PURE__ */ jsx(NumberField, {
680
+ value: Math.round(current.output.scale * 100),
681
+ min: 1,
682
+ max: 100,
683
+ step: 1,
684
+ largeStep: 10,
685
+ onValueChange: (percent) => update({ output: {
686
+ kind: "scale",
687
+ scale: Math.round(percent) / 100
688
+ } })
689
+ })
690
+ }) : ["width", "height"].map((side) => {
691
+ const output = current.output;
692
+ return /* @__PURE__ */ jsx(Field, {
693
+ label: messages.t(side === "width" ? "export.fitWidth" : "export.fitHeight"),
694
+ children: /* @__PURE__ */ jsx(NumberField, {
695
+ value: output[side],
696
+ min: 1,
697
+ step: 1,
698
+ largeStep: 100,
699
+ onValueChange: (value) => update({ output: {
700
+ ...output,
701
+ [side]: Math.max(1, Math.round(value))
702
+ } })
703
+ })
704
+ }, side);
705
+ })
706
+ }),
707
+ /* @__PURE__ */ jsxs("fieldset", {
708
+ className: "hm-image-export-metadata",
709
+ children: [
710
+ /* @__PURE__ */ jsx("legend", { children: messages.t("export.fields") }),
711
+ /* @__PURE__ */ jsx("p", {
712
+ className: "hm-image-export-hint",
713
+ children: messages.t("export.fieldsHint")
714
+ }),
715
+ /* @__PURE__ */ jsx("div", {
716
+ className: "hm-image-export-fields",
717
+ children: FIELDS.map((field) => /* @__PURE__ */ jsx(Field, {
718
+ label: messages.t(`export.field.${field}`),
719
+ children: /* @__PURE__ */ jsx(TextField, {
720
+ autoComplete: "off",
721
+ value: current.metadata[field],
722
+ onValueChange: (value) => update({ metadata: {
723
+ ...current.metadata,
724
+ [field]: keepable(value)
725
+ } })
726
+ })
727
+ }, field))
728
+ })
729
+ ]
730
+ })
731
+ ]
732
+ }),
733
+ /* @__PURE__ */ jsxs("section", {
734
+ className: "hm-image-export-summary",
735
+ "aria-label": messages.t("export.summary"),
736
+ children: [
737
+ /* @__PURE__ */ jsx("p", { children: messages.t("export.output", {
738
+ width: size.width,
739
+ height: size.height,
740
+ format: formatName(current.format)
741
+ }) }),
742
+ removed.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", { children: messages.t("export.removed") }), /* @__PURE__ */ jsx("ul", { children: removed.map((kind) => /* @__PURE__ */ jsx("li", { children: messages.t(`export.kind.${kind}`) }, kind)) })] }) : /* @__PURE__ */ jsx("p", { children: messages.t("export.removedNone") }),
743
+ kept.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", { children: messages.t("export.kept") }), /* @__PURE__ */ jsx("ul", { children: kept.map((field) => /* @__PURE__ */ jsx("li", { children: messages.t(`export.field.${field}`) }, field)) })] }) : null
744
+ ]
745
+ }),
746
+ exporting ? /* @__PURE__ */ jsx(ProgressBar, {
747
+ label: messages.t("export.progress"),
748
+ value: Math.round(phase.progress * 100),
749
+ max: 100
750
+ }) : null,
751
+ error ? /* @__PURE__ */ jsx("p", {
752
+ className: "hm-image-export-error",
753
+ role: "alert",
754
+ children: messages.error(error)
755
+ }) : null
756
+ ] })
757
+ });
758
+ }
759
+ // src/features/editor-state.ts
760
+ var IDLE = Object.freeze({
761
+ tool: null,
762
+ crop: null,
763
+ preview: null,
764
+ dialog: null
765
+ });
766
+ function createEditorStore() {
767
+ return createStore(IDLE);
768
+ }
769
+ // src/react/view-store.ts
770
+ var FITTED = Object.freeze({
771
+ zoom: 1,
772
+ pan: Object.freeze({
773
+ x: 0,
774
+ y: 0
775
+ })
776
+ });
777
+ function createViewStore() {
778
+ return createStore(FITTED);
779
+ }
780
+ // src/react/ImageEditorProvider.tsx
781
+ function own(props) {
782
+ const engine = props.engine ?? createImageEngine(props.assetsUrl === void 0 ? {} : { assetsUrl: props.assetsUrl });
783
+ const processor = props.processor ?? createImageProcessor(engine);
784
+ const session = props.session ?? createImageSession({
785
+ engine,
786
+ processor,
787
+ ...props.filePolicy ? { filePolicy: props.filePolicy } : {},
788
+ ...props.onEvent ? { onEvent: props.onEvent } : {}
789
+ });
790
+ return {
791
+ engine,
792
+ session,
793
+ dispose() {
794
+ if (!props.session) session.destroy();
795
+ if (!props.processor) processor.destroy();
796
+ if (!props.engine) engine.destroy();
797
+ }
798
+ };
799
+ }
800
+ function ImageEditorProvider(props) {
801
+ const { messages: overrides, locale = "en", children } = props;
802
+ const [owned] = useState(() => own(props));
803
+ const [view] = useState(createViewStore);
804
+ const [editor] = useState(createEditorStore);
805
+ const [opener] = useState(() => createOpener(owned.session));
806
+ useEffect(() => {
807
+ if (owned.pending !== void 0) clearTimeout(owned.pending);
808
+ return () => {
809
+ owned.pending = setTimeout(() => owned.dispose(), 0);
810
+ };
811
+ }, [owned]);
812
+ const messages = useMemo(() => createMessages(imageMessages, {
813
+ locale,
814
+ ...overrides ? { overrides } : {}
815
+ }), [locale, overrides]);
816
+ const value = useMemo(() => ({
817
+ session: owned.session,
818
+ engine: owned.engine,
819
+ messages,
820
+ view,
821
+ editor,
822
+ opener
823
+ }), [
824
+ owned,
825
+ messages,
826
+ view,
827
+ editor,
828
+ opener
829
+ ]);
830
+ return /* @__PURE__ */ jsx(ImageContext.Provider, {
831
+ value,
832
+ children: /* @__PURE__ */ jsx(UiMessagesProvider, {
833
+ messages,
834
+ children
835
+ })
836
+ });
837
+ }
838
+ function useGesture() {
839
+ const { session, editor } = useImageInternals();
840
+ const gesture = useMemo(() => {
841
+ let pending;
842
+ let timer;
843
+ const reducer = createImageReducer((id) => {
844
+ const source = session.getSnapshot().source;
845
+ return source && source.id === id ? source : void 0;
846
+ });
847
+ const clearTimer = () => {
848
+ if (timer !== void 0) clearTimeout(timer);
849
+ timer = void 0;
850
+ };
851
+ const end = () => {
852
+ clearTimer();
853
+ pending = void 0;
854
+ editor.set((state) => state.preview === null ? state : {
855
+ ...state,
856
+ preview: null
857
+ });
858
+ };
859
+ const value = {
860
+ preview(commands) {
861
+ const plan = session.getSnapshot().plan;
862
+ if (!plan) return;
863
+ const preview = applyCommands(reducer, plan, commands).state;
864
+ pending = commands;
865
+ editor.set((state) => ({
866
+ ...state,
867
+ preview
868
+ }));
869
+ },
870
+ commit() {
871
+ const commands = pending;
872
+ end();
873
+ if (commands && commands.length > 0) session.execute(commands);
874
+ },
875
+ commitSoon() {
876
+ clearTimer();
877
+ timer = setTimeout(() => value.commit(), 500);
878
+ },
879
+ cancel: end,
880
+ active: () => pending !== void 0
881
+ };
882
+ return value;
883
+ }, [editor, session]);
884
+ useEffect(() => () => gesture.commit(), [gesture]);
885
+ return gesture;
886
+ }
887
+ // src/react/panels/use-slider-gesture.ts
888
+ function sliderGesture(gesture, command) {
889
+ return {
890
+ onValueChange: (value) => gesture.preview([command(value)]),
891
+ onPointerUp: (_event) => gesture.commit(),
892
+ onBlur: (_event) => gesture.commit(),
893
+ onKeyUp: (event) => {
894
+ if (event.key !== "Escape" && gesture.active()) gesture.commitSoon();
895
+ },
896
+ onKeyDown: (event) => {
897
+ if (event.key === "Escape" && gesture.active()) {
898
+ event.preventDefault();
899
+ event.stopPropagation();
900
+ gesture.cancel();
901
+ }
902
+ }
903
+ };
904
+ }
905
+ // src/react/panels/AdjustPanel.tsx
906
+ var signed = (value) => value > 0 ? `+${value}` : String(value);
907
+ function ImageAdjustPanel(props) {
908
+ const session = useImageSession();
909
+ const { plan } = useImageDocument();
910
+ const [editor] = useImageEditorState();
911
+ const messages = useImageMessages();
912
+ const gesture = useGesture();
913
+ const announce = useAnnounce();
914
+ const first = useRef(null);
915
+ if (!plan) return null;
916
+ const develop = (editor.preview ?? plan).base.develop;
917
+ const reset = (values) => {
918
+ gesture.cancel();
919
+ session.execute({
920
+ type: "image.setDevelop",
921
+ values
922
+ });
923
+ };
924
+ const changed = DEVELOP_ADJUSTMENTS.filter((name) => plan.base.develop[name] !== 0);
925
+ return /* @__PURE__ */ jsxs("section", {
926
+ className: ["hm-image-adjust-panel", props.className].filter(Boolean).join(" "),
927
+ "aria-label": messages.t("develop.panel"),
928
+ children: [DEVELOP_ADJUSTMENTS.map((name, index) => {
929
+ const label = messages.t(`develop.${name}`);
930
+ return /* @__PURE__ */ jsx(Field, {
931
+ label,
932
+ className: "hm-image-slider-field",
933
+ children: (control) => /* @__PURE__ */ jsxs("div", {
934
+ className: "hm-image-adjust-row",
935
+ children: [
936
+ /* @__PURE__ */ jsx(Slider, {
937
+ ...control,
938
+ ...index === 0 ? { ref: first } : {},
939
+ min: -100,
940
+ max: 100,
941
+ step: 1,
942
+ largeStep: 10,
943
+ value: develop[name],
944
+ formatValue: signed,
945
+ ...sliderGesture(gesture, (value) => ({
946
+ type: "image.setDevelop",
947
+ values: { [name]: Math.round(value) }
948
+ })),
949
+ onDoubleClick: () => {
950
+ if (plan.base.develop[name] !== 0) reset({ [name]: 0 });
951
+ }
952
+ }),
953
+ /* @__PURE__ */ jsx("output", {
954
+ className: "hm-image-adjust-value",
955
+ "aria-hidden": "true",
956
+ children: signed(develop[name])
957
+ }),
958
+ plan.base.develop[name] !== 0 ? /* @__PURE__ */ jsx(Button, {
959
+ variant: "quiet",
960
+ size: "small",
961
+ onClick: () => reset({ [name]: 0 }),
962
+ children: messages.t("develop.reset", { name: label })
963
+ }) : null
964
+ ]
965
+ })
966
+ }, name);
967
+ }), /* @__PURE__ */ jsx(Button, {
968
+ variant: "secondary",
969
+ disabled: changed.length === 0,
970
+ onClick: () => {
971
+ reset(Object.fromEntries(changed.map((name) => [name, 0])));
972
+ first.current?.focus();
973
+ announce(messages.t("develop.wasReset"));
974
+ },
975
+ children: messages.t("develop.resetAll")
976
+ })]
977
+ });
978
+ }
979
+ // src/react/panels/FilterPanel.tsx
980
+ function ImageFilterPanel(props) {
981
+ const session = useImageSession();
982
+ const { plan } = useImageDocument();
983
+ const [editor] = useImageEditorState();
984
+ const messages = useImageMessages();
985
+ const gesture = useGesture();
986
+ if (!plan) return null;
987
+ const filter = (editor.preview ?? plan).base.filter;
988
+ const options = [{
989
+ value: "none",
990
+ label: messages.t("filters.none")
991
+ }, ...FILTER_PRESETS.map((preset) => ({
992
+ value: preset,
993
+ label: messages.t(`filters.${preset}`)
994
+ }))];
995
+ return /* @__PURE__ */ jsxs("section", {
996
+ className: ["hm-image-filter-panel", props.className].filter(Boolean).join(" "),
997
+ "aria-label": messages.t("filters.panel"),
998
+ children: [/* @__PURE__ */ jsx(SegmentedControl, {
999
+ label: messages.t("filters.label"),
1000
+ value: filter?.preset ?? "none",
1001
+ options,
1002
+ onValueChange: (value) => {
1003
+ gesture.cancel();
1004
+ session.execute({
1005
+ type: "image.setFilter",
1006
+ filter: value === "none" ? null : {
1007
+ preset: value,
1008
+ strength: filter?.strength ?? 100
1009
+ }
1010
+ });
1011
+ }
1012
+ }), filter ? /* @__PURE__ */ jsx(Field, {
1013
+ label: messages.t("filters.strength"),
1014
+ className: "hm-image-slider-field",
1015
+ children: /* @__PURE__ */ jsx(Slider, {
1016
+ min: 0,
1017
+ max: 100,
1018
+ step: 1,
1019
+ largeStep: 10,
1020
+ value: filter.strength,
1021
+ ...sliderGesture(gesture, (value) => ({
1022
+ type: "image.setFilter",
1023
+ filter: {
1024
+ preset: filter.preset,
1025
+ strength: Math.round(value)
1026
+ }
1027
+ }))
1028
+ })
1029
+ }) : null]
1030
+ });
1031
+ }
1032
+ // src/react/panels/Inspector.tsx
1033
+ function ImageInspector() {
1034
+ const { plan } = useImageDocument();
1035
+ const [editor] = useImageEditorState();
1036
+ const messages = useImageMessages();
1037
+ const [panel, setPanel] = useState("adjust");
1038
+ if (editor.tool === "crop") return /* @__PURE__ */ jsx(ImageCropPanel, {});
1039
+ if (!plan) return null;
1040
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(SegmentedControl, {
1041
+ label: messages.t("inspector.label"),
1042
+ value: panel,
1043
+ size: "small",
1044
+ options: [{
1045
+ value: "adjust",
1046
+ label: messages.t("inspector.adjust")
1047
+ }, {
1048
+ value: "filters",
1049
+ label: messages.t("inspector.filters")
1050
+ }],
1051
+ onValueChange: (value) => setPanel(value)
1052
+ }), panel === "adjust" ? /* @__PURE__ */ jsx(ImageAdjustPanel, {}) : /* @__PURE__ */ jsx(ImageFilterPanel, {})] });
1053
+ }
1054
+ // src/react/crop/CropFrame.tsx
1055
+ var HANDLES = [
1056
+ "nw",
1057
+ "n",
1058
+ "ne",
1059
+ "e",
1060
+ "se",
1061
+ "s",
1062
+ "sw",
1063
+ "w"
1064
+ ];
1065
+ var ARROWS = /* @__PURE__ */ new Set([
1066
+ "ArrowLeft",
1067
+ "ArrowRight",
1068
+ "ArrowUp",
1069
+ "ArrowDown"
1070
+ ]);
1071
+ function CropFrame(props) {
1072
+ const { plan, source, view } = props;
1073
+ const [state] = useImageEditorState();
1074
+ const messages = useImageMessages();
1075
+ const actions = useCropActions();
1076
+ const frame = useRef(null);
1077
+ const describedBy = useId();
1078
+ const drag = useRef(void 0);
1079
+ useEffect(() => {
1080
+ frame.current?.focus();
1081
+ }, []);
1082
+ const crop = state.crop;
1083
+ if (!crop) return null;
1084
+ const { orientation } = plan.base;
1085
+ const whole = {
1086
+ ...plan,
1087
+ base: {
1088
+ ...plan.base,
1089
+ crop: null
1090
+ }
1091
+ };
1092
+ const placed = placement(compositionSize(whole, source), view);
1093
+ if (!(placed.scale > 0)) return null;
1094
+ const shown = cropInComposition(crop.pending, orientation, source);
1095
+ const ratio = aspectRatio(crop.aspect, source);
1096
+ const onKeyDown = (event) => {
1097
+ if (event.key === "Enter") {
1098
+ event.preventDefault();
1099
+ actions.apply();
1100
+ return;
1101
+ }
1102
+ if (event.key === "Escape") {
1103
+ event.preventDefault();
1104
+ if (drag.current) {
1105
+ actions.update(drag.current.start);
1106
+ drag.current = void 0;
1107
+ } else actions.cancel();
1108
+ return;
1109
+ }
1110
+ if (!ARROWS.has(event.key)) return;
1111
+ event.preventDefault();
1112
+ event.stopPropagation();
1113
+ actions.update(nudgeCropOnScreen(crop.pending, event.key, event.shiftKey ? 10 : 1, event.altKey, orientation, source, ratio));
1114
+ };
1115
+ const onPointerDown = (handle) => (event) => {
1116
+ if (event.button !== 0) return;
1117
+ event.preventDefault();
1118
+ event.stopPropagation();
1119
+ frame.current?.focus();
1120
+ try {
1121
+ event.currentTarget.setPointerCapture(event.pointerId);
1122
+ } catch {}
1123
+ drag.current = {
1124
+ pointer: event.pointerId,
1125
+ x: event.clientX,
1126
+ y: event.clientY,
1127
+ start: crop.pending,
1128
+ handle
1129
+ };
1130
+ };
1131
+ const onPointerMove = (event) => {
1132
+ const current = drag.current;
1133
+ if (!current || current.pointer !== event.pointerId) return;
1134
+ const moved = compositionDeltaToSource((event.clientX - current.x) / placed.scale, (event.clientY - current.y) / placed.scale, orientation, source);
1135
+ actions.update(current.handle === "move" ? moveCrop(current.start, moved.dx, moved.dy, source) : dragHandle(current.start, handleInSource(current.handle, orientation), moved.dx, moved.dy, source, ratio));
1136
+ };
1137
+ const onPointerEnd = (event) => {
1138
+ if (drag.current?.pointer !== event.pointerId) return;
1139
+ if (event.type === "pointercancel") actions.update(drag.current.start);
1140
+ drag.current = void 0;
1141
+ };
1142
+ const style = {
1143
+ left: `${placed.x + shown.x * placed.scale}px`,
1144
+ top: `${placed.y + shown.y * placed.scale}px`,
1145
+ width: `${shown.width * placed.scale}px`,
1146
+ height: `${shown.height * placed.scale}px`
1147
+ };
1148
+ const pointer = {
1149
+ onPointerMove,
1150
+ onPointerUp: onPointerEnd,
1151
+ onPointerCancel: onPointerEnd
1152
+ };
1153
+ return /* @__PURE__ */ jsxs("div", {
1154
+ ref: frame,
1155
+ className: "hm-image-crop-frame",
1156
+ role: "group",
1157
+ "aria-label": messages.t("crop.frame"),
1158
+ "aria-describedby": describedBy,
1159
+ tabIndex: 0,
1160
+ style,
1161
+ onKeyDown,
1162
+ onPointerDown: onPointerDown("move"),
1163
+ ...pointer,
1164
+ children: [/* @__PURE__ */ jsx("span", {
1165
+ id: describedBy,
1166
+ hidden: true,
1167
+ children: messages.t("crop.frameDescription", {
1168
+ width: crop.pending.width,
1169
+ height: crop.pending.height,
1170
+ x: crop.pending.x,
1171
+ y: crop.pending.y
1172
+ })
1173
+ }), HANDLES.map((handle) => /* @__PURE__ */ jsx("span", {
1174
+ className: "hm-image-crop-handle",
1175
+ "data-hm-handle": handle,
1176
+ "aria-hidden": "true",
1177
+ onPointerDown: onPointerDown(handle),
1178
+ ...pointer
1179
+ }, handle))]
1180
+ });
1181
+ }
1182
+ // src/react/stage/ImageStage.tsx
1183
+ var CROP_INSET = 24;
1184
+ function useStageSize(element) {
1185
+ const [size, setSize] = useState();
1186
+ useEffect(() => {
1187
+ if (!element) return;
1188
+ let ratioQuery;
1189
+ const measure = () => {
1190
+ const { width, height } = element.getBoundingClientRect();
1191
+ const pixelRatio = globalThis.devicePixelRatio || 1;
1192
+ setSize((current) => current?.width === width && current.height === height && current.pixelRatio === pixelRatio ? current : {
1193
+ width,
1194
+ height,
1195
+ pixelRatio
1196
+ });
1197
+ };
1198
+ const watchRatio = () => {
1199
+ ratioQuery?.removeEventListener("change", onRatio);
1200
+ ratioQuery = globalThis.matchMedia?.(`(resolution: ${globalThis.devicePixelRatio || 1}dppx)`);
1201
+ ratioQuery?.addEventListener("change", onRatio);
1202
+ };
1203
+ const onRatio = () => {
1204
+ measure();
1205
+ watchRatio();
1206
+ };
1207
+ const observer = new ResizeObserver(measure);
1208
+ observer.observe(element);
1209
+ measure();
1210
+ watchRatio();
1211
+ return () => {
1212
+ observer.disconnect();
1213
+ ratioQuery?.removeEventListener("change", onRatio);
1214
+ };
1215
+ }, [element]);
1216
+ return size;
1217
+ }
1218
+ function ImageStage(props) {
1219
+ const { engine, messages, opener } = useImageInternals();
1220
+ const snapshot = useImageDocument();
1221
+ const [view] = useImageView();
1222
+ const [frame, setFrame] = useState(null);
1223
+ const size = useStageSize(frame);
1224
+ const canvasRef = useRef(null);
1225
+ const rendererRef = useRef(void 0);
1226
+ const [editorState] = useImageEditorState();
1227
+ const { source, status } = snapshot;
1228
+ const cropping = editorState.tool === "crop";
1229
+ const inset = cropping ? CROP_INSET : 0;
1230
+ const plan = useMemo(() => {
1231
+ const committed = snapshot.plan;
1232
+ if (!committed) return null;
1233
+ if (cropping) return {
1234
+ ...committed,
1235
+ base: {
1236
+ ...committed.base,
1237
+ crop: null
1238
+ }
1239
+ };
1240
+ return editorState.preview ?? committed;
1241
+ }, [
1242
+ snapshot.plan,
1243
+ cropping,
1244
+ editorState.preview
1245
+ ]);
1246
+ useEffect(() => {
1247
+ if (!frame) return;
1248
+ const canvas = document.createElement("canvas");
1249
+ canvas.className = "hm-image-stage-canvas";
1250
+ canvas.setAttribute("role", "img");
1251
+ frame.append(canvas);
1252
+ canvasRef.current = canvas;
1253
+ const renderer = createImageRenderer(engine);
1254
+ const attached = renderer.attach(canvas);
1255
+ attached.catch(() => {});
1256
+ rendererRef.current = {
1257
+ renderer,
1258
+ attached
1259
+ };
1260
+ return () => {
1261
+ rendererRef.current = void 0;
1262
+ canvasRef.current = null;
1263
+ renderer.destroy();
1264
+ canvas.remove();
1265
+ };
1266
+ }, [engine, frame]);
1267
+ const composition = plan && source ? compositionSize(plan, source) : void 0;
1268
+ const shownWidth = composition?.width;
1269
+ const shownHeight = composition?.height;
1270
+ useEffect(() => {
1271
+ const canvas = frame ? canvasRef.current : null;
1272
+ if (!canvas) return;
1273
+ canvas.hidden = shownWidth === void 0 || shownHeight === void 0;
1274
+ if (shownWidth !== void 0 && shownHeight !== void 0) canvas.setAttribute("aria-label", messages.t("editor.preview", {
1275
+ width: shownWidth,
1276
+ height: shownHeight
1277
+ }));
1278
+ else canvas.removeAttribute("aria-label");
1279
+ }, [
1280
+ shownWidth,
1281
+ shownHeight,
1282
+ messages,
1283
+ frame
1284
+ ]);
1285
+ useEffect(() => {
1286
+ const current = rendererRef.current;
1287
+ if (!current || !plan || !size || size.width < 1 || size.height < 1) return;
1288
+ const { renderer, attached } = current;
1289
+ attached.then(() => renderer.render(plan, {
1290
+ width: size.width,
1291
+ height: size.height,
1292
+ pixelRatio: size.pixelRatio,
1293
+ zoom: view.zoom,
1294
+ pan: view.pan,
1295
+ inset
1296
+ })).catch(() => {});
1297
+ }, [
1298
+ plan,
1299
+ view,
1300
+ size,
1301
+ inset
1302
+ ]);
1303
+ const className = ["hm-image-stage", props.className].filter(Boolean).join(" ");
1304
+ return /* @__PURE__ */ jsxs("div", {
1305
+ className,
1306
+ "data-status": status,
1307
+ children: [
1308
+ /* @__PURE__ */ jsx("div", {
1309
+ className: "hm-image-stage-frame",
1310
+ ref: setFrame
1311
+ }),
1312
+ cropping && snapshot.plan && source && size ? /* @__PURE__ */ jsx("div", {
1313
+ className: "hm-image-stage-overlay",
1314
+ children: /* @__PURE__ */ jsx(CropFrame, {
1315
+ plan: snapshot.plan,
1316
+ source,
1317
+ view: {
1318
+ width: size.width,
1319
+ height: size.height,
1320
+ pixelRatio: 1,
1321
+ zoom: view.zoom,
1322
+ pan: view.pan,
1323
+ inset
1324
+ }
1325
+ })
1326
+ }) : null,
1327
+ status === "empty" && !snapshot.opening ? /* @__PURE__ */ jsx(FileDropZone, {
1328
+ className: "hm-image-stage-drop",
1329
+ accept: "image/*",
1330
+ onFiles: (files) => {
1331
+ const [file] = files;
1332
+ if (file) opener.open(file);
1333
+ },
1334
+ buttonLabel: messages.t("editor.choose"),
1335
+ hint: messages.t("editor.dropHint"),
1336
+ children: /* @__PURE__ */ jsx("p", {
1337
+ className: "hm-image-stage-empty",
1338
+ children: messages.t("editor.empty")
1339
+ })
1340
+ }) : null,
1341
+ snapshot.opening ? /* @__PURE__ */ jsxs("div", {
1342
+ className: "hm-image-stage-opening",
1343
+ children: [/* @__PURE__ */ jsx(Spinner, { label: messages.t("editor.opening") }), /* @__PURE__ */ jsx(Button, {
1344
+ variant: "secondary",
1345
+ onClick: () => opener.cancel(),
1346
+ children: messages.t("editor.cancel")
1347
+ })]
1348
+ }) : null,
1349
+ snapshot.error ? /* @__PURE__ */ jsx("p", {
1350
+ className: "hm-image-stage-error",
1351
+ role: "alert",
1352
+ children: messages.error(snapshot.error)
1353
+ }) : null
1354
+ ]
1355
+ });
1356
+ }
1357
+ // src/react/toolbar/ImageToolbar.tsx
1358
+ function ImageToolbar(props) {
1359
+ const { registry, shortcuts, context, icons } = props;
1360
+ const messages = useImageMessages();
1361
+ const snapshot = useImageDocument();
1362
+ const [editor] = useImageEditorState();
1363
+ const state = {
1364
+ snapshot,
1365
+ editor
1366
+ };
1367
+ const t = messages.t;
1368
+ return /* @__PURE__ */ jsx(Toolbar, {
1369
+ label: messages.t("toolbar.label"),
1370
+ className: props.className,
1371
+ children: registry.toolbar.map((group) => /* @__PURE__ */ jsx(ToolbarGroup, {
1372
+ label: t(`toolbar.groups.${group[0]?.group ?? "other"}`),
1373
+ children: group.filter((tool) => tool.isAvailable?.(state) ?? true).map((tool) => {
1374
+ const Icon = icons[tool.icon];
1375
+ const keys = shortcuts?.ariaKeyShortcuts(tool.id);
1376
+ return /* @__PURE__ */ jsx(IconButton, {
1377
+ "data-tool": tool.id,
1378
+ label: t(tool.label),
1379
+ icon: Icon ? /* @__PURE__ */ jsx(Icon, {}) : null,
1380
+ disabled: !(tool.isEnabled?.(state) ?? true),
1381
+ ...tool.isActive ? { pressed: tool.isActive(state) } : {},
1382
+ ...keys ? { "aria-keyshortcuts": keys } : {},
1383
+ onClick: () => void tool.run(context)
1384
+ }, tool.id);
1385
+ })
1386
+ }, group.map((tool) => tool.id).join(" ")))
1387
+ });
1388
+ }
1389
+ // src/react/toolbar/icons.tsx
1390
+ var imageIcons = {
1391
+ open: OpenIcon,
1392
+ undo: UndoIcon,
1393
+ redo: RedoIcon,
1394
+ "rotate-left": RotateLeftIcon,
1395
+ "rotate-right": RotateRightIcon,
1396
+ "zoom-in": ZoomInIcon,
1397
+ "zoom-out": ZoomOutIcon,
1398
+ fit: FitIcon,
1399
+ crop: CropIcon,
1400
+ export: DownloadIcon,
1401
+ "flip-horizontal": FlipHorizontalIcon,
1402
+ "flip-vertical": FlipVerticalIcon,
1403
+ search: SearchIcon
1404
+ };
1405
+ // src/react/editor/ImageEditor.tsx
1406
+ var join = (...names) => names.filter(Boolean).join(" ");
1407
+ function ImageEditorBody(props) {
1408
+ const { initialFile, onChange, classNames = {}, unstyled = false, handle, events } = props;
1409
+ const { session, messages, view, editor, opener } = useImageInternals();
1410
+ const snapshot = useImageDocument();
1411
+ const announce = useAnnounce();
1412
+ const root = useRef(null);
1413
+ const input = useRef(null);
1414
+ const latestOnChange = useRef(onChange);
1415
+ latestOnChange.current = onChange;
1416
+ const registry = useMemo(() => createToolRegistry(imageTools, {
1417
+ ...props.tools ? { tools: props.tools } : {},
1418
+ toolbar: props.toolbar ?? DEFAULT_TOOLBAR.map((group) => group.filter((id) => !props.tools || props.tools.includes(id)))
1419
+ }), [props.tools, props.toolbar]);
1420
+ const platform = usePlatform();
1421
+ const shortcuts = useMemo(() => createShortcutRegistry({
1422
+ platform,
1423
+ tools: registry.tools
1424
+ }), [platform, registry]);
1425
+ const context = useMemo(() => ({
1426
+ session,
1427
+ view,
1428
+ editor,
1429
+ chooseFile: () => input.current?.click()
1430
+ }), [
1431
+ session,
1432
+ view,
1433
+ editor
1434
+ ]);
1435
+ const icons = useMemo(() => ({
1436
+ ...imageIcons,
1437
+ ...props.icons
1438
+ }), [props.icons]);
1439
+ useImperativeHandle(handle, () => ({
1440
+ session,
1441
+ open: (file) => opener.open(file),
1442
+ execute: (commands) => session.execute(commands),
1443
+ export: (format) => session.export(format),
1444
+ undo: () => {
1445
+ session.undo();
1446
+ },
1447
+ redo: () => {
1448
+ session.redo();
1449
+ }
1450
+ }), [session, opener]);
1451
+ const initial = useRef(initialFile);
1452
+ useEffect(() => {
1453
+ if (initial.current) opener.open(initial.current);
1454
+ }, [opener]);
1455
+ useEffect(() => {
1456
+ let before = session.getSnapshot().plan;
1457
+ return session.subscribe(() => {
1458
+ const after = session.getSnapshot().plan;
1459
+ if (after === before) return;
1460
+ before = after;
1461
+ if (after) latestOnChange.current?.(after);
1462
+ });
1463
+ }, [session]);
1464
+ useEffect(() => {
1465
+ events.current = (event) => {
1466
+ if (event.outcome !== "done") return;
1467
+ const action = event.commands[0];
1468
+ const name = action ? messages.t(`actions.${action}`) : "";
1469
+ if (event.type === "undo") announce(messages.t("editor.undid", { action: name }));
1470
+ if (event.type === "redo") announce(messages.t("editor.redid", { action: name }));
1471
+ if (event.type === "open") {
1472
+ const source = session.getSnapshot().source;
1473
+ if (source) announce(messages.t("editor.opened", {
1474
+ width: source.width,
1475
+ height: source.height
1476
+ }));
1477
+ }
1478
+ };
1479
+ return () => {
1480
+ events.current = void 0;
1481
+ };
1482
+ }, [
1483
+ announce,
1484
+ events,
1485
+ messages,
1486
+ session
1487
+ ]);
1488
+ const previous = useRef(snapshot.source?.id);
1489
+ useEffect(() => {
1490
+ const id = snapshot.source?.id;
1491
+ if (id === previous.current) return;
1492
+ previous.current = id;
1493
+ if (!id) return;
1494
+ const active = document.activeElement;
1495
+ if (!(active === null || active === document.body || root.current?.contains(active))) return;
1496
+ [...root.current?.querySelectorAll(".hm-image-editor-toolbar button:not([disabled])") ?? []].find((button) => button.dataset["tool"] !== "image.open")?.focus();
1497
+ }, [snapshot.source?.id]);
1498
+ const hostPlan = props.plan;
1499
+ const openSource = snapshot.plan?.base.source;
1500
+ useEffect(() => {
1501
+ if (!hostPlan || openSource !== hostPlan.base.source) return;
1502
+ try {
1503
+ session.applyPlan(hostPlan);
1504
+ } catch {}
1505
+ }, [
1506
+ hostPlan,
1507
+ session,
1508
+ openSource
1509
+ ]);
1510
+ const sourceId = snapshot.source?.id;
1511
+ useEffect(() => {
1512
+ if (sourceId === void 0) return;
1513
+ editor.set((state) => state.tool === null && state.dialog === null ? state : {
1514
+ ...state,
1515
+ tool: null,
1516
+ crop: null,
1517
+ dialog: null
1518
+ });
1519
+ }, [editor, sourceId]);
1520
+ const [{ tool }] = useImageEditorState();
1521
+ const returnTo = useRef(null);
1522
+ const previousTool = useRef(tool);
1523
+ useEffect(() => editor.subscribe(() => {
1524
+ if (editor.getSnapshot().tool === "crop" && previousTool.current !== "crop") {
1525
+ const active = document.activeElement;
1526
+ returnTo.current = active instanceof HTMLElement && root.current?.contains(active) ? active : null;
1527
+ }
1528
+ }), [editor]);
1529
+ useEffect(() => {
1530
+ if (previousTool.current === tool) return;
1531
+ const was = previousTool.current;
1532
+ previousTool.current = tool;
1533
+ if (was !== "crop") return;
1534
+ (returnTo.current?.isConnected ? returnTo.current : root.current?.querySelector("[data-tool=\"image.crop\"]"))?.focus();
1535
+ }, [tool]);
1536
+ const onKeyDown = (event) => {
1537
+ const id = shortcuts.match(event.nativeEvent, { root: event.currentTarget });
1538
+ const tool = id ? registry.get(id) : void 0;
1539
+ if (!tool) return;
1540
+ const state = {
1541
+ snapshot: session.getSnapshot(),
1542
+ editor: editor.getSnapshot()
1543
+ };
1544
+ if (!(tool.isEnabled?.(state) ?? true)) return;
1545
+ event.preventDefault();
1546
+ tool.run(context);
1547
+ };
1548
+ return /* @__PURE__ */ jsxs("section", {
1549
+ ref: root,
1550
+ className: join("hm-image-editor", !unstyled && "hm-image-editor--styled", props.className, classNames.root),
1551
+ onKeyDown,
1552
+ "aria-label": messages.t("editor.label"),
1553
+ children: [
1554
+ /* @__PURE__ */ jsx("input", {
1555
+ ref: input,
1556
+ type: "file",
1557
+ accept: "image/*",
1558
+ hidden: true,
1559
+ tabIndex: -1,
1560
+ onChange: (event) => {
1561
+ const file = event.currentTarget.files?.[0];
1562
+ event.currentTarget.value = "";
1563
+ if (file) opener.open(file);
1564
+ }
1565
+ }),
1566
+ /* @__PURE__ */ jsxs("div", {
1567
+ className: "hm-image-editor-layout",
1568
+ children: [
1569
+ /* @__PURE__ */ jsx(ImageToolbar, {
1570
+ registry,
1571
+ shortcuts,
1572
+ context,
1573
+ icons,
1574
+ className: join("hm-image-editor-toolbar", classNames.toolbar)
1575
+ }),
1576
+ /* @__PURE__ */ jsx(ImageStage, { className: join("hm-image-editor-stage", classNames.stage) }),
1577
+ /* @__PURE__ */ jsx("div", {
1578
+ className: join("hm-image-editor-inspector", classNames.inspector),
1579
+ children: /* @__PURE__ */ jsx(ImageInspector, {})
1580
+ })
1581
+ ]
1582
+ }),
1583
+ /* @__PURE__ */ jsx(ImageExportDialog, { ...props.onExport ? { onExport: props.onExport } : {} })
1584
+ ]
1585
+ });
1586
+ }
1587
+ var ImageEditor = forwardRef(function ImageEditor(props, ref) {
1588
+ const { initialFile, plan, onChange, tools, toolbar, icons, className, classNames, unstyled, onEvent, onExport, ...provider } = props;
1589
+ const events = useRef(void 0);
1590
+ const latestOnEvent = useRef(onEvent);
1591
+ latestOnEvent.current = onEvent;
1592
+ const [onSessionEvent] = useMemo(() => [(event) => {
1593
+ events.current?.(event);
1594
+ latestOnEvent.current?.(event);
1595
+ }], []);
1596
+ return /* @__PURE__ */ jsx(ImageEditorProvider, {
1597
+ ...provider,
1598
+ onEvent: onSessionEvent,
1599
+ children: /* @__PURE__ */ jsx(AnnouncerProvider, { children: /* @__PURE__ */ jsx(ImageEditorBody, {
1600
+ handle: ref,
1601
+ events,
1602
+ ...initialFile ? { initialFile } : {},
1603
+ ...onChange ? { onChange } : {},
1604
+ ...plan ? { plan } : {},
1605
+ ...tools ? { tools } : {},
1606
+ ...toolbar ? { toolbar } : {},
1607
+ ...icons ? { icons } : {},
1608
+ ...className ? { className } : {},
1609
+ ...classNames ? { classNames } : {},
1610
+ ...unstyled === void 0 ? {} : { unstyled },
1611
+ ...onExport ? { onExport } : {}
1612
+ }) })
1613
+ });
1614
+ });
1615
+ export { ImageFilterPanel as a, ImageExportDialog as c, useImageDocument as d, useImageEditorState as f, imageTools as g, useImageView as h, ImageStage as i, ExportListenerContext as l, useImageSession as m, imageIcons as n, ImageAdjustPanel as o, useImageMessages as p, ImageToolbar as r, ImageEditorProvider as s, ImageEditor as t, ImageCropPanel as u };
1616
+
1617
+ //# sourceMappingURL=editor-Dv5EU2YJ.js.map