@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.
@@ -4,6 +4,8 @@ import type {createCodePaneAdapter} from './code-pane.ts';
4
4
  import {getCodeSession} from './workspace.ts';
5
5
 
6
6
  export {attachCodeWorkspace} from './workspace.ts';
7
+ export {fitScriptInWorkspace} from './script-fit.ts';
8
+ export {attachWorkspaceOverview} from './workspace-overview.ts';
7
9
  export {attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane, readScriptRelationGraph} from './code-pane.ts';
8
10
  export type {SavedCodePane} from './code-pane.ts';
9
11
 
package/src/styles.css CHANGED
@@ -525,6 +525,38 @@
525
525
  --tw-script-message-stroke: light-dark(#a85a00, #ffbd66);
526
526
  }
527
527
 
528
+ .tw-workspace-overview {
529
+ position: absolute;
530
+ z-index: 1;
531
+ box-sizing: border-box;
532
+ overflow: hidden;
533
+ cursor: pointer;
534
+ color: var(--text-primary, #334155);
535
+ background: color-mix(in srgb, var(--ui-primary, white) 50%, transparent);
536
+ border: 1px solid var(--ui-black-transparent, #cbd5e1);
537
+ border-radius: 8px;
538
+ box-shadow: 0 2px 8px rgb(0 0 0 / 20%);
539
+ }
540
+ .tw-workspace-overview[hidden] { display: none; }
541
+ .tw-workspace-overview-viewport {
542
+ cursor: grab;
543
+ fill: currentColor;
544
+ fill-opacity: .06;
545
+ stroke: currentColor;
546
+ stroke-width: 1.5px;
547
+ vector-effect: non-scaling-stroke;
548
+ }
549
+ .tw-workspace-overview[data-dragging], .tw-workspace-overview[data-dragging] .tw-workspace-overview-viewport { cursor: grabbing; }
550
+ [dir] .tw-workspace-overview-watermark[data-plus-workspace-watermark] {
551
+ inset: auto var(--plus-watermark-right, 1.25rem) var(--plus-watermark-bottom, 1.25rem) auto;
552
+ }
553
+ .tw-workspace-overview-watermark > img {
554
+ display: block;
555
+ max-width: var(--plus-watermark-size, 64px);
556
+ max-height: var(--plus-watermark-size, 64px);
557
+ opacity: .6;
558
+ }
559
+
528
560
  [data-script-relation="function"] {
529
561
  --tw-script-relation-stroke: var(--tw-script-function-stroke);
530
562
  --tw-script-relation-dash: none;
@@ -543,7 +575,7 @@
543
575
  fill: none;
544
576
  stroke: var(--tw-script-relation-stroke);
545
577
  stroke-width: 1.8;
546
- stroke-opacity: 0.75;
578
+ stroke-opacity: 0.2;
547
579
  vector-effect: non-scaling-stroke;
548
580
  pointer-events: none;
549
581
  }
@@ -561,6 +593,14 @@
561
593
  stroke-opacity: 0.2;
562
594
  }
563
595
 
596
+ [data-script-relation-layer] > [data-script-relation][data-script-external] {
597
+ opacity: 0.05;
598
+ }
599
+
600
+ [data-script-relation-layer] > [data-script-relation][data-script-external] :is(.tw-script-relation-line, .tw-script-relation-head) {
601
+ stroke-opacity: 1;
602
+ }
603
+
564
604
  .tw-script-relation-script-highlight {
565
605
  fill: light-dark(#3373cc, #93c5fd);
566
606
  fill-opacity: 0.1;
@@ -0,0 +1,197 @@
1
+ type OverviewOptions = {
2
+ workspace: any;
3
+ ScratchBlocks: any;
4
+ zoomHeight?: number;
5
+ getCorner?(metrics: any): {right: number; bottom: number};
6
+ watermark?: HTMLElement;
7
+ getWatermark?(): HTMLElement | undefined | null;
8
+ };
9
+
10
+ const svgNamespace = 'http://www.w3.org/2000/svg';
11
+
12
+ /** A cached overview drawn from public block geometry; offscreen culling never changes the project map. */
13
+ export function attachWorkspaceOverview({workspace, ScratchBlocks, zoomHeight = 0, getCorner,
14
+ watermark, getWatermark}: OverviewOptions) {
15
+ const container = workspace.getInjectionDiv() as HTMLElement;
16
+ const document = container.ownerDocument;
17
+ const view = document.defaultView;
18
+ const canvas = workspace.getCanvas() as SVGElement;
19
+ const element = <K extends keyof SVGElementTagNameMap>(tag: K) => document.createElementNS(svgNamespace, tag);
20
+ const map = element('svg');
21
+ map.dataset.workspaceMinimap = '';
22
+ map.classList.add('tw-workspace-overview');
23
+ map.setAttribute('aria-hidden', 'true');
24
+ const shapes = element('g');
25
+ const clip = element('svg');
26
+ clip.setAttribute('overflow', 'hidden');
27
+ const viewport = element('rect');
28
+ viewport.classList.add('tw-workspace-overview-viewport');
29
+ clip.append(viewport);
30
+ map.append(shapes, clip);
31
+ container.append(map);
32
+ const paths = new Map<string, SVGPathElement>();
33
+ let needsShapes = true;
34
+ let frame: number | undefined;
35
+ let disposed = false;
36
+ const attribute = (node: Element, name: string, value: string | number) => {
37
+ const text = String(value);
38
+ if (node.getAttribute(name) !== text) node.setAttribute(name, text);
39
+ };
40
+ const style = (node: HTMLElement | SVGElement, name: string, value: string) => {
41
+ if (node.style.getPropertyValue(name) !== value) node.style.setProperty(name, value);
42
+ };
43
+
44
+ function refreshShapes() {
45
+ const retained = new Set<string>();
46
+ const additions = document.createDocumentFragment();
47
+ for (const block of workspace.getAllBlocks(false)) {
48
+ const root = block.getSvgRoot() as SVGElement | null;
49
+ if (!root || !canvas.contains(root) || root.closest('[data-tw-plus-hidden]')) continue;
50
+ const source = root.querySelector(':scope > .blocklyPath');
51
+ const data = source?.getAttribute('d');
52
+ if (!data) continue;
53
+ retained.add(block.id);
54
+ let path = paths.get(block.id);
55
+ if (!path) {
56
+ path = element('path');
57
+ paths.set(block.id, path);
58
+ additions.append(path);
59
+ }
60
+ const position = block.getRelativeToSurfaceXY();
61
+ attribute(path, 'd', data);
62
+ attribute(path, 'fill', source.getAttribute('fill') || block.getColour());
63
+ attribute(path, 'transform', `translate(${position.x} ${position.y})${block.RTL ? ' scale(-1 1)' : ''}`);
64
+ }
65
+ for (const [id, path] of paths) if (!retained.has(id)) {path.remove(); paths.delete(id);}
66
+ if (additions.childNodes.length) shapes.append(additions);
67
+ needsShapes = false;
68
+ }
69
+
70
+ function render() {
71
+ frame = undefined;
72
+ if (disposed) return;
73
+ const metrics = workspace.isVisible() && workspace.getMetrics();
74
+ if (!metrics || metrics.viewWidth <= 32 || metrics.viewHeight <= 32) {map.toggleAttribute('hidden', true); return;}
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); area.y = Math.min(y, area.y);
84
+ area.width = right - area.x; area.height = bottom - area.y;
85
+ }
86
+ const corner = getCorner?.(metrics);
87
+ if (!watermark?.isConnected) watermark = getWatermark?.() ?? undefined;
88
+ const mapWidth = Math.min(164, metrics.viewWidth * .4) * .8;
89
+ let mapHeight = Math.min(104, metrics.viewHeight * .35) * .8;
90
+ const spacing = zoomHeight ? zoomHeight + 8 : 0;
91
+ if (watermark && corner) mapHeight = Math.min(mapHeight, Math.max(0, corner.bottom - spacing - 8) * .6);
92
+ const right = corner ? container.clientWidth - corner.right : undefined;
93
+ const bottom = corner ? container.clientHeight - corner.bottom + spacing :
94
+ (metrics.toolboxPosition === ScratchBlocks.TOOLBOX_AT_BOTTOM ? metrics.toolboxHeight : 0) + 16;
95
+ const borderX = container.offsetWidth - container.clientWidth - container.clientLeft;
96
+ const borderY = container.offsetHeight - container.clientHeight - container.clientTop;
97
+
98
+ // All layout reads above precede writes. Identical values do not invalidate the editor's styles.
99
+ if (needsShapes) refreshShapes();
100
+ map.toggleAttribute('hidden', false);
101
+ const box = `${area.x} ${area.y} ${area.width} ${area.height}`;
102
+ attribute(map, 'viewBox', box); attribute(clip, 'viewBox', box);
103
+ for (const [name, value] of Object.entries(area)) attribute(clip, name, value);
104
+ for (const [name, value] of Object.entries({x, y, width, height})) attribute(viewport, name, value);
105
+ style(map, 'width', `${mapWidth}px`); style(map, 'height', `${mapHeight}px`);
106
+ style(map, 'bottom', `${bottom}px`);
107
+ if (right !== undefined) style(map, 'right', `${right}px`);
108
+ else style(map, 'left', `${metrics.absoluteLeft + 12}px`);
109
+ if (watermark && corner) {
110
+ if (!watermark.classList.contains('tw-workspace-overview-watermark')) watermark.classList.add('tw-workspace-overview-watermark');
111
+ if (!watermark.hasAttribute('data-plus-workspace-watermark')) watermark.dataset.plusWorkspaceWatermark = '';
112
+ style(watermark, '--plus-watermark-right', `${right + borderX}px`);
113
+ style(watermark, '--plus-watermark-bottom', `${bottom + mapHeight + 8 + borderY}px`);
114
+ style(watermark, '--plus-watermark-size', `${Math.max(0, Math.min(64, corner.bottom - spacing - mapHeight - 8))}px`);
115
+ }
116
+ }
117
+ const schedule = () => {
118
+ if (!disposed && frame === undefined) frame = view.requestAnimationFrame(render);
119
+ };
120
+ const changes = new view.MutationObserver(records => {
121
+ needsShapes ||= records.some(record => record.type === 'childList' || record.target !== canvas);
122
+ schedule();
123
+ });
124
+ // Native intersection culling only writes display styles. Those blocks still belong in the overview.
125
+ changes.observe(canvas, {subtree: true, childList: true,
126
+ attributeFilter: ['transform', 'd', 'fill', 'data-tw-plus-hidden']});
127
+ const surface = container.querySelector('.blocklyWsDragSurface');
128
+ const scrolling = new view.MutationObserver(schedule);
129
+ if (surface) scrolling.observe(surface, {attributes: true});
130
+ const resize = new view.ResizeObserver(schedule);
131
+ resize.observe(container);
132
+ const events = new view.AbortController();
133
+ view.addEventListener('resize', schedule, {signal: events.signal});
134
+ view.addEventListener('scroll', schedule, {signal: events.signal, passive: true});
135
+
136
+ const moveView = (left: number, top: number) => {
137
+ const metrics = workspace.getMetrics();
138
+ if (!metrics || !workspace.scrollbar) return;
139
+ const clamp = (value: number, maximum: number) => Math.max(0, Math.min(value, Math.max(0, maximum)));
140
+ workspace.scrollbar.set(clamp(left * workspace.scale - metrics.contentLeft, metrics.contentWidth - metrics.viewWidth),
141
+ clamp(top * workspace.scale - metrics.contentTop, metrics.contentHeight - metrics.viewHeight));
142
+ };
143
+ type Pointer = {id: number; x: number; y: number; start: DOMPoint; inverse: DOMMatrix;
144
+ left: number; top: number; viewport: boolean; moved: boolean};
145
+ let pointer: Pointer | undefined;
146
+ const point = (event: PointerEvent, inverse: DOMMatrix) =>
147
+ new view.DOMPoint(event.clientX, event.clientY).matrixTransform(inverse);
148
+ map.addEventListener('pointerdown', event => {
149
+ if (!event.isPrimary || event.button !== 0 || pointer || !workspace.scrollbar) return;
150
+ const matrix = map.getScreenCTM(), metrics = workspace.getMetrics();
151
+ if (!matrix || !metrics) return;
152
+ const inverse = matrix.inverse();
153
+ pointer = {id: event.pointerId, x: event.clientX, y: event.clientY, start: point(event, inverse), inverse,
154
+ left: metrics.viewLeft / workspace.scale, top: metrics.viewTop / workspace.scale,
155
+ viewport: event.target === viewport, moved: false};
156
+ map.setPointerCapture(event.pointerId);
157
+ }, {signal: events.signal});
158
+ const move = (event: PointerEvent) => {
159
+ if (pointer?.id !== event.pointerId) return;
160
+ if (!pointer.moved && Math.hypot(event.clientX - pointer.x, event.clientY - pointer.y) >= 3) {
161
+ pointer.moved = true;
162
+ if (pointer.viewport) {map.dataset.dragging = ''; ScratchBlocks.hideChaff(true);}
163
+ }
164
+ if (pointer.moved && pointer.viewport) {
165
+ const current = point(event, pointer.inverse);
166
+ moveView(pointer.left + current.x - pointer.start.x, pointer.top + current.y - pointer.start.y);
167
+ }
168
+ };
169
+ map.addEventListener('pointermove', move, {signal: events.signal});
170
+ const finish = (event: PointerEvent) => {
171
+ if (pointer?.id !== event.pointerId) return;
172
+ if (event.type === 'pointerup') {
173
+ move(event);
174
+ if (!pointer.moved) {
175
+ const current = point(event, pointer.inverse), metrics = workspace.getMetrics();
176
+ if (metrics) moveView(current.x - metrics.viewWidth / (2 * workspace.scale),
177
+ current.y - metrics.viewHeight / (2 * workspace.scale));
178
+ ScratchBlocks.hideChaff(true);
179
+ }
180
+ }
181
+ pointer = undefined;
182
+ delete map.dataset.dragging;
183
+ };
184
+ for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) map.addEventListener(type, finish, {signal: events.signal});
185
+ schedule();
186
+ return {dispose() {
187
+ disposed = true;
188
+ events.abort(); changes.disconnect(); scrolling.disconnect(); resize.disconnect();
189
+ if (frame !== undefined) view.cancelAnimationFrame(frame);
190
+ map.remove(); paths.clear();
191
+ if (watermark) {
192
+ watermark.classList.remove('tw-workspace-overview-watermark');
193
+ delete watermark.dataset.plusWorkspaceWatermark;
194
+ for (const name of ['right', 'bottom', 'size']) watermark.style.removeProperty(`--plus-watermark-${name}`);
195
+ }
196
+ }};
197
+ }
package/src/workspace.ts CHANGED
@@ -5,9 +5,10 @@ import {isFoldedDefinition, removeObsoleteProcedureInputs, setFoldedDefinition}
5
5
  import {decodeEdit, encodeEdit, isCommentEdit} from './protocol.ts';
6
6
  import {captureCodePreviewChrome} from './preview-chrome.ts';
7
7
  import type {PresentationElements} from './preview-chrome.ts';
8
- import {attachScriptView, getDockedScriptLayout, type ScriptView} from './script-layout-view.ts';
9
- import {attachScriptArrows, registerScriptRelationNavigation} from './script-arrows.ts';
8
+ import {attachScriptView, getDockedScriptLayout, getDockedRelationVisibility, type ScriptView} from './script-layout-view.ts';
9
+ import {attachScriptArrows, registerScriptRelationNavigation, type ScriptRelationVisibility} from './script-arrows.ts';
10
10
  import type {RelationBlock, ScriptEndpoint} from './script-relations.ts';
11
+ import {fitScriptInWorkspace} from './script-fit.ts';
11
12
 
12
13
  export type AttachPreviewMinimap = (workspace, ScratchBlocks, watermark: HTMLElement) => {dispose(): void};
13
14
  /** Adds the code area's zoom buttons and minimap to another workspace. */
@@ -20,6 +21,7 @@ export interface Presentation {
20
21
  y: number;
21
22
  visible: boolean;
22
23
  scriptView?: ScriptView;
24
+ relationVisibility?: ScriptRelationVisibility;
23
25
  /** Missing for a presentation read back from a saved workspace; the preview then draws without it. */
24
26
  chrome?: ReturnType<typeof captureCodePreviewChrome>;
25
27
  }
@@ -296,27 +298,16 @@ function attachScriptVisibility({vm, blocks, workspace, homeDocument, onError})
296
298
  }
297
299
 
298
300
  /**
299
- * Put the shown script at the top left of the view, once the code area has its size there: the view it
300
- * moves into may only be laid out after the script was picked.
301
+ * Fit the shown script once the code area has its size: its destination view may only be laid out
302
+ * after the script was picked. Later edits and manual zooms keep their viewport.
301
303
  */
302
304
  let revealPending = false;
303
305
  function reveal() {
304
306
  if (!revealPending) return;
305
- const block = focus && workspace.getBlockById(focus.id);
306
- const injection = workspace.getInjectionDiv();
307
- if (!block || !injection.clientWidth || !injection.clientHeight) return;
308
- // The scroll area follows the shown scripts, which may have changed since the scrollbars were sized.
309
- workspace.resize?.();
310
- const metrics = workspace.getMetrics?.();
311
- if (!metrics?.viewWidth || !metrics.viewHeight) return;
312
- revealPending = false;
313
- const {x, y} = block.getRelativeToSurfaceXY();
314
- const padding = 16;
315
- workspace.scrollbar?.set(x * workspace.scale - metrics.contentLeft - padding,
316
- y * workspace.scale - metrics.contentTop - padding);
307
+ if (focus && fitScriptInWorkspace(workspace, focus.id, blocks)) revealPending = false;
317
308
  }
318
309
 
319
- function setFocus(next?: {id: string; onLost?: () => void}) {
310
+ function setFocus(next?: {id: string; onLost?: () => void}, refit = false) {
320
311
  const changedScript = next?.id !== focus?.id;
321
312
  focus = next && {id: next.id, onLost: next.onLost, extras: changedScript ? new Set() : focus?.extras ?? new Set()};
322
313
  if (focus) {
@@ -337,11 +328,11 @@ function attachScriptVisibility({vm, blocks, workspace, homeDocument, onError})
337
328
  } else restoreWorkspaceMethods();
338
329
  safePaint();
339
330
  if (workspace.rendered && workspace.isVisible?.() !== false) workspace.resize?.();
340
- if (focus && changedScript) {
331
+ if (focus && (changedScript || refit)) {
341
332
  revealPending = true;
342
- reveal();
333
+ // The pane can still be moving from its previous size during this activation.
343
334
  schedulePaint();
344
- }
335
+ } else if (!focus) revealPending = false;
345
336
  }
346
337
 
347
338
  // Blocks dragged in from the palette, or pulled out of the shown script, stay in view. Only the end of a
@@ -387,8 +378,8 @@ function attachScriptVisibility({vm, blocks, workspace, homeDocument, onError})
387
378
  resized: () => {
388
379
  if (!disposed) reveal();
389
380
  },
390
- focus: (id?: string, onLost?: () => void) => {
391
- if (!disposed) setFocus(id ? {id, onLost} : undefined);
381
+ focus: (id?: string, onLost?: () => void, refit = false) => {
382
+ if (!disposed) setFocus(id ? {id, onLost} : undefined, refit);
392
383
  },
393
384
  get focusedScript() { return focus?.id; },
394
385
  dispose() {
@@ -457,6 +448,7 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
457
448
  y: workspace.scrollY + metrics.absoluteTop,
458
449
  visible,
459
450
  scriptView: getDockedScriptLayout(vm)?.view.view,
451
+ relationVisibility: getDockedRelationVisibility(vm),
460
452
  chrome: captureCodePreviewChrome(workspace, loadedTarget, presentationElements, includeNavigation)
461
453
  };
462
454
  }
@@ -597,7 +589,7 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
597
589
  const minimap = attachMinimap?.(preview, blocks, watermark);
598
590
  const scriptView = attachScriptView({workspace: preview, ScratchBlocks: blocks, mount: chrome.parentElement,
599
591
  getLocale: () => locale ?? workspace.getInjectionDiv().ownerDocument.documentElement.lang,
600
- relations: {vm, getTarget: () => target},
592
+ relations: {vm, getTarget: () => target, initialVisibility: view.relationVisibility ?? presentation?.relationVisibility},
601
593
  initialView: view.scriptView ?? presentation?.scriptView,
602
594
  onChange: next => {
603
595
  if (presentation) presentation.scriptView = next;
@@ -634,6 +626,7 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
634
626
  observer.observe(element);
635
627
  return {
636
628
  workspace: preview,
629
+ setRelationVisibility: (visibility: ScriptRelationVisibility) => scriptView.relations?.setVisibility(visibility),
637
630
  update() {
638
631
  if (vm.runtime.getTargetById(target.id) !== target) return;
639
632
  // A view that shows one script previews only that script.
@@ -664,8 +657,8 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
664
657
  * Show only one script in the code area, a hat or a function, or every script again without `id`.
665
658
  * `onLost` runs when that script is deleted.
666
659
  */
667
- focusScript(id?: string, onLost?: () => void) {
668
- visibility.focus(id, onLost);
660
+ focusScript(id?: string, onLost?: () => void, refit = false) {
661
+ visibility.focus(id, onLost, refit);
669
662
  },
670
663
  get focusedScript() { return visibility.focusedScript; },
671
664
  createFunction(target: CodeTarget & {id: string}, kind: 'procedure' | 'named', name: string, {loadNamedFunctions}: {
@@ -718,10 +711,9 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
718
711
  if (session.bridge !== bridge) return;
719
712
  // Let a target switch restore that pane's mode first. Normal views keep showing all scripts.
720
713
  if (visibility.focusedScript) {
721
- visibility.focus(endpoint.scriptId);
714
+ visibility.focus(endpoint.scriptId, undefined, true);
722
715
  session.changed(endpoint);
723
- }
724
- workspace.centerOnBlock(endpoint.scriptId);
716
+ } else workspace.centerOnBlock(endpoint.scriptId);
725
717
  });
726
718
  });
727
719
  visibility.paint();
@@ -885,15 +877,7 @@ function attachProcedureEditor({vm, blocks, workspace, options, onError, homeDoc
885
877
  let rendered: string | undefined;
886
878
  let positioned = false;
887
879
  function position() {
888
- const definition = editor.getBlockById(definitionId);
889
- const metrics = editor.getMetrics();
890
- if (!definition || !metrics?.viewWidth || !metrics.viewHeight) return false;
891
- // Put the hat at the top left whatever its place in the code area.
892
- const {x, y} = definition.getRelativeToSurfaceXY();
893
- const padding = 16;
894
- editor.scrollbar.set(x * editor.scale - metrics.contentLeft - padding,
895
- y * editor.scale - metrics.contentTop - padding);
896
- return true;
880
+ return fitScriptInWorkspace(editor, definitionId, blocks);
897
881
  }
898
882
  function load() {
899
883
  if (!exists() || !target.blocks._blocks[definitionId]) return;
@@ -939,7 +923,7 @@ function attachProcedureEditor({vm, blocks, workspace, options, onError, homeDoc
939
923
  return;
940
924
  }
941
925
  pendingBlock = undefined;
942
- editor.centerOnBlock(block.id);
926
+ fitScriptInWorkspace(editor, definitionId, blocks);
943
927
  block.select();
944
928
  }
945
929