@slate-yjs/core 0.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 (156) hide show
  1. package/dist/applyToSlate/index.d.ts +20 -0
  2. package/dist/applyToSlate/index.d.ts.map +1 -0
  3. package/dist/applyToSlate/index.js +32 -0
  4. package/dist/applyToSlate/index.js.map +1 -0
  5. package/dist/applyToSlate/textEvent.d.ts +4 -0
  6. package/dist/applyToSlate/textEvent.d.ts.map +1 -0
  7. package/dist/applyToSlate/textEvent.js +169 -0
  8. package/dist/applyToSlate/textEvent.js.map +1 -0
  9. package/dist/applyToYjs/index.d.ts +4 -0
  10. package/dist/applyToYjs/index.d.ts.map +1 -0
  11. package/dist/applyToYjs/index.js +17 -0
  12. package/dist/applyToYjs/index.js.map +1 -0
  13. package/dist/applyToYjs/node/index.d.ts +4 -0
  14. package/dist/applyToYjs/node/index.d.ts.map +1 -0
  15. package/dist/applyToYjs/node/index.js +15 -0
  16. package/dist/applyToYjs/node/index.js.map +1 -0
  17. package/dist/applyToYjs/node/insertNode.d.ts +4 -0
  18. package/dist/applyToYjs/node/insertNode.d.ts.map +1 -0
  19. package/dist/applyToYjs/node/insertNode.js +15 -0
  20. package/dist/applyToYjs/node/insertNode.js.map +1 -0
  21. package/dist/applyToYjs/node/mergeNode.d.ts +4 -0
  22. package/dist/applyToYjs/node/mergeNode.d.ts.map +1 -0
  23. package/dist/applyToYjs/node/mergeNode.js +35 -0
  24. package/dist/applyToYjs/node/mergeNode.js.map +1 -0
  25. package/dist/applyToYjs/node/moveNode.d.ts +4 -0
  26. package/dist/applyToYjs/node/moveNode.d.ts.map +1 -0
  27. package/dist/applyToYjs/node/moveNode.js +30 -0
  28. package/dist/applyToYjs/node/moveNode.js.map +1 -0
  29. package/dist/applyToYjs/node/removeNode.d.ts +4 -0
  30. package/dist/applyToYjs/node/removeNode.d.ts.map +1 -0
  31. package/dist/applyToYjs/node/removeNode.js +8 -0
  32. package/dist/applyToYjs/node/removeNode.js.map +1 -0
  33. package/dist/applyToYjs/node/setNode.d.ts +4 -0
  34. package/dist/applyToYjs/node/setNode.d.ts.map +1 -0
  35. package/dist/applyToYjs/node/setNode.js +23 -0
  36. package/dist/applyToYjs/node/setNode.js.map +1 -0
  37. package/dist/applyToYjs/node/splitNode.d.ts +4 -0
  38. package/dist/applyToYjs/node/splitNode.d.ts.map +1 -0
  39. package/dist/applyToYjs/node/splitNode.js +53 -0
  40. package/dist/applyToYjs/node/splitNode.js.map +1 -0
  41. package/dist/applyToYjs/text/index.d.ts +4 -0
  42. package/dist/applyToYjs/text/index.d.ts.map +1 -0
  43. package/dist/applyToYjs/text/index.js +7 -0
  44. package/dist/applyToYjs/text/index.js.map +1 -0
  45. package/dist/applyToYjs/text/insertText.d.ts +4 -0
  46. package/dist/applyToYjs/text/insertText.d.ts.map +1 -0
  47. package/dist/applyToYjs/text/insertText.js +14 -0
  48. package/dist/applyToYjs/text/insertText.js.map +1 -0
  49. package/dist/applyToYjs/text/removeText.d.ts +4 -0
  50. package/dist/applyToYjs/text/removeText.d.ts.map +1 -0
  51. package/dist/applyToYjs/text/removeText.js +8 -0
  52. package/dist/applyToYjs/text/removeText.js.map +1 -0
  53. package/dist/applyToYjs/types.d.ts +9 -0
  54. package/dist/applyToYjs/types.d.ts.map +1 -0
  55. package/dist/applyToYjs/types.js +2 -0
  56. package/dist/applyToYjs/types.js.map +1 -0
  57. package/dist/index.cjs +2 -0
  58. package/dist/index.cjs.map +1 -0
  59. package/dist/index.d.ts +4 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +16 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/index.modern.js +2 -0
  64. package/dist/index.modern.js.map +1 -0
  65. package/dist/index.module.js +2 -0
  66. package/dist/index.module.js.map +1 -0
  67. package/dist/index.umd.js +2 -0
  68. package/dist/index.umd.js.map +1 -0
  69. package/dist/model/types.d.ts +38 -0
  70. package/dist/model/types.d.ts.map +1 -0
  71. package/dist/model/types.js +2 -0
  72. package/dist/model/types.js.map +1 -0
  73. package/dist/plugins/index.d.ts +4 -0
  74. package/dist/plugins/index.d.ts.map +1 -0
  75. package/dist/plugins/index.js +4 -0
  76. package/dist/plugins/index.js.map +1 -0
  77. package/dist/plugins/withCursors.d.ts +37 -0
  78. package/dist/plugins/withCursors.d.ts.map +1 -0
  79. package/dist/plugins/withCursors.js +145 -0
  80. package/dist/plugins/withCursors.js.map +1 -0
  81. package/dist/plugins/withYHistory.d.ts +15 -0
  82. package/dist/plugins/withYHistory.d.ts.map +1 -0
  83. package/dist/plugins/withYHistory.js +66 -0
  84. package/dist/plugins/withYHistory.js.map +1 -0
  85. package/dist/plugins/withYjs.d.ts +40 -0
  86. package/dist/plugins/withYjs.d.ts.map +1 -0
  87. package/dist/plugins/withYjs.js +155 -0
  88. package/dist/plugins/withYjs.js.map +1 -0
  89. package/dist/utils/clone.d.ts +5 -0
  90. package/dist/utils/clone.d.ts.map +1 -0
  91. package/dist/utils/clone.js +23 -0
  92. package/dist/utils/clone.js.map +1 -0
  93. package/dist/utils/convert.d.ts +8 -0
  94. package/dist/utils/convert.d.ts.map +1 -0
  95. package/dist/utils/convert.js +35 -0
  96. package/dist/utils/convert.js.map +1 -0
  97. package/dist/utils/delta.d.ts +8 -0
  98. package/dist/utils/delta.d.ts.map +1 -0
  99. package/dist/utils/delta.js +52 -0
  100. package/dist/utils/delta.js.map +1 -0
  101. package/dist/utils/location.d.ts +12 -0
  102. package/dist/utils/location.d.ts.map +1 -0
  103. package/dist/utils/location.js +111 -0
  104. package/dist/utils/location.js.map +1 -0
  105. package/dist/utils/object.d.ts +7 -0
  106. package/dist/utils/object.d.ts.map +1 -0
  107. package/dist/utils/object.js +27 -0
  108. package/dist/utils/object.js.map +1 -0
  109. package/dist/utils/position.d.ts +20 -0
  110. package/dist/utils/position.d.ts.map +1 -0
  111. package/dist/utils/position.js +140 -0
  112. package/dist/utils/position.js.map +1 -0
  113. package/dist/utils/slate.d.ts +3 -0
  114. package/dist/utils/slate.d.ts.map +1 -0
  115. package/dist/utils/slate.js +6 -0
  116. package/dist/utils/slate.js.map +1 -0
  117. package/dist/utils/yjs.d.ts +5 -0
  118. package/dist/utils/yjs.d.ts.map +1 -0
  119. package/dist/utils/yjs.js +7 -0
  120. package/dist/utils/yjs.js.map +1 -0
  121. package/package.json +46 -0
  122. package/src/applyToSlate/index.ts +44 -0
  123. package/src/applyToSlate/textEvent.ts +253 -0
  124. package/src/applyToYjs/index.ts +28 -0
  125. package/src/applyToYjs/node/index.ts +17 -0
  126. package/src/applyToYjs/node/insertNode.ts +22 -0
  127. package/src/applyToYjs/node/mergeNode.ts +80 -0
  128. package/src/applyToYjs/node/moveNode.ts +65 -0
  129. package/src/applyToYjs/node/removeNode.ts +18 -0
  130. package/src/applyToYjs/node/setNode.ts +45 -0
  131. package/src/applyToYjs/node/splitNode.ts +106 -0
  132. package/src/applyToYjs/text/index.ts +9 -0
  133. package/src/applyToYjs/text/insertText.ts +30 -0
  134. package/src/applyToYjs/text/removeText.ts +18 -0
  135. package/src/applyToYjs/types.ts +12 -0
  136. package/src/index.ts +39 -0
  137. package/src/model/types.ts +50 -0
  138. package/src/plugins/index.ts +3 -0
  139. package/src/plugins/withCursors.ts +275 -0
  140. package/src/plugins/withYHistory.ts +139 -0
  141. package/src/plugins/withYjs.ts +241 -0
  142. package/src/utils/clone.ts +29 -0
  143. package/src/utils/convert.ts +48 -0
  144. package/src/utils/delta.ts +75 -0
  145. package/src/utils/location.ts +157 -0
  146. package/src/utils/object.ts +48 -0
  147. package/src/utils/position.ts +293 -0
  148. package/src/utils/slate.ts +11 -0
  149. package/src/utils/yjs.ts +10 -0
  150. package/test/collaboration.test.ts +395 -0
  151. package/test/concurrent.test.ts +233 -0
  152. package/test/testEditor.ts +134 -0
  153. package/test/types.d.ts +8 -0
  154. package/test/utils.ts +64 -0
  155. package/tsconfig.json +10 -0
  156. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,48 @@
1
+ import { Element, Node, Text } from 'slate';
2
+ import * as Y from 'yjs';
3
+ import { DeltaInsert, InsertDelta } from '../model/types';
4
+ import { yTextToInsertDelta } from './delta';
5
+ import { getProperties } from './slate';
6
+
7
+ export function yTextToSlateElement(yText: Y.XmlText): Element {
8
+ const delta = yTextToInsertDelta(yText);
9
+
10
+ const children =
11
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
12
+ delta.length > 0 ? delta.map(deltaInsertToSlateNode) : [{ text: '' }];
13
+
14
+ return { ...yText.getAttributes(), children };
15
+ }
16
+
17
+ export function deltaInsertToSlateNode(insert: DeltaInsert): Node {
18
+ if (typeof insert.insert === 'string') {
19
+ return { ...insert.attributes, text: insert.insert };
20
+ }
21
+
22
+ return yTextToSlateElement(insert.insert);
23
+ }
24
+
25
+ export function slateNodesToInsertDelta(nodes: Node[]): InsertDelta {
26
+ return nodes.map((node) => {
27
+ if (Text.isText(node)) {
28
+ return { insert: node.text, attributes: getProperties(node) };
29
+ }
30
+
31
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
32
+ return { insert: slateElementToYText(node) };
33
+ });
34
+ }
35
+
36
+ export function slateElementToYText({
37
+ children,
38
+ ...attributes
39
+ }: Element): Y.XmlText {
40
+ const yElement = new Y.XmlText();
41
+
42
+ Object.entries(attributes).forEach(([key, value]) => {
43
+ yElement.setAttribute(key, value);
44
+ });
45
+
46
+ yElement.applyDelta(slateNodesToInsertDelta(children), { sanitize: false });
47
+ return yElement;
48
+ }
@@ -0,0 +1,75 @@
1
+ import * as Y from 'yjs';
2
+ import { DeltaInsert, InsertDelta } from '../model/types';
3
+
4
+ const INSERT_DELTA_CACHE: WeakMap<Y.XmlText, InsertDelta> = new WeakMap();
5
+
6
+ export function invalidateDeltaCacheForYText(yText: Y.XmlText) {
7
+ INSERT_DELTA_CACHE.delete(yText);
8
+ }
9
+
10
+ export function yTextToInsertDelta(yText: Y.XmlText): InsertDelta {
11
+ const cached = INSERT_DELTA_CACHE.get(yText);
12
+ if (cached) {
13
+ return cached;
14
+ }
15
+
16
+ const delta = yText.toDelta() as InsertDelta;
17
+ INSERT_DELTA_CACHE.set(yText, delta);
18
+ return delta;
19
+ }
20
+
21
+ export function getInsertLength({ insert }: DeltaInsert): number {
22
+ return typeof insert === 'string' ? insert.length : 1;
23
+ }
24
+
25
+ export function getInsertDeltaLength(delta: InsertDelta): number {
26
+ return delta.reduce((curr, element) => curr + getInsertLength(element), 0);
27
+ }
28
+
29
+ export function sliceInsertDelta(
30
+ delta: InsertDelta,
31
+ start: number,
32
+ length: number
33
+ ): InsertDelta {
34
+ if (length < 1) {
35
+ return [];
36
+ }
37
+
38
+ let currentOffset = 0;
39
+ const sliced: InsertDelta = [];
40
+ const end = start + length;
41
+
42
+ for (let i = 0; i < delta.length; i++) {
43
+ if (currentOffset >= end) {
44
+ break;
45
+ }
46
+
47
+ const element = delta[i];
48
+ const elementLength = getInsertLength(element);
49
+
50
+ if (currentOffset + elementLength <= start) {
51
+ currentOffset += elementLength;
52
+ continue;
53
+ }
54
+
55
+ if (typeof element.insert !== 'string') {
56
+ currentOffset += elementLength;
57
+ sliced.push(element);
58
+ continue;
59
+ }
60
+
61
+ const startOffset = Math.max(0, start - currentOffset);
62
+ const endOffset = Math.min(
63
+ elementLength,
64
+ elementLength - (currentOffset + elementLength - end)
65
+ );
66
+
67
+ sliced.push({
68
+ ...element,
69
+ insert: element.insert.slice(startOffset, endOffset),
70
+ });
71
+ currentOffset += elementLength;
72
+ }
73
+
74
+ return sliced;
75
+ }
@@ -0,0 +1,157 @@
1
+ import { Element, Node, Path, Text } from 'slate';
2
+ import * as Y from 'yjs';
3
+ import { YTarget } from '../model/types';
4
+ import { sliceInsertDelta, yTextToInsertDelta } from './delta';
5
+
6
+ export function getSlateNodeYLength(node: Node | undefined): number {
7
+ if (!node) {
8
+ return 0;
9
+ }
10
+
11
+ return Text.isText(node) ? node.text.length : 1;
12
+ }
13
+
14
+ export function slatePathOffsetToYOffset(element: Element, pathOffset: number) {
15
+ return element.children
16
+ .slice(0, pathOffset)
17
+ .reduce((yOffset, node) => yOffset + getSlateNodeYLength(node), 0);
18
+ }
19
+
20
+ export function getYTarget(
21
+ yRoot: Y.XmlText,
22
+ slateRoot: Node,
23
+ path: Path
24
+ ): YTarget {
25
+ if (path.length === 0) {
26
+ throw new Error('Path has to a have a length >= 1');
27
+ }
28
+
29
+ if (Text.isText(slateRoot)) {
30
+ throw new Error('Cannot descent into slate text');
31
+ }
32
+
33
+ const [pathOffset, ...childPath] = path;
34
+
35
+ const yOffset = slatePathOffsetToYOffset(slateRoot, pathOffset);
36
+ const targetNode = slateRoot.children[pathOffset];
37
+
38
+ const delta = yTextToInsertDelta(yRoot);
39
+ const targetLength = getSlateNodeYLength(targetNode);
40
+
41
+ const targetDelta = sliceInsertDelta(delta, yOffset, targetLength);
42
+ if (targetDelta.length > 1) {
43
+ throw new Error("Path doesn't match yText, yTarget spans multiple nodes");
44
+ }
45
+
46
+ const yTarget = targetDelta[0]?.insert;
47
+ if (childPath.length > 0) {
48
+ if (!(yTarget instanceof Y.XmlText)) {
49
+ throw new Error(
50
+ "Path doesn't match yText, cannot descent into non-yText"
51
+ );
52
+ }
53
+
54
+ return getYTarget(yTarget, targetNode, childPath);
55
+ }
56
+
57
+ return {
58
+ yParent: yRoot,
59
+ textRange: { start: yOffset, end: yOffset + targetLength },
60
+ yTarget: yTarget instanceof Y.XmlText ? yTarget : undefined,
61
+ slateParent: slateRoot,
62
+ slateTarget: targetNode,
63
+ targetDelta,
64
+ };
65
+ }
66
+
67
+ export function yOffsetToSlateOffsets(
68
+ parent: Element,
69
+ yOffset: number,
70
+ opts: { assoc?: number; insert?: boolean } = {}
71
+ ): [number, number] {
72
+ const { assoc = 0, insert = false } = opts;
73
+
74
+ let currentOffset = 0;
75
+ let lastNonEmptyPathOffset = 0;
76
+ for (let pathOffset = 0; pathOffset < parent.children.length; pathOffset++) {
77
+ const child = parent.children[pathOffset];
78
+ const nodeLength = Text.isText(child) ? child.text.length : 1;
79
+
80
+ if (nodeLength > 0) {
81
+ lastNonEmptyPathOffset = pathOffset;
82
+ }
83
+
84
+ const endOffset = currentOffset + nodeLength;
85
+ if (
86
+ nodeLength > 0 &&
87
+ (assoc >= 0 ? endOffset > yOffset : endOffset >= yOffset)
88
+ ) {
89
+ return [pathOffset, yOffset - currentOffset];
90
+ }
91
+
92
+ currentOffset += nodeLength;
93
+ }
94
+
95
+ if (yOffset > currentOffset + (insert ? 1 : 0)) {
96
+ throw new Error('yOffset out of bounds');
97
+ }
98
+
99
+ if (insert) {
100
+ return [parent.children.length, 0];
101
+ }
102
+
103
+ const child = parent.children[lastNonEmptyPathOffset];
104
+ const textOffset = Text.isText(child) ? child.text.length : 1;
105
+ return [lastNonEmptyPathOffset, textOffset];
106
+ }
107
+
108
+ export function getSlatePath(
109
+ sharedRoot: Y.XmlText,
110
+ slateRoot: Node,
111
+ yText: Y.XmlText
112
+ ): Path {
113
+ const yNodePath = [yText];
114
+ while (yNodePath[0] !== sharedRoot) {
115
+ const { parent: yParent } = yNodePath[0];
116
+
117
+ if (!yParent) {
118
+ throw new Error("yText isn't a descendant of root element");
119
+ }
120
+
121
+ if (!(yParent instanceof Y.XmlText)) {
122
+ throw new Error('Unexpected y parent type');
123
+ }
124
+
125
+ yNodePath.unshift(yParent);
126
+ }
127
+
128
+ if (yNodePath.length < 2) {
129
+ return [];
130
+ }
131
+
132
+ let slateParent = slateRoot;
133
+ return yNodePath.reduce<Path>((path, yParent, idx) => {
134
+ const yChild = yNodePath[idx + 1];
135
+ if (!yChild) {
136
+ return path;
137
+ }
138
+
139
+ let yOffset = 0;
140
+ const currentDelta = yTextToInsertDelta(yParent);
141
+ for (const element of currentDelta) {
142
+ if (element.insert === yChild) {
143
+ break;
144
+ }
145
+
146
+ yOffset += typeof element.insert === 'string' ? element.insert.length : 1;
147
+ }
148
+
149
+ if (Text.isText(slateParent)) {
150
+ throw new Error('Cannot descent into slate text');
151
+ }
152
+
153
+ const [pathOffset] = yOffsetToSlateOffsets(slateParent, yOffset);
154
+ slateParent = slateParent.children[pathOffset];
155
+ return path.concat(pathOffset);
156
+ }, []);
157
+ }
@@ -0,0 +1,48 @@
1
+ type InspectableObject = Record<string | number | symbol, unknown>;
2
+
3
+ export function isObject(v: unknown): v is InspectableObject {
4
+ return v !== null && typeof v === 'object';
5
+ }
6
+
7
+ export function deepEquals(
8
+ obj: InspectableObject,
9
+ other: InspectableObject
10
+ ): boolean {
11
+ const keys1 = Object.keys(obj);
12
+ const keys2 = Object.keys(other);
13
+
14
+ if (keys1.length !== keys2.length) {
15
+ return false;
16
+ }
17
+
18
+ return keys1.every((key) => {
19
+ const val1 = obj[key];
20
+ const val2 = other[key];
21
+
22
+ if (!isObject(val1)) {
23
+ return val1 === val2;
24
+ }
25
+
26
+ return isObject(val2) && deepEquals(val1, val2);
27
+ });
28
+ }
29
+
30
+ // eslint-disable-next-line @typescript-eslint/ban-types
31
+ export function pick<TObj extends {}, TKeys extends keyof TObj>(
32
+ obj: TObj,
33
+ ...keys: TKeys[]
34
+ ): Pick<TObj, TKeys> {
35
+ return Object.fromEntries(
36
+ Object.entries(obj).filter(([key]) => keys.includes(key as TKeys))
37
+ ) as Pick<TObj, TKeys>;
38
+ }
39
+
40
+ // eslint-disable-next-line @typescript-eslint/ban-types
41
+ export function omit<TObj extends {}, TKeys extends keyof TObj>(
42
+ obj: TObj,
43
+ ...keys: TKeys[]
44
+ ): Omit<TObj, TKeys> {
45
+ return Object.fromEntries(
46
+ Object.entries(obj).filter(([key]) => !keys.includes(key as TKeys))
47
+ ) as Omit<TObj, TKeys>;
48
+ }
@@ -0,0 +1,293 @@
1
+ import { BasePoint, BaseRange, Node, Text } from 'slate';
2
+ import * as Y from 'yjs';
3
+ import { InsertDelta, RelativeRange, TextRange } from '../model/types';
4
+ import { getInsertDeltaLength, yTextToInsertDelta } from './delta';
5
+ import { getSlatePath, getYTarget, yOffsetToSlateOffsets } from './location';
6
+ import { assertDocumentAttachment } from './yjs';
7
+
8
+ export const STORED_POSITION_PREFIX = '__slateYjsStoredPosition_';
9
+
10
+ export function slatePointToRelativePosition(
11
+ sharedRoot: Y.XmlText,
12
+ slateRoot: Node,
13
+ point: BasePoint
14
+ ) {
15
+ const { yTarget, yParent, textRange } = getYTarget(
16
+ sharedRoot,
17
+ slateRoot,
18
+ point.path
19
+ );
20
+
21
+ if (yTarget) {
22
+ throw new Error(
23
+ 'Slate point points to a non-text element inside sharedRoot'
24
+ );
25
+ }
26
+
27
+ return Y.createRelativePositionFromTypeIndex(
28
+ yParent,
29
+ textRange.start + point.offset,
30
+ point.offset === textRange.end ? -1 : 0
31
+ );
32
+ }
33
+
34
+ export function absolutePositionToSlatePoint(
35
+ sharedRoot: Y.XmlText,
36
+ slateRoot: Node,
37
+ { type, index, assoc }: Y.AbsolutePosition
38
+ ): BasePoint | null {
39
+ if (!(type instanceof Y.XmlText)) {
40
+ throw new Error('Absolute position points to a non-XMLText');
41
+ }
42
+
43
+ const parentPath = getSlatePath(sharedRoot, slateRoot, type);
44
+ const parent = Node.get(slateRoot, parentPath);
45
+
46
+ if (Text.isText(parent)) {
47
+ throw new Error(
48
+ "Absolute position doesn't match slateRoot, cannot descent into text"
49
+ );
50
+ }
51
+
52
+ const [pathOffset, textOffset] = yOffsetToSlateOffsets(parent, index, {
53
+ assoc,
54
+ });
55
+
56
+ const target = parent.children[pathOffset];
57
+ if (!Text.isText(target)) {
58
+ return null;
59
+ }
60
+
61
+ return { path: [...parentPath, pathOffset], offset: textOffset };
62
+ }
63
+
64
+ export function relativePositionToSlatePoint(
65
+ sharedRoot: Y.XmlText,
66
+ slateRoot: Node,
67
+ pos: Y.RelativePosition
68
+ ) {
69
+ if (!sharedRoot.doc) {
70
+ throw new Error("sharedRoot isn't attach to a yDoc");
71
+ }
72
+
73
+ const absPos = Y.createAbsolutePositionFromRelativePosition(
74
+ pos,
75
+ sharedRoot.doc
76
+ );
77
+
78
+ return absPos && absolutePositionToSlatePoint(sharedRoot, slateRoot, absPos);
79
+ }
80
+
81
+ export function getStoredPosition(
82
+ sharedRoot: Y.XmlText,
83
+ key: string
84
+ ): Y.RelativePosition | null {
85
+ const rawPosition = sharedRoot.getAttribute(STORED_POSITION_PREFIX + key);
86
+ if (!rawPosition) {
87
+ return null;
88
+ }
89
+
90
+ return Y.decodeRelativePosition(rawPosition);
91
+ }
92
+
93
+ export function getStoredPositions(
94
+ sharedRoot: Y.XmlText
95
+ ): Record<string, Y.RelativePosition> {
96
+ return Object.fromEntries(
97
+ Object.entries(sharedRoot.getAttributes())
98
+ .filter(([key]) => key.startsWith(STORED_POSITION_PREFIX))
99
+ .map(([key, position]) => [
100
+ key.slice(STORED_POSITION_PREFIX.length),
101
+ Y.createRelativePositionFromJSON(position),
102
+ ])
103
+ );
104
+ }
105
+
106
+ function getStoredPositionsAbsolute(sharedRoot: Y.XmlText) {
107
+ assertDocumentAttachment(sharedRoot);
108
+
109
+ return Object.fromEntries(
110
+ Object.entries(sharedRoot.getAttributes())
111
+ .filter(([key]) => key.startsWith(STORED_POSITION_PREFIX))
112
+ .map(
113
+ ([key, position]) =>
114
+ [
115
+ key.slice(STORED_POSITION_PREFIX.length),
116
+ Y.createAbsolutePositionFromRelativePosition(
117
+ Y.createRelativePositionFromJSON(position),
118
+ sharedRoot.doc
119
+ ),
120
+ ] as const
121
+ )
122
+ .filter(([, position]) => position)
123
+ ) as Record<string, Y.AbsolutePosition>;
124
+ }
125
+
126
+ export function removeStoredPosition(sharedRoot: Y.XmlText, key: string) {
127
+ sharedRoot.removeAttribute(STORED_POSITION_PREFIX + key);
128
+ }
129
+
130
+ export function setStoredPosition(
131
+ sharedRoot: Y.XmlText,
132
+ key: string,
133
+ position: Y.RelativePosition
134
+ ) {
135
+ sharedRoot.setAttribute(
136
+ STORED_POSITION_PREFIX + key,
137
+ Y.encodeRelativePosition(position)
138
+ );
139
+ }
140
+
141
+ function getAbsolutePositionsInTextRange(
142
+ absolutePositions: Record<string, Y.AbsolutePosition>,
143
+ yTarget: Y.XmlText,
144
+ textRange?: TextRange
145
+ ) {
146
+ return Object.fromEntries(
147
+ Object.entries(absolutePositions).filter(([, position]) => {
148
+ if (position.type !== yTarget) {
149
+ return false;
150
+ }
151
+
152
+ if (!textRange) {
153
+ return true;
154
+ }
155
+
156
+ return position.assoc >= 0
157
+ ? position.index >= textRange.start && position.index < textRange.end
158
+ : position.index > textRange.start && position.index >= textRange.end;
159
+ })
160
+ );
161
+ }
162
+
163
+ function getAbsolutePositionsInYText(
164
+ absolutePositions: Record<string, Y.AbsolutePosition>,
165
+ yText: Y.XmlText,
166
+ parentPath = ''
167
+ ): Record<string, Record<string, Y.AbsolutePosition>> {
168
+ const positions = {
169
+ [parentPath]: getAbsolutePositionsInTextRange(absolutePositions, yText),
170
+ };
171
+
172
+ const insertDelta = yTextToInsertDelta(yText);
173
+ insertDelta.forEach(({ insert }, i) => {
174
+ if (insert instanceof Y.XmlText) {
175
+ Object.assign(
176
+ positions,
177
+ getAbsolutePositionsInYText(
178
+ absolutePositions,
179
+ insert,
180
+ parentPath ? `${parentPath}.${i}` : i.toString()
181
+ )
182
+ );
183
+ }
184
+ });
185
+
186
+ return positions;
187
+ }
188
+
189
+ export function getStoredPositionsInDeltaAbsolute(
190
+ sharedRoot: Y.XmlText,
191
+ yText: Y.XmlText,
192
+ delta: InsertDelta,
193
+ deltaOffset = 0
194
+ ) {
195
+ const absolutePositions = getStoredPositionsAbsolute(sharedRoot);
196
+
197
+ const positions = {
198
+ '': getAbsolutePositionsInTextRange(absolutePositions, yText, {
199
+ start: deltaOffset,
200
+ end: deltaOffset + getInsertDeltaLength(delta),
201
+ }),
202
+ };
203
+
204
+ delta.forEach(({ insert }, i) => {
205
+ if (insert instanceof Y.XmlText) {
206
+ Object.assign(
207
+ positions,
208
+ getAbsolutePositionsInYText(absolutePositions, insert, i.toString())
209
+ );
210
+ }
211
+ });
212
+
213
+ return positions;
214
+ }
215
+
216
+ export function restoreStoredPositionsWithDeltaAbsolute(
217
+ sharedRoot: Y.XmlText,
218
+ yText: Y.XmlText,
219
+ absolutePositions: Record<string, Record<string, Y.AbsolutePosition>>,
220
+ delta: InsertDelta,
221
+ newDeltaOffset = 0,
222
+ previousDeltaOffset = 0,
223
+ path = ''
224
+ ) {
225
+ const toRestore = absolutePositions[path];
226
+
227
+ if (toRestore) {
228
+ Object.entries(toRestore).forEach(([key, position]) => {
229
+ setStoredPosition(
230
+ sharedRoot,
231
+ key,
232
+ Y.createRelativePositionFromTypeIndex(
233
+ yText,
234
+ position.index - previousDeltaOffset + newDeltaOffset,
235
+ position.assoc
236
+ )
237
+ );
238
+ });
239
+ }
240
+
241
+ delta.forEach(({ insert }, i) => {
242
+ if (insert instanceof Y.XmlText) {
243
+ restoreStoredPositionsWithDeltaAbsolute(
244
+ sharedRoot,
245
+ insert,
246
+ absolutePositions,
247
+ yTextToInsertDelta(insert),
248
+ 0,
249
+ 0,
250
+ path ? `${path}.${i}` : i.toString()
251
+ );
252
+ }
253
+ });
254
+ }
255
+
256
+ export function slateRangeToRelativeRange(
257
+ sharedRoot: Y.XmlText,
258
+ slateRoot: Node,
259
+ range: BaseRange
260
+ ): RelativeRange {
261
+ return {
262
+ anchor: slatePointToRelativePosition(sharedRoot, slateRoot, range.anchor),
263
+ focus: slatePointToRelativePosition(sharedRoot, slateRoot, range.focus),
264
+ };
265
+ }
266
+
267
+ export function relativeRangeToSlateRange(
268
+ sharedRoot: Y.XmlText,
269
+ slateRoot: Node,
270
+ range: RelativeRange
271
+ ): BaseRange | null {
272
+ const anchor = relativePositionToSlatePoint(
273
+ sharedRoot,
274
+ slateRoot,
275
+ range.anchor
276
+ );
277
+
278
+ if (!anchor) {
279
+ return null;
280
+ }
281
+
282
+ const focus = relativePositionToSlatePoint(
283
+ sharedRoot,
284
+ slateRoot,
285
+ range.focus
286
+ );
287
+
288
+ if (!focus) {
289
+ return null;
290
+ }
291
+
292
+ return { anchor, focus };
293
+ }
@@ -0,0 +1,11 @@
1
+ import { Descendant, Text } from 'slate';
2
+ import { omit } from './object';
3
+
4
+ export function getProperties<TNode extends Descendant>(
5
+ node: TNode
6
+ ): Omit<TNode, TNode extends Text ? 'text' : 'children'> {
7
+ return omit(
8
+ node,
9
+ (Text.isText(node) ? 'text' : 'children') as keyof TNode
10
+ ) as unknown as Omit<TNode, TNode extends Text ? 'text' : 'children'>;
11
+ }
@@ -0,0 +1,10 @@
1
+ import * as Y from 'yjs';
2
+
3
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4
+ export function assertDocumentAttachment<T extends Y.AbstractType<any>>(
5
+ sharedType: T
6
+ ): asserts sharedType is T & { doc: NonNullable<T['doc']> } {
7
+ if (!sharedType.doc) {
8
+ throw new Error("shared type isn't attached to a document");
9
+ }
10
+ }