@kubohiroya/turbowarp-plus-editor-code-views 0.19.0 → 0.21.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.
@@ -3,6 +3,7 @@ import { paintScripts, readScripts } from "./script-layout-workspace.js";
3
3
  import { openRearrangement } from "./script-layout-dialog.js";
4
4
  import { attachScriptViewMenu } from "./script-view-menu.js";
5
5
  import { attachScriptArrows } from "./script-arrows.js";
6
+ import { attachCodeZoomRange } from "./code-zoom.js";
6
7
  const choices = [
7
8
  { view: 'free', label: 'Normal layout view', jaLabel: '通常配置の見え方' },
8
9
  { view: 'z', label: 'Z layout view', jaLabel: 'Z配置の見え方' },
@@ -10,6 +11,7 @@ const choices = [
10
11
  ];
11
12
  export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, initialView = 'free', canShowBlock, onChange, hasWorkspaceMenu = () => true, relations: relationContext }) {
12
13
  const injection = workspace.getInjectionDiv();
14
+ const restoreZoomRange = attachCodeZoomRange(workspace);
13
15
  const host = mount ?? injection;
14
16
  const document = host.ownerDocument;
15
17
  const window = document.defaultView;
@@ -115,6 +117,7 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
115
117
  get view() { return view; },
116
118
  setView,
117
119
  dispose() {
120
+ restoreZoomRange();
118
121
  resize.disconnect();
119
122
  observer.disconnect();
120
123
  language.disconnect();
@@ -128,6 +131,14 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
128
131
  };
129
132
  }
130
133
  const dockedViews = new WeakMap();
134
+ const relationVisibilities = new WeakMap();
135
+ export function getDockedRelationVisibility(vm) {
136
+ return { ...relationVisibilities.get(vm) ?? { function: true, message: true } };
137
+ }
138
+ export function setDockedRelationVisibility(vm, visibility) {
139
+ relationVisibilities.set(vm, { ...visibility });
140
+ dockedViews.get(vm)?.view.relations?.setVisibility(visibility);
141
+ }
131
142
  export function getDockedScriptLayout(vm) {
132
143
  return dockedViews.get(vm);
133
144
  }
@@ -148,7 +159,8 @@ export function attachDockedScriptLayout({ vm, workspace, ScratchBlocks, canUse,
148
159
  };
149
160
  const view = attachScriptView({ workspace, ScratchBlocks, getLocale: () => injection.ownerDocument.documentElement.lang || locale,
150
161
  canShowBlock: canArrange, relations: { vm: vm,
151
- getTarget: () => vm.editingTarget } });
162
+ getTarget: () => vm.editingTarget,
163
+ initialVisibility: getDockedRelationVisibility(vm) } });
152
164
  host.setAttribute('data-code-hover-surface', '');
153
165
  let dialog;
154
166
  const attachment = {
@@ -1,6 +1,8 @@
1
1
  import React from 'react';
2
2
  import type { createCodePaneAdapter } from './code-pane.ts';
3
3
  export { attachCodeWorkspace } from './workspace.ts';
4
+ export { fitScriptInWorkspace } from './script-fit.ts';
5
+ export { attachWorkspaceOverview } from './workspace-overview.ts';
4
6
  export { attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane, readScriptRelationGraph } from './code-pane.ts';
5
7
  export type { SavedCodePane } from './code-pane.ts';
6
8
  export declare function CodePaneCostumeThumbnail({ adapter }: {
@@ -2,6 +2,8 @@ import React from 'react';
2
2
  import { createPortal } from 'react-dom';
3
3
  import { getCodeSession } from "./workspace.js";
4
4
  export { attachCodeWorkspace } from "./workspace.js";
5
+ export { fitScriptInWorkspace } from "./script-fit.js";
6
+ export { attachWorkspaceOverview } from "./workspace-overview.js";
5
7
  export { attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane, readScriptRelationGraph } from "./code-pane.js";
6
8
  export function CodePaneCostumeThumbnail({ adapter }) {
7
9
  const image = React.useRef(null);
@@ -0,0 +1,16 @@
1
+ type OverviewOptions = {
2
+ workspace: any;
3
+ ScratchBlocks: any;
4
+ zoomHeight?: number;
5
+ getCorner?(metrics: any): {
6
+ right: number;
7
+ bottom: number;
8
+ };
9
+ watermark?: HTMLElement;
10
+ getWatermark?(): HTMLElement | undefined | null;
11
+ };
12
+ /** A cached overview drawn from public block geometry; offscreen culling never changes the project map. */
13
+ export declare function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight, getCorner, watermark, getWatermark }: OverviewOptions): {
14
+ dispose(): void;
15
+ };
16
+ export {};
@@ -0,0 +1,221 @@
1
+ const svgNamespace = 'http://www.w3.org/2000/svg';
2
+ /** A cached overview drawn from public block geometry; offscreen culling never changes the project map. */
3
+ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight = 0, getCorner, watermark, getWatermark }) {
4
+ const container = workspace.getInjectionDiv();
5
+ const document = container.ownerDocument;
6
+ const view = document.defaultView;
7
+ const canvas = workspace.getCanvas();
8
+ const element = (tag) => document.createElementNS(svgNamespace, tag);
9
+ const map = element('svg');
10
+ map.dataset.workspaceMinimap = '';
11
+ map.classList.add('tw-workspace-overview');
12
+ map.setAttribute('aria-hidden', 'true');
13
+ const shapes = element('g');
14
+ const clip = element('svg');
15
+ clip.setAttribute('overflow', 'hidden');
16
+ const viewport = element('rect');
17
+ viewport.classList.add('tw-workspace-overview-viewport');
18
+ clip.append(viewport);
19
+ map.append(shapes, clip);
20
+ container.append(map);
21
+ const paths = new Map();
22
+ let needsShapes = true;
23
+ let frame;
24
+ let disposed = false;
25
+ const attribute = (node, name, value) => {
26
+ const text = String(value);
27
+ if (node.getAttribute(name) !== text)
28
+ node.setAttribute(name, text);
29
+ };
30
+ const style = (node, name, value) => {
31
+ if (node.style.getPropertyValue(name) !== value)
32
+ node.style.setProperty(name, value);
33
+ };
34
+ function refreshShapes() {
35
+ const retained = new Set();
36
+ const additions = document.createDocumentFragment();
37
+ for (const block of workspace.getAllBlocks(false)) {
38
+ const root = block.getSvgRoot();
39
+ if (!root || !canvas.contains(root) || root.closest('[data-tw-plus-hidden]'))
40
+ continue;
41
+ const source = root.querySelector(':scope > .blocklyPath');
42
+ const data = source?.getAttribute('d');
43
+ if (!data)
44
+ continue;
45
+ retained.add(block.id);
46
+ let path = paths.get(block.id);
47
+ if (!path) {
48
+ path = element('path');
49
+ paths.set(block.id, path);
50
+ additions.append(path);
51
+ }
52
+ const position = block.getRelativeToSurfaceXY();
53
+ attribute(path, 'd', data);
54
+ attribute(path, 'fill', source.getAttribute('fill') || block.getColour());
55
+ attribute(path, 'transform', `translate(${position.x} ${position.y})${block.RTL ? ' scale(-1 1)' : ''}`);
56
+ }
57
+ for (const [id, path] of paths)
58
+ if (!retained.has(id)) {
59
+ path.remove();
60
+ paths.delete(id);
61
+ }
62
+ if (additions.childNodes.length)
63
+ shapes.append(additions);
64
+ needsShapes = false;
65
+ }
66
+ function render() {
67
+ frame = undefined;
68
+ if (disposed)
69
+ return;
70
+ const metrics = workspace.isVisible() && workspace.getMetrics();
71
+ if (!metrics || metrics.viewWidth <= 32 || metrics.viewHeight <= 32) {
72
+ map.toggleAttribute('hidden', true);
73
+ return;
74
+ }
75
+ const scale = workspace.scale;
76
+ const x = metrics.viewLeft / scale, y = metrics.viewTop / scale;
77
+ const width = metrics.viewWidth / scale, height = metrics.viewHeight / scale;
78
+ const content = metrics.contentWidth > 0 && metrics.contentHeight > 0;
79
+ const area = content ? { x: metrics.contentLeft / scale, y: metrics.contentTop / scale,
80
+ width: metrics.contentWidth / scale, height: metrics.contentHeight / scale } : { x, y, width, height };
81
+ if (!workspace.scrollbar && content) {
82
+ const right = Math.max(x + width, area.x + area.width), bottom = Math.max(y + height, area.y + area.height);
83
+ area.x = Math.min(x, area.x);
84
+ area.y = Math.min(y, area.y);
85
+ area.width = right - area.x;
86
+ area.height = bottom - area.y;
87
+ }
88
+ const corner = getCorner?.(metrics);
89
+ if (!watermark?.isConnected)
90
+ watermark = getWatermark?.() ?? undefined;
91
+ const mapWidth = Math.min(164, metrics.viewWidth * .4) * .8;
92
+ let mapHeight = Math.min(104, metrics.viewHeight * .35) * .8;
93
+ const spacing = zoomHeight ? zoomHeight + 8 : 0;
94
+ if (watermark && corner)
95
+ mapHeight = Math.min(mapHeight, Math.max(0, corner.bottom - spacing - 8) * .6);
96
+ const right = corner ? container.clientWidth - corner.right : undefined;
97
+ const bottom = corner ? container.clientHeight - corner.bottom + spacing :
98
+ (metrics.toolboxPosition === ScratchBlocks.TOOLBOX_AT_BOTTOM ? metrics.toolboxHeight : 0) + 16;
99
+ const borderX = container.offsetWidth - container.clientWidth - container.clientLeft;
100
+ const borderY = container.offsetHeight - container.clientHeight - container.clientTop;
101
+ // All layout reads above precede writes. Identical values do not invalidate the editor's styles.
102
+ if (needsShapes)
103
+ refreshShapes();
104
+ map.toggleAttribute('hidden', false);
105
+ const box = `${area.x} ${area.y} ${area.width} ${area.height}`;
106
+ attribute(map, 'viewBox', box);
107
+ attribute(clip, 'viewBox', box);
108
+ for (const [name, value] of Object.entries(area))
109
+ attribute(clip, name, value);
110
+ for (const [name, value] of Object.entries({ x, y, width, height }))
111
+ attribute(viewport, name, value);
112
+ style(map, 'width', `${mapWidth}px`);
113
+ style(map, 'height', `${mapHeight}px`);
114
+ style(map, 'bottom', `${bottom}px`);
115
+ if (right !== undefined)
116
+ style(map, 'right', `${right}px`);
117
+ else
118
+ style(map, 'left', `${metrics.absoluteLeft + 12}px`);
119
+ if (watermark && corner) {
120
+ if (!watermark.classList.contains('tw-workspace-overview-watermark'))
121
+ watermark.classList.add('tw-workspace-overview-watermark');
122
+ if (!watermark.hasAttribute('data-plus-workspace-watermark'))
123
+ watermark.dataset.plusWorkspaceWatermark = '';
124
+ style(watermark, '--plus-watermark-right', `${right + borderX}px`);
125
+ style(watermark, '--plus-watermark-bottom', `${bottom + mapHeight + 8 + borderY}px`);
126
+ style(watermark, '--plus-watermark-size', `${Math.max(0, Math.min(64, corner.bottom - spacing - mapHeight - 8))}px`);
127
+ }
128
+ }
129
+ const schedule = () => {
130
+ if (!disposed && frame === undefined)
131
+ frame = view.requestAnimationFrame(render);
132
+ };
133
+ const changes = new view.MutationObserver(records => {
134
+ needsShapes ||= records.some(record => record.type === 'childList' || record.target !== canvas);
135
+ schedule();
136
+ });
137
+ // Native intersection culling only writes display styles. Those blocks still belong in the overview.
138
+ changes.observe(canvas, { subtree: true, childList: true,
139
+ attributeFilter: ['transform', 'd', 'fill', 'data-tw-plus-hidden'] });
140
+ const surface = container.querySelector('.blocklyWsDragSurface');
141
+ const scrolling = new view.MutationObserver(schedule);
142
+ if (surface)
143
+ scrolling.observe(surface, { attributes: true });
144
+ const resize = new view.ResizeObserver(schedule);
145
+ resize.observe(container);
146
+ const events = new view.AbortController();
147
+ view.addEventListener('resize', schedule, { signal: events.signal });
148
+ view.addEventListener('scroll', schedule, { signal: events.signal, passive: true });
149
+ const moveView = (left, top) => {
150
+ const metrics = workspace.getMetrics();
151
+ if (!metrics || !workspace.scrollbar)
152
+ return;
153
+ const clamp = (value, maximum) => Math.max(0, Math.min(value, Math.max(0, maximum)));
154
+ workspace.scrollbar.set(clamp(left * workspace.scale - metrics.contentLeft, metrics.contentWidth - metrics.viewWidth), clamp(top * workspace.scale - metrics.contentTop, metrics.contentHeight - metrics.viewHeight));
155
+ };
156
+ let pointer;
157
+ const point = (event, inverse) => new view.DOMPoint(event.clientX, event.clientY).matrixTransform(inverse);
158
+ map.addEventListener('pointerdown', event => {
159
+ if (!event.isPrimary || event.button !== 0 || pointer || !workspace.scrollbar)
160
+ return;
161
+ const matrix = map.getScreenCTM(), metrics = workspace.getMetrics();
162
+ if (!matrix || !metrics)
163
+ return;
164
+ const inverse = matrix.inverse();
165
+ pointer = { id: event.pointerId, x: event.clientX, y: event.clientY, start: point(event, inverse), inverse,
166
+ left: metrics.viewLeft / workspace.scale, top: metrics.viewTop / workspace.scale,
167
+ viewport: event.target === viewport, moved: false };
168
+ map.setPointerCapture(event.pointerId);
169
+ }, { signal: events.signal });
170
+ const move = (event) => {
171
+ if (pointer?.id !== event.pointerId)
172
+ return;
173
+ if (!pointer.moved && Math.hypot(event.clientX - pointer.x, event.clientY - pointer.y) >= 3) {
174
+ pointer.moved = true;
175
+ if (pointer.viewport) {
176
+ map.dataset.dragging = '';
177
+ ScratchBlocks.hideChaff(true);
178
+ }
179
+ }
180
+ if (pointer.moved && pointer.viewport) {
181
+ const current = point(event, pointer.inverse);
182
+ moveView(pointer.left + current.x - pointer.start.x, pointer.top + current.y - pointer.start.y);
183
+ }
184
+ };
185
+ map.addEventListener('pointermove', move, { signal: events.signal });
186
+ const finish = (event) => {
187
+ if (pointer?.id !== event.pointerId)
188
+ return;
189
+ if (event.type === 'pointerup') {
190
+ move(event);
191
+ if (!pointer.moved) {
192
+ const current = point(event, pointer.inverse), metrics = workspace.getMetrics();
193
+ if (metrics)
194
+ moveView(current.x - metrics.viewWidth / (2 * workspace.scale), current.y - metrics.viewHeight / (2 * workspace.scale));
195
+ ScratchBlocks.hideChaff(true);
196
+ }
197
+ }
198
+ pointer = undefined;
199
+ delete map.dataset.dragging;
200
+ };
201
+ for (const type of ['pointerup', 'pointercancel', 'lostpointercapture'])
202
+ map.addEventListener(type, finish, { signal: events.signal });
203
+ schedule();
204
+ return { dispose() {
205
+ disposed = true;
206
+ events.abort();
207
+ changes.disconnect();
208
+ scrolling.disconnect();
209
+ resize.disconnect();
210
+ if (frame !== undefined)
211
+ view.cancelAnimationFrame(frame);
212
+ map.remove();
213
+ paths.clear();
214
+ if (watermark) {
215
+ watermark.classList.remove('tw-workspace-overview-watermark');
216
+ delete watermark.dataset.plusWorkspaceWatermark;
217
+ for (const name of ['right', 'bottom', 'size'])
218
+ watermark.style.removeProperty(`--plus-watermark-${name}`);
219
+ }
220
+ } };
221
+ }
@@ -2,6 +2,7 @@ import { type CodeTarget } from './history.ts';
2
2
  import { captureCodePreviewChrome } from './preview-chrome.ts';
3
3
  import type { PresentationElements } from './preview-chrome.ts';
4
4
  import { type ScriptView } from './script-layout-view.ts';
5
+ import { type ScriptRelationVisibility } from './script-arrows.ts';
5
6
  import type { ScriptEndpoint } from './script-relations.ts';
6
7
  export type AttachPreviewMinimap = (workspace: any, ScratchBlocks: any, watermark: HTMLElement) => {
7
8
  dispose(): void;
@@ -16,6 +17,7 @@ export interface Presentation {
16
17
  y: number;
17
18
  visible: boolean;
18
19
  scriptView?: ScriptView;
20
+ relationVisibility?: ScriptRelationVisibility;
19
21
  /** Missing for a presentation read back from a saved workspace; the preview then draws without it. */
20
22
  chrome?: ReturnType<typeof captureCodePreviewChrome>;
21
23
  }
@@ -72,6 +74,7 @@ export declare function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspa
72
74
  select(view: any): boolean;
73
75
  preview(element: any, chrome: any, view: any): {
74
76
  workspace: any;
77
+ setRelationVisibility: (visibility: ScriptRelationVisibility) => void;
75
78
  update(): void;
76
79
  dispose(): void;
77
80
  };
@@ -79,7 +82,7 @@ export declare function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspa
79
82
  * Show only one script in the code area, a hat or a function, or every script again without `id`.
80
83
  * `onLost` runs when that script is deleted.
81
84
  */
82
- focusScript(id?: string, onLost?: () => void): void;
85
+ focusScript(id?: string, onLost?: () => void, refit?: boolean): void;
83
86
  readonly focusedScript: string;
84
87
  createFunction(target: CodeTarget & {
85
88
  id: string;
package/dist/workspace.js CHANGED
@@ -4,8 +4,9 @@ import { workspaceXML } from "./history.js";
4
4
  import { isFoldedDefinition, removeObsoleteProcedureInputs, setFoldedDefinition } from "./procedure-edits.js";
5
5
  import { decodeEdit, encodeEdit, isCommentEdit } from "./protocol.js";
6
6
  import { captureCodePreviewChrome } from "./preview-chrome.js";
7
- import { attachScriptView, getDockedScriptLayout } from "./script-layout-view.js";
7
+ import { attachScriptView, getDockedScriptLayout, getDockedRelationVisibility } from "./script-layout-view.js";
8
8
  import { attachScriptArrows, registerScriptRelationNavigation } from "./script-arrows.js";
9
+ import { fitScriptInWorkspace } from "./script-fit.js";
9
10
  const sessions = new WeakMap();
10
11
  export function getCodeSession(vm) {
11
12
  let session = sessions.get(vm);
@@ -242,28 +243,17 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
242
243
  safePaint();
243
244
  }
244
245
  /**
245
- * Put the shown script at the top left of the view, once the code area has its size there: the view it
246
- * moves into may only be laid out after the script was picked.
246
+ * Fit the shown script once the code area has its size: its destination view may only be laid out
247
+ * after the script was picked. Later edits and manual zooms keep their viewport.
247
248
  */
248
249
  let revealPending = false;
249
250
  function reveal() {
250
251
  if (!revealPending)
251
252
  return;
252
- const block = focus && workspace.getBlockById(focus.id);
253
- const injection = workspace.getInjectionDiv();
254
- if (!block || !injection.clientWidth || !injection.clientHeight)
255
- return;
256
- // The scroll area follows the shown scripts, which may have changed since the scrollbars were sized.
257
- workspace.resize?.();
258
- const metrics = workspace.getMetrics?.();
259
- if (!metrics?.viewWidth || !metrics.viewHeight)
260
- return;
261
- revealPending = false;
262
- const { x, y } = block.getRelativeToSurfaceXY();
263
- const padding = 16;
264
- workspace.scrollbar?.set(x * workspace.scale - metrics.contentLeft - padding, y * workspace.scale - metrics.contentTop - padding);
253
+ if (focus && fitScriptInWorkspace(workspace, focus.id, blocks))
254
+ revealPending = false;
265
255
  }
266
- function setFocus(next) {
256
+ function setFocus(next, refit = false) {
267
257
  const changedScript = next?.id !== focus?.id;
268
258
  focus = next && { id: next.id, onLost: next.onLost, extras: changedScript ? new Set() : focus?.extras ?? new Set() };
269
259
  if (focus) {
@@ -288,11 +278,13 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
288
278
  safePaint();
289
279
  if (workspace.rendered && workspace.isVisible?.() !== false)
290
280
  workspace.resize?.();
291
- if (focus && changedScript) {
281
+ if (focus && (changedScript || refit)) {
292
282
  revealPending = true;
293
- reveal();
283
+ // The pane can still be moving from its previous size during this activation.
294
284
  schedulePaint();
295
285
  }
286
+ else if (!focus)
287
+ revealPending = false;
296
288
  }
297
289
  // Blocks dragged in from the palette, or pulled out of the shown script, stay in view. Only the end of a
298
290
  // drag counts: a reload of the workspace also sends a create event for every block, after the load.
@@ -342,9 +334,9 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
342
334
  if (!disposed)
343
335
  reveal();
344
336
  },
345
- focus: (id, onLost) => {
337
+ focus: (id, onLost, refit = false) => {
346
338
  if (!disposed)
347
- setFocus(id ? { id, onLost } : undefined);
339
+ setFocus(id ? { id, onLost } : undefined, refit);
348
340
  },
349
341
  get focusedScript() { return focus?.id; },
350
342
  dispose() {
@@ -414,6 +406,7 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
414
406
  y: workspace.scrollY + metrics.absoluteTop,
415
407
  visible,
416
408
  scriptView: getDockedScriptLayout(vm)?.view.view,
409
+ relationVisibility: getDockedRelationVisibility(vm),
417
410
  chrome: captureCodePreviewChrome(workspace, loadedTarget, presentationElements, includeNavigation)
418
411
  };
419
412
  }
@@ -567,7 +560,7 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
567
560
  const minimap = attachMinimap?.(preview, blocks, watermark);
568
561
  const scriptView = attachScriptView({ workspace: preview, ScratchBlocks: blocks, mount: chrome.parentElement,
569
562
  getLocale: () => locale ?? workspace.getInjectionDiv().ownerDocument.documentElement.lang,
570
- relations: { vm, getTarget: () => target },
563
+ relations: { vm, getTarget: () => target, initialVisibility: view.relationVisibility ?? presentation?.relationVisibility },
571
564
  initialView: view.scriptView ?? presentation?.scriptView,
572
565
  onChange: next => {
573
566
  if (presentation)
@@ -604,6 +597,7 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
604
597
  observer.observe(element);
605
598
  return {
606
599
  workspace: preview,
600
+ setRelationVisibility: (visibility) => scriptView.relations?.setVisibility(visibility),
607
601
  update() {
608
602
  if (vm.runtime.getTargetById(target.id) !== target)
609
603
  return;
@@ -635,8 +629,8 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
635
629
  * Show only one script in the code area, a hat or a function, or every script again without `id`.
636
630
  * `onLost` runs when that script is deleted.
637
631
  */
638
- focusScript(id, onLost) {
639
- visibility.focus(id, onLost);
632
+ focusScript(id, onLost, refit = false) {
633
+ visibility.focus(id, onLost, refit);
640
634
  },
641
635
  get focusedScript() { return visibility.focusedScript; },
642
636
  createFunction(target, kind, name, { loadNamedFunctions } = {}) {
@@ -689,10 +683,11 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
689
683
  return;
690
684
  // Let a target switch restore that pane's mode first. Normal views keep showing all scripts.
691
685
  if (visibility.focusedScript) {
692
- visibility.focus(endpoint.scriptId);
686
+ visibility.focus(endpoint.scriptId, undefined, true);
693
687
  session.changed(endpoint);
694
688
  }
695
- workspace.centerOnBlock(endpoint.scriptId);
689
+ else
690
+ workspace.centerOnBlock(endpoint.scriptId);
696
691
  });
697
692
  });
698
693
  visibility.paint();
@@ -846,15 +841,7 @@ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDo
846
841
  let rendered;
847
842
  let positioned = false;
848
843
  function position() {
849
- const definition = editor.getBlockById(definitionId);
850
- const metrics = editor.getMetrics();
851
- if (!definition || !metrics?.viewWidth || !metrics.viewHeight)
852
- return false;
853
- // Put the hat at the top left whatever its place in the code area.
854
- const { x, y } = definition.getRelativeToSurfaceXY();
855
- const padding = 16;
856
- editor.scrollbar.set(x * editor.scale - metrics.contentLeft - padding, y * editor.scale - metrics.contentTop - padding);
857
- return true;
844
+ return fitScriptInWorkspace(editor, definitionId, blocks);
858
845
  }
859
846
  function load() {
860
847
  if (!exists() || !target.blocks._blocks[definitionId])
@@ -910,7 +897,7 @@ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDo
910
897
  return;
911
898
  }
912
899
  pendingBlock = undefined;
913
- editor.centerOnBlock(block.id);
900
+ fitScriptInWorkspace(editor, definitionId, blocks);
914
901
  block.select();
915
902
  }
916
903
  let frame;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Code views for TurboWarp Plus Editor: code in tabs and windows, the detached block palette, script layout and block field editing",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
package/src/code-pane.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import {getCodeSession} from './workspace.ts';
2
2
  import type {AttachPreviewMinimap, AttachWorkspaceNavigation} from './workspace.ts';
3
- import {getDockedScriptLayout, type ScriptView} from './script-layout-view.ts';
3
+ import {getDockedScriptLayout, setDockedRelationVisibility, type ScriptView} from './script-layout-view.ts';
4
4
  import {readScriptRelations, type RelationTarget} from './script-relations.ts';
5
+ import type {ScriptRelationVisibility} from './script-arrows.ts';
5
6
 
6
7
  type Pane = {id: string; targetId: string; section: number};
7
8
  type Bridge = NonNullable<ReturnType<typeof getCodeSession>['bridge']>;
@@ -14,6 +15,7 @@ export type SavedCodePane = {
14
15
  x: number;
15
16
  y: number;
16
17
  scriptView?: ScriptView;
18
+ relationVisibility?: ScriptRelationVisibility;
17
19
  };
18
20
 
19
21
  const scriptViews: readonly ScriptView[] = ['free', 'z', 'n'];
@@ -22,22 +24,29 @@ const finite = (value: unknown, limit: number): value is number =>
22
24
 
23
25
  /** Read a saved code area back, or nothing if it does not have the shape `serialize` writes. */
24
26
  export function readSavedCodePane(value: Record<string, unknown>): SavedCodePane | undefined {
25
- const {scale, x, y, scriptView} = value;
27
+ const {scale, x, y, scriptView, relationVisibility} = value;
26
28
  if (!finite(scale, 100) || scale <= 0 || !finite(x, 1e7) || !finite(y, 1e7)) return;
27
- return {scale, x, y, ...(scriptViews.includes(scriptView as ScriptView) && {scriptView: scriptView as ScriptView})};
29
+ const visibility = relationVisibility as Partial<ScriptRelationVisibility> | null;
30
+ return {scale, x, y, ...(scriptViews.includes(scriptView as ScriptView) && {scriptView: scriptView as ScriptView}),
31
+ ...(visibility && typeof visibility.function === 'boolean' && typeof visibility.message === 'boolean' &&
32
+ {relationVisibility: {function: visibility.function, message: visibility.message}})};
28
33
  }
29
34
 
30
35
  export function createCodePaneAdapter(vm, locale: string, attachMinimap?: AttachPreviewMinimap) {
31
36
  const session = getCodeSession(vm);
32
37
  const label = /^ja(?:-|$)/i.test(locale) ? 'このペインでコードを編集' : 'Edit code in this pane';
33
38
  const views = new Map<string, ScriptView>();
39
+ const visibilities = new Map<string, ScriptRelationVisibility>();
40
+ const visibilityListeners = new Set<() => void>();
41
+ const getVisibility = (paneId: string): ScriptRelationVisibility =>
42
+ ({...visibilities.get(paneId) ?? {function: true, message: true}});
34
43
  // Views that show one script, a hat or a function, by pane id; `onLost` runs when that script is deleted.
35
44
  const focused = new Map<string, {scriptId: string; onLost?: () => void}>();
36
45
  // The code pane the code area is in, which shows its script there.
37
46
  let current: string | undefined;
38
- const applyFocus = (paneId?: string) => {
47
+ const applyFocus = (paneId?: string, refit = false) => {
39
48
  const focus = paneId === undefined ? undefined : focused.get(paneId);
40
- session.bridge?.focusScript(focus?.scriptId, focus && (() => focus.onLost?.()));
49
+ session.bridge?.focusScript(focus?.scriptId, focus && (() => focus.onLost?.()), refit);
41
50
  };
42
51
  let pending: {frame: number; pane: Pane; presentation: Presentation} | undefined;
43
52
  // The GUI can attach the code area again, with a new bridge; the view it is in still shows its script.
@@ -73,6 +82,22 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
73
82
  }
74
83
 
75
84
  return {
85
+ /** Independent arrow filters belong to a code pane, including when its workspace is parked. */
86
+ relations: {
87
+ getVisibility,
88
+ setVisibility(paneId: string, value: ScriptRelationVisibility) {
89
+ const before = getVisibility(paneId);
90
+ if (before.function === value.function && before.message === value.message) return;
91
+ visibilities.set(paneId, {...value});
92
+ if (current === paneId) setDockedRelationVisibility(vm, value);
93
+ for (const listener of visibilityListeners) listener();
94
+ session.changed();
95
+ },
96
+ subscribe(listener: () => void) {
97
+ visibilityListeners.add(listener);
98
+ return () => visibilityListeners.delete(listener);
99
+ }
100
+ },
76
101
  /**
77
102
  * Make a code view show one script, a hat or a function, or every script again without `scriptId`.
78
103
  * The code area shows it while it is in that view, and the view's preview shows it otherwise.
@@ -80,7 +105,7 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
80
105
  focusPane(paneId: string, scriptId?: string, onLost?: () => void) {
81
106
  if (scriptId) focused.set(paneId, {scriptId, onLost});
82
107
  else focused.delete(paneId);
83
- if (current === paneId) applyFocus(paneId);
108
+ if (current === paneId) applyFocus(paneId, true);
84
109
  // Previews of other views redraw with their script.
85
110
  session.changed();
86
111
  },
@@ -89,8 +114,10 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
89
114
  forgetPane(paneId: string) {
90
115
  focused.delete(paneId);
91
116
  views.delete(paneId);
117
+ visibilities.delete(paneId);
92
118
  if (current === paneId) {
93
119
  current = undefined;
120
+ setDockedRelationVisibility(vm, {function: true, message: true});
94
121
  applyFocus(undefined);
95
122
  }
96
123
  },
@@ -118,7 +145,9 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
118
145
  if (!shown) return;
119
146
  const scriptView = presentation ? presentation.scriptView : views.get(pane.id) ??
120
147
  getDockedScriptLayout(vm)?.view.view;
121
- return {scale: shown.scale, x: shown.x, y: shown.y, ...(scriptView && {scriptView})};
148
+ const relationVisibility = visibilities.get(pane.id) ?? shown.relationVisibility;
149
+ return {scale: shown.scale, x: shown.x, y: shown.y, ...(scriptView && {scriptView}),
150
+ ...(relationVisibility && {relationVisibility: {...relationVisibility}})};
122
151
  },
123
152
  /** A presentation from a saved code area. The preview draws it without the chrome of the code area. */
124
153
  deserialize(pane: Pane, value: Record<string, unknown>): Presentation | undefined {
@@ -126,19 +155,30 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
126
155
  const saved = readSavedCodePane(value);
127
156
  if (!saved) return;
128
157
  if (saved.scriptView) views.set(pane.id, saved.scriptView);
129
- return {scale: saved.scale, x: saved.x, y: saved.y, visible: true, ...(saved.scriptView && {scriptView: saved.scriptView})};
158
+ if (saved.relationVisibility) visibilities.set(pane.id, {...saved.relationVisibility});
159
+ else visibilities.delete(pane.id);
160
+ for (const listener of visibilityListeners) listener();
161
+ return {scale: saved.scale, x: saved.x, y: saved.y, visible: true, ...(saved.scriptView && {scriptView: saved.scriptView}),
162
+ ...(saved.relationVisibility && {relationVisibility: {...saved.relationVisibility}})};
130
163
  },
131
164
  restore(pane: Pane, presentation?: Presentation) {
132
165
  if (pending) cancelAnimationFrame(pending.frame);
133
166
  pending = undefined;
134
167
  if (pane.section !== 0) return;
135
168
  current = pane.id;
169
+ if (!visibilities.has(pane.id) && presentation?.relationVisibility) {
170
+ visibilities.set(pane.id, {...presentation.relationVisibility});
171
+ for (const listener of visibilityListeners) listener();
172
+ }
173
+ setDockedRelationVisibility(vm, getVisibility(pane.id));
136
174
  applyFocus(pane.id);
137
175
  getDockedScriptLayout(vm)?.view.setView(views.get(pane.id) ?? 'free');
138
176
  if (!presentation) return;
139
177
  const frame = requestAnimationFrame(() => {
140
178
  pending = undefined;
141
179
  session.bridge?.restorePane(pane.targetId, presentation);
180
+ // A picked script owns its initial viewport, including after a saved pane is restored.
181
+ if (focused.has(pane.id)) applyFocus(pane.id, true);
142
182
  });
143
183
  pending = {frame, pane, presentation};
144
184
  },
@@ -184,8 +224,10 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
184
224
  shownScript = focused.get(pane.id)?.scriptId;
185
225
  preview = bridge?.preview(blocks, chrome, {target, presentation, attachMinimap, watermark, locale, dropElement: surface,
186
226
  scriptView: views.get(pane.id), onScriptViewChange: view => views.set(pane.id, view),
227
+ relationVisibility: getVisibility(pane.id),
187
228
  scriptId: focused.get(pane.id)?.scriptId});
188
229
  }
230
+ preview?.setRelationVisibility(getVisibility(pane.id));
189
231
  preview?.update();
190
232
  }
191
233
  const unsubscribe = session.subscribe(update);