@kubohiroya/turbowarp-plus-editor-code-views 0.21.3 → 0.22.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.
@@ -5,6 +5,9 @@ import {attachScriptViewMenu, type ScriptViewMenuBlocks, type ScriptViewMenuWork
5
5
  import type {PresentationElements} from './preview-chrome.ts';
6
6
  import {attachScriptArrows, type ScriptRelationContext, type ScriptRelationVisibility} from './script-arrows.ts';
7
7
  import {attachCodeZoomRange} from './code-zoom.ts';
8
+ import {setScriptProjection} from './script-projection.ts';
9
+ import {openSerialScriptEditor} from './serial-script-editor.ts';
10
+ import {isFoldedDefinition, setFoldedDefinition} from './procedure-edits.ts';
8
11
 
9
12
  export type ScriptView = 'free' | 'z' | 'n';
10
13
 
@@ -39,10 +42,15 @@ export function attachScriptView({
39
42
  surface.className = 'tw-script-view-surface';
40
43
  surface.dataset.codeViewControl = '';
41
44
  surface.tabIndex = 0;
42
- surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock));
45
+ surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock || relationContext?.vm));
43
46
  const contents = document.createElement('div');
44
47
  surface.append(contents);
48
+ const gutter = document.createElement('div');
49
+ gutter.className = 'tw-script-fold-gutter';
50
+ gutter.dataset.codeViewControl = '';
51
+ const foldButtons = new Map<string, {button: HTMLButtonElement; top: number}>();
45
52
  let view = initialView;
53
+ let editor: ReturnType<typeof openSerialScriptEditor>;
46
54
  let frame: number | undefined;
47
55
  const svg = workspace.getParentSvg();
48
56
  const observer = new window.MutationObserver(records => {
@@ -51,6 +59,69 @@ export function attachScriptView({
51
59
  const relations = relationContext && attachScriptArrows({workspace, getLocale, ...relationContext});
52
60
  const japanese = () => /^ja(?:-|$)/i.test(getLocale());
53
61
 
62
+ function setFold(ids: string[], value?: boolean) {
63
+ const target = relationContext?.getTarget();
64
+ const runtime = relationContext?.vm?.runtime as {emitProjectChanged?(): void} | undefined;
65
+ if (!target || !runtime?.emitProjectChanged || (canShowBlock && !canShowBlock())) return;
66
+ for (const id of ids) {
67
+ const block = target.blocks._blocks[id];
68
+ if (block) setFoldedDefinition(block, value ?? !isFoldedDefinition(block));
69
+ }
70
+ runtime.emitProjectChanged();
71
+ update();
72
+ }
73
+
74
+ function positionFoldButtons() {
75
+ gutter.style.left = `${surface.offsetLeft}px`;
76
+ gutter.style.top = `${surface.offsetTop}px`;
77
+ gutter.style.height = `${surface.clientHeight}px`;
78
+ for (const {button, top} of foldButtons.values()) button.style.top = `${top - surface.scrollTop}px`;
79
+ }
80
+
81
+ function paintFoldButtons(placements: ReturnType<typeof arrangeScripts>, scale: number) {
82
+ const target = relationContext?.getTarget();
83
+ const ids = new Set(placements.map(({script}) => script.id));
84
+ for (const [id, {button}] of foldButtons) if (!ids.has(id)) {button.remove(); foldButtons.delete(id);}
85
+ for (const {script, y} of placements) {
86
+ let entry = foldButtons.get(script.id);
87
+ if (!entry) {
88
+ const button = document.createElement('button');
89
+ button.type = 'button';
90
+ button.dataset.scriptFoldToggle = script.id;
91
+ button.addEventListener('click', event => {event.stopPropagation(); setFold([script.id]);});
92
+ button.addEventListener('pointerdown', event => event.stopPropagation());
93
+ entry = {button, top: 0};
94
+ foldButtons.set(script.id, entry);
95
+ gutter.append(button);
96
+ }
97
+ const block = target?.blocks._blocks[script.id];
98
+ const folded = isFoldedDefinition(block);
99
+ const label = japanese() ? (folded ? '折りたたみを解除' : '折りたたむ') : (folded ? 'Unfold script' : 'Fold script');
100
+ entry.top = y * scale;
101
+ entry.button.textContent = folded ? '▶' : '▼';
102
+ entry.button.disabled = !block || Boolean(canShowBlock && !canShowBlock());
103
+ entry.button.setAttribute('aria-label', label);
104
+ entry.button.setAttribute('aria-expanded', String(!folded));
105
+ entry.button.title = label;
106
+ }
107
+ positionFoldButtons();
108
+ }
109
+
110
+ function foldOptions() {
111
+ const target = relationContext?.getTarget();
112
+ const runtime = relationContext?.vm?.runtime as {emitProjectChanged?(): void} | undefined;
113
+ if (view === 'free' || !target || !runtime?.emitProjectChanged || (canShowBlock && !canShowBlock())) return [];
114
+ const roots = readScripts(workspace).map(script => target.blocks._blocks[script.id]).filter(Boolean);
115
+ const options = [
116
+ {value: true, text: japanese() ? 'すべて折りたたむ' : 'Fold all'},
117
+ {value: false, text: japanese() ? '折りたたみをすべて解除' : 'Unfold all'}
118
+ ];
119
+ return options.map(({value, text}) => ({text,
120
+ enabled: roots.some(block => isFoldedDefinition(block) !== value),
121
+ callback() {setFold(readScripts(workspace).map(script => script.id), value);}
122
+ }));
123
+ }
124
+
54
125
  function labels() {
55
126
  const choice = choices.find(choice => choice.view === view);
56
127
  surface.setAttribute('aria-label', japanese() ? choice.jaLabel : choice.label);
@@ -63,6 +134,7 @@ export function attachScriptView({
63
134
  const ja = japanese();
64
135
  return {
65
136
  label: ja ? 'コードの並びの見え方を変更する' : 'Change code layout view',
137
+ options: foldOptions(),
66
138
  choices: choices.map(choice => ({
67
139
  text: ja ? choice.jaLabel : choice.label,
68
140
  enabled: true,
@@ -85,8 +157,20 @@ export function attachScriptView({
85
157
  surface.style.setProperty('--tw-script-view-left', !horizontal && bounds.left <= left + 2 ? `${bounds.width}px` : '0px');
86
158
  surface.style.setProperty('--tw-script-view-right', !horizontal && bounds.right >= right - 2 ? `${bounds.width}px` : '0px');
87
159
  }
88
- paintScripts(contents, arrangeScripts(readScripts(workspace), view, 'vertical'), workspace.scale || 1);
89
- relations?.setProjection(contents.querySelector('svg'));
160
+ const scale = workspace.scale || 1;
161
+ const scripts = readScripts(workspace).map(script => {
162
+ // Include raised hats and labels, and exclude folded bodies, when measuring the visible gap.
163
+ const box = (script.root as SVGGraphicsElement).getBBox();
164
+ return {...script, x: script.origin.x + box.x, y: script.origin.y + box.y,
165
+ width: box.width, height: box.height};
166
+ });
167
+ const placements = arrangeScripts(scripts, view, 'vertical', Math.max(64, 48 / scale))
168
+ .map(placement => ({...placement, x: Math.max(placement.x, 32 / scale)}));
169
+ paintScripts(contents, placements, scale);
170
+ paintFoldButtons(placements, scale);
171
+ const projection = contents.querySelector('svg');
172
+ relations?.setProjection(projection);
173
+ setScriptProjection(workspace, {surface, svg: projection});
90
174
  }
91
175
 
92
176
  function update() {
@@ -96,14 +180,20 @@ export function attachScriptView({
96
180
 
97
181
  function setView(next: ScriptView) {
98
182
  menu.close();
183
+ editor?.dispose();
184
+ editor = undefined;
99
185
  observer.disconnect();
100
186
  view = next;
101
187
  surface.hidden = view === 'free';
188
+ gutter.hidden = view === 'free';
102
189
  svg.toggleAttribute('data-script-serial', view !== 'free');
103
190
  labels();
104
191
  if (view === 'free') {
192
+ setScriptProjection(workspace);
105
193
  relations?.setProjection(null);
106
194
  contents.replaceChildren();
195
+ gutter.replaceChildren();
196
+ foldButtons.clear();
107
197
  }
108
198
  else {
109
199
  observer.observe(workspace.getCanvas(), {attributes: true, childList: true, subtree: true});
@@ -120,19 +210,33 @@ export function attachScriptView({
120
210
  surface.addEventListener('click', event => {
121
211
  event.stopPropagation();
122
212
  const id = (event.target as Element).closest('[data-script-view-block]')?.getAttribute('data-script-view-block');
123
- if (!id || !canShowBlock?.()) return;
213
+ if (!id || (canShowBlock && !canShowBlock())) return;
214
+ if (relationContext?.vm) {
215
+ editor?.dispose();
216
+ editor = openSerialScriptEditor(relationContext.vm, relationContext.getTarget(), id, document, getLocale());
217
+ if (editor) return;
218
+ }
219
+ if (!canShowBlock?.()) return;
124
220
  chooseView('free');
125
221
  workspace.centerOnBlock(id);
126
222
  });
127
223
  const resize = new window.ResizeObserver(update);
128
224
  resize.observe(host);
129
- const language = new window.MutationObserver(labels);
225
+ const language = new window.MutationObserver(() => {labels(); update();});
130
226
  language.observe(document.documentElement, {attributes: true, attributeFilter: ['lang']});
131
227
  // The Blockly keyboard listener is document-wide.
132
228
  surface.addEventListener('keydown', event => {
133
229
  if (event.key !== 'Tab') event.stopPropagation();
134
230
  });
135
- host.append(surface);
231
+ gutter.addEventListener('keydown', event => {
232
+ if (event.key !== 'Tab') event.stopPropagation();
233
+ });
234
+ host.append(surface, gutter);
235
+ surface.addEventListener('scroll', () => {
236
+ positionFoldButtons();
237
+ const projection = contents.querySelector('svg');
238
+ if (view !== 'free' && projection) setScriptProjection(workspace, {surface, svg: projection});
239
+ }, {passive: true});
136
240
  setView(initialView);
137
241
  return {
138
242
  update,
@@ -141,6 +245,8 @@ export function attachScriptView({
141
245
  get view() { return view; },
142
246
  setView,
143
247
  dispose() {
248
+ editor?.dispose();
249
+ setScriptProjection(workspace);
144
250
  restoreZoomRange();
145
251
  resize.disconnect();
146
252
  observer.disconnect();
@@ -149,6 +255,8 @@ export function attachScriptView({
149
255
  menu.dispose();
150
256
  relations?.dispose();
151
257
  surface.remove();
258
+ gutter.remove();
259
+ foldButtons.clear();
152
260
  svg.removeAttribute('data-script-serial');
153
261
  }
154
262
  };
@@ -40,9 +40,14 @@ export interface RenderedScript extends ScriptBounds {
40
40
  export function readScripts(workspace: LayoutWorkspace): RenderedScript[] {
41
41
  return workspace.getTopBlocks(false).flatMap(block => {
42
42
  const root = block.getSvgRoot();
43
- if (!root || !workspace.getCanvas().contains(root)) return [];
43
+ if (!root || !workspace.getCanvas().contains(root) || root.hasAttribute('data-tw-plus-hidden')) return [];
44
44
  const origin = block.getRelativeToSurfaceXY();
45
- const {topLeft, bottomRight} = block.getBoundingRectangle();
45
+ let {topLeft, bottomRight} = block.getBoundingRectangle();
46
+ if (root.querySelector(':scope > [data-tw-plus-folded-mark]')) {
47
+ const box = (root as SVGGraphicsElement).getBBox();
48
+ topLeft = {x: origin.x + box.x, y: origin.y + box.y};
49
+ bottomRight = {x: topLeft.x + box.width, y: topLeft.y + box.height};
50
+ }
46
51
  return [{
47
52
  id: block.id, block, root, origin, ...topLeft,
48
53
  width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y
@@ -15,7 +15,8 @@ export type LayoutDirection = 'vertical' | 'horizontal';
15
15
  const alignmentTolerance = 24;
16
16
  const spacing = 32;
17
17
 
18
- export function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection) {
18
+ export function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection,
19
+ gap = spacing) {
19
20
  const bandAxis = order === 'z' ? 'y' : 'x';
20
21
  const scanAxis = order === 'z' ? 'x' : 'y';
21
22
  const compare = (a: T, b: T, first: 'x' | 'y', second: 'x' | 'y') =>
@@ -29,12 +30,12 @@ export function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], or
29
30
  else bands.push([script]);
30
31
  }
31
32
 
32
- let offset = spacing;
33
+ let offset = gap;
33
34
  return bands.flatMap(band => band.sort((a, b) => compare(a, b, scanAxis, bandAxis))).map(script => {
34
35
  const vertical = direction === 'vertical';
35
36
  const x = vertical ? spacing : offset;
36
37
  const y = vertical ? offset : spacing;
37
- offset += Math.ceil(vertical ? script.height : script.width) + spacing;
38
+ offset += Math.ceil(vertical ? script.height : script.width) + gap;
38
39
  return {script, x, y};
39
40
  });
40
41
  }
@@ -0,0 +1,12 @@
1
+ export type ScriptProjection = {surface: HTMLElement; svg: SVGSVGElement};
2
+
3
+ const projections = new WeakMap<object, ScriptProjection>();
4
+
5
+ export const getScriptProjection = (workspace: object) => projections.get(workspace);
6
+
7
+ export function setScriptProjection(workspace: {getInjectionDiv(): HTMLElement}, projection?: ScriptProjection) {
8
+ if (projection) projections.set(workspace, projection);
9
+ else projections.delete(workspace);
10
+ const container = workspace.getInjectionDiv();
11
+ container.dispatchEvent(new container.ownerDocument.defaultView.Event('scriptprojectionchange'));
12
+ }
@@ -40,6 +40,7 @@ export interface ScriptViewMenuWorkspace {
40
40
 
41
41
  interface MenuConfig {
42
42
  label: string;
43
+ options?: MenuOption[];
43
44
  choices: (MenuOption & {checked: boolean})[];
44
45
  }
45
46
 
@@ -160,7 +161,7 @@ export function attachScriptViewMenu(
160
161
  // Only extend the options collected for this workspace, after the existing add-ons.
161
162
  ContextMenu.populate_ = (options, rtl) => {
162
163
  const config = getMenu();
163
- const menu = populate.call(ContextMenu, [...options, triggerOption(config.label)], rtl);
164
+ const menu = populate.call(ContextMenu, [...options, triggerOption(config.label), ...(config.options ?? [])], rtl);
164
165
  addSubmenu(menu, options.length, config, rtl, ContextMenu);
165
166
  return menu;
166
167
  };
@@ -177,7 +178,9 @@ export function attachScriptViewMenu(
177
178
  event.stopPropagation();
178
179
  const config = getMenu();
179
180
  const rtl = workspace.RTL;
180
- const menu = ContextMenu.populate_([triggerOption(config.label)], rtl);
181
+ const menu = ContextMenu.populate_([triggerOption(config.label), ...(config.options ?? []).map(option => ({...option,
182
+ callback() {WidgetDiv.hideIfOwner(surface); option.callback();}
183
+ }))], rtl);
181
184
  const outside = new document.defaultView.AbortController();
182
185
  WidgetDiv.show(surface, rtl, () => {
183
186
  outside.abort();
@@ -0,0 +1,41 @@
1
+ import {getCodeSession} from './workspace.ts';
2
+
3
+ /** Reuse the script editor: its root stays at its original project coordinates. */
4
+ export function openSerialScriptEditor(vm: object, target, id: string, document: Document, locale: string) {
5
+ const bridge = getCodeSession(vm).bridge;
6
+ if (!bridge || !target?.blocks._blocks[id]) 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: ReturnType<typeof bridge.editProcedure>;
22
+ try {
23
+ editor = bridge.editProcedure(area, {target, definitionId: id, editable: true, locale});
24
+ } catch (error) {
25
+ dialog.close();
26
+ dialog.remove();
27
+ throw error;
28
+ }
29
+ let closed = false;
30
+ const dispose = () => {
31
+ if (closed) return;
32
+ closed = true;
33
+ editor.flush();
34
+ editor.dispose();
35
+ dialog.close();
36
+ dialog.remove();
37
+ };
38
+ close.addEventListener('click', dispose);
39
+ dialog.addEventListener('cancel', event => {event.preventDefault(); dispose();});
40
+ return {dispose};
41
+ }
package/src/styles.css CHANGED
@@ -603,17 +603,19 @@
603
603
  stroke-opacity: 1;
604
604
  }
605
605
 
606
+ .tw-script-editor-menu-divider {
607
+ border-top: 1px solid var(--ui-black-transparent, rgb(0 0 0 / 15%));
608
+ margin-block-start: 4px;
609
+ }
610
+
606
611
  .tw-script-relation-script-highlight {
607
612
  fill: light-dark(#3373cc, #93c5fd);
608
613
  fill-opacity: 0.1;
609
- stroke: light-dark(#2563a8, #93c5fd);
610
- stroke-width: 2;
611
- vector-effect: non-scaling-stroke;
614
+ stroke: none;
612
615
  pointer-events: none;
613
616
  }
614
617
 
615
618
  .tw-script-relation-script-highlight[data-emphasis="source"] {
616
- stroke-width: 3;
617
619
  fill-opacity: 0.15;
618
620
  }
619
621
 
@@ -747,13 +749,48 @@
747
749
  display: none;
748
750
  }
749
751
 
752
+ .tw-script-fold-gutter {
753
+ position: absolute;
754
+ z-index: 4;
755
+ width: 28px;
756
+ overflow: hidden;
757
+ pointer-events: none;
758
+ }
759
+
760
+ .tw-script-fold-gutter[hidden] {
761
+ display: none;
762
+ }
763
+
764
+ .tw-script-fold-gutter > button {
765
+ position: absolute;
766
+ left: 2px;
767
+ width: 24px;
768
+ height: 24px;
769
+ padding: 0;
770
+ border: 0;
771
+ border-radius: 4px;
772
+ background: var(--ui-primary, Canvas);
773
+ color: var(--text-primary, CanvasText);
774
+ font: 14px/24px system-ui, sans-serif;
775
+ cursor: pointer;
776
+ pointer-events: auto;
777
+ }
778
+
779
+ .tw-script-fold-gutter > button:is(:hover, :focus-visible) {
780
+ background: var(--ui-tertiary, #e5e7eb);
781
+ outline: 2px solid var(--motion-primary, #4c97ff);
782
+ outline-offset: -2px;
783
+ }
784
+
750
785
  .blocklySvg[data-script-serial] {
751
786
  z-index: 2;
752
787
  background: transparent;
753
788
  pointer-events: none;
754
789
  }
755
790
 
756
- .blocklySvg[data-script-serial] :is(.blocklyMainBackground, .blocklyBlockCanvas, .blocklyBubbleCanvas) {
791
+ .blocklySvg[data-script-serial] :is(.blocklyMainBackground, .blocklyBlockCanvas, .blocklyBubbleCanvas, .blocklyFlyout,
792
+ .blocklyScrollbarVertical, .blocklyScrollbarHorizontal),
793
+ .injectionDiv:has(> [data-script-serial]) > .blocklyFlyout {
757
794
  visibility: hidden;
758
795
  }
759
796
 
@@ -778,6 +815,44 @@
778
815
  cursor: pointer;
779
816
  }
780
817
 
818
+ .tw-serial-script-editor {
819
+ position: fixed;
820
+ inset: 0;
821
+ box-sizing: border-box;
822
+ width: 100vw;
823
+ height: 100vh;
824
+ max-width: none;
825
+ max-height: none;
826
+ margin: 0;
827
+ padding: 1rem;
828
+ border: 0;
829
+ background: var(--ui-primary, Canvas);
830
+ color: var(--text-primary, CanvasText);
831
+ font: 0.9rem/1.4 system-ui, sans-serif;
832
+ }
833
+
834
+ .tw-serial-script-editor[open] {
835
+ display: flex;
836
+ flex-direction: column;
837
+ gap: 0.75rem;
838
+ }
839
+
840
+ .tw-serial-script-editor > h2 {
841
+ margin: 0;
842
+ font-size: 1.1rem;
843
+ }
844
+
845
+ .tw-serial-script-editor > [data-serial-script-editor] {
846
+ position: relative;
847
+ flex: 1;
848
+ min-height: 0;
849
+ }
850
+
851
+ .tw-serial-script-editor > button {
852
+ align-self: flex-end;
853
+ padding: 0.5rem 1.5rem;
854
+ }
855
+
781
856
  .tw-script-layout-dialog {
782
857
  box-sizing: border-box;
783
858
  width: min(44rem, calc(100% - 2rem));
@@ -1,3 +1,5 @@
1
+ import {getScriptProjection} from './script-projection.ts';
2
+
1
3
  type OverviewOptions = {
2
4
  workspace: any;
3
5
  ScratchBlocks: any;
@@ -44,23 +46,42 @@ export function attachWorkspaceOverview({workspace, ScratchBlocks, zoomHeight =
44
46
  function refreshShapes() {
45
47
  const retained = new Set<string>();
46
48
  const additions = document.createDocumentFragment();
47
- for (const block of workspace.getAllBlocks(false)) {
48
- const root = block.getSvgRoot() as SVGElement | null;
49
- if (!root || !canvas.contains(root) || root.closest('[data-tw-plus-hidden]')) continue;
50
- const source = root.querySelector(':scope > .blocklyPath');
51
- const data = source?.getAttribute('d');
52
- if (!data) continue;
53
- retained.add(block.id);
54
- let path = paths.get(block.id);
49
+ const paint = (id: string, data: string, fill: string, transform: string) => {
50
+ retained.add(id);
51
+ let path = paths.get(id);
55
52
  if (!path) {
56
53
  path = element('path');
57
- paths.set(block.id, path);
54
+ paths.set(id, path);
58
55
  additions.append(path);
59
56
  }
60
- const position = block.getRelativeToSurfaceXY();
61
57
  attribute(path, 'd', data);
62
- attribute(path, 'fill', source.getAttribute('fill') || block.getColour());
63
- attribute(path, 'transform', `translate(${position.x} ${position.y})${block.RTL ? ' scale(-1 1)' : ''}`);
58
+ attribute(path, 'fill', fill);
59
+ attribute(path, 'transform', transform);
60
+ };
61
+ const projection = getScriptProjection(workspace);
62
+ if (projection) {
63
+ const inverse = projection.svg.getScreenCTM()?.inverse();
64
+ if (inverse) for (const source of projection.svg.querySelectorAll<SVGPathElement>('.blocklyPath')) {
65
+ if (source.closest('[data-tw-plus-hidden]')) continue;
66
+ const id = source.closest('[data-id]')?.getAttribute('data-id');
67
+ const data = source.getAttribute('d');
68
+ const matrix = source.getScreenCTM();
69
+ if (!id || !data || !matrix) continue;
70
+ const transform = inverse.multiply(matrix);
71
+ paint(id, data, source.getAttribute('fill') || view.getComputedStyle(source).fill,
72
+ `matrix(${transform.a} ${transform.b} ${transform.c} ${transform.d} ${transform.e} ${transform.f})`);
73
+ }
74
+ } else {
75
+ for (const block of workspace.getAllBlocks(false)) {
76
+ const root = block.getSvgRoot() as SVGElement | null;
77
+ if (!root || !canvas.contains(root) || root.closest('[data-tw-plus-hidden]')) continue;
78
+ const source = root.querySelector(':scope > .blocklyPath');
79
+ const data = source?.getAttribute('d');
80
+ if (!data) continue;
81
+ const position = block.getRelativeToSurfaceXY();
82
+ paint(block.id, data, source.getAttribute('fill') || block.getColour(),
83
+ `translate(${position.x} ${position.y})${block.RTL ? ' scale(-1 1)' : ''}`);
84
+ }
64
85
  }
65
86
  for (const [id, path] of paths) if (!retained.has(id)) {path.remove(); paths.delete(id);}
66
87
  if (additions.childNodes.length) shapes.append(additions);
@@ -73,12 +94,17 @@ export function attachWorkspaceOverview({workspace, ScratchBlocks, zoomHeight =
73
94
  const metrics = workspace.isVisible() && workspace.getMetrics();
74
95
  if (!metrics || metrics.viewWidth <= 32 || metrics.viewHeight <= 32) {map.toggleAttribute('hidden', true); return;}
75
96
  const scale = workspace.scale;
76
- const x = metrics.viewLeft / scale, y = metrics.viewTop / scale;
77
- const width = metrics.viewWidth / scale, height = metrics.viewHeight / scale;
97
+ const projection = getScriptProjection(workspace);
98
+ const x = projection ? projection.surface.scrollLeft / scale : metrics.viewLeft / scale;
99
+ const y = projection ? projection.surface.scrollTop / scale : metrics.viewTop / scale;
100
+ const width = (projection ? projection.surface.clientWidth : metrics.viewWidth) / scale;
101
+ const height = (projection ? projection.surface.clientHeight : metrics.viewHeight) / scale;
78
102
  const content = metrics.contentWidth > 0 && metrics.contentHeight > 0;
79
- const area = content ? {x: metrics.contentLeft / scale, y: metrics.contentTop / scale,
103
+ const box = projection?.svg.viewBox.baseVal;
104
+ const area = box ? {x: box.x, y: box.y, width: Math.max(box.width, width), height: Math.max(box.height, height)} :
105
+ content ? {x: metrics.contentLeft / scale, y: metrics.contentTop / scale,
80
106
  width: metrics.contentWidth / scale, height: metrics.contentHeight / scale} : {x, y, width, height};
81
- if (!workspace.scrollbar && content) {
107
+ if (!projection && !workspace.scrollbar && content) {
82
108
  const right = Math.max(x + width, area.x + area.width), bottom = Math.max(y + height, area.y + area.height);
83
109
  area.x = Math.min(x, area.x); area.y = Math.min(y, area.y);
84
110
  area.width = right - area.x; area.height = bottom - area.y;
@@ -98,8 +124,8 @@ export function attachWorkspaceOverview({workspace, ScratchBlocks, zoomHeight =
98
124
  // All layout reads above precede writes. Identical values do not invalidate the editor's styles.
99
125
  if (needsShapes) refreshShapes();
100
126
  map.toggleAttribute('hidden', false);
101
- const box = `${area.x} ${area.y} ${area.width} ${area.height}`;
102
- attribute(map, 'viewBox', box); attribute(clip, 'viewBox', box);
127
+ const viewBox = `${area.x} ${area.y} ${area.width} ${area.height}`;
128
+ attribute(map, 'viewBox', viewBox); attribute(clip, 'viewBox', viewBox);
103
129
  for (const [name, value] of Object.entries(area)) attribute(clip, name, value);
104
130
  for (const [name, value] of Object.entries({x, y, width, height})) attribute(viewport, name, value);
105
131
  style(map, 'width', `${mapWidth}px`); style(map, 'height', `${mapHeight}px`);
@@ -130,10 +156,22 @@ export function attachWorkspaceOverview({workspace, ScratchBlocks, zoomHeight =
130
156
  const resize = new view.ResizeObserver(schedule);
131
157
  resize.observe(container);
132
158
  const events = new view.AbortController();
159
+ let projectedSVG: SVGSVGElement | undefined;
160
+ container.addEventListener('scriptprojectionchange', () => {
161
+ const next = getScriptProjection(workspace)?.svg;
162
+ needsShapes ||= next !== projectedSVG;
163
+ projectedSVG = next;
164
+ schedule();
165
+ }, {signal: events.signal});
133
166
  view.addEventListener('resize', schedule, {signal: events.signal});
134
167
  view.addEventListener('scroll', schedule, {signal: events.signal, passive: true});
135
168
 
136
169
  const moveView = (left: number, top: number) => {
170
+ const projection = getScriptProjection(workspace);
171
+ if (projection) {
172
+ projection.surface.scrollTo(left * workspace.scale, top * workspace.scale);
173
+ return;
174
+ }
137
175
  const metrics = workspace.getMetrics();
138
176
  if (!metrics || !workspace.scrollbar) return;
139
177
  const clamp = (value: number, maximum: number) => Math.max(0, Math.min(value, Math.max(0, maximum)));
@@ -146,12 +184,14 @@ export function attachWorkspaceOverview({workspace, ScratchBlocks, zoomHeight =
146
184
  const point = (event: PointerEvent, inverse: DOMMatrix) =>
147
185
  new view.DOMPoint(event.clientX, event.clientY).matrixTransform(inverse);
148
186
  map.addEventListener('pointerdown', event => {
149
- if (!event.isPrimary || event.button !== 0 || pointer || !workspace.scrollbar) return;
187
+ const projection = getScriptProjection(workspace);
188
+ if (!event.isPrimary || event.button !== 0 || pointer || (!projection && !workspace.scrollbar)) return;
150
189
  const matrix = map.getScreenCTM(), metrics = workspace.getMetrics();
151
190
  if (!matrix || !metrics) return;
152
191
  const inverse = matrix.inverse();
153
192
  pointer = {id: event.pointerId, x: event.clientX, y: event.clientY, start: point(event, inverse), inverse,
154
- left: metrics.viewLeft / workspace.scale, top: metrics.viewTop / workspace.scale,
193
+ left: projection ? projection.surface.scrollLeft / workspace.scale : metrics.viewLeft / workspace.scale,
194
+ top: projection ? projection.surface.scrollTop / workspace.scale : metrics.viewTop / workspace.scale,
155
195
  viewport: event.target === viewport, moved: false};
156
196
  map.setPointerCapture(event.pointerId);
157
197
  }, {signal: events.signal});
@@ -173,8 +213,9 @@ export function attachWorkspaceOverview({workspace, ScratchBlocks, zoomHeight =
173
213
  move(event);
174
214
  if (!pointer.moved) {
175
215
  const current = point(event, pointer.inverse), metrics = workspace.getMetrics();
176
- if (metrics) moveView(current.x - metrics.viewWidth / (2 * workspace.scale),
177
- current.y - metrics.viewHeight / (2 * workspace.scale));
216
+ const projection = getScriptProjection(workspace);
217
+ if (metrics) moveView(current.x - (projection ? projection.surface.clientWidth : metrics.viewWidth) / (2 * workspace.scale),
218
+ current.y - (projection ? projection.surface.clientHeight : metrics.viewHeight) / (2 * workspace.scale));
178
219
  ScratchBlocks.hideChaff(true);
179
220
  }
180
221
  }
package/src/workspace.ts CHANGED
@@ -222,7 +222,7 @@ function attachScriptVisibility({vm, blocks, workspace, homeDocument, onError})
222
222
  const labels = () => japanese() ? {fold: '折りたたみ', unfold: '折りたたみを解除', folded: '折りたたみ中'} :
223
223
  {fold: 'Fold', unfold: 'Unfold', folded: 'Folded'};
224
224
  const vmBlock = (id: string) => vm.editingTarget?.blocks._blocks[id];
225
- const isFolded = (block: StackBlock) => isHatBlock(block) && isFoldedDefinition(vmBlock(block.id));
225
+ const isFolded = (block: StackBlock) => isFoldedDefinition(vmBlock(block.id));
226
226
 
227
227
  let focus: {id: string; extras: Set<string>; onLost?: () => void} | undefined;
228
228
  // The GUI can attach the code area again; what an earlier attachment left on the workspace is not its own.
@@ -404,7 +404,7 @@ function attachScriptVisibility({vm, blocks, workspace, homeDocument, onError})
404
404
  /** Paint the folded scripts of a read-only workspace, such as the preview of a code view. */
405
405
  function paintPreviewFolds(blocks, preview, target, label: string) {
406
406
  for (const top of preview.getTopBlocks(false) as StackBlock[]) {
407
- paintFold(top, isHatBlock(top) && isFoldedDefinition(target.blocks._blocks[top.id]), label);
407
+ paintFold(top, isFoldedDefinition(target.blocks._blocks[top.id]), label);
408
408
  }
409
409
  }
410
410
 
@@ -1008,6 +1008,7 @@ function attachProcedureEditor({vm, blocks, workspace, options, onError, homeDoc
1008
1008
 
1009
1009
  return {
1010
1010
  workspace: editor,
1011
+ flush() {blocks.Events.fireNow_();},
1011
1012
  showBlock(id: string) {
1012
1013
  pendingBlock = id;
1013
1014
  reveal();