@react-fabric/draw 1.0.0-beta.9 → 1.0.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.
Files changed (57) hide show
  1. package/dist/cjs/index.js +32 -0
  2. package/dist/esm/index.js +31 -0
  3. package/dist/types/index.d.ts +26 -1
  4. package/package.json +15 -17
  5. package/src/index.ts +21 -18
  6. package/dist/cjs/_virtual/_commonjsHelpers.js +0 -7
  7. package/dist/cjs/_virtual/dom-to-image.js +0 -5
  8. package/dist/cjs/node_modules/dom-to-image/src/dom-to-image.js +0 -777
  9. package/dist/cjs/packages/draw/src/canvas/DrawCanvas.js +0 -326
  10. package/dist/cjs/packages/draw/src/canvas/DrawContext.js +0 -22
  11. package/dist/cjs/packages/draw/src/canvas/shapes/avatar/AvatarShapeTool.js +0 -271
  12. package/dist/cjs/packages/draw/src/canvas/shapes/avatar/IdleState.js +0 -59
  13. package/dist/cjs/packages/draw/src/canvas/shapes/avatar/PointingState.js +0 -84
  14. package/dist/cjs/packages/draw/src/canvas/shapes/avatar/type.js +0 -36
  15. package/dist/cjs/packages/draw/src/canvas/shapes/custom/AudioShape.js +0 -152
  16. package/dist/cjs/packages/draw/src/canvas/shapes/custom/CardShape.js +0 -115
  17. package/dist/cjs/packages/draw/src/canvas/shapes/custom/FileShape.js +0 -128
  18. package/dist/cjs/packages/draw/src/canvas/shapes/custom/ImageShape.js +0 -137
  19. package/dist/cjs/packages/draw/src/canvas/shapes/custom/VideoShape.js +0 -160
  20. package/dist/cjs/packages/draw/src/index.js +0 -7
  21. package/dist/esm/_virtual/_commonjsHelpers.js +0 -7
  22. package/dist/esm/_virtual/dom-to-image.js +0 -5
  23. package/dist/esm/node_modules/dom-to-image/src/dom-to-image.js +0 -777
  24. package/dist/esm/packages/draw/src/canvas/DrawCanvas.js +0 -325
  25. package/dist/esm/packages/draw/src/canvas/DrawContext.js +0 -21
  26. package/dist/esm/packages/draw/src/canvas/shapes/avatar/AvatarShapeTool.js +0 -270
  27. package/dist/esm/packages/draw/src/canvas/shapes/avatar/IdleState.js +0 -59
  28. package/dist/esm/packages/draw/src/canvas/shapes/avatar/PointingState.js +0 -84
  29. package/dist/esm/packages/draw/src/canvas/shapes/avatar/type.js +0 -36
  30. package/dist/esm/packages/draw/src/canvas/shapes/custom/AudioShape.js +0 -152
  31. package/dist/esm/packages/draw/src/canvas/shapes/custom/CardShape.js +0 -115
  32. package/dist/esm/packages/draw/src/canvas/shapes/custom/FileShape.js +0 -128
  33. package/dist/esm/packages/draw/src/canvas/shapes/custom/ImageShape.js +0 -137
  34. package/dist/esm/packages/draw/src/canvas/shapes/custom/VideoShape.js +0 -160
  35. package/dist/esm/packages/draw/src/index.js +0 -3
  36. package/dist/types/canvas/DrawCanvas.d.ts +0 -13
  37. package/dist/types/canvas/DrawContext.d.ts +0 -6
  38. package/dist/types/canvas/shapes/avatar/AvatarShapeTool.d.ts +0 -37
  39. package/dist/types/canvas/shapes/avatar/IdleState.d.ts +0 -8
  40. package/dist/types/canvas/shapes/avatar/PointingState.d.ts +0 -13
  41. package/dist/types/canvas/shapes/avatar/type.d.ts +0 -9
  42. package/dist/types/canvas/shapes/custom/AudioShape.d.ts +0 -18
  43. package/dist/types/canvas/shapes/custom/CardShape.d.ts +0 -23
  44. package/dist/types/canvas/shapes/custom/FileShape.d.ts +0 -18
  45. package/dist/types/canvas/shapes/custom/ImageShape.d.ts +0 -29
  46. package/dist/types/canvas/shapes/custom/VideoShape.d.ts +0 -32
  47. package/src/canvas/DrawCanvas.tsx +0 -291
  48. package/src/canvas/DrawContext.tsx +0 -36
  49. package/src/canvas/shapes/avatar/AvatarShapeTool.tsx +0 -234
  50. package/src/canvas/shapes/avatar/IdleState.ts +0 -61
  51. package/src/canvas/shapes/avatar/PointingState.ts +0 -97
  52. package/src/canvas/shapes/avatar/type.ts +0 -41
  53. package/src/canvas/shapes/custom/AudioShape.tsx +0 -134
  54. package/src/canvas/shapes/custom/CardShape.tsx +0 -106
  55. package/src/canvas/shapes/custom/FileShape.tsx +0 -101
  56. package/src/canvas/shapes/custom/ImageShape.tsx +0 -138
  57. package/src/canvas/shapes/custom/VideoShape.tsx +0 -170
@@ -1,160 +0,0 @@
1
- 'use client';
2
-
3
- import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
4
- import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
5
- import _createClass from '@babel/runtime/helpers/createClass';
6
- import _possibleConstructorReturn from '@babel/runtime/helpers/possibleConstructorReturn';
7
- import _getPrototypeOf from '@babel/runtime/helpers/getPrototypeOf';
8
- import _inherits from '@babel/runtime/helpers/inherits';
9
- import _defineProperty from '@babel/runtime/helpers/defineProperty';
10
- import _regeneratorRuntime from '@babel/runtime/regenerator';
11
- import { Format } from '@react-fabric/utilities';
12
- import { Rectangle2d, HTMLContainer, ShapeUtil } from '@tldraw/tldraw';
13
- import domtoimage from '../../../../../../node_modules/dom-to-image/src/dom-to-image.js';
14
- import { useRef, useEffect } from 'react';
15
- import { jsx, jsxs } from 'react/jsx-runtime';
16
-
17
- function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
18
- function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
19
- var VideoShapeUtil = /*#__PURE__*/function (_ShapeUtil) {
20
- function VideoShapeUtil() {
21
- _classCallCheck(this, VideoShapeUtil);
22
- return _callSuper(this, VideoShapeUtil, arguments);
23
- }
24
- _inherits(VideoShapeUtil, _ShapeUtil);
25
- return _createClass(VideoShapeUtil, [{
26
- key: "onResize",
27
- value: function onResize(shape, info) {
28
- return {
29
- props: {
30
- w: Math.max(Math.min(info.initialBounds.w * info.scaleX, 1024), 128),
31
- h: Math.max(Math.min(info.initialBounds.h * info.scaleY, 768), 128)
32
- }
33
- };
34
- }
35
- }, {
36
- key: "getDefaultProps",
37
- value: function getDefaultProps() {
38
- return {
39
- src: "",
40
- poster: "",
41
- fileName: "",
42
- fileSize: 0,
43
- w: 400,
44
- h: 300
45
- };
46
- }
47
- }, {
48
- key: "getGeometry",
49
- value: function getGeometry(shape) {
50
- return new Rectangle2d({
51
- width: shape.props.w,
52
- height: shape.props.h,
53
- isFilled: true
54
- });
55
- }
56
- }, {
57
- key: "component",
58
- value: function component(shape) {
59
- var _shape$props$fileSize;
60
- var videoRef = useRef(null);
61
- useEffect(function () {
62
- var _videoRef$current2;
63
- var handler = function handler() {
64
- var _videoRef$current;
65
- (_videoRef$current = videoRef.current) === null || _videoRef$current === void 0 || (_videoRef$current = _videoRef$current.closest(".tl-container")) === null || _videoRef$current === void 0 || _videoRef$current.querySelectorAll("video,audio").forEach(function (el) {
66
- if (el !== videoRef.current) el.pause();
67
- });
68
- };
69
- (_videoRef$current2 = videoRef.current) === null || _videoRef$current2 === void 0 || _videoRef$current2.addEventListener("play", handler);
70
- }, []);
71
- return /*#__PURE__*/jsx(HTMLContainer, {
72
- className: "relative grid",
73
- children: /*#__PURE__*/jsxs("div", {
74
- "data-shape-id": shape.id,
75
- className: "bg-zinc-900 relative p-1 flex flex-col overflow-hidden",
76
- children: [/*#__PURE__*/jsx("video", {
77
- controls: true,
78
- ref: videoRef,
79
- src: shape.props.src,
80
- poster: shape.props.poster,
81
- className: "object-contain flex-1 pointer-events-auto overflow-hidden"
82
- }), /*#__PURE__*/jsx("img", {
83
- src: shape.props.poster,
84
- alt: shape.props.fileName,
85
- className: "object-contain flex-1 pointer-events-auto overflow-hidden hidden"
86
- }), /*#__PURE__*/jsxs("div", {
87
- className: "bg-zinc-800/80 text-white items-center py-1 px-2 flex gap-1 text-sm",
88
- children: [/*#__PURE__*/jsx("svg", {
89
- xmlns: "http://www.w3.org/2000/svg",
90
- viewBox: "0 0 24 24",
91
- width: 16,
92
- height: 16,
93
- children: /*#__PURE__*/jsx("path", {
94
- d: "M17,10.5V7A1,1 0 0,0 16,6H4A1,1 0 0,0 3,7V17A1,1 0 0,0 4,18H16A1,1 0 0,0 17,17V13.5L21,17.5V6.5L17,10.5Z"
95
- })
96
- }), /*#__PURE__*/jsx("div", {
97
- className: "truncate flex-1",
98
- children: shape.props.fileName
99
- }), /*#__PURE__*/jsx("div", {
100
- children: Format.bytes((_shape$props$fileSize = shape.props.fileSize) !== null && _shape$props$fileSize !== void 0 ? _shape$props$fileSize : 0)
101
- })]
102
- })]
103
- })
104
- });
105
- }
106
- }, {
107
- key: "indicator",
108
- value: function indicator(shape) {
109
- return /*#__PURE__*/jsx("rect", {
110
- width: shape.props.w,
111
- height: shape.props.h
112
- });
113
- }
114
- }, {
115
- key: "toSvg",
116
- value: function () {
117
- var _toSvg = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(shape) {
118
- var el;
119
- return _regeneratorRuntime.wrap(function _callee$(_context) {
120
- while (1) switch (_context.prev = _context.next) {
121
- case 0:
122
- el = document.querySelector("div[data-shape-id=\"".concat(shape.id, "\"]"));
123
- if (el) {
124
- _context.next = 3;
125
- break;
126
- }
127
- return _context.abrupt("return", /*#__PURE__*/jsx("img", {
128
- src: "",
129
- alt: "svg"
130
- }));
131
- case 3:
132
- el.childNodes.item(0).style.display = "none";
133
- el.childNodes.item(1).style.display = "block";
134
- _context.next = 7;
135
- return domtoimage.toPng(el).then(function (dataUrl) {
136
- el.childNodes.item(0).style.display = "block";
137
- el.childNodes.item(1).style.display = "none";
138
- return /*#__PURE__*/jsx("img", {
139
- src: dataUrl,
140
- alt: "svg"
141
- });
142
- });
143
- case 7:
144
- return _context.abrupt("return", _context.sent);
145
- case 8:
146
- case "end":
147
- return _context.stop();
148
- }
149
- }, _callee);
150
- }));
151
- function toSvg(_x) {
152
- return _toSvg.apply(this, arguments);
153
- }
154
- return toSvg;
155
- }()
156
- }]);
157
- }(ShapeUtil);
158
- _defineProperty(VideoShapeUtil, "type", "video-card");
159
-
160
- export { VideoShapeUtil };
@@ -1,3 +0,0 @@
1
- 'use client';
2
-
3
- export { DrawCanvas } from './canvas/DrawCanvas.js';
@@ -1,13 +0,0 @@
1
- import { type TLEditorSnapshot } from "@tldraw/tldraw";
2
- import "@tldraw/tldraw/tldraw.css";
3
- import { type FC, type RefObject } from "react";
4
- export declare function getSvgAsDataUrl(svg: SVGElement): Promise<string>;
5
- export interface DrawProps {
6
- snapshot?: TLEditorSnapshot;
7
- onUpdate?: (snapshot: TLEditorSnapshot) => void;
8
- renderer?: (props: KeyValue) => AnyObject;
9
- canvasRef?: RefObject<{
10
- exportPages: () => Promise<KeyValue[]>;
11
- }>;
12
- }
13
- export declare const DrawCanvas: FC<DrawProps>;
@@ -1,6 +0,0 @@
1
- interface Props {
2
- renderer?: (props: KeyValue) => AnyObject;
3
- }
4
- export declare const DrawContextProvider: ({ children, ...props }: KeyValue) => import("react/jsx-runtime").JSX.Element;
5
- export declare const useDrawContext: () => Props;
6
- export {};
@@ -1,37 +0,0 @@
1
- import { StateNode } from "@tldraw/editor";
2
- import { Rectangle2d, ShapeUtil, type Editor } from "@tldraw/tldraw";
3
- import { Idle } from "./IdleState";
4
- import { Pointing } from "./PointingState";
5
- import { type AvatarShape } from "./type";
6
- /** @public */
7
- export declare class AvatarShapeTool extends StateNode {
8
- static id: string;
9
- static initial: string;
10
- static children: () => (typeof Idle | typeof Pointing)[];
11
- shapeType: string;
12
- }
13
- export declare class AvatarShapeUtil extends ShapeUtil<AvatarShape> {
14
- static type: "avatar";
15
- static props: {
16
- color: import("@tldraw/tlschema").EnumStyleProp<"black" | "blue" | "green" | "grey" | "light-blue" | "light-green" | "light-red" | "light-violet" | "orange" | "red" | "violet" | "white" | "yellow">;
17
- fill: import("@tldraw/tlschema").EnumStyleProp<"fill" | "none" | "pattern" | "semi" | "solid">;
18
- size: import("@tldraw/tlschema").EnumStyleProp<"l" | "m" | "s" | "xl">;
19
- font: import("@tldraw/tlschema").EnumStyleProp<"draw" | "mono" | "sans" | "serif">;
20
- text: import("@tldraw/validate").Validator<string>;
21
- };
22
- el: HTMLDivElement;
23
- canEdit: () => boolean;
24
- canResize: () => boolean;
25
- hideRotateHandle: () => boolean;
26
- getDefaultProps(): AvatarShape["props"];
27
- constructor(editor: Editor);
28
- getSize(shape: AvatarShape): {
29
- width: number;
30
- height: number;
31
- };
32
- getGeometry(shape: AvatarShape): Rectangle2d;
33
- indicator(shape: AvatarShape): import("react/jsx-runtime").JSX.Element;
34
- onChange: (shape: AvatarShape, newText: string) => void;
35
- component(shape: AvatarShape): import("react/jsx-runtime").JSX.Element;
36
- toSvg(shape: AvatarShape): Promise<import("react/jsx-runtime").JSX.Element>;
37
- }
@@ -1,8 +0,0 @@
1
- import { StateNode, type TLEventHandlers } from "@tldraw/editor";
2
- export declare class Idle extends StateNode {
3
- static id: string;
4
- onPointerDown: TLEventHandlers["onPointerDown"];
5
- onEnter: () => void;
6
- onCancel: () => void;
7
- onKeyUp: TLEventHandlers["onKeyUp"];
8
- }
@@ -1,13 +0,0 @@
1
- import { StateNode, type TLEventHandlers } from "@tldraw/editor";
2
- import { type AvatarShape } from "./type";
3
- export declare class Pointing extends StateNode {
4
- static id: string;
5
- shape?: AvatarShape;
6
- markId: string;
7
- onPointerUp: TLEventHandlers["onPointerUp"];
8
- onCancel: TLEventHandlers["onCancel"];
9
- onComplete: TLEventHandlers["onComplete"];
10
- onInterrupt: TLEventHandlers["onInterrupt"];
11
- onPointerMove: TLEventHandlers["onPointerMove"];
12
- cancel(): void;
13
- }
@@ -1,9 +0,0 @@
1
- import { T, type TLBaseShape } from "@tldraw/tldraw";
2
- export declare const AvatarShapeProps: {
3
- color: import("@tldraw/tlschema").EnumStyleProp<"black" | "blue" | "green" | "grey" | "light-blue" | "light-green" | "light-red" | "light-violet" | "orange" | "red" | "violet" | "white" | "yellow">;
4
- fill: import("@tldraw/tlschema").EnumStyleProp<"fill" | "none" | "pattern" | "semi" | "solid">;
5
- size: import("@tldraw/tlschema").EnumStyleProp<"l" | "m" | "s" | "xl">;
6
- font: import("@tldraw/tlschema").EnumStyleProp<"draw" | "mono" | "sans" | "serif">;
7
- text: T.Validator<string>;
8
- };
9
- export type AvatarShape = TLBaseShape<"avatar", typeof AvatarShapeProps>;
@@ -1,18 +0,0 @@
1
- import { Rectangle2d, ShapeUtil, type TLBaseShape } from "@tldraw/tldraw";
2
- type AudioShape = TLBaseShape<"audio-card", {
3
- src: string;
4
- poster: string;
5
- fileName: string;
6
- fileSize: number;
7
- }>;
8
- export declare class AudioShapeUtil extends ShapeUtil<AudioShape> {
9
- static type: "audio-card";
10
- containerRef?: HTMLElement;
11
- canResize: () => boolean;
12
- getDefaultProps(): AudioShape["props"];
13
- getGeometry(shape: AudioShape): Rectangle2d;
14
- component(shape: AudioShape): import("react/jsx-runtime").JSX.Element;
15
- indicator(shape: AudioShape): import("react/jsx-runtime").JSX.Element;
16
- toSvg(shape: AudioShape): Promise<import("react/jsx-runtime").JSX.Element>;
17
- }
18
- export {};
@@ -1,23 +0,0 @@
1
- import { type JsonObject, Rectangle2d, ShapeUtil, type TLBaseShape, type TLResizeInfo, type TLShapeId } from "@tldraw/tldraw";
2
- type CardShape = TLBaseShape<"data-card", {
3
- w: number;
4
- h: number;
5
- } & KeyValue>;
6
- export declare class CardShapeUtil extends ShapeUtil<CardShape> {
7
- static type: "data-card";
8
- onResize(shape: CardShape, info: TLResizeInfo<CardShape>): Omit<{
9
- id: TLShapeId;
10
- meta?: Partial<JsonObject> | undefined;
11
- props?: Partial<{
12
- w: number;
13
- h: number;
14
- } & KeyValue<any>> | undefined;
15
- type: "data-card";
16
- } & Partial<Omit<CardShape, "props" | "type" | "id" | "meta">>, "type" | "id"> | undefined;
17
- getDefaultProps(): CardShape["props"];
18
- getGeometry(shape: CardShape): Rectangle2d;
19
- component(shape: CardShape): import("react/jsx-runtime").JSX.Element;
20
- indicator(shape: CardShape): import("react/jsx-runtime").JSX.Element;
21
- toSvg(shape: CardShape): Promise<import("react/jsx-runtime").JSX.Element>;
22
- }
23
- export {};
@@ -1,18 +0,0 @@
1
- import { Rectangle2d, ShapeUtil, type TLBaseShape } from "@tldraw/tldraw";
2
- type FileShape = TLBaseShape<"file-card", {
3
- icon: string;
4
- fileType: string;
5
- fileName: string;
6
- fileSize: number;
7
- }>;
8
- export declare class FileShapeUtil extends ShapeUtil<FileShape> {
9
- static type: "file-card";
10
- containerRef?: HTMLElement;
11
- canResize: () => boolean;
12
- getDefaultProps(): FileShape["props"];
13
- getGeometry(shape: FileShape): Rectangle2d;
14
- component(shape: FileShape): import("react/jsx-runtime").JSX.Element;
15
- indicator(shape: FileShape): import("react/jsx-runtime").JSX.Element;
16
- toSvg(shape: FileShape): Promise<import("react/jsx-runtime").JSX.Element>;
17
- }
18
- export {};
@@ -1,29 +0,0 @@
1
- import { type JsonObject, Rectangle2d, ShapeUtil, type TLBaseShape, type TLResizeInfo, type TLShapeId } from "@tldraw/tldraw";
2
- type ImageShape = TLBaseShape<"image-card", {
3
- w: number;
4
- h: number;
5
- src: string;
6
- fileName: string;
7
- fileSize: number;
8
- }>;
9
- export declare class ImageShapeUtil extends ShapeUtil<ImageShape> {
10
- static type: "image-card";
11
- onResize(shape: ImageShape, info: TLResizeInfo<ImageShape>): Omit<{
12
- id: TLShapeId;
13
- meta?: Partial<JsonObject> | undefined;
14
- props?: Partial<{
15
- w: number;
16
- h: number;
17
- src: string;
18
- fileName: string;
19
- fileSize: number;
20
- }> | undefined;
21
- type: "image-card";
22
- } & Partial<Omit<ImageShape, "props" | "type" | "id" | "meta">>, "type" | "id"> | undefined;
23
- getDefaultProps(): ImageShape["props"];
24
- getGeometry(shape: ImageShape): Rectangle2d;
25
- component(shape: ImageShape): import("react/jsx-runtime").JSX.Element;
26
- indicator(shape: ImageShape): import("react/jsx-runtime").JSX.Element;
27
- toSvg(shape: ImageShape): Promise<import("react/jsx-runtime").JSX.Element>;
28
- }
29
- export {};
@@ -1,32 +0,0 @@
1
- import { type JsonObject, Rectangle2d, ShapeUtil, type TLBaseShape, type TLResizeInfo, type TLShapeId } from "@tldraw/tldraw";
2
- type VideoShape = TLBaseShape<"video-card", {
3
- w: number;
4
- h: number;
5
- src: string;
6
- poster: string;
7
- fileName: string;
8
- fileSize: number;
9
- }>;
10
- export declare class VideoShapeUtil extends ShapeUtil<VideoShape> {
11
- static type: "video-card";
12
- containerRef?: HTMLElement;
13
- onResize(shape: VideoShape, info: TLResizeInfo<VideoShape>): Omit<{
14
- id: TLShapeId;
15
- meta?: Partial<JsonObject> | undefined;
16
- props?: Partial<{
17
- w: number;
18
- h: number;
19
- src: string;
20
- poster: string;
21
- fileName: string;
22
- fileSize: number;
23
- }> | undefined;
24
- type: "video-card";
25
- } & Partial<Omit<VideoShape, "props" | "type" | "id" | "meta">>, "type" | "id"> | undefined;
26
- getDefaultProps(): VideoShape["props"];
27
- getGeometry(shape: VideoShape): Rectangle2d;
28
- component(shape: VideoShape): import("react/jsx-runtime").JSX.Element;
29
- indicator(shape: VideoShape): import("react/jsx-runtime").JSX.Element;
30
- toSvg(shape: VideoShape): Promise<import("react/jsx-runtime").JSX.Element>;
31
- }
32
- export {};
@@ -1,291 +0,0 @@
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 {
27
- DefaultToolbar,
28
- DefaultToolbarContent,
29
- getSnapshot,
30
- loadSnapshot,
31
- Tldraw,
32
- TldrawUiMenuItem,
33
- useIsToolSelected,
34
- useTools,
35
- type Editor,
36
- type TLEditorSnapshot,
37
- type TLUiAssetUrlOverrides,
38
- } from "@tldraw/tldraw";
39
- import "@tldraw/tldraw/tldraw.css";
40
- import {
41
- useCallback,
42
- useEffect,
43
- useImperativeHandle,
44
- useLayoutEffect,
45
- useMemo,
46
- useState,
47
- type DragEvent,
48
- type FC,
49
- type RefObject,
50
- } from "react";
51
- import { DrawContextProvider } from "./DrawContext";
52
- import {
53
- AvatarShapeTool,
54
- AvatarShapeUtil,
55
- } from "./shapes/avatar/AvatarShapeTool";
56
- import { AudioShapeUtil } from "./shapes/custom/AudioShape";
57
- import { CardShapeUtil } from "./shapes/custom/CardShape";
58
- import { FileShapeUtil } from "./shapes/custom/FileShape";
59
- import { ImageShapeUtil } from "./shapes/custom/ImageShape";
60
- import { VideoShapeUtil } from "./shapes/custom/VideoShape";
61
-
62
- const customAssetUrls: TLUiAssetUrlOverrides = {
63
- icons: {
64
- avatar:
65
- "data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiPgo8cGF0aCBkPSJNMjIuOCAyMi44di0yLjRjMC0xLjY1Ni0wLjY3My0zLjE1OC0xLjc1Ny00LjI0M3MtMi41ODctMS43NTctNC4yNDMtMS43NTdoLTkuNmMtMS42NTYgMC0zLjE1OCAwLjY3My00LjI0MyAxLjc1N3MtMS43NTcgMi41ODctMS43NTcgNC4yNDN2Mi40YzAgMC42NjIgMC41MzggMS4yIDEuMiAxLjJzMS4yLTAuNTM4IDEuMi0xLjJ2LTIuNGMwLTAuOTk1IDAuNDAyLTEuODkyIDEuMDU1LTIuNTQ1czEuNTUtMS4wNTUgMi41NDUtMS4wNTVoOS42YzAuOTk1IDAgMS44OTIgMC40MDIgMi41NDUgMS4wNTVzMS4wNTUgMS41NSAxLjA1NSAyLjU0NXYyLjRjMCAwLjY2MiAwLjUzOCAxLjIgMS4yIDEuMnMxLjItMC41MzggMS4yLTEuMnpNMTggNmMwLTEuNjU2LTAuNjczLTMuMTU4LTEuNzU3LTQuMjQzcy0yLjU4Ny0xLjc1Ny00LjI0My0xLjc1Ny0zLjE1OCAwLjY3My00LjI0MyAxLjc1Ny0xLjc1NyAyLjU4Ny0xLjc1NyA0LjI0MyAwLjY3MyAzLjE1OCAxLjc1NyA0LjI0MyAyLjU4NyAxLjc1NyA0LjI0MyAxLjc1NyAzLjE1OC0wLjY3MyA0LjI0My0xLjc1NyAxLjc1Ny0yLjU4NyAxLjc1Ny00LjI0M3pNMTUuNiA2YzAgMC45OTUtMC40MDIgMS44OTItMS4wNTUgMi41NDVzLTEuNTUgMS4wNTUtMi41NDUgMS4wNTUtMS44OTItMC40MDItMi41NDUtMS4wNTUtMS4wNTUtMS41NS0xLjA1NS0yLjU0NSAwLjQwMi0xLjg5MiAxLjA1NS0yLjU0NSAxLjU1LTEuMDU1IDIuNTQ1LTEuMDU1IDEuODkyIDAuNDAyIDIuNTQ1IDEuMDU1IDEuMDU1IDEuNTUgMS4wNTUgMi41NDV6Ij48L3BhdGg+Cjwvc3ZnPgo=",
66
- },
67
- };
68
-
69
- export async function getSvgAsDataUrl(svg: SVGElement) {
70
- const clone = svg.cloneNode(true) as SVGGraphicsElement;
71
- clone.setAttribute("encoding", 'UTF-8"');
72
-
73
- const fileReader = new FileReader();
74
- const imgs = Array.from(clone.querySelectorAll("image"));
75
-
76
- for (const img of imgs) {
77
- const src = img.getAttribute("xlink:href");
78
- if (src) {
79
- if (!src.startsWith("data:")) {
80
- const blob = await (await fetch(src)).blob();
81
- const base64 = await new Promise<string>((resolve, reject) => {
82
- fileReader.onload = () => resolve(fileReader.result as string);
83
- fileReader.onerror = () => reject(fileReader.error);
84
- fileReader.readAsDataURL(blob);
85
- });
86
- img.setAttribute("xlink:href", base64);
87
- }
88
- }
89
- }
90
-
91
- const svgStr = new XMLSerializer().serializeToString(clone);
92
- // NOTE: `unescape` works everywhere although deprecated
93
- const base64SVG =
94
- typeof window !== "undefined"
95
- ? window.btoa(unescape(encodeURIComponent(svgStr)))
96
- : "";
97
- return `data:image/svg+xml;base64,${base64SVG}`;
98
- }
99
-
100
- export interface DrawProps {
101
- snapshot?: TLEditorSnapshot;
102
- onUpdate?: (snapshot: TLEditorSnapshot) => void;
103
- renderer?: (props: KeyValue) => AnyObject;
104
- canvasRef?: RefObject<{ exportPages: () => Promise<KeyValue[]> }>;
105
- }
106
-
107
- const TypeMap: KeyValue = {
108
- image: "image-card",
109
- video: "video-card",
110
- audio: "audio-card",
111
- file: "file-card",
112
- card: "data-card",
113
- };
114
-
115
- export const DrawCanvas: FC<DrawProps> = ({
116
- snapshot,
117
- renderer,
118
- onUpdate,
119
- canvasRef,
120
- }) => {
121
- const [editorRef, setEditor] = useState<Editor>();
122
- const isDark = useIsDark();
123
-
124
- useEffect(() => {
125
- editorRef?.user.updateUserPreferences({
126
- colorScheme: isDark ? "dark" : "light",
127
- });
128
- }, [editorRef, isDark]);
129
-
130
- useEffect(() => {
131
- const handler = debounce(() => {
132
- editorRef && onUpdate?.(getSnapshot(editorRef.store));
133
- }, 500);
134
- editorRef?.sideEffects.registerAfterChangeHandler("shape", handler);
135
- editorRef?.sideEffects.registerAfterCreateHandler("shape", handler);
136
- editorRef?.sideEffects.registerAfterDeleteHandler("shape", handler);
137
-
138
- return () => {
139
- //
140
- };
141
- }, [editorRef]);
142
-
143
- useLayoutEffect(() => {
144
- setTimeout(() => {
145
- editorRef?.store && snapshot && loadSnapshot(editorRef.store, snapshot);
146
- }, 500);
147
- }, [editorRef, snapshot]);
148
-
149
- const handleDragOver = useCallback((e: DragEvent) => {
150
- if (!e.dataTransfer.getData("react-fabric/canvas")) {
151
- e.preventDefault();
152
- return false;
153
- }
154
- return true;
155
- }, []);
156
-
157
- const handleDrop = useCallback(
158
- (e: DragEvent) => {
159
- const data = e.dataTransfer.getData("react-fabric/canvas");
160
- if (!data) {
161
- e.preventDefault();
162
- return false;
163
- }
164
- const { type, ...props } = JSON.parse(data);
165
- if (type in TypeMap) {
166
- const { x = 0, y = 0 } =
167
- editorRef?.getContainer().getBoundingClientRect() ?? {};
168
- editorRef?.createShape({
169
- type: TypeMap[type],
170
- x: e.clientX - x,
171
- y: e.clientY - y,
172
- props,
173
- });
174
- }
175
- return true;
176
- },
177
- [editorRef],
178
- );
179
-
180
- useImperativeHandle(
181
- canvasRef,
182
- () => ({
183
- exportPages: async () => {
184
- const currentPage = editorRef?.getCurrentPageId();
185
- const pages = Object.keys(
186
- editorRef?.store.getSnapshot().store ?? {},
187
- ).filter((key) => key.startsWith("page:"));
188
- const pageSnapshots: KeyValue[] = [];
189
- while (pages.length) {
190
- const pg: AnyObject = pages.shift();
191
- await new Promise((resolve) => {
192
- editorRef?.addListener("change", () => {
193
- if (editorRef.getCurrentPageId() === pg) {
194
- editorRef.removeListener("change");
195
- resolve(0);
196
- }
197
- });
198
- editorRef?.setCurrentPage(pg);
199
- });
200
- const shapes: AnyObject = editorRef?.getCurrentPageShapeIds();
201
- const svg = await editorRef?.getSvg([...shapes], {
202
- scale: 1,
203
- background: true,
204
- });
205
- if (svg)
206
- pageSnapshots.push({
207
- id: pg,
208
- name: editorRef?.getCurrentPage().name,
209
- content: { image: await getSvgAsDataUrl(svg) },
210
- });
211
- }
212
- currentPage && editorRef?.setCurrentPage(currentPage);
213
- return pageSnapshots;
214
- },
215
- }),
216
- [editorRef],
217
- );
218
-
219
- const TLDraw = useMemo(
220
- () => (
221
- <Tldraw
222
- assetUrls={customAssetUrls}
223
- shapeUtils={[
224
- AvatarShapeUtil,
225
- AudioShapeUtil,
226
- ImageShapeUtil,
227
- VideoShapeUtil,
228
- CardShapeUtil,
229
- FileShapeUtil,
230
- ]}
231
- tools={[AvatarShapeTool]}
232
- onMount={setEditor}
233
- components={{
234
- Toolbar: (props) => {
235
- const tools = useTools();
236
- const isAvatarSelected = useIsToolSelected(tools.avatar);
237
- return (
238
- <DefaultToolbar {...props}>
239
- <DefaultToolbarContent />
240
- <TldrawUiMenuItem
241
- {...tools.avatar}
242
- isSelected={isAvatarSelected}
243
- />
244
- </DefaultToolbar>
245
- );
246
- },
247
- }}
248
- overrides={{
249
- translations: {
250
- en: {
251
- "tool.avatar": "Avatar",
252
- },
253
- },
254
- tools(editor, schema) {
255
- schema.avatar = {
256
- id: "avatar",
257
- label: "tool.avatar" as AnyObject,
258
- readonlyOk: false,
259
- icon: "avatar",
260
- onSelect() {
261
- editor.setCurrentTool("avatar");
262
- },
263
- };
264
- return { ...schema };
265
- },
266
- actions(editor, schema) {
267
- delete schema["insert-embed"];
268
- delete schema["insert-media"];
269
- return schema;
270
- },
271
- }}
272
- />
273
- ),
274
- [],
275
- );
276
-
277
- return (
278
- <DrawContextProvider renderer={renderer}>
279
- <Section>
280
- <div
281
- className="absolute inset-0"
282
- onDragOver={handleDragOver}
283
- onDrop={handleDrop}
284
- data-testid="draw-canvas"
285
- >
286
- {TLDraw}
287
- </div>
288
- </Section>
289
- </DrawContextProvider>
290
- );
291
- };