@react-fabric/draw 1.0.0-beta.3

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +10 -0
  3. package/dist/cjs/_virtual/_commonjsHelpers.js +7 -0
  4. package/dist/cjs/_virtual/dom-to-image.js +5 -0
  5. package/dist/cjs/node_modules/dom-to-image/src/dom-to-image.js +777 -0
  6. package/dist/cjs/packages/draw/src/canvas/DrawCanvas.js +299 -0
  7. package/dist/cjs/packages/draw/src/canvas/DrawContext.js +22 -0
  8. package/dist/cjs/packages/draw/src/canvas/shapes/avatar/AvatarShapeTool.js +271 -0
  9. package/dist/cjs/packages/draw/src/canvas/shapes/avatar/IdleState.js +59 -0
  10. package/dist/cjs/packages/draw/src/canvas/shapes/avatar/PointingState.js +84 -0
  11. package/dist/cjs/packages/draw/src/canvas/shapes/avatar/type.js +36 -0
  12. package/dist/cjs/packages/draw/src/canvas/shapes/custom/AudioShape.js +152 -0
  13. package/dist/cjs/packages/draw/src/canvas/shapes/custom/CardShape.js +115 -0
  14. package/dist/cjs/packages/draw/src/canvas/shapes/custom/FileShape.js +128 -0
  15. package/dist/cjs/packages/draw/src/canvas/shapes/custom/ImageShape.js +137 -0
  16. package/dist/cjs/packages/draw/src/canvas/shapes/custom/VideoShape.js +160 -0
  17. package/dist/cjs/packages/draw/src/index.js +7 -0
  18. package/dist/esm/_virtual/_commonjsHelpers.js +7 -0
  19. package/dist/esm/_virtual/dom-to-image.js +5 -0
  20. package/dist/esm/node_modules/dom-to-image/src/dom-to-image.js +777 -0
  21. package/dist/esm/packages/draw/src/canvas/DrawCanvas.js +298 -0
  22. package/dist/esm/packages/draw/src/canvas/DrawContext.js +21 -0
  23. package/dist/esm/packages/draw/src/canvas/shapes/avatar/AvatarShapeTool.js +270 -0
  24. package/dist/esm/packages/draw/src/canvas/shapes/avatar/IdleState.js +59 -0
  25. package/dist/esm/packages/draw/src/canvas/shapes/avatar/PointingState.js +84 -0
  26. package/dist/esm/packages/draw/src/canvas/shapes/avatar/type.js +36 -0
  27. package/dist/esm/packages/draw/src/canvas/shapes/custom/AudioShape.js +152 -0
  28. package/dist/esm/packages/draw/src/canvas/shapes/custom/CardShape.js +115 -0
  29. package/dist/esm/packages/draw/src/canvas/shapes/custom/FileShape.js +128 -0
  30. package/dist/esm/packages/draw/src/canvas/shapes/custom/ImageShape.js +137 -0
  31. package/dist/esm/packages/draw/src/canvas/shapes/custom/VideoShape.js +160 -0
  32. package/dist/esm/packages/draw/src/index.js +3 -0
  33. package/dist/types/canvas/DrawCanvas.d.ts +13 -0
  34. package/dist/types/canvas/DrawContext.d.ts +6 -0
  35. package/dist/types/canvas/shapes/avatar/AvatarShapeTool.d.ts +37 -0
  36. package/dist/types/canvas/shapes/avatar/IdleState.d.ts +8 -0
  37. package/dist/types/canvas/shapes/avatar/PointingState.d.ts +13 -0
  38. package/dist/types/canvas/shapes/avatar/type.d.ts +9 -0
  39. package/dist/types/canvas/shapes/custom/AudioShape.d.ts +18 -0
  40. package/dist/types/canvas/shapes/custom/CardShape.d.ts +23 -0
  41. package/dist/types/canvas/shapes/custom/FileShape.d.ts +18 -0
  42. package/dist/types/canvas/shapes/custom/ImageShape.d.ts +29 -0
  43. package/dist/types/canvas/shapes/custom/VideoShape.d.ts +32 -0
  44. package/dist/types/index.d.ts +1 -0
  45. package/package.json +54 -0
  46. package/src/canvas/DrawCanvas.tsx +256 -0
  47. package/src/canvas/DrawContext.tsx +36 -0
  48. package/src/canvas/shapes/avatar/AvatarShapeTool.tsx +234 -0
  49. package/src/canvas/shapes/avatar/IdleState.ts +61 -0
  50. package/src/canvas/shapes/avatar/PointingState.ts +97 -0
  51. package/src/canvas/shapes/avatar/type.ts +41 -0
  52. package/src/canvas/shapes/custom/AudioShape.tsx +134 -0
  53. package/src/canvas/shapes/custom/CardShape.tsx +106 -0
  54. package/src/canvas/shapes/custom/FileShape.tsx +101 -0
  55. package/src/canvas/shapes/custom/ImageShape.tsx +138 -0
  56. package/src/canvas/shapes/custom/VideoShape.tsx +170 -0
  57. package/src/index.ts +24 -0
@@ -0,0 +1,256 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2024 Adarsh Pastakia
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
10
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
11
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
16
+ * portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ import { Section, useIsDark } from "@react-fabric/core";
25
+ import { debounce } from "@react-fabric/utilities";
26
+ import { getAssetUrlsByMetaUrl } from "@tldraw/assets/urls";
27
+ import {
28
+ getSnapshot,
29
+ loadSnapshot,
30
+ Tldraw,
31
+ type Editor,
32
+ type TLEditorSnapshot,
33
+ } from "@tldraw/tldraw";
34
+ import "@tldraw/tldraw/tldraw.css";
35
+ import {
36
+ useCallback,
37
+ useEffect,
38
+ useImperativeHandle,
39
+ useLayoutEffect,
40
+ useMemo,
41
+ useState,
42
+ type DragEvent,
43
+ type FC,
44
+ type RefObject,
45
+ } from "react";
46
+ import { DrawContextProvider } from "./DrawContext";
47
+ import {
48
+ AvatarShapeTool,
49
+ AvatarShapeUtil,
50
+ } from "./shapes/avatar/AvatarShapeTool";
51
+ import { AudioShapeUtil } from "./shapes/custom/AudioShape";
52
+ import { CardShapeUtil } from "./shapes/custom/CardShape";
53
+ import { FileShapeUtil } from "./shapes/custom/FileShape";
54
+ import { ImageShapeUtil } from "./shapes/custom/ImageShape";
55
+ import { VideoShapeUtil } from "./shapes/custom/VideoShape";
56
+
57
+ export async function getSvgAsDataUrl(svg: SVGElement) {
58
+ const clone = svg.cloneNode(true) as SVGGraphicsElement;
59
+ clone.setAttribute("encoding", 'UTF-8"');
60
+
61
+ const fileReader = new FileReader();
62
+ const imgs = Array.from(clone.querySelectorAll("image"));
63
+
64
+ for (const img of imgs) {
65
+ const src = img.getAttribute("xlink:href");
66
+ if (src) {
67
+ if (!src.startsWith("data:")) {
68
+ const blob = await (await fetch(src)).blob();
69
+ const base64 = await new Promise<string>((resolve, reject) => {
70
+ fileReader.onload = () => resolve(fileReader.result as string);
71
+ fileReader.onerror = () => reject(fileReader.error);
72
+ fileReader.readAsDataURL(blob);
73
+ });
74
+ img.setAttribute("xlink:href", base64);
75
+ }
76
+ }
77
+ }
78
+
79
+ const svgStr = new XMLSerializer().serializeToString(clone);
80
+ // NOTE: `unescape` works everywhere although deprecated
81
+ const base64SVG =
82
+ typeof window !== "undefined"
83
+ ? window.btoa(unescape(encodeURIComponent(svgStr)))
84
+ : "";
85
+ return `data:image/svg+xml;base64,${base64SVG}`;
86
+ }
87
+
88
+ export interface DrawProps {
89
+ snapshot?: TLEditorSnapshot;
90
+ onUpdate?: (snapshot: TLEditorSnapshot) => void;
91
+ renderer?: (props: KeyValue) => AnyObject;
92
+ canvasRef?: RefObject<{ exportPages: () => Promise<KeyValue[]> }>;
93
+ }
94
+
95
+ const TypeMap: KeyValue = {
96
+ image: "image-card",
97
+ video: "video-card",
98
+ audio: "audio-card",
99
+ file: "file-card",
100
+ card: "data-card",
101
+ };
102
+
103
+ export const DrawCanvas: FC<DrawProps> = ({
104
+ snapshot,
105
+ renderer,
106
+ onUpdate,
107
+ canvasRef,
108
+ }) => {
109
+ const [editorRef, setEditor] = useState<Editor>();
110
+ const isDark = useIsDark();
111
+
112
+ useEffect(() => {
113
+ editorRef?.user.updateUserPreferences({
114
+ colorScheme: isDark ? "dark" : "light",
115
+ });
116
+ }, [editorRef, isDark]);
117
+
118
+ useEffect(() => {
119
+ editorRef?.addListener(
120
+ "update",
121
+ debounce(() => onUpdate?.(getSnapshot(editorRef.store)), 500),
122
+ );
123
+
124
+ return () => {
125
+ editorRef?.removeListener("update");
126
+ };
127
+ }, [editorRef]);
128
+
129
+ useLayoutEffect(() => {
130
+ setTimeout(() => {
131
+ editorRef?.store && snapshot && loadSnapshot(editorRef.store, snapshot);
132
+ }, 500);
133
+ }, [editorRef, snapshot]);
134
+
135
+ const handleDragOver = useCallback((e: DragEvent) => {
136
+ if (!e.dataTransfer.getData("react-fabric/canvas")) {
137
+ e.preventDefault();
138
+ return false;
139
+ }
140
+ return true;
141
+ }, []);
142
+
143
+ const handleDrop = useCallback(
144
+ (e: DragEvent) => {
145
+ const data = e.dataTransfer.getData("react-fabric/canvas");
146
+ if (!data) {
147
+ e.preventDefault();
148
+ return false;
149
+ }
150
+ const { type, ...props } = JSON.parse(data);
151
+ if (type in TypeMap) {
152
+ const { x = 0, y = 0 } =
153
+ editorRef?.getContainer().getBoundingClientRect() ?? {};
154
+ editorRef?.createShape({
155
+ type: TypeMap[type],
156
+ x: e.clientX - x,
157
+ y: e.clientY - y,
158
+ props,
159
+ });
160
+ }
161
+ return true;
162
+ },
163
+ [editorRef],
164
+ );
165
+
166
+ useImperativeHandle(
167
+ canvasRef,
168
+ () => ({
169
+ exportPages: async () => {
170
+ const currentPage = editorRef?.getCurrentPageId();
171
+ const pages = Object.keys(
172
+ editorRef?.store.getSnapshot().store ?? {},
173
+ ).filter((key) => key.startsWith("page:"));
174
+ const pageSnapshots: KeyValue[] = [];
175
+ while (pages.length) {
176
+ const pg: AnyObject = pages.shift();
177
+ await new Promise((resolve) => {
178
+ editorRef?.addListener("change", () => {
179
+ if (editorRef.getCurrentPageId() === pg) {
180
+ editorRef.removeListener("change");
181
+ resolve(0);
182
+ }
183
+ });
184
+ editorRef?.setCurrentPage(pg);
185
+ });
186
+ const shapes: AnyObject = editorRef?.getCurrentPageShapeIds();
187
+ const svg = await editorRef?.getSvg([...shapes], {
188
+ scale: 1,
189
+ background: true,
190
+ });
191
+ if (svg)
192
+ pageSnapshots.push({
193
+ id: pg,
194
+ name: editorRef?.getCurrentPage().name,
195
+ content: { image: await getSvgAsDataUrl(svg) },
196
+ });
197
+ }
198
+ currentPage && editorRef?.setCurrentPage(currentPage);
199
+ return pageSnapshots;
200
+ },
201
+ }),
202
+ [editorRef],
203
+ );
204
+
205
+ const TLDraw = useMemo(
206
+ () => (
207
+ <Tldraw
208
+ assetUrls={getAssetUrlsByMetaUrl()}
209
+ shapeUtils={[
210
+ AvatarShapeUtil,
211
+ AudioShapeUtil,
212
+ ImageShapeUtil,
213
+ VideoShapeUtil,
214
+ CardShapeUtil,
215
+ FileShapeUtil,
216
+ ]}
217
+ tools={[AvatarShapeTool]}
218
+ onMount={setEditor}
219
+ overrides={{
220
+ tools(editor, schema, helpers) {
221
+ schema.avatar = {
222
+ id: "avatar",
223
+ label: "tool.avatar" as AnyObject,
224
+ readonlyOk: false,
225
+ icon: "avatar",
226
+ onSelect() {
227
+ editor.setCurrentTool("avatar");
228
+ },
229
+ };
230
+ return schema;
231
+ },
232
+ actions(editor, schema, helpers) {
233
+ schema["insert-embed"].kbd = "";
234
+ schema["insert-media"].kbd = "";
235
+ return schema;
236
+ },
237
+ }}
238
+ />
239
+ ),
240
+ [],
241
+ );
242
+
243
+ return (
244
+ <DrawContextProvider renderer={renderer}>
245
+ <Section>
246
+ <div
247
+ className="absolute inset-0"
248
+ onDragOver={handleDragOver}
249
+ onDrop={handleDrop}
250
+ >
251
+ {TLDraw}
252
+ </div>
253
+ </Section>
254
+ </DrawContextProvider>
255
+ );
256
+ };
@@ -0,0 +1,36 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2024 Adarsh Pastakia
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
10
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
11
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
16
+ * portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ import { createContext, useContext } from "react";
25
+
26
+ interface Props {
27
+ renderer?: (props: KeyValue) => AnyObject;
28
+ }
29
+
30
+ const DrawContext = createContext<Props>({});
31
+
32
+ export const DrawContextProvider = ({ children, ...props }: KeyValue) => {
33
+ return <DrawContext.Provider value={props}>{children}</DrawContext.Provider>;
34
+ };
35
+
36
+ export const useDrawContext = () => useContext(DrawContext);
@@ -0,0 +1,234 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2024 Adarsh Pastakia
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
10
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
11
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
16
+ * portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ /* eslint-disable @typescript-eslint/restrict-template-expressions */
25
+ /* eslint-disable @typescript-eslint/no-base-to-string */
26
+
27
+ import { useIsDark } from "@react-fabric/core";
28
+ import { StateNode } from "@tldraw/editor";
29
+ import {
30
+ Rectangle2d,
31
+ ShapeUtil,
32
+ getDefaultColorTheme,
33
+ useIsEditing,
34
+ type Editor,
35
+ } from "@tldraw/tldraw";
36
+ import domtoimage from "dom-to-image";
37
+ import { useEffect, useRef } from "react";
38
+ import { Idle } from "./IdleState";
39
+ import { Pointing } from "./PointingState";
40
+ import { AvatarShapeProps, type AvatarShape } from "./type";
41
+
42
+ /** @public */
43
+ export class AvatarShapeTool extends StateNode {
44
+ static override id = "avatar";
45
+ static override initial = "idle";
46
+ static override children = () => [Idle, Pointing];
47
+
48
+ override shapeType = "avatar";
49
+ }
50
+
51
+ const SIZE_MAP: KeyValue = {
52
+ s: 48,
53
+ m: 72,
54
+ l: 96,
55
+ xl: 128,
56
+ };
57
+
58
+ const FONT_SIZE_MAP: KeyValue = {
59
+ s: 12,
60
+ m: 16,
61
+ l: 18,
62
+ xl: 22,
63
+ };
64
+
65
+ export class AvatarShapeUtil extends ShapeUtil<AvatarShape> {
66
+ static override type = "avatar" as const;
67
+ static override props = AvatarShapeProps;
68
+
69
+ el = document.createElement("div");
70
+
71
+ override canEdit = () => true;
72
+ override canResize = () => true;
73
+ override hideRotateHandle = () => true;
74
+
75
+ override getDefaultProps(): AvatarShape["props"] {
76
+ return {
77
+ color: "black",
78
+ fill: "none",
79
+ size: "s",
80
+ font: "draw",
81
+ text: "person",
82
+ } as AnyObject;
83
+ }
84
+
85
+ constructor(editor: Editor) {
86
+ super(editor);
87
+ this.el.style.position = "absolute";
88
+ editor.getContainer().appendChild(this.el);
89
+ }
90
+
91
+ getSize(shape: AvatarShape) {
92
+ const size = SIZE_MAP[shape.props.size as AnyObject];
93
+ this.el.innerHTML = `<div class="tl-text-label" data-font="${
94
+ shape.props.font
95
+ }" style="position:relative;align-items:end;font-size:${
96
+ FONT_SIZE_MAP[shape.props.size as AnyObject] as string
97
+ }px;">
98
+ <div class="tl-text-label__inner">
99
+ <div class="tl-text tl-text-content" style="white-space:nowrap;padding:4px;">
100
+ ${shape.props.text}
101
+ </div></div></div>`;
102
+
103
+ return {
104
+ width: Math.max(size, this.el.offsetWidth),
105
+ height: +size + this.el.offsetHeight,
106
+ };
107
+ }
108
+
109
+ getGeometry(shape: AvatarShape) {
110
+ const { width, height } = this.getSize(shape);
111
+ return new Rectangle2d({
112
+ width,
113
+ height,
114
+ isFilled: true,
115
+ });
116
+ }
117
+
118
+ indicator(shape: AvatarShape) {
119
+ const { width, height } = this.getSize(shape);
120
+ return <rect width={width} height={height} />;
121
+ }
122
+
123
+ onChange = (shape: AvatarShape, newText: string) => {
124
+ const {
125
+ id,
126
+ type,
127
+ props: { text },
128
+ } = shape as AnyObject;
129
+
130
+ if (newText && text.trim() !== newText.trim()) {
131
+ this.editor.updateShapes([
132
+ {
133
+ id,
134
+ type,
135
+ props: {
136
+ text: newText.trim(),
137
+ },
138
+ },
139
+ ]);
140
+ }
141
+ };
142
+
143
+ component(shape: AvatarShape) {
144
+ const isDark = useIsDark();
145
+ const isEditing = useIsEditing(shape.id);
146
+ const size = SIZE_MAP[shape.props.size as AnyObject];
147
+ const theme: KeyValue = getDefaultColorTheme({ isDarkMode: isDark });
148
+ const inputRef = useRef("");
149
+ const { width, height } = this.getSize(shape);
150
+ useEffect(() => {
151
+ !isEditing && inputRef.current && this.onChange(shape, inputRef.current);
152
+ }, [isEditing]);
153
+ let bg = "transparent";
154
+ if (
155
+ (shape.props.fill as AnyObject) === "solid" ||
156
+ (shape.props.fill as AnyObject) === "pattern"
157
+ )
158
+ bg = theme[shape.props.color as AnyObject]?.semi;
159
+ if ((shape.props.fill as AnyObject) === "semi")
160
+ bg = isDark ? "#28292e" : "#fcfffe";
161
+ return (
162
+ <div
163
+ data-shape-id={shape.id}
164
+ style={{ position: "relative", textAlign: "center", width, height }}
165
+ >
166
+ <svg
167
+ id={"svg-" + shape.id}
168
+ viewBox="0 0 30 30"
169
+ width={size}
170
+ height={size}
171
+ >
172
+ <path
173
+ fill={bg}
174
+ stroke={theme[shape.props.color as AnyObject]?.solid}
175
+ d="M5 27.4996C5 20.2996 8.79988 17.0996 14.9999 17.0996C21.1999 17.0996 25.0001 20.2996 25 27.4996M14.9997 15.6001C18.4792 15.6001 21.2998 12.7794 21.2998 9.30003C21.2998 5.82062 18.4792 3 14.9997 3C11.5203 3 8.69971 5.82062 8.69971 9.30003C8.69971 12.7794 11.5203 15.6001 14.9997 15.6001Z"
176
+ />
177
+ </svg>
178
+ <div
179
+ id={"label-" + shape.id}
180
+ className="tl-text-label"
181
+ data-isediting={isEditing}
182
+ data-font={shape.props.font}
183
+ style={{
184
+ alignItems: "end",
185
+ fontSize: FONT_SIZE_MAP[shape.props.size as AnyObject],
186
+ color: theme[shape.props.color as AnyObject].solid,
187
+ }}
188
+ >
189
+ <div className="tl-text-label__inner" style={{ minWidth: "100%" }}>
190
+ <div
191
+ className="tl-text tl-text-content"
192
+ style={{ whiteSpace: "nowrap", padding: 4 }}
193
+ >
194
+ {`${shape.props.text}`}
195
+ </div>
196
+ {isEditing && (
197
+ <textarea
198
+ className="tl-text tl-text-input"
199
+ style={{ whiteSpace: "nowrap", padding: 4, minWidth: "100%" }}
200
+ name="text"
201
+ tabIndex={-1}
202
+ autoComplete="false"
203
+ autoCapitalize="false"
204
+ autoCorrect="false"
205
+ autoSave="false"
206
+ placeholder=""
207
+ spellCheck="true"
208
+ wrap="off"
209
+ dir="auto"
210
+ ref={(el) => [el?.select(), el?.focus()]}
211
+ onKeyDown={(e) =>
212
+ e.key === "Enter" &&
213
+ (e.stopPropagation(),
214
+ this.onChange(shape, inputRef.current),
215
+ this.editor.setEditingShape(null))
216
+ }
217
+ onChange={(e) => (inputRef.current = e.target.value)}
218
+ defaultValue={shape.props.text as AnyObject}
219
+ />
220
+ )}
221
+ </div>
222
+ </div>
223
+ </div>
224
+ );
225
+ }
226
+
227
+ async toSvg(shape: AvatarShape) {
228
+ const el = document.querySelector(`div[data-shape-id="${shape.id}"]`);
229
+ if (!el) return <img src="" alt="svg" />;
230
+ return await domtoimage.toPng(el).then(function (dataUrl) {
231
+ return <img src={dataUrl} alt="svg" />;
232
+ });
233
+ }
234
+ }
@@ -0,0 +1,61 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2024 Adarsh Pastakia
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
10
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
11
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
16
+ * portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ import { StateNode, type TLEventHandlers } from "@tldraw/editor";
25
+
26
+ export class Idle extends StateNode {
27
+ static override id = "idle";
28
+
29
+ override onPointerDown: TLEventHandlers["onPointerDown"] = (info) => {
30
+ this.parent.transition("pointing", info);
31
+ };
32
+
33
+ override onEnter = () => {
34
+ this.editor.setCursor({ type: "cross", rotation: 0 });
35
+ };
36
+
37
+ override onCancel = () => {
38
+ this.editor.setCurrentTool("select");
39
+ };
40
+
41
+ override onKeyUp: TLEventHandlers["onKeyUp"] = (info) => {
42
+ if (info.key === "Enter") {
43
+ if (this.editor.getInstanceState().isReadonly) return null;
44
+ const onlySelectedShape = this.editor.getOnlySelectedShape();
45
+ // If the only selected shape is editable, start editing it
46
+ if (
47
+ onlySelectedShape &&
48
+ this.editor.getShapeUtil(onlySelectedShape).canEdit(onlySelectedShape)
49
+ ) {
50
+ this.editor.setCurrentTool("select");
51
+ this.editor.setEditingShape(onlySelectedShape.id);
52
+ // @ts-expect-error ignore
53
+ this.editor.root.value?.transition("editing_shape", {
54
+ ...info,
55
+ target: "shape",
56
+ shape: onlySelectedShape,
57
+ });
58
+ }
59
+ }
60
+ };
61
+ }
@@ -0,0 +1,97 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2024 Adarsh Pastakia
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
10
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
11
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
16
+ * portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ import { StateNode, type TLEventHandlers } from "@tldraw/editor";
25
+ import { createShapeId } from "@tldraw/tldraw";
26
+ import { type AvatarShape } from "./type";
27
+
28
+ export class Pointing extends StateNode {
29
+ static override id = "pointing";
30
+
31
+ shape?: AvatarShape;
32
+
33
+ markId = "";
34
+
35
+ override onPointerUp: TLEventHandlers["onPointerUp"] = () => {
36
+ this.cancel();
37
+ };
38
+
39
+ override onCancel: TLEventHandlers["onCancel"] = () => {
40
+ this.cancel();
41
+ };
42
+
43
+ override onComplete: TLEventHandlers["onComplete"] = () => {
44
+ this.cancel();
45
+ };
46
+
47
+ override onInterrupt: TLEventHandlers["onInterrupt"] = () => {
48
+ this.cancel();
49
+ };
50
+
51
+ override onPointerMove: TLEventHandlers["onPointerMove"] = (info) => {
52
+ if (this.editor.inputs.isDragging) {
53
+ const { originPagePoint } = this.editor.inputs;
54
+
55
+ const id = createShapeId();
56
+
57
+ this.markId = `creating:${id}`;
58
+
59
+ this.editor.mark(this.markId);
60
+
61
+ this.editor
62
+ .createShapes<AvatarShape>([
63
+ {
64
+ id,
65
+ type: "avatar",
66
+ x: originPagePoint.x,
67
+ y: originPagePoint.y,
68
+ props: {
69
+ color: "black",
70
+ fill: "none",
71
+ size: "m",
72
+ font: "draw",
73
+ text: "person",
74
+ } as AnyObject,
75
+ },
76
+ ])
77
+ .select(id)
78
+ .setCurrentTool("select.resizing", {
79
+ ...info,
80
+ target: "selection",
81
+ handle: "bottom_right",
82
+ isCreating: true,
83
+ creationCursorOffset: { x: 1, y: 1 },
84
+ onInteractionEnd: "avatar",
85
+ });
86
+ }
87
+ };
88
+
89
+ cancel() {
90
+ if (this.shape) {
91
+ // the arrow might not have been created yet!
92
+ this.editor.bailToMark(this.markId);
93
+ }
94
+ this.editor.setHintingShapes([]);
95
+ this.parent.transition("idle", {});
96
+ }
97
+ }