@wordpress/components
Version:
UI components for WordPress.
326 lines (325 loc) • 11.4 kB
JavaScript
import clsx from "clsx";
import { renderToString, useEffect, useMemo, useRef, useState } from "@wordpress/element";
import { useFocusableIframe, useMergeRefs } from "@wordpress/compose";
import { jsx, jsxs } from "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__ */ jsxs("html", {
lang,
className: type,
children: [/* @__PURE__ */ jsxs("head", { children: [
/* @__PURE__ */ jsx("title", { children: title }),
/* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: style } }),
styles.map((rules, i) => /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: rules } }, i)),
/* @__PURE__ */ jsx("script", {
type: "text/javascript",
dangerouslySetInnerHTML: { __html: `(${observeAndResizeJS.toString()})();` }
})
] }), /* @__PURE__ */ jsxs("body", {
"data-resizable-iframe-connected": "data-resizable-iframe-connected",
className: type,
children: [/* @__PURE__ */ jsx("div", { dangerouslySetInnerHTML: { __html: html } }), scripts.map((src) => /* @__PURE__ */ jsx("script", { src }, src))]
})]
});
return "<!DOCTYPE html>" + 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 = useRef(null);
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
const sandbox = clsx("allow-scripts", "allow-presentation", {
"allow-popups": allowPopups,
"allow-forms": allowForms
});
const srcDoc = useMemo(() => buildSandBoxDocument({
html,
title,
type,
styles,
scripts,
lang: document.documentElement.lang
}), [
html,
title,
type,
styles,
scripts
]);
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__ */ jsx("iframe", {
ref: useMergeRefs([ref, 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 = useRef(null);
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
const sandbox = clsx("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();
}
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);
};
}, []);
useEffect(() => {
trySandBox();
}, [
title,
styles,
scripts
]);
useEffect(() => {
trySandBox(true);
}, [html, type]);
return /* @__PURE__ */ jsx("iframe", {
ref: useMergeRefs([ref, 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__ */ jsx(SameOriginSandBox, { ...contentProps });
return /* @__PURE__ */ jsx(IsolatedSandBox, { ...contentProps });
}
export { VIEWPORT_UNIT_VALUE_REGEX, buildSandBoxDocument, SandBox as default };
//# sourceMappingURL=index.mjs.map