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