@prismicio/react
Version:
React components and hooks to fetch and present Prismic content
48 lines (47 loc) • 2.51 kB
JavaScript
import { jsx } from "react/jsx-runtime";
import { forwardRef } from "react";
import { asLinkAttrs } from "@prismicio/client";
import { DEV } from "esm-env";
import { devMsg } from "./lib/devMsg.js";
const defaultComponent = "a";
const PrismicLink = forwardRef(function PrismicLink2(props, ref) {
const { field, document: doc, linkResolver, internalComponent, externalComponent, children, ...restProps } = props;
if (DEV) {
if (field) {
if (!field.link_type) {
console.error(`[PrismicLink] This "field" prop value caused an error to be thrown.
`, field);
throw new Error(`[PrismicLink] The provided field is missing required properties to properly render a link. The link will not render. For more details, see ${devMsg("missing-link-properties")}`);
} else if (("text" in field ? Object.keys(field).length > 2 : Object.keys(field).length > 1) && !("url" in field || "uid" in field || "id" in field)) {
console.warn(`[PrismicLink] The provided field is missing required properties to properly render a link. The link may not render correctly. For more details, see ${devMsg("missing-link-properties")}`, field);
}
} else if (doc) {
if (!("url" in doc || "id" in doc)) {
console.warn(`[PrismicLink] The provided document is missing required properties to properly render a link. The link may not render correctly. For more details, see ${devMsg("missing-link-properties")}`, doc);
}
}
}
const { href: computedHref, rel: computedRel, ...attrs } = asLinkAttrs(field ?? doc, {
linkResolver,
rel: typeof restProps.rel === "function" ? restProps.rel : void 0
});
let rel = computedRel;
if ("rel" in restProps && typeof restProps.rel !== "function") {
rel = restProps.rel;
}
const href = ("href" in restProps ? restProps.href : computedHref) || "";
const InternalComponent = internalComponent || defaultComponent;
const ExternalComponent = externalComponent || defaultComponent;
const Component = href ? isInternalURL(href) ? InternalComponent : ExternalComponent : InternalComponent;
return jsx(Component, { ref, ...attrs, ...restProps, href, rel, children: "children" in props ? children : field == null ? void 0 : field.text });
});
function isInternalURL(url) {
const isInternal = /^(\/(?!\/)|#)/.test(url);
const isSpecialLink = !isInternal && !/^https?:\/\//.test(url);
return isInternal && !isSpecialLink;
}
export {
PrismicLink,
isInternalURL
};
//# sourceMappingURL=PrismicLink.js.map