Skip to content

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.

fix: allow placing labelable elements inside of labels (#5085)

Bogdan Chadkinbb80555bc464
diff --git a/apps/builder/app/shared/content-model.test.tsx b/apps/builder/app/shared/content-model.test.tsx
index 32146fca29..7e1aadfcd0 100644
--- a/apps/builder/app/shared/content-model.test.tsx
+++ b/apps/builder/app/shared/content-model.test.tsx
@@ -353,7 +353,7 @@ test("prevent nesting forms", () => {
).toBeFalsy();
});
-test("edge case: allow wrapping input with label", () => {
+test("allow wrapping labelable controls with label", () => {
expect(
isTreeSatisfyingContentModel({
...renderData(
@@ -363,6 +363,11 @@ test("edge case: allow wrapping input with label", () => {
<$.Input />
</$.Box>
</$.Label>
+ <$.Label>
+ <$.Box tag="span">
+ <$.Button />
+ </$.Box>
+ </$.Label>
</$.Body>
),
metas: defaultMetas,
@@ -375,7 +380,7 @@ test("edge case: allow wrapping input with label", () => {
<$.Body ws:id="bodyId">
<$.Label>
<$.Box tag="span">
- <$.Button />
+ <$.Link />
</$.Box>
</$.Label>
</$.Body>
@@ -384,6 +389,21 @@ test("edge case: allow wrapping input with label", () => {
instanceSelector: ["bodyId"],
})
).toBeFalsy();
+ expect(
+ isTreeSatisfyingContentModel({
+ ...renderData(
+ <$.Body ws:id="bodyId">
+ <$.Label>
+ <$.Button>
+ <$.Input />
+ </$.Button>
+ </$.Label>
+ </$.Body>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["bodyId"],
+ })
+ ).toBeFalsy();
});
test("edge case: allow inserting div where phrasing is required", () => {
diff --git a/apps/builder/app/shared/content-model.ts b/apps/builder/app/shared/content-model.ts
index 37d92c8284..b519449ac5 100644
--- a/apps/builder/app/shared/content-model.ts
+++ b/apps/builder/app/shared/content-model.ts
@@ -26,8 +26,19 @@ const getTagByInstanceId = (props: Props) => {
return tagByInstanceId;
};
-const getMetaTag = (meta: undefined | WsComponentMeta) => {
- return Object.keys(meta?.presetStyle ?? {}).at(0);
+const getTag = ({
+ instance,
+ metas,
+ props,
+}: {
+ instance: Instance;
+ metas: Map<Instance["component"], WsComponentMeta>;
+ props: Props;
+}) => {
+ const tagByInstanceId = getTagByInstanceId(props);
+ const meta = metas.get(instance.component);
+ const metaTag = Object.keys(meta?.presetStyle ?? {}).at(0);
+ return tagByInstanceId.get(instance.id) ?? metaTag;
};
const isIntersected = (arrayA: string[], arrayB: string[]) => {
@@ -68,18 +79,17 @@ const isTagSatisfyingContentModel = ({
if (allowedCategories.includes("phrasing") && tag === "div") {
return true;
}
- // instance does not match parent constraints
- if (isIntersected(allowedCategories, categoriesByTag[tag]) === false) {
- return false;
+ // interactive exception, label > input or label > button are considered
+ // valid way to nest interactive elements
+ if (
+ allowedCategories.includes("labelable") &&
+ categoriesByTag[tag].includes("labelable")
+ ) {
+ return true;
}
// prevent nesting interactive elements
// like button > button or a > input
if (allowedCategories.includes("non-interactive") && isTagInteractive(tag)) {
- // interactive exception, label > input is not recommended but a popular case
- // to automatically focus input when click on label text without using id
- if (allowedCategories.includes("label-content") && tag === "input") {
- return true;
- }
return false;
}
// prevent nesting form elements
@@ -87,7 +97,8 @@ const isTagSatisfyingContentModel = ({
if (allowedCategories.includes("non-form") && tag === "form") {
return false;
}
- return true;
+ // instance matches parent constraints
+ return isIntersected(allowedCategories, categoriesByTag[tag]);
};
/**
@@ -112,10 +123,15 @@ const getTagChildrenCategories = (
) {
childrenCategories = [...childrenCategories, "non-interactive"];
}
- // interactive exception, label > input is not recommended but a popular case
- // to automatically focus input when click on label text without using id
- if (tag === "label" || allowedCategories?.includes("label-content")) {
- childrenCategories = [...childrenCategories, "label-content"];
+ // interactive exception, label > input or label > button are considered
+ // valid way to nest interactive elements
+ // pass through labelable to match controls with labelable category
+ if (tag === "label" || allowedCategories?.includes("labelable")) {
+ // stop passing through labelable to control children
+ // to prevent label > button > input
+ if (tag && categoriesByTag[tag].includes("labelable") === false) {
+ childrenCategories = [...childrenCategories, "labelable"];
+ }
}
// introduce custom non-form category to restrict nesting form elements
// like form > div > form
@@ -150,9 +166,7 @@ const computeAllowedCategories = ({
if (instance === undefined) {
continue;
}
- const tagByInstanceId = getTagByInstanceId(props);
- const meta = metas.get(instance.component);
- const tag = tagByInstanceId.get(instance.id) ?? getMetaTag(meta);
+ const tag = getTag({ instance, metas, props });
allowedCategories = getTagChildrenCategories(tag, allowedCategories);
}
return allowedCategories;
@@ -198,12 +212,14 @@ export const isTreeSatisfyingContentModel = ({
props,
metas,
instanceSelector,
+ onError,
_allowedCategories: allowedCategories,
}: {
instances: Instances;
props: Props;
metas: Map<Instance["component"], WsComponentMeta>;
instanceSelector: InstanceSelector;
+ onError?: (message: string) => void;
_allowedCategories?: string[];
}): boolean => {
// compute constraints only when not passed from parent
@@ -213,19 +229,31 @@ export const isTreeSatisfyingContentModel = ({
props,
metas,
});
- const [instanceId] = instanceSelector;
+ const [instanceId, parentInstanceId] = instanceSelector;
const instance = instances.get(instanceId);
// collection item can be undefined
if (instance === undefined) {
return true;
}
- const tagByInstanceId = getTagByInstanceId(props);
- const meta = metas.get(instance.component);
- const tag = tagByInstanceId.get(instance.id) ?? getMetaTag(meta);
+ const tag = getTag({ instance, metas, props });
let isSatisfying = isTagSatisfyingContentModel({
tag,
allowedCategories,
});
+ if (isSatisfying === false && allowedCategories) {
+ const parentInstance = instances.get(parentInstanceId);
+ let parentTag: undefined | string;
+ if (parentInstance) {
+ parentTag = getTag({ instance: parentInstance, metas, props });
+ }
+ if (parentTag) {
+ onError?.(
+ `Placing <${tag}> element inside a <${parentTag}> violates HTML spec.`
+ );
+ } else {
+ onError?.(`Placing <${tag}> element here violates HTML spec.`);
+ }
+ }
const childrenCategories: string[] = getTagChildrenCategories(
tag,
allowedCategories
@@ -237,6 +265,7 @@ export const isTreeSatisfyingContentModel = ({
props,
metas,
instanceSelector: [child.value, ...instanceSelector],
+ onError,
_allowedCategories: childrenCategories,
});
}
diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsx
index 1fe0229ef1..1c80e03fd0 100644
--- a/apps/builder/app/shared/instance-utils.test.tsx
+++ b/apps/builder/app/shared/instance-utils.test.tsx
@@ -1503,22 +1503,17 @@ describe("find closest insertable", () => {
});
});
- test("forbid inserting list item in body", () => {
+ test("allow inserting list item in body even though validation fails", () => {
const { instances } = renderData(<$.Body ws:id="bodyId"></$.Body>);
$instances.set(instances);
selectInstance(["bodyId"]);
- const newListItemFragment = createFragment({
- children: [{ type: "id", value: "newListItemId" }],
- instances: [
- {
- type: "instance",
- id: "newListItemId",
- component: "ListItem",
- children: [],
- },
- ],
+ const newListItemFragment = renderTemplate(
+ <$.ListItem ws:id="newListItemId"></$.ListItem>
+ );
+ expect(findClosestInsertable(newListItemFragment)).toEqual({
+ parentSelector: ["bodyId"],
+ position: "end",
});
- expect(findClosestInsertable(newListItemFragment)).toEqual(undefined);
});
});
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index aeb8080da9..9fa93c56de 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -1319,11 +1319,13 @@ export const findClosestInsertable = (
fragment.instances[0].component
);
const label = humanizeString(componentName);
- toast.error(message || `Cannot insert "${label}"`);
+ toast.warn(message || `"${label}" has no place here`);
},
});
if (insertableIndex === -1) {
- return;
+ // fallback to closest container to always insert something
+ // even when validation fails
+ insertableIndex = 0;
}
// adjust with container lookup
diff --git a/apps/builder/app/shared/matcher.ts b/apps/builder/app/shared/matcher.ts
index de96316c1d..c1935afdbb 100644
--- a/apps/builder/app/shared/matcher.ts
+++ b/apps/builder/app/shared/matcher.ts
@@ -362,6 +362,11 @@ export const findClosestInstanceMatchingFragment = ({
props: mergedProps,
metas,
instanceSelector: childInstanceSelector,
+ onError: (message) => {
+ if (firstError === "") {
+ firstError = message;
+ }
+ },
});
}
}