@kerebron/yjs 0.0.0-stage → 0.9.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 (114) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +4 -2
  3. package/esm/ExtensionYjs.d.ts +20 -0
  4. package/esm/ExtensionYjs.d.ts.map +1 -0
  5. package/esm/ExtensionYjs.js +144 -0
  6. package/esm/ExtensionYjs.js.map +1 -0
  7. package/esm/MarkYChange.d.ts +7 -0
  8. package/esm/MarkYChange.d.ts.map +1 -0
  9. package/esm/MarkYChange.js +21 -0
  10. package/esm/MarkYChange.js.map +1 -0
  11. package/esm/WebsocketProvider.d.ts +70 -0
  12. package/esm/WebsocketProvider.d.ts.map +1 -0
  13. package/esm/WebsocketProvider.js +377 -0
  14. package/esm/WebsocketProvider.js.map +1 -0
  15. package/esm/YjsEditorKit.d.ts +11 -0
  16. package/esm/YjsEditorKit.d.ts.map +1 -0
  17. package/esm/YjsEditorKit.js +44 -0
  18. package/esm/YjsEditorKit.js.map +1 -0
  19. package/esm/YjsProvider.d.ts +48 -0
  20. package/esm/YjsProvider.d.ts.map +1 -0
  21. package/esm/YjsProvider.js +12 -0
  22. package/esm/YjsProvider.js.map +1 -0
  23. package/esm/_dnt.shims.d.ts +2 -0
  24. package/esm/_dnt.shims.d.ts.map +1 -0
  25. package/esm/_dnt.shims.js +58 -0
  26. package/esm/_dnt.shims.js.map +1 -0
  27. package/esm/binding/BindingMetadata.d.ts +6 -0
  28. package/esm/binding/BindingMetadata.d.ts.map +1 -0
  29. package/esm/binding/BindingMetadata.js +2 -0
  30. package/esm/binding/BindingMetadata.js.map +1 -0
  31. package/esm/binding/DiffViewer.d.ts +17 -0
  32. package/esm/binding/DiffViewer.d.ts.map +1 -0
  33. package/esm/binding/DiffViewer.js +95 -0
  34. package/esm/binding/DiffViewer.js.map +1 -0
  35. package/esm/binding/PmYjsBinding.d.ts +47 -0
  36. package/esm/binding/PmYjsBinding.d.ts.map +1 -0
  37. package/esm/binding/PmYjsBinding.js +246 -0
  38. package/esm/binding/PmYjsBinding.js.map +1 -0
  39. package/esm/binding/convertUtils.d.ts +48 -0
  40. package/esm/binding/convertUtils.d.ts.map +1 -0
  41. package/esm/binding/convertUtils.js +80 -0
  42. package/esm/binding/convertUtils.js.map +1 -0
  43. package/esm/binding/createNodeFromYElement.d.ts +10 -0
  44. package/esm/binding/createNodeFromYElement.d.ts.map +1 -0
  45. package/esm/binding/createNodeFromYElement.js +123 -0
  46. package/esm/binding/createNodeFromYElement.js.map +1 -0
  47. package/esm/binding/updateYFragment.d.ts +17 -0
  48. package/esm/binding/updateYFragment.d.ts.map +1 -0
  49. package/esm/binding/updateYFragment.js +337 -0
  50. package/esm/binding/updateYFragment.js.map +1 -0
  51. package/esm/debug.d.ts +13 -0
  52. package/esm/debug.d.ts.map +1 -0
  53. package/esm/debug.js +158 -0
  54. package/esm/debug.js.map +1 -0
  55. package/esm/keys.d.ts +8 -0
  56. package/esm/keys.d.ts.map +1 -0
  57. package/esm/keys.js +5 -0
  58. package/esm/keys.js.map +1 -0
  59. package/esm/lib.d.ts +8 -0
  60. package/esm/lib.d.ts.map +1 -0
  61. package/esm/lib.js +2 -0
  62. package/esm/lib.js.map +1 -0
  63. package/esm/package.json +3 -0
  64. package/esm/position.d.ts +8 -0
  65. package/esm/position.d.ts.map +1 -0
  66. package/esm/position.js +165 -0
  67. package/esm/position.js.map +1 -0
  68. package/esm/ui/RoomController.d.ts +17 -0
  69. package/esm/ui/RoomController.d.ts.map +1 -0
  70. package/esm/ui/RoomController.js +115 -0
  71. package/esm/ui/RoomController.js.map +1 -0
  72. package/esm/ui/selection.d.ts +29 -0
  73. package/esm/ui/selection.d.ts.map +1 -0
  74. package/esm/ui/selection.js +129 -0
  75. package/esm/ui/selection.js.map +1 -0
  76. package/esm/utils.d.ts +4 -0
  77. package/esm/utils.d.ts.map +1 -0
  78. package/esm/utils.js +15 -0
  79. package/esm/utils.js.map +1 -0
  80. package/esm/yPositionPlugin.d.ts +27 -0
  81. package/esm/yPositionPlugin.d.ts.map +1 -0
  82. package/esm/yPositionPlugin.js +216 -0
  83. package/esm/yPositionPlugin.js.map +1 -0
  84. package/esm/ySyncPlugin.d.ts +23 -0
  85. package/esm/ySyncPlugin.d.ts.map +1 -0
  86. package/esm/ySyncPlugin.js +140 -0
  87. package/esm/ySyncPlugin.js.map +1 -0
  88. package/esm/yUndoPlugin.d.ts +23 -0
  89. package/esm/yUndoPlugin.d.ts.map +1 -0
  90. package/esm/yUndoPlugin.js +128 -0
  91. package/esm/yUndoPlugin.js.map +1 -0
  92. package/package.json +46 -3
  93. package/src/ExtensionYjs.ts +204 -0
  94. package/src/MarkYChange.ts +23 -0
  95. package/src/WebsocketProvider.ts +528 -0
  96. package/src/YjsEditorKit.ts +58 -0
  97. package/src/YjsProvider.ts +75 -0
  98. package/src/_dnt.shims.ts +60 -0
  99. package/src/binding/BindingMetadata.ts +6 -0
  100. package/src/binding/DiffViewer.ts +138 -0
  101. package/src/binding/PmYjsBinding.ts +383 -0
  102. package/src/binding/convertUtils.ts +124 -0
  103. package/src/binding/createNodeFromYElement.ts +175 -0
  104. package/src/binding/updateYFragment.ts +447 -0
  105. package/src/debug.ts +239 -0
  106. package/src/keys.ts +14 -0
  107. package/src/lib.ts +12 -0
  108. package/src/position.ts +191 -0
  109. package/src/ui/RoomController.ts +131 -0
  110. package/src/ui/selection.ts +218 -0
  111. package/src/utils.ts +19 -0
  112. package/src/yPositionPlugin.ts +351 -0
  113. package/src/ySyncPlugin.ts +211 -0
  114. package/src/yUndoPlugin.ts +175 -0
package/src/debug.ts ADDED
@@ -0,0 +1,239 @@
1
+ import * as Y from 'yjs';
2
+ import { isVisible } from './utils.js';
3
+
4
+ interface YDebugConfig {
5
+ STRIKE: string;
6
+ RESET: string;
7
+ DIM: string;
8
+ isVisible: (item: Y.Item | null) => boolean;
9
+ renderDeleted: (text: string, item: Y.Item | null) => string;
10
+ }
11
+
12
+ const YAnsiDebugConfig: YDebugConfig = {
13
+ STRIKE: '\x1b[9m',
14
+ RESET: '\x1b[0m',
15
+ DIM: '\x1b[2m',
16
+ isVisible: () => true,
17
+ renderDeleted(text: string, item: Y.Item | null) {
18
+ if (item?.deleted) {
19
+ return this.STRIKE + text + this.RESET;
20
+ }
21
+ return text;
22
+ },
23
+ };
24
+
25
+ function indentText(text: string, indent: number = 0): string {
26
+ const indentStr = ' '.repeat(indent);
27
+ const lines = text.split('\n');
28
+ const indentedLines = lines.map((line) => indentStr + line);
29
+
30
+ if (indentedLines[indentedLines.length - 1] === indentStr) {
31
+ indentedLines[indentedLines.length - 1] = '';
32
+ }
33
+
34
+ return indentedLines.join('\n');
35
+ }
36
+
37
+ export function debugYNode(
38
+ node: Y.AbstractType<any>,
39
+ config: YDebugConfig = YAnsiDebugConfig,
40
+ ): string {
41
+ const {
42
+ STRIKE,
43
+ RESET,
44
+ DIM,
45
+ } = config;
46
+
47
+ const yDebugClient = (item: Y.Item | null) => {
48
+ if (!item) {
49
+ return '';
50
+ }
51
+ const { client, clock } = item.id;
52
+ return `\t${DIM}[${client}:${clock}]${RESET}`;
53
+ };
54
+
55
+ let retVal = '';
56
+
57
+ if (node instanceof Y.XmlText) {
58
+ if (!config.isVisible(node._item)) {
59
+ return '';
60
+ }
61
+
62
+ retVal += config.renderDeleted('XmlText', node._item) + ' {';
63
+
64
+ retVal += yDebugClient(node._item);
65
+ retVal += '\n';
66
+
67
+ let text = '';
68
+
69
+ for (let item = node._start; item; item = item.right) {
70
+ if (!config.isVisible(item)) {
71
+ continue;
72
+ }
73
+
74
+ if (item.content instanceof Y.ContentString) {
75
+ const content = item.content?.str || '';
76
+
77
+ text += config.renderDeleted(content, item);
78
+ text += yDebugClient(node._item);
79
+ text += '\n';
80
+ } else {
81
+ text += config.renderDeleted(
82
+ `Unhandled debug: ${typeof item.content}`,
83
+ item,
84
+ );
85
+ text += yDebugClient(node._item);
86
+ text += '\n';
87
+ }
88
+ }
89
+
90
+ retVal += indentText(text, 1);
91
+ retVal += `}\n`;
92
+
93
+ return retVal;
94
+ }
95
+
96
+ if (node instanceof Y.XmlElement) {
97
+ if (!config.isVisible(node._item)) {
98
+ return '';
99
+ }
100
+
101
+ retVal += config.renderDeleted(`<${node.nodeName}>`, node._item);
102
+ retVal += yDebugClient(node._item);
103
+ retVal += '\n';
104
+
105
+ retVal += indentText(
106
+ node.toArray()
107
+ .map((child) => {
108
+ return debugYNode(child, config);
109
+ })
110
+ .join('\n'),
111
+ 1,
112
+ );
113
+
114
+ retVal += config.renderDeleted(`</${node.nodeName}>`, node._item);
115
+ return retVal;
116
+ }
117
+
118
+ if (node instanceof Y.XmlFragment) {
119
+ if (!config.isVisible(node._item)) {
120
+ return '';
121
+ }
122
+
123
+ retVal += config.renderDeleted(`Y.XmlFragment`, node._item);
124
+ retVal += yDebugClient(node._item);
125
+ retVal += '\n';
126
+
127
+ retVal += indentText(
128
+ node.toArray()
129
+ .map((child) => {
130
+ return debugYNode(child, config);
131
+ })
132
+ .join('\n'),
133
+ 1,
134
+ );
135
+ return retVal;
136
+ }
137
+
138
+ if (node instanceof Y.Map) {
139
+ if (!config.isVisible(node._item)) {
140
+ return '';
141
+ }
142
+
143
+ const entries = Array.from(node.entries());
144
+
145
+ retVal += config.renderDeleted(`Y.Map(${entries.length})`, node._item);
146
+ retVal += yDebugClient(node._item);
147
+ retVal += '\n';
148
+
149
+ retVal += indentText(
150
+ entries
151
+ .map(([key, value]: [string, any]) =>
152
+ '- ' + key + ': ' + debugYNode(value, config)
153
+ )
154
+ .join('\n'),
155
+ 1,
156
+ );
157
+ return retVal;
158
+ }
159
+
160
+ if (node instanceof Y.Array) {
161
+ if (!config.isVisible(node._item)) {
162
+ return '';
163
+ }
164
+
165
+ const arr: Y.Array<any> = node;
166
+
167
+ retVal += config.renderDeleted(`Y.Array(${arr._length})`, node._item);
168
+ retVal += yDebugClient(node._item);
169
+ retVal += '\n';
170
+
171
+ retVal += indentText(
172
+ arr
173
+ .map((value) => '- ' + debugYNode(value, config))
174
+ .join('\n'),
175
+ 1,
176
+ );
177
+ return retVal;
178
+ }
179
+
180
+ if (node instanceof Y.AbstractType) {
181
+ if (!config.isVisible(node._item)) {
182
+ return '';
183
+ }
184
+
185
+ const atype: Y.AbstractType<any> = node;
186
+
187
+ retVal += config.renderDeleted(
188
+ `Y.AbstractType(${atype._length})`,
189
+ node._item,
190
+ );
191
+ retVal += yDebugClient(node._item);
192
+ retVal += '\n';
193
+
194
+ retVal += indentText(
195
+ JSON.stringify(atype._item),
196
+ 1,
197
+ );
198
+ return retVal;
199
+ }
200
+
201
+ if ('object' !== typeof node) {
202
+ retVal += '' + node;
203
+ return retVal;
204
+ }
205
+
206
+ throw new Error('Unhandled debug class: ' + node.constructor.name);
207
+ }
208
+
209
+ export function debugYDoc(
210
+ ydoc: Y.Doc,
211
+ config: YDebugConfig = YAnsiDebugConfig,
212
+ ): string {
213
+ const entries = Array.from(ydoc.share.entries());
214
+ let retVal = '';
215
+ for (const [key, value] of entries) {
216
+ retVal += `${key}: `;
217
+ retVal += debugYNode(value, config);
218
+ retVal += '\n';
219
+ }
220
+ return (`Y.Doc(${entries.length})\n` + indentText(retVal, 1)).trim();
221
+ }
222
+
223
+ export function debugYDocSnapshot(
224
+ ydoc: Y.Doc,
225
+ snapshot: Y.Snapshot,
226
+ ) {
227
+ const retVal = debugYDoc(ydoc, {
228
+ ...YAnsiDebugConfig,
229
+ isVisible: (item: Y.Item | null) => {
230
+ if (!item) return true;
231
+ return isVisible(item, snapshot);
232
+ },
233
+ renderDeleted(text: string) {
234
+ return text;
235
+ },
236
+ });
237
+
238
+ return ('Y.Snapshot\n' + indentText(retVal, 1)).trim();
239
+ }
package/src/keys.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { PluginKey } from 'prosemirror-state';
2
+ import { type UndoPluginState } from './yUndoPlugin.js';
3
+ import { type YSyncPluginState } from './ySyncPlugin.js';
4
+ import { type YPositionPluginState } from './yPositionPlugin.js';
5
+
6
+ export const ySyncPluginKey = new PluginKey<YSyncPluginState>('y-sync');
7
+
8
+ export const yPositionPluginKey = new PluginKey<YPositionPluginState>(
9
+ 'yjs-position',
10
+ );
11
+
12
+ export const yUndoPluginKey = new PluginKey<UndoPluginState>(
13
+ 'y-undo',
14
+ );
package/src/lib.ts ADDED
@@ -0,0 +1,12 @@
1
+ import * as Y from 'yjs';
2
+ import { type Node } from 'prosemirror-model';
3
+
4
+ export type TransactFunc<T> = (
5
+ f: (arg0?: Y.Transaction) => T,
6
+ origin?: any,
7
+ ) => T;
8
+
9
+ /**
10
+ * Either a node if type is YXmlElement or an Array of text nodes if YXmlText
11
+ */
12
+ export type ProsemirrorMapping = Map<Y.AbstractType<any>, Node | Array<Node>>;
@@ -0,0 +1,191 @@
1
+ import * as Y from 'yjs';
2
+ import { ProsemirrorMapping } from './lib.js';
3
+
4
+ /**
5
+ * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model).
6
+ */
7
+ export const absolutePositionToRelativePosition = (
8
+ pos: number,
9
+ type: Y.XmlFragment,
10
+ mapping: ProsemirrorMapping,
11
+ ): any => {
12
+ if (pos === 0) {
13
+ // if the type is later populated, we want to retain the 0 position (hence assoc=-1)
14
+ return Y.createRelativePositionFromTypeIndex(
15
+ type,
16
+ 0,
17
+ type.length === 0 ? -1 : 0,
18
+ );
19
+ }
20
+
21
+ let n: Y.AbstractType<any> | null = type._first === null
22
+ ? null
23
+ : /** @type {Y.ContentType} */ (type._first.content).type;
24
+ while (n !== null && type !== n) {
25
+ if (n instanceof Y.XmlText) {
26
+ if (n._length >= pos) {
27
+ return Y.createRelativePositionFromTypeIndex(
28
+ n,
29
+ pos,
30
+ type.length === 0 ? -1 : 0,
31
+ );
32
+ } else {
33
+ pos -= n._length;
34
+ }
35
+ if (n._item !== null && n._item.next !== null) {
36
+ n = /** @type {Y.ContentType} */ (n._item.next.content).type;
37
+ } else {
38
+ do {
39
+ n = n._item === null ? null : n._item.parent;
40
+ pos--;
41
+ } while (
42
+ n !== type && n !== null && n._item !== null && n._item.next === null
43
+ );
44
+ if (n !== null && n !== type) {
45
+ // @ts-gnore we know that n.next !== null because of above loop conditition
46
+ n = n._item === null
47
+ ? null
48
+ : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next)
49
+ .content).type;
50
+ }
51
+ }
52
+ } else {
53
+ const pNodeSize =
54
+ /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize;
55
+ if (n._first !== null && pos < pNodeSize) {
56
+ n = /** @type {Y.ContentType} */ (n._first.content).type;
57
+ pos--;
58
+ } else {
59
+ if (pos === 1 && n._length === 0 && pNodeSize > 1) {
60
+ // edge case, should end in this paragraph
61
+ return new Y.RelativePosition(
62
+ n._item === null ? null : n._item.id,
63
+ n._item === null ? Y.findRootTypeKey(n) : null,
64
+ null,
65
+ );
66
+ }
67
+ pos -= pNodeSize;
68
+ if (n._item !== null && n._item.next !== null) {
69
+ n = /** @type {Y.ContentType} */ (n._item.next.content).type;
70
+ } else {
71
+ if (pos === 0) {
72
+ // set to end of n.parent
73
+ n = n._item === null ? n : n._item.parent;
74
+ return new Y.RelativePosition(
75
+ n._item === null ? null : n._item.id,
76
+ n._item === null ? Y.findRootTypeKey(n) : null,
77
+ null,
78
+ );
79
+ }
80
+ do {
81
+ n = n._item.parent;
82
+ pos--;
83
+ } while (n !== type && /** @type {Y.Item} */ (n._item).next === null);
84
+ // if n is null at this point, we have an unexpected case
85
+ if (n !== type) {
86
+ // We know that n._item.next is defined because of above loop condition
87
+ n =
88
+ /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n
89
+ ._item).next).content).type;
90
+ }
91
+ }
92
+ }
93
+ }
94
+ if (n === null) {
95
+ throw new Error('Unexpected case');
96
+ }
97
+ if (pos === 0 && n.constructor !== Y.XmlText && n !== type) { // TODO: set to <= 0
98
+ return createRelativePosition(n._item.parent, n._item);
99
+ }
100
+ }
101
+ return Y.createRelativePositionFromTypeIndex(
102
+ type,
103
+ type._length,
104
+ type.length === 0 ? -1 : 0,
105
+ );
106
+ };
107
+
108
+ const createRelativePosition = (type: Y.AbstractType<any>, item: Y.Item) => {
109
+ let typeid = null;
110
+ let tname = null;
111
+ if (type._item === null) {
112
+ tname = Y.findRootTypeKey(type);
113
+ } else {
114
+ typeid = Y.createID(type._item.id.client, type._item.id.clock);
115
+ }
116
+ return new Y.RelativePosition(typeid, tname, item.id);
117
+ };
118
+
119
+ export const relativePositionToAbsolutePosition = (
120
+ yDoc: Y.Doc,
121
+ documentType: Y.XmlFragment,
122
+ relPos: Y.RelativePosition,
123
+ mapping: ProsemirrorMapping,
124
+ ): null | number => {
125
+ const decodedPos = Y.createAbsolutePositionFromRelativePosition(relPos, yDoc);
126
+ if (
127
+ decodedPos === null ||
128
+ (decodedPos.type !== documentType &&
129
+ !Y.isParentOf(documentType, decodedPos.type._item))
130
+ ) {
131
+ return null;
132
+ }
133
+ let type = decodedPos.type;
134
+ let pos = 0;
135
+ if (type instanceof Y.XmlText) {
136
+ pos = decodedPos.index;
137
+ } else if (type._item === null || !type._item.deleted) {
138
+ let n: Y.Item | null = type._first;
139
+ let i = 0;
140
+ while (i < type._length && i < decodedPos.index && n !== null) {
141
+ if (!n.deleted) {
142
+ const t: Y.AbstractType<any> = n.content.type;
143
+ i++;
144
+ if (t instanceof Y.XmlText) {
145
+ pos += t._length;
146
+ } else {
147
+ const node = mapping.get(t);
148
+ if (Array.isArray(node)) {
149
+ pos += node.reduce((prev, curr) => prev + curr?.nodeSize || 0, 0);
150
+ } else {
151
+ pos += node?.nodeSize || 0;
152
+ }
153
+ }
154
+ }
155
+ n = n.right;
156
+ }
157
+ pos += 1; // increase because we go out of n
158
+ }
159
+ while (type !== documentType && type._item !== null) {
160
+ const parent = type._item.parent;
161
+ if (parent instanceof Y.ID || parent === null) {
162
+ continue;
163
+ }
164
+ if (parent._item === null || !parent._item.deleted) {
165
+ pos += 1; // the start tag
166
+ let n = /** @type {Y.AbstractType} */ (parent)._first;
167
+ // now iterate until we found type
168
+ while (n !== null) {
169
+ const contentType: Y.AbstractType<any> = n.content.type;
170
+ if (contentType === type) {
171
+ break;
172
+ }
173
+ if (!n.deleted) {
174
+ if (contentType instanceof Y.XmlText) {
175
+ pos += contentType._length;
176
+ } else {
177
+ const node = mapping.get(contentType);
178
+ if (Array.isArray(node)) {
179
+ pos += node.reduce((prev, curr) => prev + curr?.nodeSize || 0, 0);
180
+ } else {
181
+ pos += node?.nodeSize || 0;
182
+ }
183
+ }
184
+ }
185
+ n = n.right;
186
+ }
187
+ }
188
+ type = parent;
189
+ }
190
+ return pos - 1; // we don't count the most outer tag, because it is a fragment
191
+ };
@@ -0,0 +1,131 @@
1
+ import {
2
+ generateBlankUser,
3
+ generateRandomUser,
4
+ User,
5
+ } from '@kerebron/editor/user';
6
+
7
+ export class RoomController extends EventTarget {
8
+ roomIDs: Set<string> = new Set();
9
+ roomID = '';
10
+ user: User = generateBlankUser();
11
+ hashCallback: EventListenerOrEventListenerObject | undefined;
12
+
13
+ constructor() {
14
+ super();
15
+ }
16
+
17
+ async init() {
18
+ this.hashCallback = () => this.hashChange();
19
+ globalThis.addEventListener('hashchange', this.hashCallback);
20
+ await this.fetch();
21
+ this.hashChange();
22
+ }
23
+
24
+ async fetch() {
25
+ // <a :href="'#room:' + id">{{ id }}</a>
26
+ const response = await fetch('/api/rooms');
27
+ this.roomIDs = new Set(await response.json());
28
+
29
+ const stored = localStorage.getItem('kerebron:user');
30
+ if (stored) {
31
+ this.user = JSON.parse(stored);
32
+ } else {
33
+ this.user = generateRandomUser();
34
+ this.onUserChange();
35
+ }
36
+ }
37
+
38
+ hashChange() {
39
+ const location = (globalThis.parent.location !== globalThis.location)
40
+ ? globalThis.parent.location
41
+ : globalThis.location;
42
+ if (location.hash.startsWith('#room:')) {
43
+ this.roomID = location.hash.substring('#room:'.length);
44
+ this.roomIDs.add(this.roomID);
45
+ this.onRoomChange();
46
+ }
47
+ }
48
+
49
+ onRoomChange() {
50
+ if (!this.roomID) {
51
+ return;
52
+ }
53
+ const location = (globalThis.parent.location !== globalThis.location)
54
+ ? globalThis.parent.location
55
+ : globalThis.location;
56
+ location.hash = 'room:' + this.roomID;
57
+ const event = new CustomEvent('change-room', {
58
+ detail: this.roomID,
59
+ });
60
+ this.dispatchEvent(event);
61
+ }
62
+
63
+ onUserChange() {
64
+ localStorage.setItem('kerebron:user', JSON.stringify(this.user));
65
+
66
+ const event = new CustomEvent('change-user', {
67
+ detail: this.user,
68
+ });
69
+ this.dispatchEvent(event);
70
+ }
71
+
72
+ async newRoom() {
73
+ const response = await fetch('/api/rooms', { method: 'POST' });
74
+ this.roomID = await response.json();
75
+ this.roomIDs.add(this.roomID);
76
+ this.onRoomChange();
77
+ }
78
+
79
+ bindEvents(target: EventTarget) {
80
+ target.addEventListener('submit', (event) => {
81
+ event.preventDefault();
82
+ this.onUserChange();
83
+ });
84
+ target.addEventListener('click', (event) => {
85
+ if (event.target && 'name' in event.target) {
86
+ event.stopPropagation();
87
+ switch (event.target.name) {
88
+ case 'change-name-button':
89
+ this.onUserChange();
90
+ break;
91
+ case 'new-room-button':
92
+ this.newRoom();
93
+ break;
94
+ }
95
+ }
96
+ }, true);
97
+
98
+ target.addEventListener('change', (event) => {
99
+ if (event.target && 'name' in event.target) {
100
+ event.stopPropagation();
101
+ switch (event.target.name) {
102
+ case 'room-select':
103
+ if (!(event.target as HTMLSelectElement).value) {
104
+ return;
105
+ }
106
+ this.roomID = (event.target as HTMLSelectElement).value;
107
+ this.onRoomChange();
108
+ break;
109
+ case 'user-input':
110
+ if (!(event.target as HTMLInputElement).value) {
111
+ return;
112
+ }
113
+
114
+ if (!this.user.id) {
115
+ this.user = generateRandomUser();
116
+ }
117
+ this.user.name = (event.target as HTMLInputElement).value;
118
+ this.onUserChange();
119
+ break;
120
+ }
121
+ }
122
+ }, true);
123
+ }
124
+
125
+ destroy() {
126
+ if (this.hashCallback) {
127
+ globalThis.addEventListener('hashchange', this.hashCallback);
128
+ this.hashCallback = undefined;
129
+ }
130
+ }
131
+ }