@wordpress/block-library
Version:
Block library for the WordPress editor.
103 lines (102 loc) • 2.74 kB
JavaScript
// packages/block-library/src/navigation-link/shared/use-link-preview.js
import { __ } from "@wordpress/i18n";
import { safeDecodeURI } from "@wordpress/url";
import { privateApis as blockEditorPrivateApis } from "@wordpress/block-editor";
import { unlock } from "../../lock-unlock.mjs";
var { useRemoteUrlData } = unlock(blockEditorPrivateApis);
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function computeDisplayUrl(url) {
if (!url) {
return { displayUrl: "", isExternal: false };
}
let displayUrl = safeDecodeURI(url);
let isExternal = false;
try {
const linkUrl = new URL(url);
const siteUrl = window.location.origin;
if (linkUrl.origin === siteUrl) {
let path = linkUrl.pathname + linkUrl.search + linkUrl.hash;
if (path.endsWith("/") && path.length > 1) {
path = path.slice(0, -1);
}
displayUrl = path;
} else {
isExternal = true;
}
} catch (e) {
displayUrl = safeDecodeURI(url);
}
return { displayUrl, isExternal };
}
function computeBadges({
url,
type,
isExternal,
entityStatus,
hasBinding,
isEntityAvailable
}) {
const badges = [];
if (url) {
if (isExternal) {
badges.push({
label: __("External link"),
intent: "default"
});
} else if (type) {
badges.push({ label: capitalize(type), intent: "default" });
}
}
if (!url) {
badges.push({ label: __("No link selected"), intent: "error" });
} else if (hasBinding && !isEntityAvailable) {
badges.push({ label: __("Deleted"), intent: "error" });
} else if (entityStatus) {
const statusMap = {
publish: { label: __("Published"), intent: "success" },
future: { label: __("Scheduled"), intent: "warning" },
draft: { label: __("Draft"), intent: "warning" },
pending: { label: __("Pending"), intent: "warning" },
private: { label: __("Private"), intent: "default" },
trash: { label: __("Trash"), intent: "error" }
};
const badge = statusMap[entityStatus];
if (badge) {
badges.push(badge);
}
}
return badges;
}
function useLinkPreview({
url,
title,
image,
type,
entityStatus,
hasBinding,
isEntityAvailable
}) {
const { richData } = useRemoteUrlData(title ? null : url);
const { displayUrl, isExternal } = computeDisplayUrl(url);
const badges = computeBadges({
url,
type,
isExternal,
entityStatus,
hasBinding,
isEntityAvailable
});
const displayTitle = url ? title || richData?.title || safeDecodeURI(url) : __("Add link");
return {
title: displayTitle,
url: displayUrl,
image,
badges
};
}
export {
useLinkPreview
};
//# sourceMappingURL=use-link-preview.mjs.map