gradio-pr-bot commited on
Commit
aa7b679
·
verified ·
1 Parent(s): 989ceec

Upload folder using huggingface_hub

Browse files
Files changed (34) hide show
  1. 6.26.1/imageeditor/Example.svelte +50 -0
  2. 6.26.1/imageeditor/Index.svelte +210 -0
  3. 6.26.1/imageeditor/InteractiveImageEditor.svelte +351 -0
  4. 6.26.1/imageeditor/package.json +48 -0
  5. 6.26.1/imageeditor/shared/Anchor.svelte +386 -0
  6. 6.26.1/imageeditor/shared/Controls.svelte +275 -0
  7. 6.26.1/imageeditor/shared/IconButton.svelte +172 -0
  8. 6.26.1/imageeditor/shared/ImageEditor.svelte +987 -0
  9. 6.26.1/imageeditor/shared/Layers.svelte +296 -0
  10. 6.26.1/imageeditor/shared/Resize.svelte +245 -0
  11. 6.26.1/imageeditor/shared/SecondaryToolbar.svelte +83 -0
  12. 6.26.1/imageeditor/shared/Toolbar.svelte +367 -0
  13. 6.26.1/imageeditor/shared/brush/BrushOptions.svelte +217 -0
  14. 6.26.1/imageeditor/shared/brush/BrushSize.svelte +43 -0
  15. 6.26.1/imageeditor/shared/brush/ColorField.svelte +179 -0
  16. 6.26.1/imageeditor/shared/brush/ColorPicker.svelte +289 -0
  17. 6.26.1/imageeditor/shared/brush/ColorSwatch.svelte +273 -0
  18. 6.26.1/imageeditor/shared/brush/brush-cursor.ts +366 -0
  19. 6.26.1/imageeditor/shared/brush/brush-textures.ts +757 -0
  20. 6.26.1/imageeditor/shared/brush/brush-utils.ts +76 -0
  21. 6.26.1/imageeditor/shared/brush/brush.ts +479 -0
  22. 6.26.1/imageeditor/shared/brush/types.ts +41 -0
  23. 6.26.1/imageeditor/shared/core/commands.ts +134 -0
  24. 6.26.1/imageeditor/shared/core/editor.ts +932 -0
  25. 6.26.1/imageeditor/shared/core/layers.ts +1092 -0
  26. 6.26.1/imageeditor/shared/crop/crop.ts +1027 -0
  27. 6.26.1/imageeditor/shared/image/image.ts +420 -0
  28. 6.26.1/imageeditor/shared/resize/resize.ts +1767 -0
  29. 6.26.1/imageeditor/shared/types.ts +29 -0
  30. 6.26.1/imageeditor/shared/utils/events.ts +30 -0
  31. 6.26.1/imageeditor/shared/utils/parse_placeholder.ts +27 -0
  32. 6.26.1/imageeditor/shared/utils/pixi.ts +71 -0
  33. 6.26.1/imageeditor/shared/zoom/zoom.ts +675 -0
  34. 6.26.1/imageeditor/types.ts +74 -0
6.26.1/imageeditor/Example.svelte ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { BaseImage as Image } from "@gradio/image";
3
+ import type { EditorData } from "./InteractiveImageEditor.svelte";
4
+
5
+ let {
6
+ value,
7
+ type,
8
+ selected = false
9
+ }: {
10
+ value: EditorData;
11
+ type: "gallery" | "table";
12
+ selected?: boolean;
13
+ } = $props();
14
+ </script>
15
+
16
+ <div
17
+ class="container"
18
+ class:table={type === "table"}
19
+ class:gallery={type === "gallery"}
20
+ class:selected
21
+ >
22
+ <Image src={value.composite?.url || value.background?.url} alt="" />
23
+ </div>
24
+
25
+ <style>
26
+ .container :global(img) {
27
+ width: 100%;
28
+ height: 100%;
29
+ }
30
+
31
+ .container.selected {
32
+ border-color: var(--border-color-accent);
33
+ }
34
+
35
+ .container.table {
36
+ margin: 0 auto;
37
+ border: 2px solid var(--border-color-primary);
38
+ border-radius: var(--radius-lg);
39
+ width: var(--size-20);
40
+ height: var(--size-20);
41
+ object-fit: cover;
42
+ }
43
+
44
+ .container.gallery {
45
+ border: 2px solid var(--border-color-primary);
46
+ height: var(--size-20);
47
+ max-height: var(--size-20);
48
+ object-fit: cover;
49
+ }
50
+ </style>
6.26.1/imageeditor/Index.svelte ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { ImageBlobs } from "./InteractiveImageEditor.svelte";
3
+
4
+ import { FileData } from "@gradio/client";
5
+
6
+ import { BaseStaticImage as StaticImage } from "@gradio/image";
7
+ import InteractiveImageEditor from "./InteractiveImageEditor.svelte";
8
+ import { Block } from "@gradio/atoms";
9
+ import { StatusTracker } from "@gradio/statustracker";
10
+
11
+ import { Gradio, type ShareData } from "@gradio/utils";
12
+ import type { ImageEditorEvents, ImageEditorProps } from "./types";
13
+
14
+ let props = $props();
15
+
16
+ class ImageEditorGradio extends Gradio<ImageEditorEvents, ImageEditorProps> {
17
+ async get_data() {
18
+ const data = await super.get_data();
19
+ const value = await _get_value();
20
+ return { ...data, value: value };
21
+ }
22
+ }
23
+ const gradio = new ImageEditorGradio(props, {
24
+ server: { accept_blobs: () => {} },
25
+ buttons: [],
26
+ height: 350,
27
+ border_region: 0
28
+ });
29
+
30
+ let editor_instance: InteractiveImageEditor;
31
+ let image_id: null | string = $state(null);
32
+
33
+ let has_run_change = false;
34
+ let has_run_input = false;
35
+
36
+ async function _get_value(): Promise<ImageBlobs | { id: string }> {
37
+ if (image_id) {
38
+ const val = { id: image_id };
39
+ image_id = null;
40
+ return val;
41
+ }
42
+
43
+ const blobs = await editor_instance.get_data();
44
+
45
+ return blobs;
46
+ }
47
+
48
+ let is_dragging = $state(false);
49
+
50
+ const is_browser = typeof window !== "undefined";
51
+
52
+ // function handle_change(): void {
53
+ // if (gradio.props.value) gradio.dispatch("change");
54
+ // }
55
+
56
+ function handle_save(): void {
57
+ gradio.dispatch("apply");
58
+ }
59
+
60
+ // function handle_history_change(): void {
61
+ // gradio.dispatch("change");
62
+
63
+ // gradio.dispatch("input");
64
+ // }
65
+
66
+ let has_value = $derived(
67
+ gradio.props.value?.background ||
68
+ gradio.props.value?.layers?.length ||
69
+ gradio.props.value?.composite
70
+ );
71
+
72
+ let normalised_background = $derived(
73
+ gradio.props.value?.background
74
+ ? new FileData(gradio.props.value.background)
75
+ : null
76
+ );
77
+ let normalised_composite = $derived(
78
+ gradio.props.value?.composite
79
+ ? new FileData(gradio.props.value.composite)
80
+ : null
81
+ );
82
+ let normalised_layers = $derived(
83
+ gradio.props.value?.layers?.map((layer) => new FileData(layer)) || []
84
+ );
85
+ let resolved_theme_mode: "dark" | "light" = $derived(
86
+ gradio.shared.theme_mode === "dark" ||
87
+ (gradio.shared.theme_mode === "system" &&
88
+ typeof window !== "undefined" &&
89
+ window.matchMedia?.("(prefers-color-scheme: dark)").matches)
90
+ ? "dark"
91
+ : "light"
92
+ );
93
+ </script>
94
+
95
+ {#if !gradio.shared.interactive}
96
+ <Block
97
+ visible={gradio.shared.visible}
98
+ variant={"solid"}
99
+ border_mode={is_dragging ? "focus" : "base"}
100
+ padding={false}
101
+ elem_id={gradio.shared.elem_id}
102
+ elem_classes={gradio.shared.elem_classes}
103
+ height={gradio.props.height}
104
+ width={gradio.props.width}
105
+ allow_overflow={true}
106
+ overflow_behavior="visible"
107
+ container={gradio.shared.container}
108
+ scale={gradio.shared.scale}
109
+ min_width={gradio.shared.min_width}
110
+ >
111
+ <StatusTracker
112
+ autoscroll={gradio.shared.autoscroll}
113
+ i18n={gradio.i18n}
114
+ {...gradio.shared.loading_status}
115
+ on_clear_status={() =>
116
+ gradio.dispatch("clear_status", gradio.shared.loading_status)}
117
+ />
118
+ <StaticImage
119
+ onselect={(detail) => gradio.dispatch("select", detail)}
120
+ onshare={(detail) => gradio.dispatch("share", detail as ShareData)}
121
+ onerror={(detail) => gradio.dispatch("error", detail)}
122
+ value={gradio.props.value?.composite || null}
123
+ label={gradio.shared.label}
124
+ show_label={gradio.shared.show_label}
125
+ buttons={gradio.props.buttons ?? []}
126
+ selectable={gradio.props._selectable}
127
+ i18n={gradio.i18n}
128
+ />
129
+ </Block>
130
+ {:else}
131
+ <Block
132
+ visible={gradio.shared.visible}
133
+ variant={has_value ? "solid" : "dashed"}
134
+ border_mode={is_dragging ? "focus" : "base"}
135
+ padding={false}
136
+ elem_id={gradio.shared.elem_id}
137
+ elem_classes={gradio.shared.elem_classes}
138
+ height={gradio.props.height}
139
+ width={gradio.props.width}
140
+ allow_overflow={true}
141
+ overflow_behavior="visible"
142
+ container={gradio.shared.container}
143
+ scale={gradio.shared.scale}
144
+ min_width={gradio.shared.min_width}
145
+ >
146
+ <StatusTracker
147
+ autoscroll={gradio.shared.autoscroll}
148
+ i18n={gradio.i18n}
149
+ {...gradio.shared.loading_status}
150
+ on_clear_status={() =>
151
+ gradio.dispatch("clear_status", gradio.shared.loading_status)}
152
+ />
153
+
154
+ <InteractiveImageEditor
155
+ border_region={gradio.props.border_region ?? 0}
156
+ bind:is_dragging
157
+ canvas_size={gradio.props.canvas_size ?? [800, 800]}
158
+ bind:image_id
159
+ layers={normalised_layers}
160
+ composite={normalised_composite}
161
+ background={normalised_background}
162
+ bind:this={editor_instance}
163
+ root={gradio.shared.root}
164
+ sources={gradio.props.sources ?? ["upload", "webcam", "clipboard"]}
165
+ label={gradio.shared.label}
166
+ show_label={gradio.shared.show_label}
167
+ fixed_canvas={gradio.props.fixed_canvas}
168
+ oninput={() => {
169
+ if (!has_run_input) {
170
+ has_run_input = true;
171
+ } else {
172
+ gradio.dispatch("input");
173
+ }
174
+ }}
175
+ onsave={() => handle_save()}
176
+ onclear={() => gradio.dispatch("clear")}
177
+ onupload={() => gradio.dispatch("upload")}
178
+ onreceive_null={() =>
179
+ (gradio.props.value = {
180
+ background: null,
181
+ layers: [],
182
+ composite: null
183
+ })}
184
+ onchange={() => {
185
+ if (!has_run_change) {
186
+ has_run_change = true;
187
+ } else {
188
+ gradio.dispatch("change");
189
+ }
190
+ }}
191
+ brush={gradio.props.brush ?? false}
192
+ eraser={gradio.props.eraser ?? false}
193
+ changeable={gradio.shared.attached_events?.includes("apply") ?? false}
194
+ realtime={gradio.shared.attached_events?.includes("change") ||
195
+ gradio.shared.attached_events?.includes("input")}
196
+ i18n={gradio.i18n}
197
+ transforms={gradio.props.transforms ?? []}
198
+ accept_blobs={gradio.shared.server.accept_blobs}
199
+ layer_options={gradio.props.layers!}
200
+ upload={(...args) => gradio.shared.client.upload(...args)}
201
+ placeholder={gradio.props.placeholder}
202
+ webcam_options={gradio.props.webcam_options!}
203
+ show_download_button={gradio.props.buttons === null
204
+ ? true
205
+ : (gradio.props.buttons ?? []).includes("download")}
206
+ theme_mode={resolved_theme_mode}
207
+ ondownload_error={(detail) => gradio.dispatch("error", detail)}
208
+ ></InteractiveImageEditor>
209
+ </Block>
210
+ {/if}
6.26.1/imageeditor/InteractiveImageEditor.svelte ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script module lang="ts">
2
+ export interface EditorData {
3
+ background: FileData | null;
4
+ layers: FileData[] | null;
5
+ composite: FileData | null;
6
+ }
7
+
8
+ export interface ImageBlobs {
9
+ background: FileData | null;
10
+ layers: FileData[];
11
+ composite: FileData | null;
12
+ }
13
+ </script>
14
+
15
+ <script lang="ts">
16
+ import { type I18nFormatter } from "@gradio/utils";
17
+ import { prepare_files, type FileData, type Client } from "@gradio/client";
18
+ import { type CommandNode } from "./shared/core/commands";
19
+ import ImageEditor from "./shared/ImageEditor.svelte";
20
+ import { type Brush as IBrush, type Eraser } from "./shared/brush/types";
21
+ import { type Tool as ToolbarTool } from "./shared/Toolbar.svelte";
22
+
23
+ import { BlockLabel } from "@gradio/atoms";
24
+ import { Image as ImageIcon } from "@gradio/icons";
25
+ import { inject } from "./shared/utils/parse_placeholder";
26
+ import {
27
+ type LayerOptions,
28
+ type Transform,
29
+ type Source,
30
+ type WebcamOptions
31
+ } from "./shared/types";
32
+
33
+ let {
34
+ brush,
35
+ eraser,
36
+ sources,
37
+ i18n,
38
+ root,
39
+ label = undefined,
40
+ show_label,
41
+ changeable = false,
42
+ theme_mode,
43
+ layers,
44
+ composite,
45
+ background,
46
+ layer_options = {
47
+ allow_additional_layers: true,
48
+ layers: [],
49
+ disabled: false
50
+ },
51
+ transforms,
52
+ accept_blobs,
53
+ canvas_size,
54
+ fixed_canvas = false,
55
+ realtime = false,
56
+ upload,
57
+ is_dragging = $bindable(),
58
+ placeholder = undefined,
59
+ border_region,
60
+ full_history = $bindable(null),
61
+ webcam_options = { mirror: true, constraints: {} },
62
+ show_download_button = false,
63
+ image_id = $bindable(null),
64
+ onclear,
65
+ onupload,
66
+ onchange,
67
+ oninput,
68
+ onsave,
69
+ onreceive_null,
70
+ ondownload_error
71
+ }: {
72
+ brush: IBrush | false;
73
+ eraser: Eraser | false;
74
+ sources: Source[];
75
+ i18n: I18nFormatter;
76
+ root: string;
77
+ label?: string;
78
+ show_label: boolean;
79
+ changeable?: boolean;
80
+ theme_mode: "dark" | "light";
81
+ layers: FileData[];
82
+ composite: FileData | null;
83
+ background: FileData | null;
84
+ layer_options?: LayerOptions;
85
+ transforms: Transform[];
86
+ accept_blobs: (a: any) => void;
87
+ canvas_size: [number, number];
88
+ fixed_canvas?: boolean;
89
+ realtime?: boolean;
90
+ upload: Client["upload"];
91
+ is_dragging?: boolean;
92
+ placeholder?: string;
93
+ border_region: number;
94
+ full_history?: CommandNode | null;
95
+ webcam_options?: WebcamOptions;
96
+ show_download_button?: boolean;
97
+ image_id?: null | string;
98
+ onclear?: () => void;
99
+ onupload?: () => void;
100
+ onchange?: () => void;
101
+ oninput?: () => void;
102
+ onsave?: () => void;
103
+ onreceive_null?: () => void;
104
+ ondownload_error?: (error: string) => void;
105
+ } = $props();
106
+
107
+ let editor: ImageEditor;
108
+ let has_drawn = $state(false);
109
+
110
+ function is_not_null(o: Blob | null): o is Blob {
111
+ return !!o;
112
+ }
113
+
114
+ function is_file_data(o: null | FileData): o is FileData {
115
+ return !!o;
116
+ }
117
+
118
+ $effect(() => {
119
+ if (background_image) onupload?.();
120
+ });
121
+
122
+ export async function get_data(): Promise<ImageBlobs> {
123
+ let blobs;
124
+ try {
125
+ blobs = await editor.get_blobs();
126
+ } catch (e) {
127
+ return { background: null, layers: [], composite: null };
128
+ }
129
+
130
+ const bg = blobs.background
131
+ ? upload(
132
+ await prepare_files([new File([blobs.background], "background.png")]),
133
+ root
134
+ )
135
+ : Promise.resolve(null);
136
+
137
+ const layers = blobs.layers
138
+ .filter(is_not_null)
139
+ .map(async (blob, i) =>
140
+ upload(await prepare_files([new File([blob], `layer_${i}.png`)]), root)
141
+ );
142
+
143
+ const composite = blobs.composite
144
+ ? upload(
145
+ await prepare_files([new File([blobs.composite], "composite.png")]),
146
+ root
147
+ )
148
+ : Promise.resolve(null);
149
+
150
+ const [background, composite_, ...layers_] = await Promise.all([
151
+ bg,
152
+ composite,
153
+ ...layers
154
+ ]);
155
+
156
+ return {
157
+ background: Array.isArray(background) ? background[0] : background,
158
+ layers: layers_
159
+ .flatMap((layer) => (Array.isArray(layer) ? layer : [layer]))
160
+ .filter(is_file_data),
161
+ composite: Array.isArray(composite_) ? composite_[0] : composite_
162
+ };
163
+ }
164
+
165
+ function handle_value(value: EditorData | null): void {
166
+ if (!editor) return;
167
+ if (value == null) {
168
+ editor.handle_remove();
169
+ onreceive_null?.();
170
+ }
171
+ }
172
+
173
+ $effect(() => {
174
+ handle_value({ layers, composite, background });
175
+ });
176
+
177
+ let background_image = $state(false);
178
+ let can_undo = $state(false);
179
+
180
+ type BinaryImages = [string, string, File, number | null][];
181
+
182
+ function nextframe(): Promise<void> {
183
+ return new Promise((resolve) => setTimeout(() => resolve(), 30));
184
+ }
185
+
186
+ let uploading = $state(false);
187
+ let pending = $state(false);
188
+ async function handle_change(): Promise<void> {
189
+ if (!realtime) return;
190
+ if (uploading) {
191
+ pending = true;
192
+ return;
193
+ }
194
+ uploading = true;
195
+ await nextframe();
196
+ const blobs = await editor.get_blobs();
197
+ const images: BinaryImages = [];
198
+ let id = Math.random().toString(36).substring(2);
199
+ if (blobs.background)
200
+ images.push([
201
+ id,
202
+ "background",
203
+ new File([blobs.background], "background.png"),
204
+ null
205
+ ]);
206
+ if (blobs.composite)
207
+ images.push([
208
+ id,
209
+ "composite",
210
+ new File([blobs.composite], "composite.png"),
211
+ null
212
+ ]);
213
+ blobs.layers.forEach((layer, i) => {
214
+ if (layer)
215
+ images.push([
216
+ id as string,
217
+ `layer`,
218
+ new File([layer], `layer_${i}.png`),
219
+ i
220
+ ]);
221
+ });
222
+ await Promise.all(
223
+ images.map(async ([image_id, type, data, index]) => {
224
+ return accept_blobs({
225
+ binary: true,
226
+ data: { file: data, id: image_id, type, index }
227
+ });
228
+ })
229
+ );
230
+ image_id = id;
231
+ onchange?.();
232
+ await nextframe();
233
+ uploading = false;
234
+ if (pending) {
235
+ pending = false;
236
+ uploading = false;
237
+ handle_change();
238
+ }
239
+ }
240
+
241
+ let placeholder_parts = $derived(
242
+ placeholder ? inject(placeholder) : [false, false]
243
+ );
244
+ let heading = $derived(placeholder_parts[0]);
245
+ let paragraph = $derived(placeholder_parts[1]);
246
+
247
+ let current_tool = $state<ToolbarTool>("image");
248
+ </script>
249
+
250
+ <BlockLabel
251
+ {show_label}
252
+ Icon={ImageIcon}
253
+ label={label || i18n("image.image")}
254
+ />
255
+ <ImageEditor
256
+ {transforms}
257
+ {composite}
258
+ {layers}
259
+ {background}
260
+ {canvas_size}
261
+ bind:this={editor}
262
+ {changeable}
263
+ {onsave}
264
+ {oninput}
265
+ onchange={handle_change}
266
+ onclear={() => onclear?.()}
267
+ {ondownload_error}
268
+ {sources}
269
+ bind:background_image
270
+ bind:current_tool
271
+ brush_options={brush}
272
+ eraser_options={eraser}
273
+ {fixed_canvas}
274
+ {border_region}
275
+ {layer_options}
276
+ {i18n}
277
+ {root}
278
+ {upload}
279
+ bind:is_dragging
280
+ bind:has_drawn
281
+ {webcam_options}
282
+ {show_download_button}
283
+ {theme_mode}
284
+ bind:can_undo
285
+ bind:full_history
286
+ >
287
+ {#if current_tool === "image" && !can_undo}
288
+ <div class="empty wrap">
289
+ {#if sources && sources.length}
290
+ {#if heading || paragraph}
291
+ {#if heading}
292
+ <h2>{heading}</h2>
293
+ {/if}
294
+ {#if paragraph}
295
+ <p>{paragraph}</p>
296
+ {/if}
297
+ {:else}
298
+ <div>Upload an image</div>
299
+ {/if}
300
+ {/if}
301
+
302
+ {#if sources && sources.length && brush && !placeholder}
303
+ <div class="or">or</div>
304
+ {/if}
305
+ {#if brush && !placeholder}
306
+ <div>select the draw tool to start</div>
307
+ {/if}
308
+ </div>
309
+ {/if}
310
+ </ImageEditor>
311
+
312
+ <style>
313
+ h2 {
314
+ font-size: var(--text-xl);
315
+ }
316
+
317
+ p,
318
+ h2 {
319
+ white-space: pre-line;
320
+ }
321
+
322
+ .empty {
323
+ display: flex;
324
+ flex-direction: column;
325
+ justify-content: center;
326
+ align-items: center;
327
+ position: absolute;
328
+ height: 100%;
329
+ width: 100%;
330
+ left: 0;
331
+ right: 0;
332
+ margin: auto;
333
+ z-index: var(--layer-1);
334
+ text-align: center;
335
+ color: var(--color-grey-500) !important;
336
+ cursor: pointer;
337
+ }
338
+
339
+ .wrap {
340
+ display: flex;
341
+ flex-direction: column;
342
+ justify-content: center;
343
+ align-items: center;
344
+ line-height: var(--line-md);
345
+ font-size: var(--text-md);
346
+ }
347
+
348
+ .or {
349
+ color: var(--body-text-color-subdued);
350
+ }
351
+ </style>
6.26.1/imageeditor/package.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@gradio/imageeditor",
3
+ "version": "0.20.1",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "author": "",
7
+ "license": "ISC",
8
+ "private": false,
9
+ "dependencies": {
10
+ "@gradio/atoms": "workspace:^",
11
+ "@gradio/client": "workspace:^",
12
+ "@gradio/icons": "workspace:^",
13
+ "@gradio/image": "workspace:^",
14
+ "@gradio/statustracker": "workspace:^",
15
+ "@gradio/upload": "workspace:^",
16
+ "@gradio/utils": "workspace:^",
17
+ "@types/tinycolor2": "^1.4.6",
18
+ "pixi-filters": "^6.1.4",
19
+ "pixi.js": "^8.14.0",
20
+ "tinycolor2": "^1.6.0"
21
+ },
22
+ "devDependencies": {
23
+ "@gradio/preview": "workspace:^"
24
+ },
25
+ "main_changeset": true,
26
+ "main": "./Index.svelte",
27
+ "exports": {
28
+ ".": {
29
+ "gradio": "./Index.svelte",
30
+ "svelte": "./dist/Index.svelte",
31
+ "types": "./dist/Index.svelte.d.ts"
32
+ },
33
+ "./example": {
34
+ "gradio": "./Example.svelte",
35
+ "svelte": "./dist/Example.svelte",
36
+ "types": "./dist/Example.svelte.d.ts"
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
40
+ "peerDependencies": {
41
+ "svelte": "^5.48.0"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/gradio-app/gradio.git",
46
+ "directory": "js/imageeditor"
47
+ }
48
+ }
6.26.1/imageeditor/shared/Anchor.svelte ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { spring } from "svelte/motion";
3
+ import { Image } from "@gradio/icons";
4
+ import { onMount } from "svelte";
5
+
6
+ const positions = [
7
+ "top-left",
8
+ "top",
9
+ "top-right",
10
+ "left",
11
+ "center",
12
+ "right",
13
+ "bottom-left",
14
+ "bottom",
15
+ "bottom-right"
16
+ ] as const;
17
+ let {
18
+ onposition
19
+ }: {
20
+ onposition?: (position: (typeof positions)[number]) => void;
21
+ } = $props();
22
+
23
+ const spring_opt = {
24
+ stiffness: 0.1,
25
+ precision: 0.5
26
+ };
27
+ const pos = spring([5, 5], spring_opt);
28
+ const init = [(120 - 10) / 3, (120 - 10) / 3];
29
+ const dimensions = spring(init, spring_opt);
30
+ type Arrow = {
31
+ x: number;
32
+ y: number;
33
+ x_dir: number;
34
+ y_dir: number;
35
+ rotation: number;
36
+ type: number;
37
+ };
38
+ const arrow_spring = spring<Arrow[]>([], spring_opt);
39
+
40
+ let last_i = $state(0);
41
+ let expanded = $state(true);
42
+ const box_size = (120 - 5 * 2) / 3;
43
+
44
+ async function handle_box_hover(i: number): Promise<void> {
45
+ expanded = false;
46
+ last_i = i;
47
+ const y = Math.floor(i / 3);
48
+ const x = i % 3;
49
+ pos.set([x * box_size + 5 * x + 5, y * box_size + 5 * y + 5]);
50
+
51
+ dimensions.set(init);
52
+ }
53
+
54
+ let last_pos = $state(0);
55
+ async function handle_box_click(i: number, stagger = false): Promise<void> {
56
+ if (expanded && stagger) return;
57
+
58
+ const y = Math.floor(i / 3);
59
+ const x = i % 3;
60
+
61
+ const [initial_arrows, eventual_arrows] = get_valid_offsets({
62
+ x: x,
63
+ y: y
64
+ });
65
+
66
+ if (stagger && last_i !== i) {
67
+ await Promise.all([
68
+ pos.set([x * box_size + 5 * x + 5, y * box_size + 5 * y + 5]),
69
+ arrow_spring.set(initial_arrows, { hard: true }),
70
+ dimensions.set(init)
71
+ ]);
72
+ } else {
73
+ await arrow_spring.set(initial_arrows, { hard: true });
74
+ }
75
+ last_pos = i;
76
+ expanded = true;
77
+
78
+ pos.set([0, 0]);
79
+ dimensions.set([120 + 10, 120 + 10]);
80
+ arrow_spring.set(eventual_arrows);
81
+
82
+ onposition?.(positions[i]);
83
+ }
84
+
85
+ function get_valid_offsets(anchorPoint: {
86
+ x: number;
87
+ y: number;
88
+ }): [Arrow[], Arrow[]] {
89
+ const destination_points: { x: number; y: number }[] = [
90
+ { x: 0, y: 0 },
91
+ { x: 1, y: 0 },
92
+ { x: 2, y: 0 },
93
+ { x: 0, y: 1 },
94
+ { x: 1, y: 1 },
95
+ { x: 2, y: 1 },
96
+ { x: 0, y: 2 },
97
+ { x: 1, y: 2 },
98
+ { x: 2, y: 2 }
99
+ ];
100
+
101
+ const offsets = destination_points
102
+ .map((dest) => ({
103
+ x: dest.x - anchorPoint.x,
104
+ y: dest.y - anchorPoint.y,
105
+ dest
106
+ }))
107
+ .filter((offset) => !(offset.x === 0 && offset.y === 0));
108
+
109
+ const normalized_offsets = offsets
110
+ .map((offset) => {
111
+ // cardinal
112
+ if (offset.x === 0 || offset.y === 0) {
113
+ const magnitude = Math.max(Math.abs(offset.x), Math.abs(offset.y));
114
+ return {
115
+ magnitude,
116
+ x: offset.x / magnitude,
117
+ y: offset.y / magnitude,
118
+ dest: offset.dest,
119
+ original: offset,
120
+ type: "cardinal" as const
121
+ };
122
+ }
123
+
124
+ // ordinal
125
+ if (Math.abs(offset.x) === Math.abs(offset.y)) {
126
+ const magnitude = Math.abs(offset.x);
127
+ return {
128
+ magnitude,
129
+ x: offset.x / magnitude,
130
+ y: offset.y / magnitude,
131
+ dest: offset.dest,
132
+ original: offset,
133
+ type: "ordinal" as const
134
+ };
135
+ }
136
+
137
+ // skip the rest
138
+ return null;
139
+ })
140
+ .filter((offset) => offset !== null);
141
+
142
+ const directions = new Map<
143
+ string,
144
+ {
145
+ x: number;
146
+ y: number;
147
+ dest: { x: number; y: number };
148
+ original: { x: number; y: number };
149
+ magnitude: number;
150
+ type: "cardinal" | "ordinal";
151
+ }[]
152
+ >();
153
+
154
+ normalized_offsets.forEach((offset) => {
155
+ if (directions.has(`${offset.x}-${offset.y}`)) {
156
+ directions.get(`${offset.x}-${offset.y}`)?.push(offset);
157
+ } else {
158
+ directions.set(`${offset.x}-${offset.y}`, [offset]);
159
+ }
160
+ });
161
+
162
+ const unique_directions = Array.from(directions.values()).map(
163
+ (direction) => {
164
+ return direction.sort((a, b) => b.magnitude - a.magnitude)[0];
165
+ }
166
+ );
167
+
168
+ const eventual_arrows = unique_directions.map((arrow) => ({
169
+ x:
170
+ arrow.dest.x * box_size +
171
+ 14 * arrow.dest.x +
172
+ 14 +
173
+ 10 +
174
+ (arrow.type === "ordinal" ? 0 : 12 * arrow.x),
175
+ y:
176
+ arrow.dest.y * box_size +
177
+ 14 * arrow.dest.y +
178
+ 14 +
179
+ 10 +
180
+ (arrow.type === "ordinal" ? 0 : 12 * arrow.y),
181
+ x_dir: arrow.x,
182
+ y_dir: arrow.y,
183
+ rotation:
184
+ Math.atan2(arrow.original.y, arrow.original.x) * (180 / Math.PI) + 180,
185
+ type: arrow.type === "ordinal" ? 1 : 2
186
+ }));
187
+
188
+ const initial_arrows = eventual_arrows.map((arrow) => ({
189
+ ...arrow,
190
+ x:
191
+ anchorPoint.x * box_size +
192
+ 14 * anchorPoint.x + // gaps
193
+ 14 + // padding
194
+ 10 + // arrow head
195
+ (arrow.x_dir * box_size) / 2 +
196
+ arrow.x_dir * (arrow.type === 1 ? 0 : 10), // offset based on direction
197
+
198
+ y:
199
+ anchorPoint.y * box_size +
200
+ 14 * anchorPoint.y +
201
+ 14 +
202
+ 10 +
203
+ (arrow.y_dir * box_size) / 2 +
204
+ arrow.y_dir * (arrow.type === 1 ? 0 : 10)
205
+ }));
206
+
207
+ return [initial_arrows, eventual_arrows];
208
+ }
209
+
210
+ onMount(() => {
211
+ handle_box_click(0);
212
+ });
213
+ </script>
214
+
215
+ <div class="wrap" class:expanded>
216
+ <div
217
+ class="box-wrap"
218
+ role="grid"
219
+ tabindex="0"
220
+ onmouseleave={() => handle_box_click(last_pos, true)}
221
+ >
222
+ {#each { length: 9 } as _, i}
223
+ <button
224
+ class="box"
225
+ class:active-box={last_pos === i}
226
+ onmouseenter={() => handle_box_hover(i)}
227
+ onclick={() => handle_box_click(i)}
228
+ >
229
+ <span class:active={last_pos === i} class="icon-wrap">
230
+ <Image />
231
+ </span>
232
+ </button>
233
+ {/each}
234
+ </div>
235
+ <div
236
+ class="expanding-box"
237
+ style:width="{$dimensions[0]}px"
238
+ style:height="{$dimensions[1]}px"
239
+ style:transform="translate({$pos[0]}px, {$pos[1]}px)"
240
+ ></div>
241
+ <svg viewBox="0 0 150 150">
242
+ {#each $arrow_spring as arrow}
243
+ <line
244
+ x1={(last_pos % 3) * box_size +
245
+ 14 * (last_pos % 3) +
246
+ 14 +
247
+ 10 +
248
+ (arrow.x_dir * box_size) / 2 +
249
+ arrow.x_dir * (arrow.type === 1 ? 0 : 10)}
250
+ x2={arrow.x}
251
+ y1={Math.floor(last_pos / 3) * box_size +
252
+ 14 * Math.floor(last_pos / 3) +
253
+ 14 +
254
+ 10 +
255
+ (arrow.y_dir * box_size) / 2 +
256
+ arrow.y_dir * (arrow.type === 1 ? 0 : 10)}
257
+ y2={arrow.y}
258
+ />
259
+ {/each}
260
+ {#each $arrow_spring as arrow}
261
+ <g style:transform="translate(-75px, -75px)">
262
+ <g style:transform="translate({arrow.x}px, {arrow.y}px)">
263
+ <path
264
+ d="M 70,75 80,69 80,81 Z"
265
+ style:transform="rotate({arrow.rotation}deg)"
266
+ style:transform-origin="75 75"
267
+ />
268
+ </g>
269
+ </g>
270
+ {/each}
271
+ </svg>
272
+ </div>
273
+
274
+ <style>
275
+ .wrap {
276
+ position: relative;
277
+ margin: 10px 0;
278
+ height: 130px;
279
+ width: 130px;
280
+ padding: 5px;
281
+ }
282
+
283
+ .box-wrap {
284
+ width: 100%;
285
+ height: 100%;
286
+ display: grid;
287
+ grid-template-columns: repeat(3, 1fr);
288
+ grid-template-rows: repeat(3, 1fr);
289
+ gap: 5px;
290
+
291
+ background-color: var(--block-background-fill);
292
+ }
293
+
294
+ .box {
295
+ cursor: pointer;
296
+ border: none;
297
+ border: #ccc dashed 1px;
298
+ border-radius: 4px;
299
+ transition: 0.1s;
300
+ display: flex;
301
+ justify-content: center;
302
+ align-items: center;
303
+ }
304
+
305
+ .box::after {
306
+ background: none !important;
307
+ }
308
+
309
+ .expanding-box {
310
+ --mod: 3;
311
+ --border: 2;
312
+ border: orange solid 2px;
313
+ border-radius: 4px;
314
+ position: absolute;
315
+ top: 0px;
316
+ left: 0px;
317
+ width: 100%;
318
+ height: 100%;
319
+ pointer-events: none;
320
+
321
+ width: calc(100% / var(--mod));
322
+ height: calc(100% / var(--mod));
323
+ transform-origin: 50% 0;
324
+ box-sizing: border-box;
325
+ }
326
+
327
+ svg {
328
+ position: absolute;
329
+ top: 0px;
330
+ left: 0px;
331
+ width: 100%;
332
+ height: 100%;
333
+
334
+ pointer-events: none;
335
+ }
336
+
337
+ .icon-wrap {
338
+ opacity: 0.2;
339
+ height: 50%;
340
+ width: 50%;
341
+
342
+ display: flex;
343
+ justify-content: center;
344
+ align-items: center;
345
+ border-color: #ccc;
346
+ transition: 0.1s;
347
+ padding-top: 1px;
348
+ }
349
+
350
+ .wrap.expanded .icon-wrap {
351
+ opacity: 0;
352
+ }
353
+
354
+ .wrap.expanded .box {
355
+ border-color: #fff;
356
+ }
357
+
358
+ .icon-wrap.active {
359
+ opacity: 1 !important;
360
+ }
361
+
362
+ svg {
363
+ opacity: 0;
364
+ padding: 5px;
365
+ transition: 0.1s;
366
+ }
367
+ .expanded svg {
368
+ opacity: 1;
369
+ }
370
+
371
+ svg line {
372
+ stroke: #999;
373
+ stroke-width: 3px;
374
+ stroke-linecap: round;
375
+ }
376
+
377
+ svg path {
378
+ stroke-width: 3;
379
+ stroke: #999;
380
+ stroke-linejoin: round;
381
+ stroke-linecap: round;
382
+ fill: #999;
383
+ /* transition: 0.5s; */
384
+ transform-origin: 75px 75px;
385
+ }
386
+ </style>
6.26.1/imageeditor/shared/Controls.svelte ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { IconButton, IconButtonWrapper } from "@gradio/atoms";
3
+ import {
4
+ Check,
5
+ Trash,
6
+ ZoomIn,
7
+ ZoomOut,
8
+ Pan,
9
+ Download,
10
+ Undo,
11
+ Redo
12
+ } from "@gradio/icons";
13
+ let {
14
+ can_save = false,
15
+ changeable = false,
16
+ current_zoom = 1,
17
+ tool,
18
+ min_zoom = true,
19
+ enable_download = false,
20
+ can_undo,
21
+ can_redo,
22
+ onremove_image,
23
+ onundo,
24
+ onredo,
25
+ onsave,
26
+ onzoom_in,
27
+ onzoom_out,
28
+ onset_zoom,
29
+ onpan,
30
+ ondownload
31
+ }: {
32
+ can_save?: boolean;
33
+ changeable?: boolean;
34
+ current_zoom?: number;
35
+ tool: string;
36
+ min_zoom?: boolean;
37
+ enable_download?: boolean;
38
+ can_undo: boolean;
39
+ can_redo: boolean;
40
+ onremove_image?: () => void;
41
+ onundo?: () => void;
42
+ onredo?: () => void;
43
+ onsave?: () => void;
44
+ onzoom_in?: () => void;
45
+ onzoom_out?: () => void;
46
+ onset_zoom?: (zoom: number | "fit") => void;
47
+ onpan?: () => void;
48
+ ondownload?: () => void;
49
+ } = $props();
50
+
51
+ let show_zoom_popup = $state(false);
52
+
53
+ function handle_zoom_click(e: MouseEvent): void {
54
+ e.stopPropagation();
55
+ show_zoom_popup = !show_zoom_popup;
56
+ }
57
+
58
+ function handle_zoom_change(zoom: number | "fit"): void {
59
+ onset_zoom?.(zoom);
60
+ show_zoom_popup = false;
61
+ }
62
+
63
+ function handle_zoom_keydown(e: KeyboardEvent): void {
64
+ if (e.key === "Enter") {
65
+ handle_zoom_change(current_zoom);
66
+ }
67
+ }
68
+
69
+ let formatted_zoom = $derived(Math.round(current_zoom * 100));
70
+ </script>
71
+
72
+ <IconButtonWrapper>
73
+ {#if enable_download}
74
+ <IconButton
75
+ Icon={Download}
76
+ label="Download"
77
+ onclick={(event) => {
78
+ ondownload?.();
79
+ event.stopPropagation();
80
+ }}
81
+ />
82
+ {/if}
83
+
84
+ <IconButton
85
+ Icon={Pan}
86
+ label="Pan"
87
+ onclick={(e) => {
88
+ e.stopPropagation();
89
+ onpan?.();
90
+ }}
91
+ highlight={tool === "pan"}
92
+ size="small"
93
+ padded={false}
94
+ transparent={true}
95
+ disabled={min_zoom}
96
+ />
97
+
98
+ <IconButton
99
+ Icon={ZoomOut}
100
+ label="Zoom out"
101
+ onclick={(event) => {
102
+ onzoom_out?.();
103
+ event.stopPropagation();
104
+ }}
105
+ />
106
+ <IconButton
107
+ Icon={ZoomIn}
108
+ label="Zoom in"
109
+ onclick={(event) => {
110
+ onzoom_in?.();
111
+ event.stopPropagation();
112
+ }}
113
+ />
114
+
115
+ <div class="zoom-number">
116
+ <span
117
+ role="button"
118
+ tabindex="0"
119
+ onclick={handle_zoom_click}
120
+ onkeydown={handle_zoom_keydown}>{formatted_zoom}%</span
121
+ >
122
+ {#if show_zoom_popup}
123
+ <div class="zoom-controls">
124
+ <ul>
125
+ <li>
126
+ <button
127
+ onclick={(event) => {
128
+ event.stopPropagation();
129
+ handle_zoom_change("fit");
130
+ }}
131
+ >
132
+ Fit to screen
133
+ </button>
134
+ </li>
135
+ {#each [0.25, 0.5, 1, 2, 4] as zoom}
136
+ <li>
137
+ <button
138
+ onclick={(event) => {
139
+ event.stopPropagation();
140
+ handle_zoom_change(zoom);
141
+ }}
142
+ >
143
+ {zoom * 100}%
144
+ </button>
145
+ </li>
146
+ {/each}
147
+ </ul>
148
+ </div>
149
+ {/if}
150
+ </div>
151
+ <div class="separator"></div>
152
+
153
+ <IconButton
154
+ Icon={Undo}
155
+ label="Undo"
156
+ onclick={(event) => {
157
+ onundo?.();
158
+ event.stopPropagation();
159
+ }}
160
+ disabled={!can_undo}
161
+ />
162
+
163
+ <IconButton
164
+ Icon={Redo}
165
+ label="Redo"
166
+ onclick={(event) => {
167
+ onredo?.();
168
+ event.stopPropagation();
169
+ }}
170
+ disabled={!can_redo}
171
+ />
172
+
173
+ {#if changeable}
174
+ <IconButton
175
+ disabled={!can_save}
176
+ Icon={Check}
177
+ label="Save changes"
178
+ onclick={(event) => {
179
+ onsave?.();
180
+ event.stopPropagation();
181
+ }}
182
+ color="var(--color-accent)"
183
+ />
184
+ {/if}
185
+
186
+ <IconButton
187
+ Icon={Trash}
188
+ label="Clear canvas"
189
+ onclick={(event) => {
190
+ onremove_image?.();
191
+ event.stopPropagation();
192
+ }}
193
+ />
194
+ </IconButtonWrapper>
195
+
196
+ <style>
197
+ .separator {
198
+ width: 1px;
199
+ height: 10px;
200
+ background-color: var(--border-color-primary);
201
+ }
202
+
203
+ .zoom-number {
204
+ position: relative;
205
+ width: 30px;
206
+ padding-left: 4px;
207
+ display: flex;
208
+ align-items: center;
209
+ justify-content: center;
210
+ }
211
+
212
+ .zoom-number span {
213
+ cursor: pointer;
214
+ font-size: var(--text-sm);
215
+ transition: color 0.15s ease;
216
+ }
217
+
218
+ .zoom-number span:hover {
219
+ color: var(--color-accent);
220
+ }
221
+
222
+ .zoom-controls {
223
+ position: absolute;
224
+ top: calc(100% + var(--spacing-xxs) + 3px);
225
+ left: -2px;
226
+ background: var(--block-background-fill);
227
+ border: 1px solid var(--color-gray-200);
228
+ border-radius: var(--radius-sm);
229
+ padding: var(--spacing-xxs);
230
+ box-shadow: var(--shadow-drop);
231
+ font-size: 12px;
232
+ z-index: var(--layer-2);
233
+ width: max-content;
234
+ color: var(--block-label-text-color);
235
+ border: 1px solid var(--block-border-color);
236
+ border-top-left-radius: 0;
237
+ border-top-right-radius: 0;
238
+ }
239
+
240
+ .zoom-controls ul {
241
+ list-style: none;
242
+ margin: 0;
243
+ padding: 0;
244
+ }
245
+
246
+ .zoom-controls li {
247
+ display: flex;
248
+ justify-content: space-between;
249
+ align-items: center;
250
+ transition: background-color 0.15s ease;
251
+ border-bottom: 1px solid var(--border-color-primary);
252
+ }
253
+
254
+ .zoom-controls li:last-child {
255
+ border-bottom: none;
256
+ }
257
+
258
+ .zoom-controls li:hover {
259
+ background-color: var(--background-fill-secondary);
260
+ }
261
+
262
+ .zoom-controls button {
263
+ width: 100%;
264
+ text-align: left;
265
+ padding: var(--spacing-sm) var(--spacing-md);
266
+ font-size: var(--text-sm);
267
+ line-height: var(--line-sm);
268
+ transition: all 0.15s ease;
269
+ border-radius: var(--radius-sm);
270
+ }
271
+
272
+ .zoom-controls button:hover {
273
+ color: var(--color-accent);
274
+ }
275
+ </style>
6.26.1/imageeditor/shared/IconButton.svelte ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { type Component } from "svelte";
3
+ import type { ColorInput } from "tinycolor2";
4
+
5
+ let {
6
+ Icon,
7
+ label = "",
8
+ show_label = false,
9
+ pending = false,
10
+ size = "small",
11
+ padded = true,
12
+ highlight = false,
13
+ disabled = false,
14
+ hasPopup = false,
15
+ color = "var(--block-label-text-color)",
16
+ transparent = false,
17
+ background = "var(--background-fill-primary)",
18
+ offset = 0,
19
+ label_position = "left",
20
+ roundedness = "quite",
21
+ onclick = undefined
22
+ }: {
23
+ Icon: Component<any>;
24
+ label?: string;
25
+ show_label?: boolean;
26
+ pending?: boolean;
27
+ size?: "small" | "large" | "medium";
28
+ padded?: boolean;
29
+ highlight?: boolean;
30
+ disabled?: boolean;
31
+ hasPopup?: boolean;
32
+ color?: string | ColorInput;
33
+ transparent?: boolean;
34
+ background?: string;
35
+ offset?: number;
36
+ label_position?: "left" | "right";
37
+ roundedness?: "quite" | "very";
38
+ onclick?: (event: MouseEvent) => void;
39
+ } = $props();
40
+
41
+ let _color = $derived(highlight ? "var(--color-accent)" : color.toString());
42
+ </script>
43
+
44
+ <button
45
+ {disabled}
46
+ {onclick}
47
+ aria-label={label}
48
+ aria-haspopup={hasPopup}
49
+ title={label}
50
+ class:pending
51
+ class:padded
52
+ class:highlight
53
+ class:transparent
54
+ style:color={!disabled && _color ? _color : "var(--block-label-text-color)"}
55
+ style:--bg-color={!disabled ? background : "auto"}
56
+ style:margin-left={offset + "px"}
57
+ class="{roundedness}-round"
58
+ >
59
+ {#if show_label && label_position === "left"}
60
+ <span style="margin-left: 4px;">{label}</span>
61
+ {/if}
62
+ <div
63
+ class:small={size === "small"}
64
+ class:large={size === "large"}
65
+ class:medium={size === "medium"}
66
+ >
67
+ <Icon />
68
+ </div>
69
+ {#if show_label && label_position === "right"}
70
+ <span style="margin-right: 4px;">{label}</span>
71
+ {/if}
72
+ </button>
73
+
74
+ <style>
75
+ button {
76
+ display: flex;
77
+ justify-content: center;
78
+ align-items: center;
79
+ gap: 1px;
80
+ z-index: var(--layer-2);
81
+ /* background: var(--background-fill-primary); */
82
+ /* border-radius: var(--radius-sm); */
83
+ color: var(--block-label-text-color);
84
+ border: 1px solid transparent;
85
+ }
86
+
87
+ .quite-round {
88
+ border-radius: var(--radius-sm);
89
+ }
90
+
91
+ .very-round {
92
+ border-radius: var(--radius-md);
93
+ }
94
+
95
+ button[disabled] {
96
+ opacity: 0.5;
97
+ box-shadow: none;
98
+ }
99
+
100
+ button[disabled]:hover {
101
+ cursor: not-allowed;
102
+ /* border: 1px solid var(--button-secondary-border-color); */
103
+ /* padding: 2px; */
104
+ }
105
+
106
+ .padded {
107
+ padding: 2px;
108
+ background: var(--bg-color);
109
+ box-shadow: var(--shadow-drop);
110
+ border: 1px solid var(--button-secondary-border-color);
111
+ }
112
+
113
+ button:hover,
114
+ button.highlight {
115
+ cursor: pointer;
116
+ color: var(--color-accent);
117
+ }
118
+
119
+ .padded:hover {
120
+ border: 2px solid var(--button-secondary-border-color-hover);
121
+ padding: 1px;
122
+ color: var(--block-label-text-color);
123
+ }
124
+
125
+ span {
126
+ padding: 0px 1px;
127
+ font-size: 10px;
128
+ }
129
+
130
+ div {
131
+ padding: 2px;
132
+ display: flex;
133
+ align-items: flex-end;
134
+ }
135
+
136
+ .small {
137
+ width: 14px;
138
+ height: 14px;
139
+ }
140
+
141
+ .medium {
142
+ width: 20px;
143
+ height: 20px;
144
+ }
145
+
146
+ .large {
147
+ width: 22px;
148
+ height: 22px;
149
+ }
150
+
151
+ .pending {
152
+ animation: flash 0.5s infinite;
153
+ }
154
+
155
+ @keyframes flash {
156
+ 0% {
157
+ opacity: 0.5;
158
+ }
159
+ 50% {
160
+ opacity: 1;
161
+ }
162
+ 100% {
163
+ opacity: 0.5;
164
+ }
165
+ }
166
+
167
+ .transparent {
168
+ background: transparent;
169
+ border: none;
170
+ box-shadow: none;
171
+ }
172
+ </style>
6.26.1/imageeditor/shared/ImageEditor.svelte ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script module lang="ts">
2
+ import type { Tool, Subtool } from "./Toolbar.svelte";
3
+
4
+ export const EDITOR_KEY = Symbol("editor");
5
+ export type context_type = "bg" | "layers" | "crop" | "draw" | "erase";
6
+ </script>
7
+
8
+ <script lang="ts">
9
+ import { onMount, tick, type Snippet } from "svelte";
10
+ import { get } from "svelte/store";
11
+ import Toolbar, { type Tool as ToolbarTool } from "./Toolbar.svelte";
12
+ import { CropTool } from "./crop/crop";
13
+ import { ResizeTool } from "./resize/resize";
14
+ import { Webcam } from "@gradio/image";
15
+ import type { I18nFormatter } from "@gradio/utils";
16
+ import type { Client, FileData } from "@gradio/client";
17
+ import tinycolor, { type ColorInput } from "tinycolor2";
18
+ import { ZoomTool } from "./zoom/zoom";
19
+ import { type CommandManager, type CommandNode } from "./core/commands";
20
+ import { ImageEditor } from "./core/editor";
21
+ import { type Brush, type Eraser } from "./brush/types";
22
+ import { BrushTool } from "./brush/brush";
23
+ import { create_drag } from "@gradio/upload";
24
+ import SecondaryToolbar from "./SecondaryToolbar.svelte";
25
+ import { Check } from "@gradio/icons";
26
+ import type { LayerOptions, Source, Transform, WebcamOptions } from "./types";
27
+
28
+ import { type ImageBlobs } from "./types";
29
+ import Controls from "./Controls.svelte";
30
+ import IconButton from "./IconButton.svelte";
31
+
32
+ const { drag, open_file_upload } = create_drag();
33
+
34
+ export const antialias = true;
35
+
36
+ let {
37
+ changeable = false,
38
+ sources = ["upload", "webcam", "clipboard"],
39
+ transforms = ["crop", "resize"],
40
+ canvas_size,
41
+ is_dragging = $bindable(false),
42
+ background_image = $bindable(false),
43
+ brush_options,
44
+ eraser_options,
45
+ fixed_canvas = false,
46
+ root,
47
+ i18n,
48
+ upload,
49
+ composite,
50
+ layers,
51
+ background,
52
+ border_region = 0,
53
+ layer_options,
54
+ current_tool = $bindable(),
55
+ webcam_options,
56
+ show_download_button = false,
57
+ theme_mode,
58
+ full_history = $bindable(null),
59
+ has_drawn = $bindable(false),
60
+ can_undo = $bindable(false),
61
+ onclear,
62
+ onsave,
63
+ onchange,
64
+ onupload,
65
+ oninput,
66
+ ondownload_error,
67
+ children
68
+ }: {
69
+ changeable?: boolean;
70
+ sources?: Source[];
71
+ transforms?: Transform[];
72
+ canvas_size: [number, number];
73
+ is_dragging?: boolean;
74
+ background_image?: boolean;
75
+ brush_options: Brush | false;
76
+ eraser_options: Eraser | false;
77
+ fixed_canvas?: boolean;
78
+ root: string;
79
+ i18n: I18nFormatter;
80
+ upload: Client["upload"];
81
+ composite: FileData | null;
82
+ layers: FileData[];
83
+ background: FileData | null;
84
+ border_region?: number;
85
+ layer_options: LayerOptions;
86
+ current_tool: ToolbarTool;
87
+ webcam_options: WebcamOptions;
88
+ show_download_button?: boolean;
89
+ theme_mode: "dark" | "light";
90
+ full_history?: CommandNode | null;
91
+ has_drawn?: boolean;
92
+ can_undo?: boolean;
93
+ onclear?: () => void;
94
+ onsave?: () => void;
95
+ onchange?: () => void;
96
+ onupload?: () => void;
97
+ oninput?: () => void;
98
+ ondownload_error?: (error: string) => void;
99
+ children?: Snippet;
100
+ } = $props();
101
+
102
+ let pixi_target: HTMLDivElement;
103
+ let pixi_target_crop: HTMLDivElement;
104
+
105
+ let layer_options_key: string | undefined | null = null;
106
+ $effect(() => {
107
+ if (!check_if_should_init()) return;
108
+
109
+ const next_layer_options_key = JSON.stringify(layer_options);
110
+ if (next_layer_options_key === layer_options_key) return;
111
+
112
+ layer_options_key = next_layer_options_key;
113
+ editor.set_layer_options(layer_options);
114
+ });
115
+
116
+ $effect(() => {
117
+ refresh_tools();
118
+ });
119
+
120
+ function refresh_tools(): void {
121
+ if (!editor || !ready) return;
122
+ editor.set_tool(current_tool);
123
+ editor.set_subtool(current_subtool);
124
+ }
125
+
126
+ $effect(() => {
127
+ if (!(editor && ready && editor.layers)) return;
128
+ const current_layers = get(editor.layers);
129
+
130
+ if (current_layers.layers.length > 0 && !current_layers.active_layer) {
131
+ refresh_tools_for_layer_changes(current_layers);
132
+ }
133
+ });
134
+
135
+ /**
136
+ * Refreshes tools when layer state changes
137
+ */
138
+ function refresh_tools_for_layer_changes(current_layers: any): void {
139
+ if (!editor || !ready) return;
140
+
141
+ if (current_layers.layers.length > 0 && !current_layers.active_layer) {
142
+ editor.set_layer(current_layers.layers[0].id);
143
+ }
144
+
145
+ // reapply current tool to ensure it targets the correct layer
146
+ if (current_tool) {
147
+ editor.set_tool(current_tool);
148
+ if (current_subtool) {
149
+ editor.set_subtool(current_subtool);
150
+ }
151
+ }
152
+
153
+ if (brush && (current_tool === "draw" || current_tool === "erase")) {
154
+ brush.set_tool(current_tool, current_subtool);
155
+ }
156
+ }
157
+
158
+ function check_if_should_init(): boolean {
159
+ return layer_options && editor && ready;
160
+ }
161
+
162
+ /**
163
+ * Gets the image blobs from the editor
164
+ * @returns {Promise<ImageBlobs>} Object containing background, layers, and composite image blobs
165
+ */
166
+ export async function get_blobs(): Promise<ImageBlobs> {
167
+ if (!editor) return { background: null, layers: [], composite: null };
168
+ if (!background_image && !has_drawn && !layers.length)
169
+ return { background: null, layers: [], composite: null };
170
+ const blobs = await editor.get_blobs();
171
+ return blobs;
172
+ }
173
+
174
+ let editor: ImageEditor;
175
+
176
+ /**
177
+ * Adds an image to the editor
178
+ * @param {Blob | File} image - The image to add
179
+ */
180
+ export function add_image(image: Blob | File): void {
181
+ editor.add_image({ image });
182
+ }
183
+
184
+ let pending_bg: Promise<void>;
185
+ /**
186
+ * Adds an image to the editor from a URL
187
+ * @param {string | FileData} source - The URL of the image or a FileData object
188
+ * @returns {Promise<void>}
189
+ */
190
+ export async function add_image_from_url(
191
+ source:
192
+ | string
193
+ | {
194
+ url: string;
195
+ meta: {
196
+ _type: string;
197
+ };
198
+ }
199
+ | any
200
+ ): Promise<void> {
201
+ if (!editor || !source || !check_if_should_init()) return;
202
+ let url: string;
203
+
204
+ if (typeof source === "string") {
205
+ url = source;
206
+ } else if (source?.meta?._type === "gradio.FileData" && source?.url) {
207
+ url = source.url;
208
+ } else {
209
+ console.warn("Invalid source provided to add_image_from_url:", source);
210
+ return;
211
+ }
212
+
213
+ try {
214
+ pending_bg = editor.add_image_from_url(url);
215
+ let pending_crop = crop.add_image_from_url(url);
216
+ await Promise.all([pending_bg, pending_crop]);
217
+ crop.set_tool("image");
218
+ crop.set_subtool("crop");
219
+ background_image = true;
220
+ zoom.set_zoom("fit");
221
+ onupload?.();
222
+ oninput?.();
223
+ } catch (error) {
224
+ console.error("Error adding image from URL:", error);
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Adds a new layer with an image loaded from a URL
230
+ * @param {string | FileData} source - The URL of the image or a FileData object
231
+ * @returns {Promise<string | null>} - The ID of the created layer, or null if failed
232
+ */
233
+ export async function add_layers_from_url(
234
+ source: FileData[] | any
235
+ ): Promise<void> {
236
+ if (!editor || !source.length || !check_if_should_init()) return;
237
+
238
+ if (
239
+ Array.isArray(source) &&
240
+ source.every((item) => item?.meta?._type === "gradio.FileData")
241
+ ) {
242
+ try {
243
+ await pending_bg;
244
+ await editor.add_layers_from_url(source.map((item) => item.url));
245
+ onchange?.();
246
+ oninput?.();
247
+ } catch (error) {
248
+ console.error("Error adding layer from URL:", error);
249
+ }
250
+ }
251
+ }
252
+
253
+ let brush: BrushTool;
254
+ let zoom: ZoomTool;
255
+ let zoom_level = $state(1);
256
+ let ready = $state(false);
257
+ let mounted = $state(false);
258
+ let min_zoom = $state(true);
259
+
260
+ let last_dimensions = { width: 0, height: 0 };
261
+
262
+ /**
263
+ * Handles visibility changes and resets zoom if dimensions have changed
264
+ */
265
+ async function handle_visibility_change(): Promise<void> {
266
+ if (!editor || !ready || !zoom || !pixi_target) return;
267
+ await tick();
268
+
269
+ if (!pixi_target) return;
270
+
271
+ const is_visible = pixi_target.offsetParent !== null;
272
+
273
+ if (is_visible) {
274
+ const current_dimensions = pixi_target.getBoundingClientRect();
275
+
276
+ if (
277
+ current_dimensions.width !== last_dimensions.width ||
278
+ current_dimensions.height !== last_dimensions.height
279
+ ) {
280
+ zoom.set_zoom("fit");
281
+
282
+ last_dimensions = {
283
+ width: current_dimensions.width,
284
+ height: current_dimensions.height
285
+ };
286
+ }
287
+ }
288
+ }
289
+
290
+ onMount(() => {
291
+ let intersection_observer: IntersectionObserver;
292
+ let resize_observer: ResizeObserver;
293
+
294
+ init_image_editor().then(() => {
295
+ mounted = true;
296
+ intersection_observer = new IntersectionObserver(() => {
297
+ handle_visibility_change();
298
+ });
299
+
300
+ resize_observer = new ResizeObserver(() => {
301
+ handle_visibility_change();
302
+ });
303
+
304
+ intersection_observer.observe(pixi_target);
305
+ resize_observer.observe(pixi_target);
306
+
307
+ setTimeout(() => {
308
+ if (full_history && editor) {
309
+ editor.command_manager
310
+ .replay(full_history, editor.context)
311
+ .then(() => {
312
+ refresh_tools_after_history();
313
+ });
314
+ }
315
+ }, 0);
316
+ });
317
+
318
+ if (typeof window !== "undefined") {
319
+ (window as any).editor = editor;
320
+ }
321
+
322
+ return () => {
323
+ if (intersection_observer) {
324
+ intersection_observer.disconnect();
325
+ }
326
+ if (resize_observer) {
327
+ resize_observer.disconnect();
328
+ }
329
+ if (editor) {
330
+ editor.destroy();
331
+ }
332
+ };
333
+ });
334
+
335
+ /**
336
+ * Refreshes tool state after history replay to ensure proper layer targeting
337
+ */
338
+ function refresh_tools_after_history(): void {
339
+ if (!editor || !ready) return;
340
+
341
+ const current_layers = get(editor.layers);
342
+
343
+ if (current_layers.layers.length > 0 && !current_layers.active_layer) {
344
+ editor.set_layer(current_layers.layers[0].id);
345
+ }
346
+
347
+ if (current_tool) {
348
+ editor.set_tool(current_tool);
349
+ if (current_subtool) {
350
+ editor.set_subtool(current_subtool);
351
+ }
352
+ }
353
+
354
+ if (brush && (current_tool === "draw" || current_tool === "erase")) {
355
+ brush.set_tool(current_tool, current_subtool);
356
+ }
357
+
358
+ full_history = editor.command_manager.history;
359
+ }
360
+
361
+ let crop: ImageEditor;
362
+ let crop_zoom: ZoomTool;
363
+ let can_redo = $state(false);
364
+ async function init_image_editor(): Promise<void> {
365
+ brush = new BrushTool();
366
+ zoom = new ZoomTool();
367
+ editor = new ImageEditor({
368
+ target_element: pixi_target,
369
+ width: canvas_size[0],
370
+ height: canvas_size[1],
371
+ tools: ["image", zoom, new ResizeTool(), brush],
372
+ fixed_canvas,
373
+ border_region,
374
+ layer_options,
375
+ theme_mode
376
+ });
377
+
378
+ brush.on("change", () => {
379
+ has_drawn = true;
380
+ });
381
+
382
+ crop_zoom = new ZoomTool();
383
+
384
+ crop = new ImageEditor({
385
+ target_element: pixi_target_crop,
386
+ width: canvas_size[0],
387
+ height: canvas_size[1],
388
+ tools: ["image", crop_zoom, new CropTool()],
389
+ dark: true,
390
+ fixed_canvas: false,
391
+ border_region: 0,
392
+ pad_bottom: 40
393
+ });
394
+
395
+ editor.scale.subscribe((_scale) => {
396
+ zoom_level = _scale;
397
+ });
398
+
399
+ editor.min_zoom.subscribe((is_min_zoom) => {
400
+ min_zoom = is_min_zoom;
401
+ });
402
+
403
+ editor.dimensions.subscribe((dimensions) => {
404
+ last_dimensions = { ...dimensions };
405
+ });
406
+
407
+ editor.command_manager.current_history.subscribe((history) => {
408
+ can_undo = history.previous !== null;
409
+ can_redo = history.next !== null;
410
+ });
411
+
412
+ await Promise.all([editor.ready, crop.ready]).then(() => {
413
+ handle_tool_change({ tool: "image" });
414
+ ready = true;
415
+ if (sources.length > 0) {
416
+ handle_tool_change({ tool: "image" });
417
+ } else if (brush_options) {
418
+ handle_tool_change({ tool: "draw" });
419
+ } else if (eraser_options) {
420
+ handle_tool_change({ tool: "erase" });
421
+ } else {
422
+ handle_tool_change({ tool: "image" });
423
+ }
424
+ crop.set_subtool("crop");
425
+ });
426
+
427
+ editor.on("change", () => {
428
+ onchange?.();
429
+ oninput?.();
430
+ full_history = editor.command_manager.history;
431
+ });
432
+
433
+ if (background || layers.length > 0) {
434
+ if (background) {
435
+ await add_image_from_url(background);
436
+ }
437
+ if (layers.length > 0) {
438
+ await add_layers_from_url(layers);
439
+ }
440
+ handle_tool_change({ tool: "draw" });
441
+ } else if (composite) {
442
+ await add_image_from_url(composite);
443
+ handle_tool_change({ tool: "draw" });
444
+ }
445
+
446
+ refresh_tools();
447
+ }
448
+
449
+ $effect(() => {
450
+ if (
451
+ background == null &&
452
+ layers.length == 0 &&
453
+ composite == null &&
454
+ editor &&
455
+ ready
456
+ ) {
457
+ editor.reset_canvas();
458
+ zoom.set_zoom("fit");
459
+ handle_tool_change({ tool: "image" });
460
+ background_image = false;
461
+ has_drawn = false;
462
+ }
463
+ });
464
+
465
+ $effect(() => {
466
+ if (current_tool === "image" && current_subtool === "crop") {
467
+ crop_zoom.set_zoom("fit");
468
+ }
469
+ });
470
+
471
+ /**
472
+ * Handles file uploads
473
+ * @param {File[]} files - The uploaded files
474
+ */
475
+ async function handle_files(
476
+ files: File[] | Blob[] | File | Blob | null
477
+ ): Promise<void> {
478
+ if (files == null) return;
479
+ if (!sources.includes("upload")) return;
480
+ editor.reset_canvas();
481
+ const _file = Array.isArray(files) ? files[0] : files;
482
+ await editor.add_image({ image: _file });
483
+ await crop.add_image({ image: _file });
484
+ crop.reset();
485
+
486
+ background_image = true;
487
+ zoom.set_zoom("fit");
488
+ handle_tool_change({ tool: "draw" });
489
+ onupload?.();
490
+ }
491
+
492
+ $effect(() => {
493
+ if (editor) {
494
+ background_image =
495
+ can_undo && editor.command_manager.contains("AddImage");
496
+ }
497
+ });
498
+
499
+ /**
500
+ * Handles tool change events
501
+ * @param {{ tool: ToolbarTool }} param0 - Object containing the selected tool
502
+ */
503
+ function handle_tool_change({ tool }: { tool: ToolbarTool }): void {
504
+ editor.set_tool(tool);
505
+ current_tool = tool;
506
+
507
+ if (tool === "image") {
508
+ crop.set_tool("image");
509
+ crop.set_subtool("crop");
510
+ }
511
+ }
512
+
513
+ /**
514
+ * Handles subtool change events
515
+ * @param {{ tool: ToolbarTool, subtool: Subtool }} param0 - Object containing the selected tool and subtool
516
+ */
517
+ function handle_subtool_change({
518
+ tool,
519
+ subtool
520
+ }: {
521
+ tool: ToolbarTool;
522
+ subtool: Subtool | null;
523
+ }): void {
524
+ editor.set_subtool(subtool);
525
+ current_subtool = subtool;
526
+
527
+ if (subtool === null) {
528
+ return;
529
+ }
530
+
531
+ if (tool === "draw") {
532
+ if (subtool === "size") {
533
+ brush_size_visible = true;
534
+ } else if (subtool === "color") {
535
+ brush_color_visible = true;
536
+ }
537
+ }
538
+
539
+ if (tool === "erase" && subtool === "size") {
540
+ eraser_size_visible = true;
541
+ }
542
+
543
+ if (tool === "image" && subtool === "paste") {
544
+ process_clipboard();
545
+ }
546
+
547
+ if (tool === "image" && subtool === "upload") {
548
+ tick().then(() => {
549
+ disable_click = false;
550
+ open_file_upload();
551
+ });
552
+ }
553
+ }
554
+
555
+ let eraser_size_visible = $state(false);
556
+ let selected_color = $state<ColorInput | string>();
557
+ let selected_size = $state<number>();
558
+ let selected_opacity = $state(1);
559
+ let selected_eraser_size = $state<number>();
560
+
561
+ $effect(() => {
562
+ if (brush_options) {
563
+ update_brush_options();
564
+ }
565
+
566
+ if (eraser_options) {
567
+ update_eraser_options();
568
+ }
569
+ });
570
+
571
+ function update_brush_options(): void {
572
+ if (!brush_options) return;
573
+ const options = brush_options;
574
+ const default_color =
575
+ options.default_color === "auto"
576
+ ? options.colors[0]
577
+ : options.default_color;
578
+
579
+ // color is already a tuple [color, opacity]
580
+ if (Array.isArray(default_color)) {
581
+ selected_color = default_color[0];
582
+ selected_opacity = default_color[1];
583
+ } else {
584
+ selected_color = default_color;
585
+
586
+ // color is a string, check if it has opacity info
587
+ const color = tinycolor(default_color);
588
+ if (color.getAlpha() < 1) {
589
+ selected_opacity = color.getAlpha();
590
+ } else {
591
+ selected_opacity = 1;
592
+ }
593
+ }
594
+
595
+ selected_size =
596
+ typeof options.default_size === "number" ? options.default_size : 25;
597
+ }
598
+
599
+ function update_eraser_options(): void {
600
+ if (!eraser_options) return;
601
+ const options = eraser_options;
602
+ selected_eraser_size =
603
+ options.default_size === "auto" ? 25 : options.default_size;
604
+ }
605
+
606
+ let brush_size_visible = $state(false);
607
+
608
+ let brush_color_visible = $state(false);
609
+
610
+ $effect(() => {
611
+ if (!brush) return;
612
+ brush.set_brush_color(
613
+ (() => {
614
+ let color_value: ColorInput = "black";
615
+ if (selected_color === "auto") {
616
+ if (!brush_options) return "black";
617
+ const default_color =
618
+ brush_options.colors.find((color) =>
619
+ Array.isArray(color)
620
+ ? color[0] === brush_options.default_color
621
+ : color === brush_options.default_color
622
+ ) || brush_options.colors[0];
623
+
624
+ color_value = Array.isArray(default_color)
625
+ ? default_color[0]
626
+ : default_color;
627
+ } else {
628
+ color_value = selected_color ?? "black";
629
+ }
630
+ return color_value;
631
+ })()
632
+ );
633
+ });
634
+
635
+ $effect(() => {
636
+ brush?.set_brush_size(
637
+ typeof selected_size === "number" ? selected_size : 25
638
+ );
639
+ });
640
+
641
+ $effect(() => {
642
+ brush?.set_eraser_size(
643
+ typeof selected_eraser_size === "number" ? selected_eraser_size : 25
644
+ );
645
+ });
646
+
647
+ let disable_click = $state(true);
648
+ $effect(() => {
649
+ disable_click =
650
+ current_tool !== "image" ||
651
+ (current_tool === "image" && background_image) ||
652
+ (current_tool === "image" && current_subtool === "webcam") ||
653
+ !sources.includes("upload");
654
+ });
655
+
656
+ let current_subtool = $state<Subtool | null>(null);
657
+ let preview = $state(false);
658
+ $effect(() => {
659
+ brush?.preview_brush(preview);
660
+ });
661
+ $effect(() => {
662
+ brush?.set_brush_opacity(selected_opacity);
663
+ });
664
+
665
+ function remove_image(): void {
666
+ onclear?.();
667
+ editor.reset_canvas();
668
+ handle_tool_change({ tool: "image" });
669
+ background_image = false;
670
+ has_drawn = false;
671
+ }
672
+
673
+ export function handle_remove(): void {
674
+ remove_image();
675
+ }
676
+
677
+ function handle_zoom_change(zoom_level: number | "fit"): void {
678
+ zoom.set_zoom(zoom_level);
679
+ }
680
+
681
+ function zoom_in_out(direction: "in" | "out"): void {
682
+ zoom.set_zoom(
683
+ direction === "in"
684
+ ? zoom_level + (zoom_level < 1 ? 0.1 : zoom_level * 0.1)
685
+ : zoom_level - (zoom_level < 1 ? 0.1 : zoom_level * 0.1)
686
+ );
687
+ }
688
+
689
+ async function process_clipboard(): Promise<void> {
690
+ const items = await navigator.clipboard.read();
691
+
692
+ for (let i = 0; i < items.length; i++) {
693
+ const type = items[i].types.find((t) => t.startsWith("image/"));
694
+ if (type) {
695
+ const blob = await items[i].getType(type);
696
+
697
+ handle_files(blob);
698
+ }
699
+ }
700
+ }
701
+
702
+ function handle_capture(value: FileData | Blob | null): void {
703
+ if (value !== null) {
704
+ handle_files(value as Blob);
705
+ }
706
+ handle_subtool_change({ tool: current_tool, subtool: null });
707
+ }
708
+
709
+ function handle_save(): void {
710
+ onsave?.();
711
+ }
712
+
713
+ $effect(() => {
714
+ add_image_from_url(composite || background);
715
+ });
716
+ $effect(() => {
717
+ add_layers_from_url(layers);
718
+ });
719
+
720
+ async function handle_crop_confirm(): Promise<void> {
721
+ const { image } = await crop.get_crop_bounds();
722
+ if (!image) return;
723
+
724
+ await editor.add_image({
725
+ image,
726
+ resize: false
727
+ });
728
+ handle_subtool_change({ tool: "image", subtool: null });
729
+ onchange?.();
730
+ oninput?.();
731
+ }
732
+
733
+ async function handle_download(): Promise<void> {
734
+ const blobs = await editor.get_blobs();
735
+
736
+ const blob = blobs.composite;
737
+ if (!blob) {
738
+ ondownload_error?.("Unable to generate image to download.");
739
+ return;
740
+ }
741
+ const url = URL.createObjectURL(blob);
742
+ const link = document.createElement("a");
743
+ link.href = url;
744
+ link.download = "image.png";
745
+ link.click();
746
+ URL.revokeObjectURL(url);
747
+ }
748
+
749
+ function handle_undo(): void {
750
+ editor.undo();
751
+ }
752
+
753
+ function handle_redo(): void {
754
+ editor.redo();
755
+ }
756
+
757
+ let old_background = background;
758
+
759
+ $effect(() => {
760
+ if (old_background === background) return;
761
+ handle_tool_change({ tool: "draw" });
762
+ handle_subtool_change({ tool: "draw", subtool: null });
763
+ current_tool = "draw";
764
+ old_background = background;
765
+ });
766
+ </script>
767
+
768
+ <div
769
+ data-testid="image"
770
+ class="image-container"
771
+ class:dark-bg={current_subtool === "crop"}
772
+ use:drag={{
773
+ on_drag_change: (dragging) => (is_dragging = dragging),
774
+ on_files: handle_files,
775
+ accepted_types: "image/*",
776
+ disable_click: disable_click,
777
+ ignore_click_selector: ".toolbar-wrap"
778
+ }}
779
+ aria-label={"Click to upload or drop files"}
780
+ aria-dropeffect="copy"
781
+ >
782
+ {#if ready}
783
+ {#if current_subtool !== "crop"}
784
+ <Controls
785
+ {changeable}
786
+ onset_zoom={(zoom) => handle_zoom_change(zoom)}
787
+ onzoom_in={() => zoom_in_out("in")}
788
+ onzoom_out={() => zoom_in_out("out")}
789
+ {min_zoom}
790
+ current_zoom={zoom_level}
791
+ onremove_image={remove_image}
792
+ tool={current_tool}
793
+ can_save={true}
794
+ onsave={handle_save}
795
+ onpan={() => {
796
+ handle_tool_change({ tool: "pan" });
797
+ }}
798
+ enable_download={show_download_button}
799
+ ondownload={() => handle_download()}
800
+ {can_undo}
801
+ {can_redo}
802
+ onundo={handle_undo}
803
+ onredo={handle_redo}
804
+ />
805
+ {/if}
806
+
807
+ {#if current_subtool !== "crop"}
808
+ <Toolbar
809
+ {sources}
810
+ {transforms}
811
+ background={background_image}
812
+ ontool_change={(detail) => handle_tool_change(detail)}
813
+ onsubtool_change={(detail) => handle_subtool_change(detail)}
814
+ show_brush_size={brush_size_visible}
815
+ show_brush_color={brush_color_visible}
816
+ show_eraser_size={eraser_size_visible}
817
+ {brush_options}
818
+ {eraser_options}
819
+ bind:selected_color
820
+ bind:selected_size
821
+ bind:selected_eraser_size
822
+ bind:selected_opacity
823
+ bind:preview
824
+ tool={current_tool}
825
+ subtool={current_subtool}
826
+ />
827
+ {/if}
828
+
829
+ {#if current_tool === "image" && current_subtool === "webcam"}
830
+ <div class="modal">
831
+ <div class="modal-inner">
832
+ <Webcam
833
+ {upload}
834
+ {root}
835
+ oncapture={handle_capture}
836
+ streaming={false}
837
+ mode="image"
838
+ include_audio={false}
839
+ {i18n}
840
+ mirror_webcam={webcam_options.mirror}
841
+ webcam_constraints={webcam_options.constraints}
842
+ />
843
+ </div>
844
+ </div>
845
+ {/if}
846
+
847
+ {#if current_subtool !== "crop" && !layer_options.disabled}
848
+ <SecondaryToolbar
849
+ enable_additional_layers={layer_options.allow_additional_layers}
850
+ layers={editor.layers}
851
+ onnew_layer={() => {
852
+ editor.add_layer();
853
+ }}
854
+ onchange_layer={(id) => {
855
+ editor.set_layer(id);
856
+ if (current_tool === "draw") {
857
+ handle_tool_change({ tool: "draw" });
858
+ }
859
+ }}
860
+ onmove_layer={({ id, direction }) => {
861
+ editor.move_layer(id, direction);
862
+ }}
863
+ ondelete_layer={(id) => {
864
+ editor.delete_layer(id);
865
+ }}
866
+ ontoggle_layer_visibility={(id) => {
867
+ editor.toggle_layer_visibility(id);
868
+ }}
869
+ />
870
+ {/if}
871
+ {/if}
872
+ <div
873
+ class="pixi-target"
874
+ class:visible={current_subtool !== "crop"}
875
+ bind:this={pixi_target}
876
+ ></div>
877
+ <div
878
+ class="pixi-target-crop"
879
+ class:visible={current_subtool === "crop"}
880
+ bind:this={pixi_target_crop}
881
+ ></div>
882
+
883
+ {#if current_subtool === "crop"}
884
+ <div class="crop-confirm-button">
885
+ <IconButton
886
+ Icon={Check}
887
+ label="Confirm crop"
888
+ show_label={true}
889
+ size="large"
890
+ padded={true}
891
+ color="white"
892
+ background="var(--color-green-500)"
893
+ label_position="right"
894
+ onclick={handle_crop_confirm}
895
+ />
896
+ </div>
897
+ {/if}
898
+ {#if children}{@render children()}{/if}
899
+ </div>
900
+
901
+ <style>
902
+ .image-container {
903
+ display: flex;
904
+ height: 100%;
905
+ flex-direction: column;
906
+ justify-content: center;
907
+ align-items: center;
908
+ max-height: 100%;
909
+ border-radius: var(--radius-sm);
910
+ }
911
+
912
+ .pixi-target {
913
+ width: 100%;
914
+ height: 100%;
915
+ position: absolute;
916
+ top: 0;
917
+ left: 0;
918
+ z-index: 1;
919
+ display: block;
920
+ opacity: 0;
921
+ pointer-events: none;
922
+ border-radius: var(--radius-sm);
923
+ }
924
+
925
+ .pixi-target-crop {
926
+ width: 100%;
927
+ height: 100%;
928
+ position: absolute;
929
+ top: 0;
930
+ left: 0;
931
+ z-index: 2;
932
+ display: block;
933
+ opacity: 0;
934
+ pointer-events: none;
935
+ border-radius: var(--radius-sm);
936
+ }
937
+
938
+ .visible {
939
+ opacity: 1;
940
+ pointer-events: auto;
941
+ }
942
+
943
+ .pixi-target {
944
+ width: 100%;
945
+ height: 100%;
946
+ position: absolute;
947
+ top: 0;
948
+ left: 0;
949
+ right: 0;
950
+ bottom: 0;
951
+ overflow: hidden;
952
+ }
953
+
954
+ .modal {
955
+ position: absolute;
956
+ height: 100%;
957
+ width: 100%;
958
+ left: 0;
959
+ right: 0;
960
+ margin: auto;
961
+ z-index: var(--layer-top);
962
+ display: flex;
963
+ align-items: center;
964
+ }
965
+
966
+ .modal-inner {
967
+ height: 100%;
968
+ width: 100%;
969
+ background: var(--block-background-fill);
970
+ }
971
+
972
+ .dark-bg {
973
+ background: #333;
974
+ }
975
+
976
+ .crop-confirm-button {
977
+ position: absolute;
978
+ bottom: 8px;
979
+ left: 0;
980
+ right: 0;
981
+ margin: auto;
982
+ z-index: var(--layer-top);
983
+ display: flex;
984
+ align-items: center;
985
+ justify-content: center;
986
+ }
987
+ </style>
6.26.1/imageeditor/shared/Layers.svelte ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { click_outside } from "./utils/events";
3
+ import {
4
+ Layers,
5
+ Clear,
6
+ ArrowUp,
7
+ ArrowDown,
8
+ Plus,
9
+ Visibility,
10
+ VisibilityOff
11
+ } from "@gradio/icons";
12
+ import { IconButton } from "@gradio/atoms";
13
+ import type { Writable } from "svelte/store";
14
+
15
+ let {
16
+ layers,
17
+ enable_additional_layers = true,
18
+ enable_layers = true,
19
+ show_layers = false,
20
+ onnew_layer,
21
+ onchange_layer,
22
+ onmove_layer,
23
+ ondelete_layer,
24
+ ontoggle_layer_visibility
25
+ }: {
26
+ layers: Writable<{
27
+ active_layer: string;
28
+ layers: {
29
+ name: string;
30
+ id: string;
31
+ user_created: boolean;
32
+ visible: boolean;
33
+ }[];
34
+ }>;
35
+ enable_additional_layers?: boolean;
36
+ enable_layers?: boolean;
37
+ show_layers?: boolean;
38
+ onnew_layer?: () => void;
39
+ onchange_layer?: (id: string) => void;
40
+ onmove_layer?: (value: { id: string; direction: "up" | "down" }) => void;
41
+ ondelete_layer?: (id: string) => void;
42
+ ontoggle_layer_visibility?: (id: string) => void;
43
+ } = $props();
44
+
45
+ function new_layer(): void {
46
+ onnew_layer?.();
47
+ }
48
+
49
+ function change_layer(id: string): void {
50
+ onchange_layer?.(id);
51
+ show_layers = false;
52
+ }
53
+
54
+ function move_layer(id: string, direction: "up" | "down"): void {
55
+ onmove_layer?.({ id, direction });
56
+ }
57
+
58
+ function delete_layer(id: string): void {
59
+ ondelete_layer?.(id);
60
+ }
61
+ </script>
62
+
63
+ {#if enable_layers}
64
+ <div
65
+ class="layer-wrap"
66
+ class:closed={!show_layers}
67
+ use:click_outside={() => (show_layers = false)}
68
+ >
69
+ <button
70
+ class="layer-title-button"
71
+ aria-label="Show Layers"
72
+ onclick={(event) => {
73
+ event.stopPropagation();
74
+ show_layers = !show_layers;
75
+ }}
76
+ >
77
+ {show_layers
78
+ ? "Layers"
79
+ : $layers.layers.find((l) => l.id === $layers.active_layer)?.name}
80
+ <span class="icon"><Layers /></span>
81
+ </button>
82
+ {#if show_layers}
83
+ <ul>
84
+ {#each $layers.layers as { id, name, user_created, visible }, i (i)}
85
+ <li>
86
+ {#if !visible}
87
+ <IconButton
88
+ Icon={VisibilityOff}
89
+ size="small"
90
+ onclick={(e) => {
91
+ e.stopPropagation();
92
+ ontoggle_layer_visibility?.(id);
93
+ }}
94
+ />
95
+ {:else}
96
+ <IconButton
97
+ Icon={Visibility}
98
+ size="small"
99
+ onclick={(e) => {
100
+ e.stopPropagation();
101
+ ontoggle_layer_visibility?.(id);
102
+ }}
103
+ />
104
+ {/if}
105
+ <button
106
+ class:selected_layer={$layers.active_layer === id}
107
+ aria-label={`layer-${i + 1}`}
108
+ onclick={(event) => {
109
+ event.stopPropagation();
110
+ change_layer(id);
111
+ }}>{name}</button
112
+ >
113
+ {#if $layers.layers.length > 1}
114
+ <div>
115
+ {#if i > 0}
116
+ <IconButton
117
+ onclick={(e) => {
118
+ e.stopPropagation();
119
+ move_layer(id, "up");
120
+ }}
121
+ Icon={ArrowUp}
122
+ size="x-small"
123
+ />
124
+ {/if}
125
+ {#if i < $layers.layers.length - 1}
126
+ <IconButton
127
+ onclick={(e) => {
128
+ e.stopPropagation();
129
+ move_layer(id, "down");
130
+ }}
131
+ Icon={ArrowDown}
132
+ size="x-small"
133
+ />
134
+ {/if}
135
+ {#if $layers.layers.length > 1 && user_created}
136
+ <IconButton
137
+ onclick={(e) => {
138
+ e.stopPropagation();
139
+ delete_layer(id);
140
+ }}
141
+ Icon={Clear}
142
+ size="x-small"
143
+ />
144
+ {/if}
145
+ </div>
146
+ {/if}
147
+ </li>
148
+ {/each}
149
+ {#if enable_additional_layers}
150
+ <li class="add-layer">
151
+ <IconButton
152
+ Icon={Plus}
153
+ label="Add Layer"
154
+ onclick={(e) => {
155
+ e.stopPropagation();
156
+ new_layer();
157
+ }}
158
+ size="x-small"
159
+ />
160
+ </li>
161
+ {/if}
162
+ </ul>
163
+ {/if}
164
+ </div>
165
+ {/if}
166
+
167
+ <style>
168
+ .add-layer {
169
+ display: flex;
170
+ justify-content: center;
171
+ align-items: center;
172
+ margin: var(--spacing-sm) 0 0 0;
173
+ }
174
+
175
+ .add-layer :global(button) {
176
+ width: 100%;
177
+ }
178
+ .icon {
179
+ width: 14px;
180
+ color: var(--body-text-color);
181
+ transition: color 0.15s ease;
182
+ }
183
+
184
+ .layer-wrap {
185
+ /* position: absolute; */
186
+ display: flex;
187
+ justify-content: center;
188
+ align-items: center;
189
+ /* border: 1px solid var(--border-color-primary); */
190
+ /* z-index: var(--layer-1); */
191
+ /* border-radius: var(--radius-sm); */
192
+ /* background-color: var(--block-background-fill); */
193
+ width: 100%;
194
+ flex-direction: column;
195
+ /* bottom: 5px; */
196
+ /* right: 5px; */
197
+ /* border-bottom: 0;
198
+ border-right: 0; */
199
+ /* box-shadow: var(--shadow-drop); */
200
+ }
201
+
202
+ .layer-wrap button {
203
+ justify-content: space-between;
204
+ align-items: center;
205
+ width: 100%;
206
+ display: flex;
207
+ font-size: var(--text-sm);
208
+ line-height: var(--line-sm);
209
+ transition: all 0.15s ease;
210
+ padding: var(--spacing-md) var(--spacing-lg);
211
+ /* padding-right: var(--spacing-lg); */
212
+ border-radius: var(--radius-sm);
213
+ /* padding-left: 30px; */
214
+ }
215
+
216
+ button.layer-title-button {
217
+ width: 100%;
218
+ /* padding-left: 30px; */
219
+ }
220
+
221
+ .layer-wrap button:hover .icon {
222
+ color: var(--color-accent);
223
+ }
224
+
225
+ .selected_layer {
226
+ color: var(--color-accent);
227
+ font-weight: var(--weight-semibold);
228
+ }
229
+
230
+ ul {
231
+ /* position: absolute; */
232
+ bottom: 0;
233
+ right: 0;
234
+ /* background: var(--block-background-fill); */
235
+ width: 100%;
236
+ /* min-width: 100%; */
237
+ list-style: none;
238
+ z-index: var(--layer-top);
239
+ /* border: 1px solid var(--border-color-primary); */
240
+ /* border-radius: var(--radius-sm); */
241
+ /* box-shadow: var(--shadow-drop-lg); */
242
+ padding: var(--spacing-sm);
243
+ /* transform: translate(-1px, 1px); */
244
+ border-top: 1px solid var(--border-color-primary);
245
+ }
246
+
247
+ /* .sep {
248
+ height: 12px;
249
+ background-color: var(--block-border-color);
250
+ width: 1px;
251
+ display: block;
252
+ margin-left: var(--spacing-xl);
253
+ } */
254
+
255
+ li {
256
+ display: flex;
257
+ justify-content: space-between;
258
+ align-items: center;
259
+ /* border-radius: var(--radius-sm); */
260
+ transition: background-color 0.15s ease;
261
+ border-bottom: 1px solid var(--border-color-primary);
262
+ }
263
+
264
+ .layer-wrap ul > li > button {
265
+ padding-left: calc(var(--spacing-md));
266
+ }
267
+
268
+ li:hover {
269
+ background-color: var(--background-fill-secondary);
270
+ }
271
+
272
+ li:last-child {
273
+ border-bottom: none;
274
+ }
275
+ li:last-child:hover {
276
+ background-color: unset;
277
+ }
278
+
279
+ li div {
280
+ display: flex;
281
+ gap: var(--spacing-sm);
282
+ padding: var(--spacing-sm);
283
+ }
284
+ li > button {
285
+ padding: var(--spacing-sm) var(--spacing-md);
286
+ }
287
+
288
+ /* li > div > button {
289
+ opacity: 0.7;
290
+ transition: opacity 0.15s ease;
291
+ }
292
+
293
+ li > div > button:hover {
294
+ opacity: 1;
295
+ } */
296
+ </style>
6.26.1/imageeditor/shared/Resize.svelte ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script module lang="ts">
2
+ export type Position =
3
+ | "top-left"
4
+ | "top"
5
+ | "top-right"
6
+ | "left"
7
+ | "center"
8
+ | "right"
9
+ | "bottom-left"
10
+ | "bottom"
11
+ | "bottom-right";
12
+ </script>
13
+
14
+ <script lang="ts">
15
+ import type { Spring } from "svelte/motion";
16
+ import Anchor from "./Anchor.svelte";
17
+
18
+ let {
19
+ dimensions,
20
+ onchange
21
+ }: {
22
+ dimensions: Spring<{ width: number; height: number }>;
23
+ onchange?: (value: {
24
+ anchor: Position;
25
+ scale: boolean;
26
+ width: number;
27
+ height: number;
28
+ }) => void;
29
+ } = $props();
30
+
31
+ let selected_anchor = $state<Position>("center");
32
+ let scale = $state(false);
33
+
34
+ let new_width = $state($dimensions?.width);
35
+ let new_height = $state($dimensions?.height);
36
+
37
+ function handle_click(): void {
38
+ onchange?.({
39
+ anchor: selected_anchor,
40
+ scale,
41
+ width: new_width,
42
+ height: new_height
43
+ });
44
+ }
45
+
46
+ function set_anchor(position: Position): void {
47
+ selected_anchor = position;
48
+ }
49
+ </script>
50
+
51
+ <!-- svelte-ignore a11y-click-events-have-key-events -->
52
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
53
+ <div class="wrap" onclick={(event) => event.stopPropagation()}>
54
+ <div class="size-wrap">
55
+ <div class="size-input">
56
+ <label for="width">Width</label><input
57
+ type="number"
58
+ id="width"
59
+ bind:value={new_width}
60
+ />
61
+ </div>
62
+ <div class="size-input">
63
+ <label for="height">Height </label><input
64
+ type="number"
65
+ id="height"
66
+ bind:value={new_height}
67
+ />
68
+ </div>
69
+ </div>
70
+
71
+ <div class="scale-wrap">
72
+ <h2 class="image-will-label">Image will:</h2>
73
+ <div class="toggle-container">
74
+ <label class="radio-label">
75
+ <input
76
+ type="radio"
77
+ name="resize_mode"
78
+ value={true}
79
+ bind:group={scale}
80
+ />
81
+ <span class="radio-button">rescale</span>
82
+ </label>
83
+ <label class="radio-label">
84
+ <input
85
+ type="radio"
86
+ name="resize_mode"
87
+ value={false}
88
+ bind:group={scale}
89
+ />
90
+ <span class="radio-button">anchor</span>
91
+ </label>
92
+ </div>
93
+ </div>
94
+ <div class="anchor-wrap">
95
+ <Anchor onposition={(position) => set_anchor(position)} />
96
+ </div>
97
+ <button class="apply-button" onclick={() => handle_click()}
98
+ >Resize Canvas</button
99
+ >
100
+ </div>
101
+
102
+ <!-- </div> -->
103
+
104
+ <style>
105
+ .wrap {
106
+ padding: var(--spacing-xl) var(--spacing-lg);
107
+ color: var(--block-label-text-color);
108
+ }
109
+
110
+ .size-wrap {
111
+ display: flex;
112
+ flex-direction: row;
113
+ gap: 10px;
114
+ }
115
+
116
+ .size-input {
117
+ display: flex;
118
+ flex-direction: column;
119
+ gap: var(--spacing-xxs);
120
+ }
121
+
122
+ label,
123
+ h2 {
124
+ display: flex;
125
+ align-items: center;
126
+ gap: 15px;
127
+
128
+ cursor: pointer;
129
+ color: var(--checkbox-label-text-color);
130
+ font-weight: var(--checkbox-label-text-weight);
131
+ font-size: var(--text-sm);
132
+ line-height: var(--line-md);
133
+ }
134
+
135
+ .scale-wrap {
136
+ display: flex;
137
+ flex-direction: column;
138
+ gap: var(--spacing-sm);
139
+ margin-top: var(--spacing-md);
140
+ }
141
+
142
+ input[type="number"] {
143
+ border: 1px solid var(--border-color-primary);
144
+ width: 60px;
145
+ border-radius: var(--radius-sm);
146
+ background-color: var(--checkbox-background-color-focus);
147
+ color: var(--body-text-color);
148
+ font-size: var(--text-sm);
149
+ transition: border-color 0.15s ease;
150
+ padding: var(--spacing-xs);
151
+ line-height: 1rem;
152
+ }
153
+
154
+ input[type="number"]:hover {
155
+ border-color: var(--color-accent-soft);
156
+ }
157
+
158
+ input[type="number"]:focus {
159
+ border-color: var(--color-accent);
160
+ outline: none;
161
+ box-shadow: 0 0 0 1px var(--color-accent-soft);
162
+ }
163
+
164
+ .image-will-label {
165
+ grid-column: 1;
166
+ }
167
+
168
+ .toggle-container {
169
+ display: flex;
170
+ grid-column: 2;
171
+ border-radius: var(--radius-sm);
172
+ border: 1px solid var(--border-color-primary);
173
+ overflow: hidden;
174
+ }
175
+
176
+ .toggle-container {
177
+ display: flex;
178
+ grid-column: 2;
179
+ border-radius: var(--radius-sm);
180
+ border: 1px solid var(--border-color-primary);
181
+ overflow: hidden;
182
+ }
183
+
184
+ .radio-label {
185
+ flex: 1;
186
+ margin: 0;
187
+ padding: 0;
188
+ position: relative;
189
+ cursor: pointer;
190
+ }
191
+
192
+ .radio-button {
193
+ display: flex;
194
+ justify-content: center;
195
+ align-items: center;
196
+ padding: var(--spacing-sm);
197
+ background: var(--checkbox-background-color);
198
+ color: var(--body-text-color);
199
+ font-size: var(--text-sm);
200
+ transition: background-color 0.15s ease;
201
+ width: 100%;
202
+ height: 100%;
203
+ }
204
+
205
+ input[type="radio"] {
206
+ position: absolute;
207
+ opacity: 0;
208
+ width: 0;
209
+ height: 0;
210
+ }
211
+
212
+ input[type="radio"]:not(:checked) + .radio-button:hover {
213
+ background: var(--checkbox-background-color-hover);
214
+ }
215
+
216
+ input[type="radio"]:checked + .radio-button {
217
+ background: var(--color-accent);
218
+ color: white;
219
+ }
220
+
221
+ .apply-button {
222
+ width: 100%;
223
+ margin-top: var(--spacing-md);
224
+ padding: var(--spacing-sm) var(--spacing-md);
225
+ background: var(--color-accent);
226
+ color: white;
227
+ border: none;
228
+ border-radius: var(--radius-sm);
229
+ font-size: var(--text-sm);
230
+ font-weight: var(--weight-semibold);
231
+ transition: all 0.15s ease;
232
+ }
233
+
234
+ .apply-button:hover {
235
+ background: var(--button-primary-background-fill-hover);
236
+ }
237
+
238
+ .anchor-wrap {
239
+ display: flex;
240
+ justify-content: center;
241
+ align-items: center;
242
+ flex-direction: column;
243
+ gap: 10px;
244
+ }
245
+ </style>
6.26.1/imageeditor/shared/SecondaryToolbar.svelte ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import Layers from "./Layers.svelte";
3
+ import type { Writable } from "svelte/store";
4
+
5
+ let {
6
+ layers,
7
+ enable_additional_layers = true,
8
+ enable_layers = true,
9
+ show_layers = false,
10
+ onnew_layer,
11
+ onchange_layer,
12
+ onmove_layer,
13
+ ondelete_layer,
14
+ ontoggle_layer_visibility
15
+ }: {
16
+ layers: Writable<{
17
+ active_layer: string;
18
+ layers: {
19
+ name: string;
20
+ id: string;
21
+ user_created: boolean;
22
+ visible: boolean;
23
+ }[];
24
+ }>;
25
+ enable_additional_layers?: boolean;
26
+ enable_layers?: boolean;
27
+ show_layers?: boolean;
28
+ onnew_layer?: () => void;
29
+ onchange_layer?: (id: string) => void;
30
+ onmove_layer?: (value: { id: string; direction: "up" | "down" }) => void;
31
+ ondelete_layer?: (id: string) => void;
32
+ ontoggle_layer_visibility?: (id: string) => void;
33
+ } = $props();
34
+ </script>
35
+
36
+ <div class="toolbar-wrap-wrap">
37
+ <div class="toolbar-wrap">
38
+ {#if enable_layers}
39
+ <Layers
40
+ {layers}
41
+ {enable_additional_layers}
42
+ {enable_layers}
43
+ {show_layers}
44
+ {onnew_layer}
45
+ {onchange_layer}
46
+ {onmove_layer}
47
+ {ondelete_layer}
48
+ {ontoggle_layer_visibility}
49
+ />
50
+ {/if}
51
+ </div>
52
+ </div>
53
+
54
+ <style>
55
+ .toolbar-wrap-wrap {
56
+ position: absolute;
57
+ right: 0;
58
+ bottom: 0;
59
+ width: fit-content;
60
+ max-height: 100%;
61
+ overflow-y: auto;
62
+ display: flex;
63
+ flex-direction: column-reverse;
64
+ }
65
+
66
+ .toolbar-wrap {
67
+ min-width: 110px;
68
+ display: flex;
69
+ flex-direction: column;
70
+ justify-content: center;
71
+ align-items: center;
72
+ position: relative;
73
+ right: 0;
74
+ bottom: 0;
75
+ border: 1px solid var(--block-border-color);
76
+ border-radius: 0;
77
+ border-top-left-radius: var(--radius-md);
78
+ border-right: none;
79
+ border-bottom: none;
80
+ z-index: 1000;
81
+ background-color: var(--block-background-fill);
82
+ }
83
+ </style>
6.26.1/imageeditor/shared/Toolbar.svelte ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script module lang="ts">
2
+ export type Tool = "image" | "draw" | "erase" | "pan";
3
+ export type Subtool =
4
+ | "upload"
5
+ | "paste"
6
+ | "webcam"
7
+ | "color"
8
+ | "size"
9
+ | "crop"
10
+ | "remove_background"
11
+ | null;
12
+ </script>
13
+
14
+ <script lang="ts">
15
+ import IconButton from "./IconButton.svelte";
16
+ import {
17
+ Image,
18
+ Brush,
19
+ BrushSize,
20
+ Erase,
21
+ Crop,
22
+ Upload,
23
+ ImagePaste,
24
+ Webcam,
25
+ Resize,
26
+ ColorPickerSolid
27
+ } from "@gradio/icons";
28
+ import BrushOptions from "./brush/BrushOptions.svelte";
29
+ import type { Source, Transform } from "./types";
30
+ import {
31
+ type Brush as BrushType,
32
+ type Eraser as EraserType
33
+ } from "./brush/types";
34
+
35
+ let {
36
+ tool = "image",
37
+ subtool = null,
38
+ background = false,
39
+ brush_options,
40
+ selected_size = $bindable(25),
41
+ eraser_options,
42
+ selected_eraser_size = $bindable(25),
43
+ selected_color = $bindable(),
44
+ selected_opacity = $bindable(1),
45
+ preview = $bindable(),
46
+ show_brush_color = false,
47
+ show_brush_size = false,
48
+ show_eraser_size = false,
49
+ sources,
50
+ transforms,
51
+ ontool_change,
52
+ onsubtool_change
53
+ }: {
54
+ tool?: Tool;
55
+ subtool?: Subtool;
56
+ background?: boolean;
57
+ brush_options: BrushType | false;
58
+ selected_size?: number;
59
+ eraser_options: EraserType | false;
60
+ selected_eraser_size?: number;
61
+ selected_color?: any;
62
+ selected_opacity?: number;
63
+ preview?: boolean;
64
+ show_brush_color?: boolean;
65
+ show_brush_size?: boolean;
66
+ show_eraser_size?: boolean;
67
+ sources: Source[];
68
+ transforms: Transform[];
69
+ ontool_change?: (value: { tool: Tool }) => void;
70
+ onsubtool_change?: (value: { tool: Tool; subtool: Subtool }) => void;
71
+ } = $props();
72
+
73
+ let recent_colors = $state<string[]>([]);
74
+
75
+ /**
76
+ * Handles tool click events
77
+ * @param {Tool} _tool - The selected tool
78
+ */
79
+ function handle_tool_click(e: Event, _tool: Tool): void {
80
+ e.stopPropagation();
81
+ ontool_change?.({ tool: _tool });
82
+ }
83
+
84
+ /**
85
+ * Handles subtool click events
86
+ * @param {Event} e - The click event
87
+ * @param {Subtool} _subtool - The selected subtool
88
+ */
89
+ function handle_subtool_click(e: Event, _subtool: typeof subtool): void {
90
+ e.stopPropagation();
91
+
92
+ onsubtool_change?.({ tool, subtool: _subtool });
93
+ }
94
+
95
+ $effect(() => {
96
+ show_brush_size = tool === "draw" && subtool === "size";
97
+ show_brush_color = tool === "draw" && subtool === "color";
98
+ show_eraser_size = tool === "erase" && subtool === "size";
99
+ });
100
+
101
+ let can_crop = $derived(transforms.includes("crop"));
102
+ let can_resize = $derived(transforms.includes("resize"));
103
+ let can_upload = $derived(sources.includes("upload"));
104
+ let can_webcam = $derived(sources.includes("webcam"));
105
+ let can_paste = $derived(sources.includes("clipboard"));
106
+ let can_edit_image = $derived(
107
+ sources.length > 0 || (background && transforms.length > 0)
108
+ );
109
+ </script>
110
+
111
+ <div class="toolbar-wrap" onclick={(e) => e.stopPropagation()}>
112
+ <div class="half-container">
113
+ {#if can_edit_image}
114
+ <IconButton
115
+ Icon={Image}
116
+ label="Image"
117
+ highlight={tool === "image"}
118
+ onclick={(e) => handle_tool_click(e, "image")}
119
+ size="medium"
120
+ padded={false}
121
+ transparent={true}
122
+ />
123
+ {/if}
124
+ {#if brush_options}
125
+ <IconButton
126
+ Icon={Brush}
127
+ label="Brush"
128
+ onclick={(e) => handle_tool_click(e, "draw")}
129
+ highlight={tool === "draw"}
130
+ size="medium"
131
+ padded={false}
132
+ transparent={true}
133
+ />
134
+ {/if}
135
+ {#if eraser_options}
136
+ <IconButton
137
+ Icon={Erase}
138
+ label="Erase"
139
+ onclick={(e) => handle_tool_click(e, "erase")}
140
+ highlight={tool === "erase"}
141
+ size="medium"
142
+ padded={false}
143
+ transparent={true}
144
+ />
145
+ {/if}
146
+ </div>
147
+ <div
148
+ class="half-container right"
149
+ class:hide={tool === "pan" ||
150
+ (tool === "image" && !background && sources.length === 0) ||
151
+ (tool === "image" && background && transforms.length === 0)}
152
+ >
153
+ {#if tool === "image"}
154
+ {#if background}
155
+ {#if can_crop}
156
+ <IconButton
157
+ Icon={Crop}
158
+ label="Crop"
159
+ onclick={(e) => handle_subtool_click(e, "crop")}
160
+ highlight={subtool === "crop"}
161
+ size="medium"
162
+ padded={false}
163
+ transparent={true}
164
+ offset={0}
165
+ />
166
+ {/if}
167
+ {#if can_resize}
168
+ <IconButton
169
+ Icon={Resize}
170
+ label="Resize"
171
+ onclick={(e) => handle_subtool_click(e, "size")}
172
+ highlight={subtool === "size"}
173
+ size="medium"
174
+ padded={false}
175
+ transparent={true}
176
+ offset={0}
177
+ />
178
+ {/if}
179
+ {:else}
180
+ {#if can_upload}
181
+ <IconButton
182
+ Icon={Upload}
183
+ label="Upload"
184
+ onclick={(e) => handle_subtool_click(e, "upload")}
185
+ highlight={subtool === "upload"}
186
+ size="medium"
187
+ padded={false}
188
+ transparent={true}
189
+ offset={0}
190
+ />
191
+ {/if}
192
+ {#if can_paste}
193
+ <IconButton
194
+ Icon={ImagePaste}
195
+ label="Paste"
196
+ onclick={(e) => handle_subtool_click(e, "paste")}
197
+ highlight={subtool === "paste"}
198
+ size="large"
199
+ padded={false}
200
+ transparent={true}
201
+ offset={0}
202
+ />
203
+ {/if}
204
+ {#if can_webcam}
205
+ <IconButton
206
+ Icon={Webcam}
207
+ label="Webcam"
208
+ onclick={(e) => handle_subtool_click(e, "webcam")}
209
+ highlight={subtool === "webcam"}
210
+ size="medium"
211
+ padded={false}
212
+ transparent={true}
213
+ offset={0}
214
+ />
215
+ {/if}
216
+ {/if}
217
+ {/if}
218
+
219
+ {#if tool === "draw" && brush_options}
220
+ <IconButton
221
+ Icon={ColorPickerSolid}
222
+ label="Color"
223
+ color={selected_color}
224
+ onclick={(e) => handle_subtool_click(e, "color")}
225
+ size="medium"
226
+ padded={false}
227
+ transparent={true}
228
+ offset={0}
229
+ />
230
+ <IconButton
231
+ Icon={BrushSize}
232
+ label="Brush Size"
233
+ onclick={(e) => handle_subtool_click(e, "size")}
234
+ highlight={subtool === "size"}
235
+ size="medium"
236
+ padded={false}
237
+ transparent={true}
238
+ offset={0}
239
+ />
240
+
241
+ {#if show_brush_color || show_brush_size}
242
+ <BrushOptions
243
+ colors={brush_options.colors}
244
+ color_mode={brush_options.color_mode}
245
+ {recent_colors}
246
+ show_swatch={show_brush_color}
247
+ show_size={show_brush_size}
248
+ bind:selected_size
249
+ bind:selected_color
250
+ bind:selected_opacity
251
+ bind:preview
252
+ onclick_outside={(e) => {
253
+ e.stopPropagation();
254
+ preview = false;
255
+ show_brush_color = false;
256
+ show_brush_size = false;
257
+ handle_subtool_click(e, null);
258
+ }}
259
+ mode="brush"
260
+ />
261
+ {/if}
262
+ {/if}
263
+
264
+ {#if tool === "erase" && eraser_options}
265
+ <IconButton
266
+ Icon={BrushSize}
267
+ label="Eraser Size"
268
+ onclick={(e) => handle_subtool_click(e, "size")}
269
+ highlight={subtool === "size"}
270
+ size="medium"
271
+ padded={false}
272
+ transparent={true}
273
+ offset={0}
274
+ />
275
+ {/if}
276
+ {#if show_eraser_size}
277
+ <BrushOptions
278
+ colors={[]}
279
+ show_swatch={false}
280
+ show_size={true}
281
+ bind:selected_size={selected_eraser_size}
282
+ bind:selected_color
283
+ bind:selected_opacity
284
+ bind:preview
285
+ onclick_outside={(e) => {
286
+ e.stopPropagation();
287
+ preview = false;
288
+ show_eraser_size = false;
289
+ handle_subtool_click(e, null);
290
+ }}
291
+ mode="eraser"
292
+ />
293
+ {/if}
294
+ </div>
295
+ </div>
296
+
297
+ <style>
298
+ .toolbar-wrap {
299
+ display: inline-flex;
300
+ flex-direction: column;
301
+ justify-content: center;
302
+ align-items: center;
303
+ position: absolute;
304
+ left: 15px;
305
+ right: 0;
306
+ top: 30%;
307
+ /* transform: translateY(-50%); */
308
+ width: 30px;
309
+ border: 1px solid var(--block-border-color);
310
+ border-radius: var(--radius-md);
311
+
312
+ gap: var(--spacing-sm);
313
+ z-index: 1000;
314
+ background-color: var(--block-background-fill);
315
+ }
316
+
317
+ .half-container {
318
+ flex: 1;
319
+ display: flex;
320
+ flex-direction: column;
321
+ gap: var(--spacing-sm);
322
+ position: relative;
323
+ }
324
+
325
+ .half-container {
326
+ width: 100%;
327
+ padding: var(--spacing-sm) 0;
328
+ }
329
+
330
+ .half-container:last-child {
331
+ border-top: 1px solid var(--block-border-color);
332
+ }
333
+
334
+ .hide {
335
+ display: none;
336
+ }
337
+
338
+ /* .toolbar-left,
339
+ .toolbar-right {
340
+ display: flex;
341
+ flex-direction: row;
342
+ align-items: center;
343
+ gap: var(--spacing-sm);
344
+ display: flex;
345
+ z-index: 1000;
346
+ border-radius: var(--radius-sm);
347
+ background-color: #fff;
348
+ padding: var(--spacing-sm) 0.3rem;
349
+ width: auto;
350
+ }
351
+
352
+ .toolbar-right {
353
+ border-left: 0;
354
+ border-top-left-radius: 0;
355
+ border-bottom-left-radius: 0;
356
+ }
357
+
358
+ .toolbar-left {
359
+ border-top-right-radius: 0;
360
+ border-bottom-right-radius: 0;
361
+ }
362
+
363
+ .toolbar-layers {
364
+ border-top-left-radius: 0;
365
+ border-bottom-left-radius: 0;
366
+ } */
367
+ </style>
6.26.1/imageeditor/shared/brush/BrushOptions.svelte ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { click_outside } from "../utils/events";
3
+
4
+ import { type Brush, type ColorTuple } from "./types";
5
+ import ColorPicker from "./ColorPicker.svelte";
6
+ import ColorSwatch from "./ColorSwatch.svelte";
7
+ import ColorField from "./ColorField.svelte";
8
+ import BrushSize from "./BrushSize.svelte";
9
+ import type { ColorInput } from "tinycolor2";
10
+
11
+ let {
12
+ colors,
13
+ selected_color = $bindable(),
14
+ color_mode = undefined,
15
+ recent_colors = [],
16
+ selected_size = $bindable(),
17
+ selected_opacity = $bindable(),
18
+ show_swatch,
19
+ show_size,
20
+ mode = "brush",
21
+ preview = $bindable(),
22
+ onclick_outside = () => {}
23
+ }: {
24
+ colors: (ColorInput | ColorTuple)[];
25
+ selected_color: any;
26
+ color_mode?: Brush["color_mode"];
27
+ recent_colors?: (ColorInput | ColorTuple)[];
28
+ selected_size: number;
29
+ selected_opacity: number;
30
+ show_swatch: boolean;
31
+ show_size: boolean;
32
+ mode?: "brush" | "eraser";
33
+ preview?: boolean;
34
+ onclick_outside?: (event: MouseEvent) => void;
35
+ } = $props();
36
+
37
+ let color_picker = $state(false);
38
+ let current_mode = $state<"hex" | "rgb" | "hsl">("hex");
39
+ let editing_index = $state<number | null>(null);
40
+
41
+ function handle_color_selection(
42
+ {
43
+ index,
44
+ color,
45
+ opacity
46
+ }: {
47
+ index: number | null;
48
+ color: string | null;
49
+ opacity?: number;
50
+ },
51
+ type: "core" | "user"
52
+ ): void {
53
+ if (type === "user" && !color) {
54
+ editing_index = index;
55
+ color_picker = true;
56
+ }
57
+
58
+ if (!color) return;
59
+ selected_color = color;
60
+
61
+ if (opacity !== undefined) {
62
+ selected_opacity = opacity;
63
+ }
64
+
65
+ if (type === "core") {
66
+ color_picker = false;
67
+ }
68
+ }
69
+
70
+ function handle_color_change(color: string): void {
71
+ if (editing_index === null) return;
72
+ recent_colors[editing_index] = color;
73
+ }
74
+
75
+ $effect(() => {
76
+ handle_color_change(selected_color);
77
+ });
78
+ let width = $state(0);
79
+ let height = $state(0);
80
+
81
+ function debounce(
82
+ func: (...args: any[]) => void,
83
+ delay: number
84
+ ): (...args: any[]) => void {
85
+ let timeout: NodeJS.Timeout;
86
+ return function (...args: any[]): void {
87
+ clearTimeout(timeout);
88
+ timeout = setTimeout(() => func(...args), delay);
89
+ };
90
+ }
91
+
92
+ function handle_preview(): void {
93
+ if (!preview) {
94
+ preview = true;
95
+ debounced_close_preview();
96
+ } else {
97
+ debounced_close_preview();
98
+ }
99
+ }
100
+
101
+ function handle_close_preview(): void {
102
+ preview = false;
103
+ }
104
+
105
+ const debounced_close_preview = debounce(handle_close_preview, 1000);
106
+
107
+ $effect(() => {
108
+ if (!show_size) {
109
+ preview = false;
110
+ return;
111
+ }
112
+
113
+ selected_size;
114
+ handle_preview();
115
+ });
116
+
117
+ function handle_select(color: string): void {
118
+ selected_color = color;
119
+ }
120
+
121
+ function handle_add_color(): void {
122
+ // limit to 5
123
+ if (recent_colors.length >= 5) {
124
+ recent_colors.pop();
125
+ }
126
+ // check if the color is already in the array
127
+ if (
128
+ recent_colors.some((color) => {
129
+ if (Array.isArray(color)) {
130
+ return color[0] === selected_color && color[1] === selected_opacity;
131
+ }
132
+ return color === selected_color;
133
+ })
134
+ ) {
135
+ return;
136
+ }
137
+ recent_colors.push([selected_color, selected_opacity]);
138
+ recent_colors = recent_colors;
139
+ }
140
+ </script>
141
+
142
+ <svelte:window bind:innerHeight={height} bind:innerWidth={width} />
143
+
144
+ <div
145
+ class="wrap"
146
+ class:padded={!color_picker}
147
+ use:click_outside={onclick_outside}
148
+ class:color_picker
149
+ class:size_picker={show_size && mode === "brush"}
150
+ class:eraser_picker={mode === "eraser"}
151
+ >
152
+ {#if color_mode === "defaults"}
153
+ {#if color_picker}
154
+ <ColorPicker
155
+ bind:color={selected_color}
156
+ bind:opacity={selected_opacity}
157
+ />
158
+ <ColorField
159
+ bind:current_mode
160
+ color={selected_color}
161
+ onclose={() => (color_picker = false)}
162
+ onselected={(detail) => handle_select(detail)}
163
+ />
164
+ {/if}
165
+ {/if}
166
+ {#if show_swatch}
167
+ <ColorSwatch
168
+ bind:color_picker
169
+ {colors}
170
+ onselect={(detail) => handle_color_selection(detail, "core")}
171
+ onedit={(detail) => handle_color_selection(detail, "user")}
172
+ user_colors={color_mode === "defaults" ? recent_colors : null}
173
+ {selected_color}
174
+ {current_mode}
175
+ onadd_color={handle_add_color}
176
+ />
177
+ {/if}
178
+
179
+ {#if show_size}
180
+ <BrushSize max={100} min={1} bind:selected_size />
181
+ {/if}
182
+ </div>
183
+
184
+ <style>
185
+ .wrap {
186
+ max-width: 230px;
187
+ /* width: 90%; */
188
+ position: absolute;
189
+ display: flex;
190
+ flex-direction: column;
191
+ gap: 5px;
192
+ background: var(--background-fill-secondary);
193
+ border: 1px solid var(--block-border-color);
194
+ border-radius: var(--radius-md);
195
+ box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
196
+ padding-bottom: var(--size-2);
197
+ pointer-events: all;
198
+ cursor: default;
199
+ z-index: var(--layer-top);
200
+ overflow: hidden;
201
+ top: 0;
202
+
203
+ transform: translate(35px, -12px);
204
+ }
205
+
206
+ .color_picker {
207
+ transform: translate(35px, -50%);
208
+ }
209
+
210
+ .size_picker {
211
+ transform: translate(35px, 18px);
212
+ }
213
+
214
+ .eraser_picker {
215
+ transform: translate(35px, -7px);
216
+ }
217
+ </style>
6.26.1/imageeditor/shared/brush/BrushSize.svelte ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { click_outside } from "../utils/events";
3
+ import { BrushSize } from "@gradio/icons";
4
+
5
+ let {
6
+ selected_size = $bindable(),
7
+ min,
8
+ max,
9
+ onclick_outside = () => {}
10
+ }: {
11
+ selected_size: number;
12
+ min: number;
13
+ max: number;
14
+ onclick_outside?: (event: MouseEvent) => void;
15
+ } = $props();
16
+ </script>
17
+
18
+ <div class="wrap" use:click_outside={onclick_outside}>
19
+ <span>
20
+ <BrushSize />
21
+ </span>
22
+ <input type="range" bind:value={selected_size} {min} {max} step={1} />
23
+ </div>
24
+
25
+ <style>
26
+ .wrap {
27
+ width: 230px;
28
+ display: flex;
29
+ gap: var(--size-4);
30
+ background: var(--background-fill-secondary);
31
+ padding: 0 var(--size-4);
32
+ cursor: default;
33
+ padding-top: var(--size-2-5);
34
+ }
35
+
36
+ input {
37
+ width: 100%;
38
+ }
39
+ span {
40
+ width: 26px;
41
+ color: var(--body-text-color);
42
+ }
43
+ </style>
6.26.1/imageeditor/shared/brush/ColorField.svelte ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { Eyedropper, Plus } from "@gradio/icons";
3
+
4
+ import tinycolor from "tinycolor2";
5
+ import IconButton from "../IconButton.svelte";
6
+
7
+ let {
8
+ color,
9
+ current_mode = $bindable<"hex" | "rgb" | "hsl">("hex"),
10
+ onselected,
11
+ onclose
12
+ }: {
13
+ color: string;
14
+ current_mode?: "hex" | "rgb" | "hsl";
15
+ onselected?: (color: string) => void;
16
+ onclose?: () => void;
17
+ } = $props();
18
+
19
+ const modes = [
20
+ ["Hex", "hex"],
21
+ ["RGB", "rgb"],
22
+ ["HSL", "hsl"]
23
+ ] as const;
24
+
25
+ function format_color(color: string, mode: "hex" | "rgb" | "hsl"): string {
26
+ if (mode === "hex") {
27
+ return tinycolor(color).toHexString();
28
+ } else if (mode === "rgb") {
29
+ return tinycolor(color).toRgbString();
30
+ }
31
+ return tinycolor(color).toHslString();
32
+ }
33
+
34
+ let color_string = $derived(format_color(color, current_mode));
35
+ $effect(() => {
36
+ if (color_string) onselected?.(color_string);
37
+ });
38
+
39
+ function request_eyedropper(): void {
40
+ // @ts-ignore
41
+ const eyeDropper = new EyeDropper();
42
+
43
+ eyeDropper.open().then((result: { sRGBHex: string }) => {
44
+ color = result.sRGBHex;
45
+ });
46
+ }
47
+
48
+ //@ts-ignore
49
+ const eyedropper_supported = !!window.EyeDropper;
50
+
51
+ function handle_click(): void {
52
+ onselected?.(color_string);
53
+ onclose?.();
54
+ }
55
+ </script>
56
+
57
+ <div class="input">
58
+ <button class="swatch" style:background={color} onclick={handle_click}
59
+ ></button>
60
+ <div>
61
+ <div class="input-wrap">
62
+ <input
63
+ type="text"
64
+ value={color_string}
65
+ onchange={(e) => (color = e.currentTarget.value)}
66
+ />
67
+
68
+ <button class="eyedropper" onclick={request_eyedropper}>
69
+ {#if eyedropper_supported}
70
+ <Eyedropper />
71
+ {/if}
72
+ </button>
73
+ </div>
74
+ <div class="buttons">
75
+ {#each modes as [label, value]}
76
+ <button
77
+ class="button"
78
+ class:active={current_mode === value}
79
+ onclick={() => (current_mode = value)}>{label}</button
80
+ >
81
+ {/each}
82
+ </div>
83
+ </div>
84
+ </div>
85
+
86
+ <style>
87
+ .input {
88
+ display: flex;
89
+ align-items: center;
90
+ padding: 0 10px 15px;
91
+ }
92
+
93
+ .input input {
94
+ height: 30px;
95
+ width: 100%;
96
+ flex-shrink: 1;
97
+ border-bottom-left-radius: 0;
98
+ border: 1px solid var(--block-border-color);
99
+ letter-spacing: -0.05rem;
100
+ border-left: none;
101
+ border-right: none;
102
+ font-family: var(--font-mono);
103
+ font-size: var(--scale-000);
104
+ padding-left: 15px;
105
+ padding-right: 0;
106
+ background-color: var(--background-fill-secondary);
107
+ color: var(--block-label-text-color);
108
+ }
109
+
110
+ .swatch {
111
+ width: 50px;
112
+ height: 50px;
113
+ border-top-left-radius: 15px;
114
+ border-bottom-left-radius: 15px;
115
+ flex-shrink: 0;
116
+ border: 1px solid var(--block-border-color);
117
+ }
118
+
119
+ .buttons button {
120
+ display: flex;
121
+ align-items: center;
122
+ justify-content: center;
123
+ border: 1px solid var(--block-border-color);
124
+ background: var(--background-fill-secondary);
125
+ padding: 3px 6px;
126
+ font-size: var(--scale-000);
127
+ cursor: pointer;
128
+ border-right: none;
129
+ width: 100%;
130
+ border-top: none;
131
+ }
132
+
133
+ .buttons button:first-child {
134
+ border-left: none;
135
+ }
136
+
137
+ .buttons button:last-child {
138
+ border-bottom-right-radius: 15px;
139
+ border-right: 1px solid var(--block-border-color);
140
+ }
141
+
142
+ .buttons button:hover {
143
+ background: var(--background-fill-secondary-hover);
144
+ font-weight: var(--weight-bold);
145
+ }
146
+
147
+ .buttons button.active {
148
+ background: var(--background-fill-secondary);
149
+ font-weight: var(--weight-bold);
150
+ }
151
+
152
+ .buttons {
153
+ height: 20px;
154
+
155
+ display: flex;
156
+ justify-content: stretch;
157
+ gap: 0px;
158
+ /* padding: 0 10px; */
159
+ }
160
+
161
+ .input-wrap {
162
+ display: flex;
163
+ }
164
+
165
+ .eyedropper {
166
+ display: flex;
167
+ align-items: center;
168
+ justify-content: center;
169
+ width: 25px;
170
+ height: 30px;
171
+ border-top-right-radius: 15px;
172
+ border: 1px solid var(--block-border-color);
173
+ border-left: none;
174
+ background: var(--background-fill-secondary);
175
+ height: 30px;
176
+ padding: 7px 7px 5px 0px;
177
+ cursor: pointer;
178
+ }
179
+ </style>
6.26.1/imageeditor/shared/brush/ColorPicker.svelte ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { onMount, tick } from "svelte";
3
+ import tinycolor from "tinycolor2";
4
+ import { clamp } from "../utils/pixi";
5
+
6
+ let {
7
+ color = $bindable("rgb(255, 255, 255)"),
8
+ opacity = $bindable(1)
9
+ }: {
10
+ color?: string;
11
+ opacity?: number;
12
+ } = $props();
13
+
14
+ let sl_marker_pos = $state([0, 0]);
15
+ let sl_rect: DOMRect | null = null;
16
+ let sl_moving = $state(false);
17
+ let sl = $state([0, 0]);
18
+
19
+ let hue = $state(0);
20
+ let hue_marker_pos = $state(0);
21
+ let hue_rect: DOMRect | null = null;
22
+ let hue_moving = $state(false);
23
+
24
+ let opacity_moving = $state(false);
25
+
26
+ function handle_hue_down(
27
+ event: MouseEvent & { currentTarget: HTMLDivElement }
28
+ ): void {
29
+ hue_rect = event.currentTarget.getBoundingClientRect();
30
+
31
+ hue_moving = true;
32
+ update_hue_from_mouse(event.clientX);
33
+ }
34
+
35
+ function update_hue_from_mouse(x: number): void {
36
+ if (!hue_rect) return;
37
+ const _x = clamp(x - hue_rect.left, 0, hue_rect.width); // get the x-coordinate relative to the box
38
+ hue_marker_pos = _x;
39
+ const _hue = (_x / hue_rect.width) * 360; // scale the x position to a hue value (0-360)
40
+
41
+ hue = _hue;
42
+
43
+ color = hsva_to_rgba({ h: _hue, s: sl[0], v: sl[1], a: 1 });
44
+ }
45
+
46
+ function hsva_to_rgba(hsva: {
47
+ h: number;
48
+ s: number;
49
+ v: number;
50
+ a: number;
51
+ }): string {
52
+ const saturation = hsva.s;
53
+ const value = hsva.v;
54
+ let chroma = saturation * value;
55
+ const hue_by_60 = hsva.h / 60;
56
+ let x = chroma * (1 - Math.abs((hue_by_60 % 2) - 1));
57
+ const m = value - chroma;
58
+
59
+ chroma = chroma + m;
60
+ x = x + m;
61
+
62
+ const index = Math.floor(hue_by_60) % 6;
63
+ const red = [chroma, x, m, m, x, chroma][index];
64
+ const green = [x, chroma, chroma, x, m, m][index];
65
+ const blue = [m, m, x, chroma, chroma, x][index];
66
+
67
+ return `rgba(${red * 255}, ${green * 255}, ${blue * 255}, ${hsva.a})`;
68
+ }
69
+
70
+ function update_color_from_mouse(x: number, y: number): void {
71
+ if (!sl_rect) return;
72
+ const _x = clamp(x - sl_rect.left, 0, sl_rect.width);
73
+ const _y = clamp(y - sl_rect.top, 0, sl_rect.height);
74
+ sl_marker_pos = [_x, _y];
75
+ const _hsva = {
76
+ h: hue * 1,
77
+ s: _x / sl_rect.width,
78
+ v: 1 - _y / sl_rect.height,
79
+ a: 1
80
+ };
81
+
82
+ sl = [_hsva.s, _hsva.v];
83
+
84
+ color = hsva_to_rgba(_hsva);
85
+ }
86
+
87
+ function handle_sl_down(
88
+ event: MouseEvent & { currentTarget: HTMLDivElement }
89
+ ): void {
90
+ sl_moving = true;
91
+ sl_rect = event.currentTarget.getBoundingClientRect();
92
+ update_color_from_mouse(event.clientX, event.clientY);
93
+ }
94
+
95
+ function handle_move(
96
+ event: MouseEvent & { currentTarget: EventTarget & Window }
97
+ ): void {
98
+ if (sl_moving) update_color_from_mouse(event.clientX, event.clientY);
99
+ if (hue_moving) update_hue_from_mouse(event.clientX);
100
+ if (opacity_moving) update_opacity_from_mouse(event.clientX);
101
+ }
102
+
103
+ function handle_end(): void {
104
+ if (sl_moving) sl_moving = false;
105
+ if (hue_moving) hue_moving = false;
106
+ if (opacity_moving) opacity_moving = false;
107
+ }
108
+
109
+ async function update_mouse_from_color(color: string): Promise<void> {
110
+ if (sl_moving || hue_moving) return;
111
+ await tick();
112
+ if (!color) return;
113
+ if (!sl_rect) {
114
+ sl_rect = sl_wrap.getBoundingClientRect();
115
+ }
116
+
117
+ if (!hue_rect) {
118
+ hue_rect = hue_wrap.getBoundingClientRect();
119
+ }
120
+
121
+ const hsva = tinycolor(color).toHsv();
122
+ const _x = hsva.s * sl_rect!.width;
123
+ const _y = (1 - hsva.v) * sl_rect!.height;
124
+ sl_marker_pos = [_x, _y];
125
+ sl = [hsva.s, hsva.v];
126
+ hue = hsva.h;
127
+ hue_marker_pos = (hsva.h / 360) * hue_rect!.width;
128
+ }
129
+
130
+ $effect(() => {
131
+ update_mouse_from_color(color);
132
+ });
133
+
134
+ let sl_wrap: HTMLDivElement;
135
+ let hue_wrap: HTMLDivElement;
136
+
137
+ let opacity_wrap: HTMLDivElement;
138
+
139
+ function handle_opacity_down(
140
+ event: MouseEvent & { currentTarget: HTMLDivElement }
141
+ ): void {
142
+ opacity_rect = event.currentTarget.getBoundingClientRect();
143
+ opacity_moving = true;
144
+ update_opacity_from_mouse(event.clientX);
145
+ }
146
+ let opacity_rect: DOMRect | null = null;
147
+
148
+ function update_opacity_from_mouse(x: number): void {
149
+ if (!opacity_rect) return;
150
+ const _x = clamp(x - opacity_rect.left, 0, opacity_rect.width);
151
+ opacity = _x / opacity_rect.width;
152
+ }
153
+
154
+ onMount(() => {
155
+ opacity_rect = opacity_wrap.getBoundingClientRect();
156
+ });
157
+ </script>
158
+
159
+ <svelte:window onmousemove={handle_move} onmouseup={handle_end} />
160
+
161
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
162
+ <div
163
+ class="color-gradient"
164
+ onmousedown={handle_sl_down}
165
+ style="--hue:{hue}"
166
+ bind:this={sl_wrap}
167
+ >
168
+ <div
169
+ class="marker"
170
+ style:transform="translate({sl_marker_pos[0]}px,{sl_marker_pos[1]}px)"
171
+ style:background={color}
172
+ />
173
+ </div>
174
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
175
+ <div
176
+ class="opacity-slider"
177
+ onmousedown={handle_opacity_down}
178
+ style="--color:{color === 'auto' ? 'transparent' : color}"
179
+ bind:this={opacity_wrap}
180
+ >
181
+ <div
182
+ class="opacity-marker"
183
+ style:background="white"
184
+ style:transform="translateX({opacity * (opacity_rect?.width ?? 1)}px)"
185
+ />
186
+ </div>
187
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
188
+ <div class="hue-slider" onmousedown={handle_hue_down} bind:this={hue_wrap}>
189
+ <div
190
+ class="marker"
191
+ style:background={"hsl(" + hue + ", 100%, 50%)"}
192
+ style:transform="translateX({hue_marker_pos}px)"
193
+ />
194
+ </div>
195
+
196
+ <style>
197
+ .hue-slider {
198
+ position: relative;
199
+ width: 90%;
200
+ margin: 0px auto 10px auto;
201
+ height: 12px;
202
+ border-radius: 2px;
203
+ border: 1px solid var(--block-border-color);
204
+ background: linear-gradient(
205
+ to right,
206
+ hsl(0, 100%, 50%) 0%,
207
+ #ff0 17%,
208
+ lime 33%,
209
+ cyan 50%,
210
+ blue 67%,
211
+ magenta 83%,
212
+ red 100%
213
+ );
214
+ border-top: none;
215
+ }
216
+
217
+ .opacity-slider {
218
+ position: relative;
219
+ width: 90%;
220
+ margin: 10px auto 5px auto;
221
+ height: 12px;
222
+ border-radius: 2px;
223
+ border: 1px solid var(--block-border-color);
224
+ /* background: linear-gradient(45deg, #808080 25%, transparent 25%),
225
+ linear-gradient(-45deg, #808080 25%, transparent 25%),
226
+ linear-gradient(45deg, transparent 75%, #808080 75%),
227
+ linear-gradient(-45deg, transparent 75%, #808080 75%); */
228
+ background:
229
+ linear-gradient(to right, transparent, var(--color)),
230
+ repeating-conic-gradient(#808080 0% 25%, transparent 0% 50%) 0 0 / 10px
231
+ 10px;
232
+ }
233
+
234
+ .opacity-marker {
235
+ position: absolute;
236
+ width: 16px;
237
+ height: 16px;
238
+ border-radius: 50%;
239
+ }
240
+
241
+ .opacity-slider > .opacity-marker {
242
+ box-shadow: 0 0 1px #888;
243
+ top: -4px;
244
+ margin: auto;
245
+ height: 18px;
246
+ width: 18px;
247
+ left: -9px;
248
+ margin: auto;
249
+ border: 1px solid var(--block-border-color);
250
+ }
251
+
252
+ .color-gradient {
253
+ position: relative;
254
+ --hue: white;
255
+
256
+ background:
257
+ linear-gradient(rgba(0, 0, 0, 0), #000),
258
+ linear-gradient(90deg, #fff, hsl(var(--hue), 100%, 50%));
259
+ width: 100%;
260
+ height: 150px;
261
+ border-top-left-radius: 4px;
262
+ border-top-right-radius: 4px;
263
+ }
264
+
265
+ .marker {
266
+ position: absolute;
267
+ width: 14px;
268
+ height: 14px;
269
+ border-radius: 50%;
270
+ border: 2px solid white;
271
+
272
+ top: -7px;
273
+ left: -7px;
274
+ box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
275
+ pointer-events: none;
276
+ border: 1px solid var(--block-border-color);
277
+ }
278
+
279
+ .hue-slider > .marker {
280
+ box-shadow: 0 0 1px #888;
281
+ top: -3px;
282
+ margin: auto;
283
+ height: 18px;
284
+ width: 18px;
285
+ left: -9px;
286
+
287
+ border: 1px solid var(--block-border-color);
288
+ }
289
+ </style>
6.26.1/imageeditor/shared/brush/ColorSwatch.svelte ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import tinycolor from "tinycolor2";
3
+ import type { ColorTuple } from "./types";
4
+ import type { ColorInput } from "tinycolor2";
5
+ import IconButton from "../IconButton.svelte";
6
+ import { Plus } from "@gradio/icons";
7
+
8
+ let {
9
+ selected_color,
10
+ colors,
11
+ user_colors = [],
12
+ show_empty = false,
13
+ current_mode = "hex",
14
+ color_picker = $bindable(false),
15
+ onselect,
16
+ onedit,
17
+ onadd_color
18
+ }: {
19
+ selected_color: string;
20
+ colors: (ColorInput | ColorTuple)[];
21
+ user_colors?: (ColorInput | ColorTuple)[] | null;
22
+ show_empty?: boolean;
23
+ current_mode?: "hex" | "rgb" | "hsl";
24
+ color_picker?: boolean;
25
+ onselect?: (value: {
26
+ index: number | null;
27
+ color: string | null;
28
+ opacity?: number;
29
+ }) => void;
30
+ onedit?: (value: {
31
+ index: number;
32
+ color: string | null;
33
+ opacity?: number;
34
+ }) => void;
35
+ onadd_color?: () => void;
36
+ } = $props();
37
+
38
+ let _colors = $derived(show_empty ? colors : colors.filter((c) => c));
39
+
40
+ function get_color(color_input: ColorInput | ColorTuple): string {
41
+ if (Array.isArray(color_input)) {
42
+ return color_input[0] as string;
43
+ }
44
+ return color_input as string;
45
+ }
46
+
47
+ function get_opacity(
48
+ color_input: ColorInput | ColorTuple
49
+ ): number | undefined {
50
+ if (Array.isArray(color_input)) {
51
+ return color_input[1];
52
+ }
53
+
54
+ const color = tinycolor(color_input);
55
+ return color.getAlpha();
56
+ }
57
+
58
+ function get_formatted_color(
59
+ color: ColorInput | ColorTuple,
60
+ mode: "hex" | "rgb" | "hsl"
61
+ ): string {
62
+ const color_value = get_color(color);
63
+ if (mode === "hex") {
64
+ return tinycolor(color_value).toHexString();
65
+ } else if (mode === "rgb") {
66
+ return tinycolor(color_value).toRgbString();
67
+ }
68
+ return tinycolor(color_value).toHslString();
69
+ }
70
+
71
+ let current_index = `select-${colors.findIndex(
72
+ (c) =>
73
+ get_formatted_color(c, current_mode) ===
74
+ get_formatted_color(selected_color, current_mode)
75
+ )}`;
76
+
77
+ let selected_opacity = $derived(get_opacity(selected_color));
78
+
79
+ function handle_select(
80
+ type: "edit" | "select",
81
+ detail: {
82
+ index: number;
83
+ color: string | null;
84
+ opacity?: number;
85
+ }
86
+ ): void {
87
+ current_index = `${type}-${detail.index}`;
88
+ if (type === "edit") {
89
+ onedit?.(detail);
90
+ } else {
91
+ onselect?.(detail);
92
+ }
93
+ }
94
+
95
+ function handle_picker_click(): void {
96
+ onselect?.({ index: null, color: selected_color });
97
+ color_picker = !color_picker;
98
+ }
99
+ </script>
100
+
101
+ {#if !color_picker}
102
+ <span class:lg={user_colors}></span>
103
+ {/if}
104
+
105
+ <div class="swatch-wrap">
106
+ <div class="swatch-container">
107
+ {#if user_colors}
108
+ <div class="swatch">
109
+ {#if color_picker}
110
+ <IconButton
111
+ Icon={Plus}
112
+ onclick={() => onadd_color?.()}
113
+ roundedness="very"
114
+ background={get_color(selected_color)}
115
+ color="white"
116
+ />
117
+ {/if}
118
+ {#each user_colors as color, i}
119
+ {@const color_string = get_color(color)}
120
+ {@const opacity = get_opacity(color)}
121
+ <button
122
+ onclick={() =>
123
+ handle_select("edit", {
124
+ index: i,
125
+ color: color_string,
126
+ opacity: opacity
127
+ })}
128
+ class="color"
129
+ class:empty={color === null}
130
+ style="background-color: {color_string}"
131
+ style:opacity
132
+ class:selected={`${color_string}-${opacity}` ===
133
+ `${selected_color}-${selected_opacity}`}
134
+ ></button>
135
+ {/each}
136
+
137
+ <button
138
+ onclick={handle_picker_click}
139
+ class="color colorpicker"
140
+ class:hidden={!color_picker}
141
+ ></button>
142
+ </div>
143
+ {/if}
144
+ <menu class="swatch">
145
+ {#each _colors as color_item, i}
146
+ {@const color_string = get_color(color_item)}
147
+ {@const opacity = get_opacity(color_item)}
148
+ <button
149
+ onclick={() =>
150
+ handle_select("select", {
151
+ index: i,
152
+ color: color_string,
153
+ opacity: opacity
154
+ })}
155
+ class="color"
156
+ class:empty={color_item === null}
157
+ style="background-color: {color_string}"
158
+ style:opacity
159
+ class:selected={`${color_string}-${opacity}` ===
160
+ `${selected_color}-${selected_opacity}`}
161
+ ></button>
162
+ {/each}
163
+ </menu>
164
+ </div>
165
+ </div>
166
+
167
+ <style>
168
+ .swatch-wrap {
169
+ display: flex;
170
+ justify-content: space-between;
171
+ align-items: flex-start;
172
+ /* max-width: 200px; */
173
+ width: 205px;
174
+ }
175
+
176
+ span.lg {
177
+ margin-top: var(--spacing-sm);
178
+ }
179
+ .swatch-container {
180
+ display: flex;
181
+ flex-direction: column;
182
+ gap: 10px;
183
+ width: 100%;
184
+ }
185
+ .swatch {
186
+ display: grid;
187
+ grid-template-columns: repeat(auto-fill, 25px);
188
+ gap: 8px;
189
+ justify-content: flex-start;
190
+
191
+ overflow: hidden;
192
+ justify-content: center;
193
+ }
194
+
195
+ .empty {
196
+ border: 1px solid var(--block-border-color);
197
+ font-weight: var(--weight-bold);
198
+ display: flex;
199
+ justify-content: center;
200
+ align-items: center;
201
+ padding-top: 4px;
202
+ text-align: center;
203
+ font-size: var(--scale-0);
204
+ cursor: pointer;
205
+ }
206
+
207
+ .empty::after {
208
+ content: "+";
209
+ margin-bottom: var(--size-1);
210
+ }
211
+
212
+ .color {
213
+ width: 25px;
214
+ height: 25px;
215
+ border-radius: var(--radius-md);
216
+ }
217
+
218
+ .empty.selected,
219
+ .color.selected {
220
+ border: 2px solid var(--color-accent);
221
+ }
222
+
223
+ .colorpicker {
224
+ border: 1px solid var(--block-border-color);
225
+
226
+ background: conic-gradient(
227
+ red,
228
+ #ff0 60deg,
229
+ lime 120deg,
230
+ cyan 180deg,
231
+ blue 240deg,
232
+ magenta 300deg,
233
+ red 360deg
234
+ );
235
+ overflow: hidden;
236
+ position: relative;
237
+ color: white;
238
+ cursor: pointer;
239
+ }
240
+
241
+ .colorpicker::before {
242
+ content: "";
243
+ position: absolute;
244
+ width: 100%;
245
+ height: 100%;
246
+ background: rgba(0, 0, 0, 0.6);
247
+ opacity: 1;
248
+ transition: 0.1s;
249
+ top: 0;
250
+ left: 0;
251
+ }
252
+
253
+ .colorpicker::after {
254
+ display: flex;
255
+ justify-content: center;
256
+ align-items: center;
257
+ content: "⨯";
258
+ color: white;
259
+ font-size: var(--scale-5);
260
+ position: absolute;
261
+ width: 100%;
262
+ height: 100%;
263
+ transform: translateY(-7px);
264
+ opacity: 1;
265
+ transition: 0.1s;
266
+ top: 0;
267
+ }
268
+
269
+ .colorpicker.hidden::after,
270
+ .colorpicker.hidden::before {
271
+ opacity: 0;
272
+ }
273
+ </style>
6.26.1/imageeditor/shared/brush/brush-cursor.ts ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Container,
3
+ Graphics,
4
+ Sprite,
5
+ type FederatedPointerEvent
6
+ } from "pixi.js";
7
+ import { type ImageEditorContext } from "../core/editor";
8
+ import { type BrushState } from "./types";
9
+ import tinycolor from "tinycolor2";
10
+ import { clear_timeout } from "./brush-utils";
11
+
12
+ /**
13
+ * Class to handle all cursor preview-related functionality for the brush tool.
14
+ */
15
+ export class BrushCursor {
16
+ private cursor_graphics: Graphics | null = null;
17
+ private cursor_container: Container | null = null;
18
+ private brush_preview_container: Container | null = null;
19
+ private brush_preview_graphics: Graphics | null = null;
20
+ private is_preview_visible = false;
21
+ private is_cursor_over_image = false;
22
+ private cursor_position_check_timeout: number | null = null;
23
+ private is_brush_or_erase_active = false;
24
+
25
+ private _bound_update_cursor:
26
+ | ((event: FederatedPointerEvent) => void)
27
+ | null = null;
28
+ private _bound_check_cursor_over_image:
29
+ | ((event: FederatedPointerEvent) => void)
30
+ | null = null;
31
+
32
+ constructor(
33
+ private image_editor_context: ImageEditorContext,
34
+ private state: BrushState,
35
+ private scale: number
36
+ ) {
37
+ this.initialize_cursor();
38
+ this.initialize_brush_preview();
39
+ }
40
+
41
+ /**
42
+ * Returns whether the cursor is currently over the image.
43
+ */
44
+ is_over_image(): boolean {
45
+ return this.is_cursor_over_image;
46
+ }
47
+
48
+ /**
49
+ * Sets up cursor-related event listeners.
50
+ */
51
+ setup_event_listeners(): void {
52
+ this.cleanup_event_listeners();
53
+
54
+ this._bound_update_cursor = this.update_cursor_position.bind(this);
55
+ this._bound_check_cursor_over_image =
56
+ this.check_cursor_over_image.bind(this);
57
+
58
+ const stage = this.image_editor_context.app.stage;
59
+ stage.on("pointermove", this._bound_update_cursor);
60
+ stage.on("pointermove", this._bound_check_cursor_over_image);
61
+
62
+ this.image_editor_context.image_container.on(
63
+ "pointerenter",
64
+ this.on_image_container_pointer_enter.bind(this)
65
+ );
66
+ this.image_editor_context.image_container.on(
67
+ "pointerleave",
68
+ this.on_image_container_pointer_leave.bind(this)
69
+ );
70
+ }
71
+
72
+ /**
73
+ * Removes all cursor-related event listeners.
74
+ */
75
+ cleanup_event_listeners(): void {
76
+ const stage = this.image_editor_context.app.stage;
77
+
78
+ if (this._bound_update_cursor) {
79
+ stage.off("pointermove", this._bound_update_cursor);
80
+ this._bound_update_cursor = null;
81
+ }
82
+
83
+ if (this._bound_check_cursor_over_image) {
84
+ stage.off("pointermove", this._bound_check_cursor_over_image);
85
+ this._bound_check_cursor_over_image = null;
86
+ }
87
+
88
+ this.image_editor_context.image_container.off("pointerenter");
89
+ this.image_editor_context.image_container.off("pointerleave");
90
+
91
+ this.cursor_position_check_timeout = clear_timeout(
92
+ this.cursor_position_check_timeout
93
+ );
94
+ }
95
+
96
+ /**
97
+ * initializes the cursor for the brush tool.
98
+ */
99
+ initialize_cursor(): void {
100
+ if (this.cursor_container) {
101
+ if (this.cursor_container.parent) {
102
+ this.cursor_container.parent.removeChild(this.cursor_container);
103
+ }
104
+ this.cursor_container.destroy({ children: true });
105
+ this.cursor_container = null;
106
+ }
107
+
108
+ this.cursor_container = new Container();
109
+ this.image_editor_context.ui_container.addChild(this.cursor_container);
110
+
111
+ this.cursor_graphics = new Graphics();
112
+ this.cursor_container.addChild(this.cursor_graphics);
113
+
114
+ this.update_cursor_appearance();
115
+ }
116
+
117
+ /**
118
+ * updates the appearance of the cursor.
119
+ */
120
+ update_cursor_appearance(): void {
121
+ if (!this.cursor_graphics) return;
122
+
123
+ this.cursor_graphics.clear();
124
+
125
+ const cursor_color =
126
+ this.state.mode === "draw"
127
+ ? tinycolor(this.state.color).toString()
128
+ : 0xffffff;
129
+
130
+ this.cursor_graphics
131
+ .circle(0, 0, this.state.brush_size * this.scale)
132
+ .stroke({
133
+ width: 1.5,
134
+ color: cursor_color,
135
+ alpha: 0.8
136
+ });
137
+
138
+ this.cursor_graphics.circle(0, 0, 1).fill({
139
+ color: cursor_color,
140
+ alpha: 0.8
141
+ });
142
+ }
143
+
144
+ /**
145
+ * updates the position of the cursor.
146
+ * @param {FederatedPointerEvent} event - The pointer event.
147
+ */
148
+ update_cursor_position(event: FederatedPointerEvent): void {
149
+ if (!this.cursor_container) return;
150
+
151
+ const local_pos = this.image_editor_context.image_container.toLocal(
152
+ event.global
153
+ );
154
+
155
+ const ui_pos = this.image_editor_context.ui_container.toLocal(
156
+ this.image_editor_context.image_container.toGlobal(local_pos)
157
+ );
158
+
159
+ this.cursor_container.position.set(ui_pos.x, ui_pos.y);
160
+ }
161
+
162
+ /**
163
+ * checks if the cursor is over the image container.
164
+ * @param {FederatedPointerEvent} event - The pointer event.
165
+ */
166
+ check_cursor_over_image(event: FederatedPointerEvent): void {
167
+ if (this.cursor_position_check_timeout !== null) {
168
+ window.clearTimeout(this.cursor_position_check_timeout);
169
+ this.cursor_position_check_timeout = null;
170
+ }
171
+
172
+ const image_container = this.image_editor_context.image_container;
173
+ const bounds = image_container.getBounds();
174
+
175
+ const was_over_image = this.is_cursor_over_image;
176
+ this.is_cursor_over_image =
177
+ event.global.x >= bounds.x &&
178
+ event.global.x <= bounds.x + bounds.width &&
179
+ event.global.y >= bounds.y &&
180
+ event.global.y <= bounds.y + bounds.height;
181
+
182
+ if (was_over_image !== this.is_cursor_over_image) {
183
+ this.update_cursor_and_preview_visibility();
184
+ }
185
+ }
186
+
187
+ /**
188
+ * updates the size of the cursor.
189
+ */
190
+ update_cursor_size(): void {
191
+ this.update_cursor_appearance();
192
+ }
193
+
194
+ /**
195
+ * Updates whether brush or erase tool is active
196
+ */
197
+ set_active(is_active: boolean): void {
198
+ this.is_brush_or_erase_active = is_active;
199
+ this.update_cursor_and_preview_visibility();
200
+ }
201
+
202
+ /**
203
+ * updates the visibility of the cursor.
204
+ */
205
+ update_cursor_visibility(): void {
206
+ if (this.cursor_container) {
207
+ this.cursor_container.visible =
208
+ this.is_cursor_over_image && this.is_brush_or_erase_active;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Shows or hides the brush preview.
214
+ * @param {boolean} show - Whether to show the preview.
215
+ */
216
+ preview_brush(show: boolean): void {
217
+ this.is_preview_visible = show;
218
+
219
+ if (this.brush_preview_container) {
220
+ this.brush_preview_container.visible =
221
+ show && this.is_brush_or_erase_active;
222
+ }
223
+
224
+ if (show) {
225
+ this.update_brush_preview();
226
+ this.update_brush_preview_position();
227
+ }
228
+ }
229
+
230
+ /**
231
+ * initializes the brush preview.
232
+ */
233
+ initialize_brush_preview(): void {
234
+ if (this.brush_preview_container) {
235
+ if (this.brush_preview_container.parent) {
236
+ this.brush_preview_container.parent.removeChild(
237
+ this.brush_preview_container
238
+ );
239
+ }
240
+ this.brush_preview_container.destroy({ children: true });
241
+ this.brush_preview_container = null;
242
+ }
243
+
244
+ this.brush_preview_container = new Container();
245
+ this.image_editor_context.ui_container.addChild(
246
+ this.brush_preview_container
247
+ );
248
+
249
+ this.brush_preview_graphics = new Graphics();
250
+ this.brush_preview_container.addChild(this.brush_preview_graphics);
251
+
252
+ this.brush_preview_container.visible = false;
253
+ }
254
+
255
+ /**
256
+ * updates the brush preview appearance.
257
+ */
258
+ update_brush_preview(): void {
259
+ if (!this.brush_preview_graphics) return;
260
+
261
+ this.brush_preview_graphics.clear();
262
+
263
+ const preview_size = this.state.brush_size * this.scale;
264
+ const preview_color =
265
+ this.state.mode === "draw"
266
+ ? tinycolor(this.state.color).setAlpha(this.state.opacity).toString()
267
+ : 0xffffff;
268
+
269
+ this.brush_preview_graphics.circle(0, 0, preview_size).fill({
270
+ color: preview_color,
271
+ alpha: this.state.mode === "draw" ? this.state.opacity : 0.3
272
+ });
273
+
274
+ this.brush_preview_graphics.circle(0, 0, preview_size + 1).stroke({
275
+ width: 1,
276
+ color: 0x000000,
277
+ alpha: 0.5
278
+ });
279
+ }
280
+
281
+ /**
282
+ * updates the position of the brush preview to center of canvas.
283
+ */
284
+ update_brush_preview_position(): void {
285
+ if (!this.brush_preview_container) return;
286
+
287
+ const image_container = this.image_editor_context.image_container;
288
+ const center_x = image_container.width / 2;
289
+ const center_y = image_container.height / 2;
290
+
291
+ const global_pos = image_container.toGlobal({ x: center_x, y: center_y });
292
+
293
+ const ui_pos = this.image_editor_context.ui_container.toLocal(global_pos);
294
+
295
+ this.brush_preview_container.position.set(ui_pos.x, ui_pos.y);
296
+ }
297
+
298
+ /**
299
+ * Called when the pointer enters the image container.
300
+ */
301
+ on_image_container_pointer_enter(): void {
302
+ this.is_cursor_over_image = true;
303
+ this.update_cursor_and_preview_visibility();
304
+ }
305
+
306
+ /**
307
+ * Called when the pointer leaves the image container.
308
+ */
309
+ on_image_container_pointer_leave(): void {
310
+ this.is_cursor_over_image = false;
311
+ this.update_cursor_and_preview_visibility();
312
+ }
313
+
314
+ /**
315
+ * Updates both cursor and preview visibility based on cursor position.
316
+ */
317
+ update_cursor_and_preview_visibility(): void {
318
+ this.update_cursor_visibility();
319
+ if (this.brush_preview_container) {
320
+ this.brush_preview_container.visible =
321
+ this.is_preview_visible && this.is_brush_or_erase_active;
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Cleans up all cursor resources.
327
+ */
328
+ cleanup(): void {
329
+ this.is_brush_or_erase_active = false;
330
+
331
+ if (this.cursor_container) {
332
+ if (this.cursor_container.parent) {
333
+ this.cursor_container.parent.removeChild(this.cursor_container);
334
+ }
335
+ this.cursor_container.destroy({ children: true });
336
+ this.cursor_container = null;
337
+ }
338
+
339
+ if (this.brush_preview_container) {
340
+ if (this.brush_preview_container.parent) {
341
+ this.brush_preview_container.parent.removeChild(
342
+ this.brush_preview_container
343
+ );
344
+ }
345
+ this.brush_preview_container.destroy({ children: true });
346
+ this.brush_preview_container = null;
347
+ }
348
+
349
+ if (this.cursor_position_check_timeout !== null) {
350
+ window.clearTimeout(this.cursor_position_check_timeout);
351
+ this.cursor_position_check_timeout = null;
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Updates the brush state.
357
+ */
358
+ update_state(state: BrushState, scale: number): void {
359
+ this.state = state;
360
+ this.scale = scale;
361
+ this.update_cursor_appearance();
362
+ if (this.is_preview_visible) {
363
+ this.update_brush_preview();
364
+ }
365
+ }
366
+ }
6.26.1/imageeditor/shared/brush/brush-textures.ts ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Container,
3
+ RenderTexture,
4
+ Sprite,
5
+ Graphics,
6
+ Application,
7
+ Texture
8
+ } from "pixi.js";
9
+ import { type ImageEditorContext } from "../core/editor";
10
+ import { type Command } from "../core/commands";
11
+
12
+ /**
13
+ * Represents a single drawing segment with all its parameters
14
+ */
15
+ interface BrushSegment {
16
+ from_x: number;
17
+ from_y: number;
18
+ to_x: number;
19
+ to_y: number;
20
+ size: number;
21
+ color: string;
22
+ opacity: number;
23
+ mode: "draw" | "erase";
24
+ }
25
+
26
+ /**
27
+ * Represents a complete brush stroke containing multiple segments
28
+ */
29
+ interface BrushStroke {
30
+ segments: BrushSegment[];
31
+ layer_id: string;
32
+ }
33
+
34
+ export class BrushCommand implements Command {
35
+ private stroke_data: BrushStroke;
36
+ private context: ImageEditorContext;
37
+ private original_texture: Texture | null = null;
38
+
39
+ name: string;
40
+
41
+ constructor(
42
+ context: ImageEditorContext,
43
+ stroke_data: BrushStroke,
44
+ original_texture?: Texture
45
+ ) {
46
+ this.name = "Draw";
47
+ this.stroke_data = stroke_data;
48
+ this.context = context;
49
+ if (original_texture) {
50
+ this.original_texture = this.create_texture_from(original_texture);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Creates a new texture with the same content as the source texture
56
+ */
57
+ private create_texture_from(source: Texture): Texture {
58
+ const texture = RenderTexture.create({
59
+ width: source.width,
60
+ height: source.height,
61
+ resolution: window.devicePixelRatio || 1
62
+ });
63
+
64
+ const sprite = new Sprite(source);
65
+ const container = new Container();
66
+ container.addChild(sprite);
67
+
68
+ this.context.app.renderer.render(container, {
69
+ renderTexture: texture
70
+ });
71
+
72
+ container.destroy({ children: true });
73
+ return texture;
74
+ }
75
+
76
+ /**
77
+ * Recreates the stroke by rendering all segments from the stored parameters
78
+ * Preserves the exact order of draw/erase operations
79
+ */
80
+ private render_stroke_from_data(
81
+ stroke_data: BrushStroke,
82
+ target_texture: RenderTexture
83
+ ): void {
84
+ const draw_segments = stroke_data.segments.filter((s) => s.mode === "draw");
85
+ const erase_segments = stroke_data.segments.filter(
86
+ (s) => s.mode === "erase"
87
+ );
88
+
89
+ if (draw_segments.length > 0) {
90
+ const graphics = new Graphics();
91
+ const container = new Container();
92
+ container.addChild(graphics);
93
+ let alpha = 1;
94
+
95
+ for (const segment of draw_segments) {
96
+ if (segment.opacity < alpha) {
97
+ alpha = segment.opacity;
98
+ }
99
+ let colorValue = 0xffffff;
100
+ if (segment.color.startsWith("#")) {
101
+ colorValue = parseInt(segment.color.replace("#", "0x"), 16);
102
+ }
103
+
104
+ graphics.setFillStyle({
105
+ color: colorValue,
106
+ alpha: 1
107
+ });
108
+
109
+ this.render_segment_to_graphics(graphics, segment);
110
+ }
111
+
112
+ // we need a sprite in order to set the alpha and for that we need a texture
113
+ // i'm not entirely sure why other approaches didn't work
114
+ const alpha_sprite_texture = RenderTexture.create({
115
+ width: target_texture.width,
116
+ height: target_texture.height,
117
+ resolution: window.devicePixelRatio || 1
118
+ });
119
+
120
+ const alpha_sprite = new Sprite(alpha_sprite_texture);
121
+ this.context.app.renderer.render({
122
+ container: container,
123
+ target: alpha_sprite_texture
124
+ });
125
+
126
+ alpha_sprite.alpha = alpha;
127
+
128
+ this.context.app.renderer.render({
129
+ container: alpha_sprite,
130
+ target: target_texture,
131
+ clear: false
132
+ });
133
+
134
+ container.destroy({ children: true });
135
+ alpha_sprite.destroy();
136
+ alpha_sprite_texture.destroy();
137
+ }
138
+
139
+ if (erase_segments.length > 0) {
140
+ // create a temp texture to work with
141
+ const temp_content_texture = RenderTexture.create({
142
+ width: target_texture.width,
143
+ height: target_texture.height,
144
+ resolution: window.devicePixelRatio || 1
145
+ });
146
+
147
+ const copy_sprite = new Sprite(target_texture);
148
+ const copy_container = new Container();
149
+ copy_container.addChild(copy_sprite);
150
+
151
+ this.context.app.renderer.render({
152
+ container: copy_container,
153
+ target: temp_content_texture,
154
+ clear: true
155
+ });
156
+
157
+ // create a graphics object to draw the erase segments
158
+ const erase_graphics = new Graphics();
159
+ const erase_container = new Container();
160
+ erase_container.addChild(erase_graphics);
161
+
162
+ erase_graphics.setFillStyle({
163
+ color: 0xffffff,
164
+ alpha: 1.0
165
+ });
166
+
167
+ for (const segment of erase_segments) {
168
+ this.render_segment_to_graphics(erase_graphics, segment);
169
+ }
170
+
171
+ // create a separate texture to hold the mask
172
+ const mask_texture = RenderTexture.create({
173
+ width: target_texture.width,
174
+ height: target_texture.height,
175
+ resolution: window.devicePixelRatio || 1
176
+ });
177
+
178
+ this.context.app.renderer.render({
179
+ container: erase_container,
180
+ target: mask_texture,
181
+ clear: true
182
+ });
183
+
184
+ const content_sprite = new Sprite(temp_content_texture);
185
+ const mask_sprite = new Sprite(mask_texture);
186
+
187
+ // only now do we create a sprite from the original texture and add the mask
188
+ const masked_container = new Container();
189
+ masked_container.addChild(content_sprite);
190
+ masked_container.setMask({ mask: mask_sprite, inverse: true }); // inverse mask = erase
191
+
192
+ // now we can render the masked content back to the target texture
193
+ this.context.app.renderer.render({
194
+ container: masked_container,
195
+ target: target_texture,
196
+ clear: true
197
+ });
198
+
199
+ copy_container.destroy({ children: true });
200
+ erase_container.destroy({ children: true });
201
+ masked_container.destroy({ children: true });
202
+ temp_content_texture.destroy();
203
+ mask_texture.destroy();
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Renders a segment to a graphics object (extracted from renderSegment)
209
+ */
210
+ private render_segment_to_graphics(
211
+ graphics: Graphics,
212
+ segment: BrushSegment
213
+ ): void {
214
+ const distance = Math.sqrt(
215
+ Math.pow(segment.to_x - segment.from_x, 2) +
216
+ Math.pow(segment.to_y - segment.from_y, 2)
217
+ );
218
+
219
+ if (distance < 0.1) {
220
+ graphics.circle(segment.from_x, segment.from_y, segment.size).fill();
221
+ } else {
222
+ const spacing = Math.max(segment.size / 3, 2);
223
+ const steps = Math.max(Math.ceil(distance / spacing), 2);
224
+
225
+ for (let i = 0; i < steps; i++) {
226
+ const t = i / (steps - 1);
227
+ const x = segment.from_x + (segment.to_x - segment.from_x) * t;
228
+ const y = segment.from_y + (segment.to_y - segment.from_y) * t;
229
+
230
+ graphics.circle(x, y, segment.size).fill();
231
+ }
232
+ }
233
+ }
234
+
235
+ async execute(context: ImageEditorContext): Promise<void> {
236
+ if (context) {
237
+ this.context = context;
238
+ }
239
+
240
+ let layer_textures = this.context.layer_manager.get_layer_textures(
241
+ this.stroke_data.layer_id
242
+ );
243
+
244
+ if (!layer_textures) {
245
+ const all_layers = this.context.layer_manager.get_layers();
246
+ const top_layer = all_layers[all_layers.length - 1];
247
+ layer_textures = this.context.layer_manager.get_layer_textures(
248
+ top_layer.id
249
+ );
250
+ }
251
+
252
+ if (!layer_textures) return;
253
+
254
+ // create a temporary texture to render the stroke
255
+ const temp_texture = RenderTexture.create({
256
+ width: layer_textures.draw.width,
257
+ height: layer_textures.draw.height,
258
+ resolution: window.devicePixelRatio || 1
259
+ });
260
+
261
+ // copy current layer content to temp texture
262
+ const current_sprite = new Sprite(layer_textures.draw);
263
+ const temp_container = new Container();
264
+ temp_container.addChild(current_sprite);
265
+
266
+ this.context.app.renderer.render({
267
+ container: temp_container,
268
+ target: temp_texture,
269
+ clear: true
270
+ });
271
+
272
+ temp_container.destroy({ children: true });
273
+
274
+ this.render_stroke_from_data(this.stroke_data, temp_texture);
275
+
276
+ // copy final result back to layer texture
277
+ const final_sprite = new Sprite(temp_texture);
278
+ const final_container = new Container();
279
+ final_container.addChild(final_sprite);
280
+
281
+ this.context.app.renderer.render({
282
+ container: final_container,
283
+ target: layer_textures.draw,
284
+ clear: true
285
+ });
286
+
287
+ final_container.destroy({ children: true });
288
+ temp_texture.destroy();
289
+ }
290
+
291
+ async undo(): Promise<void> {
292
+ if (!this.original_texture) return;
293
+
294
+ const layer_textures = this.context.layer_manager.get_layer_textures(
295
+ this.stroke_data.layer_id
296
+ );
297
+ if (!layer_textures) return;
298
+
299
+ const temp_sprite = new Sprite(this.original_texture);
300
+ const temp_container = new Container();
301
+ temp_container.addChild(temp_sprite);
302
+
303
+ this.context.app.renderer.render({
304
+ container: temp_container,
305
+ target: layer_textures.draw,
306
+ clear: true
307
+ });
308
+
309
+ temp_container.destroy({ children: true });
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Class to handle texture operations for the brush tool.
315
+ * Simplified to work directly with layer textures.
316
+ */
317
+ export class BrushTextures {
318
+ private stroke_texture: RenderTexture | null = null;
319
+ private erase_texture: RenderTexture | null = null;
320
+ private display_container: Container | null = null;
321
+ private stroke_container: Container | null = null;
322
+ private stroke_graphics: Graphics | null = null;
323
+ private preview_sprite: Sprite | null = null;
324
+ private erase_graphics: Graphics | null = null;
325
+ private dimensions: { width: number; height: number };
326
+ private image_editor_context: ImageEditorContext;
327
+ private app: Application;
328
+ private is_new_stroke = true;
329
+
330
+ private current_opacity = 1.0;
331
+ private original_layer_texture: Texture | null = null;
332
+ private active_layer_id: string | null = null;
333
+ private current_stroke_segments: BrushSegment[] = [];
334
+
335
+ constructor(image_editor_context: ImageEditorContext, app: Application) {
336
+ this.image_editor_context = image_editor_context;
337
+ this.app = app;
338
+
339
+ this.dimensions = {
340
+ width: this.image_editor_context.image_container.width,
341
+ height: this.image_editor_context.image_container.height
342
+ };
343
+ }
344
+
345
+ /**
346
+ * Initializes textures needed for the brush tool.
347
+ */
348
+ initialize_textures(): void {
349
+ this.cleanup_textures();
350
+
351
+ const local_bounds =
352
+ this.image_editor_context.image_container.getLocalBounds();
353
+
354
+ this.dimensions = {
355
+ width: local_bounds.width,
356
+ height: local_bounds.height
357
+ };
358
+
359
+ this.stroke_texture = RenderTexture.create({
360
+ width: this.dimensions.width,
361
+ height: this.dimensions.height,
362
+ resolution: window.devicePixelRatio || 1
363
+ });
364
+
365
+ this.erase_texture = RenderTexture.create({
366
+ width: this.dimensions.width,
367
+ height: this.dimensions.height,
368
+ resolution: window.devicePixelRatio || 1
369
+ });
370
+
371
+ this.display_container = new Container();
372
+
373
+ this.image_editor_context.image_container.addChild(this.display_container);
374
+
375
+ this.stroke_container = new Container();
376
+ this.stroke_graphics = new Graphics();
377
+ this.stroke_container.addChild(this.stroke_graphics);
378
+
379
+ this.erase_graphics = new Graphics();
380
+
381
+ this.preview_sprite = new Sprite(this.stroke_texture);
382
+ this.preview_sprite.alpha = 0;
383
+ this.display_container.addChild(this.preview_sprite);
384
+
385
+ const clear_container = new Container();
386
+ this.app.renderer.render(clear_container, {
387
+ renderTexture: this.stroke_texture
388
+ });
389
+ this.app.renderer.render(clear_container, {
390
+ renderTexture: this.erase_texture
391
+ });
392
+ clear_container.destroy();
393
+
394
+ this.is_new_stroke = true;
395
+ this.current_opacity = 1.0;
396
+ }
397
+
398
+ /**
399
+ * Reinitializes textures when needed (e.g., after resizing).
400
+ */
401
+ reinitialize(): void {
402
+ const local_bounds =
403
+ this.image_editor_context.image_container.getLocalBounds();
404
+ if (
405
+ Math.round(local_bounds.width) !== Math.round(this.dimensions.width) ||
406
+ Math.round(local_bounds.height) !== Math.round(this.dimensions.height)
407
+ ) {
408
+ this.initialize_textures();
409
+ }
410
+ }
411
+
412
+ /**
413
+ * Cleans up texture resources.
414
+ */
415
+ cleanup_textures(): void {
416
+ if (this.stroke_texture) {
417
+ this.stroke_texture.destroy();
418
+ this.stroke_texture = null;
419
+ }
420
+
421
+ if (this.erase_texture) {
422
+ this.erase_texture.destroy();
423
+ this.erase_texture = null;
424
+ }
425
+
426
+ if (this.display_container) {
427
+ if (this.display_container.parent) {
428
+ this.display_container.parent.removeChild(this.display_container);
429
+ }
430
+ this.display_container.destroy({ children: true });
431
+ this.display_container = null;
432
+ }
433
+
434
+ if (this.original_layer_texture) {
435
+ this.original_layer_texture.destroy();
436
+ this.original_layer_texture = null;
437
+ }
438
+
439
+ this.stroke_container = null;
440
+ this.stroke_graphics = null;
441
+ this.preview_sprite = null;
442
+ this.erase_graphics = null;
443
+ this.active_layer_id = null;
444
+ }
445
+
446
+ /**
447
+ * Preserve the canvas state when starting a new stroke.
448
+ */
449
+ preserve_canvas_state(): void {
450
+ const active_layer =
451
+ this.image_editor_context.layer_manager.get_active_layer();
452
+ if (!active_layer) return;
453
+
454
+ const layers = this.image_editor_context.layer_manager.get_layers();
455
+ const layer = layers.find((l) => l.container === active_layer);
456
+ if (!layer) return;
457
+
458
+ this.active_layer_id = layer.id;
459
+
460
+ const layer_textures =
461
+ this.image_editor_context.layer_manager.get_layer_textures(layer.id);
462
+ if (!layer_textures) return;
463
+
464
+ if (this.original_layer_texture) {
465
+ this.original_layer_texture.destroy();
466
+ }
467
+
468
+ this.original_layer_texture = RenderTexture.create({
469
+ width: this.dimensions.width,
470
+ height: this.dimensions.height,
471
+ resolution: window.devicePixelRatio || 1
472
+ });
473
+
474
+ const temp_sprite = new Sprite(layer_textures.draw);
475
+ const temp_container = new Container();
476
+ temp_container.addChild(temp_sprite);
477
+
478
+ this.app.renderer.render(temp_container, {
479
+ renderTexture: this.original_layer_texture
480
+ });
481
+
482
+ temp_container.destroy({ children: true });
483
+
484
+ this.is_new_stroke = true;
485
+ }
486
+
487
+ /**
488
+ * Resets the eraser mask.
489
+ */
490
+ reset_eraser_mask(): void {
491
+ if (!this.erase_graphics || !this.erase_texture) return;
492
+
493
+ this.erase_graphics.clear();
494
+ this.erase_graphics.setFillStyle({ color: 0xffffff, alpha: 1.0 });
495
+ this.erase_graphics
496
+ .rect(0, 0, this.dimensions.width, this.dimensions.height)
497
+ .fill();
498
+ this.erase_graphics.endFill();
499
+
500
+ this.app.renderer.render(this.erase_graphics, {
501
+ renderTexture: this.erase_texture
502
+ });
503
+ }
504
+
505
+ /**
506
+ * Commits the current stroke to the active layer and returns a command for undo/redo.
507
+ */
508
+ commit_stroke(): void {
509
+ if (
510
+ !this.stroke_texture ||
511
+ !this.preview_sprite ||
512
+ !this.stroke_graphics ||
513
+ !this.original_layer_texture ||
514
+ !this.active_layer_id
515
+ )
516
+ return;
517
+
518
+ this.preview_sprite.visible = false;
519
+
520
+ const active_layer =
521
+ this.image_editor_context.layer_manager.get_active_layer();
522
+
523
+ if (!active_layer) return;
524
+
525
+ const layers = this.image_editor_context.layer_manager.get_layers();
526
+ const layer = layers.find((l) => l.container === active_layer);
527
+ if (!layer) return;
528
+
529
+ if (layer.id !== this.active_layer_id) return;
530
+
531
+ const layer_textures =
532
+ this.image_editor_context.layer_manager.get_layer_textures(layer.id);
533
+ if (!layer_textures) return;
534
+
535
+ const stroke_data: BrushStroke = {
536
+ segments: [...this.current_stroke_segments],
537
+ layer_id: this.active_layer_id
538
+ };
539
+
540
+ const brush_command = new BrushCommand(
541
+ this.image_editor_context,
542
+ stroke_data,
543
+ this.original_layer_texture
544
+ );
545
+
546
+ if (this.stroke_graphics) {
547
+ this.stroke_graphics.clear();
548
+ }
549
+ const clear_container = new Container();
550
+ this.app.renderer.render(clear_container, {
551
+ renderTexture: this.stroke_texture
552
+ });
553
+ clear_container.destroy();
554
+
555
+ this.is_new_stroke = true;
556
+ this.original_layer_texture = null;
557
+ this.active_layer_id = null;
558
+ this.current_stroke_segments = [];
559
+
560
+ this.image_editor_context.command_manager.execute(
561
+ brush_command,
562
+ this.image_editor_context
563
+ );
564
+ }
565
+
566
+ /**
567
+ * Calculates the distance between two points.
568
+ */
569
+ private calculate_distance(
570
+ x1: number,
571
+ y1: number,
572
+ x2: number,
573
+ y2: number
574
+ ): number {
575
+ return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
576
+ }
577
+
578
+ /**
579
+ * Draws a segment for the current stroke using a simple "stamp" approach.
580
+ */
581
+ draw_segment(
582
+ from_x: number,
583
+ from_y: number,
584
+ to_x: number,
585
+ to_y: number,
586
+ size: number,
587
+ color: string,
588
+ opacity: number,
589
+ mode: "draw" | "erase"
590
+ ): void {
591
+ if (
592
+ !this.stroke_graphics ||
593
+ !this.stroke_texture ||
594
+ !this.stroke_container ||
595
+ !this.preview_sprite
596
+ )
597
+ return;
598
+
599
+ if (this.is_new_stroke && !this.original_layer_texture) {
600
+ this.preserve_canvas_state();
601
+ }
602
+
603
+ this.current_opacity =
604
+ mode === "draw" ? Math.min(Math.max(opacity, 0), 1) : 0.5;
605
+
606
+ const scaled_size = size;
607
+
608
+ if (this.is_new_stroke) {
609
+ this.stroke_graphics.clear();
610
+ this.current_stroke_segments = [];
611
+
612
+ const clear_container = new Container();
613
+ this.app.renderer.render(clear_container, {
614
+ renderTexture: this.stroke_texture
615
+ });
616
+ clear_container.destroy();
617
+
618
+ this.is_new_stroke = false;
619
+ }
620
+
621
+ this.current_stroke_segments.push({
622
+ from_x,
623
+ from_y,
624
+ to_x,
625
+ to_y,
626
+ size: scaled_size,
627
+ color,
628
+ opacity: this.current_opacity,
629
+ mode
630
+ });
631
+
632
+ if (mode === "draw") {
633
+ let colorValue = 0xffffff;
634
+ try {
635
+ if (color.startsWith("#")) {
636
+ colorValue = parseInt(color.replace("#", "0x"), 16);
637
+ }
638
+ } catch (e) {
639
+ colorValue = 0xffffff;
640
+ }
641
+ this.stroke_graphics.setFillStyle({
642
+ color: colorValue,
643
+ alpha: 1.0
644
+ });
645
+ } else {
646
+ this.stroke_graphics.setFillStyle({
647
+ color: 0xffffff,
648
+ alpha: 1.0
649
+ });
650
+ }
651
+
652
+ const distance = this.calculate_distance(from_x, from_y, to_x, to_y);
653
+
654
+ if (distance < 0.1) {
655
+ this.stroke_graphics.circle(from_x, from_y, scaled_size).fill();
656
+ } else {
657
+ const spacing = Math.max(scaled_size / 3, 2);
658
+ const steps = Math.max(Math.ceil(distance / spacing), 2);
659
+
660
+ for (let i = 0; i < steps; i++) {
661
+ const t = i / (steps - 1);
662
+ const x = from_x + (to_x - from_x) * t;
663
+ const y = from_y + (to_y - from_y) * t;
664
+
665
+ this.stroke_graphics.circle(x, y, scaled_size).fill();
666
+ }
667
+ }
668
+
669
+ this.stroke_graphics.endFill();
670
+
671
+ this.app.renderer.render(this.stroke_container, {
672
+ renderTexture: this.stroke_texture
673
+ });
674
+
675
+ if (mode === "draw") {
676
+ this.preview_sprite.texture = this.stroke_texture;
677
+ this.preview_sprite.alpha = this.current_opacity;
678
+
679
+ this.preview_sprite.tint = 0xffffff;
680
+ } else {
681
+ const active_layer =
682
+ this.image_editor_context.layer_manager.get_active_layer();
683
+ if (!active_layer) return;
684
+
685
+ const layers = this.image_editor_context.layer_manager.get_layers();
686
+ const layer = layers.find((l) => l.container === active_layer);
687
+ if (!layer) return;
688
+
689
+ const layer_textures =
690
+ this.image_editor_context.layer_manager.get_layer_textures(layer.id);
691
+ if (!layer_textures) return;
692
+
693
+ const preview_texture = RenderTexture.create({
694
+ width: this.dimensions.width,
695
+ height: this.dimensions.height,
696
+ resolution: window.devicePixelRatio || 1
697
+ });
698
+
699
+ const base_container = new Container();
700
+ const content_sprite = new Sprite(layer_textures.draw);
701
+ base_container.addChild(content_sprite);
702
+ this.app.renderer.render(base_container, {
703
+ renderTexture: preview_texture
704
+ });
705
+ base_container.destroy({ children: true });
706
+
707
+ const preview_container = new Container();
708
+
709
+ const mask_sprite = new Sprite(this.stroke_texture);
710
+
711
+ const overlay = new Graphics();
712
+ overlay.setFillStyle({ color: 0xffffff, alpha: 0.5 });
713
+ overlay.rect(0, 0, this.dimensions.width, this.dimensions.height).fill();
714
+
715
+ overlay.setMask({ mask: mask_sprite, inverse: false });
716
+
717
+ preview_container.addChild(overlay);
718
+
719
+ this.app.renderer.render(preview_container, {
720
+ renderTexture: preview_texture
721
+ });
722
+
723
+ this.preview_sprite.texture = preview_texture;
724
+ this.preview_sprite.alpha = 1.0;
725
+
726
+ preview_container.destroy({ children: true });
727
+ preview_texture.destroy();
728
+ }
729
+
730
+ this.preview_sprite.visible = true;
731
+ }
732
+
733
+ /**
734
+ * Gets current dimensions of the texture.
735
+ */
736
+ get_dimensions(): { width: number; height: number } {
737
+ return this.dimensions;
738
+ }
739
+
740
+ /**
741
+ * Checks if textures are properly initialized.
742
+ */
743
+ get textures_initialized(): boolean {
744
+ return !!(
745
+ this.stroke_texture &&
746
+ this.display_container &&
747
+ this.preview_sprite
748
+ );
749
+ }
750
+
751
+ /**
752
+ * Cleanup all resources.
753
+ */
754
+ cleanup(): void {
755
+ this.cleanup_textures();
756
+ }
757
+ }
6.26.1/imageeditor/shared/brush/brush-utils.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Container, Sprite, Graphics } from "pixi.js";
2
+
3
+ /**
4
+ * Sets the cursor style for a single PIXI object.
5
+ * @param child - The PIXI object to set the cursor for.
6
+ * @param cursor - The cursor style to set.
7
+ */
8
+ export function set_cursor(
9
+ child: Container | Sprite | Graphics,
10
+ cursor: "unset" | "none"
11
+ ): void {
12
+ if (child instanceof Container) {
13
+ child.cursor = cursor;
14
+ } else if ("cursor" in child) {
15
+ (child as any).cursor = cursor;
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Recursively sets the cursor style for PIXI objects.
21
+ * @param children - The PIXI objects to set the cursor for.
22
+ * @param cursor - The cursor style to set.
23
+ */
24
+ export function recurse_set_cursor(
25
+ children: (Container | Sprite | Graphics)[],
26
+ cursor: "unset" | "none"
27
+ ): void {
28
+ for (const child of children) {
29
+ set_cursor(child, cursor);
30
+ if (child instanceof Container && child.children.length > 0) {
31
+ recurse_set_cursor(
32
+ child.children as (Container | Sprite | Graphics)[],
33
+ cursor
34
+ );
35
+ }
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Safely removes a child from its parent.
41
+ * @param child - The child to remove.
42
+ */
43
+ export function safe_remove_child(
44
+ child: Container | Sprite | Graphics | null
45
+ ): void {
46
+ if (child && child.parent) {
47
+ child.parent.removeChild(child);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Safely destroys a PIXI object and nullifies it.
53
+ * @param obj - The object to destroy.
54
+ * @returns null to assist with nullifying the reference.
55
+ */
56
+ export function safe_destroy<T extends { destroy: (options?: any) => void }>(
57
+ obj: T | null
58
+ ): null {
59
+ if (obj) {
60
+ safe_remove_child(obj as any);
61
+ obj.destroy({ children: true });
62
+ }
63
+ return null;
64
+ }
65
+
66
+ /**
67
+ * Clears a timeout safely and nullifies the reference.
68
+ * @param timeout - The timeout to clear.
69
+ * @returns null to assist with nullifying the reference.
70
+ */
71
+ export function clear_timeout(timeout: number | null): null {
72
+ if (timeout !== null) {
73
+ window.clearTimeout(timeout);
74
+ }
75
+ return null;
76
+ }
6.26.1/imageeditor/shared/brush/brush.ts ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Container, type FederatedPointerEvent } from "pixi.js";
2
+ import { type ImageEditorContext, type Tool } from "../core/editor";
3
+ import { type Tool as ToolbarTool, type Subtool } from "../Toolbar.svelte";
4
+ import type { ColorInput } from "tinycolor2";
5
+ import tinycolor from "tinycolor2";
6
+ import { BrushCursor } from "./brush-cursor";
7
+ import { BrushTextures } from "./brush-textures";
8
+ import { recurse_set_cursor } from "./brush-utils";
9
+ import { type BrushState } from "./types";
10
+
11
+ /**
12
+ * BrushTool class implements the Tool interface for drawing and erasing.
13
+ * @class
14
+ * @implements {Tool}
15
+ */
16
+ export class BrushTool implements Tool {
17
+ /**
18
+ * The name of the tool.
19
+ * @type {string}
20
+ */
21
+ name = "brush" as const;
22
+
23
+ /**
24
+ * The context of the image editor.
25
+ * @private
26
+ */
27
+ private image_editor_context!: ImageEditorContext;
28
+
29
+ /**
30
+ * The current tool selected in the toolbar.
31
+ * @private
32
+ */
33
+ private current_tool!: ToolbarTool;
34
+
35
+ /**
36
+ * The current subtool selected in the toolbar.
37
+ * @private
38
+ */
39
+ private current_subtool!: Subtool;
40
+
41
+ /**
42
+ * The state of the brush tool.
43
+ * @private
44
+ */
45
+ private state: BrushState = {
46
+ opacity: 1,
47
+ brush_size: 10,
48
+ color: "#000000",
49
+ mode: "draw"
50
+ };
51
+
52
+ /**
53
+ * Size settings for brush and eraser
54
+ * @private
55
+ */
56
+ private brush_size = 10;
57
+ private eraser_size = 20;
58
+
59
+ /**
60
+ * Drawing state
61
+ * @private
62
+ */
63
+ private is_drawing = false;
64
+ private last_x = 0;
65
+ private last_y = 0;
66
+ private scale = 1;
67
+
68
+ /**
69
+ * Event listeners
70
+ * @private
71
+ */
72
+ private _bound_pointer_down: ((event: FederatedPointerEvent) => void) | null =
73
+ null;
74
+ private _bound_pointer_move: ((event: FederatedPointerEvent) => void) | null =
75
+ null;
76
+ private _bound_pointer_up: (() => void) | null = null;
77
+ private event_callbacks: Map<string, (() => void)[]> = new Map();
78
+ /**
79
+ * Utility modules
80
+ * @private
81
+ */
82
+ private brush_cursor: BrushCursor | null = null;
83
+ private brush_textures: BrushTextures | null = null;
84
+
85
+ /**
86
+ * Sets up the brush tool with the given context, tool, and subtool.
87
+ * @param {ImageEditorContext} context - The image editor context.
88
+ * @param {ToolbarTool} tool - The tool from the toolbar.
89
+ * @param {Subtool} subtool - The subtool from the toolbar.
90
+ * @returns {Promise<void>}
91
+ */
92
+ async setup(
93
+ context: ImageEditorContext,
94
+ tool: ToolbarTool,
95
+ subtool: Subtool
96
+ ): Promise<void> {
97
+ this.image_editor_context = context;
98
+ this.current_tool = tool;
99
+ this.current_subtool = subtool;
100
+
101
+ this.state.mode = tool === "erase" ? "erase" : "draw";
102
+
103
+ if (this.state.mode === "draw") {
104
+ this.state.brush_size = this.brush_size;
105
+ } else {
106
+ this.state.brush_size = this.eraser_size;
107
+ }
108
+
109
+ context.scale.subscribe((scale) => {
110
+ this.scale = scale;
111
+ if (this.brush_cursor) {
112
+ this.brush_cursor.update_state(this.state, this.scale);
113
+ }
114
+ });
115
+
116
+ this.brush_cursor = new BrushCursor(
117
+ this.image_editor_context,
118
+ this.state,
119
+ this.scale
120
+ );
121
+
122
+ this.brush_cursor.set_active(tool === "draw" || tool === "erase");
123
+
124
+ this.brush_textures = new BrushTextures(
125
+ this.image_editor_context,
126
+ context.app
127
+ );
128
+ this.brush_textures.initialize_textures();
129
+
130
+ this.setup_event_listeners();
131
+
132
+ this.handle_cursors(tool);
133
+ }
134
+
135
+ /**
136
+ * Handles cursor styles for the brush tool.
137
+ * @param {ToolbarTool} tool - The current tool.
138
+ * @private
139
+ */
140
+ private handle_cursors(tool: ToolbarTool): void {
141
+ recurse_set_cursor(
142
+ this.image_editor_context.image_container.children as Container[],
143
+ "none"
144
+ );
145
+ }
146
+
147
+ /**
148
+ * Sets the current tool and subtool.
149
+ * @param {ToolbarTool} tool - The current tool.
150
+ * @param {Subtool} subtool - The current subtool.
151
+ */
152
+ set_tool(tool: ToolbarTool, subtool: Subtool): void {
153
+ const new_mode = tool === "erase" ? "erase" : "draw";
154
+ const mode_changed = this.state.mode !== new_mode;
155
+ const needs_brush_tool = tool === "erase" || tool === "draw";
156
+
157
+ if (this.is_drawing && (!needs_brush_tool || mode_changed)) {
158
+ this.commit_pending_changes();
159
+ }
160
+
161
+ this.current_tool = tool;
162
+ this.current_subtool = subtool;
163
+
164
+ if (this.brush_cursor) {
165
+ const should_be_active = tool === "draw" || tool === "erase";
166
+
167
+ this.brush_cursor.set_active(should_be_active);
168
+ }
169
+
170
+ const textures_initialized =
171
+ this.brush_textures?.textures_initialized ?? false;
172
+
173
+ let dimensions_changed = false;
174
+ if (this.brush_textures && textures_initialized) {
175
+ const current_bounds =
176
+ this.image_editor_context.image_container.getLocalBounds();
177
+ const tex_dims = this.brush_textures.get_dimensions();
178
+ dimensions_changed =
179
+ Math.round(current_bounds.width) !== Math.round(tex_dims.width) ||
180
+ Math.round(current_bounds.height) !== Math.round(tex_dims.height);
181
+ }
182
+
183
+ if (needs_brush_tool && (!textures_initialized || dimensions_changed)) {
184
+ this.brush_textures?.initialize_textures();
185
+ }
186
+
187
+ if (this.state.mode !== new_mode) {
188
+ this.state.mode = new_mode;
189
+
190
+ if (this.state.mode === "draw") {
191
+ this.state.brush_size = this.brush_size;
192
+ } else {
193
+ this.state.brush_size = this.eraser_size;
194
+ }
195
+
196
+ if (this.brush_cursor) {
197
+ this.brush_cursor.update_state(this.state, this.scale);
198
+ }
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Commits any pending changes to the canvas.
204
+ * @private
205
+ */
206
+ private commit_pending_changes(): void {
207
+ if (this.is_drawing) {
208
+ this.on_pointer_up();
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Called when the user presses the mouse button.
214
+ * @param {FederatedPointerEvent} event - The pointer event.
215
+ * @private
216
+ */
217
+ private on_pointer_down(event: FederatedPointerEvent): void {
218
+ const current_layer =
219
+ this.image_editor_context.layer_manager.get_active_layer();
220
+
221
+ if (
222
+ !current_layer?.visible ||
223
+ (this.current_tool !== "erase" && this.current_tool !== "draw")
224
+ ) {
225
+ return;
226
+ }
227
+
228
+ if (this.brush_cursor && !this.brush_cursor.is_over_image()) {
229
+ return;
230
+ }
231
+
232
+ if (this.brush_textures) {
233
+ this.brush_textures.preserve_canvas_state();
234
+ }
235
+
236
+ const local_pos = this.image_editor_context.image_container.toLocal(
237
+ event.global
238
+ );
239
+
240
+ this.is_drawing = true;
241
+ this.last_x = local_pos.x;
242
+ this.last_y = local_pos.y;
243
+
244
+ if (this.brush_textures) {
245
+ this.brush_textures.draw_segment(
246
+ local_pos.x,
247
+ local_pos.y,
248
+ local_pos.x,
249
+ local_pos.y,
250
+ this.state.brush_size,
251
+ this.state.color,
252
+ this.state.opacity,
253
+ this.state.mode
254
+ );
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Called when the user moves the mouse while drawing.
260
+ * @param {FederatedPointerEvent} event - The pointer event.
261
+ * @private
262
+ */
263
+ private on_pointer_move(event: FederatedPointerEvent): void {
264
+ if (this.brush_cursor) {
265
+ this.brush_cursor.update_cursor_position(event);
266
+ }
267
+
268
+ if (!this.is_drawing) return;
269
+
270
+ const local_pos = this.image_editor_context.image_container.toLocal(
271
+ event.global
272
+ );
273
+
274
+ if (this.brush_textures) {
275
+ this.brush_textures.draw_segment(
276
+ this.last_x,
277
+ this.last_y,
278
+ local_pos.x,
279
+ local_pos.y,
280
+ this.state.brush_size,
281
+ this.state.color,
282
+ this.state.opacity,
283
+ this.state.mode
284
+ );
285
+ }
286
+
287
+ this.last_x = local_pos.x;
288
+ this.last_y = local_pos.y;
289
+ }
290
+
291
+ /**
292
+ * Called when the user releases the mouse button.
293
+ * @private
294
+ */
295
+ private on_pointer_up(): void {
296
+ if (!this.is_drawing) return;
297
+
298
+ this.is_drawing = false;
299
+
300
+ if (this.brush_textures) {
301
+ this.brush_textures.commit_stroke();
302
+ }
303
+
304
+ this.notify("change");
305
+ }
306
+
307
+ /**
308
+ * Sets up event listeners for drawing.
309
+ * @private
310
+ */
311
+ private setup_event_listeners(): void {
312
+ this.cleanup_event_listeners();
313
+
314
+ this._bound_pointer_down = this.on_pointer_down.bind(this);
315
+ this._bound_pointer_move = this.on_pointer_move.bind(this);
316
+ this._bound_pointer_up = this.on_pointer_up.bind(this);
317
+
318
+ const image_container = this.image_editor_context.image_container;
319
+ image_container.eventMode = "static";
320
+ image_container.interactiveChildren = true;
321
+
322
+ const stage = this.image_editor_context.app.stage;
323
+ stage.eventMode = "static";
324
+
325
+ stage.on("pointerdown", this._bound_pointer_down);
326
+ stage.on("pointermove", this._bound_pointer_move);
327
+ stage.on("pointerup", this._bound_pointer_up);
328
+ stage.on("pointerupoutside", this._bound_pointer_up);
329
+
330
+ if (this.brush_cursor) {
331
+ this.brush_cursor.setup_event_listeners();
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Cleans up event listeners.
337
+ * @private
338
+ */
339
+ private cleanup_event_listeners(): void {
340
+ const stage = this.image_editor_context.app.stage;
341
+
342
+ if (this._bound_pointer_down) {
343
+ stage.off("pointerdown", this._bound_pointer_down);
344
+ this._bound_pointer_down = null;
345
+ }
346
+
347
+ if (this._bound_pointer_move) {
348
+ stage.off("pointermove", this._bound_pointer_move);
349
+ this._bound_pointer_move = null;
350
+ }
351
+
352
+ if (this._bound_pointer_up) {
353
+ stage.off("pointerup", this._bound_pointer_up);
354
+ stage.off("pointerupoutside", this._bound_pointer_up);
355
+ this._bound_pointer_up = null;
356
+ }
357
+
358
+ if (this.brush_cursor) {
359
+ this.brush_cursor.cleanup_event_listeners();
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Sets the brush size.
365
+ * @param {number} size - The new brush size.
366
+ */
367
+ set_brush_size(size: number): void {
368
+ this.brush_size = size;
369
+
370
+ if (this.state.mode === "draw") {
371
+ this.state.brush_size = size;
372
+
373
+ if (this.brush_cursor) {
374
+ this.brush_cursor.update_state(this.state, this.scale);
375
+ }
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Sets the brush color.
381
+ * @param {string|ColorInput} color - The new brush color.
382
+ */
383
+ set_brush_color(color: string | ColorInput): void {
384
+ const color_string = tinycolor(color).toHexString();
385
+
386
+ this.state.color = color_string;
387
+
388
+ if (this.brush_cursor) {
389
+ this.brush_cursor.update_state(this.state, this.scale);
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Sets the brush opacity.
395
+ * @param {number} opacity - The new brush opacity.
396
+ */
397
+ set_brush_opacity(opacity: number): void {
398
+ const clamped_opacity = Math.max(0, Math.min(1, opacity));
399
+
400
+ this.state.opacity = clamped_opacity;
401
+
402
+ if (this.brush_cursor) {
403
+ this.brush_cursor.update_state(this.state, this.scale);
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Sets the eraser size.
409
+ * @param {number} size - The new eraser size.
410
+ */
411
+ set_eraser_size(size: number): void {
412
+ this.eraser_size = size;
413
+
414
+ if (this.state.mode === "erase") {
415
+ this.state.brush_size = size;
416
+
417
+ if (this.brush_cursor) {
418
+ this.brush_cursor.update_state(this.state, this.scale);
419
+ }
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Gets the current size based on mode (brush or eraser).
425
+ * @returns {number} The current size.
426
+ */
427
+ get_current_size(): number {
428
+ return this.state.mode === "draw" ? this.brush_size : this.eraser_size;
429
+ }
430
+
431
+ /**
432
+ * Shows or hides the brush preview.
433
+ * @param {boolean} show - Whether to show the preview.
434
+ */
435
+ preview_brush(show: boolean): void {
436
+ if (this.brush_cursor) {
437
+ this.brush_cursor.preview_brush(show);
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Cleans up resources used by the brush tool.
443
+ */
444
+ cleanup(): void {
445
+ this.commit_pending_changes();
446
+
447
+ this.cleanup_event_listeners();
448
+
449
+ if (this.brush_textures) {
450
+ this.brush_textures.cleanup();
451
+ this.brush_textures = null;
452
+ }
453
+
454
+ if (this.brush_cursor) {
455
+ this.brush_cursor.cleanup();
456
+ this.brush_cursor = null;
457
+ }
458
+ }
459
+
460
+ on<T extends string>(event: T, callback: () => void): void {
461
+ this.event_callbacks.set(event, [
462
+ ...(this.event_callbacks.get(event) || []),
463
+ callback
464
+ ]);
465
+ }
466
+
467
+ off<T extends string>(event: T, callback: () => void): void {
468
+ this.event_callbacks.set(
469
+ event,
470
+ this.event_callbacks.get(event)?.filter((cb) => cb !== callback) || []
471
+ );
472
+ }
473
+
474
+ private notify<T extends string>(event: T): void {
475
+ for (const callback of this.event_callbacks.get(event) || []) {
476
+ callback();
477
+ }
478
+ }
479
+ }
6.26.1/imageeditor/shared/brush/types.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { type ColorInput } from "tinycolor2";
2
+
3
+ /**
4
+ * Represents the state of the brush tool.
5
+ * @interface BrushState
6
+ * @property {number} opacity - The opacity of the brush.
7
+ * @property {number} brush_size - The size of the brush.
8
+ * @property {string} color - The color of the brush in hex format.
9
+ * @property {"draw"|"erase"} mode - The mode of the brush, either draw or erase.
10
+ */
11
+ export interface BrushState {
12
+ opacity: number;
13
+ brush_size: number;
14
+ color: string;
15
+ mode: "draw" | "erase";
16
+ }
17
+
18
+ export interface Eraser {
19
+ /**
20
+ * The default size of the eraser.
21
+ */
22
+ default_size: number | "auto";
23
+ }
24
+
25
+ export type ColorTuple = [ColorInput, number]; // [color, opacity]
26
+
27
+ export interface Brush extends Eraser {
28
+ /**
29
+ * The default color of the brush.
30
+ */
31
+ default_color: ColorInput;
32
+ /**
33
+ * The colors to show in the color swatch.
34
+ * Can be either simple color strings or [color, opacity] tuples.
35
+ */
36
+ colors: (ColorInput | ColorTuple)[];
37
+ /**
38
+ * Whether to show _only_ the color swatches specified in `colors`, or to show the color swatches specified in `colors` along with the colorpicker.
39
+ */
40
+ color_mode: "fixed" | "defaults";
41
+ }
6.26.1/imageeditor/shared/core/commands.ts ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { writable } from "svelte/store";
2
+ import type { ImageEditorContext } from "./editor";
3
+
4
+ /**
5
+ * Base command interface that is added to the command_managers history
6
+ */
7
+ export interface Command {
8
+ /**
9
+ * The name of the command
10
+ */
11
+ name: string;
12
+ /**
13
+ * Optionally called when the command is first executed for multi-step commands
14
+ * @param args arguments to pass to the command
15
+ */
16
+ start?: (...args: any) => any | Promise<any>;
17
+ /**
18
+ * Optionally called when the command is continued for multi-step commands
19
+ * @param args arguments to pass to the command
20
+ */
21
+ continue?: (...args: any) => any | Promise<any>;
22
+ /**
23
+ * Optionally called when the command is stopped for multi-step commands
24
+ * @param args arguments to pass to the command
25
+ */
26
+ stop?: (...args: any) => any | Promise<any>;
27
+ /**
28
+ * Called by the command manager to execute the command, can act as a no-op if the work has already been done
29
+ * This function must be able to recreate the command if the command is undone and redone (`stop`/`start`/`continue` will not be called again)
30
+ */
31
+ execute(context?: ImageEditorContext): any | Promise<any>;
32
+ /**
33
+ * Called by the command manager to undo the command
34
+ * This function must be able to undo the work done by the execute function
35
+ */
36
+ undo(): any | Promise<any>;
37
+ }
38
+
39
+ /**
40
+ * Creates a command node
41
+ * @param command command to add to the node
42
+ * @returns a command node
43
+ */
44
+ export class CommandNode {
45
+ command: Command | null;
46
+ next: CommandNode | null;
47
+ previous: CommandNode | null;
48
+
49
+ constructor(command?: Command) {
50
+ this.command = command || null;
51
+ this.next = null;
52
+ this.previous = null;
53
+ }
54
+
55
+ push(command: Command): void {
56
+ this.next = null;
57
+
58
+ const node = new CommandNode(command);
59
+ node.previous = this;
60
+ this.next = node;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Creates a command manager
66
+ * @returns a command manager
67
+ */
68
+ export class CommandManager {
69
+ history: CommandNode = new CommandNode();
70
+ current_history = writable(this.history);
71
+
72
+ undo(): void {
73
+ if (this.history.previous) {
74
+ this.history.command?.undo();
75
+ this.history = this.history.previous;
76
+
77
+ this.current_history.update(() => this.history);
78
+ }
79
+ }
80
+ redo(context?: ImageEditorContext): void {
81
+ if (this.history.next) {
82
+ this.history = this.history.next;
83
+ this.history.command?.execute(context);
84
+ this.current_history.update(() => this.history);
85
+ }
86
+ }
87
+
88
+ async execute(command: Command, context: ImageEditorContext): Promise<void> {
89
+ await command.execute(context);
90
+ this.history.push(command);
91
+ this.history = this.history.next!;
92
+
93
+ this.current_history.update(() => this.history);
94
+ }
95
+
96
+ async wait_for_next_frame(): Promise<void> {
97
+ return new Promise((resolve) => {
98
+ requestAnimationFrame(() => {
99
+ resolve();
100
+ });
101
+ });
102
+ }
103
+
104
+ async replay(
105
+ full_history: CommandNode,
106
+ context: ImageEditorContext
107
+ ): Promise<void> {
108
+ while (full_history.previous) {
109
+ full_history = full_history.previous;
110
+ }
111
+
112
+ while (full_history.next) {
113
+ await full_history.next.command!.execute(context);
114
+ full_history = full_history.next;
115
+ }
116
+
117
+ this.history = full_history;
118
+ this.current_history.update(() => this.history);
119
+ }
120
+
121
+ contains(command_name: string): boolean {
122
+ let current: CommandNode | null = this.history;
123
+ while (current) {
124
+ if (current.command?.name === command_name) return true;
125
+ current = current.next;
126
+ }
127
+ return false;
128
+ }
129
+
130
+ reset(): void {
131
+ this.history = new CommandNode();
132
+ this.current_history.update(() => this.history);
133
+ }
134
+ }
6.26.1/imageeditor/shared/core/editor.ts ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Application, Container, Graphics, Sprite, Assets } from "pixi.js";
2
+
3
+ import { DropShadowFilter as BlurFilter } from "pixi-filters/drop-shadow";
4
+
5
+ import { ImageTool } from "../image/image";
6
+
7
+ import { ZoomTool } from "../zoom/zoom";
8
+ import type { Subtool, Tool as ToolbarTool } from "../Toolbar.svelte";
9
+ import type { Readable, Writable } from "svelte/store";
10
+ import { spring, type Spring } from "svelte/motion";
11
+ import { writable } from "svelte/store";
12
+ import { type ImageBlobs, type LayerOptions } from "../types";
13
+ import type { BrushTool } from "../brush/brush";
14
+ import type { CropTool } from "../crop/crop";
15
+ import { CommandManager, type Command } from "./commands";
16
+ import {
17
+ LayerManager,
18
+ AddLayerCommand,
19
+ RemoveLayerCommand,
20
+ ReorderLayerCommand
21
+ } from "./layers";
22
+
23
+ export interface Tool {
24
+ name: string;
25
+ setup(
26
+ context: ImageEditorContext,
27
+ tool: ToolbarTool,
28
+ subtool: Subtool
29
+ ): Promise<void>;
30
+ cleanup(): void;
31
+ set_tool(tool: ToolbarTool, subtool: Subtool): void;
32
+ on?: (event: string, callback: () => void) => void;
33
+ off?: (event: string, callback: () => void) => void;
34
+ }
35
+
36
+ const core_tools = ["image", "zoom"] as const;
37
+
38
+ interface ImageEditorOptions {
39
+ target_element: HTMLElement;
40
+ width: number;
41
+ height: number;
42
+ tools: ((typeof core_tools)[number] | Tool)[];
43
+ fixed_canvas?: boolean;
44
+ dark?: boolean;
45
+ border_region?: number;
46
+ layer_options?: LayerOptions;
47
+ pad_bottom?: number;
48
+ theme_mode?: "dark" | "light";
49
+ }
50
+
51
+ const core_tool_map = {
52
+ image: () => new ImageTool(),
53
+ zoom: () => new ZoomTool()
54
+ } as const;
55
+
56
+ export interface ImageEditorContext {
57
+ app: Application;
58
+ ui_container: Container;
59
+ image_container: Container;
60
+ background_image?: Sprite;
61
+ command_manager: CommandManager;
62
+ layer_manager: LayerManager;
63
+ dimensions: Readable<{ width: number; height: number }>;
64
+ scale: Readable<number>;
65
+ position: Readable<{ x: number; y: number }>;
66
+ set_image_properties: (properties: {
67
+ width?: number;
68
+ height?: number;
69
+ scale?: number;
70
+ position?: { x: number; y: number };
71
+ animate?: boolean;
72
+ }) => Promise<void>;
73
+ execute_command: (command: Command) => Promise<void> | void;
74
+ resize_canvas: (width: number, height: number) => void;
75
+ reset: () => void;
76
+ set_background_image: (image: Sprite) => void;
77
+ request_render: () => void;
78
+ pad_bottom: number;
79
+ }
80
+
81
+ const spring_config = {
82
+ stiffness: 0.45,
83
+ damping: 0.8
84
+ };
85
+
86
+ const RENDER_IDLE_TIMEOUT_MS = 500;
87
+
88
+ interface EditorStatePublic {
89
+ position: { x: number; y: number };
90
+ scale: number;
91
+ subscribe: (callback: (value: any) => void) => () => void;
92
+ current_tool: ToolbarTool;
93
+ current_subtool: Subtool;
94
+ }
95
+
96
+ class EditorState {
97
+ state: EditorStatePublic;
98
+ private scale: number;
99
+ private position: { x: number; y: number };
100
+ private subscribers: Set<(value: any) => void>;
101
+ constructor(editor: ImageEditor) {
102
+ if (!(editor instanceof ImageEditor)) {
103
+ throw new Error("EditorState must be created by ImageEditor");
104
+ }
105
+
106
+ this.scale = 1.0;
107
+ this.position = { x: 0, y: 0 };
108
+ this.subscribers = new Set();
109
+ // @ts-ignore
110
+ this.state = Object.freeze({
111
+ get position() {
112
+ return { ...this.position };
113
+ },
114
+ get scale() {
115
+ return this.scale;
116
+ },
117
+ get current_tool() {
118
+ return this.current_tool;
119
+ },
120
+ get current_subtool() {
121
+ return this.current_subtool;
122
+ },
123
+ subscribe: this.subscribe.bind(this)
124
+ });
125
+ }
126
+
127
+ _set_position(x: number, y: number): void {
128
+ const oldPosition = { ...this.position };
129
+ this.position = { x, y };
130
+ this._notify_subscribers("position", oldPosition, this.position);
131
+ }
132
+
133
+ _set_scale(scale: number): void {
134
+ const oldScale = this.scale;
135
+ this.scale = scale;
136
+ this._notify_subscribers("scale", oldScale, scale);
137
+ }
138
+
139
+ _notify_subscribers(property: string, oldValue: any, newValue: any): void {
140
+ this.subscribers.forEach((callback) => {
141
+ callback({
142
+ property,
143
+ oldValue,
144
+ newValue,
145
+ timestamp: Date.now()
146
+ });
147
+ });
148
+ }
149
+
150
+ subscribe(callback: (value: any) => void): () => void {
151
+ this.subscribers.add(callback);
152
+ return () => this.subscribers.delete(callback);
153
+ }
154
+ }
155
+
156
+ export class ImageEditor {
157
+ public ready: Promise<void>;
158
+ public background_image_present = writable(false);
159
+ public min_zoom = writable(true);
160
+
161
+ private app!: Application;
162
+ private ui_container!: Container;
163
+ private image_container!: Container;
164
+ command_manager: CommandManager;
165
+
166
+ private layer_manager!: LayerManager;
167
+ private tools: Map<string, Tool> = new Map<string, Tool>();
168
+ private current_tool!: ToolbarTool;
169
+ private current_subtool!: Subtool;
170
+ private target_element: HTMLElement;
171
+ private width: number;
172
+ private height: number;
173
+ private original_width: number;
174
+ private original_height: number;
175
+ dimensions: Spring<{ width: number; height: number }>;
176
+ scale: Spring<number>;
177
+ private position: Spring<{ x: number; y: number }>;
178
+ private state: EditorState;
179
+ private scale_value = 1;
180
+ private position_value: { x: number; y: number } = { x: 0, y: 0 };
181
+ private dimensions_value: { width: number; height: number } = {
182
+ width: 0,
183
+ height: 0
184
+ };
185
+ layers: Writable<{
186
+ active_layer: string;
187
+ layers: {
188
+ name: string;
189
+ id: string;
190
+ user_created: boolean;
191
+ visible: boolean;
192
+ }[];
193
+ }> = writable({
194
+ active_layer: "",
195
+ layers: []
196
+ });
197
+ private outline_container!: Container;
198
+ private outline_graphics!: Graphics;
199
+ private background_image?: Sprite;
200
+ private ready_resolve!: (value: void | PromiseLike<void>) => void;
201
+ private event_callbacks: Map<string, (() => void)[]> = new Map();
202
+ private fixed_canvas: boolean;
203
+ private dark: boolean;
204
+ private border_region: number;
205
+ private layer_options: LayerOptions;
206
+ private overlay_container!: Container;
207
+ private overlay_graphics!: Graphics;
208
+ private pad_bottom: number;
209
+ private theme_mode: "dark" | "light";
210
+ private render_idle_remaining = RENDER_IDLE_TIMEOUT_MS;
211
+ private static readonly WAKE_EVENTS: string[] = [
212
+ "pointerdown",
213
+ "pointermove",
214
+ "pointerup",
215
+ "pointerenter",
216
+ "wheel"
217
+ ];
218
+ private wake_render_loop_bound = this.wake_render_loop.bind(this);
219
+ constructor(options: ImageEditorOptions) {
220
+ this.pad_bottom = options.pad_bottom || 0;
221
+ this.dark = options.dark || false;
222
+ this.theme_mode = options.theme_mode || "dark";
223
+ this.target_element = options.target_element;
224
+ this.width = options.width;
225
+ this.height = options.height;
226
+ this.original_width = options.width;
227
+ this.original_height = options.height;
228
+ this.command_manager = new CommandManager();
229
+
230
+ this.ready = new Promise((resolve) => {
231
+ this.ready_resolve = resolve;
232
+ });
233
+ this.fixed_canvas = options.fixed_canvas || false;
234
+ this.tools = new Map<string, Tool>(
235
+ options.tools.map((tool) => {
236
+ if (typeof tool === "string") {
237
+ return [tool, core_tool_map[tool]()];
238
+ }
239
+
240
+ return [tool.name, tool];
241
+ })
242
+ );
243
+
244
+ for (const tool of this.tools.values()) {
245
+ if (tool?.on) {
246
+ tool.on("change", () => {
247
+ this.notify("change");
248
+ });
249
+ }
250
+ }
251
+
252
+ this.dimensions = spring(
253
+ { width: this.width, height: this.height },
254
+ spring_config
255
+ );
256
+ this.scale = spring(1, spring_config);
257
+ this.position = spring({ x: 0, y: 0 }, spring_config);
258
+ this.state = new EditorState(this);
259
+ this.border_region = options.border_region || 0;
260
+ this.layer_options = options.layer_options || {
261
+ allow_additional_layers: true,
262
+ layers: ["Layer 1"],
263
+ disabled: false
264
+ };
265
+ this.scale.subscribe((scale) => {
266
+ this.state._set_scale(scale);
267
+ });
268
+ this.position.subscribe((position) => {
269
+ this.state._set_position(position.x, position.y);
270
+ });
271
+ this.init();
272
+ }
273
+
274
+ get context(): ImageEditorContext {
275
+ const editor = this;
276
+ return {
277
+ app: this.app,
278
+ ui_container: this.ui_container,
279
+ image_container: this.image_container,
280
+ get background_image() {
281
+ return editor.background_image;
282
+ },
283
+ pad_bottom: this.pad_bottom,
284
+ command_manager: this.command_manager,
285
+ layer_manager: this.layer_manager,
286
+ dimensions: { subscribe: this.dimensions.subscribe },
287
+ scale: { subscribe: this.scale.subscribe },
288
+ position: { subscribe: this.position.subscribe },
289
+ set_image_properties: this.set_image_properties.bind(this),
290
+ execute_command: this.execute_command.bind(this),
291
+ resize_canvas: this.resize_canvas.bind(this),
292
+ reset: this.reset.bind(this),
293
+ set_background_image: this.set_background_image.bind(this),
294
+ request_render: this.wake_render_loop.bind(this)
295
+ };
296
+ }
297
+
298
+ async init(): Promise<void> {
299
+ const container_box = this.target_element.getBoundingClientRect();
300
+ new ResizeObserver((entries) => {
301
+ entries.forEach((entry) => {
302
+ this.resize_canvas(
303
+ entry.contentBoxSize[0].inlineSize,
304
+ entry.contentBoxSize[0].blockSize
305
+ );
306
+ });
307
+ }).observe(this.target_element);
308
+
309
+ this.app = new Application();
310
+
311
+ if (!this.dark) {
312
+ (globalThis as any).__PIXI_APP__ = this.app;
313
+ }
314
+ await this.app.init({
315
+ width: container_box.width,
316
+ height: container_box.height,
317
+ backgroundAlpha: this.dark ? 0 : 1,
318
+ backgroundColor: this.theme_mode === "dark" ? "#27272a" : "#ffffff",
319
+ resolution: window.devicePixelRatio,
320
+ autoDensity: true,
321
+ antialias: true,
322
+ powerPreference: "high-performance"
323
+ });
324
+
325
+ const canvas = this.app.canvas as HTMLCanvasElement;
326
+ canvas.style.background = "transparent";
327
+
328
+ this.setup_containers();
329
+
330
+ this.layer_manager.create_background_layer(this.width, this.height);
331
+
332
+ this.layer_manager.init_layers(this.width, this.height);
333
+
334
+ for (const tool of this.tools.values()) {
335
+ await tool.setup(this.context, this.current_tool, this.current_subtool);
336
+ }
337
+
338
+ const zoom = this.tools.get("zoom") as ZoomTool;
339
+ if (zoom) {
340
+ zoom.min_zoom.subscribe((is_min_zoom) => {
341
+ this.min_zoom.set(is_min_zoom);
342
+ });
343
+ }
344
+
345
+ this.target_element.appendChild(canvas);
346
+
347
+ this.target_element.style.background = "transparent";
348
+
349
+ this.dimensions.subscribe((dimensions) => {
350
+ this.dimensions_value = dimensions;
351
+ this.image_container.width = dimensions.width;
352
+ this.image_container.height = dimensions.height;
353
+ this.wake_render_loop();
354
+ });
355
+
356
+ this.scale.subscribe((scale) => {
357
+ this.scale_value = scale;
358
+ this.wake_render_loop();
359
+ });
360
+
361
+ this.position.subscribe((position) => {
362
+ this.position_value = position;
363
+ this.wake_render_loop();
364
+ });
365
+
366
+ this.app.ticker.add((ticker) => {
367
+ this.image_container.scale.set(this.scale_value);
368
+ this.image_container.position.set(
369
+ this.position_value.x,
370
+ this.position_value.y
371
+ );
372
+
373
+ const effective_width = this.dimensions_value.width * this.scale_value;
374
+ const effective_height = this.dimensions_value.height * this.scale_value;
375
+
376
+ const local_x = Math.round(
377
+ this.image_container.position.x - this.outline_container.position.x
378
+ );
379
+ const local_y = Math.round(
380
+ this.image_container.position.y - this.outline_container.position.y
381
+ );
382
+
383
+ this.overlay_container.position.set(
384
+ this.outline_container.position.x,
385
+ this.outline_container.position.y
386
+ );
387
+
388
+ this.outline_graphics.clear();
389
+ this.outline_graphics
390
+ .rect(local_x, local_y, effective_width, effective_height)
391
+ .fill({
392
+ color: this.dark ? 0x333333 : 0xffffff,
393
+ alpha: 1
394
+ });
395
+
396
+ if (this.border_region > 0) {
397
+ const scaled_border = this.border_region * this.scale_value;
398
+ const border_x = local_x + scaled_border - 1;
399
+ const border_y = local_y + scaled_border - 1;
400
+ const border_width = effective_width - scaled_border * 2 + 1;
401
+ const border_height = effective_height - scaled_border * 2 + 1;
402
+
403
+ this.overlay_graphics.clear();
404
+
405
+ this.overlay_graphics
406
+ .rect(border_x, border_y, border_width, border_height)
407
+ .stroke({
408
+ color: 0x999999,
409
+ width: 1,
410
+ alpha: 0,
411
+ pixelLine: true
412
+ });
413
+
414
+ const dashLength = 5;
415
+ const gapLength = 5;
416
+ const totalLength = dashLength + gapLength;
417
+ const lineColor = 0x999999;
418
+
419
+ for (let x = border_x; x < border_x + border_width; x += totalLength) {
420
+ this.overlay_graphics
421
+ .rect(
422
+ x,
423
+ border_y,
424
+ Math.min(dashLength, border_x + border_width - x),
425
+ 1
426
+ )
427
+ .fill({ color: lineColor, alpha: 0.7 });
428
+
429
+ this.overlay_graphics
430
+ .rect(
431
+ x,
432
+ border_y + border_height,
433
+ Math.min(dashLength, border_x + border_width - x),
434
+ 1
435
+ )
436
+ .fill({ color: lineColor, alpha: 0.7 });
437
+ }
438
+
439
+ for (let y = border_y; y < border_y + border_height; y += totalLength) {
440
+ this.overlay_graphics
441
+ .rect(
442
+ border_x,
443
+ y,
444
+ 1,
445
+ Math.min(dashLength, border_y + border_height - y)
446
+ )
447
+ .fill({ color: lineColor, alpha: 0.7 });
448
+
449
+ this.overlay_graphics
450
+ .rect(
451
+ border_x + border_width,
452
+ y,
453
+ 1,
454
+ Math.min(dashLength, border_y + border_height - y)
455
+ )
456
+ .fill({ color: lineColor, alpha: 0.7 });
457
+ }
458
+ } else {
459
+ this.overlay_graphics.clear();
460
+ }
461
+
462
+ this.render_idle_remaining -= ticker.deltaMS;
463
+ if (this.render_idle_remaining <= 0) {
464
+ ticker.stop();
465
+ }
466
+ });
467
+
468
+ for (const event_name of ImageEditor.WAKE_EVENTS) {
469
+ canvas.addEventListener(event_name, this.wake_render_loop_bound);
470
+ }
471
+
472
+ this.wake_render_loop();
473
+ this.ready_resolve();
474
+ }
475
+
476
+ private wake_render_loop(): void {
477
+ this.render_idle_remaining = RENDER_IDLE_TIMEOUT_MS;
478
+ if (this.app?.ticker && !this.app.ticker.started) {
479
+ this.app.ticker.start();
480
+ }
481
+ }
482
+
483
+ private setup_containers(): void {
484
+ this.image_container = new Container({
485
+ eventMode: "static",
486
+ sortableChildren: true
487
+ });
488
+
489
+ this.image_container.width = this.width;
490
+ this.image_container.height = this.height;
491
+
492
+ this.app.stage.sortableChildren = true;
493
+ this.app.stage.alpha = 1;
494
+ this.app.stage.addChild(this.image_container);
495
+
496
+ this.image_container.scale.set(1);
497
+
498
+ this.ui_container = new Container({
499
+ eventMode: "static"
500
+ });
501
+ this.app.stage.addChild(this.ui_container);
502
+ this.ui_container.width = this.width;
503
+ this.ui_container.height = this.height;
504
+
505
+ this.outline_container = new Container();
506
+ this.outline_container.zIndex = -10;
507
+
508
+ this.outline_graphics = new Graphics();
509
+
510
+ this.outline_graphics.rect(0, 0, this.width, this.height).fill({
511
+ color: this.dark ? 0x333333 : 0xffffff,
512
+ alpha: 0
513
+ });
514
+
515
+ if (!this.dark) {
516
+ const blurFilter = new BlurFilter({
517
+ alpha: 0.1,
518
+ blur: 2,
519
+ color: 0x000000,
520
+ offset: { x: 0, y: 0 },
521
+ quality: 4,
522
+ shadowOnly: false
523
+ });
524
+
525
+ this.outline_graphics.filters = [blurFilter];
526
+ }
527
+
528
+ this.outline_container.addChild(this.outline_graphics);
529
+ this.app.stage.addChild(this.outline_container);
530
+
531
+ this.overlay_container = new Container();
532
+ this.app.stage.addChild(this.overlay_container);
533
+ this.overlay_container.width = this.width;
534
+ this.overlay_container.height = this.height;
535
+
536
+ this.overlay_container.zIndex = 999;
537
+ this.overlay_container.eventMode = "static";
538
+ this.overlay_container.interactiveChildren = true;
539
+ this.overlay_graphics = new Graphics();
540
+ this.overlay_container.addChild(this.overlay_graphics);
541
+
542
+ this.overlay_graphics.rect(0, 0, this.width, this.height).fill({
543
+ color: 0x000000,
544
+ alpha: 0
545
+ });
546
+
547
+ const app_center_x = this.app.screen.width / 2;
548
+ const app_center_y = this.app.screen.height / 2;
549
+
550
+ this.image_container.position.set(app_center_x, app_center_y);
551
+ this.outline_container.position.set(app_center_x, app_center_y);
552
+
553
+ this.layer_manager = new LayerManager(
554
+ this.image_container,
555
+ this.app,
556
+ this.fixed_canvas,
557
+ this.dark,
558
+ this.border_region,
559
+ this.layer_options
560
+ );
561
+ this.layers = this.layer_manager.layer_store;
562
+ }
563
+
564
+ resize_canvas(width: number, height: number): void {
565
+ if (this.app.renderer) {
566
+ this.app.renderer.resize(width, height);
567
+ }
568
+
569
+ const app_center_x = width / 2;
570
+ const app_center_y = height / 2;
571
+
572
+ if (this.image_container) {
573
+ this.image_container.position.set(app_center_x, app_center_y);
574
+ }
575
+ if (this.outline_container) {
576
+ this.outline_container.position.set(app_center_x, app_center_y);
577
+ }
578
+ this.wake_render_loop();
579
+ }
580
+
581
+ reset(): void {
582
+ const zoom = this.tools.get("zoom");
583
+
584
+ if (zoom) {
585
+ zoom.cleanup();
586
+ zoom.setup(this.context, this.current_tool, this.current_subtool);
587
+ }
588
+
589
+ const brush = this.tools.get("brush") as BrushTool;
590
+
591
+ if (brush) {
592
+ this.set_tool("draw");
593
+ }
594
+ this.wake_render_loop();
595
+ }
596
+
597
+ async set_image_properties(properties: {
598
+ width?: number;
599
+ height?: number;
600
+ scale?: number;
601
+ position?: { x: number; y: number };
602
+ animate?: boolean;
603
+ }): Promise<void> {
604
+ let hard =
605
+ typeof properties.animate !== "undefined" ? !properties.animate : true;
606
+ if (properties.position) {
607
+ const pos = this.position.set(properties.position, { hard });
608
+ if (hard) {
609
+ await pos;
610
+ }
611
+ }
612
+ if (properties.scale) {
613
+ const scale = this.scale.set(properties.scale, { hard });
614
+ if (hard) {
615
+ await scale;
616
+ }
617
+ }
618
+ if (properties.width && properties.height) {
619
+ this.width = properties.width;
620
+ this.height = properties.height;
621
+ const dimensions = this.dimensions.set(
622
+ { width: properties.width, height: properties.height },
623
+ { hard }
624
+ );
625
+ if (hard) {
626
+ await dimensions;
627
+ }
628
+ }
629
+ }
630
+
631
+ async execute_command(command: Command): Promise<void> {
632
+ await this.command_manager.execute(command, this.context);
633
+ }
634
+
635
+ undo(): void {
636
+ this.command_manager.undo();
637
+ this.notify("change");
638
+ }
639
+
640
+ redo(): void {
641
+ this.command_manager.redo(this.context);
642
+ this.notify("change");
643
+ }
644
+
645
+ async add_image({
646
+ image,
647
+ resize = true
648
+ }: {
649
+ image: Blob | File;
650
+ resize?: boolean;
651
+ }): Promise<void> {
652
+ const image_tool = this.tools.get("image") as ImageTool;
653
+ await image_tool.add_image({
654
+ image,
655
+ fixed_canvas: this.fixed_canvas,
656
+ border_region: this.border_region
657
+ });
658
+ }
659
+
660
+ /**
661
+ * Adds an image from a URL as the background layer
662
+ * @param url The URL of the image to add
663
+ */
664
+ async add_image_from_url(url: string): Promise<void> {
665
+ const image_tool = this.tools.get("image") as ImageTool;
666
+ const texture = await Assets.load(url);
667
+ await image_tool.add_image({
668
+ image: texture,
669
+ fixed_canvas: this.fixed_canvas,
670
+ border_region: this.border_region
671
+ });
672
+
673
+ const resize_tool = this.tools.get("resize") as any;
674
+ if (resize_tool && typeof resize_tool.set_border_region === "function") {
675
+ resize_tool.set_border_region(this.border_region);
676
+ }
677
+ }
678
+
679
+ set_tool(tool: ToolbarTool): void {
680
+ this.current_tool = tool;
681
+
682
+ for (const tool of this.tools.values()) {
683
+ tool.set_tool(this.current_tool, this.current_subtool);
684
+ }
685
+ this.wake_render_loop();
686
+ }
687
+
688
+ set_subtool(subtool: Subtool): void {
689
+ this.current_subtool = subtool;
690
+
691
+ for (const tool of this.tools.values()) {
692
+ tool.set_tool(this.current_tool, this.current_subtool);
693
+ }
694
+ this.wake_render_loop();
695
+ }
696
+
697
+ set_background_image(image: Sprite): void {
698
+ this.background_image = image;
699
+ }
700
+
701
+ async reset_canvas(): Promise<void> {
702
+ this.width = this.original_width;
703
+ this.height = this.original_height;
704
+
705
+ this.layer_manager.reset_layers(this.width, this.height);
706
+ this.background_image = undefined;
707
+ this.background_image_present.set(false);
708
+ this.command_manager.reset();
709
+
710
+ await this.set_image_properties({
711
+ width: this.width,
712
+ height: this.height,
713
+ scale: 1,
714
+ position: { x: 0, y: 0 },
715
+ animate: false
716
+ });
717
+
718
+ this.layer_manager.create_background_layer(this.width, this.height);
719
+
720
+ for (const tool of this.tools.values()) {
721
+ tool.cleanup();
722
+ tool.setup(this.context, this.current_tool, this.current_subtool);
723
+ }
724
+
725
+ const zoom_tool = this.tools.get("zoom") as ZoomTool;
726
+ if (zoom_tool) {
727
+ zoom_tool.min_zoom.subscribe((is_min_zoom) => {
728
+ this.min_zoom.set(is_min_zoom);
729
+ });
730
+ }
731
+
732
+ this.notify("change");
733
+ }
734
+
735
+ add_layer(): void {
736
+ const add_layer_command = new AddLayerCommand(this.context, {
737
+ width: this.width,
738
+ height: this.height,
739
+ user_created: true,
740
+ make_active: true
741
+ });
742
+
743
+ this.execute_command(add_layer_command);
744
+ this.notify("change");
745
+ }
746
+
747
+ /**
748
+ * Adds a new layer with an image loaded from a URL
749
+ * @param layer_urls The URLs of the images to load
750
+ * @returns A Promise that resolves when all layers are added
751
+ */
752
+ async add_layers_from_url(layer_urls: string[] | undefined): Promise<void> {
753
+ this.command_manager.reset();
754
+ const _layers = this.layer_manager.get_layers();
755
+ _layers.forEach((l) => this.layer_manager.delete_layer(l.id));
756
+
757
+ if (layer_urls === undefined || layer_urls.length === 0) {
758
+ this.layer_manager.create_layer({
759
+ width: this.width,
760
+ height: this.height,
761
+ layer_name: undefined,
762
+ user_created: false
763
+ });
764
+ return;
765
+ }
766
+
767
+ const created_layer_ids: string[] = [];
768
+ for await (const url of layer_urls) {
769
+ const layer_id = await this.layer_manager.add_layer_from_url(url);
770
+ if (layer_id) {
771
+ created_layer_ids.push(layer_id);
772
+ }
773
+ }
774
+
775
+ if (created_layer_ids.length > 0) {
776
+ this.layer_manager.set_active_layer(created_layer_ids[0]);
777
+ }
778
+
779
+ const resize_tool = this.tools.get("resize") as any;
780
+ if (resize_tool && typeof resize_tool.set_border_region === "function") {
781
+ resize_tool.set_border_region(this.border_region);
782
+ }
783
+
784
+ this.notify("change");
785
+ this.notify("input");
786
+ }
787
+
788
+ set_layer(id: string): void {
789
+ this.layer_manager.set_active_layer(id);
790
+ this.notify("change");
791
+ }
792
+
793
+ move_layer(id: string, direction: "up" | "down"): void {
794
+ const reorder_layer_command = new ReorderLayerCommand(
795
+ this.context,
796
+ id,
797
+ direction
798
+ );
799
+ this.execute_command(reorder_layer_command);
800
+ this.notify("change");
801
+ }
802
+
803
+ delete_layer(id: string): void {
804
+ const remove_layer_command = new RemoveLayerCommand(this.context, id);
805
+ this.execute_command(remove_layer_command);
806
+ this.notify("change");
807
+ }
808
+
809
+ modify_canvas_size(
810
+ width: number,
811
+ height: number,
812
+ anchor:
813
+ | "top-left"
814
+ | "top"
815
+ | "top-right"
816
+ | "left"
817
+ | "center"
818
+ | "right"
819
+ | "bottom-left"
820
+ | "bottom"
821
+ | "bottom-right",
822
+ scale: boolean
823
+ ): void {
824
+ const oldWidth = this.width;
825
+ const oldHeight = this.height;
826
+
827
+ this.layer_manager.resize_all_layers(
828
+ width,
829
+ height,
830
+ scale,
831
+ anchor,
832
+ oldWidth,
833
+ oldHeight
834
+ );
835
+
836
+ this.width = width;
837
+ this.height = height;
838
+
839
+ this.set_image_properties({
840
+ width,
841
+ height,
842
+ scale: 1,
843
+ position: { x: 0, y: 0 },
844
+ animate: false
845
+ });
846
+ this.notify("change");
847
+ }
848
+
849
+ async get_blobs(): Promise<ImageBlobs> {
850
+ const blobs = await this.layer_manager.get_blobs(this.width, this.height);
851
+ return blobs;
852
+ }
853
+
854
+ on(event: "change" | "input", callback: () => void): void {
855
+ this.event_callbacks.set(event, [
856
+ ...(this.event_callbacks.get(event) || []),
857
+ callback
858
+ ]);
859
+ }
860
+
861
+ off(event: "change", callback: () => void): void {
862
+ this.event_callbacks.set(
863
+ event,
864
+ this.event_callbacks.get(event)?.filter((cb) => cb !== callback) || []
865
+ );
866
+ }
867
+
868
+ private notify(event: "change" | "input"): void {
869
+ this.wake_render_loop();
870
+ for (const callback of this.event_callbacks.get(event) || []) {
871
+ callback();
872
+ }
873
+ }
874
+
875
+ destroy(): void {
876
+ if (!this.app) return;
877
+
878
+ const canvas = this.app.canvas as HTMLCanvasElement | undefined;
879
+ if (canvas) {
880
+ for (const event_name of ImageEditor.WAKE_EVENTS) {
881
+ canvas.removeEventListener(event_name, this.wake_render_loop_bound);
882
+ }
883
+ }
884
+
885
+ this.app?.destroy();
886
+ }
887
+
888
+ resize(width: number, height: number): void {
889
+ this.set_image_properties({
890
+ width,
891
+ height
892
+ });
893
+
894
+ this.reset();
895
+ }
896
+
897
+ async get_crop_bounds(): Promise<{
898
+ image: Blob | null;
899
+ crop_dimensions: { width: number; height: number };
900
+ image_dimensions: { width: number; height: number };
901
+ x: number;
902
+ y: number;
903
+ }> {
904
+ const crop_tool = this.tools.get("crop") as CropTool;
905
+ const crop_bounds = crop_tool.get_crop_bounds();
906
+ const image = await crop_tool.get_image();
907
+
908
+ return {
909
+ image,
910
+ ...crop_bounds
911
+ };
912
+ }
913
+
914
+ get background_image_sprite(): Sprite | undefined {
915
+ return this.background_image;
916
+ }
917
+
918
+ set_layer_options(layer_options: LayerOptions): void {
919
+ this.layer_options = layer_options;
920
+ this.layer_manager.set_layer_options(
921
+ layer_options,
922
+ this.width,
923
+ this.height
924
+ );
925
+ this.wake_render_loop();
926
+ }
927
+
928
+ toggle_layer_visibility(id: string): void {
929
+ this.layer_manager.toggle_layer_visibility(id);
930
+ this.wake_render_loop();
931
+ }
932
+ }
6.26.1/imageeditor/shared/core/layers.ts ADDED
@@ -0,0 +1,1092 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Application,
3
+ Container,
4
+ Graphics,
5
+ Sprite,
6
+ RenderTexture,
7
+ SCALE_MODES,
8
+ Texture,
9
+ Assets
10
+ } from "pixi.js";
11
+
12
+ import { get_canvas_blob } from "../utils/pixi";
13
+ import type { Writable } from "svelte/store";
14
+ import { writable, get } from "svelte/store";
15
+ import { type ImageBlobs, type LayerOptions } from "../types";
16
+ import { type Command } from "./commands";
17
+ import { type ImageEditorContext } from "./editor";
18
+
19
+ export class LayerManager {
20
+ private layers: {
21
+ name: string;
22
+ id: string;
23
+ container: Container;
24
+ user_created: boolean;
25
+ visible: boolean;
26
+ }[] = [];
27
+ private active_layer: Container | null = null;
28
+ private active_layer_id: string | null = null;
29
+ private draw_textures: Map<Container, RenderTexture> = new Map();
30
+ layer_store: Writable<{
31
+ active_layer: string;
32
+ layers: {
33
+ name: string;
34
+ id: string;
35
+ user_created: boolean;
36
+ visible: boolean;
37
+ }[];
38
+ }> = writable({
39
+ active_layer: "",
40
+
41
+ layers: []
42
+ });
43
+ private background_layer: Container | null = null;
44
+ private image_container: Container;
45
+ private app: Application;
46
+ private fixed_canvas: boolean;
47
+ private dark: boolean;
48
+ private border_region: number;
49
+ private layer_options: LayerOptions;
50
+ constructor(
51
+ image_container: Container,
52
+ app: Application,
53
+ fixed_canvas: boolean,
54
+ dark: boolean,
55
+ border_region: number,
56
+ layer_options: LayerOptions
57
+ ) {
58
+ this.image_container = image_container;
59
+ this.app = app;
60
+ this.fixed_canvas = fixed_canvas;
61
+ this.dark = dark;
62
+ this.border_region = border_region;
63
+ this.layer_options = layer_options;
64
+ }
65
+
66
+ toggle_layer_visibility(id: string): void {
67
+ const layer = this.layers.find((l) => l.id === id);
68
+ if (layer) {
69
+ layer.container.visible = !layer.container.visible;
70
+ layer.visible = layer.container.visible;
71
+ this.layer_store.update((state) => ({
72
+ active_layer: state.active_layer,
73
+ layers: this.layers
74
+ }));
75
+ }
76
+ }
77
+
78
+ create_background_layer(width: number, height: number): Container {
79
+ if (this.background_layer) {
80
+ this.background_layer.destroy();
81
+ }
82
+
83
+ const layer = new Container();
84
+
85
+ this.background_layer = layer;
86
+
87
+ const bg_texture = RenderTexture.create({
88
+ width,
89
+ height,
90
+ resolution: window.devicePixelRatio,
91
+ antialias: true,
92
+ scaleMode: SCALE_MODES.NEAREST
93
+ });
94
+
95
+ const bg_sprite = new Sprite(bg_texture);
96
+ layer.addChild(bg_sprite);
97
+
98
+ const clear_graphics = new Graphics();
99
+ clear_graphics.clear();
100
+
101
+ clear_graphics
102
+ .rect(0, 0, width, height)
103
+ .fill({ color: this.dark ? 0x333333 : 0xffffff, alpha: 1 });
104
+
105
+ this.app.renderer.render({
106
+ container: clear_graphics,
107
+ target: bg_texture,
108
+ clear: true
109
+ });
110
+
111
+ this.image_container.addChild(layer);
112
+
113
+ layer.zIndex = -1;
114
+
115
+ this.update_layer_order();
116
+ return layer;
117
+ }
118
+
119
+ set_layer_options(
120
+ layer_options: LayerOptions,
121
+ width: number,
122
+ height: number
123
+ ): void {
124
+ this.layer_options = layer_options;
125
+ this.reset_layers(width, height);
126
+ }
127
+
128
+ /**
129
+ * Creates a background layer from an image URL
130
+ * @param url The URL of the image to use as background
131
+ * @param width The width of the layer (if fixed_canvas is true)
132
+ * @param height The height of the layer (if fixed_canvas is true)
133
+ * @param borderRegion Minimum border region to add around the image for outpainting (in pixels)
134
+ * @returns A Promise that resolves to the background Container when the image is loaded
135
+ */
136
+ async create_background_layer_from_url(
137
+ url: string,
138
+ width?: number,
139
+ height?: number
140
+ ): Promise<Container> {
141
+ const layer = this.create_background_layer(
142
+ width || this.image_container.width,
143
+ height || this.image_container.height
144
+ );
145
+
146
+ try {
147
+ const texture = await Texture.from(url);
148
+ const sprite = new Sprite(texture);
149
+
150
+ const imageWidth = sprite.texture.width;
151
+ const imageHeight = sprite.texture.height;
152
+
153
+ const containerWidth = width || this.image_container.width;
154
+ const containerHeight = height || this.image_container.height;
155
+
156
+ if (this.fixed_canvas) {
157
+ const effectiveContainerWidth = Math.max(
158
+ containerWidth - this.border_region * 2,
159
+ 10
160
+ );
161
+ const effectiveContainerHeight = Math.max(
162
+ containerHeight - this.border_region * 2,
163
+ 10
164
+ );
165
+
166
+ const imageAspectRatio = imageWidth / imageHeight;
167
+ const containerAspectRatio =
168
+ effectiveContainerWidth / effectiveContainerHeight;
169
+
170
+ let finalWidth, finalHeight;
171
+ let posX = this.border_region,
172
+ posY = this.border_region;
173
+
174
+ if (
175
+ imageWidth <= effectiveContainerWidth &&
176
+ imageHeight <= effectiveContainerHeight
177
+ ) {
178
+ finalWidth = imageWidth;
179
+ finalHeight = imageHeight;
180
+ } else {
181
+ if (imageAspectRatio > containerAspectRatio) {
182
+ finalWidth = effectiveContainerWidth;
183
+ finalHeight = effectiveContainerWidth / imageAspectRatio;
184
+ } else {
185
+ finalHeight = effectiveContainerHeight;
186
+ finalWidth = effectiveContainerHeight * imageAspectRatio;
187
+ }
188
+ }
189
+
190
+ posX += Math.round((effectiveContainerWidth - finalWidth) / 2);
191
+ posY += Math.round((effectiveContainerHeight - finalHeight) / 2);
192
+ sprite.width = finalWidth;
193
+ sprite.height = finalHeight;
194
+ sprite.position.set(posX, posY);
195
+ } else {
196
+ sprite.position.set(this.border_region, this.border_region);
197
+
198
+ if (this.background_layer) {
199
+ this.background_layer.destroy();
200
+ }
201
+
202
+ const totalWidth = imageWidth + this.border_region * 2;
203
+ const totalHeight = imageHeight + this.border_region * 2;
204
+ const newLayer = this.create_background_layer(totalWidth, totalHeight);
205
+
206
+ sprite.width = imageWidth;
207
+ sprite.height = imageHeight;
208
+ newLayer.addChild(sprite);
209
+
210
+ return newLayer;
211
+ }
212
+
213
+ layer.addChild(sprite);
214
+
215
+ return layer;
216
+ } catch (error) {
217
+ console.error("Error loading image from URL:", error);
218
+ return layer;
219
+ }
220
+ }
221
+
222
+ create_layer({
223
+ width,
224
+ height,
225
+ layer_name,
226
+ user_created,
227
+ layer_id = undefined,
228
+ make_active = false
229
+ }: {
230
+ width: number;
231
+ height: number;
232
+ layer_name?: string;
233
+ user_created: boolean;
234
+ layer_id?: string;
235
+ make_active?: boolean;
236
+ }): Container {
237
+ const layer = new Container();
238
+ const _layer_id = layer_id || Math.random().toString(36).substring(2, 15);
239
+ const _layer_name = layer_name || `Layer ${this.layers.length + 1}`;
240
+
241
+ this.layers.push({
242
+ name: _layer_name,
243
+ id: _layer_id,
244
+ container: layer,
245
+ user_created,
246
+ visible: true
247
+ });
248
+
249
+ this.image_container.addChild(layer);
250
+
251
+ const draw_texture = RenderTexture.create({
252
+ width,
253
+ height,
254
+ resolution: window.devicePixelRatio,
255
+ antialias: true,
256
+ scaleMode: SCALE_MODES.NEAREST
257
+ });
258
+
259
+ const canvas_sprite = new Sprite(draw_texture);
260
+ layer.addChild(canvas_sprite);
261
+
262
+ const clear_graphics = new Graphics();
263
+ clear_graphics.clear();
264
+ clear_graphics.beginFill(0, 0);
265
+ clear_graphics.drawRect(0, 0, width, height);
266
+ clear_graphics.endFill();
267
+
268
+ this.app.renderer.render({
269
+ container: clear_graphics,
270
+ target: draw_texture,
271
+ clear: true
272
+ });
273
+
274
+ this.draw_textures.set(layer, draw_texture);
275
+
276
+ this.update_layer_order();
277
+ if (make_active) {
278
+ this.set_active_layer(_layer_id);
279
+ }
280
+
281
+ this.layer_store.set({
282
+ active_layer: this.active_layer_id || "",
283
+ layers: this.layers
284
+ });
285
+ return layer;
286
+ }
287
+
288
+ /**
289
+ * Creates a new layer with an image loaded from a URL
290
+ * @param url The URL of the image to load
291
+ * @param borderRegion Minimum border region to add around the image for outpainting (in pixels)
292
+ * @returns A Promise that resolves to the layer ID
293
+ */
294
+ async add_layer_from_url(url: string): Promise<string> {
295
+ const { width, height } = this.image_container.getLocalBounds();
296
+ const layer = this.create_layer({
297
+ width,
298
+ height,
299
+ layer_name: "Layer 1",
300
+ user_created: true
301
+ });
302
+
303
+ const layerIndex = this.layers.findIndex((l) => l.container === layer);
304
+ if (layerIndex === -1) {
305
+ console.error("Could not find newly created layer");
306
+ return "";
307
+ }
308
+ const layerId = this.layers[layerIndex].id;
309
+
310
+ try {
311
+ const texture = await Assets.load(url);
312
+
313
+ const drawTexture = this.draw_textures.get(layer);
314
+ if (!drawTexture) {
315
+ console.error("No draw texture found for layer");
316
+ return layerId;
317
+ }
318
+
319
+ const sprite = new Sprite(texture);
320
+ const imageWidth = sprite.width;
321
+ const imageHeight = sprite.height;
322
+
323
+ let posX = this.border_region;
324
+ let posY = this.border_region;
325
+
326
+ const effectiveWidth = this.fixed_canvas
327
+ ? width - this.border_region * 2
328
+ : width;
329
+ const effectiveHeight = this.fixed_canvas
330
+ ? height - this.border_region * 2
331
+ : height;
332
+
333
+ if (imageWidth < effectiveWidth || imageHeight < effectiveHeight) {
334
+ posX = Math.floor((effectiveWidth - imageWidth) / 2);
335
+ posY = Math.floor((effectiveHeight - imageHeight) / 2);
336
+ }
337
+
338
+ sprite.position.set(posX, posY);
339
+
340
+ if (imageWidth > effectiveWidth || imageHeight > effectiveHeight) {
341
+ const imageAspectRatio = imageWidth / imageHeight;
342
+ const areaAspectRatio = effectiveWidth / effectiveHeight;
343
+
344
+ let finalWidth, finalHeight;
345
+
346
+ if (imageAspectRatio > areaAspectRatio) {
347
+ finalWidth = effectiveWidth;
348
+ finalHeight = effectiveWidth / imageAspectRatio;
349
+ } else {
350
+ finalHeight = effectiveHeight;
351
+ finalWidth = effectiveHeight * imageAspectRatio;
352
+ }
353
+
354
+ sprite.width = finalWidth;
355
+ sprite.height = finalHeight;
356
+
357
+ posX =
358
+ this.border_region + Math.floor((effectiveWidth - finalWidth) / 2);
359
+ posY =
360
+ this.border_region + Math.floor((effectiveHeight - finalHeight) / 2);
361
+ sprite.position.set(posX, posY);
362
+ }
363
+
364
+ this.app.renderer.render(sprite, { renderTexture: drawTexture });
365
+
366
+ this.set_active_layer(layerId);
367
+
368
+ return layerId;
369
+ } catch (error) {
370
+ console.error("Error loading image from URL:", error);
371
+ return layerId;
372
+ }
373
+ }
374
+
375
+ get_active_layer(): typeof this.active_layer {
376
+ return this.active_layer;
377
+ }
378
+
379
+ set_active_layer(id: string): void {
380
+ if (this.layers.some((l) => l.id === id)) {
381
+ this.active_layer =
382
+ this.layers.find((l) => l.id === id)?.container ||
383
+ this.layers[0]?.container ||
384
+ null;
385
+ this.active_layer_id = id;
386
+ this.layer_store.set({
387
+ active_layer: id,
388
+ layers: this.layers
389
+ });
390
+ }
391
+ }
392
+
393
+ get_layers(): typeof this.layers {
394
+ return this.layers;
395
+ }
396
+
397
+ get_layer_textures(id: string): { draw: RenderTexture } | null {
398
+ const layer = this.layers.find((l) => l.id === id);
399
+ if (layer) {
400
+ const draw = this.draw_textures.get(layer.container);
401
+ if (draw) {
402
+ return { draw };
403
+ }
404
+ }
405
+ return null;
406
+ }
407
+
408
+ delete_layer(id: string): void {
409
+ const index = this.layers.findIndex((l) => l.id === id);
410
+ if (index > -1) {
411
+ const draw_texture = this.draw_textures.get(this.layers[index].container);
412
+ if (draw_texture) {
413
+ draw_texture.destroy();
414
+ this.draw_textures.delete(this.layers[index].container);
415
+ }
416
+ this.layers[index].container.destroy();
417
+ if (this.active_layer === this.layers[index].container) {
418
+ const new_active_layer = this.layers[Math.max(0, index - 1)] || null;
419
+ this.active_layer = new_active_layer?.container || null;
420
+ this.active_layer_id = new_active_layer?.id || null;
421
+ }
422
+ this.layers = this.layers.filter((l) => l.id !== id);
423
+
424
+ this.layer_store.update((_layers) => ({
425
+ active_layer:
426
+ _layers.active_layer === id
427
+ ? this.layers[this.layers.length - 1]?.id
428
+ : _layers.active_layer,
429
+ layers: this.layers
430
+ }));
431
+
432
+ this.update_layer_order();
433
+ }
434
+ }
435
+
436
+ private update_layer_order(): void {
437
+ if (this.background_layer) {
438
+ this.background_layer.zIndex = -1;
439
+ }
440
+ this.layers.forEach((layer, index) => {
441
+ layer.container.zIndex = index;
442
+ });
443
+ }
444
+
445
+ move_layer(id: string, direction: "up" | "down"): void {
446
+ const index = this.layers.findIndex((l) => l.id === id);
447
+ if (index > -1) {
448
+ const new_index = direction === "up" ? index - 1 : index + 1;
449
+
450
+ this.layers = this.layers.map((l, i) => {
451
+ if (i === index) {
452
+ return this.layers[new_index];
453
+ }
454
+ if (i === new_index) {
455
+ return this.layers[index];
456
+ }
457
+ return l;
458
+ });
459
+ this.update_layer_order();
460
+ this.layer_store.update((_layers) => ({
461
+ active_layer: id,
462
+ layers: this.layers
463
+ }));
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Resizes all layers to a new width and height
469
+ * @param newWidth The new width of the layers
470
+ * @param newHeight The new height of the layers
471
+ * @param scale If true, scales the layer content to fit the new dimensions. If false, keeps the content size unchanged.
472
+ * @param anchor The anchor point to position the content relative to the new size
473
+ */
474
+ resize_all_layers(
475
+ newWidth: number,
476
+ newHeight: number,
477
+ scale: boolean,
478
+ anchor:
479
+ | "top-left"
480
+ | "top"
481
+ | "top-right"
482
+ | "left"
483
+ | "center"
484
+ | "right"
485
+ | "bottom-left"
486
+ | "bottom"
487
+ | "bottom-right",
488
+ oldCanvasWidth: number,
489
+ oldCanvasHeight: number
490
+ ): void {
491
+ const oldLayersById = new Map(this.layers.map((l) => [l.id, l]));
492
+ const oldBackgroundLayer = this.background_layer;
493
+
494
+ const calculateOffset = (): { offsetX: number; offsetY: number } => {
495
+ let offsetX = 0;
496
+ let offsetY = 0;
497
+ const deltaWidth = newWidth - oldCanvasWidth;
498
+ const deltaHeight = newHeight - oldCanvasHeight;
499
+
500
+ if (anchor.includes("left")) {
501
+ offsetX = 0;
502
+ } else if (anchor.includes("right")) {
503
+ offsetX = deltaWidth;
504
+ } else {
505
+ offsetX = Math.floor(deltaWidth / 2);
506
+ }
507
+
508
+ if (anchor.includes("top")) {
509
+ offsetY = 0;
510
+ } else if (anchor.includes("bottom")) {
511
+ offsetY = deltaHeight;
512
+ } else {
513
+ offsetY = Math.floor(deltaHeight / 2);
514
+ }
515
+
516
+ return { offsetX, offsetY };
517
+ };
518
+
519
+ this.background_layer = this._resize_background_layer(
520
+ oldBackgroundLayer,
521
+ newWidth,
522
+ newHeight,
523
+ scale,
524
+ calculateOffset
525
+ );
526
+
527
+ const processedLayers: {
528
+ name: string;
529
+ id: string;
530
+ container: Container;
531
+ user_created: boolean;
532
+ }[] = [];
533
+
534
+ const oldLayerData = this.layers.map((oldLayer) => ({
535
+ id: oldLayer.id,
536
+ name: oldLayer.name,
537
+ user_created: oldLayer.user_created,
538
+ texture: this.draw_textures.get(oldLayer.container),
539
+ container: oldLayer.container
540
+ }));
541
+
542
+ this.layers = [];
543
+ this.draw_textures.clear();
544
+ for (const oldData of oldLayerData) {
545
+ const newLayer = this._resize_single_layer(
546
+ oldData,
547
+ newWidth,
548
+ newHeight,
549
+ scale,
550
+ calculateOffset
551
+ );
552
+ if (newLayer) {
553
+ processedLayers.push(newLayer);
554
+ }
555
+ }
556
+
557
+ const currentActiveId = get(this.layer_store).active_layer;
558
+ const activeLayerExists = processedLayers.some(
559
+ (l) => l.id === currentActiveId
560
+ );
561
+
562
+ if (!activeLayerExists && processedLayers.length > 0) {
563
+ this.set_active_layer(processedLayers[0].id);
564
+ } else if (processedLayers.length === 0) {
565
+ this.layer_store.update((s) => ({ ...s, active_layer: "" }));
566
+ } else {
567
+ this.layer_store.update((s) => ({ ...s }));
568
+ }
569
+
570
+ this.update_layer_order();
571
+
572
+ setTimeout(() => {
573
+ Assets.cache.reset();
574
+ this.app.renderer.textureGC.run();
575
+ }, 100);
576
+ }
577
+
578
+ /**
579
+ * Helper method to resize the background layer.
580
+ */
581
+ private _resize_background_layer(
582
+ oldBackgroundLayer: Container | null,
583
+ newWidth: number,
584
+ newHeight: number,
585
+ scale: boolean,
586
+ calculateOffset: () => { offsetX: number; offsetY: number }
587
+ ): Container | null {
588
+ if (!oldBackgroundLayer) {
589
+ return this.create_background_layer(newWidth, newHeight);
590
+ }
591
+
592
+ let backgroundImage: Sprite | null = oldBackgroundLayer.children.find(
593
+ (child) =>
594
+ child instanceof Sprite &&
595
+ child.texture !== (oldBackgroundLayer.children[0] as Sprite)?.texture
596
+ ) as Sprite | null;
597
+
598
+ const newBackgroundLayer = this.create_background_layer(
599
+ newWidth,
600
+ newHeight
601
+ );
602
+
603
+ if (backgroundImage) {
604
+ const newBgImage = new Sprite(backgroundImage.texture);
605
+ newBgImage.width = backgroundImage.width;
606
+ newBgImage.height = backgroundImage.height;
607
+
608
+ if (scale) {
609
+ newBgImage.width = newWidth;
610
+ newBgImage.height = newHeight;
611
+ newBgImage.position.set(0, 0);
612
+ } else {
613
+ const { offsetX, offsetY } = calculateOffset();
614
+ newBgImage.position.set(
615
+ backgroundImage.x + offsetX,
616
+ backgroundImage.y + offsetY
617
+ );
618
+ }
619
+ newBackgroundLayer.addChild(newBgImage);
620
+ }
621
+
622
+ return newBackgroundLayer;
623
+ }
624
+
625
+ /**
626
+ * Helper method to resize a single regular layer.
627
+ */
628
+ private _resize_single_layer(
629
+ oldData: {
630
+ id: string;
631
+ name: string;
632
+ user_created: boolean;
633
+ texture: RenderTexture | undefined;
634
+ container: Container;
635
+ },
636
+ newWidth: number,
637
+ newHeight: number,
638
+ scale: boolean,
639
+ calculateOffset: () => { offsetX: number; offsetY: number }
640
+ ): {
641
+ name: string;
642
+ id: string;
643
+ container: Container;
644
+ user_created: boolean;
645
+ } | null {
646
+ if (!oldData.texture) {
647
+ console.warn(
648
+ `No texture found for layer ${oldData.id}, skipping cleanup.`
649
+ );
650
+ if (oldData.container && !oldData.container.destroyed) {
651
+ if (this.image_container.children.includes(oldData.container)) {
652
+ this.image_container.removeChild(oldData.container);
653
+ }
654
+ oldData.container.destroy({ children: true });
655
+ }
656
+ return null;
657
+ }
658
+
659
+ const newContainer = this.create_layer({
660
+ width: newWidth,
661
+ height: newHeight,
662
+ layer_name: oldData.name,
663
+ user_created: oldData.user_created
664
+ });
665
+
666
+ const newLayer = this.layers[this.layers.length - 1];
667
+ newLayer.id = oldData.id;
668
+ const newTexture = this.draw_textures.get(newContainer);
669
+
670
+ if (!newTexture) {
671
+ console.error(
672
+ `Failed to get texture for newly created layer ${newLayer.id}. Cleaning up.`
673
+ );
674
+ if (newContainer && !newContainer.destroyed) {
675
+ if (this.image_container.children.includes(newContainer)) {
676
+ this.image_container.removeChild(newContainer);
677
+ }
678
+ newContainer.destroy({ children: true });
679
+ const idx = this.layers.findIndex((l) => l.container === newContainer);
680
+ if (idx > -1) this.layers.splice(idx, 1);
681
+ this.draw_textures.delete(newContainer);
682
+ }
683
+ if (oldData.texture && !oldData.texture.destroyed)
684
+ oldData.texture.destroy(true);
685
+ if (oldData.container && !oldData.container.destroyed)
686
+ oldData.container.destroy({ children: true });
687
+ return null;
688
+ }
689
+
690
+ this.app.renderer.clear({ target: newTexture, clearColor: [0, 0, 0, 0] });
691
+
692
+ const sprite = new Sprite(oldData.texture);
693
+
694
+ if (scale) {
695
+ sprite.width = newWidth;
696
+ sprite.height = newHeight;
697
+ sprite.position.set(0, 0);
698
+ } else {
699
+ const { offsetX, offsetY } = calculateOffset();
700
+ sprite.position.set(offsetX, offsetY);
701
+ }
702
+
703
+ this.app.renderer.render(sprite, { renderTexture: newTexture });
704
+
705
+ sprite.destroy();
706
+ if (oldData.texture && !oldData.texture.destroyed) {
707
+ oldData.texture.destroy(true);
708
+ }
709
+ if (oldData.container && !oldData.container.destroyed) {
710
+ if (this.image_container.children.includes(oldData.container)) {
711
+ this.image_container.removeChild(oldData.container);
712
+ }
713
+ oldData.container.destroy({ children: true });
714
+ }
715
+
716
+ return newLayer;
717
+ }
718
+
719
+ async get_blobs(width: number, height: number): Promise<ImageBlobs> {
720
+ const blobs = {
721
+ background: await get_canvas_blob(
722
+ this.app.renderer,
723
+ this.background_layer,
724
+ {
725
+ width,
726
+ height,
727
+ x: 0,
728
+ y: 0
729
+ }
730
+ ),
731
+ layers: await Promise.all(
732
+ this.layers.map(async (layer) => {
733
+ const blob = await get_canvas_blob(
734
+ this.app.renderer,
735
+ layer.container,
736
+ {
737
+ width,
738
+ height,
739
+ x: 0,
740
+ y: 0
741
+ }
742
+ );
743
+ if (blob) {
744
+ return blob;
745
+ }
746
+ return null;
747
+ })
748
+ ),
749
+ composite: await get_canvas_blob(
750
+ this.app.renderer,
751
+ this.image_container,
752
+ {
753
+ width,
754
+ height,
755
+ x: 0,
756
+ y: 0
757
+ }
758
+ )
759
+ };
760
+
761
+ return blobs;
762
+ }
763
+
764
+ reset_layers(width: number, height: number, persist = false): void {
765
+ const _layers_to_recreate = persist
766
+ ? this.layers.map((layer) => [layer.name, layer.id])
767
+ : this.layer_options.layers.map((layer) => [layer, undefined]);
768
+
769
+ this.layers.forEach((layer) => {
770
+ this.delete_layer(layer.id);
771
+ });
772
+
773
+ for (const [layer_name, layer_id] of _layers_to_recreate) {
774
+ this.create_layer({
775
+ width,
776
+ height,
777
+ layer_name: layer_name,
778
+ user_created: this.layer_options.layers.find((l) => l === layer_name)
779
+ ? false
780
+ : true,
781
+ layer_id: layer_id
782
+ });
783
+ }
784
+
785
+ if (!persist) {
786
+ this.active_layer = this.layers[0].container;
787
+ this.active_layer_id = this.layers[0].id;
788
+ } else {
789
+ this.active_layer =
790
+ this.layers.find((l) => l.id === this.active_layer_id)?.container ||
791
+ this.layers[0]?.container;
792
+
793
+ if (!this.active_layer) return;
794
+ }
795
+
796
+ this.layer_store.update((state) => ({
797
+ active_layer: this.active_layer_id || this.layers[0].id,
798
+ layers: this.layers
799
+ }));
800
+ }
801
+
802
+ init_layers(width: number, height: number): void {
803
+ for (const layer of this.layers) {
804
+ this.delete_layer(layer.id);
805
+ }
806
+ let i = 0;
807
+ for (const layer of this.layer_options.layers) {
808
+ this.create_layer({
809
+ width,
810
+ height,
811
+ layer_name: layer,
812
+ user_created: false,
813
+ layer_id: `layer-${i}`
814
+ });
815
+ i++;
816
+ }
817
+
818
+ this.active_layer = this.layers[0].container;
819
+ this.active_layer_id = this.layers[0].id;
820
+ this.layer_store.update((_layers) => ({
821
+ active_layer: this.layers[0].id,
822
+ layers: this.layers
823
+ }));
824
+ }
825
+ }
826
+
827
+ /**
828
+ * Command to add a new layer
829
+ */
830
+ export class AddLayerCommand implements Command {
831
+ private layer_id: string;
832
+ private layer_name: string;
833
+ private width: number;
834
+ private height: number;
835
+ private user_created: boolean;
836
+ private make_active: boolean;
837
+ private previous_active_layer: string | null = null;
838
+ name: string;
839
+ constructor(
840
+ private context: ImageEditorContext,
841
+ options: {
842
+ width: number;
843
+ height: number;
844
+ layer_name?: string;
845
+ user_created: boolean;
846
+ layer_id?: string;
847
+ make_active?: boolean;
848
+ }
849
+ ) {
850
+ this.width = options.width;
851
+ this.height = options.height;
852
+ this.layer_name =
853
+ options.layer_name ||
854
+ `Layer ${this.context.layer_manager.get_layers().length + 1}`;
855
+ this.user_created = options.user_created;
856
+ this.layer_id =
857
+ options.layer_id || Math.random().toString(36).substring(2, 15);
858
+ this.make_active = options.make_active || false;
859
+ this.name = "AddLayer";
860
+ const current_layers = this.context.layer_manager.get_layers();
861
+ const current_active = current_layers.find(
862
+ (l) => l.container === this.context.layer_manager.get_active_layer()
863
+ );
864
+ this.previous_active_layer = current_active?.id || null;
865
+ }
866
+
867
+ async execute(context?: ImageEditorContext): Promise<void> {
868
+ if (context) {
869
+ this.context = context;
870
+ }
871
+
872
+ this.context.layer_manager.create_layer({
873
+ width: this.width,
874
+ height: this.height,
875
+ layer_name: this.layer_name,
876
+ user_created: this.user_created,
877
+ layer_id: this.layer_id,
878
+ make_active: this.make_active
879
+ });
880
+ }
881
+
882
+ async undo(): Promise<void> {
883
+ this.context.layer_manager.delete_layer(this.layer_id);
884
+
885
+ if (this.previous_active_layer) {
886
+ this.context.layer_manager.set_active_layer(this.previous_active_layer);
887
+ }
888
+ }
889
+ }
890
+
891
+ /**
892
+ * Command to remove a layer
893
+ */
894
+ export class RemoveLayerCommand implements Command {
895
+ private layer_data: {
896
+ id: string;
897
+ name: string;
898
+ user_created: boolean;
899
+ visible: boolean;
900
+ was_active: boolean;
901
+ };
902
+ private previous_active_layer: string | null = null;
903
+ private texture_copy: RenderTexture | null = null;
904
+ name: string;
905
+
906
+ constructor(
907
+ private context: ImageEditorContext,
908
+ layer_id: string
909
+ ) {
910
+ this.name = "RemoveLayer";
911
+ const layers = this.context.layer_manager.get_layers();
912
+ const layer_to_remove = layers.find((l) => l.id === layer_id);
913
+
914
+ if (!layer_to_remove) {
915
+ throw new Error(`Layer with ID ${layer_id} not found`);
916
+ }
917
+
918
+ const active_layer = this.context.layer_manager.get_active_layer();
919
+ const was_active = layer_to_remove.container === active_layer;
920
+
921
+ if (was_active) {
922
+ const layer_index = layers.findIndex((l) => l.id === layer_id);
923
+ const next_active = layers[Math.max(0, layer_index - 1)];
924
+ this.previous_active_layer = next_active?.id || null;
925
+ }
926
+
927
+ this.layer_data = {
928
+ id: layer_to_remove.id,
929
+ name: layer_to_remove.name,
930
+ user_created: layer_to_remove.user_created,
931
+ visible: layer_to_remove.visible,
932
+ was_active
933
+ };
934
+
935
+ this.captureTextureData(layer_id);
936
+ }
937
+
938
+ /**
939
+ * Create a direct copy of the layer's texture
940
+ */
941
+ private captureTextureData(layer_id: string): void {
942
+ const layer_textures =
943
+ this.context.layer_manager.get_layer_textures(layer_id);
944
+ if (!layer_textures) return;
945
+
946
+ try {
947
+ const original_texture = layer_textures.draw;
948
+
949
+ const texture_copy = RenderTexture.create({
950
+ width: original_texture.width,
951
+ height: original_texture.height,
952
+ resolution: window.devicePixelRatio || 1
953
+ });
954
+
955
+ const sprite = new Sprite(original_texture);
956
+
957
+ this.context.app.renderer.render(sprite, { renderTexture: texture_copy });
958
+
959
+ this.texture_copy = texture_copy;
960
+
961
+ sprite.destroy();
962
+ } catch (e) {
963
+ console.error("Failed to copy layer texture:", e);
964
+ this.texture_copy = null;
965
+ }
966
+ }
967
+
968
+ async execute(context?: ImageEditorContext): Promise<void> {
969
+ if (context) {
970
+ this.context = context;
971
+ }
972
+
973
+ this.context.layer_manager.delete_layer(this.layer_data.id);
974
+ }
975
+
976
+ async undo(): Promise<void> {
977
+ const dimensions = get(this.context.dimensions);
978
+
979
+ const container = this.context.layer_manager.create_layer({
980
+ width: dimensions.width,
981
+ height: dimensions.height,
982
+ layer_name: this.layer_data.name,
983
+ user_created: this.layer_data.user_created,
984
+ layer_id: this.layer_data.id,
985
+ make_active: this.layer_data.was_active
986
+ });
987
+
988
+ if (this.texture_copy) {
989
+ try {
990
+ const layer_textures = this.context.layer_manager.get_layer_textures(
991
+ this.layer_data.id
992
+ );
993
+ if (layer_textures) {
994
+ const sprite = new Sprite(this.texture_copy);
995
+
996
+ this.context.app.renderer.render(sprite, {
997
+ renderTexture: layer_textures.draw
998
+ });
999
+
1000
+ sprite.destroy();
1001
+ }
1002
+ } catch (e) {
1003
+ console.error("Failed to restore layer content:", e);
1004
+ }
1005
+ }
1006
+
1007
+ if (!this.layer_data.visible) {
1008
+ this.context.layer_manager.toggle_layer_visibility(this.layer_data.id);
1009
+ }
1010
+
1011
+ if (!this.layer_data.was_active && this.previous_active_layer) {
1012
+ this.context.layer_manager.set_active_layer(this.previous_active_layer);
1013
+ }
1014
+ }
1015
+
1016
+ /**
1017
+ * Clean up resources when the command is no longer needed
1018
+ * This would need to be called by a garbage collection mechanism
1019
+ */
1020
+ destroy(): void {
1021
+ if (this.texture_copy) {
1022
+ this.texture_copy.destroy();
1023
+ this.texture_copy = null;
1024
+ }
1025
+ }
1026
+ }
1027
+
1028
+ /**
1029
+ * Command to reorder layers
1030
+ */
1031
+ export class ReorderLayerCommand implements Command {
1032
+ private original_order: string[];
1033
+ private new_order: string[];
1034
+ private layer_id: string;
1035
+ private direction: "up" | "down";
1036
+ name: string;
1037
+
1038
+ constructor(
1039
+ private context: ImageEditorContext,
1040
+ layer_id: string,
1041
+ direction: "up" | "down"
1042
+ ) {
1043
+ this.layer_id = layer_id;
1044
+ this.direction = direction;
1045
+ this.name = "ReorderLayer";
1046
+ const layers = this.context.layer_manager.get_layers();
1047
+ this.original_order = layers.map((l) => l.id);
1048
+
1049
+ const index = layers.findIndex((l) => l.id === layer_id);
1050
+ if (index === -1) {
1051
+ throw new Error(`Layer with ID ${layer_id} not found`);
1052
+ }
1053
+
1054
+ const new_index = direction === "up" ? index - 1 : index + 1;
1055
+ if (new_index < 0 || new_index >= layers.length) {
1056
+ this.new_order = [...this.original_order];
1057
+ } else {
1058
+ this.new_order = [...this.original_order];
1059
+ [this.new_order[index], this.new_order[new_index]] = [
1060
+ this.new_order[new_index],
1061
+ this.new_order[index]
1062
+ ];
1063
+ }
1064
+ }
1065
+
1066
+ async execute(context?: ImageEditorContext): Promise<void> {
1067
+ if (context) {
1068
+ this.context = context;
1069
+ }
1070
+
1071
+ this.context.layer_manager.move_layer(this.layer_id, this.direction);
1072
+ }
1073
+
1074
+ async undo(): Promise<void> {
1075
+ const current_layers = this.context.layer_manager.get_layers();
1076
+
1077
+ if (
1078
+ this.original_order.join(",") ===
1079
+ current_layers.map((l) => l.id).join(",")
1080
+ ) {
1081
+ return;
1082
+ }
1083
+
1084
+ const layer_index = current_layers.findIndex((l) => l.id === this.layer_id);
1085
+ if (layer_index === -1) return;
1086
+
1087
+ const original_index = this.original_order.indexOf(this.layer_id);
1088
+ const move_direction = layer_index > original_index ? "up" : "down";
1089
+
1090
+ this.context.layer_manager.move_layer(this.layer_id, move_direction);
1091
+ }
1092
+ }
6.26.1/imageeditor/shared/crop/crop.ts ADDED
@@ -0,0 +1,1027 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Container,
3
+ Graphics,
4
+ Point,
5
+ Rectangle,
6
+ FederatedPointerEvent,
7
+ Sprite
8
+ } from "pixi.js";
9
+ import { type ImageEditorContext, type Tool } from "../core/editor";
10
+
11
+ import { type Tool as ToolbarTool, type Subtool } from "../Toolbar.svelte";
12
+ import { get_canvas_blob } from "../utils/pixi";
13
+
14
+ /**
15
+ * @interface CropBounds
16
+ * @description Defines the bounds of a crop area
17
+ * @property {number} x - The x-coordinate of the crop area
18
+ * @property {number} y - The y-coordinate of the crop area
19
+ * @property {number} width - The width of the crop area
20
+ * @property {number} height - The height of the crop area
21
+ */
22
+ interface CropBounds {
23
+ x: number;
24
+ y: number;
25
+ width: number;
26
+ height: number;
27
+ }
28
+
29
+ /**
30
+ * @interface EditorState
31
+ * @description Defines the state of the editor
32
+ * @property {ToolbarTool} current_tool - The currently selected tool
33
+ * @property {Subtool} current_subtool - The currently selected subtool
34
+ */
35
+ interface EditorState {
36
+ current_tool: ToolbarTool;
37
+ current_subtool: Subtool;
38
+ }
39
+
40
+ /**
41
+ * @class CropTool
42
+ * @implements {Tool}
43
+ * @description Implements the crop tool functionality for the image editor
44
+ */
45
+ export class CropTool implements Tool {
46
+ name = "crop" as const;
47
+ private image_editor_context!: ImageEditorContext;
48
+ current_tool: ToolbarTool = "image";
49
+ current_subtool: Subtool = "crop";
50
+
51
+ // Constants
52
+ private readonly CORNER_SIZE = 25;
53
+ private readonly LINE_THICKNESS = 5;
54
+ private readonly HANDLE_COLOR = 0x000000;
55
+ private readonly HIT_AREA_SIZE = 40;
56
+
57
+ // State
58
+ private is_dragging = false;
59
+ private selected_handle: Container | null = null;
60
+ private active_corner_index = -1;
61
+ private active_edge_index = -1;
62
+ private last_pointer_position: Point | null = null;
63
+ crop_bounds: CropBounds = { x: 0, y: 0, width: 0, height: 0 };
64
+ private crop_ui_container: Container | null = null;
65
+ private crop_mask: Graphics | null = null;
66
+ private dimensions: { width: number; height: number } = {
67
+ width: 0,
68
+ height: 0
69
+ };
70
+ private position: { x: number; y: number } = { x: 0, y: 0 };
71
+ private scale = 1;
72
+ private is_dragging_window = false;
73
+ private drag_start_position: Point | null = null;
74
+ private drag_start_bounds: CropBounds | null = null;
75
+ private background_image_watcher: (() => void) | null = null;
76
+ private has_been_manually_changed = false;
77
+ private event_callbacks: Map<string, (() => void)[]> = new Map();
78
+ /**
79
+ * @method setup
80
+ * @async
81
+ * @description Sets up the crop tool with the given context and state
82
+ * @param {ImageEditorContext} context - The image editor context
83
+ * @param {ToolbarTool} tool - The current tool
84
+ * @param {Subtool} subtool - The current subtool
85
+ * @returns {Promise<void>}
86
+ */
87
+ async setup(
88
+ context: ImageEditorContext,
89
+ tool: ToolbarTool,
90
+ subtool: Subtool
91
+ ): Promise<void> {
92
+ this.image_editor_context = context;
93
+ this.current_tool = tool;
94
+ this.current_subtool = subtool;
95
+
96
+ context.dimensions.subscribe((dimensions) => {
97
+ this.dimensions = dimensions;
98
+
99
+ // Update crop bounds to match new dimensions
100
+ this.crop_bounds = {
101
+ x: 0,
102
+ y: 0,
103
+ width: dimensions.width,
104
+ height: dimensions.height
105
+ };
106
+
107
+ // Force UI update if it exists
108
+ if (this.crop_ui_container) {
109
+ this.update_crop_ui();
110
+ }
111
+
112
+ // Always update the mask when dimensions change
113
+ this.set_crop_mask();
114
+ this.update_crop_mask();
115
+ });
116
+
117
+ context.position.subscribe((position) => {
118
+ this.position = position;
119
+ });
120
+
121
+ context.scale.subscribe((scale) => {
122
+ this.scale = scale;
123
+ });
124
+
125
+ // Setup a background image watcher to ensure we always apply the mask to the current background image
126
+ this.background_image_watcher = () => {
127
+ // Only apply when crop tool is active and we have a mask
128
+ if (
129
+ this.crop_mask &&
130
+ this.current_tool === "image" &&
131
+ this.current_subtool === "crop"
132
+ ) {
133
+ // Get a fresh reference to the background image and apply the mask
134
+ if (this.image_editor_context.background_image) {
135
+ this.image_editor_context.background_image.setMask(this.crop_mask);
136
+ }
137
+ }
138
+ };
139
+
140
+ // Add the watcher to the ticker to regularly check for background image changes
141
+ this.image_editor_context.app.ticker.add(this.background_image_watcher);
142
+
143
+ // Initialize crop UI
144
+ await this.init_crop_ui();
145
+
146
+ // Setup event listeners
147
+ this.setup_event_listeners();
148
+
149
+ // Ensure the crop UI visibility matches the current tool state
150
+ const isCropActive = tool === "image" && subtool === "crop";
151
+ if (this.crop_ui_container) {
152
+ this.crop_ui_container.visible = isCropActive;
153
+ }
154
+ }
155
+
156
+ /**
157
+ * @method cleanup
158
+ * @description Cleans up the crop tool resources and removes event listeners
159
+ * @returns {void}
160
+ */
161
+ cleanup(): void {
162
+ // Remove the crop UI container
163
+ if (this.crop_ui_container) {
164
+ this.image_editor_context.app.stage.removeChild(this.crop_ui_container);
165
+ }
166
+
167
+ // Remove the mask and reset the image container's mask property
168
+ if (this.crop_mask) {
169
+ if (this.crop_mask.parent) {
170
+ this.crop_mask.parent.removeChild(this.crop_mask);
171
+ }
172
+
173
+ // Clear mask from background_image if applied
174
+ if (
175
+ this.image_editor_context.background_image &&
176
+ this.image_editor_context.background_image.mask === this.crop_mask
177
+ ) {
178
+ this.image_editor_context.background_image.mask = null;
179
+ }
180
+
181
+ // Clear mask from image_container if applied
182
+ if (this.image_editor_context.image_container.mask === this.crop_mask) {
183
+ this.image_editor_context.image_container.mask = null;
184
+ }
185
+ }
186
+
187
+ // Ensure all references to the crop mask are cleared
188
+ this.crop_mask = null;
189
+ this.crop_ui_container = null;
190
+
191
+ // Remove the background image watcher from the ticker
192
+ if (this.background_image_watcher) {
193
+ this.image_editor_context.app.ticker.remove(
194
+ this.background_image_watcher
195
+ );
196
+ this.background_image_watcher = null;
197
+ }
198
+
199
+ // Remove event listeners
200
+ this.cleanup_event_listeners();
201
+ }
202
+
203
+ /**
204
+ * @method set_tool
205
+ * @description Sets the current tool and subtool, updating UI visibility
206
+ * @param {ToolbarTool} tool - The tool to set
207
+ * @param {Subtool} subtool - The subtool to set
208
+ * @returns {void}
209
+ */
210
+ set_tool(tool: ToolbarTool, subtool: Subtool): void {
211
+ this.current_tool = tool;
212
+ this.current_subtool = subtool;
213
+
214
+ // Show/hide crop UI based on tool and subtool
215
+ const isCropActive = tool === "image" && subtool === "crop";
216
+
217
+ // Only update the UI visibility, not the mask
218
+ if (this.crop_ui_container) {
219
+ this.crop_ui_container.visible = isCropActive;
220
+ }
221
+
222
+ // If crop tool is active, ensure the mask is up to date
223
+ if (isCropActive && this.crop_mask) {
224
+ this.update_crop_mask();
225
+ }
226
+ }
227
+
228
+ /**
229
+ * @method set_crop_mask
230
+ * @private
231
+ * @description Sets up the crop mask for the image
232
+ * @returns {void}
233
+ */
234
+ private set_crop_mask(): void {
235
+ // Remove any existing mask to avoid duplicates
236
+ if (this.crop_mask) {
237
+ if (this.crop_mask.parent) {
238
+ this.crop_mask.parent.removeChild(this.crop_mask);
239
+ }
240
+
241
+ // Clear mask from image_container if it was applied there
242
+ if (this.image_editor_context.image_container.mask === this.crop_mask) {
243
+ this.image_editor_context.image_container.mask = null;
244
+ }
245
+
246
+ // Clear mask from background_image if it was applied there
247
+ if (
248
+ this.image_editor_context.background_image &&
249
+ this.image_editor_context.background_image.mask === this.crop_mask
250
+ ) {
251
+ this.image_editor_context.background_image.mask = null;
252
+ }
253
+ }
254
+
255
+ // Create a new mask that will actually be used as an overlay
256
+ this.crop_mask = new Graphics();
257
+
258
+ // Add the mask/overlay to the display list
259
+ // This time it should be visible since we want to see the semi-transparent overlay
260
+ this.image_editor_context.image_container.addChild(this.crop_mask);
261
+ }
262
+
263
+ /**
264
+ * @method init_crop_ui
265
+ * @private
266
+ * @async
267
+ * @description Initializes the crop UI elements and sets up the update loop
268
+ * @returns {Promise<void>}
269
+ */
270
+ private async init_crop_ui(): Promise<void> {
271
+ // Create crop UI with scaled dimensions
272
+ const { width, height } =
273
+ this.image_editor_context.background_image?.getLocalBounds() || {
274
+ width: false,
275
+ height: false
276
+ };
277
+
278
+ this.crop_ui_container = this.make_crop_ui(
279
+ this.dimensions.width * this.scale,
280
+ this.dimensions.height * this.scale
281
+ );
282
+
283
+ // Position the crop UI container at the image position
284
+ this.crop_ui_container.position.set(this.position.x, this.position.y);
285
+
286
+ // Initially hide the crop UI until explicitly enabled by set_tool
287
+ this.crop_ui_container.visible = false;
288
+
289
+ this.image_editor_context.app.stage.addChild(this.crop_ui_container);
290
+
291
+ // Create and apply mask to the image container
292
+ this.set_crop_mask();
293
+
294
+ // Start the update loop for the UI
295
+ this.image_editor_context.app.ticker.add(this.update_crop_ui.bind(this));
296
+
297
+ // Initialize the mask with the current crop bounds
298
+ this.update_crop_mask();
299
+ }
300
+
301
+ /**
302
+ * @method make_crop_ui
303
+ * @private
304
+ * @description Creates the crop UI with the specified dimensions
305
+ * @param {number} width - Width of the crop area
306
+ * @param {number} height - Height of the crop area
307
+ * @returns {Container} The created crop UI container
308
+ */
309
+ private make_crop_ui(width: number, height: number): Container {
310
+ const crop_container = new Container();
311
+ crop_container.eventMode = "static";
312
+ crop_container.interactiveChildren = true;
313
+
314
+ // Create crop outline with hit area for dragging
315
+ const crop_outline = new Graphics()
316
+ .rect(0, 0, width, height)
317
+ .stroke({ width: 1, color: 0x000000, alignment: 0, alpha: 0.5 });
318
+
319
+ // Make the outline interactive
320
+ crop_outline.eventMode = "static";
321
+ crop_outline.cursor = "move";
322
+
323
+ // Set hit area to match the outline's dimensions
324
+ crop_outline.hitArea = new Rectangle(0, 0, width, height);
325
+
326
+ // Add drag handlers to the outline
327
+ crop_outline.on("pointerdown", this.handle_window_drag_start.bind(this));
328
+
329
+ crop_container.addChild(crop_outline);
330
+
331
+ // Create corner handles
332
+ this.create_corner_handles(crop_container, width, height);
333
+
334
+ // Create edge handles
335
+ this.create_edge_handles(crop_container, width, height);
336
+
337
+ return crop_container;
338
+ }
339
+
340
+ /**
341
+ * @method create_handle
342
+ * @private
343
+ * @description Creates a handle for the crop UI
344
+ * @param {boolean} [is_edge=false] - Whether the handle is an edge handle
345
+ * @returns {Container} The created handle container
346
+ */
347
+ private create_handle(is_edge = false): Container {
348
+ const handle = new Container();
349
+ handle.eventMode = "static";
350
+
351
+ const handle_graphics = new Graphics();
352
+
353
+ if (is_edge) {
354
+ // Create a shorter bar for edge handles (2x instead of 3x)
355
+ handle_graphics
356
+ .rect(0, 0, this.CORNER_SIZE * 1.5, this.LINE_THICKNESS)
357
+ .fill(this.HANDLE_COLOR);
358
+ } else {
359
+ // Create L-shaped corner handles
360
+ handle_graphics
361
+ .rect(0, 0, this.CORNER_SIZE, this.LINE_THICKNESS)
362
+ .rect(0, 0, this.LINE_THICKNESS, this.CORNER_SIZE)
363
+ .fill(this.HANDLE_COLOR);
364
+ }
365
+
366
+ handle.addChild(handle_graphics);
367
+
368
+ // Adjust hit area based on handle type
369
+ const hit_size = is_edge ? this.HIT_AREA_SIZE * 1.5 : this.HIT_AREA_SIZE;
370
+ handle.hitArea = new Rectangle(
371
+ -hit_size / 2 + this.LINE_THICKNESS,
372
+ -hit_size / 2 + this.LINE_THICKNESS,
373
+ hit_size,
374
+ hit_size
375
+ );
376
+
377
+ return handle;
378
+ }
379
+
380
+ /**
381
+ * @method create_edge_handles
382
+ * @private
383
+ * @description Creates edge handles for the crop UI
384
+ * @param {Container} container - The container to add handles to
385
+ * @param {number} width - Width of the crop area
386
+ * @param {number} height - Height of the crop area
387
+ * @returns {void}
388
+ */
389
+ private create_edge_handles(
390
+ container: Container,
391
+ width: number,
392
+ height: number
393
+ ): void {
394
+ // Horizontal handles at top and bottom
395
+ [-1, 1].forEach((i, index) => {
396
+ const handle = this.create_handle(true); // true for edge handle
397
+ handle.rotation = 0;
398
+
399
+ handle.on("pointerdown", (event: FederatedPointerEvent) => {
400
+ this.handle_pointer_down(event, handle, -1, index); // 0 for top, 1 for bottom
401
+ });
402
+
403
+ // Center the handle
404
+ handle.x = width / 2 - (this.CORNER_SIZE * 3) / 2;
405
+ handle.y = i < 0 ? -this.LINE_THICKNESS : height;
406
+ handle.cursor = "ns-resize";
407
+
408
+ container.addChild(handle);
409
+ });
410
+
411
+ // Vertical handles at left and right
412
+ [-1, 1].forEach((i, index) => {
413
+ const handle = this.create_handle(true); // true for edge handle
414
+ handle.rotation = Math.PI / 2; // Rotate 90 degrees
415
+
416
+ handle.on("pointerdown", (event: FederatedPointerEvent) => {
417
+ this.handle_pointer_down(event, handle, -1, index + 2); // 2 for left, 3 for right
418
+ });
419
+
420
+ // Center the handle
421
+ handle.x = i < 0 ? -this.LINE_THICKNESS : width;
422
+ handle.y = height / 2 - (this.CORNER_SIZE * 3) / 2;
423
+ handle.cursor = "ew-resize";
424
+
425
+ container.addChild(handle);
426
+ });
427
+ }
428
+
429
+ /**
430
+ * @method create_corner_handles
431
+ * @private
432
+ * @description Creates corner handles for the crop UI
433
+ * @param {Container} container - The container to add handles to
434
+ * @param {number} width - Width of the crop area
435
+ * @param {number} height - Height of the crop area
436
+ * @returns {void}
437
+ */
438
+ private create_corner_handles(
439
+ container: Container,
440
+ width: number,
441
+ height: number
442
+ ): void {
443
+ const corners = [
444
+ { x: 0, y: 0, xScale: 1, yScale: 1, cursor: "nwse-resize" }, // Top-left
445
+ { x: width, y: 0, xScale: -1, yScale: 1, cursor: "nesw-resize" }, // Top-right
446
+ { x: 0, y: height, xScale: 1, yScale: -1, cursor: "nesw-resize" }, // Bottom-left
447
+ { x: width, y: height, xScale: -1, yScale: -1, cursor: "nwse-resize" } // Bottom-right
448
+ ];
449
+
450
+ corners.forEach(({ x, y, xScale, yScale, cursor }, i) => {
451
+ const corner = this.create_handle(false); // false for corner handle
452
+ corner.x = x - (xScale < 0 ? -this.LINE_THICKNESS : this.LINE_THICKNESS);
453
+ corner.y = y - (yScale < 0 ? -this.LINE_THICKNESS : this.LINE_THICKNESS);
454
+ corner.scale.set(xScale, yScale);
455
+
456
+ corner.on("pointerdown", (event: FederatedPointerEvent) => {
457
+ this.handle_pointer_down(event, corner, i, -1);
458
+ });
459
+
460
+ corner.cursor = cursor;
461
+
462
+ container.addChild(corner);
463
+ });
464
+ }
465
+
466
+ /**
467
+ * @method handle_pointer_down
468
+ * @private
469
+ * @description Handles pointer down events on handles
470
+ * @param {FederatedPointerEvent} event - The pointer event
471
+ * @param {Container} handle - The handle that was clicked
472
+ * @param {number} corner_index - Index of the corner (-1 if not a corner)
473
+ * @param {number} edge_index - Index of the edge (-1 if not an edge)
474
+ * @returns {void}
475
+ */
476
+ private handle_pointer_down(
477
+ event: FederatedPointerEvent,
478
+ handle: Container,
479
+ corner_index: number,
480
+ edge_index: number
481
+ ): void {
482
+ // Only handle crop events if crop tool is active
483
+ if (this.current_subtool !== "crop") return;
484
+
485
+ event.stopPropagation();
486
+
487
+ this.is_dragging = true;
488
+ this.selected_handle = handle;
489
+ this.active_corner_index = corner_index;
490
+ this.active_edge_index = edge_index;
491
+
492
+ // Convert global position to the container's local coordinates.
493
+ const local_pos = this.image_editor_context.image_container.toLocal(
494
+ event.global
495
+ );
496
+
497
+ this.last_pointer_position = new Point(local_pos.x, local_pos.y);
498
+ }
499
+
500
+ /**
501
+ * updates the crop bounds based on pointer movement
502
+ * @param delta - the change in position
503
+ */
504
+ private update_crop_bounds(delta: Point): void {
505
+ // Set flag indicating the crop has been manually changed
506
+ this.has_been_manually_changed = true;
507
+
508
+ // Scale the delta to match the image coordinates
509
+ const scaled_delta = new Point(delta.x, delta.y);
510
+
511
+ // Store original values to calculate actual changes
512
+ const original = {
513
+ x: this.crop_bounds.x,
514
+ y: this.crop_bounds.y,
515
+ width: this.crop_bounds.width,
516
+ height: this.crop_bounds.height
517
+ };
518
+
519
+ if (this.active_corner_index !== -1) {
520
+ // Handle corner dragging
521
+ switch (this.active_corner_index) {
522
+ case 0: // Top-left
523
+ // Update width and x position
524
+ const newWidth0 = Math.max(20, original.width - scaled_delta.x);
525
+ const widthDiff0 = original.width - newWidth0;
526
+ this.crop_bounds.width = newWidth0;
527
+ this.crop_bounds.x = original.x + widthDiff0;
528
+
529
+ // Update height and y position
530
+ const newHeight0 = Math.max(20, original.height - scaled_delta.y);
531
+ const heightDiff0 = original.height - newHeight0;
532
+ this.crop_bounds.height = newHeight0;
533
+ this.crop_bounds.y = original.y + heightDiff0;
534
+ break;
535
+
536
+ case 1: // Top-right
537
+ // Update width (right side)
538
+ this.crop_bounds.width = Math.max(
539
+ 20,
540
+ original.width + scaled_delta.x
541
+ );
542
+
543
+ // Update height and y position (top side)
544
+ const newHeight1 = Math.max(20, original.height - scaled_delta.y);
545
+ const heightDiff1 = original.height - newHeight1;
546
+ this.crop_bounds.height = newHeight1;
547
+ this.crop_bounds.y = original.y + heightDiff1;
548
+ break;
549
+
550
+ case 2: // Bottom-left
551
+ // Update width and x position (left side)
552
+ const newWidth2 = Math.max(20, original.width - scaled_delta.x);
553
+ const widthDiff2 = original.width - newWidth2;
554
+ this.crop_bounds.width = newWidth2;
555
+ this.crop_bounds.x = original.x + widthDiff2;
556
+
557
+ // Update height (bottom side)
558
+ this.crop_bounds.height = Math.max(
559
+ 20,
560
+ original.height + scaled_delta.y
561
+ );
562
+ break;
563
+
564
+ case 3: // Bottom-right
565
+ // Update width (right side)
566
+ this.crop_bounds.width = Math.max(
567
+ 20,
568
+ original.width + scaled_delta.x
569
+ );
570
+
571
+ // Update height (bottom side)
572
+ this.crop_bounds.height = Math.max(
573
+ 20,
574
+ original.height + scaled_delta.y
575
+ );
576
+ break;
577
+ }
578
+ } else if (this.active_edge_index !== -1) {
579
+ // Handle edge dragging
580
+ switch (this.active_edge_index) {
581
+ case 0: // Top
582
+ // Update height and y position
583
+ const newHeight = Math.max(20, original.height - scaled_delta.y);
584
+ const heightDiff = original.height - newHeight;
585
+ this.crop_bounds.height = newHeight;
586
+ this.crop_bounds.y = original.y + heightDiff;
587
+ break;
588
+
589
+ case 1: // Bottom
590
+ // Update height only
591
+ this.crop_bounds.height = Math.max(
592
+ 20,
593
+ original.height + scaled_delta.y
594
+ );
595
+ break;
596
+
597
+ case 2: // Left
598
+ // Update width and x position
599
+ const newWidth = Math.max(20, original.width - scaled_delta.x);
600
+ const widthDiff = original.width - newWidth;
601
+ this.crop_bounds.width = newWidth;
602
+ this.crop_bounds.x = original.x + widthDiff;
603
+ break;
604
+
605
+ case 3: // Right
606
+ // Update width only
607
+ this.crop_bounds.width = Math.max(
608
+ 20,
609
+ original.width + scaled_delta.x
610
+ );
611
+ break;
612
+ }
613
+ }
614
+
615
+ // Apply constraints
616
+ this.constrain_crop_bounds();
617
+
618
+ // Update the UI and mask
619
+ this.update_crop_ui();
620
+ this.update_crop_mask();
621
+
622
+ // Make sure to apply mask to the current background image
623
+ if (this.crop_mask && this.image_editor_context.background_image) {
624
+ this.image_editor_context.background_image.setMask(this.crop_mask);
625
+ }
626
+ }
627
+
628
+ /**
629
+ * constrains the crop bounds to the image dimensions
630
+ */
631
+ private constrain_crop_bounds(): void {
632
+ // Store original values
633
+ const original = {
634
+ x: this.crop_bounds.x,
635
+ y: this.crop_bounds.y,
636
+ width: this.crop_bounds.width,
637
+ height: this.crop_bounds.height
638
+ };
639
+
640
+ // First, constrain width and height to prevent exceeding image dimensions
641
+ // and ensure minimum size
642
+ this.crop_bounds.width = Math.max(
643
+ 20,
644
+ Math.min(this.crop_bounds.width, this.dimensions.width)
645
+ );
646
+
647
+ this.crop_bounds.height = Math.max(
648
+ 20,
649
+ Math.min(this.crop_bounds.height, this.dimensions.height)
650
+ );
651
+
652
+ // Then constrain x and y to keep the crop window within the image bounds
653
+ const oldX = this.crop_bounds.x;
654
+ this.crop_bounds.x = Math.max(
655
+ 0,
656
+ Math.min(
657
+ this.crop_bounds.x,
658
+ this.dimensions.width - this.crop_bounds.width
659
+ )
660
+ );
661
+
662
+ // If x position was constrained, adjust width to prevent opposite handle drift
663
+ if (
664
+ (this.crop_bounds.x !== oldX && this.active_corner_index === 0) ||
665
+ this.active_edge_index === 2
666
+ ) {
667
+ // Left side was constrained, adjust width to compensate
668
+ const xDiff = this.crop_bounds.x - oldX;
669
+ this.crop_bounds.width -= xDiff;
670
+ }
671
+
672
+ const oldY = this.crop_bounds.y;
673
+ this.crop_bounds.y = Math.max(
674
+ 0,
675
+ Math.min(
676
+ this.crop_bounds.y,
677
+ this.dimensions.height - this.crop_bounds.height
678
+ )
679
+ );
680
+
681
+ // If y position was constrained, adjust height to prevent opposite handle drift
682
+ if (
683
+ this.crop_bounds.y !== oldY &&
684
+ (this.active_corner_index === 0 ||
685
+ this.active_corner_index === 1 ||
686
+ this.active_edge_index === 0)
687
+ ) {
688
+ // Top side was constrained, adjust height to compensate
689
+ const yDiff = this.crop_bounds.y - oldY;
690
+ this.crop_bounds.height -= yDiff;
691
+ }
692
+
693
+ // Final check to ensure width and height don't exceed image dimensions from current position
694
+ this.crop_bounds.width = Math.max(
695
+ 20,
696
+ Math.min(
697
+ this.crop_bounds.width,
698
+ this.dimensions.width - this.crop_bounds.x
699
+ )
700
+ );
701
+
702
+ this.crop_bounds.height = Math.max(
703
+ 20,
704
+ Math.min(
705
+ this.crop_bounds.height,
706
+ this.dimensions.height - this.crop_bounds.y
707
+ )
708
+ );
709
+ }
710
+
711
+ /**
712
+ * updates the crop mask graphics
713
+ */
714
+ private update_crop_mask(): void {
715
+ if (!this.crop_mask) return;
716
+
717
+ // Clear the previous mask shape
718
+ this.crop_mask.clear();
719
+
720
+ const { width, height } =
721
+ this.image_editor_context.background_image?.getLocalBounds() ?? {
722
+ width: 0,
723
+ height: 0
724
+ };
725
+ this.crop_mask
726
+ .rect(0, 0, width, height)
727
+ .fill({ color: 0x000000, alpha: 0.4 })
728
+ .rect(
729
+ this.crop_bounds.x,
730
+ this.crop_bounds.y,
731
+ this.crop_bounds.width,
732
+ this.crop_bounds.height
733
+ )
734
+ .cut();
735
+
736
+ // Reset blend mode
737
+ // this.crop_mask.blendMode = "normal";
738
+
739
+ // Make the mask visible (previously we had alpha=0)
740
+ // this.crop_mask.alpha = 1;
741
+
742
+ // Since we're not using this as a mask anymore, but as an overlay,
743
+ // we should remove any existing mask assignment
744
+ if (this.image_editor_context.background_image) {
745
+ this.image_editor_context.background_image.mask = null;
746
+ }
747
+
748
+ // Make sure the mask is not applied to the image container
749
+ if (this.image_editor_context.image_container.mask === this.crop_mask) {
750
+ this.image_editor_context.image_container.mask = null;
751
+ }
752
+ }
753
+
754
+ /**
755
+ * updates the crop ui position and dimensions
756
+ */
757
+ private update_crop_ui(): void {
758
+ if (!this.crop_mask || !this.crop_ui_container) return;
759
+
760
+ // Move crop_ui_container so that (0,0) of its local space aligns with the crop_bounds on the stage
761
+ this.crop_ui_container.position.set(
762
+ this.position.x + this.crop_bounds.x * this.scale,
763
+ this.position.y + this.crop_bounds.y * this.scale
764
+ );
765
+
766
+ // Get the scaled dimensions
767
+ const scaled_width = this.crop_bounds.width * this.scale;
768
+ const scaled_height = this.crop_bounds.height * this.scale;
769
+
770
+ // Redraw the outline so it matches the crop_bounds size
771
+ const outline = this.crop_ui_container.getChildAt(0) as Graphics;
772
+ outline
773
+ .clear()
774
+ .rect(0, 0, scaled_width, scaled_height)
775
+ .stroke({ width: 1, color: 0x000000, alignment: 0, alpha: 0.5 });
776
+
777
+ // Update the hit area to match the new dimensions
778
+ outline.hitArea = new Rectangle(0, 0, scaled_width, scaled_height);
779
+
780
+ // Update handle positions to reflect the cropped area, not the full image
781
+ this.update_handle_positions(scaled_width, scaled_height);
782
+ }
783
+
784
+ /**
785
+ * updates the positions of all handles
786
+ * @param width - width of the crop area
787
+ * @param height - height of the crop area
788
+ */
789
+ private update_handle_positions(width: number, height: number): void {
790
+ if (!this.crop_ui_container) return;
791
+
792
+ // Skip the outline (index 0), get corner/edge handles
793
+ const handles = this.crop_ui_container.children.slice(1);
794
+
795
+ // First 4 are corners
796
+ const corners = handles.slice(0, 4);
797
+ const cornerPositions = [
798
+ { x: 0, y: 0 }, // Top-left
799
+ { x: width, y: 0 }, // Top-right
800
+ { x: 0, y: height }, // Bottom-left
801
+ { x: width, y: height } // Bottom-right
802
+ ];
803
+
804
+ corners.forEach((handle, i) => {
805
+ const xScale = i % 2 === 0 ? 1 : -1;
806
+ const yScale = i < 2 ? 1 : -1;
807
+ handle.position.set(
808
+ cornerPositions[i].x -
809
+ (xScale < 0 ? -this.LINE_THICKNESS : this.LINE_THICKNESS),
810
+ cornerPositions[i].y -
811
+ (yScale < 0 ? -this.LINE_THICKNESS : this.LINE_THICKNESS)
812
+ );
813
+ });
814
+
815
+ // Remaining 4 are edges
816
+ const edges = handles.slice(4);
817
+ edges.forEach((handle, i) => {
818
+ if (i < 2) {
819
+ // Top/Bottom edges
820
+ handle.position.set(
821
+ width / 2 - (this.CORNER_SIZE * 1.5) / 2, // Changed from 3 to 2
822
+ i === 0 ? -this.LINE_THICKNESS : height
823
+ );
824
+ } else {
825
+ // Left/Right edges
826
+ handle.position.set(
827
+ i === 2 ? 0 : width + this.LINE_THICKNESS,
828
+ height / 2 - (this.CORNER_SIZE * 1.5) / 2 // Changed from 3 to 2
829
+ );
830
+ }
831
+ });
832
+ }
833
+
834
+ /**
835
+ * sets up event listeners for the crop tool
836
+ */
837
+ private setup_event_listeners(): void {
838
+ const stage = this.image_editor_context.app.stage;
839
+ stage.eventMode = "static";
840
+ stage.on("pointermove", this.handle_pointer_move.bind(this));
841
+ stage.on("pointerup", this.handle_pointer_up.bind(this));
842
+ stage.on("pointerupoutside", this.handle_pointer_up.bind(this));
843
+ }
844
+
845
+ /**
846
+ * removes event listeners for the crop tool
847
+ */
848
+ private cleanup_event_listeners(): void {
849
+ const stage = this.image_editor_context.app.stage;
850
+
851
+ stage.off("pointermove", this.handle_pointer_move.bind(this));
852
+ stage.off("pointerup", this.handle_pointer_up.bind(this));
853
+ stage.off("pointerupoutside", this.handle_pointer_up.bind(this));
854
+ }
855
+
856
+ /**
857
+ * handles pointer move events
858
+ * @param event - the pointer event
859
+ */
860
+ private handle_pointer_move(event: FederatedPointerEvent): void {
861
+ if (this.current_subtool !== "crop") return;
862
+
863
+ if (
864
+ this.is_dragging_window &&
865
+ this.drag_start_position &&
866
+ this.drag_start_bounds
867
+ ) {
868
+ // Handle window dragging
869
+ const local_pos = this.image_editor_context.image_container.toLocal(
870
+ event.global
871
+ );
872
+ const delta = new Point(
873
+ local_pos.x - this.drag_start_position.x,
874
+ local_pos.y - this.drag_start_position.y
875
+ );
876
+
877
+ // Update crop bounds based on drag
878
+ this.crop_bounds = {
879
+ x: this.drag_start_bounds.x + delta.x,
880
+ y: this.drag_start_bounds.y + delta.y,
881
+ width: this.drag_start_bounds.width,
882
+ height: this.drag_start_bounds.height
883
+ };
884
+
885
+ // Constrain the bounds
886
+ this.constrain_crop_bounds();
887
+
888
+ // Update the mask
889
+ this.update_crop_mask();
890
+
891
+ // Make sure to apply mask to the current background image
892
+ if (this.crop_mask && this.image_editor_context.background_image) {
893
+ this.image_editor_context.background_image.setMask(this.crop_mask);
894
+ }
895
+
896
+ return;
897
+ }
898
+
899
+ // Handle existing resize logic
900
+ if (
901
+ this.is_dragging &&
902
+ this.selected_handle &&
903
+ this.last_pointer_position
904
+ ) {
905
+ // Convert from global to local, no extra divide
906
+ const local_pos = this.image_editor_context.image_container.toLocal(
907
+ event.global
908
+ );
909
+ const current_position = new Point(local_pos.x, local_pos.y);
910
+
911
+ const delta = new Point(
912
+ current_position.x - this.last_pointer_position.x,
913
+ current_position.y - this.last_pointer_position.y
914
+ );
915
+
916
+ this.update_crop_bounds(delta);
917
+ this.last_pointer_position = current_position;
918
+ this.update_crop_mask();
919
+ }
920
+ }
921
+
922
+ /**
923
+ * handles pointer up events
924
+ */
925
+ private handle_pointer_up(): void {
926
+ if (this.current_subtool !== "crop") return;
927
+
928
+ this.is_dragging = false;
929
+ this.is_dragging_window = false;
930
+ this.selected_handle = null;
931
+ this.last_pointer_position = null;
932
+ this.drag_start_position = null;
933
+ this.drag_start_bounds = null;
934
+ this.active_corner_index = -1;
935
+ this.active_edge_index = -1;
936
+
937
+ this.notify("change");
938
+ }
939
+
940
+ /**
941
+ * handles the start of window dragging
942
+ * @param event - the pointer event
943
+ */
944
+ private handle_window_drag_start(event: FederatedPointerEvent): void {
945
+ if (this.current_subtool !== "crop") return;
946
+ event.stopPropagation();
947
+
948
+ this.is_dragging_window = true;
949
+ // Set flag indicating the crop has been manually changed
950
+ this.has_been_manually_changed = true;
951
+
952
+ // Store the initial position and bounds
953
+ const local_pos = this.image_editor_context.image_container.toLocal(
954
+ event.global
955
+ );
956
+ this.drag_start_position = new Point(local_pos.x, local_pos.y);
957
+ this.drag_start_bounds = { ...this.crop_bounds };
958
+ }
959
+
960
+ /**
961
+ * @returns whether the crop has been manually changed by the user
962
+ */
963
+ public get crop_manually_changed(): boolean {
964
+ return this.has_been_manually_changed;
965
+ }
966
+
967
+ on<T extends string>(event: T, callback: () => void): void {
968
+ this.event_callbacks.set(event, [
969
+ ...(this.event_callbacks.get(event) || []),
970
+ callback
971
+ ]);
972
+ }
973
+
974
+ off<T extends string>(event: T, callback: () => void): void {
975
+ this.event_callbacks.set(
976
+ event,
977
+ this.event_callbacks.get(event)?.filter((cb) => cb !== callback) || []
978
+ );
979
+ }
980
+
981
+ private notify<T extends string>(event: T): void {
982
+ for (const callback of this.event_callbacks.get(event) || []) {
983
+ callback();
984
+ }
985
+ }
986
+
987
+ public get_crop_bounds(): {
988
+ x: number;
989
+ y: number;
990
+ crop_dimensions: { width: number; height: number };
991
+ image_dimensions: { width: number; height: number };
992
+ } {
993
+ const { width, height } =
994
+ this.image_editor_context.background_image?.getLocalBounds() ?? {
995
+ width: 0,
996
+ height: 0
997
+ };
998
+ return {
999
+ x: this.crop_bounds.x,
1000
+ y: this.crop_bounds.y,
1001
+ crop_dimensions: {
1002
+ width: this.crop_bounds.width,
1003
+ height: this.crop_bounds.height
1004
+ },
1005
+ image_dimensions: {
1006
+ width,
1007
+ height
1008
+ }
1009
+ };
1010
+ }
1011
+
1012
+ public get_image(): Promise<Blob | null> {
1013
+ if (!this.image_editor_context.background_image)
1014
+ return Promise.resolve(null);
1015
+ const container = new Container();
1016
+ const sprite = new Sprite(
1017
+ this.image_editor_context.background_image.texture
1018
+ );
1019
+ container.addChild(sprite);
1020
+
1021
+ return get_canvas_blob(
1022
+ this.image_editor_context.app.renderer,
1023
+ container,
1024
+ this.crop_bounds
1025
+ );
1026
+ }
1027
+ }
6.26.1/imageeditor/shared/image/image.ts ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Container,
3
+ Graphics,
4
+ Color,
5
+ type ColorSource,
6
+ RenderTexture,
7
+ Sprite,
8
+ type Renderer,
9
+ Texture
10
+ } from "pixi.js";
11
+ import { type ImageEditorContext, type Tool } from "../core/editor";
12
+ import { type Tool as ToolbarTool, type Subtool } from "../Toolbar.svelte";
13
+ import { type Command } from "../core/commands";
14
+ import { make_graphics } from "../utils/pixi";
15
+ import { get } from "svelte/store";
16
+
17
+ /**
18
+ * Handles adding images to the editor
19
+ * Only a single image can be added at a time
20
+ * Adding an image removes the current image is one exists
21
+ */
22
+ export class ImageTool implements Tool {
23
+ name = "image";
24
+ context!: ImageEditorContext;
25
+ current_tool!: ToolbarTool;
26
+ current_subtool!: Subtool;
27
+ async setup(
28
+ context: ImageEditorContext,
29
+ tool: ToolbarTool,
30
+ subtool: Subtool
31
+ ): Promise<void> {
32
+ this.context = context;
33
+ this.current_tool = tool;
34
+ this.current_subtool = subtool;
35
+ }
36
+
37
+ cleanup(): void {}
38
+
39
+ async add_image({
40
+ image,
41
+ fixed_canvas,
42
+ border_region = 0
43
+ }: {
44
+ image: Blob | File | Texture;
45
+ fixed_canvas: boolean;
46
+ border_region?: number;
47
+ }): Promise<void> {
48
+ const image_command = new AddImageCommand(
49
+ this.context,
50
+ image,
51
+ fixed_canvas,
52
+ border_region
53
+ );
54
+
55
+ await this.context.execute_command(image_command);
56
+ }
57
+
58
+ set_tool(tool: ToolbarTool, subtool: Subtool): void {
59
+ this.current_tool = tool;
60
+ this.current_subtool = subtool;
61
+ }
62
+ }
63
+
64
+ interface BgImageCommand extends Command {
65
+ /**
66
+ * Initial setup for the bg command
67
+ * @returns
68
+ */
69
+ start: () => Promise<void>;
70
+ }
71
+
72
+ export class AddImageCommand implements BgImageCommand {
73
+ sprite: Sprite | null = null;
74
+ fixed_canvas: boolean;
75
+ context: ImageEditorContext;
76
+ background: Blob | File | Texture;
77
+ current_canvas_size: { width: number; height: number };
78
+ computed_dimensions: { width: number; height: number };
79
+ current_scale: number;
80
+ current_position: { x: number; y: number };
81
+ border_region: number;
82
+
83
+ scaled_width!: number;
84
+ scaled_height!: number;
85
+
86
+ private previous_image: {
87
+ texture: Texture;
88
+ width: number;
89
+ height: number;
90
+ x: number;
91
+ y: number;
92
+ border_region: number;
93
+ } | null = null;
94
+ name: string;
95
+
96
+ constructor(
97
+ context: ImageEditorContext,
98
+ background: Blob | File | Texture,
99
+ fixed_canvas: boolean,
100
+ border_region = 0
101
+ ) {
102
+ this.name = "AddImage";
103
+ this.context = context;
104
+ this.background = background;
105
+ this.fixed_canvas = fixed_canvas;
106
+ this.border_region = border_region;
107
+ this.current_canvas_size = get(this.context.dimensions);
108
+ this.current_scale = get(this.context.scale);
109
+ this.current_position = get(this.context.position);
110
+
111
+ this.computed_dimensions = { width: 0, height: 0 };
112
+
113
+ if (
114
+ this.context.background_image &&
115
+ this.context.background_image.texture
116
+ ) {
117
+ const bg = this.context.background_image;
118
+ const stored_border_region = (bg as any).borderRegion || 0;
119
+
120
+ this.previous_image = {
121
+ texture: this.clone_texture(bg.texture),
122
+ width: bg.width,
123
+ height: bg.height,
124
+ x: bg.position.x,
125
+ y: bg.position.y,
126
+ border_region: stored_border_region
127
+ };
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Creates a copy of a texture to avoid reference issues
133
+ */
134
+ private clone_texture(texture: Texture): Texture {
135
+ const render_texture = RenderTexture.create({
136
+ width: texture.width,
137
+ height: texture.height,
138
+ resolution: window.devicePixelRatio || 1
139
+ });
140
+
141
+ const sprite = new Sprite(texture);
142
+ const container = new Container();
143
+ container.addChild(sprite);
144
+
145
+ this.context.app.renderer.render(container, {
146
+ renderTexture: render_texture
147
+ });
148
+
149
+ container.destroy({ children: true });
150
+ return render_texture;
151
+ }
152
+
153
+ async start(): Promise<void> {
154
+ let image_texture: Texture;
155
+ if (this.background instanceof Texture) {
156
+ image_texture = this.background;
157
+ } else {
158
+ const img = await createImageBitmap(this.background);
159
+ image_texture = Texture.from(img);
160
+ }
161
+
162
+ this.sprite = new Sprite(image_texture);
163
+
164
+ const [width, height] = this.handle_image();
165
+ this.computed_dimensions = { width, height };
166
+ }
167
+
168
+ private handle_image(): [number, number] {
169
+ if (this.sprite === null) {
170
+ return [0, 0];
171
+ }
172
+ if (this.fixed_canvas) {
173
+ const effectiveCanvasWidth = Math.max(
174
+ this.current_canvas_size.width - this.border_region * 2,
175
+ 10
176
+ );
177
+ const effectiveCanvasHeight = Math.max(
178
+ this.current_canvas_size.height - this.border_region * 2,
179
+ 10
180
+ );
181
+
182
+ const { width, height, x, y } = fit_image_to_canvas(
183
+ this.sprite.width,
184
+ this.sprite.height,
185
+ effectiveCanvasWidth,
186
+ effectiveCanvasHeight
187
+ );
188
+
189
+ this.sprite.width = width;
190
+ this.sprite.height = height;
191
+
192
+ this.sprite.x = x + this.border_region;
193
+ this.sprite.y = y + this.border_region;
194
+ } else {
195
+ const width = this.sprite.width;
196
+ const height = this.sprite.height;
197
+
198
+ this.sprite.x = this.border_region;
199
+ this.sprite.y = this.border_region;
200
+
201
+ return [width + this.border_region * 2, height + this.border_region * 2];
202
+ }
203
+
204
+ return [this.current_canvas_size.width, this.current_canvas_size.height];
205
+ }
206
+
207
+ async execute(context?: ImageEditorContext): Promise<void> {
208
+ if (context) {
209
+ this.context = context;
210
+ }
211
+
212
+ await this.start();
213
+
214
+ if (this.sprite === null) {
215
+ return;
216
+ }
217
+
218
+ const { width, height } = this.computed_dimensions;
219
+
220
+ await this.context.set_image_properties({
221
+ scale: 1,
222
+ position: {
223
+ x: this.context.app.screen.width / 2,
224
+ y: this.context.app.screen.height / 2
225
+ },
226
+ width: this.fixed_canvas ? this.current_canvas_size.width : width,
227
+ height: this.fixed_canvas ? this.current_canvas_size.height : height
228
+ });
229
+
230
+ const background_layer = this.context.layer_manager.create_background_layer(
231
+ this.fixed_canvas ? this.current_canvas_size.width : width,
232
+ this.fixed_canvas ? this.current_canvas_size.height : height
233
+ );
234
+ this.sprite.zIndex = 0;
235
+ background_layer.addChild(this.sprite);
236
+
237
+ this.context.layer_manager.reset_layers(
238
+ this.fixed_canvas ? this.current_canvas_size.width : width,
239
+ this.fixed_canvas ? this.current_canvas_size.height : height,
240
+ true
241
+ );
242
+
243
+ if (this.border_region > 0) {
244
+ (this.sprite as any).borderRegion = this.border_region;
245
+ }
246
+
247
+ this.context.set_background_image(this.sprite);
248
+
249
+ this.context.reset();
250
+ }
251
+
252
+ async undo(): Promise<void> {
253
+ if (this.sprite) {
254
+ this.sprite.destroy();
255
+
256
+ if (this.previous_image) {
257
+ const previous_sprite = new Sprite(this.previous_image.texture);
258
+ previous_sprite.width = this.previous_image.width;
259
+ previous_sprite.height = this.previous_image.height;
260
+ previous_sprite.position.set(
261
+ this.previous_image.x,
262
+ this.previous_image.y
263
+ );
264
+
265
+ if (this.previous_image.border_region > 0) {
266
+ (previous_sprite as any).borderRegion =
267
+ this.previous_image.border_region;
268
+ }
269
+
270
+ await this.context.set_image_properties({
271
+ scale: 1,
272
+ position: {
273
+ x: this.context.app.screen.width / 2,
274
+ y: this.context.app.screen.height / 2
275
+ },
276
+ width: this.previous_image.width,
277
+ height: this.previous_image.height
278
+ });
279
+
280
+ const background_layer =
281
+ this.context.layer_manager.create_background_layer(
282
+ this.previous_image.width,
283
+ this.previous_image.height
284
+ );
285
+
286
+ previous_sprite.zIndex = 0;
287
+ background_layer.addChild(previous_sprite);
288
+
289
+ this.context.layer_manager.reset_layers(
290
+ this.previous_image.width,
291
+ this.previous_image.height,
292
+ true
293
+ );
294
+
295
+ this.context.set_background_image(previous_sprite);
296
+ } else {
297
+ await this.context.set_image_properties({
298
+ scale: 1,
299
+ position: {
300
+ x: this.context.app.screen.width / 2,
301
+ y: this.context.app.screen.height / 2
302
+ },
303
+ width: this.current_canvas_size.width,
304
+ height: this.current_canvas_size.height
305
+ });
306
+
307
+ this.context.layer_manager.create_background_layer(
308
+ this.current_canvas_size.width,
309
+ this.current_canvas_size.height
310
+ );
311
+
312
+ this.context.layer_manager.reset_layers(
313
+ this.current_canvas_size.width,
314
+ this.current_canvas_size.height
315
+ );
316
+ }
317
+
318
+ this.context.reset();
319
+ }
320
+ }
321
+ }
322
+
323
+ /**
324
+ * Command that sets a background
325
+ */
326
+ interface BgColorCommand extends Command {
327
+ /**
328
+ * Initial setup for the bg command
329
+ * @returns
330
+ */
331
+ start: () => [number, number];
332
+ }
333
+
334
+ /**
335
+ * Adds a background color to the canvas.
336
+ * @param container The container to add the image to.
337
+ * @param renderer The renderer to use for the image.
338
+ * @param color The background color to add.
339
+ * @param width The width of the background.
340
+ * @param height The height of the background.
341
+ * @param resize The function to resize the canvas.
342
+ * @returns A command that can be used to undo the action.
343
+ */
344
+ export function add_bg_color(
345
+ container: Container,
346
+ renderer: Renderer,
347
+ color: ColorSource,
348
+ width: number,
349
+ height: number,
350
+ resize: (width: number, height: number) => void
351
+ ): BgColorCommand {
352
+ let sprite: Sprite;
353
+ return {
354
+ name: "AddBgColor",
355
+ start() {
356
+ container.removeChildren();
357
+ const graphics = make_graphics(1);
358
+ const texture = RenderTexture.create({
359
+ width,
360
+ height
361
+ });
362
+
363
+ renderer.render(graphics, { renderTexture: texture });
364
+ sprite = new Sprite(texture);
365
+ return [sprite.width, sprite.height];
366
+ },
367
+ async execute() {
368
+ resize(sprite.width, sprite.height);
369
+ sprite.zIndex = 1;
370
+ container.addChild(sprite);
371
+ },
372
+ undo() {
373
+ container.removeChildren();
374
+ }
375
+ };
376
+ }
377
+
378
+ /**
379
+ * Calculates new dimensions and position for an image to fit within a canvas while maintaining aspect ratio
380
+ * @param image_width Original width of the image
381
+ * @param image_height Original height of the image
382
+ * @param canvas_width Width of the canvas
383
+ * @param canvas_height Height of the canvas
384
+ * @returns Object containing new dimensions and position
385
+ */
386
+ export function fit_image_to_canvas(
387
+ image_width: number,
388
+ image_height: number,
389
+ canvas_width: number,
390
+ canvas_height: number
391
+ ): {
392
+ width: number;
393
+ height: number;
394
+ x: number;
395
+ y: number;
396
+ } {
397
+ const image_aspect_ratio = image_width / image_height;
398
+ const canvas_aspect_ratio = canvas_width / canvas_height;
399
+
400
+ let new_width: number;
401
+ let new_height: number;
402
+
403
+ if (image_aspect_ratio > canvas_aspect_ratio) {
404
+ new_width = canvas_width;
405
+ new_height = canvas_width / image_aspect_ratio;
406
+ } else {
407
+ new_height = canvas_height;
408
+ new_width = canvas_height * image_aspect_ratio;
409
+ }
410
+
411
+ const x = Math.round((canvas_width - new_width) / 2);
412
+ const y = Math.round((canvas_height - new_height) / 2);
413
+
414
+ return {
415
+ width: Math.round(new_width),
416
+ height: Math.round(new_height),
417
+ x,
418
+ y
419
+ };
420
+ }
6.26.1/imageeditor/shared/resize/resize.ts ADDED
@@ -0,0 +1,1767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Container,
3
+ Graphics,
4
+ Point,
5
+ Rectangle,
6
+ FederatedPointerEvent,
7
+ type FederatedOptions
8
+ } from "pixi.js";
9
+ import { type ImageEditorContext, type Tool } from "../core/editor";
10
+ import { type Tool as ToolbarTool, type Subtool } from "../Toolbar.svelte";
11
+ import { type Command } from "../core/commands";
12
+
13
+ /**
14
+ * Command that handles resizing the image and supports undo/redo
15
+ */
16
+ export class ResizeCommand implements Command {
17
+ private original_width: number;
18
+ private original_height: number;
19
+ private original_x: number;
20
+ private original_y: number;
21
+
22
+ private new_width: number;
23
+ private new_height: number;
24
+ private new_x: number;
25
+ private new_y: number;
26
+ private reset_ui: () => void;
27
+ name: string;
28
+
29
+ constructor(
30
+ private context: ImageEditorContext,
31
+ original_state: { width: number; height: number; x: number; y: number },
32
+ new_state: { width: number; height: number; x: number; y: number },
33
+ reset_ui: () => void
34
+ ) {
35
+ this.name = "Resize";
36
+ this.original_width = original_state.width;
37
+ this.original_height = original_state.height;
38
+ this.original_x = original_state.x;
39
+ this.original_y = original_state.y;
40
+
41
+ this.new_width = new_state.width;
42
+ this.new_height = new_state.height;
43
+ this.new_x = new_state.x;
44
+ this.new_y = new_state.y;
45
+ this.reset_ui = reset_ui;
46
+ }
47
+
48
+ async execute(context?: ImageEditorContext): Promise<void> {
49
+ if (context) {
50
+ this.context = context;
51
+ }
52
+
53
+ if (!this.context.background_image) return;
54
+
55
+ this.context.background_image.width = this.new_width;
56
+ this.context.background_image.height = this.new_height;
57
+ this.context.background_image.position.set(this.new_x, this.new_y);
58
+
59
+ this.reset_ui();
60
+ }
61
+
62
+ async undo(): Promise<void> {
63
+ if (!this.context.background_image) return;
64
+
65
+ this.context.background_image.width = this.original_width;
66
+ this.context.background_image.height = this.original_height;
67
+ this.context.background_image.position.set(
68
+ this.original_x,
69
+ this.original_y
70
+ );
71
+
72
+ this.reset_ui();
73
+ }
74
+ }
75
+
76
+ /**
77
+ * @class ResizeTool
78
+ * @implements {Tool}
79
+ * @description Implements the resize tool functionality for the image editor
80
+ */
81
+ export class ResizeTool implements Tool {
82
+ name = "resize" as const;
83
+ private image_editor_context!: ImageEditorContext;
84
+ current_tool: ToolbarTool = "image";
85
+ current_subtool: Subtool = "size";
86
+ private current_cursor: FederatedOptions["cursor"] = "unset";
87
+ private readonly CORNER_SIZE = 25;
88
+ private readonly LINE_THICKNESS = 5;
89
+ private readonly HANDLE_COLOR = 0x000000;
90
+ private readonly HIT_AREA_SIZE = 40;
91
+ private borderRegion = 0;
92
+
93
+ private is_dragging = false;
94
+ private selected_handle: Container | null = null;
95
+ private active_corner_index = -1;
96
+ private active_edge_index = -1;
97
+ private last_pointer_position: Point | null = null;
98
+ private resize_ui_container: Container | null = null;
99
+ private dimensions: { width: number; height: number } = {
100
+ width: 0,
101
+ height: 0
102
+ };
103
+ private position: { x: number; y: number } = { x: 0, y: 0 };
104
+ private scale = 1;
105
+ private is_moving = false;
106
+ private dom_mousedown_handler: ((e: MouseEvent) => void) | null = null;
107
+ private dom_mousemove_handler: ((e: MouseEvent) => void) | null = null;
108
+ private dom_mouseup_handler: ((e: MouseEvent) => void) | null = null;
109
+ private event_callbacks: Map<string, (() => void)[]> = new Map();
110
+ private last_scale = 1;
111
+ private readonly handle_pointer_move_bound =
112
+ this.handle_pointer_move.bind(this);
113
+ private readonly handle_pointer_up_bound = this.handle_pointer_up.bind(this);
114
+
115
+ private original_state: {
116
+ width: number;
117
+ height: number;
118
+ x: number;
119
+ y: number;
120
+ } | null = null;
121
+
122
+ /**
123
+ * @method setup
124
+ * @async
125
+ * @description Sets up the resize tool with the given context and tool/subtool
126
+ * @param {ImageEditorContext} context - The image editor context
127
+ * @param {ToolbarTool} tool - The current tool
128
+ * @param {Subtool} subtool - The current subtool
129
+ * @returns {Promise<void>}
130
+ */
131
+ async setup(
132
+ context: ImageEditorContext,
133
+ tool: ToolbarTool,
134
+ subtool: Subtool
135
+ ): Promise<void> {
136
+ this.image_editor_context = context;
137
+ this.current_tool = tool;
138
+ this.current_subtool = subtool;
139
+
140
+ if (context.background_image) {
141
+ if ((context.background_image as any).borderRegion !== undefined) {
142
+ this.borderRegion = (context.background_image as any).borderRegion;
143
+ } else {
144
+ const bg = context.background_image;
145
+ const container = context.image_container;
146
+
147
+ const isHorizontallyCentered =
148
+ Math.abs(bg.position.x - (container.width - bg.width) / 2) < 2;
149
+ const isVerticallyCentered =
150
+ Math.abs(bg.position.y - (container.height - bg.height) / 2) < 2;
151
+
152
+ if (!isHorizontallyCentered || !isVerticallyCentered) {
153
+ this.borderRegion = Math.max(bg.position.x, bg.position.y);
154
+
155
+ (context.background_image as any).borderRegion = this.borderRegion;
156
+ }
157
+ }
158
+ }
159
+
160
+ context.dimensions.subscribe((dimensions) => {
161
+ this.dimensions = dimensions;
162
+ if (this.resize_ui_container) {
163
+ this.update_resize_ui();
164
+ }
165
+ });
166
+
167
+ context.position.subscribe((position) => {
168
+ this.position = position;
169
+ if (
170
+ this.resize_ui_container &&
171
+ this.current_tool === "image" &&
172
+ this.current_subtool === "size"
173
+ ) {
174
+ this.update_resize_ui();
175
+ }
176
+ });
177
+
178
+ context.scale.subscribe((scale) => {
179
+ this.scale = scale;
180
+ if (
181
+ this.resize_ui_container &&
182
+ this.current_tool === "image" &&
183
+ this.current_subtool === "size"
184
+ ) {
185
+ this.update_resize_ui();
186
+ }
187
+ });
188
+
189
+ await this.init_resize_ui();
190
+ this.setup_event_listeners();
191
+
192
+ if (
193
+ this.current_subtool === "size" &&
194
+ this.image_editor_context.background_image
195
+ ) {
196
+ const bg = this.image_editor_context.background_image;
197
+ const container = this.image_editor_context.image_container;
198
+
199
+ const bg_width = bg.width;
200
+ const bg_height = bg.height;
201
+ const container_bounds = container.getLocalBounds();
202
+ const container_width = container_bounds.width;
203
+ const container_height = container_bounds.height;
204
+
205
+ const min_x = -(bg_width - container_width);
206
+ const min_y = -(bg_height - container_height);
207
+ const max_x = 0;
208
+ const max_y = 0;
209
+
210
+ const x_out_of_bounds =
211
+ bg_width > container_width &&
212
+ (bg.position.x < min_x || bg.position.x > max_x);
213
+ const y_out_of_bounds =
214
+ bg_height > container_height &&
215
+ (bg.position.y < min_y || bg.position.y > max_y);
216
+
217
+ if (x_out_of_bounds || y_out_of_bounds) {
218
+ this.apply_boundary_constraints();
219
+ }
220
+ }
221
+ }
222
+
223
+ /**
224
+ * @method cleanup
225
+ * @description Cleans up the resize tool resources and removes event listeners
226
+ * @returns {void}
227
+ */
228
+ cleanup(): void {
229
+ if (this.resize_ui_container && this.image_editor_context?.app) {
230
+ this.image_editor_context.app.stage.removeChild(this.resize_ui_container);
231
+ }
232
+ this.cleanup_event_listeners();
233
+ }
234
+
235
+ /**
236
+ * @method set_tool
237
+ * @description Sets the current tool and subtool, updating UI visibility
238
+ * @param {ToolbarTool} tool - The tool to set
239
+ * @param {Subtool} subtool - The subtool to set
240
+ * @returns {void}
241
+ */
242
+ set_tool(tool: ToolbarTool, subtool: Subtool): void {
243
+ this.current_tool = tool;
244
+ this.current_subtool = subtool;
245
+
246
+ if (tool === "image" && subtool === "size") {
247
+ const context = this.image_editor_context;
248
+ if (!context) return;
249
+
250
+ if (context.background_image) {
251
+ const storedBorderRegion = (context.background_image as any)
252
+ .borderRegion;
253
+ if (typeof storedBorderRegion === "number" && storedBorderRegion > 0) {
254
+ this.borderRegion = storedBorderRegion;
255
+ }
256
+ }
257
+
258
+ this.show_resize_ui();
259
+
260
+ if (context.background_image) {
261
+ const bg = context.background_image;
262
+ const container = context.image_container;
263
+
264
+ const bg_width = bg.width;
265
+ const bg_height = bg.height;
266
+ const container_bounds = container.getLocalBounds();
267
+ const container_width = container_bounds.width;
268
+ const container_height = container_bounds.height;
269
+
270
+ const effectiveWidth = container_width - this.borderRegion * 2;
271
+ const effectiveHeight = container_height - this.borderRegion * 2;
272
+
273
+ const min_x =
274
+ bg_width > effectiveWidth
275
+ ? -(bg_width - effectiveWidth) + this.borderRegion
276
+ : this.borderRegion;
277
+ const max_x =
278
+ bg_width > effectiveWidth
279
+ ? this.borderRegion
280
+ : container_width - bg_width - this.borderRegion;
281
+
282
+ const min_y =
283
+ bg_height > effectiveHeight
284
+ ? -(bg_height - effectiveHeight) + this.borderRegion
285
+ : this.borderRegion;
286
+ const max_y =
287
+ bg_height > effectiveHeight
288
+ ? this.borderRegion
289
+ : container_height - bg_height - this.borderRegion;
290
+
291
+ const x_out_of_bounds = bg.position.x < min_x || bg.position.x > max_x;
292
+ const y_out_of_bounds = bg.position.y < min_y || bg.position.y > max_y;
293
+
294
+ if (x_out_of_bounds || y_out_of_bounds) {
295
+ this.apply_boundary_constraints();
296
+ }
297
+ }
298
+ } else {
299
+ this.hide_resize_ui();
300
+ }
301
+ }
302
+
303
+ /**
304
+ * @method init_resize_ui
305
+ * @private
306
+ * @async
307
+ * @description Initializes the resize UI elements and sets up the update loop
308
+ * @returns {Promise<void>}
309
+ */
310
+ private async init_resize_ui(): Promise<void> {
311
+ this.resize_ui_container = this.make_resize_ui(
312
+ this.dimensions.width * this.scale,
313
+ this.dimensions.height * this.scale
314
+ );
315
+
316
+ this.resize_ui_container.position.set(this.position.x, this.position.y);
317
+
318
+ this.resize_ui_container.visible = false;
319
+
320
+ this.image_editor_context.app.stage.addChild(this.resize_ui_container);
321
+ }
322
+
323
+ /**
324
+ * @method make_resize_ui
325
+ * @private
326
+ * @description Creates the resize UI with the specified dimensions
327
+ * @param {number} width - Width of the resize area
328
+ * @param {number} height - Height of the resize area
329
+ * @returns {Container} The created resize UI container
330
+ */
331
+ private make_resize_ui(width: number, height: number): Container {
332
+ const resize_container = new Container();
333
+ resize_container.eventMode = "static";
334
+ resize_container.interactiveChildren = true;
335
+
336
+ const outline = new Graphics().rect(0, 0, width, height).stroke({
337
+ width: 1,
338
+ color: 0x000000,
339
+ alignment: 0,
340
+ alpha: 0.3
341
+ });
342
+
343
+ const dotted_outline = new Graphics();
344
+
345
+ dotted_outline.rect(0, 0, width, height).stroke({
346
+ width: 1,
347
+ color: 0x000000,
348
+ alpha: 0.7,
349
+ pixelLine: true
350
+ });
351
+
352
+ const dash_length = 5;
353
+ const gap_length = 5;
354
+ const total_length = dash_length + gap_length;
355
+
356
+ for (let x = 0; x < width; x += total_length * 2) {
357
+ dotted_outline
358
+ .rect(x, 0, Math.min(dash_length, width - x), 1)
359
+ .fill(0x000000);
360
+
361
+ dotted_outline
362
+ .rect(x, height - 1, Math.min(dash_length, width - x), 1)
363
+ .fill(0x000000);
364
+ }
365
+
366
+ for (let y = 0; y < height; y += total_length * 2) {
367
+ dotted_outline
368
+ .rect(0, y, 1, Math.min(dash_length, height - y))
369
+ .fill(0x000000);
370
+
371
+ dotted_outline
372
+ .rect(width - 1, y, 1, Math.min(dash_length, height - y))
373
+ .fill(0x000000);
374
+ }
375
+
376
+ resize_container.addChild(outline);
377
+ resize_container.addChild(dotted_outline);
378
+
379
+ const move_area = new Graphics()
380
+ .rect(0, 0, width, height)
381
+ .fill(0xffffff, 0);
382
+ move_area.eventMode = "static";
383
+ move_area.cursor = "move";
384
+ resize_container.addChild(move_area);
385
+
386
+ this.create_corner_handles(resize_container, width, height);
387
+ this.create_edge_handles(resize_container, width, height);
388
+
389
+ return resize_container;
390
+ }
391
+
392
+ /**
393
+ * @method create_handle
394
+ * @private
395
+ * @description Creates a handle for the resize UI
396
+ * @param {boolean} [is_edge=false] - Whether the handle is an edge handle
397
+ * @returns {Container} The created handle container
398
+ */
399
+ private create_handle(is_edge = false): Container {
400
+ const handle = new Container();
401
+ handle.eventMode = "static";
402
+ handle.cursor = "pointer";
403
+
404
+ const handle_graphics = new Graphics();
405
+ const handle_size = is_edge ? 8 : 10;
406
+ handle_graphics
407
+ .rect(-handle_size / 2, -handle_size / 2, handle_size, handle_size)
408
+ .fill(0xffffff)
409
+ .stroke({ width: 1, color: this.HANDLE_COLOR });
410
+ handle.addChild(handle_graphics);
411
+
412
+ const hit_size = is_edge ? this.HIT_AREA_SIZE * 1.5 : this.HIT_AREA_SIZE;
413
+ handle.hitArea = new Rectangle(
414
+ -hit_size / 2,
415
+ -hit_size / 2,
416
+ hit_size,
417
+ hit_size
418
+ );
419
+
420
+ return handle;
421
+ }
422
+
423
+ /**
424
+ * @method create_edge_handles
425
+ * @private
426
+ * @description Creates edge handles for the resize UI
427
+ * @param {Container} container - The container to add handles to
428
+ * @param {number} width - Width of the resize area
429
+ * @param {number} height - Height of the resize area
430
+ * @returns {void}
431
+ */
432
+ private create_edge_handles(
433
+ container: Container,
434
+ width: number,
435
+ height: number
436
+ ): void {
437
+ [-1, 1].forEach((i, index) => {
438
+ const handle = this.create_handle(true);
439
+ handle.rotation = 0;
440
+
441
+ handle.on("pointerdown", (event: FederatedPointerEvent) => {
442
+ this.handle_pointer_down(event, handle, -1, index);
443
+ });
444
+
445
+ handle.x = width / 2;
446
+ handle.y = i < 0 ? 0 : height;
447
+ handle.cursor = "ns-resize";
448
+
449
+ container.addChild(handle);
450
+ });
451
+
452
+ [-1, 1].forEach((i, index) => {
453
+ const handle = this.create_handle(true);
454
+ handle.rotation = 0;
455
+ handle.on("pointerdown", (event: FederatedPointerEvent) => {
456
+ this.handle_pointer_down(event, handle, -1, index + 2);
457
+ });
458
+
459
+ handle.x = i < 0 ? 0 : width;
460
+ handle.y = height / 2;
461
+ handle.cursor = "ew-resize";
462
+ container.addChild(handle);
463
+ });
464
+ }
465
+
466
+ /**
467
+ * @method create_corner_handles
468
+ * @private
469
+ * @description Creates corner handles for the resize UI
470
+ * @param {Container} container - The container to add handles to
471
+ * @param {number} width - Width of the resize area
472
+ * @param {number} height - Height of the resize area
473
+ * @returns {void}
474
+ */
475
+ private create_corner_handles(
476
+ container: Container,
477
+ width: number,
478
+ height: number
479
+ ): void {
480
+ const corners = [
481
+ { x: 0, y: 0, cursor: "nwse-resize" },
482
+ { x: width, y: 0, cursor: "nesw-resize" },
483
+ { x: 0, y: height, cursor: "nesw-resize" },
484
+ { x: width, y: height, cursor: "nwse-resize" }
485
+ ];
486
+
487
+ corners.forEach(({ x, y, cursor }, i) => {
488
+ const corner = this.create_handle(false);
489
+ corner.x = x;
490
+ corner.y = y;
491
+
492
+ corner.on("pointerdown", (event: FederatedPointerEvent) => {
493
+ this.handle_pointer_down(event, corner, i, -1);
494
+ });
495
+
496
+ corner.cursor = cursor;
497
+
498
+ container.addChild(corner);
499
+ });
500
+ }
501
+
502
+ /**
503
+ * @method handle_pointer_down
504
+ * @private
505
+ * @description Handles pointer down events on handles
506
+ * @param {FederatedPointerEvent} event - The pointer event
507
+ * @param {Container} handle - The handle that was clicked
508
+ * @param {number} corner_index - Index of the corner (-1 if not a corner)
509
+ * @param {number} edge_index - Index of the edge (-1 if not an edge)
510
+ * @returns {void}
511
+ */
512
+ private handle_pointer_down(
513
+ event: FederatedPointerEvent,
514
+ handle: Container,
515
+ corner_index: number,
516
+ edge_index: number
517
+ ): void {
518
+ if (this.current_subtool !== "size") return;
519
+
520
+ event.stopPropagation();
521
+
522
+ this.is_dragging = true;
523
+ this.selected_handle = handle;
524
+ this.active_corner_index = corner_index;
525
+ this.active_edge_index = edge_index;
526
+
527
+ const local_pos = this.image_editor_context.image_container.toLocal(
528
+ event.global
529
+ );
530
+ this.last_pointer_position = new Point(local_pos.x, local_pos.y);
531
+
532
+ if (this.image_editor_context.background_image) {
533
+ const bg = this.image_editor_context.background_image;
534
+ this.original_state = {
535
+ width: bg.width,
536
+ height: bg.height,
537
+ x: bg.position.x,
538
+ y: bg.position.y
539
+ };
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Maintains aspect ratio during resizing
545
+ * @param new_width - The new width
546
+ * @param new_height - The new height
547
+ * @param original_aspect_ratio - The original aspect ratio
548
+ * @param delta - The delta to apply
549
+ * @returns The adjusted dimensions
550
+ */
551
+ private maintain_aspect_ratio(
552
+ new_width: number,
553
+ new_height: number,
554
+ original_aspect_ratio: number,
555
+ delta: Point
556
+ ): { width: number; height: number } {
557
+ const abs_delta_x = Math.abs(delta.x);
558
+ const abs_delta_y = Math.abs(delta.y);
559
+
560
+ if (abs_delta_x > abs_delta_y * 1.2) {
561
+ new_height = new_width / original_aspect_ratio;
562
+ } else if (abs_delta_y > abs_delta_x * 1.2) {
563
+ new_width = new_height * original_aspect_ratio;
564
+ } else {
565
+ if (new_width / original_aspect_ratio > new_height) {
566
+ new_height = new_width / original_aspect_ratio;
567
+ } else {
568
+ new_width = new_height * original_aspect_ratio;
569
+ }
570
+ }
571
+
572
+ return { width: new_width, height: new_height };
573
+ }
574
+
575
+ /**
576
+ * Limits dimensions based on constraints
577
+ * @param width - The width to limit
578
+ * @param height - The height to limit
579
+ * @param maintain_aspect_ratio - Whether to maintain aspect ratio
580
+ * @returns The limited dimensions
581
+ */
582
+ private limit_dimensions(
583
+ width: number,
584
+ height: number,
585
+ maintain_aspect_ratio: boolean
586
+ ): { width: number; height: number } {
587
+ const max_width = this.dimensions.width;
588
+ const max_height = this.dimensions.height;
589
+
590
+ let new_width = width;
591
+ let new_height = height;
592
+
593
+ if (new_width > max_width) {
594
+ if (maintain_aspect_ratio && this.active_corner_index !== -1) {
595
+ new_height = (max_width / new_width) * new_height;
596
+ }
597
+ new_width = max_width;
598
+ }
599
+
600
+ if (new_height > max_height) {
601
+ if (maintain_aspect_ratio && this.active_corner_index !== -1) {
602
+ new_width = (max_height / new_height) * new_width;
603
+ }
604
+ new_height = max_height;
605
+ }
606
+
607
+ new_width = Math.max(20, new_width);
608
+ new_height = Math.max(20, new_height);
609
+
610
+ return { width: new_width, height: new_height };
611
+ }
612
+
613
+ /**
614
+ * Calculates position deltas based on dimension changes
615
+ * @param old_width - The original width
616
+ * @param old_height - The original height
617
+ * @param new_width - The new width
618
+ * @param new_height - The new height
619
+ * @returns Object containing x and y position deltas
620
+ */
621
+ private calculate_position_deltas(
622
+ old_width: number,
623
+ old_height: number,
624
+ new_width: number,
625
+ new_height: number
626
+ ): { x: number; y: number } {
627
+ let delta_x = 0;
628
+ let delta_y = 0;
629
+
630
+ if (this.active_corner_index === 0 || this.active_edge_index === 2) {
631
+ delta_x = old_width - new_width;
632
+ } else if (this.active_corner_index === 2) {
633
+ delta_x = old_width - new_width;
634
+ delta_y = 0;
635
+ }
636
+
637
+ if (
638
+ this.active_corner_index === 0 ||
639
+ this.active_corner_index === 1 ||
640
+ this.active_edge_index === 0
641
+ ) {
642
+ delta_y = old_height - new_height;
643
+ }
644
+
645
+ return { x: delta_x, y: delta_y };
646
+ }
647
+
648
+ /**
649
+ * Applies boundary constraints to keep the image within the container
650
+ * @private
651
+ */
652
+ private apply_boundary_constraints(): void {
653
+ if (!this.image_editor_context.background_image) return;
654
+
655
+ const bg = this.image_editor_context.background_image;
656
+ const image_container = this.image_editor_context.image_container;
657
+
658
+ let new_x = bg.position.x;
659
+ let new_y = bg.position.y;
660
+
661
+ const container_width = image_container.width;
662
+ const container_height = image_container.height;
663
+ const bg_width = bg.width;
664
+ const bg_height = bg.height;
665
+
666
+ const effectiveWidth = container_width - this.borderRegion * 2;
667
+ const effectiveHeight = container_height - this.borderRegion * 2;
668
+
669
+ if (bg_width > effectiveWidth) {
670
+ const min_x = -(bg_width - effectiveWidth) + this.borderRegion;
671
+ const max_x = this.borderRegion;
672
+ new_x = Math.max(min_x, Math.min(max_x, new_x));
673
+ } else {
674
+ const min_x = this.borderRegion;
675
+ const max_x = container_width - bg_width - this.borderRegion;
676
+ if (new_x < min_x || new_x > max_x) {
677
+ new_x = Math.max(min_x, Math.min(max_x, new_x));
678
+ }
679
+ }
680
+
681
+ if (bg_height > effectiveHeight) {
682
+ const min_y = -(bg_height - effectiveHeight) + this.borderRegion;
683
+ const max_y = this.borderRegion;
684
+ new_y = Math.max(min_y, Math.min(max_y, new_y));
685
+ } else {
686
+ const min_y = this.borderRegion;
687
+ const max_y = container_height - bg_height - this.borderRegion;
688
+ if (new_y < min_y || new_y > max_y) {
689
+ new_y = Math.max(min_y, Math.min(max_y, new_y));
690
+ }
691
+ }
692
+
693
+ bg.position.set(new_x, new_y);
694
+
695
+ if (this.resize_ui_container) {
696
+ const total_x = image_container.position.x + new_x * this.scale;
697
+ const total_y = image_container.position.y + new_y * this.scale;
698
+ this.resize_ui_container.position.set(total_x, total_y);
699
+ }
700
+ }
701
+
702
+ /**
703
+ * Updates the resize bounds based on the delta
704
+ * @param delta - The delta to apply
705
+ * @param maintain_aspect_ratio - Whether to maintain the aspect ratio
706
+ */
707
+ private update_resize_bounds(
708
+ delta: Point,
709
+ maintain_aspect_ratio = false
710
+ ): void {
711
+ const background_image = this.image_editor_context.background_image;
712
+
713
+ if (!background_image) return;
714
+
715
+ const original_width = background_image.width;
716
+ const original_height = background_image.height;
717
+ const original_x = background_image.position.x;
718
+ const original_y = background_image.position.y;
719
+ const original_aspect_ratio = original_width / original_height;
720
+
721
+ let current_position: Point;
722
+
723
+ if (this.active_corner_index !== -1) {
724
+ switch (this.active_corner_index) {
725
+ case 0:
726
+ current_position = new Point(
727
+ original_x - delta.x,
728
+ original_y - delta.y
729
+ );
730
+ break;
731
+ case 1:
732
+ current_position = new Point(
733
+ original_x + original_width + delta.x,
734
+ original_y - delta.y
735
+ );
736
+ break;
737
+ case 2:
738
+ current_position = new Point(
739
+ original_x - delta.x,
740
+ original_y + original_height + delta.y
741
+ );
742
+ break;
743
+ case 3:
744
+ current_position = new Point(
745
+ original_x + original_width + delta.x,
746
+ original_y + original_height + delta.y
747
+ );
748
+ break;
749
+ default:
750
+ return;
751
+ }
752
+
753
+ const dimensions = this.handle_direct_corner_resize(
754
+ current_position,
755
+ original_width,
756
+ original_height,
757
+ original_x,
758
+ original_y,
759
+ original_aspect_ratio,
760
+ maintain_aspect_ratio
761
+ );
762
+
763
+ background_image.width = dimensions.width;
764
+ background_image.height = dimensions.height;
765
+ background_image.position.set(dimensions.x, dimensions.y);
766
+ } else if (this.active_edge_index !== -1) {
767
+ switch (this.active_edge_index) {
768
+ case 0:
769
+ current_position = new Point(
770
+ original_x + original_width / 2,
771
+ original_y - delta.y
772
+ );
773
+ break;
774
+ case 1:
775
+ current_position = new Point(
776
+ original_x + original_width / 2,
777
+ original_y + original_height + delta.y
778
+ );
779
+ break;
780
+ case 2:
781
+ current_position = new Point(
782
+ original_x - delta.x,
783
+ original_y + original_height / 2
784
+ );
785
+ break;
786
+ case 3:
787
+ current_position = new Point(
788
+ original_x + original_width + delta.x,
789
+ original_y + original_height / 2
790
+ );
791
+ break;
792
+ default:
793
+ return;
794
+ }
795
+
796
+ const dimensions = this.handle_direct_edge_resize(
797
+ current_position,
798
+ original_width,
799
+ original_height,
800
+ original_x,
801
+ original_y
802
+ );
803
+
804
+ background_image.width = dimensions.width;
805
+ background_image.height = dimensions.height;
806
+ background_image.position.set(dimensions.x, dimensions.y);
807
+ }
808
+
809
+ this.update_resize_ui();
810
+ }
811
+
812
+ /**
813
+ * updates the resize ui position and dimensions
814
+ */
815
+ private update_resize_ui(): void {
816
+ if (
817
+ !this.resize_ui_container ||
818
+ !this.image_editor_context.background_image ||
819
+ !this.image_editor_context.background_image.position
820
+ )
821
+ return;
822
+
823
+ const background_image = this.image_editor_context.background_image;
824
+ const image_container = this.image_editor_context.image_container;
825
+
826
+ const container_global_pos = image_container.getGlobalPosition();
827
+
828
+ const bg_pos_x = background_image.position.x * this.scale;
829
+ const bg_pos_y = background_image.position.y * this.scale;
830
+
831
+ this.resize_ui_container.position.set(
832
+ container_global_pos.x + bg_pos_x,
833
+ container_global_pos.y + bg_pos_y
834
+ );
835
+
836
+ const scaled_width = background_image.width * this.scale;
837
+ const scaled_height = background_image.height * this.scale;
838
+
839
+ const outline = this.resize_ui_container.getChildAt(0) as Graphics;
840
+ outline
841
+ .clear()
842
+ .rect(0, 0, scaled_width, scaled_height)
843
+ .stroke({ width: 1, color: 0x000000, alignment: 0, alpha: 0.3 });
844
+
845
+ const dotted_outline = this.resize_ui_container.getChildAt(1) as Graphics;
846
+ dotted_outline.clear();
847
+
848
+ dotted_outline.rect(0, 0, scaled_width, scaled_height).stroke({
849
+ width: 1,
850
+ color: 0x000000,
851
+ alpha: 0.7,
852
+ pixelLine: true
853
+ });
854
+
855
+ if (
856
+ !this.is_dragging &&
857
+ !this.is_moving &&
858
+ Math.abs(this.scale - this.last_scale) < 0.001
859
+ ) {
860
+ const dash_length = 5;
861
+ const gap_length = 5;
862
+ const total_length = dash_length + gap_length;
863
+
864
+ for (let x = 0; x < scaled_width; x += total_length * 2) {
865
+ dotted_outline
866
+ .rect(x, 0, Math.min(dash_length, scaled_width - x), 1)
867
+ .fill(0x000000);
868
+
869
+ dotted_outline
870
+ .rect(
871
+ x,
872
+ scaled_height - 1,
873
+ Math.min(dash_length, scaled_width - x),
874
+ 1
875
+ )
876
+ .fill(0x000000);
877
+ }
878
+
879
+ for (let y = 0; y < scaled_height; y += total_length * 2) {
880
+ dotted_outline
881
+ .rect(0, y, 1, Math.min(dash_length, scaled_height - y))
882
+ .fill(0x000000);
883
+
884
+ dotted_outline
885
+ .rect(
886
+ scaled_width - 1,
887
+ y,
888
+ 1,
889
+ Math.min(dash_length, scaled_height - y)
890
+ )
891
+ .fill(0x000000);
892
+ }
893
+ }
894
+
895
+ this.last_scale = this.scale;
896
+
897
+ const move_area = this.resize_ui_container.getChildAt(2) as Graphics;
898
+ move_area.clear().rect(0, 0, scaled_width, scaled_height).fill(0xffffff, 0);
899
+
900
+ this.update_handle_positions(scaled_width, scaled_height);
901
+ }
902
+
903
+ /**
904
+ * updates the positions of all handles
905
+ * @param width - width of the resize area
906
+ * @param height - height of the resize area
907
+ */
908
+ private update_handle_positions(width: number, height: number): void {
909
+ if (!this.resize_ui_container) return;
910
+
911
+ const handles = this.resize_ui_container.children.slice(3);
912
+
913
+ const move_area = this.resize_ui_container.getChildAt(2) as Graphics;
914
+ move_area.clear().rect(0, 0, width, height).fill(0xffffff, 0);
915
+
916
+ const corners = handles.slice(0, 4);
917
+ const cornerPositions = [
918
+ { x: 0, y: 0 },
919
+ { x: width, y: 0 },
920
+ { x: 0, y: height },
921
+ { x: width, y: height }
922
+ ];
923
+
924
+ corners.forEach((handle, i) => {
925
+ handle.position.set(cornerPositions[i].x, cornerPositions[i].y);
926
+ });
927
+
928
+ const edges = handles.slice(4);
929
+ edges.forEach((handle, i) => {
930
+ if (i < 2) {
931
+ handle.position.set(width / 2, i === 0 ? 0 : height);
932
+ } else {
933
+ handle.position.set(i === 2 ? 0 : width, height / 2);
934
+ }
935
+ });
936
+ }
937
+
938
+ /**
939
+ * sets up event listeners for the resize tool
940
+ */
941
+ private setup_event_listeners(): void {
942
+ const stage = this.image_editor_context.app.stage;
943
+ stage.eventMode = "static";
944
+ stage.on("pointermove", this.handle_pointer_move_bound);
945
+ stage.on("pointerup", this.handle_pointer_up_bound);
946
+ stage.on("pointerupoutside", this.handle_pointer_up_bound);
947
+
948
+ this.setup_dom_event_listeners();
949
+ }
950
+
951
+ /**
952
+ * Sets up direct DOM event listeners for dragging the background image
953
+ */
954
+ private setup_dom_event_listeners(): void {
955
+ this.cleanup_dom_event_listeners();
956
+
957
+ const context = this.image_editor_context;
958
+ if (!context?.app?.canvas) return;
959
+
960
+ const canvas = context.app.canvas;
961
+
962
+ this.dom_mousedown_handler = (e: MouseEvent) => {
963
+ if (this.current_subtool !== "size") return;
964
+
965
+ if (this.is_dragging || this.selected_handle) return;
966
+
967
+ if (!this.image_editor_context.background_image) return;
968
+
969
+ const bg = this.image_editor_context.background_image;
970
+
971
+ const container = this.image_editor_context.image_container;
972
+ const containerBounds = container.getBounds();
973
+
974
+ const rect = canvas.getBoundingClientRect();
975
+ const x = e.clientX - rect.left;
976
+ const y = e.clientY - rect.top;
977
+
978
+ const localX = (x - containerBounds.x) / this.scale;
979
+ const localY = (y - containerBounds.y) / this.scale;
980
+
981
+ if (
982
+ localX >= bg.position.x &&
983
+ localX <= bg.position.x + bg.width &&
984
+ localY >= bg.position.y &&
985
+ localY <= bg.position.y + bg.height
986
+ ) {
987
+ this.is_moving = true;
988
+
989
+ this.last_pointer_position = new Point(localX, localY);
990
+
991
+ this.original_state = {
992
+ width: bg.width,
993
+ height: bg.height,
994
+ x: bg.position.x,
995
+ y: bg.position.y
996
+ };
997
+
998
+ e.preventDefault();
999
+ e.stopPropagation();
1000
+ }
1001
+ };
1002
+
1003
+ this.dom_mousemove_handler = (e: MouseEvent) => {
1004
+ if (this.current_subtool !== "size" || !this.is_moving) return;
1005
+
1006
+ if (
1007
+ !this.last_pointer_position ||
1008
+ !this.image_editor_context.background_image
1009
+ )
1010
+ return;
1011
+
1012
+ const container = this.image_editor_context.image_container;
1013
+ const containerBounds = container.getBounds();
1014
+
1015
+ const rect = canvas.getBoundingClientRect();
1016
+ const x = e.clientX - rect.left;
1017
+ const y = e.clientY - rect.top;
1018
+
1019
+ const localX = (x - containerBounds.x) / this.scale;
1020
+ const localY = (y - containerBounds.y) / this.scale;
1021
+
1022
+ const current_position = new Point(localX, localY);
1023
+
1024
+ this.handle_image_dragging(current_position);
1025
+
1026
+ this.last_pointer_position = current_position;
1027
+
1028
+ e.preventDefault();
1029
+ e.stopPropagation();
1030
+ };
1031
+
1032
+ this.dom_mouseup_handler = (e: MouseEvent) => {
1033
+ if (this.current_subtool !== "size") return;
1034
+
1035
+ if (this.original_state && this.image_editor_context.background_image) {
1036
+ const bg = this.image_editor_context.background_image;
1037
+ const new_state = {
1038
+ width: bg.width,
1039
+ height: bg.height,
1040
+ x: bg.position.x,
1041
+ y: bg.position.y
1042
+ };
1043
+
1044
+ if (
1045
+ this.original_state.width !== new_state.width ||
1046
+ this.original_state.height !== new_state.height ||
1047
+ this.original_state.x !== new_state.x ||
1048
+ this.original_state.y !== new_state.y
1049
+ ) {
1050
+ const resize_command = new ResizeCommand(
1051
+ this.image_editor_context,
1052
+ this.original_state,
1053
+ new_state,
1054
+ this.update_resize_ui.bind(this)
1055
+ );
1056
+
1057
+ this.image_editor_context.execute_command(resize_command);
1058
+ }
1059
+
1060
+ this.original_state = null;
1061
+ }
1062
+
1063
+ this.is_moving = false;
1064
+ this.last_pointer_position = null;
1065
+
1066
+ this.update_resize_ui();
1067
+
1068
+ e.preventDefault();
1069
+ e.stopPropagation();
1070
+ };
1071
+
1072
+ canvas.addEventListener("mousedown", this.dom_mousedown_handler);
1073
+ window.addEventListener("mousemove", this.dom_mousemove_handler);
1074
+ window.addEventListener("mouseup", this.dom_mouseup_handler);
1075
+ }
1076
+
1077
+ /**
1078
+ * Cleans up DOM event listeners
1079
+ */
1080
+ private cleanup_dom_event_listeners(): void {
1081
+ const canvas = this.image_editor_context?.app?.canvas;
1082
+
1083
+ if (this.dom_mousedown_handler) {
1084
+ canvas?.removeEventListener("mousedown", this.dom_mousedown_handler);
1085
+ this.dom_mousedown_handler = null;
1086
+ }
1087
+
1088
+ if (this.dom_mousemove_handler) {
1089
+ window.removeEventListener("mousemove", this.dom_mousemove_handler);
1090
+ this.dom_mousemove_handler = null;
1091
+ }
1092
+
1093
+ if (this.dom_mouseup_handler) {
1094
+ window.removeEventListener("mouseup", this.dom_mouseup_handler);
1095
+ this.dom_mouseup_handler = null;
1096
+ }
1097
+ }
1098
+
1099
+ /**
1100
+ * removes event listeners for the resize tool
1101
+ */
1102
+ private cleanup_event_listeners(): void {
1103
+ const stage = this.image_editor_context?.app?.stage;
1104
+
1105
+ stage?.off("pointermove", this.handle_pointer_move_bound);
1106
+ stage?.off("pointerup", this.handle_pointer_up_bound);
1107
+ stage?.off("pointerupoutside", this.handle_pointer_up_bound);
1108
+
1109
+ this.cleanup_dom_event_listeners();
1110
+ }
1111
+
1112
+ /**
1113
+ * Handles pointer move events
1114
+ */
1115
+ private handle_pointer_move(event: FederatedPointerEvent): void {
1116
+ if (this.current_subtool !== "size") return;
1117
+
1118
+ const local_pos = this.image_editor_context.image_container.toLocal(
1119
+ event.global
1120
+ );
1121
+ const current_position = new Point(local_pos.x, local_pos.y);
1122
+
1123
+ if (this.is_moving && this.last_pointer_position) {
1124
+ this.handle_image_dragging(current_position);
1125
+
1126
+ this.last_pointer_position = current_position;
1127
+ } else if (this.is_dragging && this.selected_handle) {
1128
+ if (!this.image_editor_context.background_image) return;
1129
+
1130
+ const bg = this.image_editor_context.background_image;
1131
+ const maintain_aspect_ratio =
1132
+ this.active_corner_index !== -1 && !event.shiftKey;
1133
+
1134
+ const original_width = bg.width;
1135
+ const original_height = bg.height;
1136
+ const original_x = bg.position.x;
1137
+ const original_y = bg.position.y;
1138
+ const original_aspect_ratio = original_width / original_height;
1139
+
1140
+ let dimensions: { width: number; height: number; x: number; y: number };
1141
+
1142
+ if (this.active_corner_index !== -1) {
1143
+ dimensions = this.handle_direct_corner_resize(
1144
+ current_position,
1145
+ original_width,
1146
+ original_height,
1147
+ original_x,
1148
+ original_y,
1149
+ original_aspect_ratio,
1150
+ maintain_aspect_ratio
1151
+ );
1152
+ } else if (this.active_edge_index !== -1) {
1153
+ dimensions = this.handle_direct_edge_resize(
1154
+ current_position,
1155
+ original_width,
1156
+ original_height,
1157
+ original_x,
1158
+ original_y
1159
+ );
1160
+ } else {
1161
+ return;
1162
+ }
1163
+
1164
+ dimensions = this.limit_dimensions_to_container(
1165
+ dimensions,
1166
+ original_x,
1167
+ original_y,
1168
+ original_width,
1169
+ original_height,
1170
+ maintain_aspect_ratio
1171
+ );
1172
+
1173
+ bg.width = dimensions.width;
1174
+ bg.height = dimensions.height;
1175
+ bg.position.set(dimensions.x, dimensions.y);
1176
+
1177
+ this.update_resize_ui();
1178
+
1179
+ this.last_pointer_position = current_position;
1180
+ }
1181
+ }
1182
+ /**
1183
+ * handles pointer up events
1184
+ */
1185
+ private handle_pointer_up(): void {
1186
+ if (this.current_subtool !== "size") return;
1187
+
1188
+ this.is_dragging = false;
1189
+ this.is_moving = false;
1190
+ this.selected_handle = null;
1191
+ this.last_pointer_position = null;
1192
+ this.active_corner_index = -1;
1193
+ this.active_edge_index = -1;
1194
+
1195
+ this.update_resize_ui();
1196
+ this.notify("change");
1197
+ }
1198
+
1199
+ /**
1200
+ * Handles dragging of the background image
1201
+ * @param current_position - The current pointer position
1202
+ * @private
1203
+ */
1204
+ private handle_image_dragging(current_position: Point): void {
1205
+ if (
1206
+ !this.last_pointer_position ||
1207
+ !this.image_editor_context.background_image
1208
+ ) {
1209
+ return;
1210
+ }
1211
+
1212
+ const bg = this.image_editor_context.background_image;
1213
+ const image_container =
1214
+ this.image_editor_context.image_container.getLocalBounds();
1215
+
1216
+ const dx = current_position.x - this.last_pointer_position.x;
1217
+ const dy = current_position.y - this.last_pointer_position.y;
1218
+
1219
+ let new_x = bg.position.x + dx;
1220
+ let new_y = bg.position.y + dy;
1221
+
1222
+ const container_width = image_container.width;
1223
+ const container_height = image_container.height;
1224
+ const bg_width = bg.width;
1225
+ const bg_height = bg.height;
1226
+
1227
+ const effectiveWidth = container_width - this.borderRegion * 2;
1228
+ const effectiveHeight = container_height - this.borderRegion * 2;
1229
+
1230
+ if (bg_width > effectiveWidth) {
1231
+ const min_x = -(bg_width - effectiveWidth) + this.borderRegion;
1232
+ const max_x = this.borderRegion;
1233
+ new_x = Math.max(min_x, Math.min(max_x, new_x));
1234
+ } else {
1235
+ const min_x = this.borderRegion;
1236
+ const max_x = container_width - bg_width - this.borderRegion;
1237
+ new_x = Math.max(min_x, Math.min(max_x, new_x));
1238
+ }
1239
+
1240
+ if (bg_height > effectiveHeight) {
1241
+ const min_y = -(bg_height - effectiveHeight) + this.borderRegion;
1242
+ const max_y = this.borderRegion;
1243
+ new_y = Math.max(min_y, Math.min(max_y, new_y));
1244
+ } else {
1245
+ const min_y = this.borderRegion;
1246
+ const max_y = container_height - bg_height - this.borderRegion;
1247
+ new_y = Math.max(min_y, Math.min(max_y, new_y));
1248
+ }
1249
+
1250
+ bg.position.set(new_x, new_y);
1251
+
1252
+ this.update_resize_ui();
1253
+ }
1254
+
1255
+ /**
1256
+ * Handles corner resizing
1257
+ * @param current_position - The current mouse position
1258
+ * @param original_width - The original width
1259
+ * @param original_height - The original height
1260
+ * @param original_x - The original x position
1261
+ * @param original_y - The original y position
1262
+ * @param original_aspect_ratio - The original aspect ratio
1263
+ * @param maintain_aspect_ratio - Whether to maintain aspect ratio
1264
+ * @returns The new dimensions and position
1265
+ * @private
1266
+ */
1267
+ private handle_direct_corner_resize(
1268
+ current_position: Point,
1269
+ original_width: number,
1270
+ original_height: number,
1271
+ original_x: number,
1272
+ original_y: number,
1273
+ original_aspect_ratio: number,
1274
+ maintain_aspect_ratio: boolean
1275
+ ): { width: number; height: number; x: number; y: number } {
1276
+ let raw_width = 0;
1277
+ let raw_height = 0;
1278
+ let new_x = original_x;
1279
+ let new_y = original_y;
1280
+
1281
+ switch (this.active_corner_index) {
1282
+ case 0:
1283
+ raw_width = original_x + original_width - current_position.x;
1284
+ raw_height = original_y + original_height - current_position.y;
1285
+ break;
1286
+ case 1:
1287
+ raw_width = current_position.x - original_x;
1288
+ raw_height = original_y + original_height - current_position.y;
1289
+ break;
1290
+ case 2:
1291
+ raw_width = original_x + original_width - current_position.x;
1292
+ raw_height = current_position.y - original_y;
1293
+ break;
1294
+ case 3:
1295
+ raw_width = current_position.x - original_x;
1296
+ raw_height = current_position.y - original_y;
1297
+ break;
1298
+ }
1299
+
1300
+ raw_width = Math.max(20, raw_width);
1301
+ raw_height = Math.max(20, raw_height);
1302
+
1303
+ let new_width = raw_width;
1304
+ let new_height = raw_height;
1305
+
1306
+ if (maintain_aspect_ratio) {
1307
+ const diagonal_vector = {
1308
+ x: current_position.x - (original_x + original_width / 2),
1309
+ y: current_position.y - (original_y + original_height / 2)
1310
+ };
1311
+
1312
+ const angle = Math.abs(Math.atan2(diagonal_vector.y, diagonal_vector.x));
1313
+
1314
+ if (angle < Math.PI / 4 || angle > (3 * Math.PI) / 4) {
1315
+ new_height = new_width / original_aspect_ratio;
1316
+ } else {
1317
+ new_width = new_height * original_aspect_ratio;
1318
+ }
1319
+ }
1320
+
1321
+ switch (this.active_corner_index) {
1322
+ case 0:
1323
+ new_x = original_x + original_width - new_width;
1324
+ new_y = original_y + original_height - new_height;
1325
+ break;
1326
+ case 1:
1327
+ new_y = original_y + original_height - new_height;
1328
+ break;
1329
+ case 2:
1330
+ new_x = original_x + original_width - new_width;
1331
+ break;
1332
+ case 3:
1333
+ break;
1334
+ }
1335
+
1336
+ return { width: new_width, height: new_height, x: new_x, y: new_y };
1337
+ }
1338
+
1339
+ /**
1340
+ * Handles edge resizing
1341
+ * @param current_position - The current mouse position
1342
+ * @param original_width - The original width
1343
+ * @param original_height - The original height
1344
+ * @param original_x - The original x position
1345
+ * @param original_y - The original y position
1346
+ * @returns The new dimensions and position
1347
+ * @private
1348
+ */
1349
+ private handle_direct_edge_resize(
1350
+ current_position: Point,
1351
+ original_width: number,
1352
+ original_height: number,
1353
+ original_x: number,
1354
+ original_y: number
1355
+ ): { width: number; height: number; x: number; y: number } {
1356
+ let new_width = original_width;
1357
+ let new_height = original_height;
1358
+ let new_x = original_x;
1359
+ let new_y = original_y;
1360
+
1361
+ switch (this.active_edge_index) {
1362
+ case 0:
1363
+ new_height = Math.max(
1364
+ 20,
1365
+ original_y + original_height - current_position.y
1366
+ );
1367
+ new_y = current_position.y;
1368
+ break;
1369
+ case 1:
1370
+ new_height = Math.max(20, current_position.y - original_y);
1371
+ break;
1372
+ case 2:
1373
+ new_width = Math.max(
1374
+ 20,
1375
+ original_x + original_width - current_position.x
1376
+ );
1377
+ new_x = current_position.x;
1378
+ break;
1379
+ case 3:
1380
+ new_width = Math.max(20, current_position.x - original_x);
1381
+ break;
1382
+ }
1383
+
1384
+ return { width: new_width, height: new_height, x: new_x, y: new_y };
1385
+ }
1386
+
1387
+ /**
1388
+ * Limits dimensions to container size
1389
+ * @param dimensions - The dimensions to limit
1390
+ * @param original_x - The original x position
1391
+ * @param original_y - The original y position
1392
+ * @param original_width - The original width
1393
+ * @param original_height - The original height
1394
+ * @param maintain_aspect_ratio - Whether to maintain aspect ratio
1395
+ * @returns The limited dimensions and position
1396
+ * @private
1397
+ */
1398
+ private limit_dimensions_to_container(
1399
+ dimensions: { width: number; height: number; x: number; y: number },
1400
+ original_x: number,
1401
+ original_y: number,
1402
+ original_width: number,
1403
+ original_height: number,
1404
+ maintain_aspect_ratio: boolean
1405
+ ): { width: number; height: number; x: number; y: number } {
1406
+ let {
1407
+ width: new_width,
1408
+ height: new_height,
1409
+ x: new_x,
1410
+ y: new_y
1411
+ } = dimensions;
1412
+
1413
+ const effective_container_width =
1414
+ this.dimensions.width - this.borderRegion * 2;
1415
+ const effective_container_height =
1416
+ this.dimensions.height - this.borderRegion * 2;
1417
+
1418
+ const pre_limit_width = new_width;
1419
+ const pre_limit_height = new_height;
1420
+
1421
+ const size_limited = this.apply_size_limits(
1422
+ new_width,
1423
+ new_height,
1424
+ effective_container_width,
1425
+ effective_container_height,
1426
+ maintain_aspect_ratio,
1427
+ pre_limit_width / pre_limit_height
1428
+ );
1429
+
1430
+ new_width = size_limited.width;
1431
+ new_height = size_limited.height;
1432
+
1433
+ const position_adjusted = this.adjust_position_for_resizing(
1434
+ new_width,
1435
+ new_height,
1436
+ original_x,
1437
+ original_y,
1438
+ original_width,
1439
+ original_height
1440
+ );
1441
+
1442
+ new_x = position_adjusted.x;
1443
+ new_y = position_adjusted.y;
1444
+
1445
+ const border_constrained = this.apply_border_constraints(
1446
+ new_width,
1447
+ new_height,
1448
+ new_x,
1449
+ new_y,
1450
+ maintain_aspect_ratio,
1451
+ pre_limit_width / pre_limit_height
1452
+ );
1453
+
1454
+ return border_constrained;
1455
+ }
1456
+
1457
+ /**
1458
+ * Apply size limits to ensure dimensions don't exceed container
1459
+ * @private
1460
+ */
1461
+ private apply_size_limits(
1462
+ width: number,
1463
+ height: number,
1464
+ max_width: number,
1465
+ max_height: number,
1466
+ maintain_aspect_ratio: boolean,
1467
+ aspect_ratio: number
1468
+ ): { width: number; height: number } {
1469
+ let new_width = width;
1470
+ let new_height = height;
1471
+
1472
+ const needs_width_limit = new_width > max_width;
1473
+ const needs_height_limit = new_height > max_height;
1474
+
1475
+ if (needs_width_limit && needs_height_limit) {
1476
+ const width_scale = max_width / new_width;
1477
+ const height_scale = max_height / new_height;
1478
+
1479
+ if (width_scale < height_scale) {
1480
+ new_width = max_width;
1481
+ if (maintain_aspect_ratio) {
1482
+ new_height = new_width / aspect_ratio;
1483
+ }
1484
+ } else {
1485
+ new_height = max_height;
1486
+ if (maintain_aspect_ratio) {
1487
+ new_width = new_height * aspect_ratio;
1488
+ }
1489
+ }
1490
+ } else if (needs_width_limit) {
1491
+ new_width = max_width;
1492
+ if (maintain_aspect_ratio) {
1493
+ new_height = new_width / aspect_ratio;
1494
+ }
1495
+ } else if (needs_height_limit) {
1496
+ new_height = max_height;
1497
+ if (maintain_aspect_ratio) {
1498
+ new_width = new_height * aspect_ratio;
1499
+ }
1500
+ }
1501
+
1502
+ return { width: new_width, height: new_height };
1503
+ }
1504
+
1505
+ /**
1506
+ * Adjust position based on which handles are being dragged
1507
+ * @private
1508
+ */
1509
+ private adjust_position_for_resizing(
1510
+ new_width: number,
1511
+ new_height: number,
1512
+ original_x: number,
1513
+ original_y: number,
1514
+ original_width: number,
1515
+ original_height: number
1516
+ ): { x: number; y: number } {
1517
+ let new_x = original_x;
1518
+ let new_y = original_y;
1519
+
1520
+ switch (this.active_corner_index) {
1521
+ case 0:
1522
+ new_x = original_x + original_width - new_width;
1523
+ new_y = original_y + original_height - new_height;
1524
+ break;
1525
+ case 1:
1526
+ new_y = original_y + original_height - new_height;
1527
+ break;
1528
+ case 2:
1529
+ new_x = original_x + original_width - new_width;
1530
+ break;
1531
+ case 3:
1532
+ break;
1533
+ }
1534
+
1535
+ if (this.active_edge_index !== -1) {
1536
+ switch (this.active_edge_index) {
1537
+ case 0:
1538
+ new_y = original_y + original_height - new_height;
1539
+ break;
1540
+ case 2:
1541
+ new_x = original_x + original_width - new_width;
1542
+ break;
1543
+ }
1544
+ }
1545
+
1546
+ return { x: new_x, y: new_y };
1547
+ }
1548
+
1549
+ /**
1550
+ * Apply border region constraints to prevent image from intruding on border
1551
+ * @private
1552
+ */
1553
+ private apply_border_constraints(
1554
+ width: number,
1555
+ height: number,
1556
+ x: number,
1557
+ y: number,
1558
+ maintain_aspect_ratio: boolean,
1559
+ aspect_ratio: number
1560
+ ): { width: number; height: number; x: number; y: number } {
1561
+ const top_left_constrained = this.apply_top_left_constraints(
1562
+ width,
1563
+ height,
1564
+ x,
1565
+ y,
1566
+ maintain_aspect_ratio,
1567
+ aspect_ratio
1568
+ );
1569
+
1570
+ const all_constrained = this.apply_bottom_right_constraints(
1571
+ top_left_constrained.width,
1572
+ top_left_constrained.height,
1573
+ top_left_constrained.x,
1574
+ top_left_constrained.y,
1575
+ maintain_aspect_ratio,
1576
+ aspect_ratio
1577
+ );
1578
+
1579
+ all_constrained.width = Math.max(20, all_constrained.width);
1580
+ all_constrained.height = Math.max(20, all_constrained.height);
1581
+
1582
+ return all_constrained;
1583
+ }
1584
+
1585
+ /**
1586
+ * Apply top and left border constraints
1587
+ * @private
1588
+ */
1589
+ private apply_top_left_constraints(
1590
+ width: number,
1591
+ height: number,
1592
+ x: number,
1593
+ y: number,
1594
+ maintain_aspect_ratio: boolean,
1595
+ aspect_ratio: number
1596
+ ): { width: number; height: number; x: number; y: number } {
1597
+ let new_width = width;
1598
+ let new_height = height;
1599
+ let new_x = x;
1600
+ let new_y = y;
1601
+
1602
+ if (new_x < this.borderRegion) {
1603
+ if (
1604
+ this.active_corner_index === 0 ||
1605
+ this.active_corner_index === 2 ||
1606
+ this.active_edge_index === 2
1607
+ ) {
1608
+ new_width -= this.borderRegion - new_x;
1609
+ if (maintain_aspect_ratio) {
1610
+ new_height = new_width / aspect_ratio;
1611
+ }
1612
+ }
1613
+ new_x = this.borderRegion;
1614
+ }
1615
+
1616
+ if (new_y < this.borderRegion) {
1617
+ if (
1618
+ this.active_corner_index === 0 ||
1619
+ this.active_corner_index === 1 ||
1620
+ this.active_edge_index === 0
1621
+ ) {
1622
+ new_height -= this.borderRegion - new_y;
1623
+ if (maintain_aspect_ratio) {
1624
+ new_width = new_height * aspect_ratio;
1625
+ }
1626
+ }
1627
+ new_y = this.borderRegion;
1628
+ }
1629
+
1630
+ return { width: new_width, height: new_height, x: new_x, y: new_y };
1631
+ }
1632
+
1633
+ /**
1634
+ * Apply bottom and right border constraints
1635
+ * @private
1636
+ */
1637
+ private apply_bottom_right_constraints(
1638
+ width: number,
1639
+ height: number,
1640
+ x: number,
1641
+ y: number,
1642
+ maintain_aspect_ratio: boolean,
1643
+ aspect_ratio: number
1644
+ ): { width: number; height: number; x: number; y: number } {
1645
+ let new_width = width;
1646
+ let new_height = height;
1647
+ let new_x = x;
1648
+ let new_y = y;
1649
+
1650
+ if (new_x + new_width > this.dimensions.width - this.borderRegion) {
1651
+ if (
1652
+ this.active_corner_index === 1 ||
1653
+ this.active_corner_index === 3 ||
1654
+ this.active_edge_index === 3
1655
+ ) {
1656
+ new_width = this.dimensions.width - this.borderRegion - new_x;
1657
+ if (maintain_aspect_ratio) {
1658
+ new_height = new_width / aspect_ratio;
1659
+ }
1660
+ } else {
1661
+ const right_edge = new_x + new_width;
1662
+ const excess = right_edge - (this.dimensions.width - this.borderRegion);
1663
+ new_x = Math.max(this.borderRegion, new_x - excess);
1664
+ }
1665
+ }
1666
+
1667
+ if (new_y + new_height > this.dimensions.height - this.borderRegion) {
1668
+ if (
1669
+ this.active_corner_index === 2 ||
1670
+ this.active_corner_index === 3 ||
1671
+ this.active_edge_index === 1
1672
+ ) {
1673
+ new_height = this.dimensions.height - this.borderRegion - new_y;
1674
+ if (maintain_aspect_ratio) {
1675
+ new_width = new_height * aspect_ratio;
1676
+ }
1677
+ } else {
1678
+ const bottom_edge = new_y + new_height;
1679
+ const excess =
1680
+ bottom_edge - (this.dimensions.height - this.borderRegion);
1681
+ new_y = Math.max(this.borderRegion, new_y - excess);
1682
+ }
1683
+ }
1684
+
1685
+ return { width: new_width, height: new_height, x: new_x, y: new_y };
1686
+ }
1687
+
1688
+ /**
1689
+ * Shows the resize UI
1690
+ * @private
1691
+ */
1692
+ private show_resize_ui(): void {
1693
+ if (this.resize_ui_container) {
1694
+ this.resize_ui_container.visible = true;
1695
+ this.update_resize_ui();
1696
+ }
1697
+
1698
+ if (this.image_editor_context?.background_image) {
1699
+ const bg = this.image_editor_context.background_image;
1700
+ this.current_cursor = bg.cursor;
1701
+ bg.cursor = "move";
1702
+ }
1703
+
1704
+ this.setup_dom_event_listeners();
1705
+ }
1706
+
1707
+ /**
1708
+ * Hides the resize UI
1709
+ * @private
1710
+ */
1711
+ private hide_resize_ui(): void {
1712
+ if (this.resize_ui_container) {
1713
+ this.resize_ui_container.visible = false;
1714
+ }
1715
+
1716
+ if (this.image_editor_context?.background_image) {
1717
+ const bg = this.image_editor_context.background_image;
1718
+ bg.cursor = this.current_cursor;
1719
+ }
1720
+
1721
+ this.cleanup_dom_event_listeners();
1722
+ }
1723
+
1724
+ on<T extends string>(event: T, callback: () => void): void {
1725
+ this.event_callbacks.set(event, [
1726
+ ...(this.event_callbacks.get(event) || []),
1727
+ callback
1728
+ ]);
1729
+ }
1730
+
1731
+ off<T extends string>(event: T, callback: () => void): void {
1732
+ this.event_callbacks.set(
1733
+ event,
1734
+ this.event_callbacks.get(event)?.filter((cb) => cb !== callback) || []
1735
+ );
1736
+ }
1737
+
1738
+ private notify<T extends string>(event: T): void {
1739
+ for (const callback of this.event_callbacks.get(event) || []) {
1740
+ callback();
1741
+ }
1742
+ }
1743
+
1744
+ /**
1745
+ * Sets the border region explicitly
1746
+ * @param borderRegion The border region size in pixels
1747
+ */
1748
+ public set_border_region(borderRegion: number): void {
1749
+ this.borderRegion = borderRegion;
1750
+
1751
+ if (this.image_editor_context?.background_image) {
1752
+ (this.image_editor_context.background_image as any).borderRegion =
1753
+ borderRegion;
1754
+ }
1755
+
1756
+ if (this.resize_ui_container) {
1757
+ this.update_resize_ui();
1758
+ }
1759
+
1760
+ if (
1761
+ this.current_subtool === "size" &&
1762
+ this.image_editor_context?.background_image
1763
+ ) {
1764
+ this.apply_boundary_constraints();
1765
+ }
1766
+ }
1767
+ }
6.26.1/imageeditor/shared/types.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface ImageBlobs {
2
+ background: Blob | null;
3
+ layers: (Blob | null)[];
4
+ composite: Blob | null;
5
+ }
6
+
7
+ export interface LayerOptions {
8
+ allow_additional_layers: boolean;
9
+ layers: string[];
10
+ disabled: boolean;
11
+ }
12
+
13
+ export type Source = "upload" | "webcam" | "clipboard";
14
+ export type Transform = "crop" | "resize";
15
+
16
+ export interface WebcamOptions {
17
+ mirror: boolean;
18
+ constraints: Record<string, any>;
19
+ }
20
+
21
+ export interface WatermarkOptions {
22
+ watermark: string | Blob | null;
23
+ position:
24
+ | [number, number]
25
+ | "top-left"
26
+ | "top-right"
27
+ | "bottom-left"
28
+ | "bottom-right";
29
+ }
6.26.1/imageeditor/shared/utils/events.ts ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { tick } from "svelte";
2
+
3
+ /**
4
+ * Svelte action to handle clicks outside of a DOM node
5
+ * @param node DOM node to check the click is outside of
6
+ * @param callback callback function to call if click is outside
7
+ * @returns svelte action return object with destroy method to remove event listener
8
+ */
9
+ export function click_outside(
10
+ node: Node,
11
+ callback: (arg: MouseEvent) => void
12
+ ): any {
13
+ const handle_click = (event: MouseEvent): void => {
14
+ if (
15
+ node &&
16
+ !node.contains(event.target as Node) &&
17
+ !event.defaultPrevented
18
+ ) {
19
+ callback(event);
20
+ }
21
+ };
22
+
23
+ document.addEventListener("mousedown", handle_click, true);
24
+
25
+ return {
26
+ destroy() {
27
+ document.removeEventListener("mousedown", handle_click, true);
28
+ }
29
+ };
30
+ }
6.26.1/imageeditor/shared/utils/parse_placeholder.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const RE_HEADING = /^(#\s*)(.+)$/m;
2
+
3
+ export function inject(text: string): [string | false, string | false] {
4
+ const trimmed_text = text.trim();
5
+
6
+ const heading_match = trimmed_text.match(RE_HEADING);
7
+ if (!heading_match) {
8
+ return [false, trimmed_text || false];
9
+ }
10
+
11
+ const [full_match, , heading_content] = heading_match;
12
+ const _heading = heading_content.trim();
13
+
14
+ if (trimmed_text === full_match) {
15
+ return [_heading, false];
16
+ }
17
+
18
+ const heading_end_index =
19
+ heading_match.index !== undefined
20
+ ? heading_match.index + full_match.length
21
+ : 0;
22
+ const remaining_text = trimmed_text.substring(heading_end_index).trim();
23
+
24
+ const _paragraph = remaining_text || false;
25
+
26
+ return [_heading, _paragraph];
27
+ }
6.26.1/imageeditor/shared/utils/pixi.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Graphics, Rectangle, type Renderer, type Container } from "pixi.js";
2
+
3
+ /**
4
+ * Creates a pixi graphics object.
5
+ * @param z_index the z index of the graphics object
6
+ * @returns a graphics object
7
+ */
8
+ export function make_graphics(z_index: number): Graphics {
9
+ const graphics = new Graphics();
10
+ graphics.eventMode = "none";
11
+ graphics.zIndex = z_index;
12
+
13
+ return graphics;
14
+ }
15
+
16
+ /**
17
+ * Clamps a number between a min and max value.
18
+ * @param n The number to clamp.
19
+ * @param min The minimum value.
20
+ * @param max The maximum value.
21
+ * @returns The clamped number.
22
+ */
23
+ export function clamp(n: number, min: number, max: number): number {
24
+ return n < min ? min : n > max ? max : n;
25
+ }
26
+
27
+ /**
28
+ * Generates a blob from a pixi object.s
29
+ * @param renderer The pixi renderer.
30
+ * @param obj The pixi object to generate a blob from.
31
+ * @param bounds The bounds of the canvas that we wish to extract
32
+ * @param width The full width of the canvas
33
+ * @param height The full height of the canvas
34
+ * @returns A promise with the blob.
35
+ */
36
+ export function get_canvas_blob(
37
+ renderer: Renderer,
38
+ obj: Container | null,
39
+ bounds?: { x: number; y: number; width: number; height: number }
40
+ ): Promise<Blob | null> {
41
+ return new Promise((resolve) => {
42
+ if (!obj) {
43
+ resolve(null);
44
+ return;
45
+ }
46
+
47
+ const image_bounds = obj.getLocalBounds();
48
+ const frame = bounds
49
+ ? new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height)
50
+ : new Rectangle(0, 0, image_bounds.width, image_bounds.height);
51
+
52
+ const src_canvas = renderer.extract.canvas({
53
+ target: obj,
54
+ resolution: 1,
55
+ frame
56
+ });
57
+
58
+ src_canvas.toBlob?.((blob) => {
59
+ if (!blob) {
60
+ resolve(null);
61
+ }
62
+ resolve(blob);
63
+ });
64
+ });
65
+ }
66
+
67
+ export interface ImageBlobs {
68
+ background: Blob | null;
69
+ layers: (Blob | null)[];
70
+ composite: Blob | null;
71
+ }
6.26.1/imageeditor/shared/zoom/zoom.ts ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Point,
3
+ type FederatedWheelEvent,
4
+ type FederatedPointerEvent
5
+ } from "pixi.js";
6
+ import { type ImageEditorContext, type Tool } from "../core/editor";
7
+ import { type Tool as ToolbarTool, type Subtool } from "../Toolbar.svelte";
8
+ import { get, writable } from "svelte/store";
9
+
10
+ /**
11
+ * ZoomTool class for handling zoom and pan functionality in the image editor
12
+ * Implements the Tool interface
13
+ */
14
+ export class ZoomTool implements Tool {
15
+ name = "zoom";
16
+ min_zoom = writable(true);
17
+
18
+ private image_editor_context!: ImageEditorContext;
19
+
20
+ private readonly max_zoom = 10;
21
+ private readonly border_padding = 30;
22
+
23
+ private pad_bottom = 0;
24
+ private is_pinching = false;
25
+ private is_dragging = false;
26
+ private is_pointer_dragging = false;
27
+ private last_touch_position: Point | null = null;
28
+ private last_pinch_distance = 0;
29
+ private drag_start = new Point();
30
+ private current_tool!: ToolbarTool;
31
+ private current_subtool!: Subtool;
32
+ private local_scale = 1;
33
+ private local_dimensions: { width: number; height: number } = {
34
+ width: 0,
35
+ height: 0
36
+ };
37
+ private local_position: { x: number; y: number } = { x: 0, y: 0 };
38
+
39
+ /**
40
+ * Prevents default behavior for events
41
+ * @param {FederatedWheelEvent | FederatedPointerEvent} event - The event to prevent default behavior for
42
+ */
43
+ prevent_default(
44
+ event: FederatedWheelEvent | FederatedPointerEvent | WheelEvent
45
+ ): void {
46
+ event.preventDefault();
47
+ event.stopPropagation();
48
+ }
49
+
50
+ /**
51
+ * Sets the current tool and subtool
52
+ * @param {ToolbarTool} tool - The tool to set
53
+ * @param {Subtool} subtool - The subtool to set
54
+ */
55
+ set_tool(tool: ToolbarTool, subtool: Subtool): void {
56
+ this.current_tool = tool;
57
+ this.current_subtool = subtool;
58
+ }
59
+
60
+ /**
61
+ * Sets the zoom level to a specific percentage or fits the image to the screen
62
+ * @param {number | 'fit'} zoom_level - The zoom level to set (0-1) or 'fit' to use min_zoom
63
+ * @returns {void}
64
+ */
65
+ set_zoom(zoom_level: number | "fit"): void {
66
+ const fit_zoom = this.calculate_min_zoom(
67
+ this.local_dimensions.width,
68
+ this.local_dimensions.height
69
+ );
70
+
71
+ let target_zoom: number;
72
+ const is_fit_zoom = zoom_level === "fit";
73
+ if (is_fit_zoom) {
74
+ target_zoom = fit_zoom;
75
+ } else {
76
+ target_zoom = Math.max(0, Math.min(this.max_zoom, zoom_level));
77
+ }
78
+
79
+ const canvas = this.image_editor_context.app.screen;
80
+ const canvas_width = canvas.width;
81
+ const canvas_height = canvas.height;
82
+
83
+ let center_point: { x: number; y: number };
84
+
85
+ center_point = {
86
+ x: canvas_width / 2,
87
+ y: canvas_height / 2
88
+ };
89
+
90
+ this.zoom_to_point(target_zoom, center_point, true, is_fit_zoom);
91
+ }
92
+
93
+ /**
94
+ * Sets up the zoom tool with the given context and state
95
+ * @param {ImageEditorContext} context - The image editor context
96
+ * @param {ToolbarTool} tool - The current tool
97
+ * @param {Subtool} subtool - The current subtool
98
+ * @returns {Promise<void>}
99
+ */
100
+ async setup(
101
+ context: ImageEditorContext,
102
+ tool: ToolbarTool,
103
+ subtool: Subtool
104
+ ): Promise<void> {
105
+ this.image_editor_context = context;
106
+ this.current_tool = tool;
107
+ this.current_subtool = subtool;
108
+ this.pad_bottom = context.pad_bottom;
109
+ const { width, height } = await this.get_container_dimensions();
110
+ const fit_zoom = this.calculate_min_zoom(width, height);
111
+ const min_zoom = Math.min(fit_zoom, 1);
112
+
113
+ this.local_scale = min_zoom;
114
+
115
+ const canvas = this.image_editor_context.app.screen;
116
+
117
+ const center_x = canvas.width / 2;
118
+ const center_y = canvas.height / 2;
119
+
120
+ const scaled_width = width * min_zoom;
121
+ const scaled_height = height * min_zoom;
122
+ const initial_x = center_x - scaled_width / 2;
123
+ const initial_y = center_y - scaled_height / 2;
124
+
125
+ this.local_position = { x: initial_x, y: initial_y };
126
+
127
+ this.setup_event_listeners();
128
+
129
+ await this.image_editor_context.set_image_properties({
130
+ scale: min_zoom,
131
+ position: { x: initial_x, y: initial_y }
132
+ });
133
+
134
+ this.image_editor_context.dimensions.subscribe((dimensions) => {
135
+ this.local_dimensions = dimensions;
136
+ });
137
+
138
+ this.image_editor_context.scale.subscribe((scale) => {
139
+ this.local_scale = scale;
140
+ });
141
+
142
+ this.image_editor_context.position.subscribe((position) => {
143
+ this.local_position = position;
144
+ });
145
+ }
146
+
147
+ /**
148
+ * Sets up event listeners for zoom and pan functionality
149
+ * @private
150
+ */
151
+ private setup_event_listeners(): void {
152
+ const stage = this.image_editor_context.app.stage;
153
+ const canvas = this.image_editor_context.app.canvas;
154
+
155
+ canvas.addEventListener("wheel", this.prevent_default, { passive: false });
156
+
157
+ stage.eventMode = "static";
158
+ stage.hitArea = this.image_editor_context.app.screen;
159
+
160
+ const wheel_listener = this.handle_wheel.bind(this);
161
+ stage.addEventListener("wheel", wheel_listener, { passive: false });
162
+
163
+ if ("ontouchstart" in window) {
164
+ stage.addEventListener(
165
+ "touchstart",
166
+ this.handle_touch_start.bind(this) as EventListener
167
+ );
168
+ stage.addEventListener(
169
+ "touchmove",
170
+ this.handle_touch_move.bind(this) as EventListener
171
+ );
172
+ stage.addEventListener(
173
+ "touchend",
174
+ this.handle_touch_end.bind(this) as EventListener
175
+ );
176
+ } else {
177
+ stage.addEventListener(
178
+ "pointerdown",
179
+ this.handle_pointer_down.bind(this)
180
+ );
181
+ stage.addEventListener(
182
+ "pointermove",
183
+ this.handle_pointer_move.bind(this)
184
+ );
185
+ stage.addEventListener("pointerup", this.handle_pointer_up.bind(this));
186
+ stage.addEventListener(
187
+ "pointerupoutside",
188
+ this.handle_pointer_up.bind(this)
189
+ );
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Handles wheel events for zooming
195
+ * @param {FederatedWheelEvent} event - The wheel event
196
+ * @private
197
+ */
198
+ private handle_wheel(event: FederatedWheelEvent): void {
199
+ const is_trackpad = event.deltaMode === 0 && Math.abs(event.deltaY) < 50;
200
+ const scroll_speed = is_trackpad ? 30 : 10;
201
+
202
+ if (event.altKey || event.metaKey) {
203
+ const local_point = this.image_editor_context.app.stage.toLocal(
204
+ event.global
205
+ );
206
+ const zoom_delta = -event.deltaY * (is_trackpad ? 0.001 : 0.0005);
207
+ const new_scale = this.local_scale * (1 + zoom_delta);
208
+ this.zoom_to_point(new_scale, local_point, true);
209
+ } else {
210
+ const delta_x = event.deltaX;
211
+ const delta_y = event.deltaY;
212
+ const raw_position = {
213
+ x: this.local_position.x - (delta_x / 100) * scroll_speed,
214
+ y: this.local_position.y - (delta_y / 100) * scroll_speed
215
+ };
216
+
217
+ const canvas = this.image_editor_context.app.screen;
218
+ const scaled_width = this.local_dimensions.width * this.local_scale;
219
+ const scaled_height = this.local_dimensions.height * this.local_scale;
220
+ const available_width = canvas.width - this.border_padding * 2;
221
+ const available_height =
222
+ canvas.height - this.border_padding * 2 - this.pad_bottom;
223
+
224
+ let final_position = { ...raw_position };
225
+
226
+ if (scaled_width <= available_width) {
227
+ final_position.x = (canvas.width - scaled_width) / 2;
228
+ } else {
229
+ const max_offset = canvas.width / 2;
230
+ const left_bound = max_offset;
231
+ const right_bound = canvas.width - max_offset - scaled_width;
232
+ final_position.x = Math.min(
233
+ Math.max(raw_position.x, right_bound),
234
+ left_bound
235
+ );
236
+ }
237
+
238
+ if (scaled_height <= available_height) {
239
+ final_position.y =
240
+ (canvas.height - this.pad_bottom - scaled_height) / 2;
241
+ } else {
242
+ const max_offset = (canvas.height - this.pad_bottom) / 2;
243
+ const top_bound = max_offset;
244
+ const bottom_bound =
245
+ canvas.height - this.pad_bottom - max_offset - scaled_height;
246
+ final_position.y = Math.min(
247
+ Math.max(raw_position.y, bottom_bound),
248
+ top_bound
249
+ );
250
+ }
251
+
252
+ this.image_editor_context.set_image_properties({
253
+ scale: this.local_scale,
254
+ position: final_position
255
+ });
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Cleans up resources and event listeners
261
+ */
262
+ cleanup(): void {
263
+ const stage = this?.image_editor_context?.app?.stage;
264
+ if (!stage) return;
265
+ stage.removeEventListener("wheel", this.handle_wheel.bind(this));
266
+
267
+ if ("ontouchstart" in window) {
268
+ stage.removeEventListener(
269
+ "touchstart",
270
+ this.handle_touch_start.bind(this) as EventListener
271
+ );
272
+ stage.removeEventListener(
273
+ "touchmove",
274
+ this.handle_touch_move.bind(this) as EventListener
275
+ );
276
+ stage.removeEventListener(
277
+ "touchend",
278
+ this.handle_touch_end.bind(this) as EventListener
279
+ );
280
+ } else {
281
+ stage.removeEventListener(
282
+ "pointerdown",
283
+ this.handle_pointer_down.bind(this)
284
+ );
285
+ stage.removeEventListener(
286
+ "pointermove",
287
+ this.handle_pointer_move.bind(this)
288
+ );
289
+ stage.removeEventListener("pointerup", this.handle_pointer_up.bind(this));
290
+ stage.removeEventListener(
291
+ "pointerupoutside",
292
+ this.handle_pointer_up.bind(this)
293
+ );
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Gets the dimensions of the container
299
+ * @returns {Promise<{width: number, height: number}>} The container dimensions
300
+ * @private
301
+ */
302
+ private async get_container_dimensions(): Promise<{
303
+ width: number;
304
+ height: number;
305
+ }> {
306
+ const bounds = this.image_editor_context.image_container.getLocalBounds();
307
+ return {
308
+ width: bounds.width,
309
+ height: bounds.height
310
+ };
311
+ }
312
+
313
+ /**
314
+ * Calculates the minimum zoom level to fit the image in the viewport
315
+ * @param {number} container_width - The width of the container
316
+ * @param {number} container_height - The height of the container
317
+ * @returns {number} The minimum zoom level
318
+ * @private
319
+ */
320
+ private calculate_min_zoom(
321
+ container_width: number,
322
+ container_height: number
323
+ ): number {
324
+ const canvas = this.image_editor_context.app.screen;
325
+ const viewport_width = canvas.width;
326
+ const viewport_height = canvas.height;
327
+
328
+ if (
329
+ !container_width ||
330
+ !viewport_width ||
331
+ !container_height ||
332
+ !viewport_height
333
+ ) {
334
+ return 1;
335
+ }
336
+
337
+ const available_width = viewport_width - this.border_padding * 2;
338
+ const available_height =
339
+ viewport_height - this.border_padding * 2 - this.pad_bottom;
340
+
341
+ const width_ratio = available_width / container_width;
342
+ const height_ratio = available_height / container_height;
343
+
344
+ return Math.min(width_ratio, height_ratio);
345
+ }
346
+
347
+ /**
348
+ * Handles touch start events
349
+ * @param {TouchEvent} event - The touch event
350
+ * @private
351
+ */
352
+ private handle_touch_start(event: FederatedPointerEvent): void {
353
+ event.preventDefault();
354
+
355
+ const touchEvent = event as any;
356
+
357
+ if (touchEvent.touches && touchEvent.touches.length === 2) {
358
+ this.is_pinching = true;
359
+ this.last_pinch_distance = Math.hypot(
360
+ touchEvent.touches[0].pageX - touchEvent.touches[1].pageX,
361
+ touchEvent.touches[0].pageY - touchEvent.touches[1].pageY
362
+ );
363
+ } else if (touchEvent.touches && touchEvent.touches.length === 1) {
364
+ this.is_dragging = true;
365
+ const rect = this.image_editor_context.app.view.getBoundingClientRect();
366
+ this.last_touch_position = new Point(
367
+ touchEvent.touches[0].pageX - rect.left,
368
+ touchEvent.touches[0].pageY - rect.top
369
+ );
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Handles touch move events
375
+ * @param {TouchEvent} event - The touch event
376
+ * @private
377
+ */
378
+ private handle_touch_move(event: FederatedPointerEvent): void {
379
+ event.preventDefault();
380
+
381
+ const touchEvent = event as any;
382
+
383
+ if (
384
+ this.is_pinching &&
385
+ touchEvent.touches &&
386
+ touchEvent.touches.length === 2
387
+ ) {
388
+ const rect = this.image_editor_context.app.view.getBoundingClientRect();
389
+ const current_distance = Math.hypot(
390
+ touchEvent.touches[0].pageX - touchEvent.touches[1].pageX,
391
+ touchEvent.touches[0].pageY - touchEvent.touches[1].pageY
392
+ );
393
+
394
+ const pinch_center = {
395
+ x:
396
+ (touchEvent.touches[0].pageX + touchEvent.touches[1].pageX) / 2 -
397
+ rect.left,
398
+ y:
399
+ (touchEvent.touches[0].pageY + touchEvent.touches[1].pageY) / 2 -
400
+ rect.top
401
+ };
402
+
403
+ const scale_val = current_distance / this.last_pinch_distance;
404
+ this.last_pinch_distance = current_distance;
405
+
406
+ this.zoom_to_point(this.local_scale * scale_val, pinch_center);
407
+ } else if (
408
+ this.is_dragging &&
409
+ touchEvent.touches &&
410
+ touchEvent.touches.length === 1 &&
411
+ this.last_touch_position
412
+ ) {
413
+ const rect = this.image_editor_context.app.view.getBoundingClientRect();
414
+ const current_position = new Point(
415
+ touchEvent.touches[0].pageX - rect.left,
416
+ touchEvent.touches[0].pageY - rect.top
417
+ );
418
+
419
+ const dx = current_position.x - this.last_touch_position.x;
420
+ const dy = current_position.y - this.last_touch_position.y;
421
+
422
+ this.image_editor_context.set_image_properties({
423
+ position: {
424
+ x: this.local_position.x + dx,
425
+ y: this.local_position.y + dy
426
+ }
427
+ });
428
+
429
+ this.last_touch_position = current_position;
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Handles touch end events
435
+ * @param {TouchEvent} event - The touch event
436
+ * @private
437
+ */
438
+ private handle_touch_end(event: FederatedPointerEvent): void {
439
+ event.preventDefault();
440
+
441
+ const touchEvent = event as any;
442
+
443
+ if (touchEvent.touches && touchEvent.touches.length < 2) {
444
+ this.is_pinching = false;
445
+ if (touchEvent.touches && touchEvent.touches.length === 1) {
446
+ const rect = this.image_editor_context.app.view.getBoundingClientRect();
447
+ this.last_touch_position = new Point(
448
+ touchEvent.touches[0].pageX - rect.left,
449
+ touchEvent.touches[0].pageY - rect.top
450
+ );
451
+ this.is_dragging = true;
452
+ }
453
+ }
454
+ if (touchEvent.touches && touchEvent.touches.length === 0) {
455
+ this.is_dragging = false;
456
+ this.last_touch_position = null;
457
+ this.last_pinch_distance = 0;
458
+ }
459
+ }
460
+
461
+ /**
462
+ * Gets the bounded position to keep the image within the viewport
463
+ * @param {Object} position - The position to bound
464
+ * @param {number} position.x - The x coordinate
465
+ * @param {number} position.y - The y coordinate
466
+ * @returns {Object} The bounded position
467
+ * @private
468
+ */
469
+ private get_bounded_position(position: { x: number; y: number }): {
470
+ x: number;
471
+ y: number;
472
+ } {
473
+ const canvas = this.image_editor_context.app.screen;
474
+ const scaled_width = this.local_dimensions.width * this.local_scale;
475
+ const scaled_height = this.local_dimensions.height * this.local_scale;
476
+
477
+ const center_position = {
478
+ x: (canvas.width - scaled_width) / 2,
479
+ y: (canvas.height - scaled_height - this.pad_bottom) / 2
480
+ };
481
+
482
+ if (scaled_width <= canvas.width && scaled_height <= canvas.height) {
483
+ return center_position;
484
+ }
485
+
486
+ let x = position.x;
487
+ let y = position.y;
488
+
489
+ if (scaled_width <= canvas.width) {
490
+ x = center_position.x;
491
+ } else {
492
+ const min_x = canvas.width - scaled_width;
493
+ const max_x = 0;
494
+ x = Math.max(min_x, Math.min(max_x, position.x));
495
+ }
496
+
497
+ if (scaled_height <= canvas.height - this.pad_bottom) {
498
+ y = center_position.y;
499
+ } else {
500
+ const min_y = canvas.height - scaled_height - this.pad_bottom;
501
+ const max_y = 0;
502
+ y = Math.max(min_y, Math.min(max_y, position.y));
503
+ }
504
+
505
+ return { x, y };
506
+ }
507
+
508
+ /**
509
+ * Zooms to a specific point with a new zoom level
510
+ * @param {number} new_zoom - The new zoom level
511
+ * @param {Object} point - The point to zoom to
512
+ * @param {number} point.x - The x coordinate of the point
513
+ * @param {number} point.y - The y coordinate of the point
514
+ * @param {boolean} hard - Whether to apply a hard zoom (no animation)
515
+ * @param {boolean} is_fit_zoom - Whether this is a fit zoom operation
516
+ * @private
517
+ */
518
+ private zoom_to_point(
519
+ new_zoom: number,
520
+ point: { x: number; y: number },
521
+ hard?: boolean,
522
+ is_fit_zoom?: boolean
523
+ ): void {
524
+ const container = this.image_editor_context.image_container;
525
+ const current_world_pos = container.getGlobalPosition();
526
+ const current_scale = container.scale.x;
527
+
528
+ const cursor_image_pixel = {
529
+ x: (point.x - current_world_pos.x) / current_scale,
530
+ y: (point.y - current_world_pos.y) / current_scale
531
+ };
532
+
533
+ const fit_zoom = this.calculate_min_zoom(
534
+ this.local_dimensions.width,
535
+ this.local_dimensions.height
536
+ );
537
+ const min_zoom = Math.min(fit_zoom, 1);
538
+ new_zoom = Math.min(Math.max(new_zoom, min_zoom), this.max_zoom);
539
+
540
+ const new_container_world_pos = {
541
+ x: point.x - cursor_image_pixel.x * new_zoom,
542
+ y: point.y - cursor_image_pixel.y * new_zoom
543
+ };
544
+
545
+ if (new_zoom === min_zoom || is_fit_zoom) {
546
+ const canvas_width = this.image_editor_context.app.screen.width;
547
+ const canvas_height = this.image_editor_context.app.screen.height;
548
+ const new_scaled_width = this.local_dimensions.width * new_zoom;
549
+ const new_scaled_height = this.local_dimensions.height * new_zoom;
550
+
551
+ new_container_world_pos.x = (canvas_width - new_scaled_width) / 2;
552
+ new_container_world_pos.y =
553
+ (canvas_height - this.pad_bottom - new_scaled_height) / 2;
554
+ }
555
+
556
+ this.image_editor_context.set_image_properties({
557
+ scale: new_zoom,
558
+ position: new_container_world_pos,
559
+ animate: typeof hard === "boolean" ? !hard : new_zoom === min_zoom
560
+ });
561
+ this.min_zoom.set(new_zoom === min_zoom);
562
+ }
563
+
564
+ /**
565
+ * Handles pointer down events
566
+ * @param {FederatedPointerEvent} event - The pointer event
567
+ * @private
568
+ */
569
+ private handle_pointer_down(event: FederatedPointerEvent): void {
570
+ if (event.button === 0 && this.current_tool === "pan") {
571
+ this.is_pointer_dragging = true;
572
+ this.drag_start.copyFrom(event.global);
573
+ this.drag_start.x -= this.local_position.x;
574
+ this.drag_start.y -= this.local_position.y;
575
+ }
576
+ }
577
+
578
+ /**
579
+ * Handles pointer move events
580
+ * @param {FederatedPointerEvent} event - The pointer event
581
+ * @private
582
+ */
583
+ private handle_pointer_move(event: FederatedPointerEvent): void {
584
+ if (this.is_pointer_dragging && this.current_tool === "pan") {
585
+ const raw_position = {
586
+ x: event.global.x - this.drag_start.x,
587
+ y: event.global.y - this.drag_start.y
588
+ };
589
+
590
+ const canvas = this.image_editor_context.app.screen;
591
+ const scaled_width = this.local_dimensions.width * this.local_scale;
592
+ const scaled_height = this.local_dimensions.height * this.local_scale;
593
+ const available_width = canvas.width - this.border_padding * 2;
594
+ const available_height =
595
+ canvas.height - this.border_padding * 2 - this.pad_bottom;
596
+
597
+ let final_position = { ...raw_position };
598
+
599
+ if (scaled_width <= available_width) {
600
+ final_position.x = (canvas.width - scaled_width) / 2;
601
+ } else {
602
+ final_position.x = raw_position.x;
603
+ }
604
+
605
+ if (scaled_height <= available_height) {
606
+ final_position.y =
607
+ (canvas.height - this.pad_bottom - scaled_height) / 2;
608
+ } else {
609
+ final_position.y = raw_position.y;
610
+ }
611
+
612
+ this.image_editor_context.set_image_properties({
613
+ scale: this.local_scale,
614
+ position: final_position
615
+ });
616
+ }
617
+ }
618
+
619
+ /**
620
+ * Handles pointer up events
621
+ * @param {FederatedPointerEvent} event - The pointer event
622
+ * @private
623
+ */
624
+ private handle_pointer_up(event: FederatedPointerEvent): void {
625
+ if (this.is_pointer_dragging && this.current_tool === "pan") {
626
+ this.is_pointer_dragging = false;
627
+
628
+ const raw_position = {
629
+ x: event.global.x - this.drag_start.x,
630
+ y: event.global.y - this.drag_start.y
631
+ };
632
+
633
+ const canvas = this.image_editor_context.app.screen;
634
+ const scaled_width = this.local_dimensions.width * this.local_scale;
635
+ const scaled_height = this.local_dimensions.height * this.local_scale;
636
+ const available_width = canvas.width - this.border_padding * 2;
637
+ const available_height =
638
+ canvas.height - this.border_padding * 2 - this.pad_bottom;
639
+
640
+ let final_position = { ...raw_position };
641
+
642
+ if (scaled_width <= available_width) {
643
+ final_position.x = (canvas.width - scaled_width) / 2;
644
+ } else {
645
+ const max_offset = canvas.width / 2;
646
+ const left_bound = max_offset;
647
+ const right_bound = canvas.width - max_offset - scaled_width;
648
+ final_position.x = Math.min(
649
+ Math.max(raw_position.x, right_bound),
650
+ left_bound
651
+ );
652
+ }
653
+
654
+ if (scaled_height <= available_height) {
655
+ final_position.y =
656
+ (canvas.height - this.pad_bottom - scaled_height) / 2;
657
+ } else {
658
+ const max_offset = (canvas.height - this.pad_bottom) / 2;
659
+ const top_bound = max_offset;
660
+ const bottom_bound =
661
+ canvas.height - this.pad_bottom - max_offset - scaled_height;
662
+ final_position.y = Math.min(
663
+ Math.max(raw_position.y, bottom_bound),
664
+ top_bound
665
+ );
666
+ }
667
+
668
+ this.image_editor_context.set_image_properties({
669
+ scale: this.local_scale,
670
+ position: final_position,
671
+ animate: true
672
+ });
673
+ }
674
+ }
675
+ }
6.26.1/imageeditor/types.ts ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { SelectData, ShareData } from "@gradio/utils";
2
+ import type { ILoadingStatus as LoadingStatus } from "@gradio/statustracker";
3
+ import type { CommandNode } from "./shared/core/commands";
4
+ import type {
5
+ LayerOptions,
6
+ Source,
7
+ Transform,
8
+ WebcamOptions
9
+ } from "./shared/types";
10
+ import type { Brush, Eraser } from "./shared/brush/types";
11
+ import type { EditorData } from "./InteractiveImageEditor.svelte";
12
+ import type { ImageBlobs } from "./shared/types";
13
+
14
+ export interface ImageEditorEvents {
15
+ change: never;
16
+ error: string;
17
+ input: never;
18
+ edit: never;
19
+ drag: never;
20
+ apply: never;
21
+ upload: never;
22
+ clear: never;
23
+ select: SelectData;
24
+ share: ShareData;
25
+ clear_status: LoadingStatus;
26
+ }
27
+
28
+ export interface ImageEditorProps {
29
+ border_region?: number;
30
+ webcam_options?: WebcamOptions;
31
+ value?: EditorData | null;
32
+ buttons?: string[] | null;
33
+ height?: number;
34
+ width?: number;
35
+ _selectable?: boolean;
36
+ sources?: Source[];
37
+ placeholder?: string | undefined;
38
+ brush?: Brush;
39
+ eraser?: Eraser;
40
+ transforms?: Transform[];
41
+ layers?: LayerOptions;
42
+ server?: {
43
+ accept_blobs: (a: any) => void;
44
+ };
45
+ canvas_size?: [number, number];
46
+ fixed_canvas?: boolean;
47
+ full_history?: CommandNode | null;
48
+ }
49
+
50
+ // export let border_region = 0;
51
+ // export let webcam_options: WebcamOptions;
52
+ // export let value: EditorData | null = {
53
+ // background: null,
54
+ // layers: [],
55
+ // composite: null,
56
+ // };
57
+ // export let buttons: string[] | null = null;
58
+ // export let height = 350;
59
+ // export let width: number | undefined;
60
+
61
+ // export let _selectable = false;
62
+ // export let sources: Source[] = [];
63
+ // export let placeholder: string | undefined;
64
+ // export let brush: Brush;
65
+ // export let eraser: Eraser;
66
+ // export let transforms: Transform[] = [];
67
+ // export let layers: LayerOptions;
68
+ // export let attached_events: string[] = [];
69
+ // export let server: {
70
+ // accept_blobs: (a: any) => void;
71
+ // };
72
+ // export let canvas_size: [number, number];
73
+ // export let fixed_canvas = false;
74
+ // export let full_history: CommandNode | null = null;