@tldraw/editor 5.5.0 → 5.6.0-canary.669b4c97f643

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.
@@ -1,3 +1,4 @@
1
+ import { clamp } from "../../../primitives/utils.mjs";
1
2
  import { Vec } from "../../../primitives/Vec.mjs";
2
3
  function resizeBox(shape, info, opts = {}) {
3
4
  const { newPoint, handle, scaleX, scaleY } = info;
@@ -6,29 +7,31 @@ function resizeBox(shape, info, opts = {}) {
6
7
  let h = shape.props.h * scaleY;
7
8
  const offset = new Vec(0, 0);
8
9
  if (w > 0) {
9
- if (w < minWidth) {
10
+ const clampedW = clamp(w, minWidth, maxWidth);
11
+ if (clampedW !== w) {
10
12
  switch (handle) {
11
13
  case "top_left":
12
14
  case "left":
13
15
  case "bottom_left": {
14
- offset.x = w - minWidth;
16
+ offset.x = w - clampedW;
15
17
  break;
16
18
  }
17
19
  case "top":
18
20
  case "bottom": {
19
- offset.x = (w - minWidth) / 2;
21
+ offset.x = (w - clampedW) / 2;
20
22
  break;
21
23
  }
22
24
  default: {
23
25
  offset.x = 0;
24
26
  }
25
27
  }
26
- w = minWidth;
28
+ w = clampedW;
27
29
  }
28
30
  } else {
29
31
  offset.x = w;
30
32
  w = -w;
31
- if (w < minWidth) {
33
+ const clampedW = clamp(w, minWidth, maxWidth);
34
+ if (clampedW !== w) {
32
35
  switch (handle) {
33
36
  case "top_left":
34
37
  case "left":
@@ -37,36 +40,38 @@ function resizeBox(shape, info, opts = {}) {
37
40
  break;
38
41
  }
39
42
  default: {
40
- offset.x = -minWidth;
43
+ offset.x = -clampedW;
41
44
  }
42
45
  }
43
- w = minWidth;
46
+ w = clampedW;
44
47
  }
45
48
  }
46
49
  if (h > 0) {
47
- if (h < minHeight) {
50
+ const clampedH = clamp(h, minHeight, maxHeight);
51
+ if (clampedH !== h) {
48
52
  switch (handle) {
49
53
  case "top_left":
50
54
  case "top":
51
55
  case "top_right": {
52
- offset.y = h - minHeight;
56
+ offset.y = h - clampedH;
53
57
  break;
54
58
  }
55
59
  case "right":
56
60
  case "left": {
57
- offset.y = (h - minHeight) / 2;
61
+ offset.y = (h - clampedH) / 2;
58
62
  break;
59
63
  }
60
64
  default: {
61
65
  offset.y = 0;
62
66
  }
63
67
  }
64
- h = minHeight;
68
+ h = clampedH;
65
69
  }
66
70
  } else {
67
71
  offset.y = h;
68
72
  h = -h;
69
- if (h < minHeight) {
73
+ const clampedH = clamp(h, minHeight, maxHeight);
74
+ if (clampedH !== h) {
70
75
  switch (handle) {
71
76
  case "top_left":
72
77
  case "top":
@@ -75,10 +80,10 @@ function resizeBox(shape, info, opts = {}) {
75
80
  break;
76
81
  }
77
82
  default: {
78
- offset.y = -minHeight;
83
+ offset.y = -clampedH;
79
84
  }
80
85
  }
81
- h = minHeight;
86
+ h = clampedH;
82
87
  }
83
88
  }
84
89
  const { x, y } = offset.rot(shape.rotation).add(newPoint);
@@ -87,8 +92,8 @@ function resizeBox(shape, info, opts = {}) {
87
92
  x,
88
93
  y,
89
94
  props: {
90
- w: Math.min(maxWidth, w),
91
- h: Math.min(maxHeight, h)
95
+ w,
96
+ h
92
97
  }
93
98
  };
94
99
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/lib/editor/shapes/shared/resizeBox.ts"],
4
- "sourcesContent": ["import { VecModel } from '@tldraw/tlschema'\nimport { Box } from '../../../primitives/Box'\nimport { Vec } from '../../../primitives/Vec'\nimport { TLResizeHandle } from '../../types/selection-types'\nimport type { TLBaseBoxShape } from '../BaseBoxShapeUtil'\nimport { TLResizeMode } from '../ShapeUtil'\n\n/** @public */\nexport interface ResizeBoxOptions {\n\tminWidth?: number\n\tmaxWidth?: number\n\tminHeight?: number\n\tmaxHeight?: number\n}\n\n/** @public */\nexport function resizeBox<T extends TLBaseBoxShape>(\n\tshape: T,\n\tinfo: {\n\t\tnewPoint: VecModel\n\t\thandle: TLResizeHandle\n\t\tmode: TLResizeMode\n\t\tscaleX: number\n\t\tscaleY: number\n\t\tinitialBounds: Box\n\t\tinitialShape: T\n\t},\n\topts = {} as ResizeBoxOptions\n): T {\n\tconst { newPoint, handle, scaleX, scaleY } = info\n\tconst { minWidth = 1, maxWidth = Infinity, minHeight = 1, maxHeight = Infinity } = opts\n\n\tlet w = shape.props.w * scaleX\n\tlet h = shape.props.h * scaleY\n\n\tconst offset = new Vec(0, 0)\n\n\tif (w > 0) {\n\t\tif (w < minWidth) {\n\t\t\tswitch (handle) {\n\t\t\t\tcase 'top_left':\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'bottom_left': {\n\t\t\t\t\toffset.x = w - minWidth\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'top':\n\t\t\t\tcase 'bottom': {\n\t\t\t\t\toffset.x = (w - minWidth) / 2\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\toffset.x = 0\n\t\t\t\t}\n\t\t\t}\n\t\t\tw = minWidth\n\t\t}\n\t} else {\n\t\toffset.x = w\n\t\tw = -w\n\t\tif (w < minWidth) {\n\t\t\tswitch (handle) {\n\t\t\t\tcase 'top_left':\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'bottom_left': {\n\t\t\t\t\toffset.x = -w\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\toffset.x = -minWidth\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tw = minWidth\n\t\t}\n\t}\n\n\tif (h > 0) {\n\t\tif (h < minHeight) {\n\t\t\tswitch (handle) {\n\t\t\t\tcase 'top_left':\n\t\t\t\tcase 'top':\n\t\t\t\tcase 'top_right': {\n\t\t\t\t\toffset.y = h - minHeight\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'right':\n\t\t\t\tcase 'left': {\n\t\t\t\t\toffset.y = (h - minHeight) / 2\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\toffset.y = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\th = minHeight\n\t\t}\n\t} else {\n\t\toffset.y = h\n\t\th = -h\n\t\tif (h < minHeight) {\n\t\t\tswitch (handle) {\n\t\t\t\tcase 'top_left':\n\t\t\t\tcase 'top':\n\t\t\t\tcase 'top_right': {\n\t\t\t\t\toffset.y = -h\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\toffset.y = -minHeight\n\t\t\t\t}\n\t\t\t}\n\t\t\th = minHeight\n\t\t}\n\t}\n\n\tconst { x, y } = offset.rot(shape.rotation).add(newPoint)\n\n\treturn {\n\t\t...shape,\n\t\tx,\n\t\ty,\n\t\tprops: {\n\t\t\tw: Math.min(maxWidth, w),\n\t\t\th: Math.min(maxHeight, h),\n\t\t},\n\t}\n}\n"],
5
- "mappings": "AAEA,SAAS,WAAW;AAcb,SAAS,UACf,OACA,MASA,OAAO,CAAC,GACJ;AACJ,QAAM,EAAE,UAAU,QAAQ,QAAQ,OAAO,IAAI;AAC7C,QAAM,EAAE,WAAW,GAAG,WAAW,UAAU,YAAY,GAAG,YAAY,SAAS,IAAI;AAEnF,MAAI,IAAI,MAAM,MAAM,IAAI;AACxB,MAAI,IAAI,MAAM,MAAM,IAAI;AAExB,QAAM,SAAS,IAAI,IAAI,GAAG,CAAC;AAE3B,MAAI,IAAI,GAAG;AACV,QAAI,IAAI,UAAU;AACjB,cAAQ,QAAQ;AAAA,QACf,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK,eAAe;AACnB,iBAAO,IAAI,IAAI;AACf;AAAA,QACD;AAAA,QACA,KAAK;AAAA,QACL,KAAK,UAAU;AACd,iBAAO,KAAK,IAAI,YAAY;AAC5B;AAAA,QACD;AAAA,QACA,SAAS;AACR,iBAAO,IAAI;AAAA,QACZ;AAAA,MACD;AACA,UAAI;AAAA,IACL;AAAA,EACD,OAAO;AACN,WAAO,IAAI;AACX,QAAI,CAAC;AACL,QAAI,IAAI,UAAU;AACjB,cAAQ,QAAQ;AAAA,QACf,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK,eAAe;AACnB,iBAAO,IAAI,CAAC;AACZ;AAAA,QACD;AAAA,QACA,SAAS;AACR,iBAAO,IAAI,CAAC;AAAA,QACb;AAAA,MACD;AAEA,UAAI;AAAA,IACL;AAAA,EACD;AAEA,MAAI,IAAI,GAAG;AACV,QAAI,IAAI,WAAW;AAClB,cAAQ,QAAQ;AAAA,QACf,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK,aAAa;AACjB,iBAAO,IAAI,IAAI;AACf;AAAA,QACD;AAAA,QACA,KAAK;AAAA,QACL,KAAK,QAAQ;AACZ,iBAAO,KAAK,IAAI,aAAa;AAC7B;AAAA,QACD;AAAA,QACA,SAAS;AACR,iBAAO,IAAI;AAAA,QACZ;AAAA,MACD;AAEA,UAAI;AAAA,IACL;AAAA,EACD,OAAO;AACN,WAAO,IAAI;AACX,QAAI,CAAC;AACL,QAAI,IAAI,WAAW;AAClB,cAAQ,QAAQ;AAAA,QACf,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK,aAAa;AACjB,iBAAO,IAAI,CAAC;AACZ;AAAA,QACD;AAAA,QACA,SAAS;AACR,iBAAO,IAAI,CAAC;AAAA,QACb;AAAA,MACD;AACA,UAAI;AAAA,IACL;AAAA,EACD;AAEA,QAAM,EAAE,GAAG,EAAE,IAAI,OAAO,IAAI,MAAM,QAAQ,EAAE,IAAI,QAAQ;AAExD,SAAO;AAAA,IACN,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA,OAAO;AAAA,MACN,GAAG,KAAK,IAAI,UAAU,CAAC;AAAA,MACvB,GAAG,KAAK,IAAI,WAAW,CAAC;AAAA,IACzB;AAAA,EACD;AACD;",
4
+ "sourcesContent": ["import { VecModel } from '@tldraw/tlschema'\nimport { Box } from '../../../primitives/Box'\nimport { clamp } from '../../../primitives/utils'\nimport { Vec } from '../../../primitives/Vec'\nimport { TLResizeHandle } from '../../types/selection-types'\nimport type { TLBaseBoxShape } from '../BaseBoxShapeUtil'\nimport { TLResizeMode } from '../ShapeUtil'\n\n/** @public */\nexport interface ResizeBoxOptions {\n\tminWidth?: number\n\tmaxWidth?: number\n\tminHeight?: number\n\tmaxHeight?: number\n}\n\n/** @public */\nexport function resizeBox<T extends TLBaseBoxShape>(\n\tshape: T,\n\tinfo: {\n\t\tnewPoint: VecModel\n\t\thandle: TLResizeHandle\n\t\tmode: TLResizeMode\n\t\tscaleX: number\n\t\tscaleY: number\n\t\tinitialBounds: Box\n\t\tinitialShape: T\n\t},\n\topts = {} as ResizeBoxOptions\n): T {\n\tconst { newPoint, handle, scaleX, scaleY } = info\n\tconst { minWidth = 1, maxWidth = Infinity, minHeight = 1, maxHeight = Infinity } = opts\n\n\tlet w = shape.props.w * scaleX\n\tlet h = shape.props.h * scaleY\n\n\tconst offset = new Vec(0, 0)\n\n\tif (w > 0) {\n\t\tconst clampedW = clamp(w, minWidth, maxWidth)\n\t\tif (clampedW !== w) {\n\t\t\tswitch (handle) {\n\t\t\t\tcase 'top_left':\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'bottom_left': {\n\t\t\t\t\toffset.x = w - clampedW\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'top':\n\t\t\t\tcase 'bottom': {\n\t\t\t\t\toffset.x = (w - clampedW) / 2\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\toffset.x = 0\n\t\t\t\t}\n\t\t\t}\n\t\t\tw = clampedW\n\t\t}\n\t} else {\n\t\toffset.x = w\n\t\tw = -w\n\t\tconst clampedW = clamp(w, minWidth, maxWidth)\n\t\tif (clampedW !== w) {\n\t\t\tswitch (handle) {\n\t\t\t\tcase 'top_left':\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'bottom_left': {\n\t\t\t\t\toffset.x = -w\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\toffset.x = -clampedW\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tw = clampedW\n\t\t}\n\t}\n\n\tif (h > 0) {\n\t\tconst clampedH = clamp(h, minHeight, maxHeight)\n\t\tif (clampedH !== h) {\n\t\t\tswitch (handle) {\n\t\t\t\tcase 'top_left':\n\t\t\t\tcase 'top':\n\t\t\t\tcase 'top_right': {\n\t\t\t\t\toffset.y = h - clampedH\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'right':\n\t\t\t\tcase 'left': {\n\t\t\t\t\toffset.y = (h - clampedH) / 2\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\toffset.y = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\th = clampedH\n\t\t}\n\t} else {\n\t\toffset.y = h\n\t\th = -h\n\t\tconst clampedH = clamp(h, minHeight, maxHeight)\n\t\tif (clampedH !== h) {\n\t\t\tswitch (handle) {\n\t\t\t\tcase 'top_left':\n\t\t\t\tcase 'top':\n\t\t\t\tcase 'top_right': {\n\t\t\t\t\toffset.y = -h\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\toffset.y = -clampedH\n\t\t\t\t}\n\t\t\t}\n\t\t\th = clampedH\n\t\t}\n\t}\n\n\tconst { x, y } = offset.rot(shape.rotation).add(newPoint)\n\n\treturn {\n\t\t...shape,\n\t\tx,\n\t\ty,\n\t\tprops: {\n\t\t\tw,\n\t\t\th,\n\t\t},\n\t}\n}\n"],
5
+ "mappings": "AAEA,SAAS,aAAa;AACtB,SAAS,WAAW;AAcb,SAAS,UACf,OACA,MASA,OAAO,CAAC,GACJ;AACJ,QAAM,EAAE,UAAU,QAAQ,QAAQ,OAAO,IAAI;AAC7C,QAAM,EAAE,WAAW,GAAG,WAAW,UAAU,YAAY,GAAG,YAAY,SAAS,IAAI;AAEnF,MAAI,IAAI,MAAM,MA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,UAAM,WAAW,MAAM,GAAG,WAAW,SAAS;AAC9C,QAAI,aAAa,GAAG;AACnB,cAAQ,QAAQ;AAAA,QACf,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK,aAAa;AACjB,iBAAO,IAAI,CAAC;AACZ;AAAA,QACD;AAAA,QACA,SAAS;AACR,iBAAO,IAAI,CAAC;AAAA,QACb;AAAA,MACD;AACA,UAAI;AAAA,IACL;AAAA,EACD;AAEA,QAAM,EAAE,GAAG,EAAE,IAAI,OAAO,IAAI,MAAM,QAAQ,EAAE,IAAI,QAAQ;AAExD,SAAO;AAAA,IACN,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA,OAAO;AAAA,MACN;AAAA,MACA;AAAA,IACD;AAAA,EACD;AACD;",
6
6
  "names": []
7
7
  }
@@ -11,9 +11,9 @@ function getCursorCss(svg, r, tr, f, color, hotspotX = 16, hotspotY = 16) {
11
11
  const c = Math.cos(a);
12
12
  const dx = 1 * c - 1 * s;
13
13
  const dy = 1 * s + 1 * c;
14
- return `url("data:image/svg+xml,<svg height='32' width='32' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' style='color: ${color};'><defs><filter id='shadow' y='-40%' x='-40%' width='180px' height='180%' color-interpolation-filters='sRGB'><feDropShadow dx='${dx}' dy='${dy}' stdDeviation='1.2' flood-opacity='.5'/></filter></defs><g fill='none' transform='rotate(${r + tr} 16 16)${f ? ` scale(-1,-1) translate(0, -32)` : ""}' filter='url(%23shadow)'>` + svg.replaceAll(`"`, `'`) + `</g></svg>") ${hotspotX} ${hotspotY}, pointer`;
14
+ return `url("data:image/svg+xml,<svg height='32' width='32' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' style='color: ${encodeURIComponent(color)};'><defs><filter id='shadow' y='-40%' x='-40%' width='180px' height='180%' color-interpolation-filters='sRGB'><feDropShadow dx='${dx}' dy='${dy}' stdDeviation='1.2' flood-opacity='.5'/></filter></defs><g fill='none' transform='rotate(${r + tr} 16 16)${f ? ` scale(-1,-1) translate(0, -32)` : ""}' filter='url(%23shadow)'>` + svg.replaceAll(`"`, `'`) + `</g></svg>") ${hotspotX} ${hotspotY}, pointer`;
15
15
  }
16
- const STATIC_CURSORS = [
16
+ const STATIC_CURSORS = /* @__PURE__ */ new Set([
17
17
  "default",
18
18
  "pointer",
19
19
  "cross",
@@ -23,9 +23,12 @@ const STATIC_CURSORS = [
23
23
  "grabbing",
24
24
  "text",
25
25
  "zoom-in",
26
- "zoom-out"
27
- ];
28
- const CURSORS = {
26
+ "zoom-out",
27
+ "rotate",
28
+ "resize-edge",
29
+ "resize-corner"
30
+ ]);
31
+ const DYNAMIC_CURSORS = {
29
32
  none: () => "none",
30
33
  "ew-resize": (r, f, c) => getCursorCss(EDGE_SVG, r, 0, f, c),
31
34
  "ns-resize": (r, f, c) => getCursorCss(EDGE_SVG, r, 90, f, c),
@@ -37,7 +40,8 @@ const CURSORS = {
37
40
  "swne-rotate": (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 270, f, c)
38
41
  };
39
42
  function getCursor(cursor, rotation = 0, color = "black") {
40
- return CURSORS[cursor](radiansToDegrees(rotation), false, color);
43
+ if (STATIC_CURSORS.has(cursor)) return `var(--tl-cursor-${cursor})`;
44
+ return DYNAMIC_CURSORS[cursor](radiansToDegrees(rotation), false, color);
41
45
  }
42
46
  function useCursor() {
43
47
  const editor = useEditor();
@@ -46,8 +50,8 @@ function useCursor() {
46
50
  "useCursor",
47
51
  () => {
48
52
  const { type, rotation } = editor.getInstanceState().cursor;
49
- if (STATIC_CURSORS.includes(type)) {
50
- container.style.setProperty("--tl-cursor", `var(--tl-cursor-${type})`);
53
+ if (STATIC_CURSORS.has(type)) {
54
+ container.style.setProperty("--tl-cursor", getCursor(type));
51
55
  return;
52
56
  }
53
57
  const { cursor } = editor.getCurrentTheme().colors[editor.getColorMode()];
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/hooks/useCursor.ts"],
4
- "sourcesContent": ["import { useQuickReactor } from '@tldraw/state-react'\nimport { TLCursorType } from '@tldraw/tlschema'\nimport { PI, radiansToDegrees } from '../primitives/utils'\nimport { useContainer } from './useContainer'\nimport { useEditor } from './useEditor'\n\nconst CORNER_SVG = `<path d='m19.7432 17.0869-4.072 4.068 2.829 2.828-8.473-.013-.013-8.47 2.841 2.842 4.075-4.068 1.414-1.415-2.844-2.842h8.486v8.484l-2.83-2.827z' fill='%23fff'/><path d='m18.6826 16.7334-4.427 4.424 1.828 1.828-5.056-.016-.014-5.054 1.842 1.841 4.428-4.422 2.474-2.475-1.844-1.843h5.073v5.071l-1.83-1.828z' fill='%23000'/>`\nconst EDGE_SVG = `<path d='m9 17.9907v.005l5.997 5.996.001-3.999h1.999 2.02v4l5.98-6.001-5.98-5.999.001 4.019-2.021.002h-2l.001-4.022zm1.411.003 3.587-3.588-.001 2.587h3.5 2.521v-2.585l3.565 3.586-3.564 3.585-.001-2.585h-2.521l-3.499-.001-.001 2.586z' fill='%23fff'/><path d='m17.4971 18.9932h2.521v2.586l3.565-3.586-3.565-3.585v2.605h-2.521-3.5v-2.607l-3.586 3.587 3.586 3.586v-2.587z' fill='%23000'/>`\nconst ROTATE_CORNER_SVG = `<path d=\"M22.4789 9.45728L25.9935 12.9942L22.4789 16.5283V14.1032C18.126 14.1502 14.6071 17.6737 14.5675 22.0283H17.05L13.513 25.543L9.97889 22.0283H12.5674C12.6071 16.5691 17.0214 12.1503 22.4789 12.1031L22.4789 9.45728Z\" fill=\"black\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M21.4789 7.03223L27.4035 12.9945L21.4789 18.9521V15.1868C18.4798 15.6549 16.1113 18.0273 15.649 21.0284H19.475L13.5128 26.953L7.55519 21.0284H11.6189C12.1243 15.8155 16.2679 11.6677 21.4789 11.1559L21.4789 7.03223ZM22.4789 12.1031C17.0214 12.1503 12.6071 16.5691 12.5674 22.0284H9.97889L13.513 25.543L17.05 22.0284H14.5675C14.5705 21.6896 14.5947 21.3558 14.6386 21.0284C15.1157 17.4741 17.9266 14.6592 21.4789 14.1761C21.8063 14.1316 22.1401 14.1069 22.4789 14.1032V16.5284L25.9935 12.9942L22.4789 9.45729L22.4789 12.1031Z\" fill=\"white\"/>`\n\nfunction getCursorCss(\n\tsvg: string,\n\tr: number,\n\ttr: number,\n\tf: boolean,\n\tcolor: string,\n\thotspotX = 16,\n\thotspotY = 16\n) {\n\tconst a = (-tr - r) * (PI / 180)\n\tconst s = Math.sin(a)\n\tconst c = Math.cos(a)\n\tconst dx = 1 * c - 1 * s\n\tconst dy = 1 * s + 1 * c\n\n\treturn (\n\t\t`url(\"data:image/svg+xml,<svg height='32' width='32' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' style='color: ${color};'><defs><filter id='shadow' y='-40%' x='-40%' width='180px' height='180%' color-interpolation-filters='sRGB'><feDropShadow dx='${dx}' dy='${dy}' stdDeviation='1.2' flood-opacity='.5'/></filter></defs><g fill='none' transform='rotate(${\n\t\t\tr + tr\n\t\t} 16 16)${f ? ` scale(-1,-1) translate(0, -32)` : ''}' filter='url(%23shadow)'>` +\n\t\tsvg.replaceAll(`\"`, `'`) +\n\t\t`</g></svg>\") ${hotspotX} ${hotspotY}, pointer`\n\t)\n}\n\nconst STATIC_CURSORS = [\n\t'default',\n\t'pointer',\n\t'cross',\n\t'comment',\n\t'move',\n\t'grab',\n\t'grabbing',\n\t'text',\n\t'zoom-in',\n\t'zoom-out',\n]\n\ntype CursorFunction = (rotation: number, flip: boolean, color: string) => string\n\nconst CURSORS: Record<TLCursorType, CursorFunction> = {\n\tnone: () => 'none',\n\t'ew-resize': (r, f, c) => getCursorCss(EDGE_SVG, r, 0, f, c),\n\t'ns-resize': (r, f, c) => getCursorCss(EDGE_SVG, r, 90, f, c),\n\t'nesw-resize': (r, f, c) => getCursorCss(CORNER_SVG, r, 0, f, c),\n\t'nwse-resize': (r, f, c) => getCursorCss(CORNER_SVG, r, 90, f, c),\n\t'nwse-rotate': (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 0, f, c),\n\t'nesw-rotate': (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 90, f, c),\n\t'senw-rotate': (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 180, f, c),\n\t'swne-rotate': (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 270, f, c),\n}\n\n/** @public */\nexport function getCursor(cursor: TLCursorType, rotation = 0, color = 'black') {\n\treturn CURSORS[cursor](radiansToDegrees(rotation), false, color)\n}\n\nexport function useCursor() {\n\tconst editor = useEditor()\n\tconst container = useContainer()\n\n\tuseQuickReactor(\n\t\t'useCursor',\n\t\t() => {\n\t\t\tconst { type, rotation } = editor.getInstanceState().cursor\n\n\t\t\tif (STATIC_CURSORS.includes(type)) {\n\t\t\t\tcontainer.style.setProperty('--tl-cursor', `var(--tl-cursor-${type})`)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst { cursor } = editor.getCurrentTheme().colors[editor.getColorMode()]\n\t\t\tcontainer.style.setProperty('--tl-cursor', getCursor(type, rotation, cursor))\n\t\t},\n\t\t[editor, container]\n\t)\n}\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,IAAI,wBAAwB;AACrC,SAAS,oBAAoB;AAC7B,SAAS,iBAAiB;AAE1B,MAAM,aAAa;AACnB,MAAM,WAAW;AACjB,MAAM,oBAAoB;AAE1B,SAAS,aACR,KACA,GACA,IACA,GACA,OACA,WAAW,IACX,WAAW,IACV;AACD,QAAM,KAAK,CAAC,KAAK,MAAM,KAAK;AAC5B,QAAM,IAAI,KAAK,IAAI,CAAC;AACpB,QAAM,IAAI,KAAK,IAAI,CAAC;AACpB,QAAM,KAAK,IAAI,IAAI,IAAI;AACvB,QAAM,KAAK,IAAI,IAAI,IAAI;AAEvB,SACC,4HAA4H,KAAK,mIAAmI,EAAE,SAAS,EAAE,6FAChR,IAAI,EACL,UAAU,IAAI,oCAAoC,EA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AM,YAAY,eAAe,mBAAmB,IAAI,GAAG;AACrE;AAAA,MACD;AAEA,YAAM,EAAE,OAAO,IAAI,OAAO,gBAAgB,EAAE,OAAO,OAAO,aAAa,CAAC;AACxE,gBAAU,MAAM,YAAY,eAAe,UAAU,MAAM,UAAU,MAAM,CAAC;AAAA,IAC7E;AAAA,IACA,CAAC,QAAQ,SAAS;AAAA,EACnB;AACD;",
4
+ "sourcesContent": ["import { useQuickReactor } from '@tldraw/state-react'\nimport { TLCursorType } from '@tldraw/tlschema'\nimport { PI, radiansToDegrees } from '../primitives/utils'\nimport { useContainer } from './useContainer'\nimport { useEditor } from './useEditor'\n\nconst CORNER_SVG = `<path d='m19.7432 17.0869-4.072 4.068 2.829 2.828-8.473-.013-.013-8.47 2.841 2.842 4.075-4.068 1.414-1.415-2.844-2.842h8.486v8.484l-2.83-2.827z' fill='%23fff'/><path d='m18.6826 16.7334-4.427 4.424 1.828 1.828-5.056-.016-.014-5.054 1.842 1.841 4.428-4.422 2.474-2.475-1.844-1.843h5.073v5.071l-1.83-1.828z' fill='%23000'/>`\nconst EDGE_SVG = `<path d='m9 17.9907v.005l5.997 5.996.001-3.999h1.999 2.02v4l5.98-6.001-5.98-5.999.001 4.019-2.021.002h-2l.001-4.022zm1.411.003 3.587-3.588-.001 2.587h3.5 2.521v-2.585l3.565 3.586-3.564 3.585-.001-2.585h-2.521l-3.499-.001-.001 2.586z' fill='%23fff'/><path d='m17.4971 18.9932h2.521v2.586l3.565-3.586-3.565-3.585v2.605h-2.521-3.5v-2.607l-3.586 3.587 3.586 3.586v-2.587z' fill='%23000'/>`\nconst ROTATE_CORNER_SVG = `<path d=\"M22.4789 9.45728L25.9935 12.9942L22.4789 16.5283V14.1032C18.126 14.1502 14.6071 17.6737 14.5675 22.0283H17.05L13.513 25.543L9.97889 22.0283H12.5674C12.6071 16.5691 17.0214 12.1503 22.4789 12.1031L22.4789 9.45728Z\" fill=\"black\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M21.4789 7.03223L27.4035 12.9945L21.4789 18.9521V15.1868C18.4798 15.6549 16.1113 18.0273 15.649 21.0284H19.475L13.5128 26.953L7.55519 21.0284H11.6189C12.1243 15.8155 16.2679 11.6677 21.4789 11.1559L21.4789 7.03223ZM22.4789 12.1031C17.0214 12.1503 12.6071 16.5691 12.5674 22.0284H9.97889L13.513 25.543L17.05 22.0284H14.5675C14.5705 21.6896 14.5947 21.3558 14.6386 21.0284C15.1157 17.4741 17.9266 14.6592 21.4789 14.1761C21.8063 14.1316 22.1401 14.1069 22.4789 14.1032V16.5284L25.9935 12.9942L22.4789 9.45729L22.4789 12.1031Z\" fill=\"white\"/>`\n\nfunction getCursorCss(\n\tsvg: string,\n\tr: number,\n\ttr: number,\n\tf: boolean,\n\tcolor: string,\n\thotspotX = 16,\n\thotspotY = 16\n) {\n\tconst a = (-tr - r) * (PI / 180)\n\tconst s = Math.sin(a)\n\tconst c = Math.cos(a)\n\tconst dx = 1 * c - 1 * s\n\tconst dy = 1 * s + 1 * c\n\n\t// A raw '#' in the colour (hex) would end the unencoded data url as a fragment.\n\treturn (\n\t\t`url(\"data:image/svg+xml,<svg height='32' width='32' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' style='color: ${encodeURIComponent(color)};'><defs><filter id='shadow' y='-40%' x='-40%' width='180px' height='180%' color-interpolation-filters='sRGB'><feDropShadow dx='${dx}' dy='${dy}' stdDeviation='1.2' flood-opacity='.5'/></filter></defs><g fill='none' transform='rotate(${\n\t\t\tr + tr\n\t\t} 16 16)${f ? ` scale(-1,-1) translate(0, -32)` : ''}' filter='url(%23shadow)'>` +\n\t\tsvg.replaceAll(`\"`, `'`) +\n\t\t`</g></svg>\") ${hotspotX} ${hotspotY}, pointer`\n\t)\n}\n\n// Cursors that map straight to a prerendered `--tl-cursor-*` css variable rather than a runtime svg.\nconst STATIC_CURSORS = new Set<TLCursorType>([\n\t'default',\n\t'pointer',\n\t'cross',\n\t'comment',\n\t'move',\n\t'grab',\n\t'grabbing',\n\t'text',\n\t'zoom-in',\n\t'zoom-out',\n\t'rotate',\n\t'resize-edge',\n\t'resize-corner',\n])\n\ntype CursorFunction = (rotation: number, flip: boolean, color: string) => string\n\nconst DYNAMIC_CURSORS: Record<TLCursorType, CursorFunction> = {\n\tnone: () => 'none',\n\t'ew-resize': (r, f, c) => getCursorCss(EDGE_SVG, r, 0, f, c),\n\t'ns-resize': (r, f, c) => getCursorCss(EDGE_SVG, r, 90, f, c),\n\t'nesw-resize': (r, f, c) => getCursorCss(CORNER_SVG, r, 0, f, c),\n\t'nwse-resize': (r, f, c) => getCursorCss(CORNER_SVG, r, 90, f, c),\n\t'nwse-rotate': (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 0, f, c),\n\t'nesw-rotate': (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 90, f, c),\n\t'senw-rotate': (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 180, f, c),\n\t'swne-rotate': (r, f, c) => getCursorCss(ROTATE_CORNER_SVG, r, 270, f, c),\n}\n\n/** @public */\nexport function getCursor(cursor: TLCursorType, rotation = 0, color = 'black') {\n\tif (STATIC_CURSORS.has(cursor)) return `var(--tl-cursor-${cursor})`\n\treturn DYNAMIC_CURSORS[cursor](radiansToDegrees(rotation), false, color)\n}\n\nexport function useCursor() {\n\tconst editor = useEditor()\n\tconst container = useContainer()\n\n\tuseQuickReactor(\n\t\t'useCursor',\n\t\t() => {\n\t\t\tconst { type, rotation } = editor.getInstanceState().cursor\n\n\t\t\t// Static cursors don't need the theme colour, so skip reading it to avoid depending on it.\n\t\t\tif (STATIC_CURSORS.has(type)) {\n\t\t\t\tcontainer.style.setProperty('--tl-cursor', getCursor(type))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst { cursor } = editor.getCurrentTheme().colors[editor.getColorMode()]\n\t\t\tcontainer.style.setProperty('--tl-cursor', getCursor(type, rotation, cursor))\n\t\t},\n\t\t[editor, container]\n\t)\n}\n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AA,EACtE,eAAe,CAAC,GAAG,GAAG,MAAM,aAAa,mBAAmB,GAAG,IAAI,GAAG,CAAC;AAAA,EACvE,eAAe,CAAC,GAAG,GAAG,MAAM,aAAa,mBAAmB,GAAG,KAAK,GAAG,CAAC;AAAA,EACxE,eAAe,CAAC,GAAG,GAAG,MAAM,aAAa,mBAAmB,GAAG,KAAK,GAAG,CAAC;AACzE;AAGO,SAAS,UAAU,QAAsB,WAAW,GAAG,QAAQ,SAAS;AAC9E,MAAI,eAAe,IAAI,MAAM,EAAG,QAAO,mBAAmB,MAAM;AAChE,SAAO,gBAAgB,MAAM,EAAE,iBAAiB,QAAQ,GAAG,OAAO,KAAK;AACxE;AAEO,SAAS,YAAY;AAC3B,QAAM,SAAS,UAAU;AACzB,QAAM,YAAY,aAAa;AAE/B;AAAA,IACC;AAAA,IACA,MAAM;AACL,YAAM,EAAE,MAAM,SAAS,IAAI,OAAO,iBAAiB,EAAE;AAGrD,UAAI,eAAe,IAAI,IAAI,GAAG;AAC7B,kBAAU,MAAM,YAAY,eAAe,UAAU,IAAI,CAAC;AAC1D;AAAA,MACD;AAEA,YAAM,EAAE,OAAO,IAAI,OAAO,gBAAgB,EAAE,OAAO,OAAO,aAAa,CAAC;AACxE,gBAAU,MAAM,YAAY,eAAe,UAAU,MAAM,UAAU,MAAM,CAAC;AAAA,IAC7E;AAAA,IACA,CAAC,QAAQ,SAAS;AAAA,EACnB;AACD;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import { transact } from "@tldraw/state";
2
2
  import { squashRecordDiffs } from "@tldraw/store";
3
- import { assert } from "@tldraw/utils";
3
+ import { assert, noop } from "@tldraw/utils";
4
4
  import {
5
5
  TAB_ID,
6
6
  createSessionStateSnapshotSignal,
@@ -24,6 +24,7 @@ class BroadcastChannelMock {
24
24
  }
25
25
  }
26
26
  const BC = typeof BroadcastChannel === "undefined" ? BroadcastChannelMock : BroadcastChannel;
27
+ const pendingFlushes = /* @__PURE__ */ new Map();
27
28
  class TLLocalSyncClient {
28
29
  constructor(store, {
29
30
  persistenceKey,
@@ -158,6 +159,8 @@ class TLLocalSyncClient {
158
159
  this.disposables.add(() => {
159
160
  this.channel.close();
160
161
  });
162
+ await pendingFlushes.get(this.persistenceKey);
163
+ if (this.didDispose) return;
161
164
  try {
162
165
  data = await this.db.load({ sessionId: this.sessionId });
163
166
  } catch (error) {
@@ -218,7 +221,6 @@ class TLLocalSyncClient {
218
221
  if (this.didDispose) return;
219
222
  this.debug("closing");
220
223
  this.didDispose = true;
221
- this.store._flushHistory();
222
224
  this.disposables.forEach((d) => d());
223
225
  if (this.scheduledPersistTimeout) {
224
226
  clearTimeout(this.scheduledPersistTimeout);
@@ -227,7 +229,13 @@ class TLLocalSyncClient {
227
229
  if (typeof window !== "undefined" && window.tlsync === this) {
228
230
  delete window.tlsync;
229
231
  }
230
- this.flushAndCloseDb();
232
+ const previous = pendingFlushes.get(this.persistenceKey);
233
+ const flush = (previous ? previous.then(() => this.flushAndCloseDb()) : this.flushAndCloseDb()).catch(noop).then(() => {
234
+ if (pendingFlushes.get(this.persistenceKey) === flush) {
235
+ pendingFlushes.delete(this.persistenceKey);
236
+ }
237
+ });
238
+ pendingFlushes.set(this.persistenceKey, flush);
231
239
  }
232
240
  /**
233
241
  * Flush queued changes so edits made in the last PERSIST_THROTTLE_MS before unmount aren't lost,
@@ -237,11 +245,10 @@ class TLLocalSyncClient {
237
245
  */
238
246
  flushAndCloseDb() {
239
247
  if (this.persistPromise) {
240
- this.persistPromise.then(() => this.flushAndCloseDb());
241
- return;
248
+ return this.persistPromise.then(() => this.flushAndCloseDb());
242
249
  }
243
250
  if (this.didLoad && this.diffQueue.length > 0) this.persistIfNeeded();
244
- this.db.close();
251
+ return this.db.close();
245
252
  }
246
253
  isPersisting = false;
247
254
  persistPromise = null;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/lib/utils/sync/TLLocalSyncClient.ts"],
4
- "sourcesContent": ["import { Signal, transact } from '@tldraw/state'\nimport { RecordsDiff, SerializedSchema, UnknownRecord, squashRecordDiffs } from '@tldraw/store'\nimport { TLStore } from '@tldraw/tlschema'\nimport { assert } from '@tldraw/utils'\nimport {\n\tTAB_ID,\n\tTLSessionStateSnapshot,\n\tcreateSessionStateSnapshotSignal,\n\textractSessionStateFromLegacySnapshot,\n\tloadSessionStateSnapshotIntoStore,\n} from '../../config/TLSessionStateSnapshot'\nimport { refreshPage } from '../runtime'\nimport { showCantReadFromIndexDbAlert, showCantWriteToIndexDbAlert } from './alerts'\nimport { LocalIndexedDb } from './LocalIndexedDb'\n\n/** How should we debounce persists? */\nconst PERSIST_THROTTLE_MS = 350\n/** If we're in an error state, how long should we wait before retrying a write? */\nconst PERSIST_RETRY_THROTTLE_MS = 10_000\n\nconst UPDATE_INSTANCE_STATE = Symbol('UPDATE_INSTANCE_STATE')\n\n/**\n * IMPORTANT!!!\n *\n * This is just a quick-n-dirty temporary solution that will be replaced with the remote sync client\n * once it has the db integrated\n */\n\ninterface SyncMessage {\n\ttype: 'diff'\n\tstoreId: string\n\tchanges: RecordsDiff<UnknownRecord>\n\tschema: SerializedSchema\n}\n\n// Sent by new clients when they connect\n// If another client is on the channel with a newer schema version\n// It will\ninterface AnnounceMessage {\n\ttype: 'announce'\n\tschema: SerializedSchema\n}\n\ntype Message = SyncMessage | AnnounceMessage\n\ntype UnpackPromise<T> = T extends Promise<infer U> ? U : T\n\nconst msg = (msg: Message) => msg\n\n/** @internal */\nexport class BroadcastChannelMock {\n\tonmessage?: (e: MessageEvent) => void\n\tconstructor(_name: string) {\n\t\t// noop\n\t}\n\tpostMessage(_msg: Message) {\n\t\t// noop\n\t}\n\tclose() {\n\t\t// noop\n\t}\n}\n\nconst BC = typeof BroadcastChannel === 'undefined' ? BroadcastChannelMock : BroadcastChannel\n\n/** @internal */\nexport class TLLocalSyncClient {\n\tprivate disposables = new Set<() => void>()\n\tprivate diffQueue: Array<RecordsDiff<UnknownRecord> | typeof UPDATE_INSTANCE_STATE> = []\n\tprivate didDispose = false\n\tprivate didLoad = false\n\tprivate shouldDoFullDBWrite = true\n\tprivate isReloading = false\n\treadonly persistenceKey: string\n\treadonly sessionId: string\n\treadonly serializedSchema: SerializedSchema\n\tprivate isDebugging = false\n\tprivate readonly documentTypes: ReadonlySet<string>\n\tprivate readonly $sessionStateSnapshot: Signal<TLSessionStateSnapshot | null>\n\t/** @internal */\n\treadonly db: LocalIndexedDb\n\n\tinitTime = Date.now()\n\tprivate debug(...args: any[]) {\n\t\tif (this.isDebugging) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.debug(...args)\n\t\t}\n\t}\n\tconstructor(\n\t\tpublic readonly store: TLStore,\n\t\t{\n\t\t\tpersistenceKey,\n\t\t\tsessionId = TAB_ID,\n\t\t\tonLoad,\n\t\t\tonLoadError,\n\t\t}: {\n\t\t\tpersistenceKey: string\n\t\t\tsessionId?: string\n\t\t\tonLoad(self: TLLocalSyncClient): void\n\t\t\tonLoadError(error: Error): void\n\t\t},\n\t\tpublic readonly channel = new BC(`tldraw-tab-sync-${persistenceKey}`)\n\t) {\n\t\tif (typeof window !== 'undefined') {\n\t\t\t;(window as any).tlsync = this\n\t\t}\n\t\tthis.persistenceKey = persistenceKey\n\t\tthis.sessionId = sessionId\n\t\tthis.db = new LocalIndexedDb(persistenceKey)\n\n\t\tthis.serializedSchema = this.store.schema.serialize()\n\t\tthis.$sessionStateSnapshot = createSessionStateSnapshotSignal(this.store)\n\n\t\tthis.disposables.add(\n\t\t\t// Set up a subscription to changes from the store: When\n\t\t\t// the store changes (and if the change was made by the user)\n\t\t\t// then immediately send the diff to other tabs via postMessage\n\t\t\t// and schedule a persist.\n\t\t\tstore.listen(\n\t\t\t\t({ changes }) => {\n\t\t\t\t\tthis.diffQueue.push(changes)\n\t\t\t\t\tthis.channel.postMessage(\n\t\t\t\t\t\tmsg({\n\t\t\t\t\t\t\ttype: 'diff',\n\t\t\t\t\t\t\tstoreId: this.store.id,\n\t\t\t\t\t\t\tchanges,\n\t\t\t\t\t\t\tschema: this.serializedSchema,\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t\tthis.schedulePersist()\n\t\t\t\t},\n\t\t\t\t{ source: 'user', scope: 'document' }\n\t\t\t)\n\t\t)\n\t\tthis.disposables.add(\n\t\t\tstore.listen(\n\t\t\t\t() => {\n\t\t\t\t\tthis.diffQueue.push(UPDATE_INSTANCE_STATE)\n\t\t\t\t\tthis.schedulePersist()\n\t\t\t\t},\n\t\t\t\t{ scope: 'session' }\n\t\t\t)\n\t\t)\n\n\t\tif (typeof window !== 'undefined') {\n\t\t\t// Persists are throttled, so without this the last PERSIST_THROTTLE_MS of edits are lost\n\t\t\t// whenever the tab is closed or reloaded. `pagehide` is the last reliable event before\n\t\t\t// unload on desktop; on mobile the page can be discarded without it firing, so we also\n\t\t\t// flush when the tab is hidden.\n\t\t\tconst flush = () => {\n\t\t\t\t// Before the initial load completes a full write would overwrite the saved\n\t\t\t\t// document with an empty store.\n\t\t\t\tif (!this.didLoad) return\n\t\t\t\tthis.persistIfNeeded()\n\t\t\t}\n\t\t\tconst onVisibilityChange = () => {\n\t\t\t\tif (document.visibilityState === 'hidden') flush()\n\t\t\t}\n\t\t\twindow.addEventListener('pagehide', flush)\n\t\t\tdocument.addEventListener('visibilitychange', onVisibilityChange)\n\t\t\tthis.disposables.add(() => {\n\t\t\t\twindow.removeEventListener('pagehide', flush)\n\t\t\t\tdocument.removeEventListener('visibilitychange', onVisibilityChange)\n\t\t\t})\n\t\t}\n\n\t\tthis.connect(onLoad, onLoadError)\n\n\t\tthis.documentTypes = new Set(\n\t\t\tObject.values(this.store.schema.types)\n\t\t\t\t.filter((t) => t.scope === 'document')\n\t\t\t\t.map((t) => t.typeName)\n\t\t)\n\t}\n\n\tprivate async connect(onLoad: (client: this) => void, onLoadError: (error: Error) => void) {\n\t\tthis.debug('connecting')\n\t\tlet data: UnpackPromise<ReturnType<LocalIndexedDb['load']>> | undefined\n\n\t\tconst handleMessage = (msg: Message) => {\n\t\t\t// if their schema is earlier than ours, we need to tell them so they can refresh\n\t\t\t// if their schema is later than ours, we need to refresh\n\t\t\tconst res = this.store.schema.getMigrationsSince(msg.schema)\n\n\t\t\tif (!res.ok) {\n\t\t\t\tthis.isReloading = true\n\t\t\t\t// we are older, refresh\n\t\t\t\t// but add a safety check to make sure we don't get in an infinite loop\n\t\t\t\tconst timeSinceInit = Date.now() - this.initTime\n\t\t\t\tif (timeSinceInit < 5000) {\n\t\t\t\t\t// This tab was just reloaded, but is out of date compared to other tabs.\n\t\t\t\t\t// Not expecting this to ever happen. It should only happen if we roll back a release that incremented\n\t\t\t\t\t// the schema version (which we should never do)\n\t\t\t\t\t// Or maybe during development if you have multiple local tabs open running the app on prod mode and you\n\t\t\t\t\t// check out an older commit. Dev server should be fine.\n\t\t\t\t\tonLoadError(new Error('Schema mismatch, please close other tabs and reload the page'))\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tthis.debug('reloading')\n\t\t\t\tif (typeof window !== 'undefined') refreshPage()\n\t\t\t\treturn false\n\t\t\t} else if (res.value.length > 0) {\n\t\t\t\t// they are older, tell them to refresh and not write any more data\n\t\t\t\tthis.debug('telling them to reload')\n\t\t\t\tthis.channel.postMessage({ type: 'announce', schema: this.serializedSchema })\n\t\t\t\t// schedule a full db write in case they wrote data anyway\n\t\t\t\tthis.shouldDoFullDBWrite = true\n\t\t\t\tthis.schedulePersist()\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// otherwise, all good, same version :)\n\t\t\tif (msg.type === 'diff') {\n\t\t\t\tthis.debug('applying diff')\n\t\t\t\ttransact(() => {\n\t\t\t\t\tthis.store.mergeRemoteChanges(() => {\n\t\t\t\t\t\tthis.store.applyDiff(msg.changes as any)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\t// Listen from the start and buffer until we've loaded: diffs other tabs broadcast while\n\t\t// we're still reading from IndexedDB would otherwise be dropped, then erased by our first\n\t\t// (full) db write.\n\t\tlet bufferedMessages: Message[] | null = []\n\t\tthis.channel.onmessage = ({ data }) => {\n\t\t\tthis.debug('got message', data)\n\t\t\tif (bufferedMessages) {\n\t\t\t\tbufferedMessages.push(data as Message)\n\t\t\t} else {\n\t\t\t\thandleMessage(data as Message)\n\t\t\t}\n\t\t}\n\t\tthis.disposables.add(() => {\n\t\t\tthis.channel.close()\n\t\t})\n\n\t\ttry {\n\t\t\tdata = await this.db.load({ sessionId: this.sessionId })\n\t\t} catch (error: any) {\n\t\t\tonLoadError(error)\n\t\t\tshowCantReadFromIndexDbAlert()\n\t\t\treturn\n\t\t}\n\n\t\tthis.debug('loaded data from store', data, 'didDispose', this.didDispose)\n\t\tif (this.didDispose) return\n\n\t\ttry {\n\t\t\tif (data) {\n\t\t\t\tconst documentSnapshot = Object.fromEntries(data.records.map((r) => [r.id, r]))\n\t\t\t\tconst sessionStateSnapshot =\n\t\t\t\t\tdata.sessionStateSnapshot ?? extractSessionStateFromLegacySnapshot(documentSnapshot)\n\t\t\t\tconst migrationResult = this.store.schema.migrateStoreSnapshot({\n\t\t\t\t\tstore: documentSnapshot,\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\tschema: data.schema ?? this.store.schema.serializeEarliestVersion(),\n\t\t\t\t})\n\n\t\t\t\tif (migrationResult.type === 'error') {\n\t\t\t\t\tconsole.error('failed to migrate store', migrationResult)\n\t\t\t\t\tonLoadError(new Error(`Failed to migrate store: ${migrationResult.reason}`))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst records = Object.values(migrationResult.value).filter((r) =>\n\t\t\t\t\tthis.documentTypes.has(r.typeName)\n\t\t\t\t)\n\t\t\t\tif (records.length > 0) {\n\t\t\t\t\t// 3. Merge the changes into the REAL STORE\n\t\t\t\t\tthis.store.mergeRemoteChanges(() => {\n\t\t\t\t\t\t// Calling put will validate the records!\n\t\t\t\t\t\tthis.store.put(records, 'initialize')\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tif (sessionStateSnapshot) {\n\t\t\t\t\tloadSessionStateSnapshotIntoStore(this.store, sessionStateSnapshot, {\n\t\t\t\t\t\tforceOverwrite: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Older-schema announcements schedule writes, so drain every diff before those writes\n\t\t\t// or an onLoad callback that immediately closes the client can capture a snapshot.\n\t\t\tconst messages = bufferedMessages\n\t\t\tbufferedMessages = null\n\t\t\tfor (const message of messages) {\n\t\t\t\tif (!handleMessage(message)) return\n\t\t\t}\n\t\t\tthis.didLoad = true\n\t\t\tif (this.diffQueue.length > 0) this.schedulePersist()\n\n\t\t\tthis.channel.postMessage({ type: 'announce', schema: this.serializedSchema })\n\t\t\tonLoad(this)\n\n\t\t\t// Session state rows accumulate one per tab, so trim them on load. Pruning is best-effort\n\t\t\t// and must never turn a successful load into a failure.\n\t\t\tthis.db.pruneSessions({ keepSessionId: this.sessionId }).catch((e: unknown) => {\n\t\t\t\tthis.debug('failed to prune session state rows', e)\n\t\t\t})\n\t\t} catch (e: any) {\n\t\t\tthis.debug('error loading data from store', e)\n\t\t\tif (this.didDispose) return\n\t\t\tonLoadError(e)\n\t\t\treturn\n\t\t}\n\t}\n\n\tclose() {\n\t\tif (this.didDispose) return\n\t\tthis.debug('closing')\n\t\tthis.didDispose = true\n\t\t// Store listeners normally run on the next frame; collect the last edits before removal.\n\t\tthis.store._flushHistory()\n\t\tthis.disposables.forEach((d) => d())\n\t\tif (this.scheduledPersistTimeout) {\n\t\t\tclearTimeout(this.scheduledPersistTimeout)\n\t\t\tthis.scheduledPersistTimeout = null\n\t\t}\n\t\tif (typeof window !== 'undefined' && (window as any).tlsync === this) {\n\t\t\tdelete (window as any).tlsync\n\t\t}\n\t\tthis.flushAndCloseDb()\n\t}\n\n\t/**\n\t * Flush queued changes so edits made in the last PERSIST_THROTTLE_MS before unmount aren't lost,\n\t * then close the db. Never flushes before load (a full write then would wipe the db with an empty\n\t * store), and only when something is queued: shouldDoFullDBWrite stays true until the first\n\t * persist, so an unconditional flush would rewrite the whole document on every no-op close.\n\t */\n\tprivate flushAndCloseDb() {\n\t\t// A persist in flight can't be joined (persistIfNeeded bails while one is running) and,\n\t\t// now that we're disposed, won't schedule a follow-up. Edits queued during that write\n\t\t// would be lost if the db closed now, so wait for it and flush again.\n\t\tif (this.persistPromise) {\n\t\t\tthis.persistPromise.then(() => this.flushAndCloseDb())\n\t\t\treturn\n\t\t}\n\t\tif (this.didLoad && this.diffQueue.length > 0) this.persistIfNeeded()\n\t\t// the db waits for the transaction the flush just opened before actually closing\n\t\tthis.db.close()\n\t}\n\n\tprivate isPersisting = false\n\tprivate persistPromise: Promise<void> | null = null\n\tprivate didLastWriteError = false\n\t// eslint-disable-next-line no-restricted-globals\n\tprivate scheduledPersistTimeout: ReturnType<typeof setTimeout> | null = null\n\n\t/**\n\t * Schedule a persist. Persists don't happen immediately: they are throttled to avoid writing too\n\t * often, and will retry if failed.\n\t *\n\t * @internal\n\t */\n\tprivate schedulePersist() {\n\t\tthis.debug('schedulePersist', this.scheduledPersistTimeout)\n\t\tif (this.scheduledPersistTimeout) return\n\t\t// A deferred persist would try to write to a database that is closing or already closed.\n\t\tif (this.didDispose) return\n\t\t// eslint-disable-next-line no-restricted-globals\n\t\tthis.scheduledPersistTimeout = setTimeout(\n\t\t\t() => {\n\t\t\t\tthis.scheduledPersistTimeout = null\n\t\t\t\tthis.persistIfNeeded()\n\t\t\t},\n\t\t\tthis.didLastWriteError ? PERSIST_RETRY_THROTTLE_MS : PERSIST_THROTTLE_MS\n\t\t)\n\t}\n\n\t/**\n\t * Persist to IndexedDB only under certain circumstances:\n\t *\n\t * - If we're not already persisting\n\t * - If we're not reloading the page\n\t * - And we have something to persist (a full db write scheduled or changes in the diff queue)\n\t *\n\t * @internal\n\t */\n\tprivate persistIfNeeded() {\n\t\tthis.debug('persistIfNeeded', {\n\t\t\tisPersisting: this.isPersisting,\n\t\t\tisReloading: this.isReloading,\n\t\t\tshouldDoFullDBWrite: this.shouldDoFullDBWrite,\n\t\t\tdiffQueueLength: this.diffQueue.length,\n\t\t\tstoreIsPossiblyCorrupt: this.store.isPossiblyCorrupted(),\n\t\t})\n\n\t\t// if we've scheduled a persist for the future, that's no longer needed\n\t\tif (this.scheduledPersistTimeout) {\n\t\t\tclearTimeout(this.scheduledPersistTimeout)\n\t\t\tthis.scheduledPersistTimeout = null\n\t\t}\n\n\t\tif (!this.didLoad) return\n\n\t\t// if a persist is already in progress, we don't need to do anything -\n\t\t// if there are still outstanding changes once it's finished, it'll\n\t\t// schedule another persist\n\t\tif (this.isPersisting) return\n\n\t\t// if we're reloading the page, it's because there's a newer client\n\t\t// present so lets not overwrite their changes\n\t\tif (this.isReloading) return\n\n\t\t// if the store is possibly corrupted, we don't want to persist\n\t\tif (this.store.isPossiblyCorrupted()) return\n\n\t\t// if we're scheduled for a full write or if we have changes outstanding, let's persist them!\n\t\tif (this.shouldDoFullDBWrite || this.diffQueue.length > 0) {\n\t\t\tthis.persistPromise = this.doPersist()\n\t\t}\n\t}\n\n\t/**\n\t * Actually persist to IndexedDB. If the write fails, then we'll retry with a full db write after\n\t * a short delay.\n\t */\n\tprivate async doPersist() {\n\t\tassert(!this.isPersisting, 'persist already in progress')\n\t\tthis.isPersisting = true\n\n\t\tthis.debug('doPersist start')\n\n\t\t// instantly empty the diff queue, but keep our own copy of it. this way\n\t\t// diffs that come in during the persist will still get tracked\n\t\tconst diffQueue = this.diffQueue\n\t\tthis.diffQueue = []\n\n\t\ttry {\n\t\t\tif (this.shouldDoFullDBWrite) {\n\t\t\t\tthis.shouldDoFullDBWrite = false\n\t\t\t\tawait this.db.storeSnapshot({\n\t\t\t\t\tschema: this.store.schema,\n\t\t\t\t\tsnapshot: this.store.serialize(),\n\t\t\t\t\tsessionId: this.sessionId,\n\t\t\t\t\tsessionStateSnapshot: this.$sessionStateSnapshot.get(),\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tconst diffs = squashRecordDiffs(\n\t\t\t\t\tdiffQueue.filter((d): d is RecordsDiff<UnknownRecord> => d !== UPDATE_INSTANCE_STATE)\n\t\t\t\t)\n\t\t\t\tawait this.db.storeChanges({\n\t\t\t\t\tchanges: diffs,\n\t\t\t\t\tschema: this.store.schema,\n\t\t\t\t\tsessionId: this.sessionId,\n\t\t\t\t\tsessionStateSnapshot: this.$sessionStateSnapshot.get(),\n\t\t\t\t})\n\t\t\t}\n\t\t\tthis.didLastWriteError = false\n\t\t} catch (e) {\n\t\t\t// set this.shouldDoFullDBWrite because we clear the diffQueue no matter what,\n\t\t\t// so if this is just a temporary error, we will still persist all changes\n\t\t\tthis.shouldDoFullDBWrite = true\n\t\t\tthis.didLastWriteError = true\n\t\t\tconsole.error('failed to store changes in indexed db', e)\n\n\t\t\tif (!this.didDispose && typeof window !== 'undefined') {\n\t\t\t\tshowCantWriteToIndexDbAlert()\n\t\t\t\trefreshPage()\n\t\t\t}\n\t\t}\n\n\t\tthis.isPersisting = false\n\t\tthis.persistPromise = null\n\t\tthis.debug('doPersist end')\n\n\t\t// changes might have come in between when we started the persist and\n\t\t// now. we request another persist so any new changes can get written\n\t\tthis.schedulePersist()\n\t}\n}\n"],
5
- "mappings": "AAAA,SAAiB,gBAAgB;AACjC,SAAuD,yBAAyB;AAEhF,SAAS,cAAc;AACvB;AAAA,EACC;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,mBAAmB;AAC5B,SAAS,8BAA8B,mCAAmC;AAC1E,SAAS,sBAAsB;AAG/B,MAAM,sBAAsB;AAE5B,MAAM,4BAA4B;AAElC,MAAM,wBAAwB,uBAAO,uBAAuB;AA4B5D,MAAM,MAAM,CAACA,SAAiBA;AAGvB,MAAM,qBAAqB;AAAA,EACjC;AAAA,EACA,YAAY,OAAe;AAAA,EAE3B;AAAA,EACA,YAAY,MAAe;AAAA,EAE3B;AAAA,EACA,QAAQ;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nknownRecord, squashRecordDiffs } from '@tldraw/store'\nimport { TLStore } from '@tldraw/tlschema'\nimport { assert, noop } from '@tldraw/utils'\nimport {\n\tTAB_ID,\n\tTLSessionStateSnapshot,\n\tcreateSessionStateSnapshotSignal,\n\textractSessionStateFromLegacySnapshot,\n\tloadSessionStateSnapshotIntoStore,\n} from '../../config/TLSessionStateSnapshot'\nimport { refreshPage } from '../runtime'\nimport { showCantReadFromIndexDbAlert, showCantWriteToIndexDbAlert } from './alerts'\nimport { LocalIndexedDb } from './LocalIndexedDb'\n\n/** How should we debounce persists? */\nconst PERSIST_THROTTLE_MS = 350\n/** If we're in an error state, how long should we wait before retrying a write? */\nconst PERSIST_RETRY_THROTTLE_MS = 10_000\n\nconst UPDATE_INSTANCE_STATE = Symbol('UPDATE_INSTANCE_STATE')\n\n/**\n * IMPORTANT!!!\n *\n * This is just a quick-n-dirty temporary solution that will be replaced with the remote sync client\n * once it has the db integrated\n */\n\ninterface SyncMessage {\n\ttype: 'diff'\n\tstoreId: string\n\tchanges: RecordsDiff<UnknownRecord>\n\tschema: SerializedSchema\n}\n\n// Sent by new clients when they connect\n// If another client is on the channel with a newer schema version\n// It will\ninterface AnnounceMessage {\n\ttype: 'announce'\n\tschema: SerializedSchema\n}\n\ntype Message = SyncMessage | AnnounceMessage\n\ntype UnpackPromise<T> = T extends Promise<infer U> ? U : T\n\nconst msg = (msg: Message) => msg\n\n/** @internal */\nexport class BroadcastChannelMock {\n\tonmessage?: (e: MessageEvent) => void\n\tconstructor(_name: string) {\n\t\t// noop\n\t}\n\tpostMessage(_msg: Message) {\n\t\t// noop\n\t}\n\tclose() {\n\t\t// noop\n\t}\n}\n\nconst BC = typeof BroadcastChannel === 'undefined' ? BroadcastChannelMock : BroadcastChannel\n\n// Flushes still running for closed clients, by key. See connect() and close().\nconst pendingFlushes = new Map<string, Promise<void>>()\n\n/** @internal */\nexport class TLLocalSyncClient {\n\tprivate disposables = new Set<() => void>()\n\tprivate diffQueue: Array<RecordsDiff<UnknownRecord> | typeof UPDATE_INSTANCE_STATE> = []\n\tprivate didDispose = false\n\tprivate didLoad = false\n\tprivate shouldDoFullDBWrite = true\n\tprivate isReloading = false\n\treadonly persistenceKey: string\n\treadonly sessionId: string\n\treadonly serializedSchema: SerializedSchema\n\tprivate isDebugging = false\n\tprivate readonly documentTypes: ReadonlySet<string>\n\tprivate readonly $sessionStateSnapshot: Signal<TLSessionStateSnapshot | null>\n\t/** @internal */\n\treadonly db: LocalIndexedDb\n\n\tinitTime = Date.now()\n\tprivate debug(...args: any[]) {\n\t\tif (this.isDebugging) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.debug(...args)\n\t\t}\n\t}\n\tconstructor(\n\t\tpublic readonly store: TLStore,\n\t\t{\n\t\t\tpersistenceKey,\n\t\t\tsessionId = TAB_ID,\n\t\t\tonLoad,\n\t\t\tonLoadError,\n\t\t}: {\n\t\t\tpersistenceKey: string\n\t\t\tsessionId?: string\n\t\t\tonLoad(self: TLLocalSyncClient): void\n\t\t\tonLoadError(error: Error): void\n\t\t},\n\t\tpublic readonly channel = new BC(`tldraw-tab-sync-${persistenceKey}`)\n\t) {\n\t\tif (typeof window !== 'undefined') {\n\t\t\t;(window as any).tlsync = this\n\t\t}\n\t\tthis.persistenceKey = persistenceKey\n\t\tthis.sessionId = sessionId\n\t\tthis.db = new LocalIndexedDb(persistenceKey)\n\n\t\tthis.serializedSchema = this.store.schema.serialize()\n\t\tthis.$sessionStateSnapshot = createSessionStateSnapshotSignal(this.store)\n\n\t\tthis.disposables.add(\n\t\t\t// Set up a subscription to changes from the store: When\n\t\t\t// the store changes (and if the change was made by the user)\n\t\t\t// then immediately send the diff to other tabs via postMessage\n\t\t\t// and schedule a persist.\n\t\t\tstore.listen(\n\t\t\t\t({ changes }) => {\n\t\t\t\t\tthis.diffQueue.push(changes)\n\t\t\t\t\tthis.channel.postMessage(\n\t\t\t\t\t\tmsg({\n\t\t\t\t\t\t\ttype: 'diff',\n\t\t\t\t\t\t\tstoreId: this.store.id,\n\t\t\t\t\t\t\tchanges,\n\t\t\t\t\t\t\tschema: this.serializedSchema,\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t\tthis.schedulePersist()\n\t\t\t\t},\n\t\t\t\t{ source: 'user', scope: 'document' }\n\t\t\t)\n\t\t)\n\t\tthis.disposables.add(\n\t\t\tstore.listen(\n\t\t\t\t() => {\n\t\t\t\t\tthis.diffQueue.push(UPDATE_INSTANCE_STATE)\n\t\t\t\t\tthis.schedulePersist()\n\t\t\t\t},\n\t\t\t\t{ scope: 'session' }\n\t\t\t)\n\t\t)\n\n\t\tif (typeof window !== 'undefined') {\n\t\t\t// Persists are throttled, so without this the last PERSIST_THROTTLE_MS of edits are lost\n\t\t\t// whenever the tab is closed or reloaded. `pagehide` is the last reliable event before\n\t\t\t// unload on desktop; on mobile the page can be discarded without it firing, so we also\n\t\t\t// flush when the tab is hidden.\n\t\t\tconst flush = () => {\n\t\t\t\t// Before the initial load completes a full write would overwrite the saved\n\t\t\t\t// document with an empty store.\n\t\t\t\tif (!this.didLoad) return\n\t\t\t\tthis.persistIfNeeded()\n\t\t\t}\n\t\t\tconst onVisibilityChange = () => {\n\t\t\t\tif (document.visibilityState === 'hidden') flush()\n\t\t\t}\n\t\t\twindow.addEventListener('pagehide', flush)\n\t\t\tdocument.addEventListener('visibilitychange', onVisibilityChange)\n\t\t\tthis.disposables.add(() => {\n\t\t\t\twindow.removeEventListener('pagehide', flush)\n\t\t\t\tdocument.removeEventListener('visibilitychange', onVisibilityChange)\n\t\t\t})\n\t\t}\n\n\t\tthis.connect(onLoad, onLoadError)\n\n\t\tthis.documentTypes = new Set(\n\t\t\tObject.values(this.store.schema.types)\n\t\t\t\t.filter((t) => t.scope === 'document')\n\t\t\t\t.map((t) => t.typeName)\n\t\t)\n\t}\n\n\tprivate async connect(onLoad: (client: this) => void, onLoadError: (error: Error) => void) {\n\t\tthis.debug('connecting')\n\t\tlet data: UnpackPromise<ReturnType<LocalIndexedDb['load']>> | undefined\n\n\t\tconst handleMessage = (msg: Message) => {\n\t\t\t// if their schema is earlier than ours, we need to tell them so they can refresh\n\t\t\t// if their schema is later than ours, we need to refresh\n\t\t\tconst res = this.store.schema.getMigrationsSince(msg.schema)\n\n\t\t\tif (!res.ok) {\n\t\t\t\tthis.isReloading = true\n\t\t\t\t// we are older, refresh\n\t\t\t\t// but add a safety check to make sure we don't get in an infinite loop\n\t\t\t\tconst timeSinceInit = Date.now() - this.initTime\n\t\t\t\tif (timeSinceInit < 5000) {\n\t\t\t\t\t// This tab was just reloaded, but is out of date compared to other tabs.\n\t\t\t\t\t// Not expecting this to ever happen. It should only happen if we roll back a release that incremented\n\t\t\t\t\t// the schema version (which we should never do)\n\t\t\t\t\t// Or maybe during development if you have multiple local tabs open running the app on prod mode and you\n\t\t\t\t\t// check out an older commit. Dev server should be fine.\n\t\t\t\t\tonLoadError(new Error('Schema mismatch, please close other tabs and reload the page'))\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tthis.debug('reloading')\n\t\t\t\tif (typeof window !== 'undefined') refreshPage()\n\t\t\t\treturn false\n\t\t\t} else if (res.value.length > 0) {\n\t\t\t\t// they are older, tell them to refresh and not write any more data\n\t\t\t\tthis.debug('telling them to reload')\n\t\t\t\tthis.channel.postMessage({ type: 'announce', schema: this.serializedSchema })\n\t\t\t\t// schedule a full db write in case they wrote data anyway\n\t\t\t\tthis.shouldDoFullDBWrite = true\n\t\t\t\tthis.schedulePersist()\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// otherwise, all good, same version :)\n\t\t\tif (msg.type === 'diff') {\n\t\t\t\tthis.debug('applying diff')\n\t\t\t\ttransact(() => {\n\t\t\t\t\tthis.store.mergeRemoteChanges(() => {\n\t\t\t\t\t\tthis.store.applyDiff(msg.changes as any)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\t// Listen from the start and buffer until we've loaded: diffs other tabs broadcast while\n\t\t// we're still reading from IndexedDB would otherwise be dropped, then erased by our first\n\t\t// (full) db write.\n\t\tlet bufferedMessages: Message[] | null = []\n\t\tthis.channel.onmessage = ({ data }) => {\n\t\t\tthis.debug('got message', data)\n\t\t\tif (bufferedMessages) {\n\t\t\t\tbufferedMessages.push(data as Message)\n\t\t\t} else {\n\t\t\t\thandleMessage(data as Message)\n\t\t\t}\n\t\t}\n\t\tthis.disposables.add(() => {\n\t\t\tthis.channel.close()\n\t\t})\n\n\t\t// our first write is a full snapshot, so it would erase whatever a client that just closed\n\t\t// on this key is still flushing\n\t\tawait pendingFlushes.get(this.persistenceKey)\n\t\tif (this.didDispose) return\n\n\t\ttry {\n\t\t\tdata = await this.db.load({ sessionId: this.sessionId })\n\t\t} catch (error: any) {\n\t\t\tonLoadError(error)\n\t\t\tshowCantReadFromIndexDbAlert()\n\t\t\treturn\n\t\t}\n\n\t\tthis.debug('loaded data from store', data, 'didDispose', this.didDispose)\n\t\tif (this.didDispose) return\n\n\t\ttry {\n\t\t\tif (data) {\n\t\t\t\tconst documentSnapshot = Object.fromEntries(data.records.map((r) => [r.id, r]))\n\t\t\t\tconst sessionStateSnapshot =\n\t\t\t\t\tdata.sessionStateSnapshot ?? extractSessionStateFromLegacySnapshot(documentSnapshot)\n\t\t\t\tconst migrationResult = this.store.schema.migrateStoreSnapshot({\n\t\t\t\t\tstore: documentSnapshot,\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\tschema: data.schema ?? this.store.schema.serializeEarliestVersion(),\n\t\t\t\t})\n\n\t\t\t\tif (migrationResult.type === 'error') {\n\t\t\t\t\tconsole.error('failed to migrate store', migrationResult)\n\t\t\t\t\tonLoadError(new Error(`Failed to migrate store: ${migrationResult.reason}`))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst records = Object.values(migrationResult.value).filter((r) =>\n\t\t\t\t\tthis.documentTypes.has(r.typeName)\n\t\t\t\t)\n\t\t\t\tif (records.length > 0) {\n\t\t\t\t\t// 3. Merge the changes into the REAL STORE\n\t\t\t\t\tthis.store.mergeRemoteChanges(() => {\n\t\t\t\t\t\t// Calling put will validate the records!\n\t\t\t\t\t\tthis.store.put(records, 'initialize')\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tif (sessionStateSnapshot) {\n\t\t\t\t\tloadSessionStateSnapshotIntoStore(this.store, sessionStateSnapshot, {\n\t\t\t\t\t\tforceOverwrite: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Older-schema announcements schedule writes, so drain every diff before those writes\n\t\t\t// or an onLoad callback that immediately closes the client can capture a snapshot.\n\t\t\tconst messages = bufferedMessages\n\t\t\tbufferedMessages = null\n\t\t\tfor (const message of messages) {\n\t\t\t\tif (!handleMessage(message)) return\n\t\t\t}\n\t\t\tthis.didLoad = true\n\t\t\tif (this.diffQueue.length > 0) this.schedulePersist()\n\n\t\t\tthis.channel.postMessage({ type: 'announce', schema: this.serializedSchema })\n\t\t\tonLoad(this)\n\n\t\t\t// Session state rows accumulate one per tab, so trim them on load. Pruning is best-effort\n\t\t\t// and must never turn a successful load into a failure.\n\t\t\tthis.db.pruneSessions({ keepSessionId: this.sessionId }).catch((e: unknown) => {\n\t\t\t\tthis.debug('failed to prune session state rows', e)\n\t\t\t})\n\t\t} catch (e: any) {\n\t\t\tthis.debug('error loading data from store', e)\n\t\t\tif (this.didDispose) return\n\t\t\tonLoadError(e)\n\t\t\treturn\n\t\t}\n\t}\n\n\tclose() {\n\t\tif (this.didDispose) return\n\t\tthis.debug('closing')\n\t\tthis.didDispose = true\n\t\tthis.disposables.forEach((d) => d())\n\t\tif (this.scheduledPersistTimeout) {\n\t\t\tclearTimeout(this.scheduledPersistTimeout)\n\t\t\tthis.scheduledPersistTimeout = null\n\t\t}\n\t\tif (typeof window !== 'undefined' && (window as any).tlsync === this) {\n\t\t\tdelete (window as any).tlsync\n\t\t}\n\t\t// flush now when the key is idle: close() runs during teardown, where a deferred write may\n\t\t// never run. wait when it isn't, or our snapshot lands first and gets overwritten.\n\t\t// connect() awaits this, so it must never reject\n\t\tconst previous = pendingFlushes.get(this.persistenceKey)\n\t\tconst flush = (previous ? previous.then(() => this.flushAndCloseDb()) : this.flushAndCloseDb())\n\t\t\t.catch(noop)\n\t\t\t.then(() => {\n\t\t\t\tif (pendingFlushes.get(this.persistenceKey) === flush) {\n\t\t\t\t\tpendingFlushes.delete(this.persistenceKey)\n\t\t\t\t}\n\t\t\t})\n\t\tpendingFlushes.set(this.persistenceKey, flush)\n\t}\n\n\t/**\n\t * Flush queued changes so edits made in the last PERSIST_THROTTLE_MS before unmount aren't lost,\n\t * then close the db. Never flushes before load (a full write then would wipe the db with an empty\n\t * store), and only when something is queued: shouldDoFullDBWrite stays true until the first\n\t * persist, so an unconditional flush would rewrite the whole document on every no-op close.\n\t */\n\tprivate flushAndCloseDb(): Promise<void> {\n\t\t// A persist in flight can't be joined (persistIfNeeded bails while one is running) and,\n\t\t// now that we're disposed, won't schedule a follow-up. Edits queued during that write\n\t\t// would be lost if the db closed now, so wait for it and flush again.\n\t\tif (this.persistPromise) {\n\t\t\treturn this.persistPromise.then(() => this.flushAndCloseDb())\n\t\t}\n\t\tif (this.didLoad && this.diffQueue.length > 0) this.persistIfNeeded()\n\t\t// the db waits for the transaction the flush just opened before actually closing\n\t\treturn this.db.close()\n\t}\n\n\tprivate isPersisting = false\n\tprivate persistPromise: Promise<void> | null = null\n\tprivate didLastWriteError = false\n\t// eslint-disable-next-line no-restricted-globals\n\tprivate scheduledPersistTimeout: ReturnType<typeof setTimeout> | null = null\n\n\t/**\n\t * Schedule a persist. Persists don't happen immediately: they are throttled to avoid writing too\n\t * often, and will retry if failed.\n\t *\n\t * @internal\n\t */\n\tprivate schedulePersist() {\n\t\tthis.debug('schedulePersist', this.scheduledPersistTimeout)\n\t\tif (this.scheduledPersistTimeout) return\n\t\t// A deferred persist would try to write to a database that is closing or already closed.\n\t\tif (this.didDispose) return\n\t\t// eslint-disable-next-line no-restricted-globals\n\t\tthis.scheduledPersistTimeout = setTimeout(\n\t\t\t() => {\n\t\t\t\tthis.scheduledPersistTimeout = null\n\t\t\t\tthis.persistIfNeeded()\n\t\t\t},\n\t\t\tthis.didLastWriteError ? PERSIST_RETRY_THROTTLE_MS : PERSIST_THROTTLE_MS\n\t\t)\n\t}\n\n\t/**\n\t * Persist to IndexedDB only under certain circumstances:\n\t *\n\t * - If we're not already persisting\n\t * - If we're not reloading the page\n\t * - And we have something to persist (a full db write scheduled or changes in the diff queue)\n\t *\n\t * @internal\n\t */\n\tprivate persistIfNeeded() {\n\t\tthis.debug('persistIfNeeded', {\n\t\t\tisPersisting: this.isPersisting,\n\t\t\tisReloading: this.isReloading,\n\t\t\tshouldDoFullDBWrite: this.shouldDoFullDBWrite,\n\t\t\tdiffQueueLength: this.diffQueue.length,\n\t\t\tstoreIsPossiblyCorrupt: this.store.isPossiblyCorrupted(),\n\t\t})\n\n\t\t// if we've scheduled a persist for the future, that's no longer needed\n\t\tif (this.scheduledPersistTimeout) {\n\t\t\tclearTimeout(this.scheduledPersistTimeout)\n\t\t\tthis.scheduledPersistTimeout = null\n\t\t}\n\n\t\tif (!this.didLoad) return\n\n\t\t// if a persist is already in progress, we don't need to do anything -\n\t\t// if there are still outstanding changes once it's finished, it'll\n\t\t// schedule another persist\n\t\tif (this.isPersisting) return\n\n\t\t// if we're reloading the page, it's because there's a newer client\n\t\t// present so lets not overwrite their changes\n\t\tif (this.isReloading) return\n\n\t\t// if the store is possibly corrupted, we don't want to persist\n\t\tif (this.store.isPossiblyCorrupted()) return\n\n\t\t// if we're scheduled for a full write or if we have changes outstanding, let's persist them!\n\t\tif (this.shouldDoFullDBWrite || this.diffQueue.length > 0) {\n\t\t\tthis.persistPromise = this.doPersist()\n\t\t}\n\t}\n\n\t/**\n\t * Actually persist to IndexedDB. If the write fails, then we'll retry with a full db write after\n\t * a short delay.\n\t */\n\tprivate async doPersist() {\n\t\tassert(!this.isPersisting, 'persist already in progress')\n\t\tthis.isPersisting = true\n\n\t\tthis.debug('doPersist start')\n\n\t\t// instantly empty the diff queue, but keep our own copy of it. this way\n\t\t// diffs that come in during the persist will still get tracked\n\t\tconst diffQueue = this.diffQueue\n\t\tthis.diffQueue = []\n\n\t\ttry {\n\t\t\tif (this.shouldDoFullDBWrite) {\n\t\t\t\tthis.shouldDoFullDBWrite = false\n\t\t\t\tawait this.db.storeSnapshot({\n\t\t\t\t\tschema: this.store.schema,\n\t\t\t\t\tsnapshot: this.store.serialize(),\n\t\t\t\t\tsessionId: this.sessionId,\n\t\t\t\t\tsessionStateSnapshot: this.$sessionStateSnapshot.get(),\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tconst diffs = squashRecordDiffs(\n\t\t\t\t\tdiffQueue.filter((d): d is RecordsDiff<UnknownRecord> => d !== UPDATE_INSTANCE_STATE)\n\t\t\t\t)\n\t\t\t\tawait this.db.storeChanges({\n\t\t\t\t\tchanges: diffs,\n\t\t\t\t\tschema: this.store.schema,\n\t\t\t\t\tsessionId: this.sessionId,\n\t\t\t\t\tsessionStateSnapshot: this.$sessionStateSnapshot.get(),\n\t\t\t\t})\n\t\t\t}\n\t\t\tthis.didLastWriteError = false\n\t\t} catch (e) {\n\t\t\t// set this.shouldDoFullDBWrite because we clear the diffQueue no matter what,\n\t\t\t// so if this is just a temporary error, we will still persist all changes\n\t\t\tthis.shouldDoFullDBWrite = true\n\t\t\tthis.didLastWriteError = true\n\t\t\tconsole.error('failed to store changes in indexed db', e)\n\n\t\t\tif (!this.didDispose && typeof window !== 'undefined') {\n\t\t\t\tshowCantWriteToIndexDbAlert()\n\t\t\t\trefreshPage()\n\t\t\t}\n\t\t}\n\n\t\tthis.isPersisting = false\n\t\tthis.persistPromise = null\n\t\tthis.debug('doPersist end')\n\n\t\t// changes might have come in between when we started the persist and\n\t\t// now. we request another persist so any new changes can get written\n\t\tthis.schedulePersist()\n\t}\n}\n"],
5
+ "mappings": "AAAA,SAAiB,gB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,QAAQ,KAAK,MAAM;AAAA,UACnB,UAAU,KAAK,MAAM,UAAU;AAAA,UAC/B,WAAW,KAAK;AAAA,UAChB,sBAAsB,KAAK,sBAAsB,IAAI;AAAA,QACtD,CAAC;AAAA,MACF,OAAO;AACN,cAAM,QAAQ;AAAA,UACb,UAAU,OAAO,CAAC,MAAuC,MAAM,qBAAqB;AAAA,QACrF;AACA,cAAM,KAAK,GAAG,aAAa;AAAA,UAC1B,SAAS;AAAA,UACT,QAAQ,KAAK,MAAM;AAAA,UACnB,WAAW,KAAK;AAAA,UAChB,sBAAsB,KAAK,sBAAsB,IAAI;AAAA,QACtD,CAAC;AAAA,MACF;AACA,WAAK,oBAAoB;AAAA,IAC1B,SAAS,GAAG;AAGX,WAAK,sBAAsB;AAC3B,WAAK,oBAAoB;AACzB,cAAQ,MAAM,yCAAyC,CAAC;AAExD,UAAI,CAAC,KAAK,cAAc,OAAO,WAAW,aAAa;AACtD,oCAA4B;AAC5B,oBAAY;AAAA,MACb;AAAA,IACD;AAEA,SAAK,eAAe;AACpB,SAAK,iBAAiB;AACtB,SAAK,MAAM,eAAe;AAI1B,SAAK,gBAAgB;AAAA,EACtB;AACD;",
6
6
  "names": ["msg", "data"]
7
7
  }
@@ -1,8 +1,8 @@
1
- const version = "5.5.0";
1
+ const version = "5.6.0-canary.669b4c97f643";
2
2
  const publishDates = {
3
3
  major: "2026-05-06T16:28:18.473Z",
4
- minor: "2026-09-30T10:03:27.724Z",
5
- patch: "2026-09-30T10:03:27.724Z"
4
+ minor: "2026-09-30T12:35:27.842Z",
5
+ patch: "2026-09-30T12:35:27.842Z"
6
6
  };
7
7
  export {
8
8
  publishDates,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/version.ts"],
4
- "sourcesContent": ["// This file is automatically generated by internal/scripts/refresh-assets.ts.\n// Do not edit manually. Or do, I'm a comment, not a cop.\n\nexport const version = '5.5.0'\nexport const publishDates = {\n\tmajor: '2026-05-06T16:28:18.473Z',\n\tminor: '2026-09-30T10:03:27.724Z',\n\tpatch: '2026-09-30T10:03:27.724Z',\n}\n"],
4
+ "sourcesContent": ["// This file is automatically generated by internal/scripts/refresh-assets.ts.\n// Do not edit manually. Or do, I'm a comment, not a cop.\n\nexport const version = '5.6.0-canary.669b4c97f643'\nexport const publishDates = {\n\tmajor: '2026-05-06T16:28:18.473Z',\n\tminor: '2026-09-30T12:35:27.842Z',\n\tpatch: '2026-09-30T12:35:27.842Z',\n}\n"],
5
5
  "mappings": "AAGO,MAAM,UAAU;AAChB,MAAM,eAAe;AAAA,EAC3B,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AACR;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tldraw/editor",
3
3
  "description": "tldraw infinite canvas SDK (editor).",
4
- "version": "5.5.0",
4
+ "version": "5.6.0-canary.669b4c97f643",
5
5
  "author": {
6
6
  "name": "tldraw Inc.",
7
7
  "email": "hello@tldraw.com"
@@ -39,27 +39,16 @@
39
39
  "dist-cjs",
40
40
  "src"
41
41
  ],
42
- "scripts": {
43
- "test-ci": "yarn run -T vitest run --passWithNoTests",
44
- "test": "yarn run -T vitest --passWithNoTests",
45
- "test-coverage": "yarn run -T vitest run --coverage --passWithNoTests",
46
- "build": "yarn run -T tsx ../../internal/scripts/build-package.ts",
47
- "build-api": "yarn run -T tsx ../../internal/scripts/build-api.ts",
48
- "prepack": "yarn run -T tsx ../../internal/scripts/prepack.ts",
49
- "postpack": "../../internal/scripts/postpack.sh",
50
- "pack-tarball": "yarn pack",
51
- "lint": "yarn run -T tsx ../../internal/scripts/lint.ts"
52
- },
53
42
  "dependencies": {
54
43
  "@tiptap/core": "^3.12.1",
55
44
  "@tiptap/pm": "^3.12.1",
56
45
  "@tiptap/react": "^3.12.1",
57
- "@tldraw/state": "5.5.0",
58
- "@tldraw/state-react": "5.5.0",
59
- "@tldraw/store": "5.5.0",
60
- "@tldraw/tlschema": "5.5.0",
61
- "@tldraw/utils": "5.5.0",
62
- "@tldraw/validate": "5.5.0",
46
+ "@tldraw/state": "5.6.0-canary.669b4c97f643",
47
+ "@tldraw/state-react": "5.6.0-canary.669b4c97f643",
48
+ "@tldraw/store": "5.6.0-canary.669b4c97f643",
49
+ "@tldraw/tlschema": "5.6.0-canary.669b4c97f643",
50
+ "@tldraw/utils": "5.6.0-canary.669b4c97f643",
51
+ "@tldraw/validate": "5.6.0-canary.669b4c97f643",
63
52
  "classnames": "^2.5.1",
64
53
  "eventemitter3": "^4.0.7",
65
54
  "idb": "^7.1.1",
@@ -79,7 +68,6 @@
79
68
  "@types/react-dom": "^19.2.3",
80
69
  "@types/wicg-file-system-access": "^2020.9.8",
81
70
  "fake-indexeddb": "^4.0.2",
82
- "lazyrepo": "0.0.0-alpha.27",
83
71
  "react": "^19.2.1",
84
72
  "react-dom": "^19.2.1",
85
73
  "resize-observer-polyfill": "^1.5.1",
@@ -96,5 +84,15 @@
96
84
  "require": "./dist-cjs/index.js"
97
85
  },
98
86
  "./editor.css": "./editor.css"
87
+ },
88
+ "scripts": {
89
+ "test-ci": "pnpm exec vitest run --passWithNoTests",
90
+ "test": "pnpm exec vitest --passWithNoTests",
91
+ "test-coverage": "pnpm exec vitest run --coverage --passWithNoTests",
92
+ "build": "pnpm exec tsx ../../internal/scripts/build-package.ts",
93
+ "build-api": "pnpm exec tsx ../../internal/scripts/build-api.ts",
94
+ "pack-tarball": "pnpm pack",
95
+ "lint": "pnpm exec tsx ../../internal/scripts/lint.ts",
96
+ "build-types": "tsc --build"
99
97
  }
100
98
  }
@@ -137,6 +137,7 @@ import {
137
137
  areAnglesCompatible,
138
138
  clamp,
139
139
  pointInPolygon,
140
+ shortAngleDist,
140
141
  } from '../primitives/utils'
141
142
  import { Vec, VecLike } from '../primitives/Vec'
142
143
  import { areShapesContentEqual } from '../utils/areShapesContentEqual'
@@ -5122,7 +5123,11 @@ export class Editor extends EventEmitter<TLEventMap> {
5122
5123
  const freshPage = this.getPage(id) // get the most recent version of the page anyway
5123
5124
  if (!freshPage) return this
5124
5125
 
5125
- const prevCamera = { ...this.getCamera() }
5126
+ // Read the source page's own camera rather than getCamera(), which is the
5127
+ // current page's and is wrong when duplicating a page that isn't being viewed
5128
+ const prevCamera = {
5129
+ ...(this.store.get(CameraRecordType.createId(freshPage.id)) ?? this.getCamera()),
5130
+ }
5126
5131
  const content = this.getContentFromCurrentPage(this.getSortedChildIdsForParent(freshPage.id))
5127
5132
 
5128
5133
  this.run(() => {
@@ -5137,8 +5142,9 @@ export class Editor extends EventEmitter<TLEventMap> {
5137
5142
  this.setCamera(prevCamera)
5138
5143
 
5139
5144
  if (content) {
5140
- // If we had content on the previous page, put it on the new page
5141
- return this.putContentOntoCurrentPage(content)
5145
+ // Without preservePosition the paste rule recenters off-screen content
5146
+ // in the viewport, so the copy's layout would not match the original
5147
+ return this.putContentOntoCurrentPage(content, { preservePosition: true })
5142
5148
  }
5143
5149
  })
5144
5150
 
@@ -8313,6 +8319,9 @@ export class Editor extends EventEmitter<TLEventMap> {
8313
8319
  initialShape: TLShape
8314
8320
  isAspectRatioLocked: boolean
8315
8321
  initialPageTransform: MatLike
8322
+ dragHandle?: TLResizeHandle
8323
+ mode?: TLResizeMode
8324
+ skipStartAndEndCallbacks?: boolean
8316
8325
  }
8317
8326
  ) {
8318
8327
  const { type } = options.initialShape
@@ -8337,19 +8346,39 @@ export class Editor extends EventEmitter<TLEventMap> {
8337
8346
  initialBounds: options.initialBounds,
8338
8347
  isAspectRatioLocked: options.isAspectRatioLocked,
8339
8348
  initialPageTransform: options.initialPageTransform,
8349
+ dragHandle: options.dragHandle,
8350
+ mode: options.mode,
8351
+ // this is one frame of the same resize, not a new one, so don't fire start/end again
8352
+ skipStartAndEndCallbacks: options.skipStartAndEndCallbacks,
8340
8353
  })
8341
8354
 
8342
8355
  // then if the shape is flipped in one axis only, we need to apply an extra rotation
8343
8356
  // to make sure the shape is mirrored correctly
8344
8357
  if (Math.sign(scale.x) * Math.sign(scale.y) < 0) {
8345
- // We need to compute the new local rotation that will result in the negated page rotation.
8346
- // For a shape with local rotation `localRot` and parent page rotation `parentRot`:
8358
+ // Mirroring across an axis at angle `axisRot` maps a page rotation `pageRot` to
8359
+ // `2 * axisRot - pageRot`. For a shape with local rotation `localRot` whose parent had
8360
+ // page rotation `parentRot` when the resize began:
8347
8361
  // - pageRot = parentRot + localRot
8348
- // - newPageRot = -pageRot (we want to negate the page rotation)
8349
- // - newPageRot = parentRot + newLocalRot (parent hasn't changed)
8350
- // - Therefore: newLocalRot = -pageRot - parentRot = -(parentRot + localRot) - parentRot = -localRot - 2*parentRot
8362
+ // - newPageRot = 2 * axisRot - pageRot
8363
+ // - newPageRot = (parentRot + parentDelta) + newLocalRot
8364
+ // - Therefore: newLocalRot = 2 * axisRot - localRot - 2 * parentRot - parentDelta
8365
+ // `parentDelta` is how far the parent has rotated since the resize began. Nested resizes
8366
+ // commit ancestors before descendants, so an unaligned parent may itself have been
8367
+ // flipped by the time its child gets here; reading the parent's current rotation as if
8368
+ // it were the initial one would then double-count that flip.
8351
8369
  const parentRotation = this.getShapeParentTransform(id).rotation()
8352
- const rotation = -options.initialShape.rotation - 2 * parentRotation
8370
+ // take the shortest arc so the stored rotation doesn't drift by 2π when the parent
8371
+ // hasn't moved and the initial page rotation happens to be wrapped
8372
+ const parentDelta = shortAngleDist(
8373
+ Mat.Cast(options.initialPageTransform).rotation() - options.initialShape.rotation,
8374
+ parentRotation
8375
+ )
8376
+ const initialParentRotation = parentRotation - parentDelta
8377
+ const rotation =
8378
+ 2 * options.scaleAxisRotation -
8379
+ options.initialShape.rotation -
8380
+ 2 * initialParentRotation -
8381
+ parentDelta
8353
8382
  this.updateShapes([{ id, type, rotation }])
8354
8383
  }
8355
8384