@kubohiroya/turbowarp-plus-editor-code-views 0.22.1 → 0.23.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.
package/README.ja.md CHANGED
@@ -16,6 +16,18 @@ Z/N配置内の矢印は、スクリプト群の右外側へ96px以上張り
16
16
 
17
17
  これらの変更の切り戻しは、本変更を revert して再ビルドする。ホストのパッケージ固定を以前の版へ戻す場合は、機能移管で追加された API との互換性も確認する。自由配置へ切り替えるだけでも元の配置を表示できる。折りたたみは既存の作品内フラグを使用するため、「折りたたみをすべて解除」で解除できる。
18
18
 
19
+ ## 関係に基づく再配置(Editor #727)
20
+
21
+ 自由配置の背景を右クリックし「スクリプトを意味に応じて再配置する」を選ぶと、現在のスプライト/ステージの再配置をプレビューする。「再配置する」で確定し、取消では作品を変更しない。Undo/Redo各1回で座標と付属コメントを戻せる。別窓では編集権を持つ画面だけで実行でき、他スプライトの座標は動かさない。
22
+
23
+ 既存の静的関係解析を再利用し、再帰・循環を強連結成分へまとめたDAGの最長経路で列を割り当て、重心法による4回の走査で列内の交差を減らす。関係のない群は別の帯に置く。今回必要な列・循環・群の制約を小さな純粋計算として検証できるため、ELKの追加導入は行わない。名前付き関数を含む関数呼び出し、通常の送信と送って待つを扱い、動的・未解決の名前には接続先を推測しない。外部接続と未解決の関係はプレビューで区別する。静的関係は実行順序を保証しない。
24
+
25
+ Matter.js 0.20.0(MIT)で、重力と回転を無効にしたコメント込みの矩形を目標位置へ引き寄せる。固定ステップとID順を使い、120ステップまたは速度の収束で終了する。8ステップごとにイベントループへ処理を戻し、取消や画面破棄で中止する。その後、列と順序を保つ決定的な間隔調整を行い、独立コメントとの衝突とスクリプト同士の重なりを検査する。上限は1000スクリプト・10000関係・1000独立コメント。上限超過や測定失敗では適用せず、元の配置を保つ。プレビュー中の対象・内容・座標・コメントの変更は確定を拒否し、「再計算する」で作り直せる。
26
+
27
+ メニュー・プレビュー・移動処理は本パッケージが所有する。ホストは従来の `attachDockedScriptLayout` の接続を使用し、新しいGUI差分や起動フラグは不要。独自の編集可能ワークスペースで `attachScriptView` を使う場合は、`semanticLayout: {events, canArrange}` と `relations` を渡す。読み取り専用画面では渡さない。
28
+
29
+ 限定検証: `npm run build`、`node --test test/semantic-script-layout.test.ts test/script-relations.test.ts`、`node --test test/semantic-layout.browser.ts`。ブラウザー検証はヘッドレスで行う。配布を切り戻す場合は本変更とホストの依存固定を導入前へ戻す。保存形式・専用メタデータの追加はなく、保存済みの座標は通常の作品データとして残る。
30
+
19
31
  ## 入口
20
32
 
21
33
  | import | 内容 |
package/README.md CHANGED
@@ -10,6 +10,16 @@ Opening a function or hat adjusts the zoom to its rendered script and places the
10
10
 
11
11
  Hosts with a separate workspace can call `fitScriptInWorkspace(workspace, scriptId, ScratchBlocks)` from the root or `./sprite-code-windows` export. It returns `false` if the viewport or block is not ready, so the host can retry after layout.
12
12
 
13
+ ## Rearranging scripts by relationships (Editor #727)
14
+
15
+ Right-click a free-layout background and choose **Rearrange scripts by relationships**. Preview the current sprite or stage, then confirm or cancel. One Undo/Redo restores the positions and attached comments. Other targets stay fixed. Editable popouts use their existing edit lease; read-only and serial views cannot run this operation.
16
+
17
+ The existing static relationship extractor supplies function calls, named functions and messages. An iterative SCC pass groups cycles; longest-path ranks and four barycentric sweeps arrange the resulting DAG. Disconnected components occupy separate bands. These bounded, testable rank constraints do not require an additional ELK dependency. Matter.js 0.20.0 (MIT) relaxes comment-inclusive rectangles with gravity and rotation disabled. Fixed steps and canonical ID order make repeated layouts stable. Simulation yields every eight steps and stops on convergence or after 120 steps. Deterministic packing and final collision checks preserve ranks and avoid loose comments. Limits are 1000 scripts, 10000 relations and 1000 loose comments; unsupported input leaves the project unchanged.
18
+
19
+ External and unresolved links are identified in the preview. Dynamic names do not acquire invented destinations; static relationships do not guarantee execution order. Program, target or geometry changes invalidate the preview. Recalculate before applying. Native block moves own attached-comment undo; comment notifications still reach the VM and popout protocol. Failed queued moves are rolled back before dispatch.
20
+
21
+ Existing `attachDockedScriptLayout` integration enables the menu without GUI changes. Custom editable `attachScriptView` hosts pass `semanticLayout: {events, canArrange}` alongside `relations`; read-only hosts omit it. Run `npm run build`, the semantic-layout and relationship unit tests, and `node --test test/semantic-layout.browser.ts` for focused headless verification. Roll back the package and host dependency pin together. No project-format migration or new metadata is needed.
22
+
13
23
  ## Entry points
14
24
 
15
25
  | Import | Contents |
@@ -66,6 +66,7 @@ export function startCodePopout({ ScratchBlocks, PopupLayout, attachWorkspaceNav
66
66
  let edits = [];
67
67
  const scriptView = attachScriptView({ workspace, ScratchBlocks, getLocale: () => locale,
68
68
  mount: workspaceArea, canShowBlock: () => editable && !blockedSnapshot,
69
+ semanticLayout: { events: ScratchBlocks.Events, canArrange: () => editable && !blockedSnapshot && document.hasFocus() && !mount.inert && !workspace.isDragging() },
69
70
  hasWorkspaceMenu: () => !mount.inert,
70
71
  relations: {
71
72
  getTarget: () => targetId ? { id: targetId, blocks: { _blocks: history.blocks } } : undefined,
@@ -164,6 +164,7 @@ export function createHorizontalBlockPalette({ getScratchBlocks, openExtensionLi
164
164
  const capture = { capture: true, signal: events.signal };
165
165
  const original = {
166
166
  dispose: toolbox.dispose,
167
+ setVisible: workspace.setVisible,
167
168
  getClientRect: toolbox.getClientRect,
168
169
  getHeight: toolbox.getHeight,
169
170
  getWidth: toolbox.getWidth,
@@ -183,6 +184,20 @@ export function createHorizontalBlockPalette({ getScratchBlocks, openExtensionLi
183
184
  let scrollBeforeSearch = 0;
184
185
  const scrollPositions = new Map();
185
186
  const verticalPosition = workspace.toolboxPosition;
187
+ // Scratch Blocks shows a workspace by setting its toolbox to display:block, overriding the
188
+ // horizontal palette's flex layout. Let the stylesheet lay it out, then refresh its metrics.
189
+ const restoreHorizontalDisplay = () => {
190
+ if (!horizontal || menu.style.display !== 'block')
191
+ return false;
192
+ menu.style.removeProperty('display');
193
+ return true;
194
+ };
195
+ const setVisible = workspace.setVisible = function (...args) {
196
+ const result = original.setVisible.apply(this, args);
197
+ if (restoreHorizontalDisplay())
198
+ workspace.resize();
199
+ return result;
200
+ };
186
201
  const categoryById = id => toolbox.categoryMenu_.categories_.find(category => category.id_ === id);
187
202
  const getLocale = () => ScratchBlocks.ScratchMsgs.currentLocale_ || doc.documentElement.lang;
188
203
  // A category nested in another opens from its group's child palette.
@@ -581,6 +596,7 @@ export function createHorizontalBlockPalette({ getScratchBlocks, openExtensionLi
581
596
  workspace.toolboxPosition = horizontal ? ScratchBlocks.TOOLBOX_AT_TOP : verticalPosition;
582
597
  menu.classList.toggle(styles.horizontal, horizontal);
583
598
  menu.toggleAttribute('data-horizontal-block-palette', horizontal);
599
+ restoreHorizontalDisplay();
584
600
  panel.classList.toggle(styles.panel, horizontal);
585
601
  scrollbar.classList.toggle(styles.scrollbar, horizontal);
586
602
  if (horizontal)
@@ -723,6 +739,8 @@ export function createHorizontalBlockPalette({ getScratchBlocks, openExtensionLi
723
739
  }
724
740
  });
725
741
  toolbox.dispose = () => {
742
+ if (workspace.setVisible === setVisible)
743
+ workspace.setVisible = original.setVisible;
726
744
  paletteRefreshers.delete(redraw);
727
745
  newSpritePrompts.splice(newSpritePrompts.indexOf(askNewSprite) >>> 0, 1);
728
746
  paletteMenu.dispose();
@@ -3,6 +3,7 @@ import { type RearrangementContext } from './script-layout-dialog.ts';
3
3
  import { type ScriptViewMenuBlocks, type ScriptViewMenuWorkspace } from './script-view-menu.ts';
4
4
  import type { PresentationElements } from './preview-chrome.ts';
5
5
  import { type ScriptRelationContext, type ScriptRelationVisibility } from './script-arrows.ts';
6
+ import { type SemanticLayoutContext } from './semantic-layout-dialog.ts';
6
7
  export type ScriptView = 'free' | 'z' | 'n';
7
8
  interface ViewOptions {
8
9
  workspace: LayoutWorkspace & ScriptViewMenuWorkspace;
@@ -14,8 +15,9 @@ interface ViewOptions {
14
15
  onChange?(view: ScriptView): void;
15
16
  hasWorkspaceMenu?(): boolean;
16
17
  relations?: ScriptRelationContext;
18
+ semanticLayout?: Pick<SemanticLayoutContext, 'events' | 'canArrange'>;
17
19
  }
18
- export declare function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, initialView, canShowBlock, onChange, hasWorkspaceMenu, relations: relationContext }: ViewOptions): {
20
+ export declare function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, initialView, canShowBlock, onChange, hasWorkspaceMenu, relations: relationContext, semanticLayout }: ViewOptions): {
19
21
  update: () => void;
20
22
  relations: {
21
23
  update: () => void;
@@ -6,13 +6,14 @@ import { attachScriptArrows } from "./script-arrows.js";
6
6
  import { attachCodeZoomRange } from "./code-zoom.js";
7
7
  import { setScriptProjection } from "./script-projection.js";
8
8
  import { openSerialScriptEditor } from "./serial-script-editor.js";
9
+ import { openSemanticLayout } from "./semantic-layout-dialog.js";
9
10
  import { isFoldedDefinition, setFoldedDefinition } from "./procedure-edits.js";
10
11
  const choices = [
11
12
  { view: 'free', label: 'Normal layout view', jaLabel: '通常配置の見え方' },
12
13
  { view: 'z', label: 'Z layout view', jaLabel: 'Z配置の見え方' },
13
14
  { view: 'n', label: 'N layout view', jaLabel: 'N配置の見え方' }
14
15
  ];
15
- export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, initialView = 'free', canShowBlock, onChange, hasWorkspaceMenu = () => true, relations: relationContext }) {
16
+ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, initialView = 'free', canShowBlock, onChange, hasWorkspaceMenu = () => true, relations: relationContext, semanticLayout }) {
16
17
  const injection = workspace.getInjectionDiv();
17
18
  const restoreZoomRange = attachCodeZoomRange(workspace);
18
19
  const host = mount ?? injection;
@@ -31,6 +32,7 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
31
32
  const foldButtons = new Map();
32
33
  let view = initialView;
33
34
  let editor;
35
+ let semanticDialog;
34
36
  let frame;
35
37
  const svg = workspace.getParentSvg();
36
38
  const observer = new window.MutationObserver(records => {
@@ -115,7 +117,17 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
115
117
  const ja = japanese();
116
118
  return {
117
119
  label: ja ? 'コードの並びの見え方を変更する' : 'Change code layout view',
118
- options: foldOptions(),
120
+ options: [...foldOptions(), ...(view === 'free' && semanticLayout && relationContext ? [{
121
+ text: ja ? 'スクリプトを意味に応じて再配置する' : 'Rearrange scripts by relationships',
122
+ enabled: semanticLayout.canArrange(),
123
+ callback() {
124
+ if (view !== 'free' || !semanticLayout.canArrange())
125
+ return;
126
+ semanticDialog?.close();
127
+ semanticDialog = openSemanticLayout({ workspace, relations: relationContext, ...semanticLayout,
128
+ canArrange: () => view === 'free' && semanticLayout.canArrange() }, getLocale());
129
+ }
130
+ }] : [])],
119
131
  choices: choices.map(choice => ({
120
132
  text: ja ? choice.jaLabel : choice.label,
121
133
  enabled: true,
@@ -230,6 +242,7 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
230
242
  get view() { return view; },
231
243
  setView,
232
244
  dispose() {
245
+ semanticDialog?.close();
233
246
  editor?.dispose();
234
247
  setScriptProjection(workspace);
235
248
  restoreZoomRange();
@@ -275,7 +288,8 @@ export function attachDockedScriptLayout({ vm, workspace, ScratchBlocks, canUse,
275
288
  (!group || group.classList.contains('dv-active-group')));
276
289
  };
277
290
  const view = attachScriptView({ workspace, ScratchBlocks, getLocale: () => injection.ownerDocument.documentElement.lang || locale,
278
- canShowBlock: canArrange, relations: { vm: vm,
291
+ canShowBlock: canArrange, semanticLayout: { events: ScratchBlocks.Events, canArrange },
292
+ relations: { vm: vm,
279
293
  getTarget: () => vm.editingTarget,
280
294
  initialVisibility: getDockedRelationVisibility(vm) } });
281
295
  host.setAttribute('data-code-hover-surface', '');
@@ -0,0 +1,12 @@
1
+ import { type LayoutEvents } from './script-layout-workspace.ts';
2
+ import type { ScriptRelationContext } from './script-arrows.ts';
3
+ import { type SemanticWorkspace } from './semantic-layout-workspace.ts';
4
+ export interface SemanticLayoutContext {
5
+ workspace: SemanticWorkspace;
6
+ events: LayoutEvents;
7
+ relations: ScriptRelationContext;
8
+ canArrange(): boolean;
9
+ }
10
+ export declare function openSemanticLayout(context: SemanticLayoutContext, locale: string): {
11
+ close: () => void;
12
+ };
@@ -0,0 +1,251 @@
1
+ import { paintScripts } from "./script-layout-workspace.js";
2
+ import { readScriptRelations } from "./script-relations.js";
3
+ import { arrangeSemanticScripts } from "./semantic-script-layout.js";
4
+ import { applySemanticLayout, readSemanticWorkspace } from "./semantic-layout-workspace.js";
5
+ const ns = 'http://www.w3.org/2000/svg';
6
+ export function openSemanticLayout(context, locale) {
7
+ const { workspace, events, relations, canArrange } = context;
8
+ const document = workspace.getInjectionDiv().ownerDocument;
9
+ const window = document.defaultView;
10
+ const ja = /^ja(?:-|$)/i.test(locale);
11
+ const t = (en, japanese) => ja ? japanese : en;
12
+ const dialog = document.createElement('dialog');
13
+ dialog.className = 'tw-script-layout-dialog';
14
+ dialog.setAttribute('aria-label', t('Rearrange scripts by relationships', 'スクリプトを意味に応じて再配置する'));
15
+ const title = document.createElement('h2');
16
+ title.textContent = dialog.getAttribute('aria-label');
17
+ const explanation = document.createElement('p');
18
+ explanation.textContent = t('Read static calls and messages from left to right. This does not guarantee execution order.', '関数の呼び出しとメッセージ送受信を左から右にたどる配置です。実行順序を保証するものではありません。');
19
+ const preview = document.createElement('div');
20
+ preview.className = 'tw-script-layout-preview';
21
+ preview.tabIndex = 0;
22
+ preview.setAttribute('aria-label', t('Layout preview', '再配置のプレビュー'));
23
+ const footer = document.createElement('footer');
24
+ footer.className = 'tw-plus-dialog-actions';
25
+ const status = document.createElement('p');
26
+ status.setAttribute('role', 'status');
27
+ const cancel = document.createElement('button');
28
+ cancel.textContent = t('Cancel', 'キャンセル');
29
+ cancel.dataset.dialogAction = 'cancel';
30
+ const apply = document.createElement('button');
31
+ apply.textContent = t('Rearrange', '再配置する');
32
+ apply.dataset.dialogAction = 'confirm';
33
+ apply.disabled = true;
34
+ const recalculate = document.createElement('button');
35
+ recalculate.textContent = t('Recalculate', '再計算する');
36
+ footer.append(status, recalculate, cancel, apply);
37
+ dialog.append(title, explanation, preview, footer);
38
+ document.body.append(dialog);
39
+ let closed = false;
40
+ let run;
41
+ let snapshot;
42
+ let placements = [];
43
+ let signature = '';
44
+ let originalTarget;
45
+ function graph() {
46
+ return relations.getRelations?.() ?? readScriptRelations(relations.vm?.runtime?.targets ??
47
+ (relations.getTarget() ? [relations.getTarget()] : []));
48
+ }
49
+ function revision() {
50
+ // Include program contents and external targets: unchanged bounds do not imply unchanged calls.
51
+ const targets = relations.vm?.runtime?.targets ?? [relations.getTarget()];
52
+ const geometry = readSemanticWorkspace(workspace);
53
+ return JSON.stringify({ targets: targets.filter(t => t && t.isOriginal !== false).map(t => [t.id, t.blocks._blocks]),
54
+ graph: relations.getRelations?.(), scripts: geometry.scripts.map(s => [s.id, s.x, s.y, s.width, s.height]),
55
+ comments: geometry.comments.map(c => [c.id, c.rootId, c.x, c.y, c.width, c.height, c.origin, c.text]) });
56
+ }
57
+ function stale() {
58
+ try {
59
+ const current = readSemanticWorkspace(workspace).scripts;
60
+ return !canArrange() || relations.getTarget()?.id !== originalTarget?.id || revision() !== signature ||
61
+ current.length !== snapshot.scripts.length || current.some(s => snapshot.scripts.find(original => original.id === s.id)?.block !== s.block);
62
+ }
63
+ catch {
64
+ return true;
65
+ }
66
+ }
67
+ function close() {
68
+ if (closed)
69
+ return;
70
+ closed = true;
71
+ run?.abort();
72
+ for (const [emitter, name] of subscriptions)
73
+ emitter?.removeListener?.(name, invalidate);
74
+ if (dialog.open)
75
+ dialog.close();
76
+ dialog.remove();
77
+ }
78
+ function invalidate() {
79
+ if (closed || !snapshot || !stale())
80
+ return;
81
+ run?.abort();
82
+ apply.disabled = true;
83
+ recalculate.disabled = false;
84
+ status.textContent = t('The code changed. Recalculate the preview.', 'コードが変わりました。プレビューを再計算してください。');
85
+ }
86
+ const subscriptions = [
87
+ [relations.vm, 'workspaceUpdate'], [relations.vm, 'targetsUpdate'], [relations.vm?.runtime, 'PROJECT_CHANGED']
88
+ ];
89
+ for (const [emitter, name] of subscriptions)
90
+ emitter?.on?.(name, invalidate);
91
+ async function calculate() {
92
+ run?.abort();
93
+ const task = new window.AbortController();
94
+ run = task;
95
+ apply.disabled = true;
96
+ recalculate.disabled = true;
97
+ preview.replaceChildren();
98
+ status.textContent = t('Calculating layout…', '配置を計算しています…');
99
+ try {
100
+ events.fireNow_();
101
+ if (!canArrange())
102
+ throw new Error('Workspace is unavailable');
103
+ originalTarget = relations.getTarget();
104
+ if (!originalTarget)
105
+ throw new Error('No target');
106
+ snapshot = readSemanticWorkspace(workspace);
107
+ signature = revision();
108
+ const edges = graph();
109
+ const started = window.performance.now();
110
+ const result = await arrangeSemanticScripts(snapshot.scripts, edges, originalTarget.id, {
111
+ signal: task.signal, obstacles: snapshot.obstacles,
112
+ yieldControl: () => new Promise(resolve => window.setTimeout(resolve, 0))
113
+ });
114
+ if (closed || run !== task || task.signal.aborted)
115
+ return;
116
+ if (stale()) {
117
+ invalidate();
118
+ return;
119
+ }
120
+ placements = result.placements;
121
+ paintPreview(edges);
122
+ const external = edges.filter(e => e.destination && e.source.targetId !== e.destination.targetId &&
123
+ [e.source.targetId, e.destination.targetId].includes(originalTarget.id)).length;
124
+ const unresolved = edges.filter(e => e.source.targetId === originalTarget.id && e.unresolved).length;
125
+ status.textContent = t(`${placements.length} scripts · ${result.metrics.edges} links · ${external} external · ${unresolved} unresolved`, `${placements.length}スクリプト・${result.metrics.edges}接続・外部${external}・未解決${unresolved}`);
126
+ preview.dataset.layoutMetrics = JSON.stringify({ ...result.metrics, milliseconds: window.performance.now() - started,
127
+ overlaps: 0, external, unresolved });
128
+ apply.disabled = !placements.some(p => p.x !== p.script.x || p.y !== p.script.y);
129
+ }
130
+ catch (error) {
131
+ if (closed || run !== task || task.signal.aborted)
132
+ return;
133
+ status.textContent = t('Unable to calculate a safe layout. The project has not changed.', '安全な配置を計算できませんでした。作品は変更されていません。');
134
+ status.title = String(error);
135
+ }
136
+ finally {
137
+ if (!closed && run === task)
138
+ recalculate.disabled = false;
139
+ }
140
+ }
141
+ function paintPreview(edges) {
142
+ paintScripts(preview, placements, .6);
143
+ const svg = preview.querySelector('svg');
144
+ const local = new Map(placements.map(p => [p.script.id, p]));
145
+ // Include loose comments and the complete cluster extents, even beyond the visible folded body.
146
+ for (const c of snapshot.comments) {
147
+ const p = local.get(c.rootId);
148
+ const x = c.x + (p ? p.x - p.script.x : 0), y = c.y + (p ? p.y - p.script.y : 0);
149
+ const rect = document.createElementNS(ns, 'rect');
150
+ for (const [key, value] of Object.entries({ x, y, width: c.width, height: c.height, fill: '#fff2ae', stroke: '#9b8524' })) {
151
+ rect.setAttribute(key, String(value));
152
+ }
153
+ const text = document.createElementNS(ns, 'title');
154
+ text.textContent = t('Comment', 'コメント');
155
+ rect.append(text);
156
+ svg.append(rect);
157
+ const content = document.createElementNS(ns, 'foreignObject');
158
+ for (const [key, value] of Object.entries({ x: x + 8, y: y + 8,
159
+ width: Math.max(0, c.width - 16), height: Math.max(0, c.height - 16) }))
160
+ content.setAttribute(key, String(value));
161
+ const prose = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
162
+ prose.style.cssText = 'height:100%;overflow:hidden;white-space:pre-wrap;color:#332f20;font:14px sans-serif';
163
+ prose.textContent = c.text;
164
+ content.append(prose);
165
+ svg.append(content);
166
+ }
167
+ const layer = document.createElementNS(ns, 'g');
168
+ layer.setAttribute('data-semantic-relations', '');
169
+ for (const edge of edges) {
170
+ const source = edge.source.targetId === originalTarget.id ? local.get(edge.source.scriptId) : undefined;
171
+ const destination = edge.destination?.targetId === originalTarget.id ? local.get(edge.destination.scriptId) : undefined;
172
+ if (!source && !destination)
173
+ continue;
174
+ const p = source ?? destination;
175
+ const end = destination ?? source;
176
+ const from = { x: p.x + (source ? p.script.width : -40), y: p.y + p.script.height / 2 };
177
+ const to = { x: destination ? end.x : end.x + end.script.width + 40, y: end.y + end.script.height / 2 };
178
+ const group = document.createElementNS(ns, 'g');
179
+ group.dataset.semanticRelation = edge.kind;
180
+ group.dataset.wait = String(edge.wait);
181
+ if (edge.unresolved)
182
+ group.dataset.unresolved = edge.unresolved;
183
+ else if (!source || !destination)
184
+ group.dataset.external = 'true';
185
+ const line = document.createElementNS(ns, 'path');
186
+ const middle = Math.max(from.x + 32, (from.x + to.x) / 2);
187
+ line.setAttribute('d', `M ${from.x} ${from.y} C ${middle} ${from.y} ${middle} ${to.y} ${to.x} ${to.y}`);
188
+ line.setAttribute('fill', 'none');
189
+ line.setAttribute('stroke', edge.kind === 'function' ? '#b65be6' : '#ba8a00');
190
+ line.setAttribute('stroke-width', '2');
191
+ if (edge.kind === 'message')
192
+ line.setAttribute('stroke-dasharray', edge.wait ? '7 5' : '3.5 2.5');
193
+ const head = document.createElementNS(ns, 'path');
194
+ head.setAttribute('d', `M ${to.x - 7} ${to.y - 4} L ${to.x} ${to.y} L ${to.x - 7} ${to.y + 4}`);
195
+ head.setAttribute('fill', 'none');
196
+ head.setAttribute('stroke', line.getAttribute('stroke'));
197
+ const label = document.createElementNS(ns, 'title');
198
+ label.textContent = `${edge.label} ${edge.unresolved ? t('(unresolved)', '(未解決)') :
199
+ !source || !destination ? t('(external)', '(外部)') : ''}`;
200
+ group.append(line, head, label);
201
+ layer.append(group);
202
+ if (edge.unresolved || !source || !destination) {
203
+ const text = document.createElementNS(ns, 'text');
204
+ text.setAttribute('x', String(to.x + 8));
205
+ text.setAttribute('y', String(to.y));
206
+ text.setAttribute('fill', 'currentColor');
207
+ text.setAttribute('font-size', '14');
208
+ const externalId = source ? edge.destination?.targetId : edge.source.targetId;
209
+ text.textContent = edge.unresolved ? `${edge.label || '?'} ${t('(unresolved)', '(未解決)')}` :
210
+ `${edge.label} ↗ ${relations.getTargetName?.(externalId) ??
211
+ relations.vm?.runtime?.targets?.find(target => target.id === externalId)?.getName?.() ?? t('external', '外部')}`;
212
+ group.append(text);
213
+ }
214
+ }
215
+ svg.prepend(layer);
216
+ const box = svg.getBBox();
217
+ const left = Math.min(0, box.x) - 16, top = Math.min(0, box.y) - 16;
218
+ const width = box.x + box.width - left + 32, height = box.y + box.height - top + 32;
219
+ svg.setAttribute('viewBox', `${left} ${top} ${width} ${height}`);
220
+ svg.setAttribute('width', String(width * .6));
221
+ svg.setAttribute('height', String(height * .6));
222
+ }
223
+ cancel.addEventListener('click', close);
224
+ dialog.addEventListener('close', close, { once: true });
225
+ dialog.addEventListener('cancel', close, { once: true });
226
+ dialog.addEventListener('keydown', e => e.stopPropagation());
227
+ recalculate.addEventListener('click', () => void calculate());
228
+ apply.addEventListener('click', () => {
229
+ events.fireNow_();
230
+ if (stale()) {
231
+ invalidate();
232
+ return;
233
+ }
234
+ try {
235
+ applySemanticLayout(workspace, events, placements, snapshot.comments);
236
+ }
237
+ catch (error) {
238
+ apply.disabled = true;
239
+ status.textContent = t('Unable to apply the layout. Original positions were restored.', '配置を適用できませんでした。元の位置に戻しました。');
240
+ status.title = String(error);
241
+ return;
242
+ }
243
+ close();
244
+ if (placements.length)
245
+ workspace.centerOnBlock(placements[0].script.id);
246
+ });
247
+ dialog.showModal();
248
+ cancel.focus();
249
+ void calculate();
250
+ return { close };
251
+ }
@@ -0,0 +1,57 @@
1
+ import { type LayoutBlock, type LayoutEvents, type LayoutWorkspace, type RenderedScript } from './script-layout-workspace.ts';
2
+ import type { ScriptBounds } from './script-layout.ts';
3
+ import type { SemanticPlacement } from './semantic-script-layout.ts';
4
+ type Point = {
5
+ x: number;
6
+ y: number;
7
+ };
8
+ export interface LayoutComment {
9
+ id: string;
10
+ block_?: LayoutBlock & {
11
+ getRootBlock(): LayoutBlock;
12
+ };
13
+ getXY?(): Point;
14
+ getRelativeToSurfaceXY?(): Point;
15
+ getBoundingRectangle(): {
16
+ topLeft: Point;
17
+ bottomRight: Point;
18
+ };
19
+ moveTo?(x: number, y: number): void;
20
+ getText?(): string;
21
+ getSvgRoot?(): SVGElement;
22
+ bubble_?: {
23
+ bubbleGroup_?: SVGElement;
24
+ };
25
+ }
26
+ export type SemanticWorkspace = LayoutWorkspace & {
27
+ getTopComments?(ordered: boolean): LayoutComment[];
28
+ };
29
+ export type SemanticEvents = LayoutEvents & {
30
+ FIRE_QUEUE_?: {
31
+ type?: string;
32
+ commentId?: string;
33
+ recordUndo?: boolean;
34
+ }[];
35
+ disable?(): void;
36
+ enable?(): void;
37
+ };
38
+ export interface CommentSnapshot extends ScriptBounds {
39
+ comment: LayoutComment;
40
+ rootId?: string;
41
+ origin: Point;
42
+ text: string;
43
+ svg?: SVGElement;
44
+ }
45
+ export interface SemanticScript extends RenderedScript {
46
+ /** Full script rectangle before attached comments are included. */
47
+ bounds: ScriptBounds;
48
+ }
49
+ /** Read expanded bounds without changing the user's folding or moving any comments. */
50
+ export declare function readSemanticWorkspace(workspace: SemanticWorkspace): {
51
+ scripts: SemanticScript[];
52
+ comments: CommentSnapshot[];
53
+ obstacles: CommentSnapshot[];
54
+ };
55
+ /** Roll back queued native moves before any of them reach the VM or the undo stacks. */
56
+ export declare function applySemanticLayout(workspace: SemanticWorkspace, events: SemanticEvents, placements: SemanticPlacement<SemanticScript>[], comments: CommentSnapshot[]): void;
57
+ export {};
@@ -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
+ }>;