Skip to content

Commit d06c670

Browse files
committed
Handle spaces edge cases
1 parent d22b20b commit d06c670

2 files changed

Lines changed: 29 additions & 4 deletions

File tree

apps/builder/app/shared/html.test.tsx

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,9 +199,25 @@ test("collapse any spacing characters inside text", () => {
199199
another line
200200
</div>
201201
`)
202+
).toEqual(
203+
renderTemplate(<ws.element ws:tag="div">{"line another line"}</ws.element>)
204+
);
205+
});
206+
207+
test("collapse any spacing characters inside rich text", () => {
208+
expect(
209+
generateFragmentFromHtml(`
210+
<div>
211+
<span> line </span>
212+
<b> another line </b>
213+
</div>
214+
`)
202215
).toEqual(
203216
renderTemplate(
204-
<ws.element ws:tag="div">{" line another line "}</ws.element>
217+
<ws.element ws:tag="div">
218+
<ws.element ws:tag="span">line</ws.element>{" "}
219+
<ws.element ws:tag="b">another line</ws.element>
220+
</ws.element>
205221
)
206222
);
207223
});

apps/builder/app/shared/html.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -231,21 +231,26 @@ export const generateFragmentFromHtml = (
231231
}
232232
}
233233
}
234-
for (const childNode of node.childNodes) {
234+
for (let index = 0; index < node.childNodes.length; index += 1) {
235+
const childNode = node.childNodes[index];
235236
if (defaultTreeAdapter.isElementNode(childNode)) {
236237
const child = convertElementToInstance(childNode);
237238
if (child) {
238239
instance.children.push(child);
239240
}
240241
}
241242
if (defaultTreeAdapter.isTextNode(childNode)) {
243+
// trim spaces around rich text
242244
if (spaceRegex.test(childNode.value)) {
243-
continue;
245+
if (index === 0 || index === node.childNodes.length - 1) {
246+
continue;
247+
}
244248
}
249+
const childValue = childNode.value.replaceAll(/\s+/g, " ");
245250
let child: Instance["children"][number] = {
246251
type: "text",
247252
// collapse spacing characters inside of text to avoid preserved newlines
248-
value: childNode.value.replaceAll(/\s+/g, " "),
253+
value: childValue === " " ? childValue : childValue.trim(),
249254
};
250255
// textarea content is initial value
251256
// and represented with fake value attribute
@@ -271,6 +276,10 @@ export const generateFragmentFromHtml = (
271276
// <article></article>
272277
// </div>
273278
if (hasNonRichTextContent) {
279+
// remove spaces between elements outside of rich text
280+
if (spaceRegex.test(childNode.value)) {
281+
continue;
282+
}
274283
const span: Instance = {
275284
type: "instance",
276285
id: getNewId(),

0 commit comments

Comments
 (0)