1 | import { __assign, __rest } from "tslib";
|
2 | import * as React from "rehackt";
|
3 | import { mergeDeepArray } from "../../utilities/index.js";
|
4 | import { useApolloClient } from "./useApolloClient.js";
|
5 | import { useSyncExternalStore } from "./useSyncExternalStore.js";
|
6 | import { useDeepMemo, useLazyRef, wrapHook } from "./internal/index.js";
|
7 | import equal from "@wry/equality";
|
8 | export function useFragment(options) {
|
9 | return wrapHook("useFragment", _useFragment, useApolloClient(options.client))(options);
|
10 | }
|
11 | function _useFragment(options) {
|
12 | var cache = useApolloClient(options.client).cache;
|
13 | var diffOptions = useDeepMemo(function () {
|
14 | var fragment = options.fragment, fragmentName = options.fragmentName, from = options.from, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, rest = __rest(options, ["fragment", "fragmentName", "from", "optimistic"]);
|
15 | return __assign(__assign({}, rest), { returnPartialData: true, id: typeof from === "string" ? from : cache.identify(from), query: cache["getFragmentDoc"](fragment, fragmentName), optimistic: optimistic });
|
16 | }, [options]);
|
17 | var resultRef = useLazyRef(function () {
|
18 | return diffToResult(cache.diff(diffOptions));
|
19 | });
|
20 | var stableOptions = useDeepMemo(function () { return options; }, [options]);
|
21 |
|
22 |
|
23 | React.useMemo(function () {
|
24 | resultRef.current = diffToResult(cache.diff(diffOptions));
|
25 | }, [diffOptions, cache]);
|
26 |
|
27 | var getSnapshot = React.useCallback(function () { return resultRef.current; }, []);
|
28 | return useSyncExternalStore(React.useCallback(function (forceUpdate) {
|
29 | var lastTimeout = 0;
|
30 | var subscription = cache.watchFragment(stableOptions).subscribe({
|
31 | next: function (result) {
|
32 | if (equal(result, resultRef.current))
|
33 | return;
|
34 | resultRef.current = result;
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | clearTimeout(lastTimeout);
|
40 | lastTimeout = setTimeout(forceUpdate);
|
41 | },
|
42 | });
|
43 | return function () {
|
44 | subscription.unsubscribe();
|
45 | clearTimeout(lastTimeout);
|
46 | };
|
47 | }, [cache, stableOptions]), getSnapshot, getSnapshot);
|
48 | }
|
49 | function diffToResult(diff) {
|
50 | var result = {
|
51 | data: diff.result,
|
52 | complete: !!diff.complete,
|
53 | };
|
54 | if (diff.missing) {
|
55 | result.missing = mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));
|
56 | }
|
57 | return result;
|
58 | }
|
59 |
|
\ | No newline at end of file |