@kubohiroya/turbowarp-plus-editor-code-views 0.22.1 → 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.
- package/README.ja.md +12 -0
- package/README.md +10 -0
- package/dist/code-popout.js +1 -0
- package/dist/horizontal-block-palette.js +18 -0
- package/dist/script-layout-view.d.ts +3 -1
- package/dist/script-layout-view.js +17 -3
- package/dist/semantic-layout-dialog.d.ts +12 -0
- package/dist/semantic-layout-dialog.js +251 -0
- package/dist/semantic-layout-workspace.d.ts +57 -0
- package/dist/semantic-layout-workspace.js +87 -0
- package/dist/semantic-script-layout.d.ts +34 -0
- package/dist/semantic-script-layout.js +271 -0
- package/package.json +4 -2
- package/src/code-popout.tsx +2 -0
- package/src/horizontal-block-palette.ts +15 -0
- package/src/script-layout-view.ts +17 -3
- package/src/semantic-layout-dialog.ts +222 -0
- package/src/semantic-layout-workspace.ts +109 -0
- package/src/semantic-script-layout.ts +254 -0
|
@@ -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.
|
|
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",
|
package/src/code-popout.tsx
CHANGED
|
@@ -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();
|
|
@@ -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,
|
|
@@ -246,6 +258,7 @@ export function attachScriptView({
|
|
|
246
258
|
get view() { return view; },
|
|
247
259
|
setView,
|
|
248
260
|
dispose() {
|
|
261
|
+
semanticDialog?.close();
|
|
249
262
|
editor?.dispose();
|
|
250
263
|
setScriptProjection(workspace);
|
|
251
264
|
restoreZoomRange();
|
|
@@ -307,7 +320,8 @@ export function attachDockedScriptLayout({vm, workspace, ScratchBlocks, canUse,
|
|
|
307
320
|
(!group || group.classList.contains('dv-active-group')));
|
|
308
321
|
};
|
|
309
322
|
const view = attachScriptView({workspace, ScratchBlocks, getLocale: () => injection.ownerDocument.documentElement.lang || locale,
|
|
310
|
-
canShowBlock: canArrange,
|
|
323
|
+
canShowBlock: canArrange, semanticLayout: {events: ScratchBlocks.Events, canArrange},
|
|
324
|
+
relations: {vm: vm as ScriptRelationContext['vm'],
|
|
311
325
|
getTarget: () => vm.editingTarget as ReturnType<ScriptRelationContext['getTarget']>,
|
|
312
326
|
initialVisibility: getDockedRelationVisibility(vm)}});
|
|
313
327
|
host.setAttribute('data-code-hover-surface', '');
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import {paintScripts, type LayoutEvents} from './script-layout-workspace.ts';
|
|
2
|
+
import {readScriptRelations, type ScriptRelation} from './script-relations.ts';
|
|
3
|
+
import type {ScriptRelationContext} from './script-arrows.ts';
|
|
4
|
+
import {arrangeSemanticScripts, type SemanticPlacement} from './semantic-script-layout.ts';
|
|
5
|
+
import {applySemanticLayout, readSemanticWorkspace, type SemanticScript, type SemanticWorkspace} from './semantic-layout-workspace.ts';
|
|
6
|
+
|
|
7
|
+
const ns = 'http://www.w3.org/2000/svg';
|
|
8
|
+
export interface SemanticLayoutContext {
|
|
9
|
+
workspace: SemanticWorkspace;
|
|
10
|
+
events: LayoutEvents;
|
|
11
|
+
relations: ScriptRelationContext;
|
|
12
|
+
canArrange(): boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function openSemanticLayout(context: SemanticLayoutContext, locale: string) {
|
|
16
|
+
const {workspace, events, relations, canArrange} = context;
|
|
17
|
+
const document = workspace.getInjectionDiv().ownerDocument;
|
|
18
|
+
const window = document.defaultView!;
|
|
19
|
+
const ja = /^ja(?:-|$)/i.test(locale);
|
|
20
|
+
const t = (en: string, japanese: string) => ja ? japanese : en;
|
|
21
|
+
const dialog = document.createElement('dialog');
|
|
22
|
+
dialog.className = 'tw-script-layout-dialog';
|
|
23
|
+
dialog.setAttribute('aria-label', t('Rearrange scripts by relationships', 'スクリプトを意味に応じて再配置する'));
|
|
24
|
+
const title = document.createElement('h2');
|
|
25
|
+
title.textContent = dialog.getAttribute('aria-label');
|
|
26
|
+
const explanation = document.createElement('p');
|
|
27
|
+
explanation.textContent = t('Read static calls and messages from left to right. This does not guarantee execution order.',
|
|
28
|
+
'関数の呼び出しとメッセージ送受信を左から右にたどる配置です。実行順序を保証するものではありません。');
|
|
29
|
+
const preview = document.createElement('div');
|
|
30
|
+
preview.className = 'tw-script-layout-preview';
|
|
31
|
+
preview.tabIndex = 0;
|
|
32
|
+
preview.setAttribute('aria-label', t('Layout preview', '再配置のプレビュー'));
|
|
33
|
+
const footer = document.createElement('footer');
|
|
34
|
+
footer.className = 'tw-plus-dialog-actions';
|
|
35
|
+
const status = document.createElement('p');
|
|
36
|
+
status.setAttribute('role', 'status');
|
|
37
|
+
const cancel = document.createElement('button');
|
|
38
|
+
cancel.textContent = t('Cancel', 'キャンセル');
|
|
39
|
+
cancel.dataset.dialogAction = 'cancel';
|
|
40
|
+
const apply = document.createElement('button');
|
|
41
|
+
apply.textContent = t('Rearrange', '再配置する');
|
|
42
|
+
apply.dataset.dialogAction = 'confirm';
|
|
43
|
+
apply.disabled = true;
|
|
44
|
+
const recalculate = document.createElement('button');
|
|
45
|
+
recalculate.textContent = t('Recalculate', '再計算する');
|
|
46
|
+
footer.append(status, recalculate, cancel, apply);
|
|
47
|
+
dialog.append(title, explanation, preview, footer);
|
|
48
|
+
document.body.append(dialog);
|
|
49
|
+
let closed = false;
|
|
50
|
+
let run: AbortController | undefined;
|
|
51
|
+
let snapshot: ReturnType<typeof readSemanticWorkspace>;
|
|
52
|
+
let placements: SemanticPlacement<SemanticScript>[] = [];
|
|
53
|
+
let signature = '';
|
|
54
|
+
let originalTarget: ReturnType<ScriptRelationContext['getTarget']>;
|
|
55
|
+
|
|
56
|
+
function graph() {
|
|
57
|
+
return relations.getRelations?.() ?? readScriptRelations(relations.vm?.runtime?.targets ??
|
|
58
|
+
(relations.getTarget() ? [relations.getTarget()!] : []));
|
|
59
|
+
}
|
|
60
|
+
function revision() {
|
|
61
|
+
// Include program contents and external targets: unchanged bounds do not imply unchanged calls.
|
|
62
|
+
const targets = relations.vm?.runtime?.targets ?? [relations.getTarget()];
|
|
63
|
+
const geometry = readSemanticWorkspace(workspace);
|
|
64
|
+
return JSON.stringify({targets: targets.filter(t => t && t.isOriginal !== false).map(t => [t.id, t.blocks._blocks]),
|
|
65
|
+
graph: relations.getRelations?.(), scripts: geometry.scripts.map(s => [s.id, s.x, s.y, s.width, s.height]),
|
|
66
|
+
comments: geometry.comments.map(c => [c.id, c.rootId, c.x, c.y, c.width, c.height, c.origin, c.text])});
|
|
67
|
+
}
|
|
68
|
+
function stale() {
|
|
69
|
+
try {
|
|
70
|
+
const current = readSemanticWorkspace(workspace).scripts;
|
|
71
|
+
return !canArrange() || relations.getTarget()?.id !== originalTarget?.id || revision() !== signature ||
|
|
72
|
+
current.length !== snapshot.scripts.length || current.some(s =>
|
|
73
|
+
snapshot.scripts.find(original => original.id === s.id)?.block !== s.block);
|
|
74
|
+
} catch {return true;}
|
|
75
|
+
}
|
|
76
|
+
function close() {
|
|
77
|
+
if (closed) return;
|
|
78
|
+
closed = true;
|
|
79
|
+
run?.abort();
|
|
80
|
+
for (const [emitter, name] of subscriptions) emitter?.removeListener?.(name, invalidate);
|
|
81
|
+
if (dialog.open) dialog.close();
|
|
82
|
+
dialog.remove();
|
|
83
|
+
}
|
|
84
|
+
function invalidate() {
|
|
85
|
+
if (closed || !snapshot || !stale()) return;
|
|
86
|
+
run?.abort(); apply.disabled = true; recalculate.disabled = false;
|
|
87
|
+
status.textContent = t('The code changed. Recalculate the preview.', 'コードが変わりました。プレビューを再計算してください。');
|
|
88
|
+
}
|
|
89
|
+
const subscriptions = [
|
|
90
|
+
[relations.vm, 'workspaceUpdate'], [relations.vm, 'targetsUpdate'], [relations.vm?.runtime, 'PROJECT_CHANGED']
|
|
91
|
+
] as const;
|
|
92
|
+
for (const [emitter, name] of subscriptions) emitter?.on?.(name, invalidate);
|
|
93
|
+
|
|
94
|
+
async function calculate() {
|
|
95
|
+
run?.abort();
|
|
96
|
+
const task = new window.AbortController(); run = task;
|
|
97
|
+
apply.disabled = true; recalculate.disabled = true; preview.replaceChildren();
|
|
98
|
+
status.textContent = t('Calculating layout…', '配置を計算しています…');
|
|
99
|
+
try {
|
|
100
|
+
events.fireNow_();
|
|
101
|
+
if (!canArrange()) throw new Error('Workspace is unavailable');
|
|
102
|
+
originalTarget = relations.getTarget();
|
|
103
|
+
if (!originalTarget) throw new Error('No target');
|
|
104
|
+
snapshot = readSemanticWorkspace(workspace);
|
|
105
|
+
signature = revision();
|
|
106
|
+
const edges = graph();
|
|
107
|
+
const started = window.performance.now();
|
|
108
|
+
const result = await arrangeSemanticScripts(snapshot.scripts, edges, originalTarget.id, {
|
|
109
|
+
signal: task.signal, obstacles: snapshot.obstacles,
|
|
110
|
+
yieldControl: () => new Promise(resolve => window.setTimeout(resolve, 0))
|
|
111
|
+
});
|
|
112
|
+
if (closed || run !== task || task.signal.aborted) return;
|
|
113
|
+
if (stale()) {invalidate(); return;}
|
|
114
|
+
placements = result.placements;
|
|
115
|
+
paintPreview(edges);
|
|
116
|
+
const external = edges.filter(e => e.destination && e.source.targetId !== e.destination.targetId &&
|
|
117
|
+
[e.source.targetId, e.destination.targetId].includes(originalTarget.id)).length;
|
|
118
|
+
const unresolved = edges.filter(e => e.source.targetId === originalTarget.id && e.unresolved).length;
|
|
119
|
+
status.textContent = t(`${placements.length} scripts · ${result.metrics.edges} links · ${external} external · ${unresolved} unresolved`,
|
|
120
|
+
`${placements.length}スクリプト・${result.metrics.edges}接続・外部${external}・未解決${unresolved}`);
|
|
121
|
+
preview.dataset.layoutMetrics = JSON.stringify({...result.metrics, milliseconds: window.performance.now() - started,
|
|
122
|
+
overlaps: 0, external, unresolved});
|
|
123
|
+
apply.disabled = !placements.some(p => p.x !== p.script.x || p.y !== p.script.y);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (closed || run !== task || task.signal.aborted) return;
|
|
126
|
+
status.textContent = t('Unable to calculate a safe layout. The project has not changed.',
|
|
127
|
+
'安全な配置を計算できませんでした。作品は変更されていません。');
|
|
128
|
+
status.title = String(error);
|
|
129
|
+
} finally {if (!closed && run === task) recalculate.disabled = false;}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function paintPreview(edges: readonly ScriptRelation[]) {
|
|
133
|
+
paintScripts(preview, placements, .6);
|
|
134
|
+
const svg = preview.querySelector('svg')!;
|
|
135
|
+
const local = new Map(placements.map(p => [p.script.id, p]));
|
|
136
|
+
// Include loose comments and the complete cluster extents, even beyond the visible folded body.
|
|
137
|
+
for (const c of snapshot.comments) {
|
|
138
|
+
const p = local.get(c.rootId);
|
|
139
|
+
const x = c.x + (p ? p.x - p.script.x : 0), y = c.y + (p ? p.y - p.script.y : 0);
|
|
140
|
+
const rect = document.createElementNS(ns, 'rect');
|
|
141
|
+
for (const [key, value] of Object.entries({x, y, width: c.width, height: c.height, fill: '#fff2ae', stroke: '#9b8524'})) {
|
|
142
|
+
rect.setAttribute(key, String(value));
|
|
143
|
+
}
|
|
144
|
+
const text = document.createElementNS(ns, 'title'); text.textContent = t('Comment', 'コメント');
|
|
145
|
+
rect.append(text); svg.append(rect);
|
|
146
|
+
const content = document.createElementNS(ns, 'foreignObject');
|
|
147
|
+
for (const [key, value] of Object.entries({x: x + 8, y: y + 8,
|
|
148
|
+
width: Math.max(0, c.width - 16), height: Math.max(0, c.height - 16)})) content.setAttribute(key, String(value));
|
|
149
|
+
const prose = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
|
|
150
|
+
prose.style.cssText = 'height:100%;overflow:hidden;white-space:pre-wrap;color:#332f20;font:14px sans-serif';
|
|
151
|
+
prose.textContent = c.text; content.append(prose); svg.append(content);
|
|
152
|
+
}
|
|
153
|
+
const layer = document.createElementNS(ns, 'g');
|
|
154
|
+
layer.setAttribute('data-semantic-relations', '');
|
|
155
|
+
for (const edge of edges) {
|
|
156
|
+
const source = edge.source.targetId === originalTarget.id ? local.get(edge.source.scriptId) : undefined;
|
|
157
|
+
const destination = edge.destination?.targetId === originalTarget.id ? local.get(edge.destination.scriptId) : undefined;
|
|
158
|
+
if (!source && !destination) continue;
|
|
159
|
+
const p = source ?? destination;
|
|
160
|
+
const end = destination ?? source;
|
|
161
|
+
const from = {x: p.x + (source ? p.script.width : -40), y: p.y + p.script.height / 2};
|
|
162
|
+
const to = {x: destination ? end.x : end.x + end.script.width + 40, y: end.y + end.script.height / 2};
|
|
163
|
+
const group = document.createElementNS(ns, 'g');
|
|
164
|
+
group.dataset.semanticRelation = edge.kind;
|
|
165
|
+
group.dataset.wait = String(edge.wait);
|
|
166
|
+
if (edge.unresolved) group.dataset.unresolved = edge.unresolved;
|
|
167
|
+
else if (!source || !destination) group.dataset.external = 'true';
|
|
168
|
+
const line = document.createElementNS(ns, 'path');
|
|
169
|
+
const middle = Math.max(from.x + 32, (from.x + to.x) / 2);
|
|
170
|
+
line.setAttribute('d', `M ${from.x} ${from.y} C ${middle} ${from.y} ${middle} ${to.y} ${to.x} ${to.y}`);
|
|
171
|
+
line.setAttribute('fill', 'none'); line.setAttribute('stroke', edge.kind === 'function' ? '#b65be6' : '#ba8a00');
|
|
172
|
+
line.setAttribute('stroke-width', '2');
|
|
173
|
+
if (edge.kind === 'message') line.setAttribute('stroke-dasharray', edge.wait ? '7 5' : '3.5 2.5');
|
|
174
|
+
const head = document.createElementNS(ns, 'path');
|
|
175
|
+
head.setAttribute('d', `M ${to.x - 7} ${to.y - 4} L ${to.x} ${to.y} L ${to.x - 7} ${to.y + 4}`);
|
|
176
|
+
head.setAttribute('fill', 'none'); head.setAttribute('stroke', line.getAttribute('stroke'));
|
|
177
|
+
const label = document.createElementNS(ns, 'title');
|
|
178
|
+
label.textContent = `${edge.label} ${edge.unresolved ? t('(unresolved)', '(未解決)') :
|
|
179
|
+
!source || !destination ? t('(external)', '(外部)') : ''}`;
|
|
180
|
+
group.append(line, head, label); layer.append(group);
|
|
181
|
+
if (edge.unresolved || !source || !destination) {
|
|
182
|
+
const text = document.createElementNS(ns, 'text');
|
|
183
|
+
text.setAttribute('x', String(to.x + 8)); text.setAttribute('y', String(to.y));
|
|
184
|
+
text.setAttribute('fill', 'currentColor'); text.setAttribute('font-size', '14');
|
|
185
|
+
const externalId = source ? edge.destination?.targetId : edge.source.targetId;
|
|
186
|
+
text.textContent = edge.unresolved ? `${edge.label || '?'} ${t('(unresolved)', '(未解決)')}` :
|
|
187
|
+
`${edge.label} ↗ ${relations.getTargetName?.(externalId) ??
|
|
188
|
+
relations.vm?.runtime?.targets?.find(target => target.id === externalId)?.getName?.() ?? t('external', '外部')}`;
|
|
189
|
+
group.append(text);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
svg.prepend(layer);
|
|
193
|
+
const box = svg.getBBox();
|
|
194
|
+
const left = Math.min(0, box.x) - 16, top = Math.min(0, box.y) - 16;
|
|
195
|
+
const width = box.x + box.width - left + 32, height = box.y + box.height - top + 32;
|
|
196
|
+
svg.setAttribute('viewBox', `${left} ${top} ${width} ${height}`);
|
|
197
|
+
svg.setAttribute('width', String(width * .6));
|
|
198
|
+
svg.setAttribute('height', String(height * .6));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
cancel.addEventListener('click', close);
|
|
202
|
+
dialog.addEventListener('close', close, {once: true});
|
|
203
|
+
dialog.addEventListener('cancel', close, {once: true});
|
|
204
|
+
dialog.addEventListener('keydown', e => e.stopPropagation());
|
|
205
|
+
recalculate.addEventListener('click', () => void calculate());
|
|
206
|
+
apply.addEventListener('click', () => {
|
|
207
|
+
events.fireNow_();
|
|
208
|
+
if (stale()) {invalidate(); return;}
|
|
209
|
+
try {applySemanticLayout(workspace, events, placements, snapshot.comments);}
|
|
210
|
+
catch (error) {
|
|
211
|
+
apply.disabled = true;
|
|
212
|
+
status.textContent = t('Unable to apply the layout. Original positions were restored.',
|
|
213
|
+
'配置を適用できませんでした。元の位置に戻しました。');
|
|
214
|
+
status.title = String(error); return;
|
|
215
|
+
}
|
|
216
|
+
close();
|
|
217
|
+
if (placements.length) workspace.centerOnBlock(placements[0].script.id);
|
|
218
|
+
});
|
|
219
|
+
dialog.showModal(); cancel.focus();
|
|
220
|
+
void calculate();
|
|
221
|
+
return {close};
|
|
222
|
+
}
|