@hussmartinez/image-sdk 0.3.0 → 0.4.0

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