@dxos/react-ui-attention 0.8.4-main.7ace549 → 0.8.4-main.937b3ca

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 (50) hide show
  1. package/dist/lib/browser/chunk-HJRZWOEX.mjs +705 -0
  2. package/dist/lib/browser/chunk-HJRZWOEX.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-PAZBZOO2.mjs +7 -0
  4. package/dist/lib/browser/chunk-PAZBZOO2.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +73 -4
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +8 -3
  9. package/dist/lib/browser/testing/index.mjs.map +3 -3
  10. package/dist/lib/browser/types.mjs +7 -0
  11. package/dist/lib/browser/types.mjs.map +7 -0
  12. package/dist/lib/node-esm/chunk-7TQWDE4M.mjs +706 -0
  13. package/dist/lib/node-esm/chunk-7TQWDE4M.mjs.map +7 -0
  14. package/dist/lib/node-esm/chunk-PMGNPL4M.mjs +9 -0
  15. package/dist/lib/node-esm/chunk-PMGNPL4M.mjs.map +7 -0
  16. package/dist/lib/node-esm/index.mjs +73 -4
  17. package/dist/lib/node-esm/index.mjs.map +4 -4
  18. package/dist/lib/node-esm/meta.json +1 -1
  19. package/dist/lib/node-esm/testing/index.mjs +8 -3
  20. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  21. package/dist/lib/node-esm/types.mjs +8 -0
  22. package/dist/lib/node-esm/types.mjs.map +7 -0
  23. package/dist/types/src/attention.d.ts +22 -18
  24. package/dist/types/src/attention.d.ts.map +1 -1
  25. package/dist/types/src/components/AttentionProvider.d.ts +3 -2
  26. package/dist/types/src/components/AttentionProvider.d.ts.map +1 -1
  27. package/dist/types/src/components/SelectionProvider.d.ts +5 -4
  28. package/dist/types/src/components/SelectionProvider.d.ts.map +1 -1
  29. package/dist/types/src/index.d.ts +1 -0
  30. package/dist/types/src/index.d.ts.map +1 -1
  31. package/dist/types/src/selection.d.ts +23 -3
  32. package/dist/types/src/selection.d.ts.map +1 -1
  33. package/dist/types/src/testing/decorators/withAttention.d.ts.map +1 -1
  34. package/dist/types/src/types.d.ts +10 -0
  35. package/dist/types/src/types.d.ts.map +1 -0
  36. package/dist/types/tsconfig.tsbuildinfo +1 -1
  37. package/package.json +35 -23
  38. package/src/attention.test.ts +12 -7
  39. package/src/attention.ts +64 -41
  40. package/src/components/AttentionGlyph.tsx +1 -1
  41. package/src/components/AttentionProvider.tsx +63 -54
  42. package/src/components/SelectionProvider.tsx +60 -15
  43. package/src/index.ts +1 -0
  44. package/src/selection.ts +111 -71
  45. package/src/testing/decorators/withAttention.ts +8 -2
  46. package/src/types.ts +16 -0
  47. package/dist/lib/browser/chunk-R3FWNCI3.mjs +0 -656
  48. package/dist/lib/browser/chunk-R3FWNCI3.mjs.map +0 -7
  49. package/dist/lib/node-esm/chunk-IKC2JDMW.mjs +0 -658
  50. package/dist/lib/node-esm/chunk-IKC2JDMW.mjs.map +0 -7
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "@dxos/react-ui-attention",
3
- "version": "0.8.4-main.7ace549",
3
+ "version": "0.8.4-main.937b3ca",
4
4
  "description": "Signifier components and providers for attention system.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/dxos/dxos"
10
+ },
7
11
  "license": "MIT",
8
12
  "author": "DXOS.org",
9
- "sideEffects": true,
13
+ "sideEffects": false,
10
14
  "type": "module",
11
15
  "exports": {
12
16
  ".": {
@@ -15,6 +19,12 @@
15
19
  "browser": "./dist/lib/browser/index.mjs",
16
20
  "node": "./dist/lib/node-esm/index.mjs"
17
21
  },
22
+ "./types": {
23
+ "source": "./src/types.ts",
24
+ "types": "./dist/types/src/types.d.ts",
25
+ "browser": "./dist/lib/browser/types.mjs",
26
+ "node": "./dist/lib/node-esm/types.mjs"
27
+ },
18
28
  "./testing": {
19
29
  "source": "./src/testing/index.ts",
20
30
  "types": "./dist/types/src/testing/index.d.ts",
@@ -25,6 +35,9 @@
25
35
  "types": "dist/types/src/index.d.ts",
26
36
  "typesVersions": {
27
37
  "*": {
38
+ "types": [
39
+ "dist/types/src/types.d.ts"
40
+ ],
28
41
  "testing": [
29
42
  "dist/types/src/testing/index.d.ts"
30
43
  ]
@@ -35,8 +48,7 @@
35
48
  "src"
36
49
  ],
37
50
  "dependencies": {
38
- "@preact-signals/safe-react": "^0.9.0",
39
- "@preact/signals-core": "^1.12.1",
51
+ "@effect-atom/atom-react": "^0.4.6",
40
52
  "@radix-ui/primitive": "1.1.1",
41
53
  "@radix-ui/react-compose-refs": "1.1.1",
42
54
  "@radix-ui/react-context": "1.1.1",
@@ -44,30 +56,30 @@
44
56
  "@radix-ui/react-primitive": "2.0.2",
45
57
  "@radix-ui/react-slot": "1.1.2",
46
58
  "@radix-ui/react-use-controllable-state": "1.1.0",
47
- "effect": "3.18.3",
48
- "@dxos/echo": "0.8.4-main.7ace549",
49
- "@dxos/live-object": "0.8.4-main.7ace549",
50
- "@dxos/invariant": "0.8.4-main.7ace549",
51
- "@dxos/util": "0.8.4-main.7ace549",
52
- "@dxos/log": "0.8.4-main.7ace549"
59
+ "effect": "3.19.11",
60
+ "@dxos/invariant": "0.8.4-main.937b3ca",
61
+ "@dxos/echo": "0.8.4-main.937b3ca",
62
+ "@dxos/log": "0.8.4-main.937b3ca",
63
+ "@dxos/react-hooks": "0.8.4-main.937b3ca",
64
+ "@dxos/util": "0.8.4-main.937b3ca"
53
65
  },
54
66
  "devDependencies": {
55
- "@types/react": "~19.2.2",
56
- "@types/react-dom": "~19.2.2",
57
- "react": "~19.2.0",
58
- "react-dom": "~19.2.0",
67
+ "@types/react": "~19.2.7",
68
+ "@types/react-dom": "~19.2.3",
69
+ "react": "~19.2.3",
70
+ "react-dom": "~19.2.3",
59
71
  "vite": "7.1.9",
60
- "@dxos/random": "0.8.4-main.7ace549",
61
- "@dxos/react-ui": "0.8.4-main.7ace549",
62
- "@dxos/react-ui-theme": "0.8.4-main.7ace549",
63
- "@dxos/storybook-utils": "0.8.4-main.7ace549"
72
+ "@dxos/random": "0.8.4-main.937b3ca",
73
+ "@dxos/react-ui": "0.8.4-main.937b3ca",
74
+ "@dxos/storybook-utils": "0.8.4-main.937b3ca",
75
+ "@dxos/ui-theme": "0.8.4-main.937b3ca"
64
76
  },
65
77
  "peerDependencies": {
66
- "effect": "^3.13.3",
67
- "react": "^19.0.0",
68
- "react-dom": "^19.0.0",
69
- "@dxos/react-ui": "0.8.4-main.7ace549",
70
- "@dxos/react-ui-theme": "0.8.4-main.7ace549"
78
+ "effect": "3.19.11",
79
+ "react": "~19.2.3",
80
+ "react-dom": "~19.2.3",
81
+ "@dxos/react-ui": "0.8.4-main.937b3ca",
82
+ "@dxos/ui-theme": "0.8.4-main.937b3ca"
71
83
  },
72
84
  "publishConfig": {
73
85
  "access": "public"
@@ -2,14 +2,16 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
+ import { Registry } from '@effect-atom/atom-react';
5
6
  import { describe, expect, test } from 'vitest';
6
7
 
7
8
  import { AttentionManager } from './attention';
8
9
 
9
10
  describe('AttentionManager', () => {
10
11
  test('takes an initial attendable', () => {
11
- const attention = new AttentionManager(['a', 'b', 'c']);
12
- expect(attention.current).to.deep.equal(['a', 'b', 'c']);
12
+ const registry = Registry.make();
13
+ const attention = new AttentionManager(registry, ['a', 'b', 'c']);
14
+ expect(attention.getCurrent()).to.deep.equal(['a', 'b', 'c']);
13
15
  expect(attention.keys()).to.deep.equal([['a'], ['b', 'c'], ['c'], ['a', 'b', 'c']]);
14
16
  expect(attention.get(['a'])).to.deep.equal({ hasAttention: false, isAncestor: false, isRelated: true });
15
17
  expect(attention.get(['b', 'c'])).to.deep.equal({ hasAttention: false, isAncestor: true, isRelated: false });
@@ -19,15 +21,17 @@ describe('AttentionManager', () => {
19
21
  });
20
22
 
21
23
  test('current returns last updated key', () => {
22
- const attention = new AttentionManager();
23
- expect(attention.current).to.deep.equal([]);
24
+ const registry = Registry.make();
25
+ const attention = new AttentionManager(registry);
26
+ expect(attention.getCurrent()).to.deep.equal([]);
24
27
 
25
28
  attention.update(['a', 'b', 'c']);
26
- expect(attention.current).to.deep.equal(['a', 'b', 'c']);
29
+ expect(attention.getCurrent()).to.deep.equal(['a', 'b', 'c']);
27
30
  });
28
31
 
29
32
  test('keys returns all stored attendables', () => {
30
- const attention = new AttentionManager();
33
+ const registry = Registry.make();
34
+ const attention = new AttentionManager(registry);
31
35
  expect(attention.keys()).to.deep.equal([]);
32
36
 
33
37
  attention.update(['a']);
@@ -38,7 +42,8 @@ describe('AttentionManager', () => {
38
42
  });
39
43
 
40
44
  test('get returns attention object for a given key', () => {
41
- const attention = new AttentionManager();
45
+ const registry = Registry.make();
46
+ const attention = new AttentionManager(registry);
42
47
  expect(attention.get(['a'])).to.deep.equal({ hasAttention: false, isAncestor: false, isRelated: false });
43
48
 
44
49
  attention.update(['a']);
package/src/attention.ts CHANGED
@@ -2,23 +2,11 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { untracked } from '@preact/signals-core';
5
+ import { Atom, type Registry } from '@effect-atom/atom-react';
6
6
 
7
- import { type Live, live } from '@dxos/live-object';
8
7
  import { ComplexMap } from '@dxos/util';
9
8
 
10
- // NOTE: Chosen from RFC 1738's `safe` characters: http://www.faqs.org/rfcs/rfc1738.html
11
- export const ATTENDABLE_PATH_SEPARATOR = '~';
12
-
13
- export type Attention = {
14
- hasAttention: boolean;
15
- isAncestor: boolean;
16
- isRelated: boolean;
17
- };
18
-
19
- export type CurrentState = {
20
- current: string[];
21
- };
9
+ import { ATTENDABLE_PATH_SEPARATOR, type Attention } from './types';
22
10
 
23
11
  // TODO(wittjosiah): Use mosaic path utility?
24
12
  const stringKey = (key: string[]) => key.join(',');
@@ -26,27 +14,44 @@ const stringKey = (key: string[]) => key.join(',');
26
14
  /**
27
15
  * Manages attention state for an application.
28
16
  */
29
- // TODO(wittjosiah): Write unit tests.
30
17
  export class AttentionManager {
31
- // TODO(wittjosiah): Migrate to Effect Atom.
32
- // Each attention path is associated with an attention object.
18
+ // Each attention path is associated with an attention atom.
33
19
  // The lookup is not a reactive object to ensure that attention for each path is subscribable independently.
34
- private readonly _map = new ComplexMap<string[], Live<Attention>>(stringKey);
35
- private readonly _state = live<CurrentState>({ current: [] });
36
-
37
- constructor(initial: string[] = []) {
20
+ private readonly _map = new ComplexMap<string[], Atom.Writable<Attention>>(stringKey);
21
+ private readonly _currentAtom: Atom.Writable<string[]>;
22
+
23
+ constructor(
24
+ private readonly _registry: Registry.Registry,
25
+ initial: string[] = [],
26
+ ) {
27
+ this._currentAtom = Atom.make<string[]>([]);
38
28
  if (initial.length > 0) {
39
29
  this.update(initial);
40
30
  }
41
31
  }
42
32
 
43
33
  /**
44
- * Currently attended element.
45
- *
46
- * @reactive
34
+ * Atom for the currently attended element path.
35
+ */
36
+ get current(): Atom.Atom<string[]> {
37
+ return this._currentAtom;
38
+ }
39
+
40
+ /**
41
+ * Gets the currently attended element path.
47
42
  */
48
- get current(): Live<readonly string[]> {
49
- return this._state.current;
43
+ getCurrent(): readonly string[] {
44
+ return this._registry.get(this._currentAtom);
45
+ }
46
+
47
+ /**
48
+ * Subscribe to changes in the current attention path.
49
+ */
50
+ subscribeCurrent(cb: (current: readonly string[]) => void): () => void {
51
+ this._registry.get(this._currentAtom);
52
+ return this._registry.subscribe(this._currentAtom, () => {
53
+ cb(this._registry.get(this._currentAtom));
54
+ });
50
55
  }
51
56
 
52
57
  /**
@@ -59,15 +64,31 @@ export class AttentionManager {
59
64
  /**
60
65
  * Get the attention state for a given path.
61
66
  */
62
- get(key: string[]): Live<Attention> {
63
- const object = this._map.get(key);
64
- if (object) {
65
- return object;
67
+ get(key: string[]): Attention {
68
+ const atom = this._getAtom(key);
69
+ return this._registry.get(atom);
70
+ }
71
+
72
+ /**
73
+ * Subscribe to changes in the attention state for a given path.
74
+ */
75
+ subscribe(key: string[], cb: (attention: Attention) => void): () => void {
76
+ const atom = this._getAtom(key);
77
+ this._registry.get(atom);
78
+ return this._registry.subscribe(atom, () => {
79
+ cb(this._registry.get(atom));
80
+ });
81
+ }
82
+
83
+ private _getAtom(key: string[]): Atom.Writable<Attention> {
84
+ const existing = this._map.get(key);
85
+ if (existing) {
86
+ return existing;
66
87
  }
67
88
 
68
- const newObject = live<Attention>({ hasAttention: false, isAncestor: false, isRelated: false });
69
- this._map.set(key, newObject);
70
- return newObject;
89
+ const newAtom = Atom.make<Attention>({ hasAttention: false, isAncestor: false, isRelated: false });
90
+ this._map.set(key, newAtom);
91
+ return newAtom;
71
92
  }
72
93
 
73
94
  /**
@@ -76,12 +97,12 @@ export class AttentionManager {
76
97
  * @internal
77
98
  */
78
99
  update(nextKey: string[]): void {
79
- const currentKey = untracked(() => this.current);
100
+ const currentKey = this.getCurrent();
80
101
  const currentRelatedTo = currentKey[0];
81
102
  const nextRelatedTo = nextKey[0];
82
103
 
83
104
  // Ensure related attention object is initialized.
84
- this.get([nextRelatedTo]);
105
+ this._getAtom([nextRelatedTo]);
85
106
 
86
107
  const currentRelatedKeys = this.keys().filter((key) => key[0] === currentRelatedTo);
87
108
  const nextRelatedKeys = this.keys().filter(
@@ -97,7 +118,7 @@ export class AttentionManager {
97
118
  (curr) => !nextAncestorKeys.find((next) => stringKey(curr) === stringKey(next)),
98
119
  );
99
120
 
100
- this._state.current = nextKey;
121
+ this._registry.set(this._currentAtom, nextKey);
101
122
  prevRelatedKeys.forEach((key) => this._set(key, {}));
102
123
  prevAncestorKeys.forEach((key) => this._set(key, {}));
103
124
  nextRelatedKeys.forEach((key) => this._set(key, { isRelated: true }));
@@ -106,15 +127,17 @@ export class AttentionManager {
106
127
  }
107
128
 
108
129
  private _set(key: string[], attention: Partial<Attention>): void {
109
- const object = this.get(key);
110
- object.hasAttention = attention.hasAttention ?? false;
111
- object.isAncestor = attention.isAncestor ?? false;
112
- object.isRelated = attention.isRelated ?? false;
130
+ const atom = this._getAtom(key);
131
+ this._registry.set(atom, {
132
+ hasAttention: attention.hasAttention ?? false,
133
+ isAncestor: attention.isAncestor ?? false,
134
+ isRelated: attention.isRelated ?? false,
135
+ });
113
136
  }
114
137
  }
115
138
 
116
139
  /**
117
- * Accumulates all attendable id’s between the element provided and the root, inclusive.
140
+ * Accumulates all attendable id's between the element provided and the root, inclusive.
118
141
  */
119
142
  export const getAttendables = (selector: string, cursor: Element, acc: string[] = []): string[] => {
120
143
  // Find the closest element with `data-attendable-id`, if any; start from cursor and move up the DOM tree.
@@ -6,7 +6,7 @@ import { type Primitive } from '@radix-ui/react-primitive';
6
6
  import React, { type CSSProperties, type ComponentPropsWithRef, forwardRef, useMemo } from 'react';
7
7
 
8
8
  import { Icon, type ThemedClassName } from '@dxos/react-ui';
9
- import { mx } from '@dxos/react-ui-theme';
9
+ import { mx } from '@dxos/ui-theme';
10
10
 
11
11
  const attentionGlyphStyles =
12
12
  'inline-block rounded-sm is-3 bs-3 bg-transparent text-accentText transition-colors [[data-contains-attended=true]_&]:bg-attentionRelated [[data-attention=true]_&]:bg-accentSurface [[data-attention=true]_&]:text-accentSurfaceText [[aria-current][data-attention=true]_&]:bg-accentSurface [[aria-current][data-attention=true]_&]:text-accentSurfaceText';
@@ -2,16 +2,28 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
+ import { RegistryContext } from '@effect-atom/atom-react';
5
6
  import { createContext } from '@radix-ui/react-context';
6
7
  import { Primitive } from '@radix-ui/react-primitive';
7
8
  import { Slot } from '@radix-ui/react-slot';
8
- import React, { type ComponentPropsWithRef, type FocusEvent, type PropsWithChildren, forwardRef, useMemo } from 'react';
9
+ import React, {
10
+ type ComponentPropsWithRef,
11
+ type FocusEvent,
12
+ type PropsWithChildren,
13
+ forwardRef,
14
+ useContext,
15
+ useEffect,
16
+ useMemo,
17
+ useState,
18
+ } from 'react';
9
19
 
10
20
  import { log } from '@dxos/log';
11
- import { type ThemedClassName, useDefaultValue } from '@dxos/react-ui';
12
- import { mx } from '@dxos/react-ui-theme';
21
+ import { useDefaultValue } from '@dxos/react-hooks';
22
+ import { type ThemedClassName } from '@dxos/react-ui';
23
+ import { mx } from '@dxos/ui-theme';
13
24
 
14
- import { ATTENDABLE_PATH_SEPARATOR, type Attention, AttentionManager, getAttendables } from '../attention';
25
+ import { AttentionManager, getAttendables } from '../attention';
26
+ import { ATTENDABLE_PATH_SEPARATOR, type Attention } from '../types';
15
27
 
16
28
  const ATTENTION_NAME = 'Attention';
17
29
  const ATTENDABLE_ATTRIBUTE = 'data-attendable-id';
@@ -23,7 +35,7 @@ type AttentionContextValue = {
23
35
  };
24
36
 
25
37
  const [AttentionContextProvider, useAttentionContext] = createContext<AttentionContextValue>(ATTENTION_NAME, {
26
- attention: new AttentionManager(),
38
+ attention: undefined as unknown as AttentionManager,
27
39
  path: [],
28
40
  });
29
41
 
@@ -31,17 +43,52 @@ const UNKNOWN_ATTENDABLE = { hasAttention: false, isAncestor: false, isRelated:
31
43
 
32
44
  const useAttention = (attendableId?: string): Attention => {
33
45
  const { attention, path } = useAttentionContext(ATTENTION_NAME);
34
- if (!attendableId) {
35
- return UNKNOWN_ATTENDABLE;
36
- }
46
+ const [state, setState] = useState<Attention>(UNKNOWN_ATTENDABLE);
37
47
 
38
- const current = [...attendableId.split(ATTENDABLE_PATH_SEPARATOR), ...path];
39
- return attention.get(current);
48
+ const key = useMemo(() => {
49
+ if (!attendableId) {
50
+ return undefined;
51
+ }
52
+ return [...attendableId.split(ATTENDABLE_PATH_SEPARATOR), ...path];
53
+ }, [attendableId, path]);
54
+
55
+ useEffect(() => {
56
+ if (!key || !attention) {
57
+ setState(UNKNOWN_ATTENDABLE);
58
+ return;
59
+ }
60
+
61
+ // Set initial state.
62
+ setState(attention.get(key));
63
+
64
+ // Subscribe to changes.
65
+ return attention.subscribe(key, (newState) => {
66
+ setState(newState);
67
+ });
68
+ }, [attention, key]);
69
+
70
+ return state;
40
71
  };
41
72
 
42
73
  const useAttended = () => {
43
74
  const { attention } = useAttentionContext(ATTENTION_NAME);
44
- return attention.current;
75
+ const [current, setCurrent] = useState<readonly string[]>([]);
76
+
77
+ useEffect(() => {
78
+ if (!attention) {
79
+ return;
80
+ }
81
+
82
+ // Set initial state.
83
+ setCurrent(attention.getCurrent());
84
+
85
+ // Subscribe to changes.
86
+ return attention.subscribeCurrent((newCurrent) => {
87
+ setCurrent(newCurrent);
88
+ });
89
+ }, [attention]);
90
+
91
+ return current;
45
92
  };
46
93
 
47
94
  /**
@@ -75,7 +122,9 @@ const RootAttentionProvider = ({
75
122
  onChange: (nextAttended: string[]) => void;
76
123
  }>
77
124
  >) => {
78
- const attention = useDefaultValue(propsAttention, () => new AttentionManager());
125
+ const registry = useContext(RegistryContext);
126
+ const attention = useDefaultValue(propsAttention, () => new AttentionManager(registry));
127
+
79
128
  const handleFocus = (event: FocusEvent) => {
80
129
  // NOTE(thure): Use the following to debug focus movement across the app:
81
130
  log('focus', { related: event.relatedTarget, target: event.target });
@@ -86,7 +135,7 @@ const RootAttentionProvider = ({
86
135
  (el) => `[id="${el.getAttribute('aria-controls')}"]`,
87
136
  ),
88
137
  ].join(',');
89
- const prev = attention.current;
138
+ const prev = attention.getCurrent();
90
139
  const next = getAttendables(selector, event.target);
91
140
  // TODO(wittjosiah): Not allowing empty state means that the attended item is not strictly guaranteed to be in the DOM.
92
141
  // Currently this depends on the deck in order to ensure that when the attended item is removed something else is attended.
@@ -97,49 +146,9 @@ const RootAttentionProvider = ({
97
146
  }
98
147
  };
99
148
 
100
- // NOTE(thure): Use the following to debug the macOS package issue #8540:
101
-
102
- // const [startEl, setStartEl] = useState<HTMLElement | null>(null);
103
- // const [endEl, setEndEl] = useState<HTMLElement | null>(null);
104
- //
105
- // const handleEventDebug = useCallback((event: any) => {
106
- // console.log(`[${event.type}]`, event.target, event.currentTarget, [event.clientX, event.clientY]);
107
- // }, []);
108
- //
109
- // const handleStartDebug = useCallback(
110
- // (event: any) => {
111
- // setStartEl(event.target);
112
- // handleEventDebug(event);
113
- // },
114
- // [handleEventDebug],
115
- // );
116
- //
117
- // const handleEndDebug = useCallback(
118
- // (event: any) => {
119
- // setEndEl(event.target);
120
- // handleEventDebug(event);
121
- // },
122
- // [handleEventDebug],
123
- // );
124
- //
125
- // const handleClickDebug = useCallback(
126
- // (event: any) => {
127
- // console.log('[click compare]', startEl, endEl, startEl === endEl);
128
- // handleEventDebug(event);
129
- // },
130
- // [startEl, endEl, handleEventDebug],
131
- // );
132
-
133
149
  return (
134
150
  <AttentionContextProvider attention={attention} path={[]}>
135
- <div
136
- role='none'
137
- className='contents'
138
- onFocusCapture={handleFocus}
139
- // onClick={handleClickDebug}
140
- // onMouseDown={handleStartDebug}
141
- // onMouseUp={handleEndDebug}
142
- >
151
+ <div role='none' className='contents' onFocusCapture={handleFocus}>
143
152
  {children}
144
153
  </div>
145
154
  </AttentionContextProvider>
@@ -2,11 +2,12 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import { RegistryContext } from '@effect-atom/atom-react';
5
6
  import { createContext } from '@radix-ui/react-context';
6
7
  import * as Match from 'effect/Match';
7
- import React, { type PropsWithChildren, useCallback, useMemo } from 'react';
8
+ import React, { type PropsWithChildren, useCallback, useContext, useEffect, useMemo, useState } from 'react';
8
9
 
9
- import { useDefaultValue } from '@dxos/react-ui';
10
+ import { useDefaultValue } from '@dxos/react-hooks';
10
11
 
11
12
  import {
12
13
  type Selection,
@@ -23,7 +24,7 @@ type SelectionContextValue = {
23
24
  };
24
25
 
25
26
  const [SelectionContextProvider, useSelectionContext] = createContext<SelectionContextValue>(SELECTION_NAME, {
26
- selection: new SelectionManager(),
27
+ selection: undefined as unknown as SelectionManager,
27
28
  });
28
29
 
29
30
  /**
@@ -34,7 +35,8 @@ export const SelectionProvider = ({
34
35
  children,
35
36
  selection: propsSelection,
36
37
  }: PropsWithChildren<{ selection?: SelectionManager }>) => {
37
- const selection = useDefaultValue(propsSelection, () => new SelectionManager());
38
+ const registry = useContext(RegistryContext);
39
+ const selection = useDefaultValue(propsSelection, () => new SelectionManager(registry));
38
40
  return <SelectionContextProvider selection={selection}>{children}</SelectionContextProvider>;
39
41
  };
40
42
 
@@ -46,6 +48,16 @@ export const useSelectionManager = () => {
46
48
  return selection;
47
49
  };
48
50
 
51
+ const getDefaultResult = <T extends SelectionMode>(mode: T): SelectionResult<T> => {
52
+ return Match.type<Selection>().pipe(
53
+ Match.when({ mode: 'single' }, (s) => s.id),
54
+ Match.when({ mode: 'multi' }, (s) => s.ids),
55
+ Match.when({ mode: 'range' }, (s) => (s.from && s.to ? { from: s.from, to: s.to } : undefined)),
56
+ Match.when({ mode: 'multi-range' }, (s) => s.ranges),
57
+ Match.exhaustive,
58
+ )(defaultSelection(mode)) as SelectionResult<T>;
59
+ };
60
+
49
61
  /**
50
62
  * Get the selected objects for a given context.
51
63
  */
@@ -54,28 +66,49 @@ export const useSelected = <T extends SelectionMode>(
54
66
  mode: T = 'multi' as T,
55
67
  ): SelectionResult<T> => {
56
68
  const { selection } = useSelectionContext(SELECTION_NAME);
57
- if (contextId) {
58
- return selection.getSelected(contextId, mode);
59
- }
69
+ const [state, setState] = useState<SelectionResult<T>>(() =>
70
+ contextId && selection ? selection.getSelected(contextId, mode) : getDefaultResult(mode),
71
+ );
60
72
 
61
- return Match.type<Selection>().pipe(
62
- Match.when({ mode: 'single' }, (s) => s.id),
63
- Match.when({ mode: 'multi' }, (s) => s.ids),
64
- Match.when({ mode: 'range' }, (s) => (s.from && s.to ? { from: s.from, to: s.to } : undefined)),
65
- Match.when({ mode: 'multi-range' }, (s) => s.ranges),
66
- Match.exhaustive,
67
- )(defaultSelection(mode)) as any;
73
+ useEffect(() => {
74
+ if (!contextId || !selection) {
75
+ setState(getDefaultResult(mode));
76
+ return;
77
+ }
78
+
79
+ // Set initial state.
80
+ setState(selection.getSelected(contextId, mode));
81
+
82
+ // Subscribe to changes.
83
+ return selection.subscribe(() => {
84
+ setState(selection.getSelected(contextId, mode));
85
+ });
86
+ }, [selection, contextId, mode]);
87
+
88
+ return state;
89
+ };
90
+
91
+ export type UseSelectionActions = {
92
+ singleSelect: (id: string) => void;
93
+ multiSelect: (ids: string[]) => void;
94
+ rangeSelect: (from: string, to: string) => void;
95
+ toggle: (id: string) => void;
96
+ clear: () => void;
68
97
  };
69
98
 
70
99
  /**
71
100
  * Provides functions to manage the selection state for multiple contexts.
72
101
  */
73
- export const useSelectionActions = (contextIds: string[], mode: SelectionMode = 'multi') => {
102
+ // TODO(burdon): Mode not used.
103
+ export const useSelectionActions = (contextIds: string[], mode: SelectionMode = 'multi'): UseSelectionActions => {
74
104
  const stableContextIds = useMemo(() => contextIds, [JSON.stringify(contextIds)]); // TODO(burdon): Avoid stringify.
75
105
  const { selection } = useSelectionContext(SELECTION_NAME);
76
106
 
77
107
  const singleSelect = useCallback(
78
108
  (id: string) => {
109
+ if (!selection) {
110
+ return;
111
+ }
79
112
  for (const contextId of stableContextIds) {
80
113
  selection.updateSingle(contextId, id);
81
114
  }
@@ -85,6 +118,9 @@ export const useSelectionActions = (contextIds: string[], mode: SelectionMode =
85
118
 
86
119
  const multiSelect = useCallback(
87
120
  (ids: string[]) => {
121
+ if (!selection) {
122
+ return;
123
+ }
88
124
  for (const contextId of stableContextIds) {
89
125
  selection.updateMulti(contextId, ids);
90
126
  }
@@ -94,6 +130,9 @@ export const useSelectionActions = (contextIds: string[], mode: SelectionMode =
94
130
 
95
131
  const rangeSelect = useCallback(
96
132
  (from: string, to: string) => {
133
+ if (!selection) {
134
+ return;
135
+ }
97
136
  for (const contextId of stableContextIds) {
98
137
  selection.updateRange(contextId, from, to);
99
138
  }
@@ -103,6 +142,9 @@ export const useSelectionActions = (contextIds: string[], mode: SelectionMode =
103
142
 
104
143
  const toggle = useCallback(
105
144
  (id: string) => {
145
+ if (!selection) {
146
+ return;
147
+ }
106
148
  for (const contextId of stableContextIds) {
107
149
  selection.toggleSelection(contextId, id);
108
150
  }
@@ -111,6 +153,9 @@ export const useSelectionActions = (contextIds: string[], mode: SelectionMode =
111
153
  );
112
154
 
113
155
  const clear = useCallback(() => {
156
+ if (!selection) {
157
+ return;
158
+ }
114
159
  for (const contextId of stableContextIds) {
115
160
  selection.clearSelection(contextId);
116
161
  }
package/src/index.ts CHANGED
@@ -5,3 +5,4 @@
5
5
  export * from './attention';
6
6
  export * from './components';
7
7
  export * from './selection';
8
+ export * from './types';