@kubohiroya/turbowarp-plus-editor-code-views 0.0.0-stage → 0.1.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.
- package/LICENSE +373 -0
- package/README.ja.md +38 -0
- package/README.md +37 -2
- package/dist/asset-edit-session.d.ts +24 -0
- package/dist/asset-edit-session.js +58 -0
- package/dist/block-argument-text.d.ts +39 -0
- package/dist/block-argument-text.js +170 -0
- package/dist/block-drag.d.ts +17 -0
- package/dist/block-drag.js +184 -0
- package/dist/code-extensions.d.ts +38 -0
- package/dist/code-extensions.js +418 -0
- package/dist/code-pane.d.ts +63 -0
- package/dist/code-pane.js +363 -0
- package/dist/custom-extension-fields.d.ts +45 -0
- package/dist/custom-extension-fields.js +144 -0
- package/dist/detached-block-palette-view.d.ts +10 -0
- package/dist/detached-block-palette-view.js +62 -0
- package/dist/detached-block-palette.d.ts +41 -0
- package/dist/detached-block-palette.js +197 -0
- package/dist/dockview-unsaved.d.ts +45 -0
- package/dist/dockview-unsaved.js +123 -0
- package/dist/history.d.ts +57 -0
- package/dist/history.js +85 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +729 -0
- package/dist/native-extension-field.d.ts +26 -0
- package/dist/native-extension-field.js +204 -0
- package/dist/native-field-svg.d.ts +20 -0
- package/dist/native-field-svg.js +156 -0
- package/dist/palette-category-reorder.d.ts +4 -0
- package/dist/palette-category-reorder.js +167 -0
- package/dist/palette-category-search.d.ts +26 -0
- package/dist/palette-category-search.js +74 -0
- package/dist/palette-dropdown-resize.d.ts +19 -0
- package/dist/palette-dropdown-resize.js +135 -0
- package/dist/parent-field-layout.d.ts +2 -0
- package/dist/parent-field-layout.js +90 -0
- package/dist/parent-field-mirror.d.ts +3 -0
- package/dist/parent-field-mirror.js +290 -0
- package/dist/parent-field-resources.d.ts +9 -0
- package/dist/parent-field-resources.js +199 -0
- package/dist/preview-chrome.d.ts +9 -0
- package/dist/preview-chrome.js +78 -0
- package/dist/procedure-editor.d.ts +9 -0
- package/dist/procedure-editor.js +122 -0
- package/dist/procedure-edits.d.ts +16 -0
- package/dist/procedure-edits.js +47 -0
- package/dist/programmatic-extension-field.d.ts +20 -0
- package/dist/programmatic-extension-field.js +69 -0
- package/dist/protocol.d.ts +15 -0
- package/dist/protocol.js +36 -0
- package/dist/script-layout-dialog.d.ts +10 -0
- package/dist/script-layout-dialog.js +93 -0
- package/dist/script-layout-view.d.ts +68 -0
- package/dist/script-layout-view.js +164 -0
- package/dist/script-layout-workspace.d.ts +45 -0
- package/dist/script-layout-workspace.js +55 -0
- package/dist/script-layout.d.ts +17 -0
- package/dist/script-layout.js +25 -0
- package/dist/script-view-menu.d.ts +46 -0
- package/dist/script-view-menu.js +161 -0
- package/dist/sprite-code-windows.d.ts +31 -0
- package/dist/sprite-code-windows.js +180 -0
- package/dist/stage-code-prewarm.d.ts +52 -0
- package/dist/stage-code-prewarm.js +216 -0
- package/dist/target-combobox.d.ts +10 -0
- package/dist/target-combobox.js +92 -0
- package/dist/variable-references.d.ts +1 -0
- package/dist/variable-references.js +87 -0
- package/dist/workspace.d.ts +103 -0
- package/dist/workspace.js +1102 -0
- package/package.json +100 -4
- package/src/asset-edit-session.ts +72 -0
- package/src/block-argument-text.ts +172 -0
- package/src/block-drag.ts +190 -0
- package/src/code-extensions.ts +394 -0
- package/src/code-pane.ts +353 -0
- package/src/custom-extension-fields.ts +154 -0
- package/src/detached-block-palette-view.tsx +97 -0
- package/src/detached-block-palette.ts +218 -0
- package/src/dockview-unsaved.ts +134 -0
- package/src/history.ts +114 -0
- package/src/index.ts +680 -0
- package/src/native-extension-field.ts +201 -0
- package/src/native-field-svg.ts +140 -0
- package/src/palette-category-reorder.ts +155 -0
- package/src/palette-category-search.ts +82 -0
- package/src/palette-dropdown-resize.ts +132 -0
- package/src/parent-field-layout.ts +88 -0
- package/src/parent-field-mirror.ts +260 -0
- package/src/parent-field-resources.ts +179 -0
- package/src/preview-chrome.ts +82 -0
- package/src/procedure-editor.ts +123 -0
- package/src/procedure-edits.ts +46 -0
- package/src/programmatic-extension-field.ts +76 -0
- package/src/protocol.ts +47 -0
- package/src/script-layout-dialog.ts +104 -0
- package/src/script-layout-view.ts +198 -0
- package/src/script-layout-workspace.ts +95 -0
- package/src/script-layout.ts +40 -0
- package/src/script-view-menu.ts +213 -0
- package/src/sprite-code-windows.tsx +182 -0
- package/src/stage-code-prewarm.ts +242 -0
- package/src/styles.css +595 -0
- package/src/target-combobox.tsx +106 -0
- package/src/variable-references.ts +85 -0
- package/src/workspace.ts +1124 -0
- package/tsconfig.json +23 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
|
|
2
|
+
type Size = {width: number; height: number};
|
|
3
|
+
type Bounds = Size & {left: number; top: number};
|
|
4
|
+
type Drag = {pointerId: number; x: number; y: number; start: Size; size: Size; previousLeft: number | undefined};
|
|
5
|
+
|
|
6
|
+
const handleSize = 18;
|
|
7
|
+
const storageKey = (id: string) => `tw-plus-palette-size:${id}`;
|
|
8
|
+
|
|
9
|
+
export function attachPaletteDropdownResize(panel: SVGElement, onResize: () => void) {
|
|
10
|
+
const doc = panel.ownerDocument;
|
|
11
|
+
const win = doc.defaultView;
|
|
12
|
+
const handle = doc.createElement('div');
|
|
13
|
+
handle.className = 'tw-palette-dropdown-resize-handle';
|
|
14
|
+
handle.setAttribute('data-palette-resize-handle', '');
|
|
15
|
+
handle.setAttribute('aria-hidden', 'true');
|
|
16
|
+
handle.style.width = handle.style.height = `${handleSize}px`;
|
|
17
|
+
handle.hidden = true;
|
|
18
|
+
panel.after(handle);
|
|
19
|
+
|
|
20
|
+
const events = new AbortController();
|
|
21
|
+
const capture = {capture: true, signal: events.signal};
|
|
22
|
+
const unsavedSizes = new Map<string, Size>();
|
|
23
|
+
let categoryId: string | null = null;
|
|
24
|
+
let preferredSize: Size | undefined;
|
|
25
|
+
let bounds: Bounds | null | undefined;
|
|
26
|
+
let drag: Drag | undefined;
|
|
27
|
+
let left: number | undefined;
|
|
28
|
+
|
|
29
|
+
const readSize = (id: string): Size | undefined => {
|
|
30
|
+
if (unsavedSizes.has(id)) return unsavedSizes.get(id);
|
|
31
|
+
try {
|
|
32
|
+
const stored = win.localStorage.getItem(storageKey(id));
|
|
33
|
+
if (!stored) return;
|
|
34
|
+
const size: {width?: unknown; height?: unknown} | null = JSON.parse(stored);
|
|
35
|
+
if (size && typeof size.width === 'number' && typeof size.height === 'number' &&
|
|
36
|
+
Number.isFinite(size.width) && size.width > 0 && Number.isFinite(size.height) && size.height > 0) {
|
|
37
|
+
return {width: size.width, height: size.height};
|
|
38
|
+
}
|
|
39
|
+
} catch {
|
|
40
|
+
// The saved preference may be malformed or storage unavailable.
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const stopDrag = () => {
|
|
45
|
+
if (!drag) return;
|
|
46
|
+
const {pointerId} = drag;
|
|
47
|
+
drag = undefined;
|
|
48
|
+
if (handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
handle.addEventListener('pointerdown', event => {
|
|
52
|
+
if (event.button !== 0 || drag || categoryId === null || !bounds) return;
|
|
53
|
+
event.preventDefault();
|
|
54
|
+
event.stopPropagation();
|
|
55
|
+
const {width, height} = bounds;
|
|
56
|
+
const start = {width, height};
|
|
57
|
+
drag = {pointerId: event.pointerId, x: event.clientX, y: event.clientY, start, size: start, previousLeft: left};
|
|
58
|
+
left = bounds.left;
|
|
59
|
+
handle.setPointerCapture(event.pointerId);
|
|
60
|
+
}, capture);
|
|
61
|
+
handle.addEventListener('pointermove', event => {
|
|
62
|
+
if (drag?.pointerId !== event.pointerId) return;
|
|
63
|
+
const {start, x, y} = drag;
|
|
64
|
+
drag.size = {
|
|
65
|
+
width: Math.max(Math.min(80, start.width), start.width + event.clientX - x),
|
|
66
|
+
height: Math.max(Math.min(64, start.height), start.height + event.clientY - y)
|
|
67
|
+
};
|
|
68
|
+
onResize();
|
|
69
|
+
}, capture);
|
|
70
|
+
handle.addEventListener('pointerup', event => {
|
|
71
|
+
if (drag?.pointerId !== event.pointerId) return;
|
|
72
|
+
if (bounds && (drag.start.width !== bounds.width || drag.start.height !== bounds.height)) {
|
|
73
|
+
preferredSize = {width: bounds.width, height: bounds.height};
|
|
74
|
+
try {
|
|
75
|
+
win.localStorage.setItem(storageKey(categoryId), JSON.stringify(preferredSize));
|
|
76
|
+
unsavedSizes.delete(categoryId);
|
|
77
|
+
} catch {
|
|
78
|
+
unsavedSizes.set(categoryId, preferredSize);
|
|
79
|
+
}
|
|
80
|
+
} else left = drag.previousLeft;
|
|
81
|
+
stopDrag();
|
|
82
|
+
onResize();
|
|
83
|
+
}, capture);
|
|
84
|
+
const cancelDrag = (event: PointerEvent) => {
|
|
85
|
+
if (drag?.pointerId !== event.pointerId) return;
|
|
86
|
+
left = drag.previousLeft;
|
|
87
|
+
stopDrag();
|
|
88
|
+
onResize();
|
|
89
|
+
};
|
|
90
|
+
handle.addEventListener('pointercancel', cancelDrag, capture);
|
|
91
|
+
handle.addEventListener('lostpointercapture', cancelDrag, capture);
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
get size() {
|
|
95
|
+
return drag?.size ?? preferredSize;
|
|
96
|
+
},
|
|
97
|
+
get left() {
|
|
98
|
+
return left;
|
|
99
|
+
},
|
|
100
|
+
open(id: string) {
|
|
101
|
+
categoryId = id;
|
|
102
|
+
preferredSize = readSize(id);
|
|
103
|
+
},
|
|
104
|
+
close() {
|
|
105
|
+
stopDrag();
|
|
106
|
+
categoryId = null;
|
|
107
|
+
preferredSize = undefined;
|
|
108
|
+
bounds = undefined;
|
|
109
|
+
left = undefined;
|
|
110
|
+
handle.hidden = true;
|
|
111
|
+
},
|
|
112
|
+
place(rect: Bounds | null) {
|
|
113
|
+
bounds = rect;
|
|
114
|
+
handle.hidden = !rect || rect.width < handleSize || rect.height < handleSize;
|
|
115
|
+
if (handle.hidden) return;
|
|
116
|
+
const x = rect.left + rect.width - handleSize;
|
|
117
|
+
const y = rect.top + rect.height - handleSize;
|
|
118
|
+
handle.style.transform = `translate(${x}px, ${y}px)`;
|
|
119
|
+
},
|
|
120
|
+
followAnchor() {
|
|
121
|
+
if (!drag) left = undefined;
|
|
122
|
+
},
|
|
123
|
+
contains(target: Node | null) {
|
|
124
|
+
return handle.contains(target);
|
|
125
|
+
},
|
|
126
|
+
dispose() {
|
|
127
|
+
stopDrag();
|
|
128
|
+
events.abort();
|
|
129
|
+
handle.remove();
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
const flexDisplays = new Set(['flex', 'inline-flex']);
|
|
2
|
+
const gridDisplays = new Set(['grid', 'inline-grid']);
|
|
3
|
+
const dimensions = ['width', 'min-width', 'max-width'];
|
|
4
|
+
const align = /^(?:normal|stretch|start|end|self-start|self-end|flex-start|flex-end|center|baseline|auto)$/;
|
|
5
|
+
const distribute = /^(?:normal|stretch|start|end|flex-start|flex-end|left|right|center|space-between|space-around|space-evenly)$/;
|
|
6
|
+
const placement = /^(?:auto|(?:span )?[1-8])$/;
|
|
7
|
+
|
|
8
|
+
function pixels(value: string, limit: number) {
|
|
9
|
+
return /^\d+(?:\.\d+)?px$/.test(value) && Number.parseFloat(value) <= limit;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function size(value: string) {
|
|
13
|
+
return value === 'auto' || pixels(value, 480) ||
|
|
14
|
+
(/^\d+(?:\.\d+)?%$/.test(value) && Number.parseFloat(value) <= 100);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function tracks(value: string) {
|
|
18
|
+
if (value === 'none') return true;
|
|
19
|
+
const list = value.split(/\s+/);
|
|
20
|
+
return list.length <= 8 && list.every(track => track === 'auto' || pixels(track, 480) ||
|
|
21
|
+
(/^\d+(?:\.\d+)?fr$/.test(track) && Number.parseFloat(track) <= 16));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Recreate the layout using the popup's own dimensions and the mirrored controls. */
|
|
25
|
+
export function createFieldLayoutMirror(original: HTMLElement, proxy: HTMLElement) {
|
|
26
|
+
let applied = new Set<string>();
|
|
27
|
+
return (computed: CSSStyleDeclaration) => {
|
|
28
|
+
const next = new Set<string>();
|
|
29
|
+
const set = (name: string, value: string) => {
|
|
30
|
+
next.add(name);
|
|
31
|
+
if (proxy.style.getPropertyValue(name) !== value) proxy.style.setProperty(name, value);
|
|
32
|
+
};
|
|
33
|
+
const copy = (name: string, accepts: (value: string) => boolean, value = computed.getPropertyValue(name)) => {
|
|
34
|
+
if (accepts(value)) set(name, value);
|
|
35
|
+
};
|
|
36
|
+
const parentDisplay = proxy.parentElement?.style.display;
|
|
37
|
+
const flexItem = flexDisplays.has(parentDisplay);
|
|
38
|
+
const gridItem = gridDisplays.has(parentDisplay);
|
|
39
|
+
const flex = flexDisplays.has(computed.display);
|
|
40
|
+
const grid = gridDisplays.has(computed.display);
|
|
41
|
+
const typed = flex || grid || flexItem || gridItem ? original.computedStyleMap?.() : undefined;
|
|
42
|
+
const computedValue = (name: string) => typed?.get(name)?.toString() ?? '';
|
|
43
|
+
|
|
44
|
+
// The CSSOM resolved track list is measured in the parent's pixels. Keep fr units.
|
|
45
|
+
const columns = grid ? computedValue('grid-template-columns') : '';
|
|
46
|
+
const rows = grid ? computedValue('grid-template-rows') : '';
|
|
47
|
+
const supportedGrid = grid && tracks(columns) && tracks(rows) && computedValue('grid-template-areas') === 'none';
|
|
48
|
+
if (flex || supportedGrid) {
|
|
49
|
+
set('display', computed.display);
|
|
50
|
+
for (const name of ['row-gap', 'column-gap']) copy(name, value => value === 'normal' || pixels(value, 64));
|
|
51
|
+
copy('justify-content', value => distribute.test(value));
|
|
52
|
+
copy('align-content', value => distribute.test(value) || value === 'baseline');
|
|
53
|
+
copy('align-items', value => align.test(value));
|
|
54
|
+
}
|
|
55
|
+
if (flex) {
|
|
56
|
+
copy('flex-direction', value => /^(?:row|column)(?:-reverse)?$/.test(value));
|
|
57
|
+
copy('flex-wrap', value => /^(?:nowrap|wrap|wrap-reverse)$/.test(value));
|
|
58
|
+
}
|
|
59
|
+
if (supportedGrid) {
|
|
60
|
+
set('grid-template-columns', columns);
|
|
61
|
+
set('grid-template-rows', rows);
|
|
62
|
+
copy('grid-auto-flow', value => /^(?:row|column)(?: dense)?$/.test(value) || value === 'dense');
|
|
63
|
+
copy('justify-items', value => align.test(value));
|
|
64
|
+
}
|
|
65
|
+
if (flex || supportedGrid || flexItem || gridItem) {
|
|
66
|
+
for (const name of dimensions) copy(name, value => size(value) || value === 'none', computedValue(name));
|
|
67
|
+
copy('box-sizing', value => value === 'border-box' || value === 'content-box');
|
|
68
|
+
}
|
|
69
|
+
if (flexItem || gridItem) {
|
|
70
|
+
copy('align-self', value => align.test(value));
|
|
71
|
+
}
|
|
72
|
+
if (flexItem) {
|
|
73
|
+
for (const name of ['flex-grow', 'flex-shrink']) {
|
|
74
|
+
copy(name, value => /^\d+(?:\.\d+)?$/.test(value) && Number(value) <= 16);
|
|
75
|
+
}
|
|
76
|
+
copy('flex-basis', size);
|
|
77
|
+
}
|
|
78
|
+
if (gridItem) {
|
|
79
|
+
copy('justify-self', value => align.test(value));
|
|
80
|
+
for (const axis of ['column', 'row']) {
|
|
81
|
+
copy(`grid-${axis}-start`, value => placement.test(value));
|
|
82
|
+
copy(`grid-${axis}-end`, value => placement.test(value));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
for (const name of applied) if (!next.has(name)) proxy.style.removeProperty(name);
|
|
86
|
+
applied = next;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import {createFieldLayoutMirror} from './parent-field-layout.ts';
|
|
2
|
+
import {createFieldResources, type FieldResourceOptions} from './parent-field-resources.ts';
|
|
3
|
+
|
|
4
|
+
const htmlNamespace = 'http://www.w3.org/1999/xhtml';
|
|
5
|
+
const elements = new Set(['div', 'span', 'p', 'fieldset', 'legend', 'label', 'textarea', 'input', 'button']);
|
|
6
|
+
const inputTypes = new Set(['text', 'number', 'range']);
|
|
7
|
+
const attributes = ['aria-label', 'title', 'placeholder', 'min', 'max', 'step', 'maxlength'];
|
|
8
|
+
|
|
9
|
+
const sides = ['top', 'right', 'bottom', 'left'];
|
|
10
|
+
const colors = ['color', 'background-color', ...sides.map(side => `border-${side}-color`)];
|
|
11
|
+
const lengths = ['font-size', 'line-height', ...sides.flatMap(side => [`padding-${side}`, `border-${side}-width`]),
|
|
12
|
+
'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'];
|
|
13
|
+
const borderStyles = sides.map(side => `border-${side}-style`);
|
|
14
|
+
const typography = ['font-family', 'font-style', 'font-weight'];
|
|
15
|
+
const length = /^\d+(?:\.\d+)?px$/;
|
|
16
|
+
const color = /^(?:#[\da-f]{3,8}|[a-z]+|rgba?\([\d.,%\s]+\))$/i;
|
|
17
|
+
const generatedText = /^(?:"[^"\\\x00-\x1f]{0,120}"|none|normal)$/;
|
|
18
|
+
const stateSelector = /^\.([\w-]+)(:hover|:focus|:focus-visible)(::before|::after)?$/;
|
|
19
|
+
const pseudoElements = ['::before', '::after'];
|
|
20
|
+
const animatedColors = colors.map(name => name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()));
|
|
21
|
+
|
|
22
|
+
function widgetAnimation(original: HTMLElement) {
|
|
23
|
+
const parent = original.ownerDocument.defaultView;
|
|
24
|
+
if (!parent?.CSSAnimation || !parent.KeyframeEffect || !original.getAnimations) return;
|
|
25
|
+
const animations = original.getAnimations().filter(animation => animation instanceof parent.CSSAnimation &&
|
|
26
|
+
animation.effect instanceof parent.KeyframeEffect && animation.effect.target === original &&
|
|
27
|
+
!animation.effect.pseudoElement);
|
|
28
|
+
if (animations.length !== 1) return;
|
|
29
|
+
const [animation] = animations;
|
|
30
|
+
if (animation.playState !== 'running' || animation.playbackRate !== 1 ||
|
|
31
|
+
animation.timeline !== original.ownerDocument.timeline) return;
|
|
32
|
+
const effect = animation.effect as KeyframeEffect;
|
|
33
|
+
const timing = effect.getTiming();
|
|
34
|
+
if (effect.composite !== 'replace' || typeof timing.duration !== 'number' ||
|
|
35
|
+
timing.duration <= 0 || timing.duration > 60000 || Math.abs(timing.delay) > 60000) return;
|
|
36
|
+
const source = effect.getKeyframes();
|
|
37
|
+
if (source.length < 2 || source.length > 32 ||
|
|
38
|
+
source.some(frame => frame.composite !== 'auto' && frame.composite !== 'replace')) return;
|
|
39
|
+
const accepts = (property: string, value: unknown) => typeof value === 'string' && value.length <= 128 &&
|
|
40
|
+
(property === 'opacity' ? /^\d+(?:\.\d+)?$/.test(value) && Number(value) <= 1 : color.test(value));
|
|
41
|
+
// Require explicit endpoints so the replay does not interpolate from the parent's sampled style.
|
|
42
|
+
const properties = [...animatedColors, 'opacity'].filter(property =>
|
|
43
|
+
source[0].computedOffset === 0 && source.at(-1).computedOffset === 1 &&
|
|
44
|
+
accepts(property, source[0][property]) && accepts(property, source.at(-1)[property]));
|
|
45
|
+
if (!properties.length) return;
|
|
46
|
+
const keyframes: Keyframe[] = source.map(frame => {
|
|
47
|
+
const projected: Keyframe = {offset: frame.computedOffset, easing: frame.easing};
|
|
48
|
+
for (const property of properties) {
|
|
49
|
+
if (accepts(property, frame[property])) projected[property] = frame[property];
|
|
50
|
+
}
|
|
51
|
+
return projected;
|
|
52
|
+
});
|
|
53
|
+
return {keyframes, timing};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function mirrorWidgetAnimations(host: HTMLElement, nodes: [HTMLElement, HTMLElement][]) {
|
|
57
|
+
const motion = host.ownerDocument.defaultView?.matchMedia('(prefers-reduced-motion: reduce)');
|
|
58
|
+
if (!motion || motion.matches) return () => {};
|
|
59
|
+
const animations: Animation[] = [];
|
|
60
|
+
for (const [original, proxy] of nodes) {
|
|
61
|
+
const projection = widgetAnimation(original);
|
|
62
|
+
if (projection) animations.push(proxy.animate(projection.keyframes, projection.timing));
|
|
63
|
+
}
|
|
64
|
+
const stop = () => {
|
|
65
|
+
motion.removeEventListener('change', stop);
|
|
66
|
+
for (const animation of animations) animation.cancel();
|
|
67
|
+
};
|
|
68
|
+
if (animations.length) motion.addEventListener('change', stop, {once: true});
|
|
69
|
+
return stop;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function copyAppearance(source: CSSStyleDeclaration, target: CSSStyleDeclaration, {
|
|
73
|
+
pseudo = false, priority = '', fontFamily = ''
|
|
74
|
+
} = {}) {
|
|
75
|
+
const copy = (name: string, accept: (value: string) => boolean) => {
|
|
76
|
+
const value = name === 'font-family' && fontFamily ? fontFamily : source.getPropertyValue(name);
|
|
77
|
+
const safe = value.length <= 128 && accept(value) ? value : '';
|
|
78
|
+
if (target.getPropertyValue(name) !== safe) target.setProperty(name, safe, priority);
|
|
79
|
+
};
|
|
80
|
+
for (const name of colors) copy(name, value => color.test(value));
|
|
81
|
+
for (const name of lengths) copy(name, value => (name === 'line-height' && value === 'normal') ||
|
|
82
|
+
(length.test(value) && Number.parseFloat(value) <= 128));
|
|
83
|
+
for (const name of borderStyles) copy(name, value => /^(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)$/.test(value));
|
|
84
|
+
for (const name of typography) copy(name, value => {
|
|
85
|
+
if (name === 'font-family') return /^[\w ,'"-]+$/.test(value);
|
|
86
|
+
if (name === 'font-style') return /^(normal|italic|oblique)$/.test(value);
|
|
87
|
+
return /^(normal|bold|[1-9]00)$/.test(value);
|
|
88
|
+
});
|
|
89
|
+
if (pseudo) copy('content', value => generatedText.test(value));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function readStateRules(document: Document) {
|
|
93
|
+
const rules: {className: string; state: string; pseudo: string; style: CSSStyleDeclaration}[] = [];
|
|
94
|
+
for (const sheet of document.styleSheets) {
|
|
95
|
+
if (sheet.disabled || (sheet.media.mediaText && !document.defaultView?.matchMedia(sheet.media.mediaText).matches)) continue;
|
|
96
|
+
let source: CSSRuleList;
|
|
97
|
+
try {
|
|
98
|
+
source = sheet.cssRules;
|
|
99
|
+
} catch {
|
|
100
|
+
continue; // Cross-origin stylesheets are opaque.
|
|
101
|
+
}
|
|
102
|
+
for (const rule of source) {
|
|
103
|
+
if (rule.type !== 1) continue;
|
|
104
|
+
const {selectorText, style} = rule as CSSStyleRule;
|
|
105
|
+
const match = stateSelector.exec(selectorText);
|
|
106
|
+
if (match) rules.push({className: match[1], state: match[2], pseudo: match[3] ?? '', style});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return rules;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function mirrorWidgetStyles(parent: Window, host: HTMLElement, nodes: [HTMLElement, HTMLElement][]) {
|
|
113
|
+
const style = host.ownerDocument.createElement('style');
|
|
114
|
+
host.append(style);
|
|
115
|
+
const sheet = style.sheet;
|
|
116
|
+
if (!sheet) return () => {};
|
|
117
|
+
const stateRules = readStateRules(parent.document);
|
|
118
|
+
const refresh: (() => void)[] = [];
|
|
119
|
+
nodes.forEach(([original, proxy], index) => {
|
|
120
|
+
proxy.dataset.plusNativeFieldNode = String(index);
|
|
121
|
+
const selector = `[data-plus-native-field] [data-plus-native-field-node="${index}"]`;
|
|
122
|
+
const add = (suffix: string) => {
|
|
123
|
+
const index = sheet.insertRule(`${selector}${suffix} {}`, sheet.cssRules.length);
|
|
124
|
+
return (sheet.cssRules[index] as CSSStyleRule).style;
|
|
125
|
+
};
|
|
126
|
+
for (const pseudo of pseudoElements) {
|
|
127
|
+
let target: CSSStyleDeclaration | undefined;
|
|
128
|
+
refresh.push(() => {
|
|
129
|
+
const computed = parent.getComputedStyle(original, pseudo);
|
|
130
|
+
if (!target && (!generatedText.test(computed.content) || !computed.content.startsWith('"'))) return;
|
|
131
|
+
target ??= add(pseudo);
|
|
132
|
+
copyAppearance(computed, target, {pseudo: true});
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
for (const {className, state, pseudo, style} of stateRules) {
|
|
136
|
+
if (!original.classList.contains(className)) continue;
|
|
137
|
+
// Override the inline baseline while letting the child browser resolve the state.
|
|
138
|
+
copyAppearance(style, add(state + pseudo), {pseudo: Boolean(pseudo), priority: 'important'});
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
return () => {for (const update of refresh) update();};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
type TextControl = HTMLInputElement | HTMLTextAreaElement;
|
|
145
|
+
|
|
146
|
+
/** The parent's widget remains authoritative, including its document-level handlers. */
|
|
147
|
+
export function mirrorParentField(source: HTMLElement, host: HTMLElement, valid: () => boolean, options?: FieldResourceOptions) {
|
|
148
|
+
const parent = source.ownerDocument.defaultView;
|
|
149
|
+
if (!parent) return;
|
|
150
|
+
const sync: (() => void)[] = [];
|
|
151
|
+
const nodes: [HTMLElement, HTMLElement][] = [];
|
|
152
|
+
const resources = createFieldResources(source, options, valid);
|
|
153
|
+
const fonts = new WeakMap<HTMLElement, string>();
|
|
154
|
+
let remaining = 128;
|
|
155
|
+
let controls = 0;
|
|
156
|
+
|
|
157
|
+
function mirror(node: Node, depth: number): Node | undefined {
|
|
158
|
+
if (remaining <= 0 || depth > 8) return;
|
|
159
|
+
remaining--;
|
|
160
|
+
if (node.nodeType === 3) {
|
|
161
|
+
const copy = host.ownerDocument.createTextNode('');
|
|
162
|
+
sync.push(() => {copy.data = (node.textContent ?? '').slice(0, 1024);});
|
|
163
|
+
return copy;
|
|
164
|
+
}
|
|
165
|
+
if (node.nodeType !== 1) return;
|
|
166
|
+
const original = node as HTMLElement;
|
|
167
|
+
const tag = original.localName;
|
|
168
|
+
if (original.namespaceURI !== htmlNamespace || !(elements.has(tag) || (tag === 'img' && resources.hasImage(original)))) return;
|
|
169
|
+
if (tag === 'input' && !inputTypes.has((original as HTMLInputElement).type)) return;
|
|
170
|
+
if (tag === 'button' && (original as HTMLButtonElement).form && (original as HTMLButtonElement).type !== 'button') return;
|
|
171
|
+
const proxy = host.ownerDocument.createElement(tag);
|
|
172
|
+
const mirrorLayout = createFieldLayoutMirror(original, proxy);
|
|
173
|
+
nodes.push([original, proxy]);
|
|
174
|
+
sync.push(() => {
|
|
175
|
+
proxy.hidden = original.hidden;
|
|
176
|
+
const computed = parent.getComputedStyle(original);
|
|
177
|
+
copyAppearance(computed, proxy.style, {fontFamily: fonts.get(proxy)});
|
|
178
|
+
mirrorLayout(computed);
|
|
179
|
+
});
|
|
180
|
+
for (const name of attributes) {
|
|
181
|
+
const value = original.getAttribute(name);
|
|
182
|
+
if (value !== null) proxy.setAttribute(name, value.slice(0, 1024));
|
|
183
|
+
}
|
|
184
|
+
if (tag === 'img') {
|
|
185
|
+
proxy.setAttribute('alt', (original.getAttribute('alt') ?? '').slice(0, 1024));
|
|
186
|
+
for (const name of ['width', 'height']) {
|
|
187
|
+
const size = original.getAttribute(name) ?? '';
|
|
188
|
+
if (/^[1-9]\d{0,2}$/.test(size) && Number(size) <= 512) proxy.setAttribute(name, size);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const canRelay = () => valid() && source.contains(original);
|
|
192
|
+
if (tag === 'input' || tag === 'textarea') {
|
|
193
|
+
controls++;
|
|
194
|
+
const control = original as TextControl;
|
|
195
|
+
const copy = proxy as TextControl;
|
|
196
|
+
if (tag === 'input') (copy as HTMLInputElement).type = (control as HTMLInputElement).type;
|
|
197
|
+
sync.push(() => {
|
|
198
|
+
copy.disabled = control.disabled;
|
|
199
|
+
copy.readOnly = control.readOnly;
|
|
200
|
+
if (copy.value !== control.value) copy.value = control.value;
|
|
201
|
+
});
|
|
202
|
+
for (const type of ['input', 'change']) {
|
|
203
|
+
copy.addEventListener(type, event => {
|
|
204
|
+
if (!canRelay() || control.disabled || control.readOnly) return;
|
|
205
|
+
control.value = copy.value;
|
|
206
|
+
const input = event as InputEvent;
|
|
207
|
+
control.dispatchEvent(type === 'input' ? new parent.InputEvent(type, {
|
|
208
|
+
bubbles: true, data: input.data, inputType: input.inputType, isComposing: input.isComposing
|
|
209
|
+
}) : new parent.Event(type, {bubbles: true}));
|
|
210
|
+
refresh();
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
} else {
|
|
214
|
+
if (tag === 'button') {
|
|
215
|
+
controls++;
|
|
216
|
+
const button = proxy as HTMLButtonElement;
|
|
217
|
+
const control = original as HTMLButtonElement;
|
|
218
|
+
button.type = 'button';
|
|
219
|
+
sync.push(() => {button.disabled = control.disabled;});
|
|
220
|
+
button.addEventListener('click', () => {
|
|
221
|
+
if (!canRelay() || control.disabled) return;
|
|
222
|
+
original.dispatchEvent(new parent.MouseEvent('click', {bubbles: true, cancelable: true}));
|
|
223
|
+
refresh();
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
if (tag === 'fieldset') sync.push(() => {
|
|
227
|
+
(proxy as HTMLFieldSetElement).disabled = (original as HTMLFieldSetElement).disabled;
|
|
228
|
+
});
|
|
229
|
+
for (const child of original.childNodes) {
|
|
230
|
+
const copy = mirror(child, depth + 1);
|
|
231
|
+
if (copy) proxy.append(copy);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return proxy;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function refresh() {
|
|
238
|
+
for (const update of sync) update();
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
for (const node of source.childNodes) {
|
|
242
|
+
const copy = mirror(node, 0);
|
|
243
|
+
if (copy) host.append(copy);
|
|
244
|
+
}
|
|
245
|
+
if (!controls) return;
|
|
246
|
+
sync.push(mirrorWidgetStyles(parent, host, nodes));
|
|
247
|
+
refresh();
|
|
248
|
+
const stopAnimations = mirrorWidgetAnimations(host, nodes);
|
|
249
|
+
for (const [original, proxy] of nodes) {
|
|
250
|
+
void resources.attach(original, proxy)?.then(family => {
|
|
251
|
+
if (!family || !valid()) return;
|
|
252
|
+
fonts.set(proxy, family);
|
|
253
|
+
proxy.style.fontFamily = family;
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
return () => {
|
|
257
|
+
resources.dispose();
|
|
258
|
+
stopAnimations();
|
|
259
|
+
};
|
|
260
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import {isSafeSvgDrawingAttribute, svgDrawingElements} from './native-field-svg.ts';
|
|
2
|
+
|
|
3
|
+
const maxBytes = 256 * 1024;
|
|
4
|
+
const maxSide = 512;
|
|
5
|
+
const idPattern = /^[\w-]{1,48}$/;
|
|
6
|
+
const pngHeader = [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82];
|
|
7
|
+
const svgNamespace = 'http://www.w3.org/2000/svg';
|
|
8
|
+
|
|
9
|
+
type Asset = {kind: 'image' | 'font'; url: string};
|
|
10
|
+
export type FieldResourceOptions = {manifest: unknown; canFetch(url: string): boolean | Promise<boolean>};
|
|
11
|
+
|
|
12
|
+
function readManifest(manifest: unknown) {
|
|
13
|
+
const assets = new Map<string, Asset>();
|
|
14
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) return assets;
|
|
15
|
+
for (const [id, value] of Object.entries(manifest).slice(0, 8)) {
|
|
16
|
+
if (!idPattern.test(id) || !value || typeof value !== 'object') continue;
|
|
17
|
+
const {kind, url} = value as Partial<Asset>;
|
|
18
|
+
if ((kind !== 'image' && kind !== 'font') || typeof url !== 'string' || url.length > 2048) continue;
|
|
19
|
+
const parsed = URL.parse(url);
|
|
20
|
+
if (parsed?.protocol !== 'https:' || parsed.username || parsed.password || parsed.hash) continue;
|
|
21
|
+
assets.set(id, {kind, url: parsed.href});
|
|
22
|
+
}
|
|
23
|
+
return assets;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function readAsset(parent: Window, asset: Asset, signal: AbortSignal) {
|
|
27
|
+
const response = await parent.fetch(asset.url, {
|
|
28
|
+
signal, mode: 'cors', credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer'
|
|
29
|
+
});
|
|
30
|
+
const type = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
|
|
31
|
+
const acceptable = asset.kind === 'font' ? type === 'font/woff2' : type === 'image/png' || type === 'image/svg+xml';
|
|
32
|
+
if (!response.ok || !acceptable || !response.body || Number(response.headers.get('content-length')) > maxBytes) {
|
|
33
|
+
await response.body?.cancel();
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const reader = response.body.getReader();
|
|
37
|
+
const buffer = new Uint8Array(maxBytes);
|
|
38
|
+
let count = 0;
|
|
39
|
+
try {
|
|
40
|
+
for (;;) {
|
|
41
|
+
const {done, value} = await reader.read();
|
|
42
|
+
if (done) return {type, bytes: buffer.slice(0, count)};
|
|
43
|
+
if (count + value.byteLength > maxBytes) {
|
|
44
|
+
await reader.cancel();
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
buffer.set(value, count);
|
|
48
|
+
count += value.byteLength;
|
|
49
|
+
}
|
|
50
|
+
} finally {
|
|
51
|
+
reader.releaseLock();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function staticSvg(document: Document, bytes: Uint8Array<ArrayBuffer>) {
|
|
56
|
+
const view = document.defaultView;
|
|
57
|
+
const markup = new TextDecoder().decode(bytes);
|
|
58
|
+
if (/<!doctype/i.test(markup)) return;
|
|
59
|
+
const svg = new view.DOMParser().parseFromString(markup, 'image/svg+xml').documentElement;
|
|
60
|
+
if (svg.localName !== 'svg' || svg.namespaceURI !== svgNamespace) return;
|
|
61
|
+
const output = document.createElementNS(svgNamespace, 'svg');
|
|
62
|
+
for (const name of ['width', 'height']) {
|
|
63
|
+
const size = svg.getAttribute(name) ?? '';
|
|
64
|
+
if (!/^\d+(?:\.\d+)?(?:px)?$/.test(size) || Number.parseFloat(size) <= 0 || Number.parseFloat(size) > maxSide) return;
|
|
65
|
+
output.setAttribute(name, size);
|
|
66
|
+
}
|
|
67
|
+
const viewBox = svg.getAttribute('viewBox')?.trim().split(/[\s,]+/);
|
|
68
|
+
if (viewBox?.length === 4 && viewBox.every(value => /^-?\d+(?:\.\d+)?$/.test(value) && Number.isFinite(Number(value))) &&
|
|
69
|
+
Number(viewBox[2]) > 0 && Number(viewBox[3]) > 0) output.setAttribute('viewBox', viewBox.join(' '));
|
|
70
|
+
let remaining = 128;
|
|
71
|
+
function copy(original: Element, target: SVGElement, depth: number) {
|
|
72
|
+
for (const {name, value} of original.attributes) {
|
|
73
|
+
if ((depth || (name !== 'width' && name !== 'height')) &&
|
|
74
|
+
isSafeSvgDrawingAttribute(name, value)) target.setAttribute(name, value);
|
|
75
|
+
}
|
|
76
|
+
for (const child of original.childNodes) {
|
|
77
|
+
if (remaining <= 0) break;
|
|
78
|
+
if (child.nodeType === 3 && (original.localName === 'text' || original.localName === 'tspan')) {
|
|
79
|
+
remaining--;
|
|
80
|
+
target.append(child.textContent.slice(0, 1024));
|
|
81
|
+
} else if (child.nodeType === 1 && depth < 8) {
|
|
82
|
+
const element = child as Element;
|
|
83
|
+
if (element.namespaceURI !== svgNamespace || !svgDrawingElements.has(element.localName)) continue;
|
|
84
|
+
remaining--;
|
|
85
|
+
const next = document.createElementNS(svgNamespace, element.localName);
|
|
86
|
+
copy(element, next, depth + 1);
|
|
87
|
+
target.append(next);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
copy(svg, output, 0);
|
|
92
|
+
return new view.XMLSerializer().serializeToString(output);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function rasterize(document: Document, type: string, bytes: Uint8Array<ArrayBuffer>, signal: AbortSignal) {
|
|
96
|
+
if (signal.aborted) return;
|
|
97
|
+
let data: BlobPart = bytes;
|
|
98
|
+
if (type === 'image/png') {
|
|
99
|
+
if (bytes.length < 24 || !pngHeader.every((byte, index) => bytes[index] === byte)) return;
|
|
100
|
+
const header = new DataView(bytes.buffer);
|
|
101
|
+
if (![header.getUint32(16), header.getUint32(20)].every(side => side > 0 && side <= maxSide)) return;
|
|
102
|
+
} else {
|
|
103
|
+
data = staticSvg(document, bytes);
|
|
104
|
+
if (!data) return;
|
|
105
|
+
}
|
|
106
|
+
const view = document.defaultView;
|
|
107
|
+
const image = document.createElement('img');
|
|
108
|
+
const url = view.URL.createObjectURL(new view.Blob([data], {type}));
|
|
109
|
+
const revoke = () => view.URL.revokeObjectURL(url);
|
|
110
|
+
signal.addEventListener('abort', revoke, {once: true});
|
|
111
|
+
try {
|
|
112
|
+
// Decode SVG only in image mode, then send pixels to the popup.
|
|
113
|
+
image.src = url;
|
|
114
|
+
await image.decode();
|
|
115
|
+
const {naturalWidth: width, naturalHeight: height} = image;
|
|
116
|
+
if (signal.aborted || !width || !height || width > maxSide || height > maxSide) return;
|
|
117
|
+
const canvas = document.createElement('canvas');
|
|
118
|
+
canvas.width = width;
|
|
119
|
+
canvas.height = height;
|
|
120
|
+
const context = canvas.getContext('2d');
|
|
121
|
+
if (!context) return;
|
|
122
|
+
context.drawImage(image, 0, 0);
|
|
123
|
+
return canvas.toDataURL('image/png');
|
|
124
|
+
} finally {
|
|
125
|
+
signal.removeEventListener('abort', revoke);
|
|
126
|
+
revoke();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function createFieldResources(source: HTMLElement, options: FieldResourceOptions | undefined, valid: () => boolean) {
|
|
131
|
+
const assets = readManifest(options?.manifest);
|
|
132
|
+
const pending = new Map<Asset, Promise<string | undefined>>();
|
|
133
|
+
const fonts: {document: Document; face: FontFace}[] = [];
|
|
134
|
+
const controller = new AbortController();
|
|
135
|
+
const parent = source.ownerDocument.defaultView;
|
|
136
|
+
|
|
137
|
+
async function load(asset: Asset, child: Document) {
|
|
138
|
+
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);
|
|
139
|
+
if (!await options.canFetch(asset.url) || signal.aborted || !valid()) return;
|
|
140
|
+
const resource = await readAsset(parent, asset, signal);
|
|
141
|
+
if (!resource || signal.aborted || !valid()) return;
|
|
142
|
+
const {type, bytes} = resource;
|
|
143
|
+
if (asset.kind === 'image') return rasterize(source.ownerDocument, type, bytes, signal);
|
|
144
|
+
if (String.fromCharCode(...bytes.subarray(0, 4)) !== 'wOF2') return;
|
|
145
|
+
const family = `tw-field-font-${parent.crypto.randomUUID()}`;
|
|
146
|
+
const face = new child.defaultView.FontFace(family, bytes);
|
|
147
|
+
await face.load();
|
|
148
|
+
if (signal.aborted || !valid()) return;
|
|
149
|
+
child.fonts.add(face);
|
|
150
|
+
fonts.push({document: child, face});
|
|
151
|
+
return family;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function assetFor(node: HTMLElement, kind: Asset['kind']) {
|
|
155
|
+
const asset = assets.get(node.getAttribute(`data-plus-field-${kind}`) ?? '');
|
|
156
|
+
return asset?.kind === kind ? asset : undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
hasImage(node: HTMLElement) {
|
|
161
|
+
return Boolean(assetFor(node, 'image'));
|
|
162
|
+
},
|
|
163
|
+
attach(original: HTMLElement, proxy: HTMLElement) {
|
|
164
|
+
const image = proxy.localName === 'img';
|
|
165
|
+
const asset = assetFor(original, image ? 'image' : 'font');
|
|
166
|
+
if (!asset) return;
|
|
167
|
+
if (!pending.has(asset)) pending.set(asset, load(asset, proxy.ownerDocument).catch(() => undefined));
|
|
168
|
+
return pending.get(asset).then(value => {
|
|
169
|
+
if (!value || controller.signal.aborted || !valid()) return;
|
|
170
|
+
if (image) (proxy as HTMLImageElement).src = value;
|
|
171
|
+
return image ? undefined : value;
|
|
172
|
+
});
|
|
173
|
+
},
|
|
174
|
+
dispose() {
|
|
175
|
+
controller.abort();
|
|
176
|
+
for (const {document, face} of fonts) document.fonts.delete(face);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|