@dxos/react-ui-attention 0.16.0 → 0.17.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 (58) hide show
  1. package/dist/lib/chunk-ViewStateProvider.mjs +1 -1
  2. package/dist/lib/chunk-types.mjs +240 -9
  3. package/dist/lib/chunk-types.mjs.map +1 -1
  4. package/dist/lib/index.mjs +242 -56
  5. package/dist/lib/index.mjs.map +1 -1
  6. package/dist/lib/testing.mjs +1 -1
  7. package/dist/lib/types.mjs +1 -1
  8. package/dist/types/src/components/AttentionGlyph/AttentionGlyph.d.ts +6 -11
  9. package/dist/types/src/components/AttentionGlyph/AttentionGlyph.d.ts.map +1 -1
  10. package/dist/types/src/components/AttentionGlyph/AttentionGlyph.stories.d.ts +13 -6
  11. package/dist/types/src/components/AttentionGlyph/AttentionGlyph.stories.d.ts.map +1 -1
  12. package/dist/types/src/components/RemoteCursor/RemoteCursor.d.ts +18 -0
  13. package/dist/types/src/components/RemoteCursor/RemoteCursor.d.ts.map +1 -0
  14. package/dist/types/src/components/RemoteCursor/RemoteCursorLayer.d.ts +32 -0
  15. package/dist/types/src/components/RemoteCursor/RemoteCursorLayer.d.ts.map +1 -0
  16. package/dist/types/src/components/RemoteCursor/RemoteCursorLayer.test.d.ts +2 -0
  17. package/dist/types/src/components/RemoteCursor/RemoteCursorLayer.test.d.ts.map +1 -0
  18. package/dist/types/src/components/RemoteCursor/index.d.ts +3 -0
  19. package/dist/types/src/components/RemoteCursor/index.d.ts.map +1 -0
  20. package/dist/types/src/components/ScrollScope/ScrollScope.d.ts +11 -0
  21. package/dist/types/src/components/ScrollScope/ScrollScope.d.ts.map +1 -0
  22. package/dist/types/src/components/ScrollScope/ScrollScope.stories.d.ts +15 -0
  23. package/dist/types/src/components/ScrollScope/ScrollScope.stories.d.ts.map +1 -0
  24. package/dist/types/src/components/ScrollScope/index.d.ts +2 -0
  25. package/dist/types/src/components/ScrollScope/index.d.ts.map +1 -0
  26. package/dist/types/src/components/index.d.ts +2 -0
  27. package/dist/types/src/components/index.d.ts.map +1 -1
  28. package/dist/types/src/types/Activity.d.ts +71 -0
  29. package/dist/types/src/types/Activity.d.ts.map +1 -0
  30. package/dist/types/src/types/Activity.test.d.ts +2 -0
  31. package/dist/types/src/types/Activity.test.d.ts.map +1 -0
  32. package/dist/types/src/types/ScrollPosition.d.ts +24 -0
  33. package/dist/types/src/types/ScrollPosition.d.ts.map +1 -0
  34. package/dist/types/src/types/ViewLocation.d.ts +16 -0
  35. package/dist/types/src/types/ViewLocation.d.ts.map +1 -0
  36. package/dist/types/src/types/ViewState.d.ts +44 -2
  37. package/dist/types/src/types/ViewState.d.ts.map +1 -1
  38. package/dist/types/src/types/index.d.ts +3 -0
  39. package/dist/types/src/types/index.d.ts.map +1 -1
  40. package/dist/types/tsconfig.tsbuildinfo +1 -1
  41. package/package.json +17 -16
  42. package/src/components/AttentionGlyph/AttentionGlyph.stories.tsx +424 -31
  43. package/src/components/AttentionGlyph/AttentionGlyph.tsx +80 -56
  44. package/src/components/RemoteCursor/RemoteCursor.tsx +55 -0
  45. package/src/components/RemoteCursor/RemoteCursorLayer.test.tsx +98 -0
  46. package/src/components/RemoteCursor/RemoteCursorLayer.tsx +97 -0
  47. package/src/components/RemoteCursor/index.ts +6 -0
  48. package/src/components/ScrollScope/ScrollScope.stories.tsx +97 -0
  49. package/src/components/ScrollScope/ScrollScope.tsx +59 -0
  50. package/src/components/ScrollScope/index.ts +5 -0
  51. package/src/components/index.ts +2 -0
  52. package/src/types/Activity.test.ts +53 -0
  53. package/src/types/Activity.ts +110 -0
  54. package/src/types/ScrollPosition.ts +34 -0
  55. package/src/types/ViewLocation.ts +28 -0
  56. package/src/types/ViewState.test.ts +74 -1
  57. package/src/types/ViewState.ts +217 -4
  58. package/src/types/index.ts +3 -0
@@ -0,0 +1,110 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { type Hue, type Label } from '@dxos/ui-types';
6
+
7
+ /**
8
+ * The places on the attention glyph an activity can draw: the square's fill, the mark inside it, its edge, and a dot
9
+ * at its corner. Each holds at most one treatment.
10
+ */
11
+ export type Slot = 'fill' | 'mark' | 'edge' | 'corner';
12
+
13
+ /** The slots in drawing order, back to front. */
14
+ export const Slots: readonly Slot[] = ['fill', 'mark', 'edge', 'corner'];
15
+
16
+ /** A mark the glyph draws itself; any other mark is a Phosphor icon id (e.g. `ph--warning--fill`). */
17
+ export type MarkShape = 'dot' | 'dots' | 'star';
18
+
19
+ /** What every treatment carries, whatever its slot. */
20
+ type Common = {
21
+ /** Within a slot the highest priority wins, and a tie goes to the first requested. */
22
+ readonly priority: number;
23
+ /** Asks for the slot's motion; at most one slot moves (see {@link resolve}). */
24
+ readonly animate?: boolean;
25
+ };
26
+
27
+ /** A wash of colour behind the mark. Attention always takes the fill first. */
28
+ export type Fill = Common & {
29
+ readonly slot: 'fill';
30
+ readonly hue: Hue;
31
+ /** How much of the hue shows, from 0 to 1; 0.25 when unset. */
32
+ readonly opacity?: number;
33
+ };
34
+
35
+ export type Mark = Common & {
36
+ readonly slot: 'mark';
37
+ readonly icon: MarkShape | (string & {});
38
+ /** The text colour when unset. */
39
+ readonly hue?: Hue;
40
+ };
41
+
42
+ /** An outline around the square, dashed for something due rather than under way. */
43
+ export type Edge = Omit<Common, 'animate'> & {
44
+ readonly slot: 'edge';
45
+ readonly hue: Hue;
46
+ readonly dashed?: boolean;
47
+ };
48
+
49
+ /** A dot, or a ring, just outside the square's top-right corner. */
50
+ export type Corner = Common & {
51
+ readonly slot: 'corner';
52
+ readonly hue: Hue;
53
+ readonly shape?: 'dot' | 'ring';
54
+ };
55
+
56
+ /** How one activity draws: which slot it claims, what it draws there and how strongly it claims it. */
57
+ export type Treatment = Fill | Mark | Edge | Corner;
58
+
59
+ /** Something happening on an object, as one line of the glyph's tooltip and, optionally, one treatment on it. */
60
+ export type Entry = {
61
+ /** Who reported it, e.g. `presence` or `assistant`. */
62
+ readonly source: string;
63
+ /** Shown in the tooltip whether or not the treatment wins its slot. */
64
+ readonly label: Label;
65
+ readonly treatment?: Treatment;
66
+ };
67
+
68
+ /** Which slot keeps its motion when several animate: what asks for you first, then who is there. */
69
+ const MOTION_ORDER: readonly ('corner' | 'mark' | 'fill')[] = ['corner', 'mark', 'fill'];
70
+
71
+ /** What the glyph draws: the winning treatment per slot, and the one slot whose treatment animates. */
72
+ export type Resolved = {
73
+ readonly fill?: Fill;
74
+ readonly mark?: Mark;
75
+ readonly edge?: Edge;
76
+ readonly corner?: Corner;
77
+ readonly moving?: Slot;
78
+ };
79
+
80
+ export type ResolveOptions = {
81
+ /** The item is attended, or contains the attended item: attention holds the fill, still, over any treatment. */
82
+ readonly attention?: boolean;
83
+ };
84
+
85
+ type InSlot<S extends Slot> = Extract<Treatment, { slot: S }>;
86
+
87
+ const winner = <S extends Slot>(treatments: readonly Treatment[], slot: S): InSlot<S> | undefined =>
88
+ treatments
89
+ .filter((treatment): treatment is InSlot<S> => treatment.slot === slot)
90
+ .reduce<InSlot<S> | undefined>(
91
+ (best, treatment) => (!best || treatment.priority > best.priority ? treatment : best),
92
+ undefined,
93
+ );
94
+
95
+ /**
96
+ * Reduces any set of requested treatments to one per slot by priority, then lets only the first animated slot in
97
+ * {@link MOTION_ORDER} move, so every combination draws at most four things and animates at most one.
98
+ */
99
+ export const resolve = (treatments: Iterable<Treatment>, { attention }: ResolveOptions = {}): Resolved => {
100
+ const requested = [...treatments];
101
+ const resolved = {
102
+ fill: attention ? undefined : winner(requested, 'fill'),
103
+ mark: winner(requested, 'mark'),
104
+ edge: winner(requested, 'edge'),
105
+ corner: winner(requested, 'corner'),
106
+ };
107
+ const moving = MOTION_ORDER.find((slot) => resolved[slot]?.animate);
108
+
109
+ return { ...resolved, moving };
110
+ };
@@ -0,0 +1,34 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Schema from 'effect/Schema';
6
+
7
+ import { type Aspect, define } from './ViewState.ts';
8
+
9
+ /** Where one scrolling area is scrolled to; see `ScrollArea.ScrollPosition` in react-ui. */
10
+ export const Position = Schema.Struct({
11
+ anchor: Schema.optional(Schema.String),
12
+ offset: Schema.optional(Schema.Number),
13
+ y: Schema.Number,
14
+ x: Schema.optional(Schema.Number),
15
+ });
16
+
17
+ export type Position = Schema.Schema.Type<typeof Position>;
18
+
19
+ /** The position of each tracked scrolling area in an object's view, by area name (`main` for the outermost). */
20
+ export const State = Schema.Record(Schema.String, Position);
21
+
22
+ export type State = Schema.Schema.Type<typeof State>;
23
+
24
+ /**
25
+ * The scroll of an object's article, keyed by the object's EID and kept for the session, so a view comes back where it
26
+ * was left; a follower takes the leader's.
27
+ */
28
+ export const aspect: Aspect<State> = define<State>({
29
+ key: 'org.dxos.react-ui-attention.scroll',
30
+ backend: 'memory',
31
+ schema: State,
32
+ defaultValue: () => ({}),
33
+ follow: 'write',
34
+ });
@@ -0,0 +1,28 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Schema from 'effect/Schema';
6
+
7
+ import { type Aspect, define } from './ViewState.ts';
8
+
9
+ /**
10
+ * Where the local user is in an object, as anchors in the object type's own format (the format its
11
+ * comments and its `Locator` use), so a peer's view of the same object can reveal it.
12
+ */
13
+ export const ViewLocation = Schema.Struct({
14
+ /** The caret or selection. */
15
+ selection: Schema.optional(Schema.String),
16
+ /** The top of what the view shows. */
17
+ viewport: Schema.optional(Schema.String),
18
+ });
19
+
20
+ export type ViewLocation = Schema.Schema.Type<typeof ViewLocation>;
21
+
22
+ /** View location for an object, keyed by the object's URI and stored in memory (ephemeral, per-device session). */
23
+ export const aspect: Aspect<ViewLocation> = define<ViewLocation>({
24
+ key: 'view-location',
25
+ backend: 'memory',
26
+ schema: ViewLocation,
27
+ defaultValue: () => ({}),
28
+ });
@@ -8,7 +8,7 @@ import * as Struct from 'effect/Struct';
8
8
  import { describe, test } from 'vitest';
9
9
 
10
10
  import { createDefaultBackends } from '../core/index.ts';
11
- import { Manager, define } from './ViewState.ts';
11
+ import { Manager, define, patch } from './ViewState.ts';
12
12
 
13
13
  const Counter = define({
14
14
  key: 'counter',
@@ -17,6 +17,19 @@ const Counter = define({
17
17
  defaultValue: () => ({ value: 0 }),
18
18
  });
19
19
 
20
+ const Followed = define({ ...Counter, key: 'followed', follow: 'write' });
21
+
22
+ const Camera = define({
23
+ key: 'camera',
24
+ backend: 'memory',
25
+ schema: Schema.Struct({ zoom: Schema.Number, grid: Schema.Boolean }).mapFields(Struct.map(Schema.mutableKey)),
26
+ defaultValue: () => ({ zoom: 1, grid: false }),
27
+ follow: { policy: 'write', fields: ['zoom'] },
28
+ });
29
+
30
+ const A = 'echo:@A';
31
+ const B = 'echo:@B';
32
+
20
33
  describe('Manager', () => {
21
34
  const make = () => {
22
35
  const registry = Registry.make();
@@ -52,4 +65,64 @@ describe('Manager', () => {
52
65
  manager.set(Counter, 'b', { value: 2 });
53
66
  expect(new Set(manager.contexts(Counter))).toEqual(new Set(['a', 'b']));
54
67
  });
68
+
69
+ test("a follower takes the leader's encoded values of followed aspects, holding those for an aspect it has not used", ({
70
+ expect,
71
+ }) => {
72
+ const leader = make();
73
+ leader.set(Counter, 'a', { value: 1 });
74
+ leader.set(Followed, 'a', { value: 2 });
75
+ leader.set(Followed, 'b', { value: 3 });
76
+ const sent = leader.followed(['a']);
77
+ expect(sent).toEqual({ followed: { a: { value: 2 } } });
78
+
79
+ const follower = make();
80
+ follower.setEncoded('followed', 'a', sent.followed.a);
81
+ follower.setEncoded('followed', 'c', 'not a counter');
82
+ expect(follower.get(Followed, 'a')).toEqual({ value: 2 });
83
+ expect(follower.get(Followed, 'c')).toEqual({ value: 0 });
84
+ });
85
+
86
+ test("an aspect following some fields sends only those and merges the leader's into the follower's own", ({
87
+ expect,
88
+ }) => {
89
+ const leader = make();
90
+ leader.set(Camera, A, { zoom: 2, grid: true });
91
+ const sent = leader.followed([A]);
92
+ expect(sent).toEqual({ camera: { [A]: { zoom: 2 } } });
93
+
94
+ const follower = make();
95
+ follower.set(Camera, A, { zoom: 1, grid: false });
96
+ follower.setEncoded('camera', A, sent.camera[A]);
97
+ expect(follower.get(Camera, A)).toEqual({ zoom: 2, grid: false });
98
+ });
99
+
100
+ test('a value written from the leader has the follow origin until this session sets it', ({ expect }) => {
101
+ const manager = make();
102
+ const origins: string[] = [];
103
+ const dispose = manager.subscribe(Followed, A, (_, origin) => origins.push(origin));
104
+ manager.setEncoded('followed', A, { value: 2 });
105
+ expect(manager.origin(Followed, A)).toBe('follow');
106
+ manager.set(Followed, A, { value: 3 });
107
+ expect(manager.origin(Followed, A)).toBe('local');
108
+ expect(origins).toEqual(['follow', 'local']);
109
+ dispose();
110
+ });
111
+
112
+ test('a patch merges its fields over the current value, held until the aspect is used', ({ expect }) => {
113
+ const manager = make();
114
+ manager.apply(patch(Camera, A, { zoom: 2 }));
115
+ manager.set(Camera, B, { zoom: 1, grid: true });
116
+ manager.apply(patch(Camera, B, { zoom: 3 }));
117
+ expect(manager.get(Camera, A)).toEqual({ zoom: 2, grid: false });
118
+ expect(manager.get(Camera, B)).toEqual({ zoom: 3, grid: true });
119
+ expect(manager.origin(Camera, A)).toBe('local');
120
+ });
121
+
122
+ test('a patch that does not decode is dropped', ({ expect }) => {
123
+ const manager = make();
124
+ manager.set(Camera, A, { zoom: 2, grid: true });
125
+ manager.apply({ aspect: 'camera', context: A, fields: { zoom: 'near' } });
126
+ expect(manager.get(Camera, A)).toEqual({ zoom: 2, grid: true });
127
+ });
55
128
  });
@@ -2,15 +2,39 @@
2
2
  // Copyright 2026 DXOS.org
3
3
  //
4
4
 
5
+ import * as Option from 'effect/Option';
5
6
  import type * as Atom from 'effect/reactivity/Atom';
6
7
  import type * as Registry from 'effect/reactivity/AtomRegistry';
7
- import type * as Schema from 'effect/Schema';
8
+ import * as Schema from 'effect/Schema';
9
+
10
+ import { EID } from '@dxos/keys';
11
+ import { log } from '@dxos/log';
8
12
 
9
13
  /**
10
14
  * Persistence backend identifier. `personal` (ECHO/personal-space) is reserved for a future backend.
11
15
  */
12
16
  export type BackendName = 'memory' | 'local';
13
17
 
18
+ /**
19
+ * How a session following another takes the leader's values of an aspect: `write` sets them into its own view state,
20
+ * which the view already reads; `reveal` leaves them to the follow, for state a view reports but does not read back.
21
+ */
22
+ export type FollowPolicy = 'write' | 'reveal';
23
+
24
+ /**
25
+ * What of an aspect a follower takes: the whole value under a policy, or only the named fields of a struct value,
26
+ * which a `write` follower merges into its own value.
27
+ */
28
+ export type Follow<T> =
29
+ | FollowPolicy
30
+ | { readonly policy: FollowPolicy; readonly fields: ReadonlyArray<keyof T & string> };
31
+
32
+ /** Whether a value was set by this session or written from the session it follows. */
33
+ export type Origin = 'local' | 'follow';
34
+
35
+ export const getFollowPolicy = (aspect: Aspect<any, any>): FollowPolicy | undefined =>
36
+ typeof aspect.follow === 'object' ? aspect.follow.policy : aspect.follow;
37
+
14
38
  /**
15
39
  * Declares a kind of per-context UI state. The value type `T` and its persisted wire type `Encoded`
16
40
  * are inferred from the schema; `Encoded` defaults to `T` for the common no-transform case.
@@ -20,6 +44,8 @@ export interface Aspect<T, Encoded = T> {
20
44
  readonly backend: BackendName;
21
45
  readonly schema: Schema.Codec<T, Encoded>;
22
46
  readonly defaultValue: () => T;
47
+ /** Set for state a follower takes from the session it follows; contexts are then EIDs of the space or its objects. */
48
+ readonly follow?: Follow<T>;
23
49
  }
24
50
 
25
51
  /**
@@ -38,6 +64,31 @@ export interface Aspect<T, Encoded = T> {
38
64
  */
39
65
  export const define = <T, Encoded = T>(def: Aspect<T, Encoded>): Aspect<T, Encoded> => def;
40
66
 
67
+ /** Encoded fields to merge over one aspect's value for one context; plain JSON, so it can cross an operation. */
68
+ export const Patch = Schema.Struct({
69
+ aspect: Schema.String.annotate({ description: "The aspect's key." }),
70
+ context: Schema.String.annotate({ description: 'The context the aspect is keyed by.' }),
71
+ fields: Schema.Record(Schema.String, Schema.Unknown).annotate({
72
+ description: "Encoded top-level fields, merged over the aspect's current value.",
73
+ }),
74
+ });
75
+
76
+ export type Patch = Schema.Schema.Type<typeof Patch>;
77
+
78
+ /** A patch setting `fields` of `aspect` for `context`, encoded by the aspect's schema. */
79
+ export const patch = <T extends object, Encoded>(
80
+ aspect: Aspect<T, Encoded>,
81
+ context: string,
82
+ fields: Partial<T>,
83
+ ): Patch => {
84
+ const encoded = Schema.encodeUnknownSync(Schema.toCodecJson(aspect.schema))({ ...aspect.defaultValue(), ...fields });
85
+ return {
86
+ aspect: aspect.key,
87
+ context,
88
+ fields: isRecord(encoded) ? pickKeys(encoded, Object.keys(fields)) : {},
89
+ };
90
+ };
91
+
41
92
  /**
42
93
  * A backend produces a reactive, writable atom for each `(aspect, contextId)` pair. Backends may
43
94
  * hydrate asynchronously (an ECHO backend would), yielding `aspect.defaultValue()` until loaded;
@@ -66,6 +117,17 @@ export interface ManagerOptions {
66
117
  export class Manager {
67
118
  readonly #registry: Registry.AtomRegistry;
68
119
  readonly #backends: Record<BackendName, Backend>;
120
+ // Aspects are declared where they are used, so the manager learns them from the calls that pass them.
121
+ readonly #aspects = new Map<string, Aspect<any, any>>();
122
+ // A leader's encoded values of an aspect this session has not used yet, decoded when it first is.
123
+ readonly #pending = new Map<string, Map<string, unknown>>();
124
+ // Patches to an aspect this session has not used yet, applied in order when it first is.
125
+ readonly #pendingPatches = new Map<string, Patch[]>();
126
+ readonly #followListeners = new Set<(key: string, contextId: string) => void>();
127
+ // Values written from the followed session, by aspect key and context; a local write clears its entry.
128
+ readonly #fromFollow = new Set<string>();
129
+ // Followed aspects already warned about for a context that is not an EID.
130
+ readonly #warned = new Set<string>();
69
131
 
70
132
  constructor({ registry, backends }: ManagerOptions) {
71
133
  this.#registry = registry;
@@ -74,6 +136,14 @@ export class Manager {
74
136
 
75
137
  /** Reactive atom for `(aspect, contextId)`; pass to `registry.get` inside derived atoms/hooks. */
76
138
  atom<T, Encoded>(aspect: Aspect<T, Encoded>, contextId: string): Atom.Writable<T> {
139
+ this.#learn(aspect);
140
+ if (aspect.follow && !EID.isEID(contextId) && !this.#warned.has(aspect.key)) {
141
+ this.#warned.add(aspect.key);
142
+ log.warn('a followed aspect is keyed by something other than an EID, so it is never followed', {
143
+ aspect: aspect.key,
144
+ contextId,
145
+ });
146
+ }
77
147
  return this.#backends[aspect.backend].atom(aspect, contextId);
78
148
  }
79
149
 
@@ -82,21 +152,164 @@ export class Manager {
82
152
  }
83
153
 
84
154
  set<T, Encoded>(aspect: Aspect<T, Encoded>, contextId: string, value: T): void {
155
+ this.#write(aspect, contextId, value, 'local');
156
+ }
157
+
158
+ /** Whether the value of `(aspect, contextId)` was set here or written from the followed session. */
159
+ origin<T, Encoded>(aspect: Aspect<T, Encoded>, contextId: string): Origin {
160
+ return this.#fromFollow.has(originKey(aspect.key, contextId)) ? 'follow' : 'local';
161
+ }
162
+
163
+ #write<T, Encoded>(aspect: Aspect<T, Encoded>, contextId: string, value: T, origin: Origin): void {
85
164
  const backend = this.#backends[aspect.backend];
86
- this.#registry.set(backend.atom(aspect, contextId), value);
165
+ if (origin === 'follow') {
166
+ this.#fromFollow.add(originKey(aspect.key, contextId));
167
+ } else {
168
+ this.#fromFollow.delete(originKey(aspect.key, contextId));
169
+ }
170
+ this.#registry.set(this.atom(aspect, contextId), value);
87
171
  backend.persist?.(aspect, contextId, value);
172
+ if (aspect.follow) {
173
+ this.#followListeners.forEach((listener) => listener(aspect.key, contextId));
174
+ }
88
175
  }
89
176
 
90
177
  update<T, Encoded>(aspect: Aspect<T, Encoded>, contextId: string, fn: (prev: T) => T): void {
91
178
  this.set(aspect, contextId, fn(this.get(aspect, contextId)));
92
179
  }
93
180
 
94
- subscribe<T, Encoded>(aspect: Aspect<T, Encoded>, contextId: string, cb: (value: T) => void): () => void {
181
+ subscribe<T, Encoded>(
182
+ aspect: Aspect<T, Encoded>,
183
+ contextId: string,
184
+ cb: (value: T, origin: Origin) => void,
185
+ ): () => void {
95
186
  const atom = this.atom(aspect, contextId);
96
- return this.#registry.subscribe(atom, () => cb(this.#registry.get(atom)));
187
+ return this.#registry.subscribe(atom, () => cb(this.#registry.get(atom), this.origin(aspect, contextId)));
97
188
  }
98
189
 
99
190
  contexts<T, Encoded>(aspect: Aspect<T, Encoded>): string[] {
191
+ this.#learn(aspect);
100
192
  return this.#backends[aspect.backend].contexts(aspect);
101
193
  }
194
+
195
+ /** The aspect with `key`, once this session has used it. */
196
+ aspect(key: string): Aspect<unknown, unknown> | undefined {
197
+ return this.#aspects.get(key);
198
+ }
199
+
200
+ /** This session's values of every followed aspect it has used, encoded as JSON, by aspect key and then context. */
201
+ followed(contextIds: readonly string[]): Record<string, Record<string, Schema.Json>> {
202
+ return Object.fromEntries(
203
+ [...this.#aspects.values()].flatMap((aspect) => {
204
+ if (!aspect.follow) {
205
+ return [];
206
+ }
207
+ const held = new Set(this.contexts(aspect));
208
+ const values = Object.fromEntries(
209
+ contextIds.flatMap((contextId) =>
210
+ held.has(contextId)
211
+ ? Option.match(this.#encode(aspect, contextId), {
212
+ onNone: () => [],
213
+ onSome: (json) => [[contextId, pickFollowed(aspect, json)]],
214
+ })
215
+ : [],
216
+ ),
217
+ );
218
+ return Object.keys(values).length > 0 ? [[aspect.key, values]] : [];
219
+ }),
220
+ );
221
+ }
222
+
223
+ /** Calls `listener` when a followed aspect's value is set. */
224
+ subscribeFollowed(listener: (key: string, contextId: string) => void): () => void {
225
+ this.#followListeners.add(listener);
226
+ return () => this.#followListeners.delete(listener);
227
+ }
228
+
229
+ /** Sets a leader's encoded value of a `write` aspect; one not used yet is held until it is, and one that does not decode is dropped. */
230
+ setEncoded(key: string, contextId: string, value: unknown): void {
231
+ const aspect = this.#aspects.get(key);
232
+ if (aspect) {
233
+ this.#decodeInto(aspect, contextId, value);
234
+ } else {
235
+ this.#pending.set(key, (this.#pending.get(key) ?? new Map()).set(contextId, value));
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Merges a patch's fields over its aspect's value for its context, as a local write. A patch to an aspect this
241
+ * session has not used yet is held until it is; one whose merged value does not decode is dropped.
242
+ */
243
+ apply(patch: Patch): void {
244
+ const aspect = this.#aspects.get(patch.aspect);
245
+ if (aspect) {
246
+ this.#patchInto(aspect, patch);
247
+ } else {
248
+ this.#pendingPatches.set(patch.aspect, [...(this.#pendingPatches.get(patch.aspect) ?? []), patch]);
249
+ }
250
+ }
251
+
252
+ #learn(aspect: Aspect<any, any>): void {
253
+ if (this.#aspects.has(aspect.key)) {
254
+ return;
255
+ }
256
+ this.#aspects.set(aspect.key, aspect);
257
+ const pending = this.#pending.get(aspect.key);
258
+ this.#pending.delete(aspect.key);
259
+ pending?.forEach((value, contextId) => this.#decodeInto(aspect, contextId, value));
260
+ const patches = this.#pendingPatches.get(aspect.key);
261
+ this.#pendingPatches.delete(aspect.key);
262
+ patches?.forEach((patch) => this.#patchInto(aspect, patch));
263
+ }
264
+
265
+ #patchInto(aspect: Aspect<any, any>, { context, fields }: Patch): void {
266
+ const own = this.#encode(aspect, context).pipe(
267
+ Option.filter(isRecord),
268
+ Option.getOrElse(() => ({})),
269
+ );
270
+ Option.match(Schema.decodeUnknownOption(Schema.toCodecJson(aspect.schema))({ ...own, ...fields }), {
271
+ onNone: () => log.warn('dropped a view-state patch that does not decode', { aspect: aspect.key, context }),
272
+ onSome: (decoded) => this.#write(aspect, context, decoded, 'local'),
273
+ });
274
+ }
275
+
276
+ #encode(aspect: Aspect<any, any>, contextId: string): Option.Option<Schema.Json> {
277
+ return Schema.encodeUnknownOption(Schema.toCodecJson(aspect.schema))(this.get(aspect, contextId));
278
+ }
279
+
280
+ // Only a `write` aspect takes a leader's value; a `reveal` one is the follow's to apply. An aspect that follows some
281
+ // fields takes the leader's values of those over its own value.
282
+ #decodeInto(aspect: Aspect<any, any>, contextId: string, value: unknown): void {
283
+ if (getFollowPolicy(aspect) !== 'write') {
284
+ return;
285
+ }
286
+ const merged =
287
+ typeof aspect.follow === 'object' && isRecord(value)
288
+ ? Option.match(this.#encode(aspect, contextId), {
289
+ onNone: () => value,
290
+ onSome: (own) => ({ ...(isRecord(own) ? own : {}), ...pickFields(aspect, value) }),
291
+ })
292
+ : value;
293
+ Option.match(Schema.decodeUnknownOption(Schema.toCodecJson(aspect.schema))(merged), {
294
+ onNone: () => {},
295
+ onSome: (decoded) => this.#write(aspect, contextId, decoded, 'follow'),
296
+ });
297
+ }
102
298
  }
299
+
300
+ const originKey = (key: string, contextId: string) => `${key}\n${contextId}`;
301
+
302
+ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
303
+ typeof value === 'object' && value !== null && !Array.isArray(value);
304
+
305
+ const isJsonObject = (value: Schema.Json): value is Schema.JsonObject => isRecord(value);
306
+
307
+ const pickKeys = <V>(record: Readonly<Record<string, V>>, keys: readonly string[]): Record<string, V> =>
308
+ Object.fromEntries(Object.entries(record).filter(([key]) => keys.includes(key)));
309
+
310
+ const pickFields = <V>(aspect: Aspect<any, any>, record: Readonly<Record<string, V>>): Record<string, V> =>
311
+ pickKeys(record, typeof aspect.follow === 'object' ? aspect.follow.fields : []);
312
+
313
+ // An aspect that follows some fields sends only those; struct fields encode under their own names.
314
+ const pickFollowed = (aspect: Aspect<any, any>, json: Schema.Json): Schema.Json =>
315
+ typeof aspect.follow === 'object' && isJsonObject(json) ? pickFields(aspect, json) : json;
@@ -6,8 +6,11 @@
6
6
  // operation handlers and app-graph builders running under node or bun can use them without pulling
7
7
  // the components.
8
8
 
9
+ export * as Activity from './Activity.ts';
9
10
  export * as Attention from './Attention.ts';
11
+ export * as ScrollPosition from './ScrollPosition.ts';
10
12
  export * as Selection from './Selection.ts';
13
+ export * as ViewLocation from './ViewLocation.ts';
11
14
  export * as ViewState from './ViewState.ts';
12
15
 
13
16
  // The view-state backends: Effect atoms over the definitions above, with no React of their own, so