@kubohiroya/turbowarp-plus-editor-code-views 0.22.0 → 0.22.2

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.
@@ -0,0 +1,87 @@
1
+ import { readScripts } from "./script-layout-workspace.js";
2
+ /** Read expanded bounds without changing the user's folding or moving any comments. */
3
+ export function readSemanticWorkspace(workspace) {
4
+ const scripts = readScripts(workspace).map(script => {
5
+ const { topLeft, bottomRight } = script.block.getBoundingRectangle();
6
+ const bounds = { id: script.id, ...topLeft, width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y };
7
+ return { ...script, ...bounds, bounds };
8
+ });
9
+ const byId = new Map(scripts.map(s => [s.id, s]));
10
+ const comments = (workspace.getTopComments?.(false) ?? []).map(comment => {
11
+ const { topLeft, bottomRight } = comment.getBoundingRectangle();
12
+ const rootId = comment.block_?.getRootBlock().id;
13
+ if (rootId && (!comment.getXY || !comment.moveTo))
14
+ throw new Error('Comment cannot be moved safely');
15
+ return { id: comment.id, comment, rootId, origin: comment.getXY?.() ?? comment.getRelativeToSurfaceXY?.() ?? topLeft,
16
+ text: comment.getText?.() ?? '',
17
+ ...topLeft, width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y,
18
+ svg: comment.getSvgRoot?.() ?? comment.bubble_?.bubbleGroup_ };
19
+ });
20
+ for (const comment of comments) {
21
+ const script = byId.get(comment.rootId);
22
+ if (!script)
23
+ continue;
24
+ const right = Math.max(script.x + script.width, comment.x + comment.width);
25
+ const bottom = Math.max(script.y + script.height, comment.y + comment.height);
26
+ script.x = Math.min(script.x, comment.x);
27
+ script.y = Math.min(script.y, comment.y);
28
+ script.width = right - script.x;
29
+ script.height = bottom - script.y;
30
+ }
31
+ return { scripts, comments, obstacles: comments.filter(c => !byId.has(c.rootId)) };
32
+ }
33
+ /** Roll back queued native moves before any of them reach the VM or the undo stacks. */
34
+ export function applySemanticLayout(workspace, events, placements, comments) {
35
+ const outer = events.getGroup();
36
+ const queue = events.FIRE_QUEUE_;
37
+ if (!queue || !events.disable || !events.enable)
38
+ throw new Error('Transactional move events are unavailable');
39
+ const start = queue.length;
40
+ const roots = placements.map(p => ({ block: p.script.block, position: p.script.block.getRelativeToSurfaceXY() }));
41
+ const byId = new Map(placements.map(p => [p.script.id, p]));
42
+ events.setGroup(true);
43
+ workspace.setResizesEnabled(false);
44
+ try {
45
+ for (const p of placements) {
46
+ const dx = p.x - p.script.x, dy = p.y - p.script.y;
47
+ if (dx || dy)
48
+ p.script.block.moveBy(dx, dy);
49
+ }
50
+ for (const c of comments) {
51
+ const p = byId.get(c.rootId);
52
+ if (!p)
53
+ continue;
54
+ c.comment.moveTo(c.origin.x + p.x - p.script.x, c.origin.y + p.y - p.script.y);
55
+ }
56
+ // Native block moves already carry their attached comments on undo/redo. Recording an
57
+ // absolute comment move as well would move it twice on redo. Keep the notification for
58
+ // the VM (including child-window serialization), but let the block own its undo step.
59
+ const attached = new Set(comments.filter(c => byId.has(c.rootId)).map(c => c.id));
60
+ for (const event of queue.slice(start)) {
61
+ if (event.type === 'comment_move' && attached.has(event.commentId))
62
+ event.recordUndo = false;
63
+ }
64
+ }
65
+ catch (error) {
66
+ queue.splice(start);
67
+ events.disable();
68
+ try {
69
+ for (const { block, position } of roots) {
70
+ const current = block.getRelativeToSurfaceXY();
71
+ block.moveBy(position.x - current.x, position.y - current.y);
72
+ }
73
+ for (const c of comments)
74
+ if (byId.has(c.rootId))
75
+ c.comment.moveTo(c.origin.x, c.origin.y);
76
+ }
77
+ finally {
78
+ events.enable();
79
+ }
80
+ throw error;
81
+ }
82
+ finally {
83
+ workspace.setResizesEnabled(true);
84
+ events.setGroup(outer);
85
+ }
86
+ events.fireNow_();
87
+ }
@@ -0,0 +1,34 @@
1
+ import type { ScriptBounds } from './script-layout.ts';
2
+ import type { ScriptRelation } from './script-relations.ts';
3
+ export interface SemanticPlacement<T extends ScriptBounds = ScriptBounds> {
4
+ script: T;
5
+ x: number;
6
+ y: number;
7
+ column: number;
8
+ group: number;
9
+ }
10
+ export interface SemanticLayoutOptions {
11
+ signal?: AbortSignal;
12
+ /** Yield to the host without making the simulation depend on elapsed time. */
13
+ yieldControl?(): Promise<void>;
14
+ obstacles?: readonly ScriptBounds[];
15
+ }
16
+ export declare const semanticLayoutLimits: {
17
+ scripts: number;
18
+ relations: number;
19
+ steps: number;
20
+ };
21
+ /**
22
+ * Lay out the SCC condensation DAG in ranks, then relax rectangles with Matter.js.
23
+ * Canonical ID order, fixed steps and final packing keep repeated runs stable.
24
+ * Relations to other targets are shown by the preview, never used to move those targets.
25
+ */
26
+ export declare function arrangeSemanticScripts<T extends ScriptBounds>(scripts: readonly T[], relations: readonly ScriptRelation[], targetId: string, options?: SemanticLayoutOptions): Promise<{
27
+ placements: SemanticPlacement<T>[];
28
+ metrics: {
29
+ nodes: number;
30
+ edges: number;
31
+ steps: number;
32
+ fallback: boolean;
33
+ };
34
+ }>;
@@ -0,0 +1,271 @@
1
+ import Matter from 'matter-js';
2
+ export const semanticLayoutLimits = { scripts: 1000, relations: 10000, steps: 120 };
3
+ const gap = 64;
4
+ const compareId = (a, b) => a < b ? -1 : Number(a > b);
5
+ const overlaps = (a, b) => a.x < b.x + b.width + gap && b.x < a.x + a.width + gap &&
6
+ a.y < b.y + b.height + gap && b.y < a.y + a.height + gap;
7
+ function check(signal) {
8
+ if (signal?.aborted)
9
+ throw new Error('Layout cancelled');
10
+ }
11
+ /** Iterative Kosaraju traversal: recursive projects must not exhaust the JS stack. */
12
+ function components(ids, outgoing, incoming) {
13
+ const seen = new Set();
14
+ const finished = [];
15
+ for (const id of ids) {
16
+ if (seen.has(id))
17
+ continue;
18
+ const stack = [[id, 0]];
19
+ seen.add(id);
20
+ while (stack.length) {
21
+ const entry = stack.at(-1);
22
+ const edges = outgoing.get(entry[0]);
23
+ if (entry[1] === edges.length) {
24
+ finished.push(entry[0]);
25
+ stack.pop();
26
+ continue;
27
+ }
28
+ const next = edges[entry[1]++];
29
+ if (!seen.has(next)) {
30
+ seen.add(next);
31
+ stack.push([next, 0]);
32
+ }
33
+ }
34
+ }
35
+ seen.clear();
36
+ const groups = [];
37
+ for (const id of finished.reverse()) {
38
+ if (seen.has(id))
39
+ continue;
40
+ const group = [], stack = [id];
41
+ seen.add(id);
42
+ while (stack.length) {
43
+ const current = stack.pop();
44
+ group.push(current);
45
+ for (const next of incoming.get(current))
46
+ if (!seen.has(next)) {
47
+ seen.add(next);
48
+ stack.push(next);
49
+ }
50
+ }
51
+ groups.push(group.sort(compareId));
52
+ }
53
+ return groups.sort((a, b) => compareId(a[0], b[0]));
54
+ }
55
+ /**
56
+ * Lay out the SCC condensation DAG in ranks, then relax rectangles with Matter.js.
57
+ * Canonical ID order, fixed steps and final packing keep repeated runs stable.
58
+ * Relations to other targets are shown by the preview, never used to move those targets.
59
+ */
60
+ export async function arrangeSemanticScripts(scripts, relations, targetId, options = {}) {
61
+ const { signal, obstacles = [] } = options;
62
+ const yieldControl = options.yieldControl ?? (() => new Promise(resolve => setTimeout(resolve, 0)));
63
+ check(signal);
64
+ if (scripts.length > semanticLayoutLimits.scripts || relations.length > semanticLayoutLimits.relations ||
65
+ obstacles.length > semanticLayoutLimits.scripts)
66
+ throw new Error('Layout size limit exceeded');
67
+ const ordered = [...scripts].sort((a, b) => compareId(a.id, b.id));
68
+ if (new Set(ordered.map(s => s.id)).size !== ordered.length || [...ordered, ...obstacles].some(s => ![s.x, s.y, s.width, s.height].every(Number.isFinite) || s.width <= 0 || s.height <= 0)) {
69
+ throw new Error('Invalid script bounds');
70
+ }
71
+ const ids = ordered.map(s => s.id);
72
+ const outgoing = new Map(ids.map(id => [id, []]));
73
+ const incoming = new Map(ids.map(id => [id, []]));
74
+ const edges = new Set();
75
+ for (const { source, destination, unresolved } of relations) {
76
+ if (unresolved || source.targetId !== targetId || destination?.targetId !== targetId ||
77
+ !outgoing.has(source.scriptId) || !incoming.has(destination.scriptId))
78
+ continue;
79
+ const key = JSON.stringify([source.scriptId, destination.scriptId]);
80
+ if (edges.has(key))
81
+ continue;
82
+ edges.add(key);
83
+ outgoing.get(source.scriptId).push(destination.scriptId);
84
+ incoming.get(destination.scriptId).push(source.scriptId);
85
+ }
86
+ for (const map of [outgoing, incoming])
87
+ for (const entries of map.values())
88
+ entries.sort(compareId);
89
+ const scc = components(ids, outgoing, incoming);
90
+ const owner = new Map(scc.flatMap((group, index) => group.map(id => [id, index])));
91
+ const next = scc.map(() => new Set()), before = scc.map(() => new Set());
92
+ for (const [id, children] of outgoing)
93
+ for (const child of children) {
94
+ const a = owner.get(id), b = owner.get(child);
95
+ if (a !== b) {
96
+ next[a].add(b);
97
+ before[b].add(a);
98
+ }
99
+ }
100
+ const rank = scc.map(() => 0), remaining = before.map(set => set.size);
101
+ const ready = remaining.flatMap((n, i) => n ? [] : [i]);
102
+ for (let cursor = 0; cursor < ready.length; cursor++) {
103
+ const current = ready[cursor];
104
+ for (const child of next[current]) {
105
+ rank[child] = Math.max(rank[child], rank[current] + 1);
106
+ if (--remaining[child] === 0)
107
+ ready.push(child);
108
+ }
109
+ }
110
+ // Separate weak components, including orphan scripts, into non-overlapping bands.
111
+ const band = new Map();
112
+ let bandCount = 0;
113
+ for (const id of ids) {
114
+ if (band.has(id))
115
+ continue;
116
+ const stack = [id];
117
+ band.set(id, bandCount);
118
+ while (stack.length) {
119
+ const current = stack.pop();
120
+ for (const adjacent of [...outgoing.get(current), ...incoming.get(current)]) {
121
+ if (!band.has(adjacent)) {
122
+ band.set(adjacent, bandCount);
123
+ stack.push(adjacent);
124
+ }
125
+ }
126
+ }
127
+ bandCount++;
128
+ }
129
+ await yieldControl();
130
+ check(signal);
131
+ const widths = new Map();
132
+ for (const script of ordered) {
133
+ const column = rank[owner.get(script.id)];
134
+ widths.set(column, Math.max(widths.get(column) ?? 0, script.width));
135
+ }
136
+ const columnX = [];
137
+ let x = gap;
138
+ for (let column = 0; column < widths.size; column++) {
139
+ columnX[column] = x;
140
+ x += widths.get(column) + gap * 2;
141
+ }
142
+ const placements = [];
143
+ let bandTop = gap;
144
+ for (let group = 0; group < bandCount; group++) {
145
+ const columns = new Map();
146
+ for (const script of ordered)
147
+ if (band.get(script.id) === group) {
148
+ const column = rank[owner.get(script.id)];
149
+ const entries = columns.get(column) ?? [];
150
+ entries.push(script);
151
+ columns.set(column, entries);
152
+ }
153
+ // Barycentric sweeps reduce crossings; SCC members stay contiguous.
154
+ const order = new Map();
155
+ for (const entries of columns.values())
156
+ entries.forEach((s, i) => order.set(s.id, i));
157
+ const ranks = [...columns.keys()].sort((a, b) => a - b);
158
+ for (let sweep = 0; sweep < 4; sweep++) {
159
+ const neighbors = sweep % 2 ? outgoing : incoming;
160
+ for (const column of sweep % 2 ? [...ranks].reverse() : ranks) {
161
+ const mean = (id) => {
162
+ const members = scc[owner.get(id)];
163
+ const values = members.flatMap(member => neighbors.get(member))
164
+ .filter(n => owner.get(n) !== owner.get(id)).map(n => order.get(n) ?? 0);
165
+ return values.length ? values.reduce((a, b) => a + b, 0) / values.length : order.get(members[0]) ?? 0;
166
+ };
167
+ const entries = columns.get(column);
168
+ entries.sort((a, b) => owner.get(a.id) === owner.get(b.id) ? compareId(a.id, b.id) :
169
+ mean(a.id) - mean(b.id) || owner.get(a.id) - owner.get(b.id));
170
+ entries.forEach((s, i) => order.set(s.id, i));
171
+ }
172
+ }
173
+ let bottom = bandTop;
174
+ for (const column of ranks) {
175
+ let y = bandTop;
176
+ for (const script of columns.get(column)) {
177
+ placements.push({ script, x: columnX[column], y, column, group });
178
+ y += script.height + gap;
179
+ }
180
+ bottom = Math.max(bottom, y);
181
+ }
182
+ bandTop = bottom + gap * 2;
183
+ }
184
+ const engine = Matter.Engine.create({ gravity: { x: 0, y: 0, scale: 0 }, enableSleeping: false });
185
+ let steps = 0;
186
+ let fallback = false;
187
+ try {
188
+ const bodies = placements.map((p, index) => Matter.Bodies.rectangle(p.x + p.script.width / 2, p.y + p.script.height / 2, p.script.width + gap, p.script.height + gap, { id: index + 1, inertia: Infinity, restitution: 0, frictionAir: .35, friction: 0 }));
189
+ const fixed = [...obstacles].sort((a, b) => compareId(a.id, b.id)).map((o, index) => Matter.Bodies.rectangle(o.x + o.width / 2, o.y + o.height / 2, o.width + gap, o.height + gap, { id: bodies.length + index + 1, isStatic: true }));
190
+ Matter.Composite.add(engine.world, [...bodies, ...fixed]);
191
+ const byId = new Map(placements.map((p, i) => [p.script.id, i]));
192
+ // Attract related rectangles to the same reading band, without losing their rank.
193
+ const targets = placements.map(p => {
194
+ const parents = incoming.get(p.script.id).filter(id => owner.get(id) !== owner.get(p.script.id));
195
+ const centers = parents.map(id => {
196
+ const parent = placements[byId.get(id)];
197
+ return parent.y + parent.script.height / 2;
198
+ });
199
+ return { x: p.x + p.script.width / 2, y: centers.length ?
200
+ centers.reduce((a, b) => a + b, 0) / centers.length : p.y + p.script.height / 2 };
201
+ });
202
+ let stableSteps = 0;
203
+ for (; steps < semanticLayoutLimits.steps && bodies.length; steps++) {
204
+ if (steps % 8 === 0) {
205
+ await yieldControl();
206
+ check(signal);
207
+ }
208
+ bodies.forEach((body, i) => {
209
+ const target = targets[i];
210
+ Matter.Body.applyForce(body, body.position, {
211
+ x: (target.x - body.position.x) * body.mass * .00002,
212
+ y: (target.y - body.position.y) * body.mass * .00002
213
+ });
214
+ });
215
+ Matter.Engine.update(engine, 1000 / 60);
216
+ stableSteps = bodies.every(body => body.speed < .01) ? stableSteps + 1 : 0;
217
+ if (stableSteps >= 12) {
218
+ steps++;
219
+ break;
220
+ }
221
+ }
222
+ if (steps === semanticLayoutLimits.steps)
223
+ fallback = true;
224
+ // Snap ranks and preserve canonical within-column order after the physical relaxation.
225
+ let bottom = gap;
226
+ for (let group = 0; group < bandCount; group++) {
227
+ let groupBottom = bottom;
228
+ for (const column of [...widths.keys()].sort((a, b) => a - b)) {
229
+ let y = bottom;
230
+ for (const p of placements.filter(p => p.group === group && p.column === column)) {
231
+ const body = bodies[byId.get(p.script.id)];
232
+ const relaxed = body.position.y - p.script.height / 2;
233
+ if (!Number.isFinite(relaxed))
234
+ fallback = true;
235
+ p.y = Math.ceil(Math.max(y, Number.isFinite(relaxed) ? relaxed : y));
236
+ // Keep loose comments fixed. Move past any intersecting obstacle.
237
+ let changed = true;
238
+ while (changed) {
239
+ changed = false;
240
+ for (const obstacle of obstacles)
241
+ if (overlaps({ ...p.script, x: p.x, y: p.y }, obstacle)) {
242
+ p.y = obstacle.y + obstacle.height + gap;
243
+ changed = true;
244
+ fallback = true;
245
+ }
246
+ }
247
+ y = p.y + p.script.height + gap;
248
+ }
249
+ groupBottom = Math.max(groupBottom, y);
250
+ }
251
+ bottom = groupBottom + gap * 2;
252
+ if (group % 32 === 0) {
253
+ await yieldControl();
254
+ check(signal);
255
+ }
256
+ }
257
+ const boxes = placements.map(p => ({ ...p.script, x: p.x, y: p.y }));
258
+ for (let i = 0; i < boxes.length; i++) {
259
+ if (![boxes[i].x, boxes[i].y].every(Number.isFinite) ||
260
+ boxes.slice(i + 1).some(b => overlaps(boxes[i], b)) || obstacles.some(o => overlaps(boxes[i], o))) {
261
+ throw new Error('Layout validation failed');
262
+ }
263
+ }
264
+ check(signal);
265
+ return { placements, metrics: { nodes: scripts.length, edges: edges.size, steps, fallback } };
266
+ }
267
+ finally {
268
+ Matter.Composite.clear(engine.world, false);
269
+ Matter.Engine.clear(engine);
270
+ }
271
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.22.0",
3
+ "version": "0.22.2",
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",
@@ -144,7 +144,8 @@
144
144
  "test:browser": "npm run build && node --test test/*.browser.ts"
145
145
  },
146
146
  "dependencies": {
147
- "@kubohiroya/turbowarp-script-transfer": "0.1.5"
147
+ "@kubohiroya/turbowarp-script-transfer": "0.1.5",
148
+ "matter-js": "0.20.0"
148
149
  },
149
150
  "peerDependencies": {
150
151
  "@kubohiroya/turbowarp-extension-security-dialog": ">=0.9.0 <0.10.0",
@@ -157,6 +158,7 @@
157
158
  "@kubohiroya/turbowarp-plus-editor-test-runtime": "0.2.0",
158
159
  "@kubohiroya/turbowarp-plus-editor-windows": "0.2.0",
159
160
  "@playwright/test": "1.64.1",
161
+ "@types/matter-js": "0.20.2",
160
162
  "@types/react": "18.3.31",
161
163
  "@types/react-dom": "18.3.7",
162
164
  "jsdom": "26.1.0",
@@ -74,6 +74,8 @@ export function startCodePopout({ScratchBlocks, PopupLayout, attachWorkspaceNavi
74
74
  let edits = [];
75
75
  const scriptView = attachScriptView({workspace, ScratchBlocks, getLocale: () => locale,
76
76
  mount: workspaceArea, canShowBlock: () => editable && !blockedSnapshot,
77
+ semanticLayout: {events: ScratchBlocks.Events, canArrange: () =>
78
+ editable && !blockedSnapshot && document.hasFocus() && !mount.inert && !workspace.isDragging()},
77
79
  hasWorkspaceMenu: () => !mount.inert,
78
80
  relations: {
79
81
  getTarget: () => targetId ? {id: targetId, blocks: {_blocks: history.blocks}} : undefined,
@@ -189,6 +189,7 @@ export function createHorizontalBlockPalette({getScratchBlocks, openExtensionLib
189
189
  const capture = {capture: true, signal: events.signal};
190
190
  const original = {
191
191
  dispose: toolbox.dispose,
192
+ setVisible: workspace.setVisible,
192
193
  getClientRect: toolbox.getClientRect,
193
194
  getHeight: toolbox.getHeight,
194
195
  getWidth: toolbox.getWidth,
@@ -209,6 +210,18 @@ export function createHorizontalBlockPalette({getScratchBlocks, openExtensionLib
209
210
  let scrollBeforeSearch = 0;
210
211
  const scrollPositions = new Map();
211
212
  const verticalPosition = workspace.toolboxPosition;
213
+ // Scratch Blocks shows a workspace by setting its toolbox to display:block, overriding the
214
+ // horizontal palette's flex layout. Let the stylesheet lay it out, then refresh its metrics.
215
+ const restoreHorizontalDisplay = () => {
216
+ if (!horizontal || menu.style.display !== 'block') return false;
217
+ menu.style.removeProperty('display');
218
+ return true;
219
+ };
220
+ const setVisible = workspace.setVisible = function (...args) {
221
+ const result = original.setVisible.apply(this, args);
222
+ if (restoreHorizontalDisplay()) workspace.resize();
223
+ return result;
224
+ };
212
225
  const categoryById = id => toolbox.categoryMenu_.categories_.find(category => category.id_ === id);
213
226
  const getLocale = () => ScratchBlocks.ScratchMsgs.currentLocale_ || doc.documentElement.lang;
214
227
  // A category nested in another opens from its group's child palette.
@@ -597,6 +610,7 @@ export function createHorizontalBlockPalette({getScratchBlocks, openExtensionLib
597
610
  workspace.toolboxPosition = horizontal ? ScratchBlocks.TOOLBOX_AT_TOP : verticalPosition;
598
611
  menu.classList.toggle(styles.horizontal, horizontal);
599
612
  menu.toggleAttribute('data-horizontal-block-palette', horizontal);
613
+ restoreHorizontalDisplay();
600
614
  panel.classList.toggle(styles.panel, horizontal);
601
615
  scrollbar.classList.toggle(styles.scrollbar, horizontal);
602
616
  if (horizontal) body.setAttribute('transform', `translate(0 ${paletteSearchHeight}) ${bodyTransform ?? ''}`);
@@ -713,6 +727,7 @@ export function createHorizontalBlockPalette({getScratchBlocks, openExtensionLib
713
727
  }
714
728
  });
715
729
  toolbox.dispose = () => {
730
+ if (workspace.setVisible === setVisible) workspace.setVisible = original.setVisible;
716
731
  paletteRefreshers.delete(redraw);
717
732
  newSpritePrompts.splice(newSpritePrompts.indexOf(askNewSprite) >>> 0, 1);
718
733
  paletteMenu.dispose();
@@ -24,15 +24,15 @@ type Point = {x: number; y: number};
24
24
  type Box = Point & {width: number; height: number};
25
25
  type Anchor = {id: string; box: Box; point(side: 'left' | 'right', fraction: number): Point};
26
26
  type Drawing = {relation: ScriptRelation; source?: Anchor; destination?: Anchor; count: number;
27
- serialRoute?: {right: number; top: number; clearance: number}};
27
+ serialRoute?: {right: number; top: number; clearance: number; radius: number}};
28
28
 
29
- function roundedRoute(points: Point[], radius: number) {
29
+ function roundedRoute(points: Point[], radii: readonly number[]) {
30
30
  let path = `M ${points[0].x} ${points[0].y}`;
31
31
  for (let index = 1; index < points.length - 1; index++) {
32
32
  const before = points[index - 1], corner = points[index], after = points[index + 1];
33
33
  const entering = Math.hypot(corner.x - before.x, corner.y - before.y);
34
34
  const leaving = Math.hypot(after.x - corner.x, after.y - corner.y);
35
- const size = Math.min(radius, entering / 2, leaving / 2);
35
+ const size = Math.min(radii[index - 1], entering / 2, leaving / 2);
36
36
  if (!size) {path += ` L ${corner.x} ${corner.y}`; continue;}
37
37
  const first = {x: corner.x + (before.x - corner.x) * size / entering,
38
38
  y: corner.y + (before.y - corner.y) * size / entering};
@@ -44,23 +44,6 @@ function roundedRoute(points: Point[], radius: number) {
44
44
  return `${path} L ${end.x} ${end.y}`;
45
45
  }
46
46
  const ns = 'http://www.w3.org/2000/svg';
47
- // Keep the same sixteen-unit hourglass as the call graph's relation badge.
48
- const relationWaitGlyph = 'M1 1h14M1 15h14M2 1v3l12 8v3M14 1v3l-12 8v3M2 4h12M2 12h12';
49
-
50
- /** Keep the badge beside the receiving end of the path, leaving its stroke visible. */
51
- function waitBadgePoint(path: string, offset: number): Point {
52
- const values = path.match(/-?(?:\d*\.?\d+)(?:e[+-]?\d+)?/gi).map(Number);
53
- const [sx, sy] = values;
54
- const [bx, by, tx, ty] = values.slice(-4);
55
- const endX = tx - bx;
56
- const endY = ty - by;
57
- const dx = endX || endY ? endX : tx - sx;
58
- const dy = endX || endY ? endY : ty - sy;
59
- const length = Math.hypot(dx, dy) || 1;
60
- const side = -dy < 0 || dy === 0 && dx > 0 ? -1 : 1;
61
- return {x: tx - dx / length * offset * .75 - dy / length * offset * side,
62
- y: ty - dy / length * offset * .75 + dx / length * offset * side};
63
- }
64
47
  type Outline = {points: (Point & {distance: number})[]; cuts: Map<string, Point>};
65
48
  const outlines = new Map<string, Outline>();
66
49
 
@@ -306,26 +289,20 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
306
289
  badgePoint = {x: middle, y: top - 6};
307
290
  }
308
291
  if (serialRoute && source && destination) {
309
- const {right, top, clearance} = serialRoute;
292
+ const {right, top, clearance, radius} = serialRoute;
310
293
  // Leave room beside every script before turning vertically, then return through the gap above the hat.
311
294
  const approach = end.x - clearance;
312
295
  path = roundedRoute([start, {x: right, y: start.y}, {x: right, y: top},
313
- {x: approach, y: top}, {x: approach, y: end.y}, end], clearance);
296
+ {x: approach, y: top}, {x: approach, y: end.y}, end], [radius, radius, clearance, clearance]);
314
297
  badgePoint = {x: right, y: (start.y + top) / 2};
315
298
  }
316
299
  const head = `M ${end.x - 9} ${end.y - 5} L ${end.x} ${end.y} L ${end.x - 9} ${end.y + 5}`;
317
- let waitTransform: string | undefined;
318
- if (relation.kind === 'message' && relation.wait) {
319
- const point = waitBadgePoint(path, 24);
320
- badgePoint = {x: point.x + 16, y: point.y + 4};
321
- waitTransform = `translate(${point.x} ${point.y})`;
322
- }
323
- return {path, head, recursive, badgePoint, waitTransform};
300
+ return {path, head, recursive, badgePoint};
324
301
  }
325
302
 
326
303
  function drawArrow(drawing: Drawing, matrix: DOMMatrix, inverse: DOMMatrix, area: DOMRect, highlighted: boolean) {
327
304
  const {relation, source, destination, count} = drawing;
328
- const {path, head, recursive, badgePoint, waitTransform} = arrowGeometry(drawing, matrix, inverse, area, highlighted);
305
+ const {path, head, recursive, badgePoint} = arrowGeometry(drawing, matrix, inverse, area, highlighted);
329
306
  const strings = text();
330
307
  const group = element('g', {
331
308
  'data-script-relation': relation.kind,
@@ -348,18 +325,9 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
348
325
  class: 'tw-script-relation-head',
349
326
  d: head
350
327
  }));
351
- if (waiting) {
352
- const badge = element('g', {class: 'tw-script-relation-wait', 'aria-label': strings.wait,
353
- transform: waitTransform});
354
- const title = element('title');
355
- title.textContent = strings.wait;
356
- badge.append(title, element('rect', {x: '-10', y: '-10', width: '20', height: '20', rx: '4'}),
357
- element('path', {class: 'tw-script-relation-wait-glyph', d: relationWaitGlyph, transform: 'translate(-8 -8)'}));
358
- group.append(badge);
359
- }
360
328
  if (count > 1) {
361
329
  const badge = element('text', {x: String(badgePoint.x), y: String(badgePoint.y),
362
- class: 'tw-script-relation-badge', 'text-anchor': waiting ? 'start' : 'middle'});
330
+ class: 'tw-script-relation-badge', 'text-anchor': 'middle'});
363
331
  badge.textContent = `×${count}`;
364
332
  group.append(badge);
365
333
  }
@@ -414,7 +382,6 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
414
382
  };
415
383
  set(group.querySelector('.tw-script-relation-line'), 'd', shape.path);
416
384
  set(group.querySelector('.tw-script-relation-head'), 'd', shape.head);
417
- if (shape.waitTransform) set(group.querySelector('.tw-script-relation-wait'), 'transform', shape.waitTransform);
418
385
  const count = group.querySelector('.tw-script-relation-badge');
419
386
  set(count, 'x', shape.badgePoint.x); set(count, 'y', shape.badgePoint.y);
420
387
  }
@@ -482,7 +449,7 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
482
449
  const destination = scripts.get(drawing.relation.destination.scriptId);
483
450
  if (!destination) continue;
484
451
  drawing.serialRoute = {right: rightEdge + (96 + lane * 16) * unit,
485
- top: destination.y - (14 + lane % 4 * 6) * unit, clearance: 8 * unit};
452
+ top: destination.y - (14 + lane % 4 * 6) * unit, clearance: 8 * unit, radius: 48 * unit};
486
453
  lane++;
487
454
  }
488
455
  // Reserve actual scrollable SVG width for the right-hand routes while preserving the block scale.
@@ -535,7 +502,7 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
535
502
  vm?.runtime?.targets?.find(item => item.id === endpoint.targetId)?.getName?.());
536
503
  const reason = relation.unresolved && strings[relation.unresolved];
537
504
  external.textContent = `${name ? `${name} · ` : ''}` +
538
- `${relation.label}${reason ? ` · ${reason}` : ''}${relation.kind === 'message' && relation.wait ? ' ⏳' : ''}${count > 1 ? ` ×${count}` : ''}`;
505
+ `${relation.label}${reason ? ` · ${reason}` : ''}${count > 1 ? ` ×${count}` : ''}`;
539
506
  external.disabled = !endpoint;
540
507
  external.setAttribute('aria-label', `${strings[relation.kind]}: ${external.textContent}`);
541
508
  external.toggleAttribute('data-highlighted', Boolean(highlighted));
@@ -7,6 +7,7 @@ import {attachScriptArrows, type ScriptRelationContext, type ScriptRelationVisib
7
7
  import {attachCodeZoomRange} from './code-zoom.ts';
8
8
  import {setScriptProjection} from './script-projection.ts';
9
9
  import {openSerialScriptEditor} from './serial-script-editor.ts';
10
+ import {openSemanticLayout, type SemanticLayoutContext} from './semantic-layout-dialog.ts';
10
11
  import {isFoldedDefinition, setFoldedDefinition} from './procedure-edits.ts';
11
12
 
12
13
  export type ScriptView = 'free' | 'z' | 'n';
@@ -21,6 +22,7 @@ interface ViewOptions {
21
22
  onChange?(view: ScriptView): void;
22
23
  hasWorkspaceMenu?(): boolean;
23
24
  relations?: ScriptRelationContext;
25
+ semanticLayout?: Pick<SemanticLayoutContext, 'events' | 'canArrange'>;
24
26
  }
25
27
 
26
28
  const choices = [
@@ -31,7 +33,7 @@ const choices = [
31
33
 
32
34
  export function attachScriptView({
33
35
  workspace, ScratchBlocks, getLocale, mount, initialView = 'free', canShowBlock, onChange, hasWorkspaceMenu = () => true,
34
- relations: relationContext
36
+ relations: relationContext, semanticLayout
35
37
  }: ViewOptions) {
36
38
  const injection = workspace.getInjectionDiv();
37
39
  const restoreZoomRange = attachCodeZoomRange(workspace);
@@ -51,6 +53,7 @@ export function attachScriptView({
51
53
  const foldButtons = new Map<string, {button: HTMLButtonElement; top: number}>();
52
54
  let view = initialView;
53
55
  let editor: ReturnType<typeof openSerialScriptEditor>;
56
+ let semanticDialog: ReturnType<typeof openSemanticLayout> | undefined;
54
57
  let frame: number | undefined;
55
58
  const svg = workspace.getParentSvg();
56
59
  const observer = new window.MutationObserver(records => {
@@ -134,7 +137,16 @@ export function attachScriptView({
134
137
  const ja = japanese();
135
138
  return {
136
139
  label: ja ? 'コードの並びの見え方を変更する' : 'Change code layout view',
137
- options: foldOptions(),
140
+ options: [...foldOptions(), ...(view === 'free' && semanticLayout && relationContext ? [{
141
+ text: ja ? 'スクリプトを意味に応じて再配置する' : 'Rearrange scripts by relationships',
142
+ enabled: semanticLayout.canArrange(),
143
+ callback() {
144
+ if (view !== 'free' || !semanticLayout.canArrange()) return;
145
+ semanticDialog?.close();
146
+ semanticDialog = openSemanticLayout({workspace, relations: relationContext, ...semanticLayout,
147
+ canArrange: () => view === 'free' && semanticLayout.canArrange()}, getLocale());
148
+ }
149
+ }] : [])],
138
150
  choices: choices.map(choice => ({
139
151
  text: ja ? choice.jaLabel : choice.label,
140
152
  enabled: true,
@@ -165,7 +177,8 @@ export function attachScriptView({
165
177
  width: box.width, height: box.height};
166
178
  });
167
179
  const placements = arrangeScripts(scripts, view, 'vertical', Math.max(64, 48 / scale))
168
- .map(placement => ({...placement, x: Math.max(placement.x, 32 / scale)}));
180
+ // Leave room for incoming arrowheads and return paths beside the fixed fold gutter.
181
+ .map(placement => ({...placement, x: placement.x + 40 / scale}));
169
182
  paintScripts(contents, placements, scale);
170
183
  paintFoldButtons(placements, scale);
171
184
  const projection = contents.querySelector('svg');
@@ -245,6 +258,7 @@ export function attachScriptView({
245
258
  get view() { return view; },
246
259
  setView,
247
260
  dispose() {
261
+ semanticDialog?.close();
248
262
  editor?.dispose();
249
263
  setScriptProjection(workspace);
250
264
  restoreZoomRange();
@@ -306,7 +320,8 @@ export function attachDockedScriptLayout({vm, workspace, ScratchBlocks, canUse,
306
320
  (!group || group.classList.contains('dv-active-group')));
307
321
  };
308
322
  const view = attachScriptView({workspace, ScratchBlocks, getLocale: () => injection.ownerDocument.documentElement.lang || locale,
309
- canShowBlock: canArrange, relations: {vm: vm as ScriptRelationContext['vm'],
323
+ canShowBlock: canArrange, semanticLayout: {events: ScratchBlocks.Events, canArrange},
324
+ relations: {vm: vm as ScriptRelationContext['vm'],
310
325
  getTarget: () => vm.editingTarget as ReturnType<ScriptRelationContext['getTarget']>,
311
326
  initialVisibility: getDockedRelationVisibility(vm)}});
312
327
  host.setAttribute('data-code-hover-surface', '');