@gradio/imageeditor 0.12.14 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/Example.svelte +1 -1
  3. package/IMAGE_EDITOR_OVERVIEW.md +224 -0
  4. package/ImageEditor.stories.svelte +13 -5
  5. package/Index.svelte +46 -45
  6. package/{shared/InteractiveImageEditor.svelte → InteractiveImageEditor.svelte} +65 -103
  7. package/README.md +2 -0
  8. package/dist/Example.svelte.d.ts +1 -1
  9. package/dist/Index.svelte +35 -33
  10. package/dist/Index.svelte.d.ts +25 -16
  11. package/dist/{shared/InteractiveImageEditor.svelte → InteractiveImageEditor.svelte} +54 -88
  12. package/dist/{shared/InteractiveImageEditor.svelte.d.ts → InteractiveImageEditor.svelte.d.ts} +17 -15
  13. package/dist/shared/Anchor.svelte +311 -0
  14. package/dist/shared/Anchor.svelte.d.ts +18 -0
  15. package/dist/shared/Controls.svelte +169 -18
  16. package/dist/shared/Controls.svelte.d.ts +9 -2
  17. package/dist/shared/{tools/IconButton.svelte → IconButton.svelte} +19 -3
  18. package/dist/shared/{tools/IconButton.svelte.d.ts → IconButton.svelte.d.ts} +4 -1
  19. package/dist/shared/ImageEditor.svelte +572 -289
  20. package/dist/shared/ImageEditor.svelte.d.ts +54 -56
  21. package/dist/shared/Layers.svelte +260 -0
  22. package/dist/shared/Layers.svelte.d.ts +37 -0
  23. package/dist/shared/Resize.svelte +218 -0
  24. package/dist/shared/Resize.svelte.d.ts +29 -0
  25. package/dist/shared/SecondaryToolbar.svelte +55 -0
  26. package/dist/shared/SecondaryToolbar.svelte.d.ts +37 -0
  27. package/dist/shared/Toolbar.svelte +337 -0
  28. package/dist/shared/Toolbar.svelte.d.ts +42 -0
  29. package/dist/shared/{tools → brush}/BrushOptions.svelte +68 -64
  30. package/dist/shared/{tools → brush}/BrushOptions.svelte.d.ts +9 -9
  31. package/dist/shared/{tools → brush}/BrushSize.svelte +2 -27
  32. package/dist/shared/{tools → brush}/ColorField.svelte +2 -1
  33. package/dist/shared/{tools → brush}/ColorField.svelte.d.ts +1 -0
  34. package/dist/shared/{tools → brush}/ColorPicker.svelte +81 -9
  35. package/dist/shared/{tools → brush}/ColorPicker.svelte.d.ts +1 -0
  36. package/dist/shared/{tools → brush}/ColorSwatch.svelte +78 -38
  37. package/dist/shared/{tools → brush}/ColorSwatch.svelte.d.ts +6 -2
  38. package/dist/shared/brush/brush-cursor.d.ts +101 -0
  39. package/dist/shared/brush/brush-cursor.js +327 -0
  40. package/dist/shared/brush/brush-textures.d.ts +65 -0
  41. package/dist/shared/brush/brush-textures.js +385 -0
  42. package/dist/shared/brush/brush-utils.d.ts +32 -0
  43. package/dist/shared/brush/brush-utils.js +59 -0
  44. package/dist/shared/brush/brush.d.ts +152 -0
  45. package/dist/shared/brush/brush.js +397 -0
  46. package/dist/shared/brush/types.d.ts +37 -0
  47. package/dist/shared/brush/types.js +1 -0
  48. package/dist/shared/core/editor.d.ts +261 -0
  49. package/dist/shared/core/editor.js +1264 -0
  50. package/dist/shared/crop/crop.d.ts +201 -0
  51. package/dist/shared/crop/crop.js +727 -0
  52. package/dist/shared/image/image.d.ts +89 -0
  53. package/dist/shared/image/image.js +183 -0
  54. package/dist/shared/resize/resize.d.ts +270 -0
  55. package/dist/shared/resize/resize.js +1413 -0
  56. package/dist/shared/types.d.ts +16 -0
  57. package/dist/shared/utils/pixi.d.ts +16 -57
  58. package/dist/shared/utils/pixi.js +15 -113
  59. package/dist/shared/zoom/zoom.d.ts +136 -0
  60. package/dist/shared/zoom/zoom.js +548 -0
  61. package/package.json +8 -7
  62. package/shared/Anchor.svelte +384 -0
  63. package/shared/Controls.svelte +178 -37
  64. package/shared/{tools/IconButton.svelte → IconButton.svelte} +21 -4
  65. package/shared/ImageEditor.svelte +712 -350
  66. package/shared/Layers.svelte +282 -0
  67. package/shared/Resize.svelte +239 -0
  68. package/shared/SecondaryToolbar.svelte +67 -0
  69. package/shared/Toolbar.svelte +386 -0
  70. package/shared/brush/BRUSH_TOOL.md +134 -0
  71. package/shared/brush/BrushOptions.svelte +200 -0
  72. package/shared/{tools → brush}/BrushSize.svelte +2 -30
  73. package/shared/{tools → brush}/ColorField.svelte +3 -1
  74. package/shared/{tools → brush}/ColorPicker.svelte +86 -9
  75. package/shared/{tools → brush}/ColorSwatch.svelte +95 -42
  76. package/shared/brush/brush-cursor.ts +408 -0
  77. package/shared/brush/brush-textures.ts +485 -0
  78. package/shared/brush/brush-utils.ts +76 -0
  79. package/shared/brush/brush.ts +510 -0
  80. package/shared/brush/types.ts +41 -0
  81. package/shared/core/EDITOR.md +182 -0
  82. package/shared/core/editor.ts +1788 -0
  83. package/shared/crop/CROP.md +139 -0
  84. package/shared/crop/crop.ts +1027 -0
  85. package/shared/image/IMAGE.md +135 -0
  86. package/shared/image/image.ts +298 -0
  87. package/shared/resize/resize.ts +1894 -0
  88. package/shared/types.ts +19 -0
  89. package/shared/utils/pixi.ts +19 -246
  90. package/shared/zoom/zoom.ts +729 -0
  91. package/dist/shared/layers/Layers.svelte +0 -231
  92. package/dist/shared/layers/Layers.svelte.d.ts +0 -18
  93. package/dist/shared/layers/utils.d.ts +0 -73
  94. package/dist/shared/layers/utils.js +0 -156
  95. package/dist/shared/tools/Brush.svelte +0 -215
  96. package/dist/shared/tools/Brush.svelte.d.ts +0 -29
  97. package/dist/shared/tools/Crop.svelte +0 -155
  98. package/dist/shared/tools/Crop.svelte.d.ts +0 -16
  99. package/dist/shared/tools/Cropper.svelte +0 -271
  100. package/dist/shared/tools/Cropper.svelte.d.ts +0 -41
  101. package/dist/shared/tools/Handle.svelte +0 -260
  102. package/dist/shared/tools/Handle.svelte.d.ts +0 -29
  103. package/dist/shared/tools/Sources.svelte +0 -257
  104. package/dist/shared/tools/Sources.svelte.d.ts +0 -34
  105. package/dist/shared/tools/Tools.svelte +0 -102
  106. package/dist/shared/tools/Tools.svelte.d.ts +0 -48
  107. package/dist/shared/tools/brush.d.ts +0 -62
  108. package/dist/shared/tools/brush.js +0 -133
  109. package/dist/shared/tools/crop.d.ts +0 -15
  110. package/dist/shared/tools/crop.js +0 -154
  111. package/dist/shared/tools/index.d.ts +0 -5
  112. package/dist/shared/tools/index.js +0 -5
  113. package/dist/shared/tools/sources.d.ts +0 -46
  114. package/dist/shared/tools/sources.js +0 -121
  115. package/dist/shared/tools/types.d.ts +0 -1
  116. package/shared/layers/Layers.svelte +0 -250
  117. package/shared/layers/utils.ts +0 -294
  118. package/shared/tools/Brush.svelte +0 -280
  119. package/shared/tools/BrushOptions.svelte +0 -180
  120. package/shared/tools/Crop.svelte +0 -189
  121. package/shared/tools/Cropper.svelte +0 -346
  122. package/shared/tools/Handle.svelte +0 -289
  123. package/shared/tools/Sources.svelte +0 -283
  124. package/shared/tools/Tools.svelte +0 -162
  125. package/shared/tools/brush.ts +0 -247
  126. package/shared/tools/crop.ts +0 -213
  127. package/shared/tools/index.ts +0 -5
  128. package/shared/tools/sources.ts +0 -195
  129. package/shared/tools/types.ts +0 -1
  130. /package/dist/shared/{tools → brush}/BrushSize.svelte.d.ts +0 -0
  131. /package/dist/shared/{tools/types.js → types.js} +0 -0
@@ -0,0 +1,1264 @@
1
+ import { Application, Container, Graphics, Sprite, Filter, RenderTexture, GlProgram, defaultFilterVert, SCALE_MODES, Texture, Assets } from "pixi.js";
2
+ import { DropShadowFilter as BlurFilter } from "pixi-filters/drop-shadow";
3
+ import { ImageTool } from "../image/image";
4
+ import { AddImageCommand } from "../image/image";
5
+ import { ZoomTool } from "../zoom/zoom";
6
+ import { spring } from "svelte/motion";
7
+ import { writable, get } from "svelte/store";
8
+ import { Rectangle } from "pixi.js";
9
+ import {} from "../types";
10
+ import { get_canvas_blob } from "../utils/pixi";
11
+ export class CommandManager {
12
+ undo_stack = [];
13
+ redo_stack = [];
14
+ async execute(command) {
15
+ await command.execute();
16
+ this.undo_stack.push(command);
17
+ this.redo_stack = []; // Clear redo stack when new command is executed
18
+ }
19
+ async undo() {
20
+ const command = this.undo_stack.pop();
21
+ if (command) {
22
+ await command.undo();
23
+ this.redo_stack.push(command);
24
+ }
25
+ }
26
+ async redo() {
27
+ const command = this.redo_stack.pop();
28
+ if (command) {
29
+ await command.execute();
30
+ this.undo_stack.push(command);
31
+ }
32
+ }
33
+ }
34
+ export class LayerManager {
35
+ layers = [];
36
+ active_layer = null;
37
+ active_layer_id = null;
38
+ draw_textures = new Map();
39
+ layer_store = writable({
40
+ active_layer: "",
41
+ layers: []
42
+ });
43
+ background_layer = null;
44
+ image_container;
45
+ app;
46
+ fixed_canvas;
47
+ dark;
48
+ border_region;
49
+ layer_options;
50
+ constructor(image_container, app, fixed_canvas, dark, border_region, layer_options) {
51
+ this.image_container = image_container;
52
+ this.app = app;
53
+ this.fixed_canvas = fixed_canvas;
54
+ this.dark = dark;
55
+ this.border_region = border_region;
56
+ this.layer_options = layer_options;
57
+ }
58
+ toggle_layer_visibility(id) {
59
+ const layer = this.layers.find((l) => l.id === id);
60
+ if (layer) {
61
+ layer.container.visible = !layer.container.visible;
62
+ layer.visible = layer.container.visible;
63
+ this.layer_store.update((state) => ({
64
+ active_layer: state.active_layer,
65
+ layers: this.layers
66
+ }));
67
+ }
68
+ }
69
+ create_background_layer(width, height) {
70
+ if (this.background_layer) {
71
+ this.background_layer.destroy();
72
+ }
73
+ // Create new background layer
74
+ const layer = new Container();
75
+ this.background_layer = layer;
76
+ // Create a render texture for the background with transparency
77
+ const bg_texture = RenderTexture.create({
78
+ width,
79
+ height,
80
+ resolution: window.devicePixelRatio,
81
+ antialias: true,
82
+ scaleMode: SCALE_MODES.NEAREST
83
+ });
84
+ // Create sprite to display the texture with transparency
85
+ const bg_sprite = new Sprite(bg_texture);
86
+ layer.addChild(bg_sprite);
87
+ // Clear the texture with transparency
88
+ const clear_graphics = new Graphics();
89
+ clear_graphics.clear();
90
+ clear_graphics
91
+ .rect(0, 0, width, height)
92
+ .fill({ color: this.dark ? 0x333333 : 0xffffff, alpha: 1 });
93
+ // Render with transparency
94
+ this.app.renderer.render({
95
+ container: clear_graphics,
96
+ target: bg_texture,
97
+ clear: true
98
+ });
99
+ this.image_container.addChild(layer);
100
+ layer.zIndex = -1;
101
+ this.update_layer_order();
102
+ return layer;
103
+ }
104
+ set_layer_options(layer_options, width, height) {
105
+ this.layer_options = layer_options;
106
+ this.reset_layers(width, height);
107
+ }
108
+ /**
109
+ * Creates a background layer from an image URL
110
+ * @param url The URL of the image to use as background
111
+ * @param width The width of the layer (if fixed_canvas is true)
112
+ * @param height The height of the layer (if fixed_canvas is true)
113
+ * @param borderRegion Minimum border region to add around the image for outpainting (in pixels)
114
+ * @returns A Promise that resolves to the background Container when the image is loaded
115
+ */
116
+ async create_background_layer_from_url(url, width, height) {
117
+ const layer = this.create_background_layer(width || this.image_container.width, height || this.image_container.height);
118
+ try {
119
+ const texture = await Texture.from(url);
120
+ const sprite = new Sprite(texture);
121
+ const imageWidth = sprite.texture.width;
122
+ const imageHeight = sprite.texture.height;
123
+ // Calculate dimensions based on whether canvas size is fixed
124
+ const containerWidth = width || this.image_container.width;
125
+ const containerHeight = height || this.image_container.height;
126
+ if (this.fixed_canvas) {
127
+ // If fixed canvas, fit the image within the specified dimensions minus border region
128
+ // Calculate aspect-preserving dimensions
129
+ const effectiveContainerWidth = Math.max(containerWidth - this.border_region * 2, 10);
130
+ const effectiveContainerHeight = Math.max(containerHeight - this.border_region * 2, 10);
131
+ const imageAspectRatio = imageWidth / imageHeight;
132
+ const containerAspectRatio = effectiveContainerWidth / effectiveContainerHeight;
133
+ let finalWidth, finalHeight;
134
+ let posX = this.border_region, // Start with border offset
135
+ posY = this.border_region;
136
+ if (imageWidth <= effectiveContainerWidth &&
137
+ imageHeight <= effectiveContainerHeight) {
138
+ // Image fits within container without scaling
139
+ finalWidth = imageWidth;
140
+ finalHeight = imageHeight;
141
+ }
142
+ else {
143
+ if (imageAspectRatio > containerAspectRatio) {
144
+ // Width is the limiting factor
145
+ finalWidth = effectiveContainerWidth;
146
+ finalHeight = effectiveContainerWidth / imageAspectRatio;
147
+ }
148
+ else {
149
+ // Height is the limiting factor
150
+ finalHeight = effectiveContainerHeight;
151
+ finalWidth = effectiveContainerHeight * imageAspectRatio;
152
+ }
153
+ }
154
+ // Center image within the effective container area (which already accounts for border)
155
+ posX += Math.round((effectiveContainerWidth - finalWidth) / 2);
156
+ posY += Math.round((effectiveContainerHeight - finalHeight) / 2);
157
+ sprite.width = finalWidth;
158
+ sprite.height = finalHeight;
159
+ sprite.position.set(posX, posY);
160
+ }
161
+ else {
162
+ // If not fixed canvas, use the natural dimensions of the image plus border
163
+ // Position starts at the border offset
164
+ sprite.position.set(this.border_region, this.border_region);
165
+ // We need to re-create the background layer with the actual image dimensions plus border
166
+ if (this.background_layer) {
167
+ this.background_layer.destroy();
168
+ }
169
+ // Create new layer with image dimensions plus border on all sides
170
+ const totalWidth = imageWidth + this.border_region * 2;
171
+ const totalHeight = imageHeight + this.border_region * 2;
172
+ const newLayer = this.create_background_layer(totalWidth, totalHeight);
173
+ sprite.width = imageWidth;
174
+ sprite.height = imageHeight;
175
+ newLayer.addChild(sprite);
176
+ return newLayer;
177
+ }
178
+ layer.addChild(sprite);
179
+ return layer;
180
+ }
181
+ catch (error) {
182
+ console.error("Error loading image from URL:", error);
183
+ return layer;
184
+ }
185
+ }
186
+ create_layer({ width, height, layer_name, user_created, layer_id = undefined, make_active = false }) {
187
+ const layer = new Container();
188
+ const _layer_id = layer_id || Math.random().toString(36).substring(2, 15);
189
+ const _layer_name = layer_name || `Layer ${this.layers.length + 1}`;
190
+ this.layers.push({
191
+ name: _layer_name,
192
+ id: _layer_id,
193
+ container: layer,
194
+ user_created,
195
+ visible: true
196
+ });
197
+ this.image_container.addChild(layer);
198
+ // Create a single render texture for drawing with transparency
199
+ const draw_texture = RenderTexture.create({
200
+ width,
201
+ height,
202
+ resolution: window.devicePixelRatio,
203
+ antialias: true,
204
+ scaleMode: SCALE_MODES.NEAREST
205
+ });
206
+ const canvas_sprite = new Sprite(draw_texture);
207
+ layer.addChild(canvas_sprite);
208
+ const clear_graphics = new Graphics();
209
+ clear_graphics.clear();
210
+ clear_graphics.beginFill(0, 0);
211
+ clear_graphics.drawRect(0, 0, width, height);
212
+ clear_graphics.endFill();
213
+ this.app.renderer.render({
214
+ container: clear_graphics,
215
+ target: draw_texture,
216
+ clear: true
217
+ });
218
+ // Store texture for drawing
219
+ this.draw_textures.set(layer, draw_texture);
220
+ this.update_layer_order();
221
+ if (make_active) {
222
+ this.set_active_layer(_layer_id);
223
+ }
224
+ this.layer_store.set({
225
+ active_layer: this.active_layer_id || "",
226
+ layers: this.layers
227
+ });
228
+ return layer;
229
+ }
230
+ /**
231
+ * Creates a new layer with an image loaded from a URL
232
+ * @param url The URL of the image to load
233
+ * @param borderRegion Minimum border region to add around the image for outpainting (in pixels)
234
+ * @returns A Promise that resolves to the layer ID
235
+ */
236
+ async add_layer_from_url(url) {
237
+ const { width, height } = this.image_container.getLocalBounds();
238
+ const layer = this.create_layer({
239
+ width,
240
+ height,
241
+ layer_name: "Layer 1",
242
+ user_created: true
243
+ });
244
+ const layerIndex = this.layers.findIndex((l) => l.container === layer);
245
+ if (layerIndex === -1) {
246
+ console.error("Could not find newly created layer");
247
+ return "";
248
+ }
249
+ const layerId = this.layers[layerIndex].id;
250
+ try {
251
+ const texture = await Assets.load(url);
252
+ const drawTexture = this.draw_textures.get(layer);
253
+ if (!drawTexture) {
254
+ console.error("No draw texture found for layer");
255
+ return layerId;
256
+ }
257
+ const sprite = new Sprite(texture);
258
+ const imageWidth = sprite.width;
259
+ const imageHeight = sprite.height;
260
+ let posX = this.border_region;
261
+ let posY = this.border_region;
262
+ // Calculate effective dimensions (accounting for border)
263
+ const effectiveWidth = this.fixed_canvas
264
+ ? width - this.border_region * 2
265
+ : width;
266
+ const effectiveHeight = this.fixed_canvas
267
+ ? height - this.border_region * 2
268
+ : height;
269
+ // If the image is smaller than the effective layer area, center it within that area
270
+ if (imageWidth < effectiveWidth || imageHeight < effectiveHeight) {
271
+ posX = Math.floor((effectiveWidth - imageWidth) / 2);
272
+ posY = Math.floor((effectiveHeight - imageHeight) / 2);
273
+ }
274
+ sprite.position.set(posX, posY);
275
+ // If the image is larger than the effective layer area, scale it down to fit
276
+ if (imageWidth > effectiveWidth || imageHeight > effectiveHeight) {
277
+ const imageAspectRatio = imageWidth / imageHeight;
278
+ const areaAspectRatio = effectiveWidth / effectiveHeight;
279
+ let finalWidth, finalHeight;
280
+ if (imageAspectRatio > areaAspectRatio) {
281
+ // Width is the limiting factor
282
+ finalWidth = effectiveWidth;
283
+ finalHeight = effectiveWidth / imageAspectRatio;
284
+ }
285
+ else {
286
+ // Height is the limiting factor
287
+ finalHeight = effectiveHeight;
288
+ finalWidth = effectiveHeight * imageAspectRatio;
289
+ }
290
+ sprite.width = finalWidth;
291
+ sprite.height = finalHeight;
292
+ // Recalculate position to center within effective area
293
+ posX =
294
+ this.border_region + Math.floor((effectiveWidth - finalWidth) / 2);
295
+ posY =
296
+ this.border_region + Math.floor((effectiveHeight - finalHeight) / 2);
297
+ sprite.position.set(posX, posY);
298
+ }
299
+ this.app.renderer.render(sprite, { renderTexture: drawTexture });
300
+ this.set_active_layer(layerId);
301
+ return layerId;
302
+ }
303
+ catch (error) {
304
+ console.error("Error loading image from URL:", error);
305
+ return layerId;
306
+ }
307
+ }
308
+ get_active_layer() {
309
+ return this.active_layer;
310
+ }
311
+ set_active_layer(id) {
312
+ if (this.layers.some((l) => l.id === id)) {
313
+ this.active_layer =
314
+ this.layers.find((l) => l.id === id)?.container ||
315
+ this.layers[0]?.container ||
316
+ null;
317
+ this.active_layer_id = id;
318
+ this.layer_store.set({
319
+ active_layer: id,
320
+ layers: this.layers
321
+ });
322
+ }
323
+ }
324
+ get_layers() {
325
+ return this.layers;
326
+ }
327
+ get_layer_textures(id) {
328
+ const layer = this.layers.find((l) => l.id === id);
329
+ if (layer) {
330
+ const draw = this.draw_textures.get(layer.container);
331
+ if (draw) {
332
+ return { draw };
333
+ }
334
+ }
335
+ return null;
336
+ }
337
+ delete_layer(id) {
338
+ const index = this.layers.findIndex((l) => l.id === id);
339
+ if (index > -1) {
340
+ // Clean up texture
341
+ const draw_texture = this.draw_textures.get(this.layers[index].container);
342
+ if (draw_texture) {
343
+ draw_texture.destroy();
344
+ this.draw_textures.delete(this.layers[index].container);
345
+ }
346
+ this.layers[index].container.destroy();
347
+ if (this.active_layer === this.layers[index].container) {
348
+ const new_active_layer = this.layers[Math.max(0, index - 1)] || null;
349
+ this.active_layer = new_active_layer?.container || null;
350
+ this.active_layer_id = new_active_layer?.id || null;
351
+ }
352
+ this.layers = this.layers.filter((l) => l.id !== id);
353
+ this.layer_store.update((_layers) => ({
354
+ active_layer: _layers.active_layer === id
355
+ ? this.layers[this.layers.length - 1]?.id
356
+ : _layers.active_layer,
357
+ layers: this.layers
358
+ }));
359
+ this.update_layer_order();
360
+ }
361
+ }
362
+ update_layer_order() {
363
+ // Ensure background layer always has lowest z-index
364
+ if (this.background_layer) {
365
+ this.background_layer.zIndex = -1;
366
+ }
367
+ // Update other layers starting from 0
368
+ this.layers.forEach((layer, index) => {
369
+ layer.container.zIndex = index;
370
+ });
371
+ }
372
+ move_layer(id, direction) {
373
+ const index = this.layers.findIndex((l) => l.id === id);
374
+ if (index > -1) {
375
+ const new_index = direction === "up" ? index - 1 : index + 1;
376
+ this.layers = this.layers.map((l, i) => {
377
+ if (i === index) {
378
+ return this.layers[new_index];
379
+ }
380
+ if (i === new_index) {
381
+ return this.layers[index];
382
+ }
383
+ return l;
384
+ });
385
+ this.update_layer_order();
386
+ this.layer_store.update((_layers) => ({
387
+ active_layer: id,
388
+ layers: this.layers
389
+ }));
390
+ }
391
+ }
392
+ /**
393
+ * Resizes all layers to a new width and height
394
+ * @param newWidth The new width of the layers
395
+ * @param newHeight The new height of the layers
396
+ * @param scale If true, scales the layer content to fit the new dimensions. If false, keeps the content size unchanged.
397
+ * @param anchor The anchor point to position the content relative to the new size
398
+ */
399
+ resize_all_layers(newWidth, newHeight, scale, anchor,
400
+ // Add old canvas dimensions for anchor calculations when not scaling
401
+ oldCanvasWidth, oldCanvasHeight) {
402
+ // Create a map of the old layers by ID for reference
403
+ const oldLayersById = new Map(this.layers.map((l) => [l.id, l]));
404
+ const oldBackgroundLayer = this.background_layer;
405
+ // Calculate offset for non-scaling resize based on anchor and dimension change
406
+ const calculateOffset = () => {
407
+ let offsetX = 0;
408
+ let offsetY = 0;
409
+ const deltaWidth = newWidth - oldCanvasWidth;
410
+ const deltaHeight = newHeight - oldCanvasHeight;
411
+ // Determine X offset based on anchor point
412
+ if (anchor.includes("left")) {
413
+ offsetX = 0;
414
+ }
415
+ else if (anchor.includes("right")) {
416
+ offsetX = deltaWidth;
417
+ }
418
+ else {
419
+ // center
420
+ offsetX = Math.floor(deltaWidth / 2);
421
+ }
422
+ // Determine Y offset based on anchor point
423
+ if (anchor.includes("top")) {
424
+ offsetY = 0;
425
+ }
426
+ else if (anchor.includes("bottom")) {
427
+ offsetY = deltaHeight;
428
+ }
429
+ else {
430
+ // center
431
+ offsetY = Math.floor(deltaHeight / 2);
432
+ }
433
+ return { offsetX, offsetY };
434
+ };
435
+ // First, handle the background layer using the helper method
436
+ // Note: create_background_layer called inside the helper might destroy the old one
437
+ this.background_layer = this._resize_background_layer(oldBackgroundLayer, // Pass the potentially null old layer
438
+ newWidth, newHeight, scale, calculateOffset);
439
+ // Now process regular layers
440
+ const processedLayers = [];
441
+ // Store old layer data before clearing the main arrays
442
+ const oldLayerData = this.layers.map((oldLayer) => ({
443
+ id: oldLayer.id,
444
+ name: oldLayer.name,
445
+ user_created: oldLayer.user_created,
446
+ texture: this.draw_textures.get(oldLayer.container),
447
+ container: oldLayer.container
448
+ }));
449
+ // Clear the current layers array and textures map. New layers will be added by the helper.
450
+ this.layers = [];
451
+ this.draw_textures.clear(); // Ensure map is cleared before helpers add to it
452
+ // Rebuild layers in the original order using the helper method
453
+ for (const oldData of oldLayerData) {
454
+ // The helper _resize_single_layer handles creating the new layer,
455
+ // drawing content, cleanup, and adding the new layer to this.layers.
456
+ // It returns null if resizing failed for that layer.
457
+ const newLayer = this._resize_single_layer(oldData, newWidth, newHeight, scale, calculateOffset);
458
+ if (newLayer) {
459
+ processedLayers.push(newLayer);
460
+ }
461
+ }
462
+ // Ensure the active layer still exists, otherwise select the top one
463
+ const currentActiveId = get(this.layer_store).active_layer;
464
+ const activeLayerExists = processedLayers.some((l) => l.id === currentActiveId);
465
+ if (!activeLayerExists && processedLayers.length > 0) {
466
+ this.set_active_layer(processedLayers[0].id); // Set to top layer (index 0 is bottom visually)
467
+ }
468
+ else if (processedLayers.length === 0) {
469
+ this.layer_store.update((s) => ({ ...s, active_layer: "" })); // No layers left
470
+ }
471
+ else {
472
+ // If the active layer still exists, just trigger an update to ensure consistency
473
+ this.layer_store.update((s) => ({ ...s }));
474
+ }
475
+ // Update Z-indices
476
+ this.update_layer_order();
477
+ // Final cleanup attempt - textures might need explicit destroy calls
478
+ // Using setTimeout allows the current execution stack to clear
479
+ setTimeout(() => {
480
+ // Attempt to force GC or resource cleanup if needed, though Pixi often handles this
481
+ Assets.cache.reset(); // Be careful with this, might clear too much
482
+ this.app.renderer.textureGC.run(); // Force texture garbage collection
483
+ }, 100);
484
+ }
485
+ /**
486
+ * Helper method to resize the background layer.
487
+ */
488
+ _resize_background_layer(oldBackgroundLayer, newWidth, newHeight, scale, calculateOffset) {
489
+ if (!oldBackgroundLayer) {
490
+ // If no old background layer existed, create a new one
491
+ return this.create_background_layer(newWidth, newHeight);
492
+ }
493
+ // Identify the actual image sprite within the background container
494
+ let backgroundImage = oldBackgroundLayer.children.find((child) => child instanceof Sprite &&
495
+ child.texture !== oldBackgroundLayer.children[0]?.texture);
496
+ // Create the new background layer first (this also destroys the old one implicitly if it exists)
497
+ const newBackgroundLayer = this.create_background_layer(newWidth, newHeight);
498
+ if (backgroundImage) {
499
+ const newBgImage = new Sprite(backgroundImage.texture);
500
+ newBgImage.width = backgroundImage.width; // Preserve original size unless scaling
501
+ newBgImage.height = backgroundImage.height;
502
+ if (scale) {
503
+ newBgImage.width = newWidth;
504
+ newBgImage.height = newHeight;
505
+ newBgImage.position.set(0, 0);
506
+ }
507
+ else {
508
+ const { offsetX, offsetY } = calculateOffset();
509
+ newBgImage.position.set(backgroundImage.x + offsetX, backgroundImage.y + offsetY);
510
+ }
511
+ newBackgroundLayer.addChild(newBgImage);
512
+ }
513
+ // If no background image, the new layer created above is already blank and correctly sized.
514
+ return newBackgroundLayer;
515
+ }
516
+ /**
517
+ * Helper method to resize a single regular layer.
518
+ */
519
+ _resize_single_layer(oldData, newWidth, newHeight, scale, calculateOffset) {
520
+ if (!oldData.texture) {
521
+ console.warn(`No texture found for layer ${oldData.id}, skipping cleanup.`);
522
+ // Destroy the old container if it exists and is not destroyed
523
+ if (oldData.container && !oldData.container.destroyed) {
524
+ if (this.image_container.children.includes(oldData.container)) {
525
+ this.image_container.removeChild(oldData.container);
526
+ }
527
+ oldData.container.destroy({ children: true });
528
+ }
529
+ return null;
530
+ }
531
+ // Create a new layer container and associated render texture
532
+ const newContainer = this.create_layer({
533
+ // This adds the layer to this.layers and draw_textures
534
+ width: newWidth,
535
+ height: newHeight,
536
+ layer_name: oldData.name,
537
+ user_created: oldData.user_created
538
+ });
539
+ // Retrieve the newly created layer data (it's the last one added by create_layer)
540
+ const newLayer = this.layers[this.layers.length - 1];
541
+ newLayer.id = oldData.id; // Restore the original ID
542
+ // Get the render texture for the new layer
543
+ const newTexture = this.draw_textures.get(newContainer);
544
+ if (!newTexture) {
545
+ console.error(`Failed to get texture for newly created layer ${newLayer.id}. Cleaning up.`);
546
+ // Clean up the partially created new layer resources
547
+ if (newContainer && !newContainer.destroyed) {
548
+ if (this.image_container.children.includes(newContainer)) {
549
+ this.image_container.removeChild(newContainer);
550
+ }
551
+ newContainer.destroy({ children: true });
552
+ const idx = this.layers.findIndex((l) => l.container === newContainer);
553
+ if (idx > -1)
554
+ this.layers.splice(idx, 1);
555
+ this.draw_textures.delete(newContainer);
556
+ }
557
+ // Clean up old resources
558
+ if (oldData.texture && !oldData.texture.destroyed)
559
+ oldData.texture.destroy(true);
560
+ if (oldData.container && !oldData.container.destroyed)
561
+ oldData.container.destroy({ children: true });
562
+ return null;
563
+ }
564
+ // Explicitly clear the new render texture (create_layer might already do this, but explicit is safer)
565
+ this.app.renderer.clear({ target: newTexture, clearColor: [0, 0, 0, 0] });
566
+ // Create a sprite with the old texture content
567
+ const sprite = new Sprite(oldData.texture);
568
+ if (scale) {
569
+ sprite.width = newWidth;
570
+ sprite.height = newHeight;
571
+ sprite.position.set(0, 0);
572
+ }
573
+ else {
574
+ const { offsetX, offsetY } = calculateOffset();
575
+ sprite.position.set(offsetX, offsetY);
576
+ }
577
+ // Render the sprite onto the new texture
578
+ this.app.renderer.render(sprite, { renderTexture: newTexture });
579
+ // Clean up temporary sprite and old resources
580
+ sprite.destroy();
581
+ if (oldData.texture && !oldData.texture.destroyed) {
582
+ oldData.texture.destroy(true);
583
+ }
584
+ if (oldData.container && !oldData.container.destroyed) {
585
+ if (this.image_container.children.includes(oldData.container)) {
586
+ this.image_container.removeChild(oldData.container);
587
+ }
588
+ oldData.container.destroy({ children: true });
589
+ }
590
+ // Return the data for the successfully resized layer
591
+ return newLayer;
592
+ }
593
+ async get_blobs(width, height) {
594
+ const blobs = {
595
+ background: await get_canvas_blob(this.app.renderer, this.background_layer, {
596
+ width,
597
+ height,
598
+ x: 0,
599
+ y: 0
600
+ }),
601
+ layers: await Promise.all(this.layers.map(async (layer) => {
602
+ const blob = await get_canvas_blob(this.app.renderer, layer.container, {
603
+ width,
604
+ height,
605
+ x: 0,
606
+ y: 0
607
+ });
608
+ if (blob) {
609
+ return blob;
610
+ }
611
+ return null;
612
+ })),
613
+ composite: await get_canvas_blob(this.app.renderer, this.image_container)
614
+ };
615
+ return blobs;
616
+ }
617
+ reset_layers(width, height, persist = false) {
618
+ const _layers_to_recreate = persist
619
+ ? this.layers.map((layer) => [layer.name, layer.id])
620
+ : this.layer_options.layers.map((layer) => [layer, undefined]);
621
+ this.layers.forEach((layer) => {
622
+ this.delete_layer(layer.id);
623
+ });
624
+ for (const [layer_name, layer_id] of _layers_to_recreate) {
625
+ this.create_layer({
626
+ width,
627
+ height,
628
+ layer_name: layer_name,
629
+ user_created: this.layer_options.layers.find((l) => l === layer_name)
630
+ ? false
631
+ : true,
632
+ layer_id: layer_id
633
+ });
634
+ }
635
+ if (!persist) {
636
+ this.active_layer = this.layers[0].container;
637
+ this.active_layer_id = this.layers[0].id;
638
+ }
639
+ this.layer_store.update((state) => ({
640
+ active_layer: this.active_layer_id || this.layers[0].id,
641
+ layers: this.layers
642
+ }));
643
+ }
644
+ init_layers(width, height) {
645
+ for (const layer of this.layers) {
646
+ this.delete_layer(layer.id);
647
+ }
648
+ for (const layer of this.layer_options.layers) {
649
+ this.create_layer({
650
+ width,
651
+ height,
652
+ layer_name: layer,
653
+ user_created: false
654
+ });
655
+ }
656
+ this.active_layer = this.layers[0].container;
657
+ this.active_layer_id = this.layers[0].id;
658
+ this.layer_store.update((_layers) => ({
659
+ active_layer: this.layers[0].id,
660
+ layers: this.layers
661
+ }));
662
+ }
663
+ }
664
+ const core_tools = ["image", "zoom"];
665
+ const core_tool_map = {
666
+ image: () => new ImageTool(),
667
+ zoom: () => new ZoomTool()
668
+ };
669
+ const spring_config = {
670
+ stiffness: 0.45,
671
+ damping: 0.8
672
+ };
673
+ class EditorState {
674
+ state;
675
+ scale;
676
+ position;
677
+ subscribers;
678
+ constructor(editor) {
679
+ if (!(editor instanceof ImageEditor)) {
680
+ throw new Error("EditorState must be created by ImageEditor");
681
+ }
682
+ // Store private data
683
+ this.scale = 1.0;
684
+ this.position = { x: 0, y: 0 };
685
+ this.subscribers = new Set();
686
+ // @ts-ignore
687
+ this.state = Object.freeze({
688
+ get position() {
689
+ return { ...this.position };
690
+ },
691
+ get scale() {
692
+ return this.scale;
693
+ },
694
+ get current_tool() {
695
+ return this.current_tool;
696
+ },
697
+ get current_subtool() {
698
+ return this.current_subtool;
699
+ },
700
+ subscribe: this.subscribe.bind(this)
701
+ });
702
+ }
703
+ // Internal methods - only accessible to EditorState class
704
+ _set_position(x, y) {
705
+ const oldPosition = { ...this.position };
706
+ this.position = { x, y };
707
+ this._notify_subscribers("position", oldPosition, this.position);
708
+ }
709
+ _set_scale(scale) {
710
+ const oldScale = this.scale;
711
+ this.scale = scale;
712
+ this._notify_subscribers("scale", oldScale, scale);
713
+ }
714
+ _notify_subscribers(property, oldValue, newValue) {
715
+ this.subscribers.forEach((callback) => {
716
+ callback({
717
+ property,
718
+ oldValue,
719
+ newValue,
720
+ timestamp: Date.now()
721
+ });
722
+ });
723
+ }
724
+ // Public method but only affects notifications
725
+ subscribe(callback) {
726
+ this.subscribers.add(callback);
727
+ return () => this.subscribers.delete(callback);
728
+ }
729
+ }
730
+ export class ImageEditor {
731
+ ready;
732
+ background_image_present = writable(false);
733
+ min_zoom = writable(true);
734
+ app;
735
+ ui_container;
736
+ image_container;
737
+ command_manager;
738
+ layer_manager;
739
+ tools = new Map();
740
+ current_tool;
741
+ current_subtool;
742
+ target_element;
743
+ width;
744
+ height;
745
+ dimensions;
746
+ scale;
747
+ position;
748
+ state;
749
+ scale_value = 1;
750
+ position_value = { x: 0, y: 0 };
751
+ dimensions_value = {
752
+ width: 0,
753
+ height: 0
754
+ };
755
+ layers = writable({
756
+ active_layer: "",
757
+ layers: []
758
+ });
759
+ outline_container;
760
+ outline_graphics;
761
+ background_image;
762
+ ready_resolve;
763
+ event_callbacks = new Map();
764
+ fixed_canvas;
765
+ dark;
766
+ border_region;
767
+ layer_options;
768
+ overlay_container;
769
+ overlay_graphics;
770
+ pad_bottom;
771
+ theme_mode;
772
+ constructor(options) {
773
+ this.pad_bottom = options.pad_bottom || 0;
774
+ this.dark = options.dark || false;
775
+ this.theme_mode = options.theme_mode || "dark";
776
+ this.target_element = options.target_element;
777
+ this.width = options.width;
778
+ this.height = options.height;
779
+ this.command_manager = new CommandManager();
780
+ this.ready = new Promise((resolve) => {
781
+ this.ready_resolve = resolve;
782
+ });
783
+ this.fixed_canvas = options.fixed_canvas || false;
784
+ this.tools = new Map(options.tools.map((tool) => {
785
+ if (typeof tool === "string") {
786
+ return [tool, core_tool_map[tool]()];
787
+ }
788
+ return [tool.name, tool];
789
+ }));
790
+ for (const tool of this.tools.values()) {
791
+ if (tool?.on) {
792
+ tool.on("change", () => {
793
+ this.notify("change");
794
+ });
795
+ }
796
+ }
797
+ this.dimensions = spring({ width: this.width, height: this.height }, spring_config);
798
+ this.scale = spring(1, spring_config);
799
+ this.position = spring({ x: 0, y: 0 }, spring_config);
800
+ this.state = new EditorState(this);
801
+ this.border_region = options.border_region || 0;
802
+ this.layer_options = options.layer_options || {
803
+ allow_additional_layers: true,
804
+ layers: ["Layer 1"],
805
+ disabled: false
806
+ };
807
+ this.scale.subscribe((scale) => {
808
+ this.state._set_scale(scale);
809
+ });
810
+ this.position.subscribe((position) => {
811
+ this.state._set_position(position.x, position.y);
812
+ });
813
+ this.init();
814
+ }
815
+ get context() {
816
+ const editor = this;
817
+ return {
818
+ app: this.app,
819
+ ui_container: this.ui_container,
820
+ image_container: this.image_container,
821
+ get background_image() {
822
+ return editor.background_image;
823
+ },
824
+ pad_bottom: this.pad_bottom,
825
+ command_manager: this.command_manager,
826
+ layer_manager: this.layer_manager,
827
+ dimensions: { subscribe: this.dimensions.subscribe },
828
+ scale: { subscribe: this.scale.subscribe },
829
+ position: { subscribe: this.position.subscribe },
830
+ set_image_properties: this.set_image_properties.bind(this),
831
+ execute_command: this.execute_command.bind(this),
832
+ resize_canvas: this.resize_canvas.bind(this),
833
+ reset: this.reset.bind(this),
834
+ set_background_image: this.set_background_image.bind(this)
835
+ };
836
+ }
837
+ async init() {
838
+ const container_box = this.target_element.getBoundingClientRect();
839
+ new ResizeObserver((entries) => {
840
+ entries.forEach((entry) => {
841
+ this.resize_canvas(entry.contentBoxSize[0].inlineSize, entry.contentBoxSize[0].blockSize);
842
+ });
843
+ }).observe(this.target_element);
844
+ this.app = new Application();
845
+ await this.app.init({
846
+ width: container_box.width,
847
+ height: container_box.height,
848
+ backgroundAlpha: this.dark ? 0 : 1,
849
+ backgroundColor: this.theme_mode === "dark" ? "#27272a" : "#ffffff",
850
+ resolution: window.devicePixelRatio,
851
+ autoDensity: true,
852
+ antialias: true,
853
+ powerPreference: "high-performance"
854
+ });
855
+ // Set canvas properties
856
+ const canvas = this.app.canvas;
857
+ canvas.style.background = "transparent";
858
+ await this.setup_containers();
859
+ //create background layer
860
+ this.layer_manager.create_background_layer(this.width, this.height);
861
+ // Create initial layer
862
+ this.layer_manager.init_layers(this.width, this.height);
863
+ for (const tool of this.tools.values()) {
864
+ await tool.setup(this.context, this.current_tool, this.current_subtool);
865
+ }
866
+ const zoom = this.tools.get("zoom");
867
+ if (zoom) {
868
+ zoom.min_zoom.subscribe((is_min_zoom) => {
869
+ this.min_zoom.set(is_min_zoom);
870
+ });
871
+ }
872
+ this.target_element.appendChild(canvas);
873
+ // Ensure parent element is transparent
874
+ this.target_element.style.background = "transparent";
875
+ this.dimensions.subscribe((dimensions) => {
876
+ this.dimensions_value = dimensions;
877
+ this.image_container.width = dimensions.width;
878
+ this.image_container.height = dimensions.height;
879
+ });
880
+ this.scale.subscribe((scale) => {
881
+ this.scale_value = scale;
882
+ });
883
+ this.position.subscribe((position) => {
884
+ this.position_value = position;
885
+ });
886
+ this.app.ticker.add(() => {
887
+ this.image_container.scale.set(this.scale_value);
888
+ this.image_container.position.set(this.position_value.x, this.position_value.y);
889
+ const effective_width = this.dimensions_value.width * this.scale_value;
890
+ const effective_height = this.dimensions_value.height * this.scale_value;
891
+ // Convert image_container's position (in stage space) to outline_container local coordinates.
892
+ const local_x = Math.round(this.image_container.position.x - this.outline_container.position.x);
893
+ const local_y = Math.round(this.image_container.position.y - this.outline_container.position.y);
894
+ // Make sure overlay container follows the same position as outline container
895
+ this.overlay_container.position.set(this.outline_container.position.x, this.outline_container.position.y);
896
+ this.outline_graphics.clear();
897
+ this.outline_graphics
898
+ .rect(local_x, local_y, effective_width, effective_height)
899
+ .fill({
900
+ color: this.dark ? 0x333333 : 0xffffff,
901
+ alpha: 1
902
+ });
903
+ // Draw border region indicator if border_region > 0
904
+ if (this.border_region > 0) {
905
+ const scaled_border = this.border_region * this.scale_value;
906
+ const border_x = local_x + scaled_border - 1;
907
+ const border_y = local_y + scaled_border - 1;
908
+ const border_width = effective_width - scaled_border * 2 + 1;
909
+ const border_height = effective_height - scaled_border * 2 + 1;
910
+ // Clear previous overlay graphics
911
+ this.overlay_graphics.clear();
912
+ // Draw border rectangle using pixelLine for crisp 1px outline
913
+ this.overlay_graphics
914
+ .rect(border_x, border_y, border_width, border_height)
915
+ .stroke({
916
+ color: 0x999999,
917
+ width: 1,
918
+ alpha: 0,
919
+ pixelLine: true
920
+ });
921
+ // Create dashed line effect by drawing small rects along the border
922
+ const dashLength = 5;
923
+ const gapLength = 5;
924
+ const totalLength = dashLength + gapLength;
925
+ const lineColor = 0x999999;
926
+ // Draw dashed horizontal lines (top and bottom)
927
+ for (let x = border_x; x < border_x + border_width; x += totalLength) {
928
+ // Top dash
929
+ this.overlay_graphics
930
+ .rect(x, border_y, Math.min(dashLength, border_x + border_width - x), 1)
931
+ .fill({ color: lineColor, alpha: 0.7 });
932
+ // Bottom dash
933
+ this.overlay_graphics
934
+ .rect(x, border_y + border_height, Math.min(dashLength, border_x + border_width - x), 1)
935
+ .fill({ color: lineColor, alpha: 0.7 });
936
+ }
937
+ // Draw dashed vertical lines (left and right)
938
+ for (let y = border_y; y < border_y + border_height; y += totalLength) {
939
+ // Left dash
940
+ this.overlay_graphics
941
+ .rect(border_x, y, 1, Math.min(dashLength, border_y + border_height - y))
942
+ .fill({ color: lineColor, alpha: 0.7 });
943
+ // Right dash
944
+ this.overlay_graphics
945
+ .rect(border_x + border_width, y, 1, Math.min(dashLength, border_y + border_height - y))
946
+ .fill({ color: lineColor, alpha: 0.7 });
947
+ }
948
+ }
949
+ else {
950
+ // Clear overlay graphics if no border region
951
+ this.overlay_graphics.clear();
952
+ }
953
+ });
954
+ this.ready_resolve();
955
+ }
956
+ async setup_containers() {
957
+ this.image_container = new Container({
958
+ eventMode: "static",
959
+ sortableChildren: true
960
+ });
961
+ this.image_container.width = this.width;
962
+ this.image_container.height = this.height;
963
+ this.app.stage.sortableChildren = true;
964
+ this.app.stage.alpha = 1;
965
+ this.app.stage.addChild(this.image_container);
966
+ this.image_container.scale.set(1);
967
+ this.ui_container = new Container({
968
+ eventMode: "static"
969
+ });
970
+ this.app.stage.addChild(this.ui_container);
971
+ this.ui_container.width = this.width;
972
+ this.ui_container.height = this.height;
973
+ this.outline_container = new Container();
974
+ this.outline_container.zIndex = -10;
975
+ this.outline_graphics = new Graphics();
976
+ this.outline_graphics.rect(0, 0, this.width, this.height).fill({
977
+ color: this.dark ? 0x333333 : 0xffffff,
978
+ alpha: 0
979
+ });
980
+ if (!this.dark) {
981
+ const blurFilter = new BlurFilter({
982
+ alpha: 0.1,
983
+ blur: 2,
984
+ color: 0x000000,
985
+ offset: { x: 0, y: 0 },
986
+ quality: 4,
987
+ shadowOnly: false
988
+ });
989
+ this.outline_graphics.filters = [blurFilter];
990
+ }
991
+ this.outline_container.addChild(this.outline_graphics);
992
+ this.app.stage.addChild(this.outline_container);
993
+ this.overlay_container = new Container();
994
+ this.app.stage.addChild(this.overlay_container);
995
+ this.overlay_container.width = this.width;
996
+ this.overlay_container.height = this.height;
997
+ this.overlay_container.zIndex = 999;
998
+ this.overlay_container.eventMode = "static";
999
+ this.overlay_container.interactiveChildren = true;
1000
+ this.overlay_graphics = new Graphics();
1001
+ this.overlay_container.addChild(this.overlay_graphics);
1002
+ this.overlay_graphics.rect(0, 0, this.width, this.height).fill({
1003
+ color: 0x000000,
1004
+ alpha: 0
1005
+ });
1006
+ const app_center_x = this.app.screen.width / 2;
1007
+ const app_center_y = this.app.screen.height / 2;
1008
+ this.image_container.position.set(app_center_x, app_center_y);
1009
+ this.outline_container.position.set(app_center_x, app_center_y);
1010
+ this.layer_manager = new LayerManager(this.image_container, this.app, this.fixed_canvas, this.dark, this.border_region, this.layer_options);
1011
+ this.layers = this.layer_manager.layer_store;
1012
+ }
1013
+ resize_canvas(width, height) {
1014
+ if (this.app.renderer) {
1015
+ this.app.renderer.resize(width, height);
1016
+ }
1017
+ // Instead, update the container position to stay centered
1018
+ const app_center_x = width / 2;
1019
+ const app_center_y = height / 2;
1020
+ if (this.image_container) {
1021
+ this.image_container.position.set(app_center_x, app_center_y);
1022
+ }
1023
+ if (this.outline_container) {
1024
+ this.outline_container.position.set(app_center_x, app_center_y);
1025
+ }
1026
+ }
1027
+ reset() {
1028
+ const zoom = this.tools.get("zoom");
1029
+ if (zoom) {
1030
+ zoom.cleanup();
1031
+ zoom.setup(this.context, this.current_tool, this.current_subtool);
1032
+ }
1033
+ }
1034
+ async set_image_properties(properties) {
1035
+ let hard = typeof properties.animate !== "undefined" ? !properties.animate : true;
1036
+ if (properties.position) {
1037
+ const pos = this.position.set(properties.position, { hard });
1038
+ if (hard) {
1039
+ await pos;
1040
+ }
1041
+ }
1042
+ if (properties.scale) {
1043
+ const scale = this.scale.set(properties.scale, { hard });
1044
+ if (hard) {
1045
+ await scale;
1046
+ }
1047
+ }
1048
+ if (properties.width && properties.height) {
1049
+ this.width = properties.width;
1050
+ this.height = properties.height;
1051
+ const dimensions = this.dimensions.set({ width: properties.width, height: properties.height }, { hard });
1052
+ if (hard) {
1053
+ await dimensions;
1054
+ }
1055
+ }
1056
+ }
1057
+ async execute_command(command) {
1058
+ await this.command_manager.execute(command);
1059
+ }
1060
+ undo() {
1061
+ this.command_manager.undo();
1062
+ this.notify("change");
1063
+ }
1064
+ redo() {
1065
+ this.command_manager.redo();
1066
+ this.notify("change");
1067
+ }
1068
+ async add_image({ image, resize = true }) {
1069
+ const image_tool = this.tools.get("image");
1070
+ await image_tool.add_image({
1071
+ image,
1072
+ fixed_canvas: this.fixed_canvas,
1073
+ border_region: this.border_region
1074
+ });
1075
+ }
1076
+ /**
1077
+ * Adds an image from a URL as the background layer
1078
+ * @param url The URL of the image to add
1079
+ */
1080
+ async add_image_from_url(url) {
1081
+ const image_tool = this.tools.get("image");
1082
+ const texture = await Assets.load(url);
1083
+ await image_tool.add_image({
1084
+ image: texture,
1085
+ fixed_canvas: this.fixed_canvas,
1086
+ border_region: this.border_region
1087
+ });
1088
+ // Update resize tool if present
1089
+ const resize_tool = this.tools.get("resize");
1090
+ if (resize_tool && typeof resize_tool.set_border_region === "function") {
1091
+ resize_tool.set_border_region(this.border_region);
1092
+ }
1093
+ this.notify("change");
1094
+ this.notify("input");
1095
+ }
1096
+ set_tool(tool) {
1097
+ this.current_tool = tool;
1098
+ for (const tool of this.tools.values()) {
1099
+ tool.set_tool(this.current_tool, this.current_subtool);
1100
+ }
1101
+ }
1102
+ set_subtool(subtool) {
1103
+ this.current_subtool = subtool;
1104
+ for (const tool of this.tools.values()) {
1105
+ tool.set_tool(this.current_tool, this.current_subtool);
1106
+ }
1107
+ }
1108
+ set_background_image(image) {
1109
+ this.background_image = image;
1110
+ }
1111
+ async reset_canvas() {
1112
+ this.layer_manager.reset_layers(this.width, this.height);
1113
+ // Clear background image
1114
+ this.background_image = undefined;
1115
+ this.background_image_present.set(false);
1116
+ // Reset position, scale and dimensions to default values
1117
+ await this.set_image_properties({
1118
+ width: this.width,
1119
+ height: this.height,
1120
+ scale: 1,
1121
+ position: { x: 0, y: 0 },
1122
+ animate: false
1123
+ });
1124
+ // Reset command stacks
1125
+ this.command_manager = new CommandManager();
1126
+ //create background layer
1127
+ this.layer_manager.create_background_layer(this.width, this.height);
1128
+ // Reset tools
1129
+ for (const tool of this.tools.values()) {
1130
+ tool.cleanup();
1131
+ tool.setup(this.context, this.current_tool, this.current_subtool);
1132
+ }
1133
+ const zoom_tool = this.tools.get("zoom");
1134
+ if (zoom_tool) {
1135
+ zoom_tool.min_zoom.subscribe((is_min_zoom) => {
1136
+ this.min_zoom.set(is_min_zoom);
1137
+ });
1138
+ }
1139
+ this.notify("change");
1140
+ }
1141
+ add_layer() {
1142
+ this.layer_manager.create_layer({
1143
+ width: this.width,
1144
+ height: this.height,
1145
+ layer_name: undefined,
1146
+ user_created: true,
1147
+ layer_id: undefined,
1148
+ make_active: true
1149
+ });
1150
+ this.notify("change");
1151
+ }
1152
+ /**
1153
+ * Adds a new layer with an image loaded from a URL
1154
+ * @param layer_urls The URLs of the images to load
1155
+ * @returns A Promise that resolves when all layers are added
1156
+ */
1157
+ async add_layers_from_url(layer_urls) {
1158
+ const _layers = this.layer_manager.get_layers();
1159
+ _layers.forEach((l) => this.layer_manager.delete_layer(l.id));
1160
+ if (layer_urls === undefined || layer_urls.length === 0) {
1161
+ this.layer_manager.create_layer({
1162
+ width: this.width,
1163
+ height: this.height,
1164
+ layer_name: undefined,
1165
+ user_created: false
1166
+ });
1167
+ return;
1168
+ }
1169
+ for await (const url of layer_urls) {
1170
+ await this.layer_manager.add_layer_from_url(url);
1171
+ }
1172
+ this.layer_manager.set_active_layer(_layers[0].id);
1173
+ // Update resize tool if present with border region
1174
+ const resize_tool = this.tools.get("resize");
1175
+ if (resize_tool && typeof resize_tool.set_border_region === "function") {
1176
+ resize_tool.set_border_region(this.border_region);
1177
+ }
1178
+ this.notify("change");
1179
+ this.notify("input");
1180
+ }
1181
+ set_layer(id) {
1182
+ this.layer_manager.set_active_layer(id);
1183
+ this.notify("change");
1184
+ }
1185
+ move_layer(id, direction) {
1186
+ this.layer_manager.move_layer(id, direction);
1187
+ this.notify("change");
1188
+ }
1189
+ delete_layer(id) {
1190
+ this.layer_manager.delete_layer(id);
1191
+ this.notify("change");
1192
+ }
1193
+ modify_canvas_size(width, height, anchor, scale) {
1194
+ // Store old dimensions before updating
1195
+ const oldWidth = this.width;
1196
+ const oldHeight = this.height;
1197
+ // Resize layers first, passing old dimensions for anchor calculation
1198
+ this.layer_manager.resize_all_layers(width, height, scale, anchor, oldWidth, oldHeight);
1199
+ // Update the editor's main dimension tracking *after* resizing layers
1200
+ this.width = width;
1201
+ this.height = height;
1202
+ // Update the dimensions store and reset view scale/position
1203
+ this.set_image_properties({
1204
+ width,
1205
+ height,
1206
+ scale: 1, // Reset scale
1207
+ position: { x: 0, y: 0 }, // Reset pan/position of the image_container
1208
+ animate: false
1209
+ });
1210
+ this.notify("change");
1211
+ }
1212
+ async get_blobs() {
1213
+ const blobs = await this.layer_manager.get_blobs(this.width, this.height);
1214
+ return blobs;
1215
+ }
1216
+ on(event, callback) {
1217
+ this.event_callbacks.set(event, [
1218
+ ...(this.event_callbacks.get(event) || []),
1219
+ callback
1220
+ ]);
1221
+ }
1222
+ off(event, callback) {
1223
+ this.event_callbacks.set(event, this.event_callbacks.get(event)?.filter((cb) => cb !== callback) || []);
1224
+ }
1225
+ notify(event) {
1226
+ for (const callback of this.event_callbacks.get(event) || []) {
1227
+ callback();
1228
+ }
1229
+ }
1230
+ destroy() {
1231
+ if (!this.app)
1232
+ return;
1233
+ // for (const tool of this.tools) {
1234
+ // tool[1]?.cleanup();
1235
+ // }
1236
+ this.app?.destroy();
1237
+ }
1238
+ resize(width, height) {
1239
+ this.set_image_properties({
1240
+ width,
1241
+ height
1242
+ });
1243
+ this.reset();
1244
+ }
1245
+ async get_crop_bounds() {
1246
+ const crop_tool = this.tools.get("crop");
1247
+ const crop_bounds = crop_tool.get_crop_bounds();
1248
+ const image = await crop_tool.get_image();
1249
+ return {
1250
+ image,
1251
+ ...crop_bounds
1252
+ };
1253
+ }
1254
+ get background_image_sprite() {
1255
+ return this.background_image;
1256
+ }
1257
+ set_layer_options(layer_options) {
1258
+ this.layer_options = layer_options;
1259
+ this.layer_manager.set_layer_options(layer_options, this.width, this.height);
1260
+ }
1261
+ toggle_layer_visibility(id) {
1262
+ this.layer_manager.toggle_layer_visibility(id);
1263
+ }
1264
+ }