@dovetail-ts/ember 0.0.0-stage → 1.0.0

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 (81) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +21 -0
  3. package/README.md +180 -2
  4. package/addon-main.cjs +4 -0
  5. package/declarations/-private/status-dot.d.ts +14 -0
  6. package/declarations/-private/status-dot.d.ts.map +1 -0
  7. package/declarations/-private/visually-hidden.d.ts +6 -0
  8. package/declarations/-private/visually-hidden.d.ts.map +1 -0
  9. package/declarations/components/dovetail/avatar-stack.d.ts +31 -0
  10. package/declarations/components/dovetail/avatar-stack.d.ts.map +1 -0
  11. package/declarations/components/dovetail/connection-badge.d.ts +24 -0
  12. package/declarations/components/dovetail/connection-badge.d.ts.map +1 -0
  13. package/declarations/components/dovetail/dead-letters.d.ts +25 -0
  14. package/declarations/components/dovetail/dead-letters.d.ts.map +1 -0
  15. package/declarations/components/dovetail/editor.d.ts +58 -0
  16. package/declarations/components/dovetail/editor.d.ts.map +1 -0
  17. package/declarations/components/dovetail/live-cursors.d.ts +31 -0
  18. package/declarations/components/dovetail/live-cursors.d.ts.map +1 -0
  19. package/declarations/components/dovetail/presence.d.ts +27 -0
  20. package/declarations/components/dovetail/presence.d.ts.map +1 -0
  21. package/declarations/components/dovetail/sync-status.d.ts +25 -0
  22. package/declarations/components/dovetail/sync-status.d.ts.map +1 -0
  23. package/declarations/components/dovetail/typing.d.ts +17 -0
  24. package/declarations/components/dovetail/typing.d.ts.map +1 -0
  25. package/declarations/editor.d.ts +3 -0
  26. package/declarations/editor.d.ts.map +1 -0
  27. package/declarations/index.d.ts +25 -0
  28. package/declarations/index.d.ts.map +1 -0
  29. package/declarations/live.d.ts +46 -0
  30. package/declarations/live.d.ts.map +1 -0
  31. package/declarations/people.d.ts +51 -0
  32. package/declarations/people.d.ts.map +1 -0
  33. package/declarations/services/dovetail.d.ts +90 -0
  34. package/declarations/services/dovetail.d.ts.map +1 -0
  35. package/declarations/status.d.ts +16 -0
  36. package/declarations/status.d.ts.map +1 -0
  37. package/dist/_app_/components/dovetail/avatar-stack.js +1 -0
  38. package/dist/_app_/components/dovetail/connection-badge.js +1 -0
  39. package/dist/_app_/components/dovetail/dead-letters.js +1 -0
  40. package/dist/_app_/components/dovetail/editor.js +1 -0
  41. package/dist/_app_/components/dovetail/live-cursors.js +1 -0
  42. package/dist/_app_/components/dovetail/presence.js +1 -0
  43. package/dist/_app_/components/dovetail/sync-status.js +1 -0
  44. package/dist/_app_/components/dovetail/typing.js +1 -0
  45. package/dist/_app_/services/dovetail.js +1 -0
  46. package/dist/components/dovetail/avatar-stack.js +52 -0
  47. package/dist/components/dovetail/avatar-stack.js.map +1 -0
  48. package/dist/components/dovetail/connection-badge.js +43 -0
  49. package/dist/components/dovetail/connection-badge.js.map +1 -0
  50. package/dist/components/dovetail/dead-letters.js +47 -0
  51. package/dist/components/dovetail/dead-letters.js.map +1 -0
  52. package/dist/components/dovetail/editor.js +107 -0
  53. package/dist/components/dovetail/editor.js.map +1 -0
  54. package/dist/components/dovetail/live-cursors.js +46 -0
  55. package/dist/components/dovetail/live-cursors.js.map +1 -0
  56. package/dist/components/dovetail/presence.js +35 -0
  57. package/dist/components/dovetail/presence.js.map +1 -0
  58. package/dist/components/dovetail/sync-status.js +39 -0
  59. package/dist/components/dovetail/sync-status.js.map +1 -0
  60. package/dist/components/dovetail/typing.js +23 -0
  61. package/dist/components/dovetail/typing.js.map +1 -0
  62. package/dist/css.d.ts +2 -0
  63. package/dist/css.d.ts.map +1 -0
  64. package/dist/editor.js +2 -0
  65. package/dist/editor.js.map +1 -0
  66. package/dist/index.js +12 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/live-u5cQDrwU.js +93 -0
  69. package/dist/live-u5cQDrwU.js.map +1 -0
  70. package/dist/people-GBjAG7ZI.js +105 -0
  71. package/dist/people-GBjAG7ZI.js.map +1 -0
  72. package/dist/services/dovetail.js +233 -0
  73. package/dist/services/dovetail.js.map +1 -0
  74. package/dist/status-CYJBlnG7.js +59 -0
  75. package/dist/status-CYJBlnG7.js.map +1 -0
  76. package/dist/status-dot-DSQMdQhW.js +31 -0
  77. package/dist/status-dot-DSQMdQhW.js.map +1 -0
  78. package/dist/styles/editor.css +27 -0
  79. package/dist/visually-hidden-BFhJXHGu.js +10 -0
  80. package/dist/visually-hidden-BFhJXHGu.js.map +1 -0
  81. package/package.json +121 -3
@@ -0,0 +1,35 @@
1
+ import Component from '@glimmer/component';
2
+ import { service } from '@ember/service';
3
+ import { precompileTemplate } from '@ember/template-compilation';
4
+ import { setComponentTemplate } from '@ember/component';
5
+ import { g, i } from 'decorator-transforms/runtime';
6
+
7
+ /**
8
+ * Yields the presence of a room (`dovetail.presence(this, room)`), and stops it when it leaves
9
+ * the page. Give the yielded presence to the presence components.
10
+ *
11
+ * <Dovetail::Presence @room="board:1" as |presence|>
12
+ * <Dovetail::AvatarStack @presence={{presence}} />
13
+ * </Dovetail::Presence>
14
+ */
15
+ class Presence extends Component {
16
+ static {
17
+ g(this.prototype, "dovetail", [service('dovetail')]);
18
+ }
19
+ #dovetail = (i(this, "dovetail"), void 0);
20
+ presence;
21
+ constructor(owner, args) {
22
+ super(owner, args);
23
+ // shortcut: the room is read once; render a new <Presence> (for example in an {{#each}}
24
+ // keyed on the room) to change it.
25
+ this.presence = this.dovetail.presence(this, args.room);
26
+ }
27
+ static {
28
+ setComponentTemplate(precompileTemplate("{{yield this.presence}}", {
29
+ strictMode: true
30
+ }), this);
31
+ }
32
+ }
33
+
34
+ export { Presence as default };
35
+ //# sourceMappingURL=presence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence.js","sources":["../../../src/components/dovetail/presence.gts"],"sourcesContent":["import Component from '@glimmer/component'\nimport { service } from '@ember/service'\nimport type Owner from '@ember/owner'\nimport type DovetailService from '../../services/dovetail.ts'\nimport type { LivePresence } from '../../live.ts'\n\nexport interface PresenceSignature {\n Args: {\n /** The room. A change of the room after the first render does nothing. */\n room: string\n }\n Blocks: { default: [LivePresence] }\n}\n\n/**\n * Yields the presence of a room (`dovetail.presence(this, room)`), and stops it when it leaves\n * the page. Give the yielded presence to the presence components.\n *\n * <Dovetail::Presence @room=\"board:1\" as |presence|>\n * <Dovetail::AvatarStack @presence={{presence}} />\n * </Dovetail::Presence>\n */\nexport default class Presence extends Component<PresenceSignature> {\n @service('dovetail') declare dovetail: DovetailService\n\n readonly presence: LivePresence\n\n constructor(owner: Owner, args: PresenceSignature['Args']) {\n super(owner, args)\n // shortcut: the room is read once; render a new <Presence> (for example in an {{#each}}\n // keyed on the room) to change it.\n this.presence = this.dovetail.presence(this, args.room)\n }\n\n <template>{{yield this.presence}}</template>\n}\n"],"names":["Presence","Component","g","prototype","service","i","presence","constructor","owner","args","dovetail","room","setComponentTemplate","precompileTemplate","strictMode"],"mappings":";;;;;;AAcA;;;;;;;;AAQe,MAAMA,QAAA,SAAiBC,SAAA,CAAU;AAAA,EAAA;AAAAC,IAAAA,CAAA,MAAAC,SAAA,EAAA,UAAA,EAAA,CAC7CC,OAAA,CAAQ,UAAA,CAAA,CAAA,CAAA;AAAA;EAAA,SAAA,IAAAC,CAAA,CAAA,IAAA,EAAA,UAAA,CAAA,EAAA,MAAA;EAEAC;AAETC,EAAAA,WAAAA,CAAYC,KAAY,EAAEC,IAA+B,EAAE;AACzD,IAAA,KAAK,CAACD,KAAA,EAAOC,IAAA,CAAA;AACb;AACA;AACA,IAAA,IAAI,CAACH,QAAQ,GAAG,IAAI,CAACI,QAAQ,CAACJ,QAAQ,CAAC,IAAI,EAAEG,IAAA,CAAKE,IAAI,CAAA;AACxD,EAAA;AAEA,EAAA;IAAAC,oBAAA,CAAAC,kBAAA,CAAA,yBAAA,EAAiC;MAAAC,UAAA,EAAA;KAAU,CAAA,EAAV,IAAW,CAAA;AAAD;AAC7C;;"}
@@ -0,0 +1,39 @@
1
+ import Component from '@glimmer/component';
2
+ import { service } from '@ember/service';
3
+ import { s as syncStatus } from '../../status-CYJBlnG7.js';
4
+ import { S as StatusDot } from '../../status-dot-DSQMdQhW.js';
5
+ import { precompileTemplate } from '@ember/template-compilation';
6
+ import { setComponentTemplate } from '@ember/component';
7
+ import { g, i } from 'decorator-transforms/runtime';
8
+
9
+ /**
10
+ * Whether the local changes reached the server: `Saved`, `Syncing 3 changes` or
11
+ * `Offline: 3 changes wait`. It is a live region.
12
+ */
13
+ class SyncStatus extends Component {
14
+ static {
15
+ g(this.prototype, "dovetail", [service('dovetail')]);
16
+ }
17
+ #dovetail = (i(this, "dovetail"), void 0);
18
+ get view() {
19
+ return syncStatus(this.args.status ?? this.dovetail.status, this.args.queued ?? this.dovetail.queued);
20
+ }
21
+ get dot() {
22
+ return {
23
+ saved: 'online',
24
+ syncing: 'reconnecting',
25
+ offline: 'offline'
26
+ }[this.view.state];
27
+ }
28
+ static {
29
+ setComponentTemplate(precompileTemplate("<p role=\"status\" data-test-dovetail-sync-status data-state={{this.view.state}} style=\"display: inline-flex; align-items: center; gap: 0.5rem; margin: 0; font-size: 0.875rem; color: var(--muted-foreground)\" ...attributes>\n <StatusDot @status={{this.dot}} />\n {{this.view.text}}\n</p>", {
30
+ strictMode: true,
31
+ scope: () => ({
32
+ StatusDot
33
+ })
34
+ }), this);
35
+ }
36
+ }
37
+
38
+ export { SyncStatus as default };
39
+ //# sourceMappingURL=sync-status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-status.js","sources":["../../../src/components/dovetail/sync-status.gts"],"sourcesContent":["import Component from '@glimmer/component'\nimport { service } from '@ember/service'\nimport type DovetailService from '../../services/dovetail.ts'\nimport { syncStatus } from '../../status.ts'\nimport type { ConnectionStatus } from '../../status.ts'\nimport StatusDot from '../../-private/status-dot.gts'\n\nexport interface SyncStatusSignature {\n Args: {\n /** The connection status. The default is the status of the `dovetail` service. */\n status?: ConnectionStatus\n /** The count of queued writes. The default is the count of the `dovetail` service. */\n queued?: number\n }\n Element: HTMLParagraphElement\n}\n\n/**\n * Whether the local changes reached the server: `Saved`, `Syncing 3 changes` or\n * `Offline: 3 changes wait`. It is a live region.\n */\nexport default class SyncStatus extends Component<SyncStatusSignature> {\n @service('dovetail') declare dovetail: DovetailService\n\n get view() {\n return syncStatus(\n this.args.status ?? this.dovetail.status,\n this.args.queued ?? this.dovetail.queued,\n )\n }\n\n get dot(): string {\n return { saved: 'online', syncing: 'reconnecting', offline: 'offline' }[this.view.state]\n }\n\n <template>\n <p\n role='status'\n data-test-dovetail-sync-status\n data-state={{this.view.state}}\n style='display: inline-flex; align-items: center; gap: 0.5rem; margin: 0; font-size: 0.875rem; color: var(--muted-foreground)'\n ...attributes\n >\n <StatusDot @status={{this.dot}} />\n {{this.view.text}}\n </p>\n </template>\n}\n"],"names":["SyncStatus","Component","g","prototype","service","i","view","syncStatus","args","status","dovetail","queued","dot","saved","syncing","offline","state","setComponentTemplate","precompileTemplate","strictMode","scope","StatusDot"],"mappings":";;;;;;;;AAiBA;;;;AAIe,MAAMA,UAAA,SAAmBC,SAAA,CAAU;AAAA,EAAA;AAAAC,IAAAA,CAAA,MAAAC,SAAA,EAAA,UAAA,EAAA,CAC/CC,OAAA,CAAQ,UAAA,CAAA,CAAA,CAAA;AAAA;EAAA,SAAA,IAAAC,CAAA,CAAA,IAAA,EAAA,UAAA,CAAA,EAAA,MAAA;EAET,IAAIC,IAAAA,GAAO;IACT,OAAOC,UAAA,CACL,IAAI,CAACC,IAAI,CAACC,MAAM,IAAI,IAAI,CAACC,QAAQ,CAACD,MAAM,EACxC,IAAI,CAACD,IAAI,CAACG,MAAM,IAAI,IAAI,CAACD,QAAQ,CAACC,MAAM,CAAA;AAE5C,EAAA;EAEA,IAAIC,GAAAA,GAAc;IAChB,OAAO;AAAEC,MAAAA,KAAA,EAAO,QAAA;AAAUC,MAAAA,OAAA,EAAS,cAAA;AAAgBC,MAAAA,OAAA,EAAS;AAAU,KAAC,CAAC,IAAI,CAACT,IAAI,CAACU,KAAK,CAAC;AAC1F,EAAA;AAEA,EAAA;IAAAC,oBAAA,CAAAC,kBAAA,CAAA,oSAAA,EAWA;MAAAC,UAAA,EAAA,IAAA;AAAAC,MAAAA,KAAA,EAAAA,OAAA;AAAAC,QAAAA;AAAA,OAAA;KAAU,CAAA,EAAV,IAAW,CAAA;AAAD;AACZ;;"}
@@ -0,0 +1,23 @@
1
+ import Component from '@glimmer/component';
2
+ import { t as typingNames } from '../../people-GBjAG7ZI.js';
3
+ import { t as typingText } from '../../status-CYJBlnG7.js';
4
+ import { precompileTemplate } from '@ember/template-compilation';
5
+ import { setComponentTemplate } from '@ember/component';
6
+
7
+ /**
8
+ * Who types in the room: `Ana is typing`, `Ana and Ben are typing`, `3 people are typing`. It
9
+ * is a live region, and it stays in the page when it is empty, so each change is read.
10
+ */
11
+ class Typing extends Component {
12
+ get text() {
13
+ return typingText(typingNames(this.args.presence.state));
14
+ }
15
+ static {
16
+ setComponentTemplate(precompileTemplate("<p role=\"status\" data-test-dovetail-typing data-state={{if this.text \"typing\" \"idle\"}} style=\"margin: 0; min-block-size: 1.25rem; font-size: 0.875rem; color: var(--muted-foreground)\" ...attributes>{{this.text}}</p>", {
17
+ strictMode: true
18
+ }), this);
19
+ }
20
+ }
21
+
22
+ export { Typing as default };
23
+ //# sourceMappingURL=typing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typing.js","sources":["../../../src/components/dovetail/typing.gts"],"sourcesContent":["import Component from '@glimmer/component'\nimport type { PresenceSource } from '../../live.ts'\nimport { typingNames } from '../../people.ts'\nimport { typingText } from '../../status.ts'\n\nexport interface TypingSignature {\n Args: {\n /** The presence of the room. Call `presence.typing()` at each keystroke of the local user. */\n presence: PresenceSource\n }\n Element: HTMLParagraphElement\n}\n\n/**\n * Who types in the room: `Ana is typing`, `Ana and Ben are typing`, `3 people are typing`. It\n * is a live region, and it stays in the page when it is empty, so each change is read.\n */\nexport default class Typing extends Component<TypingSignature> {\n get text(): string {\n return typingText(typingNames(this.args.presence.state))\n }\n\n <template>\n <p\n role='status'\n data-test-dovetail-typing\n data-state={{if this.text 'typing' 'idle'}}\n style='margin: 0; min-block-size: 1.25rem; font-size: 0.875rem; color: var(--muted-foreground)'\n ...attributes\n >{{this.text}}</p>\n </template>\n}\n"],"names":["Typing","Component","text","typingText","typingNames","args","presence","state","setComponentTemplate","precompileTemplate","strictMode"],"mappings":";;;;;;AAaA;;;;AAIe,MAAMA,MAAA,SAAeC,SAAA,CAAU;EAC5C,IAAIC,IAAAA,GAAe;AACjB,IAAA,OAAOC,UAAA,CAAWC,YAAY,IAAI,CAACC,IAAI,CAACC,QAAQ,CAACC,KAAK,CAAA,CAAA;AACxD,EAAA;AAEA,EAAA;IAAAC,oBAAA,CAAAC,kBAAA,CAAA,gOAAA,EAQA;MAAAC,UAAA,EAAA;KAAU,CAAA,EAAV,IAAW,CAAA;AAAD;AACZ;;"}
package/dist/css.d.ts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=css.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"css.d.ts","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/dist/editor.js ADDED
@@ -0,0 +1,2 @@
1
+ export { default as Editor } from './components/dovetail/editor.js';
2
+ //# sourceMappingURL=editor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"editor.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export { default as DovetailService } from './services/dovetail.js';
2
+ export { a as LiveDoc, L as LivePresence } from './live-u5cQDrwU.js';
3
+ export { c as connectionLabel, a as connectionStatus, s as syncStatus, t as typingText } from './status-CYJBlnG7.js';
4
+ export { default as ConnectionBadge } from './components/dovetail/connection-badge.js';
5
+ export { default as AvatarStack } from './components/dovetail/avatar-stack.js';
6
+ export { default as DeadLetters } from './components/dovetail/dead-letters.js';
7
+ export { default as LiveCursors } from './components/dovetail/live-cursors.js';
8
+ export { default as Presence } from './components/dovetail/presence.js';
9
+ export { default as SyncStatus } from './components/dovetail/sync-status.js';
10
+ export { default as Typing } from './components/dovetail/typing.js';
11
+ export { d as describeError, a as describeWrite, i as initials, b as isSafeAvatarUrl, p as people, r as relativePointer, s as safeColor, t as typingNames } from './people-GBjAG7ZI.js';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
@@ -0,0 +1,93 @@
1
+ import { tracked } from '@glimmer/tracking';
2
+ import { g, i } from 'decorator-transforms/runtime';
3
+
4
+ // Tracked wrappers of the core objects of a room. The core has no framework code (ADR 0011), so
5
+ // these copy each change of its state into a tracked field.
6
+ /** The presence of a room, with a tracked `state`. */
7
+ class LivePresence {
8
+ static {
9
+ g(this.prototype, "state", [tracked]);
10
+ }
11
+ #state = (i(this, "state"), void 0);
12
+ room;
13
+ presence;
14
+ #stop;
15
+ constructor(room, presence) {
16
+ this.room = room;
17
+ this.presence = presence;
18
+ this.state = presence.state;
19
+ this.#stop = presence.subscribe(state => this.state = state);
20
+ }
21
+ activity() {
22
+ this.presence.activity();
23
+ }
24
+ setPointer(pointer) {
25
+ this.presence.setPointer(pointer);
26
+ }
27
+ typing() {
28
+ this.presence.typing();
29
+ }
30
+ stopTyping() {
31
+ this.presence.stopTyping();
32
+ }
33
+ set(fields) {
34
+ this.presence.set(fields);
35
+ }
36
+ destroy() {
37
+ this.#stop();
38
+ this.presence.destroy();
39
+ }
40
+ }
41
+
42
+ /** A CRDT document of a room, synced by a `DocSession`, with a tracked `synced`. */
43
+ class LiveDoc {
44
+ static {
45
+ g(this.prototype, "synced", [tracked], function () {
46
+ return false;
47
+ });
48
+ }
49
+ #synced = (i(this, "synced"), void 0);
50
+ static {
51
+ g(this.prototype, "started", [tracked], function () {
52
+ return false;
53
+ });
54
+ }
55
+ #started = (i(this, "started"), void 0);
56
+ /**
57
+ * True when the session started: the stored updates are in the document. A local update
58
+ * before the start is not lost: it waits in the storage, and the session sends it.
59
+ */
60
+ /** The session, when it started. */
61
+ session;
62
+ /** Resolves when the session started. */
63
+ ready;
64
+ room;
65
+ handle;
66
+ #destroyed;
67
+ constructor(room, handle, makeSession) {
68
+ this.room = room;
69
+ this.handle = handle;
70
+ this.ready = this.#start(makeSession);
71
+ }
72
+ async #start(makeSession) {
73
+ const session = await makeSession();
74
+ if (this.#destroyed) return;
75
+ this.session = session;
76
+ session.onSyncChange(synced => this.synced = synced);
77
+ await session.start();
78
+ this.started = true;
79
+ }
80
+
81
+ /** Stops the session and destroys the document. A second call gives the same promise. */
82
+ destroy() {
83
+ this.#destroyed ??= (async () => {
84
+ await this.ready.catch(() => {});
85
+ await this.session?.destroy();
86
+ this.handle.destroy();
87
+ })();
88
+ return this.#destroyed;
89
+ }
90
+ }
91
+
92
+ export { LivePresence as L, LiveDoc as a };
93
+ //# sourceMappingURL=live-u5cQDrwU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-u5cQDrwU.js","sources":["../src/live.ts"],"sourcesContent":["// Tracked wrappers of the core objects of a room. The core has no framework code (ADR 0011), so\n// these copy each change of its state into a tracked field.\nimport { tracked } from '@glimmer/tracking'\nimport type { DocSession, PresencePointer, PresenceRoom, PresenceState } from '@dovetail-ts/core'\nimport type { DocHandle, JsonObject } from '@dovetail-ts/crdt'\n\n/**\n * What the presence components read: a state, and the calls for the local user. A\n * `LivePresence` has this shape. A story can give a plain object.\n */\nexport interface PresenceSource {\n readonly state: PresenceState\n activity?(): void\n setPointer?(pointer: PresencePointer | null): void\n typing?(): void\n}\n\n/** The presence of a room, with a tracked `state`. */\nexport class LivePresence implements PresenceSource {\n @tracked state: PresenceState\n readonly room: string\n readonly presence: PresenceRoom\n readonly #stop: () => void\n\n constructor(room: string, presence: PresenceRoom) {\n this.room = room\n this.presence = presence\n this.state = presence.state\n this.#stop = presence.subscribe(state => (this.state = state))\n }\n\n activity(): void {\n this.presence.activity()\n }\n\n setPointer(pointer: PresencePointer | null): void {\n this.presence.setPointer(pointer)\n }\n\n typing(): void {\n this.presence.typing()\n }\n\n stopTyping(): void {\n this.presence.stopTyping()\n }\n\n set(fields: JsonObject): void {\n this.presence.set(fields)\n }\n\n destroy(): void {\n this.#stop()\n this.presence.destroy()\n }\n}\n\n/** A CRDT document of a room, synced by a `DocSession`, with a tracked `synced`. */\nexport class LiveDoc {\n @tracked synced = false\n /**\n * True when the session started: the stored updates are in the document. A local update\n * before the start is not lost: it waits in the storage, and the session sends it.\n */\n @tracked started = false\n /** The session, when it started. */\n session: DocSession | undefined\n /** Resolves when the session started. */\n readonly ready: Promise<void>\n readonly room: string\n readonly handle: DocHandle\n #destroyed: Promise<void> | undefined\n\n constructor(room: string, handle: DocHandle, makeSession: () => Promise<DocSession>) {\n this.room = room\n this.handle = handle\n this.ready = this.#start(makeSession)\n }\n\n async #start(makeSession: () => Promise<DocSession>): Promise<void> {\n const session = await makeSession()\n if (this.#destroyed) return\n this.session = session\n session.onSyncChange(synced => (this.synced = synced))\n await session.start()\n this.started = true\n }\n\n /** Stops the session and destroys the document. A second call gives the same promise. */\n destroy(): Promise<void> {\n this.#destroyed ??= (async () => {\n await this.ready.catch(() => {})\n await this.session?.destroy()\n this.handle.destroy()\n })()\n return this.#destroyed\n }\n}\n"],"names":["LivePresence","g","prototype","tracked","i","room","presence","constructor","state","subscribe","activity","setPointer","pointer","typing","stopTyping","set","fields","destroy","LiveDoc","session","ready","handle","makeSession","#start","onSyncChange","synced","start","started","catch"],"mappings":";;;AAAA;AACA;AAgBA;AACO,MAAMA,YAAY,CAA2B;AAAA,EAAA;IAAAC,CAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,OAAA,EAAA,CACjDC,OAAO,CAAA,CAAA;AAAA;EAAA,MAAA,IAAAC,CAAA,CAAA,IAAA,EAAA,OAAA,CAAA,EAAA,MAAA;EACCC,IAAI;EACJC,QAAQ;AACR,EAAA,KAAK;AAEdC,EAAAA,WAAWA,CAACF,IAAY,EAAEC,QAAsB,EAAE;IAChD,IAAI,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OAAW,KAAK;AAAA,IAAA,CAAA,CAAA;AAAA;EAAA,QAAA,IAAAC,CAAA,CAAA,IAAA,EAAA,SAAA,CAAA,EAAA,MAAA;AAJxB;AACF;AACA;AACA;AAEE;EACAe,OAAO;AACP;EACSC,KAAK;EACLf,IAAI;EACJgB,MAAM;AACf,EAAA,UAAU;AAEVd,EAAAA,WAAWA,CAACF,IAAY,EAAEgB,MAAiB,EAAEC,WAAsC,EAAE;IACnF,IAAI,CAACjB,IAAI,GAAGA,IAAI;IAChB,IAAI,CAACgB,MAAM,GAAGA,MAAM;IACpB,IAAI,CAACD,KAAK,GAAG,IAAI,CAAC,MAAM,CAACE,WAAW,CAAC;AACvC,EAAA;AAEA,EAAA,MAAM,MAAMC,CAACD,WAAsC,EAAiB;AAClE,IAAA,MAAMH,OAAO,GAAG,MAAMG,WAAW,EAAE;AACnC,IAAA,IAAI,IAAI,CAAC,UAAU,EAAE;IACrB,IAAI,CAACH,OAAO,GAAGA,OAAO;IACtBA,OAAO,CAACK,YAAY,CAACC,MAAM,IAAK,IAAI,CAACA,MAAM,GAAGA,MAAO,CAAC;AACtD,IAAA,MAAMN,OAAO,CAACO,KAAK,EAAE;IACrB,IAAI,CAACC,OAAO,GAAG,IAAI;AACrB,EAAA;;AAEA;AACAV,EAAAA,OAAOA,GAAkB;AACvB,IAAA,IAAI,CAAC,UAAU,KAAK,CAAC,YAAY;MAC/B,MAAM,IAAI,CAACG,KAAK,CAACQ,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;AAChC,MAAA,MAAM,IAAI,CAACT,OAAO,EAAEF,OAAO,EAAE;AAC7B,MAAA,IAAI,CAACI,MAAM,CAACJ,OAAO,EAAE;AACvB,IAAA,CAAC,GAAG;IACJ,OAAO,IAAI,CAAC,UAAU;AACxB,EAAA;AACF;;"}
@@ -0,0 +1,105 @@
1
+ import { isHexColor } from '@dovetail-ts/core';
2
+
3
+ // The data of the presence and dead-letter components, as plain functions. Remote states are
4
+ // not trusted: `readPresence` of core checked them, and the components show names as text.
5
+
6
+ /** One person in a room. A user with more than one client (tabs) is one person. */
7
+
8
+ /** The color of a pointer when the color of the peer is not a hex color. */
9
+ const FALLBACK_COLOR = '#6b7280';
10
+
11
+ /**
12
+ * `color` when it is a hex color (`#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, the rule of
13
+ * `isHexColor` of core), or else the fallback. A remote color goes into a style, so a value such
14
+ * as `url(...)` must not pass.
15
+ */
16
+ function safeColor(color) {
17
+ return isHexColor(color) ? color : FALLBACK_COLOR;
18
+ }
19
+
20
+ /**
21
+ * The default policy of the avatar URLs of the peers: an `https:` URL only. A relative URL
22
+ * (for example `/ann.png`) resolves against the page, so it passes on an `https:` page.
23
+ */
24
+ function isSafeAvatarUrl(url) {
25
+ try {
26
+ return new URL(url, globalThis.location?.href).protocol === 'https:';
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
31
+
32
+ /** The people that the avatar stack shows, and the people of the overflow count. */
33
+ function people(state, options) {
34
+ const allow = options.allowAvatarUrl ?? isSafeAvatarUrl;
35
+ const byId = new Map();
36
+ const add = (presence, self) => {
37
+ const {
38
+ id,
39
+ name,
40
+ color,
41
+ avatarUrl
42
+ } = presence.user;
43
+ const known = byId.get(id);
44
+ if (known) {
45
+ if (presence.status === 'online') known.status = 'online';
46
+ return;
47
+ }
48
+ byId.set(id, {
49
+ id,
50
+ name,
51
+ color: safeColor(color),
52
+ avatarUrl: avatarUrl !== undefined && allow(avatarUrl) ? avatarUrl : undefined,
53
+ status: presence.status,
54
+ self
55
+ });
56
+ };
57
+ if (options.includeSelf) add(state.self, true);
58
+ for (const peer of state.peers) {
59
+ if (peer.user.id !== state.self.user.id || options.includeSelf) add(peer, false);
60
+ }
61
+ const all = [...byId.values()];
62
+ return {
63
+ visible: all.slice(0, options.max),
64
+ hidden: all.slice(options.max)
65
+ };
66
+ }
67
+
68
+ /** The names of the peers that type, each user once. */
69
+ function typingNames(state) {
70
+ const names = new Map();
71
+ for (const peer of state.peers) if (peer.typing) names.set(peer.user.id, peer.user.name);
72
+ return [...names.values()];
73
+ }
74
+
75
+ /** The initials of a name: the first letter of the first two words. */
76
+ function initials(name) {
77
+ const letters = name.trim().split(/\s+/).filter(Boolean).slice(0, 2).map(word => word[0]?.toUpperCase()).join('');
78
+ return letters || '?';
79
+ }
80
+
81
+ /** A pointer position as a fraction (0 to 1) of a box, so clients with other sizes agree. */
82
+ function relativePointer(clientX, clientY, box) {
83
+ const fraction = (value, size) => size > 0 ? Math.min(1, Math.max(0, value / size)) : 0;
84
+ return {
85
+ x: fraction(clientX - box.left, box.width),
86
+ y: fraction(clientY - box.top, box.height)
87
+ };
88
+ }
89
+
90
+ /** A short name of a write: `Save note 1`, `Delete note 2`. */
91
+ function describeWrite(op) {
92
+ if (op.op === 'delete') return `Delete ${op.ref.type} ${op.ref.id}`;
93
+ const data = op.document.data;
94
+ if (Array.isArray(data)) return `Save ${data.length} records`;
95
+ return data ? `Save ${data.type} ${data.id}` : 'Save';
96
+ }
97
+
98
+ /** Why the server refused a write: the detail or the title of the first error, or the status. */
99
+ function describeError(status, errors) {
100
+ const first = errors[0];
101
+ return first?.detail ?? first?.title ?? `The server refused the change (${status})`;
102
+ }
103
+
104
+ export { describeWrite as a, isSafeAvatarUrl as b, describeError as d, initials as i, people as p, relativePointer as r, safeColor as s, typingNames as t };
105
+ //# sourceMappingURL=people-GBjAG7ZI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"people-GBjAG7ZI.js","sources":["../src/people.ts"],"sourcesContent":["// The data of the presence and dead-letter components, as plain functions. Remote states are\n// not trusted: `readPresence` of core checked them, and the components show names as text.\nimport { isHexColor } from '@dovetail-ts/core'\nimport type { PresencePointer, PresenceState, PresenceStatus } from '@dovetail-ts/core'\nimport type { JsonApiError, StoreOp } from '@dovetail-ts/protocol'\n\n/** One person in a room. A user with more than one client (tabs) is one person. */\nexport interface Person {\n id: string\n name: string\n color: string\n avatarUrl: string | undefined\n status: PresenceStatus\n /** True for the local user. */\n self: boolean\n}\n\n/** The color of a pointer when the color of the peer is not a hex color. */\nexport const FALLBACK_COLOR = '#6b7280'\n\n/**\n * `color` when it is a hex color (`#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, the rule of\n * `isHexColor` of core), or else the fallback. A remote color goes into a style, so a value such\n * as `url(...)` must not pass.\n */\nexport function safeColor(color: unknown): string {\n return isHexColor(color) ? color : FALLBACK_COLOR\n}\n\n/**\n * The default policy of the avatar URLs of the peers: an `https:` URL only. A relative URL\n * (for example `/ann.png`) resolves against the page, so it passes on an `https:` page.\n */\nexport function isSafeAvatarUrl(url: string): boolean {\n try {\n return new URL(url, globalThis.location?.href).protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/** The people that the avatar stack shows, and the people of the overflow count. */\nexport function people(\n state: PresenceState,\n options: {\n max: number\n includeSelf: boolean\n /** True for an avatar URL that the page can load. The default is `isSafeAvatarUrl`. */\n allowAvatarUrl?: (url: string) => boolean\n },\n): { visible: Person[]; hidden: Person[] } {\n const allow = options.allowAvatarUrl ?? isSafeAvatarUrl\n const byId = new Map<string, Person>()\n const add = (presence: PresenceState['self'], self: boolean) => {\n const { id, name, color, avatarUrl } = presence.user\n const known = byId.get(id)\n if (known) {\n if (presence.status === 'online') known.status = 'online'\n return\n }\n byId.set(id, {\n id,\n name,\n color: safeColor(color),\n avatarUrl: avatarUrl !== undefined && allow(avatarUrl) ? avatarUrl : undefined,\n status: presence.status,\n self,\n })\n }\n if (options.includeSelf) add(state.self, true)\n for (const peer of state.peers) {\n if (peer.user.id !== state.self.user.id || options.includeSelf) add(peer, false)\n }\n const all = [...byId.values()]\n return { visible: all.slice(0, options.max), hidden: all.slice(options.max) }\n}\n\n/** The names of the peers that type, each user once. */\nexport function typingNames(state: PresenceState): string[] {\n const names = new Map<string, string>()\n for (const peer of state.peers) if (peer.typing) names.set(peer.user.id, peer.user.name)\n return [...names.values()]\n}\n\n/** The initials of a name: the first letter of the first two words. */\nexport function initials(name: string): string {\n const letters = name\n .trim()\n .split(/\\s+/)\n .filter(Boolean)\n .slice(0, 2)\n .map(word => word[0]?.toUpperCase())\n .join('')\n return letters || '?'\n}\n\n/** A pointer position as a fraction (0 to 1) of a box, so clients with other sizes agree. */\nexport function relativePointer(\n clientX: number,\n clientY: number,\n box: { left: number; top: number; width: number; height: number },\n): PresencePointer {\n const fraction = (value: number, size: number) =>\n size > 0 ? Math.min(1, Math.max(0, value / size)) : 0\n return { x: fraction(clientX - box.left, box.width), y: fraction(clientY - box.top, box.height) }\n}\n\n/** A short name of a write: `Save note 1`, `Delete note 2`. */\nexport function describeWrite(op: StoreOp): string {\n if (op.op === 'delete') return `Delete ${op.ref.type} ${op.ref.id}`\n const data = op.document.data\n if (Array.isArray(data)) return `Save ${data.length} records`\n return data ? `Save ${data.type} ${data.id}` : 'Save'\n}\n\n/** Why the server refused a write: the detail or the title of the first error, or the status. */\nexport function describeError(status: number, errors: readonly JsonApiError[]): string {\n const first = errors[0]\n return first?.detail ?? first?.title ?? `The server refused the change (${status})`\n}\n"],"names":["FALLBACK_COLOR","safeColor","color","isHexColor","isSafeAvatarUrl","url","URL","globalThis","location","href","protocol","people","state","options","allow","allowAvatarUrl","byId","Map","add","presence","self","id","name","avatarUrl","user","known","get","status","set","undefined","includeSelf","peer","peers","all","values","visible","slice","max","hidden","typingNames","names","typing","initials","letters","trim","split","filter","Boolean","map","word","toUpperCase","join","relativePointer","clientX","clientY","box","fraction","value","size","Math","min","x","left","width","y","top","height","describeWrite","op","ref","type","data","document","Array","isArray","length","describeError","errors","first","detail","title"],"mappings":";;AAAA;AACA;;AAKA;;AAWA;AACO,MAAMA,cAAc,GAAG,SAAS;;AAEvC;AACA;AACA;AACA;AACA;AACO,SAASC,SAASA,CAACC,KAAc,EAAU;AAChD,EAAA,OAAOC,UAAU,CAACD,KAAK,CAAC,GAAGA,KAAK,GAAGF,cAAc;AACnD;;AAEA;AACA;AACA;AACA;AACO,SAASI,eAAeA,CAACC,GAAW,EAAW;EACpD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mer/tracking';
3
+ import { registerDestructor } from '@ember/destroyable';
4
+ import { waitForPromise } from '@ember/test-waiters';
5
+ import { Connection, SyncClient, WriteQueue, openDovetailDB, PresenceRoom, IndexedDBDocStorage, DocSession } from '@dovetail-ts/core';
6
+ import { a as connectionStatus } from '../status-CYJBlnG7.js';
7
+ import { L as LivePresence, a as LiveDoc } from '../live-u5cQDrwU.js';
8
+ import { g, i } from 'decorator-transforms/runtime';
9
+
10
+ // The `dovetail` service: one connection and one sync client for the app, with tracked state
11
+ // for the components, and the live objects of a room (presence, store feed, documents) that
12
+ // stop when their owner is destroyed.
13
+ /** Counts the owners of a shared object, and calls `release` when the last owner goes. */
14
+ function hold(map, key, owner, make, release) {
15
+ let entry = map.get(key);
16
+ if (!entry) {
17
+ entry = {
18
+ value: make(),
19
+ count: 0
20
+ };
21
+ map.set(key, entry);
22
+ }
23
+ entry.count++;
24
+ const held = entry;
25
+ registerDestructor(owner, () => {
26
+ if (--held.count > 0) return;
27
+ map.delete(key);
28
+ release(held.value);
29
+ });
30
+ return held.value;
31
+ }
32
+ class DovetailService extends Service {
33
+ static {
34
+ g(this.prototype, "connectionState", [tracked], function () {
35
+ return 'idle';
36
+ });
37
+ }
38
+ #connectionState = (i(this, "connectionState"), void 0);
39
+ /** The state of the connection: `idle`, `connecting`, `open`, `reconnecting`, `offline` or `closed`. */
40
+ static {
41
+ g(this.prototype, "online", [tracked], function () {
42
+ return true;
43
+ });
44
+ }
45
+ #online = (i(this, "online"), void 0);
46
+ /** True when the device is online. */
47
+ static {
48
+ g(this.prototype, "queued", [tracked], function () {
49
+ return 0;
50
+ });
51
+ }
52
+ #queued = (i(this, "queued"), void 0);
53
+ /** The number of writes in the queue. */
54
+ static {
55
+ g(this.prototype, "deadLetters", [tracked], function () {
56
+ return [];
57
+ });
58
+ }
59
+ #deadLetters = (i(this, "deadLetters"), void 0);
60
+ /** The writes that the server rejected. */
61
+ static {
62
+ g(this.prototype, "errors", [tracked], function () {
63
+ return [];
64
+ });
65
+ }
66
+ #errors = (i(this, "errors"), void 0);
67
+ /** The rejected local changes of this tab, which rolled back. */
68
+ connection;
69
+ sync;
70
+ #config;
71
+ #db;
72
+ #stops = [];
73
+ #presences = new Map();
74
+ #docs = new Map();
75
+ /** The documents that stop. The database closes after them. */
76
+ #closing = new Set();
77
+
78
+ /** The status that the components show: `online`, `connecting`, `reconnecting` or `offline`. */
79
+ get status() {
80
+ return connectionStatus(this.connectionState, this.online);
81
+ }
82
+
83
+ /** The local user. */
84
+ get user() {
85
+ return this.#configured().user;
86
+ }
87
+
88
+ /**
89
+ * Makes the connection and connects, then starts the sync client when there is a `sink`.
90
+ * Call it once, for example in the application route.
91
+ */
92
+ async configure(config) {
93
+ if (this.#config) throw new Error('Dovetail: the service is already configured.');
94
+ this.#config = config;
95
+ const connection = new Connection({
96
+ ...config.connection,
97
+ transport: config.transport,
98
+ ...(config.getToken ? {
99
+ getToken: config.getToken
100
+ } : {})
101
+ });
102
+ this.connection = connection;
103
+ const read = () => {
104
+ this.connectionState = connection.state.value;
105
+ this.online = connection.isOnline;
106
+ };
107
+ this.#stops.push(connection.onStateChange(read));
108
+ read();
109
+ connection.connect();
110
+ if (!config.sink) return;
111
+ const sync = new SyncClient({
112
+ ...config.sync,
113
+ connection,
114
+ sink: config.sink,
115
+ queue: config.queue ?? new WriteQueue(await this.#database())
116
+ });
117
+ this.sync = sync;
118
+ this.#stops.push(sync.onChange(state => {
119
+ this.queued = state.queued;
120
+ this.deadLetters = state.deadLetters;
121
+ this.errors = state.errors;
122
+ }));
123
+ await sync.start();
124
+ }
125
+
126
+ /** Applies `op` at once, and puts it in the queue for `room`. Resolves with the id of the write. */
127
+ write(room, op) {
128
+ return this.#sync().write(room, op);
129
+ }
130
+
131
+ /** Sends a dead letter again. */
132
+ retry(id) {
133
+ return this.#sync().retry(id);
134
+ }
135
+
136
+ /** Removes a dead letter and the writes that depend on it. Their changes roll back. */
137
+ discard(id) {
138
+ return this.#sync().discard(id);
139
+ }
140
+
141
+ /** Puts the store feed of `room` in the store until `owner` is destroyed. */
142
+ subscribe(owner, room) {
143
+ registerDestructor(owner, this.#sync().subscribe(room));
144
+ }
145
+
146
+ /**
147
+ * The presence of `room` until `owner` is destroyed. All owners of a room share one presence
148
+ * room. When a `doc()` of the room exists, the presence uses the awareness of its document,
149
+ * so call `doc()` first for a room with a document.
150
+ */
151
+ presence(owner, room) {
152
+ return hold(this.#presences, room, owner, () => {
153
+ const config = this.#configured();
154
+ const doc = [...this.#docs.values()].find(entry => entry.value.room === room)?.value;
155
+ const options = doc ? {
156
+ ...config.presence,
157
+ user: config.user,
158
+ awareness: doc.handle.awareness
159
+ } : {
160
+ ...config.presence,
161
+ user: config.user,
162
+ connection: this.#connection(),
163
+ room
164
+ };
165
+ return new LivePresence(room, new PresenceRoom(options));
166
+ }, live => live.destroy());
167
+ }
168
+
169
+ /**
170
+ * A CRDT document of `room` (`engine.create()`), synced by a `DocSession` until `owner` is
171
+ * destroyed. The local updates wait in `docStorage` until the server has them.
172
+ */
173
+ doc(owner, room, engine, options = {}) {
174
+ const name = options.doc ?? 'body';
175
+ return hold(this.#docs, `${room}\n${name}`, owner, () => {
176
+ const config = this.#configured();
177
+ const connection = this.#connection();
178
+ const handle = engine.create();
179
+ // The session listens to the document at once, so an edit before the database opens
180
+ // waits in the storage and is not lost.
181
+ const storage = config.docStorage ?? new IndexedDBDocStorage(this.#database());
182
+ const session = new DocSession({
183
+ connection,
184
+ room,
185
+ doc: name,
186
+ handle,
187
+ storage
188
+ });
189
+ return new LiveDoc(room, handle, () => Promise.resolve(session));
190
+ }, live => {
191
+ const closing = live.destroy();
192
+ this.#closing.add(closing);
193
+ void closing.finally(() => this.#closing.delete(closing));
194
+ });
195
+ }
196
+ willDestroy() {
197
+ super.willDestroy();
198
+ for (const stop of this.#stops.splice(0)) stop();
199
+ const sync = this.sync;
200
+ const connection = this.connection;
201
+ const db = this.#db;
202
+ // `stop()` waits for the queue reads, and the documents for their storage writes, so the
203
+ // database can close after them.
204
+ void waitForPromise((async () => {
205
+ await sync?.stop();
206
+ for (const {
207
+ value
208
+ } of this.#docs.values()) this.#closing.add(value.destroy());
209
+ await Promise.allSettled([...this.#closing]);
210
+ connection?.close();
211
+ (await db)?.close();
212
+ })());
213
+ }
214
+ #configured() {
215
+ if (!this.#config) throw new Error('Dovetail: call `configure()` on the service first.');
216
+ return this.#config;
217
+ }
218
+ #connection() {
219
+ if (!this.connection) throw new Error('Dovetail: call `configure()` on the service first.');
220
+ return this.connection;
221
+ }
222
+ #sync() {
223
+ if (!this.sync) throw new Error('Dovetail: give a `sink` to `configure()` to write.');
224
+ return this.sync;
225
+ }
226
+ #database() {
227
+ this.#db ??= openDovetailDB(this.#config?.dbName);
228
+ return this.#db;
229
+ }
230
+ }
231
+
232
+ export { DovetailService as default };
233
+ //# sourceMappingURL=dovetail.js.map