@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.
package/README.ja.md CHANGED
@@ -14,12 +14,17 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
14
14
  | `./code-extensions` | コードの表示の拡張パレットと、入力欄の操作のダイアログ |
15
15
  | `./procedure-editor` | 関数の編集ダイアログ |
16
16
  | `./variable-references` | 編集中の対象に絞った変数の参照 |
17
+ | `./variable-merge` | 名前の変更で変数・リストを既存のものに統合し、パレットから「このスプライトのみ」と「すべてのスプライト用」を切り替える |
17
18
  | `./target-combobox` | コードの窓の対象の選択 |
18
19
  | `./detached-block-palette` | 別窓のブロックパレット |
19
20
  | `./palette-category-reorder`・`./palette-category-search`・`./palette-dropdown-resize` | パレットのカテゴリの並べ替えと検索、パレットのドロップダウンの大きさの変更 |
20
21
  | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ |
21
- | `./block-argument-text` | 長いテキストの引数を短く表示し、ダイアログで編集する |
22
+ | `./block-argument-text` | 長いテキストの引数を短く表示し、ダイアログで編集する。テキストの引数で Shift+Enter を押すと、改行を入れてダイアログで編集を続ける |
22
23
  | `./block-number-input` | 数値の引数に入力した全角の数字・記号を半角にする |
24
+ | `./clean-up-comments` | 「きれいにする」でコメントをスクリプトについて動かす。ブロックのコメントはブロックとの相対位置を保ち、コメントを含めたスクリプト同士が重ならないようにし、スクリプトに重なるワークスペースのコメントはスクリプトの横へ移す(`installCleanUpComments(ScratchBlocks)`) |
25
+ | `./target-undo-history` | コードエリアの元に戻す・やり直しの履歴を、スプライト・ステージごとに保ち、切り替えて戻ったときに返す(`attachTargetUndoHistory({vm, getBlockly})`)。履歴を返すのは、離れたときからその対象のコードが変わっていない場合に限る |
26
+ | `./sprite-restore-history` | 「編集 → スプライトの復元」で、直前の1件だけでなく、削除した最近の10件まで順に戻せるようにする(`attachSpriteRestoreHistory({store, vm})`、GUI の Redux ストアを渡す) |
27
+ | `./sprite-copy-notice` | `attachSpriteCopyNotice`。スプライト一覧の上で離したスクリプトがスプライトや背景にコピーされたとき、そのタイルに印を付け、コピー先を示す通知を出す。通知の「元に戻す」でコピーを取り除く |
23
28
  | `./asset-edit-session`・`./dockview-unsaved` | 素材の編集のセッションと、Dockview のタブの未保存の印。ホストが GUI のエディターとレイアウトにつなぐ |
24
29
  | `./styles.css` | 上のすべてのスタイルシート |
25
30
 
package/README.md CHANGED
@@ -14,12 +14,17 @@ The code views of TurboWarp Plus Editor: code in tabs and windows that share one
14
14
  | `./code-extensions` | The extension palette and field action dialog of a code view |
15
15
  | `./procedure-editor` | The function editor dialog |
16
16
  | `./variable-references` | Variable references scoped to the edited target |
17
+ | `./variable-merge` | Merges a variable or list into another one on rename, and moves one between this sprite and all sprites from the palette |
17
18
  | `./target-combobox` | The target picker of a code window |
18
19
  | `./detached-block-palette` | The block palette in its own window |
19
20
  | `./palette-category-visibility`, `./palette-visibility-dialog` | Choose which block groups the palette shows for each sprite and the stage. The setting is saved with the editor's screen state, with a screen to choose |
20
21
  | `./palette-category-reorder`, `./palette-category-search`, `./palette-dropdown-resize` | Reordering and searching palette categories, and resizing palette dropdowns |
21
- | `./block-argument-text` | Shortens long text arguments and edits them in a dialog |
22
+ | `./block-argument-text` | Shortens long text arguments and edits them in a dialog. Shift+Enter in a text argument continues in the dialog with a line break |
22
23
  | `./block-number-input` | Converts full-width digits and signs typed into number arguments to half-width |
24
+ | `./clean-up-comments` | Keeps comments with their scripts in "Clean up blocks": block comments keep their offset from the block, scripts with their comments do not cover one another, and workspace comments that cover a script move beside the scripts (`installCleanUpComments(ScratchBlocks)`) |
25
+ | `./target-undo-history` | Keeps the code area's undo and redo history for each sprite and the stage across target switches (`attachTargetUndoHistory({vm, getBlockly})`). A history comes back only while the target's code is unchanged since it was put aside |
26
+ | `./sprite-restore-history` | Lets Edit → Restore Sprite go back through the last 10 deleted sprites, not only the last one (`attachSpriteRestoreHistory({store, vm})`, with the GUI's Redux store) |
27
+ | `./sprite-copy-notice` | `attachSpriteCopyNotice`: when a script dropped on the sprite list is copied into a sprite or the stage, marks its tile and shows a notice naming it, with Undo to remove the copy |
23
28
  | `./asset-edit-session`, `./dockview-unsaved` | The asset edit session and the unsaved marks on Dockview tabs, which the host connects to the GUI's editors and layout |
24
29
  | `./styles.css` | The stylesheet for all of the above |
25
30
 
@@ -4,6 +4,10 @@
4
4
  * The vertical renderer sets `MAX_DISPLAY_LENGTH` to Infinity, so a text argument draws every
5
5
  * character and the block grows until it covers its neighbours. This caps what a text argument
6
6
  * shows, and edits a value that no longer fits in a dialog instead of the one-line inline editor.
7
+ *
8
+ * A line break cannot be typed into the inline editor, which is a one-line `<input>` where Enter
9
+ * finishes the edit. Shift+Enter there finishes the inline edit as Enter would, then continues in
10
+ * the dialog with a line break at the caret. The block shows a value up to its first line break.
7
11
  */
8
12
  /** Display budget in half-width columns. A wide character, such as a kanji, takes two. */
9
13
  export declare const ARGUMENT_TEXT_COLUMNS = 30;
@@ -27,9 +31,16 @@ export declare const editsInDialog: (text: string) => boolean;
27
31
  * @param {string} value The current value.
28
32
  * @param {string} locale The editor's language.
29
33
  * @param {(value: string) => void} save Called with the edited value when the dialog is saved.
34
+ * @param {number} [caret] Where the caret starts, in UTF-16 units; the end of the value by default.
30
35
  * @returns {HTMLDialogElement} The open dialog.
31
36
  */
32
- export declare const openArgumentTextDialog: (document: Document, value: string, locale: string, save: (value: string) => void) => HTMLDialogElement;
37
+ export declare const openArgumentTextDialog: (document: Document, value: string, locale: string, save: (value: string) => void, caret?: number) => HTMLDialogElement;
38
+ /**
39
+ * True for Shift+Enter alone, outside an IME composition.
40
+ * @param {KeyboardEvent} event The keydown.
41
+ * @returns {boolean} Whether the key asks for a line break.
42
+ */
43
+ export declare const isLineBreakKey: (event?: Partial<KeyboardEvent> | null) => boolean;
33
44
  /**
34
45
  * Cap text arguments and route long values to the dialog.
35
46
  * Only plain text inputs open the dialog: number, text-with-menu and procedure-name fields keep
@@ -4,6 +4,10 @@
4
4
  * The vertical renderer sets `MAX_DISPLAY_LENGTH` to Infinity, so a text argument draws every
5
5
  * character and the block grows until it covers its neighbours. This caps what a text argument
6
6
  * shows, and edits a value that no longer fits in a dialog instead of the one-line inline editor.
7
+ *
8
+ * A line break cannot be typed into the inline editor, which is a one-line `<input>` where Enter
9
+ * finishes the edit. Shift+Enter there finishes the inline edit as Enter would, then continues in
10
+ * the dialog with a line break at the caret. The block shows a value up to its first line break.
7
11
  */
8
12
  /** Display budget in half-width columns. A wide character, such as a kanji, takes two. */
9
13
  export const ARGUMENT_TEXT_COLUMNS = 30;
@@ -49,9 +53,10 @@ const text = (locale) => /^ja(?:-|$)/i.test(locale) ? {
49
53
  * @param {string} value The current value.
50
54
  * @param {string} locale The editor's language.
51
55
  * @param {(value: string) => void} save Called with the edited value when the dialog is saved.
56
+ * @param {number} [caret] Where the caret starts, in UTF-16 units; the end of the value by default.
52
57
  * @returns {HTMLDialogElement} The open dialog.
53
58
  */
54
- export const openArgumentTextDialog = (document, value, locale, save) => {
59
+ export const openArgumentTextDialog = (document, value, locale, save, caret = value.length) => {
55
60
  const labels = text(locale);
56
61
  const dialog = document.createElement('dialog');
57
62
  dialog.className = 'twPlusArgumentTextDialog';
@@ -106,9 +111,18 @@ export const openArgumentTextDialog = (document, value, locale, save) => {
106
111
  document.body.append(dialog);
107
112
  dialog.showModal();
108
113
  area.focus();
109
- area.setSelectionRange(area.value.length, area.value.length);
114
+ const at = Math.max(0, Math.min(caret, area.value.length));
115
+ area.setSelectionRange(at, at);
110
116
  return dialog;
111
117
  };
118
+ /**
119
+ * True for Shift+Enter alone, outside an IME composition.
120
+ * @param {KeyboardEvent} event The keydown.
121
+ * @returns {boolean} Whether the key asks for a line break.
122
+ */
123
+ export const isLineBreakKey = (event) => !!event &&
124
+ (event.key === 'Enter' || event.keyCode === 13) && !!event.shiftKey &&
125
+ !event.ctrlKey && !event.metaKey && !event.altKey && !event.isComposing && event.keyCode !== 229;
112
126
  const installed = new WeakSet();
113
127
  /**
114
128
  * Cap text arguments and route long values to the dialog.
@@ -122,7 +136,7 @@ export const installBlockArgumentText = ScratchBlocks => {
122
136
  if (!field?.showEditor_ || !field.getDisplayText_ || installed.has(field))
123
137
  return;
124
138
  installed.add(field);
125
- const { getDisplayText_: displayText, showEditor_: showEditor } = field;
139
+ const { getDisplayText_: displayText, showEditor_: showEditor, onHtmlInputKeyDown_: keyDown } = field;
126
140
  field.getDisplayText_ = function (...args) {
127
141
  const value = this.text_;
128
142
  const cut = typeof value === 'string' ? argumentTextCut(value) : undefined;
@@ -146,25 +160,56 @@ export const installBlockArgumentText = ScratchBlocks => {
146
160
  }
147
161
  ScratchBlocks.WidgetDiv?.hide?.();
148
162
  ScratchBlocks.DropDownDiv?.hideWithoutAnimation?.();
163
+ openDialog(this, document, this.text_);
164
+ };
165
+ /**
166
+ * Edit a plain text field's value in the dialog and apply what is saved there.
167
+ * @param {object} self The field.
168
+ * @param {Document} document The editor's document.
169
+ * @param {string} value The value the dialog starts with.
170
+ * @param {number} [caret] Where the caret starts.
171
+ */
172
+ const openDialog = (self, document, value, caret) => {
173
+ const block = self.sourceBlock_;
149
174
  const locale = ScratchBlocks.ScratchMsgs?.currentLocale_ ?? document.documentElement.lang ?? 'en';
150
- openArgumentTextDialog(document, this.text_, locale, value => {
151
- if (this.sourceBlock_ !== block || !block.workspace)
175
+ openArgumentTextDialog(document, value, locale, next => {
176
+ if (self.sourceBlock_ !== block || !block?.workspace)
152
177
  return;
153
- const validated = this.callValidator(value);
178
+ const validated = self.callValidator(next);
154
179
  if (validated === null)
155
180
  return;
156
181
  const events = ScratchBlocks.Events;
157
182
  events?.setGroup?.(true);
158
183
  try {
159
184
  // Same path as the inline editor's save: one change event, then the render.
160
- this.setText(validated);
161
- this.onFinishEditing_?.(validated);
185
+ self.setText(validated);
186
+ self.onFinishEditing_?.(validated);
162
187
  }
163
188
  finally {
164
189
  events?.setGroup?.(false);
165
190
  }
166
191
  if (block.rendered)
167
192
  block.render();
168
- });
193
+ }, caret);
194
+ };
195
+ if (!keyDown)
196
+ return;
197
+ field.onHtmlInputKeyDown_ = function (event, ...rest) {
198
+ const input = FieldTextInput.htmlInput_;
199
+ const document = input?.ownerDocument;
200
+ if (!isLineBreakKey(event) || Object.getPrototypeOf(this) !== field || this.restrictor_ ||
201
+ !input || input.readOnly || !document) {
202
+ return keyDown.call(this, event, ...rest);
203
+ }
204
+ event.preventDefault?.();
205
+ const { value } = input;
206
+ const start = input.selectionStart ?? value.length;
207
+ const end = input.selectionEnd ?? start;
208
+ const next = `${value.slice(0, start)}\n${value.slice(end)}`;
209
+ // Finish the inline edit as Enter does, so the dialog edits a saved value.
210
+ ScratchBlocks.WidgetDiv?.hide?.();
211
+ ScratchBlocks.DropDownDiv?.hideWithoutAnimation?.();
212
+ if (this.sourceBlock_?.workspace)
213
+ openDialog(this, document, next, start + 1);
169
214
  };
170
215
  };
@@ -0,0 +1,70 @@
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
+ interface Point {
17
+ x: number;
18
+ y: number;
19
+ }
20
+ export interface Rect {
21
+ left: number;
22
+ top: number;
23
+ right: number;
24
+ bottom: number;
25
+ }
26
+ /** A script with its block comments, as it stands after the wrapped clean-up. */
27
+ export interface ScriptCluster {
28
+ id: string;
29
+ /** Where the wrapped clean-up put the top block. */
30
+ x: number;
31
+ y: number;
32
+ /** The script and its block comments together. */
33
+ rect: Rect;
34
+ }
35
+ export interface LooseComment {
36
+ id: string;
37
+ rect: Rect;
38
+ }
39
+ /** Room left between a script and what it would otherwise cover. */
40
+ export declare const cleanUpGap = 32;
41
+ /**
42
+ * How far to move each script so that no script with its comments covers another.
43
+ * The clean-up's columns are kept: scripts that start at the same x form a column, read from left to right and
44
+ * each from top to bottom. A script that would cover the one above it moves down, and every script below it with
45
+ * it; a column that would cover the columns to its left moves right, and every column after it with it. Where
46
+ * nothing is covered nothing moves, so the clean-up's own spacing stays.
47
+ * @param {ScriptCluster[]} clusters The scripts after the clean-up.
48
+ * @param {number} gap Room left between a script and the next.
49
+ * @returns {Map<string, Point>} The offset of each script that moves.
50
+ */
51
+ export declare function separateClusters(clusters: readonly ScriptCluster[], gap?: number): Map<string, Point>;
52
+ /**
53
+ * Where to put the workspace comments that cover a script.
54
+ * A comment that covers nothing stays. The others go, in reading order, into a column to the right of the scripts
55
+ * and of the comments that stay, from the top of the scripts down.
56
+ * @param {Rect[]} scripts The scripts with their block comments, where they end up.
57
+ * @param {LooseComment[]} comments The workspace comments.
58
+ * @param {number} gap Room left around a moved comment.
59
+ * @returns {Map<string, Point>} The offset of each comment that moves.
60
+ */
61
+ export declare function placeLooseComments(scripts: readonly Rect[], comments: readonly LooseComment[], gap?: number): Map<string, Point>;
62
+ /**
63
+ * Keep comments with their scripts in "Clean up blocks".
64
+ * `WorkspaceSvg.prototype.cleanUp` becomes an accessor, so a `cleanUp` that an addon puts there later is wrapped
65
+ * too. A workspace that is given its own `cleanUp` keeps it as its own, unwrapped. Workspaces laid out right to
66
+ * left are cleaned up as before.
67
+ * @param {object} ScratchBlocks The loaded ScratchBlocks.
68
+ */
69
+ export declare const installCleanUpComments: (ScratchBlocks: any) => void;
70
+ export {};
@@ -0,0 +1,226 @@
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
+ /** Room left between a script and what it would otherwise cover. */
17
+ export const cleanUpGap = 32;
18
+ const overlaps = (a, b) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
19
+ const shifted = (rect, dx, dy) => ({ left: rect.left + dx, top: rect.top + dy, right: rect.right + dx, bottom: rect.bottom + dy });
20
+ /**
21
+ * How far to move each script so that no script with its comments covers another.
22
+ * The clean-up's columns are kept: scripts that start at the same x form a column, read from left to right and
23
+ * each from top to bottom. A script that would cover the one above it moves down, and every script below it with
24
+ * it; a column that would cover the columns to its left moves right, and every column after it with it. Where
25
+ * nothing is covered nothing moves, so the clean-up's own spacing stays.
26
+ * @param {ScriptCluster[]} clusters The scripts after the clean-up.
27
+ * @param {number} gap Room left between a script and the next.
28
+ * @returns {Map<string, Point>} The offset of each script that moves.
29
+ */
30
+ export function separateClusters(clusters, gap = cleanUpGap) {
31
+ const columns = new Map();
32
+ for (const cluster of clusters) {
33
+ const column = columns.get(cluster.x);
34
+ if (column)
35
+ column.push(cluster);
36
+ else
37
+ columns.set(cluster.x, [cluster]);
38
+ }
39
+ const moves = new Map();
40
+ let shiftX = 0;
41
+ let rightEdge = -Infinity;
42
+ for (const x of [...columns.keys()].sort((a, b) => a - b)) {
43
+ const column = columns.get(x).sort((a, b) => a.y - b.y || a.rect.top - b.rect.top || (a.id < b.id ? -1 : 1));
44
+ const left = Math.min(...column.map(cluster => cluster.rect.left));
45
+ if (left + shiftX < rightEdge + gap)
46
+ shiftX = rightEdge + gap - left;
47
+ let shiftY = 0;
48
+ let bottomEdge = -Infinity;
49
+ for (const cluster of column) {
50
+ if (cluster.rect.top + shiftY < bottomEdge + gap)
51
+ shiftY = bottomEdge + gap - cluster.rect.top;
52
+ bottomEdge = cluster.rect.bottom + shiftY;
53
+ rightEdge = Math.max(rightEdge, cluster.rect.right + shiftX);
54
+ if (shiftX || shiftY)
55
+ moves.set(cluster.id, { x: shiftX, y: shiftY });
56
+ }
57
+ }
58
+ return moves;
59
+ }
60
+ /**
61
+ * Where to put the workspace comments that cover a script.
62
+ * A comment that covers nothing stays. The others go, in reading order, into a column to the right of the scripts
63
+ * and of the comments that stay, from the top of the scripts down.
64
+ * @param {Rect[]} scripts The scripts with their block comments, where they end up.
65
+ * @param {LooseComment[]} comments The workspace comments.
66
+ * @param {number} gap Room left around a moved comment.
67
+ * @returns {Map<string, Point>} The offset of each comment that moves.
68
+ */
69
+ export function placeLooseComments(scripts, comments, gap = cleanUpGap) {
70
+ const moves = new Map();
71
+ const covering = comments.filter(comment => scripts.some(script => overlaps(script, comment.rect)));
72
+ if (!covering.length)
73
+ return moves;
74
+ const staying = comments.filter(comment => !covering.includes(comment)).map(comment => comment.rect);
75
+ const occupied = [...scripts, ...staying];
76
+ const x = Math.max(...occupied.map(rect => rect.right)) + gap;
77
+ let y = scripts.length ? Math.min(...scripts.map(rect => rect.top)) : 0;
78
+ const ordered = [...covering].sort((a, b) => a.rect.top - b.rect.top || a.rect.left - b.rect.left ||
79
+ (a.id < b.id ? -1 : 1));
80
+ for (const comment of ordered) {
81
+ moves.set(comment.id, { x: x - comment.rect.left, y: y - comment.rect.top });
82
+ y += comment.rect.bottom - comment.rect.top + gap;
83
+ }
84
+ return moves;
85
+ }
86
+ const toRect = ({ topLeft, bottomRight }) => ({ left: topLeft.x, top: topLeft.y, right: bottomRight.x, bottom: bottomRight.y });
87
+ const union = (a, b) => ({ left: Math.min(a.left, b.left), top: Math.min(a.top, b.top),
88
+ right: Math.max(a.right, b.right), bottom: Math.max(a.bottom, b.bottom) });
89
+ const alive = (item) => Boolean(item?.workspace);
90
+ const isBlockComment = (comment) => Boolean(comment.block_);
91
+ /**
92
+ * Read each block comment's offset from its block.
93
+ * @param {object} workspace The workspace about to be cleaned up.
94
+ * @returns {Attached[]} The block comments with their offsets.
95
+ */
96
+ function readAttached(workspace) {
97
+ return (workspace.getTopComments?.(false) ?? []).flatMap(comment => {
98
+ const block = comment.block_;
99
+ if (!block || !alive(block) || !comment.getXY || !comment.moveTo)
100
+ return [];
101
+ const commentXY = comment.getXY();
102
+ const blockXY = block.getRelativeToSurfaceXY();
103
+ return [{ comment, block, offset: { x: commentXY.x - blockXY.x, y: commentXY.y - blockXY.y } }];
104
+ });
105
+ }
106
+ /**
107
+ * Lay out the scripts and comments again after the wrapped clean-up.
108
+ * @param {object} workspace The cleaned-up workspace.
109
+ * @param {Attached[]} attached The block comments read before the clean-up.
110
+ * @param {object} events `ScratchBlocks.Events`.
111
+ */
112
+ function followUp(workspace, attached, events) {
113
+ const kept = attached.filter(({ comment, block }) => alive(comment) && alive(block));
114
+ const placed = (item) => {
115
+ const blockXY = item.block.getRelativeToSurfaceXY();
116
+ return { x: blockXY.x + item.offset.x, y: blockXY.y + item.offset.y };
117
+ };
118
+ const commentRect = (item) => {
119
+ const rect = toRect(item.comment.getBoundingRectangle());
120
+ const { x, y } = placed(item);
121
+ return { left: x, top: y, right: x + rect.right - rect.left, bottom: y + rect.bottom - rect.top };
122
+ };
123
+ const scripts = workspace.getTopBlocks(false).filter(alive);
124
+ const clusters = scripts.map(block => {
125
+ const { x, y } = block.getRelativeToSurfaceXY();
126
+ let rect = toRect(block.getBoundingRectangle());
127
+ for (const item of kept) {
128
+ if (item.block.getRootBlock() === block)
129
+ rect = union(rect, commentRect(item));
130
+ }
131
+ return { id: block.id, x, y, rect, block };
132
+ });
133
+ const scriptMoves = separateClusters(clusters);
134
+ // Join the clean-up's undo group, which scratch-blocks has already closed by now, so that one undo takes back
135
+ // the clean-up and these moves together.
136
+ const outer = events?.getGroup() ?? '';
137
+ const group = outer || events?.FIRE_QUEUE_?.at(-1)?.group || true;
138
+ events?.setGroup(group);
139
+ workspace.setResizesEnabled?.(false);
140
+ try {
141
+ for (const cluster of clusters) {
142
+ const move = scriptMoves.get(cluster.id);
143
+ if (move)
144
+ cluster.block.moveBy(move.x, move.y);
145
+ }
146
+ // scratch-blocks moves an open comment with its block, but the addon's clean-up puts it back beside the
147
+ // block; put every one back where it was from its block, which also tells the VM where it is.
148
+ for (const item of kept) {
149
+ const { x, y } = placed(item);
150
+ item.comment.moveTo(x, y);
151
+ }
152
+ const loose = (workspace.getTopComments?.(false) ?? [])
153
+ .filter(comment => alive(comment) && !isBlockComment(comment) && comment.moveBy);
154
+ const looseMoves = placeLooseComments(clusters.map(({ id, rect }) => {
155
+ const move = scriptMoves.get(id);
156
+ return move ? shifted(rect, move.x, move.y) : rect;
157
+ }), loose.map(comment => ({ id: comment.id, rect: toRect(comment.getBoundingRectangle()) })));
158
+ for (const comment of loose) {
159
+ const move = looseMoves.get(comment.id);
160
+ if (move)
161
+ comment.moveBy(move.x, move.y);
162
+ }
163
+ }
164
+ finally {
165
+ workspace.setResizesEnabled?.(true);
166
+ events?.setGroup(outer);
167
+ }
168
+ }
169
+ const installed = new WeakSet();
170
+ /**
171
+ * Keep comments with their scripts in "Clean up blocks".
172
+ * `WorkspaceSvg.prototype.cleanUp` becomes an accessor, so a `cleanUp` that an addon puts there later is wrapped
173
+ * too. A workspace that is given its own `cleanUp` keeps it as its own, unwrapped. Workspaces laid out right to
174
+ * left are cleaned up as before.
175
+ * @param {object} ScratchBlocks The loaded ScratchBlocks.
176
+ */
177
+ export const installCleanUpComments = ScratchBlocks => {
178
+ const prototype = ScratchBlocks?.WorkspaceSvg?.prototype;
179
+ if (!prototype || installed.has(prototype) || typeof prototype.cleanUp !== 'function')
180
+ return;
181
+ installed.add(prototype);
182
+ const events = ScratchBlocks.Events;
183
+ const wrappers = new WeakMap();
184
+ let running = false;
185
+ const wrap = (cleanUp) => {
186
+ if (typeof cleanUp !== 'function')
187
+ return cleanUp;
188
+ let wrapper = wrappers.get(cleanUp);
189
+ if (wrapper)
190
+ return wrapper;
191
+ wrapper = function (...args) {
192
+ // An addon's clean-up can call the one it replaced, which is wrapped as well.
193
+ if (running || this.RTL || this.isFlyout)
194
+ return cleanUp.apply(this, args);
195
+ const attached = readAttached(this);
196
+ running = true;
197
+ let result;
198
+ try {
199
+ result = cleanUp.apply(this, args);
200
+ }
201
+ finally {
202
+ running = false;
203
+ }
204
+ followUp(this, attached, events);
205
+ return result;
206
+ };
207
+ wrappers.set(cleanUp, wrapper);
208
+ return wrapper;
209
+ };
210
+ let current = prototype.cleanUp;
211
+ Object.defineProperty(prototype, 'cleanUp', {
212
+ configurable: true,
213
+ enumerable: false,
214
+ get() {
215
+ return wrap(current);
216
+ },
217
+ set(value) {
218
+ if (this === prototype) {
219
+ current = value;
220
+ return;
221
+ }
222
+ // Assigning to a workspace gives it its own clean-up, as it did before this accessor.
223
+ Object.defineProperty(this, 'cleanUp', { value, writable: true, configurable: true, enumerable: true });
224
+ }
225
+ });
226
+ };
@@ -0,0 +1,106 @@
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
+ interface SharedBlock {
12
+ id: string;
13
+ parent?: string | null;
14
+ topLevel?: boolean;
15
+ }
16
+ interface NoticeTarget {
17
+ id: string;
18
+ isStage: boolean;
19
+ isOriginal?: boolean;
20
+ getName(): string;
21
+ blocks: {
22
+ _blocks: Record<string, SharedBlock>;
23
+ deleteBlock(id: string): void;
24
+ getAllVariableAndListReferences(optBlocks?: unknown): Record<string, unknown>;
25
+ };
26
+ variables: Record<string, unknown>;
27
+ deleteVariable(id: string): void;
28
+ }
29
+ interface NoticeVM {
30
+ editingTarget: NoticeTarget | null;
31
+ runtime: {
32
+ targets: NoticeTarget[];
33
+ getTargetById(id: string): NoticeTarget | undefined;
34
+ getTargetForStage(): NoticeTarget | undefined;
35
+ };
36
+ shareBlocksToTarget(blocks: unknown, targetId: string, fromTargetId?: string): Promise<unknown>;
37
+ emitWorkspaceUpdate?(): void;
38
+ emitTargetsUpdate?(triggerProjectChange?: boolean): void;
39
+ }
40
+ export interface SpriteCopyNoticeOptions {
41
+ vm: NoticeVM;
42
+ document: Document;
43
+ /** The GUI's locale, or a function that reads it when a notice is shown. */
44
+ locale?: string | (() => string | undefined);
45
+ /** How long a notice stays, in milliseconds, while the pointer is not on it. */
46
+ timeout?: number;
47
+ /** The tile of a target in the sprite list. The default finds the GUI's sprite and stage tiles. */
48
+ findTargetElement?(target: NoticeTarget, document: Document): Element | null | undefined;
49
+ }
50
+ /** What one drop added to a target, and how to take it back. */
51
+ export interface SharedCopy {
52
+ target: NoticeTarget;
53
+ /** The top blocks of the copied scripts. */
54
+ roots: string[];
55
+ /** Variables the copy created, with the target that holds each. */
56
+ variables: Array<{
57
+ owner: NoticeTarget;
58
+ id: string;
59
+ }>;
60
+ }
61
+ declare const messages: {
62
+ en: {
63
+ copiedToSprite: (name: string) => string;
64
+ copiedToStage: string;
65
+ undo: string;
66
+ close: string;
67
+ removedFromSprite: (name: string) => string;
68
+ removedFromStage: string;
69
+ };
70
+ ja: {
71
+ copiedToSprite: (name: string) => string;
72
+ copiedToStage: string;
73
+ undo: string;
74
+ close: string;
75
+ removedFromSprite: (name: string) => string;
76
+ removedFromStage: string;
77
+ };
78
+ 'ja-hira': {
79
+ copiedToSprite: (name: string) => string;
80
+ copiedToStage: string;
81
+ undo: string;
82
+ close: string;
83
+ removedFromSprite: (name: string) => string;
84
+ removedFromStage: string;
85
+ };
86
+ };
87
+ export type SpriteCopyNoticeMessages = typeof messages.en;
88
+ /** The notice's wording for a locale: ja-hira, ja, and English for anything else. */
89
+ export declare function spriteCopyNoticeMessages(locale?: string): SpriteCopyNoticeMessages;
90
+ /** Marks the tile of the target that received a copy, for as long as the notice is shown. */
91
+ export declare const RECEIVED_COPY_ATTRIBUTE = "data-tw-received-copy";
92
+ /**
93
+ * Remove what a drop copied into a target: its scripts, and the variables it created that no
94
+ * script refers to any more. Scripts the user already deleted are skipped.
95
+ * @returns Whether anything was removed.
96
+ */
97
+ export declare function removeSharedCopy(vm: NoticeVM, copy: SharedCopy): boolean;
98
+ /**
99
+ * Show a notice naming the sprite (or the stage) that a drop on the sprite list copied a script
100
+ * into, mark its tile, and offer to undo the copy.
101
+ * @returns `dispose`, which removes the notice and stops watching the VM.
102
+ */
103
+ export declare function attachSpriteCopyNotice({ vm, document, locale, timeout, findTargetElement }: SpriteCopyNoticeOptions): {
104
+ dispose(): void;
105
+ };
106
+ export {};