@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,82 @@
1
+ export type PresentationElements = (injection: HTMLElement) => {
2
+ wrapper?: Element | null;
3
+ extensionButton?: HTMLElement | null;
4
+ watermark?: HTMLElement | null;
5
+ };
6
+
7
+ // These are display-only copies of the controls that belong to the shared editable workspace.
8
+ export function captureCodePreviewChrome(workspace, target, presentationElements: PresentationElements | null,
9
+ includeNavigation: boolean) {
10
+ const injection: HTMLElement = workspace.getInjectionDiv();
11
+ const svg = workspace.getParentSvg();
12
+ const {wrapper, extensionButton, watermark} = presentationElements?.(injection) ?? {};
13
+ if (!wrapper) return null;
14
+
15
+ const chrome = injection.ownerDocument.createElement('div');
16
+ chrome.setAttribute('inert', '');
17
+ chrome.dataset.codePreviewChrome = '';
18
+ const origin = wrapper.getBoundingClientRect();
19
+
20
+ function copy(node: HTMLElement | SVGElement | null | undefined, {right = false, bottom = false, stretch = false, deep = true} = {}) {
21
+ if (!node) return;
22
+ const rect = node.getBoundingClientRect();
23
+ if (!rect.width || !rect.height) return;
24
+ const clone = node.cloneNode(deep) as HTMLElement | SVGElement;
25
+ clone.removeAttribute('id');
26
+ for (const child of clone.querySelectorAll('[id]')) child.removeAttribute('id');
27
+ const style = clone.style;
28
+ // Override the native positioning rules while retaining the control's theme and contents.
29
+ for (const [key, value] of Object.entries({
30
+ position: 'absolute',
31
+ left: right && !stretch ? 'auto' : `${rect.left - origin.left}px`,
32
+ right: right || stretch ? `${origin.right - rect.right}px` : 'auto',
33
+ top: bottom ? 'auto' : `${rect.top - origin.top}px`,
34
+ bottom: bottom ? `${origin.bottom - rect.bottom}px` : 'auto',
35
+ width: stretch ? 'auto' : `${rect.width}px`,
36
+ height: `${rect.height}px`
37
+ })) style.setProperty(key, value, 'important');
38
+ chrome.appendChild(clone);
39
+ return clone;
40
+ }
41
+
42
+ const palette = injection.querySelector<HTMLElement | SVGElement>(':scope > .blocklyToolboxDiv');
43
+ const paletteCopy = copy(palette, {stretch: palette?.hasAttribute('data-horizontal-block-palette')});
44
+ const paletteScroll = palette?.scrollLeft ?? 0;
45
+ copy(injection.querySelector<HTMLElement | SVGElement>(':scope > .blocklyFlyout'));
46
+ copy(injection.querySelector<HTMLElement | SVGElement>(':scope > .blocklyFlyoutScrollbar'));
47
+ copy(extensionButton);
48
+ const zoom = includeNavigation && svg.querySelector('.blocklyZoom');
49
+ if (zoom) {
50
+ const shell = copy(svg, {right: true, bottom: true, deep: false});
51
+ if (shell) {
52
+ shell.classList.remove('blocklySvg');
53
+ shell.appendChild(zoom.cloneNode(true));
54
+ }
55
+ }
56
+ copy(injection.querySelector<HTMLElement | SVGElement>(':scope > .blocklyScrollbarVertical.blocklyMainWorkspaceScrollbar'), {right: true});
57
+ copy(injection.querySelector<HTMLElement | SVGElement>(':scope > .blocklyScrollbarHorizontal.blocklyMainWorkspaceScrollbar'), {bottom: true});
58
+ if (includeNavigation) {
59
+ const minimap = copy(injection.querySelector<SVGElement>(':scope > [data-workspace-minimap]'), {right: true, bottom: true});
60
+ const image = copy(watermark, {right: true, bottom: true});
61
+ // The GUI throttles costume changes, so the last frame may still show the previous target.
62
+ const asset = target.getCostumes()[target.currentCostume]?.asset;
63
+ if (minimap && watermark && asset) {
64
+ const mark = image ?? watermark.cloneNode(false) as HTMLElement;
65
+ const img = mark.ownerDocument.createElement('img');
66
+ img.src = asset.encodeDataURI();
67
+ mark.replaceChildren(img);
68
+ mark.style.cssText = watermark.style.cssText;
69
+ mark.style.position = 'absolute';
70
+ chrome.appendChild(mark);
71
+ }
72
+ }
73
+ return {
74
+ mount(container) {
75
+ container.appendChild(chrome);
76
+ if (paletteCopy) paletteCopy.scrollLeft = paletteScroll;
77
+ },
78
+ dispose() {
79
+ chrome.remove();
80
+ }
81
+ };
82
+ }
@@ -0,0 +1,123 @@
1
+
2
+ export function installProcedureEditor({blocks, workspace, getLocale, canEdit, commit}) {
3
+ const document = workspace.getInjectionDiv().ownerDocument as Document;
4
+ let cancel = () => {};
5
+ let creating = false;
6
+ const createDefinition = blocks.Procedures.createProcedureDefCallback_;
7
+ blocks.Procedures.createProcedureDefCallback_ = function (source) {
8
+ creating = true;
9
+ try {
10
+ createDefinition.call(this, source);
11
+ } finally {
12
+ creating = false;
13
+ }
14
+ };
15
+
16
+ blocks.Procedures.externalProcedureDefCallback = (mutation, apply) => {
17
+ if (!canEdit()) return;
18
+ cancel();
19
+ const originalName = creating ? null : mutation.getAttribute('proccode');
20
+ const ja = /^ja(?:-|$)/i.test(getLocale());
21
+ const text = ja ? {
22
+ title: 'ブロック定義', input: '引数を追加(数値または文字列)', boolean: '真偽値の引数を追加',
23
+ label: 'ラベルを追加', warp: '画面を再描画せずに実行する', cancel: 'キャンセル', save: 'OK',
24
+ duplicate: 'このブロック定義はすでにあります。'
25
+ } : {
26
+ title: 'Block definition', input: 'Add number or text input', boolean: 'Add boolean input',
27
+ label: 'Add label', warp: 'Run without screen refresh', cancel: 'Cancel', save: 'OK',
28
+ duplicate: 'This block definition already exists.'
29
+ };
30
+ const dialog = document.createElement('dialog');
31
+ dialog.className = 'twPlusProcedureDialog';
32
+ dialog.setAttribute('aria-label', text.title);
33
+ dialog.innerHTML = `<form>
34
+ <h2></h2>
35
+ <div data-procedure-workspace></div>
36
+ <div data-procedure-buttons></div>
37
+ <label><input type="checkbox"><span></span></label>
38
+ <p role="alert" hidden></p>
39
+ <footer class="tw-plus-dialog-actions"></footer>
40
+ </form>`;
41
+ dialog.querySelector('h2').textContent = text.title;
42
+ dialog.querySelector('label span').textContent = text.warp;
43
+ const error = dialog.querySelector('p');
44
+ const form = dialog.querySelector('form');
45
+ const addButton = (container, label, onClick?: () => void) => {
46
+ const button = document.createElement('button');
47
+ button.type = onClick ? 'button' : 'submit';
48
+ button.textContent = label;
49
+ if (onClick) button.addEventListener('click', onClick);
50
+ dialog.querySelector(container).appendChild(button);
51
+ return button;
52
+ };
53
+ const area = dialog.querySelector<HTMLElement>('[data-procedure-workspace]');
54
+ document.body.appendChild(dialog);
55
+ dialog.showModal();
56
+
57
+ // ScratchBlocks positions its text editor in document coordinates.
58
+ // The full-viewport dialog keeps that widget inside the modal focus scope.
59
+ const widget = blocks.WidgetDiv.DIV;
60
+ dialog.appendChild(widget);
61
+ const draft = blocks.inject(area, {
62
+ toolbox: '<xml></xml>', media: workspace.options.pathToMedia, scrollbars: true,
63
+ rtl: workspace.RTL, zoom: {startScale: 0.9}
64
+ });
65
+ const declaration = draft.newBlock('procedures_declaration');
66
+ declaration.setMovable(false);
67
+ declaration.setDeletable(false);
68
+ declaration.contextMenu = false;
69
+ declaration.domToMutation(mutation);
70
+ declaration.initSvg();
71
+ declaration.render();
72
+ declaration.moveBy(16, 20);
73
+ const warp = dialog.querySelector('input');
74
+ warp.checked = declaration.getWarp();
75
+
76
+ cancel = () => {
77
+ cancel = () => {};
78
+ blocks.WidgetDiv.hide(true);
79
+ document.body.appendChild(widget);
80
+ draft.dispose();
81
+ workspace.markFocused();
82
+ dialog.close();
83
+ dialog.remove();
84
+ };
85
+ dialog.addEventListener('cancel', event => {
86
+ event.preventDefault();
87
+ cancel();
88
+ });
89
+ const addPart = (label, add) => addButton('[data-procedure-buttons]', label, () => {
90
+ blocks.WidgetDiv.hide(true);
91
+ declaration.onChangeFn();
92
+ add.call(declaration);
93
+ });
94
+ addPart(text.input, declaration.addStringNumberExternal);
95
+ addPart(text.boolean, declaration.addBooleanExternal);
96
+ addPart(text.label, declaration.addLabelExternal);
97
+ addButton('footer', text.cancel, () => cancel()).dataset.dialogAction = 'cancel';
98
+ addButton('footer', text.save).dataset.dialogAction = 'confirm';
99
+ form.addEventListener('submit', event => {
100
+ event.preventDefault();
101
+ if (!canEdit()) {
102
+ cancel();
103
+ return;
104
+ }
105
+ blocks.WidgetDiv.hide(true);
106
+ declaration.onChangeFn();
107
+ declaration.setWarp(warp.checked);
108
+ const result = declaration.mutationToDom(true);
109
+ const name = result.getAttribute('proccode');
110
+ if (name !== originalName && blocks.Procedures.getDefineBlock(name, workspace)) {
111
+ error.textContent = text.duplicate;
112
+ error.hidden = false;
113
+ return;
114
+ }
115
+ cancel();
116
+ commit(() => {
117
+ apply(result);
118
+ workspace.refreshToolboxSelection_();
119
+ });
120
+ });
121
+ };
122
+ return {cancel: () => cancel()};
123
+ }
@@ -0,0 +1,46 @@
1
+ // ScratchBlocks disconnects removed arguments before emitting the mutation.
2
+ // The VM keeps the old input slots and ignores delete events for their shadows.
3
+ export function removeObsoleteProcedureInputs(blocks, blockIds: Set<string>) {
4
+ for (const id of blockIds) {
5
+ const block = blocks.getBlock(id);
6
+ if (block?.opcode !== 'procedures_call' && block?.opcode !== 'procedures_prototype') continue;
7
+ const argumentIds = new Set<string>(JSON.parse(block.mutation.argumentids));
8
+ for (const name of Object.keys(block.inputs)) {
9
+ if (argumentIds.has(name)) continue;
10
+ const {block: childId, shadow: shadowId} = block.inputs[name];
11
+ if (childId && childId !== shadowId && blocks.getBlock(childId)?.parent === id) {
12
+ throw new Error('Procedure edit left a removed argument connected');
13
+ }
14
+ delete block.inputs[name];
15
+ const shadow = shadowId && blocks.getBlock(shadowId);
16
+ if (shadow?.shadow && (shadow.parent === id || shadow.parent == null)) blocks.deleteBlock(shadowId);
17
+ }
18
+ blocks.resetCache();
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Whether a script editor shows only the hat of a script. The flag is kept in the hat's mutation, so it is
24
+ * saved in the project and travels with the script. ScratchBlocks ignores the attribute on hats that read
25
+ * no mutation, such as a function definition's.
26
+ */
27
+ export const foldedDefinitionAttribute = 'tw-plus-folded';
28
+
29
+ type MutableBlock = {mutation?: Record<string, unknown> & {tagName?: string; children?: unknown[]}} | undefined;
30
+
31
+ export function isFoldedDefinition(block: MutableBlock) {
32
+ return block?.mutation?.[foldedDefinitionAttribute] === 'true';
33
+ }
34
+
35
+ export function setFoldedDefinition(block: NonNullable<MutableBlock>, folded: boolean) {
36
+ if (folded) {
37
+ block.mutation = {tagName: 'mutation', children: [], ...block.mutation, [foldedDefinitionAttribute]: 'true'};
38
+ return;
39
+ }
40
+ if (!block.mutation) return;
41
+ const {[foldedDefinitionAttribute]: _, ...rest} = block.mutation;
42
+ // Drop the mutation this flag made, so an unfolded hat saves as it did before.
43
+ const empty = Object.keys(rest).every(key => key === 'tagName' || key === 'children') && !rest.children?.length;
44
+ if (empty) delete block.mutation;
45
+ else block.mutation = rest;
46
+ }
@@ -0,0 +1,76 @@
1
+ export type FieldAction = {id: string; label: string};
2
+ export type FieldActionPanel = {title: string; actions: readonly FieldAction[]};
3
+
4
+ /** A field editor supplied by a trusted extension. Callbacks run in the parent editor. */
5
+ export interface ProgrammaticExtensionField {
6
+ type: 'turbowarp_plus_actions';
7
+ getEditor(value: string): FieldActionPanel;
8
+ applyAction(value: string, actionId: string): string | undefined | Promise<string | undefined>;
9
+ }
10
+
11
+ export function runFieldAction(editor: ProgrammaticExtensionField, value: string, actionId: string,
12
+ complete: (next: string | undefined) => void, onError: (error: unknown) => void) {
13
+ try {
14
+ const next = editor.applyAction(value, actionId);
15
+ if (typeof next === 'string') complete(next);
16
+ else if (next === undefined) complete(undefined);
17
+ else void Promise.resolve(next).then(complete).catch(onError);
18
+ } catch (error) {
19
+ onError(error);
20
+ }
21
+ }
22
+
23
+ export function readFieldActionPanel(editor: ProgrammaticExtensionField, value: string): FieldActionPanel | undefined {
24
+ const panel = editor.getEditor(value);
25
+ if (typeof panel?.title !== 'string' || !Array.isArray(panel.actions) ||
26
+ !panel.actions.length || panel.actions.length > 32) return;
27
+ const actions: FieldAction[] = [];
28
+ const ids = new Set<string>();
29
+ for (const action of panel.actions) {
30
+ if (typeof action?.id !== 'string' || !action.id || typeof action.label !== 'string' || ids.has(action.id)) return;
31
+ ids.add(action.id);
32
+ actions.push({id: action.id, label: action.label});
33
+ }
34
+ return {title: panel.title, actions};
35
+ }
36
+
37
+ export function createFieldActionDialog(document: Document) {
38
+ let current: HTMLDialogElement | undefined;
39
+ const close = () => {
40
+ current?.close();
41
+ current?.remove();
42
+ current = undefined;
43
+ };
44
+ return {close, show(panel: FieldActionPanel, select: (id: string) => void, locale?: string) {
45
+ close();
46
+ const dialog = document.createElement('dialog');
47
+ const title = document.createElement('h2');
48
+ title.textContent = panel.title;
49
+ dialog.setAttribute('aria-label', panel.title);
50
+ dialog.append(title);
51
+ for (const {id, label} of panel.actions) {
52
+ const button = document.createElement('button');
53
+ button.textContent = label;
54
+ button.addEventListener('click', () => {
55
+ close();
56
+ select(id);
57
+ });
58
+ dialog.append(button);
59
+ }
60
+ const cancel = document.createElement('button');
61
+ cancel.textContent = /^ja(?:-|$)/i.test(locale) ? 'キャンセル' : 'Cancel';
62
+ cancel.addEventListener('click', close);
63
+ cancel.dataset.dialogAction = 'cancel';
64
+ const footer = document.createElement('div');
65
+ footer.className = 'tw-plus-dialog-actions';
66
+ footer.append(cancel);
67
+ dialog.append(footer);
68
+ dialog.addEventListener('cancel', event => {
69
+ event.preventDefault();
70
+ close();
71
+ });
72
+ document.body.append(dialog);
73
+ current = dialog;
74
+ dialog.showModal();
75
+ }};
76
+ }
@@ -0,0 +1,47 @@
1
+ interface Edit {
2
+ type: string;
3
+ commentId?: string;
4
+ blockId?: string;
5
+ element?: string;
6
+ xml?: string | {outerHTML: string};
7
+ [field: string]: unknown;
8
+ }
9
+
10
+ const blockFields: Record<string, string[]> = {
11
+ create: ['blockId', 'xml'],
12
+ change: ['blockId', 'element', 'name', 'newValue'],
13
+ move: ['blockId', 'oldParentId', 'oldInputName', 'newParentId', 'newInputName', 'newCoordinate'],
14
+ delete: ['blockId']
15
+ };
16
+
17
+ const commentFields: Record<string, string[]> = {
18
+ comment_create: ['commentId', 'blockId', 'text', 'xy', 'width', 'height', 'minimized'],
19
+ comment_change: ['commentId', 'newContents_'],
20
+ comment_move: ['commentId', 'newCoordinate_'],
21
+ comment_delete: ['commentId', 'blockId']
22
+ };
23
+
24
+ export function isCommentEdit(event: Edit) {
25
+ return event && Object.hasOwn(commentFields, event.type) && typeof event.commentId === 'string';
26
+ }
27
+
28
+ function isBlockEdit(event: Edit) {
29
+ return event && Object.hasOwn(blockFields, event.type) && typeof event.blockId === 'string' &&
30
+ (event.type !== 'change' || ['field', 'mutation'].includes(event.element));
31
+ }
32
+
33
+ export const isCodeEdit = (event: Edit) => isBlockEdit(event) || isCommentEdit(event);
34
+
35
+ export function encodeEdit(event: Edit) {
36
+ if (!isCodeEdit(event)) return null;
37
+ const fields = isCommentEdit(event) ? commentFields : blockFields;
38
+ const data: Edit = {type: event.type};
39
+ for (const key of fields[event.type]) data[key] = key === 'xml' ? (event.xml as {outerHTML: string}).outerHTML : event[key];
40
+ return data;
41
+ }
42
+
43
+ export function decodeEdit(event: Edit) {
44
+ if (!isCodeEdit(event)) return null;
45
+ if (event.type === 'create') return typeof event.xml === 'string' ? {...event, xml: {outerHTML: event.xml}} : null;
46
+ return event;
47
+ }
@@ -0,0 +1,104 @@
1
+ import {arrangeScripts, type LayoutDirection, type ScriptOrder} from './script-layout.ts';
2
+ import {moveScripts, paintScripts, readScripts, type LayoutEvents, type LayoutWorkspace} from './script-layout-workspace.ts';
3
+
4
+ export interface RearrangementContext {
5
+ workspace: LayoutWorkspace;
6
+ events: LayoutEvents;
7
+ canArrange(): boolean;
8
+ target(): unknown;
9
+ }
10
+
11
+ export function openRearrangement({workspace, events, canArrange, target}: RearrangementContext, locale: string) {
12
+ const document = workspace.getInjectionDiv().ownerDocument;
13
+ const ja = /^ja(?:-|$)/i.test(locale);
14
+ const translate = (en: string, japanese: string) => ja ? japanese : en;
15
+ events.fireNow_();
16
+ const originalTarget = target();
17
+ const scripts = readScripts(workspace);
18
+ const dialog = document.createElement('dialog');
19
+ dialog.className = 'tw-script-layout-dialog';
20
+ dialog.setAttribute('aria-label', translate('Rearrange Code Blocks', 'コードブロックの再配置'));
21
+ const title = document.createElement('h2');
22
+ title.textContent = dialog.getAttribute('aria-label');
23
+ const controls = document.createElement('div');
24
+ controls.className = 'tw-script-layout-options';
25
+ const preview = document.createElement('div');
26
+ preview.className = 'tw-script-layout-preview';
27
+ preview.tabIndex = 0;
28
+ preview.setAttribute('aria-label', translate('Layout preview', '再配置のプレビュー'));
29
+ const footer = document.createElement('footer');
30
+ footer.className = 'tw-plus-dialog-actions';
31
+ const status = document.createElement('p');
32
+ status.setAttribute('role', 'status');
33
+ const cancel = document.createElement('button');
34
+ cancel.textContent = translate('Cancel', 'キャンセル');
35
+ const apply = document.createElement('button');
36
+ apply.textContent = translate('Rearrange', '再配置する');
37
+ const order = select(translate('Order', '順序'), [
38
+ ['z', translate('Z · by row', 'Z方式(行順)')], ['n', translate('N · by column', 'N方式(列順)')]
39
+ ]);
40
+ const direction = select(translate('Direction', '方向'), [
41
+ ['vertical', translate('Vertical', '垂直')], ['horizontal', translate('Horizontal', '水平')]
42
+ ]);
43
+ let placements: ReturnType<typeof arrangeScripts<(typeof scripts)[number]>>;
44
+
45
+ function select(label: string, choices: [string, string][]) {
46
+ const field = document.createElement('label');
47
+ field.textContent = label;
48
+ const input = document.createElement('select');
49
+ for (const [value, text] of choices) {
50
+ const option = document.createElement('option');
51
+ option.value = value;
52
+ option.textContent = text;
53
+ input.append(option);
54
+ }
55
+ input.addEventListener('change', update);
56
+ field.append(input);
57
+ controls.append(field);
58
+ return input;
59
+ }
60
+
61
+ function update() {
62
+ placements = arrangeScripts(scripts, order.value as ScriptOrder, direction.value as LayoutDirection);
63
+ paintScripts(preview, placements, 0.8);
64
+ preview.scrollTo(0, 0);
65
+ apply.disabled = scripts.length === 0;
66
+ status.textContent = scripts.length ? '' : translate('There are no scripts to rearrange.', '再配置するスクリプトがありません。');
67
+ }
68
+
69
+ function close() {
70
+ if (dialog.open) dialog.close();
71
+ dialog.remove();
72
+ }
73
+
74
+ cancel.addEventListener('click', close);
75
+ dialog.addEventListener('close', close, {once: true});
76
+ dialog.addEventListener('keydown', event => event.stopPropagation());
77
+ apply.addEventListener('click', () => {
78
+ events.fireNow_();
79
+ const current = readScripts(workspace);
80
+ if (!canArrange() || target() !== originalTarget || current.length !== scripts.length ||
81
+ current.some(({block, x, y, width, height}, i) => {
82
+ const original = scripts[i];
83
+ return block !== original.block || x !== original.x || y !== original.y ||
84
+ width !== original.width || height !== original.height;
85
+ })) {
86
+ status.textContent = translate('The code changed. Reopen this dialog to preview it again.',
87
+ 'コードが変わりました。ダイアログを開き直して再度プレビューしてください。');
88
+ apply.disabled = true;
89
+ return;
90
+ }
91
+ moveScripts(workspace, events, placements);
92
+ close();
93
+ if (placements.length) workspace.centerOnBlock(placements[0].script.id);
94
+ });
95
+ cancel.dataset.dialogAction = 'cancel';
96
+ apply.dataset.dialogAction = 'confirm';
97
+ footer.append(status, cancel, apply);
98
+ dialog.append(title, controls, preview, footer);
99
+ document.body.append(dialog);
100
+ update();
101
+ dialog.showModal();
102
+ order.focus();
103
+ return {close};
104
+ }