@hussmartinez/image-sdk 0.2.0 → 0.4.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,3817 @@
1
+ import { A as compositionSize, C as cropInComposition, Ct as createImageProcessor, D as moveCrop, E as handleInSource, H as FORBIDDEN_IN_TEXT, M as cropRect, Mt as asImageError, O as nudgeCropOnScreen, P as outputSize, Pt as isImageError, Q as MAX_METADATA_LENGTH, S as compositionDeltaToSource, St as placement, T as fitAspect, Tt as engineInternals, V as createImageReducer, a as fitRedactionRegion, at as LAYER_FONTS, b as ASPECT_PRESETS, d as applyMatrix, et as longerThan, ft as MAX_SCENE_COORDINATE, g as layerToScene, h as layerToOutput, i as compositionRectToScene, it as LAYER_ALIGNMENTS, k as wholeCrop, n as createImageSession, nt as FILTER_PRESETS, p as invertMatrix, pt as MAX_STROKE_WIDTH, r as newLayerBox, t as imageMessages, tt as DEVELOP_ADJUSTMENTS, u as sceneRectToComposition, ut as MAX_LAYER_TEXT_LENGTH, v as sceneToOutput, vt as createImageRenderer, w as dragHandle, wt as createImageEngine, x as aspectRatio, y as createImageKey } from "./core-BlFeJWak.js";
2
+ import { applyCommands, createMessages, createShortcutRegistry, createStore, createToolRegistry, defineMessages, defineTool, plural } from "@hussmartinez/sdk-core";
3
+ import { AddIcon, AnnouncerProvider, Button, CloseIcon, ColorField, CropIcon, DeleteIcon, Dialog, DownloadIcon, DuplicateIcon, EllipseIcon, Field, FileDropZone, FitIcon, FlipHorizontalIcon, FlipVerticalIcon, HiddenIcon, IconButton, LayersIcon, MoveDownIcon, MoveUpIcon, NumberField, OpenIcon, ProgressBar, RectangleIcon, RedactIcon, RedoIcon, RotateLeftIcon, RotateRightIcon, SearchIcon, SegmentedControl, Slider, Spinner, TextArea, TextField, TextIcon, ToggleButton, Toolbar, ToolbarGroup, UiMessagesProvider, UndoIcon, VisibleIcon, 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
+ import { uiMessages } from "@hussmartinez/ui";
7
+ // src/features/tool-types.ts
8
+ var hasDocument = ({ snapshot }) => snapshot.plan !== null;
9
+ // src/features/crop/crop-tools.ts
10
+ function startCrop({ session, editor }) {
11
+ const { plan, source } = session.getSnapshot();
12
+ if (!plan || !source) return;
13
+ editor.set((state) => ({
14
+ ...state,
15
+ tool: "crop",
16
+ crop: {
17
+ pending: plan.base.crop ?? wholeCrop(source),
18
+ aspect: "free"
19
+ },
20
+ redact: null,
21
+ layers: null,
22
+ preview: null
23
+ }));
24
+ }
25
+ var cropTool = /* @__PURE__ */ defineTool({
26
+ id: "image.crop",
27
+ label: "tools.crop",
28
+ icon: "crop",
29
+ group: "crop",
30
+ isEnabled: hasDocument,
31
+ isActive: ({ editor }) => editor.tool === "crop",
32
+ run: (context) => {
33
+ if (context.editor.getSnapshot().tool === "crop") return;
34
+ startCrop(context);
35
+ },
36
+ shortcuts: ["C"]
37
+ });
38
+ function flip({ session }, axis) {
39
+ const plan = session.getSnapshot().plan;
40
+ if (!plan) return;
41
+ const orientation = {
42
+ ...plan.base.orientation,
43
+ [axis]: !plan.base.orientation[axis]
44
+ };
45
+ session.execute({
46
+ type: "image.setOrientation",
47
+ orientation
48
+ });
49
+ }
50
+ var flipHorizontalTool = /* @__PURE__ */ defineTool({
51
+ id: "image.flip-horizontal",
52
+ label: "tools.flip-horizontal",
53
+ icon: "flip-horizontal",
54
+ group: "orientation",
55
+ isEnabled: hasDocument,
56
+ run: (context) => flip(context, "flipX")
57
+ });
58
+ var flipVerticalTool = /* @__PURE__ */ defineTool({
59
+ id: "image.flip-vertical",
60
+ label: "tools.flip-vertical",
61
+ icon: "flip-vertical",
62
+ group: "orientation",
63
+ isEnabled: hasDocument,
64
+ run: (context) => flip(context, "flipY")
65
+ });
66
+ // src/features/export/export-tool.ts
67
+ var exportTool = /* @__PURE__ */ defineTool({
68
+ id: "image.export",
69
+ label: "tools.export",
70
+ icon: "export",
71
+ group: "export",
72
+ isEnabled: ({ snapshot, editor }) => snapshot.plan !== null && editor.tool === null,
73
+ run: ({ editor }) => editor.set((state) => ({
74
+ ...state,
75
+ dialog: "export"
76
+ }))
77
+ });
78
+ // src/features/history/history-tools.ts
79
+ var undoTool = /* @__PURE__ */ defineTool({
80
+ id: "image.undo",
81
+ label: "tools.undo",
82
+ icon: "undo",
83
+ group: "history",
84
+ isEnabled: ({ snapshot }) => snapshot.canUndo,
85
+ run: ({ session }) => {
86
+ session.undo();
87
+ },
88
+ shortcuts: "undo"
89
+ });
90
+ var redoTool = /* @__PURE__ */ defineTool({
91
+ id: "image.redo",
92
+ label: "tools.redo",
93
+ icon: "redo",
94
+ group: "history",
95
+ isEnabled: ({ snapshot }) => snapshot.canRedo,
96
+ run: ({ session }) => {
97
+ session.redo();
98
+ },
99
+ shortcuts: "redo"
100
+ });
101
+ // src/features/layers/new-layer.ts
102
+ var DEFAULT_TEXT_COLOUR = "#000000";
103
+ var DEFAULT_SHAPE_COLOUR = "#e02020";
104
+ var clamp$2 = (value, min, max) => Math.min(max, Math.max(min, value));
105
+ function newLayerKey(plan) {
106
+ return createImageKey(new Set([...plan.layers, ...plan.redactions].map((item) => item.key)));
107
+ }
108
+ var common = (plan) => ({
109
+ key: newLayerKey(plan),
110
+ name: "",
111
+ visible: true,
112
+ opacity: 100
113
+ });
114
+ function newTextLayer(plan, source) {
115
+ const { width, height } = compositionSize(plan, source);
116
+ return {
117
+ ...common(plan),
118
+ kind: "text",
119
+ text: "",
120
+ font: "sans-serif",
121
+ bold: false,
122
+ colour: DEFAULT_TEXT_COLOUR,
123
+ align: "center",
124
+ ...newLayerBox(plan, source, {
125
+ width: width / 2,
126
+ height: height / 5
127
+ })
128
+ };
129
+ }
130
+ function defaultStrokeWidth(plan, source) {
131
+ const { width, height } = compositionSize(plan, source);
132
+ return clamp$2(Math.round(Math.min(width, height) / 100), 2, MAX_STROKE_WIDTH);
133
+ }
134
+ function newShapeLayer(plan, source, shape) {
135
+ const { width, height } = compositionSize(plan, source);
136
+ const box = newLayerBox(plan, source, {
137
+ width: width / 4,
138
+ height: height / 4
139
+ });
140
+ return {
141
+ ...common(plan),
142
+ kind: "shape",
143
+ shape,
144
+ fill: null,
145
+ stroke: {
146
+ colour: DEFAULT_SHAPE_COLOUR,
147
+ width: Math.max(1, Math.min(defaultStrokeWidth(plan, source), Math.floor(Math.min(box.width, box.height) / 2)))
148
+ },
149
+ ...box
150
+ };
151
+ }
152
+ var insertOnTop = (plan, layer) => ({
153
+ type: "image.insertLayers",
154
+ at: plan.layers.length,
155
+ layers: [layer]
156
+ });
157
+ // src/features/layers/add-layer-tools.ts
158
+ function add({ session, editor }, create, edit = false) {
159
+ const { plan, source } = session.getSnapshot();
160
+ if (!plan || !source) return;
161
+ const layer = create(plan, source);
162
+ try {
163
+ session.execute(insertOnTop(plan, layer));
164
+ } catch (reason) {
165
+ const error = isImageError(reason) ? reason : asImageError(reason);
166
+ editor.set((state) => ({
167
+ ...state,
168
+ error
169
+ }));
170
+ return;
171
+ }
172
+ editor.set((state) => ({
173
+ ...state,
174
+ tool: "layers",
175
+ crop: null,
176
+ redact: null,
177
+ preview: null,
178
+ error: null,
179
+ layers: edit ? {
180
+ selected: layer.key,
181
+ focus: "text"
182
+ } : { selected: layer.key }
183
+ }));
184
+ }
185
+ var addTextTool = /* @__PURE__ */ defineTool({
186
+ id: "image.add-text",
187
+ label: "tools.add-text",
188
+ icon: "text",
189
+ group: "add",
190
+ isEnabled: hasDocument,
191
+ run: (context) => add(context, newTextLayer, true),
192
+ shortcuts: ["T"]
193
+ });
194
+ var addRectangleTool = /* @__PURE__ */ defineTool({
195
+ id: "image.add-rectangle",
196
+ label: "tools.add-rectangle",
197
+ icon: "rectangle",
198
+ group: "add",
199
+ isEnabled: hasDocument,
200
+ run: (context) => add(context, (plan, source) => newShapeLayer(plan, source, "rectangle"))
201
+ });
202
+ var addEllipseTool = /* @__PURE__ */ defineTool({
203
+ id: "image.add-ellipse",
204
+ label: "tools.add-ellipse",
205
+ icon: "ellipse",
206
+ group: "add",
207
+ isEnabled: hasDocument,
208
+ run: (context) => add(context, (plan, source) => newShapeLayer(plan, source, "ellipse"))
209
+ });
210
+ var addImageTool = /* @__PURE__ */ defineTool({
211
+ id: "image.add-image",
212
+ label: "tools.add-image",
213
+ icon: "add-image",
214
+ group: "add",
215
+ isEnabled: (state) => hasDocument(state) && !state.snapshot.inserting,
216
+ run: ({ chooseLayerImage }) => chooseLayerImage()
217
+ });
218
+ // src/features/layers/layers-tool.ts
219
+ var layersTool = /* @__PURE__ */ defineTool({
220
+ id: "image.layers",
221
+ label: "tools.layers",
222
+ icon: "layers",
223
+ group: "layers",
224
+ isEnabled: hasDocument,
225
+ isActive: ({ editor }) => editor.tool === "layers",
226
+ run: ({ editor, session }) => {
227
+ const top = session.getSnapshot().plan?.layers.at(-1)?.key ?? null;
228
+ editor.set((state) => state.tool === "layers" ? {
229
+ ...state,
230
+ tool: null,
231
+ layers: null,
232
+ preview: null
233
+ } : {
234
+ ...state,
235
+ tool: "layers",
236
+ crop: null,
237
+ redact: null,
238
+ preview: null,
239
+ layers: {
240
+ selected: top,
241
+ focus: "list"
242
+ }
243
+ });
244
+ },
245
+ shortcuts: ["L"]
246
+ });
247
+ // src/features/open/open-tool.ts
248
+ var openTool = /* @__PURE__ */ defineTool({
249
+ id: "image.open",
250
+ label: "tools.open",
251
+ icon: "open",
252
+ group: "file",
253
+ run: ({ chooseFile }) => chooseFile()
254
+ });
255
+ // src/features/orientation/orientation-tools.ts
256
+ function turned$1(orientation, direction) {
257
+ const mirrored = orientation.flipX !== orientation.flipY;
258
+ const clockwise = direction === "right" !== mirrored;
259
+ const rotate = (orientation.rotate + (clockwise ? 90 : 270)) % 360;
260
+ return {
261
+ ...orientation,
262
+ rotate
263
+ };
264
+ }
265
+ function turn({ session }, direction) {
266
+ const plan = session.getSnapshot().plan;
267
+ if (!plan) return;
268
+ session.execute({
269
+ type: "image.setOrientation",
270
+ orientation: turned$1(plan.base.orientation, direction)
271
+ });
272
+ }
273
+ var rotateLeftTool = /* @__PURE__ */ defineTool({
274
+ id: "image.rotate-left",
275
+ label: "tools.rotate-left",
276
+ icon: "rotate-left",
277
+ group: "orientation",
278
+ isEnabled: hasDocument,
279
+ run: (context) => turn(context, "left"),
280
+ shortcuts: ["["]
281
+ });
282
+ var rotateRightTool = /* @__PURE__ */ defineTool({
283
+ id: "image.rotate-right",
284
+ label: "tools.rotate-right",
285
+ icon: "rotate-right",
286
+ group: "orientation",
287
+ isEnabled: hasDocument,
288
+ run: (context) => turn(context, "right"),
289
+ shortcuts: ["]"]
290
+ });
291
+ // src/features/redact/redact-tool.ts
292
+ var DEFAULT_REDACTION_COLOUR = "#000000";
293
+ var redactTool = /* @__PURE__ */ defineTool({
294
+ id: "image.redact",
295
+ label: "tools.redact",
296
+ icon: "redact",
297
+ group: "redact",
298
+ isEnabled: hasDocument,
299
+ isActive: ({ editor }) => editor.tool === "redact",
300
+ run: ({ editor }) => {
301
+ editor.set((state) => state.tool === "redact" ? {
302
+ ...state,
303
+ tool: null,
304
+ redact: null,
305
+ preview: null
306
+ } : {
307
+ ...state,
308
+ tool: "redact",
309
+ crop: null,
310
+ layers: null,
311
+ preview: null,
312
+ redact: {
313
+ selected: null,
314
+ mode: "solid",
315
+ colour: DEFAULT_REDACTION_COLOUR
316
+ }
317
+ });
318
+ },
319
+ shortcuts: ["R"]
320
+ });
321
+ // src/features/zoom/zoom-tools.ts
322
+ var STEP = 1.25;
323
+ var clamp$1 = (zoom) => Math.min(16, Math.max(.1, zoom));
324
+ // src/features/tools.ts
325
+ var imageTools = [
326
+ openTool,
327
+ undoTool,
328
+ redoTool,
329
+ rotateLeftTool,
330
+ rotateRightTool,
331
+ flipHorizontalTool,
332
+ flipVerticalTool,
333
+ cropTool,
334
+ redactTool,
335
+ addTextTool,
336
+ addRectangleTool,
337
+ addEllipseTool,
338
+ addImageTool,
339
+ layersTool,
340
+ /* @__PURE__ */ defineTool({
341
+ id: "image.zoom-in",
342
+ label: "tools.zoom-in",
343
+ icon: "zoom-in",
344
+ group: "zoom",
345
+ isEnabled: hasDocument,
346
+ run: ({ view }) => view.set((v) => ({
347
+ ...v,
348
+ zoom: clamp$1(v.zoom * STEP)
349
+ })),
350
+ shortcuts: "zoom-in"
351
+ }),
352
+ /* @__PURE__ */ defineTool({
353
+ id: "image.zoom-out",
354
+ label: "tools.zoom-out",
355
+ icon: "zoom-out",
356
+ group: "zoom",
357
+ isEnabled: hasDocument,
358
+ run: ({ view }) => view.set((v) => ({
359
+ ...v,
360
+ zoom: clamp$1(v.zoom / STEP)
361
+ })),
362
+ shortcuts: "zoom-out"
363
+ }),
364
+ /* @__PURE__ */ defineTool({
365
+ id: "image.zoom-fit",
366
+ label: "tools.zoom-fit",
367
+ icon: "fit",
368
+ group: "zoom",
369
+ isEnabled: hasDocument,
370
+ run: ({ view }) => view.set({
371
+ zoom: 1,
372
+ pan: {
373
+ x: 0,
374
+ y: 0
375
+ }
376
+ }),
377
+ shortcuts: "zoom-reset"
378
+ }),
379
+ exportTool
380
+ ];
381
+ var DEFAULT_TOOLBAR = [
382
+ ["image.open"],
383
+ ["image.undo", "image.redo"],
384
+ [
385
+ "image.rotate-left",
386
+ "image.rotate-right",
387
+ "image.flip-horizontal",
388
+ "image.flip-vertical"
389
+ ],
390
+ ["image.crop"],
391
+ ["image.redact"],
392
+ [
393
+ "image.add-text",
394
+ "image.add-rectangle",
395
+ "image.add-ellipse",
396
+ "image.add-image"
397
+ ],
398
+ ["image.layers"],
399
+ [
400
+ "image.zoom-in",
401
+ "image.zoom-out",
402
+ "image.zoom-fit"
403
+ ],
404
+ ["image.export"]
405
+ ];
406
+ // src/react/context.ts
407
+ function createInserter(session, editor) {
408
+ let controller;
409
+ return {
410
+ async insert(file) {
411
+ controller?.abort();
412
+ const current = new AbortController();
413
+ controller = current;
414
+ try {
415
+ const image = await session.insertImage(file, { signal: current.signal });
416
+ const selected = [...session.getSnapshot().plan?.layers ?? []].reverse().find((layer) => layer.kind === "image" && layer.source === image.id)?.key ?? null;
417
+ editor.set((state) => ({
418
+ ...state,
419
+ tool: "layers",
420
+ crop: null,
421
+ redact: null,
422
+ preview: null,
423
+ error: null,
424
+ layers: { selected }
425
+ }));
426
+ } catch (reason) {
427
+ const error = isImageError(reason) ? reason : asImageError(reason);
428
+ if (error.code !== "ABORTED") editor.set((state) => ({
429
+ ...state,
430
+ error
431
+ }));
432
+ } finally {
433
+ if (controller === current) controller = void 0;
434
+ }
435
+ },
436
+ cancel() {
437
+ controller?.abort();
438
+ controller = void 0;
439
+ }
440
+ };
441
+ }
442
+ function createOpener(session) {
443
+ let controller;
444
+ return {
445
+ async open(file) {
446
+ controller?.abort();
447
+ const current = new AbortController();
448
+ controller = current;
449
+ try {
450
+ await session.open(file, { signal: current.signal });
451
+ } catch {} finally {
452
+ if (controller === current) controller = void 0;
453
+ }
454
+ },
455
+ cancel() {
456
+ controller?.abort();
457
+ controller = void 0;
458
+ }
459
+ };
460
+ }
461
+ var ImageContext = /* @__PURE__ */ createContext(void 0);
462
+ // src/react/hooks.ts
463
+ function useImageContext(hook) {
464
+ const value = useContext(ImageContext);
465
+ if (!value) throw new Error(`${hook}() must be used inside an ImageEditorProvider.`);
466
+ return value;
467
+ }
468
+ function useImageSession() {
469
+ return useImageContext("useImageSession").session;
470
+ }
471
+ function useImageDocument() {
472
+ const { session } = useImageContext("useImageDocument");
473
+ return useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot);
474
+ }
475
+ function useImageView() {
476
+ const { view } = useImageContext("useImageView");
477
+ return [useSyncExternalStore(view.subscribe, view.getSnapshot, view.getSnapshot), view];
478
+ }
479
+ function useImageEditorState() {
480
+ const { editor } = useImageContext("useImageEditorState");
481
+ return [useSyncExternalStore(editor.subscribe, editor.getSnapshot, editor.getSnapshot), editor];
482
+ }
483
+ function useImageMessages() {
484
+ return useImageContext("useImageMessages").messages;
485
+ }
486
+ function useImageInternals() {
487
+ return useImageContext("useImageInternals");
488
+ }
489
+ // src/react/crop/use-crop.ts
490
+ function useCropActions() {
491
+ const { session, editor, messages } = useImageInternals();
492
+ const announce = useAnnounce();
493
+ return useMemo(() => {
494
+ const pendingCrop = () => editor.getSnapshot().crop;
495
+ return {
496
+ update(crop) {
497
+ const current = pendingCrop();
498
+ if (!current) return;
499
+ editor.set((state) => ({
500
+ ...state,
501
+ crop: {
502
+ ...current,
503
+ pending: crop
504
+ }
505
+ }));
506
+ },
507
+ setAspect(aspect) {
508
+ const current = pendingCrop();
509
+ const source = session.getSnapshot().source;
510
+ if (!current || !source) return;
511
+ const pending = fitAspect(current.pending, aspectRatio(aspect, source));
512
+ editor.set((state) => ({
513
+ ...state,
514
+ crop: {
515
+ aspect,
516
+ pending
517
+ }
518
+ }));
519
+ },
520
+ apply() {
521
+ const current = pendingCrop();
522
+ const { plan, source } = session.getSnapshot();
523
+ editor.set((state) => ({
524
+ ...state,
525
+ tool: null,
526
+ crop: null
527
+ }));
528
+ if (!current || !plan || !source) return;
529
+ const whole = wholeCrop(source);
530
+ const crop = current.pending.x === 0 && current.pending.y === 0 && current.pending.width === whole.width && current.pending.height === whole.height ? null : current.pending;
531
+ if (JSON.stringify(crop) !== JSON.stringify(plan.base.crop)) session.execute({
532
+ type: "image.setCrop",
533
+ crop
534
+ });
535
+ announce(messages.t("crop.applied", {
536
+ width: current.pending.width,
537
+ height: current.pending.height
538
+ }));
539
+ },
540
+ cancel() {
541
+ editor.set((state) => ({
542
+ ...state,
543
+ tool: null,
544
+ crop: null
545
+ }));
546
+ }
547
+ };
548
+ }, [
549
+ announce,
550
+ editor,
551
+ messages,
552
+ session
553
+ ]);
554
+ }
555
+ // src/react/crop/CropPanel.tsx
556
+ var aspectKey = (aspect) => typeof aspect === "string" ? aspect : `${aspect[0]}:${aspect[1]}`;
557
+ function ImageCropPanel(props) {
558
+ const [state] = useImageEditorState();
559
+ const { source } = useImageDocument();
560
+ const messages = useImageMessages();
561
+ const actions = useCropActions();
562
+ const crop = state.crop;
563
+ if (state.tool !== "crop" || !crop || !source) return null;
564
+ const { pending } = crop;
565
+ const field = (name) => {
566
+ const max = name === "x" ? source.width - pending.width : name === "y" ? source.height - pending.height : name === "width" ? source.width - pending.x : source.height - pending.y;
567
+ return /* @__PURE__ */ jsx(Field, {
568
+ label: messages.t(`crop.${name}`),
569
+ children: /* @__PURE__ */ jsx(NumberField, {
570
+ value: pending[name],
571
+ min: name === "width" || name === "height" ? 1 : 0,
572
+ max,
573
+ step: 1,
574
+ largeStep: 10,
575
+ onValueChange: (value) => {
576
+ const next = {
577
+ ...pending,
578
+ [name]: Math.round(value)
579
+ };
580
+ actions.update(name === "x" || name === "y" ? moveCrop(next, 0, 0, source) : next);
581
+ }
582
+ })
583
+ }, name);
584
+ };
585
+ const options = ASPECT_PRESETS.map((aspect) => ({
586
+ value: aspectKey(aspect),
587
+ label: typeof aspect === "string" ? messages.t(`crop.aspects.${aspect}`) : messages.t("crop.aspects.ratio", {
588
+ width: aspect[0],
589
+ height: aspect[1]
590
+ })
591
+ }));
592
+ return /* @__PURE__ */ jsxs("section", {
593
+ className: ["hm-image-crop-panel", props.className].filter(Boolean).join(" "),
594
+ "aria-label": messages.t("crop.panel"),
595
+ children: [
596
+ /* @__PURE__ */ jsx("div", {
597
+ className: "hm-image-crop-fields",
598
+ children: [
599
+ "x",
600
+ "y",
601
+ "width",
602
+ "height"
603
+ ].map(field)
604
+ }),
605
+ /* @__PURE__ */ jsx(SegmentedControl, {
606
+ label: messages.t("crop.aspect"),
607
+ value: aspectKey(crop.aspect),
608
+ options,
609
+ size: "small",
610
+ onValueChange: (value) => {
611
+ const aspect = ASPECT_PRESETS.find((a) => aspectKey(a) === value);
612
+ if (aspect) actions.setAspect(aspect);
613
+ }
614
+ }),
615
+ /* @__PURE__ */ jsxs("div", {
616
+ className: "hm-image-crop-actions",
617
+ children: [
618
+ /* @__PURE__ */ jsx(Button, {
619
+ variant: "secondary",
620
+ onClick: () => actions.update(wholeCrop(source)),
621
+ children: messages.t("crop.reset")
622
+ }),
623
+ /* @__PURE__ */ jsx(Button, {
624
+ variant: "secondary",
625
+ onClick: () => actions.cancel(),
626
+ children: messages.t("crop.cancel")
627
+ }),
628
+ /* @__PURE__ */ jsx(Button, {
629
+ variant: "primary",
630
+ onClick: () => actions.apply(),
631
+ children: messages.t("crop.apply")
632
+ })
633
+ ]
634
+ })
635
+ ]
636
+ });
637
+ }
638
+ // src/react/EngineBoundary.tsx
639
+ var usable = () => false;
640
+ var unchanged = () => () => {};
641
+ function EngineBoundary({ children }) {
642
+ const { engine, messages } = useImageInternals();
643
+ const lifecycle = engineInternals(engine);
644
+ const surface = useRef(null);
645
+ const notice = useRef(null);
646
+ const ownedFocus = useRef(null);
647
+ const subscribe = useMemo(() => lifecycle ? (changed) => lifecycle.subscribe(() => {
648
+ const active = document.activeElement;
649
+ ownedFocus.current = active && surface.current?.contains(active) ? active : null;
650
+ changed();
651
+ }) : unchanged, [lifecycle]);
652
+ const terminal = useSyncExternalStore(subscribe, lifecycle?.getSnapshot ?? usable, usable);
653
+ useEffect(() => {
654
+ if (!terminal || !ownedFocus.current) return;
655
+ const active = document.activeElement;
656
+ if (active === document.body || active === ownedFocus.current) notice.current?.focus();
657
+ ownedFocus.current = null;
658
+ }, [terminal]);
659
+ return /* @__PURE__ */ jsx("div", {
660
+ ref: surface,
661
+ className: "hm-image-engine-boundary",
662
+ children: terminal ? /* @__PURE__ */ jsx("p", {
663
+ ref: notice,
664
+ role: "alert",
665
+ tabIndex: -1,
666
+ className: "hm-image-engine-unavailable",
667
+ children: messages.t("editor.engineUnavailable")
668
+ }) : children
669
+ });
670
+ }
671
+ // src/react/export/export-listener.ts
672
+ var ExportListenerContext = createContext(null);
673
+ // src/react/export/ExportDialog.tsx
674
+ var FORMATS = [
675
+ "png",
676
+ "jpeg",
677
+ "webp"
678
+ ];
679
+ var EXTENSIONS = {
680
+ png: "png",
681
+ jpeg: "jpg",
682
+ webp: "webp"
683
+ };
684
+ var FIELDS$1 = [
685
+ "title",
686
+ "description",
687
+ "artist",
688
+ "copyright"
689
+ ];
690
+ var KINDS$1 = [
691
+ "location",
692
+ "camera",
693
+ "timestamps",
694
+ "thumbnail",
695
+ "colourProfile",
696
+ "other"
697
+ ];
698
+ var DEFAULT_QUALITY = 92;
699
+ var keepable = (text) => longerThan(text, 2e3) ? [...text].slice(0, MAX_METADATA_LENGTH).join("") : text;
700
+ function initialDraft(plan, source) {
701
+ return {
702
+ format: FORMATS.includes(source.format) ? source.format : "png",
703
+ quality: DEFAULT_QUALITY,
704
+ output: plan.output,
705
+ metadata: plan.metadata
706
+ };
707
+ }
708
+ 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;
709
+ function changes(plan, draft) {
710
+ const commands = [];
711
+ if (!sameOutput(plan.output, draft.output)) commands.push({
712
+ type: "image.setOutput",
713
+ output: draft.output
714
+ });
715
+ for (const field of FIELDS$1) if (plan.metadata[field] !== draft.metadata[field]) commands.push({
716
+ type: "image.setMetadata",
717
+ field,
718
+ value: draft.metadata[field]
719
+ });
720
+ return commands;
721
+ }
722
+ var formatOf = (draft) => draft.format === "png" ? { type: "png" } : {
723
+ type: draft.format,
724
+ quality: draft.quality / 100
725
+ };
726
+ function ImageExportDialog(props) {
727
+ const { onExport, fileName = "image" } = props;
728
+ const lifecycle = engineInternals(useImageInternals().engine);
729
+ const session = useImageSession();
730
+ const { plan, source } = useImageDocument();
731
+ const [editor, editorStore] = useImageEditorState();
732
+ const messages = useImageMessages();
733
+ const announce = useAnnounce();
734
+ const listener = useContext(ExportListenerContext);
735
+ const [draft, setDraft] = useState(null);
736
+ const [phase, setPhase] = useState({ kind: "choose" });
737
+ const [error, setError] = useState(null);
738
+ const controller = useRef(null);
739
+ const objectUrl = useRef(null);
740
+ const downloadButton = useRef(null);
741
+ const open = editor.dialog === "export" && plan !== null && source !== null;
742
+ const current = draft ?? (plan && source ? initialDraft(plan, source) : null);
743
+ const revoke = () => {
744
+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
745
+ objectUrl.current = null;
746
+ };
747
+ useEffect(() => {
748
+ if (open) return;
749
+ const running = controller.current;
750
+ controller.current = null;
751
+ running?.abort();
752
+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
753
+ objectUrl.current = null;
754
+ setDraft(null);
755
+ setPhase((now) => now.kind === "choose" ? now : { kind: "choose" });
756
+ setError(null);
757
+ }, [open]);
758
+ useEffect(() => () => {
759
+ controller.current?.abort();
760
+ controller.current = null;
761
+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
762
+ }, []);
763
+ const done = phase.kind === "done";
764
+ useEffect(() => {
765
+ if (done) downloadButton.current?.focus();
766
+ }, [done]);
767
+ const close = () => {
768
+ editorStore.set((state) => state.dialog === null ? state : {
769
+ ...state,
770
+ dialog: null
771
+ });
772
+ };
773
+ if (!plan || !source || !current) return null;
774
+ const update = (patch) => setDraft({
775
+ ...current,
776
+ ...patch
777
+ });
778
+ const formatName = (format) => messages.t(`export.formats.${format}`);
779
+ const run = async () => {
780
+ setError(null);
781
+ try {
782
+ const commands = changes(plan, current);
783
+ if (commands.length > 0) session.execute(commands);
784
+ } catch (reason) {
785
+ setError(reason);
786
+ return;
787
+ }
788
+ const running = new AbortController();
789
+ controller.current = running;
790
+ setPhase({
791
+ kind: "exporting",
792
+ progress: 0
793
+ });
794
+ try {
795
+ const result = await session.export(formatOf(current), {
796
+ signal: running.signal,
797
+ onProgress: (progress) => setPhase((now) => now.kind === "exporting" ? {
798
+ kind: "exporting",
799
+ progress
800
+ } : now)
801
+ });
802
+ if (controller.current !== running || lifecycle?.getSnapshot()) return;
803
+ controller.current = null;
804
+ announce(messages.t("export.done", {
805
+ format: formatName(current.format),
806
+ size: result.blob.size
807
+ }));
808
+ listener?.({
809
+ format: current.format,
810
+ width: result.width,
811
+ height: result.height,
812
+ size: result.blob.size,
813
+ removed: result.removed,
814
+ kept: result.kept
815
+ });
816
+ if (onExport) {
817
+ onExport(result.blob, result);
818
+ close();
819
+ return;
820
+ }
821
+ setPhase({
822
+ kind: "done",
823
+ result,
824
+ format: current.format
825
+ });
826
+ } catch (reason) {
827
+ if (controller.current !== running || lifecycle?.getSnapshot()) return;
828
+ controller.current = null;
829
+ setPhase({ kind: "choose" });
830
+ if (isImageError(reason) && reason.code === "ABORTED") {
831
+ announce(messages.t("export.cancelled"));
832
+ return;
833
+ }
834
+ setError(reason);
835
+ }
836
+ };
837
+ const stop = () => controller.current?.abort();
838
+ const download = () => {
839
+ if (phase.kind !== "done" || lifecycle?.getSnapshot()) return;
840
+ revoke();
841
+ objectUrl.current = URL.createObjectURL(phase.result.blob);
842
+ const link = document.createElement("a");
843
+ link.href = objectUrl.current;
844
+ link.download = `${fileName}.${EXTENSIONS[phase.format]}`;
845
+ link.click();
846
+ };
847
+ const composition = compositionSize(plan, source);
848
+ const size = outputSize(current.output, composition);
849
+ const removed = KINDS$1.filter((kind) => source.metadata[kind]);
850
+ const kept = FIELDS$1.filter((field) => current.metadata[field] !== "");
851
+ const exporting = phase.kind === "exporting";
852
+ const footer = phase.kind === "done" ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
853
+ variant: "secondary",
854
+ onClick: close,
855
+ children: messages.t("export.close")
856
+ }), /* @__PURE__ */ jsx(Button, {
857
+ ref: downloadButton,
858
+ variant: "primary",
859
+ onClick: download,
860
+ children: messages.t("export.download")
861
+ })] }) : exporting ? /* @__PURE__ */ jsx(Button, {
862
+ variant: "secondary",
863
+ onClick: stop,
864
+ children: messages.t("export.stop")
865
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
866
+ variant: "secondary",
867
+ onClick: close,
868
+ children: messages.t("export.cancel")
869
+ }), /* @__PURE__ */ jsx(Button, {
870
+ variant: "primary",
871
+ onClick: () => void run(),
872
+ children: messages.t("export.confirm")
873
+ })] });
874
+ return /* @__PURE__ */ jsx(Dialog, {
875
+ open,
876
+ onOpenChange: (next) => {
877
+ if (!next) close();
878
+ },
879
+ title: messages.t("export.title"),
880
+ description: messages.t("export.description"),
881
+ footer,
882
+ className: ["hm-image-export", props.className].filter(Boolean).join(" "),
883
+ children: phase.kind === "done" ? /* @__PURE__ */ jsx("p", {
884
+ className: "hm-image-export-result",
885
+ children: messages.t("export.ready", {
886
+ width: phase.result.width,
887
+ height: phase.result.height,
888
+ format: formatName(phase.format),
889
+ size: phase.result.blob.size
890
+ })
891
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
892
+ /* @__PURE__ */ jsxs("fieldset", {
893
+ className: "hm-image-export-choices",
894
+ disabled: exporting,
895
+ children: [
896
+ /* @__PURE__ */ jsx(SegmentedControl, {
897
+ label: messages.t("export.format"),
898
+ value: current.format,
899
+ size: "small",
900
+ options: FORMATS.map((format) => ({
901
+ value: format,
902
+ label: formatName(format)
903
+ })),
904
+ onValueChange: (format) => update({ format })
905
+ }),
906
+ current.format === "png" ? null : /* @__PURE__ */ jsx(Field, {
907
+ label: messages.t("export.quality"),
908
+ className: "hm-image-slider-field",
909
+ children: (control) => /* @__PURE__ */ jsxs("div", {
910
+ className: "hm-image-adjust-row",
911
+ children: [/* @__PURE__ */ jsx(Slider, {
912
+ ...control,
913
+ min: 1,
914
+ max: 100,
915
+ step: 1,
916
+ largeStep: 10,
917
+ value: current.quality,
918
+ formatValue: (quality) => messages.t("export.qualityValue", { quality }),
919
+ onValueChange: (quality) => update({ quality: Math.round(quality) })
920
+ }), /* @__PURE__ */ jsx("output", {
921
+ className: "hm-image-adjust-value",
922
+ "aria-hidden": "true",
923
+ children: messages.t("export.qualityValue", { quality: current.quality })
924
+ })]
925
+ })
926
+ }),
927
+ /* @__PURE__ */ jsx(SegmentedControl, {
928
+ label: messages.t("export.size"),
929
+ value: current.output.kind,
930
+ size: "small",
931
+ options: [{
932
+ value: "scale",
933
+ label: messages.t("export.sizes.scale")
934
+ }, {
935
+ value: "fit",
936
+ label: messages.t("export.sizes.fit")
937
+ }],
938
+ onValueChange: (kind) => update({ output: kind === "fit" ? {
939
+ kind: "fit",
940
+ width: composition.width,
941
+ height: composition.height
942
+ } : {
943
+ kind: "scale",
944
+ scale: 1
945
+ } })
946
+ }),
947
+ /* @__PURE__ */ jsx("div", {
948
+ className: "hm-image-export-fields",
949
+ children: current.output.kind === "scale" ? /* @__PURE__ */ jsx(Field, {
950
+ label: messages.t("export.scale"),
951
+ children: /* @__PURE__ */ jsx(NumberField, {
952
+ value: Math.round(current.output.scale * 100),
953
+ min: 1,
954
+ max: 100,
955
+ step: 1,
956
+ largeStep: 10,
957
+ onValueChange: (percent) => update({ output: {
958
+ kind: "scale",
959
+ scale: Math.round(percent) / 100
960
+ } })
961
+ })
962
+ }) : ["width", "height"].map((side) => {
963
+ const output = current.output;
964
+ return /* @__PURE__ */ jsx(Field, {
965
+ label: messages.t(side === "width" ? "export.fitWidth" : "export.fitHeight"),
966
+ children: /* @__PURE__ */ jsx(NumberField, {
967
+ value: output[side],
968
+ min: 1,
969
+ step: 1,
970
+ largeStep: 100,
971
+ onValueChange: (value) => update({ output: {
972
+ ...output,
973
+ [side]: Math.max(1, Math.round(value))
974
+ } })
975
+ })
976
+ }, side);
977
+ })
978
+ }),
979
+ /* @__PURE__ */ jsxs("fieldset", {
980
+ className: "hm-image-export-metadata",
981
+ children: [
982
+ /* @__PURE__ */ jsx("legend", { children: messages.t("export.fields") }),
983
+ /* @__PURE__ */ jsx("p", {
984
+ className: "hm-image-export-hint",
985
+ children: messages.t("export.fieldsHint")
986
+ }),
987
+ /* @__PURE__ */ jsx("div", {
988
+ className: "hm-image-export-fields",
989
+ children: FIELDS$1.map((field) => /* @__PURE__ */ jsx(Field, {
990
+ label: messages.t(`export.field.${field}`),
991
+ children: /* @__PURE__ */ jsx(TextField, {
992
+ autoComplete: "off",
993
+ value: current.metadata[field],
994
+ onValueChange: (value) => update({ metadata: {
995
+ ...current.metadata,
996
+ [field]: keepable(value)
997
+ } })
998
+ })
999
+ }, field))
1000
+ })
1001
+ ]
1002
+ })
1003
+ ]
1004
+ }),
1005
+ /* @__PURE__ */ jsxs("section", {
1006
+ className: "hm-image-export-summary",
1007
+ "aria-label": messages.t("export.summary"),
1008
+ children: [
1009
+ /* @__PURE__ */ jsx("p", { children: messages.t("export.output", {
1010
+ width: size.width,
1011
+ height: size.height,
1012
+ format: formatName(current.format)
1013
+ }) }),
1014
+ plan.redactions.length > 0 ? /* @__PURE__ */ jsxs("p", { children: [messages.t("export.redacted", { count: plan.redactions.length }), plan.redactions.some((redaction) => redaction.mode === "pixelate") ? ` ${messages.t("export.redactedPixelated")}` : null] }) : null,
1015
+ 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") }),
1016
+ 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
1017
+ ]
1018
+ }),
1019
+ exporting ? /* @__PURE__ */ jsx(ProgressBar, {
1020
+ label: messages.t("export.progress"),
1021
+ value: Math.round(phase.progress * 100),
1022
+ max: 100
1023
+ }) : null,
1024
+ error ? /* @__PURE__ */ jsx("p", {
1025
+ className: "hm-image-export-error",
1026
+ role: "alert",
1027
+ children: messages.error(error)
1028
+ }) : null
1029
+ ] })
1030
+ });
1031
+ }
1032
+ // src/features/editor-state.ts
1033
+ var IDLE = Object.freeze({
1034
+ tool: null,
1035
+ crop: null,
1036
+ redact: null,
1037
+ layers: null,
1038
+ error: null,
1039
+ preview: null,
1040
+ dialog: null
1041
+ });
1042
+ function createEditorStore() {
1043
+ return createStore(IDLE);
1044
+ }
1045
+ // src/messages/editor-en.ts
1046
+ var imageEditorText = /* @__PURE__ */ defineMessages({
1047
+ "editor.engineUnavailable": "Image processing stopped. Reload this page or reopen the editor, then choose the image again. Unsaved edits will be lost unless your application has saved them.",
1048
+ "editor.label": "Image editor",
1049
+ "editor.preview": "Edited image preview, {width, number} × {height, number}",
1050
+ "editor.empty": "Open an image to start editing. It stays on this device.",
1051
+ "editor.choose": "Choose an image",
1052
+ "editor.dropHint": "or drop it here",
1053
+ "editor.opening": "Opening the image…",
1054
+ "editor.cancel": "Cancel",
1055
+ "editor.opened": "Image opened, {width, number} × {height, number}.",
1056
+ "editor.undid": "Undid {action}.",
1057
+ "editor.redid": "Redid {action}.",
1058
+ "actions.image.setCrop": "crop",
1059
+ "actions.image.setOrientation": "rotate or flip",
1060
+ "actions.image.setOutput": "size",
1061
+ "actions.image.setMetadata": "metadata",
1062
+ "actions.image.setDevelop": "adjustment",
1063
+ "actions.image.setFilter": "filter",
1064
+ "actions.image.insertLayers": "layer",
1065
+ "actions.image.removeLayers": "layer",
1066
+ "actions.image.restoreLayers": "layer",
1067
+ "actions.image.moveLayers": "layer order",
1068
+ "actions.image.setLayerOrder": "layer order",
1069
+ "actions.image.updateLayers": "layer change",
1070
+ "actions.image.insertRedactions": "redaction",
1071
+ "actions.image.removeRedactions": "redaction",
1072
+ "actions.image.restoreRedactions": "redaction",
1073
+ "actions.image.moveRedactions": "redaction order",
1074
+ "actions.image.setRedactionOrder": "redaction order",
1075
+ "actions.image.updateRedactions": "redaction change",
1076
+ "toolbar.label": "Image tools",
1077
+ "toolbar.groups.file": "File",
1078
+ "toolbar.groups.history": "History",
1079
+ "toolbar.groups.orientation": "Rotate",
1080
+ "toolbar.groups.zoom": "Zoom",
1081
+ "toolbar.groups.other": "More tools",
1082
+ "tools.open": "Open image",
1083
+ "tools.undo": "Undo",
1084
+ "tools.redo": "Redo",
1085
+ "tools.rotate-left": "Rotate left",
1086
+ "tools.rotate-right": "Rotate right",
1087
+ "tools.zoom-in": "Zoom in",
1088
+ "tools.zoom-out": "Zoom out",
1089
+ "tools.zoom-fit": "Fit to the stage",
1090
+ "tools.crop": "Crop",
1091
+ "tools.flip-horizontal": "Flip horizontally",
1092
+ "tools.flip-vertical": "Flip vertically",
1093
+ "toolbar.groups.crop": "Crop",
1094
+ "crop.frame": "Crop area",
1095
+ "crop.frameDescription": "{width, number} × {height, number} pixels, from {x, number}, {y, number}. Arrow keys move it; with Shift, they resize it; Enter applies and Escape cancels.",
1096
+ "crop.size": "{width, number} × {height, number}, from {x, number}, {y, number}",
1097
+ "crop.panel": "Crop",
1098
+ "crop.x": "Left",
1099
+ "crop.y": "Top",
1100
+ "crop.width": "Width",
1101
+ "crop.height": "Height",
1102
+ "crop.aspect": "Aspect ratio",
1103
+ "crop.aspects.free": "Free",
1104
+ "crop.aspects.original": "Original",
1105
+ "crop.aspects.ratio": "{width}:{height}",
1106
+ "crop.apply": "Apply crop",
1107
+ "crop.cancel": "Cancel",
1108
+ "crop.reset": "Whole image",
1109
+ "crop.applied": "Cropped to {width, number} × {height, number}.",
1110
+ "tools.redact": "Redact",
1111
+ "toolbar.groups.redact": "Redact",
1112
+ "redact.panel": "Redact",
1113
+ "redact.intro": "Cover parts of the image. Only the exported image is redacted: the original stays in the editor.",
1114
+ "redact.add": "Add area",
1115
+ "redact.done": "Done",
1116
+ "redact.mode": "Cover with",
1117
+ "redact.modes.solid": "Solid colour",
1118
+ "redact.modes.pixelate": "Pixelation",
1119
+ "redact.pixelateHint": "Pixelation may not hide text. For text and numbers, use a solid colour.",
1120
+ "redact.colour": "Colour",
1121
+ "redact.colours.black": "Black",
1122
+ "redact.colours.white": "White",
1123
+ "redact.x": "Left",
1124
+ "redact.y": "Top",
1125
+ "redact.width": "Width",
1126
+ "redact.height": "Height",
1127
+ "redact.areas": "Redacted areas",
1128
+ "redact.none": "No areas yet. Drag across the image, or add one.",
1129
+ "redact.area": "Area {index, number}: {mode}, {width, number} × {height, number}",
1130
+ "redact.modeNames.solid": "solid colour",
1131
+ "redact.modeNames.pixelate": "pixelated",
1132
+ "redact.remove": "Remove area {index, number}",
1133
+ "redact.frame": "Redacted area {index, number} of {count, number}",
1134
+ "redact.frameDescription": "{mode}, {width, number} × {height, number} pixels, from {x, number}, {y, number}. Arrow keys move it; with Shift, they resize it; Delete removes it and Escape ends redacting.",
1135
+ "redact.added": /* @__PURE__ */ plural("count", {
1136
+ one: "Area added. {count} area is redacted.",
1137
+ other: "Area added. {count, number} areas are redacted."
1138
+ }),
1139
+ "redact.removedLast": "Area removed. Nothing is redacted.",
1140
+ "redact.removed": /* @__PURE__ */ plural("count", {
1141
+ one: "Area removed. {count} area is redacted.",
1142
+ other: "Area removed. {count, number} areas are redacted."
1143
+ }),
1144
+ "tools.add-text": "Add text",
1145
+ "tools.add-rectangle": "Add a rectangle",
1146
+ "tools.add-ellipse": "Add an ellipse",
1147
+ "tools.add-image": "Add an image",
1148
+ "toolbar.groups.add": "Add",
1149
+ "editor.inserting": "Adding the image…",
1150
+ "layers.text": "Text",
1151
+ "layers.font": "Font",
1152
+ "layers.fonts.sans-serif": "Sans",
1153
+ "layers.fonts.serif": "Serif",
1154
+ "layers.fonts.monospace": "Mono",
1155
+ "layers.align": "Alignment",
1156
+ "layers.alignments.start": "Start",
1157
+ "layers.alignments.center": "Centre",
1158
+ "layers.alignments.end": "End",
1159
+ "layers.bold": "Bold",
1160
+ "layers.colour": "Colour",
1161
+ "layers.fill": "Fill",
1162
+ "layers.outline": "Outline",
1163
+ "layers.fillColour": "Fill colour",
1164
+ "layers.outlineColour": "Outline colour",
1165
+ "layers.outlineWidth": "Outline width",
1166
+ "layers.colours.black": "Black",
1167
+ "layers.colours.white": "White",
1168
+ "layers.colours.red": "Red",
1169
+ "layers.colours.yellow": "Yellow",
1170
+ "layers.colours.green": "Green",
1171
+ "layers.colours.blue": "Blue",
1172
+ "tools.layers": "Layers",
1173
+ "toolbar.groups.layers": "Layers",
1174
+ "layers.panel": "Layers",
1175
+ "layers.list": "Layers, the top one first",
1176
+ "layers.none": "No layers yet. Add text, a shape or an image from the toolbar.",
1177
+ "layers.kinds.text": "Text",
1178
+ "layers.kinds.rectangle": "Rectangle",
1179
+ "layers.kinds.ellipse": "Ellipse",
1180
+ "layers.kinds.image": "Image",
1181
+ "layers.visible": "Show {name}",
1182
+ "layers.selected": "Selected layer",
1183
+ "layers.moveUp": "Move up",
1184
+ "layers.moveDown": "Move down",
1185
+ "layers.mirror": "Mirror",
1186
+ "layers.duplicate": "Duplicate",
1187
+ "layers.remove": "Delete",
1188
+ "layers.name": "Name",
1189
+ "layers.x": "Left",
1190
+ "layers.y": "Top",
1191
+ "layers.width": "Width",
1192
+ "layers.height": "Height",
1193
+ "layers.rotation": "Turn, in degrees",
1194
+ "layers.opacity": "Opacity, in percent",
1195
+ "layers.done": "Done",
1196
+ "layers.frame": "Layer {index, number} of {count, number}: {name}",
1197
+ "layers.frameDescription": "{width, number} × {height, number} pixels, from {x, number}, {y, number}, turned {degrees, number}°. Arrow keys move it; with Shift, they resize it; Delete removes it and Escape closes the layers.",
1198
+ "layers.movedUp": "Moved {name} up. It's layer {index, number} of {count, number}.",
1199
+ "layers.movedDown": "Moved {name} down. It's layer {index, number} of {count, number}.",
1200
+ "layers.duplicated": "Duplicated {name}.",
1201
+ "layers.removed": "Deleted {name}.",
1202
+ "inspector.label": "Panels",
1203
+ "inspector.adjust": "Adjust",
1204
+ "inspector.filters": "Filters",
1205
+ "inspector.info": "Info",
1206
+ "notices.label": "Notices",
1207
+ "notices.dismiss": "Dismiss",
1208
+ "notices.colourProfile": "This image has a colour profile. Colours outside sRGB will be clipped in the exported file.",
1209
+ "info.panel": "Image info",
1210
+ "info.size": "Size",
1211
+ "info.sizeValue": "{width, number} × {height, number} pixels",
1212
+ "info.format": "Format",
1213
+ "info.formats.png": "PNG",
1214
+ "info.formats.jpeg": "JPEG",
1215
+ "info.formats.webp": "WebP",
1216
+ "info.formats.gif": "GIF",
1217
+ "info.formats.avif": "AVIF",
1218
+ "info.formats.heif": "HEIF",
1219
+ "info.formats.bmp": "BMP",
1220
+ "info.frames": "Frames",
1221
+ "info.fileSize": "File size",
1222
+ "info.fileSizeValue": "{size, fileSize}",
1223
+ "info.metadata": "Metadata in the file",
1224
+ "info.metadataNone": "None",
1225
+ "info.kept": "Kept on export",
1226
+ "info.keptNone": "Nothing",
1227
+ "develop.panel": "Adjust",
1228
+ "develop.temperature": "Temperature",
1229
+ "develop.tint": "Tint",
1230
+ "develop.exposure": "Exposure",
1231
+ "develop.highlights": "Highlights",
1232
+ "develop.shadows": "Shadows",
1233
+ "develop.contrast": "Contrast",
1234
+ "develop.saturation": "Saturation",
1235
+ "develop.vibrance": "Vibrance",
1236
+ "develop.reset": "Reset {name}",
1237
+ "develop.resetAll": "Reset all",
1238
+ "develop.wasReset": "All adjustments reset.",
1239
+ "filters.panel": "Filters",
1240
+ "filters.label": "Filter",
1241
+ "filters.none": "None",
1242
+ "filters.vivid": "Vivid",
1243
+ "filters.warm": "Warm",
1244
+ "filters.cool": "Cool",
1245
+ "filters.fade": "Fade",
1246
+ "filters.mono": "Mono",
1247
+ "filters.noir": "Noir",
1248
+ "filters.sepia": "Sepia",
1249
+ "filters.strength": "Strength",
1250
+ "toolbar.groups.export": "Export",
1251
+ "tools.export": "Export",
1252
+ "export.title": "Export image",
1253
+ "export.description": "The file is made on this device, and nothing is uploaded.",
1254
+ "export.format": "Format",
1255
+ "export.formats.png": "PNG",
1256
+ "export.formats.jpeg": "JPEG",
1257
+ "export.formats.webp": "WebP",
1258
+ "export.quality": "Quality",
1259
+ "export.qualityValue": "{quality, number}%",
1260
+ "export.size": "Size",
1261
+ "export.sizes.scale": "Scale",
1262
+ "export.sizes.fit": "Fit in a box",
1263
+ "export.scale": "Scale, in percent",
1264
+ "export.fitWidth": "Largest width",
1265
+ "export.fitHeight": "Largest height",
1266
+ "export.fields": "Details to include",
1267
+ "export.fieldsHint": "Only what you fill in is written to the file.",
1268
+ "export.field.title": "Title",
1269
+ "export.field.description": "Description",
1270
+ "export.field.artist": "Artist",
1271
+ "export.field.copyright": "Copyright",
1272
+ "export.summary": "Summary",
1273
+ "export.output": "{width, number} × {height, number} pixels, {format}",
1274
+ "export.removed": "Removed from the file",
1275
+ "export.removedNone": "The image had no other details to remove.",
1276
+ "export.redacted": /* @__PURE__ */ plural("count", {
1277
+ one: "{count} area is redacted.",
1278
+ other: "{count, number} areas are redacted."
1279
+ }),
1280
+ "export.redactedPixelated": "Pixelated areas may not hide text.",
1281
+ "export.kind.location": "Location",
1282
+ "export.kind.camera": "Camera details",
1283
+ "export.kind.timestamps": "Dates and times",
1284
+ "export.kind.thumbnail": "Embedded thumbnail",
1285
+ "export.kind.colourProfile": "Colour profile: colours outside sRGB are clipped",
1286
+ "export.kind.other": "Other metadata",
1287
+ "export.kept": "Kept in the file",
1288
+ "export.confirm": "Export",
1289
+ "export.cancel": "Cancel",
1290
+ "export.progress": "Exporting the image",
1291
+ "export.stop": "Stop exporting",
1292
+ "export.cancelled": "Export stopped.",
1293
+ "export.done": "Exported a {format} of {size, fileSize}.",
1294
+ "export.ready": "{width, number} × {height, number} pixels, {format}, {size, fileSize}",
1295
+ "export.download": "Download",
1296
+ "export.close": "Done"
1297
+ });
1298
+ // src/react/editor-messages.ts
1299
+ var imageEditorMessages = /* @__PURE__ */ defineMessages({
1300
+ ...imageMessages,
1301
+ ...uiMessages,
1302
+ ...imageEditorText
1303
+ });
1304
+ // src/react/view-store.ts
1305
+ var FITTED = Object.freeze({
1306
+ zoom: 1,
1307
+ pan: Object.freeze({
1308
+ x: 0,
1309
+ y: 0
1310
+ })
1311
+ });
1312
+ function createViewStore() {
1313
+ return createStore(FITTED);
1314
+ }
1315
+ // src/react/ImageEditorProvider.tsx
1316
+ function own(props) {
1317
+ const engine = props.engine ?? createImageEngine(props.assetsUrl === void 0 ? {} : { assetsUrl: props.assetsUrl });
1318
+ const processor = props.processor ?? createImageProcessor(engine);
1319
+ const session = props.session ?? createImageSession({
1320
+ engine,
1321
+ processor,
1322
+ ...props.filePolicy ? { filePolicy: props.filePolicy } : {},
1323
+ ...props.onEvent ? { onEvent: props.onEvent } : {}
1324
+ });
1325
+ return {
1326
+ engine,
1327
+ session,
1328
+ dispose() {
1329
+ if (!props.session) session.destroy();
1330
+ if (!props.processor) processor.destroy();
1331
+ if (!props.engine) engine.destroy();
1332
+ }
1333
+ };
1334
+ }
1335
+ function ImageEditorProvider(props) {
1336
+ return /* @__PURE__ */ jsx(ImageProvider, { ...props });
1337
+ }
1338
+ function ImageProvider(props) {
1339
+ const { messages: overrides, locale = "en", children } = props;
1340
+ const [owned] = useState(() => own(props));
1341
+ const [view] = useState(createViewStore);
1342
+ const [editor] = useState(createEditorStore);
1343
+ const [opener] = useState(() => createOpener(owned.session));
1344
+ const [inserter] = useState(() => createInserter(owned.session, editor));
1345
+ useEffect(() => {
1346
+ if (owned.pending !== void 0) clearTimeout(owned.pending);
1347
+ return () => {
1348
+ owned.pending = setTimeout(() => owned.dispose(), 0);
1349
+ };
1350
+ }, [owned]);
1351
+ const messages = useMemo(() => createMessages(imageEditorMessages, {
1352
+ locale,
1353
+ ...overrides ? { overrides } : {}
1354
+ }), [locale, overrides]);
1355
+ const value = useMemo(() => ({
1356
+ session: owned.session,
1357
+ engine: owned.engine,
1358
+ messages,
1359
+ view,
1360
+ editor,
1361
+ opener,
1362
+ inserter
1363
+ }), [
1364
+ owned,
1365
+ messages,
1366
+ view,
1367
+ editor,
1368
+ opener,
1369
+ inserter
1370
+ ]);
1371
+ return /* @__PURE__ */ jsx(ImageContext.Provider, {
1372
+ value,
1373
+ children: /* @__PURE__ */ jsx(UiMessagesProvider, {
1374
+ messages,
1375
+ children: props.boundary === false ? children : /* @__PURE__ */ jsx(EngineBoundary, { children })
1376
+ })
1377
+ });
1378
+ }
1379
+ function createGesture(session, editor) {
1380
+ let pending;
1381
+ let timer;
1382
+ const reducer = createImageReducer((id) => session.getSnapshot().sources.find((source) => source.id === id));
1383
+ const clearTimer = () => {
1384
+ if (timer !== void 0) clearTimeout(timer);
1385
+ timer = void 0;
1386
+ };
1387
+ const end = () => {
1388
+ clearTimer();
1389
+ pending = void 0;
1390
+ editor.set((state) => state.preview === null ? state : {
1391
+ ...state,
1392
+ preview: null
1393
+ });
1394
+ };
1395
+ const value = {
1396
+ preview(commands) {
1397
+ const plan = session.getSnapshot().plan;
1398
+ if (!plan) return;
1399
+ const preview = applyCommands(reducer, plan, commands).state;
1400
+ pending = commands;
1401
+ editor.set((state) => ({
1402
+ ...state,
1403
+ preview
1404
+ }));
1405
+ },
1406
+ commit() {
1407
+ const commands = pending;
1408
+ end();
1409
+ if (commands && commands.length > 0) session.execute(commands);
1410
+ },
1411
+ commitSoon() {
1412
+ clearTimer();
1413
+ timer = setTimeout(() => value.commit(), 500);
1414
+ },
1415
+ cancel: end,
1416
+ active: () => pending !== void 0
1417
+ };
1418
+ return value;
1419
+ }
1420
+ function useGesture() {
1421
+ const { session, editor } = useImageInternals();
1422
+ const gesture = useMemo(() => createGesture(session, editor), [editor, session]);
1423
+ useEffect(() => () => gesture.commit(), [gesture]);
1424
+ return gesture;
1425
+ }
1426
+ var shared = /* @__PURE__ */ new WeakMap();
1427
+ function useSharedGesture() {
1428
+ const { session, editor } = useImageInternals();
1429
+ const gesture = useMemo(() => {
1430
+ const existing = shared.get(editor);
1431
+ if (existing) return existing;
1432
+ const created = createGesture(session, editor);
1433
+ shared.set(editor, created);
1434
+ return created;
1435
+ }, [editor, session]);
1436
+ useEffect(() => () => gesture.commit(), [gesture]);
1437
+ return gesture;
1438
+ }
1439
+ // src/react/redact/use-redact.ts
1440
+ var keysOf = (plan) => new Set([...plan.layers, ...plan.redactions].map((item) => item.key));
1441
+ function newRedactionKey(plan) {
1442
+ return createImageKey(keysOf(plan));
1443
+ }
1444
+ function useRedactActions() {
1445
+ const { session, editor, messages } = useImageInternals();
1446
+ const announce = useAnnounce();
1447
+ const gesture = useSharedGesture();
1448
+ return useMemo(() => {
1449
+ const settings = () => editor.getSnapshot().redact ?? {
1450
+ selected: null,
1451
+ mode: "solid",
1452
+ colour: "#000000"
1453
+ };
1454
+ const set = (changes) => editor.set((state) => state.tool === "redact" ? {
1455
+ ...state,
1456
+ redact: {
1457
+ ...settings(),
1458
+ ...changes
1459
+ }
1460
+ } : state);
1461
+ const redaction = (key, region) => {
1462
+ const { mode, colour } = settings();
1463
+ const fitted = fitRedactionRegion(region);
1464
+ return mode === "solid" ? {
1465
+ key,
1466
+ mode,
1467
+ ...fitted,
1468
+ colour
1469
+ } : {
1470
+ key,
1471
+ mode,
1472
+ ...fitted
1473
+ };
1474
+ };
1475
+ const insert = (item, plan) => ({
1476
+ type: "image.insertRedactions",
1477
+ at: plan.redactions.length,
1478
+ redactions: [item]
1479
+ });
1480
+ const count = () => session.getSnapshot().plan?.redactions.length ?? 0;
1481
+ return {
1482
+ gesture,
1483
+ add() {
1484
+ const { plan, source } = session.getSnapshot();
1485
+ if (!plan || !source) return;
1486
+ gesture.commit();
1487
+ const { width, height } = compositionSize(plan, source);
1488
+ const shown = {
1489
+ x: Math.round(width * .375),
1490
+ y: Math.round(height * .375),
1491
+ width: Math.max(1, Math.round(width / 4)),
1492
+ height: Math.max(1, Math.round(height / 4))
1493
+ };
1494
+ const key = newRedactionKey(plan);
1495
+ const region = compositionRectToScene(shown, cropRect(plan.base.crop, source), plan.base.orientation);
1496
+ session.execute(insert(redaction(key, region), plan));
1497
+ set({ selected: key });
1498
+ announce(messages.t("redact.added", { count: count() }));
1499
+ },
1500
+ select(key) {
1501
+ if (settings().selected === key) return;
1502
+ gesture.commit();
1503
+ const item = session.getSnapshot().plan?.redactions.find((r) => r.key === key);
1504
+ set({
1505
+ selected: item ? key : null,
1506
+ ...item ? { mode: item.mode } : {},
1507
+ ...item?.mode === "solid" ? { colour: item.colour } : {}
1508
+ });
1509
+ },
1510
+ remove(key) {
1511
+ gesture.cancel();
1512
+ if (!session.getSnapshot().plan?.redactions.some((r) => r.key === key)) return;
1513
+ session.execute({
1514
+ type: "image.removeRedactions",
1515
+ keys: [key]
1516
+ });
1517
+ if (settings().selected === key) set({ selected: null });
1518
+ announce(count() === 0 ? messages.t("redact.removedLast") : messages.t("redact.removed", { count: count() }));
1519
+ },
1520
+ drawing(key, rect) {
1521
+ const { plan, source } = session.getSnapshot();
1522
+ if (!plan || !source) return;
1523
+ const region = compositionRectToScene(rect, cropRect(plan.base.crop, source), plan.base.orientation);
1524
+ gesture.preview([insert(redaction(key, region), plan)]);
1525
+ },
1526
+ moving(key, region) {
1527
+ gesture.preview([{
1528
+ type: "image.updateRedactions",
1529
+ updates: [{
1530
+ key,
1531
+ props: fitRedactionRegion(region)
1532
+ }]
1533
+ }]);
1534
+ },
1535
+ commit(soon = false) {
1536
+ if (soon) {
1537
+ gesture.commitSoon();
1538
+ return;
1539
+ }
1540
+ const drew = gesture.active() && count();
1541
+ gesture.commit();
1542
+ if (drew !== false && count() > drew) announce(messages.t("redact.added", { count: count() }));
1543
+ },
1544
+ cancel() {
1545
+ gesture.cancel();
1546
+ },
1547
+ setRegion(key, region) {
1548
+ gesture.commit();
1549
+ session.execute({
1550
+ type: "image.updateRedactions",
1551
+ updates: [{
1552
+ key,
1553
+ props: fitRedactionRegion(region)
1554
+ }]
1555
+ });
1556
+ },
1557
+ setMode(mode) {
1558
+ gesture.commit();
1559
+ const { selected, colour } = settings();
1560
+ const item = session.getSnapshot().plan?.redactions.find((r) => r.key === selected);
1561
+ if (item && item.mode !== mode) session.execute({
1562
+ type: "image.updateRedactions",
1563
+ updates: [{
1564
+ key: item.key,
1565
+ props: mode === "solid" ? {
1566
+ mode,
1567
+ colour
1568
+ } : { mode }
1569
+ }]
1570
+ });
1571
+ set({ mode });
1572
+ },
1573
+ setColour(colour) {
1574
+ gesture.commit();
1575
+ const item = session.getSnapshot().plan?.redactions.find((r) => r.key === settings().selected);
1576
+ if (item?.mode === "solid" && item.colour !== colour) session.execute({
1577
+ type: "image.updateRedactions",
1578
+ updates: [{
1579
+ key: item.key,
1580
+ props: { colour }
1581
+ }]
1582
+ });
1583
+ set({ colour });
1584
+ },
1585
+ done() {
1586
+ gesture.commit();
1587
+ editor.set((state) => state.tool === "redact" ? {
1588
+ ...state,
1589
+ tool: null,
1590
+ redact: null,
1591
+ preview: null
1592
+ } : state);
1593
+ }
1594
+ };
1595
+ }, [
1596
+ announce,
1597
+ editor,
1598
+ gesture,
1599
+ messages,
1600
+ session
1601
+ ]);
1602
+ }
1603
+ // src/react/layers/use-layers.ts
1604
+ var DUPLICATE_OFFSET = 8;
1605
+ var LABEL_LENGTH = 40;
1606
+ var EVERY_FORBIDDEN = new RegExp(FORBIDDEN_IN_TEXT.source, "gu");
1607
+ function layerLabel(layer, messages) {
1608
+ if (layer.name !== "") return layer.name;
1609
+ if (layer.kind === "text") {
1610
+ const line = layer.text.split("\n").find((text) => text.trim() !== "");
1611
+ if (line) return [...line.trim()].slice(0, LABEL_LENGTH).join("");
1612
+ }
1613
+ return messages.t(`layers.kinds.${layer.kind === "shape" ? layer.shape : layer.kind}`);
1614
+ }
1615
+ function fitLayerName(name) {
1616
+ return [...name.replace(EVERY_FORBIDDEN, "").trim()].slice(0, 100).join("");
1617
+ }
1618
+ function fitLayerText(text) {
1619
+ return [...text.replace(/\r\n?/g, "\n").replace(/\t/g, " ").replace(EVERY_FORBIDDEN, "")].slice(0, MAX_LAYER_TEXT_LENGTH).join("");
1620
+ }
1621
+ function useLayerActions() {
1622
+ const { session, editor, messages } = useImageInternals();
1623
+ const announce = useAnnounce();
1624
+ const gesture = useSharedGesture();
1625
+ return useMemo(() => {
1626
+ const layers = () => session.getSnapshot().plan?.layers ?? [];
1627
+ const select = (key) => editor.set((state) => state.tool === "layers" && state.layers?.selected !== key ? {
1628
+ ...state,
1629
+ layers: { selected: key }
1630
+ } : state);
1631
+ return {
1632
+ gesture,
1633
+ select(key) {
1634
+ if (editor.getSnapshot().layers?.selected === key) return;
1635
+ gesture.commit();
1636
+ select(key !== null && layers().some((layer) => layer.key === key) ? key : null);
1637
+ },
1638
+ remove(key) {
1639
+ gesture.cancel();
1640
+ const index = layers().findIndex((layer) => layer.key === key);
1641
+ const layer = layers()[index];
1642
+ if (!layer) return null;
1643
+ session.execute({
1644
+ type: "image.removeLayers",
1645
+ keys: [key]
1646
+ });
1647
+ const next = (layers()[index] ?? layers().at(-1))?.key ?? null;
1648
+ select(next);
1649
+ announce(messages.t("layers.removed", { name: layerLabel(layer, messages) }));
1650
+ return next;
1651
+ },
1652
+ duplicate(key) {
1653
+ gesture.commit();
1654
+ const plan = session.getSnapshot().plan;
1655
+ const index = layers().findIndex((layer) => layer.key === key);
1656
+ const layer = layers()[index];
1657
+ if (!plan || !layer) return;
1658
+ const copy = {
1659
+ ...layer,
1660
+ key: newRedactionKey(plan),
1661
+ x: Math.min(layer.x + DUPLICATE_OFFSET, MAX_SCENE_COORDINATE),
1662
+ y: Math.min(layer.y + DUPLICATE_OFFSET, MAX_SCENE_COORDINATE)
1663
+ };
1664
+ session.execute({
1665
+ type: "image.insertLayers",
1666
+ at: index + 1,
1667
+ layers: [copy]
1668
+ });
1669
+ select(copy.key);
1670
+ announce(messages.t("layers.duplicated", { name: layerLabel(layer, messages) }));
1671
+ },
1672
+ shift(key, by) {
1673
+ gesture.commit();
1674
+ const index = layers().findIndex((layer) => layer.key === key);
1675
+ const layer = layers()[index];
1676
+ const to = index + by;
1677
+ if (!layer || to < 0 || to >= layers().length) return;
1678
+ session.execute({
1679
+ type: "image.moveLayers",
1680
+ keys: [key],
1681
+ to
1682
+ });
1683
+ announce(messages.t(by > 0 ? "layers.movedUp" : "layers.movedDown", {
1684
+ name: layerLabel(layer, messages),
1685
+ index: layers().length - to,
1686
+ count: layers().length
1687
+ }));
1688
+ },
1689
+ moving(key, box) {
1690
+ const { x, y, width, height } = box;
1691
+ gesture.preview([{
1692
+ type: "image.updateLayers",
1693
+ updates: [{
1694
+ key,
1695
+ props: {
1696
+ x,
1697
+ y,
1698
+ width,
1699
+ height
1700
+ }
1701
+ }]
1702
+ }]);
1703
+ },
1704
+ commit(soon = false) {
1705
+ if (soon) gesture.commitSoon();
1706
+ else gesture.commit();
1707
+ },
1708
+ cancel() {
1709
+ gesture.cancel();
1710
+ },
1711
+ set(key, props) {
1712
+ gesture.commit();
1713
+ session.execute({
1714
+ type: "image.updateLayers",
1715
+ updates: [{
1716
+ key,
1717
+ props
1718
+ }]
1719
+ });
1720
+ },
1721
+ typing(key, props) {
1722
+ gesture.preview([{
1723
+ type: "image.updateLayers",
1724
+ updates: [{
1725
+ key,
1726
+ props
1727
+ }]
1728
+ }]);
1729
+ gesture.commitSoon();
1730
+ },
1731
+ done() {
1732
+ gesture.commit();
1733
+ editor.set((state) => state.tool === "layers" ? {
1734
+ ...state,
1735
+ tool: null,
1736
+ layers: null,
1737
+ preview: null
1738
+ } : state);
1739
+ }
1740
+ };
1741
+ }, [
1742
+ announce,
1743
+ editor,
1744
+ gesture,
1745
+ messages,
1746
+ session
1747
+ ]);
1748
+ }
1749
+ // src/react/layers/LayerFields.tsx
1750
+ var SWATCHES = [
1751
+ {
1752
+ value: "#000000",
1753
+ name: "black"
1754
+ },
1755
+ {
1756
+ value: "#ffffff",
1757
+ name: "white"
1758
+ },
1759
+ {
1760
+ value: "#e02020",
1761
+ name: "red"
1762
+ },
1763
+ {
1764
+ value: "#f0c020",
1765
+ name: "yellow"
1766
+ },
1767
+ {
1768
+ value: "#20a040",
1769
+ name: "green"
1770
+ },
1771
+ {
1772
+ value: "#2060e0",
1773
+ name: "blue"
1774
+ }
1775
+ ];
1776
+ function useSwatches() {
1777
+ const messages = useImageMessages();
1778
+ return SWATCHES.map(({ value, name }) => ({
1779
+ value,
1780
+ label: messages.t(`layers.colours.${name}`)
1781
+ }));
1782
+ }
1783
+ function TextLayerFields(props) {
1784
+ const { layer, actions, run } = props;
1785
+ const messages = useImageMessages();
1786
+ const swatches = useSwatches();
1787
+ const key = layer?.key ?? null;
1788
+ const text = layer?.text ?? "";
1789
+ const [value, setValue] = useState(text);
1790
+ useEffect(() => setValue(text), [key, text]);
1791
+ const off = layer === null;
1792
+ return /* @__PURE__ */ jsxs("div", {
1793
+ className: "hm-image-layer-kind",
1794
+ "data-hm-inactive": off ? "" : void 0,
1795
+ children: [
1796
+ /* @__PURE__ */ jsx(Field, {
1797
+ label: messages.t("layers.text"),
1798
+ className: "hm-image-layers-text",
1799
+ children: /* @__PURE__ */ jsx(TextArea, {
1800
+ rows: 3,
1801
+ value,
1802
+ disabled: off,
1803
+ onValueChange: (typed) => {
1804
+ const fitted = fitLayerText(typed);
1805
+ setValue(fitted);
1806
+ if (layer) run(() => actions.typing(layer.key, { text: fitted }));
1807
+ },
1808
+ onBlur: () => actions.commit()
1809
+ })
1810
+ }),
1811
+ /* @__PURE__ */ jsx(SegmentedControl, {
1812
+ label: messages.t("layers.font"),
1813
+ size: "small",
1814
+ value: layer?.font ?? "sans-serif",
1815
+ options: LAYER_FONTS.map((font) => ({
1816
+ value: font,
1817
+ label: messages.t(`layers.fonts.${font}`),
1818
+ disabled: off
1819
+ })),
1820
+ onValueChange: (font) => layer && run(() => actions.set(layer.key, { font }))
1821
+ }),
1822
+ /* @__PURE__ */ jsxs("div", {
1823
+ className: "hm-image-layer-row",
1824
+ children: [/* @__PURE__ */ jsx(SegmentedControl, {
1825
+ label: messages.t("layers.align"),
1826
+ size: "small",
1827
+ value: layer?.align ?? "center",
1828
+ options: LAYER_ALIGNMENTS.map((align) => ({
1829
+ value: align,
1830
+ label: messages.t(`layers.alignments.${align}`),
1831
+ disabled: off
1832
+ })),
1833
+ onValueChange: (align) => layer && run(() => actions.set(layer.key, { align }))
1834
+ }), /* @__PURE__ */ jsx(ToggleButton, {
1835
+ size: "small",
1836
+ pressed: layer?.bold ?? false,
1837
+ disabled: off,
1838
+ onPressedChange: (bold) => layer && run(() => actions.set(layer.key, { bold })),
1839
+ children: messages.t("layers.bold")
1840
+ })]
1841
+ }),
1842
+ /* @__PURE__ */ jsx(Field, {
1843
+ label: messages.t("layers.colour"),
1844
+ children: /* @__PURE__ */ jsx(ColorField, {
1845
+ value: layer?.colour ?? "#000000",
1846
+ swatches,
1847
+ disabled: off,
1848
+ onValueChange: (colour) => {
1849
+ if (layer && colour !== layer.colour) run(() => actions.set(layer.key, { colour }));
1850
+ }
1851
+ })
1852
+ })
1853
+ ]
1854
+ });
1855
+ }
1856
+ function ShapeLayerFields(props) {
1857
+ const { layer, actions, run } = props;
1858
+ const messages = useImageMessages();
1859
+ const session = useImageSession();
1860
+ const swatches = useSwatches();
1861
+ const off = layer === null;
1862
+ const fill = layer?.fill ?? null;
1863
+ const stroke = layer?.stroke ?? null;
1864
+ const outline = (colour) => {
1865
+ const { plan, source } = session.getSnapshot();
1866
+ const widest = layer ? Math.max(1, Math.floor(Math.min(layer.width, layer.height) / 2)) : 1;
1867
+ return {
1868
+ colour,
1869
+ width: plan && source ? Math.min(defaultStrokeWidth(plan, source), widest) : 1
1870
+ };
1871
+ };
1872
+ const set = (props) => {
1873
+ if (layer) run(() => actions.set(layer.key, props));
1874
+ };
1875
+ return /* @__PURE__ */ jsxs("div", {
1876
+ className: "hm-image-layer-kind",
1877
+ "data-hm-inactive": off ? "" : void 0,
1878
+ children: [
1879
+ /* @__PURE__ */ jsxs("div", {
1880
+ className: "hm-image-layer-row",
1881
+ children: [/* @__PURE__ */ jsx(ToggleButton, {
1882
+ size: "small",
1883
+ pressed: fill !== null,
1884
+ disabled: off,
1885
+ onPressedChange: (on) => {
1886
+ if (on) set({ fill: stroke?.colour ?? "#e02020" });
1887
+ else if (stroke) set({ fill: null });
1888
+ else set({
1889
+ fill: null,
1890
+ stroke: outline(fill ?? "#e02020")
1891
+ });
1892
+ },
1893
+ children: messages.t("layers.fill")
1894
+ }), /* @__PURE__ */ jsx(ToggleButton, {
1895
+ size: "small",
1896
+ pressed: stroke !== null,
1897
+ disabled: off,
1898
+ onPressedChange: (on) => {
1899
+ if (on) set({ stroke: outline(fill ?? "#e02020") });
1900
+ else if (fill !== null) set({ stroke: null });
1901
+ else set({
1902
+ stroke: null,
1903
+ fill: stroke?.colour ?? "#e02020"
1904
+ });
1905
+ },
1906
+ children: messages.t("layers.outline")
1907
+ })]
1908
+ }),
1909
+ /* @__PURE__ */ jsx(Field, {
1910
+ label: messages.t("layers.fillColour"),
1911
+ children: /* @__PURE__ */ jsx(ColorField, {
1912
+ value: fill ?? "#e02020",
1913
+ swatches,
1914
+ disabled: off || fill === null,
1915
+ onValueChange: (colour) => {
1916
+ if (fill !== null && colour !== fill) set({ fill: colour });
1917
+ }
1918
+ })
1919
+ }),
1920
+ /* @__PURE__ */ jsx(Field, {
1921
+ label: messages.t("layers.outlineColour"),
1922
+ children: /* @__PURE__ */ jsx(ColorField, {
1923
+ value: stroke?.colour ?? "#e02020",
1924
+ swatches,
1925
+ disabled: off || stroke === null,
1926
+ onValueChange: (colour) => {
1927
+ if (stroke && colour !== stroke.colour) set({ stroke: {
1928
+ ...stroke,
1929
+ colour
1930
+ } });
1931
+ }
1932
+ })
1933
+ }),
1934
+ /* @__PURE__ */ jsx(Field, {
1935
+ label: messages.t("layers.outlineWidth"),
1936
+ children: /* @__PURE__ */ jsx(NumberField, {
1937
+ value: stroke?.width ?? 1,
1938
+ min: 1,
1939
+ max: MAX_STROKE_WIDTH,
1940
+ step: 1,
1941
+ largeStep: 5,
1942
+ disabled: off || stroke === null,
1943
+ onValueChange: (width) => {
1944
+ if (stroke) set({ stroke: {
1945
+ ...stroke,
1946
+ width: Math.round(width)
1947
+ } });
1948
+ }
1949
+ })
1950
+ })
1951
+ ]
1952
+ });
1953
+ }
1954
+ // src/react/layers/LayersPanel.tsx
1955
+ function NameField(props) {
1956
+ const { layerKey, name, onRename } = props;
1957
+ const [value, setValue] = useState(name);
1958
+ useEffect(() => setValue(name), [layerKey, name]);
1959
+ return /* @__PURE__ */ jsx(TextField, {
1960
+ autoComplete: "off",
1961
+ value,
1962
+ placeholder: props.placeholder,
1963
+ disabled: layerKey === null,
1964
+ onValueChange: setValue,
1965
+ onBlur: () => {
1966
+ onRename(value);
1967
+ setValue(fitLayerName(value));
1968
+ },
1969
+ onKeyDown: (event) => {
1970
+ if (event.key === "Enter") onRename(event.currentTarget.value);
1971
+ }
1972
+ });
1973
+ }
1974
+ function ImageLayersPanel(props) {
1975
+ const [state, editor] = useImageEditorState();
1976
+ const { plan } = useImageDocument();
1977
+ const messages = useImageMessages();
1978
+ const actions = useLayerActions();
1979
+ const session = useImageSession();
1980
+ const list = useRef(null);
1981
+ const panel = useRef(null);
1982
+ const [problem, setProblem] = useState(null);
1983
+ const focusNext = useRef(null);
1984
+ useEffect(() => {
1985
+ const next = focusNext.current;
1986
+ if (!next) return;
1987
+ focusNext.current = null;
1988
+ const active = document.activeElement;
1989
+ if (active && active !== document.body && !list.current?.contains(active)) return;
1990
+ list.current?.querySelector(`[data-hm-layer="${CSS.escape(next.key)}"] ${next.visibility ? ".hm-image-layer-visibility" : ".hm-image-layer-select"}`)?.focus();
1991
+ });
1992
+ const focus = state.tool === "layers" ? state.layers?.focus : void 0;
1993
+ useEffect(() => {
1994
+ if (!focus) return;
1995
+ panel.current?.querySelector(focus === "text" ? ".hm-image-layers-text textarea" : ".hm-image-layers-list [aria-pressed=\"true\"], .hm-image-layers-list button")?.focus();
1996
+ editor.set((current) => current.layers?.focus ? {
1997
+ ...current,
1998
+ layers: { selected: current.layers.selected }
1999
+ } : current);
2000
+ }, [focus, editor]);
2001
+ if (state.tool !== "layers" || !state.layers || !plan) return null;
2002
+ const { layers } = plan;
2003
+ const selectedIndex = layers.findIndex((layer) => layer.key === state.layers?.selected);
2004
+ const selected = layers[selectedIndex];
2005
+ const count = layers.length;
2006
+ const run = (action) => {
2007
+ try {
2008
+ action();
2009
+ setProblem(null);
2010
+ } catch (error) {
2011
+ setProblem(error);
2012
+ }
2013
+ };
2014
+ const onListKeyDown = (event) => {
2015
+ const target = event.target instanceof HTMLElement ? event.target : null;
2016
+ const key = target?.closest("[data-hm-layer]")?.dataset["hmLayer"];
2017
+ if (key === void 0 || event.ctrlKey || event.metaKey || event.shiftKey) return;
2018
+ const visibility = target?.closest(".hm-image-layer-visibility") != null;
2019
+ if (event.altKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
2020
+ event.preventDefault();
2021
+ event.stopPropagation();
2022
+ actions.select(key);
2023
+ const by = event.key === "ArrowUp" ? 1 : -1;
2024
+ const to = layers.findIndex((layer) => layer.key === key) + by;
2025
+ if (to < 0 || to >= count) return;
2026
+ focusNext.current = {
2027
+ key,
2028
+ visibility
2029
+ };
2030
+ run(() => actions.shift(key, by));
2031
+ return;
2032
+ }
2033
+ if (!event.altKey && (event.key === "Delete" || event.key === "Backspace")) {
2034
+ event.preventDefault();
2035
+ event.stopPropagation();
2036
+ run(() => {
2037
+ const next = actions.remove(key);
2038
+ if (next !== null) focusNext.current = {
2039
+ key: next,
2040
+ visibility: false
2041
+ };
2042
+ else list.current?.closest(".hm-image-layers-panel")?.querySelector(".hm-image-layers-done")?.focus();
2043
+ });
2044
+ }
2045
+ };
2046
+ const boxField = (name) => {
2047
+ const length = name === "width" || name === "height";
2048
+ return /* @__PURE__ */ jsx(Field, {
2049
+ label: messages.t(`layers.${name}`),
2050
+ children: /* @__PURE__ */ jsx(NumberField, {
2051
+ value: selected ? selected[name] : length ? 1 : 0,
2052
+ min: length ? 1 : -MAX_SCENE_COORDINATE,
2053
+ max: MAX_SCENE_COORDINATE,
2054
+ step: 1,
2055
+ largeStep: 10,
2056
+ disabled: !selected,
2057
+ onValueChange: (value) => {
2058
+ if (selected) run(() => actions.set(selected.key, { [name]: Math.round(value) }));
2059
+ }
2060
+ })
2061
+ }, name);
2062
+ };
2063
+ const rename = (value) => {
2064
+ const current = session.getSnapshot().plan?.layers.find((layer) => layer.key === selected?.key);
2065
+ const name = fitLayerName(value);
2066
+ if (current && name !== current.name) run(() => actions.set(current.key, { name }));
2067
+ };
2068
+ return /* @__PURE__ */ jsxs("section", {
2069
+ ref: panel,
2070
+ className: ["hm-image-layers-panel", props.className].filter(Boolean).join(" "),
2071
+ "aria-label": messages.t("layers.panel"),
2072
+ children: [
2073
+ /* @__PURE__ */ jsx("section", {
2074
+ className: "hm-image-layers-list",
2075
+ "aria-label": messages.t("layers.list"),
2076
+ children: count === 0 ? /* @__PURE__ */ jsx("p", {
2077
+ className: "hm-image-layers-none",
2078
+ children: messages.t("layers.none")
2079
+ }) : /* @__PURE__ */ jsx("ul", {
2080
+ ref: list,
2081
+ onKeyDown: onListKeyDown,
2082
+ children: [...layers].reverse().map((layer) => {
2083
+ const name = layerLabel(layer, messages);
2084
+ return /* @__PURE__ */ jsxs("li", {
2085
+ "data-hm-layer": layer.key,
2086
+ children: [/* @__PURE__ */ jsx(Button, {
2087
+ variant: "secondary",
2088
+ className: "hm-image-layer-select",
2089
+ pressed: layer.key === selected?.key,
2090
+ "aria-keyshortcuts": "Alt+ArrowUp Alt+ArrowDown Delete",
2091
+ onClick: () => actions.select(layer.key),
2092
+ children: name
2093
+ }), /* @__PURE__ */ jsx(IconButton, {
2094
+ className: "hm-image-layer-visibility",
2095
+ label: messages.t("layers.visible", { name }),
2096
+ icon: layer.visible ? /* @__PURE__ */ jsx(VisibleIcon, {}) : /* @__PURE__ */ jsx(HiddenIcon, {}),
2097
+ pressed: layer.visible,
2098
+ onClick: () => run(() => actions.set(layer.key, { visible: !layer.visible }))
2099
+ })]
2100
+ }, layer.key);
2101
+ })
2102
+ })
2103
+ }),
2104
+ /* @__PURE__ */ jsxs("div", {
2105
+ className: "hm-image-layers-order",
2106
+ role: "group",
2107
+ "aria-label": messages.t("layers.selected"),
2108
+ children: [
2109
+ /* @__PURE__ */ jsx(IconButton, {
2110
+ label: messages.t("layers.moveUp"),
2111
+ icon: /* @__PURE__ */ jsx(MoveUpIcon, {}),
2112
+ disabled: !selected || selectedIndex === count - 1,
2113
+ focusableWhenDisabled: true,
2114
+ onClick: () => selected && run(() => actions.shift(selected.key, 1))
2115
+ }),
2116
+ /* @__PURE__ */ jsx(IconButton, {
2117
+ label: messages.t("layers.moveDown"),
2118
+ icon: /* @__PURE__ */ jsx(MoveDownIcon, {}),
2119
+ disabled: !selected || selectedIndex === 0,
2120
+ focusableWhenDisabled: true,
2121
+ onClick: () => selected && run(() => actions.shift(selected.key, -1))
2122
+ }),
2123
+ /* @__PURE__ */ jsx(IconButton, {
2124
+ label: messages.t("layers.mirror"),
2125
+ icon: /* @__PURE__ */ jsx(FlipHorizontalIcon, {}),
2126
+ pressed: selected?.flipX ?? false,
2127
+ disabled: !selected,
2128
+ focusableWhenDisabled: true,
2129
+ onClick: () => selected && run(() => actions.set(selected.key, { flipX: !selected.flipX }))
2130
+ }),
2131
+ /* @__PURE__ */ jsx(IconButton, {
2132
+ label: messages.t("layers.duplicate"),
2133
+ icon: /* @__PURE__ */ jsx(DuplicateIcon, {}),
2134
+ disabled: !selected,
2135
+ focusableWhenDisabled: true,
2136
+ onClick: () => selected && run(() => actions.duplicate(selected.key))
2137
+ }),
2138
+ /* @__PURE__ */ jsx(IconButton, {
2139
+ label: messages.t("layers.remove"),
2140
+ icon: /* @__PURE__ */ jsx(DeleteIcon, {}),
2141
+ disabled: !selected,
2142
+ focusableWhenDisabled: true,
2143
+ onClick: () => selected && run(() => void actions.remove(selected.key))
2144
+ })
2145
+ ]
2146
+ }),
2147
+ problem === null ? null : /* @__PURE__ */ jsx("p", {
2148
+ className: "hm-image-layers-problem",
2149
+ role: "alert",
2150
+ children: messages.error(problem)
2151
+ }),
2152
+ /* @__PURE__ */ jsxs("div", {
2153
+ className: "hm-image-layers-fields",
2154
+ "data-hm-inactive": selected ? void 0 : "",
2155
+ children: [
2156
+ /* @__PURE__ */ jsx(Field, {
2157
+ label: messages.t("layers.name"),
2158
+ className: "hm-image-layers-name",
2159
+ children: /* @__PURE__ */ jsx(NameField, {
2160
+ layerKey: selected?.key ?? null,
2161
+ name: selected?.name ?? "",
2162
+ placeholder: selected ? layerLabel({
2163
+ ...selected,
2164
+ name: ""
2165
+ }, messages) : "",
2166
+ onRename: rename
2167
+ })
2168
+ }),
2169
+ [
2170
+ "x",
2171
+ "y",
2172
+ "width",
2173
+ "height"
2174
+ ].map(boxField),
2175
+ /* @__PURE__ */ jsx(Field, {
2176
+ label: messages.t("layers.rotation"),
2177
+ children: /* @__PURE__ */ jsx(NumberField, {
2178
+ value: selected ? selected.rotation / 10 : 0,
2179
+ min: 0,
2180
+ max: 359.9,
2181
+ step: 1,
2182
+ largeStep: 15,
2183
+ disabled: !selected,
2184
+ onValueChange: (value) => {
2185
+ if (!selected) return;
2186
+ const rotation = (Math.round(value * 10) % 3600 + 3600) % 3600;
2187
+ run(() => actions.set(selected.key, { rotation }));
2188
+ }
2189
+ })
2190
+ }),
2191
+ /* @__PURE__ */ jsx(Field, {
2192
+ label: messages.t("layers.opacity"),
2193
+ children: /* @__PURE__ */ jsx(NumberField, {
2194
+ value: selected ? selected.opacity : 100,
2195
+ min: 0,
2196
+ max: 100,
2197
+ step: 1,
2198
+ largeStep: 10,
2199
+ disabled: !selected,
2200
+ onValueChange: (value) => {
2201
+ if (selected) run(() => actions.set(selected.key, { opacity: Math.round(value) }));
2202
+ }
2203
+ })
2204
+ })
2205
+ ]
2206
+ }),
2207
+ /* @__PURE__ */ jsxs("div", {
2208
+ className: "hm-image-layer-kinds",
2209
+ children: [/* @__PURE__ */ jsx(TextLayerFields, {
2210
+ layer: selected?.kind === "text" ? selected : null,
2211
+ actions,
2212
+ run
2213
+ }), /* @__PURE__ */ jsx(ShapeLayerFields, {
2214
+ layer: selected?.kind === "shape" ? selected : null,
2215
+ actions,
2216
+ run
2217
+ })]
2218
+ }),
2219
+ /* @__PURE__ */ jsx("div", {
2220
+ className: "hm-image-layers-actions",
2221
+ children: /* @__PURE__ */ jsx(Button, {
2222
+ variant: "primary",
2223
+ className: "hm-image-layers-done",
2224
+ onClick: () => actions.done(),
2225
+ children: messages.t("layers.done")
2226
+ })
2227
+ })
2228
+ ]
2229
+ });
2230
+ }
2231
+ // src/react/redact/RedactPanel.tsx
2232
+ var COLOURS = [{
2233
+ value: DEFAULT_REDACTION_COLOUR,
2234
+ name: "black"
2235
+ }, {
2236
+ value: "#ffffff",
2237
+ name: "white"
2238
+ }];
2239
+ function ImageRedactPanel(props) {
2240
+ const [state] = useImageEditorState();
2241
+ const { plan } = useImageDocument();
2242
+ const messages = useImageMessages();
2243
+ const actions = useRedactActions();
2244
+ const settings = state.redact;
2245
+ if (state.tool !== "redact" || !settings || !plan) return null;
2246
+ const { redactions } = plan;
2247
+ const selected = redactions.find((redaction) => redaction.key === settings.selected);
2248
+ const field = (name) => {
2249
+ const length = name === "width" || name === "height";
2250
+ return /* @__PURE__ */ jsx(Field, {
2251
+ label: messages.t(`redact.${name}`),
2252
+ children: /* @__PURE__ */ jsx(NumberField, {
2253
+ value: selected ? selected[name] : length ? 1 : 0,
2254
+ min: length ? 1 : -MAX_SCENE_COORDINATE,
2255
+ max: MAX_SCENE_COORDINATE,
2256
+ step: 1,
2257
+ largeStep: 10,
2258
+ disabled: !selected,
2259
+ onValueChange: (value) => {
2260
+ if (!selected) return;
2261
+ const { x, y, width, height } = selected;
2262
+ actions.setRegion(selected.key, {
2263
+ x,
2264
+ y,
2265
+ width,
2266
+ height,
2267
+ [name]: Math.round(value)
2268
+ });
2269
+ }
2270
+ })
2271
+ }, name);
2272
+ };
2273
+ const pixelating = settings.mode === "pixelate";
2274
+ return /* @__PURE__ */ jsxs("section", {
2275
+ className: ["hm-image-redact-panel", props.className].filter(Boolean).join(" "),
2276
+ "aria-label": messages.t("redact.panel"),
2277
+ children: [
2278
+ /* @__PURE__ */ jsx("p", {
2279
+ className: "hm-image-redact-intro",
2280
+ children: messages.t("redact.intro")
2281
+ }),
2282
+ /* @__PURE__ */ jsx(SegmentedControl, {
2283
+ label: messages.t("redact.mode"),
2284
+ value: settings.mode,
2285
+ size: "small",
2286
+ options: [{
2287
+ value: "solid",
2288
+ label: messages.t("redact.modes.solid")
2289
+ }, {
2290
+ value: "pixelate",
2291
+ label: messages.t("redact.modes.pixelate")
2292
+ }],
2293
+ onValueChange: (value) => actions.setMode(value === "pixelate" ? "pixelate" : "solid")
2294
+ }),
2295
+ /* @__PURE__ */ jsxs("div", {
2296
+ className: "hm-image-redact-cover",
2297
+ children: [/* @__PURE__ */ jsx("div", {
2298
+ "data-hm-inactive": pixelating ? "" : void 0,
2299
+ children: /* @__PURE__ */ jsx(SegmentedControl, {
2300
+ label: messages.t("redact.colour"),
2301
+ value: settings.colour,
2302
+ size: "small",
2303
+ options: COLOURS.map(({ value, name }) => ({
2304
+ value,
2305
+ label: messages.t(`redact.colours.${name}`)
2306
+ })),
2307
+ onValueChange: (value) => actions.setColour(value)
2308
+ })
2309
+ }), /* @__PURE__ */ jsx("p", {
2310
+ className: "hm-image-redact-hint",
2311
+ "data-hm-inactive": pixelating ? void 0 : "",
2312
+ children: messages.t("redact.pixelateHint")
2313
+ })]
2314
+ }),
2315
+ /* @__PURE__ */ jsx(Button, {
2316
+ variant: "secondary",
2317
+ className: "hm-image-redact-add",
2318
+ onClick: () => actions.add(),
2319
+ children: messages.t("redact.add")
2320
+ }),
2321
+ /* @__PURE__ */ jsx("div", {
2322
+ className: "hm-image-redact-fields",
2323
+ "data-hm-inactive": selected ? void 0 : "",
2324
+ children: [
2325
+ "x",
2326
+ "y",
2327
+ "width",
2328
+ "height"
2329
+ ].map(field)
2330
+ }),
2331
+ /* @__PURE__ */ jsx("section", {
2332
+ className: "hm-image-redact-areas",
2333
+ "aria-label": messages.t("redact.areas"),
2334
+ children: redactions.length === 0 ? /* @__PURE__ */ jsx("p", {
2335
+ className: "hm-image-redact-none",
2336
+ children: messages.t("redact.none")
2337
+ }) : /* @__PURE__ */ jsx("ul", { children: redactions.map((redaction, index) => /* @__PURE__ */ jsxs("li", { children: [/* @__PURE__ */ jsx(Button, {
2338
+ variant: "secondary",
2339
+ pressed: redaction.key === settings.selected,
2340
+ onClick: () => actions.select(redaction.key),
2341
+ children: messages.t("redact.area", {
2342
+ index: index + 1,
2343
+ mode: messages.t(`redact.modeNames.${redaction.mode}`),
2344
+ width: redaction.width,
2345
+ height: redaction.height
2346
+ })
2347
+ }), /* @__PURE__ */ jsx(IconButton, {
2348
+ label: messages.t("redact.remove", { index: index + 1 }),
2349
+ icon: /* @__PURE__ */ jsx(DeleteIcon, {}),
2350
+ onClick: () => actions.remove(redaction.key)
2351
+ })] }, redaction.key)) })
2352
+ }),
2353
+ /* @__PURE__ */ jsx("div", {
2354
+ className: "hm-image-redact-actions",
2355
+ children: /* @__PURE__ */ jsx(Button, {
2356
+ variant: "primary",
2357
+ onClick: () => actions.done(),
2358
+ children: messages.t("redact.done")
2359
+ })
2360
+ })
2361
+ ]
2362
+ });
2363
+ }
2364
+ // src/react/panels/use-slider-gesture.ts
2365
+ function sliderGesture(gesture, command) {
2366
+ return {
2367
+ onValueChange: (value) => gesture.preview([command(value)]),
2368
+ onPointerUp: (_event) => gesture.commit(),
2369
+ onBlur: (_event) => gesture.commit(),
2370
+ onKeyUp: (event) => {
2371
+ if (event.key !== "Escape" && gesture.active()) gesture.commitSoon();
2372
+ },
2373
+ onKeyDown: (event) => {
2374
+ if (event.key === "Escape" && gesture.active()) {
2375
+ event.preventDefault();
2376
+ event.stopPropagation();
2377
+ gesture.cancel();
2378
+ }
2379
+ }
2380
+ };
2381
+ }
2382
+ // src/react/panels/AdjustPanel.tsx
2383
+ var signed = (value) => value > 0 ? `+${value}` : String(value);
2384
+ function ImageAdjustPanel(props) {
2385
+ const session = useImageSession();
2386
+ const { plan } = useImageDocument();
2387
+ const [editor] = useImageEditorState();
2388
+ const messages = useImageMessages();
2389
+ const gesture = useGesture();
2390
+ const announce = useAnnounce();
2391
+ const first = useRef(null);
2392
+ if (!plan) return null;
2393
+ const develop = (editor.preview ?? plan).base.develop;
2394
+ const reset = (values) => {
2395
+ gesture.cancel();
2396
+ session.execute({
2397
+ type: "image.setDevelop",
2398
+ values
2399
+ });
2400
+ };
2401
+ const changed = DEVELOP_ADJUSTMENTS.filter((name) => plan.base.develop[name] !== 0);
2402
+ return /* @__PURE__ */ jsxs("section", {
2403
+ className: ["hm-image-adjust-panel", props.className].filter(Boolean).join(" "),
2404
+ "aria-label": messages.t("develop.panel"),
2405
+ children: [/* @__PURE__ */ jsx("div", {
2406
+ className: "hm-image-adjust-actions",
2407
+ children: /* @__PURE__ */ jsx(Button, {
2408
+ variant: "secondary",
2409
+ disabled: changed.length === 0,
2410
+ onClick: () => {
2411
+ reset(Object.fromEntries(changed.map((name) => [name, 0])));
2412
+ first.current?.focus();
2413
+ announce(messages.t("develop.wasReset"));
2414
+ },
2415
+ children: messages.t("develop.resetAll")
2416
+ })
2417
+ }), DEVELOP_ADJUSTMENTS.map((name, index) => {
2418
+ const label = messages.t(`develop.${name}`);
2419
+ return /* @__PURE__ */ jsx(Field, {
2420
+ label,
2421
+ className: "hm-image-slider-field",
2422
+ children: (control) => /* @__PURE__ */ jsxs("div", {
2423
+ className: "hm-image-adjust-row",
2424
+ children: [
2425
+ /* @__PURE__ */ jsx(Slider, {
2426
+ ...control,
2427
+ ...index === 0 ? { ref: first } : {},
2428
+ min: -100,
2429
+ max: 100,
2430
+ step: 1,
2431
+ largeStep: 10,
2432
+ value: develop[name],
2433
+ formatValue: signed,
2434
+ ...sliderGesture(gesture, (value) => ({
2435
+ type: "image.setDevelop",
2436
+ values: { [name]: Math.round(value) }
2437
+ })),
2438
+ onDoubleClick: () => {
2439
+ if (plan.base.develop[name] !== 0) reset({ [name]: 0 });
2440
+ }
2441
+ }),
2442
+ /* @__PURE__ */ jsx("output", {
2443
+ className: "hm-image-adjust-value",
2444
+ "aria-hidden": "true",
2445
+ children: signed(develop[name])
2446
+ }),
2447
+ plan.base.develop[name] !== 0 ? /* @__PURE__ */ jsx(Button, {
2448
+ variant: "quiet",
2449
+ size: "small",
2450
+ onClick: () => reset({ [name]: 0 }),
2451
+ children: messages.t("develop.reset", { name: label })
2452
+ }) : null
2453
+ ]
2454
+ })
2455
+ }, name);
2456
+ })]
2457
+ });
2458
+ }
2459
+ // src/react/panels/FilterPanel.tsx
2460
+ function ImageFilterPanel(props) {
2461
+ const session = useImageSession();
2462
+ const { plan } = useImageDocument();
2463
+ const [editor] = useImageEditorState();
2464
+ const messages = useImageMessages();
2465
+ const gesture = useGesture();
2466
+ if (!plan) return null;
2467
+ const filter = (editor.preview ?? plan).base.filter;
2468
+ const options = [{
2469
+ value: "none",
2470
+ label: messages.t("filters.none")
2471
+ }, ...FILTER_PRESETS.map((preset) => ({
2472
+ value: preset,
2473
+ label: messages.t(`filters.${preset}`)
2474
+ }))];
2475
+ return /* @__PURE__ */ jsxs("section", {
2476
+ className: ["hm-image-filter-panel", props.className].filter(Boolean).join(" "),
2477
+ "aria-label": messages.t("filters.panel"),
2478
+ children: [/* @__PURE__ */ jsx(SegmentedControl, {
2479
+ label: messages.t("filters.label"),
2480
+ value: filter?.preset ?? "none",
2481
+ options,
2482
+ onValueChange: (value) => {
2483
+ gesture.cancel();
2484
+ session.execute({
2485
+ type: "image.setFilter",
2486
+ filter: value === "none" ? null : {
2487
+ preset: value,
2488
+ strength: filter?.strength ?? 100
2489
+ }
2490
+ });
2491
+ }
2492
+ }), filter ? /* @__PURE__ */ jsx(Field, {
2493
+ label: messages.t("filters.strength"),
2494
+ className: "hm-image-slider-field",
2495
+ children: /* @__PURE__ */ jsx(Slider, {
2496
+ min: 0,
2497
+ max: 100,
2498
+ step: 1,
2499
+ largeStep: 10,
2500
+ value: filter.strength,
2501
+ ...sliderGesture(gesture, (value) => ({
2502
+ type: "image.setFilter",
2503
+ filter: {
2504
+ preset: filter.preset,
2505
+ strength: Math.round(value)
2506
+ }
2507
+ }))
2508
+ })
2509
+ }) : null]
2510
+ });
2511
+ }
2512
+ // src/react/panels/InfoPanel.tsx
2513
+ var KINDS = [
2514
+ "location",
2515
+ "camera",
2516
+ "timestamps",
2517
+ "thumbnail",
2518
+ "colourProfile",
2519
+ "other"
2520
+ ];
2521
+ var FIELDS = [
2522
+ "title",
2523
+ "description",
2524
+ "artist",
2525
+ "copyright"
2526
+ ];
2527
+ function ImageInfoPanel(props) {
2528
+ const { plan, source } = useImageDocument();
2529
+ const messages = useImageMessages();
2530
+ if (!plan || !source) return null;
2531
+ const carried = KINDS.filter((kind) => source.metadata[kind]);
2532
+ const kept = FIELDS.filter((field) => plan.metadata[field] !== "");
2533
+ return /* @__PURE__ */ jsx("section", {
2534
+ className: ["hm-image-info-panel", props.className].filter(Boolean).join(" "),
2535
+ "aria-label": messages.t("info.panel"),
2536
+ children: /* @__PURE__ */ jsxs("dl", {
2537
+ className: "hm-image-info-list",
2538
+ children: [
2539
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.size") }),
2540
+ /* @__PURE__ */ jsx("dd", { children: messages.t("info.sizeValue", {
2541
+ width: source.width,
2542
+ height: source.height
2543
+ }) }),
2544
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.format") }),
2545
+ /* @__PURE__ */ jsx("dd", { children: messages.t(`info.formats.${source.format}`) }),
2546
+ source.frames > 1 ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("dt", { children: messages.t("info.frames") }), /* @__PURE__ */ jsx("dd", { children: source.frames })] }) : null,
2547
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.fileSize") }),
2548
+ /* @__PURE__ */ jsx("dd", { children: messages.t("info.fileSizeValue", { size: source.fileSize }) }),
2549
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.metadata") }),
2550
+ /* @__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") }),
2551
+ /* @__PURE__ */ jsx("dt", { children: messages.t("info.kept") }),
2552
+ /* @__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") })
2553
+ ]
2554
+ })
2555
+ });
2556
+ }
2557
+ // src/react/panels/Inspector.tsx
2558
+ var PANELS = [
2559
+ "adjust",
2560
+ "filters",
2561
+ "info"
2562
+ ];
2563
+ function ImageInspector(props) {
2564
+ const { plan } = useImageDocument();
2565
+ const [editor] = useImageEditorState();
2566
+ const messages = useImageMessages();
2567
+ const [chosen, setPanel] = useState("adjust");
2568
+ if (editor.tool === "crop") return /* @__PURE__ */ jsx(ImageCropPanel, {});
2569
+ if (editor.tool === "redact") return /* @__PURE__ */ jsx(ImageRedactPanel, {});
2570
+ if (editor.tool === "layers") return /* @__PURE__ */ jsx(ImageLayersPanel, {});
2571
+ if (!plan) return null;
2572
+ const panels = PANELS.filter((name) => props.features?.[name] !== false);
2573
+ const first = panels[0];
2574
+ if (first === void 0) return null;
2575
+ const panel = panels.includes(chosen) ? chosen : first;
2576
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2577
+ panels.length > 1 ? /* @__PURE__ */ jsx(SegmentedControl, {
2578
+ label: messages.t("inspector.label"),
2579
+ value: panel,
2580
+ size: "small",
2581
+ options: panels.map((name) => ({
2582
+ value: name,
2583
+ label: messages.t(`inspector.${name}`)
2584
+ })),
2585
+ onValueChange: (value) => setPanel(value)
2586
+ }) : null,
2587
+ panel === "adjust" ? /* @__PURE__ */ jsx(ImageAdjustPanel, {}) : null,
2588
+ panel === "filters" ? /* @__PURE__ */ jsx(ImageFilterPanel, {}) : null,
2589
+ panel === "info" ? /* @__PURE__ */ jsx(ImageInfoPanel, {}) : null
2590
+ ] });
2591
+ }
2592
+ // src/react/crop/CropFrame.tsx
2593
+ var HANDLES$1 = [
2594
+ "nw",
2595
+ "n",
2596
+ "ne",
2597
+ "e",
2598
+ "se",
2599
+ "s",
2600
+ "sw",
2601
+ "w"
2602
+ ];
2603
+ var ARROWS$2 = /* @__PURE__ */ new Set([
2604
+ "ArrowLeft",
2605
+ "ArrowRight",
2606
+ "ArrowUp",
2607
+ "ArrowDown"
2608
+ ]);
2609
+ function CropFrame(props) {
2610
+ const { plan, source, view } = props;
2611
+ const [state] = useImageEditorState();
2612
+ const messages = useImageMessages();
2613
+ const actions = useCropActions();
2614
+ const frame = useRef(null);
2615
+ const describedBy = useId();
2616
+ const drag = useRef(void 0);
2617
+ useEffect(() => {
2618
+ frame.current?.focus();
2619
+ }, []);
2620
+ const crop = state.crop;
2621
+ if (!crop) return null;
2622
+ const { orientation } = plan.base;
2623
+ const whole = {
2624
+ ...plan,
2625
+ base: {
2626
+ ...plan.base,
2627
+ crop: null
2628
+ }
2629
+ };
2630
+ const placed = placement(compositionSize(whole, source), view);
2631
+ if (!(placed.scale > 0)) return null;
2632
+ const shown = cropInComposition(crop.pending, orientation, source);
2633
+ const ratio = aspectRatio(crop.aspect, source);
2634
+ const onKeyDown = (event) => {
2635
+ if (event.key === "Enter") {
2636
+ event.preventDefault();
2637
+ actions.apply();
2638
+ return;
2639
+ }
2640
+ if (event.key === "Escape") {
2641
+ event.preventDefault();
2642
+ if (drag.current) {
2643
+ actions.update(drag.current.start);
2644
+ drag.current = void 0;
2645
+ } else actions.cancel();
2646
+ return;
2647
+ }
2648
+ if (!ARROWS$2.has(event.key)) return;
2649
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
2650
+ event.preventDefault();
2651
+ event.stopPropagation();
2652
+ actions.update(nudgeCropOnScreen(crop.pending, event.key, 1, event.shiftKey, orientation, source, ratio));
2653
+ };
2654
+ const onPointerDown = (handle) => (event) => {
2655
+ if (event.button !== 0) return;
2656
+ event.preventDefault();
2657
+ event.stopPropagation();
2658
+ frame.current?.focus();
2659
+ try {
2660
+ event.currentTarget.setPointerCapture(event.pointerId);
2661
+ } catch {}
2662
+ drag.current = {
2663
+ pointer: event.pointerId,
2664
+ x: event.clientX,
2665
+ y: event.clientY,
2666
+ start: crop.pending,
2667
+ handle
2668
+ };
2669
+ };
2670
+ const onPointerMove = (event) => {
2671
+ const current = drag.current;
2672
+ if (!current || current.pointer !== event.pointerId) return;
2673
+ const moved = compositionDeltaToSource((event.clientX - current.x) / placed.scale, (event.clientY - current.y) / placed.scale, orientation, source);
2674
+ 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));
2675
+ };
2676
+ const onPointerEnd = (event) => {
2677
+ if (drag.current?.pointer !== event.pointerId) return;
2678
+ if (event.type === "pointercancel") actions.update(drag.current.start);
2679
+ drag.current = void 0;
2680
+ };
2681
+ const style = {
2682
+ left: `${placed.x + shown.x * placed.scale}px`,
2683
+ top: `${placed.y + shown.y * placed.scale}px`,
2684
+ width: `${shown.width * placed.scale}px`,
2685
+ height: `${shown.height * placed.scale}px`
2686
+ };
2687
+ const pointer = {
2688
+ onPointerMove,
2689
+ onPointerUp: onPointerEnd,
2690
+ onPointerCancel: onPointerEnd
2691
+ };
2692
+ return /* @__PURE__ */ jsxs("div", {
2693
+ ref: frame,
2694
+ className: "hm-image-crop-frame",
2695
+ role: "group",
2696
+ "aria-label": messages.t("crop.frame"),
2697
+ "aria-describedby": describedBy,
2698
+ tabIndex: 0,
2699
+ style,
2700
+ onKeyDown,
2701
+ onPointerDown: onPointerDown("move"),
2702
+ ...pointer,
2703
+ children: [/* @__PURE__ */ jsx("span", {
2704
+ id: describedBy,
2705
+ hidden: true,
2706
+ children: messages.t("crop.frameDescription", {
2707
+ width: crop.pending.width,
2708
+ height: crop.pending.height,
2709
+ x: crop.pending.x,
2710
+ y: crop.pending.y
2711
+ })
2712
+ }), HANDLES$1.map((handle) => /* @__PURE__ */ jsx("span", {
2713
+ className: "hm-image-crop-handle",
2714
+ "data-hm-handle": handle,
2715
+ "aria-hidden": "true",
2716
+ onPointerDown: onPointerDown(handle),
2717
+ ...pointer
2718
+ }, handle))]
2719
+ });
2720
+ }
2721
+ // src/react/layers/frame-geometry.ts
2722
+ var LAYER_HANDLES = [
2723
+ "nw",
2724
+ "n",
2725
+ "ne",
2726
+ "e",
2727
+ "se",
2728
+ "s",
2729
+ "sw",
2730
+ "w"
2731
+ ];
2732
+ function turned([a, b, c, d], x, y) {
2733
+ return {
2734
+ x: a * x + c * y,
2735
+ y: b * x + d * y
2736
+ };
2737
+ }
2738
+ var clamp = (value, min, max) => Math.min(max, Math.max(min, value));
2739
+ var whole = (value) => Math.round(value) || 0;
2740
+ var boxOf = ({ x, y, width, height, rotation, flipX }) => ({
2741
+ x,
2742
+ y,
2743
+ width,
2744
+ height,
2745
+ rotation,
2746
+ flipX
2747
+ });
2748
+ function moveLayerBox(box, sceneToComposition, dx, dy) {
2749
+ const by = turned(invertMatrix(sceneToComposition), dx, dy);
2750
+ const limit = MAX_SCENE_COORDINATE;
2751
+ return {
2752
+ ...box,
2753
+ x: clamp(box.x + whole(by.x), -limit, limit),
2754
+ y: clamp(box.y + whole(by.y), -limit, limit)
2755
+ };
2756
+ }
2757
+ function resizeLayerBox(box, handle, dx, dy) {
2758
+ const west = handle.includes("w");
2759
+ const north = handle.includes("n");
2760
+ const size = (length, by) => clamp(whole(length + by), 1, MAX_SCENE_COORDINATE);
2761
+ const width = handle.includes("e") ? size(box.width, dx) : west ? size(box.width, -dx) : box.width;
2762
+ const height = handle.includes("s") ? size(box.height, dy) : north ? size(box.height, -dy) : box.height;
2763
+ const matrix = layerToScene(box);
2764
+ const anchor = applyMatrix(matrix, {
2765
+ x: west ? box.width : 0,
2766
+ y: north ? box.height : 0
2767
+ });
2768
+ const fromCentre = turned(matrix, (west ? width : 0) - width / 2, (north ? height : 0) - height / 2);
2769
+ const limit = MAX_SCENE_COORDINATE;
2770
+ return {
2771
+ x: clamp(whole(anchor.x - fromCentre.x - width / 2), -limit, limit),
2772
+ y: clamp(whole(anchor.y - fromCentre.y - height / 2), -limit, limit),
2773
+ width,
2774
+ height,
2775
+ rotation: box.rotation,
2776
+ flipX: box.flipX
2777
+ };
2778
+ }
2779
+ function edgeFacing(layerToComposition, direction) {
2780
+ const east = turned(layerToComposition, 1, 0);
2781
+ const south = turned(layerToComposition, 0, 1);
2782
+ const along = (vector) => direction === "right" ? vector.x : vector.y;
2783
+ const facing = [
2784
+ ["e", along(east)],
2785
+ ["s", along(south)],
2786
+ ["w", -along(east)],
2787
+ ["n", -along(south)]
2788
+ ];
2789
+ let best = facing[0];
2790
+ for (const edge of facing) if (edge[1] > best[1] + 1e-9) best = edge;
2791
+ return best[0];
2792
+ }
2793
+ function resizeLayerBoxOnScreen(box, layerToComposition, direction, by) {
2794
+ const edge = edgeFacing(layerToComposition, direction);
2795
+ const outward = edge === "e" || edge === "s" ? by : -by;
2796
+ return resizeLayerBox(box, edge, outward, outward);
2797
+ }
2798
+ var CURSORS = [
2799
+ "ew-resize",
2800
+ "nwse-resize",
2801
+ "ns-resize",
2802
+ "nesw-resize"
2803
+ ];
2804
+ function handleCursor(layerToComposition, handle) {
2805
+ const seen = turned(layerToComposition, handle.includes("e") ? 1 : handle.includes("w") ? -1 : 0, handle.includes("s") ? 1 : handle.includes("n") ? -1 : 0);
2806
+ return CURSORS[(Math.round(Math.atan2(seen.y, seen.x) / (Math.PI / 4)) % 4 + 4) % 4];
2807
+ }
2808
+ // src/react/layers/LayersOverlay.tsx
2809
+ var ARROWS$1 = {
2810
+ ArrowLeft: [-1, 0],
2811
+ ArrowRight: [1, 0],
2812
+ ArrowUp: [0, -1],
2813
+ ArrowDown: [0, 1]
2814
+ };
2815
+ function LayersOverlay(props) {
2816
+ const { plan, source, view } = props;
2817
+ const [state] = useImageEditorState();
2818
+ const messages = useImageMessages();
2819
+ const actions = useLayerActions();
2820
+ const overlay = useRef(null);
2821
+ const describedBy = useId();
2822
+ const drag = useRef(void 0);
2823
+ const focusNext = useRef(null);
2824
+ const frameOf = (key) => overlay.current?.querySelector(`[data-hm-layer="${CSS.escape(key)}"]`);
2825
+ useEffect(() => {
2826
+ const key = focusNext.current;
2827
+ if (!key) return;
2828
+ const frame = frameOf(key);
2829
+ if (!frame) return;
2830
+ focusNext.current = null;
2831
+ frame.focus();
2832
+ });
2833
+ const selected = state.layers?.selected ?? null;
2834
+ const composition = compositionSize(plan, source);
2835
+ const placed = placement(composition, view);
2836
+ if (!(placed.scale > 0)) return null;
2837
+ const crop = cropRect(plan.base.crop, source);
2838
+ const { orientation } = plan.base;
2839
+ const sceneToComposition = sceneToOutput(crop, orientation, composition);
2840
+ const seen = (box) => layerToOutput(box, crop, orientation, composition);
2841
+ const capture = (event) => {
2842
+ try {
2843
+ event.currentTarget.setPointerCapture(event.pointerId);
2844
+ } catch {}
2845
+ };
2846
+ const onFramePointerDown = (layer, handle) => (event) => {
2847
+ if (event.button !== 0) return;
2848
+ event.preventDefault();
2849
+ event.stopPropagation();
2850
+ actions.select(layer.key);
2851
+ frameOf(layer.key)?.focus();
2852
+ capture(event);
2853
+ drag.current = {
2854
+ pointer: event.pointerId,
2855
+ x: event.clientX,
2856
+ y: event.clientY,
2857
+ key: layer.key,
2858
+ handle,
2859
+ start: boxOf(layer),
2860
+ moved: false
2861
+ };
2862
+ };
2863
+ const onPointerMove = (event) => {
2864
+ const current = drag.current;
2865
+ if (!current || current.pointer !== event.pointerId) return;
2866
+ const dx = (event.clientX - current.x) / placed.scale;
2867
+ const dy = (event.clientY - current.y) / placed.scale;
2868
+ current.moved = true;
2869
+ if (current.handle === "move") {
2870
+ actions.moving(current.key, moveLayerBox(current.start, sceneToComposition, dx, dy));
2871
+ return;
2872
+ }
2873
+ const own = turned(invertMatrix(seen(current.start)), dx, dy);
2874
+ actions.moving(current.key, resizeLayerBox(current.start, current.handle, own.x, own.y));
2875
+ };
2876
+ const onPointerEnd = (event) => {
2877
+ const current = drag.current;
2878
+ if (!current || current.pointer !== event.pointerId) return;
2879
+ drag.current = void 0;
2880
+ if (event.type === "pointercancel") actions.cancel();
2881
+ else if (current.moved) actions.commit();
2882
+ };
2883
+ const pointer = {
2884
+ onPointerMove,
2885
+ onPointerUp: onPointerEnd,
2886
+ onPointerCancel: onPointerEnd
2887
+ };
2888
+ const onKeyDown = (layer) => (event) => {
2889
+ if (event.key === "Escape") {
2890
+ event.preventDefault();
2891
+ event.stopPropagation();
2892
+ if (drag.current) {
2893
+ drag.current = void 0;
2894
+ actions.cancel();
2895
+ } else actions.done();
2896
+ return;
2897
+ }
2898
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
2899
+ if (event.key === "Delete" || event.key === "Backspace") {
2900
+ event.preventDefault();
2901
+ event.stopPropagation();
2902
+ const next = actions.remove(layer.key);
2903
+ if (next !== null) focusNext.current = next;
2904
+ else overlay.current?.closest(".hm-image-editor")?.querySelector(".hm-image-layers-done")?.focus();
2905
+ return;
2906
+ }
2907
+ const arrow = ARROWS$1[event.key];
2908
+ if (!arrow) return;
2909
+ event.preventDefault();
2910
+ event.stopPropagation();
2911
+ const [dx, dy] = arrow;
2912
+ const box = boxOf(layer);
2913
+ const moved = event.shiftKey ? resizeLayerBoxOnScreen(box, seen(box), dx !== 0 ? "right" : "down", dx + dy) : moveLayerBox(box, sceneToComposition, dx, dy);
2914
+ actions.moving(layer.key, moved);
2915
+ actions.commit(true);
2916
+ };
2917
+ const count = plan.layers.length;
2918
+ const shown = plan.layers.filter((layer) => layer.visible || layer.key === selected);
2919
+ const tabStop = shown.some((layer) => layer.key === selected) ? selected : shown.at(-1)?.key;
2920
+ return /* @__PURE__ */ jsx("div", {
2921
+ ref: overlay,
2922
+ className: "hm-image-layers-overlay",
2923
+ onPointerDown: (event) => {
2924
+ if (event.button === 0) actions.select(null);
2925
+ },
2926
+ children: shown.map((layer) => {
2927
+ const index = plan.layers.indexOf(layer);
2928
+ const isSelected = layer.key === selected;
2929
+ const [a, b, c, d, e, f] = seen(layer);
2930
+ return /* @__PURE__ */ jsxs("div", {
2931
+ className: "hm-image-layer-frame",
2932
+ "data-hm-layer": layer.key,
2933
+ "data-hm-selected": isSelected ? "" : void 0,
2934
+ "data-hm-hidden": layer.visible ? void 0 : "",
2935
+ role: "group",
2936
+ "aria-label": messages.t("layers.frame", {
2937
+ index: count - index,
2938
+ count,
2939
+ name: layerLabel(layer, messages)
2940
+ }),
2941
+ "aria-describedby": `${describedBy}-${index}`,
2942
+ tabIndex: layer.key === tabStop ? 0 : -1,
2943
+ style: {
2944
+ width: `${layer.width * placed.scale}px`,
2945
+ height: `${layer.height * placed.scale}px`,
2946
+ transform: `matrix(${a}, ${b}, ${c}, ${d}, ${placed.x + e * placed.scale}, ${placed.y + f * placed.scale})`
2947
+ },
2948
+ onFocus: () => actions.select(layer.key),
2949
+ onKeyDown: onKeyDown(layer),
2950
+ onPointerDown: onFramePointerDown(layer, "move"),
2951
+ ...pointer,
2952
+ children: [/* @__PURE__ */ jsx("span", {
2953
+ id: `${describedBy}-${index}`,
2954
+ hidden: true,
2955
+ children: messages.t("layers.frameDescription", {
2956
+ width: layer.width,
2957
+ height: layer.height,
2958
+ x: layer.x,
2959
+ y: layer.y,
2960
+ degrees: layer.rotation / 10
2961
+ })
2962
+ }), isSelected ? LAYER_HANDLES.map((handle) => /* @__PURE__ */ jsx("span", {
2963
+ className: "hm-image-layer-handle",
2964
+ "data-hm-handle": handle,
2965
+ "aria-hidden": "true",
2966
+ style: { cursor: handleCursor([
2967
+ a,
2968
+ b,
2969
+ c,
2970
+ d,
2971
+ e,
2972
+ f
2973
+ ], handle) },
2974
+ onPointerDown: onFramePointerDown(layer, handle),
2975
+ ...pointer
2976
+ }, handle)) : null]
2977
+ }, layer.key);
2978
+ })
2979
+ });
2980
+ }
2981
+ // src/react/redact/RedactOverlay.tsx
2982
+ var HANDLES = [
2983
+ "nw",
2984
+ "n",
2985
+ "ne",
2986
+ "e",
2987
+ "se",
2988
+ "s",
2989
+ "sw",
2990
+ "w"
2991
+ ];
2992
+ var ARROWS = {
2993
+ ArrowLeft: [-1, 0],
2994
+ ArrowRight: [1, 0],
2995
+ ArrowUp: [0, -1],
2996
+ ArrowDown: [0, 1]
2997
+ };
2998
+ var DRAW_THRESHOLD = 3;
2999
+ var EDGE_TOLERANCE = .25;
3000
+ function dragged(start, handle, dx, dy) {
3001
+ if (handle === "move") return {
3002
+ ...start,
3003
+ x: start.x + dx,
3004
+ y: start.y + dy
3005
+ };
3006
+ let left = start.x;
3007
+ let top = start.y;
3008
+ let right = start.x + start.width;
3009
+ let bottom = start.y + start.height;
3010
+ if (handle.includes("w")) left = Math.min(left + dx, right - 1);
3011
+ if (handle.includes("e")) right = Math.max(right + dx, left + 1);
3012
+ if (handle.includes("n")) top = Math.min(top + dy, bottom - 1);
3013
+ if (handle.includes("s")) bottom = Math.max(bottom + dy, top + 1);
3014
+ return {
3015
+ x: left,
3016
+ y: top,
3017
+ width: right - left,
3018
+ height: bottom - top
3019
+ };
3020
+ }
3021
+ function RedactOverlay(props) {
3022
+ const { plan, source, view } = props;
3023
+ const [state] = useImageEditorState();
3024
+ const messages = useImageMessages();
3025
+ const actions = useRedactActions();
3026
+ const overlay = useRef(null);
3027
+ const describedBy = useId();
3028
+ const drag = useRef(void 0);
3029
+ const focusNext = useRef(null);
3030
+ const selected = state.redact?.selected ?? null;
3031
+ const exists = plan.redactions.some((redaction) => redaction.key === selected);
3032
+ const previous = useRef(null);
3033
+ useEffect(() => {
3034
+ if (selected === previous.current) return;
3035
+ previous.current = selected;
3036
+ if (!selected || !exists || drag.current) return;
3037
+ const active = document.activeElement;
3038
+ if (active instanceof HTMLElement && active.closest(".hm-image-redact-panel input") !== null) return;
3039
+ overlay.current?.querySelector(`[data-hm-redaction="${CSS.escape(selected)}"]`)?.focus();
3040
+ }, [selected, exists]);
3041
+ useEffect(() => {
3042
+ const key = focusNext.current;
3043
+ if (!key || !plan.redactions.some((redaction) => redaction.key === key)) return;
3044
+ focusNext.current = null;
3045
+ overlay.current?.querySelector(`[data-hm-redaction="${CSS.escape(key)}"]`)?.focus();
3046
+ });
3047
+ const crop = cropRect(plan.base.crop, source);
3048
+ const { orientation } = plan.base;
3049
+ const placed = placement(compositionSize(plan, source), view);
3050
+ if (!(placed.scale > 0)) return null;
3051
+ const shown = (redaction) => sceneRectToComposition(redaction, crop, orientation);
3052
+ const toScene = (rect) => compositionRectToScene(rect, crop, orientation);
3053
+ const onComposition = (event) => {
3054
+ const box = overlay.current?.getBoundingClientRect();
3055
+ return {
3056
+ x: (event.clientX - (box?.left ?? 0) - placed.x) / placed.scale,
3057
+ y: (event.clientY - (box?.top ?? 0) - placed.y) / placed.scale
3058
+ };
3059
+ };
3060
+ const capture = (event) => {
3061
+ try {
3062
+ event.currentTarget.setPointerCapture(event.pointerId);
3063
+ } catch {}
3064
+ };
3065
+ const onFramePointerDown = (redaction, handle) => (event) => {
3066
+ if (event.button !== 0) return;
3067
+ event.preventDefault();
3068
+ event.stopPropagation();
3069
+ actions.select(redaction.key);
3070
+ overlay.current?.querySelector(`[data-hm-redaction="${CSS.escape(redaction.key)}"]`)?.focus();
3071
+ capture(event);
3072
+ drag.current = {
3073
+ pointer: event.pointerId,
3074
+ x: event.clientX,
3075
+ y: event.clientY,
3076
+ key: redaction.key,
3077
+ handle,
3078
+ start: shown(redaction),
3079
+ drawn: false
3080
+ };
3081
+ };
3082
+ const onBackgroundPointerDown = (event) => {
3083
+ if (event.button !== 0) return;
3084
+ event.preventDefault();
3085
+ capture(event);
3086
+ const at = onComposition(event);
3087
+ drag.current = {
3088
+ pointer: event.pointerId,
3089
+ x: event.clientX,
3090
+ y: event.clientY,
3091
+ key: newRedactionKey(plan),
3092
+ handle: "draw",
3093
+ start: {
3094
+ x: at.x,
3095
+ y: at.y,
3096
+ width: 0,
3097
+ height: 0
3098
+ },
3099
+ drawn: false
3100
+ };
3101
+ };
3102
+ const onPointerMove = (event) => {
3103
+ const current = drag.current;
3104
+ if (!current || current.pointer !== event.pointerId) return;
3105
+ const dx = (event.clientX - current.x) / placed.scale;
3106
+ const dy = (event.clientY - current.y) / placed.scale;
3107
+ if (current.handle === "draw") {
3108
+ const far = Math.hypot(event.clientX - current.x, event.clientY - current.y) >= DRAW_THRESHOLD;
3109
+ if (!current.drawn && !far) return;
3110
+ current.drawn = true;
3111
+ const EDGE = EDGE_TOLERANCE / placed.scale;
3112
+ const left = Math.floor(Math.min(current.start.x, current.start.x + dx) + EDGE);
3113
+ const top = Math.floor(Math.min(current.start.y, current.start.y + dy) + EDGE);
3114
+ const right = Math.ceil(Math.max(current.start.x, current.start.x + dx) - EDGE);
3115
+ const bottom = Math.ceil(Math.max(current.start.y, current.start.y + dy) - EDGE);
3116
+ actions.drawing(current.key, {
3117
+ x: left,
3118
+ y: top,
3119
+ width: Math.max(1, right - left),
3120
+ height: Math.max(1, bottom - top)
3121
+ });
3122
+ return;
3123
+ }
3124
+ current.drawn = true;
3125
+ actions.moving(current.key, toScene(dragged(current.start, current.handle, Math.round(dx), Math.round(dy))));
3126
+ };
3127
+ const onPointerEnd = (event) => {
3128
+ const current = drag.current;
3129
+ if (!current || current.pointer !== event.pointerId) return;
3130
+ drag.current = void 0;
3131
+ if (event.type === "pointercancel") {
3132
+ actions.cancel();
3133
+ return;
3134
+ }
3135
+ if (current.handle === "draw" && !current.drawn) {
3136
+ actions.select(null);
3137
+ return;
3138
+ }
3139
+ actions.commit();
3140
+ if (current.handle === "draw") {
3141
+ focusNext.current = current.key;
3142
+ actions.select(current.key);
3143
+ }
3144
+ };
3145
+ const pointer = {
3146
+ onPointerMove,
3147
+ onPointerUp: onPointerEnd,
3148
+ onPointerCancel: onPointerEnd
3149
+ };
3150
+ const onKeyDown = (redaction) => (event) => {
3151
+ if (event.key === "Escape") {
3152
+ event.preventDefault();
3153
+ event.stopPropagation();
3154
+ if (drag.current) {
3155
+ drag.current = void 0;
3156
+ actions.cancel();
3157
+ } else actions.done();
3158
+ return;
3159
+ }
3160
+ if (event.key === "Delete" || event.key === "Backspace") {
3161
+ event.preventDefault();
3162
+ event.stopPropagation();
3163
+ const index = plan.redactions.findIndex((item) => item.key === redaction.key);
3164
+ const next = plan.redactions[index + 1] ?? plan.redactions[index - 1];
3165
+ actions.remove(redaction.key);
3166
+ if (next) actions.select(next.key);
3167
+ else overlay.current?.closest(".hm-image-editor")?.querySelector(".hm-image-redact-add")?.focus();
3168
+ return;
3169
+ }
3170
+ const arrow = ARROWS[event.key];
3171
+ if (!arrow) return;
3172
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
3173
+ event.preventDefault();
3174
+ event.stopPropagation();
3175
+ const [dx, dy] = arrow;
3176
+ const moved = event.shiftKey ? dragged(shown(redaction), dx !== 0 ? "e" : "s", dx, dy) : dragged(shown(redaction), "move", dx, dy);
3177
+ actions.moving(redaction.key, toScene(moved));
3178
+ actions.commit(true);
3179
+ };
3180
+ const count = plan.redactions.length;
3181
+ const tabStop = exists ? selected : plan.redactions[0]?.key;
3182
+ return /* @__PURE__ */ jsx("div", {
3183
+ ref: overlay,
3184
+ className: "hm-image-redact-overlay",
3185
+ onPointerDown: onBackgroundPointerDown,
3186
+ ...pointer,
3187
+ children: plan.redactions.map((redaction, index) => {
3188
+ const rect = shown(redaction);
3189
+ const isSelected = redaction.key === selected;
3190
+ return /* @__PURE__ */ jsxs("div", {
3191
+ className: "hm-image-redact-frame",
3192
+ "data-hm-redaction": redaction.key,
3193
+ "data-hm-selected": isSelected ? "" : void 0,
3194
+ role: "group",
3195
+ "aria-label": messages.t("redact.frame", {
3196
+ index: index + 1,
3197
+ count
3198
+ }),
3199
+ "aria-describedby": `${describedBy}-${index}`,
3200
+ tabIndex: redaction.key === tabStop ? 0 : -1,
3201
+ style: {
3202
+ left: `${placed.x + rect.x * placed.scale}px`,
3203
+ top: `${placed.y + rect.y * placed.scale}px`,
3204
+ width: `${rect.width * placed.scale}px`,
3205
+ height: `${rect.height * placed.scale}px`
3206
+ },
3207
+ onFocus: () => actions.select(redaction.key),
3208
+ onKeyDown: onKeyDown(redaction),
3209
+ onPointerDown: onFramePointerDown(redaction, "move"),
3210
+ ...pointer,
3211
+ children: [/* @__PURE__ */ jsx("span", {
3212
+ id: `${describedBy}-${index}`,
3213
+ hidden: true,
3214
+ children: messages.t("redact.frameDescription", {
3215
+ mode: messages.t(`redact.modeNames.${redaction.mode}`),
3216
+ width: redaction.width,
3217
+ height: redaction.height,
3218
+ x: redaction.x,
3219
+ y: redaction.y
3220
+ })
3221
+ }), isSelected ? HANDLES.map((handle) => /* @__PURE__ */ jsx("span", {
3222
+ className: "hm-image-redact-handle",
3223
+ "data-hm-handle": handle,
3224
+ "aria-hidden": "true",
3225
+ onPointerDown: onFramePointerDown(redaction, handle),
3226
+ ...pointer
3227
+ }, handle)) : null]
3228
+ }, redaction.key);
3229
+ })
3230
+ });
3231
+ }
3232
+ // src/react/stage/StageNotices.tsx
3233
+ function warningValues(limit, source) {
3234
+ if (limit === "maxFileSize") return { actual: source.fileSize };
3235
+ if (limit === "maxFrames") return { actual: source.frames };
3236
+ return {};
3237
+ }
3238
+ function StageNotices() {
3239
+ const { source, warnings, status } = useImageDocument();
3240
+ const messages = useImageMessages();
3241
+ const id = useId();
3242
+ const [dismissed, setDismissed] = useState(() => /* @__PURE__ */ new Set());
3243
+ if (!source || status !== "ready") return null;
3244
+ const t = messages.t;
3245
+ const notices = [];
3246
+ for (const limit of warnings) {
3247
+ if (limit === "maxSessionSize" || limit === "maxLayers") continue;
3248
+ notices.push({
3249
+ key: `${source.id}:${limit}`,
3250
+ text: t(`warnings.${limit}`, warningValues(limit, source))
3251
+ });
3252
+ }
3253
+ if (source.metadata.colourProfile) notices.push({
3254
+ key: `${source.id}:colourProfile`,
3255
+ text: messages.t("notices.colourProfile")
3256
+ });
3257
+ const shown = notices.filter((notice) => !dismissed.has(notice.key));
3258
+ return /* @__PURE__ */ jsx("div", {
3259
+ className: "hm-image-stage-notices",
3260
+ role: "status",
3261
+ "aria-label": messages.t("notices.label"),
3262
+ children: shown.length > 0 ? /* @__PURE__ */ jsx("ul", { children: shown.map((notice, index) => /* @__PURE__ */ jsxs("li", {
3263
+ className: "hm-image-stage-notice",
3264
+ children: [/* @__PURE__ */ jsx("span", {
3265
+ id: `${id}-${index}`,
3266
+ children: notice.text
3267
+ }), /* @__PURE__ */ jsx(IconButton, {
3268
+ label: messages.t("notices.dismiss"),
3269
+ "aria-describedby": `${id}-${index}`,
3270
+ icon: /* @__PURE__ */ jsx(CloseIcon, {}),
3271
+ size: "small",
3272
+ variant: "quiet",
3273
+ onClick: () => setDismissed((before) => new Set(before).add(notice.key))
3274
+ })]
3275
+ }, notice.key)) }) : null
3276
+ });
3277
+ }
3278
+ // src/react/stage/ImageStage.tsx
3279
+ var CROP_INSET = 24;
3280
+ function useStageSize(element) {
3281
+ const [size, setSize] = useState();
3282
+ useEffect(() => {
3283
+ if (!element) return;
3284
+ let ratioQuery;
3285
+ const measure = () => {
3286
+ const { width, height } = element.getBoundingClientRect();
3287
+ const pixelRatio = globalThis.devicePixelRatio || 1;
3288
+ setSize((current) => current?.width === width && current.height === height && current.pixelRatio === pixelRatio ? current : {
3289
+ width,
3290
+ height,
3291
+ pixelRatio
3292
+ });
3293
+ };
3294
+ const watchRatio = () => {
3295
+ ratioQuery?.removeEventListener("change", onRatio);
3296
+ ratioQuery = globalThis.matchMedia?.(`(resolution: ${globalThis.devicePixelRatio || 1}dppx)`);
3297
+ ratioQuery?.addEventListener("change", onRatio);
3298
+ };
3299
+ const onRatio = () => {
3300
+ measure();
3301
+ watchRatio();
3302
+ };
3303
+ const observer = new ResizeObserver(measure);
3304
+ observer.observe(element);
3305
+ measure();
3306
+ watchRatio();
3307
+ return () => {
3308
+ observer.disconnect();
3309
+ ratioQuery?.removeEventListener("change", onRatio);
3310
+ };
3311
+ }, [element]);
3312
+ return size;
3313
+ }
3314
+ function ImageStage(props) {
3315
+ const { engine, messages, opener, inserter } = useImageInternals();
3316
+ const snapshot = useImageDocument();
3317
+ const [view] = useImageView();
3318
+ const [frame, setFrame] = useState(null);
3319
+ const size = useStageSize(frame);
3320
+ const canvasRef = useRef(null);
3321
+ const rendererRef = useRef(void 0);
3322
+ const [editorState] = useImageEditorState();
3323
+ const { source, status } = snapshot;
3324
+ const cropping = editorState.tool === "crop";
3325
+ const redacting = editorState.tool === "redact";
3326
+ const layering = editorState.tool === "layers";
3327
+ const inset = cropping || redacting || layering ? CROP_INSET : 0;
3328
+ const plan = useMemo(() => {
3329
+ const committed = snapshot.plan;
3330
+ if (!committed) return null;
3331
+ if (cropping) return {
3332
+ ...committed,
3333
+ base: {
3334
+ ...committed.base,
3335
+ crop: null
3336
+ }
3337
+ };
3338
+ return editorState.preview ?? committed;
3339
+ }, [
3340
+ snapshot.plan,
3341
+ cropping,
3342
+ editorState.preview
3343
+ ]);
3344
+ useEffect(() => {
3345
+ if (!frame) return;
3346
+ const canvas = document.createElement("canvas");
3347
+ canvas.className = "hm-image-stage-canvas";
3348
+ canvas.setAttribute("role", "img");
3349
+ frame.append(canvas);
3350
+ canvasRef.current = canvas;
3351
+ const renderer = createImageRenderer(engine);
3352
+ const current = {
3353
+ renderer,
3354
+ attached: renderer.attach(canvas),
3355
+ failed: false
3356
+ };
3357
+ current.attached.catch(() => {
3358
+ current.failed = true;
3359
+ });
3360
+ rendererRef.current = current;
3361
+ return () => {
3362
+ rendererRef.current = void 0;
3363
+ canvasRef.current = null;
3364
+ renderer.destroy();
3365
+ canvas.remove();
3366
+ };
3367
+ }, [engine, frame]);
3368
+ const composition = plan && source ? compositionSize(plan, source) : void 0;
3369
+ const shownWidth = composition?.width;
3370
+ const shownHeight = composition?.height;
3371
+ useEffect(() => {
3372
+ const canvas = frame ? canvasRef.current : null;
3373
+ if (!canvas) return;
3374
+ canvas.hidden = shownWidth === void 0 || shownHeight === void 0;
3375
+ if (shownWidth !== void 0 && shownHeight !== void 0) canvas.setAttribute("aria-label", messages.t("editor.preview", {
3376
+ width: shownWidth,
3377
+ height: shownHeight
3378
+ }));
3379
+ else canvas.removeAttribute("aria-label");
3380
+ }, [
3381
+ shownWidth,
3382
+ shownHeight,
3383
+ messages,
3384
+ frame
3385
+ ]);
3386
+ useEffect(() => {
3387
+ const current = rendererRef.current;
3388
+ if (!current || !plan || !size || size.width < 1 || size.height < 1) return;
3389
+ const { renderer } = current;
3390
+ if (current.failed && canvasRef.current) {
3391
+ current.failed = false;
3392
+ current.attached = renderer.attach(canvasRef.current);
3393
+ current.attached.catch(() => {
3394
+ current.failed = true;
3395
+ });
3396
+ }
3397
+ current.attached.then(() => renderer.render(plan, {
3398
+ width: size.width,
3399
+ height: size.height,
3400
+ pixelRatio: size.pixelRatio,
3401
+ zoom: view.zoom,
3402
+ pan: view.pan,
3403
+ inset
3404
+ })).catch(() => {});
3405
+ }, [
3406
+ plan,
3407
+ view,
3408
+ size,
3409
+ inset
3410
+ ]);
3411
+ const className = ["hm-image-stage", props.className].filter(Boolean).join(" ");
3412
+ const empty = status === "empty" && !snapshot.opening;
3413
+ const failure = snapshot.error ?? editorState.error;
3414
+ const error = failure ? /* @__PURE__ */ jsx("p", {
3415
+ className: "hm-image-stage-error",
3416
+ role: "alert",
3417
+ children: messages.error(failure)
3418
+ }) : null;
3419
+ return /* @__PURE__ */ jsxs("div", {
3420
+ className,
3421
+ "data-status": status,
3422
+ children: [
3423
+ /* @__PURE__ */ jsx("div", {
3424
+ className: "hm-image-stage-frame",
3425
+ ref: setFrame
3426
+ }),
3427
+ cropping && snapshot.plan && source && size ? /* @__PURE__ */ jsx("div", {
3428
+ className: "hm-image-stage-overlay",
3429
+ children: /* @__PURE__ */ jsx(CropFrame, {
3430
+ plan: snapshot.plan,
3431
+ source,
3432
+ view: {
3433
+ width: size.width,
3434
+ height: size.height,
3435
+ pixelRatio: 1,
3436
+ zoom: view.zoom,
3437
+ pan: view.pan,
3438
+ inset
3439
+ }
3440
+ })
3441
+ }) : null,
3442
+ redacting && plan && source && size ? /* @__PURE__ */ jsx("div", {
3443
+ className: "hm-image-stage-overlay",
3444
+ children: /* @__PURE__ */ jsx(RedactOverlay, {
3445
+ plan,
3446
+ source,
3447
+ view: {
3448
+ width: size.width,
3449
+ height: size.height,
3450
+ pixelRatio: 1,
3451
+ zoom: view.zoom,
3452
+ pan: view.pan,
3453
+ inset
3454
+ }
3455
+ })
3456
+ }) : null,
3457
+ layering && plan && source && size ? /* @__PURE__ */ jsx("div", {
3458
+ className: "hm-image-stage-overlay",
3459
+ children: /* @__PURE__ */ jsx(LayersOverlay, {
3460
+ plan,
3461
+ source,
3462
+ view: {
3463
+ width: size.width,
3464
+ height: size.height,
3465
+ pixelRatio: 1,
3466
+ zoom: view.zoom,
3467
+ pan: view.pan,
3468
+ inset
3469
+ }
3470
+ })
3471
+ }) : null,
3472
+ empty ? /* @__PURE__ */ jsxs(FileDropZone, {
3473
+ className: "hm-image-stage-drop",
3474
+ accept: "image/*",
3475
+ onFiles: (files) => {
3476
+ const [file] = files;
3477
+ if (file) opener.open(file);
3478
+ },
3479
+ buttonLabel: messages.t("editor.choose"),
3480
+ hint: messages.t("editor.dropHint"),
3481
+ children: [/* @__PURE__ */ jsx("p", {
3482
+ className: "hm-image-stage-empty",
3483
+ children: messages.t("editor.empty")
3484
+ }), error]
3485
+ }) : null,
3486
+ snapshot.opening || snapshot.inserting ? /* @__PURE__ */ jsxs("div", {
3487
+ className: "hm-image-stage-opening",
3488
+ children: [/* @__PURE__ */ jsx(Spinner, { label: messages.t(snapshot.opening ? "editor.opening" : "editor.inserting") }), /* @__PURE__ */ jsx(Button, {
3489
+ variant: "secondary",
3490
+ onClick: () => snapshot.opening ? opener.cancel() : inserter.cancel(),
3491
+ children: messages.t("editor.cancel")
3492
+ })]
3493
+ }) : null,
3494
+ empty ? null : /* @__PURE__ */ jsxs("div", {
3495
+ className: "hm-image-stage-foot",
3496
+ children: [/* @__PURE__ */ jsx(StageNotices, {}), error]
3497
+ })
3498
+ ]
3499
+ });
3500
+ }
3501
+ // src/react/toolbar/ImageToolbar.tsx
3502
+ function ImageToolbar(props) {
3503
+ const { registry, shortcuts, context, icons } = props;
3504
+ const messages = useImageMessages();
3505
+ const snapshot = useImageDocument();
3506
+ const [editor] = useImageEditorState();
3507
+ const state = {
3508
+ snapshot,
3509
+ editor
3510
+ };
3511
+ const t = messages.t;
3512
+ return /* @__PURE__ */ jsx(Toolbar, {
3513
+ label: messages.t("toolbar.label"),
3514
+ className: props.className,
3515
+ children: registry.toolbar.map((group) => /* @__PURE__ */ jsx(ToolbarGroup, {
3516
+ label: t(`toolbar.groups.${group[0]?.group ?? "other"}`),
3517
+ children: group.filter((tool) => tool.isAvailable?.(state) ?? true).map((tool) => {
3518
+ const Icon = icons[tool.icon];
3519
+ const keys = shortcuts?.ariaKeyShortcuts(tool.id);
3520
+ return /* @__PURE__ */ jsx(IconButton, {
3521
+ "data-tool": tool.id,
3522
+ label: t(tool.label),
3523
+ icon: Icon ? /* @__PURE__ */ jsx(Icon, {}) : null,
3524
+ disabled: !(tool.isEnabled?.(state) ?? true),
3525
+ ...tool.isActive ? { pressed: tool.isActive(state) } : {},
3526
+ ...keys ? { "aria-keyshortcuts": keys } : {},
3527
+ onClick: () => void tool.run(context)
3528
+ }, tool.id);
3529
+ })
3530
+ }, group.map((tool) => tool.id).join(" ")))
3531
+ });
3532
+ }
3533
+ // src/react/toolbar/icons.tsx
3534
+ var imageIcons = {
3535
+ open: OpenIcon,
3536
+ undo: UndoIcon,
3537
+ redo: RedoIcon,
3538
+ "rotate-left": RotateLeftIcon,
3539
+ "rotate-right": RotateRightIcon,
3540
+ "zoom-in": ZoomInIcon,
3541
+ "zoom-out": ZoomOutIcon,
3542
+ fit: FitIcon,
3543
+ crop: CropIcon,
3544
+ redact: RedactIcon,
3545
+ layers: LayersIcon,
3546
+ text: TextIcon,
3547
+ rectangle: RectangleIcon,
3548
+ ellipse: EllipseIcon,
3549
+ "add-image": AddIcon,
3550
+ export: DownloadIcon,
3551
+ "flip-horizontal": FlipHorizontalIcon,
3552
+ "flip-vertical": FlipVerticalIcon,
3553
+ search: SearchIcon
3554
+ };
3555
+ // src/react/editor/ImageEditor.tsx
3556
+ var join = (...names) => names.filter(Boolean).join(" ");
3557
+ function ImageEditorBody(props) {
3558
+ const { initialFile, onChange, classNames = {}, unstyled = false, handle, events } = props;
3559
+ const { engine, session, messages, view, editor, opener, inserter } = useImageInternals();
3560
+ const snapshot = useImageDocument();
3561
+ const announce = useAnnounce();
3562
+ const root = useRef(null);
3563
+ const input = useRef(null);
3564
+ const layerInput = useRef(null);
3565
+ const latestOnChange = useRef(onChange);
3566
+ latestOnChange.current = onChange;
3567
+ const exportOn = props.features?.export !== false;
3568
+ const registry = useMemo(() => {
3569
+ const wanted = (id) => (!props.tools || props.tools.includes(id)) && (exportOn || id !== "image.export");
3570
+ const tools = props.tools ?? imageTools.map((tool) => tool.id);
3571
+ return createToolRegistry(imageTools, {
3572
+ tools: tools.filter(wanted),
3573
+ toolbar: (props.toolbar ?? DEFAULT_TOOLBAR).map((group) => group.filter(wanted)).filter((group) => group.length > 0)
3574
+ });
3575
+ }, [
3576
+ props.tools,
3577
+ props.toolbar,
3578
+ exportOn
3579
+ ]);
3580
+ const platform = usePlatform();
3581
+ const shortcuts = useMemo(() => createShortcutRegistry({
3582
+ platform,
3583
+ tools: registry.tools
3584
+ }), [platform, registry]);
3585
+ const context = useMemo(() => ({
3586
+ session,
3587
+ view,
3588
+ editor,
3589
+ chooseFile: () => input.current?.click(),
3590
+ chooseLayerImage: () => layerInput.current?.click()
3591
+ }), [
3592
+ session,
3593
+ view,
3594
+ editor
3595
+ ]);
3596
+ const icons = useMemo(() => ({
3597
+ ...imageIcons,
3598
+ ...props.icons
3599
+ }), [props.icons]);
3600
+ useImperativeHandle(handle, () => ({
3601
+ session,
3602
+ open: async (file) => {
3603
+ engineInternals(engine)?.check();
3604
+ await opener.open(file);
3605
+ },
3606
+ insertImage: async (file) => {
3607
+ engineInternals(engine)?.check();
3608
+ await inserter.insert(file);
3609
+ },
3610
+ execute: (commands) => session.execute(commands),
3611
+ export: (format) => session.export(format),
3612
+ undo: () => {
3613
+ session.undo();
3614
+ },
3615
+ redo: () => {
3616
+ session.redo();
3617
+ }
3618
+ }), [
3619
+ engine,
3620
+ session,
3621
+ opener,
3622
+ inserter
3623
+ ]);
3624
+ const initial = useRef(initialFile);
3625
+ useEffect(() => {
3626
+ if (initial.current) opener.open(initial.current);
3627
+ }, [opener]);
3628
+ useEffect(() => {
3629
+ let before = session.getSnapshot().plan;
3630
+ return session.subscribe(() => {
3631
+ const after = session.getSnapshot().plan;
3632
+ if (after === before) return;
3633
+ before = after;
3634
+ if (after) latestOnChange.current?.(after);
3635
+ });
3636
+ }, [session]);
3637
+ useEffect(() => {
3638
+ events.current = (event) => {
3639
+ if (event.outcome !== "done") return;
3640
+ const action = event.commands[0];
3641
+ const name = action ? messages.t(`actions.${action}`) : "";
3642
+ if (event.type === "undo") announce(messages.t("editor.undid", { action: name }));
3643
+ if (event.type === "redo") announce(messages.t("editor.redid", { action: name }));
3644
+ if (event.type === "open") {
3645
+ const source = session.getSnapshot().source;
3646
+ if (source) announce(messages.t("editor.opened", {
3647
+ width: source.width,
3648
+ height: source.height
3649
+ }));
3650
+ }
3651
+ };
3652
+ return () => {
3653
+ events.current = void 0;
3654
+ };
3655
+ }, [
3656
+ announce,
3657
+ events,
3658
+ messages,
3659
+ session
3660
+ ]);
3661
+ const previous = useRef(snapshot.source?.id);
3662
+ useEffect(() => {
3663
+ const id = snapshot.source?.id;
3664
+ if (id === previous.current) return;
3665
+ previous.current = id;
3666
+ if (!id) return;
3667
+ const active = document.activeElement;
3668
+ if (!(active === null || active === document.body || root.current?.contains(active))) return;
3669
+ [...root.current?.querySelectorAll(".hm-image-editor-toolbar button:not([disabled])") ?? []].find((button) => button.dataset["tool"] !== "image.open")?.focus();
3670
+ }, [snapshot.source?.id]);
3671
+ const hostPlan = props.plan;
3672
+ const openSource = snapshot.plan?.base.source;
3673
+ useEffect(() => {
3674
+ if (!hostPlan || openSource !== hostPlan.base.source) return;
3675
+ try {
3676
+ session.applyPlan(hostPlan);
3677
+ } catch {}
3678
+ }, [
3679
+ hostPlan,
3680
+ session,
3681
+ openSource
3682
+ ]);
3683
+ const sourceId = snapshot.source?.id;
3684
+ useEffect(() => {
3685
+ if (sourceId === void 0) return;
3686
+ editor.set((state) => state.tool === null && state.dialog === null && state.error === null ? state : {
3687
+ ...state,
3688
+ tool: null,
3689
+ crop: null,
3690
+ redact: null,
3691
+ layers: null,
3692
+ preview: null,
3693
+ dialog: null,
3694
+ error: null
3695
+ });
3696
+ }, [editor, sourceId]);
3697
+ const [{ tool }] = useImageEditorState();
3698
+ const returnTo = useRef(null);
3699
+ const previousTool = useRef(tool);
3700
+ useEffect(() => editor.subscribe(() => {
3701
+ const next = editor.getSnapshot().tool;
3702
+ if (next !== null && previousTool.current !== next) {
3703
+ const active = document.activeElement;
3704
+ returnTo.current = active instanceof HTMLElement && root.current?.contains(active) ? active : null;
3705
+ }
3706
+ }), [editor]);
3707
+ useEffect(() => {
3708
+ if (previousTool.current === tool) return;
3709
+ const was = previousTool.current;
3710
+ previousTool.current = tool;
3711
+ if (tool === "redact") {
3712
+ root.current?.querySelector(".hm-image-redact-add")?.focus();
3713
+ return;
3714
+ }
3715
+ if (tool === "layers") return;
3716
+ if (was === null || tool !== null) return;
3717
+ (returnTo.current?.isConnected ? returnTo.current : root.current?.querySelector(`[data-tool="image.${was}"]`))?.focus();
3718
+ }, [tool]);
3719
+ const onKeyDown = (event) => {
3720
+ if (engineInternals(engine)?.getSnapshot()) return;
3721
+ const id = shortcuts.match(event.nativeEvent, { root: event.currentTarget });
3722
+ const tool = id ? registry.get(id) : void 0;
3723
+ if (!tool) return;
3724
+ const state = {
3725
+ snapshot: session.getSnapshot(),
3726
+ editor: editor.getSnapshot()
3727
+ };
3728
+ if (!(tool.isEnabled?.(state) ?? true)) return;
3729
+ event.preventDefault();
3730
+ tool.run(context);
3731
+ };
3732
+ return /* @__PURE__ */ jsx("section", {
3733
+ ref: root,
3734
+ className: join("hm-image-editor", !unstyled && "hm-image-editor--styled", props.className, classNames.root),
3735
+ onKeyDown,
3736
+ "aria-label": messages.t("editor.label"),
3737
+ ...props.theme ? { "data-hm-theme": props.theme } : {},
3738
+ children: /* @__PURE__ */ jsxs(EngineBoundary, { children: [
3739
+ /* @__PURE__ */ jsx("input", {
3740
+ ref: input,
3741
+ type: "file",
3742
+ accept: "image/*",
3743
+ hidden: true,
3744
+ tabIndex: -1,
3745
+ onChange: (event) => {
3746
+ const file = event.currentTarget.files?.[0];
3747
+ event.currentTarget.value = "";
3748
+ if (file) opener.open(file);
3749
+ }
3750
+ }),
3751
+ /* @__PURE__ */ jsx("input", {
3752
+ ref: layerInput,
3753
+ type: "file",
3754
+ accept: "image/*",
3755
+ hidden: true,
3756
+ tabIndex: -1,
3757
+ onChange: (event) => {
3758
+ const file = event.currentTarget.files?.[0];
3759
+ event.currentTarget.value = "";
3760
+ if (file) inserter.insert(file);
3761
+ }
3762
+ }),
3763
+ /* @__PURE__ */ jsxs("div", {
3764
+ className: "hm-image-editor-layout",
3765
+ children: [
3766
+ /* @__PURE__ */ jsx(ImageToolbar, {
3767
+ registry,
3768
+ shortcuts,
3769
+ context,
3770
+ icons,
3771
+ className: join("hm-image-editor-toolbar", classNames.toolbar)
3772
+ }),
3773
+ /* @__PURE__ */ jsx(ImageStage, { className: join("hm-image-editor-stage", classNames.stage) }),
3774
+ /* @__PURE__ */ jsx("div", {
3775
+ className: join("hm-image-editor-inspector", classNames.inspector),
3776
+ children: /* @__PURE__ */ jsx(ImageInspector, { ...props.features ? { features: props.features } : {} })
3777
+ })
3778
+ ]
3779
+ }),
3780
+ exportOn ? /* @__PURE__ */ jsx(ImageExportDialog, { ...props.onExport ? { onExport: props.onExport } : {} }) : null
3781
+ ] })
3782
+ });
3783
+ }
3784
+ var ImageEditor = forwardRef(function ImageEditor(props, ref) {
3785
+ const { initialFile, plan, onChange, tools, toolbar, icons, className, classNames, unstyled, onEvent, onExport, features, theme, ...provider } = props;
3786
+ const events = useRef(void 0);
3787
+ const latestOnEvent = useRef(onEvent);
3788
+ latestOnEvent.current = onEvent;
3789
+ const [onSessionEvent] = useMemo(() => [(event) => {
3790
+ events.current?.(event);
3791
+ latestOnEvent.current?.(event);
3792
+ }], []);
3793
+ return /* @__PURE__ */ jsx(ImageProvider, {
3794
+ ...provider,
3795
+ onEvent: onSessionEvent,
3796
+ boundary: false,
3797
+ children: /* @__PURE__ */ jsx(AnnouncerProvider, { children: /* @__PURE__ */ jsx(ImageEditorBody, {
3798
+ handle: ref,
3799
+ events,
3800
+ ...initialFile ? { initialFile } : {},
3801
+ ...onChange ? { onChange } : {},
3802
+ ...plan ? { plan } : {},
3803
+ ...tools ? { tools } : {},
3804
+ ...toolbar ? { toolbar } : {},
3805
+ ...icons ? { icons } : {},
3806
+ ...className ? { className } : {},
3807
+ ...classNames ? { classNames } : {},
3808
+ ...unstyled === void 0 ? {} : { unstyled },
3809
+ ...onExport ? { onExport } : {},
3810
+ ...features ? { features } : {},
3811
+ ...theme ? { theme } : {}
3812
+ }) })
3813
+ });
3814
+ });
3815
+ export { useImageMessages as _, ImageInfoPanel as a, imageTools as b, ImageRedactPanel as c, imageEditorMessages as d, ImageExportDialog as f, useImageEditorState as g, useImageDocument as h, ImageStage as i, ImageLayersPanel as l, ImageCropPanel as m, imageIcons as n, ImageFilterPanel as o, ExportListenerContext as p, ImageToolbar as r, ImageAdjustPanel as s, ImageEditor as t, ImageEditorProvider as u, useImageSession as v, useImageView as y };
3816
+
3817
+ //# sourceMappingURL=editor-Bjv32UmV.js.map