@wordpress/block-library
Version:
Block library for the WordPress editor.
1 lines • 16.3 kB
Source Map (JSON)
{"version":3,"file":"link-picker.cjs","names":["unlock","blockEditorPrivateApis","safeDecodeURI","__","sprintf","useSelect","coreDataStore"],"sources":["../../src/utils/link-picker.ts"],"sourcesContent":["import { __, sprintf } from '@wordpress/i18n';\nimport { safeDecodeURI } from '@wordpress/url';\nimport { privateApis as blockEditorPrivateApis } from '@wordpress/block-editor';\nimport { useSelect } from '@wordpress/data';\nimport { store as coreDataStore, type Attachment } from '@wordpress/core-data';\nimport { unlock } from '../lock-unlock';\n\n/**\n * Helpers for a block that edits a link with the block editor's `LinkPicker`:\n * the preview it shows for the current link, and the search options for its\n * suggestions.\n */\n\nconst { useRemoteUrlData, isHashLink, isRelativePath } = unlock(\n\tblockEditorPrivateApis\n);\n\ninterface SearchOptions {\n\ttype: string;\n\tsubtype?: string;\n}\n\nexport interface SuggestionsQuery {\n\tpreferTypes: ( SearchOptions | string )[];\n\tinitialSuggestionsSearchOptions: SearchOptions & { perPage: number };\n}\n\n/**\n * Given the Link block's type attribute, return the query params for that one\n * entity type.\n *\n * @param type Link block's type attribute.\n * @param kind Link block's entity of kind (post-type|taxonomy)\n * @return Search query params.\n */\nfunction getOwnTypeSearchOptions(\n\ttype?: string,\n\tkind?: string\n): SearchOptions {\n\tswitch ( type ) {\n\t\tcase 'post':\n\t\tcase 'page':\n\t\t\treturn { type: 'post', subtype: type };\n\t\tcase 'category':\n\t\t\treturn { type: 'term', subtype: 'category' };\n\t\tcase 'tag':\n\t\t\treturn { type: 'term', subtype: 'post_tag' };\n\t\tcase 'post_format':\n\t\t\treturn { type: 'post-format' };\n\t\tdefault:\n\t\t\tif ( kind === 'taxonomy' ) {\n\t\t\t\treturn { type: 'term', subtype: type };\n\t\t\t}\n\t\t\tif ( kind === 'post-type' ) {\n\t\t\t\treturn { type: 'post', subtype: type };\n\t\t\t}\n\t\t\t// for custom link which has no type\n\t\t\t// always show pages as initial suggestions\n\t\t\treturn { type: 'post', subtype: 'page' };\n\t}\n}\n\n/**\n * Given the Link block's type attribute, return the query params to give to\n * /wp/v2/search.\n *\n * @param type Link block's type attribute.\n * @param kind Link block's entity of kind (post-type|taxonomy)\n * @return Search query params.\n */\nexport function getSuggestionsQuery(\n\ttype?: string,\n\tkind?: string\n): SuggestionsQuery {\n\tconst ownType = getOwnTypeSearchOptions( type, kind );\n\n\treturn {\n\t\tpreferTypes: [ ownType.subtype ? ownType : ownType.type ],\n\t\tinitialSuggestionsSearchOptions: { ...ownType, perPage: 20 },\n\t};\n}\n\n/**\n * Capitalize the first letter of a string.\n *\n * @param str The string to capitalize\n * @return Capitalized string\n */\nfunction capitalize( str: string ) {\n\treturn str.charAt( 0 ).toUpperCase() + str.slice( 1 );\n}\n\n/**\n * Check if a URL points to the site homepage.\n * Handles protocol (http/https) and trailing slash variations.\n * Does not match subdomains unless they are the site URL.\n *\n * @param url The URL to check\n * @param homeUrl The WordPress site URL\n * @return True if url is the homepage\n */\nexport function isHomepage( url?: string | null, homeUrl?: string ) {\n\tif ( url === '/' ) {\n\t\treturn true;\n\t}\n\tif ( ! url || ! homeUrl ) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tconst urlParsed = new URL( url, homeUrl );\n\t\tconst homeParsed = new URL( homeUrl );\n\n\t\t// Same host, i.e. sub.homepage.com or homepage.com\n\t\tif ( urlParsed.hostname !== homeParsed.hostname ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Path must match site root (normalize trailing slash)\n\t\tconst urlPath = urlParsed.pathname.replace( /\\/$/, '' );\n\t\tconst homePath = homeParsed.pathname.replace( /\\/$/, '' );\n\n\t\treturn urlPath === homePath;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Compute display URL - strips site URL if internal, shows full URL if external.\n *\n * @param options Parameters object\n * @param options.linkUrl The URL to process\n * @param options.homeUrl The WordPress site URL (required for internal/external detection)\n * @return Object with displayUrl and isExternal flag\n */\nexport function computeDisplayUrl( {\n\tlinkUrl,\n\thomeUrl,\n}: { linkUrl?: string | null; homeUrl?: string } = {} ) {\n\tif ( ! linkUrl ) {\n\t\treturn { displayUrl: '', isExternal: false };\n\t}\n\n\tlet displayUrl = safeDecodeURI( linkUrl );\n\tlet isExternal = false;\n\n\t// Check hash links and relative paths first - these are always internal\n\tif ( isRelativePath( linkUrl ) || isHashLink( linkUrl ) ) {\n\t\treturn { displayUrl, isExternal: false };\n\t}\n\n\t// Try to parse as a full URL to determine if it's actually external\n\t// This must happen before trusting the type attribute\n\ttry {\n\t\tconst parsedUrl = new URL( linkUrl );\n\t\t// Compare by host (not origin) so http/https to same site both count as internal\n\t\tconst siteHost = new URL( homeUrl as string ).host;\n\n\t\tif ( parsedUrl.host === siteHost ) {\n\t\t\t// Show only the pathname (and search/hash if present)\n\t\t\tlet path = parsedUrl.pathname + parsedUrl.search + parsedUrl.hash;\n\t\t\t// Remove trailing slash\n\t\t\tif ( path.endsWith( '/' ) && path.length > 1 ) {\n\t\t\t\tpath = path.slice( 0, -1 );\n\t\t\t}\n\t\t\tdisplayUrl = path;\n\t\t} else {\n\t\t\t// Different host - this is an external link\n\t\t\tisExternal = true;\n\t\t}\n\t} catch {\n\t\t// URL parsing failed - treat as external (e.g. no homeUrl, or URL without protocol)\n\t\tisExternal = true;\n\t}\n\n\treturn { displayUrl, isExternal };\n}\n\nexport interface Badge {\n\tlabel: string;\n\t/** A `@wordpress/ui` `Badge` intent. */\n\tintent: 'none' | 'high' | 'low' | 'stable' | 'informational';\n}\n\n/**\n * Compute badges for the link preview.\n *\n * @param options Options object\n * @param options.url Link URL\n * @param options.homeUrl WordPress site URL (for homepage detection)\n * @param options.type Entity type (page, post, etc.)\n * @param options.isExternal Whether link is external\n * @param options.entityStatus Entity status (publish, draft, etc.)\n * @param options.hasBinding Whether link has entity binding\n * @param options.isEntityAvailable Whether bound entity exists\n * @return Array of badge objects with label and `@wordpress/ui` `Badge` intent\n */\nexport function computeBadges( {\n\turl,\n\thomeUrl,\n\ttype,\n\tisExternal,\n\tentityStatus,\n\thasBinding,\n\tisEntityAvailable,\n}: {\n\turl?: string | null;\n\thomeUrl?: string;\n\ttype?: string | null;\n\tisExternal?: boolean;\n\tentityStatus?: string;\n\thasBinding?: boolean;\n\tisEntityAvailable?: boolean;\n} ): Badge[] {\n\tconst badges: Badge[] = [];\n\t// Kind badge\n\tif ( url ) {\n\t\tif ( isExternal ) {\n\t\t\tbadges.push( {\n\t\t\t\tlabel: __( 'External link' ),\n\t\t\t\tintent: 'none',\n\t\t\t} );\n\t\t} else if ( isHashLink( url ) ) {\n\t\t\t// Hash links should be detected before type check\n\t\t\t// because they're not entity links even if type is set\n\t\t\tbadges.push( {\n\t\t\t\tlabel: __( 'Internal link' ),\n\t\t\t\tintent: 'none',\n\t\t\t} );\n\t\t} else if ( isHomepage( url, homeUrl ) ) {\n\t\t\tbadges.push( {\n\t\t\t\tlabel: __( 'Homepage' ),\n\t\t\t\tintent: 'none',\n\t\t\t} );\n\t\t} else if ( type && type !== 'custom' ) {\n\t\t\t// Show entity type badge (page, post, category, etc.)\n\t\t\t// but not 'custom' since that's just a manual link\n\t\t\tbadges.push( { label: capitalize( type ), intent: 'none' } );\n\t\t} else {\n\t\t\t// Internal link (not external, not hash, not entity)\n\t\t\tbadges.push( {\n\t\t\t\tlabel: __( 'Page' ),\n\t\t\t\tintent: 'none',\n\t\t\t} );\n\t\t}\n\t}\n\n\t// Status badge\n\tif ( hasBinding && ! isEntityAvailable ) {\n\t\tbadges.push( {\n\t\t\tlabel: sprintf(\n\t\t\t\t/* translators: %s is the entity type (e.g., \"page\", \"post\", \"category\") */\n\t\t\t\t__( 'Missing %s' ),\n\t\t\t\ttype as string\n\t\t\t),\n\t\t\tintent: 'high',\n\t\t} );\n\t} else if ( ! url ) {\n\t\tbadges.push( { label: __( 'No link selected' ), intent: 'high' } );\n\t} else if ( entityStatus ) {\n\t\tconst statusMap: Record< string, Badge > = {\n\t\t\tpublish: { label: __( 'Published' ), intent: 'stable' },\n\t\t\tfuture: { label: __( 'Scheduled' ), intent: 'informational' },\n\t\t\tdraft: { label: __( 'Draft' ), intent: 'low' },\n\t\t\tpending: { label: __( 'Pending' ), intent: 'low' },\n\t\t\tprivate: { label: __( 'Private' ), intent: 'informational' },\n\t\t\ttrash: { label: __( 'Trashed' ), intent: 'high' },\n\t\t};\n\t\tconst badge = statusMap[ entityStatus ];\n\t\tif ( badge ) {\n\t\t\tbadges.push( badge );\n\t\t}\n\t}\n\n\treturn badges;\n}\n\n/**\n * The parts of an entity record the link preview reads. Posts and pages\n * expose `title` as a `{ raw, rendered }` object; terms use a plain `name`.\n */\nexport interface LinkPreviewEntityRecord {\n\ttitle?: string | { raw?: string; rendered?: string };\n\tname?: string;\n\tstatus?: string;\n\tfeatured_media?: number;\n}\n\n/**\n * Returns an entity record's display title: the rendered title, \"(no title)\"\n * for an untitled entity, or the record's name.\n *\n * @param entityRecord The entity record.\n * @return The display title.\n */\nfunction getEntityTitle( entityRecord?: LinkPreviewEntityRecord | null ) {\n\tconst title = entityRecord?.title;\n\n\t// Some entity types use a plain string for the title.\n\tif ( typeof title === 'string' ) {\n\t\treturn title;\n\t}\n\n\t// Posts and pages expose `title` as a { raw, rendered } object.\n\tif ( title && 'rendered' in title ) {\n\t\treturn title.rendered || __( '(no title)' );\n\t}\n\n\treturn entityRecord?.name;\n}\n\n/**\n * Hook to compute link preview data for display.\n *\n * This hook takes raw link data and entity information and computes\n * presentation-ready preview data including formatted title, URL, and badges.\n *\n * @param options Options object\n * @param options.url Link URL\n * @param options.type Entity type (page, post, etc.)\n * @param options.entityRecord Entity record\n * @param options.hasBinding Whether link has entity binding\n * @param options.isEntityAvailable Whether bound entity exists\n * @return Preview data object with title, url, image, and badges\n */\nexport function useLinkPreview( {\n\turl,\n\tentityRecord,\n\ttype,\n\thasBinding,\n\tisEntityAvailable,\n}: {\n\turl?: string | null;\n\tentityRecord?: LinkPreviewEntityRecord | null;\n\ttype?: string | null;\n\thasBinding?: boolean;\n\tisEntityAvailable?: boolean;\n} ) {\n\t// Get the WordPress homepage URL from settings\n\tconst homeUrl = useSelect( ( select ) => {\n\t\treturn select( coreDataStore ).getEntityRecord< { home?: string } >(\n\t\t\t'root',\n\t\t\t'__unstableBase'\n\t\t)?.home;\n\t}, [] );\n\n\tconst title = getEntityTitle( entityRecord );\n\n\t// Fetch rich URL data if we don't have a title. Internal links should have passed a title.\n\tconst { richData } = useRemoteUrlData( title ? null : url );\n\n\t// Compute display URL and external flag\n\tconst { displayUrl, isExternal } = computeDisplayUrl( {\n\t\tlinkUrl: url,\n\t\thomeUrl,\n\t} );\n\n\tconst image = useSelect(\n\t\t( select ) => {\n\t\t\t// Only fetch for post-type entities with featured media\n\t\t\tif ( ! entityRecord?.featured_media ) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst { getEntityRecord } = select( coreDataStore );\n\n\t\t\t// Get the media entity to fetch the image URL\n\t\t\tconst media = getEntityRecord< Attachment >(\n\t\t\t\t'postType',\n\t\t\t\t'attachment',\n\t\t\t\tentityRecord.featured_media\n\t\t\t);\n\n\t\t\t// Return the thumbnail or medium size URL, fallback to source_url\n\t\t\treturn (\n\t\t\t\tmedia?.media_details?.sizes?.thumbnail?.source_url ||\n\t\t\t\tmedia?.media_details?.sizes?.medium?.source_url ||\n\t\t\t\tmedia?.source_url ||\n\t\t\t\tnull\n\t\t\t);\n\t\t},\n\t\t[ entityRecord?.featured_media ]\n\t);\n\n\t// Compute badges\n\tconst badges = computeBadges( {\n\t\turl,\n\t\thomeUrl,\n\t\ttype,\n\t\tisExternal,\n\t\tentityStatus: entityRecord?.status,\n\t\thasBinding,\n\t\tisEntityAvailable,\n\t} );\n\n\t// Get display title - use provided title, fallback to rich data, or URL\n\tconst displayTitle = url\n\t\t? title || richData?.title || safeDecodeURI( url )\n\t\t: __( 'Add link' );\n\n\treturn {\n\t\ttitle: displayTitle,\n\t\turl: displayUrl,\n\t\timage,\n\t\tbadges,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;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