@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,198 @@
1
+ import {arrangeScripts} from './script-layout.ts';
2
+ import {paintScripts, readScripts, type LayoutWorkspace} from './script-layout-workspace.ts';
3
+ import {openRearrangement, type RearrangementContext} from './script-layout-dialog.ts';
4
+ import {attachScriptViewMenu, type ScriptViewMenuBlocks, type ScriptViewMenuWorkspace} from './script-view-menu.ts';
5
+ import type {PresentationElements} from './preview-chrome.ts';
6
+
7
+ export type ScriptView = 'free' | 'z' | 'n';
8
+
9
+ interface ViewOptions {
10
+ workspace: LayoutWorkspace & ScriptViewMenuWorkspace;
11
+ ScratchBlocks: ScriptViewMenuBlocks;
12
+ getLocale(): string;
13
+ mount?: HTMLElement;
14
+ initialView?: ScriptView;
15
+ canShowBlock?(): boolean;
16
+ onChange?(view: ScriptView): void;
17
+ hasWorkspaceMenu?(): boolean;
18
+ }
19
+
20
+ const choices = [
21
+ {view: 'free', label: 'Normal layout view', jaLabel: '通常配置の見え方'},
22
+ {view: 'z', label: 'Z layout view', jaLabel: 'Z配置の見え方'},
23
+ {view: 'n', label: 'N layout view', jaLabel: 'N配置の見え方'}
24
+ ] as const;
25
+
26
+ export function attachScriptView({
27
+ workspace, ScratchBlocks, getLocale, mount, initialView = 'free', canShowBlock, onChange, hasWorkspaceMenu = () => true
28
+ }: ViewOptions) {
29
+ const injection = workspace.getInjectionDiv();
30
+ const host = mount ?? injection;
31
+ const document = host.ownerDocument;
32
+ const window = document.defaultView;
33
+ const surface = document.createElement('div');
34
+ surface.className = 'tw-script-view-surface';
35
+ surface.dataset.codeViewControl = '';
36
+ surface.tabIndex = 0;
37
+ surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock));
38
+ const contents = document.createElement('div');
39
+ surface.append(contents);
40
+ let view = initialView;
41
+ let frame: number | undefined;
42
+ const svg = workspace.getParentSvg();
43
+ const observer = new window.MutationObserver(update);
44
+ const japanese = () => /^ja(?:-|$)/i.test(getLocale());
45
+
46
+ function labels() {
47
+ const choice = choices.find(choice => choice.view === view);
48
+ surface.setAttribute('aria-label', japanese() ? choice.jaLabel : choice.label);
49
+ }
50
+
51
+ const menu = attachScriptViewMenu(ScratchBlocks, workspace, host, surface, target =>
52
+ view === 'free' ? !hasWorkspaceMenu() && (target === host || target.closest('.blocklyMainBackground') !== null) :
53
+ surface.contains(target) && !target.closest('[data-script-view-block]'),
54
+ () => {
55
+ const ja = japanese();
56
+ return {
57
+ label: ja ? 'コードの並びの見え方を変更する' : 'Change code layout view',
58
+ choices: choices.map(choice => ({
59
+ text: ja ? choice.jaLabel : choice.label,
60
+ enabled: true,
61
+ checked: choice.view === view,
62
+ callback: () => chooseView(choice.view)
63
+ }))
64
+ };
65
+ });
66
+
67
+ function render() {
68
+ frame = undefined;
69
+ labels();
70
+ if (view === 'free') return;
71
+ const {left, right, top} = svg.getBoundingClientRect();
72
+ const toolbox = injection.querySelector(':scope > .blocklyToolboxDiv');
73
+ if (toolbox) {
74
+ const bounds = toolbox.getBoundingClientRect();
75
+ const horizontal = toolbox.hasAttribute('data-horizontal-block-palette');
76
+ surface.style.setProperty('--tw-script-view-top', horizontal ? `${Math.max(0, bounds.bottom - top)}px` : '0px');
77
+ surface.style.setProperty('--tw-script-view-left', !horizontal && bounds.left <= left + 2 ? `${bounds.width}px` : '0px');
78
+ surface.style.setProperty('--tw-script-view-right', !horizontal && bounds.right >= right - 2 ? `${bounds.width}px` : '0px');
79
+ }
80
+ paintScripts(contents, arrangeScripts(readScripts(workspace), view, 'vertical'), workspace.scale || 1);
81
+ }
82
+
83
+ function update() {
84
+ if (view === 'free' || frame !== undefined) return;
85
+ frame = window.requestAnimationFrame(render);
86
+ }
87
+
88
+ function setView(next: ScriptView) {
89
+ menu.close();
90
+ observer.disconnect();
91
+ view = next;
92
+ surface.hidden = view === 'free';
93
+ svg.toggleAttribute('data-script-serial', view !== 'free');
94
+ labels();
95
+ if (view === 'free') contents.replaceChildren();
96
+ else {
97
+ observer.observe(workspace.getCanvas(), {attributes: true, childList: true, subtree: true});
98
+ surface.scrollTo(0, 0);
99
+ update();
100
+ }
101
+ }
102
+
103
+ function chooseView(next: ScriptView) {
104
+ setView(next);
105
+ onChange?.(next);
106
+ }
107
+
108
+ surface.addEventListener('click', event => {
109
+ event.stopPropagation();
110
+ const id = (event.target as Element).closest('[data-script-view-block]')?.getAttribute('data-script-view-block');
111
+ if (!id || !canShowBlock?.()) return;
112
+ chooseView('free');
113
+ workspace.centerOnBlock(id);
114
+ });
115
+ const resize = new window.ResizeObserver(update);
116
+ resize.observe(host);
117
+ const language = new window.MutationObserver(labels);
118
+ language.observe(document.documentElement, {attributes: true, attributeFilter: ['lang']});
119
+ // The Blockly keyboard listener is document-wide.
120
+ surface.addEventListener('keydown', event => {
121
+ if (event.key !== 'Tab') event.stopPropagation();
122
+ });
123
+ host.append(surface);
124
+ setView(initialView);
125
+ return {
126
+ update,
127
+ labels,
128
+ get view() { return view; },
129
+ setView,
130
+ dispose() {
131
+ resize.disconnect();
132
+ observer.disconnect();
133
+ language.disconnect();
134
+ if (frame !== undefined) window.cancelAnimationFrame(frame);
135
+ menu.dispose();
136
+ surface.remove();
137
+ svg.removeAttribute('data-script-serial');
138
+ }
139
+ };
140
+ }
141
+
142
+ interface DockedScriptLayoutOptions {
143
+ vm: {editingTarget?: object; runtime?: {getEditingTarget(): unknown}};
144
+ workspace: LayoutWorkspace & ScriptViewMenuWorkspace & {
145
+ options: {readOnly: boolean};
146
+ };
147
+ ScratchBlocks: ScriptViewMenuBlocks & {Events: RearrangementContext['events']; getMainWorkspace(): unknown};
148
+ canUse(): boolean;
149
+ locale: string;
150
+ /** The host's elements around the workspace. Without them, the workspace's own element is the surface. */
151
+ presentationElements?: PresentationElements | null;
152
+ }
153
+
154
+ const dockedViews = new WeakMap<object, ReturnType<typeof attachDockedScriptLayout>>();
155
+
156
+ export function getDockedScriptLayout(vm: object) {
157
+ return dockedViews.get(vm);
158
+ }
159
+
160
+ export function attachDockedScriptLayout({vm, workspace, ScratchBlocks, canUse, locale, presentationElements}: DockedScriptLayoutOptions) {
161
+ const injection = workspace.getInjectionDiv();
162
+ const {wrapper, extensionButton, watermark} = presentationElements?.(injection) ?? {};
163
+ const host = wrapper?.parentElement ?? injection;
164
+ // The stylesheet hides these on a hover surface and in an inactive split view by these marks.
165
+ watermark?.setAttribute('data-code-watermark', '');
166
+ extensionButton?.setAttribute('data-code-extension-button', '');
167
+ const canArrange = () => {
168
+ const group = host.closest('.dv-groupview');
169
+ // The last sprite's workspace can stay visible when a stage or document group is active.
170
+ return Boolean(vm.editingTarget && vm.runtime?.getEditingTarget() === vm.editingTarget &&
171
+ canUse() && workspace.isVisible() && !workspace.isDragging() && !workspace.options.readOnly &&
172
+ ScratchBlocks.getMainWorkspace() === workspace && !host.closest('[hidden], [inert]') &&
173
+ (!group || group.classList.contains('dv-active-group')));
174
+ };
175
+ const view = attachScriptView({workspace, ScratchBlocks, getLocale: () => injection.ownerDocument.documentElement.lang || locale,
176
+ canShowBlock: canArrange});
177
+ host.setAttribute('data-code-hover-surface', '');
178
+ let dialog: ReturnType<typeof openRearrangement> | undefined;
179
+ const attachment = {
180
+ view,
181
+ canArrange,
182
+ open(locale: string) {
183
+ if (!canArrange()) return;
184
+ dialog?.close();
185
+ dialog = openRearrangement({workspace, events: ScratchBlocks.Events, canArrange, target: () => vm.editingTarget}, locale);
186
+ },
187
+ dispose() {
188
+ dialog?.close();
189
+ view.dispose();
190
+ host.removeAttribute('data-code-hover-surface');
191
+ watermark?.removeAttribute('data-code-watermark');
192
+ extensionButton?.removeAttribute('data-code-extension-button');
193
+ if (dockedViews.get(vm) === attachment) dockedViews.delete(vm);
194
+ }
195
+ };
196
+ dockedViews.set(vm, attachment);
197
+ return attachment;
198
+ }
@@ -0,0 +1,95 @@
1
+ import type {ScriptBounds} from './script-layout.ts';
2
+
3
+ interface Point {
4
+ x: number;
5
+ y: number;
6
+ }
7
+
8
+ export interface LayoutBlock {
9
+ id: string;
10
+ getRelativeToSurfaceXY(): Point;
11
+ getBoundingRectangle(): {topLeft: Point; bottomRight: Point};
12
+ getSvgRoot(): SVGElement | null;
13
+ moveBy(dx: number, dy: number): void;
14
+ }
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
+
28
+ export interface LayoutEvents {
29
+ getGroup(): string;
30
+ setGroup(group: string | boolean): void;
31
+ fireNow_(): void;
32
+ }
33
+
34
+ export interface RenderedScript extends ScriptBounds {
35
+ block: LayoutBlock;
36
+ origin: Point;
37
+ root: SVGElement;
38
+ }
39
+
40
+ export function readScripts(workspace: LayoutWorkspace): RenderedScript[] {
41
+ return workspace.getTopBlocks(false).flatMap(block => {
42
+ const root = block.getSvgRoot();
43
+ if (!root || !workspace.getCanvas().contains(root)) return [];
44
+ const origin = block.getRelativeToSurfaceXY();
45
+ const {topLeft, bottomRight} = block.getBoundingRectangle();
46
+ return [{
47
+ id: block.id, block, root, origin, ...topLeft,
48
+ width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y
49
+ }];
50
+ });
51
+ }
52
+
53
+ type Placement = {script: RenderedScript; x: number; y: number};
54
+
55
+ export function moveScripts(workspace: LayoutWorkspace, events: LayoutEvents, placements: Placement[]) {
56
+ const group = events.getGroup();
57
+ events.setGroup(true);
58
+ workspace.setResizesEnabled(false);
59
+ try {
60
+ for (const {script, x, y} of placements) {
61
+ const dx = x - script.x;
62
+ const dy = y - script.y;
63
+ if (dx || dy) script.block.moveBy(dx, dy);
64
+ }
65
+ } finally {
66
+ events.setGroup(group);
67
+ workspace.setResizesEnabled(true);
68
+ }
69
+ events.fireNow_();
70
+ }
71
+
72
+ export function paintScripts(element: HTMLElement, placements: Placement[], scale: number) {
73
+ const document = element.ownerDocument;
74
+ const ns = 'http://www.w3.org/2000/svg';
75
+ const svg = document.createElementNS(ns, 'svg');
76
+ svg.setAttribute('class', 'tw-script-layout-svg');
77
+ svg.setAttribute('aria-hidden', 'true');
78
+ const width = placements.reduce((edge, {script, x}) => Math.max(edge, x + script.width), 0) + 32;
79
+ const height = placements.reduce((edge, {script, y}) => Math.max(edge, y + script.height), 0) + 32;
80
+ svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
81
+ svg.setAttribute('width', String(Math.ceil(width * scale)));
82
+ svg.setAttribute('height', String(Math.ceil(height * scale)));
83
+ for (const {script, x, y} of placements) {
84
+ const clone = script.root.cloneNode(true) as SVGElement;
85
+ clone.style.removeProperty('display');
86
+ clone.removeAttribute('id');
87
+ clone.querySelectorAll('[id]').forEach(node => node.removeAttribute('id'));
88
+ clone.classList.remove('blocklySelected', 'blocklyDragging');
89
+ // The original block owns its fields and all native editing handlers.
90
+ clone.setAttribute('data-script-view-block', script.id);
91
+ clone.setAttribute('transform', `translate(${x + script.origin.x - script.x} ${y + script.origin.y - script.y})`);
92
+ svg.append(clone);
93
+ }
94
+ element.replaceChildren(svg);
95
+ }
@@ -0,0 +1,40 @@
1
+ interface Point {
2
+ x: number;
3
+ y: number;
4
+ }
5
+
6
+ export interface ScriptBounds extends Point {
7
+ id: string;
8
+ width: number;
9
+ height: number;
10
+ }
11
+
12
+ export type ScriptOrder = 'z' | 'n';
13
+ export type LayoutDirection = 'vertical' | 'horizontal';
14
+
15
+ const alignmentTolerance = 24;
16
+ const spacing = 32;
17
+
18
+ export function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection) {
19
+ const bandAxis = order === 'z' ? 'y' : 'x';
20
+ const scanAxis = order === 'z' ? 'x' : 'y';
21
+ const compare = (a: T, b: T, first: 'x' | 'y', second: 'x' | 'y') =>
22
+ a[first] - b[first] || a[second] - b[second] || (a.id < b.id ? -1 : Number(a.id > b.id));
23
+ const ordered = [...scripts].sort((a, b) => compare(a, b, bandAxis, scanAxis));
24
+ const bands: T[][] = [];
25
+ for (const script of ordered) {
26
+ const band = bands.at(-1);
27
+ // Measure each band from its first script so small offsets cannot chain across rows or columns.
28
+ if (band && script[bandAxis] - band[0][bandAxis] <= alignmentTolerance) band.push(script);
29
+ else bands.push([script]);
30
+ }
31
+
32
+ let offset = spacing;
33
+ return bands.flatMap(band => band.sort((a, b) => compare(a, b, scanAxis, bandAxis))).map(script => {
34
+ const vertical = direction === 'vertical';
35
+ const x = vertical ? spacing : offset;
36
+ const y = vertical ? offset : spacing;
37
+ offset += Math.ceil(vertical ? script.height : script.width) + spacing;
38
+ return {script, x, y};
39
+ });
40
+ }
@@ -0,0 +1,213 @@
1
+ interface MenuOption {
2
+ text: string | Node[];
3
+ enabled: boolean;
4
+ callback(): void;
5
+ }
6
+
7
+ interface MenuItem {
8
+ getElement(): HTMLElement;
9
+ setCheckable(checkable: boolean): void;
10
+ setChecked(checked: boolean): void;
11
+ performActionInternal(): boolean;
12
+ handleContextMenu(): void;
13
+ }
14
+
15
+ interface Menu {
16
+ getElement(): HTMLElement;
17
+ getChildAt(index: number): MenuItem;
18
+ setHighlightedIndex(index: number): void;
19
+ dispose(): void;
20
+ }
21
+
22
+ export interface ScriptViewMenuBlocks {
23
+ ContextMenu: {
24
+ populate_(options: MenuOption[], rtl: boolean): Menu;
25
+ position_(menu: Menu, event: MouseEvent, rtl: boolean): void;
26
+ createWidget_(menu: Menu): void;
27
+ };
28
+ WidgetDiv: {
29
+ DIV: HTMLElement;
30
+ dispose_: (() => void) | null;
31
+ show(owner: object, rtl: boolean, dispose: () => void): void;
32
+ hideIfOwner(owner: object): void;
33
+ };
34
+ }
35
+
36
+ export interface ScriptViewMenuWorkspace {
37
+ RTL: boolean;
38
+ showContextMenu_(event: MouseEvent): void;
39
+ }
40
+
41
+ interface MenuConfig {
42
+ label: string;
43
+ choices: (MenuOption & {checked: boolean})[];
44
+ }
45
+
46
+ export function attachScriptViewMenu(
47
+ {ContextMenu, WidgetDiv}: ScriptViewMenuBlocks,
48
+ workspace: ScriptViewMenuWorkspace,
49
+ host: HTMLElement,
50
+ surface: HTMLElement,
51
+ isBackground: (target: Element) => boolean,
52
+ getMenu: () => MenuConfig
53
+ ) {
54
+ const document = host.ownerDocument;
55
+ let closeMenu: (() => void) | undefined;
56
+
57
+ function addSubmenu(menu: Menu, index: number, {label, choices}: MenuConfig, rtl: boolean, owner: object) {
58
+ const root = menu.getElement();
59
+ const item = menu.getChildAt(index);
60
+ const trigger = item.getElement();
61
+ trigger.setAttribute('aria-haspopup', 'menu');
62
+ trigger.setAttribute('aria-expanded', 'false');
63
+ const nextKey = rtl ? 'ArrowLeft' : 'ArrowRight';
64
+ const backKey = rtl ? 'ArrowRight' : 'ArrowLeft';
65
+ let submenu: Menu | undefined;
66
+ const close = () => WidgetDiv.hideIfOwner(owner);
67
+
68
+ function closeSubmenu(restoreFocus = false) {
69
+ if (!submenu) return;
70
+ const hadFocus = submenu.getElement().contains(document.activeElement);
71
+ submenu.dispose();
72
+ submenu = undefined;
73
+ trigger.setAttribute('aria-expanded', 'false');
74
+ if (restoreFocus && hadFocus) root.focus();
75
+ }
76
+
77
+ function openSubmenu(focus: boolean) {
78
+ if (!submenu) {
79
+ submenu = ContextMenu.populate_(choices.map(choice => ({
80
+ ...choice,
81
+ callback() {
82
+ close();
83
+ choice.callback();
84
+ }
85
+ })), rtl);
86
+ ContextMenu.createWidget_(submenu);
87
+ choices.forEach(({checked}, choiceIndex) => {
88
+ const option = submenu.getChildAt(choiceIndex);
89
+ option.setCheckable(true);
90
+ option.setChecked(checked);
91
+ const element = option.getElement();
92
+ element.setAttribute('role', 'menuitemradio');
93
+ element.setAttribute('aria-checked', String(checked));
94
+ });
95
+ const popup = submenu.getElement();
96
+ popup.classList.add('tw-script-view-submenu');
97
+ popup.setAttribute('aria-label', label);
98
+ const {clientWidth, clientHeight} = document.documentElement;
99
+ const {width, height} = popup.getBoundingClientRect();
100
+ const {left, right} = root.getBoundingClientRect();
101
+ const {top} = trigger.getBoundingClientRect();
102
+ const placeLeft = rtl ? left >= width : right + width > clientWidth && left >= width;
103
+ const x = placeLeft ? left - width + 1 : right - 1;
104
+ popup.style.left = `${Math.max(0, Math.min(x, clientWidth - width))}px`;
105
+ popup.style.top = `${Math.max(0, Math.min(top, clientHeight - height))}px`;
106
+ popup.addEventListener('keydown', event => {
107
+ if (event.key !== backKey && event.key !== 'Escape') return;
108
+ event.preventDefault();
109
+ event.stopPropagation();
110
+ closeSubmenu(true);
111
+ }, true);
112
+ trigger.setAttribute('aria-expanded', 'true');
113
+ }
114
+ if (focus) {
115
+ submenu.getElement().focus();
116
+ submenu.setHighlightedIndex(choices.findIndex(choice => choice.checked));
117
+ }
118
+ }
119
+
120
+ trigger.addEventListener('pointerenter', () => openSubmenu(false));
121
+ root.addEventListener('pointerover', event => {
122
+ if (!trigger.contains(event.target as Node)) closeSubmenu(true);
123
+ });
124
+ root.addEventListener('keydown', event => {
125
+ if (event.key === nextKey && trigger.contains(document.getElementById(root.getAttribute('aria-activedescendant')))) {
126
+ event.preventDefault();
127
+ event.stopPropagation();
128
+ openSubmenu(true);
129
+ } else if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {
130
+ closeSubmenu();
131
+ } else if (event.key === 'Escape' || event.key === 'Tab') {
132
+ close();
133
+ }
134
+ }, true);
135
+ item.performActionInternal = () => {
136
+ openSubmenu(true);
137
+ return true;
138
+ };
139
+ item.handleContextMenu = () => {};
140
+
141
+ closeMenu = close;
142
+ const dispose = WidgetDiv.dispose_;
143
+ WidgetDiv.dispose_ = () => {
144
+ closeSubmenu();
145
+ if (closeMenu === close) closeMenu = undefined;
146
+ dispose?.();
147
+ };
148
+ }
149
+
150
+ function triggerOption(label: string): MenuOption {
151
+ const arrow = document.createElement('span');
152
+ arrow.className = 'tw-script-view-menu-arrow';
153
+ arrow.setAttribute('aria-hidden', 'true');
154
+ return {text: [document.createTextNode(label), arrow], enabled: true, callback() {}};
155
+ }
156
+
157
+ const showContextMenu = workspace.showContextMenu_;
158
+ workspace.showContextMenu_ = function (event) {
159
+ const populate = ContextMenu.populate_;
160
+ // Only extend the options collected for this workspace, after the existing add-ons.
161
+ ContextMenu.populate_ = (options, rtl) => {
162
+ const config = getMenu();
163
+ const menu = populate.call(ContextMenu, [...options, triggerOption(config.label)], rtl);
164
+ addSubmenu(menu, options.length, config, rtl, ContextMenu);
165
+ return menu;
166
+ };
167
+ try {
168
+ showContextMenu.call(this, event);
169
+ } finally {
170
+ ContextMenu.populate_ = populate;
171
+ }
172
+ };
173
+
174
+ function showStandaloneMenu(event: MouseEvent) {
175
+ if (!isBackground(event.target as Element)) return;
176
+ event.preventDefault();
177
+ event.stopPropagation();
178
+ const config = getMenu();
179
+ const rtl = workspace.RTL;
180
+ const menu = ContextMenu.populate_([triggerOption(config.label)], rtl);
181
+ const outside = new document.defaultView.AbortController();
182
+ WidgetDiv.show(surface, rtl, () => {
183
+ outside.abort();
184
+ menu.dispose();
185
+ });
186
+ addSubmenu(menu, 0, config, rtl, surface);
187
+ ContextMenu.position_(menu, event, rtl);
188
+ document.addEventListener('pointerdown', event => {
189
+ if (!WidgetDiv.DIV.contains(event.target as Node)) WidgetDiv.hideIfOwner(surface);
190
+ }, {capture: true, signal: outside.signal});
191
+ }
192
+
193
+ function keepPreviewInactive(event: PointerEvent) {
194
+ // Focusing a background pane on pointerdown would replace its preview before contextmenu.
195
+ if ((event.button === 2 || (event.button === 0 && event.ctrlKey)) && isBackground(event.target as Element)) {
196
+ event.preventDefault();
197
+ }
198
+ }
199
+
200
+ host.addEventListener('pointerdown', keepPreviewInactive);
201
+ host.addEventListener('contextmenu', showStandaloneMenu);
202
+ return {
203
+ close() {
204
+ closeMenu?.();
205
+ },
206
+ dispose() {
207
+ closeMenu?.();
208
+ workspace.showContextMenu_ = showContextMenu;
209
+ host.removeEventListener('pointerdown', keepPreviewInactive);
210
+ host.removeEventListener('contextmenu', showStandaloneMenu);
211
+ }
212
+ };
213
+ }