UNPKG

@wordpress/block-library

Version:
273 lines (272 loc) • 7.96 kB
import { __, sprintf } from "@wordpress/i18n"; import { safeDecodeURI } from "@wordpress/url"; import { privateApis } from "@wordpress/block-editor"; import { useSelect } from "@wordpress/data"; import { store } from "@wordpress/core-data"; import { unlock } from "../lock-unlock.mjs"; // 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 } = unlock(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 = 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: __("External link"), intent: "none" }); else if (isHashLink(url)) badges.push({ label: __("Internal link"), intent: "none" }); else if (isHomepage(url, homeUrl)) badges.push({ label: __("Homepage"), intent: "none" }); else if (type && type !== "custom") badges.push({ label: capitalize(type), intent: "none" }); else badges.push({ label: __("Page"), intent: "none" }); } if (hasBinding && !isEntityAvailable) badges.push({ label: sprintf(__("Missing %s"), type), intent: "high" }); else if (!url) badges.push({ label: __("No link selected"), intent: "high" }); else if (entityStatus) { const badge = { publish: { label: __("Published"), intent: "stable" }, future: { label: __("Scheduled"), intent: "informational" }, draft: { label: __("Draft"), intent: "low" }, pending: { label: __("Pending"), intent: "low" }, private: { label: __("Private"), intent: "informational" }, trash: { label: __("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 || __("(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 = useSelect((select) => { return select(store).getEntityRecord("root", "__unstableBase")?.home; }, []); const title = getEntityTitle(entityRecord); const { richData } = useRemoteUrlData(title ? null : url); const { displayUrl, isExternal } = computeDisplayUrl({ linkUrl: url, homeUrl }); const image = useSelect((select) => { if (!entityRecord?.featured_media) return null; const { getEntityRecord } = select(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 || safeDecodeURI(url) : __("Add link"), url: displayUrl, image, badges }; } export { computeBadges, computeDisplayUrl, getSuggestionsQuery, isHomepage, useLinkPreview }; //# sourceMappingURL=link-picker.mjs.map