@sanity/sdk-react 0.0.0-alpha.9 → 0.0.0-rc.1
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.
- package/README.md +33 -126
- package/dist/index.d.ts +4742 -2
- package/dist/index.js +1054 -2
- package/dist/index.js.map +1 -1
- package/package.json +19 -43
- package/src/_exports/index.ts +66 -10
- package/src/components/Login/LoginLinks.test.tsx +90 -0
- package/src/components/Login/LoginLinks.tsx +58 -0
- package/src/components/SDKProvider.test.tsx +79 -0
- package/src/components/SDKProvider.tsx +42 -0
- package/src/components/SanityApp.test.tsx +104 -2
- package/src/components/SanityApp.tsx +54 -17
- package/src/components/auth/AuthBoundary.test.tsx +2 -2
- package/src/components/auth/AuthBoundary.tsx +13 -3
- package/src/components/auth/Login.test.tsx +1 -1
- package/src/components/auth/Login.tsx +11 -26
- package/src/components/auth/LoginCallback.tsx +4 -7
- package/src/components/auth/LoginError.tsx +12 -8
- package/src/components/auth/LoginFooter.tsx +13 -20
- package/src/components/auth/LoginLayout.tsx +8 -9
- package/src/components/auth/authTestHelpers.tsx +1 -8
- package/src/components/utils.ts +22 -0
- package/src/context/SanityInstanceContext.ts +4 -0
- package/src/context/SanityProvider.test.tsx +1 -1
- package/src/context/SanityProvider.tsx +10 -8
- package/src/hooks/_synchronous-groq-js.mjs +4 -0
- package/src/hooks/auth/useAuthState.tsx +0 -2
- package/src/hooks/auth/useCurrentUser.tsx +26 -20
- package/src/hooks/auth/useDashboardOrganizationId.test.tsx +42 -0
- package/src/hooks/auth/useDashboardOrganizationId.tsx +29 -0
- package/src/hooks/client/useClient.ts +8 -30
- package/src/hooks/comlink/useFrameConnection.test.tsx +55 -10
- package/src/hooks/comlink/useFrameConnection.ts +39 -43
- package/src/hooks/comlink/useManageFavorite.test.ts +106 -0
- package/src/hooks/comlink/useManageFavorite.ts +101 -0
- package/src/hooks/comlink/useRecordDocumentHistoryEvent.test.ts +77 -0
- package/src/hooks/comlink/useRecordDocumentHistoryEvent.ts +79 -0
- package/src/hooks/comlink/useWindowConnection.test.ts +53 -12
- package/src/hooks/comlink/useWindowConnection.ts +69 -29
- package/src/hooks/context/useSanityInstance.test.tsx +1 -1
- package/src/hooks/context/useSanityInstance.ts +21 -5
- package/src/hooks/dashboard/useNavigateToStudioDocument.ts +97 -0
- package/src/hooks/dashboard/useStudioWorkspacesByResourceId.test.tsx +274 -0
- package/src/hooks/dashboard/useStudioWorkspacesByResourceId.ts +91 -0
- package/src/hooks/datasets/useDatasets.ts +37 -0
- package/src/hooks/document/useApplyActions.test.ts +5 -4
- package/src/hooks/document/useApplyActions.ts +55 -5
- package/src/hooks/document/useDocument.test.ts +2 -2
- package/src/hooks/document/useDocument.ts +90 -21
- package/src/hooks/document/useDocumentEvent.test.ts +13 -3
- package/src/hooks/document/useDocumentEvent.ts +36 -4
- package/src/hooks/document/useDocumentSyncStatus.test.ts +1 -1
- package/src/hooks/document/useDocumentSyncStatus.ts +26 -2
- package/src/hooks/document/useEditDocument.test.ts +55 -10
- package/src/hooks/document/useEditDocument.ts +159 -31
- package/src/hooks/document/usePermissions.ts +82 -0
- package/src/hooks/helpers/createCallbackHook.tsx +3 -2
- package/src/hooks/helpers/createStateSourceHook.test.tsx +66 -0
- package/src/hooks/helpers/createStateSourceHook.tsx +29 -10
- package/src/hooks/infiniteList/useInfiniteList.test.tsx +152 -0
- package/src/hooks/infiniteList/useInfiniteList.ts +174 -0
- package/src/hooks/paginatedList/usePaginatedList.test.tsx +259 -0
- package/src/hooks/paginatedList/usePaginatedList.ts +290 -0
- package/src/hooks/preview/usePreview.test.tsx +6 -6
- package/src/hooks/preview/usePreview.tsx +12 -9
- package/src/hooks/projection/useProjection.test.tsx +218 -0
- package/src/hooks/projection/useProjection.ts +147 -0
- package/src/hooks/projects/useProject.ts +45 -0
- package/src/hooks/projects/useProjects.ts +41 -0
- package/src/hooks/query/useQuery.test.tsx +188 -0
- package/src/hooks/query/useQuery.ts +103 -0
- package/src/hooks/users/useUsers.test.ts +163 -0
- package/src/hooks/users/useUsers.ts +107 -0
- package/src/utils/getEnv.ts +21 -0
- package/src/version.ts +8 -0
- package/dist/_chunks-es/context.js +0 -8
- package/dist/_chunks-es/context.js.map +0 -1
- package/dist/_chunks-es/useLogOut.js +0 -45
- package/dist/_chunks-es/useLogOut.js.map +0 -1
- package/dist/components.d.ts +0 -111
- package/dist/components.js +0 -153
- package/dist/components.js.map +0 -1
- package/dist/context.d.ts +0 -45
- package/dist/context.js +0 -5
- package/dist/context.js.map +0 -1
- package/dist/hooks.d.ts +0 -3532
- package/dist/hooks.js +0 -218
- package/dist/hooks.js.map +0 -1
- package/src/_exports/components.ts +0 -2
- package/src/_exports/context.ts +0 -2
- package/src/_exports/hooks.ts +0 -32
- package/src/hooks/client/useClient.test.tsx +0 -130
- package/src/hooks/documentCollection/useDocuments.test.ts +0 -130
- package/src/hooks/documentCollection/useDocuments.ts +0 -135
package/dist/hooks.js
DELETED
|
@@ -1,218 +0,0 @@
|
|
|
1
|
-
import { createStateSourceHook, useSanityInstance, createCallbackHook } from "./_chunks-es/useLogOut.js";
|
|
2
|
-
import { useAuthState, useHandleCallback, useLogOut, useLoginUrls } from "./_chunks-es/useLogOut.js";
|
|
3
|
-
import { getTokenState, getCurrentUserState, getSubscribableClient, getClient, getOrCreateController, getOrCreateChannel, releaseChannel, getOrCreateNode, releaseNode, applyActions, getDocumentState, resolveDocument, subscribeDocumentEvents, getDocumentSyncStatus, editDocument, createDocumentListStore, getPreviewState, resolvePreview } from "@sanity/sdk";
|
|
4
|
-
import { useCallback, useSyncExternalStore, useMemo, useEffect, useRef, useInsertionEffect, useState } from "react";
|
|
5
|
-
import { Observable, startWith, distinctUntilChanged, switchMap, EMPTY } from "rxjs";
|
|
6
|
-
const useAuthToken = createStateSourceHook(getTokenState), useCurrentUser = createStateSourceHook(getCurrentUserState);
|
|
7
|
-
function useClient(options) {
|
|
8
|
-
const instance = useSanityInstance(), subscribe = useCallback(
|
|
9
|
-
(onStoreChange) => {
|
|
10
|
-
const subscription = getSubscribableClient(instance, options).subscribe({
|
|
11
|
-
next: onStoreChange,
|
|
12
|
-
error: (error) => {
|
|
13
|
-
console.error("Error in useClient subscription:", error);
|
|
14
|
-
}
|
|
15
|
-
});
|
|
16
|
-
return () => subscription.unsubscribe();
|
|
17
|
-
},
|
|
18
|
-
[instance, options]
|
|
19
|
-
), getSnapshot = useCallback(() => getClient(instance, options), [instance, options]);
|
|
20
|
-
return useSyncExternalStore(subscribe, getSnapshot);
|
|
21
|
-
}
|
|
22
|
-
function useFrameConnection(options) {
|
|
23
|
-
const { onMessage, targetOrigin, name, connectTo } = options, instance = useSanityInstance(), controller = useMemo(
|
|
24
|
-
() => getOrCreateController(instance, targetOrigin),
|
|
25
|
-
[instance, targetOrigin]
|
|
26
|
-
), channel = useMemo(
|
|
27
|
-
() => getOrCreateChannel(instance, {
|
|
28
|
-
name,
|
|
29
|
-
connectTo
|
|
30
|
-
}),
|
|
31
|
-
[instance, name, connectTo]
|
|
32
|
-
);
|
|
33
|
-
useEffect(() => {
|
|
34
|
-
if (!channel || !onMessage) return;
|
|
35
|
-
const unsubscribers = [];
|
|
36
|
-
return Object.entries(onMessage).forEach(([type, handler]) => {
|
|
37
|
-
const unsubscribe = channel.on(type, handler);
|
|
38
|
-
unsubscribers.push(unsubscribe);
|
|
39
|
-
}), () => {
|
|
40
|
-
unsubscribers.forEach((unsub) => unsub());
|
|
41
|
-
};
|
|
42
|
-
}, [channel, onMessage]);
|
|
43
|
-
const connect = useCallback(
|
|
44
|
-
(frameWindow) => {
|
|
45
|
-
const removeTarget = controller?.addTarget(frameWindow);
|
|
46
|
-
return () => {
|
|
47
|
-
removeTarget?.();
|
|
48
|
-
};
|
|
49
|
-
},
|
|
50
|
-
[controller]
|
|
51
|
-
), sendMessage = useCallback(
|
|
52
|
-
(type, data) => {
|
|
53
|
-
channel?.post(type, data);
|
|
54
|
-
},
|
|
55
|
-
[channel]
|
|
56
|
-
);
|
|
57
|
-
return useEffect(() => () => {
|
|
58
|
-
releaseChannel(instance, name);
|
|
59
|
-
}, [name, instance]), {
|
|
60
|
-
connect,
|
|
61
|
-
sendMessage
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
function useWindowConnection(options) {
|
|
65
|
-
const { name, onMessage, connectTo } = options, instance = useSanityInstance(), node = useMemo(
|
|
66
|
-
() => getOrCreateNode(instance, { name, connectTo }),
|
|
67
|
-
[instance, name, connectTo]
|
|
68
|
-
);
|
|
69
|
-
useEffect(() => {
|
|
70
|
-
if (!onMessage) return;
|
|
71
|
-
const unsubscribers = [];
|
|
72
|
-
return Object.entries(onMessage).forEach(([type, handler]) => {
|
|
73
|
-
const unsubscribe = node.on(type, handler);
|
|
74
|
-
unsubscribers.push(unsubscribe);
|
|
75
|
-
}), () => {
|
|
76
|
-
unsubscribers.forEach((unsub) => unsub());
|
|
77
|
-
};
|
|
78
|
-
}, [node, onMessage]);
|
|
79
|
-
const sendMessage = useCallback(
|
|
80
|
-
(type, data) => {
|
|
81
|
-
node?.post(type, data);
|
|
82
|
-
},
|
|
83
|
-
[node]
|
|
84
|
-
);
|
|
85
|
-
return useEffect(() => () => {
|
|
86
|
-
releaseNode(instance, name);
|
|
87
|
-
}, [instance, name]), {
|
|
88
|
-
sendMessage
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
function useApplyActions() {
|
|
92
|
-
return _useApplyActions();
|
|
93
|
-
}
|
|
94
|
-
const _useApplyActions = createCallbackHook(applyActions);
|
|
95
|
-
function useDocument(doc, path) {
|
|
96
|
-
const documentId = typeof doc == "string" ? doc : doc._id, instance = useSanityInstance();
|
|
97
|
-
if (!useCallback(
|
|
98
|
-
() => getDocumentState(instance, documentId).getCurrent() !== void 0,
|
|
99
|
-
[instance, documentId]
|
|
100
|
-
)()) throw resolveDocument(instance, documentId);
|
|
101
|
-
const { subscribe, getCurrent } = useMemo(
|
|
102
|
-
() => getDocumentState(instance, documentId, path),
|
|
103
|
-
[documentId, instance, path]
|
|
104
|
-
);
|
|
105
|
-
return useSyncExternalStore(subscribe, getCurrent);
|
|
106
|
-
}
|
|
107
|
-
function useDocumentEvent(handler) {
|
|
108
|
-
const ref = useRef(handler);
|
|
109
|
-
useInsertionEffect(() => {
|
|
110
|
-
ref.current = handler;
|
|
111
|
-
});
|
|
112
|
-
const stableHandler = useCallback((documentEvent) => ref.current(documentEvent), []), instance = useSanityInstance();
|
|
113
|
-
useEffect(() => subscribeDocumentEvents(instance, stableHandler), [instance, stableHandler]);
|
|
114
|
-
}
|
|
115
|
-
const useDocumentSyncStatus = createStateSourceHook(getDocumentSyncStatus), ignoredKeys = ["_id", "_type", "_createdAt", "_updatedAt", "_rev"];
|
|
116
|
-
function useEditDocument(doc, path) {
|
|
117
|
-
const documentId = typeof doc == "string" ? doc : doc._id, instance = useSanityInstance(), apply = useApplyActions();
|
|
118
|
-
if (!useCallback(
|
|
119
|
-
() => getDocumentState(instance, documentId).getCurrent() !== void 0,
|
|
120
|
-
[instance, documentId]
|
|
121
|
-
)()) throw resolveDocument(instance, documentId);
|
|
122
|
-
return useCallback(
|
|
123
|
-
(next) => {
|
|
124
|
-
if (path)
|
|
125
|
-
return apply(editDocument(documentId, { set: { [path]: next } }));
|
|
126
|
-
const current = getDocumentState(instance, documentId).getCurrent();
|
|
127
|
-
if (typeof next != "object" || !next)
|
|
128
|
-
throw new Error(
|
|
129
|
-
"No path was provided to `useEditDocument` and the value provided was not a document object."
|
|
130
|
-
);
|
|
131
|
-
const editActions = Object.entries(next).filter(([key]) => !ignoredKeys.includes(key)).filter(([key, value]) => current?.[key] !== value).map(([key, value]) => editDocument(documentId, { set: { [key]: value } }));
|
|
132
|
-
return apply(editActions);
|
|
133
|
-
},
|
|
134
|
-
[apply, documentId, instance, path]
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
const STABLE_EMPTY = {
|
|
138
|
-
results: [],
|
|
139
|
-
isPending: !1,
|
|
140
|
-
hasMore: !1,
|
|
141
|
-
count: 0
|
|
142
|
-
};
|
|
143
|
-
function useDocuments(options = {}) {
|
|
144
|
-
const instance = useSanityInstance(), [ref] = useState(() => ({
|
|
145
|
-
storeInstance: null,
|
|
146
|
-
getCurrent: () => STABLE_EMPTY,
|
|
147
|
-
initialOptions: options
|
|
148
|
-
})), serializedOptions = JSON.stringify(options);
|
|
149
|
-
useEffect(() => {
|
|
150
|
-
ref.storeInstance?.setOptions(JSON.parse(serializedOptions));
|
|
151
|
-
}, [ref, serializedOptions]);
|
|
152
|
-
const subscribe = useCallback(
|
|
153
|
-
(onStoreChanged) => {
|
|
154
|
-
ref.storeInstance = createDocumentListStore(instance), ref.storeInstance.setOptions(ref.initialOptions);
|
|
155
|
-
const state2 = ref.storeInstance.getState();
|
|
156
|
-
ref.getCurrent = state2.getCurrent;
|
|
157
|
-
const unsubscribe = state2.subscribe(onStoreChanged);
|
|
158
|
-
return () => {
|
|
159
|
-
unsubscribe(), ref.storeInstance?.dispose();
|
|
160
|
-
};
|
|
161
|
-
},
|
|
162
|
-
[instance, ref]
|
|
163
|
-
), getSnapshot = useCallback(() => ref.getCurrent(), [ref]), state = useSyncExternalStore(subscribe, getSnapshot);
|
|
164
|
-
return { loadMore: useCallback(() => {
|
|
165
|
-
ref.storeInstance?.loadMore();
|
|
166
|
-
}, [ref]), ...state };
|
|
167
|
-
}
|
|
168
|
-
function usePreview({ document: { _id, _type }, ref }) {
|
|
169
|
-
const instance = useSanityInstance(), stateSource = useMemo(
|
|
170
|
-
() => getPreviewState(instance, { document: { _id, _type } }),
|
|
171
|
-
[instance, _id, _type]
|
|
172
|
-
), subscribe = useCallback(
|
|
173
|
-
(onStoreChanged) => {
|
|
174
|
-
const subscription = new Observable((observer) => {
|
|
175
|
-
if (typeof IntersectionObserver > "u" || typeof HTMLElement > "u")
|
|
176
|
-
return;
|
|
177
|
-
const intersectionObserver = new IntersectionObserver(
|
|
178
|
-
([entry]) => observer.next(entry.isIntersecting),
|
|
179
|
-
{ rootMargin: "0px", threshold: 0 }
|
|
180
|
-
);
|
|
181
|
-
return ref?.current && ref.current instanceof HTMLElement && intersectionObserver.observe(ref.current), () => intersectionObserver.disconnect();
|
|
182
|
-
}).pipe(
|
|
183
|
-
startWith(!1),
|
|
184
|
-
distinctUntilChanged(),
|
|
185
|
-
switchMap(
|
|
186
|
-
(isVisible) => isVisible ? new Observable((obs) => stateSource.subscribe(() => obs.next())) : EMPTY
|
|
187
|
-
)
|
|
188
|
-
).subscribe({ next: onStoreChanged });
|
|
189
|
-
return () => subscription.unsubscribe();
|
|
190
|
-
},
|
|
191
|
-
[stateSource, ref]
|
|
192
|
-
), getSnapshot = useCallback(() => {
|
|
193
|
-
const currentState = stateSource.getCurrent();
|
|
194
|
-
if (currentState.results === null) throw resolvePreview(instance, { document: { _id, _type } });
|
|
195
|
-
return currentState;
|
|
196
|
-
}, [_id, _type, instance, stateSource]);
|
|
197
|
-
return useSyncExternalStore(subscribe, getSnapshot);
|
|
198
|
-
}
|
|
199
|
-
export {
|
|
200
|
-
useApplyActions,
|
|
201
|
-
useAuthState,
|
|
202
|
-
useAuthToken,
|
|
203
|
-
useClient,
|
|
204
|
-
useCurrentUser,
|
|
205
|
-
useDocument,
|
|
206
|
-
useDocumentEvent,
|
|
207
|
-
useDocumentSyncStatus,
|
|
208
|
-
useDocuments,
|
|
209
|
-
useEditDocument,
|
|
210
|
-
useFrameConnection,
|
|
211
|
-
useHandleCallback,
|
|
212
|
-
useLogOut,
|
|
213
|
-
useLoginUrls,
|
|
214
|
-
usePreview,
|
|
215
|
-
useSanityInstance,
|
|
216
|
-
useWindowConnection
|
|
217
|
-
};
|
|
218
|
-
//# sourceMappingURL=hooks.js.map
|
package/dist/hooks.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","sources":["../src/hooks/auth/useAuthToken.tsx","../src/hooks/auth/useCurrentUser.tsx","../src/hooks/client/useClient.ts","../src/hooks/comlink/useFrameConnection.ts","../src/hooks/comlink/useWindowConnection.ts","../src/hooks/document/useApplyActions.ts","../src/hooks/document/useDocument.ts","../src/hooks/document/useDocumentEvent.ts","../src/hooks/document/useDocumentSyncStatus.ts","../src/hooks/document/useEditDocument.ts","../src/hooks/documentCollection/useDocuments.ts","../src/hooks/preview/usePreview.tsx"],"sourcesContent":["import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @TODO This should suspend! And possibly not return `null`?\n *\n * @public\n *\n * The `useCurrentUser` hook returns the currently authenticated user’s profile information (their name, email, roles, etc).\n * If no users are currently logged in, the hook returns null.\n *\n * @returns The current user data, or `null` if not authenticated\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\nexport const useCurrentUser: () => CurrentUser | null = createStateSourceHook(getCurrentUserState)\n","import {type SanityClient} from '@sanity/client'\nimport {type ClientOptions, getClient, getSubscribableClient} from '@sanity/sdk'\nimport {useCallback, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n * such as user authentication changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to changes\n * and ensure consistency between server and client rendering.\n *\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient()\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n */\nexport function useClient(options: ClientOptions): SanityClient {\n const instance = useSanityInstance()\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const client$ = getSubscribableClient(instance, options)\n const subscription = client$.subscribe({\n next: onStoreChange,\n error: (error) => {\n // @TODO: We should tackle error handling / error boundaries soon\n // eslint-disable-next-line no-console\n console.error('Error in useClient subscription:', error)\n },\n })\n return () => subscription.unsubscribe()\n },\n [instance, options],\n )\n\n const getSnapshot = useCallback(() => {\n return getClient(instance, options)\n }, [instance, options])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n","import {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: Record<string, FrameMessageHandler<TWindowMessage>>\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo} = options\n const instance = useSanityInstance()\n\n const controller = useMemo(\n () => getOrCreateController(instance, targetOrigin),\n [instance, targetOrigin],\n )\n\n const channel = useMemo(\n () =>\n getOrCreateChannel(instance, {\n name,\n connectTo,\n }),\n [instance, name, connectTo],\n )\n\n useEffect(() => {\n if (!channel || !onMessage) return\n\n const unsubscribers: Array<() => void> = []\n\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = channel.on(type, handler)\n unsubscribers.push(unsubscribe)\n })\n\n return () => {\n unsubscribers.forEach((unsub) => unsub())\n }\n }, [channel, onMessage])\n\n const connect = useCallback(\n (frameWindow: Window) => {\n const removeTarget = controller?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n },\n [controller],\n )\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channel?.post(type, data)\n },\n [channel],\n )\n\n // cleanup channel on unmount\n useEffect(() => {\n return () => {\n releaseChannel(instance, name)\n }\n }, [name, instance])\n\n return {\n connect,\n sendMessage,\n }\n}\n","import {type FrameMessage, getOrCreateNode, releaseNode, type WindowMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type WindowMessageHandler<TFrameMessage extends FrameMessage> = (\n event: TFrameMessage['data'],\n) => TFrameMessage['response']\n\n/**\n * @internal\n */\nexport interface UseWindowConnectionOptions<TMessage extends FrameMessage> {\n name: string\n connectTo: string\n onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>\n}\n\n/**\n * @internal\n */\nexport interface WindowConnection<TMessage extends WindowMessage> {\n sendMessage: <TType extends TMessage['type']>(\n type: TType,\n data?: Extract<TMessage, {type: TType}>['data'],\n ) => void\n}\n\n/**\n * @internal\n */\nexport function useWindowConnection<\n TWindowMessage extends WindowMessage,\n TFrameMessage extends FrameMessage,\n>(options: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const {name, onMessage, connectTo} = options\n const instance = useSanityInstance()\n\n const node = useMemo(\n () => getOrCreateNode(instance, {name, connectTo}),\n [instance, name, connectTo],\n )\n\n useEffect(() => {\n if (!onMessage) return\n\n const unsubscribers: Array<() => void> = []\n\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n unsubscribers.push(unsubscribe)\n })\n\n return () => {\n unsubscribers.forEach((unsub) => unsub())\n }\n }, [node, onMessage])\n\n const sendMessage = useCallback(\n <TType extends WindowMessage['type']>(\n type: TType,\n data?: Extract<WindowMessage, {type: TType}>['data'],\n ) => {\n node?.post(type, data)\n },\n [node],\n )\n\n // cleanup node on unmount\n useEffect(() => {\n return () => {\n releaseNode(instance, name)\n }\n }, [instance, name])\n\n return {\n sendMessage,\n }\n}\n","import {\n type ActionsResult,\n applyActions,\n type ApplyActionsOptions,\n type DocumentAction,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/** @beta */\nexport function useApplyActions(): <TDocument extends SanityDocument>(\n action: DocumentAction<TDocument> | DocumentAction<TDocument>[],\n options?: ApplyActionsOptions,\n) => Promise<ActionsResult<TDocument>>\n/** @beta */\nexport function useApplyActions(): (\n action: DocumentAction | DocumentAction[],\n options?: ApplyActionsOptions,\n) => Promise<ActionsResult> {\n return _useApplyActions()\n}\n\nconst _useApplyActions = createCallbackHook(applyActions)\n","import {\n type DocumentHandle,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/** @beta */\nexport function useDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(doc: string | DocumentHandle<TDocument>, path: TPath): JsonMatch<TDocument, TPath> | undefined\n/** @beta */\nexport function useDocument<TDocument extends SanityDocument>(\n doc: string | DocumentHandle<TDocument>,\n): TDocument | null\n/** @beta */\nexport function useDocument(doc: string | DocumentHandle, path?: string): unknown {\n const documentId = typeof doc === 'string' ? doc : doc._id\n const instance = useSanityInstance()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, documentId).getCurrent() !== undefined,\n [instance, documentId],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, documentId)\n\n const {subscribe, getCurrent} = useMemo(\n () => getDocumentState(instance, documentId, path),\n [documentId, instance, path],\n )\n\n return useSyncExternalStore(subscribe, getCurrent)\n}\n","import {type DocumentEvent, subscribeDocumentEvents} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/** @beta */\nexport function useDocumentEvent(handler: (documentEvent: DocumentEvent) => void): void {\n const ref = useRef(handler)\n\n useInsertionEffect(() => {\n ref.current = handler\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance()\n useEffect(() => {\n return subscribeDocumentEvents(instance, stableHandler)\n }, [instance, stableHandler])\n}\n","import {getDocumentSyncStatus} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/** @beta */\nexport const useDocumentSyncStatus = createStateSourceHook(getDocumentSyncStatus)\n","import {\n type ActionsResult,\n type DocumentHandle,\n editDocument,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useApplyActions} from './useApplyActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\n/** @beta */\nexport function useEditDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(\n doc: string | DocumentHandle<TDocument>,\n path: TPath,\n): (nextValue: JsonMatch<TDocument, TPath>) => Promise<ActionsResult<TDocument>>\n/** @beta */\nexport function useEditDocument<TDocument extends SanityDocument>(\n doc: string | DocumentHandle<TDocument>,\n): (nextValue: Partial<TDocument>) => Promise<ActionsResult<TDocument>>\n/** @beta */\nexport function useEditDocument(\n doc: string | DocumentHandle,\n path?: string,\n): (nextValue: unknown) => Promise<ActionsResult> {\n const documentId = typeof doc === 'string' ? doc : doc._id\n const instance = useSanityInstance()\n const apply = useApplyActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, documentId).getCurrent() !== undefined,\n [instance, documentId],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, documentId)\n\n return useCallback(\n (next: unknown) => {\n if (path) {\n return apply(editDocument(documentId, {set: {[path]: next}}))\n }\n\n const current = getDocumentState(instance, documentId).getCurrent()\n\n if (typeof next !== 'object' || !next) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const editActions = Object.entries(next)\n .filter(([key]) => !ignoredKeys.includes(key))\n .filter(([key, value]) => current?.[key] !== value)\n .map(([key, value]) => editDocument(documentId, {set: {[key]: value}}))\n\n return apply(editActions)\n },\n [apply, documentId, instance, path],\n )\n}\n","import {createDocumentListStore, type DocumentHandle, type DocumentListOptions} from '@sanity/sdk'\nimport {useCallback, useEffect, useState, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n */\nexport interface DocumentCollection {\n /** Retrieve more documents matching the provided options */\n loadMore: () => void\n /** The retrieved document handles of the documents matching the provided options */\n results: DocumentHandle[]\n /** Whether a retrieval of documents is in flight */\n isPending: boolean\n /** Whether more documents exist that match the provided options than have been retrieved */\n hasMore: boolean\n /** The total number of documents in the collection */\n count: number\n}\n\ntype DocumentListStore = ReturnType<typeof createDocumentListStore>\ntype DocumentListState = ReturnType<DocumentListStore['getState']>['getCurrent']\nconst STABLE_EMPTY = {\n results: [],\n isPending: false,\n hasMore: false,\n count: 0,\n}\n\n/**\n * @public\n *\n * The `useDocuments` hook retrieves and provides access to a live collection of documents, optionally filtered, sorted, and matched to a given Content Lake perspective.\n * Because the returned document collection is live, the results will update in real time until the component invoking the hook is unmounted.\n *\n * @param options - Options for narrowing and sorting the document collection\n * @returns The collection of documents matching the provided options (if any), as well as properties describing the collection and a function to load more.\n *\n * @example Retrieving all documents of type 'movie'\n * ```\n * const { results, isPending } = useDocuments({ filter: '_type == \"movie\"' })\n *\n * return (\n * <div>\n * <h1>Movies</h1>\n * {results && (\n * <ul>\n * {results.map(movie => (<li key={movie._id}>…</li>))}\n * </ul>\n * )}\n * {isPending && <div>Loading movies…</div>}\n * </div>\n * )\n * ```\n *\n * @example Retrieving all movies released since 1980, sorted by director’s last name\n * ```\n * const { results } = useDocuments({\n * filter: '_type == \"movie\" && releaseDate >= \"1980-01-01\"',\n * sort: [\n * {\n * // Expand the `director` reference field with the dereferencing operator `->`\n * field: 'director->lastName',\n * sort: 'asc',\n * },\n * ],\n * })\n *\n * return (\n * <div>\n * <h1>Movies released since 1980</h1>\n * {results && (\n * <ol>\n * {results.map(movie => (<li key={movie._id}>…</li>))}\n * </ol>\n * )}\n * </div>\n * )\n * ```\n */\nexport function useDocuments(options: DocumentListOptions = {}): DocumentCollection {\n const instance = useSanityInstance()\n\n // NOTE: useState is used because it guaranteed to return a stable reference\n // across renders\n const [ref] = useState<{\n storeInstance: DocumentListStore | null\n getCurrent: DocumentListState\n initialOptions: DocumentListOptions\n }>(() => ({\n storeInstance: null,\n getCurrent: () => STABLE_EMPTY,\n initialOptions: options,\n }))\n\n // serialize options to ensure it only calls `setOptions` when the values\n // themselves changes (in cases where devs put config inline)\n const serializedOptions = JSON.stringify(options)\n useEffect(() => {\n ref.storeInstance?.setOptions(JSON.parse(serializedOptions))\n }, [ref, serializedOptions])\n\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n // to match the lifecycle of `useSyncExternalState`, we create the store\n // instance after subscribe and mutate the ref to connect everything\n ref.storeInstance = createDocumentListStore(instance)\n ref.storeInstance.setOptions(ref.initialOptions)\n const state = ref.storeInstance.getState()\n ref.getCurrent = state.getCurrent\n const unsubscribe = state.subscribe(onStoreChanged)\n\n return () => {\n // unsubscribe to clean up the state subscriptions\n unsubscribe()\n // dispose of the instance\n ref.storeInstance?.dispose()\n }\n },\n [instance, ref],\n )\n\n const getSnapshot = useCallback(() => {\n return ref.getCurrent()\n }, [ref])\n\n const state = useSyncExternalStore(subscribe, getSnapshot)\n\n const loadMore = useCallback(() => {\n ref.storeInstance?.loadMore()\n }, [ref])\n\n return {loadMore, ...state}\n}\n","import {type DocumentHandle, getPreviewState, type PreviewValue, resolvePreview} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @alpha\n */\nexport interface UsePreviewOptions {\n document: DocumentHandle\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @alpha\n */\nexport interface UsePreviewResults {\n /** The results of resolving the document’s preview values */\n results: PreviewValue\n /** True when preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @alpha\n *\n * The `usePreview` hook takes a document (via a `DocumentHandle`) and returns its resolved preview values,\n * including the document’s `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @param options - The document handle for the document you want to resolve preview values for, and an optional ref\n * @returns The preview values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { results: { title, subtitle, media }, isPending } = usePreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { results, isPending } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {isPending ? 'Loading…' : results.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function usePreview({document: {_id, _type}, ref}: UsePreviewOptions): UsePreviewResults {\n const instance = useSanityInstance()\n\n const stateSource = useMemo(\n () => getPreviewState(instance, {document: {_id, _type}}),\n [instance, _id, _type],\n )\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // for environments that don't have an intersection observer\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n // Create getSnapshot function to return current state\n const getSnapshot = useCallback(() => {\n const currentState = stateSource.getCurrent()\n if (currentState.results === null) throw resolvePreview(instance, {document: {_id, _type}})\n return currentState as UsePreviewResults\n }, [_id, _type, instance, stateSource])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n"],"names":["state"],"mappings":";;;;;AASa,MAAA,eAAe,sBAAsB,aAAa,GCiBlD,iBAA2C,sBAAsB,mBAAmB;ACK1F,SAAS,UAAU,SAAsC;AACxD,QAAA,WAAW,qBAEX,YAAY;AAAA,IAChB,CAAC,kBAA8B;AAE7B,YAA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
DELETED
package/src/_exports/hooks.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
export {useAuthState} from '../hooks/auth/useAuthState'
|
|
2
|
-
export {useAuthToken} from '../hooks/auth/useAuthToken'
|
|
3
|
-
export {useCurrentUser} from '../hooks/auth/useCurrentUser'
|
|
4
|
-
export {useHandleCallback} from '../hooks/auth/useHandleCallback'
|
|
5
|
-
export {useLoginUrls} from '../hooks/auth/useLoginUrls'
|
|
6
|
-
export {useLogOut} from '../hooks/auth/useLogOut'
|
|
7
|
-
export {useClient} from '../hooks/client/useClient'
|
|
8
|
-
export {
|
|
9
|
-
type FrameConnection,
|
|
10
|
-
type FrameMessageHandler as MessageHandler,
|
|
11
|
-
useFrameConnection,
|
|
12
|
-
type UseFrameConnectionOptions,
|
|
13
|
-
} from '../hooks/comlink/useFrameConnection'
|
|
14
|
-
export {
|
|
15
|
-
useWindowConnection,
|
|
16
|
-
type UseWindowConnectionOptions,
|
|
17
|
-
type WindowConnection,
|
|
18
|
-
type WindowMessageHandler,
|
|
19
|
-
} from '../hooks/comlink/useWindowConnection'
|
|
20
|
-
export {useSanityInstance} from '../hooks/context/useSanityInstance'
|
|
21
|
-
export {useApplyActions} from '../hooks/document/useApplyActions'
|
|
22
|
-
export {useDocument} from '../hooks/document/useDocument'
|
|
23
|
-
export {useDocumentEvent} from '../hooks/document/useDocumentEvent'
|
|
24
|
-
export {useDocumentSyncStatus} from '../hooks/document/useDocumentSyncStatus'
|
|
25
|
-
export {useEditDocument} from '../hooks/document/useEditDocument'
|
|
26
|
-
export {type DocumentCollection, useDocuments} from '../hooks/documentCollection/useDocuments'
|
|
27
|
-
export {
|
|
28
|
-
usePreview,
|
|
29
|
-
type UsePreviewOptions,
|
|
30
|
-
type UsePreviewResults,
|
|
31
|
-
} from '../hooks/preview/usePreview'
|
|
32
|
-
export {type CurrentUser} from '@sanity/sdk'
|
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
import {type SanityClient} from '@sanity/client'
|
|
2
|
-
import {act} from '@testing-library/react'
|
|
3
|
-
import {type Subscribable, type Subscriber} from 'rxjs'
|
|
4
|
-
import {beforeEach, describe, expect, it, vi} from 'vitest'
|
|
5
|
-
|
|
6
|
-
import {renderHook} from '../../../test/test-utils'
|
|
7
|
-
import {useClient} from './useClient'
|
|
8
|
-
|
|
9
|
-
vi.mock(import('@sanity/sdk'), async (importOriginal) => {
|
|
10
|
-
const actual = await importOriginal()
|
|
11
|
-
return {
|
|
12
|
-
...actual,
|
|
13
|
-
getClient: vi.fn(),
|
|
14
|
-
getSubscribableClient: vi.fn(),
|
|
15
|
-
}
|
|
16
|
-
})
|
|
17
|
-
|
|
18
|
-
const {getClient, getSubscribableClient} = await import('@sanity/sdk')
|
|
19
|
-
|
|
20
|
-
describe('useClient', () => {
|
|
21
|
-
let subscribers: {next: (client: SanityClient) => void}[] = []
|
|
22
|
-
let currentClient: SanityClient
|
|
23
|
-
|
|
24
|
-
beforeEach(() => {
|
|
25
|
-
subscribers = []
|
|
26
|
-
|
|
27
|
-
currentClient = {
|
|
28
|
-
config: () => ({token: undefined, apiVersion: 'v2024-11-12'}),
|
|
29
|
-
} as unknown as SanityClient
|
|
30
|
-
|
|
31
|
-
// Create a subscribable interface directly
|
|
32
|
-
const createSubscribable = (): Subscribable<SanityClient> => ({
|
|
33
|
-
subscribe: (subscriber: {next: (client: SanityClient) => void}) => {
|
|
34
|
-
subscribers.push(subscriber)
|
|
35
|
-
subscriber.next(currentClient)
|
|
36
|
-
return {
|
|
37
|
-
unsubscribe: () => {
|
|
38
|
-
const index = subscribers.indexOf(subscriber)
|
|
39
|
-
if (index > -1) subscribers.splice(index, 1)
|
|
40
|
-
},
|
|
41
|
-
}
|
|
42
|
-
},
|
|
43
|
-
})
|
|
44
|
-
|
|
45
|
-
vi.mocked(getClient).mockReturnValue(currentClient)
|
|
46
|
-
vi.mocked(getSubscribableClient).mockImplementation(() => createSubscribable())
|
|
47
|
-
})
|
|
48
|
-
it('should return initial client', () => {
|
|
49
|
-
const {result} = renderHook(() => useClient({apiVersion: 'v2024-11-12'}))
|
|
50
|
-
|
|
51
|
-
expect(result.current.config().token).toBeUndefined()
|
|
52
|
-
expect(result.current.config().apiVersion).toBe('v2024-11-12')
|
|
53
|
-
})
|
|
54
|
-
|
|
55
|
-
it('should handle client update through authentication changes', async () => {
|
|
56
|
-
let clientSubscriber: Subscriber<SanityClient> | undefined
|
|
57
|
-
|
|
58
|
-
// Create a subscribable that can simulate updates
|
|
59
|
-
vi.mocked(getSubscribableClient).mockImplementation(() => ({
|
|
60
|
-
subscribe: (subscriber: Subscriber<SanityClient>) => {
|
|
61
|
-
clientSubscriber = subscriber
|
|
62
|
-
// Send initial client
|
|
63
|
-
subscriber.next(currentClient)
|
|
64
|
-
return {
|
|
65
|
-
unsubscribe: vi.fn(),
|
|
66
|
-
}
|
|
67
|
-
},
|
|
68
|
-
}))
|
|
69
|
-
|
|
70
|
-
const {result} = renderHook(() => useClient({apiVersion: 'v2024-11-12'}))
|
|
71
|
-
|
|
72
|
-
// Verify initial state
|
|
73
|
-
expect(result.current.config().token).toBeUndefined()
|
|
74
|
-
expect(clientSubscriber).toBeDefined()
|
|
75
|
-
|
|
76
|
-
// Create authenticated client
|
|
77
|
-
const authenticatedClient = {
|
|
78
|
-
config: () => ({token: 'auth-token', apiVersion: 'v2024-11-12'}),
|
|
79
|
-
} as unknown as SanityClient
|
|
80
|
-
|
|
81
|
-
// Update getClient to return the new client
|
|
82
|
-
vi.mocked(getClient).mockReturnValue(authenticatedClient)
|
|
83
|
-
|
|
84
|
-
// Simulate the client update that would happen after auth change
|
|
85
|
-
await act(async () => {
|
|
86
|
-
clientSubscriber!.next(authenticatedClient)
|
|
87
|
-
})
|
|
88
|
-
|
|
89
|
-
// Verify the client was updated with the new token
|
|
90
|
-
expect(result.current.config().token).toBe('auth-token')
|
|
91
|
-
})
|
|
92
|
-
|
|
93
|
-
it('should unsubscribe on unmount', () => {
|
|
94
|
-
const unsubscribeSpy = vi.fn()
|
|
95
|
-
vi.mocked(getSubscribableClient).mockImplementation(() => ({
|
|
96
|
-
subscribe: () => ({
|
|
97
|
-
unsubscribe: unsubscribeSpy,
|
|
98
|
-
}),
|
|
99
|
-
}))
|
|
100
|
-
|
|
101
|
-
const {unmount} = renderHook(() => useClient({apiVersion: 'v2024-11-12'}))
|
|
102
|
-
|
|
103
|
-
unmount()
|
|
104
|
-
expect(unsubscribeSpy).toHaveBeenCalled()
|
|
105
|
-
})
|
|
106
|
-
|
|
107
|
-
it('should handle subscription errors', () => {
|
|
108
|
-
vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
109
|
-
|
|
110
|
-
const testError = new Error('Subscription error')
|
|
111
|
-
let errorSubscriber: Subscriber<SanityClient> | undefined
|
|
112
|
-
|
|
113
|
-
// Mock getSubscribableClient to create a subscription that will error
|
|
114
|
-
vi.mocked(getSubscribableClient).mockImplementation(() => ({
|
|
115
|
-
subscribe: (subscriber: Subscriber<SanityClient>) => {
|
|
116
|
-
errorSubscriber = subscriber
|
|
117
|
-
return {
|
|
118
|
-
unsubscribe: vi.fn(),
|
|
119
|
-
}
|
|
120
|
-
},
|
|
121
|
-
}))
|
|
122
|
-
|
|
123
|
-
renderHook(() => useClient({apiVersion: 'v2024-11-12'}))
|
|
124
|
-
|
|
125
|
-
errorSubscriber!.error(testError)
|
|
126
|
-
|
|
127
|
-
// eslint-disable-next-line no-console
|
|
128
|
-
expect(console.error).toHaveBeenCalledWith('Error in useClient subscription:', testError)
|
|
129
|
-
})
|
|
130
|
-
})
|
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
import {createDocumentListStore, type DocumentListOptions} from '@sanity/sdk'
|
|
2
|
-
import {act, renderHook} from '@testing-library/react'
|
|
3
|
-
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
|
|
4
|
-
|
|
5
|
-
import {useSanityInstance} from '../context/useSanityInstance'
|
|
6
|
-
import {useDocuments} from './useDocuments'
|
|
7
|
-
|
|
8
|
-
vi.mock('@sanity/sdk')
|
|
9
|
-
vi.mock('../context/useSanityInstance')
|
|
10
|
-
|
|
11
|
-
describe('useDocuments', () => {
|
|
12
|
-
const mockInstance = {}
|
|
13
|
-
|
|
14
|
-
const getCurrent = vi.fn()
|
|
15
|
-
const unsubscribe = vi.fn()
|
|
16
|
-
const subscribe = vi.fn().mockReturnValue(unsubscribe)
|
|
17
|
-
const dispose = vi.fn()
|
|
18
|
-
|
|
19
|
-
const mockDocumentListStore: ReturnType<typeof createDocumentListStore> = {
|
|
20
|
-
setOptions: vi.fn(),
|
|
21
|
-
loadMore: vi.fn(),
|
|
22
|
-
getState: vi.fn().mockReturnValue({getCurrent, subscribe}),
|
|
23
|
-
dispose,
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
beforeEach(() => {
|
|
27
|
-
vi.mocked(useSanityInstance).mockReturnValue(
|
|
28
|
-
mockInstance as unknown as ReturnType<typeof useSanityInstance>,
|
|
29
|
-
)
|
|
30
|
-
vi.mocked(createDocumentListStore).mockReturnValue(
|
|
31
|
-
mockDocumentListStore as unknown as ReturnType<typeof createDocumentListStore>,
|
|
32
|
-
)
|
|
33
|
-
})
|
|
34
|
-
|
|
35
|
-
afterEach(() => {
|
|
36
|
-
vi.clearAllMocks()
|
|
37
|
-
})
|
|
38
|
-
|
|
39
|
-
it('should initialize with given options', () => {
|
|
40
|
-
const options: DocumentListOptions = {
|
|
41
|
-
filter: 'some-filter',
|
|
42
|
-
sort: [{field: 'name', direction: 'asc'}],
|
|
43
|
-
}
|
|
44
|
-
renderHook(() => useDocuments(options))
|
|
45
|
-
|
|
46
|
-
expect(createDocumentListStore).toHaveBeenCalledWith(mockInstance)
|
|
47
|
-
expect(mockDocumentListStore.setOptions).toHaveBeenCalledWith(options)
|
|
48
|
-
})
|
|
49
|
-
|
|
50
|
-
it('should subscribe to document list store changes', () => {
|
|
51
|
-
const options: DocumentListOptions = {}
|
|
52
|
-
|
|
53
|
-
renderHook(() => useDocuments(options))
|
|
54
|
-
expect(subscribe).toHaveBeenCalledTimes(1)
|
|
55
|
-
})
|
|
56
|
-
|
|
57
|
-
it('should return the current document list state', () => {
|
|
58
|
-
const options = {}
|
|
59
|
-
const currentState = {result: [], isPending: false}
|
|
60
|
-
getCurrent.mockReturnValue(currentState)
|
|
61
|
-
|
|
62
|
-
const {result} = renderHook(() => useDocuments(options))
|
|
63
|
-
expect(result.current).toMatchObject(currentState)
|
|
64
|
-
})
|
|
65
|
-
|
|
66
|
-
it('should call loadMore when loadMore is invoked', () => {
|
|
67
|
-
const options = {}
|
|
68
|
-
const {result} = renderHook(() => useDocuments(options))
|
|
69
|
-
|
|
70
|
-
act(() => {
|
|
71
|
-
result.current.loadMore()
|
|
72
|
-
})
|
|
73
|
-
|
|
74
|
-
expect(mockDocumentListStore.loadMore).toHaveBeenCalled()
|
|
75
|
-
})
|
|
76
|
-
|
|
77
|
-
it('should update state when document list store changes', () => {
|
|
78
|
-
const options = {
|
|
79
|
-
filter: 'some-filter',
|
|
80
|
-
sort: [{field: 'name', direction: 'asc'}],
|
|
81
|
-
}
|
|
82
|
-
getCurrent.mockReturnValue({results: [], isPending: true})
|
|
83
|
-
const {result, rerender} = renderHook(() => useDocuments(options as DocumentListOptions))
|
|
84
|
-
|
|
85
|
-
expect(subscribe).toHaveBeenCalledTimes(1)
|
|
86
|
-
const [subscriber] = subscribe.mock.calls[0]
|
|
87
|
-
|
|
88
|
-
const newState = {results: [{id: 'doc1'}], isPending: false}
|
|
89
|
-
getCurrent.mockReturnValue(newState)
|
|
90
|
-
|
|
91
|
-
act(() => {
|
|
92
|
-
subscriber()
|
|
93
|
-
rerender()
|
|
94
|
-
})
|
|
95
|
-
|
|
96
|
-
expect(result.current).toMatchObject(newState)
|
|
97
|
-
})
|
|
98
|
-
|
|
99
|
-
it('should handle empty options', () => {
|
|
100
|
-
const options = {}
|
|
101
|
-
renderHook(() => useDocuments(options))
|
|
102
|
-
|
|
103
|
-
expect(createDocumentListStore).toHaveBeenCalledWith(mockInstance)
|
|
104
|
-
expect(mockDocumentListStore.setOptions).toHaveBeenCalledWith(options)
|
|
105
|
-
})
|
|
106
|
-
|
|
107
|
-
it('should handle null result from document list store', () => {
|
|
108
|
-
const options = {}
|
|
109
|
-
getCurrent.mockReturnValue({result: null, isPending: false})
|
|
110
|
-
|
|
111
|
-
const {result} = renderHook(() => useDocuments(options))
|
|
112
|
-
|
|
113
|
-
expect(result.current).toMatchObject({
|
|
114
|
-
result: null,
|
|
115
|
-
isPending: false,
|
|
116
|
-
})
|
|
117
|
-
})
|
|
118
|
-
|
|
119
|
-
it('should unsubscribe from document list store on unmount', () => {
|
|
120
|
-
const options = {}
|
|
121
|
-
const unsubscribeSpy = vi.fn()
|
|
122
|
-
subscribe.mockReturnValue(unsubscribeSpy)
|
|
123
|
-
|
|
124
|
-
const {unmount} = renderHook(() => useDocuments(options))
|
|
125
|
-
|
|
126
|
-
unmount()
|
|
127
|
-
expect(mockDocumentListStore.dispose).toHaveBeenCalled()
|
|
128
|
-
expect(unsubscribeSpy).toHaveBeenCalled()
|
|
129
|
-
})
|
|
130
|
-
})
|