@web-canvas-ui/react 0.1.1 → 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 (157) hide show
  1. package/README.md +172 -76
  2. package/index.js +2682 -0
  3. package/package.json +36 -27
  4. package/types/canvas-handle.d.ts +22 -0
  5. package/types/components/Button/button.d.ts +20 -0
  6. package/types/components/Button/logic.d.ts +3 -0
  7. package/types/components/CanvasView/canvasView.d.ts +28 -0
  8. package/types/components/CanvasView/index.d.ts +2 -0
  9. package/types/components/Carousel/carousel.d.ts +31 -0
  10. package/types/components/Carousel/logic.d.ts +2 -0
  11. package/types/components/Checkbox/checkbox.d.ts +8 -0
  12. package/types/components/ChoiceGroup/choiceGroup.d.ts +33 -0
  13. package/types/components/ChoiceGroup/logic.d.ts +3 -0
  14. package/types/components/Circle/circle.d.ts +9 -0
  15. package/types/components/Collapse/collapse.d.ts +32 -0
  16. package/types/components/Collapse/logic.d.ts +1 -0
  17. package/types/components/CustomDraw/customDraw.d.ts +22 -0
  18. package/types/components/CustomDraw/index.d.ts +2 -0
  19. package/types/components/DatePicker/datePicker.d.ts +24 -0
  20. package/types/components/Dialog/dialog.d.ts +20 -0
  21. package/types/components/Dropdown/dropdown.d.ts +30 -0
  22. package/types/components/Dropdown/logic.d.ts +5 -0
  23. package/{components/Grid/grid.ts → types/components/Grid/grid.d.ts} +3 -4
  24. package/{components/GridItem/gridItem.ts → types/components/GridItem/gridItem.d.ts} +1 -4
  25. package/{components/Group/group.ts → types/components/Group/group.d.ts} +1 -4
  26. package/types/components/Icon/icon.d.ts +14 -0
  27. package/types/components/Image/image.d.ts +12 -0
  28. package/types/components/Input/input.d.ts +32 -0
  29. package/types/components/Progress/progress.d.ts +15 -0
  30. package/types/components/Radio/radio.d.ts +8 -0
  31. package/types/components/Rect/rect.d.ts +11 -0
  32. package/types/components/Slider/logic.d.ts +1 -0
  33. package/types/components/Slider/slider.d.ts +17 -0
  34. package/types/components/Switch/logic.d.ts +2 -0
  35. package/types/components/Switch/switch.d.ts +14 -0
  36. package/types/components/Tabs/logic.d.ts +2 -0
  37. package/types/components/Tabs/tabs.d.ts +35 -0
  38. package/types/components/Text/text.d.ts +39 -0
  39. package/types/components/Textarea/textarea.d.ts +10 -0
  40. package/types/components/Upload/upload.d.ts +20 -0
  41. package/types/components/Video/index.d.ts +2 -0
  42. package/types/components/Video/video.d.ts +20 -0
  43. package/types/components/draw-utils.d.ts +48 -0
  44. package/types/components/shared.d.ts +7 -0
  45. package/types/components/size.d.ts +6 -0
  46. package/{components/types.ts → types/components/types.d.ts} +3 -12
  47. package/types/engine/carousel.d.ts +10 -0
  48. package/types/engine/events.d.ts +14 -0
  49. package/types/engine/hit-test.d.ts +31 -0
  50. package/types/engine/images.d.ts +8 -0
  51. package/types/engine/interaction.d.ts +11 -0
  52. package/types/engine/layout.d.ts +6 -0
  53. package/types/engine/nodes.d.ts +18 -0
  54. package/{engine/state.ts → types/engine/state.d.ts} +27 -22
  55. package/types/engine/text-controls.d.ts +10 -0
  56. package/types/engine/transform.d.ts +13 -0
  57. package/types/engine/videos.d.ts +14 -0
  58. package/types/engine/vnodes.d.ts +36 -0
  59. package/types/engine.d.ts +36 -0
  60. package/types/image-assets.d.ts +2 -0
  61. package/types/input-bridge.d.ts +40 -0
  62. package/types/react/Canvas.d.ts +4 -0
  63. package/types/react/components.d.ts +30 -0
  64. package/types/react/index.d.ts +4 -0
  65. package/types/renderer.d.ts +20 -0
  66. package/types/scene.d.ts +15 -0
  67. package/{types.ts → types/types.d.ts} +10 -142
  68. package/types/video-assets.d.ts +11 -0
  69. package/Canvas.tsx +0 -142
  70. package/__tests__/pure-logic.test.ts +0 -153
  71. package/__tests__/scene-and-node.test.ts +0 -131
  72. package/__tests__/scratch-space.test.ts +0 -30
  73. package/__tests__/textarea-caret.test.ts +0 -96
  74. package/__tests__/utils.test.ts +0 -114
  75. package/canvas-handle.ts +0 -114
  76. package/components/Button/button.ts +0 -57
  77. package/components/Button/logic.ts +0 -11
  78. package/components/CanvasView/canvasView.ts +0 -103
  79. package/components/CanvasView/index.ts +0 -7
  80. package/components/Carousel/carousel.ts +0 -107
  81. package/components/Carousel/logic.ts +0 -36
  82. package/components/Checkbox/checkbox.ts +0 -14
  83. package/components/ChoiceGroup/choiceGroup.ts +0 -172
  84. package/components/ChoiceGroup/logic.ts +0 -14
  85. package/components/Circle/circle.ts +0 -31
  86. package/components/Collapse/collapse.ts +0 -69
  87. package/components/Collapse/logic.ts +0 -14
  88. package/components/CustomDraw/customDraw.ts +0 -50
  89. package/components/CustomDraw/index.ts +0 -7
  90. package/components/DatePicker/datePicker.ts +0 -70
  91. package/components/Dialog/dialog.ts +0 -102
  92. package/components/Dropdown/dropdown.ts +0 -125
  93. package/components/Dropdown/logic.ts +0 -29
  94. package/components/Icon/icon.ts +0 -669
  95. package/components/Image/image.ts +0 -69
  96. package/components/Input/input.ts +0 -139
  97. package/components/Progress/progress.ts +0 -59
  98. package/components/Radio/radio.ts +0 -14
  99. package/components/Rect/rect.ts +0 -35
  100. package/components/Slider/logic.ts +0 -19
  101. package/components/Slider/slider.ts +0 -58
  102. package/components/Switch/logic.ts +0 -8
  103. package/components/Switch/switch.ts +0 -37
  104. package/components/Tabs/logic.ts +0 -14
  105. package/components/Tabs/tabs.ts +0 -78
  106. package/components/Text/text.ts +0 -95
  107. package/components/Textarea/textarea.ts +0 -16
  108. package/components/Upload/upload.ts +0 -66
  109. package/components/draw-utils.ts +0 -230
  110. package/components/shared.ts +0 -15
  111. package/components/size.ts +0 -20
  112. package/components.ts +0 -98
  113. package/engine/__tests__/carousel.test.ts +0 -218
  114. package/engine/__tests__/hit-test.test.ts +0 -282
  115. package/engine/__tests__/layout.test.ts +0 -474
  116. package/engine/carousel.ts +0 -150
  117. package/engine/events.ts +0 -73
  118. package/engine/hit-test.ts +0 -321
  119. package/engine/images.ts +0 -41
  120. package/engine/interaction.ts +0 -442
  121. package/engine/layout.ts +0 -355
  122. package/engine/nodes.ts +0 -166
  123. package/engine/text-controls.ts +0 -122
  124. package/engine/transform.ts +0 -61
  125. package/engine/vnodes.ts +0 -204
  126. package/engine.ts +0 -162
  127. package/image-assets.ts +0 -37
  128. package/index.ts +0 -78
  129. package/input-bridge.ts +0 -285
  130. package/renderer.ts +0 -303
  131. package/scene.ts +0 -122
  132. package/theme.scss +0 -234
  133. package/web-canvas-ui-react-0.1.1.tgz +0 -0
  134. /package/{components/Button/index.ts → types/components/Button/index.d.ts} +0 -0
  135. /package/{components/Carousel/index.ts → types/components/Carousel/index.d.ts} +0 -0
  136. /package/{components/Checkbox/index.ts → types/components/Checkbox/index.d.ts} +0 -0
  137. /package/{components/ChoiceGroup/index.ts → types/components/ChoiceGroup/index.d.ts} +0 -0
  138. /package/{components/Circle/index.ts → types/components/Circle/index.d.ts} +0 -0
  139. /package/{components/Collapse/index.ts → types/components/Collapse/index.d.ts} +0 -0
  140. /package/{components/DatePicker/index.ts → types/components/DatePicker/index.d.ts} +0 -0
  141. /package/{components/Dialog/index.ts → types/components/Dialog/index.d.ts} +0 -0
  142. /package/{components/Dropdown/index.ts → types/components/Dropdown/index.d.ts} +0 -0
  143. /package/{components/Grid/index.ts → types/components/Grid/index.d.ts} +0 -0
  144. /package/{components/GridItem/index.ts → types/components/GridItem/index.d.ts} +0 -0
  145. /package/{components/Group/index.ts → types/components/Group/index.d.ts} +0 -0
  146. /package/{components/Icon/index.ts → types/components/Icon/index.d.ts} +0 -0
  147. /package/{components/Image/index.ts → types/components/Image/index.d.ts} +0 -0
  148. /package/{components/Input/index.ts → types/components/Input/index.d.ts} +0 -0
  149. /package/{components/Progress/index.ts → types/components/Progress/index.d.ts} +0 -0
  150. /package/{components/Radio/index.ts → types/components/Radio/index.d.ts} +0 -0
  151. /package/{components/Rect/index.ts → types/components/Rect/index.d.ts} +0 -0
  152. /package/{components/Slider/index.ts → types/components/Slider/index.d.ts} +0 -0
  153. /package/{components/Switch/index.ts → types/components/Switch/index.d.ts} +0 -0
  154. /package/{components/Tabs/index.ts → types/components/Tabs/index.d.ts} +0 -0
  155. /package/{components/Text/index.ts → types/components/Text/index.d.ts} +0 -0
  156. /package/{components/Textarea/index.ts → types/components/Textarea/index.d.ts} +0 -0
  157. /package/{components/Upload/index.ts → types/components/Upload/index.d.ts} +0 -0
@@ -1,131 +0,0 @@
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
- });
@@ -1,30 +0,0 @@
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
- });
@@ -1,96 +0,0 @@
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
- });
@@ -1,114 +0,0 @@
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 DELETED
@@ -1,114 +0,0 @@
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
- }
@@ -1,57 +0,0 @@
1
- import type { TransformProps } from '../../types';
2
- import { fitText, number, string, themeColor } from '../draw-utils';
3
- import { createComponent } from '../shared';
4
-
5
- export interface ButtonProps extends TransformProps {
6
- children?: string | number;
7
- text?: string;
8
- width?: number;
9
- height?: number;
10
- disabled?: boolean;
11
- backgroundColor?: string;
12
- fontColor?: string;
13
- borderColor?: string;
14
- borderRadius?: number;
15
- fontSize?: number;
16
- onClick?: () => void;
17
- }
18
-
19
- export const Button = createComponent<ButtonProps>('button');
20
-
21
- /** Public props plus the engine-injected press state consumed by the draw layer. */
22
- export type ButtonDrawProps = ButtonProps & { pressed?: boolean };
23
-
24
- export function drawButton(context: CanvasRenderingContext2D, props: ButtonDrawProps): void {
25
- const width = number(props.width, 120);
26
- const height = number(props.height, 40);
27
- const radius = number(props.borderRadius, 6);
28
- context.beginPath();
29
- context.roundRect(0, 0, width, height, radius);
30
- context.fillStyle = props.pressed
31
- ? themeColor(context, '--canvas-ui-button-pressed-background', '#0958d9')
32
- : string(
33
- props.backgroundColor,
34
- themeColor(context, '--canvas-ui-button-background', '#1677ff'),
35
- );
36
- context.fill();
37
- if (props.borderColor) {
38
- context.strokeStyle = string(
39
- props.borderColor,
40
- themeColor(context, '--canvas-ui-button-border', '#1677ff'),
41
- );
42
- context.stroke();
43
- }
44
- context.font = `${number(props.fontSize, 15)}px sans-serif`;
45
- context.textBaseline = 'middle';
46
- context.textAlign = 'center';
47
- context.fillStyle = string(
48
- props.fontColor,
49
- themeColor(context, '--canvas-ui-button-color', '#fff'),
50
- );
51
- context.fillText(
52
- fitText(context, String(props.text ?? ''), Math.max(0, width - 16)),
53
- width / 2,
54
- height / 2,
55
- );
56
- context.textAlign = 'left';
57
- }
@@ -1,11 +0,0 @@
1
- import type { SceneNode } from '../../scene';
2
-
3
- export function setButtonPressed(button: SceneNode, pressed: boolean): void {
4
- button.setProps({ pressed });
5
- }
6
-
7
- export function activateButton(button: SceneNode): void {
8
- if (button.props.disabled === true) return;
9
- const onClick = button.props.onClick;
10
- if (typeof onClick === 'function') onClick();
11
- }
@@ -1,103 +0,0 @@
1
- import type { TransformProps } from '../../types';
2
- import { createComponent } from '../shared';
3
- import type { CustomDrawSize } from '../CustomDraw';
4
-
5
- export type CanvasViewFit = 'contain' | 'cover' | 'fill';
6
-
7
- export interface CanvasViewPointerEvent {
8
- readonly type: 'pointerdown' | 'pointermove' | 'pointerup' | 'pointercancel' | 'click';
9
- readonly source: HTMLCanvasElement;
10
- readonly x: number;
11
- readonly y: number;
12
- readonly sourceX: number;
13
- readonly sourceY: number;
14
- readonly sourceWidth: number;
15
- readonly sourceHeight: number;
16
- readonly pointerId: number;
17
- readonly pointerType?: string;
18
- readonly pressure?: number;
19
- readonly isPrimary?: boolean;
20
- readonly button?: number;
21
- readonly buttons?: number;
22
- }
23
-
24
- export type CanvasViewPointerEventHandler = (event: CanvasViewPointerEvent) => void;
25
-
26
- export interface CanvasViewProps extends TransformProps {
27
- source: HTMLCanvasElement;
28
- width: number;
29
- height: number;
30
- fit?: CanvasViewFit;
31
- onPointerEvent?: CanvasViewPointerEventHandler;
32
- }
33
-
34
- export const CanvasView = createComponent<CanvasViewProps>('canvasView');
35
-
36
- export function drawCanvasView(context: CanvasRenderingContext2D, props: CanvasViewProps): void {
37
- const source = props.source;
38
- if (!isHTMLCanvasElement(source)) {
39
- throw new TypeError('<CanvasView> requires an HTMLCanvasElement source.');
40
- }
41
- if (source === context.canvas) {
42
- throw new TypeError('<CanvasView> cannot draw the destination Canvas into itself.');
43
- }
44
-
45
- const width = dimension(props.width, 'width');
46
- const height = dimension(props.height, 'height');
47
- if (!source.width || !source.height || !width || !height) return;
48
-
49
- const size: CustomDrawSize = { width, height };
50
- const fit = props.fit ?? 'contain';
51
- context.save();
52
- try {
53
- context.beginPath();
54
- context.rect(0, 0, size.width, size.height);
55
- context.clip();
56
- if (fit === 'fill') {
57
- context.drawImage(source, 0, 0, size.width, size.height);
58
- return;
59
- }
60
-
61
- if (fit !== 'contain' && fit !== 'cover') {
62
- throw new RangeError('<CanvasView> fit must be "contain", "cover", or "fill".');
63
- }
64
-
65
- const scale =
66
- fit === 'cover'
67
- ? Math.max(size.width / source.width, size.height / source.height)
68
- : Math.min(size.width / source.width, size.height / source.height);
69
- const drawWidth = source.width * scale;
70
- const drawHeight = source.height * scale;
71
- context.drawImage(
72
- source,
73
- (size.width - drawWidth) / 2,
74
- (size.height - drawHeight) / 2,
75
- drawWidth,
76
- drawHeight,
77
- );
78
- } finally {
79
- context.restore();
80
- }
81
- }
82
-
83
- function dimension(value: unknown, name: string): number {
84
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
85
- throw new RangeError(`<CanvasView> ${name} must be a non-negative finite number.`);
86
- }
87
- return value;
88
- }
89
-
90
- function isHTMLCanvasElement(value: unknown): value is HTMLCanvasElement {
91
- return (
92
- typeof value === 'object' &&
93
- value !== null &&
94
- 'nodeName' in value &&
95
- value.nodeName === 'CANVAS' &&
96
- 'width' in value &&
97
- typeof value.width === 'number' &&
98
- 'height' in value &&
99
- typeof value.height === 'number' &&
100
- 'getContext' in value &&
101
- typeof value.getContext === 'function'
102
- );
103
- }
@@ -1,7 +0,0 @@
1
- export { CanvasView, drawCanvasView } from './canvasView';
2
- export type {
3
- CanvasViewFit,
4
- CanvasViewPointerEvent,
5
- CanvasViewPointerEventHandler,
6
- CanvasViewProps,
7
- } from './canvasView';