@kubohiroya/turbowarp-plus-editor-code-views 0.0.0-stage → 0.2.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 +42 -0
  3. package/README.md +41 -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 +80 -0
  13. package/dist/code-pane.js +398 -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 +32 -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 +104 -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 +393 -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 +183 -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 +1125 -0
  108. package/tsconfig.json +23 -0
@@ -0,0 +1,398 @@
1
+ import { getCodeSession } from "./workspace.js";
2
+ import { getDockedScriptLayout } from "./script-layout-view.js";
3
+ const scriptViews = ['free', 'z', 'n'];
4
+ const finite = (value, limit) => typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= limit;
5
+ /** Read a saved code area back, or nothing if it does not have the shape `serialize` writes. */
6
+ export function readSavedCodePane(value) {
7
+ const { scale, x, y, scriptView } = value;
8
+ if (!finite(scale, 100) || scale <= 0 || !finite(x, 1e7) || !finite(y, 1e7))
9
+ return;
10
+ return { scale, x, y, ...(scriptViews.includes(scriptView) && { scriptView: scriptView }) };
11
+ }
12
+ export function createCodePaneAdapter(vm, locale, attachMinimap) {
13
+ const session = getCodeSession(vm);
14
+ const label = /^ja(?:-|$)/i.test(locale) ? 'このペインでコードを編集' : 'Edit code in this pane';
15
+ const views = new Map();
16
+ // Views that show one script, a hat or a function, by pane id; `onLost` runs when that script is deleted.
17
+ const focused = new Map();
18
+ // The code pane the code area is in, which shows its script there.
19
+ let current;
20
+ const applyFocus = (paneId) => {
21
+ const focus = paneId === undefined ? undefined : focused.get(paneId);
22
+ session.bridge?.focusScript(focus?.scriptId, focus && (() => focus.onLost?.()));
23
+ };
24
+ let pending;
25
+ // The GUI can attach the code area again, with a new bridge; the view it is in still shows its script.
26
+ let attached = session.bridge;
27
+ session.subscribe(() => {
28
+ if (session.bridge === attached)
29
+ return;
30
+ attached = session.bridge;
31
+ if (current !== undefined)
32
+ applyFocus(current);
33
+ });
34
+ const costumeUpdates = new Set();
35
+ const updateCostumes = () => costumeUpdates.forEach(update => update());
36
+ function watchCostume(image, readTarget) {
37
+ let shownAsset;
38
+ image.removeAttribute('src');
39
+ function update() {
40
+ const target = readTarget();
41
+ const asset = target?.getCostumes()[target.currentCostume]?.asset;
42
+ if (shownAsset === asset)
43
+ return;
44
+ shownAsset = asset;
45
+ if (asset)
46
+ image.src = asset.encodeDataURI();
47
+ else
48
+ image.removeAttribute('src');
49
+ }
50
+ if (!costumeUpdates.size)
51
+ vm.on('targetsUpdate', updateCostumes);
52
+ costumeUpdates.add(update);
53
+ update();
54
+ return () => {
55
+ costumeUpdates.delete(update);
56
+ if (!costumeUpdates.size)
57
+ vm.removeListener('targetsUpdate', updateCostumes);
58
+ };
59
+ }
60
+ return {
61
+ /**
62
+ * Make a code view show one script, a hat or a function, or every script again without `scriptId`.
63
+ * The code area shows it while it is in that view, and the view's preview shows it otherwise.
64
+ */
65
+ focusPane(paneId, scriptId, onLost) {
66
+ if (scriptId)
67
+ focused.set(paneId, { scriptId, onLost });
68
+ else
69
+ focused.delete(paneId);
70
+ if (current === paneId)
71
+ applyFocus(paneId);
72
+ // Previews of other views redraw with their script.
73
+ session.changed();
74
+ },
75
+ focusedScript: (paneId) => focused.get(paneId)?.scriptId,
76
+ /** Forget a view that has closed. */
77
+ forgetPane(paneId) {
78
+ focused.delete(paneId);
79
+ views.delete(paneId);
80
+ if (current === paneId) {
81
+ current = undefined;
82
+ applyFocus(undefined);
83
+ }
84
+ },
85
+ ownsClick: (element) => Boolean(element?.closest?.('[data-code-view-control]')),
86
+ watchEditingCostume: (image) => watchCostume(image, () => vm.editingTarget),
87
+ capture(pane) {
88
+ if (pane.section !== 0)
89
+ return;
90
+ if (pending?.pane.id === pane.id) {
91
+ const { frame, presentation } = pending;
92
+ cancelAnimationFrame(frame);
93
+ pending = undefined;
94
+ return presentation;
95
+ }
96
+ views.set(pane.id, getDockedScriptLayout(vm)?.view.view ?? 'free');
97
+ return session.bridge?.capturePane(pane.targetId);
98
+ },
99
+ /**
100
+ * The code area of a tab for a saved workspace. Without a presentation, the code area on screen is read; a
101
+ * presentation still waiting to be applied is what that tab shows.
102
+ */
103
+ serialize(pane, presentation) {
104
+ if (pane.section !== 0)
105
+ return;
106
+ const shown = presentation ?? (pending?.pane.id === pane.id ? pending.presentation :
107
+ session.bridge?.capturePane(pane.targetId));
108
+ if (!shown)
109
+ return;
110
+ const scriptView = presentation ? presentation.scriptView : views.get(pane.id) ??
111
+ getDockedScriptLayout(vm)?.view.view;
112
+ return { scale: shown.scale, x: shown.x, y: shown.y, ...(scriptView && { scriptView }) };
113
+ },
114
+ /** A presentation from a saved code area. The preview draws it without the chrome of the code area. */
115
+ deserialize(pane, value) {
116
+ if (pane.section !== 0)
117
+ return;
118
+ const saved = readSavedCodePane(value);
119
+ if (!saved)
120
+ return;
121
+ if (saved.scriptView)
122
+ views.set(pane.id, saved.scriptView);
123
+ return { scale: saved.scale, x: saved.x, y: saved.y, visible: true, ...(saved.scriptView && { scriptView: saved.scriptView }) };
124
+ },
125
+ restore(pane, presentation) {
126
+ if (pending)
127
+ cancelAnimationFrame(pending.frame);
128
+ pending = undefined;
129
+ if (pane.section !== 0)
130
+ return;
131
+ current = pane.id;
132
+ applyFocus(pane.id);
133
+ getDockedScriptLayout(vm)?.view.setView(views.get(pane.id) ?? 'free');
134
+ if (!presentation)
135
+ return;
136
+ const frame = requestAnimationFrame(() => {
137
+ pending = undefined;
138
+ session.bridge?.restorePane(pane.targetId, presentation);
139
+ });
140
+ pending = { frame, pane, presentation };
141
+ },
142
+ renderInactive(container, pane, presentation) {
143
+ if (pane.section !== 0)
144
+ return;
145
+ const target = vm.runtime.getTargetById(pane.targetId);
146
+ if (!target)
147
+ return;
148
+ const document = container.ownerDocument;
149
+ const surface = document.createElement('div');
150
+ surface.dataset.codePreview = '';
151
+ surface.dataset.codeHoverSurface = '';
152
+ surface.tabIndex = 0;
153
+ surface.setAttribute('role', 'button');
154
+ surface.setAttribute('aria-label', label);
155
+ surface.addEventListener('keydown', event => {
156
+ if (event.target !== surface || (event.key !== 'Enter' && event.key !== ' '))
157
+ return;
158
+ event.preventDefault();
159
+ event.stopPropagation();
160
+ surface.click();
161
+ });
162
+ const blocks = document.createElement('div');
163
+ const chrome = document.createElement('div');
164
+ chrome.className = 'tw-code-preview-chrome';
165
+ for (const child of [blocks, chrome])
166
+ child.setAttribute('inert', '');
167
+ const watermark = document.createElement('div');
168
+ watermark.dataset.dockviewCostumeThumbnail = '';
169
+ const image = document.createElement('img');
170
+ image.alt = '';
171
+ watermark.appendChild(image);
172
+ chrome.appendChild(watermark);
173
+ surface.append(blocks, chrome);
174
+ container.appendChild(surface);
175
+ const stopCostume = watchCostume(image, () => target);
176
+ let bridge;
177
+ let preview;
178
+ let shownScript;
179
+ function update() {
180
+ if (bridge !== session.bridge || shownScript !== focused.get(pane.id)?.scriptId) {
181
+ preview?.dispose();
182
+ bridge = session.bridge;
183
+ shownScript = focused.get(pane.id)?.scriptId;
184
+ preview = bridge?.preview(blocks, chrome, { target, presentation, attachMinimap, watermark, locale, dropElement: surface,
185
+ scriptView: views.get(pane.id), onScriptViewChange: view => views.set(pane.id, view),
186
+ scriptId: focused.get(pane.id)?.scriptId });
187
+ }
188
+ preview?.update();
189
+ }
190
+ const unsubscribe = session.subscribe(update);
191
+ update();
192
+ return () => {
193
+ stopCostume();
194
+ unsubscribe();
195
+ preview?.dispose();
196
+ surface.remove();
197
+ };
198
+ }
199
+ };
200
+ }
201
+ /**
202
+ * Mount an editor of one custom block definition in `element`, for the functions section.
203
+ * It follows the code area: when the GUI replaces its workspace, the editor is rebuilt on the new one.
204
+ */
205
+ export function mountProcedureEditor(vm, locale, element, targetId, definitionId, { editable, attachNavigation, focusBlock }) {
206
+ const session = getCodeSession(vm);
207
+ const notice = element.ownerDocument.createElement('p');
208
+ notice.className = 'tw-sprite-functions__empty';
209
+ notice.textContent = /^ja(?:-|$)/i.test(locale) ? 'コード領域の準備ができるまで待っています…' : 'Waiting for the code area…';
210
+ let bridge;
211
+ let editor;
212
+ // A block to show waits for the editor, which waits for the code area.
213
+ let pendingBlock = focusBlock;
214
+ function update() {
215
+ if (bridge === session.bridge)
216
+ return;
217
+ editor?.dispose();
218
+ editor = undefined;
219
+ bridge = session.bridge;
220
+ const target = vm.runtime.getTargetById(targetId);
221
+ if (!bridge || !target) {
222
+ element.appendChild(notice);
223
+ return;
224
+ }
225
+ notice.remove();
226
+ try {
227
+ editor = bridge.editProcedure(element, { target, definitionId, editable, attachNavigation, locale, focusBlock: pendingBlock });
228
+ pendingBlock = undefined;
229
+ }
230
+ catch (error) {
231
+ bridge.onError?.(error);
232
+ }
233
+ }
234
+ const unsubscribe = session.subscribe(update);
235
+ update();
236
+ return Object.assign(() => {
237
+ unsubscribe();
238
+ editor?.dispose();
239
+ notice.remove();
240
+ }, {
241
+ /** Show one block of the script, such as a call picked in the list of a function's uses. */
242
+ showBlock(id) {
243
+ if (editor)
244
+ editor.showBlock(id);
245
+ else
246
+ pendingBlock = id;
247
+ }
248
+ });
249
+ }
250
+ const svgNamespace = 'http://www.w3.org/2000/svg';
251
+ const hatDrawings = new WeakMap();
252
+ /**
253
+ * Draw a hat block as a standalone SVG, for the list of hats. ScratchBlocks renders it in a hidden workspace of
254
+ * its own; the drawing keeps the block's shapes and images and carries the text styles the page gives them.
255
+ * Drawings are kept by the hat's XML, so an unchanged hat is drawn once.
256
+ */
257
+ function drawHat(ScratchBlocks, xml) {
258
+ let state = hatDrawings.get(ScratchBlocks);
259
+ if (!state) {
260
+ const main = ScratchBlocks.getMainWorkspace?.();
261
+ if (!main?.options)
262
+ return undefined;
263
+ const document = main.getInjectionDiv().ownerDocument;
264
+ const host = document.createElement('div');
265
+ host.setAttribute('aria-hidden', 'true');
266
+ host.style.cssText = 'position:fixed;left:-10000px;top:0;inline-size:600px;block-size:200px;visibility:hidden;pointer-events:none';
267
+ document.body.appendChild(host);
268
+ const workspace = ScratchBlocks.inject(host, { readOnly: true, media: main.options.pathToMedia, scrollbars: false,
269
+ sounds: false, zoom: { startScale: 1 } });
270
+ // Injecting focuses the new workspace; the GUI keeps reading the code area as the main one.
271
+ main.markFocused();
272
+ state = { workspace, drawings: new Map() };
273
+ hatDrawings.set(ScratchBlocks, state);
274
+ }
275
+ const kept = state.drawings.get(xml);
276
+ if (kept)
277
+ return kept;
278
+ const { workspace } = state;
279
+ const block = ScratchBlocks.Xml.domToBlock(ScratchBlocks.Xml.textToDom(`<xml>${xml}</xml>`).firstElementChild, workspace);
280
+ try {
281
+ const root = block.getSvgRoot();
282
+ const box = root.getBBox();
283
+ if (!box.width || !box.height)
284
+ return undefined;
285
+ const document = root.ownerDocument;
286
+ const drawing = document.createElementNS(svgNamespace, 'svg');
287
+ drawing.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`);
288
+ drawing.setAttribute('width', String(box.width));
289
+ drawing.setAttribute('height', String(box.height));
290
+ const copy = root.cloneNode(true);
291
+ copy.removeAttribute('transform');
292
+ copy.removeAttribute('id');
293
+ for (const node of copy.querySelectorAll('[id]'))
294
+ node.removeAttribute('id');
295
+ const texts = root.querySelectorAll('text');
296
+ copy.querySelectorAll('text').forEach((text, index) => {
297
+ const style = document.defaultView.getComputedStyle(texts[index]);
298
+ for (const name of ['fill', 'font-family', 'font-size', 'font-weight']) {
299
+ text.setAttribute(name, style.getPropertyValue(name));
300
+ }
301
+ });
302
+ drawing.appendChild(copy);
303
+ if (state.drawings.size > 500)
304
+ state.drawings.clear();
305
+ state.drawings.set(xml, drawing);
306
+ return drawing;
307
+ }
308
+ finally {
309
+ block.dispose(false);
310
+ }
311
+ }
312
+ /**
313
+ * Read the scripts of a target that start with a hat, such as “when green flag clicked”, leaving out `skip`
314
+ * (its function definitions). A script is a hat script when its top block has nothing to attach above it or
315
+ * to plug it into; its label is how ScratchBlocks spells that block.
316
+ */
317
+ export function readHatScripts(target, ScratchBlocks, skip = new Set()) {
318
+ const blocks = target.blocks._blocks;
319
+ const tops = Object.values(blocks).filter(block => block.topLevel && !block.shadow && !skip.has(block.id));
320
+ if (!tops.length || !ScratchBlocks?.Workspace)
321
+ return [];
322
+ const flag = /^ja(?:-|$)/i.test(ScratchBlocks.ScratchMsgs?.currentLocale_ ?? '') ? '緑の旗' : 'green flag';
323
+ const workspace = new ScratchBlocks.Workspace();
324
+ ScratchBlocks.Events.disable();
325
+ try {
326
+ const hats = [];
327
+ for (const top of tops) {
328
+ try {
329
+ const dom = ScratchBlocks.Xml.textToDom(`<xml>${target.blocks.blockToXML(top.id, {})}</xml>`).firstElementChild;
330
+ // Only the hat itself is spelled and drawn; the rest of the script is not needed.
331
+ for (const child of [...dom.children])
332
+ if (child.tagName.toLowerCase() === 'next')
333
+ child.remove();
334
+ const hatXml = ScratchBlocks.Xml.domToText(dom);
335
+ const block = ScratchBlocks.Xml.domToBlock(dom, workspace);
336
+ // The green flag is an image whose text is its alt, “flag”; read it as the flag's name.
337
+ for (const field of block.inputList.flatMap(input => input.fieldRow)) {
338
+ if (field instanceof ScratchBlocks.FieldImage && /green-flag/.test(field.src_ ?? ''))
339
+ field.text_ = flag;
340
+ }
341
+ if (!block.previousConnection && !block.outputConnection) {
342
+ hats.push({ id: top.id, label: block.toString().replace(/\s+/g, ' ').trim(), x: top.x ?? 0, y: top.y ?? 0,
343
+ thumbnail: drawHat(ScratchBlocks, hatXml) });
344
+ }
345
+ }
346
+ catch {
347
+ // A block whose definition is not loaded, such as one of a missing extension, is left out.
348
+ }
349
+ workspace.clear();
350
+ }
351
+ return hats;
352
+ }
353
+ finally {
354
+ ScratchBlocks.Events.enable();
355
+ workspace.dispose();
356
+ }
357
+ }
358
+ /**
359
+ * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
360
+ * in the script editors. `find` names the function a block calls, if any; `open` shows it.
361
+ */
362
+ export function attachFunctionCallMenu(ScratchBlocks, { label, find, open }) {
363
+ const prototype = ScratchBlocks.BlockSvg.prototype;
364
+ const showContextMenu = prototype.showContextMenu_;
365
+ const patched = function (event) {
366
+ const functionId = this.isInFlyout ? undefined : find(this.id);
367
+ if (!functionId)
368
+ return showContextMenu.call(this, event);
369
+ const owned = Object.prototype.hasOwnProperty.call(this, 'customContextMenu');
370
+ const custom = this.customContextMenu;
371
+ this.customContextMenu = function (options) {
372
+ custom?.call(this, options);
373
+ options.unshift({ text: label(), enabled: true, callback: () => open(functionId) });
374
+ };
375
+ try {
376
+ return showContextMenu.call(this, event);
377
+ }
378
+ finally {
379
+ if (owned)
380
+ this.customContextMenu = custom;
381
+ else
382
+ delete this.customContextMenu;
383
+ }
384
+ };
385
+ prototype.showContextMenu_ = patched;
386
+ return () => {
387
+ if (prototype.showContextMenu_ === patched)
388
+ prototype.showContextMenu_ = showContextMenu;
389
+ };
390
+ }
391
+ /** Add a function definition of this name to a target through the code area's bridge. Resolves with the new hat's id. */
392
+ export async function createFunction(vm, targetId, kind, name, options = {}) {
393
+ const bridge = getCodeSession(vm).bridge;
394
+ const target = vm.runtime.getTargetById(targetId);
395
+ if (!bridge || !target)
396
+ throw Object.assign(new Error('The code area is not ready'), { code: 'unavailable' });
397
+ return bridge.createFunction(target, kind, name, options);
398
+ }
@@ -0,0 +1,45 @@
1
+ import { type NativeFieldGraphic } from './native-field-svg.ts';
2
+ import type { ProgrammaticExtensionField } from './programmatic-extension-field.ts';
3
+ type FieldEditor = {
4
+ type: 'field_input' | 'turbowarp_plus_actions' | 'native_widget';
5
+ } | {
6
+ type: 'field_dropdown';
7
+ options: [string, string][];
8
+ };
9
+ type NativeFactory = {
10
+ fromJson(options: unknown): unknown;
11
+ parentDocument?: boolean;
12
+ resources?: unknown;
13
+ asyncCommit?: boolean;
14
+ isolatedEditor?: boolean;
15
+ attachedEditor?: boolean;
16
+ };
17
+ export type CustomField = {
18
+ name: string;
19
+ editor: FieldEditor;
20
+ };
21
+ export declare function createIsolatedNativeField(field: any, native: NativeFactory): any;
22
+ export declare const usesAttachedNativeEditor: (native: NativeFactory) => boolean;
23
+ export declare function reserveAttachedNativeField(field: any, native: NativeFactory): boolean;
24
+ export declare function getNativeFieldEditor(field: any): any;
25
+ export declare function getCustomFields(category: any): {
26
+ declaration: CustomField;
27
+ definition: {
28
+ type: string;
29
+ [key: string]: unknown;
30
+ };
31
+ programmatic?: ProgrammaticExtensionField;
32
+ native?: NativeFactory;
33
+ }[];
34
+ export declare function customField(runtime: any, opcode: string, name: string): {
35
+ declaration: CustomField;
36
+ definition: {
37
+ type: string;
38
+ [key: string]: unknown;
39
+ };
40
+ programmatic?: ProgrammaticExtensionField;
41
+ native?: NativeFactory;
42
+ };
43
+ export declare const programmaticField: (runtime: any, opcode: string, name: string) => ProgrammaticExtensionField;
44
+ export declare function registerCustomFields(blocks: any, declarations: CustomField[], openCustomEditor?: any, getNative?: (name: string) => NativeFactory, getGraphic?: (blockId: string, name: string, value: string) => NativeFieldGraphic | undefined, openDockedNative?: (field: any, name: string) => void): () => void;
45
+ export {};
@@ -0,0 +1,144 @@
1
+ import { attachNativeFieldGraphic } from "./native-field-svg.js";
2
+ const isolatedFactory = Symbol.for('turbowarp-plus-editor.isolated-native-field');
3
+ const reserveAttached = Symbol.for('turbowarp-plus-editor.reserve-attached-native-field');
4
+ const nativeEditor = Symbol.for('turbowarp-plus-editor.native-field-editor');
5
+ const nativeInstances = new WeakMap();
6
+ function cloneOptions(options) {
7
+ try {
8
+ return structuredClone(options);
9
+ }
10
+ catch {
11
+ // Preserve the docked factory for extensions whose options cannot be copied.
12
+ }
13
+ }
14
+ export function createIsolatedNativeField(field, native) {
15
+ return field?.[isolatedFactory]?.(native);
16
+ }
17
+ export const usesAttachedNativeEditor = (native) => native.parentDocument === true && native.attachedEditor === true && native.isolatedEditor !== true;
18
+ export function reserveAttachedNativeField(field, native) {
19
+ return Boolean(field?.sourceBlock_) && field[reserveAttached]?.(native) === true;
20
+ }
21
+ export function getNativeFieldEditor(field) {
22
+ const show = field?.[nativeEditor] ?? field?.showEditor_;
23
+ return typeof show === 'function' ? show.bind(field) : undefined;
24
+ }
25
+ function readEditor(implementation) {
26
+ if (implementation?.type === 'turbowarp_plus_actions' &&
27
+ typeof implementation.getEditor === 'function' && typeof implementation.applyAction === 'function') {
28
+ return { type: 'turbowarp_plus_actions' };
29
+ }
30
+ if (implementation?.type === 'field_input')
31
+ return { type: 'field_input' };
32
+ if (implementation?.type !== 'field_dropdown') {
33
+ if (typeof implementation?.fromJson === 'function')
34
+ return { type: 'native_widget' };
35
+ return;
36
+ }
37
+ if (!Array.isArray(implementation.options) || !implementation.options.length)
38
+ return;
39
+ const options = [];
40
+ for (const option of implementation.options) {
41
+ if (!Array.isArray(option) || option.length !== 2 ||
42
+ typeof option[0] !== 'string' || typeof option[1] !== 'string')
43
+ return;
44
+ options.push([option[0], option[1]]);
45
+ }
46
+ return { type: 'field_dropdown', options };
47
+ }
48
+ export function getCustomFields(category) {
49
+ const fields = [];
50
+ for (const { extendedName, fieldImplementation, scratchBlocksDefinition } of Object.values(category.customFieldTypes ?? {})) {
51
+ if (!extendedName?.startsWith(`${category.id}_`) || scratchBlocksDefinition?.json?.type !== extendedName)
52
+ continue;
53
+ const editor = readEditor(fieldImplementation);
54
+ if (editor)
55
+ fields.push({
56
+ declaration: { name: `field_${extendedName}`, editor }, definition: scratchBlocksDefinition.json,
57
+ programmatic: editor.type === 'turbowarp_plus_actions' ? fieldImplementation : undefined,
58
+ native: editor.type === 'native_widget' ? fieldImplementation : undefined
59
+ });
60
+ }
61
+ return fields;
62
+ }
63
+ export function customField(runtime, opcode, name) {
64
+ if (typeof opcode !== 'string' || name !== `field_${opcode}`)
65
+ return;
66
+ const category = runtime._blockInfo?.find(category => opcode.startsWith(`${category.id}_`));
67
+ return category && getCustomFields(category).find(field => field.definition.type === opcode);
68
+ }
69
+ export const programmaticField = (runtime, opcode, name) => customField(runtime, opcode, name)?.programmatic;
70
+ export function registerCustomFields(blocks, declarations, openCustomEditor, getNative, getGraphic, openDockedNative) {
71
+ const registry = blocks.Field?.TYPE_MAP_;
72
+ const registered = new Map();
73
+ if (registry) {
74
+ for (const { name, editor } of declarations) {
75
+ if (Object.hasOwn(registry, name))
76
+ continue;
77
+ const factory = {
78
+ fromJson(options) {
79
+ const native = getNative?.(name);
80
+ if (native) {
81
+ const snapshot = native.parentDocument === true && native.isolatedEditor === true ?
82
+ cloneOptions(options) : undefined;
83
+ const field = native.fromJson(options);
84
+ if (!field || typeof field !== 'object')
85
+ return field;
86
+ const previous = nativeInstances.get(field);
87
+ if (previous && previous !== 'docked')
88
+ return;
89
+ nativeInstances.set(field, 'docked');
90
+ if (usesAttachedNativeEditor(native) && Object.isExtensible(field)) {
91
+ Object.defineProperty(field, reserveAttached, { configurable: true, value: (current) => {
92
+ if (!usesAttachedNativeEditor(current) || nativeInstances.get(field) !== 'docked')
93
+ return false;
94
+ // An outstanding callback can keep this exact object after the editor closes.
95
+ nativeInstances.set(field, 'reserved');
96
+ return true;
97
+ } });
98
+ if (openDockedNative && 'showEditor_' in field && typeof field.showEditor_ === 'function') {
99
+ if (!Object.hasOwn(field, nativeEditor)) {
100
+ Object.defineProperty(field, nativeEditor, { value: field.showEditor_ });
101
+ }
102
+ field.showEditor_ = () => openDockedNative(field, name);
103
+ }
104
+ }
105
+ if (snapshot !== undefined && Object.isExtensible(field)) {
106
+ Object.defineProperty(field, isolatedFactory, { configurable: true, value: (current) => {
107
+ if (current.parentDocument !== true || current.isolatedEditor !== true)
108
+ return;
109
+ const editor = current.fromJson(structuredClone(snapshot));
110
+ if (!editor || typeof editor !== 'object' || editor.sourceBlock_ || nativeInstances.has(editor) ||
111
+ typeof editor.showEditor_ !== 'function' || typeof editor.getValue !== 'function' ||
112
+ typeof editor.setValue !== 'function')
113
+ return;
114
+ nativeInstances.set(editor, 'isolated');
115
+ return editor;
116
+ } });
117
+ }
118
+ return field;
119
+ }
120
+ if (editor.type !== 'field_dropdown') {
121
+ const field = new blocks.FieldTextInput('');
122
+ if (editor.type === 'native_widget' && getGraphic) {
123
+ attachNativeFieldGraphic(field, (blockId, value) => getGraphic(blockId, name, value));
124
+ }
125
+ if (editor.type !== 'field_input') {
126
+ field.showEditor_ = () => openCustomEditor?.(field, name);
127
+ }
128
+ return field;
129
+ }
130
+ // The native dropdown preserves a saved value even if it leaves the option list.
131
+ return new blocks.FieldDropdown(editor.options.map(([label, value]) => [label, value]));
132
+ }
133
+ };
134
+ blocks.Field.register(name, factory);
135
+ registered.set(name, factory);
136
+ }
137
+ }
138
+ return () => {
139
+ for (const [name, factory] of registered) {
140
+ if (registry[name] === factory)
141
+ delete registry[name];
142
+ }
143
+ };
144
+ }
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+ import type { PaletteItem, PaletteSource } from './detached-block-palette.ts';
3
+ export default function Palette({ source, locale, categoryIcons, close, startDrag, endDrag }: {
4
+ source: PaletteSource;
5
+ locale: string;
6
+ categoryIcons: Readonly<Record<string, string>>;
7
+ close(): void;
8
+ startDrag(item: PaletteItem, data: DataTransfer): void;
9
+ endDrag(): void;
10
+ }): React.JSX.Element;
@@ -0,0 +1,62 @@
1
+ import React from 'react';
2
+ import { IconMenuButton } from '@kubohiroya/turbowarp-plus-editor-windows';
3
+ const horizontalLayoutIconPath = 'M2 5h5v6H2zm7 0h5v6H9z';
4
+ const verticalLayoutIconPath = 'M5 2h6v5H5zm0 7h6v5H5z';
5
+ function BlockPreview({ svg }) {
6
+ const ref = React.useRef(null);
7
+ React.useLayoutEffect(() => {
8
+ const node = ref.current;
9
+ node.replaceChildren(node.ownerDocument.importNode(svg, true));
10
+ }, [svg]);
11
+ return React.createElement("span", { ref: ref, "aria-hidden": "true" });
12
+ }
13
+ function LayoutIcon({ path }) {
14
+ return React.createElement("svg", { viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" },
15
+ React.createElement("path", { d: path }));
16
+ }
17
+ export default function Palette({ source, locale, categoryIcons, close, startDrag, endDrag }) {
18
+ const ja = /^ja(?:-|$)/i.test(locale);
19
+ const [vertical, setVertical] = React.useState(false);
20
+ const [categoryId, setCategory] = React.useState('');
21
+ const [revision, refresh] = React.useReducer(value => value + 1, 0);
22
+ const [items, setItems] = React.useState([]);
23
+ const [tooltip, setTooltip] = React.useState(null);
24
+ const categories = source.categories();
25
+ const selected = categories.find(category => category.id === categoryId) ?? categories[0];
26
+ const selectedId = selected?.id;
27
+ React.useLayoutEffect(() => source.subscribe(refresh), [source]);
28
+ React.useLayoutEffect(() => {
29
+ setItems(selectedId ? source.read(selectedId) : []);
30
+ }, [source, selectedId, revision]);
31
+ function showLabel(button, label) {
32
+ const { left, right, top, bottom, height } = button.getBoundingClientRect();
33
+ const viewportWidth = button.ownerDocument.documentElement.clientWidth;
34
+ const positionOnLeft = left < viewportWidth / 2;
35
+ const position = vertical
36
+ ? { top: bottom + 8, ...(positionOnLeft ? { left } : { right: viewportWidth - right }) }
37
+ : { top: top + height / 2, ...(positionOnLeft ? { left: right + 8 } : { right: viewportWidth - left + 8 }) };
38
+ setTooltip({ label, position });
39
+ }
40
+ return React.createElement("main", { className: "tw-detached-palette", "data-palette-orientation": vertical ? 'vertical' : 'horizontal' },
41
+ React.createElement("div", { className: "tw-detached-palette__content" },
42
+ React.createElement("div", { className: "tw-detached-palette__categories", role: "group", "aria-label": ja ? 'ブロックのカテゴリ' : 'Block categories', onScroll: () => setTooltip(null) }, categories.map(({ id, label, color, image }) => {
43
+ const artwork = categoryIcons[id];
44
+ const backgroundImage = image || (artwork ? `url("${artwork}")` : undefined);
45
+ return React.createElement("button", { key: id, type: "button", "aria-label": label, "aria-pressed": id === selectedId, onMouseEnter: event => showLabel(event.currentTarget, label), onMouseLeave: () => setTooltip(null), onFocus: event => showLabel(event.currentTarget, label), onBlur: () => setTooltip(null), onKeyDown: event => { if (event.key === 'Escape')
46
+ setTooltip(null); }, onClick: () => {
47
+ setCategory(id);
48
+ setTooltip(null);
49
+ } },
50
+ React.createElement("span", { "aria-hidden": "true", className: "tw-detached-palette__category-icon", style: { backgroundColor: color, backgroundImage } }, !backgroundImage && React.createElement(LayoutIcon, { path: "M2 4h5V2h3v2h4v8H2z" })));
51
+ })),
52
+ React.createElement("div", { className: "tw-detached-palette__blocks", role: "group", "aria-label": selected?.label }, items.map((item, index) => item.insert ? React.createElement("button", { key: index, type: "button", "aria-label": item.label, title: item.label, disabled: item.disabled, draggable: Boolean(item.preview && !item.disabled), onDragStart: event => startDrag(item, event.dataTransfer), onDragEnd: endDrag, onClick: () => item.insert() }, item.preview ? React.createElement(BlockPreview, { svg: item.preview }) : item.label) : React.createElement("span", { key: index }, item.label)))),
53
+ tooltip && React.createElement("div", { className: "tw-detached-palette__tooltip", role: "tooltip", style: tooltip.position }, tooltip.label),
54
+ React.createElement(IconMenuButton, { className: "tw-detached-palette__layout-menu", label: ja ? 'ブロックパレットのレイアウト' : 'Block palette layout', icon: React.createElement(LayoutIcon, { path: vertical ? verticalLayoutIconPath : horizontalLayoutIconPath }), items: [
55
+ { id: 'horizontal', label: ja ? '横並びにする' : 'Arrange horizontally', checked: !vertical,
56
+ icon: React.createElement(LayoutIcon, { path: horizontalLayoutIconPath }), onSelect: () => setVertical(false) },
57
+ { id: 'vertical', label: ja ? '縦並びにする' : 'Arrange vertically', checked: vertical,
58
+ icon: React.createElement(LayoutIcon, { path: verticalLayoutIconPath }), onSelect: () => setVertical(true) },
59
+ { id: 'dock', label: ja ? 'このパネルを別画面から元に戻す' : 'Return this panel to the editor',
60
+ icon: React.createElement(LayoutIcon, { path: "M9 3h4v10H3V9m0-6 6 6M5 9h4V5" }), onSelect: close }
61
+ ] }));
62
+ }