Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion apps/builder/app/shared/html.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from "vitest";
import { css, renderTemplate, ws } from "@webstudio-is/template";
import { $, css, renderTemplate, ws } from "@webstudio-is/template";
import { generateFragmentFromHtml } from "./html";

test("generate instances from html", () => {
Expand Down Expand Up @@ -222,3 +222,25 @@ test("generate style attribute as local styles", () => {
)
);
});

test("paste svg as html embed", () => {
expect(
generateFragmentFromHtml(`
<div>
<svg viewBox="0 0 20 20">
<rect x="5" y="5" width="10" height="10" />
</svg>
</div>
`)
).toEqual(
renderTemplate(
<ws.element ws:tag="div">
<$.HtmlEmbed
code={`<svg viewBox="0 0 20 20">
<rect x="5" y="5" width="10" height="10" />
</svg>`}
/>
</ws.element>
)
);
});
37 changes: 36 additions & 1 deletion apps/builder/app/shared/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,38 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {
};

const convertElementToInstance = (node: ElementNode) => {
if (node.tagName === "svg" && node.sourceCodeLocation) {
const { startCol, startOffset, endOffset } = node.sourceCodeLocation;
const indent = startCol - 1;
const htmlFragment = html
.slice(startOffset, endOffset)
// try to preserve indentation
.split("\n")
.map((line, index) => {
if (index > 0 && /^\s+$/.test(line.slice(0, indent))) {
return line.slice(indent);
}
return line;
})
.join("\n");
const instance: Instance = {
type: "instance",
id: getNewId(),
component: "HtmlEmbed",
children: [],
};
instances.set(instance.id, instance);
const name = "code";
const codeProp: Prop = {
id: `${instance.id}:${name}`,
instanceId: instance.id,
name,
type: "string",
value: htmlFragment,
};
props.push(codeProp);
return { type: "id" as const, value: instance.id };
}
if (!tags.includes(node.tagName)) {
return;
}
Expand Down Expand Up @@ -196,7 +228,10 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {
return { type: "id" as const, value: instance.id };
};

const documentFragment = parseFragment(html, { scriptingEnabled: false });
const documentFragment = parseFragment(html, {
scriptingEnabled: false,
sourceCodeLocationInfo: true,
});
const children: Instance["children"] = [];
for (const childNode of documentFragment.childNodes) {
if (defaultTreeAdapter.isElementNode(childNode)) {
Expand Down