@wordpress/block-library
Version:
Block library for the WordPress editor.
281 lines (280 loc) • 8.69 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_i18n = require("@wordpress/i18n");
let _wordpress_url = require("@wordpress/url");
let _wordpress_block_editor = require("@wordpress/block-editor");
let _wordpress_data = require("@wordpress/data");
let _wordpress_core_data = require("@wordpress/core-data");
// packages/block-library/src/utils/link-picker.ts
/**
* Helpers for a block that edits a link with the block editor's `LinkPicker`:
* the preview it shows for the current link, and the search options for its
* suggestions.
*/
const { useRemoteUrlData, isHashLink, isRelativePath } = (0, require("../lock-unlock.cjs").unlock)(_wordpress_block_editor.privateApis);
/**
* Given the Link block's type attribute, return the query params for that one
* entity type.
*
* @param type Link block's type attribute.
* @param kind Link block's entity of kind (post-type|taxonomy)
* @return Search query params.
*/
function getOwnTypeSearchOptions(type, kind) {
switch (type) {
case "post":
case "page": return {
type: "post",
subtype: type
};
case "category": return {
type: "term",
subtype: "category"
};
case "tag": return {
type: "term",
subtype: "post_tag"
};
case "post_format": return { type: "post-format" };
default:
if (kind === "taxonomy") return {
type: "term",
subtype: type
};
if (kind === "post-type") return {
type: "post",
subtype: type
};
return {
type: "post",
subtype: "page"
};
}
}
/**
* Given the Link block's type attribute, return the query params to give to
* /wp/v2/search.
*
* @param type Link block's type attribute.
* @param kind Link block's entity of kind (post-type|taxonomy)
* @return Search query params.
*/
function getSuggestionsQuery(type, kind) {
const ownType = getOwnTypeSearchOptions(type, kind);
return {
preferTypes: [ownType.subtype ? ownType : ownType.type],
initialSuggestionsSearchOptions: {
...ownType,
perPage: 20
}
};
}
/**
* Capitalize the first letter of a string.
*
* @param str The string to capitalize
* @return Capitalized string
*/
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* Check if a URL points to the site homepage.
* Handles protocol (http/https) and trailing slash variations.
* Does not match subdomains unless they are the site URL.
*
* @param url The URL to check
* @param homeUrl The WordPress site URL
* @return True if url is the homepage
*/
function isHomepage(url, homeUrl) {
if (url === "/") return true;
if (!url || !homeUrl) return false;
try {
const urlParsed = new URL(url, homeUrl);
const homeParsed = new URL(homeUrl);
if (urlParsed.hostname !== homeParsed.hostname) return false;
return urlParsed.pathname.replace(/\/$/, "") === homeParsed.pathname.replace(/\/$/, "");
} catch {
return false;
}
}
/**
* Compute display URL - strips site URL if internal, shows full URL if external.
*
* @param options Parameters object
* @param options.linkUrl The URL to process
* @param options.homeUrl The WordPress site URL (required for internal/external detection)
* @return Object with displayUrl and isExternal flag
*/
function computeDisplayUrl({ linkUrl, homeUrl } = {}) {
if (!linkUrl) return {
displayUrl: "",
isExternal: false
};
let displayUrl = (0, _wordpress_url.safeDecodeURI)(linkUrl);
let isExternal = false;
if (isRelativePath(linkUrl) || isHashLink(linkUrl)) return {
displayUrl,
isExternal: false
};
try {
const parsedUrl = new URL(linkUrl);
const siteHost = new URL(homeUrl).host;
if (parsedUrl.host === siteHost) {
let path = parsedUrl.pathname + parsedUrl.search + parsedUrl.hash;
if (path.endsWith("/") && path.length > 1) path = path.slice(0, -1);
displayUrl = path;
} else isExternal = true;
} catch {
isExternal = true;
}
return {
displayUrl,
isExternal
};
}
/**
* Compute badges for the link preview.
*
* @param options Options object
* @param options.url Link URL
* @param options.homeUrl WordPress site URL (for homepage detection)
* @param options.type Entity type (page, post, etc.)
* @param options.isExternal Whether link is external
* @param options.entityStatus Entity status (publish, draft, etc.)
* @param options.hasBinding Whether link has entity binding
* @param options.isEntityAvailable Whether bound entity exists
* @return Array of badge objects with label and `@wordpress/ui` `Badge` intent
*/
function computeBadges({ url, homeUrl, type, isExternal, entityStatus, hasBinding, isEntityAvailable }) {
const badges = [];
if (url) {
if (isExternal) badges.push({
label: (0, _wordpress_i18n.__)("External link"),
intent: "none"
});
else if (isHashLink(url)) badges.push({
label: (0, _wordpress_i18n.__)("Internal link"),
intent: "none"
});
else if (isHomepage(url, homeUrl)) badges.push({
label: (0, _wordpress_i18n.__)("Homepage"),
intent: "none"
});
else if (type && type !== "custom") badges.push({
label: capitalize(type),
intent: "none"
});
else badges.push({
label: (0, _wordpress_i18n.__)("Page"),
intent: "none"
});
}
if (hasBinding && !isEntityAvailable) badges.push({
label: (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Missing %s"), type),
intent: "high"
});
else if (!url) badges.push({
label: (0, _wordpress_i18n.__)("No link selected"),
intent: "high"
});
else if (entityStatus) {
const badge = {
publish: {
label: (0, _wordpress_i18n.__)("Published"),
intent: "stable"
},
future: {
label: (0, _wordpress_i18n.__)("Scheduled"),
intent: "informational"
},
draft: {
label: (0, _wordpress_i18n.__)("Draft"),
intent: "low"
},
pending: {
label: (0, _wordpress_i18n.__)("Pending"),
intent: "low"
},
private: {
label: (0, _wordpress_i18n.__)("Private"),
intent: "informational"
},
trash: {
label: (0, _wordpress_i18n.__)("Trashed"),
intent: "high"
}
}[entityStatus];
if (badge) badges.push(badge);
}
return badges;
}
/**
* Returns an entity record's display title: the rendered title, "(no title)"
* for an untitled entity, or the record's name.
*
* @param entityRecord The entity record.
* @return The display title.
*/
function getEntityTitle(entityRecord) {
const title = entityRecord?.title;
if (typeof title === "string") return title;
if (title && "rendered" in title) return title.rendered || (0, _wordpress_i18n.__)("(no title)");
return entityRecord?.name;
}
/**
* Hook to compute link preview data for display.
*
* This hook takes raw link data and entity information and computes
* presentation-ready preview data including formatted title, URL, and badges.
*
* @param options Options object
* @param options.url Link URL
* @param options.type Entity type (page, post, etc.)
* @param options.entityRecord Entity record
* @param options.hasBinding Whether link has entity binding
* @param options.isEntityAvailable Whether bound entity exists
* @return Preview data object with title, url, image, and badges
*/
function useLinkPreview({ url, entityRecord, type, hasBinding, isEntityAvailable }) {
const homeUrl = (0, _wordpress_data.useSelect)((select) => {
return select(_wordpress_core_data.store).getEntityRecord("root", "__unstableBase")?.home;
}, []);
const title = getEntityTitle(entityRecord);
const { richData } = useRemoteUrlData(title ? null : url);
const { displayUrl, isExternal } = computeDisplayUrl({
linkUrl: url,
homeUrl
});
const image = (0, _wordpress_data.useSelect)((select) => {
if (!entityRecord?.featured_media) return null;
const { getEntityRecord } = select(_wordpress_core_data.store);
const media = getEntityRecord("postType", "attachment", entityRecord.featured_media);
return media?.media_details?.sizes?.thumbnail?.source_url || media?.media_details?.sizes?.medium?.source_url || media?.source_url || null;
}, [entityRecord?.featured_media]);
const badges = computeBadges({
url,
homeUrl,
type,
isExternal,
entityStatus: entityRecord?.status,
hasBinding,
isEntityAvailable
});
return {
title: url ? title || richData?.title || (0, _wordpress_url.safeDecodeURI)(url) : (0, _wordpress_i18n.__)("Add link"),
url: displayUrl,
image,
badges
};
}
exports.computeBadges = computeBadges;
exports.computeDisplayUrl = computeDisplayUrl;
exports.getSuggestionsQuery = getSuggestionsQuery;
exports.isHomepage = isHomepage;
exports.useLinkPreview = useLinkPreview;
//# sourceMappingURL=link-picker.cjs.map