@kubohiroya/turbowarp-plus-editor-code-views 0.6.0 → 0.7.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,305 @@
1
+ /**
2
+ * Comments in "Clean up blocks".
3
+ *
4
+ * The code area's "Clean up blocks" runs `WorkspaceSvg.prototype.cleanUp`. In the GUI that is the editor-devtools
5
+ * addon's column layout unless the user turned it off, and scratch-blocks' single column otherwise. Neither keeps
6
+ * the comments in step with the scripts: the addon hides and shows every block comment so that scratch-blocks puts
7
+ * it again at its default place beside the block, which the VM does not hear of, and both lay the scripts out by
8
+ * the blocks alone, so a comment can cover the next script. Workspace comments are not moved at all.
9
+ *
10
+ * This wraps whichever `cleanUp` is in place, now or later. Before it runs, every block comment's offset from its
11
+ * block is read. After it runs, the scripts are pushed apart where a script and its comments would cover the next
12
+ * one, every block comment is put back at its offset from its block, and a workspace comment that covers a script
13
+ * is moved to a column beside the scripts. Every move goes through scratch-blocks, so the VM hears of it and the
14
+ * saved project keeps the positions.
15
+ */
16
+
17
+ interface Point {
18
+ x: number;
19
+ y: number;
20
+ }
21
+
22
+ export interface Rect {
23
+ left: number;
24
+ top: number;
25
+ right: number;
26
+ bottom: number;
27
+ }
28
+
29
+ /** A script with its block comments, as it stands after the wrapped clean-up. */
30
+ export interface ScriptCluster {
31
+ id: string;
32
+ /** Where the wrapped clean-up put the top block. */
33
+ x: number;
34
+ y: number;
35
+ /** The script and its block comments together. */
36
+ rect: Rect;
37
+ }
38
+
39
+ export interface LooseComment {
40
+ id: string;
41
+ rect: Rect;
42
+ }
43
+
44
+ /** Room left between a script and what it would otherwise cover. */
45
+ export const cleanUpGap = 32;
46
+
47
+ const overlaps = (a: Rect, b: Rect) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
48
+ const shifted = (rect: Rect, dx: number, dy: number): Rect =>
49
+ ({left: rect.left + dx, top: rect.top + dy, right: rect.right + dx, bottom: rect.bottom + dy});
50
+
51
+ /**
52
+ * How far to move each script so that no script with its comments covers another.
53
+ * The clean-up's columns are kept: scripts that start at the same x form a column, read from left to right and
54
+ * each from top to bottom. A script that would cover the one above it moves down, and every script below it with
55
+ * it; a column that would cover the columns to its left moves right, and every column after it with it. Where
56
+ * nothing is covered nothing moves, so the clean-up's own spacing stays.
57
+ * @param {ScriptCluster[]} clusters The scripts after the clean-up.
58
+ * @param {number} gap Room left between a script and the next.
59
+ * @returns {Map<string, Point>} The offset of each script that moves.
60
+ */
61
+ export function separateClusters(clusters: readonly ScriptCluster[], gap = cleanUpGap): Map<string, Point> {
62
+ const columns = new Map<number, ScriptCluster[]>();
63
+ for (const cluster of clusters) {
64
+ const column = columns.get(cluster.x);
65
+ if (column) column.push(cluster);
66
+ else columns.set(cluster.x, [cluster]);
67
+ }
68
+ const moves = new Map<string, Point>();
69
+ let shiftX = 0;
70
+ let rightEdge = -Infinity;
71
+ for (const x of [...columns.keys()].sort((a, b) => a - b)) {
72
+ const column = columns.get(x).sort((a, b) => a.y - b.y || a.rect.top - b.rect.top || (a.id < b.id ? -1 : 1));
73
+ const left = Math.min(...column.map(cluster => cluster.rect.left));
74
+ if (left + shiftX < rightEdge + gap) shiftX = rightEdge + gap - left;
75
+ let shiftY = 0;
76
+ let bottomEdge = -Infinity;
77
+ for (const cluster of column) {
78
+ if (cluster.rect.top + shiftY < bottomEdge + gap) shiftY = bottomEdge + gap - cluster.rect.top;
79
+ bottomEdge = cluster.rect.bottom + shiftY;
80
+ rightEdge = Math.max(rightEdge, cluster.rect.right + shiftX);
81
+ if (shiftX || shiftY) moves.set(cluster.id, {x: shiftX, y: shiftY});
82
+ }
83
+ }
84
+ return moves;
85
+ }
86
+
87
+ /**
88
+ * Where to put the workspace comments that cover a script.
89
+ * A comment that covers nothing stays. The others go, in reading order, into a column to the right of the scripts
90
+ * and of the comments that stay, from the top of the scripts down.
91
+ * @param {Rect[]} scripts The scripts with their block comments, where they end up.
92
+ * @param {LooseComment[]} comments The workspace comments.
93
+ * @param {number} gap Room left around a moved comment.
94
+ * @returns {Map<string, Point>} The offset of each comment that moves.
95
+ */
96
+ export function placeLooseComments(scripts: readonly Rect[], comments: readonly LooseComment[], gap = cleanUpGap) {
97
+ const moves = new Map<string, Point>();
98
+ const covering = comments.filter(comment => scripts.some(script => overlaps(script, comment.rect)));
99
+ if (!covering.length) return moves;
100
+ const staying = comments.filter(comment => !covering.includes(comment)).map(comment => comment.rect);
101
+ const occupied = [...scripts, ...staying];
102
+ const x = Math.max(...occupied.map(rect => rect.right)) + gap;
103
+ let y = scripts.length ? Math.min(...scripts.map(rect => rect.top)) : 0;
104
+ const ordered = [...covering].sort((a, b) => a.rect.top - b.rect.top || a.rect.left - b.rect.left ||
105
+ (a.id < b.id ? -1 : 1));
106
+ for (const comment of ordered) {
107
+ moves.set(comment.id, {x: x - comment.rect.left, y: y - comment.rect.top});
108
+ y += comment.rect.bottom - comment.rect.top + gap;
109
+ }
110
+ return moves;
111
+ }
112
+
113
+ // Shapes from scratch-blocks core/block_svg.js, scratch_block_comment.js and workspace_comment_svg.js, reduced to
114
+ // what the wrapper reads.
115
+ interface Bounds {
116
+ topLeft: Point;
117
+ bottomRight: Point;
118
+ }
119
+
120
+ interface CleanUpBlock {
121
+ id: string;
122
+ workspace: unknown;
123
+ getRelativeToSurfaceXY(): Point;
124
+ getBoundingRectangle(): Bounds;
125
+ getRootBlock(): CleanUpBlock;
126
+ moveBy(dx: number, dy: number): void;
127
+ }
128
+
129
+ interface CleanUpComment {
130
+ id: string;
131
+ workspace: unknown;
132
+ /** Only a block comment has its block. */
133
+ block_?: CleanUpBlock;
134
+ getXY?(): Point;
135
+ getRelativeToSurfaceXY?(): Point;
136
+ getBoundingRectangle(): Bounds;
137
+ moveTo?(x: number, y: number): void;
138
+ moveBy?(dx: number, dy: number): void;
139
+ }
140
+
141
+ interface CleanUpWorkspace {
142
+ RTL?: boolean;
143
+ isFlyout?: boolean;
144
+ getTopBlocks(ordered: boolean): CleanUpBlock[];
145
+ getTopComments?(ordered: boolean): CleanUpComment[];
146
+ setResizesEnabled?(enabled: boolean): void;
147
+ }
148
+
149
+ interface CleanUpEvents {
150
+ getGroup(): string;
151
+ setGroup(group: string | boolean): void;
152
+ FIRE_QUEUE_?: {group?: string}[];
153
+ }
154
+
155
+ type CleanUp = (this: CleanUpWorkspace, ...args: unknown[]) => unknown;
156
+
157
+ const toRect = ({topLeft, bottomRight}: Bounds): Rect =>
158
+ ({left: topLeft.x, top: topLeft.y, right: bottomRight.x, bottom: bottomRight.y});
159
+ const union = (a: Rect, b: Rect): Rect => ({left: Math.min(a.left, b.left), top: Math.min(a.top, b.top),
160
+ right: Math.max(a.right, b.right), bottom: Math.max(a.bottom, b.bottom)});
161
+ const alive = (item: {workspace: unknown} | undefined) => Boolean(item?.workspace);
162
+ const isBlockComment = (comment: CleanUpComment) => Boolean(comment.block_);
163
+
164
+ interface Attached {
165
+ comment: CleanUpComment;
166
+ block: CleanUpBlock;
167
+ offset: Point;
168
+ }
169
+
170
+ /**
171
+ * Read each block comment's offset from its block.
172
+ * @param {object} workspace The workspace about to be cleaned up.
173
+ * @returns {Attached[]} The block comments with their offsets.
174
+ */
175
+ function readAttached(workspace: CleanUpWorkspace): Attached[] {
176
+ return (workspace.getTopComments?.(false) ?? []).flatMap(comment => {
177
+ const block = comment.block_;
178
+ if (!block || !alive(block) || !comment.getXY || !comment.moveTo) return [];
179
+ const commentXY = comment.getXY();
180
+ const blockXY = block.getRelativeToSurfaceXY();
181
+ return [{comment, block, offset: {x: commentXY.x - blockXY.x, y: commentXY.y - blockXY.y}}];
182
+ });
183
+ }
184
+
185
+ /**
186
+ * Lay out the scripts and comments again after the wrapped clean-up.
187
+ * @param {object} workspace The cleaned-up workspace.
188
+ * @param {Attached[]} attached The block comments read before the clean-up.
189
+ * @param {object} events `ScratchBlocks.Events`.
190
+ */
191
+ function followUp(workspace: CleanUpWorkspace, attached: Attached[], events: CleanUpEvents | undefined) {
192
+ const kept = attached.filter(({comment, block}) => alive(comment) && alive(block));
193
+ const placed = (item: Attached) => {
194
+ const blockXY = item.block.getRelativeToSurfaceXY();
195
+ return {x: blockXY.x + item.offset.x, y: blockXY.y + item.offset.y};
196
+ };
197
+ const commentRect = (item: Attached): Rect => {
198
+ const rect = toRect(item.comment.getBoundingRectangle());
199
+ const {x, y} = placed(item);
200
+ return {left: x, top: y, right: x + rect.right - rect.left, bottom: y + rect.bottom - rect.top};
201
+ };
202
+
203
+ const scripts = workspace.getTopBlocks(false).filter(alive);
204
+ const clusters = scripts.map(block => {
205
+ const {x, y} = block.getRelativeToSurfaceXY();
206
+ let rect = toRect(block.getBoundingRectangle());
207
+ for (const item of kept) {
208
+ if (item.block.getRootBlock() === block) rect = union(rect, commentRect(item));
209
+ }
210
+ return {id: block.id, x, y, rect, block};
211
+ });
212
+ const scriptMoves = separateClusters(clusters);
213
+
214
+ // Join the clean-up's undo group, which scratch-blocks has already closed by now, so that one undo takes back
215
+ // the clean-up and these moves together.
216
+ const outer = events?.getGroup() ?? '';
217
+ const group = outer || events?.FIRE_QUEUE_?.at(-1)?.group || true;
218
+ events?.setGroup(group);
219
+ workspace.setResizesEnabled?.(false);
220
+ try {
221
+ for (const cluster of clusters) {
222
+ const move = scriptMoves.get(cluster.id);
223
+ if (move) cluster.block.moveBy(move.x, move.y);
224
+ }
225
+ // scratch-blocks moves an open comment with its block, but the addon's clean-up puts it back beside the
226
+ // block; put every one back where it was from its block, which also tells the VM where it is.
227
+ for (const item of kept) {
228
+ const {x, y} = placed(item);
229
+ item.comment.moveTo(x, y);
230
+ }
231
+ const loose = (workspace.getTopComments?.(false) ?? [])
232
+ .filter(comment => alive(comment) && !isBlockComment(comment) && comment.moveBy);
233
+ const looseMoves = placeLooseComments(
234
+ clusters.map(({id, rect}) => {
235
+ const move = scriptMoves.get(id);
236
+ return move ? shifted(rect, move.x, move.y) : rect;
237
+ }),
238
+ loose.map(comment => ({id: comment.id, rect: toRect(comment.getBoundingRectangle())}))
239
+ );
240
+ for (const comment of loose) {
241
+ const move = looseMoves.get(comment.id);
242
+ if (move) comment.moveBy(move.x, move.y);
243
+ }
244
+ } finally {
245
+ workspace.setResizesEnabled?.(true);
246
+ events?.setGroup(outer);
247
+ }
248
+ }
249
+
250
+ const installed = new WeakSet<object>();
251
+
252
+ /**
253
+ * Keep comments with their scripts in "Clean up blocks".
254
+ * `WorkspaceSvg.prototype.cleanUp` becomes an accessor, so a `cleanUp` that an addon puts there later is wrapped
255
+ * too. A workspace that is given its own `cleanUp` keeps it as its own, unwrapped. Workspaces laid out right to
256
+ * left are cleaned up as before.
257
+ * @param {object} ScratchBlocks The loaded ScratchBlocks.
258
+ */
259
+ export const installCleanUpComments = ScratchBlocks => {
260
+ const prototype = ScratchBlocks?.WorkspaceSvg?.prototype;
261
+ if (!prototype || installed.has(prototype) || typeof prototype.cleanUp !== 'function') return;
262
+ installed.add(prototype);
263
+
264
+ const events: CleanUpEvents | undefined = ScratchBlocks.Events;
265
+ const wrappers = new WeakMap<CleanUp, CleanUp>();
266
+ let running = false;
267
+ const wrap = (cleanUp: CleanUp): CleanUp => {
268
+ if (typeof cleanUp !== 'function') return cleanUp;
269
+ let wrapper = wrappers.get(cleanUp);
270
+ if (wrapper) return wrapper;
271
+ wrapper = function (this: CleanUpWorkspace, ...args: unknown[]) {
272
+ // An addon's clean-up can call the one it replaced, which is wrapped as well.
273
+ if (running || this.RTL || this.isFlyout) return cleanUp.apply(this, args);
274
+ const attached = readAttached(this);
275
+ running = true;
276
+ let result: unknown;
277
+ try {
278
+ result = cleanUp.apply(this, args);
279
+ } finally {
280
+ running = false;
281
+ }
282
+ followUp(this, attached, events);
283
+ return result;
284
+ };
285
+ wrappers.set(cleanUp, wrapper);
286
+ return wrapper;
287
+ };
288
+
289
+ let current: CleanUp = prototype.cleanUp;
290
+ Object.defineProperty(prototype, 'cleanUp', {
291
+ configurable: true,
292
+ enumerable: false,
293
+ get () {
294
+ return wrap(current);
295
+ },
296
+ set (value: CleanUp) {
297
+ if (this === prototype) {
298
+ current = value;
299
+ return;
300
+ }
301
+ // Assigning to a workspace gives it its own clean-up, as it did before this accessor.
302
+ Object.defineProperty(this, 'cleanUp', {value, writable: true, configurable: true, enumerable: true});
303
+ }
304
+ });
305
+ };
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Makes a script copied by dropping it on a sprite or the stage in the sprite list visible, and
3
+ * lets the user take that copy back in one action.
4
+ *
5
+ * The GUI copies a dragged script when the pointer is released over a tile of the sprite list: its
6
+ * target pane listens for the VM's BLOCK_DRAG_END and calls
7
+ * `vm.shareBlocksToTarget(blocks, targetId, editingTargetId)`. That is the only caller that passes
8
+ * the source target, so a call with a source different from the receiving target is a drop on the
9
+ * sprite list. Pasting and backpack drops pass no source and are left alone.
10
+ */
11
+
12
+ interface SharedBlock {
13
+ id: string;
14
+ parent?: string | null;
15
+ topLevel?: boolean;
16
+ }
17
+ interface NoticeTarget {
18
+ id: string;
19
+ isStage: boolean;
20
+ isOriginal?: boolean;
21
+ getName(): string;
22
+ blocks: {
23
+ _blocks: Record<string, SharedBlock>;
24
+ deleteBlock(id: string): void;
25
+ getAllVariableAndListReferences(optBlocks?: unknown): Record<string, unknown>;
26
+ };
27
+ variables: Record<string, unknown>;
28
+ deleteVariable(id: string): void;
29
+ }
30
+ interface NoticeVM {
31
+ editingTarget: NoticeTarget | null;
32
+ runtime: {
33
+ targets: NoticeTarget[];
34
+ getTargetById(id: string): NoticeTarget | undefined;
35
+ getTargetForStage(): NoticeTarget | undefined;
36
+ };
37
+ shareBlocksToTarget(blocks: unknown, targetId: string, fromTargetId?: string): Promise<unknown>;
38
+ emitWorkspaceUpdate?(): void;
39
+ emitTargetsUpdate?(triggerProjectChange?: boolean): void;
40
+ }
41
+
42
+ export interface SpriteCopyNoticeOptions {
43
+ vm: NoticeVM;
44
+ document: Document;
45
+ /** The GUI's locale, or a function that reads it when a notice is shown. */
46
+ locale?: string | (() => string | undefined);
47
+ /** How long a notice stays, in milliseconds, while the pointer is not on it. */
48
+ timeout?: number;
49
+ /** The tile of a target in the sprite list. The default finds the GUI's sprite and stage tiles. */
50
+ findTargetElement?(target: NoticeTarget, document: Document): Element | null | undefined;
51
+ }
52
+
53
+ /** What one drop added to a target, and how to take it back. */
54
+ export interface SharedCopy {
55
+ target: NoticeTarget;
56
+ /** The top blocks of the copied scripts. */
57
+ roots: string[];
58
+ /** Variables the copy created, with the target that holds each. */
59
+ variables: Array<{owner: NoticeTarget; id: string}>;
60
+ }
61
+
62
+ const messages = {
63
+ en: {
64
+ copiedToSprite: (name: string) => `Copied the script to “${name}”.`,
65
+ copiedToStage: 'Copied the script to the Stage.',
66
+ undo: 'Undo', close: 'Close',
67
+ removedFromSprite: (name: string) => `Removed the copy from “${name}”.`,
68
+ removedFromStage: 'Removed the copy from the Stage.'
69
+ },
70
+ ja: {
71
+ copiedToSprite: (name: string) => `スプライト「${name}」にスクリプトをコピーしました。`,
72
+ copiedToStage: '背景にスクリプトをコピーしました。',
73
+ undo: '元に戻す', close: '閉じる',
74
+ removedFromSprite: (name: string) => `スプライト「${name}」からコピーを取り消しました。`,
75
+ removedFromStage: '背景からコピーを取り消しました。'
76
+ },
77
+ 'ja-hira': {
78
+ copiedToSprite: (name: string) => `スプライト「${name}」にスクリプトをコピーしました。`,
79
+ copiedToStage: 'はいけいにスクリプトをコピーしました。',
80
+ undo: 'もとにもどす', close: 'とじる',
81
+ removedFromSprite: (name: string) => `スプライト「${name}」からコピーをとりけしました。`,
82
+ removedFromStage: 'はいけいからコピーをとりけしました。'
83
+ }
84
+ };
85
+ export type SpriteCopyNoticeMessages = typeof messages.en;
86
+
87
+ /** The notice's wording for a locale: ja-hira, ja, and English for anything else. */
88
+ export function spriteCopyNoticeMessages(locale?: string): SpriteCopyNoticeMessages {
89
+ if (/^ja-hira$/i.test(locale ?? '')) return messages['ja-hira'];
90
+ return /^ja(?:-|$)/i.test(locale ?? '') ? messages.ja : messages.en;
91
+ }
92
+
93
+ /** Marks the tile of the target that received a copy, for as long as the notice is shown. */
94
+ export const RECEIVED_COPY_ATTRIBUTE = 'data-tw-received-copy';
95
+
96
+ function defaultTargetElement(target: NoticeTarget, document: Document) {
97
+ if (target.isStage) return document.querySelector('[class*="stage-selector_stage-selector_"]');
98
+ const name = target.getName();
99
+ for (const label of document.querySelectorAll('[class*="sprite-selector-item_sprite-name_"]')) {
100
+ if (label.textContent === name) return label.closest('[class*="sprite-selector-item_sprite-selector-item_"]');
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * Remove what a drop copied into a target: its scripts, and the variables it created that no
107
+ * script refers to any more. Scripts the user already deleted are skipped.
108
+ * @returns Whether anything was removed.
109
+ */
110
+ export function removeSharedCopy(vm: NoticeVM, copy: SharedCopy) {
111
+ const {target} = copy;
112
+ if (vm.runtime.getTargetById(target.id) !== target) return false;
113
+ let removed = false;
114
+ for (const id of copy.roots) {
115
+ if (!target.blocks._blocks[id]) continue;
116
+ target.blocks.deleteBlock(id);
117
+ removed = true;
118
+ }
119
+ const referenced = new Set<string>();
120
+ for (const each of vm.runtime.targets) {
121
+ if (each.isOriginal === false) continue;
122
+ for (const id of Object.keys(each.blocks.getAllVariableAndListReferences())) referenced.add(id);
123
+ }
124
+ let stageChanged = false;
125
+ for (const {owner, id} of copy.variables) {
126
+ if (referenced.has(id) || !Object.prototype.hasOwnProperty.call(owner.variables, id)) continue;
127
+ owner.deleteVariable(id);
128
+ removed = true;
129
+ if (owner.isStage) stageChanged = true;
130
+ }
131
+ if (removed) {
132
+ // Only the code area that shows the target (or the stage's variables) has to be redrawn.
133
+ if (vm.editingTarget === target || stageChanged) vm.emitWorkspaceUpdate?.();
134
+ vm.emitTargetsUpdate?.();
135
+ }
136
+ return removed;
137
+ }
138
+
139
+ const svgNS = 'http://www.w3.org/2000/svg';
140
+ function closeIcon(document: Document) {
141
+ const svg = document.createElementNS(svgNS, 'svg');
142
+ svg.setAttribute('viewBox', '0 0 16 16');
143
+ svg.setAttribute('width', '12');
144
+ svg.setAttribute('height', '12');
145
+ svg.setAttribute('aria-hidden', 'true');
146
+ const path = document.createElementNS(svgNS, 'path');
147
+ path.setAttribute('d', 'M3 3 L13 13 M13 3 L3 13');
148
+ path.setAttribute('stroke', 'currentColor');
149
+ path.setAttribute('stroke-width', '2');
150
+ path.setAttribute('stroke-linecap', 'round');
151
+ svg.append(path);
152
+ return svg;
153
+ }
154
+
155
+ /**
156
+ * Show a notice naming the sprite (or the stage) that a drop on the sprite list copied a script
157
+ * into, mark its tile, and offer to undo the copy.
158
+ * @returns `dispose`, which removes the notice and stops watching the VM.
159
+ */
160
+ export function attachSpriteCopyNotice({vm, document, locale, timeout = 10000,
161
+ findTargetElement = defaultTargetElement}: SpriteCopyNoticeOptions) {
162
+ const hadOwn = Object.prototype.hasOwnProperty.call(vm, 'shareBlocksToTarget');
163
+ const original = vm.shareBlocksToTarget;
164
+ let disposed = false;
165
+ let hide: (() => void) | undefined;
166
+ const text = () => spriteCopyNoticeMessages(typeof locale === 'function' ? locale() : locale);
167
+
168
+ function show(copy: SharedCopy) {
169
+ hide?.();
170
+ const words = text();
171
+ const {target} = copy;
172
+ const name = target.isStage ? '' : target.getName();
173
+ const notice = document.createElement('div');
174
+ notice.className = 'tw-sprite-copy-notice';
175
+ notice.setAttribute('role', 'status');
176
+ notice.setAttribute('aria-live', 'polite');
177
+ const message = document.createElement('span');
178
+ message.className = 'tw-sprite-copy-notice-text';
179
+ message.textContent = target.isStage ? words.copiedToStage : words.copiedToSprite(name);
180
+ const undo = document.createElement('button');
181
+ undo.type = 'button';
182
+ undo.className = 'tw-sprite-copy-notice-undo';
183
+ undo.textContent = words.undo;
184
+ const close = document.createElement('button');
185
+ close.type = 'button';
186
+ close.className = 'tw-sprite-copy-notice-close';
187
+ close.title = words.close;
188
+ close.setAttribute('aria-label', words.close);
189
+ close.append(closeIcon(document));
190
+ notice.append(message, undo, close);
191
+ document.body.append(notice);
192
+
193
+ let tile: Element | null | undefined;
194
+ try {
195
+ tile = findTargetElement(target, document);
196
+ } catch {
197
+ tile = null;
198
+ }
199
+ tile?.setAttribute(RECEIVED_COPY_ATTRIBUTE, '');
200
+
201
+ let timer: ReturnType<typeof setTimeout> | undefined;
202
+ let wait = timeout;
203
+ const view = document.defaultView;
204
+ const schedule = () => {
205
+ if (timer !== undefined) view.clearTimeout(timer);
206
+ timer = view.setTimeout(() => hide?.(), wait);
207
+ };
208
+ // Keep the notice while the pointer or the keyboard focus is on it. The listeners go with
209
+ // the notice, which is removed when it is dismissed.
210
+ notice.addEventListener('mouseenter', () => {
211
+ if (timer !== undefined) view.clearTimeout(timer);
212
+ timer = undefined;
213
+ });
214
+ notice.addEventListener('mouseleave', schedule);
215
+ notice.addEventListener('focusin', () => {
216
+ if (timer !== undefined) view.clearTimeout(timer);
217
+ timer = undefined;
218
+ });
219
+ notice.addEventListener('focusout', event => {
220
+ if (!notice.contains(event.relatedTarget as Node | null)) schedule();
221
+ });
222
+ close.addEventListener('click', () => hide?.());
223
+ undo.addEventListener('click', () => {
224
+ if (!removeSharedCopy(vm, copy)) {
225
+ hide?.();
226
+ return;
227
+ }
228
+ tile?.removeAttribute(RECEIVED_COPY_ATTRIBUTE);
229
+ undo.remove();
230
+ message.textContent = target.isStage ? words.removedFromStage : words.removedFromSprite(name);
231
+ close.focus();
232
+ wait = Math.min(timeout, 3000);
233
+ schedule();
234
+ });
235
+
236
+ const dismiss = () => {
237
+ if (timer !== undefined) view.clearTimeout(timer);
238
+ tile?.removeAttribute(RECEIVED_COPY_ATTRIBUTE);
239
+ notice.remove();
240
+ if (hide === dismiss) hide = undefined;
241
+ };
242
+ hide = dismiss;
243
+ schedule();
244
+ }
245
+
246
+ const patched = function (this: NoticeVM, blocks: unknown, targetId: string, fromTargetId?: string) {
247
+ const target = !disposed && fromTargetId && fromTargetId !== targetId ?
248
+ vm.runtime.getTargetById(targetId) : undefined;
249
+ if (!target) return original.call(this, blocks, targetId, fromTargetId);
250
+ const stage = vm.runtime.getTargetForStage();
251
+ const blocksBefore = new Set(Object.keys(target.blocks._blocks));
252
+ // Resolving variable conflicts runs synchronously, before the returned promise.
253
+ const owners = [...new Set([target, stage].filter(Boolean))];
254
+ const variablesBefore = new Map(owners.map(owner => [owner, new Set(Object.keys(owner.variables))]));
255
+ const result = original.call(this, blocks, targetId, fromTargetId);
256
+ Promise.resolve(result).then(() => {
257
+ if (disposed || vm.runtime.getTargetById(target.id) !== target) return;
258
+ const created = Object.keys(target.blocks._blocks).filter(id => !blocksBefore.has(id));
259
+ const createdSet = new Set(created);
260
+ const roots = created.filter(id => {
261
+ const block = target.blocks._blocks[id];
262
+ return block.topLevel || !block.parent || !createdSet.has(block.parent);
263
+ });
264
+ if (!roots.length) return;
265
+ const variables = owners.flatMap(owner => Object.keys(owner.variables)
266
+ .filter(id => !variablesBefore.get(owner).has(id)).map(id => ({owner, id})));
267
+ show({target, roots, variables});
268
+ }, () => {});
269
+ return result;
270
+ };
271
+ vm.shareBlocksToTarget = patched;
272
+
273
+ return {
274
+ dispose() {
275
+ disposed = true;
276
+ hide?.();
277
+ if (vm.shareBlocksToTarget !== patched) return;
278
+ if (hadOwn) vm.shareBlocksToTarget = original;
279
+ else delete vm.shareBlocksToTarget;
280
+ }
281
+ };
282
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Let "Restore Sprite" go back through more than the last deleted sprite.
3
+ *
4
+ * The GUI keeps one restore function in `scratchGui.restoreDeletion` and replaces it on every deletion,
5
+ * so only the last deleted sprite can be restored. This keeps the restore functions of earlier sprite
6
+ * deletions, and when the menu has used one and cleared the slot, it puts the previous one back.
7
+ * Nothing is added to the project: each restore function holds the deleted sprite itself.
8
+ */
9
+
10
+ export const RESTORE_UPDATE = 'scratch-gui/restore-deletion/RESTORE_UPDATE';
11
+ const sprite = 'Sprite';
12
+
13
+ /** How many deleted sprites can be restored, the one in the GUI's slot included. */
14
+ export const spriteRestoreLimit = 10;
15
+
16
+ type RestoreFunction = () => unknown;
17
+ interface RestoreDeletion {
18
+ restoreFun: RestoreFunction | null;
19
+ deletedItem: string;
20
+ }
21
+
22
+ export interface RestoreStore {
23
+ getState(): {scratchGui: {restoreDeletion: RestoreDeletion}};
24
+ dispatch(action: {type: string; state: RestoreDeletion}): unknown;
25
+ subscribe(listener: () => void): () => void;
26
+ }
27
+
28
+ interface ProjectEvents {
29
+ runtime: {
30
+ on(event: 'PROJECT_LOADED', listener: () => void): unknown;
31
+ removeListener(event: 'PROJECT_LOADED', listener: () => void): unknown;
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Keep up to `limit` sprite restore functions for the GUI's store. Pass `vm` to forget the earlier ones
37
+ * when another project is loaded; the one in the GUI's slot stays, as it did before.
38
+ * @returns Something to dispose, plus `count()` for the number of sprites that can be restored.
39
+ */
40
+ export function attachSpriteRestoreHistory({store, vm, limit = spriteRestoreLimit}: {
41
+ store: RestoreStore;
42
+ vm?: ProjectEvents;
43
+ limit?: number;
44
+ }) {
45
+ const read = () => store.getState().scratchGui.restoreDeletion;
46
+ // Oldest first. The last one is the one in the GUI's slot, or the next to put back there.
47
+ const stack: RestoreFunction[] = [];
48
+ let last = read();
49
+ if (last.restoreFun && last.deletedItem === sprite) stack.push(last.restoreFun);
50
+
51
+ const update = () => {
52
+ const current = read();
53
+ if (current.restoreFun === last.restoreFun && current.deletedItem === last.deletedItem) return;
54
+ const previous = last;
55
+ last = current;
56
+ if (current.restoreFun) {
57
+ if (current.deletedItem === sprite && !stack.includes(current.restoreFun)) {
58
+ stack.push(current.restoreFun);
59
+ if (stack.length > Math.max(1, limit)) stack.splice(0, stack.length - Math.max(1, limit));
60
+ }
61
+ return;
62
+ }
63
+ // The menu restored what the slot held and cleared it.
64
+ if (previous.restoreFun && previous.restoreFun === stack.at(-1)) stack.pop();
65
+ const next = stack.at(-1);
66
+ if (next) store.dispatch({type: RESTORE_UPDATE, state: {restoreFun: next, deletedItem: sprite}});
67
+ };
68
+ const unsubscribe = store.subscribe(update);
69
+
70
+ const projectLoaded = () => {
71
+ const {restoreFun} = read();
72
+ stack.length = 0;
73
+ if (restoreFun && read().deletedItem === sprite) stack.push(restoreFun);
74
+ };
75
+ vm?.runtime.on('PROJECT_LOADED', projectLoaded);
76
+
77
+ return {
78
+ count: () => stack.length,
79
+ dispose() {
80
+ unsubscribe();
81
+ vm?.runtime.removeListener('PROJECT_LOADED', projectLoaded);
82
+ stack.length = 0;
83
+ }
84
+ };
85
+ }