@gradio/imageeditor 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,178 @@
1
+ <script lang="ts">
2
+ import { createEventDispatcher, getContext, onMount, tick } from "svelte";
3
+ import { DropdownArrow } from "@gradio/icons";
4
+ import { click_outside } from "../utils/events";
5
+ import { layer_manager, type LayerScene } from "./utils";
6
+ import { EDITOR_KEY, type EditorContext } from "../ImageEditor.svelte";
7
+ import type { FileData } from "@gradio/client";
8
+
9
+ let show_layers = false;
10
+
11
+ export let layer_files: (FileData | null)[] | null = [];
12
+
13
+ const { pixi, current_layer, dimensions, register_context } =
14
+ getContext<EditorContext>(EDITOR_KEY);
15
+
16
+ const LayerManager = layer_manager();
17
+ let layers: LayerScene[] = [];
18
+
19
+ register_context("layers", {
20
+ init_fn: () => {
21
+ new_layer();
22
+ },
23
+ reset_fn: () => {
24
+ LayerManager.reset();
25
+ }
26
+ });
27
+
28
+ async function new_layer(): Promise<void> {
29
+ if (!$pixi) return;
30
+
31
+ const [active_layer, all_layers] = LayerManager.add_layer(
32
+ $pixi.layer_container,
33
+ $pixi.renderer,
34
+ ...$dimensions
35
+ );
36
+
37
+ $current_layer = active_layer;
38
+ layers = all_layers;
39
+ }
40
+
41
+ $: render_layer_files(layer_files);
42
+
43
+ function is_not_null<T>(x: T | null): x is T {
44
+ return x !== null;
45
+ }
46
+
47
+ async function render_layer_files(
48
+ _layer_files: typeof layer_files
49
+ ): Promise<void> {
50
+ await tick();
51
+ if (!_layer_files || _layer_files.length == 0) return;
52
+ if (!$pixi) return;
53
+
54
+ const fetch_promises = await Promise.all(
55
+ _layer_files.map((f) => {
56
+ if (!f || !f.url) return null;
57
+
58
+ return fetch(f.url);
59
+ })
60
+ );
61
+
62
+ const blobs = await Promise.all(
63
+ fetch_promises.map((p) => {
64
+ if (!p) return null;
65
+ return p.blob();
66
+ })
67
+ );
68
+
69
+ LayerManager.reset();
70
+
71
+ let last_layer: [LayerScene, LayerScene[]] | null = null;
72
+ for (const blob of blobs.filter(is_not_null)) {
73
+ last_layer = await LayerManager.add_layer_from_blob(
74
+ $pixi.layer_container,
75
+ $pixi.renderer,
76
+ blob
77
+ );
78
+ }
79
+
80
+ if (!last_layer) return;
81
+
82
+ $current_layer = last_layer[0];
83
+ layers = last_layer[1];
84
+ }
85
+
86
+ onMount(async () => {
87
+ await tick();
88
+ if (!$pixi) return;
89
+
90
+ $pixi = { ...$pixi!, get_layers: LayerManager.get_layers };
91
+ });
92
+ </script>
93
+
94
+ <div
95
+ class="layer-wrap"
96
+ class:closed={!show_layers}
97
+ use:click_outside={() => (show_layers = false)}
98
+ >
99
+ <button aria-label="Show Layers" on:click={() => (show_layers = !show_layers)}
100
+ >Layers<span class="layer-toggle"><DropdownArrow /></span></button
101
+ >
102
+ {#if show_layers}
103
+ <ul>
104
+ {#each layers as layer, i (i)}
105
+ <li>
106
+ <button
107
+ class:selected_layer={$current_layer === layer}
108
+ on:click={() =>
109
+ ($current_layer = LayerManager.change_active_layer(i))}
110
+ >Layer {i + 1}</button
111
+ >
112
+ </li>
113
+ {/each}
114
+ <li>
115
+ <button aria-label="Add Layer" on:click={new_layer}> +</button>
116
+ </li>
117
+ </ul>
118
+ {/if}
119
+ </div>
120
+
121
+ <style>
122
+ .layer-toggle {
123
+ width: 20px;
124
+ transform: rotate(0deg);
125
+ }
126
+
127
+ .closed .layer-toggle {
128
+ transform: rotate(-90deg);
129
+ }
130
+
131
+ .layer-wrap {
132
+ position: absolute;
133
+ bottom: 0;
134
+ left: 0;
135
+ display: inline-block;
136
+ border: 1px solid var(--block-border-color);
137
+ border-radius: var(--radius-md);
138
+
139
+ transition: var(--button-transition);
140
+ box-shadow: var(--button-shadow);
141
+
142
+ text-align: left;
143
+ border-bottom: none;
144
+ border-left: none;
145
+ border-bottom-right-radius: 0;
146
+ border-top-left-radius: 0;
147
+ background-color: var(--background-fill-primary);
148
+ overflow: hidden;
149
+ }
150
+
151
+ .layer-wrap button {
152
+ display: inline-flex;
153
+ justify-content: flex-start;
154
+ align-items: flex-start;
155
+ padding: var(--size-2) var(--size-4);
156
+ width: 100%;
157
+ border-bottom: 1px solid var(--block-border-color);
158
+ }
159
+
160
+ .layer-wrap li:last-child button {
161
+ border-bottom: none;
162
+ text-align: center;
163
+ }
164
+
165
+ .closed > button {
166
+ border-bottom: none;
167
+ }
168
+
169
+ .layer-wrap button:hover {
170
+ background-color: var(--background-fill-secondary);
171
+ }
172
+
173
+ .selected_layer {
174
+ background-color: var(--color-accent) !important;
175
+ color: white;
176
+ font-weight: bold;
177
+ }
178
+ </style>
@@ -0,0 +1,223 @@
1
+ import {
2
+ Container,
3
+ type IRenderer,
4
+ type DisplayObject,
5
+ RenderTexture,
6
+ Texture,
7
+ Sprite,
8
+ Filter
9
+ } from "pixi.js";
10
+
11
+ /**
12
+ * GLSL Shader that takes two textures and erases the second texture from the first.
13
+ */
14
+ export const erase_shader = `
15
+ precision highp float;
16
+
17
+ uniform sampler2D uDrawingTexture;
18
+ uniform sampler2D uEraserTexture;
19
+
20
+ varying vec2 vTextureCoord;
21
+
22
+ void main(void) {
23
+ vec4 drawingColor = texture2D(uDrawingTexture,vTextureCoord);
24
+ vec4 eraserColor = texture2D(uEraserTexture, vTextureCoord);
25
+
26
+ // Use the alpha of the eraser to determine how much to "erase" from the drawing
27
+ float alpha = 1.0 - eraserColor.a;
28
+ gl_FragColor = vec4(drawingColor.rgb * alpha, drawingColor.a * alpha);
29
+ }`;
30
+
31
+ /**
32
+ * Interface holding data for a layer
33
+ */
34
+ export interface LayerScene {
35
+ /**
36
+ * The texture used for tracking brush strokes.
37
+ */
38
+ draw_texture: RenderTexture;
39
+ /**
40
+ * The texture used for tracking eraser strokes.
41
+ */
42
+ erase_texture: RenderTexture;
43
+ /**
44
+ * The sprite used for displaying the composite of the draw and erase textures.
45
+ */
46
+ composite: Sprite;
47
+ /**
48
+ * The filter used for combining the draw and erase textures into a composite texture.
49
+ */
50
+ filter?: Filter;
51
+ }
52
+
53
+ /**
54
+ * Interface for managing layers.
55
+ */
56
+ interface LayerManager {
57
+ /**
58
+ * Adds a layer to the container.
59
+ * @param layer The container to add the layer to.
60
+ * @param renderer The renderer to use for the layer.
61
+ * @param width the width of the layer
62
+ * @param height the height of the layer
63
+ */
64
+ add_layer(
65
+ container: Container,
66
+ renderer: IRenderer,
67
+ width: number,
68
+ height: number
69
+ ): [LayerScene, LayerScene[]];
70
+ /**
71
+ * Swaps the layer with the layer above or below it.
72
+ * @param layer The index layer to swap.
73
+ * @param direction The direction to swap the layer.
74
+ */
75
+ swap_layers(layer: number, direction: "up" | "down"): LayerScene;
76
+ /**
77
+ * Changes the active layer.
78
+ * @param layer The index of the layer to make active.
79
+ */
80
+ change_active_layer(layer: number): LayerScene;
81
+ /**
82
+ * Resizes the layers.
83
+ * @param width The new width of the layers.
84
+ * @param height The new height of the layers.
85
+ */
86
+ reset(): void;
87
+ /**
88
+ * Gets the layers.
89
+ * @returns The layers.
90
+ */
91
+ get_layers(): LayerScene[];
92
+
93
+ add_layer_from_blob(
94
+ container: Container,
95
+ renderer: IRenderer,
96
+ blob: Blob
97
+ ): Promise<[LayerScene, LayerScene[]]>;
98
+ }
99
+
100
+ /**
101
+ * Swaps two adjacent elements in an array.
102
+ * @param array The array to swap elements in.
103
+ * @param index The index of the first element to swap.
104
+ */
105
+ function swap_adjacent(array: any[], index: number): void {
106
+ if (index < 0 || index >= array.length - 1) {
107
+ throw new Error("Index out of bounds");
108
+ }
109
+
110
+ [array[index], array[index + 1]] = [array[index + 1], array[index]];
111
+ }
112
+
113
+ /**
114
+ * Creates a layer manager.
115
+ * @param canvas_resize a function to resize the canvas
116
+ * @returns a layer manager
117
+ */
118
+ export function layer_manager(): LayerManager {
119
+ let _layers: LayerScene[] = [];
120
+ let current_layer = 0;
121
+ let position = 0;
122
+
123
+ return {
124
+ add_layer: function (
125
+ container: Container,
126
+ renderer: IRenderer,
127
+ width: number,
128
+ height: number
129
+ ): [LayerScene, LayerScene[]] {
130
+ const layer_container = new Container() as Container & DisplayObject;
131
+ position++;
132
+ layer_container.zIndex = position;
133
+
134
+ const composite_texture = RenderTexture.create({
135
+ width,
136
+ height
137
+ });
138
+
139
+ const composite = new Sprite(composite_texture) as Sprite & DisplayObject;
140
+
141
+ layer_container.addChild(composite);
142
+
143
+ composite.zIndex = position;
144
+
145
+ const layer_scene: LayerScene = {
146
+ draw_texture: RenderTexture.create({
147
+ width,
148
+ height
149
+ }),
150
+ erase_texture: RenderTexture.create({
151
+ width,
152
+ height
153
+ }),
154
+ composite
155
+ };
156
+
157
+ const erase_filter = new Filter(undefined, erase_shader, {
158
+ uEraserTexture: layer_scene.erase_texture,
159
+ uDrawingTexture: layer_scene.draw_texture
160
+ });
161
+
162
+ composite.filters = [erase_filter];
163
+
164
+ container.addChild(layer_container);
165
+
166
+ _layers.push(layer_scene);
167
+
168
+ return [layer_scene, _layers];
169
+ },
170
+
171
+ swap_layers: function (
172
+ layer: number,
173
+ direction: "up" | "down"
174
+ ): LayerScene {
175
+ if (direction === "up") {
176
+ swap_adjacent(_layers, layer);
177
+ } else {
178
+ swap_adjacent(_layers, layer - 1);
179
+ }
180
+ return _layers[layer];
181
+ },
182
+
183
+ change_active_layer: function (layer: number): LayerScene {
184
+ current_layer = layer;
185
+ return _layers[layer];
186
+ },
187
+ reset() {
188
+ _layers.forEach((layer) => {
189
+ layer.draw_texture.destroy(true);
190
+ layer.erase_texture.destroy(true);
191
+ layer.composite.destroy(true);
192
+ });
193
+ _layers = [];
194
+ current_layer = 0;
195
+ position = 0;
196
+ },
197
+ async add_layer_from_blob(
198
+ container: Container,
199
+ renderer: IRenderer,
200
+ blob: Blob
201
+ ) {
202
+ const img = await createImageBitmap(blob);
203
+ const bitmap_texture = Texture.from(img);
204
+ const sprite = new Sprite(bitmap_texture) as Sprite & DisplayObject;
205
+ sprite.zIndex = 0;
206
+
207
+ const [layer, layers] = this.add_layer(
208
+ container,
209
+ renderer,
210
+ sprite.width,
211
+ sprite.height
212
+ );
213
+ renderer.render(sprite, {
214
+ renderTexture: layer.draw_texture
215
+ });
216
+
217
+ return [layer, layers];
218
+ },
219
+ get_layers() {
220
+ return _layers;
221
+ }
222
+ };
223
+ }
@@ -0,0 +1,301 @@
1
+ <script lang="ts" context="module">
2
+ import { type ColorInput } from "tinycolor2";
3
+
4
+ export interface Eraser {
5
+ /**
6
+ * The default size of the eraser.
7
+ */
8
+ default_size: number | "auto";
9
+ /**
10
+ * The sizes to show in the size swatch
11
+ */
12
+ sizes: number[] | "auto";
13
+ /**
14
+ * Whether to show _only_ the sizes specified in `sizes`, or to show the sizes specified in `sizes` along with the size slider.
15
+ */
16
+ size_mode: "fixed" | "defaults";
17
+ /**
18
+ * Whether to use antialiasing when drawing the eraser.
19
+ */
20
+ antialias: boolean;
21
+ }
22
+
23
+ export interface Brush extends Eraser {
24
+ /**
25
+ * The default color of the brush.
26
+ */
27
+ default_color: ColorInput;
28
+ /**
29
+ * The colors to show in the color swatch
30
+ */
31
+ colors: ColorInput[];
32
+ /**
33
+ * Whether to show _only_ the color swatches specified in `colors`, or to show the color swatches specified in `colors` along with the colorpicker.
34
+ */
35
+ color_mode: "fixed" | "defaults";
36
+ }
37
+
38
+ type brush_option_type = "color" | "size";
39
+ </script>
40
+
41
+ <script lang="ts">
42
+ import tinycolor from "tinycolor2";
43
+ import { clamp } from "../utils/pixi";
44
+
45
+ import { getContext, onMount, tick } from "svelte";
46
+ import { type ToolContext, TOOL_KEY } from "./Tools.svelte";
47
+ import { Palette, BrushSize as SizeIcon } from "@gradio/icons";
48
+ import { type EditorContext, EDITOR_KEY } from "../ImageEditor.svelte";
49
+ import { draw_path, type DrawCommand } from "./brush";
50
+ import BrushColor from "./BrushColor.svelte";
51
+ import BrushSize from "./BrushSize.svelte";
52
+ import type { FederatedPointerEvent } from "pixi.js";
53
+
54
+ export let default_size: Brush["default_size"];
55
+ export let default_color: Brush["default_color"] | undefined = undefined;
56
+ export let colors: Brush["colors"] | undefined = undefined;
57
+ export let color_mode: Brush["color_mode"] | undefined = undefined;
58
+ export let mode: "erase" | "draw";
59
+
60
+ const processed_colors = colors
61
+ ? colors.map(process_color).filter((_, i) => i < 5)
62
+ : [];
63
+
64
+ let selected_color =
65
+ default_color === "auto"
66
+ ? processed_colors[0]
67
+ : !default_color
68
+ ? "black"
69
+ : process_color(default_color);
70
+
71
+ const paint_meta = {
72
+ color: {
73
+ icon: Palette,
74
+ label: "Color",
75
+ order: 0,
76
+ id: "brush_color",
77
+ cb() {
78
+ current_option = "color";
79
+ }
80
+ },
81
+ size: {
82
+ icon: SizeIcon,
83
+ label: "Size",
84
+ order: 1,
85
+ id: "brush_size",
86
+ cb() {
87
+ current_option = "size";
88
+ }
89
+ }
90
+ } as const;
91
+
92
+ let brush_options: (typeof paint_meta)[brush_option_type][];
93
+ $: brush_options =
94
+ mode === "draw" ? Object.values(paint_meta) : [paint_meta.size];
95
+
96
+ let current_option: brush_option_type | null = null;
97
+
98
+ const {
99
+ pixi,
100
+ dimensions,
101
+ current_layer,
102
+ command_manager,
103
+ register_context,
104
+ editor_box,
105
+ crop
106
+ } = getContext<EditorContext>(EDITOR_KEY);
107
+
108
+ const { active_tool, register_tool, current_color } =
109
+ getContext<ToolContext>(TOOL_KEY);
110
+
111
+ let drawing = false;
112
+ let draw: DrawCommand;
113
+
114
+ function generate_sizes(x: number, y: number): number {
115
+ const min = clamp(Math.min(x, y), 500, 1000);
116
+
117
+ return Math.round((min * 2) / 100);
118
+ }
119
+
120
+ $: mode === "draw" && current_color.set(selected_color);
121
+
122
+ let selected_size =
123
+ default_size === "auto" ? generate_sizes(...$dimensions) : default_size;
124
+
125
+ function pointer_down_handler(event: FederatedPointerEvent): void {
126
+ if ($active_tool !== mode) {
127
+ return;
128
+ }
129
+ drawing = true;
130
+
131
+ if (!$pixi || !$current_layer) {
132
+ return;
133
+ }
134
+
135
+ draw = draw_path(
136
+ $pixi.renderer!,
137
+ $pixi.layer_container,
138
+ $current_layer,
139
+ mode
140
+ );
141
+
142
+ draw.start({
143
+ x: event.screen.x,
144
+ y: event.screen.y,
145
+ color: selected_color || undefined,
146
+ size: selected_size,
147
+ opacity: 1
148
+ });
149
+ }
150
+
151
+ function pointer_up_handler(event: FederatedPointerEvent): void {
152
+ if (!$pixi || !$current_layer) {
153
+ return;
154
+ }
155
+ if ($active_tool !== mode) {
156
+ return;
157
+ }
158
+ draw.stop();
159
+ command_manager.execute(draw);
160
+ drawing = false;
161
+ }
162
+
163
+ function pointer_move_handler(event: FederatedPointerEvent): void {
164
+ if ($active_tool !== mode) {
165
+ return;
166
+ }
167
+ if (drawing) {
168
+ draw.continue({
169
+ x: event.screen.x,
170
+ y: event.screen.y
171
+ });
172
+ }
173
+
174
+ const x_bound = $crop[0] * $dimensions[0];
175
+ const y_bound = $crop[1] * $dimensions[1];
176
+
177
+ if (
178
+ x_bound > event.screen.x ||
179
+ y_bound > event.screen.y ||
180
+ event.screen.x > x_bound + $crop[2] * $dimensions[0] ||
181
+ event.screen.y > y_bound + $crop[3] * $dimensions[1]
182
+ ) {
183
+ brush_cursor = false;
184
+ document.body.style.cursor = "auto";
185
+ } else {
186
+ brush_cursor = true;
187
+ document.body.style.cursor = "none";
188
+ }
189
+ if (brush_cursor) {
190
+ pos = {
191
+ x: event.clientX - $editor_box.child_left,
192
+ y: event.clientY - $editor_box.child_top
193
+ };
194
+ }
195
+ }
196
+
197
+ let brush_cursor = false;
198
+
199
+ async function toggle_listeners(on_off: "on" | "off"): Promise<void> {
200
+ $pixi?.layer_container[on_off]("pointerdown", pointer_down_handler);
201
+
202
+ $pixi?.layer_container[on_off]("pointerup", pointer_up_handler);
203
+
204
+ $pixi?.layer_container[on_off]("pointermove", pointer_move_handler);
205
+ $pixi?.layer_container[on_off](
206
+ "pointerenter",
207
+ (event: FederatedPointerEvent) => {
208
+ if ($active_tool === mode) {
209
+ brush_cursor = true;
210
+ document.body.style.cursor = "none";
211
+ }
212
+ }
213
+ );
214
+ $pixi?.layer_container[on_off](
215
+ "pointerleave",
216
+ () => ((brush_cursor = false), (document.body.style.cursor = "auto"))
217
+ );
218
+ }
219
+
220
+ register_context(mode, {
221
+ init_fn: () => {
222
+ toggle_listeners("on");
223
+ },
224
+ reset_fn: () => {
225
+ toggle_listeners("off");
226
+ }
227
+ });
228
+
229
+ onMount(() => {
230
+ const unregister = register_tool(mode, {
231
+ default: null,
232
+ options: brush_options
233
+ });
234
+
235
+ return () => {
236
+ unregister();
237
+ toggle_listeners("off");
238
+ };
239
+ });
240
+
241
+ let recent_colors: (string | null)[] = [null, null, null];
242
+
243
+ function process_color(color: ColorInput): string {
244
+ return tinycolor(color).toRgbString();
245
+ }
246
+
247
+ $: {
248
+ if ($active_tool !== mode) {
249
+ current_option = null;
250
+ }
251
+ }
252
+
253
+ let pos = { x: 0, y: 0 };
254
+ $: brush_size =
255
+ (selected_size / $dimensions[0]) * $editor_box.child_width * 2;
256
+ </script>
257
+
258
+ <svelte:window
259
+ on:keydown={({ key }) => key === "Escape" && (current_option = null)}
260
+ />
261
+
262
+ <span
263
+ style:transform="translate({pos.x}px, {pos.y}px)"
264
+ style:top="{$editor_box.child_top -
265
+ $editor_box.parent_top -
266
+ brush_size / 2}px"
267
+ style:left="{$editor_box.child_left -
268
+ $editor_box.parent_left -
269
+ brush_size / 2}px"
270
+ style:width="{brush_size}px"
271
+ style:height="{brush_size}px"
272
+ style:opacity={brush_cursor ? 1 : 0}
273
+ />
274
+
275
+ {#if current_option === "color" && colors}
276
+ <div>
277
+ <BrushColor
278
+ on:click_outside={() => (current_option = null)}
279
+ colors={processed_colors}
280
+ bind:selected_color
281
+ {color_mode}
282
+ bind:recent_colors
283
+ />
284
+ </div>
285
+ {:else if current_option === "size"}
286
+ <BrushSize
287
+ on:click_outside={() => (current_option = null)}
288
+ max={$dimensions[0] / 10}
289
+ min={1}
290
+ bind:selected_size
291
+ />
292
+ {/if}
293
+
294
+ <style>
295
+ span {
296
+ position: absolute;
297
+ background: rgba(0, 0, 0, 0.5);
298
+ pointer-events: none;
299
+ border-radius: 50%;
300
+ }
301
+ </style>