|
1 | | -import {type DocumentHandle, getPreviewState, type PreviewValue, resolvePreview} from '@sanity/sdk' |
2 | | -import {useCallback, useSyncExternalStore} from 'react' |
| 1 | +import { |
| 2 | + type DocumentSource, |
| 3 | + getPreviewState, |
| 4 | + type GetPreviewStateOptions, |
| 5 | + type PreviewValue, |
| 6 | + resolvePreview, |
| 7 | +} from '@sanity/sdk' |
| 8 | +import {useCallback, useMemo, useSyncExternalStore} from 'react' |
3 | 9 | import {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs' |
4 | 10 |
|
5 | | -import {useSanityInstance} from '../context/useSanityInstance' |
| 11 | +import {useSanityInstanceAndSource} from '../context/useSanityInstance' |
6 | 12 |
|
7 | 13 | /** |
8 | 14 | * @public |
9 | 15 | * @category Types |
10 | 16 | */ |
11 | | -export interface useDocumentPreviewOptions extends DocumentHandle { |
| 17 | +export interface useDocumentPreviewOptions extends Omit<GetPreviewStateOptions, 'source'> { |
12 | 18 | /** |
13 | 19 | * Optional ref object to track visibility. When provided, preview resolution |
14 | 20 | * only occurs when the referenced element is visible in the viewport. |
15 | 21 | */ |
16 | 22 | ref?: React.RefObject<unknown> |
| 23 | + |
| 24 | + projectId?: string |
| 25 | + dataset?: string |
| 26 | + |
| 27 | + source?: DocumentSource |
17 | 28 | } |
18 | 29 |
|
19 | 30 | /** |
@@ -81,10 +92,14 @@ export interface useDocumentPreviewResults { |
81 | 92 | */ |
82 | 93 | export function useDocumentPreview({ |
83 | 94 | ref, |
| 95 | + projectId, |
| 96 | + dataset, |
| 97 | + source, |
84 | 98 | ...docHandle |
85 | 99 | }: useDocumentPreviewOptions): useDocumentPreviewResults { |
86 | | - const instance = useSanityInstance(docHandle) |
87 | | - const stateSource = getPreviewState(instance, docHandle) |
| 100 | + const [instance, actualSource] = useSanityInstanceAndSource({projectId, dataset, source}) |
| 101 | + const options = useMemo(() => ({...docHandle, source: actualSource}), [docHandle, actualSource]) |
| 102 | + const stateSource = getPreviewState(instance, options) |
88 | 103 |
|
89 | 104 | // Create subscribe function for useSyncExternalStore |
90 | 105 | const subscribe = useCallback( |
@@ -131,9 +146,9 @@ export function useDocumentPreview({ |
131 | 146 | // Create getSnapshot function to return current state |
132 | 147 | const getSnapshot = useCallback(() => { |
133 | 148 | const currentState = stateSource.getCurrent() |
134 | | - if (currentState.data === null) throw resolvePreview(instance, docHandle) |
| 149 | + if (currentState.data === null) throw resolvePreview(instance, options) |
135 | 150 | return currentState as useDocumentPreviewResults |
136 | | - }, [docHandle, instance, stateSource]) |
| 151 | + }, [instance, options, stateSource]) |
137 | 152 |
|
138 | 153 | return useSyncExternalStore(subscribe, getSnapshot) |
139 | 154 | } |
0 commit comments