@kubohiroya/turbowarp-plus-editor-code-views 0.21.3 → 0.22.1

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.
@@ -4,6 +4,9 @@ import { openRearrangement } from "./script-layout-dialog.js";
4
4
  import { attachScriptViewMenu } from "./script-view-menu.js";
5
5
  import { attachScriptArrows } from "./script-arrows.js";
6
6
  import { attachCodeZoomRange } from "./code-zoom.js";
7
+ import { setScriptProjection } from "./script-projection.js";
8
+ import { openSerialScriptEditor } from "./serial-script-editor.js";
9
+ import { isFoldedDefinition, setFoldedDefinition } from "./procedure-edits.js";
7
10
  const choices = [
8
11
  { view: 'free', label: 'Normal layout view', jaLabel: '通常配置の見え方' },
9
12
  { view: 'z', label: 'Z layout view', jaLabel: 'Z配置の見え方' },
@@ -19,10 +22,15 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
19
22
  surface.className = 'tw-script-view-surface';
20
23
  surface.dataset.codeViewControl = '';
21
24
  surface.tabIndex = 0;
22
- surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock));
25
+ surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock || relationContext?.vm));
23
26
  const contents = document.createElement('div');
24
27
  surface.append(contents);
28
+ const gutter = document.createElement('div');
29
+ gutter.className = 'tw-script-fold-gutter';
30
+ gutter.dataset.codeViewControl = '';
31
+ const foldButtons = new Map();
25
32
  let view = initialView;
33
+ let editor;
26
34
  let frame;
27
35
  const svg = workspace.getParentSvg();
28
36
  const observer = new window.MutationObserver(records => {
@@ -31,6 +39,73 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
31
39
  });
32
40
  const relations = relationContext && attachScriptArrows({ workspace, getLocale, ...relationContext });
33
41
  const japanese = () => /^ja(?:-|$)/i.test(getLocale());
42
+ function setFold(ids, value) {
43
+ const target = relationContext?.getTarget();
44
+ const runtime = relationContext?.vm?.runtime;
45
+ if (!target || !runtime?.emitProjectChanged || (canShowBlock && !canShowBlock()))
46
+ return;
47
+ for (const id of ids) {
48
+ const block = target.blocks._blocks[id];
49
+ if (block)
50
+ setFoldedDefinition(block, value ?? !isFoldedDefinition(block));
51
+ }
52
+ runtime.emitProjectChanged();
53
+ update();
54
+ }
55
+ function positionFoldButtons() {
56
+ gutter.style.left = `${surface.offsetLeft}px`;
57
+ gutter.style.top = `${surface.offsetTop}px`;
58
+ gutter.style.height = `${surface.clientHeight}px`;
59
+ for (const { button, top } of foldButtons.values())
60
+ button.style.top = `${top - surface.scrollTop}px`;
61
+ }
62
+ function paintFoldButtons(placements, scale) {
63
+ const target = relationContext?.getTarget();
64
+ const ids = new Set(placements.map(({ script }) => script.id));
65
+ for (const [id, { button }] of foldButtons)
66
+ if (!ids.has(id)) {
67
+ button.remove();
68
+ foldButtons.delete(id);
69
+ }
70
+ for (const { script, y } of placements) {
71
+ let entry = foldButtons.get(script.id);
72
+ if (!entry) {
73
+ const button = document.createElement('button');
74
+ button.type = 'button';
75
+ button.dataset.scriptFoldToggle = script.id;
76
+ button.addEventListener('click', event => { event.stopPropagation(); setFold([script.id]); });
77
+ button.addEventListener('pointerdown', event => event.stopPropagation());
78
+ entry = { button, top: 0 };
79
+ foldButtons.set(script.id, entry);
80
+ gutter.append(button);
81
+ }
82
+ const block = target?.blocks._blocks[script.id];
83
+ const folded = isFoldedDefinition(block);
84
+ const label = japanese() ? (folded ? '折りたたみを解除' : '折りたたむ') : (folded ? 'Unfold script' : 'Fold script');
85
+ entry.top = y * scale;
86
+ entry.button.textContent = folded ? '▶' : '▼';
87
+ entry.button.disabled = !block || Boolean(canShowBlock && !canShowBlock());
88
+ entry.button.setAttribute('aria-label', label);
89
+ entry.button.setAttribute('aria-expanded', String(!folded));
90
+ entry.button.title = label;
91
+ }
92
+ positionFoldButtons();
93
+ }
94
+ function foldOptions() {
95
+ const target = relationContext?.getTarget();
96
+ const runtime = relationContext?.vm?.runtime;
97
+ if (view === 'free' || !target || !runtime?.emitProjectChanged || (canShowBlock && !canShowBlock()))
98
+ return [];
99
+ const roots = readScripts(workspace).map(script => target.blocks._blocks[script.id]).filter(Boolean);
100
+ const options = [
101
+ { value: true, text: japanese() ? 'すべて折りたたむ' : 'Fold all' },
102
+ { value: false, text: japanese() ? '折りたたみをすべて解除' : 'Unfold all' }
103
+ ];
104
+ return options.map(({ value, text }) => ({ text,
105
+ enabled: roots.some(block => isFoldedDefinition(block) !== value),
106
+ callback() { setFold(readScripts(workspace).map(script => script.id), value); }
107
+ }));
108
+ }
34
109
  function labels() {
35
110
  const choice = choices.find(choice => choice.view === view);
36
111
  surface.setAttribute('aria-label', japanese() ? choice.jaLabel : choice.label);
@@ -40,6 +115,7 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
40
115
  const ja = japanese();
41
116
  return {
42
117
  label: ja ? 'コードの並びの見え方を変更する' : 'Change code layout view',
118
+ options: foldOptions(),
43
119
  choices: choices.map(choice => ({
44
120
  text: ja ? choice.jaLabel : choice.label,
45
121
  enabled: true,
@@ -62,8 +138,21 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
62
138
  surface.style.setProperty('--tw-script-view-left', !horizontal && bounds.left <= left + 2 ? `${bounds.width}px` : '0px');
63
139
  surface.style.setProperty('--tw-script-view-right', !horizontal && bounds.right >= right - 2 ? `${bounds.width}px` : '0px');
64
140
  }
65
- paintScripts(contents, arrangeScripts(readScripts(workspace), view, 'vertical'), workspace.scale || 1);
66
- relations?.setProjection(contents.querySelector('svg'));
141
+ const scale = workspace.scale || 1;
142
+ const scripts = readScripts(workspace).map(script => {
143
+ // Include raised hats and labels, and exclude folded bodies, when measuring the visible gap.
144
+ const box = script.root.getBBox();
145
+ return { ...script, x: script.origin.x + box.x, y: script.origin.y + box.y,
146
+ width: box.width, height: box.height };
147
+ });
148
+ const placements = arrangeScripts(scripts, view, 'vertical', Math.max(64, 48 / scale))
149
+ // Leave room for incoming arrowheads and return paths beside the fixed fold gutter.
150
+ .map(placement => ({ ...placement, x: placement.x + 40 / scale }));
151
+ paintScripts(contents, placements, scale);
152
+ paintFoldButtons(placements, scale);
153
+ const projection = contents.querySelector('svg');
154
+ relations?.setProjection(projection);
155
+ setScriptProjection(workspace, { surface, svg: projection });
67
156
  }
68
157
  function update() {
69
158
  if (view === 'free' || frame !== undefined)
@@ -72,14 +161,20 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
72
161
  }
73
162
  function setView(next) {
74
163
  menu.close();
164
+ editor?.dispose();
165
+ editor = undefined;
75
166
  observer.disconnect();
76
167
  view = next;
77
168
  surface.hidden = view === 'free';
169
+ gutter.hidden = view === 'free';
78
170
  svg.toggleAttribute('data-script-serial', view !== 'free');
79
171
  labels();
80
172
  if (view === 'free') {
173
+ setScriptProjection(workspace);
81
174
  relations?.setProjection(null);
82
175
  contents.replaceChildren();
176
+ gutter.replaceChildren();
177
+ foldButtons.clear();
83
178
  }
84
179
  else {
85
180
  observer.observe(workspace.getCanvas(), { attributes: true, childList: true, subtree: true });
@@ -94,21 +189,39 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
94
189
  surface.addEventListener('click', event => {
95
190
  event.stopPropagation();
96
191
  const id = event.target.closest('[data-script-view-block]')?.getAttribute('data-script-view-block');
97
- if (!id || !canShowBlock?.())
192
+ if (!id || (canShowBlock && !canShowBlock()))
193
+ return;
194
+ if (relationContext?.vm) {
195
+ editor?.dispose();
196
+ editor = openSerialScriptEditor(relationContext.vm, relationContext.getTarget(), id, document, getLocale());
197
+ if (editor)
198
+ return;
199
+ }
200
+ if (!canShowBlock?.())
98
201
  return;
99
202
  chooseView('free');
100
203
  workspace.centerOnBlock(id);
101
204
  });
102
205
  const resize = new window.ResizeObserver(update);
103
206
  resize.observe(host);
104
- const language = new window.MutationObserver(labels);
207
+ const language = new window.MutationObserver(() => { labels(); update(); });
105
208
  language.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'] });
106
209
  // The Blockly keyboard listener is document-wide.
107
210
  surface.addEventListener('keydown', event => {
108
211
  if (event.key !== 'Tab')
109
212
  event.stopPropagation();
110
213
  });
111
- host.append(surface);
214
+ gutter.addEventListener('keydown', event => {
215
+ if (event.key !== 'Tab')
216
+ event.stopPropagation();
217
+ });
218
+ host.append(surface, gutter);
219
+ surface.addEventListener('scroll', () => {
220
+ positionFoldButtons();
221
+ const projection = contents.querySelector('svg');
222
+ if (view !== 'free' && projection)
223
+ setScriptProjection(workspace, { surface, svg: projection });
224
+ }, { passive: true });
112
225
  setView(initialView);
113
226
  return {
114
227
  update,
@@ -117,6 +230,8 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
117
230
  get view() { return view; },
118
231
  setView,
119
232
  dispose() {
233
+ editor?.dispose();
234
+ setScriptProjection(workspace);
120
235
  restoreZoomRange();
121
236
  resize.disconnect();
122
237
  observer.disconnect();
@@ -126,6 +241,8 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
126
241
  menu.dispose();
127
242
  relations?.dispose();
128
243
  surface.remove();
244
+ gutter.remove();
245
+ foldButtons.clear();
129
246
  svg.removeAttribute('data-script-serial');
130
247
  }
131
248
  };
@@ -1,10 +1,15 @@
1
1
  export function readScripts(workspace) {
2
2
  return workspace.getTopBlocks(false).flatMap(block => {
3
3
  const root = block.getSvgRoot();
4
- if (!root || !workspace.getCanvas().contains(root))
4
+ if (!root || !workspace.getCanvas().contains(root) || root.hasAttribute('data-tw-plus-hidden'))
5
5
  return [];
6
6
  const origin = block.getRelativeToSurfaceXY();
7
- const { topLeft, bottomRight } = block.getBoundingRectangle();
7
+ let { topLeft, bottomRight } = block.getBoundingRectangle();
8
+ if (root.querySelector(':scope > [data-tw-plus-folded-mark]')) {
9
+ const box = root.getBBox();
10
+ topLeft = { x: origin.x + box.x, y: origin.y + box.y };
11
+ bottomRight = { x: topLeft.x + box.width, y: topLeft.y + box.height };
12
+ }
8
13
  return [{
9
14
  id: block.id, block, root, origin, ...topLeft,
10
15
  width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y
@@ -9,7 +9,7 @@ export interface ScriptBounds extends Point {
9
9
  }
10
10
  export type ScriptOrder = 'z' | 'n';
11
11
  export type LayoutDirection = 'vertical' | 'horizontal';
12
- export declare function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection): {
12
+ export declare function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection, gap?: number): {
13
13
  script: T;
14
14
  x: number;
15
15
  y: number;
@@ -1,6 +1,6 @@
1
1
  const alignmentTolerance = 24;
2
2
  const spacing = 32;
3
- export function arrangeScripts(scripts, order, direction) {
3
+ export function arrangeScripts(scripts, order, direction, gap = spacing) {
4
4
  const bandAxis = order === 'z' ? 'y' : 'x';
5
5
  const scanAxis = order === 'z' ? 'x' : 'y';
6
6
  const compare = (a, b, first, second) => a[first] - b[first] || a[second] - b[second] || (a.id < b.id ? -1 : Number(a.id > b.id));
@@ -14,12 +14,12 @@ export function arrangeScripts(scripts, order, direction) {
14
14
  else
15
15
  bands.push([script]);
16
16
  }
17
- let offset = spacing;
17
+ let offset = gap;
18
18
  return bands.flatMap(band => band.sort((a, b) => compare(a, b, scanAxis, bandAxis))).map(script => {
19
19
  const vertical = direction === 'vertical';
20
20
  const x = vertical ? spacing : offset;
21
21
  const y = vertical ? offset : spacing;
22
- offset += Math.ceil(vertical ? script.height : script.width) + spacing;
22
+ offset += Math.ceil(vertical ? script.height : script.width) + gap;
23
23
  return { script, x, y };
24
24
  });
25
25
  }
@@ -0,0 +1,8 @@
1
+ export type ScriptProjection = {
2
+ surface: HTMLElement;
3
+ svg: SVGSVGElement;
4
+ };
5
+ export declare const getScriptProjection: (workspace: object) => ScriptProjection;
6
+ export declare function setScriptProjection(workspace: {
7
+ getInjectionDiv(): HTMLElement;
8
+ }, projection?: ScriptProjection): void;
@@ -0,0 +1,10 @@
1
+ const projections = new WeakMap();
2
+ export const getScriptProjection = (workspace) => projections.get(workspace);
3
+ export function setScriptProjection(workspace, projection) {
4
+ if (projection)
5
+ projections.set(workspace, projection);
6
+ else
7
+ projections.delete(workspace);
8
+ const container = workspace.getInjectionDiv();
9
+ container.dispatchEvent(new container.ownerDocument.defaultView.Event('scriptprojectionchange'));
10
+ }
@@ -35,6 +35,7 @@ export interface ScriptViewMenuWorkspace {
35
35
  }
36
36
  interface MenuConfig {
37
37
  label: string;
38
+ options?: MenuOption[];
38
39
  choices: (MenuOption & {
39
40
  checked: boolean;
40
41
  })[];
@@ -108,7 +108,7 @@ export function attachScriptViewMenu({ ContextMenu, WidgetDiv }, workspace, host
108
108
  // Only extend the options collected for this workspace, after the existing add-ons.
109
109
  ContextMenu.populate_ = (options, rtl) => {
110
110
  const config = getMenu();
111
- const menu = populate.call(ContextMenu, [...options, triggerOption(config.label)], rtl);
111
+ const menu = populate.call(ContextMenu, [...options, triggerOption(config.label), ...(config.options ?? [])], rtl);
112
112
  addSubmenu(menu, options.length, config, rtl, ContextMenu);
113
113
  return menu;
114
114
  };
@@ -126,7 +126,9 @@ export function attachScriptViewMenu({ ContextMenu, WidgetDiv }, workspace, host
126
126
  event.stopPropagation();
127
127
  const config = getMenu();
128
128
  const rtl = workspace.RTL;
129
- const menu = ContextMenu.populate_([triggerOption(config.label)], rtl);
129
+ const menu = ContextMenu.populate_([triggerOption(config.label), ...(config.options ?? []).map(option => ({ ...option,
130
+ callback() { WidgetDiv.hideIfOwner(surface); option.callback(); }
131
+ }))], rtl);
130
132
  const outside = new document.defaultView.AbortController();
131
133
  WidgetDiv.show(surface, rtl, () => {
132
134
  outside.abort();
@@ -0,0 +1,4 @@
1
+ /** Reuse the script editor: its root stays at its original project coordinates. */
2
+ export declare function openSerialScriptEditor(vm: object, target: any, id: string, document: Document, locale: string): {
3
+ dispose: () => void;
4
+ };
@@ -0,0 +1,43 @@
1
+ import { getCodeSession } from "./workspace.js";
2
+ /** Reuse the script editor: its root stays at its original project coordinates. */
3
+ export function openSerialScriptEditor(vm, target, id, document, locale) {
4
+ const bridge = getCodeSession(vm).bridge;
5
+ if (!bridge || !target?.blocks._blocks[id])
6
+ return;
7
+ const dialog = document.createElement('dialog');
8
+ dialog.className = 'tw-serial-script-editor';
9
+ const title = document.createElement('h2');
10
+ title.textContent = /^ja(?:-|$)/i.test(locale) ? 'スクリプトを編集' : 'Edit script';
11
+ title.id = `script-editor-${document.defaultView.crypto.randomUUID()}`;
12
+ dialog.setAttribute('aria-labelledby', title.id);
13
+ const area = document.createElement('div');
14
+ area.dataset.serialScriptEditor = id;
15
+ const close = document.createElement('button');
16
+ close.type = 'button';
17
+ close.textContent = /^ja(?:-|$)/i.test(locale) ? '閉じる' : 'Close';
18
+ dialog.append(title, area, close);
19
+ document.body.append(dialog);
20
+ dialog.showModal();
21
+ let editor;
22
+ try {
23
+ editor = bridge.editProcedure(area, { target, definitionId: id, editable: true, locale });
24
+ }
25
+ catch (error) {
26
+ dialog.close();
27
+ dialog.remove();
28
+ throw error;
29
+ }
30
+ let closed = false;
31
+ const dispose = () => {
32
+ if (closed)
33
+ return;
34
+ closed = true;
35
+ editor.flush();
36
+ editor.dispose();
37
+ dialog.close();
38
+ dialog.remove();
39
+ };
40
+ close.addEventListener('click', dispose);
41
+ dialog.addEventListener('cancel', event => { event.preventDefault(); dispose(); });
42
+ return { dispose };
43
+ }
@@ -1,3 +1,4 @@
1
+ import { getScriptProjection } from "./script-projection.js";
1
2
  const svgNamespace = 'http://www.w3.org/2000/svg';
2
3
  /** A cached overview drawn from public block geometry; offscreen culling never changes the project map. */
3
4
  export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight = 0, getCorner, watermark, getWatermark }) {
@@ -34,25 +35,46 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
34
35
  function refreshShapes() {
35
36
  const retained = new Set();
36
37
  const additions = document.createDocumentFragment();
37
- for (const block of workspace.getAllBlocks(false)) {
38
- const root = block.getSvgRoot();
39
- if (!root || !canvas.contains(root) || root.closest('[data-tw-plus-hidden]'))
40
- continue;
41
- const source = root.querySelector(':scope > .blocklyPath');
42
- const data = source?.getAttribute('d');
43
- if (!data)
44
- continue;
45
- retained.add(block.id);
46
- let path = paths.get(block.id);
38
+ const paint = (id, data, fill, transform) => {
39
+ retained.add(id);
40
+ let path = paths.get(id);
47
41
  if (!path) {
48
42
  path = element('path');
49
- paths.set(block.id, path);
43
+ paths.set(id, path);
50
44
  additions.append(path);
51
45
  }
52
- const position = block.getRelativeToSurfaceXY();
53
46
  attribute(path, 'd', data);
54
- attribute(path, 'fill', source.getAttribute('fill') || block.getColour());
55
- attribute(path, 'transform', `translate(${position.x} ${position.y})${block.RTL ? ' scale(-1 1)' : ''}`);
47
+ attribute(path, 'fill', fill);
48
+ attribute(path, 'transform', transform);
49
+ };
50
+ const projection = getScriptProjection(workspace);
51
+ if (projection) {
52
+ const inverse = projection.svg.getScreenCTM()?.inverse();
53
+ if (inverse)
54
+ for (const source of projection.svg.querySelectorAll('.blocklyPath')) {
55
+ if (source.closest('[data-tw-plus-hidden]'))
56
+ continue;
57
+ const id = source.closest('[data-id]')?.getAttribute('data-id');
58
+ const data = source.getAttribute('d');
59
+ const matrix = source.getScreenCTM();
60
+ if (!id || !data || !matrix)
61
+ continue;
62
+ const transform = inverse.multiply(matrix);
63
+ paint(id, data, source.getAttribute('fill') || view.getComputedStyle(source).fill, `matrix(${transform.a} ${transform.b} ${transform.c} ${transform.d} ${transform.e} ${transform.f})`);
64
+ }
65
+ }
66
+ else {
67
+ for (const block of workspace.getAllBlocks(false)) {
68
+ const root = block.getSvgRoot();
69
+ if (!root || !canvas.contains(root) || root.closest('[data-tw-plus-hidden]'))
70
+ continue;
71
+ const source = root.querySelector(':scope > .blocklyPath');
72
+ const data = source?.getAttribute('d');
73
+ if (!data)
74
+ continue;
75
+ const position = block.getRelativeToSurfaceXY();
76
+ paint(block.id, data, source.getAttribute('fill') || block.getColour(), `translate(${position.x} ${position.y})${block.RTL ? ' scale(-1 1)' : ''}`);
77
+ }
56
78
  }
57
79
  for (const [id, path] of paths)
58
80
  if (!retained.has(id)) {
@@ -73,12 +95,17 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
73
95
  return;
74
96
  }
75
97
  const scale = workspace.scale;
76
- const x = metrics.viewLeft / scale, y = metrics.viewTop / scale;
77
- const width = metrics.viewWidth / scale, height = metrics.viewHeight / scale;
98
+ const projection = getScriptProjection(workspace);
99
+ const x = projection ? projection.surface.scrollLeft / scale : metrics.viewLeft / scale;
100
+ const y = projection ? projection.surface.scrollTop / scale : metrics.viewTop / scale;
101
+ const width = (projection ? projection.surface.clientWidth : metrics.viewWidth) / scale;
102
+ const height = (projection ? projection.surface.clientHeight : metrics.viewHeight) / scale;
78
103
  const content = metrics.contentWidth > 0 && metrics.contentHeight > 0;
79
- const area = content ? { x: metrics.contentLeft / scale, y: metrics.contentTop / scale,
80
- width: metrics.contentWidth / scale, height: metrics.contentHeight / scale } : { x, y, width, height };
81
- if (!workspace.scrollbar && content) {
104
+ const box = projection?.svg.viewBox.baseVal;
105
+ const area = box ? { x: box.x, y: box.y, width: Math.max(box.width, width), height: Math.max(box.height, height) } :
106
+ content ? { x: metrics.contentLeft / scale, y: metrics.contentTop / scale,
107
+ width: metrics.contentWidth / scale, height: metrics.contentHeight / scale } : { x, y, width, height };
108
+ if (!projection && !workspace.scrollbar && content) {
82
109
  const right = Math.max(x + width, area.x + area.width), bottom = Math.max(y + height, area.y + area.height);
83
110
  area.x = Math.min(x, area.x);
84
111
  area.y = Math.min(y, area.y);
@@ -102,9 +129,9 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
102
129
  if (needsShapes)
103
130
  refreshShapes();
104
131
  map.toggleAttribute('hidden', false);
105
- const box = `${area.x} ${area.y} ${area.width} ${area.height}`;
106
- attribute(map, 'viewBox', box);
107
- attribute(clip, 'viewBox', box);
132
+ const viewBox = `${area.x} ${area.y} ${area.width} ${area.height}`;
133
+ attribute(map, 'viewBox', viewBox);
134
+ attribute(clip, 'viewBox', viewBox);
108
135
  for (const [name, value] of Object.entries(area))
109
136
  attribute(clip, name, value);
110
137
  for (const [name, value] of Object.entries({ x, y, width, height }))
@@ -144,9 +171,21 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
144
171
  const resize = new view.ResizeObserver(schedule);
145
172
  resize.observe(container);
146
173
  const events = new view.AbortController();
174
+ let projectedSVG;
175
+ container.addEventListener('scriptprojectionchange', () => {
176
+ const next = getScriptProjection(workspace)?.svg;
177
+ needsShapes ||= next !== projectedSVG;
178
+ projectedSVG = next;
179
+ schedule();
180
+ }, { signal: events.signal });
147
181
  view.addEventListener('resize', schedule, { signal: events.signal });
148
182
  view.addEventListener('scroll', schedule, { signal: events.signal, passive: true });
149
183
  const moveView = (left, top) => {
184
+ const projection = getScriptProjection(workspace);
185
+ if (projection) {
186
+ projection.surface.scrollTo(left * workspace.scale, top * workspace.scale);
187
+ return;
188
+ }
150
189
  const metrics = workspace.getMetrics();
151
190
  if (!metrics || !workspace.scrollbar)
152
191
  return;
@@ -156,14 +195,16 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
156
195
  let pointer;
157
196
  const point = (event, inverse) => new view.DOMPoint(event.clientX, event.clientY).matrixTransform(inverse);
158
197
  map.addEventListener('pointerdown', event => {
159
- if (!event.isPrimary || event.button !== 0 || pointer || !workspace.scrollbar)
198
+ const projection = getScriptProjection(workspace);
199
+ if (!event.isPrimary || event.button !== 0 || pointer || (!projection && !workspace.scrollbar))
160
200
  return;
161
201
  const matrix = map.getScreenCTM(), metrics = workspace.getMetrics();
162
202
  if (!matrix || !metrics)
163
203
  return;
164
204
  const inverse = matrix.inverse();
165
205
  pointer = { id: event.pointerId, x: event.clientX, y: event.clientY, start: point(event, inverse), inverse,
166
- left: metrics.viewLeft / workspace.scale, top: metrics.viewTop / workspace.scale,
206
+ left: projection ? projection.surface.scrollLeft / workspace.scale : metrics.viewLeft / workspace.scale,
207
+ top: projection ? projection.surface.scrollTop / workspace.scale : metrics.viewTop / workspace.scale,
167
208
  viewport: event.target === viewport, moved: false };
168
209
  map.setPointerCapture(event.pointerId);
169
210
  }, { signal: events.signal });
@@ -190,8 +231,9 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
190
231
  move(event);
191
232
  if (!pointer.moved) {
192
233
  const current = point(event, pointer.inverse), metrics = workspace.getMetrics();
234
+ const projection = getScriptProjection(workspace);
193
235
  if (metrics)
194
- moveView(current.x - metrics.viewWidth / (2 * workspace.scale), current.y - metrics.viewHeight / (2 * workspace.scale));
236
+ moveView(current.x - (projection ? projection.surface.clientWidth : metrics.viewWidth) / (2 * workspace.scale), current.y - (projection ? projection.surface.clientHeight : metrics.viewHeight) / (2 * workspace.scale));
195
237
  ScratchBlocks.hideChaff(true);
196
238
  }
197
239
  }
@@ -100,6 +100,7 @@ export declare function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspa
100
100
  focusBlock?: string;
101
101
  }): {
102
102
  workspace: any;
103
+ flush(): void;
103
104
  showBlock(id: string): void;
104
105
  dispose(): void;
105
106
  };
package/dist/workspace.js CHANGED
@@ -163,7 +163,7 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
163
163
  const labels = () => japanese() ? { fold: '折りたたみ', unfold: '折りたたみを解除', folded: '折りたたみ中' } :
164
164
  { fold: 'Fold', unfold: 'Unfold', folded: 'Folded' };
165
165
  const vmBlock = (id) => vm.editingTarget?.blocks._blocks[id];
166
- const isFolded = (block) => isHatBlock(block) && isFoldedDefinition(vmBlock(block.id));
166
+ const isFolded = (block) => isFoldedDefinition(vmBlock(block.id));
167
167
  let focus;
168
168
  // The GUI can attach the code area again; what an earlier attachment left on the workspace is not its own.
169
169
  const own = (name) => Object.prototype.hasOwnProperty.call(workspace, name) && !workspace[name][focusOverride] ?
@@ -364,7 +364,7 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
364
364
  /** Paint the folded scripts of a read-only workspace, such as the preview of a code view. */
365
365
  function paintPreviewFolds(blocks, preview, target, label) {
366
366
  for (const top of preview.getTopBlocks(false)) {
367
- paintFold(top, isHatBlock(top) && isFoldedDefinition(target.blocks._blocks[top.id]), label);
367
+ paintFold(top, isFoldedDefinition(target.blocks._blocks[top.id]), label);
368
368
  }
369
369
  }
370
370
  export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, options, onError, presentationElements = null }) {
@@ -988,6 +988,7 @@ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDo
988
988
  modal.appendChild(popup);
989
989
  return {
990
990
  workspace: editor,
991
+ flush() { blocks.Events.fireNow_(); },
991
992
  showBlock(id) {
992
993
  pendingBlock = id;
993
994
  reveal();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.21.3",
3
+ "version": "0.22.1",
4
4
  "description": "Code views for TurboWarp Plus Editor: code in tabs and windows, the detached block palette, script layout and block field editing",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
package/src/code-pane.ts CHANGED
@@ -427,26 +427,64 @@ export function readScriptRelationGraph(targets: readonly RelationTarget[], Scra
427
427
  /**
428
428
  * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
429
429
  * in the script editors. `find` names the function a block calls, if any; `open` shows it.
430
+ * With `scriptEditor`, free-layout blocks first offer to edit their own containing script.
430
431
  */
431
- export function attachFunctionCallMenu(ScratchBlocks, {label, find, open}: {
432
+ export function attachFunctionCallMenu(ScratchBlocks, {label, find, open, scriptEditor}: {
432
433
  label(): string;
433
434
  find(blockId: string): string | undefined;
434
435
  open(functionId: string): void;
436
+ scriptEditor?: {vm: any; locale: string;
437
+ open(scriptId: string, blockId: string, section: 'functions' | 'calls'): void};
435
438
  }) {
436
439
  const prototype = ScratchBlocks.BlockSvg.prototype;
437
440
  const showContextMenu = prototype.showContextMenu_;
438
441
  const patched = function (event) {
439
442
  const functionId = this.isInFlyout ? undefined : find(this.id);
440
- if (!functionId) return showContextMenu.call(this, event);
443
+ const target = scriptEditor?.vm.editingTarget;
444
+ const layout = scriptEditor && getDockedScriptLayout(scriptEditor.vm);
445
+ const script = scriptEditor && !this.isInFlyout && !this.workspace.options.readOnly &&
446
+ this.workspace === ScratchBlocks.getMainWorkspace?.() && layout?.view.view === 'free' &&
447
+ layout.canArrange() && !getCodeSession(scriptEditor.vm).bridge?.focusedScript ? this.getRootBlock() : undefined;
448
+ const scriptId = script && target?.blocks._blocks[script.id] ? script.id : undefined;
449
+ if (!functionId && !scriptId) return showContextMenu.call(this, event);
450
+ const blockId = this.id;
451
+ const japanese = scriptEditor && /^ja(?:-|$)/i.test(scriptEditor.locale);
452
+ const scriptOptions = scriptId ? [
453
+ {section: 'functions' as const, text: japanese ?
454
+ 'このスクリプトを個別の画面で編集する' : 'Edit this script in a separate view'},
455
+ {section: 'calls' as const, text: japanese ?
456
+ 'このスクリプトの呼び出し関係を開く' : 'Open relationships for this script'}
457
+ ].map(({section, text}) => ({text, twPlusMenuIcon: section, separator: false, enabled: true, callback() {
458
+ if (scriptEditor.vm.editingTarget === target && target.blocks._blocks[scriptId]) {
459
+ scriptEditor.open(scriptId, blockId, section);
460
+ }
461
+ }})) : [];
441
462
  const owned = Object.prototype.hasOwnProperty.call(this, 'customContextMenu');
442
463
  const custom = this.customContextMenu;
443
464
  this.customContextMenu = function (options) {
444
465
  custom?.call(this, options);
445
- options.unshift({text: label(), enabled: true, callback: () => open(functionId)});
466
+ if (functionId) options.unshift({text: label(), enabled: true, callback: () => open(functionId)});
467
+ options.unshift(...scriptOptions);
468
+ };
469
+ const {ContextMenu} = ScratchBlocks;
470
+ const populate = scriptOptions.length ? ContextMenu.populate_ : undefined;
471
+ if (scriptOptions.length) ContextMenu.populate_ = function (options, rtl) {
472
+ // Addons reorder ContextMenu.show's options after customContextMenu. Prioritize the final list,
473
+ // in place so their separator indices and the host's icon decoration still use the same order.
474
+ for (const priority of [...scriptOptions].reverse()) {
475
+ const index = options.findIndex(option => option.callback === priority.callback);
476
+ if (index > 0) options.unshift(...options.splice(index, 1));
477
+ }
478
+ for (const option of scriptOptions) option.separator = false;
479
+ if (options.length > 2) options[2].separator = true;
480
+ const menu = populate.call(this, options, rtl);
481
+ menu.getChildAt(2)?.getElement().classList.add('tw-script-editor-menu-divider');
482
+ return menu;
446
483
  };
447
484
  try {
448
485
  return showContextMenu.call(this, event);
449
486
  } finally {
487
+ if (scriptOptions.length) ContextMenu.populate_ = populate;
450
488
  if (owned) this.customContextMenu = custom;
451
489
  else delete this.customContextMenu;
452
490
  }