@sanity/preview-kit
Version:
General purpose utils for live content and visual editing
57 lines (56 loc) • 2.38 kB
JavaScript
"use client";
import { useContext, useMemo, useState, useCallback, useSyncExternalStore, cloneElement, Children, isValidElement } from "react";
import { defineStoreContext, useQueryParams } from "../_chunks-es/hooks.js";
function useLiveQuery(initialData, query, queryParams2) {
const defineStore = useContext(defineStoreContext), queryParams = useQueryParams(queryParams2), store = useMemo(
() => defineStore?.(initialData, query, queryParams, null),
[defineStore, initialData, queryParams, query]
), [serverSnapshot] = useState(() => {
if (initialData === void 0)
throw new Error(
"initialSnapshot can't be undefined, if you don't want an initial value use null instead"
);
try {
return JSON.parse(JSON.stringify(initialData));
} catch (error) {
return console.warn(
"Failed to deep clone initialSnapshot, this is likely an error and an indication that the snapshot isn't JSON serializable",
{ initialSnapshot: initialData, error }
), initialData;
}
}), getServerSnapshot = useCallback(() => serverSnapshot, [serverSnapshot]);
return [
useSyncExternalStore(
store?.subscribe || noop,
store?.getSnapshot || getServerSnapshot,
getServerSnapshot
),
defineStore !== null
];
}
function noop() {
return () => {
};
}
function LiveQueryClientComponent(props) {
const { initialData, query, params, children, throwOnMissingProvider = !0 } = props, [data, enabled] = useLiveQuery(initialData, query, params);
if (throwOnMissingProvider && !enabled)
throw new Error(
"<LiveQuery> require you to wrap them in a parent <LiveQueryProvider> when its 'enabled' prop is true, or set the 'throwOnMissingProvider' prop to 'false' to ignore this error"
);
return isValidElement(children) ? cloneElement(children, {
// eslint-disable-next-line no-warning-comments
// @ts-expect-error -- @todo fix the typings
...children.props,
// all child props should override, except for `data`
data,
// eslint-disable-next-line no-warning-comments
// @ts-expect-error -- @todo fix the typings
ref: children.ref
}) : Children.count(children) > 1 ? Children.only(null) : null;
}
LiveQueryClientComponent.displayName = "LiveQueryClientComponent";
export {
LiveQueryClientComponent as default
};
//# sourceMappingURL=client-component.js.map