-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcanvas-editor.ts
More file actions
79 lines (71 loc) · 1.45 KB
/
canvas-editor.ts
File metadata and controls
79 lines (71 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Canvas editor example.
*
* Pointer-move updates stay live, and pointer-up archives them as one undo step.
*/
import { createTravels } from '../src/index';
type Shape = {
id: string;
kind: 'rect' | 'ellipse' | 'text';
x: number;
y: number;
width: number;
height: number;
rotation: number;
fill: string;
};
type CanvasState = {
shapes: Shape[];
selectedIds: string[];
zoom: number;
};
export const canvasHistory = createTravels<CanvasState>(
{
shapes: [],
selectedIds: [],
zoom: 1,
},
{
autoArchive: false,
maxHistory: 500,
}
);
export function addRectangle(x: number, y: number) {
canvasHistory.setState((draft) => {
const id = crypto.randomUUID();
draft.shapes.push({
id,
kind: 'rect',
x,
y,
width: 160,
height: 96,
rotation: 0,
fill: '#3b82f6',
});
draft.selectedIds = [id];
});
canvasHistory.archive();
}
export function dragSelected(deltaX: number, deltaY: number) {
canvasHistory.setState((draft) => {
const selected = new Set(draft.selectedIds);
for (const shape of draft.shapes) {
if (selected.has(shape.id)) {
shape.x += deltaX;
shape.y += deltaY;
}
}
});
}
export function commitDrag() {
if (canvasHistory.canArchive()) {
canvasHistory.archive();
}
}
export function groupSelected() {
canvasHistory.setState((draft) => {
draft.selectedIds.sort();
});
canvasHistory.archive();
}