UNPKG

@wordpress/components

Version:
355 lines (354 loc) • 13.3 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 _wordpress_element = require("@wordpress/element"); let _wordpress_compose = require("@wordpress/compose"); let react_jsx_runtime = require("react/jsx-runtime"); // packages/components/src/sandbox/index.tsx /** * Matches CSS viewport-relative length values such as `100vh`, `50.5vw`, * and `.5dvh`. Used to strip viewport units from user-supplied HTML inside * the sandbox iframe, because those units are relative to the iframe's * own size and would create a measurement feedback loop with the * resize observer. * * Exported for tests. NOTE: an identical regex literal is duplicated * inside `observeAndResizeJS` below because that function is serialized * via `.toString()` and embedded into the iframe's `srcdoc` — it has no * access to this module's scope at runtime. If you change one, change * the other; the "is embedded in the sandbox iframe srcdoc" test * guards against drift. */ const VIEWPORT_UNIT_VALUE_REGEX = /^\d*\.?\d+(?:vw|vh|svw|lvw|dvw|svh|lvh|dvh|vi|svi|lvi|dvi|vb|svb|lvb|dvb|vmin|svmin|lvmin|dvmin|vmax|svmax|lvmax|dvmax)$/; const observeAndResizeJS = function() { const { MutationObserver } = window; if (!MutationObserver || !window.parent) return; function sendResize() { if (!document.body) return; const clientBoundingRect = document.body.getBoundingClientRect(); window.parent.postMessage({ action: "resize", width: clientBoundingRect.width, height: clientBoundingRect.height }, "*"); } function connect() { const { body } = document; if (!body) return; new MutationObserver(sendResize).observe(body, { attributes: true, attributeOldValue: false, characterData: true, characterDataOldValue: false, childList: true, subtree: true }); function removeViewportStyles(ruleOrNode) { if (ruleOrNode.style) [ "width", "height", "minHeight", "maxHeight" ].forEach(function(style) { if (/^\d*\.?\d+(?:vw|vh|svw|lvw|dvw|svh|lvh|dvh|vi|svi|lvi|dvi|vb|svb|lvb|dvb|vmin|svmin|lvmin|dvmin|vmax|svmax|lvmax|dvmax)$/.test(ruleOrNode.style[style])) ruleOrNode.style[style] = ""; }); } Array.prototype.forEach.call(document.querySelectorAll("[style]"), removeViewportStyles); Array.prototype.forEach.call(document.styleSheets, function(stylesheet) { let rules; try { rules = stylesheet.cssRules || stylesheet.rules; } catch { return; } Array.prototype.forEach.call(rules, removeViewportStyles); }); body.style.position = "absolute"; body.style.width = "100%"; body.setAttribute("data-resizable-iframe-connected", ""); sendResize(); } window.addEventListener("load", sendResize, true); window.addEventListener("resize", sendResize, true); if (document.body) connect(); else document.addEventListener("DOMContentLoaded", connect); }; const style = ` body { margin: 0; } html, body, body > div { width: 100%; } html.wp-has-aspect-ratio, body.wp-has-aspect-ratio, body.wp-has-aspect-ratio > div, body.wp-has-aspect-ratio > div iframe { width: 100%; height: 100%; overflow: hidden; /* If it has an aspect ratio, it shouldn't scroll. */ } body > div > * { margin-top: 0 !important; /* Has to have !important to override inline styles. */ margin-bottom: 0 !important; } `; /** * Builds the full HTML document string for the sandbox iframe content. Shared * by both the isolated (`srcdoc`) and same-origin (`contentDocument.write`) * sandboxes so the two paths always emit the same markup — notably keeping the * resize script in `<head>`, ahead of the user content, on both. A single * builder means the write path cannot drift back to putting the script in * `<body>` while the `srcdoc` path keeps it in `<head>`. * * `lang` is passed in rather than read here because the two callers source it * from different documents: the isolated sandbox uses the module's `document`, * while the same-origin sandbox uses the iframe's `ownerDocument`. They are * normally the same document, but keeping the argument preserves each path's * exact prior behavior. * * Exported for tests. * * @param props * @param props.html User-supplied HTML for the iframe body. * @param props.title Document title. * @param props.type Optional class name for the `<html>`/`<body>` elements. * @param props.styles CSS rule strings, injected as `<style>` tags in the head. * @param props.scripts External script URLs, injected as `<script src>` in the * body (embeds expect their scripts there). * @param props.lang Language for the `<html lang>` attribute. * @return The full `<!DOCTYPE html>…` document string. */ function buildSandBoxDocument({ html, title, type, styles, scripts, lang }) { const htmlDoc = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("html", { lang, className: type, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("head", { children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("title", { children: title }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { dangerouslySetInnerHTML: { __html: style } }), styles.map((rules, i) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { dangerouslySetInnerHTML: { __html: rules } }, i)), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("script", { type: "text/javascript", dangerouslySetInnerHTML: { __html: `(${observeAndResizeJS.toString()})();` } }) ] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("body", { "data-resizable-iframe-connected": "data-resizable-iframe-connected", className: type, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { dangerouslySetInnerHTML: { __html: html } }), scripts.map((src) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("script", { src }, src))] })] }); return "<!DOCTYPE html>" + (0, _wordpress_element.renderToString)(htmlDoc); } /** * Isolated sandbox that uses the `srcdoc` attribute to render content * without `allow-same-origin`. This is the default for user-controlled * content (e.g., the HTML block) where same-origin access would be a * security risk. * * Because `srcdoc` is a declarative attribute, the browser automatically * re-renders the content when the iframe is moved in the DOM (e.g., * block reordering), so no `load` event listener is needed. * The `message` listener is re-synced on every `load` so * it follows the iframe if it's reparented into a different document. */ function IsolatedSandBox({ html = "", title = "", type, styles = [], scripts = [], onFocus, tabIndex, allowPopups = false, allowForms = false }) { const ref = (0, _wordpress_element.useRef)(null); const [width, setWidth] = (0, _wordpress_element.useState)(0); const [height, setHeight] = (0, _wordpress_element.useState)(0); const sandbox = (0, clsx.default)("allow-scripts", "allow-presentation", { "allow-popups": allowPopups, "allow-forms": allowForms }); const srcDoc = (0, _wordpress_element.useMemo)(() => buildSandBoxDocument({ html, title, type, styles, scripts, lang: document.documentElement.lang }), [ html, title, type, styles, scripts ]); (0, _wordpress_element.useEffect)(() => { const iframe = ref.current; if (!iframe) return; function checkMessageForResize(event) { if (!iframe || iframe.contentWindow !== event.source) return; let data = event.data || {}; if ("string" === typeof data) try { data = JSON.parse(data); } catch {} if ("resize" !== data.action) return; setWidth(data.width); setHeight(data.height); } let currentView = null; function syncListener() { const view = iframe?.ownerDocument?.defaultView ?? null; if (view === currentView) return; currentView?.removeEventListener("message", checkMessageForResize); currentView = view; currentView?.addEventListener("message", checkMessageForResize); } syncListener(); iframe.addEventListener("load", syncListener); return () => { iframe.removeEventListener("load", syncListener); currentView?.removeEventListener("message", checkMessageForResize); }; }, []); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("iframe", { ref: (0, _wordpress_compose.useMergeRefs)([ref, (0, _wordpress_compose.useFocusableIframe)()]), title, tabIndex, className: "components-sandbox", sandbox, srcDoc, onFocus, width: Math.ceil(width), height: Math.ceil(height) }); } /** * Same-origin sandbox that writes to `contentDocument` directly. This * preserves the parent page's URL as the iframe's document URL, which * provides a valid Referer header for nested iframes (required by * providers like YouTube). * * Only used when `allowSameOrigin` is true — i.e., for server-fetched * oEmbed previews that are not directly user-controlled. * * This implementation is intentionally kept close to the original * pre-refactor code to preserve past bugfixes: * - load listener for iframe re-initialization after DOM moves (#21916) * - forceRerender guard to avoid unnecessary full rewrites (#20176) */ function SameOriginSandBox({ html = "", title = "", type, styles = [], scripts = [], onFocus, tabIndex, allowPopups = false, allowForms = false }) { const ref = (0, _wordpress_element.useRef)(null); const [width, setWidth] = (0, _wordpress_element.useState)(0); const [height, setHeight] = (0, _wordpress_element.useState)(0); const sandbox = (0, clsx.default)("allow-scripts", "allow-same-origin", "allow-presentation", { "allow-popups": allowPopups, "allow-forms": allowForms }); function isFrameAccessible() { try { return !!ref.current?.contentDocument?.body; } catch { return false; } } function trySandBox(forceRerender = false) { if (!isFrameAccessible()) return; const { contentDocument, ownerDocument } = ref.current; if (!forceRerender && null !== contentDocument?.body.getAttribute("data-resizable-iframe-connected")) return; contentDocument.open(); try { contentDocument.defaultView?.history.replaceState(null, "", window.location.href); } catch {} contentDocument.write(buildSandBoxDocument({ html, title, type, styles, scripts, lang: ownerDocument.documentElement.lang })); contentDocument.close(); } (0, _wordpress_element.useEffect)(() => { trySandBox(); function tryNoForceSandBox() { trySandBox(false); } function checkMessageForResize(event) { const iframe = ref.current; if (!iframe || iframe.contentWindow !== event.source) return; let data = event.data || {}; if ("string" === typeof data) try { data = JSON.parse(data); } catch {} if ("resize" !== data.action) return; setWidth(data.width); setHeight(data.height); } const iframe = ref.current; const defaultView = iframe?.ownerDocument?.defaultView; iframe?.addEventListener("load", tryNoForceSandBox, false); defaultView?.addEventListener("message", checkMessageForResize); return () => { iframe?.removeEventListener("load", tryNoForceSandBox, false); defaultView?.removeEventListener("message", checkMessageForResize); }; }, []); (0, _wordpress_element.useEffect)(() => { trySandBox(); }, [ title, styles, scripts ]); (0, _wordpress_element.useEffect)(() => { trySandBox(true); }, [html, type]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("iframe", { ref: (0, _wordpress_compose.useMergeRefs)([ref, (0, _wordpress_compose.useFocusableIframe)()]), title, tabIndex, className: "components-sandbox", sandbox, onFocus, width: Math.ceil(width), height: Math.ceil(height) }); } /** * This component provides an isolated environment for arbitrary HTML via iframes. * * ```jsx * import { SandBox } from '@wordpress/components'; * * const MySandBox = () => ( * <SandBox html="<p>Content</p>" title="SandBox" type="embed" /> * ); * ``` */ function SandBox({ allowSameOrigin = false, ...contentProps }) { if (allowSameOrigin) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SameOriginSandBox, { ...contentProps }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IsolatedSandBox, { ...contentProps }); } exports.VIEWPORT_UNIT_VALUE_REGEX = VIEWPORT_UNIT_VALUE_REGEX; exports.buildSandBoxDocument = buildSandBoxDocument; exports.default = SandBox; //# sourceMappingURL=index.cjs.map