@kubohiroya/turbowarp-plus-editor-code-views 0.0.0-stage → 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.
Files changed (108) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +38 -0
  3. package/README.md +37 -2
  4. package/dist/asset-edit-session.d.ts +24 -0
  5. package/dist/asset-edit-session.js +58 -0
  6. package/dist/block-argument-text.d.ts +39 -0
  7. package/dist/block-argument-text.js +170 -0
  8. package/dist/block-drag.d.ts +17 -0
  9. package/dist/block-drag.js +184 -0
  10. package/dist/code-extensions.d.ts +38 -0
  11. package/dist/code-extensions.js +418 -0
  12. package/dist/code-pane.d.ts +63 -0
  13. package/dist/code-pane.js +363 -0
  14. package/dist/custom-extension-fields.d.ts +45 -0
  15. package/dist/custom-extension-fields.js +144 -0
  16. package/dist/detached-block-palette-view.d.ts +10 -0
  17. package/dist/detached-block-palette-view.js +62 -0
  18. package/dist/detached-block-palette.d.ts +41 -0
  19. package/dist/detached-block-palette.js +197 -0
  20. package/dist/dockview-unsaved.d.ts +45 -0
  21. package/dist/dockview-unsaved.js +123 -0
  22. package/dist/history.d.ts +57 -0
  23. package/dist/history.js +85 -0
  24. package/dist/index.d.ts +28 -0
  25. package/dist/index.js +729 -0
  26. package/dist/native-extension-field.d.ts +26 -0
  27. package/dist/native-extension-field.js +204 -0
  28. package/dist/native-field-svg.d.ts +20 -0
  29. package/dist/native-field-svg.js +156 -0
  30. package/dist/palette-category-reorder.d.ts +4 -0
  31. package/dist/palette-category-reorder.js +167 -0
  32. package/dist/palette-category-search.d.ts +26 -0
  33. package/dist/palette-category-search.js +74 -0
  34. package/dist/palette-dropdown-resize.d.ts +19 -0
  35. package/dist/palette-dropdown-resize.js +135 -0
  36. package/dist/parent-field-layout.d.ts +2 -0
  37. package/dist/parent-field-layout.js +90 -0
  38. package/dist/parent-field-mirror.d.ts +3 -0
  39. package/dist/parent-field-mirror.js +290 -0
  40. package/dist/parent-field-resources.d.ts +9 -0
  41. package/dist/parent-field-resources.js +199 -0
  42. package/dist/preview-chrome.d.ts +9 -0
  43. package/dist/preview-chrome.js +78 -0
  44. package/dist/procedure-editor.d.ts +9 -0
  45. package/dist/procedure-editor.js +122 -0
  46. package/dist/procedure-edits.d.ts +16 -0
  47. package/dist/procedure-edits.js +47 -0
  48. package/dist/programmatic-extension-field.d.ts +20 -0
  49. package/dist/programmatic-extension-field.js +69 -0
  50. package/dist/protocol.d.ts +15 -0
  51. package/dist/protocol.js +36 -0
  52. package/dist/script-layout-dialog.d.ts +10 -0
  53. package/dist/script-layout-dialog.js +93 -0
  54. package/dist/script-layout-view.d.ts +68 -0
  55. package/dist/script-layout-view.js +164 -0
  56. package/dist/script-layout-workspace.d.ts +45 -0
  57. package/dist/script-layout-workspace.js +55 -0
  58. package/dist/script-layout.d.ts +17 -0
  59. package/dist/script-layout.js +25 -0
  60. package/dist/script-view-menu.d.ts +46 -0
  61. package/dist/script-view-menu.js +161 -0
  62. package/dist/sprite-code-windows.d.ts +31 -0
  63. package/dist/sprite-code-windows.js +180 -0
  64. package/dist/stage-code-prewarm.d.ts +52 -0
  65. package/dist/stage-code-prewarm.js +216 -0
  66. package/dist/target-combobox.d.ts +10 -0
  67. package/dist/target-combobox.js +92 -0
  68. package/dist/variable-references.d.ts +1 -0
  69. package/dist/variable-references.js +87 -0
  70. package/dist/workspace.d.ts +103 -0
  71. package/dist/workspace.js +1102 -0
  72. package/package.json +100 -4
  73. package/src/asset-edit-session.ts +72 -0
  74. package/src/block-argument-text.ts +172 -0
  75. package/src/block-drag.ts +190 -0
  76. package/src/code-extensions.ts +394 -0
  77. package/src/code-pane.ts +353 -0
  78. package/src/custom-extension-fields.ts +154 -0
  79. package/src/detached-block-palette-view.tsx +97 -0
  80. package/src/detached-block-palette.ts +218 -0
  81. package/src/dockview-unsaved.ts +134 -0
  82. package/src/history.ts +114 -0
  83. package/src/index.ts +680 -0
  84. package/src/native-extension-field.ts +201 -0
  85. package/src/native-field-svg.ts +140 -0
  86. package/src/palette-category-reorder.ts +155 -0
  87. package/src/palette-category-search.ts +82 -0
  88. package/src/palette-dropdown-resize.ts +132 -0
  89. package/src/parent-field-layout.ts +88 -0
  90. package/src/parent-field-mirror.ts +260 -0
  91. package/src/parent-field-resources.ts +179 -0
  92. package/src/preview-chrome.ts +82 -0
  93. package/src/procedure-editor.ts +123 -0
  94. package/src/procedure-edits.ts +46 -0
  95. package/src/programmatic-extension-field.ts +76 -0
  96. package/src/protocol.ts +47 -0
  97. package/src/script-layout-dialog.ts +104 -0
  98. package/src/script-layout-view.ts +198 -0
  99. package/src/script-layout-workspace.ts +95 -0
  100. package/src/script-layout.ts +40 -0
  101. package/src/script-view-menu.ts +213 -0
  102. package/src/sprite-code-windows.tsx +182 -0
  103. package/src/stage-code-prewarm.ts +242 -0
  104. package/src/styles.css +595 -0
  105. package/src/target-combobox.tsx +106 -0
  106. package/src/variable-references.ts +85 -0
  107. package/src/workspace.ts +1124 -0
  108. package/tsconfig.json +23 -0
@@ -0,0 +1,1102 @@
1
+ import { attachBlockDrag } from "./block-drag.js";
2
+ import { workspaceXML } from "./history.js";
3
+ import { isFoldedDefinition, removeObsoleteProcedureInputs, setFoldedDefinition } from "./procedure-edits.js";
4
+ import { decodeEdit, encodeEdit, isCommentEdit } from "./protocol.js";
5
+ import { captureCodePreviewChrome } from "./preview-chrome.js";
6
+ import { attachScriptView, getDockedScriptLayout } from "./script-layout-view.js";
7
+ const sessions = new WeakMap();
8
+ export function getCodeSession(vm) {
9
+ let session = sessions.get(vm);
10
+ if (!session) {
11
+ const listeners = new Set();
12
+ session = {
13
+ bridge: null,
14
+ frontView: null,
15
+ subscribe(listener) {
16
+ listeners.add(listener);
17
+ return () => listeners.delete(listener);
18
+ },
19
+ changed() {
20
+ for (const listener of listeners)
21
+ listener();
22
+ }
23
+ };
24
+ sessions.set(vm, session);
25
+ }
26
+ return session;
27
+ }
28
+ const withoutEvents = (blocks, action) => {
29
+ blocks.Events.disable();
30
+ try {
31
+ return action();
32
+ }
33
+ finally {
34
+ blocks.Events.enable();
35
+ }
36
+ };
37
+ /**
38
+ * Lay out again the blocks a workspace drew while it was not displayed. ScratchBlocks measures text with the
39
+ * SVG it draws, which reads as no width in a hidden container, and keeps that width: labels then overlap and
40
+ * blocks shrink. Children are laid out before their parents, so each parent takes their new size.
41
+ * Returns whether anything was laid out again.
42
+ */
43
+ /** The variables of a target and one of its scripts, as `targetXml` gives all of them. */
44
+ function scriptXml(vm, target, id) {
45
+ const stage = vm.runtime.getTargetForStage();
46
+ const globals = Object.values(stage.variables).map(variable => variable.toXML());
47
+ const locals = target === stage ? [] : Object.values(target.variables).map(variable => variable.toXML(true));
48
+ return `<xml xmlns="http://www.w3.org/1999/xhtml"><variables>${globals.join('')}${locals.join('')}</variables>` +
49
+ `${target.blocks.blockToXML(id, target.comments)}</xml>`;
50
+ }
51
+ export function remeasureHiddenFields(workspace) {
52
+ const unmeasured = (field) => Boolean(field.textElement_?.textContent) && field.size_?.width === 0;
53
+ const roots = new Set();
54
+ for (const block of workspace.getAllBlocks(false)) {
55
+ if (block.rendered && block.inputList.some(input => input.fieldRow.some(unmeasured)))
56
+ roots.add(block.getRootBlock());
57
+ }
58
+ for (const root of roots) {
59
+ for (const block of root.getDescendants(false).reverse()) {
60
+ for (const input of block.inputList) {
61
+ for (const field of input.fieldRow)
62
+ if (field.size_ && field.textElement_)
63
+ field.size_.width = 0;
64
+ }
65
+ if (block.rendered)
66
+ block.render(false);
67
+ }
68
+ }
69
+ return roots.size > 0;
70
+ }
71
+ function targetXml(vm, target) {
72
+ const stage = vm.runtime.getTargetForStage();
73
+ const globals = Object.values(stage.variables).map(variable => variable.toXML());
74
+ const locals = target === stage ? [] : Object.values(target.variables).map(variable => variable.toXML(true));
75
+ const comments = Object.values(target.comments).filter(comment => comment.blockId === null)
76
+ .map(comment => comment.toXML());
77
+ return `<xml xmlns="http://www.w3.org/1999/xhtml"><variables>${globals.join('')}${locals.join('')}</variables>` +
78
+ `${comments.join('')}${target.blocks.toXML(target.comments)}</xml>`;
79
+ }
80
+ const svgNamespace = 'http://www.w3.org/2000/svg';
81
+ const foldMarkAttribute = 'data-tw-plus-folded-mark';
82
+ /** Marks the workspace methods the one-script mode puts in place, so a later attachment can take them away. */
83
+ const focusOverride = Symbol('tw-plus-focus-override');
84
+ /** Hide an element of the workspace in a way ScratchBlocks does not undo (see script-layout.css). */
85
+ const setElementHidden = (element, hidden) => element?.toggleAttribute('data-tw-plus-hidden', hidden);
86
+ const isElementHidden = (element) => Boolean(element?.hasAttribute('data-tw-plus-hidden'));
87
+ const isHatBlock = (block) => !block.previousConnection && !block.outputConnection;
88
+ function setCommentsHidden(block, hidden) {
89
+ for (const item of block.getDescendants(false)) {
90
+ setElementHidden(item.comment?.bubble_?.bubbleGroup_, hidden);
91
+ }
92
+ }
93
+ /**
94
+ * Show a hat without the rest of its script, with a “Folded” mark below it, or show the whole script again.
95
+ * The body stays in the workspace, so editing a function still updates its calls there; it is only hidden
96
+ * and cannot be snapped to. `onUnfold` makes the mark a button.
97
+ */
98
+ function paintFold(hat, folded, label, onUnfold) {
99
+ const root = hat.getSvgRoot();
100
+ const body = hat.getNextBlock();
101
+ const mark = root?.querySelector(`:scope > [${foldMarkAttribute}]`);
102
+ if (!folded || !body || !root) {
103
+ mark?.remove();
104
+ if (isElementHidden(body?.getSvgRoot())) {
105
+ setElementHidden(body.getSvgRoot(), false);
106
+ body.setConnectionsHidden(false);
107
+ setCommentsHidden(body, false);
108
+ hat.nextConnection?.setHidden(false);
109
+ }
110
+ return;
111
+ }
112
+ setElementHidden(body.getSvgRoot(), true);
113
+ body.setConnectionsHidden(true);
114
+ setCommentsHidden(body, true);
115
+ hat.nextConnection?.setHidden(true);
116
+ if (mark)
117
+ mark.remove();
118
+ const document = root.ownerDocument;
119
+ const group = document.createElementNS(svgNamespace, 'g');
120
+ group.setAttribute(foldMarkAttribute, '');
121
+ group.setAttribute('transform', `translate(0, ${hat.height ?? 48})`);
122
+ const width = Math.max(120, Math.min(hat.width ?? 120, 220));
123
+ const back = document.createElementNS(svgNamespace, 'rect');
124
+ for (const [name, value] of Object.entries({ width, height: 28, rx: 4, fill: hat.getColour?.() ?? '#888',
125
+ stroke: hat.getColourTertiary?.() ?? '#666', 'fill-opacity': 0.6, 'stroke-dasharray': '4 3' })) {
126
+ back.setAttribute(name, String(value));
127
+ }
128
+ const text = document.createElementNS(svgNamespace, 'text');
129
+ text.setAttribute('class', 'blocklyText');
130
+ text.setAttribute('x', '12');
131
+ text.setAttribute('y', '18');
132
+ text.textContent = `▸ ${label}`;
133
+ group.append(back, text);
134
+ if (onUnfold) {
135
+ group.setAttribute('role', 'button');
136
+ group.style.cursor = 'pointer';
137
+ // The mark sits in the hat's group; pressing it must not start dragging the hat.
138
+ for (const type of ['mousedown', 'pointerdown', 'touchstart'])
139
+ group.addEventListener(type, event => event.stopPropagation());
140
+ group.addEventListener('click', event => {
141
+ event.stopPropagation();
142
+ onUnfold();
143
+ });
144
+ }
145
+ root.appendChild(group);
146
+ }
147
+ /**
148
+ * Folding and the one-script mode of the code area.
149
+ *
150
+ * A hat whose script is folded (`tw-plus-folded` in its mutation, as the script editors save it) shows only the
151
+ * hat and a mark that unfolds it. In the one-script mode the code area shows a single hat or function and what is
152
+ * made or pulled out there; the other scripts and the workspace comments stay in the workspace, hidden, with no
153
+ * connections to snap to and outside the scroll area. Both are painted again after every reload of the workspace.
154
+ */
155
+ const visibilities = new WeakMap();
156
+ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }) {
157
+ // The GUI can attach the code area again without letting go of the earlier attachment; only the latest paints.
158
+ visibilities.get(workspace)?.dispose();
159
+ const japanese = () => /^ja(?:-|$)/i.test(blocks.ScratchMsgs?.currentLocale_ ?? homeDocument.documentElement.lang ?? '');
160
+ const labels = () => japanese() ? { fold: '折りたたみ', unfold: '折りたたみを解除', folded: '折りたたみ中' } :
161
+ { fold: 'Fold', unfold: 'Unfold', folded: 'Folded' };
162
+ const vmBlock = (id) => vm.editingTarget?.blocks._blocks[id];
163
+ const isFolded = (block) => isHatBlock(block) && isFoldedDefinition(vmBlock(block.id));
164
+ let focus;
165
+ // The GUI can attach the code area again; what an earlier attachment left on the workspace is not its own.
166
+ const own = (name) => Object.prototype.hasOwnProperty.call(workspace, name) && !workspace[name][focusOverride] ?
167
+ workspace[name] : undefined;
168
+ const ownBoundingBox = own('getBlocksBoundingBox');
169
+ const ownCleanUp = own('cleanUp');
170
+ if (workspace.getBlocksBoundingBox?.[focusOverride] || workspace.cleanUp?.[focusOverride])
171
+ restoreWorkspaceMethods();
172
+ const shown = (block) => !focus || block.id === focus.id || focus.extras.has(block.id);
173
+ function restoreWorkspaceMethods() {
174
+ if (ownBoundingBox)
175
+ workspace.getBlocksBoundingBox = ownBoundingBox;
176
+ else
177
+ delete workspace.getBlocksBoundingBox;
178
+ if (ownCleanUp)
179
+ workspace.cleanUp = ownCleanUp;
180
+ else
181
+ delete workspace.cleanUp;
182
+ }
183
+ function paint() {
184
+ if (focus && !vmBlock(focus.id)) {
185
+ const { onLost } = focus;
186
+ setFocus(undefined);
187
+ onLost?.();
188
+ return;
189
+ }
190
+ for (const top of workspace.getTopBlocks(false)) {
191
+ const visible = shown(top);
192
+ setElementHidden(top.getSvgRoot(), !visible);
193
+ top.setConnectionsHidden(!visible);
194
+ setCommentsHidden(top, !visible);
195
+ if (visible)
196
+ paintFold(top, isFolded(top), labels().folded, () => fold(top.id, false));
197
+ }
198
+ for (const comment of workspace.getTopComments?.(false) ?? []) {
199
+ setElementHidden(comment.getSvgRoot?.(), Boolean(focus));
200
+ }
201
+ }
202
+ function safePaint() {
203
+ try {
204
+ paint();
205
+ }
206
+ catch (error) {
207
+ onError(error);
208
+ }
209
+ }
210
+ // The GUI redraws the workspace on several paths; paint again whenever scripts are added to the canvas.
211
+ // A block dragged in from the palette is painted once the drag ends, when it has been counted.
212
+ const view = homeDocument.defaultView;
213
+ let frame;
214
+ function schedulePaint() {
215
+ if (frame !== undefined)
216
+ return;
217
+ frame = view.requestAnimationFrame(() => {
218
+ frame = undefined;
219
+ if (workspace.isDragging?.())
220
+ return;
221
+ safePaint();
222
+ reveal();
223
+ });
224
+ }
225
+ const canvasObserver = new view.MutationObserver(schedulePaint);
226
+ // The VM takes in an edit after the workspace shows it, such as the deletion of the shown script.
227
+ vm.runtime.on('PROJECT_CHANGED', schedulePaint);
228
+ const observeCanvas = () => {
229
+ const canvas = workspace.getCanvas?.();
230
+ if (canvas)
231
+ canvasObserver.observe(canvas, { childList: true });
232
+ };
233
+ observeCanvas();
234
+ function fold(id, value) {
235
+ const hat = vmBlock(id);
236
+ if (!hat || isFoldedDefinition(hat) === value || workspace.options.readOnly)
237
+ return;
238
+ setFoldedDefinition(hat, value);
239
+ vm.runtime.emitProjectChanged();
240
+ safePaint();
241
+ }
242
+ /**
243
+ * Put the shown script at the top left of the view, once the code area has its size there: the view it
244
+ * moves into may only be laid out after the script was picked.
245
+ */
246
+ let revealPending = false;
247
+ function reveal() {
248
+ if (!revealPending)
249
+ return;
250
+ const block = focus && workspace.getBlockById(focus.id);
251
+ const injection = workspace.getInjectionDiv();
252
+ if (!block || !injection.clientWidth || !injection.clientHeight)
253
+ return;
254
+ // The scroll area follows the shown scripts, which may have changed since the scrollbars were sized.
255
+ workspace.resize?.();
256
+ const metrics = workspace.getMetrics?.();
257
+ if (!metrics?.viewWidth || !metrics.viewHeight)
258
+ return;
259
+ revealPending = false;
260
+ const { x, y } = block.getRelativeToSurfaceXY();
261
+ const padding = 16;
262
+ workspace.scrollbar?.set(x * workspace.scale - metrics.contentLeft - padding, y * workspace.scale - metrics.contentTop - padding);
263
+ }
264
+ function setFocus(next) {
265
+ const changedScript = next?.id !== focus?.id;
266
+ focus = next && { id: next.id, onLost: next.onLost, extras: changedScript ? new Set() : focus?.extras ?? new Set() };
267
+ if (focus) {
268
+ workspace.getBlocksBoundingBox = Object.assign(function () {
269
+ let box;
270
+ for (const top of this.getTopBlocks(false)) {
271
+ if (!shown(top))
272
+ continue;
273
+ const { topLeft, bottomRight } = top.getBoundingRectangle();
274
+ box = box ? { left: Math.min(box.left, topLeft.x), top: Math.min(box.top, topLeft.y),
275
+ right: Math.max(box.right, bottomRight.x), bottom: Math.max(box.bottom, bottomRight.y) } :
276
+ { left: topLeft.x, top: topLeft.y, right: bottomRight.x, bottom: bottomRight.y };
277
+ }
278
+ return box ? { x: box.left, y: box.top, width: box.right - box.left, height: box.bottom - box.top } :
279
+ { x: 0, y: 0, width: 0, height: 0 };
280
+ }, { [focusOverride]: true });
281
+ // Cleaning up would also move the scripts that are not shown.
282
+ workspace.cleanUp = Object.assign(() => undefined, { [focusOverride]: true });
283
+ }
284
+ else
285
+ restoreWorkspaceMethods();
286
+ safePaint();
287
+ if (workspace.rendered && workspace.isVisible?.() !== false)
288
+ workspace.resize?.();
289
+ if (focus && changedScript) {
290
+ revealPending = true;
291
+ reveal();
292
+ schedulePaint();
293
+ }
294
+ }
295
+ // Blocks dragged in from the palette, or pulled out of the shown script, stay in view. Only the end of a
296
+ // drag counts: a reload of the workspace also sends a create event for every block, after the load.
297
+ const listener = event => {
298
+ if (event.type !== 'endDrag')
299
+ return;
300
+ const block = focus && !event.isOutside ? workspace.getBlockById(event.blockId) : null;
301
+ if (block && !block.getParent() && block.id !== focus.id)
302
+ focus.extras.add(block.id);
303
+ schedulePaint();
304
+ };
305
+ workspace.addChangeListener(listener);
306
+ const prototype = blocks.BlockSvg.prototype;
307
+ const showContextMenu = prototype.showContextMenu_;
308
+ const patched = function (event) {
309
+ if (this.workspace !== workspace || this.isInFlyout || this.getParent() || !isHatBlock(this) ||
310
+ workspace.options.readOnly || (!this.getNextBlock() && !isFolded(this))) {
311
+ return showContextMenu.call(this, event);
312
+ }
313
+ const owned = Object.prototype.hasOwnProperty.call(this, 'customContextMenu');
314
+ const custom = this.customContextMenu;
315
+ const folded = isFolded(this);
316
+ const id = this.id;
317
+ this.customContextMenu = function (options) {
318
+ custom?.call(this, options);
319
+ options.push({ text: folded ? labels().unfold : labels().fold, enabled: true, callback: () => fold(id, !folded) });
320
+ };
321
+ try {
322
+ return showContextMenu.call(this, event);
323
+ }
324
+ finally {
325
+ if (owned)
326
+ this.customContextMenu = custom;
327
+ else
328
+ delete this.customContextMenu;
329
+ }
330
+ };
331
+ prototype.showContextMenu_ = patched;
332
+ let disposed = false;
333
+ const visibility = {
334
+ paint: () => {
335
+ if (!disposed)
336
+ safePaint();
337
+ },
338
+ /** The code area has a size again, such as after moving to another view. */
339
+ resized: () => {
340
+ if (!disposed)
341
+ reveal();
342
+ },
343
+ focus: (id, onLost) => {
344
+ if (!disposed)
345
+ setFocus(id ? { id, onLost } : undefined);
346
+ },
347
+ get focusedScript() { return focus?.id; },
348
+ dispose() {
349
+ if (disposed)
350
+ return;
351
+ disposed = true;
352
+ if (visibilities.get(workspace) === visibility)
353
+ visibilities.delete(workspace);
354
+ workspace.removeChangeListener(listener);
355
+ canvasObserver.disconnect();
356
+ vm.runtime.removeListener('PROJECT_CHANGED', schedulePaint);
357
+ if (frame !== undefined)
358
+ view.cancelAnimationFrame(frame);
359
+ if (prototype.showContextMenu_ === patched)
360
+ prototype.showContextMenu_ = showContextMenu;
361
+ if (focus) {
362
+ focus = undefined;
363
+ restoreWorkspaceMethods();
364
+ }
365
+ }
366
+ };
367
+ visibilities.set(workspace, visibility);
368
+ return visibility;
369
+ }
370
+ /** Paint the folded scripts of a read-only workspace, such as the preview of a code view. */
371
+ function paintPreviewFolds(blocks, preview, target, label) {
372
+ for (const top of preview.getTopBlocks(false)) {
373
+ paintFold(top, isHatBlock(top) && isFoldedDefinition(target.blocks._blocks[top.id]), label);
374
+ }
375
+ }
376
+ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, options, onError, presentationElements = null }) {
377
+ const session = getCodeSession(vm);
378
+ const homeDocument = workspace.getInjectionDiv().ownerDocument;
379
+ const histories = new WeakMap();
380
+ const signature = target => target.blocks.toXML(target.comments);
381
+ let loadedTarget = vm.editingTarget;
382
+ let loadedSignature = loadedTarget && signature(loadedTarget);
383
+ let pendingFrame = null;
384
+ function changed() {
385
+ if (pendingFrame !== null)
386
+ return;
387
+ pendingFrame = requestAnimationFrame(() => {
388
+ pendingFrame = null;
389
+ session.changed();
390
+ });
391
+ }
392
+ function flush() {
393
+ workspace.cancelCurrentGesture();
394
+ blocks.hideChaff();
395
+ blocks.Events.fireNow_();
396
+ }
397
+ function capturePresentation({ preserveViewport = false, includeNavigation = true } = {}) {
398
+ const metrics = workspace.getMetrics();
399
+ if (!metrics || !loadedTarget)
400
+ return;
401
+ const area = workspace.getParentSvg().getBoundingClientRect();
402
+ const roots = workspace.getTopBlocks(false);
403
+ const visible = preserveViewport || !roots.length || roots.some(block => {
404
+ const bounds = block.getSvgRoot()?.getBoundingClientRect();
405
+ return bounds && bounds.left < area.right && bounds.right > area.left + metrics.absoluteLeft &&
406
+ bounds.top < area.bottom && bounds.bottom > area.top + metrics.absoluteTop;
407
+ });
408
+ return {
409
+ scale: workspace.scale,
410
+ x: workspace.scrollX + metrics.absoluteLeft,
411
+ y: workspace.scrollY + metrics.absoluteTop,
412
+ visible,
413
+ scriptView: getDockedScriptLayout(vm)?.view.view,
414
+ chrome: captureCodePreviewChrome(workspace, loadedTarget, presentationElements, includeNavigation)
415
+ };
416
+ }
417
+ function rememberView() {
418
+ const { frontView } = session;
419
+ if (!frontView || frontView.target !== loadedTarget ||
420
+ !frontView.mount?.contains(workspace.getInjectionDiv()))
421
+ return;
422
+ const presentation = capturePresentation();
423
+ if (presentation)
424
+ frontView.presentation = presentation;
425
+ }
426
+ let parentFrame = null;
427
+ // Show edits made in a function editor in the code area when it displays the same target.
428
+ function refreshParent(target) {
429
+ if (parentFrame !== null)
430
+ return;
431
+ parentFrame = requestAnimationFrame(() => {
432
+ parentFrame = null;
433
+ if (vm.editingTarget !== target || vm.runtime.getTargetById(target.id) !== target)
434
+ return;
435
+ withoutEvents(blocks, () => vm.emit('workspaceUpdate', { xml: workspaceXML(vm, target) }));
436
+ });
437
+ }
438
+ // Function editors take the code area's palette, which the GUI replaces as the editing target changes.
439
+ const toolboxListeners = new Set();
440
+ const updateToolbox = workspace.updateToolbox;
441
+ workspace.updateToolbox = function (...args) {
442
+ const result = updateToolbox.apply(this, args);
443
+ for (const listener of toolboxListeners)
444
+ listener();
445
+ return result;
446
+ };
447
+ const bridge = {
448
+ onError,
449
+ capturePane(targetId) {
450
+ if (loadedTarget?.id === targetId)
451
+ return capturePresentation({ preserveViewport: true, includeNavigation: false });
452
+ },
453
+ restorePane(targetId, presentation) {
454
+ const injection = workspace.getInjectionDiv();
455
+ if (loadedTarget?.id !== targetId || !injection.clientWidth || !injection.clientHeight)
456
+ return;
457
+ blocks.svgResize(workspace);
458
+ workspace.setScale(presentation.scale);
459
+ const metrics = workspace.getMetrics();
460
+ if (!metrics)
461
+ return;
462
+ workspace.scrollbar.set(metrics.absoluteLeft - presentation.x - metrics.contentLeft, metrics.absoluteTop - presentation.y - metrics.contentTop);
463
+ },
464
+ prepareImport(target) {
465
+ if (loadedTarget === target)
466
+ flush();
467
+ const before = signature(target);
468
+ const stored = histories.get(target);
469
+ const previous = loadedTarget === target && loadedSignature === before ? workspace.undoStack_.slice() :
470
+ (stored?.signature === before ? stored.undo : []);
471
+ return ({ blockIds, rootBlockIds }) => {
472
+ const group = crypto.randomUUID();
473
+ const added = new Set(blockIds);
474
+ const events = rootBlockIds.map(blockId => {
475
+ const xml = target.blocks.blockToXML(blockId, target.comments);
476
+ const root = blocks.Xml.textToDom(`<xml>${xml}</xml>`).firstElementChild;
477
+ const ids = [blockId, ...Array.from(root.querySelectorAll('block[id], shadow[id]'), child => child.id)].filter(id => added.has(id));
478
+ const event = blocks.Events.fromJson({ type: 'create', blockId, xml, ids }, workspace);
479
+ // The pinned ScratchBlocks block decoder does not restore the event group.
480
+ event.group = group;
481
+ return event;
482
+ });
483
+ const history = { signature: signature(target), undo: [...previous, ...events], redo: [] };
484
+ histories.set(target, history);
485
+ if (loadedTarget === target) {
486
+ loadedSignature = history.signature;
487
+ workspace.undoStack_ = history.undo.slice();
488
+ workspace.redoStack_ = [];
489
+ }
490
+ };
491
+ },
492
+ blockListener(event) {
493
+ if (event.workspaceId !== workspace.id || !loadedTarget || vm.editingTarget !== loadedTarget ||
494
+ vm.runtime.getEditingTarget() !== loadedTarget)
495
+ return;
496
+ vm.blockListener(event);
497
+ if (event.recordUndo !== undefined && event.type !== 'ui')
498
+ loadedSignature = signature(loadedTarget);
499
+ changed();
500
+ },
501
+ beforeReload() {
502
+ if (loadedTarget !== vm.editingTarget)
503
+ rememberView();
504
+ if (loadedTarget && vm.runtime.getTargetById(loadedTarget.id) === loadedTarget) {
505
+ if (signature(loadedTarget) === loadedSignature) {
506
+ histories.set(loadedTarget, { signature: loadedSignature,
507
+ undo: workspace.undoStack_.slice(), redo: workspace.redoStack_.slice() });
508
+ }
509
+ else {
510
+ histories.delete(loadedTarget);
511
+ }
512
+ }
513
+ },
514
+ load: action => withoutEvents(blocks, action),
515
+ afterReload() {
516
+ loadedTarget = vm.editingTarget;
517
+ loadedSignature = loadedTarget && signature(loadedTarget);
518
+ const history = histories.get(loadedTarget);
519
+ if (history && history.signature === loadedSignature) {
520
+ workspace.undoStack_ = history.undo.slice();
521
+ workspace.redoStack_ = history.redo.slice();
522
+ }
523
+ visibility.paint();
524
+ changed();
525
+ },
526
+ select(view) {
527
+ const { target } = view;
528
+ if (vm.runtime.getTargetById(target.id) !== target)
529
+ return false;
530
+ if (target !== vm.editingTarget) {
531
+ flush();
532
+ vm.setEditingTarget(target.id);
533
+ }
534
+ else if (session.frontView !== view) {
535
+ rememberView();
536
+ flush();
537
+ }
538
+ if (session.frontView !== view)
539
+ getDockedScriptLayout(vm)?.view.setView(view.presentation?.scriptView ?? 'free');
540
+ return true;
541
+ },
542
+ preview(element, chrome, view) {
543
+ const { target, presentation, attachMinimap, watermark, locale, onScriptViewChange, dropElement, scriptId } = view;
544
+ // ScratchBlocks injects into the document where its bundle was evaluated.
545
+ // Initialize the read-only preview there, then move it into the popout.
546
+ const staging = element.ownerDocument === homeDocument ? null : homeDocument.createElement('div');
547
+ if (staging)
548
+ homeDocument.body.appendChild(staging);
549
+ let preview;
550
+ try {
551
+ preview = withoutEvents(blocks, () => blocks.inject(staging ?? element, {
552
+ readOnly: true, scrollbars: false, sounds: false, media: options.media, rtl: options.rtl,
553
+ colours: options.colours, grid: options.grid,
554
+ zoom: { startScale: presentation?.scale ?? options.zoom?.startScale }
555
+ }));
556
+ if (staging)
557
+ element.appendChild(preview.getInjectionDiv());
558
+ }
559
+ finally {
560
+ staging?.remove();
561
+ }
562
+ workspace.markFocused();
563
+ presentation?.chrome?.mount(chrome);
564
+ const minimap = attachMinimap?.(preview, blocks, watermark);
565
+ const scriptView = attachScriptView({ workspace: preview, ScratchBlocks: blocks, mount: chrome.parentElement,
566
+ getLocale: () => locale ?? workspace.getInjectionDiv().ownerDocument.documentElement.lang,
567
+ initialView: view.scriptView ?? presentation?.scriptView,
568
+ onChange: next => {
569
+ if (presentation)
570
+ presentation.scriptView = next;
571
+ onScriptViewChange?.(next);
572
+ }, hasWorkspaceMenu: () => false });
573
+ let renderedXml;
574
+ const resize = () => {
575
+ blocks.svgResize(preview);
576
+ if (presentation?.visible) {
577
+ preview.scrollX = presentation.x;
578
+ preview.scrollY = presentation.y;
579
+ preview.translate(presentation.x, presentation.y);
580
+ return;
581
+ }
582
+ const width = element.clientWidth;
583
+ const height = element.clientHeight;
584
+ if (!width || !height)
585
+ return;
586
+ const bounds = preview.getBlocksBoundingBox();
587
+ // Preserve the existing coordinates when the whole preview already fits.
588
+ const fits = bounds.x >= 0 && bounds.y >= 0 &&
589
+ bounds.x + bounds.width <= width && bounds.y + bounds.height <= height;
590
+ const padding = Math.min(16, width / 4, height / 4);
591
+ const scale = fits ? 1 : Math.min(1, (width - 2 * padding) / Math.max(1, bounds.width), (height - 2 * padding) / Math.max(1, bounds.height));
592
+ // setScale hides Blockly widgets globally, including those in the active editor.
593
+ preview.scale = scale;
594
+ const x = fits ? 0 : (width - bounds.width * scale) / 2 - bounds.x * scale;
595
+ const y = fits ? 0 : (height - bounds.height * scale) / 2 - bounds.y * scale;
596
+ preview.translate(x, y);
597
+ };
598
+ const unregister = blockDrag.register({ element: dropElement, workspace: preview, target });
599
+ const observer = new ResizeObserver(resize);
600
+ observer.observe(element);
601
+ return {
602
+ workspace: preview,
603
+ update() {
604
+ if (vm.runtime.getTargetById(target.id) !== target)
605
+ return;
606
+ // A view that shows one script previews only that script.
607
+ const xml = scriptId && target.blocks._blocks[scriptId] ? scriptXml(vm, target, scriptId) : targetXml(vm, target);
608
+ if (renderedXml === xml)
609
+ return;
610
+ try {
611
+ withoutEvents(blocks, () => blocks.Xml.clearWorkspaceAndLoadFromXml(blocks.Xml.textToDom(xml), preview));
612
+ paintPreviewFolds(blocks, preview, target, /^ja(?:-|$)/i.test(locale ?? homeDocument.documentElement.lang ?? '') ? '折りたたみ中' : 'Folded');
613
+ renderedXml = xml;
614
+ resize();
615
+ }
616
+ catch (error) {
617
+ onError(error);
618
+ }
619
+ },
620
+ dispose() {
621
+ unregister();
622
+ observer.disconnect();
623
+ scriptView.dispose();
624
+ minimap?.dispose();
625
+ presentation?.chrome?.dispose();
626
+ withoutEvents(blocks, () => preview.dispose());
627
+ }
628
+ };
629
+ },
630
+ /**
631
+ * Show only one script in the code area, a hat or a function, or every script again without `id`.
632
+ * `onLost` runs when that script is deleted.
633
+ */
634
+ focusScript(id, onLost) {
635
+ visibility.focus(id, onLost);
636
+ },
637
+ get focusedScript() { return visibility.focusedScript; },
638
+ createFunction(target, kind, name, { loadNamedFunctions } = {}) {
639
+ return createFunctionDefinition({ vm, blocks, workspace, target, kind, name, loadNamedFunctions,
640
+ loadedTarget: () => loadedTarget, refreshParent });
641
+ },
642
+ editProcedure(element, { target, definitionId, editable, attachNavigation, locale = '', focusBlock }) {
643
+ return attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDocument, element, target,
644
+ definitionId, editable, attachNavigation, toolboxListeners, refreshParent, locale, focusBlock });
645
+ },
646
+ dispose() {
647
+ blockDrag.dispose();
648
+ shown?.disconnect();
649
+ visibility.dispose();
650
+ if (pendingFrame !== null)
651
+ cancelAnimationFrame(pendingFrame);
652
+ if (parentFrame !== null)
653
+ cancelAnimationFrame(parentFrame);
654
+ if (workspace.updateToolbox !== updateToolbox)
655
+ workspace.updateToolbox = updateToolbox;
656
+ if (session.bridge === bridge) {
657
+ session.bridge = null;
658
+ session.changed();
659
+ }
660
+ vm.runtime.removeListener('PROJECT_CHANGED', changed);
661
+ }
662
+ };
663
+ // The code area loads the editing target's scripts while another section covers it, such as after a function
664
+ // is added from the functions sections; lay them out again once it shows.
665
+ const injection = workspace.getInjectionDiv();
666
+ const view = injection.ownerDocument.defaultView;
667
+ const shown = typeof view?.ResizeObserver === 'function' ? new view.ResizeObserver(() => {
668
+ if (!injection.clientWidth || !injection.clientHeight)
669
+ return;
670
+ withoutEvents(blocks, () => remeasureHiddenFields(workspace));
671
+ visibility.resized();
672
+ }) : null;
673
+ shown?.observe(injection);
674
+ const blockDrag = attachBlockDrag({ vm, workspace, ScratchBlocks: blocks, onError, prepareImport: bridge.prepareImport });
675
+ const visibility = attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError });
676
+ visibility.paint();
677
+ session.bridge = bridge;
678
+ vm.runtime.on('PROJECT_CHANGED', changed);
679
+ changed();
680
+ return bridge;
681
+ }
682
+ const foldedBodyType = 'twplus_folded_body';
683
+ /** The mark below a folded hat: a statement that ends the stack and holds only its label. */
684
+ function registerFoldedBodyBlock(blocks) {
685
+ blocks.Blocks[foldedBodyType] ??= {
686
+ init() {
687
+ this.jsonInit({
688
+ message0: '%1', args0: [{ type: 'field_label', name: 'LABEL', text: '' }],
689
+ previousStatement: null, colour: '#9E9E9E', colourSecondary: '#8A8A8A', colourTertiary: '#757575'
690
+ });
691
+ }
692
+ };
693
+ }
694
+ /**
695
+ * An editor of one custom block definition script, for the functions section of a sprite tab.
696
+ * It shares this page's ScratchBlocks, so extension blocks and field editors work as in the code area,
697
+ * and it takes the code area's palette, zoom buttons and minimap, which show while the pointer is over it.
698
+ * Edits go straight to the target's blocks, and edits made anywhere else reload it.
699
+ * The definition hat cannot be moved or deleted here: moving it would rearrange the code area, and
700
+ * deleting it would leave the calls in other scripts without a definition.
701
+ */
702
+ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDocument, element, target: codeTarget, definitionId, editable, attachNavigation, toolboxListeners, refreshParent, locale, focusBlock }) {
703
+ const target = codeTarget;
704
+ const document = element.ownerDocument;
705
+ // ScratchBlocks injects only into a container in its own document, and a tab may mount before it is shown.
706
+ const staging = document === homeDocument && element.isConnected ? null : homeDocument.createElement('div');
707
+ if (staging)
708
+ homeDocument.body.appendChild(staging);
709
+ // The palette is the code area's, which holds the editing target's blocks; a read-only editor has none.
710
+ const palette = () => editable && vm.editingTarget === codeTarget ?
711
+ workspace.options.languageTree?.cloneNode(true) ?? null : null;
712
+ let editor;
713
+ try {
714
+ // An editable workspace gets the default categories when it has no toolbox.
715
+ const defaultToolbox = blocks.Blocks.defaultToolbox;
716
+ blocks.Blocks.defaultToolbox = null;
717
+ try {
718
+ editor = withoutEvents(blocks, () => blocks.inject(staging ?? element, {
719
+ readOnly: !editable, toolbox: palette() ?? undefined,
720
+ scrollbars: true, sounds: false, comments: true, trashcan: false,
721
+ media: options.media, rtl: options.rtl, colours: options.colours, grid: options.grid,
722
+ zoom: { ...options.zoom, controls: true }
723
+ }));
724
+ }
725
+ finally {
726
+ blocks.Blocks.defaultToolbox = defaultToolbox;
727
+ }
728
+ if (staging)
729
+ element.appendChild(editor.getInjectionDiv());
730
+ }
731
+ finally {
732
+ staging?.remove();
733
+ }
734
+ // Injecting focuses the new workspace; the GUI keeps reading the code area as the main one.
735
+ workspace.markFocused();
736
+ function refreshPalette() {
737
+ const tree = palette();
738
+ if (tree && editor.toolbox_)
739
+ editor.updateToolbox(tree);
740
+ }
741
+ if (editor.toolbox_) {
742
+ // My Blocks lists every function of the target, as in the code area, not only the one shown here.
743
+ const callbacks = { ...editor.toolboxCategoryCallbacks_ };
744
+ const procedures = callbacks[blocks.PROCEDURE_CATEGORY_NAME];
745
+ callbacks[blocks.PROCEDURE_CATEGORY_NAME] = flyoutWorkspace => vm.editingTarget === target ?
746
+ blocks.Procedures.flyoutCategory(workspace) : procedures(flyoutWorkspace);
747
+ editor.toolboxCategoryCallbacks_ = callbacks;
748
+ toolboxListeners.add(refreshPalette);
749
+ }
750
+ // The zoom buttons and minimap show while the pointer is over the editor, as in the code area,
751
+ // and so does the palette, which would otherwise sit over a single script all the time.
752
+ element.setAttribute('data-code-hover-surface', '');
753
+ element.setAttribute('data-hover-palette', '');
754
+ let navigation;
755
+ try {
756
+ navigation = attachNavigation?.(editor, blocks) ?? undefined;
757
+ }
758
+ catch (error) {
759
+ onError(error);
760
+ }
761
+ const exists = () => vm.runtime.getTargetById(target.id) === target;
762
+ // Scripts pulled out of the definition here stay in view until this editor closes.
763
+ const detached = new Set();
764
+ const roots = () => [definitionId, ...detached].filter(id => id === definitionId ? target.blocks._blocks[id] :
765
+ target.blocks._blocks[id]?.topLevel);
766
+ function xml() {
767
+ const stage = vm.runtime.getTargetForStage();
768
+ const globals = Object.values(stage.variables).map(variable => variable.toXML());
769
+ const locals = target.isStage ? [] : Object.values(target.variables).map(variable => variable.toXML(true));
770
+ return `<xml xmlns="http://www.w3.org/1999/xhtml"><variables>${globals.join('')}${locals.join('')}</variables>` +
771
+ roots().map(id => target.blocks.blockToXML(id, target.comments)).join('') + '</xml>';
772
+ }
773
+ // A script can be folded to its hat, with a mark below it that unfolds it when clicked.
774
+ // The dialog, for working on the whole body, always shows it.
775
+ const modal = element.closest('dialog');
776
+ const foldable = !modal;
777
+ const foldLabels = /^ja(?:-|$)/i.test(locale) ? { fold: '折りたたみ', unfold: '折りたたみを解除', folded: '折りたたみ中' } :
778
+ { fold: 'Fold', unfold: 'Unfold', folded: 'Folded' };
779
+ const foldedBodyId = `${definitionId}:tw-plus-folded`;
780
+ const folded = () => foldable && isFoldedDefinition(target.blocks._blocks[definitionId]);
781
+ function fold(value) {
782
+ const hat = target.blocks._blocks[definitionId];
783
+ if (!editable || !exists() || !hat || isFoldedDefinition(hat) === value)
784
+ return;
785
+ setFoldedDefinition(hat, value);
786
+ vm.runtime.emitProjectChanged();
787
+ // A click or menu choice is still being handled, so reload after it.
788
+ scheduleLoad();
789
+ }
790
+ // Add-ons append items such as cut to every block menu; these blocks offer only folding.
791
+ function offerOnly(block, option) {
792
+ block.contextMenu = editable;
793
+ block.customContextMenu = options => {
794
+ options.splice(0, options.length, option);
795
+ };
796
+ // Shown as ScratchBlocks shows a menu, without ContextMenu.show, where add-ons append and decorate items.
797
+ block.showContextMenu_ = function (event) {
798
+ if (this.workspace.options.readOnly || !this.contextMenu)
799
+ return;
800
+ const { ContextMenu, WidgetDiv } = blocks;
801
+ WidgetDiv.show(ContextMenu, this.RTL, null);
802
+ const menu = ContextMenu.populate_([{ ...option, callback() {
803
+ ContextMenu.hide();
804
+ option.callback();
805
+ } }], this.RTL);
806
+ ContextMenu.position_(menu, event, this.RTL);
807
+ setTimeout(() => menu.getElement()?.focus(), 1);
808
+ };
809
+ }
810
+ const unfoldOption = { text: foldLabels.unfold, enabled: true, callback: () => fold(false) };
811
+ function showFolded(hat) {
812
+ withoutEvents(blocks, () => {
813
+ hat.nextConnection?.targetBlock()?.dispose(false);
814
+ registerFoldedBodyBlock(blocks);
815
+ const mark = blocks.Xml.domToBlock(blocks.Xml.textToDom(`<xml><block type="${foldedBodyType}" id="${foldedBodyId}"></block></xml>`).firstElementChild, editor);
816
+ mark.setFieldValue(foldLabels.folded, 'LABEL');
817
+ mark.setMovable(false);
818
+ mark.setDeletable(false);
819
+ mark.setEditable(false);
820
+ offerOnly(mark, unfoldOption);
821
+ hat.nextConnection?.connect(mark.previousConnection);
822
+ });
823
+ }
824
+ let rendered;
825
+ let positioned = false;
826
+ function position() {
827
+ const definition = editor.getBlockById(definitionId);
828
+ const metrics = editor.getMetrics();
829
+ if (!definition || !metrics?.viewWidth || !metrics.viewHeight)
830
+ return false;
831
+ // Put the hat at the top left whatever its place in the code area.
832
+ const { x, y } = definition.getRelativeToSurfaceXY();
833
+ const padding = 16;
834
+ editor.scrollbar.set(x * editor.scale - metrics.contentLeft - padding, y * editor.scale - metrics.contentTop - padding);
835
+ return true;
836
+ }
837
+ function load() {
838
+ if (!exists() || !target.blocks._blocks[definitionId])
839
+ return;
840
+ const next = xml();
841
+ if (next === rendered)
842
+ return;
843
+ const { scrollX, scrollY } = editor;
844
+ try {
845
+ withoutEvents(blocks, () => blocks.Xml.clearWorkspaceAndLoadFromXml(blocks.Xml.textToDom(next), editor));
846
+ }
847
+ catch (error) {
848
+ onError(error);
849
+ return;
850
+ }
851
+ rendered = next;
852
+ const definition = editor.getBlockById(definitionId);
853
+ if (definition) {
854
+ definition.setMovable(false);
855
+ definition.setDeletable(false);
856
+ // A definition's own menu edits its inputs, which needs the callers that live in other scripts.
857
+ // Only folding is offered here, and the dialog offers nothing.
858
+ if (foldable)
859
+ offerOnly(definition, folded() ? unfoldOption :
860
+ { text: foldLabels.fold, enabled: true, callback: () => fold(true) });
861
+ else
862
+ definition.contextMenu = false;
863
+ if (folded())
864
+ showFolded(definition);
865
+ }
866
+ editor.clearUndo();
867
+ if (positioned) {
868
+ editor.scrollX = scrollX;
869
+ editor.scrollY = scrollY;
870
+ editor.resize();
871
+ }
872
+ else
873
+ positioned = position();
874
+ reveal();
875
+ }
876
+ // A block to show, such as a call picked in the list of a function's uses. A folded script unfolds for it,
877
+ // and a hidden tab shows it once it is laid out.
878
+ let pendingBlock = focusBlock;
879
+ function reveal() {
880
+ if (!pendingBlock || !element.clientWidth || !element.clientHeight)
881
+ return;
882
+ const block = editor.getBlockById(pendingBlock);
883
+ if (!block) {
884
+ if (folded() && target.blocks._blocks[pendingBlock])
885
+ fold(false);
886
+ else
887
+ pendingBlock = undefined;
888
+ return;
889
+ }
890
+ pendingBlock = undefined;
891
+ editor.centerOnBlock(block.id);
892
+ block.select();
893
+ }
894
+ let frame;
895
+ const view = document.defaultView;
896
+ function scheduleLoad() {
897
+ if (frame !== undefined)
898
+ return;
899
+ frame = view.requestAnimationFrame(() => {
900
+ frame = undefined;
901
+ if (editor.isDragging())
902
+ scheduleLoad();
903
+ else
904
+ load();
905
+ });
906
+ }
907
+ editor.addChangeListener(event => {
908
+ if (!editable || !exists())
909
+ return;
910
+ if (event.type === 'ui' && event.element === 'click' && event.blockId === foldedBodyId) {
911
+ fold(false);
912
+ return;
913
+ }
914
+ const edit = decodeEdit(encodeEdit(event));
915
+ if (!edit)
916
+ return;
917
+ // The folded mark stands for the body the VM still has: nothing may take its place under the hat.
918
+ if (folded() && (edit.blockId === foldedBodyId || edit.newParentId === definitionId ||
919
+ edit.newParentId === foldedBodyId)) {
920
+ rendered = undefined;
921
+ scheduleLoad();
922
+ return;
923
+ }
924
+ // The VM files comments under the editing target, whatever blocks container receives them.
925
+ if (isCommentEdit(edit) && vm.runtime.getEditingTarget() !== target) {
926
+ rendered = undefined;
927
+ scheduleLoad();
928
+ return;
929
+ }
930
+ try {
931
+ target.blocks.blocklyListen(edit);
932
+ if (edit.type === 'change' && edit.element === 'mutation') {
933
+ removeObsoleteProcedureInputs(target.blocks, new Set([edit.blockId]));
934
+ }
935
+ }
936
+ catch (error) {
937
+ onError(error);
938
+ rendered = undefined;
939
+ scheduleLoad();
940
+ return;
941
+ }
942
+ if ((edit.type === 'create' || edit.type === 'move') && edit.blockId !== definitionId &&
943
+ target.blocks._blocks[edit.blockId]?.topLevel)
944
+ detached.add(edit.blockId);
945
+ rendered = xml();
946
+ refreshParent(target);
947
+ });
948
+ const observer = new view.ResizeObserver(() => {
949
+ if (!element.clientWidth || !element.clientHeight)
950
+ return;
951
+ // A tab may load its script before it is shown.
952
+ withoutEvents(blocks, () => remeasureHiddenFields(editor));
953
+ blocks.svgResize(editor);
954
+ if (!positioned)
955
+ positioned = position();
956
+ reveal();
957
+ });
958
+ observer.observe(element);
959
+ // A click elsewhere in the GUI gives the code area back its place as the main workspace,
960
+ // which the GUI and the project search read through ScratchBlocks.getMainWorkspace().
961
+ const releaseFocus = (event) => {
962
+ const node = event.target;
963
+ if (blocks.mainWorkspace !== editor || element.contains(node) ||
964
+ node?.closest?.('.blocklyWidgetDiv, .blocklyDropDownDiv'))
965
+ return;
966
+ workspace.markFocused();
967
+ };
968
+ document.addEventListener('pointerdown', releaseFocus, true);
969
+ vm.runtime.on('PROJECT_CHANGED', scheduleLoad);
970
+ load();
971
+ // In a modal dialog the rest of the page is inert, including the text and dropdown editors
972
+ // ScratchBlocks keeps in the body. Lend them to the dialog, which covers the viewport so their
973
+ // page coordinates still line up, as the block definition dialog does.
974
+ const popups = modal ? [blocks.WidgetDiv?.DIV, blocks.DropDownDiv?.DIV_].filter(Boolean) : [];
975
+ const lent = popups.map(popup => ({ popup, parent: popup.parentNode }));
976
+ for (const popup of popups)
977
+ modal.appendChild(popup);
978
+ return {
979
+ workspace: editor,
980
+ showBlock(id) {
981
+ pendingBlock = id;
982
+ reveal();
983
+ },
984
+ dispose() {
985
+ toolboxListeners.delete(refreshPalette);
986
+ navigation?.dispose();
987
+ element.removeAttribute('data-code-hover-surface');
988
+ element.removeAttribute('data-hover-palette');
989
+ observer.disconnect();
990
+ document.removeEventListener('pointerdown', releaseFocus, true);
991
+ vm.runtime.removeListener('PROJECT_CHANGED', scheduleLoad);
992
+ if (frame !== undefined)
993
+ view.cancelAnimationFrame(frame);
994
+ if (blocks.mainWorkspace === editor) {
995
+ blocks.hideChaff();
996
+ workspace.markFocused();
997
+ }
998
+ if (lent.length) {
999
+ blocks.WidgetDiv.hide?.(true);
1000
+ blocks.DropDownDiv.hideWithoutAnimation?.();
1001
+ for (const { popup, parent } of lent)
1002
+ (parent ?? homeDocument.body).appendChild(popup);
1003
+ }
1004
+ withoutEvents(blocks, () => editor.dispose());
1005
+ }
1006
+ };
1007
+ }
1008
+ const namedFunctionsExtension = 'kubohiroyanamedfunctions';
1009
+ const escapeXml = (text) => text.replace(/[<>&"']/g, character => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[character]);
1010
+ const createError = (message, code) => Object.assign(new Error(message), { code });
1011
+ /**
1012
+ * Add a function definition of the name the functions section asked for. A Scratch custom block gets
1013
+ * that text and no arguments, which its own Edit dialog can add later; a named function starts from the
1014
+ * extension's palette entry with that name. A name another definition here already has is refused.
1015
+ * The definition goes into the target's blocks directly, so it does not depend on the code area being
1016
+ * shown, and the code area is reloaded when it shows this target. Resolves with the id of the new hat.
1017
+ */
1018
+ async function createFunctionDefinition({ vm, blocks, workspace, target: codeTarget, kind, name: asked, loadNamedFunctions, loadedTarget, refreshParent }) {
1019
+ const name = String(asked ?? '').replace(/\s+/g, ' ').trim();
1020
+ if (!name)
1021
+ throw createError('A function needs a name', 'invalid');
1022
+ const target = codeTarget;
1023
+ const exists = () => vm.runtime.getTargetById(target.id) === target;
1024
+ const tops = () => Object.values(target.blocks._blocks).filter(block => block.topLevel && !block.shadow);
1025
+ // Below the scripts already there, in the code area's coordinates.
1026
+ function place() {
1027
+ const shown = loadedTarget() === target ? workspace : null;
1028
+ let x = Infinity;
1029
+ let bottom = -Infinity;
1030
+ for (const [id, block] of Object.entries(target.blocks._blocks)) {
1031
+ if (!block.topLevel || block.shadow)
1032
+ continue;
1033
+ x = Math.min(x, Number(block.x) || 0);
1034
+ const height = shown?.getBlockById(id)?.getHeightWidth?.().height;
1035
+ bottom = Math.max(bottom, (Number(block.y) || 0) + (height || 160));
1036
+ }
1037
+ return Number.isFinite(x) ? { x: Math.round(x), y: Math.round(bottom + 48) } : { x: 48, y: 48 };
1038
+ }
1039
+ function insert(xml, id) {
1040
+ if (!exists())
1041
+ throw new Error('The sprite was removed');
1042
+ target.blocks.blocklyListen({ type: 'create', blockId: id, xml: { outerHTML: xml } });
1043
+ refreshParent(target);
1044
+ return id;
1045
+ }
1046
+ const id = blocks.utils.genUid();
1047
+ if (kind === 'procedure') {
1048
+ // %s, %n and %b would read as argument slots in the block text.
1049
+ if (/%[snb]/.test(name))
1050
+ throw createError('The name reads as an argument', 'invalid');
1051
+ // Each definition has one prototype, so a prototype with this proccode means the block exists.
1052
+ if (Object.values(target.blocks._blocks).some(block => block.opcode === 'procedures_prototype' && block.mutation?.proccode === name)) {
1053
+ throw createError('A block with this definition already exists', 'duplicate');
1054
+ }
1055
+ const { x, y } = place();
1056
+ return insert(`<block type="procedures_definition" id="${id}" x="${x}" y="${y}"><value name="custom_block">` +
1057
+ `<shadow type="procedures_prototype" id="${blocks.utils.genUid()}"><mutation proccode="${escapeXml(name)}" ` +
1058
+ `argumentids="[]" argumentnames="[]" argumentdefaults="[]" warp="false"></mutation></shadow></value></block>`, id);
1059
+ }
1060
+ if (!vm.extensionManager.isExtensionLoaded(namedFunctionsExtension)) {
1061
+ if (!loadNamedFunctions)
1062
+ throw Object.assign(new Error('named-functions is not loaded'), { code: 'unavailable' });
1063
+ await loadNamedFunctions();
1064
+ if (!vm.extensionManager.isExtensionLoaded(namedFunctionsExtension) || !exists()) {
1065
+ throw Object.assign(new Error('named-functions could not be loaded'), { code: 'unavailable' });
1066
+ }
1067
+ }
1068
+ // The palette entry has the defaults of the loaded version, including fields a newer one adds.
1069
+ const category = vm.runtime.getBlocksXML(target).find(entry => entry.id === namedFunctionsExtension);
1070
+ const palette = new DOMParser().parseFromString(category?.xml ?? '<xml/>', 'text/xml');
1071
+ const hat = [...palette.getElementsByTagName('block')]
1072
+ .find(block => block.getAttribute('type') === `${namedFunctionsExtension}_defineFunction`);
1073
+ if (!hat)
1074
+ throw Object.assign(new Error('named-functions has no define function block'), { code: 'unavailable' });
1075
+ const used = new Set(tops().filter(block => block.opcode === `${namedFunctionsExtension}_defineFunction`)
1076
+ .map(block => String(target.blocks._blocks[block.inputs?.NAME?.block]?.fields?.TEXT?.value ?? '').trim()));
1077
+ if (used.has(name))
1078
+ throw createError('A named function with this name already exists', 'duplicate');
1079
+ const field = (name) => [...hat.children].find(child => child.getAttribute('name') === name)
1080
+ ?.getElementsByTagName('field')[0];
1081
+ const nameField = field('NAME');
1082
+ if (nameField)
1083
+ nameField.textContent = name;
1084
+ for (const name of ['DESCRIPTION', 'RETURNS']) {
1085
+ const text = field(name);
1086
+ if (text)
1087
+ text.textContent = '';
1088
+ }
1089
+ const schema = field('SCHEMA');
1090
+ if (schema)
1091
+ schema.textContent = '{"type":"object","properties":{}}';
1092
+ // Shadows from the palette carry no ids; the VM needs one for each block.
1093
+ for (const node of [hat, ...hat.querySelectorAll('block, shadow')]) {
1094
+ if (node !== hat && !node.getAttribute('id'))
1095
+ node.setAttribute('id', blocks.utils.genUid());
1096
+ }
1097
+ const { x, y } = place();
1098
+ hat.setAttribute('id', id);
1099
+ hat.setAttribute('x', String(x));
1100
+ hat.setAttribute('y', String(y));
1101
+ return insert(new XMLSerializer().serializeToString(hat), id);
1102
+ }