@hussmartinez/image-sdk 0.0.0-stage → 0.2.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,1748 @@
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-CAX3GOaj.js";
2
+ import { applyCommands, createMessages, createShortcutRegistry, createStore, createToolRegistry, defineTool } from "@hussmartinez/sdk-core";
3
+ import { AnnouncerProvider, Button, CloseIcon, 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$1 = [
423
+ "title",
424
+ "description",
425
+ "artist",
426
+ "copyright"
427
+ ];
428
+ var KINDS$1 = [
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$1) 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$1.filter((kind) => source.metadata[kind]);
587
+ const kept = FIELDS$1.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: (control) => /* @__PURE__ */ jsxs("div", {
647
+ className: "hm-image-adjust-row",
648
+ children: [/* @__PURE__ */ jsx(Slider, {
649
+ ...control,
650
+ min: 1,
651
+ max: 100,
652
+ step: 1,
653
+ largeStep: 10,
654
+ value: current.quality,
655
+ formatValue: (quality) => messages.t("export.qualityValue", { quality }),
656
+ onValueChange: (quality) => update({ quality: Math.round(quality) })
657
+ }), /* @__PURE__ */ jsx("output", {
658
+ className: "hm-image-adjust-value",
659
+ "aria-hidden": "true",
660
+ children: messages.t("export.qualityValue", { quality: current.quality })
661
+ })]
662
+ })
663
+ }),
664
+ /* @__PURE__ */ jsx(SegmentedControl, {
665
+ label: messages.t("export.size"),
666
+ value: current.output.kind,
667
+ size: "small",
668
+ options: [{
669
+ value: "scale",
670
+ label: messages.t("export.sizes.scale")
671
+ }, {
672
+ value: "fit",
673
+ label: messages.t("export.sizes.fit")
674
+ }],
675
+ onValueChange: (kind) => update({ output: kind === "fit" ? {
676
+ kind: "fit",
677
+ width: composition.width,
678
+ height: composition.height
679
+ } : {
680
+ kind: "scale",
681
+ scale: 1
682
+ } })
683
+ }),
684
+ /* @__PURE__ */ jsx("div", {
685
+ className: "hm-image-export-fields",
686
+ children: current.output.kind === "scale" ? /* @__PURE__ */ jsx(Field, {
687
+ label: messages.t("export.scale"),
688
+ children: /* @__PURE__ */ jsx(NumberField, {
689
+ value: Math.round(current.output.scale * 100),
690
+ min: 1,
691
+ max: 100,
692
+ step: 1,
693
+ largeStep: 10,
694
+ onValueChange: (percent) => update({ output: {
695
+ kind: "scale",
696
+ scale: Math.round(percent) / 100
697
+ } })
698
+ })
699
+ }) : ["width", "height"].map((side) => {
700
+ const output = current.output;
701
+ return /* @__PURE__ */ jsx(Field, {
702
+ label: messages.t(side === "width" ? "export.fitWidth" : "export.fitHeight"),
703
+ children: /* @__PURE__ */ jsx(NumberField, {
704
+ value: output[side],
705
+ min: 1,
706
+ step: 1,
707
+ largeStep: 100,
708
+ onValueChange: (value) => update({ output: {
709
+ ...output,
710
+ [side]: Math.max(1, Math.round(value))
711
+ } })
712
+ })
713
+ }, side);
714
+ })
715
+ }),
716
+ /* @__PURE__ */ jsxs("fieldset", {
717
+ className: "hm-image-export-metadata",
718
+ children: [
719
+ /* @__PURE__ */ jsx("legend", { children: messages.t("export.fields") }),
720
+ /* @__PURE__ */ jsx("p", {
721
+ className: "hm-image-export-hint",
722
+ children: messages.t("export.fieldsHint")
723
+ }),
724
+ /* @__PURE__ */ jsx("div", {
725
+ className: "hm-image-export-fields",
726
+ children: FIELDS$1.map((field) => /* @__PURE__ */ jsx(Field, {
727
+ label: messages.t(`export.field.${field}`),
728
+ children: /* @__PURE__ */ jsx(TextField, {
729
+ autoComplete: "off",
730
+ value: current.metadata[field],
731
+ onValueChange: (value) => update({ metadata: {
732
+ ...current.metadata,
733
+ [field]: keepable(value)
734
+ } })
735
+ })
736
+ }, field))
737
+ })
738
+ ]
739
+ })
740
+ ]
741
+ }),
742
+ /* @__PURE__ */ jsxs("section", {
743
+ className: "hm-image-export-summary",
744
+ "aria-label": messages.t("export.summary"),
745
+ children: [
746
+ /* @__PURE__ */ jsx("p", { children: messages.t("export.output", {
747
+ width: size.width,
748
+ height: size.height,
749
+ format: formatName(current.format)
750
+ }) }),
751
+ 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") }),
752
+ 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
753
+ ]
754
+ }),
755
+ exporting ? /* @__PURE__ */ jsx(ProgressBar, {
756
+ label: messages.t("export.progress"),
757
+ value: Math.round(phase.progress * 100),
758
+ max: 100
759
+ }) : null,
760
+ error ? /* @__PURE__ */ jsx("p", {
761
+ className: "hm-image-export-error",
762
+ role: "alert",
763
+ children: messages.error(error)
764
+ }) : null
765
+ ] })
766
+ });
767
+ }
768
+ // src/features/editor-state.ts
769
+ var IDLE = Object.freeze({
770
+ tool: null,
771
+ crop: null,
772
+ preview: null,
773
+ dialog: null
774
+ });
775
+ function createEditorStore() {
776
+ return createStore(IDLE);
777
+ }
778
+ // src/react/view-store.ts
779
+ var FITTED = Object.freeze({
780
+ zoom: 1,
781
+ pan: Object.freeze({
782
+ x: 0,
783
+ y: 0
784
+ })
785
+ });
786
+ function createViewStore() {
787
+ return createStore(FITTED);
788
+ }
789
+ // src/react/ImageEditorProvider.tsx
790
+ function own(props) {
791
+ const engine = props.engine ?? createImageEngine(props.assetsUrl === void 0 ? {} : { assetsUrl: props.assetsUrl });
792
+ const processor = props.processor ?? createImageProcessor(engine);
793
+ const session = props.session ?? createImageSession({
794
+ engine,
795
+ processor,
796
+ ...props.filePolicy ? { filePolicy: props.filePolicy } : {},
797
+ ...props.onEvent ? { onEvent: props.onEvent } : {}
798
+ });
799
+ return {
800
+ engine,
801
+ session,
802
+ dispose() {
803
+ if (!props.session) session.destroy();
804
+ if (!props.processor) processor.destroy();
805
+ if (!props.engine) engine.destroy();
806
+ }
807
+ };
808
+ }
809
+ function ImageEditorProvider(props) {
810
+ const { messages: overrides, locale = "en", children } = props;
811
+ const [owned] = useState(() => own(props));
812
+ const [view] = useState(createViewStore);
813
+ const [editor] = useState(createEditorStore);
814
+ const [opener] = useState(() => createOpener(owned.session));
815
+ useEffect(() => {
816
+ if (owned.pending !== void 0) clearTimeout(owned.pending);
817
+ return () => {
818
+ owned.pending = setTimeout(() => owned.dispose(), 0);
819
+ };
820
+ }, [owned]);
821
+ const messages = useMemo(() => createMessages(imageMessages, {
822
+ locale,
823
+ ...overrides ? { overrides } : {}
824
+ }), [locale, overrides]);
825
+ const value = useMemo(() => ({
826
+ session: owned.session,
827
+ engine: owned.engine,
828
+ messages,
829
+ view,
830
+ editor,
831
+ opener
832
+ }), [
833
+ owned,
834
+ messages,
835
+ view,
836
+ editor,
837
+ opener
838
+ ]);
839
+ return /* @__PURE__ */ jsx(ImageContext.Provider, {
840
+ value,
841
+ children: /* @__PURE__ */ jsx(UiMessagesProvider, {
842
+ messages,
843
+ children
844
+ })
845
+ });
846
+ }
847
+ function useGesture() {
848
+ const { session, editor } = useImageInternals();
849
+ const gesture = useMemo(() => {
850
+ let pending;
851
+ let timer;
852
+ const reducer = createImageReducer((id) => {
853
+ const source = session.getSnapshot().source;
854
+ return source && source.id === id ? source : void 0;
855
+ });
856
+ const clearTimer = () => {
857
+ if (timer !== void 0) clearTimeout(timer);
858
+ timer = void 0;
859
+ };
860
+ const end = () => {
861
+ clearTimer();
862
+ pending = void 0;
863
+ editor.set((state) => state.preview === null ? state : {
864
+ ...state,
865
+ preview: null
866
+ });
867
+ };
868
+ const value = {
869
+ preview(commands) {
870
+ const plan = session.getSnapshot().plan;
871
+ if (!plan) return;
872
+ const preview = applyCommands(reducer, plan, commands).state;
873
+ pending = commands;
874
+ editor.set((state) => ({
875
+ ...state,
876
+ preview
877
+ }));
878
+ },
879
+ commit() {
880
+ const commands = pending;
881
+ end();
882
+ if (commands && commands.length > 0) session.execute(commands);
883
+ },
884
+ commitSoon() {
885
+ clearTimer();
886
+ timer = setTimeout(() => value.commit(), 500);
887
+ },
888
+ cancel: end,
889
+ active: () => pending !== void 0
890
+ };
891
+ return value;
892
+ }, [editor, session]);
893
+ useEffect(() => () => gesture.commit(), [gesture]);
894
+ return gesture;
895
+ }
896
+ // src/react/panels/use-slider-gesture.ts
897
+ function sliderGesture(gesture, command) {
898
+ return {
899
+ onValueChange: (value) => gesture.preview([command(value)]),
900
+ onPointerUp: (_event) => gesture.commit(),
901
+ onBlur: (_event) => gesture.commit(),
902
+ onKeyUp: (event) => {
903
+ if (event.key !== "Escape" && gesture.active()) gesture.commitSoon();
904
+ },
905
+ onKeyDown: (event) => {
906
+ if (event.key === "Escape" && gesture.active()) {
907
+ event.preventDefault();
908
+ event.stopPropagation();
909
+ gesture.cancel();
910
+ }
911
+ }
912
+ };
913
+ }
914
+ // src/react/panels/AdjustPanel.tsx
915
+ var signed = (value) => value > 0 ? `+${value}` : String(value);
916
+ function ImageAdjustPanel(props) {
917
+ const session = useImageSession();
918
+ const { plan } = useImageDocument();
919
+ const [editor] = useImageEditorState();
920
+ const messages = useImageMessages();
921
+ const gesture = useGesture();
922
+ const announce = useAnnounce();
923
+ const first = useRef(null);
924
+ if (!plan) return null;
925
+ const develop = (editor.preview ?? plan).base.develop;
926
+ const reset = (values) => {
927
+ gesture.cancel();
928
+ session.execute({
929
+ type: "image.setDevelop",
930
+ values
931
+ });
932
+ };
933
+ const changed = DEVELOP_ADJUSTMENTS.filter((name) => plan.base.develop[name] !== 0);
934
+ return /* @__PURE__ */ jsxs("section", {
935
+ className: ["hm-image-adjust-panel", props.className].filter(Boolean).join(" "),
936
+ "aria-label": messages.t("develop.panel"),
937
+ children: [/* @__PURE__ */ jsx("div", {
938
+ className: "hm-image-adjust-actions",
939
+ children: /* @__PURE__ */ jsx(Button, {
940
+ variant: "secondary",
941
+ disabled: changed.length === 0,
942
+ onClick: () => {
943
+ reset(Object.fromEntries(changed.map((name) => [name, 0])));
944
+ first.current?.focus();
945
+ announce(messages.t("develop.wasReset"));
946
+ },
947
+ children: messages.t("develop.resetAll")
948
+ })
949
+ }), DEVELOP_ADJUSTMENTS.map((name, index) => {
950
+ const label = messages.t(`develop.${name}`);
951
+ return /* @__PURE__ */ jsx(Field, {
952
+ label,
953
+ className: "hm-image-slider-field",
954
+ children: (control) => /* @__PURE__ */ jsxs("div", {
955
+ className: "hm-image-adjust-row",
956
+ children: [
957
+ /* @__PURE__ */ jsx(Slider, {
958
+ ...control,
959
+ ...index === 0 ? { ref: first } : {},
960
+ min: -100,
961
+ max: 100,
962
+ step: 1,
963
+ largeStep: 10,
964
+ value: develop[name],
965
+ formatValue: signed,
966
+ ...sliderGesture(gesture, (value) => ({
967
+ type: "image.setDevelop",
968
+ values: { [name]: Math.round(value) }
969
+ })),
970
+ onDoubleClick: () => {
971
+ if (plan.base.develop[name] !== 0) reset({ [name]: 0 });
972
+ }
973
+ }),
974
+ /* @__PURE__ */ jsx("output", {
975
+ className: "hm-image-adjust-value",
976
+ "aria-hidden": "true",
977
+ children: signed(develop[name])
978
+ }),
979
+ plan.base.develop[name] !== 0 ? /* @__PURE__ */ jsx(Button, {
980
+ variant: "quiet",
981
+ size: "small",
982
+ onClick: () => reset({ [name]: 0 }),
983
+ children: messages.t("develop.reset", { name: label })
984
+ }) : null
985
+ ]
986
+ })
987
+ }, name);
988
+ })]
989
+ });
990
+ }
991
+ // src/react/panels/FilterPanel.tsx
992
+ function ImageFilterPanel(props) {
993
+ const session = useImageSession();
994
+ const { plan } = useImageDocument();
995
+ const [editor] = useImageEditorState();
996
+ const messages = useImageMessages();
997
+ const gesture = useGesture();
998
+ if (!plan) return null;
999
+ const filter = (editor.preview ?? plan).base.filter;
1000
+ const options = [{
1001
+ value: "none",
1002
+ label: messages.t("filters.none")
1003
+ }, ...FILTER_PRESETS.map((preset) => ({
1004
+ value: preset,
1005
+ label: messages.t(`filters.${preset}`)
1006
+ }))];
1007
+ return /* @__PURE__ */ jsxs("section", {
1008
+ className: ["hm-image-filter-panel", props.className].filter(Boolean).join(" "),
1009
+ "aria-label": messages.t("filters.panel"),
1010
+ children: [/* @__PURE__ */ jsx(SegmentedControl, {
1011
+ label: messages.t("filters.label"),
1012
+ value: filter?.preset ?? "none",
1013
+ options,
1014
+ onValueChange: (value) => {
1015
+ gesture.cancel();
1016
+ session.execute({
1017
+ type: "image.setFilter",
1018
+ filter: value === "none" ? null : {
1019
+ preset: value,
1020
+ strength: filter?.strength ?? 100
1021
+ }
1022
+ });
1023
+ }
1024
+ }), filter ? /* @__PURE__ */ jsx(Field, {
1025
+ label: messages.t("filters.strength"),
1026
+ className: "hm-image-slider-field",
1027
+ children: /* @__PURE__ */ jsx(Slider, {
1028
+ min: 0,
1029
+ max: 100,
1030
+ step: 1,
1031
+ largeStep: 10,
1032
+ value: filter.strength,
1033
+ ...sliderGesture(gesture, (value) => ({
1034
+ type: "image.setFilter",
1035
+ filter: {
1036
+ preset: filter.preset,
1037
+ strength: Math.round(value)
1038
+ }
1039
+ }))
1040
+ })
1041
+ }) : null]
1042
+ });
1043
+ }
1044
+ // src/react/panels/InfoPanel.tsx
1045
+ var KINDS = [
1046
+ "location",
1047
+ "camera",
1048
+ "timestamps",
1049
+ "thumbnail",
1050
+ "colourProfile",
1051
+ "other"
1052
+ ];
1053
+ var FIELDS = [
1054
+ "title",
1055
+ "description",
1056
+ "artist",
1057
+ "copyright"
1058
+ ];
1059
+ function ImageInfoPanel(props) {
1060
+ const { plan, source } = useImageDocument();
1061
+ const messages = useImageMessages();
1062
+ if (!plan || !source) return null;
1063
+ const carried = KINDS.filter((kind) => source.metadata[kind]);
1064
+ const kept = FIELDS.filter((field) => plan.metadata[field] !== "");
1065
+ return /* @__PURE__ */ jsx("section", {
1066
+ className: ["hm-image-info-panel", props.className].filter(Boolean).join(" "),
1067
+ "aria-label": messages.t("info.panel"),
1068
+ children: /* @__PURE__ */ jsxs("dl", {
1069
+ className: "hm-image-info-list",
1070
+ children: [
1071
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.size") }),
1072
+ /* @__PURE__ */ jsx("dd", { children: messages.t("info.sizeValue", {
1073
+ width: source.width,
1074
+ height: source.height
1075
+ }) }),
1076
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.format") }),
1077
+ /* @__PURE__ */ jsx("dd", { children: messages.t(`info.formats.${source.format}`) }),
1078
+ source.frames > 1 ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("dt", { children: messages.t("info.frames") }), /* @__PURE__ */ jsx("dd", { children: source.frames })] }) : null,
1079
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.fileSize") }),
1080
+ /* @__PURE__ */ jsx("dd", { children: messages.t("info.fileSizeValue", { size: source.fileSize }) }),
1081
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.metadata") }),
1082
+ /* @__PURE__ */ jsx("dd", { children: carried.length > 0 ? /* @__PURE__ */ jsx("ul", { children: carried.map((kind) => /* @__PURE__ */ jsx("li", { children: messages.t(`export.kind.${kind}`) }, kind)) }) : messages.t("info.metadataNone") }),
1083
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.kept") }),
1084
+ /* @__PURE__ */ jsx("dd", { children: kept.length > 0 ? /* @__PURE__ */ jsx("ul", { children: kept.map((field) => /* @__PURE__ */ jsx("li", { children: messages.t(`export.field.${field}`) }, field)) }) : messages.t("info.keptNone") })
1085
+ ]
1086
+ })
1087
+ });
1088
+ }
1089
+ // src/react/panels/Inspector.tsx
1090
+ var PANELS = [
1091
+ "adjust",
1092
+ "filters",
1093
+ "info"
1094
+ ];
1095
+ function ImageInspector(props) {
1096
+ const { plan } = useImageDocument();
1097
+ const [editor] = useImageEditorState();
1098
+ const messages = useImageMessages();
1099
+ const [chosen, setPanel] = useState("adjust");
1100
+ if (editor.tool === "crop") return /* @__PURE__ */ jsx(ImageCropPanel, {});
1101
+ if (!plan) return null;
1102
+ const panels = PANELS.filter((name) => props.features?.[name] !== false);
1103
+ const first = panels[0];
1104
+ if (first === void 0) return null;
1105
+ const panel = panels.includes(chosen) ? chosen : first;
1106
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1107
+ panels.length > 1 ? /* @__PURE__ */ jsx(SegmentedControl, {
1108
+ label: messages.t("inspector.label"),
1109
+ value: panel,
1110
+ size: "small",
1111
+ options: panels.map((name) => ({
1112
+ value: name,
1113
+ label: messages.t(`inspector.${name}`)
1114
+ })),
1115
+ onValueChange: (value) => setPanel(value)
1116
+ }) : null,
1117
+ panel === "adjust" ? /* @__PURE__ */ jsx(ImageAdjustPanel, {}) : null,
1118
+ panel === "filters" ? /* @__PURE__ */ jsx(ImageFilterPanel, {}) : null,
1119
+ panel === "info" ? /* @__PURE__ */ jsx(ImageInfoPanel, {}) : null
1120
+ ] });
1121
+ }
1122
+ // src/react/crop/CropFrame.tsx
1123
+ var HANDLES = [
1124
+ "nw",
1125
+ "n",
1126
+ "ne",
1127
+ "e",
1128
+ "se",
1129
+ "s",
1130
+ "sw",
1131
+ "w"
1132
+ ];
1133
+ var ARROWS = /* @__PURE__ */ new Set([
1134
+ "ArrowLeft",
1135
+ "ArrowRight",
1136
+ "ArrowUp",
1137
+ "ArrowDown"
1138
+ ]);
1139
+ function CropFrame(props) {
1140
+ const { plan, source, view } = props;
1141
+ const [state] = useImageEditorState();
1142
+ const messages = useImageMessages();
1143
+ const actions = useCropActions();
1144
+ const frame = useRef(null);
1145
+ const describedBy = useId();
1146
+ const drag = useRef(void 0);
1147
+ useEffect(() => {
1148
+ frame.current?.focus();
1149
+ }, []);
1150
+ const crop = state.crop;
1151
+ if (!crop) return null;
1152
+ const { orientation } = plan.base;
1153
+ const whole = {
1154
+ ...plan,
1155
+ base: {
1156
+ ...plan.base,
1157
+ crop: null
1158
+ }
1159
+ };
1160
+ const placed = placement(compositionSize(whole, source), view);
1161
+ if (!(placed.scale > 0)) return null;
1162
+ const shown = cropInComposition(crop.pending, orientation, source);
1163
+ const ratio = aspectRatio(crop.aspect, source);
1164
+ const onKeyDown = (event) => {
1165
+ if (event.key === "Enter") {
1166
+ event.preventDefault();
1167
+ actions.apply();
1168
+ return;
1169
+ }
1170
+ if (event.key === "Escape") {
1171
+ event.preventDefault();
1172
+ if (drag.current) {
1173
+ actions.update(drag.current.start);
1174
+ drag.current = void 0;
1175
+ } else actions.cancel();
1176
+ return;
1177
+ }
1178
+ if (!ARROWS.has(event.key)) return;
1179
+ event.preventDefault();
1180
+ event.stopPropagation();
1181
+ actions.update(nudgeCropOnScreen(crop.pending, event.key, event.shiftKey ? 10 : 1, event.altKey, orientation, source, ratio));
1182
+ };
1183
+ const onPointerDown = (handle) => (event) => {
1184
+ if (event.button !== 0) return;
1185
+ event.preventDefault();
1186
+ event.stopPropagation();
1187
+ frame.current?.focus();
1188
+ try {
1189
+ event.currentTarget.setPointerCapture(event.pointerId);
1190
+ } catch {}
1191
+ drag.current = {
1192
+ pointer: event.pointerId,
1193
+ x: event.clientX,
1194
+ y: event.clientY,
1195
+ start: crop.pending,
1196
+ handle
1197
+ };
1198
+ };
1199
+ const onPointerMove = (event) => {
1200
+ const current = drag.current;
1201
+ if (!current || current.pointer !== event.pointerId) return;
1202
+ const moved = compositionDeltaToSource((event.clientX - current.x) / placed.scale, (event.clientY - current.y) / placed.scale, orientation, source);
1203
+ 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));
1204
+ };
1205
+ const onPointerEnd = (event) => {
1206
+ if (drag.current?.pointer !== event.pointerId) return;
1207
+ if (event.type === "pointercancel") actions.update(drag.current.start);
1208
+ drag.current = void 0;
1209
+ };
1210
+ const style = {
1211
+ left: `${placed.x + shown.x * placed.scale}px`,
1212
+ top: `${placed.y + shown.y * placed.scale}px`,
1213
+ width: `${shown.width * placed.scale}px`,
1214
+ height: `${shown.height * placed.scale}px`
1215
+ };
1216
+ const pointer = {
1217
+ onPointerMove,
1218
+ onPointerUp: onPointerEnd,
1219
+ onPointerCancel: onPointerEnd
1220
+ };
1221
+ return /* @__PURE__ */ jsxs("div", {
1222
+ ref: frame,
1223
+ className: "hm-image-crop-frame",
1224
+ role: "group",
1225
+ "aria-label": messages.t("crop.frame"),
1226
+ "aria-describedby": describedBy,
1227
+ tabIndex: 0,
1228
+ style,
1229
+ onKeyDown,
1230
+ onPointerDown: onPointerDown("move"),
1231
+ ...pointer,
1232
+ children: [/* @__PURE__ */ jsx("span", {
1233
+ id: describedBy,
1234
+ hidden: true,
1235
+ children: messages.t("crop.frameDescription", {
1236
+ width: crop.pending.width,
1237
+ height: crop.pending.height,
1238
+ x: crop.pending.x,
1239
+ y: crop.pending.y
1240
+ })
1241
+ }), HANDLES.map((handle) => /* @__PURE__ */ jsx("span", {
1242
+ className: "hm-image-crop-handle",
1243
+ "data-hm-handle": handle,
1244
+ "aria-hidden": "true",
1245
+ onPointerDown: onPointerDown(handle),
1246
+ ...pointer
1247
+ }, handle))]
1248
+ });
1249
+ }
1250
+ // src/react/stage/StageNotices.tsx
1251
+ function warningValues(limit, source) {
1252
+ if (limit === "maxFileSize") return { actual: source.fileSize };
1253
+ if (limit === "maxFrames") return { actual: source.frames };
1254
+ return {};
1255
+ }
1256
+ function StageNotices() {
1257
+ const { source, warnings, status } = useImageDocument();
1258
+ const messages = useImageMessages();
1259
+ const id = useId();
1260
+ const [dismissed, setDismissed] = useState(() => /* @__PURE__ */ new Set());
1261
+ if (!source || status !== "ready") return null;
1262
+ const t = messages.t;
1263
+ const notices = [];
1264
+ for (const limit of warnings) {
1265
+ if (limit === "maxSessionSize" || limit === "maxLayers") continue;
1266
+ notices.push({
1267
+ key: `${source.id}:${limit}`,
1268
+ text: t(`warnings.${limit}`, warningValues(limit, source))
1269
+ });
1270
+ }
1271
+ if (source.metadata.colourProfile) notices.push({
1272
+ key: `${source.id}:colourProfile`,
1273
+ text: messages.t("notices.colourProfile")
1274
+ });
1275
+ const shown = notices.filter((notice) => !dismissed.has(notice.key));
1276
+ return /* @__PURE__ */ jsx("div", {
1277
+ className: "hm-image-stage-notices",
1278
+ role: "status",
1279
+ "aria-label": messages.t("notices.label"),
1280
+ children: shown.length > 0 ? /* @__PURE__ */ jsx("ul", { children: shown.map((notice, index) => /* @__PURE__ */ jsxs("li", {
1281
+ className: "hm-image-stage-notice",
1282
+ children: [/* @__PURE__ */ jsx("span", {
1283
+ id: `${id}-${index}`,
1284
+ children: notice.text
1285
+ }), /* @__PURE__ */ jsx(IconButton, {
1286
+ label: messages.t("notices.dismiss"),
1287
+ "aria-describedby": `${id}-${index}`,
1288
+ icon: /* @__PURE__ */ jsx(CloseIcon, {}),
1289
+ size: "small",
1290
+ variant: "quiet",
1291
+ onClick: () => setDismissed((before) => new Set(before).add(notice.key))
1292
+ })]
1293
+ }, notice.key)) }) : null
1294
+ });
1295
+ }
1296
+ // src/react/stage/ImageStage.tsx
1297
+ var CROP_INSET = 24;
1298
+ function useStageSize(element) {
1299
+ const [size, setSize] = useState();
1300
+ useEffect(() => {
1301
+ if (!element) return;
1302
+ let ratioQuery;
1303
+ const measure = () => {
1304
+ const { width, height } = element.getBoundingClientRect();
1305
+ const pixelRatio = globalThis.devicePixelRatio || 1;
1306
+ setSize((current) => current?.width === width && current.height === height && current.pixelRatio === pixelRatio ? current : {
1307
+ width,
1308
+ height,
1309
+ pixelRatio
1310
+ });
1311
+ };
1312
+ const watchRatio = () => {
1313
+ ratioQuery?.removeEventListener("change", onRatio);
1314
+ ratioQuery = globalThis.matchMedia?.(`(resolution: ${globalThis.devicePixelRatio || 1}dppx)`);
1315
+ ratioQuery?.addEventListener("change", onRatio);
1316
+ };
1317
+ const onRatio = () => {
1318
+ measure();
1319
+ watchRatio();
1320
+ };
1321
+ const observer = new ResizeObserver(measure);
1322
+ observer.observe(element);
1323
+ measure();
1324
+ watchRatio();
1325
+ return () => {
1326
+ observer.disconnect();
1327
+ ratioQuery?.removeEventListener("change", onRatio);
1328
+ };
1329
+ }, [element]);
1330
+ return size;
1331
+ }
1332
+ function ImageStage(props) {
1333
+ const { engine, messages, opener } = useImageInternals();
1334
+ const snapshot = useImageDocument();
1335
+ const [view] = useImageView();
1336
+ const [frame, setFrame] = useState(null);
1337
+ const size = useStageSize(frame);
1338
+ const canvasRef = useRef(null);
1339
+ const rendererRef = useRef(void 0);
1340
+ const [editorState] = useImageEditorState();
1341
+ const { source, status } = snapshot;
1342
+ const cropping = editorState.tool === "crop";
1343
+ const inset = cropping ? CROP_INSET : 0;
1344
+ const plan = useMemo(() => {
1345
+ const committed = snapshot.plan;
1346
+ if (!committed) return null;
1347
+ if (cropping) return {
1348
+ ...committed,
1349
+ base: {
1350
+ ...committed.base,
1351
+ crop: null
1352
+ }
1353
+ };
1354
+ return editorState.preview ?? committed;
1355
+ }, [
1356
+ snapshot.plan,
1357
+ cropping,
1358
+ editorState.preview
1359
+ ]);
1360
+ useEffect(() => {
1361
+ if (!frame) return;
1362
+ const canvas = document.createElement("canvas");
1363
+ canvas.className = "hm-image-stage-canvas";
1364
+ canvas.setAttribute("role", "img");
1365
+ frame.append(canvas);
1366
+ canvasRef.current = canvas;
1367
+ const renderer = createImageRenderer(engine);
1368
+ const attached = renderer.attach(canvas);
1369
+ attached.catch(() => {});
1370
+ rendererRef.current = {
1371
+ renderer,
1372
+ attached
1373
+ };
1374
+ return () => {
1375
+ rendererRef.current = void 0;
1376
+ canvasRef.current = null;
1377
+ renderer.destroy();
1378
+ canvas.remove();
1379
+ };
1380
+ }, [engine, frame]);
1381
+ const composition = plan && source ? compositionSize(plan, source) : void 0;
1382
+ const shownWidth = composition?.width;
1383
+ const shownHeight = composition?.height;
1384
+ useEffect(() => {
1385
+ const canvas = frame ? canvasRef.current : null;
1386
+ if (!canvas) return;
1387
+ canvas.hidden = shownWidth === void 0 || shownHeight === void 0;
1388
+ if (shownWidth !== void 0 && shownHeight !== void 0) canvas.setAttribute("aria-label", messages.t("editor.preview", {
1389
+ width: shownWidth,
1390
+ height: shownHeight
1391
+ }));
1392
+ else canvas.removeAttribute("aria-label");
1393
+ }, [
1394
+ shownWidth,
1395
+ shownHeight,
1396
+ messages,
1397
+ frame
1398
+ ]);
1399
+ useEffect(() => {
1400
+ const current = rendererRef.current;
1401
+ if (!current || !plan || !size || size.width < 1 || size.height < 1) return;
1402
+ const { renderer, attached } = current;
1403
+ attached.then(() => renderer.render(plan, {
1404
+ width: size.width,
1405
+ height: size.height,
1406
+ pixelRatio: size.pixelRatio,
1407
+ zoom: view.zoom,
1408
+ pan: view.pan,
1409
+ inset
1410
+ })).catch(() => {});
1411
+ }, [
1412
+ plan,
1413
+ view,
1414
+ size,
1415
+ inset
1416
+ ]);
1417
+ const className = ["hm-image-stage", props.className].filter(Boolean).join(" ");
1418
+ const empty = status === "empty" && !snapshot.opening;
1419
+ const error = snapshot.error ? /* @__PURE__ */ jsx("p", {
1420
+ className: "hm-image-stage-error",
1421
+ role: "alert",
1422
+ children: messages.error(snapshot.error)
1423
+ }) : null;
1424
+ return /* @__PURE__ */ jsxs("div", {
1425
+ className,
1426
+ "data-status": status,
1427
+ children: [
1428
+ /* @__PURE__ */ jsx("div", {
1429
+ className: "hm-image-stage-frame",
1430
+ ref: setFrame
1431
+ }),
1432
+ cropping && snapshot.plan && source && size ? /* @__PURE__ */ jsx("div", {
1433
+ className: "hm-image-stage-overlay",
1434
+ children: /* @__PURE__ */ jsx(CropFrame, {
1435
+ plan: snapshot.plan,
1436
+ source,
1437
+ view: {
1438
+ width: size.width,
1439
+ height: size.height,
1440
+ pixelRatio: 1,
1441
+ zoom: view.zoom,
1442
+ pan: view.pan,
1443
+ inset
1444
+ }
1445
+ })
1446
+ }) : null,
1447
+ empty ? /* @__PURE__ */ jsxs(FileDropZone, {
1448
+ className: "hm-image-stage-drop",
1449
+ accept: "image/*",
1450
+ onFiles: (files) => {
1451
+ const [file] = files;
1452
+ if (file) opener.open(file);
1453
+ },
1454
+ buttonLabel: messages.t("editor.choose"),
1455
+ hint: messages.t("editor.dropHint"),
1456
+ children: [/* @__PURE__ */ jsx("p", {
1457
+ className: "hm-image-stage-empty",
1458
+ children: messages.t("editor.empty")
1459
+ }), error]
1460
+ }) : null,
1461
+ snapshot.opening ? /* @__PURE__ */ jsxs("div", {
1462
+ className: "hm-image-stage-opening",
1463
+ children: [/* @__PURE__ */ jsx(Spinner, { label: messages.t("editor.opening") }), /* @__PURE__ */ jsx(Button, {
1464
+ variant: "secondary",
1465
+ onClick: () => opener.cancel(),
1466
+ children: messages.t("editor.cancel")
1467
+ })]
1468
+ }) : null,
1469
+ empty ? null : /* @__PURE__ */ jsxs("div", {
1470
+ className: "hm-image-stage-foot",
1471
+ children: [/* @__PURE__ */ jsx(StageNotices, {}), error]
1472
+ })
1473
+ ]
1474
+ });
1475
+ }
1476
+ // src/react/toolbar/ImageToolbar.tsx
1477
+ function ImageToolbar(props) {
1478
+ const { registry, shortcuts, context, icons } = props;
1479
+ const messages = useImageMessages();
1480
+ const snapshot = useImageDocument();
1481
+ const [editor] = useImageEditorState();
1482
+ const state = {
1483
+ snapshot,
1484
+ editor
1485
+ };
1486
+ const t = messages.t;
1487
+ return /* @__PURE__ */ jsx(Toolbar, {
1488
+ label: messages.t("toolbar.label"),
1489
+ className: props.className,
1490
+ children: registry.toolbar.map((group) => /* @__PURE__ */ jsx(ToolbarGroup, {
1491
+ label: t(`toolbar.groups.${group[0]?.group ?? "other"}`),
1492
+ children: group.filter((tool) => tool.isAvailable?.(state) ?? true).map((tool) => {
1493
+ const Icon = icons[tool.icon];
1494
+ const keys = shortcuts?.ariaKeyShortcuts(tool.id);
1495
+ return /* @__PURE__ */ jsx(IconButton, {
1496
+ "data-tool": tool.id,
1497
+ label: t(tool.label),
1498
+ icon: Icon ? /* @__PURE__ */ jsx(Icon, {}) : null,
1499
+ disabled: !(tool.isEnabled?.(state) ?? true),
1500
+ ...tool.isActive ? { pressed: tool.isActive(state) } : {},
1501
+ ...keys ? { "aria-keyshortcuts": keys } : {},
1502
+ onClick: () => void tool.run(context)
1503
+ }, tool.id);
1504
+ })
1505
+ }, group.map((tool) => tool.id).join(" ")))
1506
+ });
1507
+ }
1508
+ // src/react/toolbar/icons.tsx
1509
+ var imageIcons = {
1510
+ open: OpenIcon,
1511
+ undo: UndoIcon,
1512
+ redo: RedoIcon,
1513
+ "rotate-left": RotateLeftIcon,
1514
+ "rotate-right": RotateRightIcon,
1515
+ "zoom-in": ZoomInIcon,
1516
+ "zoom-out": ZoomOutIcon,
1517
+ fit: FitIcon,
1518
+ crop: CropIcon,
1519
+ export: DownloadIcon,
1520
+ "flip-horizontal": FlipHorizontalIcon,
1521
+ "flip-vertical": FlipVerticalIcon,
1522
+ search: SearchIcon
1523
+ };
1524
+ // src/react/editor/ImageEditor.tsx
1525
+ var join = (...names) => names.filter(Boolean).join(" ");
1526
+ function ImageEditorBody(props) {
1527
+ const { initialFile, onChange, classNames = {}, unstyled = false, handle, events } = props;
1528
+ const { session, messages, view, editor, opener } = useImageInternals();
1529
+ const snapshot = useImageDocument();
1530
+ const announce = useAnnounce();
1531
+ const root = useRef(null);
1532
+ const input = useRef(null);
1533
+ const latestOnChange = useRef(onChange);
1534
+ latestOnChange.current = onChange;
1535
+ const exportOn = props.features?.export !== false;
1536
+ const registry = useMemo(() => {
1537
+ const wanted = (id) => (!props.tools || props.tools.includes(id)) && (exportOn || id !== "image.export");
1538
+ const tools = props.tools ?? imageTools.map((tool) => tool.id);
1539
+ return createToolRegistry(imageTools, {
1540
+ tools: tools.filter(wanted),
1541
+ toolbar: (props.toolbar ?? DEFAULT_TOOLBAR).map((group) => group.filter(wanted)).filter((group) => group.length > 0)
1542
+ });
1543
+ }, [
1544
+ props.tools,
1545
+ props.toolbar,
1546
+ exportOn
1547
+ ]);
1548
+ const platform = usePlatform();
1549
+ const shortcuts = useMemo(() => createShortcutRegistry({
1550
+ platform,
1551
+ tools: registry.tools
1552
+ }), [platform, registry]);
1553
+ const context = useMemo(() => ({
1554
+ session,
1555
+ view,
1556
+ editor,
1557
+ chooseFile: () => input.current?.click()
1558
+ }), [
1559
+ session,
1560
+ view,
1561
+ editor
1562
+ ]);
1563
+ const icons = useMemo(() => ({
1564
+ ...imageIcons,
1565
+ ...props.icons
1566
+ }), [props.icons]);
1567
+ useImperativeHandle(handle, () => ({
1568
+ session,
1569
+ open: (file) => opener.open(file),
1570
+ execute: (commands) => session.execute(commands),
1571
+ export: (format) => session.export(format),
1572
+ undo: () => {
1573
+ session.undo();
1574
+ },
1575
+ redo: () => {
1576
+ session.redo();
1577
+ }
1578
+ }), [session, opener]);
1579
+ const initial = useRef(initialFile);
1580
+ useEffect(() => {
1581
+ if (initial.current) opener.open(initial.current);
1582
+ }, [opener]);
1583
+ useEffect(() => {
1584
+ let before = session.getSnapshot().plan;
1585
+ return session.subscribe(() => {
1586
+ const after = session.getSnapshot().plan;
1587
+ if (after === before) return;
1588
+ before = after;
1589
+ if (after) latestOnChange.current?.(after);
1590
+ });
1591
+ }, [session]);
1592
+ useEffect(() => {
1593
+ events.current = (event) => {
1594
+ if (event.outcome !== "done") return;
1595
+ const action = event.commands[0];
1596
+ const name = action ? messages.t(`actions.${action}`) : "";
1597
+ if (event.type === "undo") announce(messages.t("editor.undid", { action: name }));
1598
+ if (event.type === "redo") announce(messages.t("editor.redid", { action: name }));
1599
+ if (event.type === "open") {
1600
+ const source = session.getSnapshot().source;
1601
+ if (source) announce(messages.t("editor.opened", {
1602
+ width: source.width,
1603
+ height: source.height
1604
+ }));
1605
+ }
1606
+ };
1607
+ return () => {
1608
+ events.current = void 0;
1609
+ };
1610
+ }, [
1611
+ announce,
1612
+ events,
1613
+ messages,
1614
+ session
1615
+ ]);
1616
+ const previous = useRef(snapshot.source?.id);
1617
+ useEffect(() => {
1618
+ const id = snapshot.source?.id;
1619
+ if (id === previous.current) return;
1620
+ previous.current = id;
1621
+ if (!id) return;
1622
+ const active = document.activeElement;
1623
+ if (!(active === null || active === document.body || root.current?.contains(active))) return;
1624
+ [...root.current?.querySelectorAll(".hm-image-editor-toolbar button:not([disabled])") ?? []].find((button) => button.dataset["tool"] !== "image.open")?.focus();
1625
+ }, [snapshot.source?.id]);
1626
+ const hostPlan = props.plan;
1627
+ const openSource = snapshot.plan?.base.source;
1628
+ useEffect(() => {
1629
+ if (!hostPlan || openSource !== hostPlan.base.source) return;
1630
+ try {
1631
+ session.applyPlan(hostPlan);
1632
+ } catch {}
1633
+ }, [
1634
+ hostPlan,
1635
+ session,
1636
+ openSource
1637
+ ]);
1638
+ const sourceId = snapshot.source?.id;
1639
+ useEffect(() => {
1640
+ if (sourceId === void 0) return;
1641
+ editor.set((state) => state.tool === null && state.dialog === null ? state : {
1642
+ ...state,
1643
+ tool: null,
1644
+ crop: null,
1645
+ dialog: null
1646
+ });
1647
+ }, [editor, sourceId]);
1648
+ const [{ tool }] = useImageEditorState();
1649
+ const returnTo = useRef(null);
1650
+ const previousTool = useRef(tool);
1651
+ useEffect(() => editor.subscribe(() => {
1652
+ if (editor.getSnapshot().tool === "crop" && previousTool.current !== "crop") {
1653
+ const active = document.activeElement;
1654
+ returnTo.current = active instanceof HTMLElement && root.current?.contains(active) ? active : null;
1655
+ }
1656
+ }), [editor]);
1657
+ useEffect(() => {
1658
+ if (previousTool.current === tool) return;
1659
+ const was = previousTool.current;
1660
+ previousTool.current = tool;
1661
+ if (was !== "crop") return;
1662
+ (returnTo.current?.isConnected ? returnTo.current : root.current?.querySelector("[data-tool=\"image.crop\"]"))?.focus();
1663
+ }, [tool]);
1664
+ const onKeyDown = (event) => {
1665
+ const id = shortcuts.match(event.nativeEvent, { root: event.currentTarget });
1666
+ const tool = id ? registry.get(id) : void 0;
1667
+ if (!tool) return;
1668
+ const state = {
1669
+ snapshot: session.getSnapshot(),
1670
+ editor: editor.getSnapshot()
1671
+ };
1672
+ if (!(tool.isEnabled?.(state) ?? true)) return;
1673
+ event.preventDefault();
1674
+ tool.run(context);
1675
+ };
1676
+ return /* @__PURE__ */ jsxs("section", {
1677
+ ref: root,
1678
+ className: join("hm-image-editor", !unstyled && "hm-image-editor--styled", props.className, classNames.root),
1679
+ onKeyDown,
1680
+ "aria-label": messages.t("editor.label"),
1681
+ ...props.theme ? { "data-hm-theme": props.theme } : {},
1682
+ children: [
1683
+ /* @__PURE__ */ jsx("input", {
1684
+ ref: input,
1685
+ type: "file",
1686
+ accept: "image/*",
1687
+ hidden: true,
1688
+ tabIndex: -1,
1689
+ onChange: (event) => {
1690
+ const file = event.currentTarget.files?.[0];
1691
+ event.currentTarget.value = "";
1692
+ if (file) opener.open(file);
1693
+ }
1694
+ }),
1695
+ /* @__PURE__ */ jsxs("div", {
1696
+ className: "hm-image-editor-layout",
1697
+ children: [
1698
+ /* @__PURE__ */ jsx(ImageToolbar, {
1699
+ registry,
1700
+ shortcuts,
1701
+ context,
1702
+ icons,
1703
+ className: join("hm-image-editor-toolbar", classNames.toolbar)
1704
+ }),
1705
+ /* @__PURE__ */ jsx(ImageStage, { className: join("hm-image-editor-stage", classNames.stage) }),
1706
+ /* @__PURE__ */ jsx("div", {
1707
+ className: join("hm-image-editor-inspector", classNames.inspector),
1708
+ children: /* @__PURE__ */ jsx(ImageInspector, { ...props.features ? { features: props.features } : {} })
1709
+ })
1710
+ ]
1711
+ }),
1712
+ exportOn ? /* @__PURE__ */ jsx(ImageExportDialog, { ...props.onExport ? { onExport: props.onExport } : {} }) : null
1713
+ ]
1714
+ });
1715
+ }
1716
+ var ImageEditor = forwardRef(function ImageEditor(props, ref) {
1717
+ const { initialFile, plan, onChange, tools, toolbar, icons, className, classNames, unstyled, onEvent, onExport, features, theme, ...provider } = props;
1718
+ const events = useRef(void 0);
1719
+ const latestOnEvent = useRef(onEvent);
1720
+ latestOnEvent.current = onEvent;
1721
+ const [onSessionEvent] = useMemo(() => [(event) => {
1722
+ events.current?.(event);
1723
+ latestOnEvent.current?.(event);
1724
+ }], []);
1725
+ return /* @__PURE__ */ jsx(ImageEditorProvider, {
1726
+ ...provider,
1727
+ onEvent: onSessionEvent,
1728
+ children: /* @__PURE__ */ jsx(AnnouncerProvider, { children: /* @__PURE__ */ jsx(ImageEditorBody, {
1729
+ handle: ref,
1730
+ events,
1731
+ ...initialFile ? { initialFile } : {},
1732
+ ...onChange ? { onChange } : {},
1733
+ ...plan ? { plan } : {},
1734
+ ...tools ? { tools } : {},
1735
+ ...toolbar ? { toolbar } : {},
1736
+ ...icons ? { icons } : {},
1737
+ ...className ? { className } : {},
1738
+ ...classNames ? { classNames } : {},
1739
+ ...unstyled === void 0 ? {} : { unstyled },
1740
+ ...onExport ? { onExport } : {},
1741
+ ...features ? { features } : {},
1742
+ ...theme ? { theme } : {}
1743
+ }) })
1744
+ });
1745
+ });
1746
+ export { imageTools as _, ImageInfoPanel as a, ImageEditorProvider as c, ImageCropPanel as d, useImageDocument as f, useImageView as g, useImageSession as h, ImageStage as i, ImageExportDialog as l, useImageMessages as m, imageIcons as n, ImageFilterPanel as o, useImageEditorState as p, ImageToolbar as r, ImageAdjustPanel as s, ImageEditor as t, ExportListenerContext as u };
1747
+
1748
+ //# sourceMappingURL=editor-DziYqEP3.js.map