{"version":3,"file":"util.cjs","names":["metadata","getBlockVariations","getAuthority","renderToString","getBlockType","WP_EMBED_TYPE","createBlock","ASPECT_RATIOS","memoize","kebabCase"],"sources":["../../src/embed/util.jsx"],"sourcesContent":["import clsx from 'clsx';\nimport memoize from 'memize';\nimport { renderToString } from '@wordpress/element';\nimport {\n\tcreateBlock,\n\tgetBlockType,\n\tgetBlockVariations,\n} from '@wordpress/blocks';\nimport { getAuthority } from '@wordpress/url';\nimport { kebabCase } from '@wordpress/kebab-case';\nimport metadata from './block.json';\nimport { ASPECT_RATIOS, WP_EMBED_TYPE } from './constants';\n\nconst { name: DEFAULT_EMBED_BLOCK } = metadata;\n\n/** @typedef {import('@wordpress/blocks').WPBlockVariation} WPBlockVariation */\n\n/**\n * Returns the embed block's information by matching the provided service provider\n *\n * @param {string} provider The embed block's provider\n * @return {WPBlockVariation} The embed block's information\n */\nexport const getEmbedInfoByProvider = ( provider ) =>\n\tgetBlockVariations( DEFAULT_EMBED_BLOCK )?.find(\n\t\t( { name } ) => name === provider\n\t);\n\n/**\n * Returns true if any of the regular expressions match the URL.\n *\n * @param {string} url      The URL to test.\n * @param {Array}  patterns The list of regular expressions to test against.\n * @return {boolean} True if any of the regular expressions match the URL.\n */\nexport const matchesPatterns = ( url, patterns = [] ) =>\n\tpatterns.some( ( pattern ) => url.match( pattern ) );\n\n/**\n * Finds the block variation that should be used for the URL,\n * based on the provided URL and the variation's patterns.\n *\n * @param {string} url The URL to test.\n * @return {WPBlockVariation} The block variation that should be used for this URL\n */\nexport const findMoreSuitableBlock = ( url ) =>\n\tgetBlockVariations( DEFAULT_EMBED_BLOCK )?.find( ( { patterns } ) =>\n\t\tmatchesPatterns( url, patterns )\n\t);\n\n/**\n * Rewrites `x.com` URLs to `twitter.com` as a workaround while the\n * WordPress oEmbed registry lacks an X provider. See: https://core.trac.wordpress.org/ticket/59142.\n *\n * @param {string} url The URL to rewrite.\n * @return {string} The (possibly) rewritten URL.\n */\nexport function rewriteXToTwitter( url ) {\n\tif ( ! url || getAuthority( url ) !== 'x.com' ) {\n\t\treturn url;\n\t}\n\tconst rewritten = new URL( url );\n\trewritten.host = 'twitter.com';\n\treturn rewritten.toString();\n}\n\nexport const isFromWordPress = ( html ) =>\n\thtml && html.includes( 'class=\"wp-embedded-content\"' );\n\nexport const getPhotoHtml = ( photo ) => {\n\t// If full image url not found use thumbnail.\n\tconst imageUrl = photo.url || photo.thumbnail_url;\n\n\t// 100% width for the preview so it fits nicely into the document, some \"thumbnails\" are\n\t// actually the full size photo.\n\tconst photoPreview = (\n\t\t<p>\n\t\t\t<img src={ imageUrl } alt={ photo.title } width=\"100%\" />\n\t\t</p>\n\t);\n\treturn renderToString( photoPreview );\n};\n\n/**\n * Creates a more suitable embed block based on the passed in props\n * and attributes generated from an embed block's preview.\n *\n * We require `attributesFromPreview` to be generated from the latest attributes\n * and preview, and because of the way the react lifecycle operates, we can't\n * guarantee that the attributes contained in the block's props are the latest\n * versions, so we require that these are generated separately.\n * See `getAttributesFromPreview` in the generated embed edit component.\n *\n * @param {Object} props                   The block's props.\n * @param {Object} [attributesFromPreview] Attributes generated from the block's most up to date preview.\n * @return {Object|undefined} A more suitable embed block if one exists.\n */\nexport const createUpgradedEmbedBlock = (\n\tprops,\n\tattributesFromPreview = {}\n) => {\n\tconst { preview, attributes = {} } = props;\n\tconst { url, providerNameSlug, type, ...restAttributes } = attributes;\n\n\tif ( ! url || ! getBlockType( DEFAULT_EMBED_BLOCK ) ) {\n\t\treturn;\n\t}\n\n\tconst matchedBlock = findMoreSuitableBlock( url );\n\n\t// WordPress blocks can work on multiple sites, and so don't have patterns,\n\t// so if we're in a WordPress block, assume the user has chosen it for a WordPress URL.\n\tconst isCurrentBlockWP =\n\t\tproviderNameSlug === 'wordpress' || type === WP_EMBED_TYPE;\n\t// If current block is not WordPress and a more suitable block found\n\t// that is different from the current one, create the new matched block.\n\tconst shouldCreateNewBlock =\n\t\t! isCurrentBlockWP &&\n\t\tmatchedBlock &&\n\t\t( matchedBlock.attributes.providerNameSlug !== providerNameSlug ||\n\t\t\t! providerNameSlug );\n\tif ( shouldCreateNewBlock ) {\n\t\treturn createBlock( DEFAULT_EMBED_BLOCK, {\n\t\t\turl,\n\t\t\t...restAttributes,\n\t\t\t...matchedBlock.attributes,\n\t\t} );\n\t}\n\n\tconst wpVariation = getBlockVariations( DEFAULT_EMBED_BLOCK )?.find(\n\t\t( { name } ) => name === 'wordpress'\n\t);\n\n\t// We can't match the URL for WordPress embeds, we have to check the HTML instead.\n\tif (\n\t\t! wpVariation ||\n\t\t! preview ||\n\t\t! isFromWordPress( preview.html ) ||\n\t\tisCurrentBlockWP\n\t) {\n\t\treturn;\n\t}\n\n\t// This is not the WordPress embed block so transform it into one.\n\treturn createBlock( DEFAULT_EMBED_BLOCK, {\n\t\turl,\n\t\t...wpVariation.attributes,\n\t\t// By now we have the preview, but when the new block first renders, it\n\t\t// won't have had all the attributes set, and so won't get the correct\n\t\t// type and it won't render correctly. So, we pass through the current attributes\n\t\t// here so that the initial render works when we switch to the WordPress\n\t\t// block. This only affects the WordPress block because it can't be\n\t\t// rendered in the usual Sandbox (it has a sandbox of its own) and it\n\t\t// relies on the preview to set the correct render type.\n\t\t...attributesFromPreview,\n\t} );\n};\n\n/**\n * Determine if the block already has an aspect ratio class applied.\n *\n * @param {string} existingClassNames Existing block classes.\n * @return {boolean} True or false if the classnames contain an aspect ratio class.\n */\nexport const hasAspectRatioClass = ( existingClassNames ) => {\n\tif ( ! existingClassNames ) {\n\t\treturn false;\n\t}\n\treturn ASPECT_RATIOS.some( ( { className } ) =>\n\t\texistingClassNames.includes( className )\n\t);\n};\n\n/**\n * Removes all previously set aspect ratio related classes and return the rest\n * existing class names.\n *\n * @param {string} existingClassNames Any existing class names.\n * @return {string} The class names without any aspect ratio related class.\n */\nexport const removeAspectRatioClasses = ( existingClassNames ) => {\n\tif ( ! existingClassNames ) {\n\t\t// Avoids extraneous work and also, by returning the same value as\n\t\t// received, ensures the post is not dirtied by a change of the block\n\t\t// attribute from `undefined` to an empty string.\n\t\treturn existingClassNames;\n\t}\n\tconst aspectRatioClassNames = ASPECT_RATIOS.reduce(\n\t\t( accumulator, { className } ) => {\n\t\t\taccumulator.push( className );\n\t\t\treturn accumulator;\n\t\t},\n\t\t[ 'wp-has-aspect-ratio' ]\n\t);\n\tlet outputClassNames = existingClassNames;\n\tfor ( const className of aspectRatioClassNames ) {\n\t\toutputClassNames = outputClassNames.replace( className, '' );\n\t}\n\treturn outputClassNames.trim();\n};\n\n/**\n * Checks if HTML already contains responsive aspect ratio styling.\n * Some embed providers (like Flickr) include their own responsive wrapper\n * with padding-bottom or padding-top percentages for aspect ratio.\n *\n * @param {string} html The embed HTML to check.\n * @return {boolean} True if the HTML already has responsive styling.\n */\nexport function hasInlineResponsivePadding( html ) {\n\t// Check for padding-bottom or padding-top with percentage values in style attributes\n\t// This pattern matches: padding-bottom: 56.25%; or padding-top: 50%; etc.\n\tconst paddingPattern = /padding-(top|bottom)\\s*:\\s*[\\d.]+%/i;\n\treturn paddingPattern.test( html );\n}\n\n/**\n * Returns class names with any relevant responsive aspect ratio names.\n *\n * @param {string}  html               The preview HTML that possibly contains an iframe with width and height set.\n * @param {string}  existingClassNames Any existing class names.\n * @param {boolean} allowResponsive    If the responsive class names should be added, or removed.\n * @return {string} Deduped class names.\n */\nexport function getClassNames(\n\thtml,\n\texistingClassNames,\n\tallowResponsive = true\n) {\n\tif ( ! allowResponsive ) {\n\t\treturn removeAspectRatioClasses( existingClassNames );\n\t}\n\n\t// If the embed HTML already contains responsive wrapper styling (like Flickr),\n\t// don't add our own aspect ratio classes to avoid double padding.\n\tif ( hasInlineResponsivePadding( html ) ) {\n\t\treturn removeAspectRatioClasses( existingClassNames );\n\t}\n\n\tconst previewDocument = document.implementation.createHTMLDocument( '' );\n\tpreviewDocument.body.innerHTML = html;\n\tconst iframe = previewDocument.body.querySelector( 'iframe' );\n\n\t// If we have a fixed aspect iframe, and it's a responsive embed block.\n\tif ( iframe && iframe.height && iframe.width ) {\n\t\tconst aspectRatio = ( iframe.width / iframe.height ).toFixed( 2 );\n\t\t// Given the actual aspect ratio, find the widest ratio to support it.\n\t\tfor (\n\t\t\tlet ratioIndex = 0;\n\t\t\tratioIndex < ASPECT_RATIOS.length;\n\t\t\tratioIndex++\n\t\t) {\n\t\t\tconst potentialRatio = ASPECT_RATIOS[ ratioIndex ];\n\t\t\tif ( aspectRatio >= potentialRatio.ratio ) {\n\t\t\t\t// Evaluate the difference between actual aspect ratio and closest match.\n\t\t\t\t// If the difference is too big, do not scale the embed according to aspect ratio.\n\t\t\t\tconst ratioDiff = aspectRatio - potentialRatio.ratio;\n\t\t\t\tif ( ratioDiff > 0.1 ) {\n\t\t\t\t\t// No close aspect ratio match found.\n\t\t\t\t\treturn removeAspectRatioClasses( existingClassNames );\n\t\t\t\t}\n\t\t\t\t// Close aspect ratio match found.\n\t\t\t\treturn clsx(\n\t\t\t\t\tremoveAspectRatioClasses( existingClassNames ),\n\t\t\t\t\tpotentialRatio.className,\n\t\t\t\t\t'wp-has-aspect-ratio'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn existingClassNames;\n}\n\n/**\n * Fallback behaviour for unembeddable URLs.\n * Creates a paragraph block containing a link to the URL, and calls `onReplace`.\n *\n * @param {string}   url       The URL that could not be embedded.\n * @param {Function} onReplace Function to call with the created fallback block.\n */\nexport function fallback( url, onReplace ) {\n\tconst link = <a href={ url }>{ url }</a>;\n\tonReplace(\n\t\tcreateBlock( 'core/paragraph', { content: renderToString( link ) } )\n\t);\n}\n\n/***\n * Gets block attributes based on the preview and responsive state.\n *\n * @param {Object} preview The preview data.\n * @param {string} title The block's title, e.g. Twitter.\n * @param {Object} currentClassNames The block's current class names.\n * @param {boolean} isResponsive Boolean indicating if the block supports responsive content.\n * @param {boolean} allowResponsive Apply responsive classes to fixed size content.\n * @return {Object} Attributes and values.\n */\nexport const getAttributesFromPreview = memoize(\n\t(\n\t\tpreview,\n\t\ttitle,\n\t\tcurrentClassNames,\n\t\tisResponsive,\n\t\tallowResponsive = true\n\t) => {\n\t\tif ( ! preview ) {\n\t\t\treturn {};\n\t\t}\n\n\t\tconst attributes = {};\n\t\t// Some plugins only return HTML with no type info, so default this to 'rich'.\n\t\tlet { type = 'rich' } = preview;\n\t\t// If we got a provider name from the API, use it for the slug, otherwise we use the title,\n\t\t// because not all embed code gives us a provider name.\n\t\tconst { html, provider_name: providerName } = preview;\n\t\tconst providerNameSlug = kebabCase(\n\t\t\t( providerName || title ).toLowerCase()\n\t\t);\n\n\t\tif ( isFromWordPress( html ) ) {\n\t\t\ttype = WP_EMBED_TYPE;\n\t\t}\n\n\t\tif ( html || 'photo' === type ) {\n\t\t\tattributes.type = type;\n\t\t\tattributes.providerNameSlug = providerNameSlug;\n\t\t}\n\n\t\t// Aspect ratio classes are removed when the embed URL is updated.\n\t\t// If the embed already has an aspect ratio class, that means the URL has not changed.\n\t\t// Which also means no need to regenerate it with getClassNames.\n\t\tif ( hasAspectRatioClass( currentClassNames ) ) {\n\t\t\treturn attributes;\n\t\t}\n\n\t\tattributes.className = getClassNames(\n\t\t\thtml,\n\t\t\tcurrentClassNames,\n\t\t\tisResponsive && allowResponsive\n\t\t);\n\n\t\treturn attributes;\n\t}\n);\n\n/**\n * Returns the attributes derived from the preview, merged with the current attributes.\n *\n * @param {Object}  currentAttributes The current attributes of the block.\n * @param {Object}  preview           The preview data.\n * @param {string}  title             The block's title, e.g. Twitter.\n * @param {boolean} isResponsive      Boolean indicating if the block supports responsive content.\n * @return {Object} Merged attributes.\n */\nexport const getMergedAttributesWithPreview = (\n\tcurrentAttributes,\n\tpreview,\n\ttitle,\n\tisResponsive\n) => {\n\tconst { allowResponsive, className } = currentAttributes;\n\n\treturn {\n\t\t...currentAttributes,\n\t\t...getAttributesFromPreview(\n\t\t\tpreview,\n\t\t\ttitle,\n\t\t\tclassName,\n\t\t\tisResponsive,\n\t\t\tallowResponsive\n\t\t),\n\t};\n};\n"],"mappings":";;;;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