UNPKG

@wordpress/block-library

Version:
257 lines (256 loc) • 11.9 kB
"use strict"; Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); // \0rolldown/runtime.js var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); let clsx = require("clsx"); clsx = __toESM(clsx); let memize = require("memize"); memize = __toESM(memize); let _wordpress_element = require("@wordpress/element"); let _wordpress_blocks = require("@wordpress/blocks"); let _wordpress_url = require("@wordpress/url"); let _wordpress_kebab_case = require("@wordpress/kebab-case"); let __block_json = require("./block.json"); __block_json = __toESM(__block_json); let __constants_js = require("./constants.cjs"); let react_jsx_runtime = require("react/jsx-runtime"); // packages/block-library/src/embed/util.jsx const { name: DEFAULT_EMBED_BLOCK } = __block_json.default; /** @typedef {import('@wordpress/blocks').WPBlockVariation} WPBlockVariation */ /** * Returns the embed block's information by matching the provided service provider * * @param {string} provider The embed block's provider * @return {WPBlockVariation|undefined} The embed block's information */ const getEmbedInfoByProvider = (provider) => { if (!provider) return; return (0, _wordpress_blocks.getBlockVariations)(DEFAULT_EMBED_BLOCK)?.find(({ name, attributes }) => name === provider || attributes?.providerNameSlug === provider); }; /** * Returns true if any of the regular expressions match the URL. * * @param {string} url The URL to test. * @param {Array} patterns The list of regular expressions to test against. * @return {boolean} True if any of the regular expressions match the URL. */ const matchesPatterns = (url, patterns = []) => patterns.some((pattern) => url.match(pattern)); /** * Finds the block variation that should be used for the URL, * based on the provided URL and the variation's patterns. * * @param {string} url The URL to test. * @return {WPBlockVariation} The block variation that should be used for this URL */ const findMoreSuitableBlock = (url) => (0, _wordpress_blocks.getBlockVariations)(DEFAULT_EMBED_BLOCK)?.find(({ patterns }) => matchesPatterns(url, patterns)); /** * Rewrites `x.com` URLs to `twitter.com` as a workaround while the * WordPress oEmbed registry lacks an X provider. See: https://core.trac.wordpress.org/ticket/59142. * * @param {string} url The URL to rewrite. * @return {string} The (possibly) rewritten URL. */ function rewriteXToTwitter(url) { if (!url || (0, _wordpress_url.getAuthority)(url) !== "x.com") return url; const rewritten = new URL(url); rewritten.host = "twitter.com"; return rewritten.toString(); } const isFromWordPress = (html) => html && html.includes("class=\"wp-embedded-content\""); const getPhotoHtml = (photo) => { const imageUrl = photo.url || photo.thumbnail_url; const photoPreview = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { src: imageUrl, alt: photo.title, width: "100%" }) }); return (0, _wordpress_element.renderToString)(photoPreview); }; /** * Creates a more suitable embed block based on the passed in props * and attributes generated from an embed block's preview. * * We require `attributesFromPreview` to be generated from the latest attributes * and preview, and because of the way the react lifecycle operates, we can't * guarantee that the attributes contained in the block's props are the latest * versions, so we require that these are generated separately. * See `getAttributesFromPreview` in the generated embed edit component. * * @param {Object} props The block's props. * @param {Object} [attributesFromPreview] Attributes generated from the block's most up to date preview. * @return {Object|undefined} A more suitable embed block if one exists. */ const createUpgradedEmbedBlock = (props, attributesFromPreview = {}) => { const { preview, attributes = {} } = props; const { url, providerNameSlug, type, ...restAttributes } = attributes; if (!url || !(0, _wordpress_blocks.getBlockType)(DEFAULT_EMBED_BLOCK)) return; const matchedBlock = findMoreSuitableBlock(url); const isCurrentBlockWP = providerNameSlug === "wordpress" || type === __constants_js.WP_EMBED_TYPE; if (!isCurrentBlockWP && matchedBlock && (matchedBlock.attributes.providerNameSlug !== providerNameSlug || !providerNameSlug)) return (0, _wordpress_blocks.createBlock)(DEFAULT_EMBED_BLOCK, { url, ...restAttributes, ...matchedBlock.attributes }); const wpVariation = (0, _wordpress_blocks.getBlockVariations)(DEFAULT_EMBED_BLOCK)?.find(({ name }) => name === "wordpress"); if (!wpVariation || !preview || !isFromWordPress(preview.html) || isCurrentBlockWP) return; return (0, _wordpress_blocks.createBlock)(DEFAULT_EMBED_BLOCK, { url, ...wpVariation.attributes, ...attributesFromPreview }); }; /** * Determine if the block already has an aspect ratio class applied. * * @param {string} existingClassNames Existing block classes. * @return {boolean} True or false if the classnames contain an aspect ratio class. */ const hasAspectRatioClass = (existingClassNames) => { if (!existingClassNames) return false; return __constants_js.ASPECT_RATIOS.some(({ className }) => existingClassNames.includes(className)); }; /** * Removes all previously set aspect ratio related classes and return the rest * existing class names. * * @param {string} existingClassNames Any existing class names. * @return {string} The class names without any aspect ratio related class. */ const removeAspectRatioClasses = (existingClassNames) => { if (!existingClassNames) return existingClassNames; const aspectRatioClassNames = __constants_js.ASPECT_RATIOS.reduce((accumulator, { className }) => { accumulator.push(className); return accumulator; }, ["wp-has-aspect-ratio"]); let outputClassNames = existingClassNames; for (const className of aspectRatioClassNames) outputClassNames = outputClassNames.replace(className, ""); return outputClassNames.trim(); }; /** * Checks if HTML already contains responsive aspect ratio styling. * Some embed providers (like Flickr) include their own responsive wrapper * with padding-bottom or padding-top percentages for aspect ratio. * * @param {string} html The embed HTML to check. * @return {boolean} True if the HTML already has responsive styling. */ function hasInlineResponsivePadding(html) { return /padding-(top|bottom)\s*:\s*[\d.]+%/i.test(html); } /** * Returns class names with any relevant responsive aspect ratio names. * * @param {string} html The preview HTML that possibly contains an iframe with width and height set. * @param {string} existingClassNames Any existing class names. * @param {boolean} allowResponsive If the responsive class names should be added, or removed. * @return {string} Deduped class names. */ function getClassNames(html, existingClassNames, allowResponsive = true) { if (!allowResponsive) return removeAspectRatioClasses(existingClassNames); if (hasInlineResponsivePadding(html)) return removeAspectRatioClasses(existingClassNames); const previewDocument = document.implementation.createHTMLDocument(""); previewDocument.body.innerHTML = html; const iframe = previewDocument.body.querySelector("iframe"); if (iframe && iframe.height && iframe.width) { const aspectRatio = (iframe.width / iframe.height).toFixed(2); for (let ratioIndex = 0; ratioIndex < __constants_js.ASPECT_RATIOS.length; ratioIndex++) { const potentialRatio = __constants_js.ASPECT_RATIOS[ratioIndex]; if (aspectRatio >= potentialRatio.ratio) { if (aspectRatio - potentialRatio.ratio > .1) return removeAspectRatioClasses(existingClassNames); return (0, clsx.default)(removeAspectRatioClasses(existingClassNames), potentialRatio.className, "wp-has-aspect-ratio"); } } } return existingClassNames; } /** * Fallback behaviour for unembeddable URLs. * Creates a paragraph block containing a link to the URL, and calls `onReplace`. * * @param {string} url The URL that could not be embedded. * @param {Function} onReplace Function to call with the created fallback block. */ function fallback(url, onReplace) { onReplace((0, _wordpress_blocks.createBlock)("core/paragraph", { content: (0, _wordpress_element.renderToString)(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", { href: url, children: url })) })); } /*** * Gets block attributes based on the preview and responsive state. * * @param {Object} preview The preview data. * @param {string} title The block's title, e.g. Twitter. * @param {Object} currentClassNames The block's current class names. * @param {boolean} isResponsive Boolean indicating if the block supports responsive content. * @param {boolean} allowResponsive Apply responsive classes to fixed size content. * @return {Object} Attributes and values. */ const getAttributesFromPreview = (0, memize.default)((preview, title, currentClassNames, isResponsive, allowResponsive = true) => { if (!preview) return {}; const attributes = {}; let { type = "rich" } = preview; const { html, provider_name: providerName } = preview; const providerNameSlug = (0, _wordpress_kebab_case.kebabCase)((providerName || title).toLowerCase()); if (isFromWordPress(html)) type = __constants_js.WP_EMBED_TYPE; if (html) { attributes.type = type; attributes.providerNameSlug = providerNameSlug; } if (hasAspectRatioClass(currentClassNames)) return attributes; attributes.className = getClassNames(html, currentClassNames, isResponsive && allowResponsive); return attributes; }); /** * Returns the attributes derived from the preview, merged with the current attributes. * * @param {Object} currentAttributes The current attributes of the block. * @param {Object} preview The preview data. * @param {string} title The block's title, e.g. Twitter. * @param {boolean} isResponsive Boolean indicating if the block supports responsive content. * @return {Object} Merged attributes. */ const getMergedAttributesWithPreview = (currentAttributes, preview, title, isResponsive) => { const { allowResponsive, className } = currentAttributes; return { ...currentAttributes, ...getAttributesFromPreview(preview, title, className, isResponsive, allowResponsive) }; }; exports.createUpgradedEmbedBlock = createUpgradedEmbedBlock; exports.fallback = fallback; exports.findMoreSuitableBlock = findMoreSuitableBlock; exports.getAttributesFromPreview = getAttributesFromPreview; exports.getClassNames = getClassNames; exports.getEmbedInfoByProvider = getEmbedInfoByProvider; exports.getMergedAttributesWithPreview = getMergedAttributesWithPreview; exports.getPhotoHtml = getPhotoHtml; exports.hasAspectRatioClass = hasAspectRatioClass; exports.hasInlineResponsivePadding = hasInlineResponsivePadding; exports.isFromWordPress = isFromWordPress; exports.matchesPatterns = matchesPatterns; exports.removeAspectRatioClasses = removeAspectRatioClasses; exports.rewriteXToTwitter = rewriteXToTwitter; //# sourceMappingURL=util.cjs.map