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
refactor: add child and descendant matchers (#4520)
Bogdan Chadkince2babe3d0d7
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 1c99aad819..97607d8a89 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -18,7 +18,6 @@ import {findAvailableDataSources,extractWebstudioFragment,insertWebstudioFragmentCopy,- isInstanceDetachable,updateWebstudioData,} from "~/shared/instance-utils";import type { InstanceSelector } from "~/shared/tree-utils";@@ -287,13 +286,6 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({if (instanceSelector === undefined) {return;}- const instances = $instances.get();- if (isInstanceDetachable(instances, instanceSelector) === false) {- builderApi.toast.error(- "This instance can not be moved outside of its parent component."- );- return;- }// @todo tell user they can't copy or cut rootif (instanceSelector.length === 1) {return;diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex e105c6d72d..d9a83b9726 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -66,6 +66,7 @@ import { $awareness, $selectedPage, selectInstance } from "./awareness";import {findClosestContainer,findClosestInstanceMatchingFragment,+ isTreeMatching,} from "./matcher";export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {@@ -281,16 +282,31 @@ export const isInstanceDetachable = (instanceSelector: InstanceSelector) => {const metas = $registeredComponentMetas.get();- const [instanceId] = instanceSelector;+ const [instanceId, parentId] = instanceSelector;+ const newInstances = new Map(instances);+ // replace parent with the one without selected instance+ let parentInstance = newInstances.get(parentId);+ if (parentInstance) {+ parentInstance = {+ ...parentInstance,+ children: parentInstance.children.filter(+ (child) => child.type === "id" && child.value !== instanceId+ ),+ };+ newInstances.set(parentInstance.id, parentInstance);+ }+ // check parent can follow constraints without selected instance+ const matches = isTreeMatching({+ instances: newInstances,+ metas,+ instanceSelector: instanceSelector.slice(1),+ });const instance = instances.get(instanceId);if (instance === undefined) {return false;}const meta = metas.get(instance.component);- if (meta === undefined) {- return true;- }- return meta.detachable ?? true;+ return (meta?.detachable ?? true) && matches;};export const insertInstanceChildrenMutable = (diff --git a/apps/builder/app/shared/matcher.test.tsx b/apps/builder/app/shared/matcher.test.tsxindex b57425306d..7516380292 100644--- a/apps/builder/app/shared/matcher.test.tsx+++ b/apps/builder/app/shared/matcher.test.tsx@@ -382,6 +382,187 @@ describe("is instance matching", () => {})).toBeFalsy();});++ test("matches a child with child matcher", () => {+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list">+ <$.ListItem ws:id="listitem"></$.ListItem>+ </$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "child",+ component: { $eq: "ListItem" },+ },+ })+ ).toBeTruthy();+ });++ test("matches a child with negated child matcher", () => {+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list"></$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "child",+ component: { $neq: "ListItem" },+ },+ })+ ).toBeTruthy();+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list">+ <$.Box ws:id="box"></$.Box>+ </$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "child",+ component: { $neq: "ListItem" },+ },+ })+ ).toBeTruthy();+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list">+ <$.ListItem ws:id="listitem"></$.ListItem>+ </$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "child",+ component: { $neq: "ListItem" },+ },+ })+ ).toBeFalsy();+ });++ test("not matches a parent without a child with child matcher", () => {+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list"></$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "child",+ component: { $eq: "ListItem" },+ },+ })+ ).toBeFalsy();+ });++ test("not matches a parent with different child with child matcher", () => {+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list">+ <$.Box ws:id="box"></$.Box>+ </$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "child",+ component: { $eq: "ListItem" },+ },+ })+ ).toBeFalsy();+ });++ test("matches a child with descendant matcher", () => {+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list">+ <$.ListItem ws:id="listitem"></$.ListItem>+ </$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "descendant",+ component: { $eq: "ListItem" },+ },+ })+ ).toBeTruthy();+ });++ test("matches a descendant with descendant matcher", () => {+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list">+ <$.Box ws:id="box">+ <$.ListItem ws:id="listitem"></$.ListItem>+ </$.Box>+ </$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "descendant",+ component: { $eq: "ListItem" },+ },+ })+ ).toBeTruthy();+ });++ test("matches a descendant with negated descendant matcher", () => {+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list">+ <$.Box ws:id="box"></$.Box>+ </$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "descendant",+ component: { $neq: "ListItem" },+ },+ })+ ).toBeTruthy();+ expect(+ isInstanceMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.List ws:id="list">+ <$.Box ws:id="box">+ <$.ListItem ws:id="listitem"></$.ListItem>+ </$.Box>+ </$.List>+ </$.Body>+ ),+ instanceSelector: ["list", "body"],+ query: {+ relation: "descendant",+ component: { $neq: "ListItem" },+ },+ })+ ).toBeFalsy();+ });});describe("is tree matching", () => {@@ -397,6 +578,17 @@ describe("is tree matching", () => {},},],+ [+ "Tabs",+ {+ type: "container",+ icon: "",+ constraints: {+ relation: "descendant",+ component: { $eq: "TabsTrigger" },+ },+ },+ ],]);test("match selected instance", () => {@@ -453,6 +645,37 @@ describe("is tree matching", () => {})).toBeFalsy();});++ test("match ancestors", () => {+ expect(+ isTreeMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.Tabs ws:id="tabs">+ <$.Box ws:id="box">+ <$.TabsTrigger ws:id="trigger"></$.TabsTrigger>+ </$.Box>+ </$.Tabs>+ </$.Body>+ ),+ metas,+ instanceSelector: ["trigger", "box", "tabs", "body"],+ })+ ).toBeTruthy();+ expect(+ isTreeMatching({+ ...renderJsx(+ <$.Body ws:id="body">+ <$.Tabs ws:id="tabs">+ <$.Box ws:id="box"></$.Box>+ </$.Tabs>+ </$.Body>+ ),+ metas,+ instanceSelector: ["box", "tabs", "body"],+ })+ ).toBeFalsy();+ });});describe("find closest instance matching fragment", () => {diff --git a/apps/builder/app/shared/matcher.ts b/apps/builder/app/shared/matcher.tsindex 8a2260529b..a987d2bb21 100644--- a/apps/builder/app/shared/matcher.ts+++ b/apps/builder/app/shared/matcher.ts@@ -1,4 +1,5 @@import type {+ Instance,Instances,Matcher,MatcherOperation,@@ -31,18 +32,24 @@ const isMatching = (return false;};-const isRelationMatching = (index: number, relation: MatcherRelation) => {+const isDepthMatchingRelation = (depth: number, relation: MatcherRelation) => {return (- (relation === "self" && index === 0) ||- (relation === "parent" && index === 1) ||- (relation === "ancestor" && index >= 1)+ (relation === "self" && depth === 0) ||+ (relation === "parent" && depth === 1) ||+ (relation === "ancestor" && depth >= 1)+ );+};++const isLevelMatchingRelation = (level: number, relation: MatcherRelation) => {+ return (+ (relation === "self" && level === 0) ||+ (relation === "child" && level === 1) ||+ (relation === "descendant" && level >= 1));};/*** @todo following features are missing- * - child matcher- * - descendant matcher* - tag matcher*/export const isInstanceMatching = ({@@ -60,39 +67,76 @@ export const isInstanceMatching = ({}const queries = Array.isArray(query) ? query : [query];const matchesByMatcher = new Map<Matcher, boolean>();+ let aborted = false;+ const matchInstance = (instance: Instance, matcher: Matcher) => {+ let matches = isMatching(instance.component, matcher.component);+ if (isNegated(matcher.component)) {+ if (matches) {+ aborted = true;+ return;+ }+ // inverse negated match+ matches = true;+ }+ matchesByMatcher.set(+ matcher,+ (matchesByMatcher.get(matcher) ?? false) || matches+ );+ };let index = 0;for (const instanceId of instanceSelector) {const instance = instances.get(instanceId);for (const matcher of queries) {- const { relation, component } = matcher;- if (isRelationMatching(index, relation)) {- let matches = isMatching(instance?.component, component);- if (isNegated(component)) {- if (matches) {- return false;- }- // inverse negated match- matches = true;- }- matchesByMatcher.set(- matcher,- (matchesByMatcher.get(matcher) ?? false) || matches- );+ if (isDepthMatchingRelation(index, matcher.relation) && instance) {+ matchInstance(instance, matcher);}}index += 1;}- return Array.from(matchesByMatcher.values()).every((matched) => matched);+ const populateDescendants = (+ instanceId: Instance["id"],+ matcher: Matcher,+ level: number+ ) => {+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ return;+ }+ // ignore self matchers which already handled above+ if (level > 0 && isLevelMatchingRelation(level, matcher.relation)) {+ matchInstance(instance, matcher);+ }+ for (const child of instance.children) {+ if (child.type === "id") {+ populateDescendants(child.value, matcher, level + 1);+ }+ }+ };+ for (const matcher of queries) {+ // setup default in case no children found+ matchesByMatcher.set(+ matcher,+ // negated operations matches by default+ matchesByMatcher.get(matcher) ?? isNegated(matcher.component)+ );+ populateDescendants(instanceSelector[0], matcher, 0);+ }+ if (aborted) {+ return false;+ }+ return queries.every((matcher) => matchesByMatcher.get(matcher));};export const isTreeMatching = ({instances,metas,instanceSelector,+ level = 0,}: {instances: Instances;metas: Map<string, WsComponentMeta>;instanceSelector: InstanceSelector;+ level?: number;}): boolean => {const [instanceId] = instanceSelector;const instance = instances.get(instanceId);@@ -101,11 +145,31 @@ export const isTreeMatching = ({return true;}const meta = metas.get(instance.component);+ // check selflet matches = isInstanceMatching({instances,instanceSelector,query: meta?.constraints,});+ // check ancestors only on the first run+ if (level === 0) {+ // skip self+ for (let index = 1; index < instanceSelector.length; index += 1) {+ const instance = instances.get(instanceSelector[index]);+ if (instance === undefined) {+ continue;+ }+ const meta = metas.get(instance.component);+ const matches = isInstanceMatching({+ instances,+ instanceSelector: instanceSelector.slice(index),+ query: meta?.constraints,+ });+ if (matches === false) {+ return false;+ }+ }+ }if (matches === false) {return false;}@@ -115,6 +179,7 @@ export const isTreeMatching = ({instances,metas,instanceSelector: [child.value, ...instanceSelector],+ level: level + 1,});if (matches === false) {return false;diff --git a/packages/sdk-components-react-radix/src/tabs.ws.ts b/packages/sdk-components-react-radix/src/tabs.ws.tsindex 2317bc5a31..79ec3ed26f 100644--- a/packages/sdk-components-react-radix/src/tabs.ws.ts+++ b/packages/sdk-components-react-radix/src/tabs.ws.ts@@ -72,6 +72,20 @@ export const metaTabs: WsComponentMeta = {order: 2,type: "container",icon: TabsIcon,+ constraints: [+ {+ relation: "descendant",+ component: { $eq: "TabsTrigger" },+ },+ {+ relation: "descendant",+ component: { $eq: "TabsList" },+ },+ {+ relation: "descendant",+ component: { $eq: "TabsContent" },+ },+ ],presetStyle,description:"A set of panels with content that are displayed one at a time. Duplicate both a tab trigger and tab content to add more tabs. Triggers and content are connected according to their order in the Navigator.",@@ -143,7 +157,6 @@ export const metaTabs: WsComponentMeta = {export const metaTabsList: WsComponentMeta = {category: "hidden",- detachable: false,type: "container",icon: HeaderIcon,requiredAncestors: ["Tabs"],