@kubohiroya/turbowarp-plus-editor-code-views 0.0.0-stage → 0.2.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.
Files changed (108) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +42 -0
  3. package/README.md +41 -2
  4. package/dist/asset-edit-session.d.ts +24 -0
  5. package/dist/asset-edit-session.js +58 -0
  6. package/dist/block-argument-text.d.ts +39 -0
  7. package/dist/block-argument-text.js +170 -0
  8. package/dist/block-drag.d.ts +17 -0
  9. package/dist/block-drag.js +184 -0
  10. package/dist/code-extensions.d.ts +38 -0
  11. package/dist/code-extensions.js +418 -0
  12. package/dist/code-pane.d.ts +80 -0
  13. package/dist/code-pane.js +398 -0
  14. package/dist/custom-extension-fields.d.ts +45 -0
  15. package/dist/custom-extension-fields.js +144 -0
  16. package/dist/detached-block-palette-view.d.ts +10 -0
  17. package/dist/detached-block-palette-view.js +62 -0
  18. package/dist/detached-block-palette.d.ts +41 -0
  19. package/dist/detached-block-palette.js +197 -0
  20. package/dist/dockview-unsaved.d.ts +45 -0
  21. package/dist/dockview-unsaved.js +123 -0
  22. package/dist/history.d.ts +57 -0
  23. package/dist/history.js +85 -0
  24. package/dist/index.d.ts +28 -0
  25. package/dist/index.js +729 -0
  26. package/dist/native-extension-field.d.ts +26 -0
  27. package/dist/native-extension-field.js +204 -0
  28. package/dist/native-field-svg.d.ts +20 -0
  29. package/dist/native-field-svg.js +156 -0
  30. package/dist/palette-category-reorder.d.ts +4 -0
  31. package/dist/palette-category-reorder.js +167 -0
  32. package/dist/palette-category-search.d.ts +26 -0
  33. package/dist/palette-category-search.js +74 -0
  34. package/dist/palette-dropdown-resize.d.ts +19 -0
  35. package/dist/palette-dropdown-resize.js +135 -0
  36. package/dist/parent-field-layout.d.ts +2 -0
  37. package/dist/parent-field-layout.js +90 -0
  38. package/dist/parent-field-mirror.d.ts +3 -0
  39. package/dist/parent-field-mirror.js +290 -0
  40. package/dist/parent-field-resources.d.ts +9 -0
  41. package/dist/parent-field-resources.js +199 -0
  42. package/dist/preview-chrome.d.ts +9 -0
  43. package/dist/preview-chrome.js +78 -0
  44. package/dist/procedure-editor.d.ts +9 -0
  45. package/dist/procedure-editor.js +122 -0
  46. package/dist/procedure-edits.d.ts +16 -0
  47. package/dist/procedure-edits.js +47 -0
  48. package/dist/programmatic-extension-field.d.ts +20 -0
  49. package/dist/programmatic-extension-field.js +69 -0
  50. package/dist/protocol.d.ts +15 -0
  51. package/dist/protocol.js +36 -0
  52. package/dist/script-layout-dialog.d.ts +10 -0
  53. package/dist/script-layout-dialog.js +93 -0
  54. package/dist/script-layout-view.d.ts +68 -0
  55. package/dist/script-layout-view.js +164 -0
  56. package/dist/script-layout-workspace.d.ts +45 -0
  57. package/dist/script-layout-workspace.js +55 -0
  58. package/dist/script-layout.d.ts +17 -0
  59. package/dist/script-layout.js +25 -0
  60. package/dist/script-view-menu.d.ts +46 -0
  61. package/dist/script-view-menu.js +161 -0
  62. package/dist/sprite-code-windows.d.ts +32 -0
  63. package/dist/sprite-code-windows.js +180 -0
  64. package/dist/stage-code-prewarm.d.ts +52 -0
  65. package/dist/stage-code-prewarm.js +216 -0
  66. package/dist/target-combobox.d.ts +10 -0
  67. package/dist/target-combobox.js +92 -0
  68. package/dist/variable-references.d.ts +1 -0
  69. package/dist/variable-references.js +87 -0
  70. package/dist/workspace.d.ts +104 -0
  71. package/dist/workspace.js +1102 -0
  72. package/package.json +100 -4
  73. package/src/asset-edit-session.ts +72 -0
  74. package/src/block-argument-text.ts +172 -0
  75. package/src/block-drag.ts +190 -0
  76. package/src/code-extensions.ts +394 -0
  77. package/src/code-pane.ts +393 -0
  78. package/src/custom-extension-fields.ts +154 -0
  79. package/src/detached-block-palette-view.tsx +97 -0
  80. package/src/detached-block-palette.ts +218 -0
  81. package/src/dockview-unsaved.ts +134 -0
  82. package/src/history.ts +114 -0
  83. package/src/index.ts +680 -0
  84. package/src/native-extension-field.ts +201 -0
  85. package/src/native-field-svg.ts +140 -0
  86. package/src/palette-category-reorder.ts +155 -0
  87. package/src/palette-category-search.ts +82 -0
  88. package/src/palette-dropdown-resize.ts +132 -0
  89. package/src/parent-field-layout.ts +88 -0
  90. package/src/parent-field-mirror.ts +260 -0
  91. package/src/parent-field-resources.ts +179 -0
  92. package/src/preview-chrome.ts +82 -0
  93. package/src/procedure-editor.ts +123 -0
  94. package/src/procedure-edits.ts +46 -0
  95. package/src/programmatic-extension-field.ts +76 -0
  96. package/src/protocol.ts +47 -0
  97. package/src/script-layout-dialog.ts +104 -0
  98. package/src/script-layout-view.ts +198 -0
  99. package/src/script-layout-workspace.ts +95 -0
  100. package/src/script-layout.ts +40 -0
  101. package/src/script-view-menu.ts +213 -0
  102. package/src/sprite-code-windows.tsx +183 -0
  103. package/src/stage-code-prewarm.ts +242 -0
  104. package/src/styles.css +595 -0
  105. package/src/target-combobox.tsx +106 -0
  106. package/src/variable-references.ts +85 -0
  107. package/src/workspace.ts +1125 -0
  108. package/tsconfig.json +23 -0
@@ -0,0 +1,93 @@
1
+ import { arrangeScripts } from "./script-layout.js";
2
+ import { moveScripts, paintScripts, readScripts } from "./script-layout-workspace.js";
3
+ export function openRearrangement({ workspace, events, canArrange, target }, locale) {
4
+ const document = workspace.getInjectionDiv().ownerDocument;
5
+ const ja = /^ja(?:-|$)/i.test(locale);
6
+ const translate = (en, japanese) => ja ? japanese : en;
7
+ events.fireNow_();
8
+ const originalTarget = target();
9
+ const scripts = readScripts(workspace);
10
+ const dialog = document.createElement('dialog');
11
+ dialog.className = 'tw-script-layout-dialog';
12
+ dialog.setAttribute('aria-label', translate('Rearrange Code Blocks', 'コードブロックの再配置'));
13
+ const title = document.createElement('h2');
14
+ title.textContent = dialog.getAttribute('aria-label');
15
+ const controls = document.createElement('div');
16
+ controls.className = 'tw-script-layout-options';
17
+ const preview = document.createElement('div');
18
+ preview.className = 'tw-script-layout-preview';
19
+ preview.tabIndex = 0;
20
+ preview.setAttribute('aria-label', translate('Layout preview', '再配置のプレビュー'));
21
+ const footer = document.createElement('footer');
22
+ footer.className = 'tw-plus-dialog-actions';
23
+ const status = document.createElement('p');
24
+ status.setAttribute('role', 'status');
25
+ const cancel = document.createElement('button');
26
+ cancel.textContent = translate('Cancel', 'キャンセル');
27
+ const apply = document.createElement('button');
28
+ apply.textContent = translate('Rearrange', '再配置する');
29
+ const order = select(translate('Order', '順序'), [
30
+ ['z', translate('Z · by row', 'Z方式(行順)')], ['n', translate('N · by column', 'N方式(列順)')]
31
+ ]);
32
+ const direction = select(translate('Direction', '方向'), [
33
+ ['vertical', translate('Vertical', '垂直')], ['horizontal', translate('Horizontal', '水平')]
34
+ ]);
35
+ let placements;
36
+ function select(label, choices) {
37
+ const field = document.createElement('label');
38
+ field.textContent = label;
39
+ const input = document.createElement('select');
40
+ for (const [value, text] of choices) {
41
+ const option = document.createElement('option');
42
+ option.value = value;
43
+ option.textContent = text;
44
+ input.append(option);
45
+ }
46
+ input.addEventListener('change', update);
47
+ field.append(input);
48
+ controls.append(field);
49
+ return input;
50
+ }
51
+ function update() {
52
+ placements = arrangeScripts(scripts, order.value, direction.value);
53
+ paintScripts(preview, placements, 0.8);
54
+ preview.scrollTo(0, 0);
55
+ apply.disabled = scripts.length === 0;
56
+ status.textContent = scripts.length ? '' : translate('There are no scripts to rearrange.', '再配置するスクリプトがありません。');
57
+ }
58
+ function close() {
59
+ if (dialog.open)
60
+ dialog.close();
61
+ dialog.remove();
62
+ }
63
+ cancel.addEventListener('click', close);
64
+ dialog.addEventListener('close', close, { once: true });
65
+ dialog.addEventListener('keydown', event => event.stopPropagation());
66
+ apply.addEventListener('click', () => {
67
+ events.fireNow_();
68
+ const current = readScripts(workspace);
69
+ if (!canArrange() || target() !== originalTarget || current.length !== scripts.length ||
70
+ current.some(({ block, x, y, width, height }, i) => {
71
+ const original = scripts[i];
72
+ return block !== original.block || x !== original.x || y !== original.y ||
73
+ width !== original.width || height !== original.height;
74
+ })) {
75
+ status.textContent = translate('The code changed. Reopen this dialog to preview it again.', 'コードが変わりました。ダイアログを開き直して再度プレビューしてください。');
76
+ apply.disabled = true;
77
+ return;
78
+ }
79
+ moveScripts(workspace, events, placements);
80
+ close();
81
+ if (placements.length)
82
+ workspace.centerOnBlock(placements[0].script.id);
83
+ });
84
+ cancel.dataset.dialogAction = 'cancel';
85
+ apply.dataset.dialogAction = 'confirm';
86
+ footer.append(status, cancel, apply);
87
+ dialog.append(title, controls, preview, footer);
88
+ document.body.append(dialog);
89
+ update();
90
+ dialog.showModal();
91
+ order.focus();
92
+ return { close };
93
+ }
@@ -0,0 +1,68 @@
1
+ import { type LayoutWorkspace } from './script-layout-workspace.ts';
2
+ import { type RearrangementContext } from './script-layout-dialog.ts';
3
+ import { type ScriptViewMenuBlocks, type ScriptViewMenuWorkspace } from './script-view-menu.ts';
4
+ import type { PresentationElements } from './preview-chrome.ts';
5
+ export type ScriptView = 'free' | 'z' | 'n';
6
+ interface ViewOptions {
7
+ workspace: LayoutWorkspace & ScriptViewMenuWorkspace;
8
+ ScratchBlocks: ScriptViewMenuBlocks;
9
+ getLocale(): string;
10
+ mount?: HTMLElement;
11
+ initialView?: ScriptView;
12
+ canShowBlock?(): boolean;
13
+ onChange?(view: ScriptView): void;
14
+ hasWorkspaceMenu?(): boolean;
15
+ }
16
+ export declare function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, initialView, canShowBlock, onChange, hasWorkspaceMenu }: ViewOptions): {
17
+ update: () => void;
18
+ labels: () => void;
19
+ readonly view: ScriptView;
20
+ setView: (next: ScriptView) => void;
21
+ dispose(): void;
22
+ };
23
+ interface DockedScriptLayoutOptions {
24
+ vm: {
25
+ editingTarget?: object;
26
+ runtime?: {
27
+ getEditingTarget(): unknown;
28
+ };
29
+ };
30
+ workspace: LayoutWorkspace & ScriptViewMenuWorkspace & {
31
+ options: {
32
+ readOnly: boolean;
33
+ };
34
+ };
35
+ ScratchBlocks: ScriptViewMenuBlocks & {
36
+ Events: RearrangementContext['events'];
37
+ getMainWorkspace(): unknown;
38
+ };
39
+ canUse(): boolean;
40
+ locale: string;
41
+ /** The host's elements around the workspace. Without them, the workspace's own element is the surface. */
42
+ presentationElements?: PresentationElements | null;
43
+ }
44
+ export declare function getDockedScriptLayout(vm: object): {
45
+ view: {
46
+ update: () => void;
47
+ labels: () => void;
48
+ readonly view: ScriptView;
49
+ setView: (next: ScriptView) => void;
50
+ dispose(): void;
51
+ };
52
+ canArrange: () => boolean;
53
+ open(locale: string): void;
54
+ dispose(): void;
55
+ };
56
+ export declare function attachDockedScriptLayout({ vm, workspace, ScratchBlocks, canUse, locale, presentationElements }: DockedScriptLayoutOptions): {
57
+ view: {
58
+ update: () => void;
59
+ labels: () => void;
60
+ readonly view: ScriptView;
61
+ setView: (next: ScriptView) => void;
62
+ dispose(): void;
63
+ };
64
+ canArrange: () => boolean;
65
+ open(locale: string): void;
66
+ dispose(): void;
67
+ };
68
+ export {};
@@ -0,0 +1,164 @@
1
+ import { arrangeScripts } from "./script-layout.js";
2
+ import { paintScripts, readScripts } from "./script-layout-workspace.js";
3
+ import { openRearrangement } from "./script-layout-dialog.js";
4
+ import { attachScriptViewMenu } from "./script-view-menu.js";
5
+ const choices = [
6
+ { view: 'free', label: 'Normal layout view', jaLabel: '通常配置の見え方' },
7
+ { view: 'z', label: 'Z layout view', jaLabel: 'Z配置の見え方' },
8
+ { view: 'n', label: 'N layout view', jaLabel: 'N配置の見え方' }
9
+ ];
10
+ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, initialView = 'free', canShowBlock, onChange, hasWorkspaceMenu = () => true }) {
11
+ const injection = workspace.getInjectionDiv();
12
+ const host = mount ?? injection;
13
+ const document = host.ownerDocument;
14
+ const window = document.defaultView;
15
+ const surface = document.createElement('div');
16
+ surface.className = 'tw-script-view-surface';
17
+ surface.dataset.codeViewControl = '';
18
+ surface.tabIndex = 0;
19
+ surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock));
20
+ const contents = document.createElement('div');
21
+ surface.append(contents);
22
+ let view = initialView;
23
+ let frame;
24
+ const svg = workspace.getParentSvg();
25
+ const observer = new window.MutationObserver(update);
26
+ const japanese = () => /^ja(?:-|$)/i.test(getLocale());
27
+ function labels() {
28
+ const choice = choices.find(choice => choice.view === view);
29
+ surface.setAttribute('aria-label', japanese() ? choice.jaLabel : choice.label);
30
+ }
31
+ const menu = attachScriptViewMenu(ScratchBlocks, workspace, host, surface, target => view === 'free' ? !hasWorkspaceMenu() && (target === host || target.closest('.blocklyMainBackground') !== null) :
32
+ surface.contains(target) && !target.closest('[data-script-view-block]'), () => {
33
+ const ja = japanese();
34
+ return {
35
+ label: ja ? 'コードの並びの見え方を変更する' : 'Change code layout view',
36
+ choices: choices.map(choice => ({
37
+ text: ja ? choice.jaLabel : choice.label,
38
+ enabled: true,
39
+ checked: choice.view === view,
40
+ callback: () => chooseView(choice.view)
41
+ }))
42
+ };
43
+ });
44
+ function render() {
45
+ frame = undefined;
46
+ labels();
47
+ if (view === 'free')
48
+ return;
49
+ const { left, right, top } = svg.getBoundingClientRect();
50
+ const toolbox = injection.querySelector(':scope > .blocklyToolboxDiv');
51
+ if (toolbox) {
52
+ const bounds = toolbox.getBoundingClientRect();
53
+ const horizontal = toolbox.hasAttribute('data-horizontal-block-palette');
54
+ surface.style.setProperty('--tw-script-view-top', horizontal ? `${Math.max(0, bounds.bottom - top)}px` : '0px');
55
+ surface.style.setProperty('--tw-script-view-left', !horizontal && bounds.left <= left + 2 ? `${bounds.width}px` : '0px');
56
+ surface.style.setProperty('--tw-script-view-right', !horizontal && bounds.right >= right - 2 ? `${bounds.width}px` : '0px');
57
+ }
58
+ paintScripts(contents, arrangeScripts(readScripts(workspace), view, 'vertical'), workspace.scale || 1);
59
+ }
60
+ function update() {
61
+ if (view === 'free' || frame !== undefined)
62
+ return;
63
+ frame = window.requestAnimationFrame(render);
64
+ }
65
+ function setView(next) {
66
+ menu.close();
67
+ observer.disconnect();
68
+ view = next;
69
+ surface.hidden = view === 'free';
70
+ svg.toggleAttribute('data-script-serial', view !== 'free');
71
+ labels();
72
+ if (view === 'free')
73
+ contents.replaceChildren();
74
+ else {
75
+ observer.observe(workspace.getCanvas(), { attributes: true, childList: true, subtree: true });
76
+ surface.scrollTo(0, 0);
77
+ update();
78
+ }
79
+ }
80
+ function chooseView(next) {
81
+ setView(next);
82
+ onChange?.(next);
83
+ }
84
+ surface.addEventListener('click', event => {
85
+ event.stopPropagation();
86
+ const id = event.target.closest('[data-script-view-block]')?.getAttribute('data-script-view-block');
87
+ if (!id || !canShowBlock?.())
88
+ return;
89
+ chooseView('free');
90
+ workspace.centerOnBlock(id);
91
+ });
92
+ const resize = new window.ResizeObserver(update);
93
+ resize.observe(host);
94
+ const language = new window.MutationObserver(labels);
95
+ language.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'] });
96
+ // The Blockly keyboard listener is document-wide.
97
+ surface.addEventListener('keydown', event => {
98
+ if (event.key !== 'Tab')
99
+ event.stopPropagation();
100
+ });
101
+ host.append(surface);
102
+ setView(initialView);
103
+ return {
104
+ update,
105
+ labels,
106
+ get view() { return view; },
107
+ setView,
108
+ dispose() {
109
+ resize.disconnect();
110
+ observer.disconnect();
111
+ language.disconnect();
112
+ if (frame !== undefined)
113
+ window.cancelAnimationFrame(frame);
114
+ menu.dispose();
115
+ surface.remove();
116
+ svg.removeAttribute('data-script-serial');
117
+ }
118
+ };
119
+ }
120
+ const dockedViews = new WeakMap();
121
+ export function getDockedScriptLayout(vm) {
122
+ return dockedViews.get(vm);
123
+ }
124
+ export function attachDockedScriptLayout({ vm, workspace, ScratchBlocks, canUse, locale, presentationElements }) {
125
+ const injection = workspace.getInjectionDiv();
126
+ const { wrapper, extensionButton, watermark } = presentationElements?.(injection) ?? {};
127
+ const host = wrapper?.parentElement ?? injection;
128
+ // The stylesheet hides these on a hover surface and in an inactive split view by these marks.
129
+ watermark?.setAttribute('data-code-watermark', '');
130
+ extensionButton?.setAttribute('data-code-extension-button', '');
131
+ const canArrange = () => {
132
+ const group = host.closest('.dv-groupview');
133
+ // The last sprite's workspace can stay visible when a stage or document group is active.
134
+ return Boolean(vm.editingTarget && vm.runtime?.getEditingTarget() === vm.editingTarget &&
135
+ canUse() && workspace.isVisible() && !workspace.isDragging() && !workspace.options.readOnly &&
136
+ ScratchBlocks.getMainWorkspace() === workspace && !host.closest('[hidden], [inert]') &&
137
+ (!group || group.classList.contains('dv-active-group')));
138
+ };
139
+ const view = attachScriptView({ workspace, ScratchBlocks, getLocale: () => injection.ownerDocument.documentElement.lang || locale,
140
+ canShowBlock: canArrange });
141
+ host.setAttribute('data-code-hover-surface', '');
142
+ let dialog;
143
+ const attachment = {
144
+ view,
145
+ canArrange,
146
+ open(locale) {
147
+ if (!canArrange())
148
+ return;
149
+ dialog?.close();
150
+ dialog = openRearrangement({ workspace, events: ScratchBlocks.Events, canArrange, target: () => vm.editingTarget }, locale);
151
+ },
152
+ dispose() {
153
+ dialog?.close();
154
+ view.dispose();
155
+ host.removeAttribute('data-code-hover-surface');
156
+ watermark?.removeAttribute('data-code-watermark');
157
+ extensionButton?.removeAttribute('data-code-extension-button');
158
+ if (dockedViews.get(vm) === attachment)
159
+ dockedViews.delete(vm);
160
+ }
161
+ };
162
+ dockedViews.set(vm, attachment);
163
+ return attachment;
164
+ }
@@ -0,0 +1,45 @@
1
+ import type { ScriptBounds } from './script-layout.ts';
2
+ interface Point {
3
+ x: number;
4
+ y: number;
5
+ }
6
+ export interface LayoutBlock {
7
+ id: string;
8
+ getRelativeToSurfaceXY(): Point;
9
+ getBoundingRectangle(): {
10
+ topLeft: Point;
11
+ bottomRight: Point;
12
+ };
13
+ getSvgRoot(): SVGElement | null;
14
+ moveBy(dx: number, dy: number): void;
15
+ }
16
+ export interface LayoutWorkspace {
17
+ getTopBlocks(ordered: boolean): LayoutBlock[];
18
+ getInjectionDiv(): HTMLElement;
19
+ getParentSvg(): SVGElement;
20
+ getCanvas(): SVGElement;
21
+ isDragging(): boolean;
22
+ isVisible(): boolean;
23
+ setResizesEnabled(enabled: boolean): void;
24
+ centerOnBlock(id: string): void;
25
+ scale: number;
26
+ }
27
+ export interface LayoutEvents {
28
+ getGroup(): string;
29
+ setGroup(group: string | boolean): void;
30
+ fireNow_(): void;
31
+ }
32
+ export interface RenderedScript extends ScriptBounds {
33
+ block: LayoutBlock;
34
+ origin: Point;
35
+ root: SVGElement;
36
+ }
37
+ export declare function readScripts(workspace: LayoutWorkspace): RenderedScript[];
38
+ type Placement = {
39
+ script: RenderedScript;
40
+ x: number;
41
+ y: number;
42
+ };
43
+ export declare function moveScripts(workspace: LayoutWorkspace, events: LayoutEvents, placements: Placement[]): void;
44
+ export declare function paintScripts(element: HTMLElement, placements: Placement[], scale: number): void;
45
+ export {};
@@ -0,0 +1,55 @@
1
+ export function readScripts(workspace) {
2
+ return workspace.getTopBlocks(false).flatMap(block => {
3
+ const root = block.getSvgRoot();
4
+ if (!root || !workspace.getCanvas().contains(root))
5
+ return [];
6
+ const origin = block.getRelativeToSurfaceXY();
7
+ const { topLeft, bottomRight } = block.getBoundingRectangle();
8
+ return [{
9
+ id: block.id, block, root, origin, ...topLeft,
10
+ width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y
11
+ }];
12
+ });
13
+ }
14
+ export function moveScripts(workspace, events, placements) {
15
+ const group = events.getGroup();
16
+ events.setGroup(true);
17
+ workspace.setResizesEnabled(false);
18
+ try {
19
+ for (const { script, x, y } of placements) {
20
+ const dx = x - script.x;
21
+ const dy = y - script.y;
22
+ if (dx || dy)
23
+ script.block.moveBy(dx, dy);
24
+ }
25
+ }
26
+ finally {
27
+ events.setGroup(group);
28
+ workspace.setResizesEnabled(true);
29
+ }
30
+ events.fireNow_();
31
+ }
32
+ export function paintScripts(element, placements, scale) {
33
+ const document = element.ownerDocument;
34
+ const ns = 'http://www.w3.org/2000/svg';
35
+ const svg = document.createElementNS(ns, 'svg');
36
+ svg.setAttribute('class', 'tw-script-layout-svg');
37
+ svg.setAttribute('aria-hidden', 'true');
38
+ const width = placements.reduce((edge, { script, x }) => Math.max(edge, x + script.width), 0) + 32;
39
+ const height = placements.reduce((edge, { script, y }) => Math.max(edge, y + script.height), 0) + 32;
40
+ svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
41
+ svg.setAttribute('width', String(Math.ceil(width * scale)));
42
+ svg.setAttribute('height', String(Math.ceil(height * scale)));
43
+ for (const { script, x, y } of placements) {
44
+ const clone = script.root.cloneNode(true);
45
+ clone.style.removeProperty('display');
46
+ clone.removeAttribute('id');
47
+ clone.querySelectorAll('[id]').forEach(node => node.removeAttribute('id'));
48
+ clone.classList.remove('blocklySelected', 'blocklyDragging');
49
+ // The original block owns its fields and all native editing handlers.
50
+ clone.setAttribute('data-script-view-block', script.id);
51
+ clone.setAttribute('transform', `translate(${x + script.origin.x - script.x} ${y + script.origin.y - script.y})`);
52
+ svg.append(clone);
53
+ }
54
+ element.replaceChildren(svg);
55
+ }
@@ -0,0 +1,17 @@
1
+ interface Point {
2
+ x: number;
3
+ y: number;
4
+ }
5
+ export interface ScriptBounds extends Point {
6
+ id: string;
7
+ width: number;
8
+ height: number;
9
+ }
10
+ export type ScriptOrder = 'z' | 'n';
11
+ export type LayoutDirection = 'vertical' | 'horizontal';
12
+ export declare function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection): {
13
+ script: T;
14
+ x: number;
15
+ y: number;
16
+ }[];
17
+ export {};
@@ -0,0 +1,25 @@
1
+ const alignmentTolerance = 24;
2
+ const spacing = 32;
3
+ export function arrangeScripts(scripts, order, direction) {
4
+ const bandAxis = order === 'z' ? 'y' : 'x';
5
+ const scanAxis = order === 'z' ? 'x' : 'y';
6
+ const compare = (a, b, first, second) => a[first] - b[first] || a[second] - b[second] || (a.id < b.id ? -1 : Number(a.id > b.id));
7
+ const ordered = [...scripts].sort((a, b) => compare(a, b, bandAxis, scanAxis));
8
+ const bands = [];
9
+ for (const script of ordered) {
10
+ const band = bands.at(-1);
11
+ // Measure each band from its first script so small offsets cannot chain across rows or columns.
12
+ if (band && script[bandAxis] - band[0][bandAxis] <= alignmentTolerance)
13
+ band.push(script);
14
+ else
15
+ bands.push([script]);
16
+ }
17
+ let offset = spacing;
18
+ return bands.flatMap(band => band.sort((a, b) => compare(a, b, scanAxis, bandAxis))).map(script => {
19
+ const vertical = direction === 'vertical';
20
+ const x = vertical ? spacing : offset;
21
+ const y = vertical ? offset : spacing;
22
+ offset += Math.ceil(vertical ? script.height : script.width) + spacing;
23
+ return { script, x, y };
24
+ });
25
+ }
@@ -0,0 +1,46 @@
1
+ interface MenuOption {
2
+ text: string | Node[];
3
+ enabled: boolean;
4
+ callback(): void;
5
+ }
6
+ interface MenuItem {
7
+ getElement(): HTMLElement;
8
+ setCheckable(checkable: boolean): void;
9
+ setChecked(checked: boolean): void;
10
+ performActionInternal(): boolean;
11
+ handleContextMenu(): void;
12
+ }
13
+ interface Menu {
14
+ getElement(): HTMLElement;
15
+ getChildAt(index: number): MenuItem;
16
+ setHighlightedIndex(index: number): void;
17
+ dispose(): void;
18
+ }
19
+ export interface ScriptViewMenuBlocks {
20
+ ContextMenu: {
21
+ populate_(options: MenuOption[], rtl: boolean): Menu;
22
+ position_(menu: Menu, event: MouseEvent, rtl: boolean): void;
23
+ createWidget_(menu: Menu): void;
24
+ };
25
+ WidgetDiv: {
26
+ DIV: HTMLElement;
27
+ dispose_: (() => void) | null;
28
+ show(owner: object, rtl: boolean, dispose: () => void): void;
29
+ hideIfOwner(owner: object): void;
30
+ };
31
+ }
32
+ export interface ScriptViewMenuWorkspace {
33
+ RTL: boolean;
34
+ showContextMenu_(event: MouseEvent): void;
35
+ }
36
+ interface MenuConfig {
37
+ label: string;
38
+ choices: (MenuOption & {
39
+ checked: boolean;
40
+ })[];
41
+ }
42
+ export declare function attachScriptViewMenu({ ContextMenu, WidgetDiv }: ScriptViewMenuBlocks, workspace: ScriptViewMenuWorkspace, host: HTMLElement, surface: HTMLElement, isBackground: (target: Element) => boolean, getMenu: () => MenuConfig): {
43
+ close(): void;
44
+ dispose(): void;
45
+ };
46
+ export {};
@@ -0,0 +1,161 @@
1
+ export function attachScriptViewMenu({ ContextMenu, WidgetDiv }, workspace, host, surface, isBackground, getMenu) {
2
+ const document = host.ownerDocument;
3
+ let closeMenu;
4
+ function addSubmenu(menu, index, { label, choices }, rtl, owner) {
5
+ const root = menu.getElement();
6
+ const item = menu.getChildAt(index);
7
+ const trigger = item.getElement();
8
+ trigger.setAttribute('aria-haspopup', 'menu');
9
+ trigger.setAttribute('aria-expanded', 'false');
10
+ const nextKey = rtl ? 'ArrowLeft' : 'ArrowRight';
11
+ const backKey = rtl ? 'ArrowRight' : 'ArrowLeft';
12
+ let submenu;
13
+ const close = () => WidgetDiv.hideIfOwner(owner);
14
+ function closeSubmenu(restoreFocus = false) {
15
+ if (!submenu)
16
+ return;
17
+ const hadFocus = submenu.getElement().contains(document.activeElement);
18
+ submenu.dispose();
19
+ submenu = undefined;
20
+ trigger.setAttribute('aria-expanded', 'false');
21
+ if (restoreFocus && hadFocus)
22
+ root.focus();
23
+ }
24
+ function openSubmenu(focus) {
25
+ if (!submenu) {
26
+ submenu = ContextMenu.populate_(choices.map(choice => ({
27
+ ...choice,
28
+ callback() {
29
+ close();
30
+ choice.callback();
31
+ }
32
+ })), rtl);
33
+ ContextMenu.createWidget_(submenu);
34
+ choices.forEach(({ checked }, choiceIndex) => {
35
+ const option = submenu.getChildAt(choiceIndex);
36
+ option.setCheckable(true);
37
+ option.setChecked(checked);
38
+ const element = option.getElement();
39
+ element.setAttribute('role', 'menuitemradio');
40
+ element.setAttribute('aria-checked', String(checked));
41
+ });
42
+ const popup = submenu.getElement();
43
+ popup.classList.add('tw-script-view-submenu');
44
+ popup.setAttribute('aria-label', label);
45
+ const { clientWidth, clientHeight } = document.documentElement;
46
+ const { width, height } = popup.getBoundingClientRect();
47
+ const { left, right } = root.getBoundingClientRect();
48
+ const { top } = trigger.getBoundingClientRect();
49
+ const placeLeft = rtl ? left >= width : right + width > clientWidth && left >= width;
50
+ const x = placeLeft ? left - width + 1 : right - 1;
51
+ popup.style.left = `${Math.max(0, Math.min(x, clientWidth - width))}px`;
52
+ popup.style.top = `${Math.max(0, Math.min(top, clientHeight - height))}px`;
53
+ popup.addEventListener('keydown', event => {
54
+ if (event.key !== backKey && event.key !== 'Escape')
55
+ return;
56
+ event.preventDefault();
57
+ event.stopPropagation();
58
+ closeSubmenu(true);
59
+ }, true);
60
+ trigger.setAttribute('aria-expanded', 'true');
61
+ }
62
+ if (focus) {
63
+ submenu.getElement().focus();
64
+ submenu.setHighlightedIndex(choices.findIndex(choice => choice.checked));
65
+ }
66
+ }
67
+ trigger.addEventListener('pointerenter', () => openSubmenu(false));
68
+ root.addEventListener('pointerover', event => {
69
+ if (!trigger.contains(event.target))
70
+ closeSubmenu(true);
71
+ });
72
+ root.addEventListener('keydown', event => {
73
+ if (event.key === nextKey && trigger.contains(document.getElementById(root.getAttribute('aria-activedescendant')))) {
74
+ event.preventDefault();
75
+ event.stopPropagation();
76
+ openSubmenu(true);
77
+ }
78
+ else if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {
79
+ closeSubmenu();
80
+ }
81
+ else if (event.key === 'Escape' || event.key === 'Tab') {
82
+ close();
83
+ }
84
+ }, true);
85
+ item.performActionInternal = () => {
86
+ openSubmenu(true);
87
+ return true;
88
+ };
89
+ item.handleContextMenu = () => { };
90
+ closeMenu = close;
91
+ const dispose = WidgetDiv.dispose_;
92
+ WidgetDiv.dispose_ = () => {
93
+ closeSubmenu();
94
+ if (closeMenu === close)
95
+ closeMenu = undefined;
96
+ dispose?.();
97
+ };
98
+ }
99
+ function triggerOption(label) {
100
+ const arrow = document.createElement('span');
101
+ arrow.className = 'tw-script-view-menu-arrow';
102
+ arrow.setAttribute('aria-hidden', 'true');
103
+ return { text: [document.createTextNode(label), arrow], enabled: true, callback() { } };
104
+ }
105
+ const showContextMenu = workspace.showContextMenu_;
106
+ workspace.showContextMenu_ = function (event) {
107
+ const populate = ContextMenu.populate_;
108
+ // Only extend the options collected for this workspace, after the existing add-ons.
109
+ ContextMenu.populate_ = (options, rtl) => {
110
+ const config = getMenu();
111
+ const menu = populate.call(ContextMenu, [...options, triggerOption(config.label)], rtl);
112
+ addSubmenu(menu, options.length, config, rtl, ContextMenu);
113
+ return menu;
114
+ };
115
+ try {
116
+ showContextMenu.call(this, event);
117
+ }
118
+ finally {
119
+ ContextMenu.populate_ = populate;
120
+ }
121
+ };
122
+ function showStandaloneMenu(event) {
123
+ if (!isBackground(event.target))
124
+ return;
125
+ event.preventDefault();
126
+ event.stopPropagation();
127
+ const config = getMenu();
128
+ const rtl = workspace.RTL;
129
+ const menu = ContextMenu.populate_([triggerOption(config.label)], rtl);
130
+ const outside = new document.defaultView.AbortController();
131
+ WidgetDiv.show(surface, rtl, () => {
132
+ outside.abort();
133
+ menu.dispose();
134
+ });
135
+ addSubmenu(menu, 0, config, rtl, surface);
136
+ ContextMenu.position_(menu, event, rtl);
137
+ document.addEventListener('pointerdown', event => {
138
+ if (!WidgetDiv.DIV.contains(event.target))
139
+ WidgetDiv.hideIfOwner(surface);
140
+ }, { capture: true, signal: outside.signal });
141
+ }
142
+ function keepPreviewInactive(event) {
143
+ // Focusing a background pane on pointerdown would replace its preview before contextmenu.
144
+ if ((event.button === 2 || (event.button === 0 && event.ctrlKey)) && isBackground(event.target)) {
145
+ event.preventDefault();
146
+ }
147
+ }
148
+ host.addEventListener('pointerdown', keepPreviewInactive);
149
+ host.addEventListener('contextmenu', showStandaloneMenu);
150
+ return {
151
+ close() {
152
+ closeMenu?.();
153
+ },
154
+ dispose() {
155
+ closeMenu?.();
156
+ workspace.showContextMenu_ = showContextMenu;
157
+ host.removeEventListener('pointerdown', keepPreviewInactive);
158
+ host.removeEventListener('contextmenu', showStandaloneMenu);
159
+ }
160
+ };
161
+ }