@prismicio/next
Version:
Helpers to integrate Prismic into Next.js apps
65 lines (64 loc) • 2.63 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const react = require("react");
const router = require("next/router");
const Script = require("next/script");
const client = require("@prismicio/client");
const PrismicPreview = (props) => {
const { repositoryName, updatePreviewURL = "/api/preview", exitPreviewURL = "/api/exit-preview", children } = props;
const router$1 = router.useRouter();
const toolbarSrc = client.getToolbarSrc(repositoryName);
react.useEffect(() => {
const controller = new AbortController();
window.addEventListener("prismicPreviewUpdate", onUpdate, {
signal: controller.signal
});
window.addEventListener("prismicPreviewEnd", onEnd, {
signal: controller.signal
});
if (window.location.href.startsWith(window.location.origin + router$1.basePath) && getPreviewCookieRepositoryName() === repositoryName && !router$1.isPreview) {
start();
}
function onEnd(event) {
event.preventDefault();
fetch(router$1.basePath + exitPreviewURL, { signal: controller.signal }).then((res) => {
if (!res.ok) {
console.error(`[<PrismicPreview>] Failed to exit Preview Mode using the "${exitPreviewURL}" API endpoint. Does it exist?`);
return;
}
refresh();
}).catch(() => {
});
}
function onUpdate(event) {
event.preventDefault();
start();
}
function start() {
fetch(router$1.basePath + updatePreviewURL, {
redirect: "manual",
signal: controller.signal
}).then((res) => {
if (res.type !== "opaqueredirect") {
console.error(`[<PrismicPreview>] Failed to start or update the preview using "${updatePreviewURL}". Does it exist?`);
return;
}
refresh();
}).catch(() => {
});
}
function refresh() {
router$1.replace(router$1.asPath, void 0, { scroll: false });
}
return () => controller.abort();
}, [exitPreviewURL, updatePreviewURL, repositoryName, router$1]);
return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [children, jsxRuntime.jsx(Script, { src: toolbarSrc, strategy: "lazyOnload" })] });
};
function getPreviewCookieRepositoryName() {
var _a;
const cookie = (_a = window.document.cookie.split("; ").find((row) => row.startsWith(`${client.cookie.preview}=`))) == null ? void 0 : _a.split("=")[1];
return (decodeURIComponent(cookie ?? "").match(/"([^"]+)\.prismic\.io"/) || [])[1];
}
exports.PrismicPreview = PrismicPreview;
//# sourceMappingURL=PrismicPreview.cjs.map