@web-canvas-ui/react 0.0.0-stage → 0.1.1
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/Canvas.tsx +142 -0
- package/README.md +988 -2
- package/__tests__/pure-logic.test.ts +153 -0
- package/__tests__/scene-and-node.test.ts +131 -0
- package/__tests__/scratch-space.test.ts +30 -0
- package/__tests__/textarea-caret.test.ts +96 -0
- package/__tests__/utils.test.ts +114 -0
- package/canvas-handle.ts +114 -0
- package/components/Button/button.ts +57 -0
- package/components/Button/index.ts +3 -0
- package/components/Button/logic.ts +11 -0
- package/components/CanvasView/canvasView.ts +103 -0
- package/components/CanvasView/index.ts +7 -0
- package/components/Carousel/carousel.ts +107 -0
- package/components/Carousel/index.ts +3 -0
- package/components/Carousel/logic.ts +36 -0
- package/components/Checkbox/checkbox.ts +14 -0
- package/components/Checkbox/index.ts +2 -0
- package/components/ChoiceGroup/choiceGroup.ts +172 -0
- package/components/ChoiceGroup/index.ts +3 -0
- package/components/ChoiceGroup/logic.ts +14 -0
- package/components/Circle/circle.ts +31 -0
- package/components/Circle/index.ts +2 -0
- package/components/Collapse/collapse.ts +69 -0
- package/components/Collapse/index.ts +3 -0
- package/components/Collapse/logic.ts +14 -0
- package/components/CustomDraw/customDraw.ts +50 -0
- package/components/CustomDraw/index.ts +7 -0
- package/components/DatePicker/datePicker.ts +70 -0
- package/components/DatePicker/index.ts +2 -0
- package/components/Dialog/dialog.ts +102 -0
- package/components/Dialog/index.ts +2 -0
- package/components/Dropdown/dropdown.ts +125 -0
- package/components/Dropdown/index.ts +3 -0
- package/components/Dropdown/logic.ts +29 -0
- package/components/Grid/grid.ts +15 -0
- package/components/Grid/index.ts +2 -0
- package/components/GridItem/gridItem.ts +11 -0
- package/components/GridItem/index.ts +2 -0
- package/components/Group/group.ts +8 -0
- package/components/Group/index.ts +2 -0
- package/components/Icon/icon.ts +669 -0
- package/components/Icon/index.ts +2 -0
- package/components/Image/image.ts +69 -0
- package/components/Image/index.ts +2 -0
- package/components/Input/index.ts +2 -0
- package/components/Input/input.ts +139 -0
- package/components/Progress/index.ts +2 -0
- package/components/Progress/progress.ts +59 -0
- package/components/Radio/index.ts +2 -0
- package/components/Radio/radio.ts +14 -0
- package/components/Rect/index.ts +2 -0
- package/components/Rect/rect.ts +35 -0
- package/components/Slider/index.ts +3 -0
- package/components/Slider/logic.ts +19 -0
- package/components/Slider/slider.ts +58 -0
- package/components/Switch/index.ts +3 -0
- package/components/Switch/logic.ts +8 -0
- package/components/Switch/switch.ts +37 -0
- package/components/Tabs/index.ts +3 -0
- package/components/Tabs/logic.ts +14 -0
- package/components/Tabs/tabs.ts +78 -0
- package/components/Text/index.ts +2 -0
- package/components/Text/text.ts +95 -0
- package/components/Textarea/index.ts +2 -0
- package/components/Textarea/textarea.ts +16 -0
- package/components/Upload/index.ts +2 -0
- package/components/Upload/upload.ts +66 -0
- package/components/draw-utils.ts +230 -0
- package/components/shared.ts +15 -0
- package/components/size.ts +20 -0
- package/components/types.ts +37 -0
- package/components.ts +98 -0
- package/engine/__tests__/carousel.test.ts +218 -0
- package/engine/__tests__/hit-test.test.ts +282 -0
- package/engine/__tests__/layout.test.ts +474 -0
- package/engine/carousel.ts +150 -0
- package/engine/events.ts +73 -0
- package/engine/hit-test.ts +321 -0
- package/engine/images.ts +41 -0
- package/engine/interaction.ts +442 -0
- package/engine/layout.ts +355 -0
- package/engine/nodes.ts +166 -0
- package/engine/state.ts +75 -0
- package/engine/text-controls.ts +122 -0
- package/engine/transform.ts +61 -0
- package/engine/vnodes.ts +204 -0
- package/engine.ts +162 -0
- package/image-assets.ts +37 -0
- package/index.ts +78 -0
- package/input-bridge.ts +285 -0
- package/package.json +27 -4
- package/renderer.ts +303 -0
- package/scene.ts +122 -0
- package/theme.css +327 -0
- package/theme.scss +234 -0
- package/types.ts +256 -0
- package/web-canvas-ui-react-0.1.1.tgz +0 -0
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { toggleCollapseKeys } from '../components/Collapse/logic';
|
|
3
|
+
import { checkboxSelection, radioSelection } from '../components/ChoiceGroup/logic';
|
|
4
|
+
import { dropdownOptionAt, normalizeDropdownOptions } from '../components/Dropdown/logic';
|
|
5
|
+
import { carouselControlIndex, carouselIndex } from '../components/Carousel/logic';
|
|
6
|
+
import { sliderValueAt } from '../components/Slider/logic';
|
|
7
|
+
import { overlayTextStyle } from '../input-bridge';
|
|
8
|
+
|
|
9
|
+
describe('toggleCollapseKeys', () => {
|
|
10
|
+
it('adds a new key and toggles it off when already active', () => {
|
|
11
|
+
expect(toggleCollapseKeys(['a'], 'b', false)).toEqual(['a', 'b']);
|
|
12
|
+
expect(toggleCollapseKeys(['a', 'b'], 'a', false)).toEqual(['b']);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('clears other keys in accordion mode', () => {
|
|
16
|
+
expect(toggleCollapseKeys(['a'], 'b', true)).toEqual(['b']);
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
describe('radioSelection', () => {
|
|
21
|
+
const option = { label: 'X', value: 'x' };
|
|
22
|
+
it('deselects when re-picking the active value', () => {
|
|
23
|
+
expect(radioSelection('x', option)).toBeUndefined();
|
|
24
|
+
});
|
|
25
|
+
it('selects the new value otherwise', () => {
|
|
26
|
+
expect(radioSelection('y', option)).toBe('x');
|
|
27
|
+
expect(radioSelection(undefined, option)).toBe('x');
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe('checkboxSelection', () => {
|
|
32
|
+
const option = { label: 'X', value: 'x' };
|
|
33
|
+
it('removes an already-selected value', () => {
|
|
34
|
+
expect(checkboxSelection(['x'], option)).toEqual([]);
|
|
35
|
+
});
|
|
36
|
+
it('adds a value and filters out non-strings', () => {
|
|
37
|
+
expect(checkboxSelection(['y'], option)).toEqual(['y', 'x']);
|
|
38
|
+
expect(checkboxSelection(['y', 1], option)).toEqual(['y', 'x']);
|
|
39
|
+
expect(checkboxSelection(undefined, option)).toEqual(['x']);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('normalizeDropdownOptions / dropdownOptionAt', () => {
|
|
44
|
+
it('expands string options and keeps object options', () => {
|
|
45
|
+
expect(normalizeDropdownOptions(['a', { label: 'L', value: 'V' }])).toEqual([
|
|
46
|
+
{ label: 'a', value: 'a' },
|
|
47
|
+
{ label: 'L', value: 'V', disabled: false },
|
|
48
|
+
]);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('preserves the disabled flag', () => {
|
|
52
|
+
expect(
|
|
53
|
+
normalizeDropdownOptions([{ label: 'L', value: 'V', disabled: true }])[0].disabled,
|
|
54
|
+
).toBe(true);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('drops invalid entries and non-arrays', () => {
|
|
58
|
+
expect(normalizeDropdownOptions([{ label: 1, value: 2 }])).toEqual([]);
|
|
59
|
+
expect(normalizeDropdownOptions(['a', null, 5])).toEqual([{ label: 'a', value: 'a' }]);
|
|
60
|
+
expect(normalizeDropdownOptions('nope')).toEqual([]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('indexes into the normalized list', () => {
|
|
64
|
+
expect(dropdownOptionAt(['a', 'b'], 1)).toEqual({ label: 'b', value: 'b' });
|
|
65
|
+
expect(dropdownOptionAt(['a'], 5)).toBeUndefined();
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe('carouselIndex', () => {
|
|
70
|
+
it('wraps around when looping', () => {
|
|
71
|
+
expect(carouselIndex(5, 0, 3, true)).toBe(2);
|
|
72
|
+
expect(carouselIndex(-1, 0, 3, true)).toBe(2);
|
|
73
|
+
});
|
|
74
|
+
it('clamps when not looping', () => {
|
|
75
|
+
expect(carouselIndex(5, 0, 3, false)).toBe(2);
|
|
76
|
+
expect(carouselIndex(-1, 0, 3, false)).toBe(0);
|
|
77
|
+
});
|
|
78
|
+
it('returns 0 for an empty carousel', () => {
|
|
79
|
+
expect(carouselIndex(2, 0, 0, true)).toBe(0);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe('carouselControlIndex', () => {
|
|
84
|
+
const props = {};
|
|
85
|
+
it('ignores interaction for fewer than two items', () => {
|
|
86
|
+
expect(carouselControlIndex(props, 10, 90, 1, 0, 300, 180)).toBeUndefined();
|
|
87
|
+
});
|
|
88
|
+
it('hits the previous arrow on the left edge', () => {
|
|
89
|
+
expect(carouselControlIndex(props, 10, 90, 3, 0, 300, 180)).toBe(-1);
|
|
90
|
+
});
|
|
91
|
+
it('hits the next arrow on the right edge', () => {
|
|
92
|
+
expect(carouselControlIndex(props, 290, 90, 3, 0, 300, 180)).toBe(1);
|
|
93
|
+
});
|
|
94
|
+
it('hits a dot near the bottom', () => {
|
|
95
|
+
// startX = (300 - (3-1)*14) / 2 = 136, first dot at x = 136.
|
|
96
|
+
expect(carouselControlIndex({ showDots: true }, 136, 160, 3, 1, 300, 180)).toBe(0);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe('sliderValueAt', () => {
|
|
101
|
+
const props = { min: 0, max: 100, step: 1, height: 32 };
|
|
102
|
+
it('maps the midpoint to the middle value', () => {
|
|
103
|
+
// thumbRadius = 8, width = 160 -> ratio (80-8)/144 = 0.5
|
|
104
|
+
expect(sliderValueAt(props, 160, 80)).toBe(50);
|
|
105
|
+
});
|
|
106
|
+
it('clamps to the ends', () => {
|
|
107
|
+
expect(sliderValueAt(props, 160, 0)).toBe(0);
|
|
108
|
+
expect(sliderValueAt(props, 160, 160)).toBe(100);
|
|
109
|
+
});
|
|
110
|
+
it('snaps to the configured step', () => {
|
|
111
|
+
expect(sliderValueAt({ min: 0, max: 100, step: 10, height: 32 }, 160, 80)).toBe(50);
|
|
112
|
+
});
|
|
113
|
+
it('returns undefined for an inverted range', () => {
|
|
114
|
+
expect(sliderValueAt({ min: 10, max: 10 }, 160, 80)).toBeUndefined();
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
describe('overlayTextStyle', () => {
|
|
119
|
+
it('mirrors the font and inset the Canvas draws with', () => {
|
|
120
|
+
expect(
|
|
121
|
+
overlayTextStyle({ fontSize: 20, fontFamily: 'monospace', padding: 12 }, false),
|
|
122
|
+
).toMatchObject({
|
|
123
|
+
fontFamily: 'monospace',
|
|
124
|
+
fontSize: '20px',
|
|
125
|
+
paddingLeft: '12px',
|
|
126
|
+
paddingRight: '12px',
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('falls back to the drawing defaults when nothing is declared', () => {
|
|
131
|
+
const styles = overlayTextStyle({}, false);
|
|
132
|
+
expect(styles.fontSize).toBe('14px');
|
|
133
|
+
expect(styles.fontFamily).toBe('sans-serif');
|
|
134
|
+
expect(styles.paddingLeft).toBe('8px');
|
|
135
|
+
// A single-line control is vertically centred by the element itself, like the Canvas middle baseline.
|
|
136
|
+
expect(styles.paddingTop).toBeUndefined();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('keeps the 1.35 leading and vertical padding for a textarea', () => {
|
|
140
|
+
expect(overlayTextStyle({ padding: 6 }, true)).toMatchObject({
|
|
141
|
+
paddingTop: '6px',
|
|
142
|
+
paddingBottom: '6px',
|
|
143
|
+
lineHeight: '1.35',
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('tolerates a datePicker, which declares neither padding nor fontFamily', () => {
|
|
148
|
+
expect(overlayTextStyle({ value: '2024-01-02' }, false)).toMatchObject({
|
|
149
|
+
paddingLeft: '8px',
|
|
150
|
+
fontFamily: 'sans-serif',
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
});
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { SceneNode } from '../scene';
|
|
3
|
+
import { toggleSwitch } from '../components/Switch/logic';
|
|
4
|
+
import { activateButton, setButtonPressed } from '../components/Button/logic';
|
|
5
|
+
import { selectDropdownOption } from '../components/Dropdown/logic';
|
|
6
|
+
import { tabKeyAt } from '../components/Tabs/logic';
|
|
7
|
+
|
|
8
|
+
describe('SceneNode', () => {
|
|
9
|
+
it('initialises with sensible defaults', () => {
|
|
10
|
+
const node = new SceneNode('rect', { x: 1 });
|
|
11
|
+
expect(node.type).toBe('rect');
|
|
12
|
+
expect(node.props.x).toBe(1);
|
|
13
|
+
expect(node.dirty).toBe(true);
|
|
14
|
+
expect(node.children).toEqual([]);
|
|
15
|
+
expect(node.parent).toBeNull();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('merges props via setProps and marks itself dirty', () => {
|
|
19
|
+
const node = new SceneNode('rect', { x: 1 });
|
|
20
|
+
node.dirty = false;
|
|
21
|
+
node.setProps({ y: 2 });
|
|
22
|
+
expect(node.props).toEqual({ x: 1, y: 2 });
|
|
23
|
+
expect(node.dirty).toBe(true);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('ignores replaceProps when nothing actually changed', () => {
|
|
27
|
+
const node = new SceneNode('rect', { x: 1 });
|
|
28
|
+
node.dirty = false;
|
|
29
|
+
node.replaceProps({ x: 1 });
|
|
30
|
+
expect(node.dirty).toBe(false);
|
|
31
|
+
node.replaceProps({ x: 5 });
|
|
32
|
+
expect(node.dirty).toBe(true);
|
|
33
|
+
expect(node.props.x).toBe(5);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('propagates dirtiness up to ancestors', () => {
|
|
37
|
+
const parent = new SceneNode('group');
|
|
38
|
+
const child = new SceneNode('rect');
|
|
39
|
+
child.parent = parent;
|
|
40
|
+
parent.dirty = false;
|
|
41
|
+
child.dirty = false;
|
|
42
|
+
child.markDirty();
|
|
43
|
+
expect(child.dirty).toBe(true);
|
|
44
|
+
expect(parent.dirty).toBe(true);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('visits every node in the subtree via traverse', () => {
|
|
48
|
+
const root = new SceneNode('root');
|
|
49
|
+
root.syncChildren([{ type: 'rect', key: null, props: {}, children: [] }], () => {});
|
|
50
|
+
const visited: string[] = [];
|
|
51
|
+
root.traverse((node) => visited.push(node.type));
|
|
52
|
+
expect(visited).toEqual(['root', 'rect']);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('injects default value/focus state for controlled text inputs', () => {
|
|
56
|
+
const root = new SceneNode('root');
|
|
57
|
+
root.syncChildren([{ type: 'input', key: null, props: {}, children: [] }], () => {});
|
|
58
|
+
const input = root.children[0];
|
|
59
|
+
expect(input.props.value).toBe('');
|
|
60
|
+
expect(input.props.focused).toBe(false);
|
|
61
|
+
expect(input.props.cursorPos).toBe(0);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe('node-driven interaction logic', () => {
|
|
66
|
+
it('toggleSwitch flips checked and notifies onChange', () => {
|
|
67
|
+
const node = new SceneNode('switch', { checked: false });
|
|
68
|
+
let emitted: unknown;
|
|
69
|
+
node.setProps({
|
|
70
|
+
onChange: (value: boolean) => {
|
|
71
|
+
emitted = value;
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
toggleSwitch(node);
|
|
75
|
+
expect(node.props.checked).toBe(true);
|
|
76
|
+
expect(emitted).toBe(true);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('activateButton fires onClick only when enabled', () => {
|
|
80
|
+
let calls = 0;
|
|
81
|
+
const enabled = new SceneNode('button');
|
|
82
|
+
enabled.setProps({
|
|
83
|
+
onClick: () => {
|
|
84
|
+
calls += 1;
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
activateButton(enabled);
|
|
88
|
+
expect(calls).toBe(1);
|
|
89
|
+
|
|
90
|
+
const disabled = new SceneNode('button', { disabled: true });
|
|
91
|
+
disabled.setProps({
|
|
92
|
+
onClick: () => {
|
|
93
|
+
calls += 1;
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
activateButton(disabled);
|
|
97
|
+
expect(calls).toBe(1);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('setButtonPressed records the press state', () => {
|
|
101
|
+
const node = new SceneNode('button');
|
|
102
|
+
setButtonPressed(node, true);
|
|
103
|
+
expect(node.props.pressed).toBe(true);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('selectDropdownOption sets the value, closes the list and notifies', () => {
|
|
107
|
+
const node = new SceneNode('dropdown', { open: true });
|
|
108
|
+
let emitted: unknown;
|
|
109
|
+
node.setProps({
|
|
110
|
+
onChange: (value: string) => {
|
|
111
|
+
emitted = value;
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
selectDropdownOption(node, { label: 'A', value: 'a' });
|
|
115
|
+
expect(node.props.value).toBe('a');
|
|
116
|
+
expect(node.props.open).toBe(false);
|
|
117
|
+
expect(emitted).toBe('a');
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('tabKeyAt resolves the header index under the pointer', () => {
|
|
121
|
+
const items = [
|
|
122
|
+
new SceneNode('tabItem', { id: 't1' }),
|
|
123
|
+
new SceneNode('tabItem', { id: 't2' }),
|
|
124
|
+
];
|
|
125
|
+
expect(tabKeyAt(items, 150, 0, 200, 40)).toBe('t2');
|
|
126
|
+
expect(tabKeyAt(items, 150, 40, 200, 40)).toBeUndefined();
|
|
127
|
+
expect(
|
|
128
|
+
tabKeyAt([new SceneNode('tabItem', { id: 't1', disabled: true })], 10, 0, 200, 40),
|
|
129
|
+
).toBeUndefined();
|
|
130
|
+
});
|
|
131
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { measureLines, measureTextWidth } from '../components/draw-utils';
|
|
3
|
+
import { measureTextBox } from '../components/Text';
|
|
4
|
+
|
|
5
|
+
describe('scratch: maxLines 1 with spaces', () => {
|
|
6
|
+
const font = '16px sans-serif';
|
|
7
|
+
const measure = (text: string) => measureTextWidth(text, font);
|
|
8
|
+
const cases = [
|
|
9
|
+
'你好世界',
|
|
10
|
+
' 你好世界',
|
|
11
|
+
' 你好世界',
|
|
12
|
+
'\u3000你好世界',
|
|
13
|
+
'你好 世界',
|
|
14
|
+
'你好世界 ',
|
|
15
|
+
'你好世界\n',
|
|
16
|
+
'你好\n世界',
|
|
17
|
+
' a b c',
|
|
18
|
+
'hello world foo',
|
|
19
|
+
];
|
|
20
|
+
it('prints', () => {
|
|
21
|
+
for (const text of cases) {
|
|
22
|
+
const lines = measureLines(measure, text, 500, 1);
|
|
23
|
+
const box = measureTextBox({ text, width: 500, maxLines: 1 });
|
|
24
|
+
console.log(
|
|
25
|
+
`${JSON.stringify(text)} -> ${JSON.stringify(lines)} box.height=${String(box.height)}`,
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
expect(true).toBe(true);
|
|
29
|
+
});
|
|
30
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { drawInput } from '../components/Input';
|
|
3
|
+
import type { InputDrawProps } from '../components/Input';
|
|
4
|
+
|
|
5
|
+
// 5px per glyph keeps the wrapping arithmetic readable, and the recorded fillRect calls expose where
|
|
6
|
+
// the caret was actually painted: the caret is the only 1px-wide rectangle in the drawing.
|
|
7
|
+
function makeContext(): {
|
|
8
|
+
context: CanvasRenderingContext2D;
|
|
9
|
+
rects: number[][];
|
|
10
|
+
lines: { text: string; y: number }[];
|
|
11
|
+
} {
|
|
12
|
+
const rects: number[][] = [];
|
|
13
|
+
const lines: { text: string; y: number }[] = [];
|
|
14
|
+
const context = {
|
|
15
|
+
font: '',
|
|
16
|
+
fillStyle: '',
|
|
17
|
+
strokeStyle: '',
|
|
18
|
+
lineWidth: 1,
|
|
19
|
+
textBaseline: '',
|
|
20
|
+
canvas: {},
|
|
21
|
+
beginPath: () => {},
|
|
22
|
+
closePath: () => {},
|
|
23
|
+
roundRect: () => {},
|
|
24
|
+
rect: () => {},
|
|
25
|
+
clip: () => {},
|
|
26
|
+
save: () => {},
|
|
27
|
+
restore: () => {},
|
|
28
|
+
fill: () => {},
|
|
29
|
+
stroke: () => {},
|
|
30
|
+
fillRect: (x: number, y: number, w: number, h: number) => rects.push([x, y, w, h]),
|
|
31
|
+
fillText: (text: string, _x: number, y: number) => lines.push({ text, y }),
|
|
32
|
+
measureText: (text: string) => ({ width: text.length * 5 }),
|
|
33
|
+
};
|
|
34
|
+
return { context: context as unknown as CanvasRenderingContext2D, rects, lines };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Draws a focused textarea and returns the caret plus the lines that were painted. */
|
|
38
|
+
function caretOf(props: InputDrawProps): {
|
|
39
|
+
caret?: number[];
|
|
40
|
+
lines: { text: string; y: number }[];
|
|
41
|
+
} {
|
|
42
|
+
const { context, rects, lines } = makeContext();
|
|
43
|
+
drawInput(context, { focused: true, ...props }, true);
|
|
44
|
+
return { caret: rects.filter((rect) => rect[2] === 1).at(-1), lines };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const BASE: InputDrawProps = { width: 68, height: 100, padding: 8, fontSize: 10 };
|
|
48
|
+
// 68 - 2 * 8 = 52 of usable width, 5px per glyph -> ten characters per line.
|
|
49
|
+
const LINE_HEIGHT = 10 * 1.35;
|
|
50
|
+
|
|
51
|
+
describe('textarea caret', () => {
|
|
52
|
+
it('follows hard line breaks down the box', () => {
|
|
53
|
+
const props = { ...BASE, value: 'aa\nbb\ncc' };
|
|
54
|
+
expect(caretOf({ ...props, cursorPos: 0 }).caret?.[1]).toBe(8);
|
|
55
|
+
expect(caretOf({ ...props, cursorPos: 3 }).caret?.[1]).toBe(8 + LINE_HEIGHT);
|
|
56
|
+
expect(caretOf({ ...props, cursorPos: 9 }).caret?.[1]).toBe(8 + 2 * LINE_HEIGHT);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('paints the caret on the line the text itself was wrapped onto', () => {
|
|
60
|
+
// A soft-wrapped paragraph: the caret is resolved from a character index, so its row has to
|
|
61
|
+
// come out of the same wrapping the painter used, or it lands a line away from the glyph.
|
|
62
|
+
const props = { ...BASE, value: 'a'.repeat(24) };
|
|
63
|
+
for (const cursorPos of [0, 9, 11, 19, 23]) {
|
|
64
|
+
const { caret, lines } = caretOf({ ...props, cursorPos });
|
|
65
|
+
const charactersPerLine = 10;
|
|
66
|
+
const row = Math.floor(cursorPos / charactersPerLine);
|
|
67
|
+
expect(caret).toBeDefined();
|
|
68
|
+
expect(caret?.[1]).toBe(lines[row]?.y);
|
|
69
|
+
expect(caret?.[0]).toBe(8 + (cursorPos % charactersPerLine) * 5);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('scrolls the caret together with the text', () => {
|
|
74
|
+
const props: InputDrawProps = {
|
|
75
|
+
...BASE,
|
|
76
|
+
value: 'a'.repeat(60),
|
|
77
|
+
_scrollHeight: 200,
|
|
78
|
+
_scrollTop: 30,
|
|
79
|
+
cursorPos: 45,
|
|
80
|
+
};
|
|
81
|
+
const { caret, lines } = caretOf(props);
|
|
82
|
+
// Line 4 is the line the offset sits on, and both it and the caret carry the scroll offset.
|
|
83
|
+
expect(caret?.[1]).toBe(lines[4]?.y);
|
|
84
|
+
expect(caret?.[1]).toBe(8 + 4 * LINE_HEIGHT - 30);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('keeps the caret off the box once it is scrolled out of view', () => {
|
|
88
|
+
const { caret } = caretOf({
|
|
89
|
+
...BASE,
|
|
90
|
+
height: 30,
|
|
91
|
+
value: 'aa\nbb\ncc\ndd',
|
|
92
|
+
cursorPos: 12,
|
|
93
|
+
});
|
|
94
|
+
expect(caret).toBeUndefined();
|
|
95
|
+
});
|
|
96
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { measureLines, number, string, wrapText } from '../components/draw-utils';
|
|
3
|
+
import { componentHeight, componentWidth } from '../components/size';
|
|
4
|
+
|
|
5
|
+
// A measureText stub: every glyph is treated as 5px wide so wrapping is deterministic.
|
|
6
|
+
function makeContext(): CanvasRenderingContext2D {
|
|
7
|
+
return {
|
|
8
|
+
measureText: (text: string) => ({ width: text.length * 5 }),
|
|
9
|
+
} as unknown as CanvasRenderingContext2D;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
describe('number coercion', () => {
|
|
13
|
+
it('returns finite numbers as-is', () => {
|
|
14
|
+
expect(number(5, 1)).toBe(5);
|
|
15
|
+
expect(number(0, 1)).toBe(0);
|
|
16
|
+
expect(number(-3, 1)).toBe(-3);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('falls back for non-numbers and non-finite values', () => {
|
|
20
|
+
expect(number('x', 1)).toBe(1);
|
|
21
|
+
expect(number(NaN, 1)).toBe(1);
|
|
22
|
+
expect(number(Infinity, 1)).toBe(1);
|
|
23
|
+
expect(number(undefined, 2)).toBe(2);
|
|
24
|
+
expect(number(null, 7)).toBe(7);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe('string coercion', () => {
|
|
29
|
+
it('keeps strings and falls back otherwise', () => {
|
|
30
|
+
expect(string('a', 'x')).toBe('a');
|
|
31
|
+
expect(string('', 'x')).toBe('');
|
|
32
|
+
expect(string(1, 'x')).toBe('x');
|
|
33
|
+
expect(string(undefined, 'x')).toBe('x');
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
describe('wrapText', () => {
|
|
38
|
+
it('keeps short paragraphs on a single line', () => {
|
|
39
|
+
expect(wrapText(makeContext(), 'aa', 20)).toEqual(['aa']);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('wraps words that exceed the width onto new lines', () => {
|
|
43
|
+
// 'aa bb' is 5 chars -> width 25 > 20, so it splits into two lines.
|
|
44
|
+
expect(wrapText(makeContext(), 'aa bb', 20)).toEqual(['aa', 'bb']);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('breaks a single over-long word by characters', () => {
|
|
48
|
+
expect(wrapText(makeContext(), 'aaaa', 15)).toEqual(['aaa', 'a']);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('keeps filling the line with a CJK run that does not fit whole', () => {
|
|
52
|
+
// 5px per glyph: 'aa ' is 15 wide, so one more character still fits before the break. A
|
|
53
|
+
// Latin word would have moved down whole instead - the DOM wraps CJK runs this way, and a
|
|
54
|
+
// textarea caret is resolved against those line breaks.
|
|
55
|
+
expect(wrapText(makeContext(), 'aa 甲甲甲', 20)).toEqual(['aa 甲', '甲甲']);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('honours explicit newlines', () => {
|
|
59
|
+
expect(wrapText(makeContext(), 'a\nb', 20)).toEqual(['a', 'b']);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe('measureLines', () => {
|
|
64
|
+
// Same 5px-per-glyph stub the wrapping tests use.
|
|
65
|
+
const measure = (text: string) => text.length * 5;
|
|
66
|
+
|
|
67
|
+
it('wraps without a limit when maxLines is omitted', () => {
|
|
68
|
+
expect(measureLines(measure, 'aaaa', 15)).toEqual(['aaa', 'a']);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('keeps at most maxLines lines and marks the cut with a single ellipsis', () => {
|
|
72
|
+
expect(measureLines(measure, 'aaaa', 15, 1)).toEqual(['aa…']);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('leaves a block untouched when it already fits the limit', () => {
|
|
76
|
+
expect(measureLines(measure, 'aa', 20, 2)).toEqual(['aa']);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('counts hard newlines against the limit', () => {
|
|
80
|
+
// 'b' is the last visible line and still leaves room, but the dropped third line
|
|
81
|
+
// has to be signalled.
|
|
82
|
+
expect(measureLines(measure, 'a\nb\nc', 20, 2)).toEqual(['a', 'b…']);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('treats a missing width as one unwrapped line', () => {
|
|
86
|
+
expect(measureLines(measure, 'aa bb cc', 0, 2)).toEqual(['aa bb cc']);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('never clamps below one line and ignores non-positive limits', () => {
|
|
90
|
+
expect(measureLines(measure, 'aaaa', 15, 0.4)).toEqual(['aa…']);
|
|
91
|
+
expect(measureLines(measure, 'aaaa', 15, -1)).toEqual(['aaa', 'a']);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe('size resolution', () => {
|
|
96
|
+
it('prefers the size object over the flat width/height', () => {
|
|
97
|
+
expect(componentWidth({ size: { width: 30 }, width: 50 }, 100)).toBe(30);
|
|
98
|
+
expect(componentHeight({ size: { height: 30 }, height: 50 }, 100)).toBe(30);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('falls back to width/height when no size object is present', () => {
|
|
102
|
+
expect(componentWidth({ width: 50 }, 100)).toBe(50);
|
|
103
|
+
expect(componentHeight({ height: 40 }, 100)).toBe(40);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('uses the provided fallback when nothing is set', () => {
|
|
107
|
+
expect(componentWidth({}, 100)).toBe(100);
|
|
108
|
+
expect(componentHeight({}, 20)).toBe(20);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('ignores array-valued size (not a size object)', () => {
|
|
112
|
+
expect(componentWidth({ size: [1, 2], width: 8 }, 100)).toBe(8);
|
|
113
|
+
});
|
|
114
|
+
});
|
package/canvas-handle.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { CanvasEngine } from './engine';
|
|
2
|
+
|
|
3
|
+
export interface CanvasExportOptions {
|
|
4
|
+
/** Output dimensions in logical pixels; pixelRatio determines the bitmap resolution. */
|
|
5
|
+
width?: number;
|
|
6
|
+
height?: number;
|
|
7
|
+
/** Output pixels per logical pixel. Defaults to the Canvas device pixel ratio. */
|
|
8
|
+
pixelRatio?: number;
|
|
9
|
+
type?: string;
|
|
10
|
+
/** Image quality from 0 to 1; used by lossy formats such as JPEG and WebP. */
|
|
11
|
+
quality?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface CanvasHandle {
|
|
15
|
+
getCanvas(): HTMLCanvasElement | null;
|
|
16
|
+
requestRender(): void;
|
|
17
|
+
toDataURL(optionsOrType?: CanvasExportOptions | string, quality?: number): string;
|
|
18
|
+
toBlob(optionsOrType?: CanvasExportOptions | string, quality?: number): Promise<Blob>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function getDevicePixelRatio(): number {
|
|
22
|
+
return Math.max(1, window.devicePixelRatio || 1);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function normalizeExportOptions(
|
|
26
|
+
optionsOrType: CanvasExportOptions | string = {},
|
|
27
|
+
legacyQuality?: number,
|
|
28
|
+
): Required<Pick<CanvasExportOptions, 'type'>> & CanvasExportOptions {
|
|
29
|
+
return typeof optionsOrType === 'string'
|
|
30
|
+
? { type: optionsOrType, quality: legacyQuality }
|
|
31
|
+
: { ...optionsOrType, type: optionsOrType.type ?? 'image/png' };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function exportCanvasDataURL(
|
|
35
|
+
canvas: HTMLCanvasElement,
|
|
36
|
+
type: string,
|
|
37
|
+
quality?: number,
|
|
38
|
+
): string {
|
|
39
|
+
try {
|
|
40
|
+
return canvas.toDataURL(type, quality);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (isSecurityError(error)) throw createCrossOriginExportError();
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function exportCanvasBlob(
|
|
48
|
+
canvas: HTMLCanvasElement,
|
|
49
|
+
type: string,
|
|
50
|
+
quality?: number,
|
|
51
|
+
): Promise<Blob> {
|
|
52
|
+
return new Promise((resolve, reject) => {
|
|
53
|
+
try {
|
|
54
|
+
canvas.toBlob(
|
|
55
|
+
(blob) => {
|
|
56
|
+
if (blob) resolve(blob);
|
|
57
|
+
else reject(new Error('Canvas image export failed.'));
|
|
58
|
+
},
|
|
59
|
+
type,
|
|
60
|
+
quality,
|
|
61
|
+
);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
reject(isSecurityError(error) ? createCrossOriginExportError() : error);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function createExportCanvas(
|
|
69
|
+
source: HTMLCanvasElement,
|
|
70
|
+
engine: CanvasEngine | null,
|
|
71
|
+
options: CanvasExportOptions,
|
|
72
|
+
defaultPixelRatio: number,
|
|
73
|
+
): HTMLCanvasElement {
|
|
74
|
+
const pixelRatio = options.pixelRatio ?? defaultPixelRatio;
|
|
75
|
+
if (!Number.isFinite(pixelRatio) || pixelRatio <= 0) {
|
|
76
|
+
throw new RangeError('Export pixelRatio must be a positive finite number.');
|
|
77
|
+
}
|
|
78
|
+
const logicalWidth = options.width ?? source.width / defaultPixelRatio;
|
|
79
|
+
const logicalHeight = options.height ?? source.height / defaultPixelRatio;
|
|
80
|
+
if (
|
|
81
|
+
!Number.isFinite(logicalWidth) ||
|
|
82
|
+
logicalWidth <= 0 ||
|
|
83
|
+
!Number.isFinite(logicalHeight) ||
|
|
84
|
+
logicalHeight <= 0
|
|
85
|
+
) {
|
|
86
|
+
throw new RangeError('Export width and height must be positive finite numbers.');
|
|
87
|
+
}
|
|
88
|
+
const output = document.createElement('canvas');
|
|
89
|
+
output.width = Math.max(1, Math.round(logicalWidth * pixelRatio));
|
|
90
|
+
output.height = Math.max(1, Math.round(logicalHeight * pixelRatio));
|
|
91
|
+
const context = output.getContext('2d');
|
|
92
|
+
if (!context) throw new Error('Canvas 2D context is not available for image export.');
|
|
93
|
+
if (engine) {
|
|
94
|
+
engine.renderTo(context, output.width / logicalWidth, output.height / logicalHeight);
|
|
95
|
+
} else {
|
|
96
|
+
context.drawImage(source, 0, 0, output.width, output.height);
|
|
97
|
+
}
|
|
98
|
+
return output;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function isSecurityError(error: unknown): boolean {
|
|
102
|
+
return (
|
|
103
|
+
typeof error === 'object' &&
|
|
104
|
+
error !== null &&
|
|
105
|
+
'name' in error &&
|
|
106
|
+
error.name === 'SecurityError'
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function createCrossOriginExportError(): Error {
|
|
111
|
+
return new Error(
|
|
112
|
+
'Canvas 导出失败:画布包含未授权跨域读取的图片。请配置图片服务器 CORS(Access-Control-Allow-Origin),或移除该跨域图片后重试。',
|
|
113
|
+
);
|
|
114
|
+
}
|