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
import { elementsByTag } from "@webstudio-is/html-data";
import {
blockTemplateComponent,
elementComponent,
getHtmlTagFromInstance,
getHtmlTagsFromProps,
parseComponentName,
type ContentModel,
type Instance,
type Instances,
type Props,
type WsComponentMeta,
} from "@webstudio-is/sdk";
import { setIsSubsetOf } from "./set-utils";
import type { InstanceSelector } from "./instance-path";
type Metas = Map<Instance["component"], WsComponentMeta>;
type HtmlTagsByInstanceId = Map<Instance["id"], string>;
const getTag = ({
instance,
metas,
props,
htmlTagsByInstanceId,
}: {
instance: Instance;
metas: Metas;
props: Props;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
return getHtmlTagFromInstance({
instance,
metas,
props,
htmlTagsByInstanceId: htmlTagsByInstanceId ?? getHtmlTagsFromProps(props),
});
};
const isIntersected = (arrayA: string[], arrayB: string[]) => {
return arrayA.some((item) => arrayB.includes(item));
};
const getElementContentModel = (tag: undefined | string) => {
if (tag === undefined) {
return;
}
return elementsByTag[tag] as (typeof elementsByTag)[string] | undefined;
};
/**
* checks if tag has interactive category
* though img is an exception and historically its interactivity ignored
* so img can be put into links and buttons
*/
const isTagInteractive = (tag: string) => {
return (
tag !== "img" &&
getElementContentModel(tag)?.categories.includes("interactive") === true
);
};
const isTagSatisfyingContentModel = ({
tag,
component,
allowedCategories,
}: {
tag: undefined | string;
component: Instance["component"];
allowedCategories: undefined | string[];
}) => {
// slot or collection does not have tag and should pass through allowed categories
if (tag === undefined) {
return true;
}
// body does not have parent
if (allowedCategories === undefined) {
return true;
}
// for example ul has "li" as children category
if (allowedCategories.includes(tag)) {
return true;
}
// very big hack to support putting div into buttons or headings
// users put "Embed HTML" all over the place to embed icons
// radix templates do it as well
if (allowedCategories.includes("phrasing") && tag === "div") {
return true;
}
const elementContentModel = getElementContentModel(tag);
// Preserve legacy components whose rendered tags are missing from HTML data.
// Explicit tags on the generic Element must still be known and valid.
if (elementContentModel === undefined) {
return component !== elementComponent;
}
// interactive exception, label > input or label > button are considered
// valid way to nest interactive elements
if (
allowedCategories.includes("labelable") &&
elementContentModel.categories.includes("labelable")
) {
return true;
}
// prevent nesting interactive elements
// like button > button or a > input
if (allowedCategories.includes("non-interactive") && isTagInteractive(tag)) {
return false;
}
// prevent nesting form elements
// like form > div > form
if (allowedCategories.includes("non-form") && tag === "form") {
return false;
}
// instance matches parent constraints
return isIntersected(allowedCategories, elementContentModel.categories);
};
/**
* compute possible categories for tag children
*/
const getElementChildren = (
tag: undefined | string,
allowedCategories: undefined | string[],
parentTag: undefined | string
) => {
// A transparent component without a known parent imposes no constraint.
if (tag === undefined && allowedCategories === undefined) {
return;
}
// components without tag behave like transparent category
// and pass through parent constraints
let elementChildren = getElementContentModel(tag)?.children ?? [
"transparent",
];
if (elementChildren.includes("transparent")) {
// Transparent elements inherit their parent's content model. Without a
// known parent, HTML allows any flow content.
const inheritedCategories = allowedCategories ?? ["flow"];
elementChildren = elementChildren.flatMap((category) =>
category === "transparent" ? inheritedCategories : category
);
}
// A div directly under dl contains name-value groups instead of flow content.
if (tag === "div" && parentTag === "dl") {
elementChildren = ["dt", "dd", "script-supporting elements"];
}
// introduce custom non-interactive category to restrict nesting interactive elements
// like button > button or a > input
if (
tag &&
(isTagInteractive(tag) || allowedCategories?.includes("non-interactive"))
) {
elementChildren = [...elementChildren, "non-interactive"];
}
// 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 &&
getElementContentModel(tag)?.categories.includes("labelable") === false
) {
elementChildren = [...elementChildren, "labelable"];
}
}
// introduce custom non-form category to restrict nesting form elements
// like form > div > form
if (tag === "form" || allowedCategories?.includes("non-form")) {
elementChildren = [...elementChildren, "non-form"];
}
return elementChildren;
};
/**
* compute allowed categories from all ancestors
* considering inherited (transparent) categories
* and other ancestor specific behaviors
*/
const computeAllowedCategories = ({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId,
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
let instance: undefined | Instance;
let allowedCategories: undefined | string[];
let parentTag: undefined | string;
// skip selected instance for which these constraints are computed
for (const instanceId of instanceSelector.slice(1).reverse()) {
instance = instances.get(instanceId);
// collection item can be undefined
if (instance === undefined) {
continue;
}
// Template roots are reusable definitions, not children of the page HTML.
if (instance.component === blockTemplateComponent) {
allowedCategories = undefined;
parentTag = undefined;
continue;
}
const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });
allowedCategories = getElementChildren(tag, allowedCategories, parentTag);
// Tagless components do not change the rendered HTML parent.
parentTag = tag ?? parentTag;
}
return { allowedCategories, parentTag };
};
const findHtmlConstraintInstance = ({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId,
tag,
component,
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
tag: undefined | string;
component: Instance["component"];
}) => {
let allowedCategories: undefined | string[];
let parentTag: undefined | string;
let wasSatisfying = true;
let constraintInstance: undefined | Instance;
for (const instanceId of instanceSelector.slice(1).reverse()) {
const ancestor = instances.get(instanceId);
if (ancestor === undefined) {
continue;
}
if (ancestor.component === blockTemplateComponent) {
allowedCategories = undefined;
parentTag = undefined;
constraintInstance = undefined;
wasSatisfying = true;
continue;
}
const ancestorTag = getTag({
instance: ancestor,
metas,
props,
htmlTagsByInstanceId,
});
allowedCategories = getElementChildren(
ancestorTag,
allowedCategories,
parentTag
);
parentTag = ancestorTag ?? parentTag;
const isSatisfying = isTagSatisfyingContentModel({
tag,
component,
allowedCategories,
});
if (wasSatisfying && isSatisfying === false) {
constraintInstance = ancestor;
}
wasSatisfying = isSatisfying;
}
return constraintInstance;
};
const defaultComponentContentModel: ContentModel = {
category: "instance",
children: ["rich-text", "instance"],
};
const getComponentContentModel = (meta: undefined | WsComponentMeta) =>
meta?.contentModel ?? defaultComponentContentModel;
const isTextContentCapableInstance = ({
instance,
props,
metas,
htmlTagsByInstanceId,
}: {
instance: Instance;
props: Props;
metas: Metas;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });
const elementContentModel = getElementContentModel(tag);
const componentChildren = getComponentContentModel(
metas.get(instance.component)
).children;
return (
(elementContentModel === undefined ||
elementContentModel.children.length > 0) &&
(componentChildren.includes("rich-text") ||
componentChildren.includes("text"))
);
};
export const canHaveTextContent = ({
instanceId,
instances,
props,
metas,
htmlTagsByInstanceId,
}: {
instanceId: Instance["id"];
instances: Instances;
props: Props;
metas: Metas;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
const instance = instances.get(instanceId);
if (instance === undefined) {
return false;
}
return isTextContentCapableInstance({
instance,
props,
metas,
htmlTagsByInstanceId,
});
};
const isComponentSatisfyingContentModel = ({
metas,
component,
allowedParentCategories,
allowedAncestorCategories,
}: {
metas: Metas;
component: string;
allowedParentCategories: undefined | string[];
allowedAncestorCategories: undefined | string[];
}) => {
const contentModel = getComponentContentModel(metas.get(component));
return (
// body does not have parent
allowedParentCategories === undefined ||
// parents may restrict specific components with none category
// any instances
// or nothing
allowedParentCategories.includes(component) ||
allowedParentCategories.includes(contentModel.category) ||
allowedAncestorCategories?.includes(component) === true ||
allowedAncestorCategories?.includes(contentModel.category) === true
);
};
const computeAllowedAncestorCategories = ({
instances,
metas,
instanceSelector,
}: {
instances: Instances;
metas: Metas;
instanceSelector: InstanceSelector;
}) => {
let allowedCategories: undefined | string[];
// skip selected instance for which these constraints are computed
for (const instanceId of instanceSelector.slice(1).reverse()) {
const instance = instances.get(instanceId);
// collection item can be undefined
if (instance === undefined) {
continue;
}
const contentModel = getComponentContentModel(
metas.get(instance.component)
);
if (contentModel.descendants) {
allowedCategories ??= [];
allowedCategories = [...allowedCategories, ...contentModel.descendants];
}
}
return allowedCategories;
};
const getAllowedParentCategories = ({
instances,
metas,
instanceSelector,
}: {
instances: Instances;
metas: Metas;
instanceSelector: InstanceSelector;
}) => {
const instanceId = instanceSelector[1];
const instance = instances.get(instanceId);
if (instance === undefined) {
return;
}
const contentModel = getComponentContentModel(metas.get(instance.component));
return contentModel.children;
};
/**
* Check all tags starting with specified instance select
* for example
*
* Most rules are described by categoriesByTag and childrenCategoriesByTag
* from html-data package. Basically all elements enforce children categories
* and all elements has own categories. We check intersections to match them.
*
* See https://html.spec.whatwg.org/multipage/indices.html#elements-3
*
* div > span = true
* where div is flow category
* and requires flow or phrasing category in children
* span is flow and phrasing category
* and requires phrasing in children
*
* span > div = false
* because span requires phrasing category in children
*
* p > div = false
* because paragraph also requires phrasing category in children
*
* Interactive categories and form elements are exception
* because button requires phrasing children
* and does not prevent nesting interactive elements by content model
* They pass through negative categories
*
* [categories] [children]
* interactive non-interactive
*
* exampeles
* button > input = false
* form > div > form = false
*
*/
export const isTreeSatisfyingContentModel = ({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId = getHtmlTagsFromProps(props),
onError,
_allowedCategories: allowedCategories,
_parentTag: parentTag,
_allowedAncestorCategories: allowedAncestorCategories,
_allowedParentCategories: allowedParentCategories,
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
onError?: (message: string, instanceSelector: InstanceSelector) => void;
_allowedCategories?: string[];
_parentTag?: string;
_allowedAncestorCategories?: string[];
_allowedParentCategories?: string[];
}): boolean => {
// compute constraints only when not passed from parent
if (allowedCategories === undefined) {
({ allowedCategories, parentTag } = computeAllowedCategories({
instanceSelector,
instances,
props,
metas,
htmlTagsByInstanceId,
}));
}
allowedParentCategories ??= getAllowedParentCategories({
instanceSelector,
instances,
metas,
});
allowedAncestorCategories ??= computeAllowedAncestorCategories({
instanceSelector,
instances,
metas,
});
const [instanceId, parentInstanceId] = instanceSelector;
const instance = instances.get(instanceId);
// collection item can be undefined
if (instance === undefined) {
return true;
}
const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });
const isTagSatisfying = isTagSatisfyingContentModel({
tag,
component: instance.component,
allowedCategories,
});
if (isTagSatisfying === false) {
const constraintInstance = findHtmlConstraintInstance({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId,
tag,
component: instance.component,
});
let constraintTag: undefined | string;
if (constraintInstance) {
constraintTag = getTag({
instance: constraintInstance,
metas,
props,
htmlTagsByInstanceId,
});
}
if (constraintTag) {
onError?.(
`Placing <${tag}> element inside a <${constraintTag}> violates HTML spec.`,
instanceSelector
);
} else {
onError?.(
`Placing <${tag}> element here violates HTML spec.`,
instanceSelector
);
}
}
const isComponentSatisfying = isComponentSatisfyingContentModel({
metas,
component: instance.component,
allowedParentCategories,
allowedAncestorCategories,
});
if (isComponentSatisfying === false) {
const [_namespace, name] = parseComponentName(instance.component);
const parentInstance = instances.get(parentInstanceId);
let parentName: undefined | string;
if (parentInstance) {
const [_namespace, name] = parseComponentName(parentInstance.component);
parentName = name;
}
if (parentName) {
onError?.(
`Placing "${name}" element inside a "${parentName}" violates content model.`,
instanceSelector
);
} else {
onError?.(
`Placing "${name}" element here violates content model.`,
instanceSelector
);
}
}
let isSatisfying = isTagSatisfying && isComponentSatisfying;
if (
instance.children.some((child) => child.type !== "id") &&
isTextContentCapableInstance({
instance,
props,
metas,
htmlTagsByInstanceId,
}) === false
) {
const [, name] = parseComponentName(instance.component);
onError?.(
`"${name}" does not accept text content. Insert an element child instead.`,
instanceSelector
);
isSatisfying = false;
}
const contentModel = getComponentContentModel(metas.get(instance.component));
allowedCategories = getElementChildren(tag, allowedCategories, parentTag);
allowedParentCategories = contentModel.children;
if (contentModel.descendants) {
allowedAncestorCategories ??= [];
allowedAncestorCategories = [
...allowedAncestorCategories,
...contentModel.descendants,
];
}
for (const child of instance.children) {
if (child.type === "id") {
isSatisfying &&= isTreeSatisfyingContentModel({
instances,
props,
metas,
htmlTagsByInstanceId,
instanceSelector: [child.value, ...instanceSelector],
onError,
_allowedCategories:
instance.component === blockTemplateComponent
? undefined
: allowedCategories,
_parentTag: tag ?? parentTag,
_allowedParentCategories: allowedParentCategories,
_allowedAncestorCategories: allowedAncestorCategories,
});
}
}
return isSatisfying;
};
export const richTextContentTags = new Set<undefined | string>([
"sup",
"sub",
"b",
"strong",
"i",
"em",
"a",
"span",
]);
export const richTextContentComponents = new Set<undefined | string>([
elementComponent,
"Subscript",
"Bold",
"Italic",
"RichTextLink",
"Span",
]);
/**
* textual placeholder is used when no content specified while in builder
* also signals to not insert components inside unless dropped explicitly
*/
export const richTextPlaceholders: Map<undefined | string, string> = new Map([
["h1", "Heading 1"],
["h2", "Heading 2"],
["h3", "Heading 3"],
["h4", "Heading 4"],
["h5", "Heading 5"],
["h6", "Heading 6"],
["p", "Paragraph"],
["blockquote", "Blockquote"],
["code", "Code Text"],
["li", "List item"],
["a", "Link"],
["span", ""],
]);
const findContentTags = ({
instances,
props,
metas,
instance,
htmlTagsByInstanceId,
_tags: tags = new Set(),
}: {
instances: Instances;
props: Props;
metas: Metas;
instance: Instance;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
_tags?: Set<undefined | string>;
}) => {
for (const child of instance.children) {
if (child.type === "id") {
const childInstance = instances.get(child.value);
// consider collection item as well
if (childInstance === undefined) {
tags.add(undefined);
continue;
}
const tag = getTag({
instance: childInstance,
metas,
props,
htmlTagsByInstanceId,
});
tags.add(tag);
findContentTags({
instances,
props,
metas,
instance: childInstance,
htmlTagsByInstanceId,
_tags: tags,
});
}
}
return tags;
};
const findContentComponents = ({
instances,
instance,
_components: components = new Set(),
}: {
instances: Instances;
instance: Instance;
_components?: Set<undefined | string>;
}) => {
for (const child of instance.children) {
if (child.type === "id") {
const childInstance = instances.get(child.value);
// consider collection item as well
if (childInstance === undefined) {
components.add(undefined);
continue;
}
components.add(childInstance.component);
findContentComponents({
instances,
instance: childInstance,
_components: components,
});
}
}
return components;
};
export const isRichTextTree = ({
instanceId,
instances,
props,
metas,
htmlTagsByInstanceId = getHtmlTagsFromProps(props),
}: {
instanceId: Instance["id"];
instances: Instances;
props: Props;
metas: Metas;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}): boolean => {
const instance = instances.get(instanceId);
// collection item is not rich text
if (instance === undefined) {
return false;
}
const isRichText = isTextContentCapableInstance({
instance,
props,
metas,
htmlTagsByInstanceId,
});
// only empty instance with rich text content can be edited
if (instance.children.length === 0) {
return isRichText;
}
const contentTags = findContentTags({
instances,
props,
metas,
instance,
htmlTagsByInstanceId,
});
const contentComponents = findContentComponents({
instances,
instance,
});
const supportsRichTextContent =
setIsSubsetOf(contentTags, richTextContentTags) &&
setIsSubsetOf(contentComponents, richTextContentComponents);
if (
instance.children.some(
(child) => child.type === "text" || child.type === "expression"
)
) {
return contentTags.has("img") === false;
}
return (
isRichText &&
// rich text must contain only supported elements in editor
supportsRichTextContent &&
// rich text cannot contain only span and only link
// those links and spans are containers in such cases
!setIsSubsetOf(contentTags, new Set(richTextPlaceholders.keys()))
);
};
export const findClosestRichText = ({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId = getHtmlTagsFromProps(props),
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}): undefined | InstanceSelector => {
let foundRichText: undefined | InstanceSelector = undefined;
for (let index = 0; index < instanceSelector.length; index += 1) {
const instanceId = instanceSelector[index];
if (
!isRichTextTree({
instanceId,
instances,
props,
metas,
htmlTagsByInstanceId,
})
) {
break;
}
foundRichText = instanceSelector.slice(index);
}
return foundRichText;
};
export const isRichTextContent = ({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId,
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
const richTextSelector = findClosestRichText({
instanceSelector,
instances,
props,
metas,
htmlTagsByInstanceId,
});
return (
richTextSelector && richTextSelector.join() !== instanceSelector.join()
);
};
export const isRichText = ({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId,
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
const richTextSelector = findClosestRichText({
instanceSelector,
instances,
props,
metas,
htmlTagsByInstanceId,
});
return (
richTextSelector && richTextSelector.join() === instanceSelector.join()
);
};
export const findClosestContainer = ({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId = getHtmlTagsFromProps(props),
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
// page root with text can be used as container
if (instanceSelector.length === 1) {
return instanceSelector;
}
for (let index = 0; index < instanceSelector.length; index += 1) {
const instanceId = instanceSelector[index];
const instance = instances.get(instanceId);
// collection item can be undefined
if (instance === undefined) {
continue;
}
const tag = getTag({ instance, props, metas, htmlTagsByInstanceId });
const meta = metas.get(instance.component);
const elementChildren = getElementContentModel(tag)?.children;
const componentChildren = getComponentContentModel(meta).children;
if (
componentChildren.length === 0 ||
(elementChildren && elementChildren.length === 0)
) {
continue;
}
return instanceSelector.slice(index);
}
return instanceSelector;
};
export const findClosestNonTextualContainer = ({
instances,
props,
metas,
instanceSelector,
htmlTagsByInstanceId = getHtmlTagsFromProps(props),
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
// page root with text can be used as container
if (instanceSelector.length === 1) {
return instanceSelector;
}
for (let index = 0; index < instanceSelector.length; index += 1) {
const instanceId = instanceSelector[index];
const instance = instances.get(instanceId);
// collection item can be undefined
if (instance === undefined) {
continue;
}
const tag = getTag({ instance, props, metas, htmlTagsByInstanceId });
const meta = metas.get(instance.component);
const elementChildren = getElementContentModel(tag)?.children;
const componentChildren = getComponentContentModel(meta).children;
if (
componentChildren.length === 0 ||
(elementChildren && elementChildren.length === 0)
) {
continue;
}
if (
instance.children.length === 0 &&
!richTextPlaceholders.has(tag) &&
!richTextContentTags.has(tag)
) {
return instanceSelector.slice(index);
}
// placeholder exists only inside of empty instances
let hasText = false;
for (const child of instance.children) {
if (child.type === "text" || child.type === "expression") {
hasText = true;
}
}
const contentTags = findContentTags({
instances,
props,
metas,
instance,
htmlTagsByInstanceId,
});
const contentComponents = findContentComponents({
instances,
instance,
});
if (
setIsSubsetOf(contentTags, richTextContentTags) &&
setIsSubsetOf(contentComponents, richTextContentComponents)
) {
hasText = true;
}
if (!hasText) {
return instanceSelector.slice(index);
}
}
return instanceSelector;
};