@prismicio/next
Version:
Helpers to integrate Prismic into Next.js apps
73 lines (72 loc) • 2.5 kB
JavaScript
"use client";
require("./_virtual/_rolldown/runtime.cjs");
let _prismicio_client = require("@prismicio/client");
let next_navigation = require("next/navigation");
let react = require("react");
//#region src/PrismicPreviewClient.tsx
const PrismicPreviewClient = (props) => {
const { repositoryName, isDraftMode, updatePreviewURL = "/api/preview", exitPreviewURL = "/api/exit-preview" } = props;
const { refresh } = (0, next_navigation.useRouter)();
(0, react.useEffect)(() => {
const controller = new AbortController();
window.addEventListener("prismicPreviewUpdate", onUpdate, { signal: controller.signal });
window.addEventListener("prismicPreviewEnd", onEnd, { signal: controller.signal });
const cookie = getPrismicPreviewCookie(window.document.cookie);
if ((cookie ? (decodeURIComponent(cookie).match(/"([^"]+)\.prismic\.io"/) || [])[1] : void 0) === repositoryName && !isDraftMode) globalThis.fetch(updatePreviewURL, {
redirect: "manual",
signal: controller.signal
}).then((res) => {
if (res.type !== "opaqueredirect") {
console.error(`[<PrismicPreview>] Failed to start the preview using "${updatePreviewURL}". Does it exist?`);
return;
}
refresh();
}).catch(() => {});
function onUpdate(event) {
event.preventDefault();
refresh();
}
function onEnd(event) {
event.preventDefault();
globalThis.fetch(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(() => {});
}
return () => controller.abort();
}, [
repositoryName,
isDraftMode,
updatePreviewURL,
exitPreviewURL,
refresh
]);
return null;
};
/**
* Returns the value of a cookie from a given cookie store.
*
* @param cookieJar - The stringified cookie store from which to read the cookie.
* @returns The value of the cookie, if it exists.
*/
function getPrismicPreviewCookie(cookieJar) {
function readValue(value) {
return value.replace(/%3B/g, ";");
}
const cookies = cookieJar.split("; ");
let value;
for (const cookie of cookies) {
const parts = cookie.split("=");
if (readValue(parts[0]).replace(/%3D/g, "=") === _prismicio_client.cookie.preview) {
value = readValue(parts.slice(1).join("="));
continue;
}
}
return value;
}
//#endregion
exports.PrismicPreviewClient = PrismicPreviewClient;
//# sourceMappingURL=PrismicPreviewClient.cjs.map