Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: keep the execution order of scripts when executing HTML Embed on the client (#3046)
Oleg Isonend9eb1e2941bd
diff --git a/packages/react-sdk/src/context.tsx b/packages/react-sdk/src/context.tsxindex cc6e47bd72..31f880560c 100644--- a/packages/react-sdk/src/context.tsx+++ b/packages/react-sdk/src/context.tsx@@ -2,6 +2,11 @@ import { createContext, useContext } from "react";import type { ImageLoader } from "@webstudio-is/image";export type Params = {+ /**+ * When rendering a published version, there is no renderer defined.+ * - canvas is the builder canvas in dev mode+ * - preview is the preview mode in builder+ */renderer?: "canvas" | "preview";/*** Base url ir base path for images with ending slash.diff --git a/packages/sdk-components-react/src/html-embed.tsx b/packages/sdk-components-react/src/html-embed.tsxindex f1760e2b96..b62ef05a20 100644--- a/packages/sdk-components-react/src/html-embed.tsx+++ b/packages/sdk-components-react/src/html-embed.tsx@@ -8,21 +8,83 @@ import {import { mergeRefs } from "@react-aria/utils";import { ReactSdkContext } from "@webstudio-is/react-sdk";-type Props = {- code: string;- executeScriptOnCanvas?: boolean;- clientOnly?: boolean;+const insertScript = (+ sourceScript: HTMLScriptElement+): Promise<HTMLScriptElement> => {+ return new Promise((resolve, reject) => {+ const script = document.createElement("script");+ const hasSrc = sourceScript.hasAttribute("src");++ // Copy all attributes from the source script to the new script, because we are going to replace the source script with the new one+ // and the user might rely on some attributes.+ for (const { name, value } of sourceScript.attributes) {+ script.setAttribute(name, value);+ }++ if (hasSrc) {+ script.onload = () => {+ resolve(script);+ };+ script.onerror = reject;+ script.src = sourceScript.src;+ } else {+ script.textContent = sourceScript.innerText;+ }++ sourceScript.replaceWith(script);++ // Run the callback immediately for inline scripts.+ if (hasSrc === false) {+ resolve(script);+ }+ });+};++type ScriptTask = () => Promise<HTMLScriptElement>;++// Inspiration https://ghinda.net/article/script-tags+const execute = async (container: HTMLElement) => {+ const scripts = container.querySelectorAll("script");+ const syncTasks: Array<ScriptTask> = [];+ const asyncTasks: Array<ScriptTask> = [];++ scripts.forEach((script) => {+ const type = script.getAttribute("type");+ if (type == null || type === "" || type === "text/javascript") {+ const tasks = script.hasAttribute("async") ? asyncTasks : syncTasks;+ tasks.push(() => {+ return insertScript(script);+ });+ }+ });++ // Insert the script tags in parallel.+ Promise.all(asyncTasks.map((task) => task()));++ // Insert the script tags sequentially to preserve execution order.+ for (const task of syncTasks) {+ await task();+ }};type ChildProps = {innerRef: ForwardedRef<HTMLDivElement>;// code can be actually undefined when prop is not providedcode?: string;+ shouldExecute?: boolean;+};++const Placeholder = (props: ChildProps) => {+ const { code, innerRef, ...rest } = props;+ return (+ <div ref={innerRef} {...rest} style={{ padding: "20px" }}>+ {'Open the "Settings" panel to insert HTML code'}+ </div>+ );};/**- * Scripts are executed when rendered client side.- * Necessary on canvas which does not have server rendering.+ * Executes scripts when rendered in the builder manually, because innerHTML doesn't execute scripts.*/const ExecutableHtml = (props: ChildProps) => {const { code, innerRef, ...rest } = props;@@ -30,31 +92,23 @@ const ExecutableHtml = (props: ChildProps) => {useEffect(() => {const container = containerRef.current;- if (container === null || code === undefined) {- return;- }- // the trick to execute inserted scripts- // https://ghinda.net/article/script-tags- const range = document.createRange();- range.setStart(container, 0);- const fragment = range.createContextualFragment(code);- while (container.firstChild) {- container.removeChild(container.firstChild);+ if (container) {+ execute(container);}- container.append(fragment);- }, [code]);+ }, []);return (<div{...rest}ref={mergeRefs(innerRef, containerRef)}style={{ display: "contents" }}+ dangerouslySetInnerHTML={{ __html: code ?? "" }}/>);};/**- * Scripts are executed when rendered server side+ * Scripts are executed when rendered server side without any manual intervention.*/const InnerHtml = (props: ChildProps) => {const { code, innerRef, ...rest } = props;@@ -64,41 +118,67 @@ const InnerHtml = (props: ChildProps) => {{...rest}ref={innerRef}style={{ display: "contents" }}- dangerouslySetInnerHTML={{ __html: props.code ?? "" }}+ dangerouslySetInnerHTML={{ __html: code ?? "" }}/>);};-const Placeholder = (props: ChildProps) => {- const { code, innerRef, ...rest } = props;- return (- <div ref={innerRef} {...rest} style={{ padding: "20px" }}>- {'Open the "Settings" panel to insert HTML code'}- </div>- );-};--export const HtmlEmbed = forwardRef<HTMLDivElement, Props>((props, ref) => {- const { renderer } = useContext(ReactSdkContext);- const { code, executeScriptOnCanvas, clientOnly, ...rest } = props;+const shouldExecute = ({+ renderer,+ executeScriptOnCanvas = false,+ clientOnly = false,+}: {+ renderer?: "canvas" | "preview";+ executeScriptOnCanvas?: boolean;+ clientOnly?: boolean;+}) => {+ // We are rendering in published mode.+ if (renderer === undefined) {+ return clientOnly;+ }- // code can be actually undefined when prop is not provided- //- // cast code to string in case non-string value is computed- // from expression- if (code === undefined || String(code).trim().length === 0) {- return <Placeholder innerRef={ref} {...rest} />;+ // On canvas in preview we always execute the scripts, because in doesn't have SSR.+ if (renderer === "preview") {+ return true;}- if (- (renderer === "canvas" && executeScriptOnCanvas === true) ||- renderer === "preview" ||- clientOnly- ) {- return <ExecutableHtml innerRef={ref} code={code} {...rest} />;+ // On builder canvas we have a special setting to allow execution. This is useful if the execution doesn't hurt the build process.+ if (renderer === "canvas") {+ return executeScriptOnCanvas;}- return <InnerHtml innerRef={ref} code={code} {...rest} />;-});+ return false;+};++type HtmlEmbedProps = {+ code: string;+ executeScriptOnCanvas?: boolean;+ clientOnly?: boolean;+};++export const HtmlEmbed = forwardRef<HTMLDivElement, HtmlEmbedProps>(+ (props, ref) => {+ const { renderer } = useContext(ReactSdkContext);+ const { code, executeScriptOnCanvas, clientOnly, ...rest } = props;++ // - code can be actually undefined when prop is not provided+ // - cast code to string in case non-string value is computed from expression+ if (code === undefined || String(code).trim().length === 0) {+ return <Placeholder innerRef={ref} {...rest} />;+ }++ const execute = shouldExecute({+ renderer,+ executeScriptOnCanvas,+ clientOnly,+ });++ if (execute) {+ return <ExecutableHtml innerRef={ref} code={code} {...rest} />;+ }++ return <InnerHtml innerRef={ref} code={code} {...rest} />;+ }+);HtmlEmbed.displayName = "HtmlEmbed";diff --git a/packages/sdk-components-react/src/html-embed.ws.ts b/packages/sdk-components-react/src/html-embed.ws.tsindex 20d520b6cc..3738afd622 100644--- a/packages/sdk-components-react/src/html-embed.ws.ts+++ b/packages/sdk-components-react/src/html-embed.ws.ts@@ -18,9 +18,16 @@ export const meta: WsComponentMeta = {export const propsMeta: WsComponentPropsMeta = {props: {...props,+ clientOnly: {+ ...props.clientOnly,+ description:+ "Activate it for any scripts that can mutate the DOM or introduce interactivity. This only affects the published site.",+ },executeScriptOnCanvas: {...props.executeScriptOnCanvas,- label: "Run script on canvas",+ label: "Run scripts on canvas",+ description:+ "Allow script execution on canvas without switching to preview mode. This only affects build mode.",},code: {required: true,