@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,26 @@
1
+ import type { FieldResourceOptions } from './parent-field-resources.ts';
2
+ type Anchor = {
3
+ left: number;
4
+ bottom: number;
5
+ };
6
+ /** The capability belongs to one popup editor invocation. */
7
+ export type NativeFieldEditSession = {
8
+ signal: AbortSignal;
9
+ commit(value: string): void;
10
+ };
11
+ /** The parent field owns the widget and its value. */
12
+ export declare function openNativeField({ blocks, field, document, anchor, parentDocument, asyncCommit, isolatedValue, onAttachedClose, resources, valid, commit, onError }: {
13
+ blocks: any;
14
+ field: any;
15
+ document: Document;
16
+ anchor?: Anchor;
17
+ parentDocument?: boolean;
18
+ asyncCommit?: boolean;
19
+ isolatedValue?: string;
20
+ resources?: FieldResourceOptions;
21
+ valid(): boolean;
22
+ commit(value: string): void;
23
+ onAttachedClose?(): void;
24
+ onError?(error: unknown): void;
25
+ }): () => void;
26
+ export {};
@@ -0,0 +1,204 @@
1
+ import { getNativeFieldEditor } from "./custom-extension-fields.js";
2
+ import { mirrorParentField } from "./parent-field-mirror.js";
3
+ /** The parent field owns the widget and its value. */
4
+ export function openNativeField({ blocks, field, document, anchor, parentDocument = false, asyncCommit = false, isolatedValue, onAttachedClose, resources, valid, commit, onError }) {
5
+ const widget = blocks.WidgetDiv;
6
+ const original = widget?.DIV;
7
+ const window = document.defaultView;
8
+ const show = getNativeFieldEditor(field);
9
+ if (!window || !original || !show) {
10
+ onAttachedClose?.();
11
+ return;
12
+ }
13
+ const isolated = isolatedValue !== undefined;
14
+ const oneUse = isolated || Boolean(onAttachedClose);
15
+ const value = isolated ? isolatedValue : field.getValue();
16
+ const setValue = field.setValue;
17
+ const host = anchor ? document.createElement('div') : original;
18
+ const mirrorWidget = parentDocument && Boolean(anchor);
19
+ if (anchor) {
20
+ host.className = original.className;
21
+ host.dataset.plusNativeField = '';
22
+ document.body.append(host);
23
+ }
24
+ const widgetHost = parentDocument ? original : host;
25
+ const originalOpacity = original.style.opacity;
26
+ const originalInert = original.inert;
27
+ let ownsWidget = false;
28
+ let widgetOwner;
29
+ let disposeMirror;
30
+ let closed = false;
31
+ let queued = false;
32
+ const editController = parentDocument && asyncCommit ? new AbortController() : undefined;
33
+ const scoped = Boolean(editController || oneUse);
34
+ function withoutEvents(apply) {
35
+ blocks.Events.disable();
36
+ try {
37
+ apply();
38
+ }
39
+ finally {
40
+ blocks.Events.enable();
41
+ }
42
+ }
43
+ function close() {
44
+ if (closed)
45
+ return;
46
+ closed = true;
47
+ observer.disconnect();
48
+ document.removeEventListener('keydown', escape, true);
49
+ document.removeEventListener('pointerdown', outside, true);
50
+ if (scoped) {
51
+ window.removeEventListener('blur', close);
52
+ window.removeEventListener('pagehide', close);
53
+ editController?.abort();
54
+ }
55
+ try {
56
+ if (ownsWidget && widget.DIV === widgetHost && (!parentDocument || widget.owner_ === widgetOwner))
57
+ widget.hide(true);
58
+ }
59
+ catch (error) {
60
+ onError?.(error);
61
+ }
62
+ finally {
63
+ disposeMirror?.();
64
+ if (!parentDocument && widget.DIV === host)
65
+ widget.DIV = original;
66
+ if (mirrorWidget && ownsWidget) {
67
+ original.style.opacity = originalOpacity;
68
+ original.inert = originalInert;
69
+ }
70
+ field.setValue = oneUse ? () => { } : setValue;
71
+ if (anchor)
72
+ host.remove();
73
+ if (isolated) {
74
+ try {
75
+ field.dispose?.();
76
+ }
77
+ catch (error) {
78
+ onError?.(error);
79
+ }
80
+ }
81
+ else if (field.sourceBlock_ && field.getValue() !== value) {
82
+ try {
83
+ withoutEvents(() => setValue.call(field, value));
84
+ }
85
+ catch (error) {
86
+ onError?.(error);
87
+ }
88
+ }
89
+ onAttachedClose?.();
90
+ }
91
+ }
92
+ function escape(event) {
93
+ if (event.key !== 'Escape')
94
+ return;
95
+ event.preventDefault();
96
+ event.stopPropagation();
97
+ close();
98
+ }
99
+ function outside(event) {
100
+ if (!host.contains(event.target))
101
+ close();
102
+ }
103
+ const observer = new MutationObserver(() => {
104
+ if (!queued && (!widget.isVisible() || (parentDocument && widget.owner_ !== widgetOwner)))
105
+ close();
106
+ });
107
+ const ownsOpenWidget = () => !scoped ||
108
+ (widget.DIV === widgetHost && widget.owner_ === widgetOwner && widget.isVisible());
109
+ function stageValue(next) {
110
+ if (closed || (oneUse && queued) || !valid() || !ownsOpenWidget())
111
+ return;
112
+ withoutEvents(() => setValue.call(field, next));
113
+ if (queued || field.getValue() === value)
114
+ return;
115
+ queued = true;
116
+ const finish = () => {
117
+ if (closed)
118
+ return;
119
+ try {
120
+ const result = field.getValue();
121
+ const accepted = valid() && ownsOpenWidget() && typeof result === 'string' && result !== value;
122
+ close();
123
+ if (accepted && valid())
124
+ commit(result);
125
+ }
126
+ catch (error) {
127
+ close();
128
+ onError?.(error);
129
+ }
130
+ };
131
+ if (anchor)
132
+ queueMicrotask(finish);
133
+ else
134
+ finish();
135
+ }
136
+ try {
137
+ if (isolated) {
138
+ withoutEvents(() => setValue.call(field, value));
139
+ if (field.getValue() !== value) {
140
+ close();
141
+ return;
142
+ }
143
+ }
144
+ widget.hide(true);
145
+ widget.DIV = widgetHost;
146
+ ownsWidget = true;
147
+ if (mirrorWidget) {
148
+ original.style.opacity = '0';
149
+ original.inert = true;
150
+ }
151
+ field.setValue = stageValue;
152
+ try {
153
+ if (editController) {
154
+ const edit = { signal: editController.signal, commit(next) {
155
+ if (queued || typeof next !== 'string')
156
+ return;
157
+ try {
158
+ stageValue(next);
159
+ }
160
+ catch (error) {
161
+ close();
162
+ onError?.(error);
163
+ }
164
+ } };
165
+ show(edit);
166
+ }
167
+ else {
168
+ show();
169
+ }
170
+ }
171
+ finally {
172
+ widgetOwner = widget.owner_;
173
+ }
174
+ if (!valid() || !widget.isVisible() || !widgetHost.childElementCount) {
175
+ close();
176
+ return;
177
+ }
178
+ if (mirrorWidget) {
179
+ disposeMirror = mirrorParentField(original, host, () => !closed && valid(), resources);
180
+ if (!disposeMirror) {
181
+ close();
182
+ return;
183
+ }
184
+ host.style.display = 'block';
185
+ }
186
+ if (anchor) {
187
+ host.style.position = 'fixed';
188
+ host.style.left = `${Math.max(0, Math.min(anchor.left, window.innerWidth - host.offsetWidth))}px`;
189
+ host.style.top = `${Math.max(0, Math.min(anchor.bottom, window.innerHeight - host.offsetHeight))}px`;
190
+ }
191
+ observer.observe(widgetHost, { attributes: true, attributeFilter: ['style'] });
192
+ document.addEventListener('keydown', escape, true);
193
+ document.addEventListener('pointerdown', outside, true);
194
+ if (scoped) {
195
+ window.addEventListener('blur', close);
196
+ window.addEventListener('pagehide', close);
197
+ }
198
+ return close;
199
+ }
200
+ catch (error) {
201
+ close();
202
+ onError?.(error);
203
+ }
204
+ }
@@ -0,0 +1,20 @@
1
+ export declare const svgDrawingElements: Set<string>;
2
+ type Drawing = {
3
+ tag: string;
4
+ attributes: [string, string][];
5
+ children: (Drawing | string)[];
6
+ };
7
+ export type NativeFieldGraphic = {
8
+ blockId: string;
9
+ name: string;
10
+ value: string;
11
+ bounds: [number, number, number, number];
12
+ drawing: Drawing;
13
+ };
14
+ export declare function isSafeSvgDrawingAttribute(name: string, value: string): boolean;
15
+ /** Project inert drawing data from a trusted, already rendered field. */
16
+ export declare function captureNativeFieldDrawing(root: SVGGraphicsElement): Pick<NativeFieldGraphic, 'bounds' | 'drawing'> | undefined;
17
+ export declare function projectNativeFieldGraphics(runtime: any, target: any, workspace: any): NativeFieldGraphic[];
18
+ /** Keep the child proxy's click handling and saved value. Only its drawing changes. */
19
+ export declare function attachNativeFieldGraphic(field: any, lookup: (blockId: string, value: string) => NativeFieldGraphic | undefined): void;
20
+ export {};
@@ -0,0 +1,156 @@
1
+ const svgNamespace = 'http://www.w3.org/2000/svg';
2
+ export const svgDrawingElements = new Set(['g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'tspan']);
3
+ const numbers = /^[\d.eE+,%\s-]+$/;
4
+ const geometry = new Set(['x', 'y', 'x1', 'y1', 'x2', 'y2', 'width', 'height', 'cx', 'cy', 'r', 'rx', 'ry', 'dx', 'dy',
5
+ 'points', 'stroke-width', 'opacity', 'fill-opacity', 'stroke-opacity', 'font-size']);
6
+ const paint = /^(?:#[\da-f]{3,8}|[a-z]+|rgba?\([\d.,%\s]+\))$/i;
7
+ const svgPaint = ['fill', 'stroke', 'stroke-width', 'opacity', 'fill-opacity', 'stroke-opacity'];
8
+ const svgTypography = ['font-size', 'font-family', 'font-weight', 'font-style'];
9
+ const textStyle = new Set(['text-anchor', 'dominant-baseline', 'alignment-baseline', 'font-weight', 'font-style']);
10
+ export function isSafeSvgDrawingAttribute(name, value) {
11
+ if (value.length > 4096)
12
+ return false;
13
+ if (geometry.has(name))
14
+ return numbers.test(value);
15
+ if (name === 'fill' || name === 'stroke')
16
+ return paint.test(value);
17
+ if (name === 'd')
18
+ return /^[\d.aAcCeEhHlLmMqQsStTvVzZ+,\s-]+$/.test(value);
19
+ if (name === 'transform')
20
+ return /^(?:(?:matrix|translate|scale|rotate|skewX|skewY)\([\d.eE+,\s-]+\)[\s,]*)+$/.test(value);
21
+ if (name === 'font-family')
22
+ return /^[\w ,'"-]+$/.test(value);
23
+ return textStyle.has(name) && /^[\w-]+$/.test(value);
24
+ }
25
+ /** Project inert drawing data from a trusted, already rendered field. */
26
+ export function captureNativeFieldDrawing(root) {
27
+ let remaining = 128;
28
+ function read(element, depth) {
29
+ if (element.namespaceURI !== svgNamespace || !svgDrawingElements.has(element.localName) || depth > 8 || remaining <= 0)
30
+ return;
31
+ remaining--;
32
+ const tag = element.localName;
33
+ const attributes = [];
34
+ for (const { name, value } of element.attributes) {
35
+ if ((depth || name !== 'transform') && isSafeSvgDrawingAttribute(name, value))
36
+ attributes.push([name, value]);
37
+ }
38
+ // Use the applied appearance so that parent-only CSS selectors need not exist in the child.
39
+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);
40
+ const properties = tag === 'text' || tag === 'tspan' ? [...svgPaint, ...svgTypography] : svgPaint;
41
+ if (style)
42
+ for (const name of properties) {
43
+ const computed = style.getPropertyValue(name);
44
+ const value = name === 'font-size' || name === 'stroke-width' ? computed.replace(/px$/, '') : computed;
45
+ const index = attributes.findIndex(([key]) => key === name);
46
+ if (isSafeSvgDrawingAttribute(name, value)) {
47
+ const attribute = [name, value];
48
+ if (index === -1)
49
+ attributes.push(attribute);
50
+ else
51
+ attributes[index] = attribute;
52
+ }
53
+ else if (computed && index !== -1) {
54
+ attributes.splice(index, 1);
55
+ }
56
+ }
57
+ const children = [];
58
+ for (const child of element.childNodes) {
59
+ if (child.nodeType === 1) {
60
+ const drawing = read(child, depth + 1);
61
+ if (drawing)
62
+ children.push(drawing);
63
+ }
64
+ else if (child.nodeType === 3 && (tag === 'text' || tag === 'tspan') && remaining > 0) {
65
+ remaining--;
66
+ children.push(child.textContent.slice(0, 1024));
67
+ }
68
+ }
69
+ if (tag === 'g' && !children.length)
70
+ return;
71
+ return { tag, attributes, children };
72
+ }
73
+ const drawing = read(root, 0);
74
+ if (!drawing)
75
+ return;
76
+ try {
77
+ const { x, y, width, height } = root.getBBox();
78
+ if ([x, y, width, height].every(Number.isFinite) && width > 0 && height > 0) {
79
+ return { bounds: [x, y, width, height], drawing };
80
+ }
81
+ }
82
+ catch {
83
+ // The docked field can be temporarily unrendered.
84
+ }
85
+ }
86
+ export function projectNativeFieldGraphics(runtime, target, workspace) {
87
+ const types = new Set();
88
+ for (const category of runtime._blockInfo ?? []) {
89
+ for (const entry of Object.values(category.customFieldTypes ?? {})) {
90
+ if (typeof entry.fieldImplementation?.fromJson === 'function')
91
+ types.add(entry.extendedName);
92
+ }
93
+ }
94
+ if (!types.size)
95
+ return [];
96
+ const graphics = [];
97
+ for (const [blockId, block] of Object.entries(target.blocks._blocks)) {
98
+ if (!types.has(block.opcode))
99
+ continue;
100
+ const name = `field_${block.opcode}`;
101
+ const value = block.fields[name]?.value;
102
+ const field = workspace.getBlockById(blockId)?.getField(name);
103
+ const root = field?.getSvgRoot?.();
104
+ if (typeof value !== 'string' || !root || field.getValue() !== value)
105
+ continue;
106
+ const graphic = captureNativeFieldDrawing(root);
107
+ if (graphic)
108
+ graphics.push({ blockId, name, value, ...graphic });
109
+ }
110
+ return graphics;
111
+ }
112
+ /** Keep the child proxy's click handling and saved value. Only its drawing changes. */
113
+ export function attachNativeFieldGraphic(field, lookup) {
114
+ const render = field.render_;
115
+ let drawn;
116
+ let svg;
117
+ field.render_ = function () {
118
+ render.call(this);
119
+ const root = this.getSvgRoot();
120
+ if (!root || !this.textElement_)
121
+ return;
122
+ const graphic = lookup(this.sourceBlock_.id, this.getValue());
123
+ if (graphic !== drawn) {
124
+ svg?.remove();
125
+ svg = undefined;
126
+ drawn = graphic;
127
+ this.textElement_.style.visibility = graphic ? 'hidden' : '';
128
+ if (graphic) {
129
+ const document = root.ownerDocument;
130
+ const materialize = (drawing) => {
131
+ const node = document.createElementNS(svgNamespace, drawing.tag);
132
+ for (const [name, value] of drawing.attributes)
133
+ node.setAttribute(name, value);
134
+ for (const child of drawing.children)
135
+ node.append(typeof child === 'string' ? child : materialize(child));
136
+ return node;
137
+ };
138
+ svg = document.createElementNS(svgNamespace, 'svg');
139
+ svg.setAttribute('aria-hidden', 'true');
140
+ svg.setAttribute('pointer-events', 'none');
141
+ svg.setAttribute('viewBox', graphic.bounds.join(' '));
142
+ svg.append(materialize(graphic.drawing));
143
+ root.append(svg);
144
+ }
145
+ }
146
+ if (graphic && svg) {
147
+ const [, , width, height] = graphic.bounds;
148
+ const scale = Math.min(1, this.size_.height / height, 192 / width);
149
+ this.size_.width = Math.max(16, width * scale);
150
+ svg.setAttribute('width', String(width * scale));
151
+ svg.setAttribute('height', String(height * scale));
152
+ svg.setAttribute('y', String((this.size_.height - height * scale) / 2));
153
+ this.box_?.setAttribute('width', String(this.size_.width));
154
+ }
155
+ };
156
+ }
@@ -0,0 +1,4 @@
1
+ export declare function attachPaletteCategoryReorder(menu: HTMLElement, getItems: () => HTMLElement[], onDrop: (from: number, to: number) => void): {
2
+ cancel: () => void;
3
+ dispose(): void;
4
+ };
@@ -0,0 +1,167 @@
1
+ const holdDelay = 500;
2
+ const movementThreshold = 8;
3
+ export function attachPaletteCategoryReorder(menu, getItems, onDrop) {
4
+ const doc = menu.ownerDocument;
5
+ const win = doc.defaultView;
6
+ const events = new AbortController();
7
+ const capture = { capture: true, signal: events.signal };
8
+ let press;
9
+ let preview;
10
+ let suppressRelease = false;
11
+ let target;
12
+ const markTarget = (item) => {
13
+ target?.removeAttribute('data-palette-reorder-target');
14
+ target = item === press?.source ? undefined : item;
15
+ target?.setAttribute('data-palette-reorder-target', '');
16
+ };
17
+ const cancel = () => {
18
+ if (!press)
19
+ return;
20
+ const { pointerId, source, timer } = press;
21
+ win.clearTimeout(timer);
22
+ markTarget();
23
+ press = undefined;
24
+ preview?.remove();
25
+ preview = undefined;
26
+ source.removeAttribute('data-palette-reorder-source');
27
+ menu.classList.remove('tw-palette-category-reordering');
28
+ menu.removeAttribute('data-palette-reordering');
29
+ if (menu.hasPointerCapture(pointerId))
30
+ menu.releasePointerCapture(pointerId);
31
+ };
32
+ const itemAt = (event, items) => {
33
+ const hit = doc.elementFromPoint(event.clientX, event.clientY);
34
+ if (!items.length || !menu.contains(hit))
35
+ return;
36
+ const item = items.find(candidate => candidate.parentElement.contains(hit));
37
+ if (item)
38
+ return item;
39
+ const first = items[0];
40
+ const last = items[items.length - 1];
41
+ const start = first.getBoundingClientRect();
42
+ const end = last.getBoundingClientRect();
43
+ if (!menu.hasAttribute('data-horizontal-block-palette')) {
44
+ if (event.clientY < start.top)
45
+ return first;
46
+ if (event.clientY > end.bottom)
47
+ return last;
48
+ }
49
+ else if (menu.dir === 'rtl') {
50
+ if (event.clientX > start.right)
51
+ return first;
52
+ if (event.clientX < end.left)
53
+ return last;
54
+ }
55
+ else {
56
+ if (event.clientX < start.left)
57
+ return first;
58
+ if (event.clientX > end.right)
59
+ return last;
60
+ }
61
+ };
62
+ doc.addEventListener('pointerdown', event => {
63
+ if (!event.isPrimary || event.button !== 0)
64
+ return;
65
+ cancel();
66
+ suppressRelease = false;
67
+ if (event.ctrlKey || !menu.contains(event.target))
68
+ return;
69
+ const source = getItems().find(item => item.contains(event.target));
70
+ if (!source)
71
+ return;
72
+ const { pointerId, clientX: x, clientY: y } = event;
73
+ const timer = win.setTimeout(() => {
74
+ if (!getItems().includes(source))
75
+ return cancel();
76
+ try {
77
+ menu.setPointerCapture(pointerId);
78
+ }
79
+ catch {
80
+ // The pointer may have been released outside the browser during the hold.
81
+ return cancel();
82
+ }
83
+ const { left, top, width, height } = source.getBoundingClientRect();
84
+ const { backgroundColor, color, direction, font, padding, whiteSpace } = win.getComputedStyle(source);
85
+ preview = source.cloneNode(true);
86
+ preview.classList.add('tw-palette-category-drag-preview');
87
+ preview.setAttribute('data-palette-reorder-preview', '');
88
+ preview.inert = true;
89
+ Object.assign(preview.style, {
90
+ left: `${left}px`, top: `${top}px`, width: `${width}px`, height: `${height}px`,
91
+ backgroundColor: backgroundColor === 'rgba(0, 0, 0, 0)' ?
92
+ win.getComputedStyle(menu).backgroundColor : backgroundColor,
93
+ color, direction, font, padding, whiteSpace
94
+ });
95
+ // Mount outside the toolbox so its scrolling and clipping don't constrain the preview.
96
+ doc.body.append(preview);
97
+ suppressRelease = true;
98
+ menu.classList.add('tw-palette-category-reordering');
99
+ menu.setAttribute('data-palette-reordering', '');
100
+ source.setAttribute('data-palette-reorder-source', '');
101
+ }, holdDelay);
102
+ press = { pointerId, source, x, y, timer };
103
+ }, capture);
104
+ doc.addEventListener('pointermove', event => {
105
+ if (press?.pointerId !== event.pointerId)
106
+ return;
107
+ if (preview) {
108
+ preview.style.transform = `translate(${event.clientX - press.x}px, ${event.clientY - press.y}px)`;
109
+ markTarget(itemAt(event, getItems()));
110
+ }
111
+ else if (Math.hypot(event.clientX - press.x, event.clientY - press.y) > movementThreshold)
112
+ cancel();
113
+ }, capture);
114
+ doc.addEventListener('pointerup', event => {
115
+ if (press?.pointerId !== event.pointerId)
116
+ return;
117
+ if (!preview)
118
+ return cancel();
119
+ const items = getItems();
120
+ const from = items.indexOf(press.source);
121
+ const to = items.indexOf(itemAt(event, items));
122
+ cancel();
123
+ if (from >= 0 && to >= 0 && from !== to)
124
+ onDrop(from, to);
125
+ }, capture);
126
+ doc.addEventListener('pointercancel', event => {
127
+ if (press?.pointerId === event.pointerId)
128
+ cancel();
129
+ }, capture);
130
+ menu.addEventListener('lostpointercapture', event => {
131
+ if (event.target === menu && press?.pointerId === event.pointerId)
132
+ cancel();
133
+ }, capture);
134
+ win.addEventListener('blur', cancel, capture);
135
+ doc.addEventListener('keydown', event => {
136
+ if (!preview || event.key !== 'Escape')
137
+ return;
138
+ event.stopImmediatePropagation();
139
+ cancel();
140
+ }, capture);
141
+ // ScratchBlocks selects categories on mouseup or touchend. Ignore the release of a reorder.
142
+ const swallowRelease = (event) => {
143
+ if (!suppressRelease)
144
+ return;
145
+ event.preventDefault();
146
+ event.stopImmediatePropagation();
147
+ };
148
+ menu.addEventListener('mouseup', swallowRelease, capture);
149
+ menu.addEventListener('touchend', swallowRelease, { ...capture, passive: false });
150
+ menu.addEventListener('touchmove', event => {
151
+ if (preview)
152
+ event.preventDefault();
153
+ }, { ...capture, passive: false });
154
+ doc.addEventListener('contextmenu', event => {
155
+ if (!press || !menu.contains(event.target))
156
+ return;
157
+ event.preventDefault();
158
+ event.stopImmediatePropagation();
159
+ }, capture);
160
+ return {
161
+ cancel,
162
+ dispose() {
163
+ cancel();
164
+ events.abort();
165
+ }
166
+ };
167
+ }
@@ -0,0 +1,26 @@
1
+ export declare const paletteSearchHeight = 36;
2
+ type Bounds = {
3
+ left: number;
4
+ top: number;
5
+ width: number;
6
+ };
7
+ type PaletteItem<Block> = {
8
+ type: 'block';
9
+ block: Block;
10
+ } | {
11
+ type: 'button';
12
+ button: {
13
+ isLabel_: boolean;
14
+ getText(): string;
15
+ };
16
+ };
17
+ export declare function matchPaletteBlocks<Block>(items: PaletteItem<Block>[], category: string, query: string, heading: (text: string) => string, labels: (block: Block) => string): Set<Block>;
18
+ export declare function attachPaletteCategorySearch(panel: SVGElement, getLocale: () => string, change: (query: string, previous: string) => void): {
19
+ readonly query: string;
20
+ readonly emptyLabel: "一致するブロックがありません" | "No matching blocks";
21
+ place(bounds: Bounds | null): void;
22
+ close(): void;
23
+ contains(target: Node | null): boolean;
24
+ dispose(): void;
25
+ };
26
+ export {};
@@ -0,0 +1,74 @@
1
+ export const paletteSearchHeight = 36;
2
+ const normalize = (text) => text.normalize('NFKC').trim().toLocaleLowerCase();
3
+ export function matchPaletteBlocks(items, category, query, heading, labels) {
4
+ const matches = (text) => normalize(text).includes(query);
5
+ const categoryMatches = matches(heading(category));
6
+ let headingMatches = false;
7
+ const visible = new Set();
8
+ for (const item of items) {
9
+ if (item.type === 'button') {
10
+ if (item.button.isLabel_)
11
+ headingMatches = matches(heading(item.button.getText()));
12
+ }
13
+ else if (categoryMatches || headingMatches || matches(labels(item.block))) {
14
+ visible.add(item.block);
15
+ }
16
+ }
17
+ return visible;
18
+ }
19
+ export function attachPaletteCategorySearch(panel, getLocale, change) {
20
+ const doc = panel.ownerDocument;
21
+ const japanese = () => /^ja(?:-|$)/i.test(getLocale());
22
+ const input = doc.createElement('input');
23
+ input.type = 'search';
24
+ input.className = 'tw-palette-category-search';
25
+ input.autocomplete = 'off';
26
+ input.spellcheck = false;
27
+ input.hidden = true;
28
+ panel.after(input);
29
+ let query = '';
30
+ const update = () => {
31
+ const next = normalize(input.value);
32
+ if (next === query)
33
+ return;
34
+ const previous = query;
35
+ query = next;
36
+ change(query, previous);
37
+ };
38
+ input.addEventListener('input', event => {
39
+ if (!event.isComposing)
40
+ update();
41
+ });
42
+ input.addEventListener('compositionend', update);
43
+ return {
44
+ get query() {
45
+ return query;
46
+ },
47
+ get emptyLabel() {
48
+ return japanese() ? '一致するブロックがありません' : 'No matching blocks';
49
+ },
50
+ place(bounds) {
51
+ input.hidden = !bounds || bounds.width <= 59;
52
+ if (!bounds || input.hidden)
53
+ return;
54
+ const label = japanese() ? 'ブロックを検索' : 'Search blocks';
55
+ if (input.placeholder !== label) {
56
+ input.placeholder = label;
57
+ input.setAttribute('aria-label', label);
58
+ }
59
+ input.style.width = `${bounds.width - 59}px`;
60
+ input.style.transform = `translate(${bounds.left + 8}px, ${bounds.top + 4}px)`;
61
+ },
62
+ close() {
63
+ query = '';
64
+ input.value = '';
65
+ input.hidden = true;
66
+ },
67
+ contains(target) {
68
+ return input.contains(target);
69
+ },
70
+ dispose() {
71
+ input.remove();
72
+ }
73
+ };
74
+ }