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