@sanity/sdk-react 3.0.0-rc.1 → 3.0.0-rc.2

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 (57) hide show
  1. package/dist/index.d.ts +2289 -2702
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +4315 -1915
  4. package/dist/index.js.map +1 -1
  5. package/package.json +13 -14
  6. package/src/_exports/sdk-react.ts +9 -6
  7. package/src/components/SanityApp.tsx +2 -3
  8. package/src/components/auth/AuthBoundary.test.tsx +1 -19
  9. package/src/components/auth/AuthBoundary.tsx +2 -1
  10. package/src/components/auth/LoginError.tsx +2 -3
  11. package/src/context/ComlinkTokenRefresh.tsx +3 -5
  12. package/src/context/ResourceProvider.test.tsx +21 -0
  13. package/src/context/ResourceProvider.tsx +4 -1
  14. package/src/hooks/agent/agentActions.test.tsx +1 -1
  15. package/src/hooks/agent/agentActions.ts +1 -1
  16. package/src/hooks/agent/useAgentResourceContext.ts +1 -1
  17. package/src/hooks/comlink/useFrameConnection.test.tsx +3 -2
  18. package/src/hooks/comlink/useFrameConnection.ts +1 -1
  19. package/src/hooks/comlink/useWindowConnection.test.tsx +4 -3
  20. package/src/hooks/comlink/useWindowConnection.ts +2 -3
  21. package/src/hooks/comments/useCommentActions.test.tsx +150 -0
  22. package/src/hooks/comments/useCommentActions.ts +109 -0
  23. package/src/hooks/comments/useCommentList.ts +79 -0
  24. package/src/hooks/comments/useCommentThreads.test.tsx +107 -0
  25. package/src/hooks/comments/useCommentThreads.ts +73 -0
  26. package/src/hooks/comments/useComments.test.tsx +242 -0
  27. package/src/hooks/comments/useComments.ts +59 -0
  28. package/src/hooks/context/useSanityInstance.test.tsx +2 -54
  29. package/src/hooks/context/useSanityInstance.ts +2 -24
  30. package/src/hooks/dashboard/useManageFavorite.ts +1 -1
  31. package/src/hooks/dashboard/useRecordDocumentHistoryEvent.ts +2 -1
  32. package/src/hooks/documents/useDocuments.ts +2 -7
  33. package/src/hooks/helpers/useNormalizedResourceOptions.test.tsx +0 -27
  34. package/src/hooks/helpers/useNormalizedResourceOptions.ts +14 -25
  35. package/src/hooks/paginatedDocuments/usePaginatedDocuments.ts +2 -7
  36. package/src/hooks/presence/usePresence.ts +14 -1
  37. package/src/hooks/presence/usePresenceForDocument.test.tsx +141 -0
  38. package/src/hooks/presence/usePresenceForDocument.ts +104 -0
  39. package/src/hooks/presence/useReportPresence.test.tsx +202 -0
  40. package/src/hooks/presence/useReportPresence.ts +170 -0
  41. package/src/hooks/preview/useDocumentPreview.tsx +2 -6
  42. package/src/hooks/projects/useProjects.ts +0 -8
  43. package/src/hooks/query/useQuery.ts +3 -8
  44. package/src/hooks/releases/useActiveReleases.ts +2 -2
  45. package/src/hooks/releases/useAllReleases.ts +2 -2
  46. package/src/hooks/users/useUser.ts +2 -8
  47. package/src/hooks/users/useUsers.ts +1 -2
  48. package/src/hooks/applications/useCreateUserApplication.test-d.ts +0 -14
  49. package/src/hooks/applications/useCreateUserApplication.ts +0 -11
  50. package/src/hooks/applications/useDeleteUserApplication.test-d.ts +0 -14
  51. package/src/hooks/applications/useDeleteUserApplication.ts +0 -11
  52. package/src/hooks/applications/useUpdateUserApplication.test-d.ts +0 -14
  53. package/src/hooks/applications/useUpdateUserApplication.ts +0 -11
  54. package/src/hooks/applications/useUserApplication.test-d.ts +0 -11
  55. package/src/hooks/applications/useUserApplication.ts +0 -14
  56. package/src/hooks/applications/useUserApplications.test-d.ts +0 -11
  57. package/src/hooks/applications/useUserApplications.ts +0 -14
@@ -6,7 +6,8 @@ import {
6
6
  SDK_NODE_NAME,
7
7
  type StudioResource,
8
8
  } from '@sanity/message-protocol'
9
- import {type DocumentHandle, type FrameMessage} from '@sanity/sdk'
9
+ import {type DocumentHandle} from '@sanity/sdk'
10
+ import {type FrameMessage} from '@sanity/sdk/comlink'
10
11
  import {useCallback} from 'react'
11
12
 
12
13
  import {useWindowConnection} from '../comlink/useWindowConnection'
@@ -1,10 +1,5 @@
1
- import {
2
- createGroqSearchFilter,
3
- type DocumentHandle,
4
- isDatasetResource,
5
- type QueryOptions,
6
- } from '@sanity/sdk'
7
- import {pickProperties} from '@sanity/sdk/_internal'
1
+ import {type DocumentHandle, isDatasetResource, type QueryOptions} from '@sanity/sdk'
2
+ import {createGroqSearchFilter, pickProperties} from '@sanity/sdk/_internal'
8
3
  import {type SortOrderingItem} from '@sanity/types'
9
4
  import {useCallback, useMemo, useState} from 'react'
10
5
 
@@ -91,21 +91,6 @@ describe('useNormalizedResourceOptions', () => {
91
91
  ),
92
92
  ).toThrow()
93
93
  })
94
-
95
- it('resolves deprecated `source` as `resource`', () => {
96
- const {result} = renderHook(() =>
97
- useNormalizedResourceOptions({source: {projectId: 'src', dataset: 'src-ds'}}),
98
- )
99
- expect(result.current.resource).toEqual({projectId: 'src', dataset: 'src-ds'})
100
- })
101
-
102
- it('resolves deprecated `sourceName` as `resourceName`', () => {
103
- const {result} = renderHook(() => useNormalizedResourceOptions({sourceName: 'dataset'}))
104
- expect(result.current.resource).toEqual({
105
- projectId: 'resource-project-id',
106
- dataset: 'resource-dataset',
107
- })
108
- })
109
94
  })
110
95
 
111
96
  describe('tier 2 — bare projectId/dataset in options', () => {
@@ -232,18 +217,6 @@ describe('useNormalizedResourceOptions', () => {
232
217
  expect(result.current).not.toHaveProperty('dataset')
233
218
  })
234
219
 
235
- it('strips deprecated source from the result', () => {
236
- const {result} = renderHook(() =>
237
- useNormalizedResourceOptions({source: {projectId: 'src', dataset: 'src-ds'}}),
238
- )
239
- expect(result.current).not.toHaveProperty('source')
240
- })
241
-
242
- it('strips deprecated sourceName from the result', () => {
243
- const {result} = renderHook(() => useNormalizedResourceOptions({sourceName: 'dataset'}))
244
- expect(result.current).not.toHaveProperty('sourceName')
245
- })
246
-
247
220
  it('preserves unrelated fields', () => {
248
221
  const opts: DocumentHandle = {documentId: 'doc-1', documentType: 'article'}
249
222
  const {result} = renderHook(() => useNormalizedResourceOptions(opts))
@@ -6,7 +6,7 @@ import {PerspectiveContext} from '../../context/PerspectiveContext'
6
6
  import {ResourcesContext} from '../../context/ResourcesContext'
7
7
  import {SanityInstanceContext} from '../../context/SanityInstanceContext'
8
8
 
9
- type NormalizedResourceFields = 'resourceName' | 'source' | 'sourceName' | 'projectId' | 'dataset'
9
+ type NormalizedResourceFields = 'resourceName' | 'projectId' | 'dataset'
10
10
 
11
11
  /**
12
12
  * Adds React hook support (resourceName resolution) to core types.
@@ -24,11 +24,6 @@ export type WithResourceNameSupport<T extends {resource?: DocumentResource}> = T
24
24
  * @beta
25
25
  */
26
26
  resourceName?: string
27
- /**
28
- * @deprecated Use `resourceName` instead.
29
- * @beta
30
- */
31
- sourceName?: string
32
27
  }
33
28
 
34
29
  /**
@@ -48,8 +43,6 @@ export function normalizeResourceOptions<
48
43
  T extends {
49
44
  resource?: DocumentResource
50
45
  resourceName?: string
51
- source?: DocumentResource
52
- sourceName?: string
53
46
  projectId?: string
54
47
  dataset?: string
55
48
  perspective?: unknown
@@ -60,30 +53,27 @@ export function normalizeResourceOptions<
60
53
  contextResource?: DocumentResource,
61
54
  contextPerspective?: PerspectiveHandle['perspective'],
62
55
  ): Omit<T, NormalizedResourceFields> {
63
- const {resourceName, sourceName, source, projectId, dataset, ...rest} = options
64
-
65
- // Coalesce deprecated aliases to their canonical equivalents
66
- const effectiveResourceName = resourceName ?? sourceName
67
- const effectiveResource = options.resource ?? source
56
+ const {resourceName, projectId, dataset, ...rest} = options
57
+ const resource = options.resource
68
58
 
69
- if (effectiveResourceName && effectiveResource) {
59
+ if (resourceName && resource) {
70
60
  throw new Error(
71
- `Resource name ${JSON.stringify(effectiveResourceName)} and resource ${JSON.stringify(effectiveResource)} cannot be used together.`,
61
+ `Resource name ${JSON.stringify(resourceName)} and resource ${JSON.stringify(resource)} cannot be used together.`,
72
62
  )
73
63
  }
74
64
 
75
65
  let resolvedResource: DocumentResource | undefined
76
66
 
77
67
  // Tier (a): explicit resource object or resourceName lookup
78
- if (effectiveResource) {
79
- resolvedResource = effectiveResource
80
- } else if (effectiveResourceName) {
81
- if (!Object.hasOwn(resources, effectiveResourceName)) {
68
+ if (resource) {
69
+ resolvedResource = resource
70
+ } else if (resourceName) {
71
+ if (!Object.hasOwn(resources, resourceName)) {
82
72
  throw new Error(
83
- `There's no resource named ${JSON.stringify(effectiveResourceName)} in context. Please use <ResourceProvider>.`,
73
+ `There's no resource named ${JSON.stringify(resourceName)} in context. Please use <ResourceProvider>.`,
84
74
  )
85
75
  }
86
- resolvedResource = resources[effectiveResourceName]
76
+ resolvedResource = resources[resourceName]
87
77
  }
88
78
 
89
79
  // Tier (b): projectId or dataset in options → synthesize a resource
@@ -121,13 +111,14 @@ export function normalizeResourceOptions<
121
111
  export function useEffectiveContextResource(): DocumentResource | undefined {
122
112
  const contextResource = useContext(ResourceContext)
123
113
  const instance = useContext(SanityInstanceContext)
124
- const {projectId, dataset} = instance?.config ?? {}
114
+ const {projectId, dataset, resource: configResource} = instance?.config ?? {}
125
115
 
126
116
  return useMemo(() => {
127
117
  if (contextResource) return contextResource
118
+ if (configResource) return configResource
128
119
  if (projectId && dataset) return {projectId, dataset}
129
120
  return undefined
130
- }, [contextResource, projectId, dataset])
121
+ }, [contextResource, configResource, projectId, dataset])
131
122
  }
132
123
 
133
124
  /**
@@ -149,8 +140,6 @@ export function useNormalizedResourceOptions<
149
140
  T extends {
150
141
  resource?: DocumentResource
151
142
  resourceName?: string
152
- source?: DocumentResource
153
- sourceName?: string
154
143
  projectId?: string
155
144
  dataset?: string
156
145
  perspective?: PerspectiveHandle['perspective']
@@ -1,10 +1,5 @@
1
- import {
2
- createGroqSearchFilter,
3
- type DocumentHandle,
4
- isDatasetResource,
5
- type QueryOptions,
6
- } from '@sanity/sdk'
7
- import {pickProperties} from '@sanity/sdk/_internal'
1
+ import {type DocumentHandle, isDatasetResource, type QueryOptions} from '@sanity/sdk'
2
+ import {createGroqSearchFilter, pickProperties} from '@sanity/sdk/_internal'
8
3
  import {type SortOrderingItem} from '@sanity/types'
9
4
  import {useCallback, useMemo, useState} from 'react'
10
5
 
@@ -7,7 +7,20 @@ import {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOpti
7
7
  import {trackHookUsage} from '../helpers/useTrackHookUsage'
8
8
 
9
9
  /**
10
- * A hook for subscribing to presence information for the current project or Canvas.
10
+ * Every participant in the current project and dataset, or Canvas.
11
+ *
12
+ * Reading presence never announces anything. Call `useReportPresence` to make the
13
+ * current user visible to others, including to the Studio, which shares the same
14
+ * presence room.
15
+ *
16
+ * This returns everyone in the whole resource and leaves the filtering to you.
17
+ * Prefer `usePresenceForDocument` when you care about one document: it scopes and
18
+ * flattens the result for rendering. Note that participants are counted by session,
19
+ * so one person in two tabs appears twice.
20
+ *
21
+ * Presence is scoped to a single project and dataset. It is not a list of everyone
22
+ * signed in to your organization.
23
+ *
11
24
  * @public
12
25
  */
13
26
  export function usePresence(options: ResourceHandle = {}): {
@@ -0,0 +1,141 @@
1
+ import {type DocumentPresence, getDocumentPresence} from '@sanity/sdk'
2
+ import {act, renderHook} from '@testing-library/react'
3
+ import {beforeEach, describe, expect, it, vi} from 'vitest'
4
+
5
+ import {ResourceProvider} from '../../context/ResourceProvider'
6
+ import {usePresenceForDocument} from './usePresenceForDocument'
7
+
8
+ vi.mock('@sanity/sdk', async (importOriginal) => {
9
+ const actual = await importOriginal<typeof import('@sanity/sdk')>()
10
+ return {...actual, getDocumentPresence: vi.fn()}
11
+ })
12
+
13
+ const entry = (sessionId: string): DocumentPresence =>
14
+ ({
15
+ sessionId,
16
+ documentId: 'movie-1',
17
+ path: ['title'],
18
+ lastActiveAt: '2026-07-30T12:00:00Z',
19
+ user: {sanityUserId: 'u1', profile: {id: 'u1'}, memberships: []},
20
+ }) as unknown as DocumentPresence
21
+
22
+ /** A minimal StateSource stand-in whose value can be pushed. */
23
+ function createSource(initial: DocumentPresence[]) {
24
+ let current = initial
25
+ const listeners = new Set<() => void>()
26
+ return {
27
+ source: {
28
+ getCurrent: () => current,
29
+ subscribe: (cb: () => void) => {
30
+ listeners.add(cb)
31
+ return () => listeners.delete(cb)
32
+ },
33
+ },
34
+ push: (next: DocumentPresence[]) => {
35
+ current = next
36
+ listeners.forEach((cb) => cb())
37
+ },
38
+ }
39
+ }
40
+
41
+ const wrapper = ({children}: {children: React.ReactNode}) => (
42
+ <ResourceProvider projectId="p" dataset="d" fallback={null}>
43
+ {children}
44
+ </ResourceProvider>
45
+ )
46
+
47
+ describe('usePresenceForDocument', () => {
48
+ beforeEach(() => {
49
+ // Without this, `mock.calls[0]` is whatever the previous test did.
50
+ vi.clearAllMocks()
51
+ })
52
+
53
+ it('returns presence and updates when the store changes', () => {
54
+ const {source, push} = createSource([entry('s1')])
55
+ vi.mocked(getDocumentPresence).mockReturnValue(source as never)
56
+
57
+ const {result} = renderHook(
58
+ () => usePresenceForDocument({documentId: 'movie-1', documentType: 'movie'}),
59
+ {wrapper},
60
+ )
61
+
62
+ expect(result.current.presence).toHaveLength(1)
63
+
64
+ act(() => push([entry('s1'), entry('s2')]))
65
+ expect(result.current.presence).toHaveLength(2)
66
+ })
67
+
68
+ it('passes the document, path, and excludeVersions through', () => {
69
+ const {source} = createSource([])
70
+ vi.mocked(getDocumentPresence).mockReturnValue(source as never)
71
+
72
+ renderHook(
73
+ () =>
74
+ usePresenceForDocument({
75
+ documentId: 'drafts.movie-1',
76
+ documentType: 'movie',
77
+ path: ['cast', {_key: 'm1'}],
78
+ excludeVersions: true,
79
+ }),
80
+ {wrapper},
81
+ )
82
+
83
+ // Already a draft id, so resolution leaves it alone.
84
+ expect(vi.mocked(getDocumentPresence).mock.calls[0][1]).toMatchObject({
85
+ documentId: 'drafts.movie-1',
86
+ path: ['cast', {_key: 'm1'}],
87
+ excludeVersions: true,
88
+ })
89
+ })
90
+
91
+ it('reads the same id useReportPresence writes, or reads never match writes', () => {
92
+ const {source} = createSource([])
93
+ vi.mocked(getDocumentPresence).mockReturnValue(source as never)
94
+
95
+ // Forwarded unresolved, exactly as `useReportPresence` forwards it, so core
96
+ // resolves both the same way. If these diverged, field-level presence would
97
+ // silently never match.
98
+ renderHook(
99
+ () =>
100
+ usePresenceForDocument({
101
+ documentId: 'movie-1',
102
+ documentType: 'movie',
103
+ perspective: 'published',
104
+ }),
105
+ {wrapper},
106
+ )
107
+
108
+ expect(vi.mocked(getDocumentPresence).mock.calls[0][1]).toMatchObject({
109
+ documentId: 'movie-1',
110
+ perspective: 'published',
111
+ })
112
+ })
113
+
114
+ it('does not rebuild the source when a caller passes a fresh path each render', () => {
115
+ const {source} = createSource([])
116
+ vi.mocked(getDocumentPresence).mockReturnValue(source as never)
117
+
118
+ const {rerender} = renderHook(
119
+ // A new array identity every render, which is what real callers write.
120
+ () => usePresenceForDocument({documentId: 'movie-1', documentType: 'movie', path: ['title']}),
121
+ {wrapper},
122
+ )
123
+
124
+ rerender()
125
+ rerender()
126
+
127
+ expect(vi.mocked(getDocumentPresence)).toHaveBeenCalledTimes(1)
128
+ })
129
+
130
+ it('returns an empty array rather than undefined before anything arrives', () => {
131
+ const {source} = createSource(undefined as unknown as DocumentPresence[])
132
+ vi.mocked(getDocumentPresence).mockReturnValue(source as never)
133
+
134
+ const {result} = renderHook(
135
+ () => usePresenceForDocument({documentId: 'movie-1', documentType: 'movie'}),
136
+ {wrapper},
137
+ )
138
+
139
+ expect(result.current.presence).toEqual([])
140
+ })
141
+ })
@@ -0,0 +1,104 @@
1
+ import {type DocumentPresence, getDocumentPresence, isMediaLibraryResource} from '@sanity/sdk'
2
+ import {type Path} from '@sanity/types'
3
+ import {useCallback, useMemo, useSyncExternalStore} from 'react'
4
+
5
+ import {type DocumentHandle} from '../../config/handles'
6
+ import {useSanityInstance} from '../context/useSanityInstance'
7
+ import {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'
8
+ import {trackHookUsage} from '../helpers/useTrackHookUsage'
9
+
10
+ /** @beta */
11
+ export interface UsePresenceForDocumentOptions extends DocumentHandle {
12
+ /**
13
+ * Narrows to participants at or below this field path, which is what a field
14
+ * indicator wants. Omit it for everyone in the document.
15
+ */
16
+ path?: Path
17
+
18
+ /**
19
+ * By default a draft, its published version, and any release versions count as
20
+ * the same document, which is what document lists want. Set this to compare ids
21
+ * exactly, so that a draft and a release version do not bleed into each other.
22
+ */
23
+ excludeVersions?: boolean
24
+ }
25
+
26
+ /**
27
+ * Who else is in a document, flattened to one entry per participant per location
28
+ * so it can be rendered straight against a field.
29
+ *
30
+ * Reading presence never announces anything. Use `useReportPresence` to make the
31
+ * current user visible to others.
32
+ *
33
+ * Prefer this over `usePresence` when you care about one document: `usePresence`
34
+ * returns every participant in the whole project and dataset, leaving the filtering
35
+ * to you.
36
+ *
37
+ * Resolves the document through its perspective exactly as `useReportPresence` does,
38
+ * so reads match writes. Participants are counted by session, so one person in two
39
+ * tabs appears twice.
40
+ *
41
+ * @example Avatars on a document
42
+ * ```tsx
43
+ * const {presence} = usePresenceForDocument({documentId, documentType})
44
+ * return presence.map((p) => <Avatar key={p.sessionId} user={p.user} />)
45
+ * ```
46
+ *
47
+ * @example Avatars on a single field
48
+ * ```tsx
49
+ * const {presence} = usePresenceForDocument({
50
+ * documentId,
51
+ * documentType,
52
+ * path: ['title'],
53
+ * excludeVersions: true,
54
+ * })
55
+ * ```
56
+ *
57
+ * @beta
58
+ */
59
+ export function usePresenceForDocument(options: UsePresenceForDocumentOptions): {
60
+ presence: DocumentPresence[]
61
+ } {
62
+ const {path, excludeVersions, ...handle} = options
63
+
64
+ const normalizedOptions = useNormalizedResourceOptions(handle)
65
+ if (normalizedOptions.resource && isMediaLibraryResource(normalizedOptions.resource)) {
66
+ throw new Error(
67
+ 'usePresenceForDocument() does not support media library resources. Presence tracking requires a canvas or dataset resource.',
68
+ )
69
+ }
70
+
71
+ const sanityInstance = useSanityInstance()
72
+ trackHookUsage(sanityInstance, 'usePresenceForDocument')
73
+
74
+ const {resource, perspective} = normalizedOptions
75
+ const {documentId, liveEdit} = options
76
+
77
+ // Serialized so a caller passing a fresh `path` array each render does not
78
+ // rebuild the state source every render.
79
+ const pathKey = useMemo(() => JSON.stringify(path ?? null), [path])
80
+
81
+ const source = useMemo(
82
+ () =>
83
+ getDocumentPresence(sanityInstance, {
84
+ ...(resource ? {resource} : {}),
85
+ documentId,
86
+ // Forwarded, not resolved here, so this matches what `useReportPresence`
87
+ // sends. Core owns turning a perspective into a specific document id.
88
+ ...(perspective ? {perspective} : {}),
89
+ ...(liveEdit ? {liveEdit} : {}),
90
+ ...(pathKey === 'null' ? {} : {path: JSON.parse(pathKey) as Path}),
91
+ ...(excludeVersions === undefined ? {} : {excludeVersions}),
92
+ }),
93
+ [sanityInstance, resource, documentId, perspective, liveEdit, pathKey, excludeVersions],
94
+ )
95
+
96
+ const subscribe = useCallback((callback: () => void) => source.subscribe(callback), [source])
97
+ const presence = useSyncExternalStore(
98
+ subscribe,
99
+ () => source.getCurrent(),
100
+ () => source.getCurrent(),
101
+ )
102
+
103
+ return {presence: presence || []}
104
+ }
@@ -0,0 +1,202 @@
1
+ import {reportPresence} from '@sanity/sdk'
2
+ import {act, renderHook} from '@testing-library/react'
3
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
4
+
5
+ import {ResourceProvider} from '../../context/ResourceProvider'
6
+ import {useReportPresence} from './useReportPresence'
7
+
8
+ vi.mock('@sanity/sdk', async (importOriginal) => {
9
+ const actual = await importOriginal<typeof import('@sanity/sdk')>()
10
+ return {
11
+ ...actual,
12
+ reportPresence: vi.fn(),
13
+ }
14
+ })
15
+
16
+ const reported = () => vi.mocked(reportPresence).mock.calls.map(([, params]) => params.locations)
17
+
18
+ const wrapper = ({children}: {children: React.ReactNode}) => (
19
+ <ResourceProvider projectId="p" dataset="d" fallback={null}>
20
+ {children}
21
+ </ResourceProvider>
22
+ )
23
+
24
+ describe('useReportPresence', () => {
25
+ beforeEach(() => {
26
+ vi.clearAllMocks()
27
+ vi.useFakeTimers()
28
+ })
29
+
30
+ afterEach(() => {
31
+ vi.useRealTimers()
32
+ })
33
+
34
+ it('reports the document with no path or selection keys when neither was given', () => {
35
+ renderHook(() => useReportPresence({documentId: 'doc-1', documentType: 'movie'}), {wrapper})
36
+
37
+ // Keys absent rather than set to `undefined`. The id stays unresolved here:
38
+ // core turns a perspective into a specific document id, so the read and write
39
+ // sides cannot drift apart.
40
+ expect(reported()).toEqual([[{documentId: 'doc-1'}]])
41
+ })
42
+
43
+ it('forwards an explicit perspective for core to resolve', () => {
44
+ renderHook(
45
+ () =>
46
+ useReportPresence({
47
+ documentId: 'doc-1',
48
+ documentType: 'movie',
49
+ perspective: {releaseName: 'autumn'},
50
+ }),
51
+ {wrapper},
52
+ )
53
+
54
+ expect(reported()[0][0]).toMatchObject({
55
+ documentId: 'doc-1',
56
+ perspective: {releaseName: 'autumn'},
57
+ })
58
+ })
59
+
60
+ it('forwards liveEdit, which core resolves to the published document', () => {
61
+ renderHook(
62
+ () => useReportPresence({documentId: 'doc-1', documentType: 'movie', liveEdit: true}),
63
+ {wrapper},
64
+ )
65
+
66
+ expect(reported()[0][0]).toMatchObject({documentId: 'doc-1', liveEdit: true})
67
+ })
68
+
69
+ it('picks up an ambient perspective from the provider', () => {
70
+ // The whole point of resolving after normalization: a perspective set once on
71
+ // `ResourceProvider` has to reach presence without every call site passing it.
72
+ const ambient = ({children}: {children: React.ReactNode}) => (
73
+ <ResourceProvider projectId="p" dataset="d" perspective="published" fallback={null}>
74
+ {children}
75
+ </ResourceProvider>
76
+ )
77
+
78
+ renderHook(() => useReportPresence({documentId: 'doc-1', documentType: 'movie'}), {
79
+ wrapper: ambient,
80
+ })
81
+
82
+ expect(reported()[0][0]).toMatchObject({documentId: 'doc-1', perspective: 'published'})
83
+ })
84
+
85
+ it('announces a field path', () => {
86
+ renderHook(
87
+ () => useReportPresence({documentId: 'doc-1', documentType: 'movie', path: ['title']}),
88
+ {wrapper},
89
+ )
90
+
91
+ expect(reported()[0][0].path).toEqual(['title'])
92
+ })
93
+
94
+ it('carries keyed segments and a selection', () => {
95
+ const path = ['body', {_key: 'b1'}, 'children', {_key: 's1'}, 'text']
96
+ const selection = {
97
+ anchor: {path: [{_key: 'b1'}, 'children', {_key: 's1'}], offset: 1},
98
+ focus: {path: [{_key: 'b1'}, 'children', {_key: 's1'}], offset: 4},
99
+ }
100
+
101
+ renderHook(
102
+ () => useReportPresence({documentId: 'doc-1', documentType: 'movie', path, selection}),
103
+ {wrapper},
104
+ )
105
+
106
+ expect(reported()[0][0].path).toEqual(path)
107
+ expect(reported()[0][0].selection).toEqual(selection)
108
+ })
109
+
110
+ it('does not re-announce when a caller passes fresh literals each render', () => {
111
+ const {rerender} = renderHook(
112
+ () =>
113
+ useReportPresence({
114
+ documentId: 'doc-1',
115
+ documentType: 'movie',
116
+ // A new array identity on every render, which is what real callers do.
117
+ path: ['title'],
118
+ }),
119
+ {wrapper},
120
+ )
121
+
122
+ rerender()
123
+ rerender()
124
+
125
+ expect(reported()).toHaveLength(1)
126
+ })
127
+
128
+ it('throttles a burst and announces the final position', () => {
129
+ const {rerender} = renderHook(
130
+ ({path}: {path: string[]}) =>
131
+ useReportPresence({documentId: 'doc-1', documentType: 'movie', path}),
132
+ {wrapper, initialProps: {path: ['a']}},
133
+ )
134
+
135
+ expect(reported()).toHaveLength(1)
136
+
137
+ rerender({path: ['b']})
138
+ rerender({path: ['c']})
139
+ expect(reported()).toHaveLength(1)
140
+
141
+ // Trailing edge, so the position the user actually settled on is the one sent.
142
+ act(() => {
143
+ vi.advanceTimersByTime(1000)
144
+ })
145
+ expect(reported()).toHaveLength(2)
146
+ expect(reported()[1][0].path).toEqual(['c'])
147
+ })
148
+
149
+ it('announces selections more often than field focus', () => {
150
+ const selectionAt = (offset: number) => ({
151
+ anchor: {path: [{_key: 'b1'}], offset},
152
+ focus: {path: [{_key: 'b1'}], offset},
153
+ })
154
+
155
+ const {rerender} = renderHook(
156
+ ({offset}: {offset: number}) =>
157
+ useReportPresence({
158
+ documentId: 'doc-1',
159
+ documentType: 'movie',
160
+ path: ['body'],
161
+ selection: selectionAt(offset),
162
+ }),
163
+ {wrapper, initialProps: {offset: 1}},
164
+ )
165
+
166
+ expect(reported()).toHaveLength(1)
167
+ rerender({offset: 2})
168
+
169
+ // Would still be pending at the 1000ms focus interval. A caret that lags a
170
+ // full second reads as broken, so selections use 250ms.
171
+ act(() => {
172
+ vi.advanceTimersByTime(250)
173
+ })
174
+ expect(reported()).toHaveLength(2)
175
+ })
176
+
177
+ it('clears its location on unmount, staying present but nowhere', () => {
178
+ const {unmount} = renderHook(
179
+ () => useReportPresence({documentId: 'doc-1', documentType: 'movie'}),
180
+ {wrapper},
181
+ )
182
+
183
+ unmount()
184
+
185
+ expect(reported().at(-1)).toEqual([])
186
+ })
187
+
188
+ it('does not clear on every location change, only on unmount', () => {
189
+ const {rerender} = renderHook(
190
+ ({path}: {path: string[]}) =>
191
+ useReportPresence({documentId: 'doc-1', documentType: 'movie', path}),
192
+ {wrapper, initialProps: {path: ['a']}},
193
+ )
194
+
195
+ rerender({path: ['b']})
196
+ act(() => {
197
+ vi.advanceTimersByTime(1000)
198
+ })
199
+
200
+ expect(reported().every((locations) => locations.length === 1)).toBe(true)
201
+ })
202
+ })