@dxos/react-ui-attention 0.9.0 → 0.9.1-main.c7dcc2e112

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 (76) hide show
  1. package/dist/lib/browser/chunk-4HYAJ4IO.mjs +434 -0
  2. package/dist/lib/browser/chunk-4HYAJ4IO.mjs.map +7 -0
  3. package/dist/lib/browser/{chunk-I4VO2RQM.mjs → chunk-KCQFVRZ6.mjs} +88 -112
  4. package/dist/lib/browser/chunk-KCQFVRZ6.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +29 -11
  6. package/dist/lib/browser/index.mjs.map +1 -1
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +4 -4
  9. package/dist/lib/browser/testing/index.mjs.map +2 -2
  10. package/dist/lib/browser/types/index.mjs +19 -5
  11. package/dist/lib/node-esm/{chunk-ZTUVSH4P.mjs → chunk-5JUZQDCR.mjs} +88 -112
  12. package/dist/lib/node-esm/chunk-5JUZQDCR.mjs.map +7 -0
  13. package/dist/lib/node-esm/chunk-HWN7KJDX.mjs +436 -0
  14. package/dist/lib/node-esm/chunk-HWN7KJDX.mjs.map +7 -0
  15. package/dist/lib/node-esm/index.mjs +29 -11
  16. package/dist/lib/node-esm/index.mjs.map +1 -1
  17. package/dist/lib/node-esm/meta.json +1 -1
  18. package/dist/lib/node-esm/testing/index.mjs +4 -4
  19. package/dist/lib/node-esm/testing/index.mjs.map +2 -2
  20. package/dist/lib/node-esm/types/index.mjs +19 -5
  21. package/dist/types/src/components/ViewStateProvider/ViewStateProvider.d.ts +29 -0
  22. package/dist/types/src/components/ViewStateProvider/ViewStateProvider.d.ts.map +1 -0
  23. package/dist/types/src/components/ViewStateProvider/ViewStateProvider.test.d.ts +2 -0
  24. package/dist/types/src/components/ViewStateProvider/ViewStateProvider.test.d.ts.map +1 -0
  25. package/dist/types/src/components/ViewStateProvider/index.d.ts +2 -0
  26. package/dist/types/src/components/ViewStateProvider/index.d.ts.map +1 -0
  27. package/dist/types/src/components/index.d.ts +1 -1
  28. package/dist/types/src/index.d.ts +1 -0
  29. package/dist/types/src/index.d.ts.map +1 -1
  30. package/dist/types/src/selection.d.ts +10 -40
  31. package/dist/types/src/selection.d.ts.map +1 -1
  32. package/dist/types/src/selection.test.d.ts +2 -0
  33. package/dist/types/src/selection.test.d.ts.map +1 -0
  34. package/dist/types/src/types/index.d.ts +1 -0
  35. package/dist/types/src/types/index.d.ts.map +1 -1
  36. package/dist/types/src/view-state/backends.d.ts +24 -0
  37. package/dist/types/src/view-state/backends.d.ts.map +1 -0
  38. package/dist/types/src/view-state/backends.test.d.ts +2 -0
  39. package/dist/types/src/view-state/backends.test.d.ts.map +1 -0
  40. package/dist/types/src/view-state/index.d.ts +3 -0
  41. package/dist/types/src/view-state/index.d.ts.map +1 -0
  42. package/dist/types/src/view-state/view-state.d.ts +54 -0
  43. package/dist/types/src/view-state/view-state.d.ts.map +1 -0
  44. package/dist/types/src/view-state/view-state.test.d.ts +2 -0
  45. package/dist/types/src/view-state/view-state.test.d.ts.map +1 -0
  46. package/dist/types/src/vitest-setup.d.ts +2 -0
  47. package/dist/types/src/vitest-setup.d.ts.map +1 -0
  48. package/dist/types/tsconfig.tsbuildinfo +1 -1
  49. package/package.json +15 -13
  50. package/src/components/ViewStateProvider/ViewStateProvider.test.tsx +45 -0
  51. package/src/components/ViewStateProvider/ViewStateProvider.tsx +123 -0
  52. package/src/components/ViewStateProvider/index.ts +5 -0
  53. package/src/components/index.ts +1 -1
  54. package/src/index.ts +1 -0
  55. package/src/selection.test.ts +67 -0
  56. package/src/selection.ts +39 -169
  57. package/src/testing/decorators/withAttention.ts +2 -2
  58. package/src/types/index.ts +1 -0
  59. package/src/view-state/backends.test.ts +104 -0
  60. package/src/view-state/backends.ts +145 -0
  61. package/src/view-state/index.ts +6 -0
  62. package/src/view-state/view-state.test.ts +54 -0
  63. package/src/view-state/view-state.ts +91 -0
  64. package/src/vitest-setup.ts +6 -0
  65. package/dist/lib/browser/chunk-D2BLVJ6Z.mjs +0 -421
  66. package/dist/lib/browser/chunk-D2BLVJ6Z.mjs.map +0 -7
  67. package/dist/lib/browser/chunk-I4VO2RQM.mjs.map +0 -7
  68. package/dist/lib/node-esm/chunk-6INLBC62.mjs +0 -423
  69. package/dist/lib/node-esm/chunk-6INLBC62.mjs.map +0 -7
  70. package/dist/lib/node-esm/chunk-ZTUVSH4P.mjs.map +0 -7
  71. package/dist/types/src/components/SelectionProvider/SelectionProvider.d.ts +0 -28
  72. package/dist/types/src/components/SelectionProvider/SelectionProvider.d.ts.map +0 -1
  73. package/dist/types/src/components/SelectionProvider/index.d.ts +0 -2
  74. package/dist/types/src/components/SelectionProvider/index.d.ts.map +0 -1
  75. package/src/components/SelectionProvider/SelectionProvider.tsx +0 -174
  76. package/src/components/SelectionProvider/index.ts +0 -5
@@ -0,0 +1,436 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+
3
+ // src/attention.ts
4
+ import { Atom } from "@effect-atom/atom-react";
5
+ var AttentionManager = class {
6
+ _registry;
7
+ _map = /* @__PURE__ */ new Map();
8
+ _currentAtom;
9
+ constructor(_registry, initial = []) {
10
+ this._registry = _registry;
11
+ this._currentAtom = Atom.make([]).pipe(Atom.keepAlive);
12
+ if (initial.length > 0) {
13
+ this.update(initial);
14
+ }
15
+ }
16
+ /**
17
+ * Atom for the currently attended element IDs.
18
+ */
19
+ get current() {
20
+ return this._currentAtom;
21
+ }
22
+ /**
23
+ * Gets the currently attended element IDs.
24
+ */
25
+ getCurrent() {
26
+ return this._registry.get(this._currentAtom);
27
+ }
28
+ /**
29
+ * Subscribe to changes in the current attention IDs.
30
+ */
31
+ subscribeCurrent(cb) {
32
+ this._registry.get(this._currentAtom);
33
+ return this._registry.subscribe(this._currentAtom, () => {
34
+ cb(this._registry.get(this._currentAtom));
35
+ });
36
+ }
37
+ /**
38
+ * All tracked qualified IDs.
39
+ */
40
+ keys() {
41
+ return Array.from(this._map.keys());
42
+ }
43
+ /**
44
+ * Get the attention state for a given qualified ID.
45
+ */
46
+ get(id) {
47
+ const atom = this._getAtom(id);
48
+ return this._registry.get(atom);
49
+ }
50
+ /**
51
+ * Subscribe to changes in the attention state for a given qualified ID.
52
+ */
53
+ subscribe(id, cb) {
54
+ const atom = this._getAtom(id);
55
+ this._registry.get(atom);
56
+ return this._registry.subscribe(atom, () => {
57
+ cb(this._registry.get(atom));
58
+ });
59
+ }
60
+ _getAtom(id) {
61
+ const existing = this._map.get(id);
62
+ if (existing) {
63
+ return existing;
64
+ }
65
+ const newAtom = Atom.make({
66
+ hasAttention: false,
67
+ isAncestor: false,
68
+ isRelated: false
69
+ }).pipe(Atom.keepAlive);
70
+ this._map.set(id, newAtom);
71
+ return newAtom;
72
+ }
73
+ /**
74
+ * Update the currently attended element.
75
+ * Takes the array of qualified IDs collected from the DOM; the first element is the primary attended item.
76
+ * Ancestry is derived from the progressive prefixes of the primary ID.
77
+ * Relatedness is derived from the segment ID: any tracked key whose last `/` segment matches the
78
+ * attended ID's segment ID is marked `isRelated`. Additionally, if the primary ID is a linked segment
79
+ * (starts with `~`), its immediate parent gets `isRelated` alongside `isAncestor`.
80
+ *
81
+ * @internal
82
+ */
83
+ update(nextIds) {
84
+ const primaryId = nextIds[0];
85
+ if (!primaryId) {
86
+ return;
87
+ }
88
+ const currentIds = this.getCurrent();
89
+ const prevPrimaryId = currentIds[0];
90
+ if (prevPrimaryId) {
91
+ const prevPrefixes = expandAttendableId(prevPrimaryId);
92
+ for (const prefix of prevPrefixes) {
93
+ this._set(prefix, {});
94
+ }
95
+ const prevSegmentId = getSegmentId(prevPrimaryId);
96
+ for (const key of this.keys()) {
97
+ if (getSegmentId(key) === prevSegmentId) {
98
+ this._set(key, {});
99
+ }
100
+ }
101
+ }
102
+ this._registry.set(this._currentAtom, nextIds);
103
+ const prefixes = expandAttendableId(primaryId);
104
+ const prefixSet = new Set(prefixes);
105
+ const linkedParent = isLinkedSegment(primaryId) ? getParentId(primaryId) : void 0;
106
+ for (const prefix of prefixes) {
107
+ if (prefix === primaryId) {
108
+ this._set(prefix, {
109
+ hasAttention: true
110
+ });
111
+ } else if (prefix === linkedParent) {
112
+ this._set(prefix, {
113
+ isAncestor: true,
114
+ isRelated: true
115
+ });
116
+ } else {
117
+ this._set(prefix, {
118
+ isAncestor: true
119
+ });
120
+ }
121
+ }
122
+ const segmentId = getSegmentId(primaryId);
123
+ for (const key of this.keys()) {
124
+ if (!prefixSet.has(key) && getSegmentId(key) === segmentId) {
125
+ this._set(key, {
126
+ isRelated: true
127
+ });
128
+ }
129
+ }
130
+ }
131
+ _set(id, attention) {
132
+ const atom = this._getAtom(id);
133
+ this._registry.set(atom, {
134
+ hasAttention: attention.hasAttention ?? false,
135
+ isAncestor: attention.isAncestor ?? false,
136
+ isRelated: attention.isRelated ?? false
137
+ });
138
+ }
139
+ };
140
+ var getAttendables = (selector, cursor, acc = []) => {
141
+ const closestAttendable = cursor.closest(selector);
142
+ if (closestAttendable) {
143
+ const attendableId = closestAttendable.getAttribute("data-attendable-id");
144
+ if (!attendableId) {
145
+ const trigger = document.querySelector(`[aria-controls="${closestAttendable.getAttribute("id")}"]`);
146
+ if (!trigger) {
147
+ return acc;
148
+ } else {
149
+ return getAttendables(selector, trigger, acc);
150
+ }
151
+ } else {
152
+ acc.push(attendableId);
153
+ return !closestAttendable.parentElement ? acc : getAttendables(selector, closestAttendable.parentElement, acc);
154
+ }
155
+ }
156
+ return [
157
+ ...new Set(acc)
158
+ ];
159
+ };
160
+ var LINKED_PREFIX = "~";
161
+ var expandAttendableId = (qualifiedId) => {
162
+ const segments = qualifiedId.split("/");
163
+ return segments.map((_, index) => segments.slice(0, index + 1).join("/"));
164
+ };
165
+ var isLinkedSegment = (qualifiedId) => {
166
+ const lastSegment = qualifiedId.split("/").pop() ?? "";
167
+ return lastSegment.startsWith(LINKED_PREFIX);
168
+ };
169
+ var linkedSegment = (variant) => `${LINKED_PREFIX}${variant}`;
170
+ var getLinkedVariant = (qualifiedId) => {
171
+ const lastSegment = qualifiedId.split("/").pop() ?? "";
172
+ return lastSegment.startsWith(LINKED_PREFIX) ? lastSegment.slice(LINKED_PREFIX.length) : lastSegment;
173
+ };
174
+ var getParentId = (qualifiedId) => {
175
+ if (!qualifiedId) {
176
+ return void 0;
177
+ }
178
+ const lastSlash = qualifiedId.lastIndexOf("/");
179
+ return lastSlash > 0 ? qualifiedId.slice(0, lastSlash) : void 0;
180
+ };
181
+ var getSegmentId = (qualifiedId) => {
182
+ return qualifiedId.split("/").pop() ?? qualifiedId;
183
+ };
184
+
185
+ // src/view-state/view-state.ts
186
+ var defineViewState = (def) => def;
187
+ var ViewStateManager = class {
188
+ #registry;
189
+ #backends;
190
+ constructor({ registry, backends }) {
191
+ this.#registry = registry;
192
+ this.#backends = backends;
193
+ }
194
+ /** Reactive atom for `(aspect, contextId)`; pass to `registry.get` inside derived atoms/hooks. */
195
+ atom(aspect, contextId) {
196
+ return this.#backends[aspect.backend].atom(aspect, contextId);
197
+ }
198
+ get(aspect, contextId) {
199
+ return this.#registry.get(this.atom(aspect, contextId));
200
+ }
201
+ set(aspect, contextId, value) {
202
+ const backend = this.#backends[aspect.backend];
203
+ this.#registry.set(backend.atom(aspect, contextId), value);
204
+ backend.persist?.(aspect, contextId, value);
205
+ }
206
+ update(aspect, contextId, fn) {
207
+ this.set(aspect, contextId, fn(this.get(aspect, contextId)));
208
+ }
209
+ subscribe(aspect, contextId, cb) {
210
+ const atom = this.atom(aspect, contextId);
211
+ return this.#registry.subscribe(atom, () => cb(this.#registry.get(atom)));
212
+ }
213
+ contexts(aspect) {
214
+ return this.#backends[aspect.backend].contexts(aspect);
215
+ }
216
+ };
217
+
218
+ // src/view-state/backends.ts
219
+ import { Atom as Atom2 } from "@effect-atom/atom-react";
220
+ import * as Schema from "effect/Schema";
221
+ var cacheKey = (aspect, contextId) => `${aspect.key}:${contextId}`;
222
+ var MemoryBackend = class {
223
+ #atoms = /* @__PURE__ */ new Map();
224
+ atom(aspect, contextId) {
225
+ const key = cacheKey(aspect, contextId);
226
+ let atom = this.#atoms.get(key);
227
+ if (!atom) {
228
+ atom = Atom2.make(aspect.defaultValue());
229
+ this.#atoms.set(key, atom);
230
+ }
231
+ return atom;
232
+ }
233
+ contexts(aspect) {
234
+ const prefix = `${aspect.key}:`;
235
+ return [
236
+ ...this.#atoms.keys()
237
+ ].filter((key) => key.startsWith(prefix)).map((key) => key.slice(prefix.length));
238
+ }
239
+ };
240
+ var STORAGE_PREFIX = "dxos:view-state:";
241
+ var storageKeyFor = (aspect, contextId) => `${STORAGE_PREFIX}${aspect.key}:${contextId}`;
242
+ var safeLocalStorage = () => {
243
+ try {
244
+ return globalThis.localStorage;
245
+ } catch {
246
+ return void 0;
247
+ }
248
+ };
249
+ var LocalBackend = class {
250
+ #registry;
251
+ // Absent in non-browser contexts (SSR/tests without injection); the backend then degrades to
252
+ // ephemeral, in-memory behaviour rather than crashing on a missing `localStorage`.
253
+ #storage;
254
+ #atoms = /* @__PURE__ */ new Map();
255
+ // Reverse map: storage key -> (aspect, contextId) so `storage` events can target the right atom.
256
+ #byStorageKey = /* @__PURE__ */ new Map();
257
+ #storageListener;
258
+ constructor({ registry, storage }) {
259
+ this.#registry = registry;
260
+ this.#storage = storage ?? safeLocalStorage();
261
+ if (this.#storage && typeof globalThis.addEventListener === "function") {
262
+ this.#storageListener = (event) => {
263
+ if (!event.key || !event.key.startsWith(STORAGE_PREFIX)) {
264
+ return;
265
+ }
266
+ const entry = this.#byStorageKey.get(event.key);
267
+ const atom = entry && this.#atoms.get(cacheKey(entry.aspect, entry.contextId));
268
+ if (entry && atom) {
269
+ this.#registry.set(atom, this.#read(entry.aspect, event.key));
270
+ }
271
+ };
272
+ globalThis.addEventListener("storage", this.#storageListener);
273
+ }
274
+ }
275
+ atom(aspect, contextId) {
276
+ const key = cacheKey(aspect, contextId);
277
+ let atom = this.#atoms.get(key);
278
+ if (!atom) {
279
+ const storageKey = storageKeyFor(aspect, contextId);
280
+ atom = Atom2.make(this.#read(aspect, storageKey));
281
+ this.#atoms.set(key, atom);
282
+ this.#byStorageKey.set(storageKey, {
283
+ aspect,
284
+ contextId
285
+ });
286
+ }
287
+ return atom;
288
+ }
289
+ persist(aspect, contextId, value) {
290
+ this.#storage?.setItem(storageKeyFor(aspect, contextId), JSON.stringify(Schema.encodeSync(aspect.schema)(value)));
291
+ }
292
+ contexts(aspect) {
293
+ if (!this.#storage) {
294
+ const prefix2 = `${aspect.key}:`;
295
+ return [
296
+ ...this.#atoms.keys()
297
+ ].filter((key) => key.startsWith(prefix2)).map((key) => key.slice(prefix2.length));
298
+ }
299
+ const prefix = storageKeyFor(aspect, "");
300
+ const ids = [];
301
+ for (let index = 0; index < this.#storage.length; index++) {
302
+ const key = this.#storage.key(index);
303
+ if (key?.startsWith(prefix)) {
304
+ ids.push(key.slice(prefix.length));
305
+ }
306
+ }
307
+ return ids;
308
+ }
309
+ dispose() {
310
+ if (this.#storageListener && typeof globalThis.removeEventListener === "function") {
311
+ globalThis.removeEventListener("storage", this.#storageListener);
312
+ }
313
+ this.#atoms.clear();
314
+ this.#byStorageKey.clear();
315
+ }
316
+ #read(aspect, storageKey) {
317
+ const raw = this.#storage?.getItem(storageKey);
318
+ if (raw == null) {
319
+ return aspect.defaultValue();
320
+ }
321
+ try {
322
+ return Schema.decodeUnknownSync(aspect.schema)(JSON.parse(raw));
323
+ } catch {
324
+ return aspect.defaultValue();
325
+ }
326
+ }
327
+ };
328
+ var createDefaultBackends = (registry) => ({
329
+ memory: new MemoryBackend(),
330
+ local: new LocalBackend({
331
+ registry
332
+ })
333
+ });
334
+
335
+ // src/selection.ts
336
+ import * as Match from "effect/Match";
337
+ import * as Schema2 from "effect/Schema";
338
+ var SelectionSchema = Schema2.Union(Schema2.Struct({
339
+ mode: Schema2.Literal("single"),
340
+ id: Schema2.optional(Schema2.String)
341
+ }).pipe(Schema2.mutable), Schema2.Struct({
342
+ mode: Schema2.Literal("multi"),
343
+ ids: Schema2.Array(Schema2.String).pipe(Schema2.mutable)
344
+ }).pipe(Schema2.mutable), Schema2.Struct({
345
+ mode: Schema2.Literal("range"),
346
+ from: Schema2.optional(Schema2.String),
347
+ to: Schema2.optional(Schema2.String)
348
+ }).pipe(Schema2.mutable), Schema2.Struct({
349
+ mode: Schema2.Literal("multi-range"),
350
+ ranges: Schema2.Array(Schema2.Struct({
351
+ from: Schema2.String,
352
+ to: Schema2.String
353
+ })).pipe(Schema2.mutable)
354
+ }).pipe(Schema2.mutable)).pipe(Schema2.mutable);
355
+ var defaultSelection = Match.type().pipe(Match.withReturnType(), Match.when("single", () => ({
356
+ mode: "single"
357
+ })), Match.when("multi", () => ({
358
+ mode: "multi",
359
+ ids: []
360
+ })), Match.when("range", () => ({
361
+ mode: "range"
362
+ })), Match.when("multi-range", () => ({
363
+ mode: "multi-range",
364
+ ranges: []
365
+ })), Match.exhaustive);
366
+ var selectionAspect = defineViewState({
367
+ key: "selection",
368
+ backend: "memory",
369
+ schema: SelectionSchema,
370
+ defaultValue: () => ({
371
+ mode: "multi",
372
+ ids: []
373
+ })
374
+ });
375
+ var resolveSelection = (selection, mode) => {
376
+ const value = selection?.mode === mode ? selection : defaultSelection(mode);
377
+ return Match.type().pipe(Match.when({
378
+ mode: "single"
379
+ }, (s) => s.id), Match.when({
380
+ mode: "multi"
381
+ }, (s) => s.ids), Match.when({
382
+ mode: "range"
383
+ }, (s) => s.from && s.to ? {
384
+ from: s.from,
385
+ to: s.to
386
+ } : void 0), Match.when({
387
+ mode: "multi-range"
388
+ }, (s) => s.ranges), Match.exhaustive)(value);
389
+ };
390
+ var toggleSelection = (selection, id) => {
391
+ const ids = selection?.mode === "multi" ? selection.ids : [];
392
+ return {
393
+ mode: "multi",
394
+ ids: ids.includes(id) ? ids.filter((existing) => existing !== id) : [
395
+ ...ids,
396
+ id
397
+ ]
398
+ };
399
+ };
400
+ var getSelectionSet = (manager, contextId) => {
401
+ const ids = new Set(contextId ? [
402
+ contextId
403
+ ] : []);
404
+ for (const context of manager.contexts(selectionAspect)) {
405
+ const selection = manager.get(selectionAspect, context);
406
+ if (selection.mode === "multi") {
407
+ for (const id of selection.ids) {
408
+ ids.add(id);
409
+ }
410
+ }
411
+ }
412
+ return ids;
413
+ };
414
+
415
+ export {
416
+ AttentionManager,
417
+ getAttendables,
418
+ expandAttendableId,
419
+ isLinkedSegment,
420
+ linkedSegment,
421
+ getLinkedVariant,
422
+ getParentId,
423
+ getSegmentId,
424
+ defineViewState,
425
+ ViewStateManager,
426
+ MemoryBackend,
427
+ LocalBackend,
428
+ createDefaultBackends,
429
+ SelectionSchema,
430
+ defaultSelection,
431
+ selectionAspect,
432
+ resolveSelection,
433
+ toggleSelection,
434
+ getSelectionSet
435
+ };
436
+ //# sourceMappingURL=chunk-HWN7KJDX.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/attention.ts", "../../../src/view-state/view-state.ts", "../../../src/view-state/backends.ts", "../../../src/selection.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Atom, type Registry } from '@effect-atom/atom-react';\n\nexport type Attention = {\n hasAttention: boolean;\n isAncestor: boolean;\n isRelated: boolean;\n};\n\n/**\n * Manages attention state for an application.\n * Attention keys are slash-qualified graph IDs; ancestry is derived from progressive prefixes.\n */\nexport class AttentionManager {\n private readonly _map = new Map<string, Atom.Writable<Attention>>();\n private readonly _currentAtom: Atom.Writable<string[]>;\n\n constructor(\n private readonly _registry: Registry.Registry,\n initial: string[] = [],\n ) {\n this._currentAtom = Atom.make<string[]>([]).pipe(Atom.keepAlive);\n if (initial.length > 0) {\n this.update(initial);\n }\n }\n\n /**\n * Atom for the currently attended element IDs.\n */\n get current(): Atom.Atom<string[]> {\n return this._currentAtom;\n }\n\n /**\n * Gets the currently attended element IDs.\n */\n getCurrent(): readonly string[] {\n return this._registry.get(this._currentAtom);\n }\n\n /**\n * Subscribe to changes in the current attention IDs.\n */\n subscribeCurrent(cb: (current: readonly string[]) => void): () => void {\n this._registry.get(this._currentAtom);\n return this._registry.subscribe(this._currentAtom, () => {\n cb(this._registry.get(this._currentAtom));\n });\n }\n\n /**\n * All tracked qualified IDs.\n */\n keys(): string[] {\n return Array.from(this._map.keys());\n }\n\n /**\n * Get the attention state for a given qualified ID.\n */\n get(id: string): Attention {\n const atom = this._getAtom(id);\n return this._registry.get(atom);\n }\n\n /**\n * Subscribe to changes in the attention state for a given qualified ID.\n */\n subscribe(id: string, cb: (attention: Attention) => void): () => void {\n const atom = this._getAtom(id);\n this._registry.get(atom);\n return this._registry.subscribe(atom, () => {\n cb(this._registry.get(atom));\n });\n }\n\n private _getAtom(id: string): Atom.Writable<Attention> {\n const existing = this._map.get(id);\n if (existing) {\n return existing;\n }\n\n const newAtom = Atom.make<Attention>({ hasAttention: false, isAncestor: false, isRelated: false }).pipe(\n Atom.keepAlive,\n );\n this._map.set(id, newAtom);\n return newAtom;\n }\n\n /**\n * Update the currently attended element.\n * Takes the array of qualified IDs collected from the DOM; the first element is the primary attended item.\n * Ancestry is derived from the progressive prefixes of the primary ID.\n * Relatedness is derived from the segment ID: any tracked key whose last `/` segment matches the\n * attended ID's segment ID is marked `isRelated`. Additionally, if the primary ID is a linked segment\n * (starts with `~`), its immediate parent gets `isRelated` alongside `isAncestor`.\n *\n * @internal\n */\n update(nextIds: string[]): void {\n const primaryId = nextIds[0];\n if (!primaryId) {\n return;\n }\n\n const currentIds = this.getCurrent();\n const prevPrimaryId = currentIds[0];\n // Clear previous attention state: ancestors, primary, and related keys.\n if (prevPrimaryId) {\n const prevPrefixes = expandAttendableId(prevPrimaryId);\n for (const prefix of prevPrefixes) {\n this._set(prefix, {});\n }\n const prevSegmentId = getSegmentId(prevPrimaryId);\n for (const key of this.keys()) {\n if (getSegmentId(key) === prevSegmentId) {\n this._set(key, {});\n }\n }\n }\n\n this._registry.set(this._currentAtom, nextIds);\n\n // Set ancestors and primary.\n const prefixes = expandAttendableId(primaryId);\n const prefixSet = new Set(prefixes);\n const linkedParent = isLinkedSegment(primaryId) ? getParentId(primaryId) : undefined;\n\n for (const prefix of prefixes) {\n if (prefix === primaryId) {\n this._set(prefix, { hasAttention: true });\n } else if (prefix === linkedParent) {\n this._set(prefix, { isAncestor: true, isRelated: true });\n } else {\n this._set(prefix, { isAncestor: true });\n }\n }\n\n // Set related keys: any tracked key sharing the same segment ID.\n const segmentId = getSegmentId(primaryId);\n for (const key of this.keys()) {\n if (!prefixSet.has(key) && getSegmentId(key) === segmentId) {\n this._set(key, { isRelated: true });\n }\n }\n }\n\n private _set(id: string, attention: Partial<Attention>): void {\n const atom = this._getAtom(id);\n this._registry.set(atom, {\n hasAttention: attention.hasAttention ?? false,\n isAncestor: attention.isAncestor ?? false,\n isRelated: attention.isRelated ?? false,\n });\n }\n}\n\n/**\n * Accumulates all attendable IDs between the element provided and the root, inclusive.\n * Each `data-attendable-id` value is treated as a single qualified ID (no splitting).\n */\nexport const getAttendables = (selector: string, cursor: Element, acc: string[] = []): string[] => {\n // Find the closest element with `data-attendable-id`, if any; start from cursor and move up the DOM tree.\n const closestAttendable = cursor.closest(selector);\n if (closestAttendable) {\n const attendableId = closestAttendable.getAttribute('data-attendable-id');\n if (!attendableId) {\n // This has an id of an aria-controls elsewhere on the page, move cursor to that trigger.\n const trigger = document.querySelector(`[aria-controls=\"${closestAttendable.getAttribute('id')}\"]`);\n if (!trigger) {\n return acc;\n } else {\n return getAttendables(selector, trigger, acc);\n }\n } else {\n acc.push(attendableId);\n return !closestAttendable.parentElement ? acc : getAttendables(selector, closestAttendable.parentElement, acc);\n }\n }\n\n return [...new Set(acc)];\n};\n\nexport type AttendableId = { attendableId?: string };\n\nexport type Related = { related?: boolean };\n\n/**\n * Prefix for linked segments. A linked segment's attention state is shared with its parent:\n * when a linked node has attention, the parent is marked as both ancestor and related.\n */\nconst LINKED_PREFIX = '~';\n\n/**\n * Decompose a qualified graph ID into progressive prefixes for ancestry tracking.\n * e.g. `root/a/b/c` yields `['root', 'root/a', 'root/a/b', 'root/a/b/c']`.\n */\nexport const expandAttendableId = (qualifiedId: string): string[] => {\n const segments = qualifiedId.split('/');\n return segments.map((_, index) => segments.slice(0, index + 1).join('/'));\n};\n\n/**\n * Whether the last segment of a qualified ID is a linked segment (starts with `~`).\n * Linked segments share their attention state with the parent node.\n */\nexport const isLinkedSegment = (qualifiedId: string): boolean => {\n const lastSegment = qualifiedId.split('/').pop() ?? '';\n return lastSegment.startsWith(LINKED_PREFIX);\n};\n\n/**\n * Build a linked segment ID from a variant name (e.g., `'settings'` -> `'~settings'`).\n * Nodes identified by linked segments share their attention state with the parent node.\n */\nexport const linkedSegment = (variant: string): string => `${LINKED_PREFIX}${variant}`;\n\n/**\n * Extract the variant name from the last segment of a qualified ID, stripping the linked prefix.\n * e.g. `'root/space/obj/~settings'` -> `'settings'`.\n * If the segment is not linked (no `~` prefix), returns the segment as-is.\n */\nexport const getLinkedVariant = (qualifiedId: string): string => {\n const lastSegment = qualifiedId.split('/').pop() ?? '';\n return lastSegment.startsWith(LINKED_PREFIX) ? lastSegment.slice(LINKED_PREFIX.length) : lastSegment;\n};\n\n/**\n * Get the parent qualified ID (everything before the last `/` segment).\n */\nexport const getParentId = (qualifiedId: string | undefined): string | undefined => {\n if (!qualifiedId) {\n return undefined;\n }\n\n const lastSlash = qualifiedId.lastIndexOf('/');\n return lastSlash > 0 ? qualifiedId.slice(0, lastSlash) : undefined;\n};\n\n/**\n * Extract the segment ID (last segment) of a qualified ID.\n */\nexport const getSegmentId = (qualifiedId: string): string => {\n return qualifiedId.split('/').pop() ?? qualifiedId;\n};\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Atom, type Registry } from '@effect-atom/atom-react';\nimport type * as Schema from 'effect/Schema';\n\n/**\n * Persistence backend identifier. `personal` (ECHO/personal-space) is reserved for a future backend.\n */\nexport type BackendName = 'memory' | 'local';\n\n/**\n * Declares a kind of per-context UI state. The value type `T` is inferred from the schema.\n */\nexport interface AspectDef<T> {\n readonly key: string;\n readonly backend: BackendName;\n // Encoded type is intentionally unconstrained: persisted backends serialize `T` through the\n // schema to an arbitrary wire form, and only the decoded `T` matters to consumers.\n readonly schema: Schema.Schema<T, any>;\n readonly defaultValue: () => T;\n}\n\n/**\n * Identity helper that pins the value type from the schema while keeping the literal `key`/`backend`.\n */\nexport const defineViewState = <T>(def: AspectDef<T>): AspectDef<T> => def;\n\n/**\n * A backend produces a reactive, writable atom for each `(aspect, contextId)` pair. Backends may\n * hydrate asynchronously (an ECHO backend would), yielding `aspect.defaultValue()` until loaded;\n * the memory and local backends resolve synchronously.\n */\nexport interface ViewStateBackend {\n /** Stable atom for the pair; created (and seeded) on first access, cached thereafter. */\n atom: <T>(aspect: AspectDef<T>, contextId: string) => Atom.Writable<T>;\n /** Persist a value after the atom is updated. No-op for in-memory backends. */\n persist?: <T>(aspect: AspectDef<T>, contextId: string, value: T) => void;\n /** Context ids that currently hold a value for the aspect. */\n contexts: <T>(aspect: AspectDef<T>) => string[];\n /** Release listeners/timers (used by tests; app-lifetime managers do not call this). */\n dispose?: () => void;\n}\n\nexport interface ViewStateManagerOptions {\n readonly registry: Registry.Registry;\n readonly backends: Record<BackendName, ViewStateBackend>;\n}\n\n/**\n * Routes per-context UI state to the backend declared by each aspect. Reads/writes go through the\n * effect-atom registry so React hooks and graph atoms observe changes uniformly.\n */\nexport class ViewStateManager {\n readonly #registry: Registry.Registry;\n readonly #backends: Record<BackendName, ViewStateBackend>;\n\n constructor({ registry, backends }: ViewStateManagerOptions) {\n this.#registry = registry;\n this.#backends = backends;\n }\n\n /** Reactive atom for `(aspect, contextId)`; pass to `registry.get` inside derived atoms/hooks. */\n atom<T>(aspect: AspectDef<T>, contextId: string): Atom.Writable<T> {\n return this.#backends[aspect.backend].atom(aspect, contextId);\n }\n\n get<T>(aspect: AspectDef<T>, contextId: string): T {\n return this.#registry.get(this.atom(aspect, contextId));\n }\n\n set<T>(aspect: AspectDef<T>, contextId: string, value: T): void {\n const backend = this.#backends[aspect.backend];\n this.#registry.set(backend.atom(aspect, contextId), value);\n backend.persist?.(aspect, contextId, value);\n }\n\n update<T>(aspect: AspectDef<T>, contextId: string, fn: (prev: T) => T): void {\n this.set(aspect, contextId, fn(this.get(aspect, contextId)));\n }\n\n subscribe<T>(aspect: AspectDef<T>, contextId: string, cb: (value: T) => void): () => void {\n const atom = this.atom(aspect, contextId);\n return this.#registry.subscribe(atom, () => cb(this.#registry.get(atom)));\n }\n\n contexts<T>(aspect: AspectDef<T>): string[] {\n return this.#backends[aspect.backend].contexts(aspect);\n }\n}\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport { Atom, type Registry } from '@effect-atom/atom-react';\nimport * as Schema from 'effect/Schema';\n\nimport { type AspectDef, type BackendName, type ViewStateBackend } from './view-state';\n\n// Only the stable `key` string is needed to form the map key; avoids variance issues with AspectDef<T>.\nconst cacheKey = (aspect: { key: string }, contextId: string) => `${aspect.key}:${contextId}`;\n\n/** In-memory backend: state is ephemeral and scoped to the session (never persisted). */\nexport class MemoryBackend implements ViewStateBackend {\n readonly #atoms = new Map<string, Atom.Writable<unknown>>();\n\n atom<T>(aspect: AspectDef<T>, contextId: string): Atom.Writable<T> {\n const key = cacheKey(aspect, contextId);\n let atom = this.#atoms.get(key);\n if (!atom) {\n atom = Atom.make<unknown>(aspect.defaultValue());\n this.#atoms.set(key, atom);\n }\n // Cast bridges the per-aspect value type erased by the shared atom map; safe by construction.\n return atom as Atom.Writable<T>;\n }\n\n contexts<T>(aspect: AspectDef<T>): string[] {\n const prefix = `${aspect.key}:`;\n return [...this.#atoms.keys()].filter((key) => key.startsWith(prefix)).map((key) => key.slice(prefix.length));\n }\n}\n\nconst STORAGE_PREFIX = 'dxos:view-state:';\n\nconst storageKeyFor = (aspect: { key: string }, contextId: string) => `${STORAGE_PREFIX}${aspect.key}:${contextId}`;\n\n// Accessing `globalThis.localStorage` can throw a SecurityError in sandboxed iframes or when\n// storage is blocked; degrade to in-memory behaviour instead of crashing.\nconst safeLocalStorage = (): Storage | undefined => {\n try {\n return globalThis.localStorage;\n } catch {\n return undefined;\n }\n};\n\nexport interface LocalBackendOptions {\n readonly registry: Registry.Registry;\n /** Injectable for tests; defaults to `window.localStorage`. */\n readonly storage?: Storage;\n}\n\n/** localStorage-backed backend: seeds atoms from storage, persists on set, syncs across tabs. */\nexport class LocalBackend implements ViewStateBackend {\n readonly #registry: Registry.Registry;\n // Absent in non-browser contexts (SSR/tests without injection); the backend then degrades to\n // ephemeral, in-memory behaviour rather than crashing on a missing `localStorage`.\n readonly #storage: Storage | undefined;\n readonly #atoms = new Map<string, Atom.Writable<unknown>>();\n // Reverse map: storage key -> (aspect, contextId) so `storage` events can target the right atom.\n readonly #byStorageKey = new Map<string, { aspect: AspectDef<unknown>; contextId: string }>();\n #storageListener?: (event: StorageEvent) => void;\n\n constructor({ registry, storage }: LocalBackendOptions) {\n this.#registry = registry;\n this.#storage = storage ?? safeLocalStorage();\n if (this.#storage && typeof globalThis.addEventListener === 'function') {\n this.#storageListener = (event) => {\n if (!event.key || !event.key.startsWith(STORAGE_PREFIX)) {\n return;\n }\n const entry = this.#byStorageKey.get(event.key);\n const atom = entry && this.#atoms.get(cacheKey(entry.aspect, entry.contextId));\n if (entry && atom) {\n this.#registry.set(atom, this.#read(entry.aspect, event.key));\n }\n };\n globalThis.addEventListener('storage', this.#storageListener);\n }\n }\n\n atom<T>(aspect: AspectDef<T>, contextId: string): Atom.Writable<T> {\n const key = cacheKey(aspect, contextId);\n let atom = this.#atoms.get(key);\n if (!atom) {\n const storageKey = storageKeyFor(aspect, contextId);\n atom = Atom.make<unknown>(this.#read(aspect, storageKey));\n this.#atoms.set(key, atom);\n // Cast erases the per-aspect value type so the reverse map can hold aspects of any `T`; the\n // stored aspect is only used to re-read/decode its own value, so the erasure is safe.\n this.#byStorageKey.set(storageKey, { aspect: aspect as AspectDef<unknown>, contextId });\n }\n // Cast bridges the per-aspect value type erased by the shared atom map; safe by construction.\n return atom as Atom.Writable<T>;\n }\n\n persist<T>(aspect: AspectDef<T>, contextId: string, value: T): void {\n this.#storage?.setItem(storageKeyFor(aspect, contextId), JSON.stringify(Schema.encodeSync(aspect.schema)(value)));\n }\n\n contexts<T>(aspect: AspectDef<T>): string[] {\n if (!this.#storage) {\n // No persistent storage: fall back to the in-memory atoms (mirrors `atom()`'s ephemeral path).\n const prefix = `${aspect.key}:`;\n return [...this.#atoms.keys()].filter((key) => key.startsWith(prefix)).map((key) => key.slice(prefix.length));\n }\n const prefix = storageKeyFor(aspect, '');\n const ids: string[] = [];\n for (let index = 0; index < this.#storage.length; index++) {\n const key = this.#storage.key(index);\n if (key?.startsWith(prefix)) {\n ids.push(key.slice(prefix.length));\n }\n }\n return ids;\n }\n\n dispose(): void {\n if (this.#storageListener && typeof globalThis.removeEventListener === 'function') {\n globalThis.removeEventListener('storage', this.#storageListener);\n }\n // Allow safe reuse after disposal: drop cached atoms and their reverse-key entries.\n this.#atoms.clear();\n this.#byStorageKey.clear();\n }\n\n #read<T>(aspect: AspectDef<T>, storageKey: string): T {\n const raw = this.#storage?.getItem(storageKey);\n if (raw == null) {\n return aspect.defaultValue();\n }\n try {\n return Schema.decodeUnknownSync(aspect.schema)(JSON.parse(raw));\n } catch {\n // Tolerate stale/corrupt entries (e.g. a prior schema shape) by falling back to the default.\n return aspect.defaultValue();\n }\n }\n}\n\nexport const createDefaultBackends = (registry: Registry.Registry): Record<BackendName, ViewStateBackend> => ({\n memory: new MemoryBackend(),\n local: new LocalBackend({ registry }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Match from 'effect/Match';\nimport * as Schema from 'effect/Schema';\n\nimport { type AspectDef, type ViewStateManager, defineViewState } from './view-state';\n\nexport type SelectionMode = 'single' | 'multi' | 'range' | 'multi-range';\n\nexport const SelectionSchema = Schema.Union(\n Schema.Struct({\n mode: Schema.Literal('single'),\n id: Schema.optional(Schema.String),\n }).pipe(Schema.mutable),\n Schema.Struct({\n mode: Schema.Literal('multi'),\n ids: Schema.Array(Schema.String).pipe(Schema.mutable),\n }).pipe(Schema.mutable),\n Schema.Struct({\n mode: Schema.Literal('range'),\n from: Schema.optional(Schema.String),\n to: Schema.optional(Schema.String),\n }).pipe(Schema.mutable),\n Schema.Struct({\n mode: Schema.Literal('multi-range'),\n ranges: Schema.Array(Schema.Struct({ from: Schema.String, to: Schema.String })).pipe(Schema.mutable),\n }).pipe(Schema.mutable),\n).pipe(Schema.mutable);\n\nexport type Selection = Schema.Schema.Type<typeof SelectionSchema>;\n\nexport const defaultSelection = Match.type<SelectionMode>().pipe(\n Match.withReturnType<Selection>(),\n Match.when('single', () => ({ mode: 'single' })),\n Match.when('multi', () => ({ mode: 'multi', ids: [] })),\n Match.when('range', () => ({ mode: 'range' })),\n Match.when('multi-range', () => ({ mode: 'multi-range', ranges: [] })),\n Match.exhaustive,\n);\n\nexport type SelectionResult<T extends SelectionMode> = T extends 'single'\n ? string | undefined\n : T extends 'multi'\n ? string[]\n : T extends 'range'\n ? { from: string; to: string } | undefined\n : T extends 'multi-range'\n ? { from: string; to: string }[]\n : never;\n\n/** Selection state for a context, stored in memory (ephemeral, per-device session). */\nexport const selectionAspect: AspectDef<Selection> = defineViewState<Selection>({\n key: 'selection',\n backend: 'memory',\n schema: SelectionSchema,\n defaultValue: () => ({ mode: 'multi', ids: [] }),\n});\n\n/**\n * Extract the typed result for `mode` from a stored selection value, returning the requested\n * mode's default when the stored value is absent or holds a different mode.\n */\nexport const resolveSelection = <T extends SelectionMode>(\n selection: Selection | undefined,\n mode: T,\n): SelectionResult<T> => {\n const value = selection?.mode === mode ? selection : defaultSelection(mode);\n // Cast required because TypeScript cannot relate the `Match` result to the generic `T`.\n return Match.type<Selection>().pipe(\n Match.when({ mode: 'single' }, (s) => s.id),\n Match.when({ mode: 'multi' }, (s) => s.ids),\n Match.when({ mode: 'range' }, (s) => (s.from && s.to ? { from: s.from, to: s.to } : undefined)),\n Match.when({ mode: 'multi-range' }, (s) => s.ranges),\n Match.exhaustive,\n )(value) as SelectionResult<T>;\n};\n\n/** Toggle `id` within a multi selection; resets to a multi selection if the current value differs. */\nexport const toggleSelection = (selection: Selection | undefined, id: string): Selection => {\n const ids = selection?.mode === 'multi' ? selection.ids : [];\n return { mode: 'multi', ids: ids.includes(id) ? ids.filter((existing) => existing !== id) : [...ids, id] };\n};\n\n/** Union of all multi-selected ids across every selection context, plus an optional explicit id. */\nexport const getSelectionSet = (manager: ViewStateManager, contextId?: string): Set<string> => {\n const ids = new Set<string>(contextId ? [contextId] : []);\n for (const context of manager.contexts(selectionAspect)) {\n const selection = manager.get(selectionAspect, context);\n if (selection.mode === 'multi') {\n for (const id of selection.ids) {\n ids.add(id);\n }\n }\n }\n return ids;\n};\n"],
5
+ "mappings": ";;;AAIA,SAASA,YAA2B;AAY7B,IAAMC,mBAAN,MAAMA;;EACMC,OAAO,oBAAIC,IAAAA;EACXC;EAEjB,YACmBC,WACjBC,UAAoB,CAAA,GACpB;SAFiBD,YAAAA;AAGjB,SAAKD,eAAeJ,KAAKO,KAAe,CAAA,CAAE,EAAEC,KAAKR,KAAKS,SAAS;AAC/D,QAAIH,QAAQI,SAAS,GAAG;AACtB,WAAKC,OAAOL,OAAAA;IACd;EACF;;;;EAKA,IAAIM,UAA+B;AACjC,WAAO,KAAKR;EACd;;;;EAKAS,aAAgC;AAC9B,WAAO,KAAKR,UAAUS,IAAI,KAAKV,YAAY;EAC7C;;;;EAKAW,iBAAiBC,IAAsD;AACrE,SAAKX,UAAUS,IAAI,KAAKV,YAAY;AACpC,WAAO,KAAKC,UAAUY,UAAU,KAAKb,cAAc,MAAA;AACjDY,SAAG,KAAKX,UAAUS,IAAI,KAAKV,YAAY,CAAA;IACzC,CAAA;EACF;;;;EAKAc,OAAiB;AACf,WAAOC,MAAMC,KAAK,KAAKlB,KAAKgB,KAAI,CAAA;EAClC;;;;EAKAJ,IAAIO,IAAuB;AACzB,UAAMC,OAAO,KAAKC,SAASF,EAAAA;AAC3B,WAAO,KAAKhB,UAA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9BA,YAAIgC,IAAIrC,EAAAA;MACV;IACF;EACF;AACA,SAAOK;AACT;",
6
+ "names": ["Atom", "AttentionManager", "_map", "Map", "_currentAtom", "_registry", "initial", "make", "pipe", "keepAlive", "length", "update", "current", "getCurrent", "get", "subscribeCurrent", "cb", "subscribe", "keys", "Array", "from", "id", "atom", "_getAtom", "existing", "newAtom", "hasAttention", "isAncestor", "isRelated", "set", "nextIds", "primaryId", "currentIds", "prevPrimaryId", "prevPrefixes", "expandAttendableId", "prefix", "_set", "prevSegmentId", "getSegmentId", "key", "prefixes", "prefixSet", "Set", "linkedParent", "isLinkedSegment", "getParentId", "undefined", "segmentId", "has", "attention", "getAttendables", "selector", "cursor", "acc", "closestAttendable", "closest", "attendableId", "getAttribute", "trigger", "document", "querySelector", "push", "parentElement", "LINKED_PREFIX", "qualifiedId", "segments", "split", "map", "_", "index", "slice", "join", "lastSegment", "pop", "startsWith", "linkedSegment", "variant", "getLinkedVariant", "lastSlash", "lastIndexOf", "defineViewState", "def", "ViewStateManager", "registry", "backends", "atom", "aspect", "contextId", "backend", "get", "set", "value", "persist", "update", "fn", "subscribe", "cb", "contexts", "Atom", "Schema", "cacheKey", "aspect", "contextId", "key", "MemoryBackend", "Map", "atom", "get", "make", "defaultValue", "set", "contexts", "prefix", "keys", "filter", "startsWith", "map", "slice", "length", "STORAGE_PREFIX", "storageKeyFor", "safeLocalStorage", "globalThis", "localStorage", "undefined", "LocalBackend", "registry", "storage", "addEventListener", "event", "entry", "storageKey", "persist", "value", "setItem", "JSON", "stringify", "encodeSync", "schema", "ids", "index", "push", "dispose", "removeEventListener", "clear", "raw", "getItem", "decodeUnknownSync", "parse", "createDefaultBackends", "memory", "local", "Match", "Schema", "SelectionSchema", "Union", "Struct", "mode", "Literal", "id", "optional", "String", "pipe", "mutable", "ids", "Array", "from", "to", "ranges", "defaultSelection", "type", "withReturnType", "when", "exhaustive", "selectionAspect", "defineViewState", "key", "backend", "schema", "defaultValue", "resolveSelection", "selection", "value", "s", "undefined", "toggleSelection", "includes", "filter", "existing", "getSelectionSet", "manager", "contextId", "Set", "context", "contexts", "get", "add"]
7
+ }
@@ -2,20 +2,26 @@ import { createRequire } from 'node:module';const require = createRequire(import
2
2
  import {
3
3
  AttendableContainer,
4
4
  RootAttentionProvider,
5
- SelectionProvider,
5
+ ViewStateProvider,
6
6
  useAttended,
7
7
  useAttention,
8
8
  useAttentionAttributes,
9
9
  useAttentionContext,
10
- useSelected,
10
+ useSelection,
11
11
  useSelectionActions,
12
- useSelectionManager
13
- } from "./chunk-ZTUVSH4P.mjs";
12
+ useViewState,
13
+ useViewStateActions,
14
+ useViewStateManager
15
+ } from "./chunk-5JUZQDCR.mjs";
14
16
  import {
15
17
  AttentionManager,
16
- SelectionManager,
18
+ LocalBackend,
19
+ MemoryBackend,
17
20
  SelectionSchema,
21
+ ViewStateManager,
22
+ createDefaultBackends,
18
23
  defaultSelection,
24
+ defineViewState,
19
25
  expandAttendableId,
20
26
  getAttendables,
21
27
  getLinkedVariant,
@@ -23,8 +29,11 @@ import {
23
29
  getSegmentId,
24
30
  getSelectionSet,
25
31
  isLinkedSegment,
26
- linkedSegment
27
- } from "./chunk-6INLBC62.mjs";
32
+ linkedSegment,
33
+ resolveSelection,
34
+ selectionAspect,
35
+ toggleSelection
36
+ } from "./chunk-HWN7KJDX.mjs";
28
37
 
29
38
  // src/components/AttentionGlyph/AttentionGlyph.tsx
30
39
  import React, { forwardRef, useMemo } from "react";
@@ -171,13 +180,17 @@ export {
171
180
  AttendableContainer,
172
181
  AttentionGlyph,
173
182
  AttentionManager,
183
+ LocalBackend,
184
+ MemoryBackend,
174
185
  RootAttentionProvider,
175
- SelectionManager,
176
- SelectionProvider,
177
186
  SelectionSchema,
178
187
  Syncing,
188
+ ViewStateManager,
189
+ ViewStateProvider,
179
190
  advance,
191
+ createDefaultBackends,
180
192
  defaultSelection,
193
+ defineViewState,
181
194
  expandAttendableId,
182
195
  getAttendables,
183
196
  getLinkedVariant,
@@ -186,13 +199,18 @@ export {
186
199
  getSelectionSet,
187
200
  isLinkedSegment,
188
201
  linkedSegment,
202
+ resolveSelection,
203
+ selectionAspect,
204
+ toggleSelection,
189
205
  useArticleKeyboardNavigation,
190
206
  useAttended,
191
207
  useAttention,
192
208
  useAttentionAttributes,
193
209
  useAttentionContext,
194
- useSelected,
210
+ useSelection,
195
211
  useSelectionActions,
196
- useSelectionManager
212
+ useViewState,
213
+ useViewStateActions,
214
+ useViewStateManager
197
215
  };
198
216
  //# sourceMappingURL=index.mjs.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../src/components/AttentionGlyph/AttentionGlyph.tsx", "../../../src/useArticleKeyboardNavigation.ts"],
4
4
  "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Primitive } from '@radix-ui/react-primitive';\nimport React, { type CSSProperties, type ComponentPropsWithRef, forwardRef, useMemo } from 'react';\n\nimport { Icon, type ThemedClassName } from '@dxos/react-ui';\nimport { mx } from '@dxos/ui-theme';\n\nconst attentionGlyphStyles = mx(\n 'inline-block rounded-xs w-3 h-3 bg-transparent text-accent-text transition-colors',\n '[[data-contains-attended=true]_&]:bg-attention-contains',\n '[[data-attention=true]_&]:bg-accent-bg',\n '[[data-attention=true]_&]:text-accent-fg',\n '[[aria-current][data-attention=true]_&]:bg-accent-bg',\n '[[aria-current][data-attention=true]_&]:text-accent-fg',\n '[[aria-selected=\"true\"][data-attention=true]_&]:bg-accent-bg',\n '[[aria-selected=\"true\"][data-attention=true]_&]:text-accent-fg',\n);\n\nconst presenceIconStyles = mx('w-3 h-3');\n\nconst PresenceOne = () => {\n return (\n <svg\n width='12'\n height='12'\n viewBox='0 0 12 12'\n className={presenceIconStyles}\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n >\n <circle cx='6' cy='6' r='2.5' fill='currentColor' />\n </svg>\n );\n};\n\nconst PresenceMany = () => {\n return (\n <svg\n width='12'\n height='12'\n viewBox='0 0 12 12'\n className={presenceIconStyles}\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n >\n <path\n d='M6.75 8.27311C7.38815 7.72296 7.79212 6.90866 7.79212 6C7.79212 5.09134 7.38815 4.27704 6.75 3.72689C7.06722 3.58122 7.42019 3.5 7.79212 3.5C9.17283 3.5 10.2921 4.61929 10.2921 6C10.2921 7.38071 9.17283 8.5 7.79212 8.5C7.42019 8.5 7.06723 8.41878 6.75 8.27311Z'\n fill='currentColor'\n />\n <circle cx='4.25' cy='6' r='2.5' fill='currentColor' />\n </svg>\n );\n};\n\nexport const Syncing = () => {\n const animationProps = useMemo<CSSProperties>(\n () => ({\n // Synchronize animations.\n animationDelay: `-${Date.now() % 2_000}ms`,\n }),\n [],\n );\n\n return (\n <div role='status' className='flex items-center'>\n <Icon\n icon='ph--circle-notch--bold'\n size={3}\n style={animationProps}\n classNames='text-subdued animate-[spin_2s_linear_infinite]'\n />\n </div>\n );\n};\n\nexport type AttentionGlyphProps = {\n attended?: boolean;\n containsAttended?: boolean;\n syncing?: boolean;\n presence?: 'none' | 'one' | 'many';\n} & ThemedClassName<Omit<ComponentPropsWithRef<typeof Primitive.span>, 'children'>>;\n\nexport const AttentionGlyph = forwardRef<HTMLSpanElement, AttentionGlyphProps>(\n ({ presence, attended, syncing, containsAttended, classNames, ...props }, forwardedRef) => {\n const icon = syncing ? (\n <Syncing />\n ) : presence === 'many' ? (\n <PresenceMany />\n ) : presence === 'one' ? (\n <PresenceOne />\n ) : null;\n\n return (\n <div className='flex group' data-attention={attended} data-contains-attended={containsAttended}>\n <span {...props} className={mx(attentionGlyphStyles, classNames)} ref={forwardedRef}>\n {icon}\n </span>\n </div>\n );\n },\n);\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport { useEffect, useMemo } from 'react';\n\nimport { Keyboard } from '@dxos/keyboard';\n\nimport { useAttention } from './components';\n\n/**\n * Compute the id to select after pressing 'j' (delta = 1) or 'k' (delta = -1).\n * Clamps at the list ends — pressing 'j' on the last item keeps the last item\n * selected (vim-style), and 'k' on the first item keeps the first.\n *\n * When no current selection exists, returns the first id (for delta = 1) or the\n * last id (for delta = -1) so the user can enter the list with either key.\n */\nexport const advance = ({\n ids,\n currentId,\n delta,\n}: {\n ids: readonly string[];\n currentId: string | undefined;\n delta: 1 | -1;\n}): string | undefined => {\n if (ids.length === 0) {\n return undefined;\n }\n\n const idx = currentId ? ids.indexOf(currentId) : -1;\n if (idx === -1) {\n return delta === 1 ? ids[0] : ids[ids.length - 1];\n }\n\n const next = Math.max(0, Math.min(ids.length - 1, idx + delta));\n return ids[next];\n};\n\nexport type UseArticleKeyboardNavigationOptions<T> = {\n /** Stable id for the article (used as the keyboard context path). */\n articleId: string;\n /** Ordered list of selectable items as they appear in the article. */\n items: readonly T[];\n /** Currently-selected id, if any. */\n currentId: string | undefined;\n /** Extracts the id from an item. Defaults to `item.id`. */\n getId?: (item: T) => string;\n /** Called with the id to select when the user presses 'j' or 'k'. */\n onSelect: (id: string) => void;\n};\n\n/**\n * Wire 'j' (next) and 'k' (previous) keyboard shortcuts for an article that\n * navigates a list of items (e.g., messages, events). Bindings are scoped to\n * the article's keyboard context so they only fire while the article has attention.\n *\n * Pass the items directly; ids are derived via `getId` (defaults to `item.id`).\n * Clamps at list boundaries. Active only when the article is attended.\n */\nexport const useArticleKeyboardNavigation: {\n <T extends { id: string }>(options: UseArticleKeyboardNavigationOptions<T>): void;\n <T>(options: UseArticleKeyboardNavigationOptions<T> & { getId: (item: T) => string }): void;\n} = <T>({ articleId, items, currentId, getId, onSelect }: UseArticleKeyboardNavigationOptions<T>): void => {\n const { hasAttention } = useAttention(articleId);\n\n // `getId` is optional only when `T extends { id: string }` (enforced by the overloads above),\n // so the fallback is sound; the cast bridges the generic erased by the implementation signature.\n const ids = useMemo(() => items.map((item) => (getId ? getId(item) : (item as { id: string }).id)), [items, getId]);\n\n useEffect(() => {\n if (!hasAttention) {\n return;\n }\n\n const context = Keyboard.singleton.getContext(articleId);\n const prevContext = Keyboard.singleton.getCurrentContext();\n Keyboard.singleton.setCurrentContext(articleId);\n\n const nextBinding = {\n shortcut: 'j',\n handler: () => {\n const target = advance({ ids, currentId, delta: 1 });\n if (target !== undefined) {\n onSelect(target);\n }\n },\n data: 'Next item',\n disableInput: true,\n };\n const prevBinding = {\n shortcut: 'k',\n handler: () => {\n const target = advance({ ids, currentId, delta: -1 });\n if (target !== undefined) {\n onSelect(target);\n }\n },\n data: 'Previous item',\n disableInput: true,\n };\n\n context.bind(nextBinding);\n context.bind(prevBinding);\n\n return () => {\n context.unbind('j');\n context.unbind('k');\n // Restore the prior context if we were the ones who set it.\n if (Keyboard.singleton.getCurrentContext() === articleId) {\n Keyboard.singleton.setCurrentContext(prevContext);\n }\n };\n }, [articleId, ids, currentId, onSelect, hasAttention]);\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAOA,SAAyDC,YAAYC,eAAe;AAE3F,SAASC,YAAkC;AAC3C,SAASC,UAAU;AAEnB,IAAMC,uBAAuBD,GAC3B,qFACA,2DACA,0CACA,4CACA,wDACA,0DACA,gEACA,gEAAA;AAGF,IAAME,qBAAqBF,GAAG,SAAA;AAE9B,IAAMG,cAAc,MAAA;AAClB,SACE,sBAAA,cAACC,OAAAA;IACCC,OAAM;IACNC,QAAO;IACPC,SAAQ;IACRC,WAAWN;IACXO,MAAK;IACLC,OAAM;KAEN,sBAAA,cAACC,UAAAA;IAAOC,IAAG;IAAIC,IAAG;IAAIC,GAAE;IAAML,MAAK;;AAGzC;AAEA,IAAMM,eAAe,MAAA;AACnB,SACE,sBAAA,cAACX,OAAAA;IACCC,OAAM;IACNC,QAAO;IACPC,SAAQ;IACRC,WAAWN;IACXO,MAAK;IACLC,OAAM;KAEN,sBAAA,cAACM,QAAAA;IACCC,GAAE;IACFR,MAAK;MAEP,sBAAA,cAACE,UAAAA;IAAOC,IAAG;IAAOC,IAAG;IAAIC,GAAE;IAAML,MAAK;;AAG5C;AAEO,IAAMS,UAAU,MAAA;AACrB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c;MAClBL,UAAU;MACVC,SAAS,MAAA;AACP,cAAMC,SAASlC,QAAQ;UAAEC;UAAKC;UAAWC,OAAO;QAAG,CAAA;AACnD,YAAI+B,WAAW7B,QAAW;AACxBW,mBAASkB,MAAAA;QACX;MACF;MACAC,MAAM;MACNC,cAAc;IAChB;AAEAZ,YAAQc,KAAKP,WAAAA;AACbP,YAAQc,KAAKD,WAAAA;AAEb,WAAO,MAAA;AACLb,cAAQe,OAAO,GAAA;AACff,cAAQe,OAAO,GAAA;AAEf,UAAId,SAASC,UAAUG,kBAAiB,MAAOhB,WAAW;AACxDY,iBAASC,UAAUI,kBAAkBF,WAAAA;MACvC;IACF;EACF,GAAG;IAACf;IAAWZ;IAAKC;IAAWc;IAAUC;GAAa;AACxD;",
6
6
  "names": ["React", "forwardRef", "useMemo", "Icon", "mx", "attentionGlyphStyles", "presenceIconStyles", "PresenceOne", "svg", "width", "height", "viewBox", "className", "fill", "xmlns", "circle", "cx", "cy", "r", "PresenceMany", "path", "d", "Syncing", "animationProps", "animationDelay", "Date", "now", "div", "role", "icon", "size", "style", "classNames", "AttentionGlyph", "presence", "attended", "syncing", "containsAttended", "props", "forwardedRef", "data-attention", "data-contains-attended", "span", "ref", "useEffect", "useMemo", "Keyboard", "advance", "ids", "currentId", "delta", "length", "undefined", "idx", "indexOf", "next", "Math", "max", "min", "useArticleKeyboardNavigation", "articleId", "items", "getId", "onSelect", "hasAttention", "useAttention", "useMemo", "map", "item", "id", "useEffect", "context", "Keyboard", "singleton", "getContext", "prevContext", "getCurrentContext", "setCurrentContext", "nextBinding", "shortcut", "handler", "target", "data", "disableInput", "prevBinding", "bind", "unbind"]
7
7
  }