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