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.

refactor: drop legacy matchers (#5146)

Bogdan Chadkine622e08df686
diff --git a/apps/builder/app/builder/features/ai/apply-operations.ts b/apps/builder/app/builder/features/ai/apply-operations.ts
index 51f097e0e4..7230694891 100644
--- a/apps/builder/app/builder/features/ai/apply-operations.ts
+++ b/apps/builder/app/builder/features/ai/apply-operations.ts
@@ -1,5 +1,10 @@
import { nanoid } from "nanoid";
-import { getStyleDeclKey, Instance, type StyleSource } from "@webstudio-is/sdk";
+import {
+ getStyleDeclKey,
+ Instance,
+ isComponentDetachable,
+ type StyleSource,
+} from "@webstudio-is/sdk";
import { generateDataFromEmbedTemplate } from "@webstudio-is/react-sdk";
import type { copywriter, operations } from "@webstudio-is/ai";
import { serverSyncStore } from "~/shared/sync";
@@ -23,7 +28,6 @@ import {
} from "~/shared/nano-states";
import type { InstanceSelector } from "~/shared/tree-utils";
import { $selectedInstance, getInstancePath } from "~/shared/awareness";
-import { isInstanceDetachable } from "~/shared/matcher";
import { isRichTextTree } from "~/shared/content-model";
export const applyOperations = (operations: operations.WsOperations) => {
@@ -91,15 +95,10 @@ const deleteInstanceByOp = (
if (instanceSelector.length === 1) {
return;
}
- const metas = $registeredComponentMetas.get();
updateWebstudioData((data) => {
- if (
- isInstanceDetachable({
- metas,
- instances: data.instances,
- instanceSelector,
- }) === false
- ) {
+ const [instanceId] = instanceSelector;
+ const instance = data.instances.get(instanceId);
+ if (instance && !isComponentDetachable(instance.component)) {
return;
}
deleteInstanceMutable(
diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsx
index 062363b041..0dd8d960e6 100644
--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx
+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx
@@ -66,7 +66,6 @@ import {
getInstanceKey,
selectInstance,
} from "~/shared/awareness";
-import { isTreeMatching } from "~/shared/matcher";
import {
findClosestContainer,
isRichTextContent,
@@ -562,12 +561,7 @@ const canDrop = (
}
// make sure dragging tree can be put inside of drop instance
const containerInstanceSelector = [dragSelector[0], ...dropSelector];
- let matches = isTreeMatching({
- instances,
- metas,
- instanceSelector: containerInstanceSelector,
- });
- matches &&= isTreeSatisfyingContentModel({
+ const matches = isTreeSatisfyingContentModel({
instances,
metas,
props,
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index bc32942d65..ccf3b04896 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -1,5 +1,8 @@
import { nanoid } from "nanoid";
-import { blockTemplateComponent } from "@webstudio-is/sdk";
+import {
+ blockTemplateComponent,
+ isComponentDetachable,
+} from "@webstudio-is/sdk";
import type { Instance } from "@webstudio-is/sdk";
import { toast } from "@webstudio-is/design-system";
import { createCommandsEmitter, type Command } from "~/shared/commands-emitter";
@@ -36,7 +39,6 @@ import {
import { $selectedInstancePath, selectInstance } from "~/shared/awareness";
import { openCommandPanel } from "../features/command-panel";
import { builderApi } from "~/shared/builder-api";
-import { isInstanceDetachable, isTreeMatching } from "~/shared/matcher";
import { getSetting, setSetting } from "./client-settings";
import { findAvailableVariables } from "~/shared/data-variables";
import { atom } from "nanostores";
@@ -77,14 +79,7 @@ export const deleteSelectedInstance = () => {
const [selectedItem, parentItem] = instancePath;
const selectedInstanceSelector = selectedItem.instanceSelector;
const instances = $instances.get();
- const metas = $registeredComponentMetas.get();
- if (
- isInstanceDetachable({
- metas,
- instances,
- instanceSelector: selectedInstanceSelector,
- }) === false
- ) {
+ if (!isComponentDetachable(selectedItem.instance.component)) {
toast.error(
"This instance can not be moved outside of its parent component."
);
@@ -110,12 +105,12 @@ export const deleteSelectedInstance = () => {
blockTemplateComponent;
if (isTemplateInstance) {
- builderApi.toast.info("You can't delete this instance in conent mode.");
+ builderApi.toast.info("You can't delete this instance in content mode.");
return;
}
if (!isChildOfBlock) {
- builderApi.toast.info("You can't delete this instance in conent mode.");
+ builderApi.toast.info("You can't delete this instance in content mode.");
return;
}
}
@@ -180,12 +175,7 @@ export const wrapIn = (component: string) => {
}
}
}
- let matches = isTreeMatching({
- metas,
- instances: data.instances,
- instanceSelector: newInstanceSelector,
- });
- matches &&= isTreeSatisfyingContentModel({
+ const matches = isTreeSatisfyingContentModel({
instances: data.instances,
props: data.props,
metas,
@@ -231,12 +221,7 @@ export const unwrap = () => {
);
parentInstance.children.splice(index, 1, ...selectedInstance.children);
}
- let matches = isTreeMatching({
- metas: $registeredComponentMetas.get(),
- instances: data.instances,
- instanceSelector: parentItem.instanceSelector,
- });
- matches &&= isTreeSatisfyingContentModel({
+ const matches = isTreeSatisfyingContentModel({
instances: data.instances,
props: data.props,
metas: $registeredComponentMetas.get(),
diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.ts
index ffdb6e6fdb..aa7a1ff1d2 100644
--- a/apps/builder/app/canvas/shared/use-drag-drop.ts
+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts
@@ -29,10 +29,7 @@ import {
type InstanceSelector,
areInstanceSelectorsEqual,
} from "~/shared/tree-utils";
-import {
- findClosestInstanceMatchingFragment,
- isTreeMatching,
-} from "~/shared/matcher";
+import { findClosestInstanceMatchingFragment } from "~/shared/matcher";
import {
findClosestContainer,
findClosestRichText,
@@ -98,12 +95,7 @@ const findClosestDroppableInstanceSelector = (
dragPayload.dragInstanceSelector[0],
...instanceSelector,
];
- let matches = isTreeMatching({
- instances,
- metas,
- instanceSelector: dropInstanceSelector,
- });
- matches &&= isTreeSatisfyingContentModel({
+ const matches = isTreeSatisfyingContentModel({
instances,
props,
metas,
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 049809226f..38126bc754 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -6,13 +6,10 @@ import {
Instances,
WebstudioFragment,
findTreeInstanceIdsExcludingSlotDescendants,
+ isComponentDetachable,
portalComponent,
} from "@webstudio-is/sdk";
-import {
- $selectedInstanceSelector,
- $instances,
- $registeredComponentMetas,
-} from "../nano-states";
+import { $selectedInstanceSelector, $instances } from "../nano-states";
import type { InstanceSelector } from "../tree-utils";
import {
deleteInstanceMutable,
@@ -24,7 +21,6 @@ import {
findClosestInsertable,
type Insertable,
} from "../instance-utils";
-import { isInstanceDetachable } from "../matcher";
import { $selectedInstancePath } from "../awareness";
import { findAvailableVariables } from "../data-variables";
@@ -38,8 +34,9 @@ type InstanceData = z.infer<typeof InstanceData>;
const getTreeData = (instanceSelector: InstanceSelector) => {
const instances = $instances.get();
- const metas = $registeredComponentMetas.get();
- if (isInstanceDetachable({ metas, instances, instanceSelector }) === false) {
+ const [targetInstanceId] = instanceSelector;
+ const instance = instances.get(targetInstanceId);
+ if (instance && !isComponentDetachable(instance.component)) {
toast.error(
"This instance can not be moved outside of its parent component."
);
@@ -51,8 +48,6 @@ const getTreeData = (instanceSelector: InstanceSelector) => {
return;
}
- const [targetInstanceId] = instanceSelector;
-
return {
instanceSelector,
...extractWebstudioFragment(getWebstudioData(), targetInstanceId),
diff --git a/apps/builder/app/shared/matcher.test.tsx b/apps/builder/app/shared/matcher.test.tsx
index ef17481f4e..9447e35bcf 100644
--- a/apps/builder/app/shared/matcher.test.tsx
+++ b/apps/builder/app/shared/matcher.test.tsx
@@ -1,831 +1,10 @@
import { describe, expect, test, vi } from "vitest";
-import {
- $,
- renderTemplate,
- renderData,
- createProxy,
-} from "@webstudio-is/template";
+import { $, renderTemplate, renderData } from "@webstudio-is/template";
import { coreMetas } from "@webstudio-is/sdk";
import * as baseMetas from "@webstudio-is/sdk-components-react/metas";
-import * as radixMetas from "@webstudio-is/sdk-components-react-radix/metas";
-import type { Matcher, WsComponentMeta } from "@webstudio-is/sdk";
-import {
- findClosestInstanceMatchingFragment,
- isTreeMatching,
- isInstanceDetachable,
- __testing__,
-} from "./matcher";
-
-const { isInstanceMatching } = __testing__;
+import { findClosestInstanceMatchingFragment } from "./matcher";
const metas = new Map(Object.entries({ ...coreMetas, ...baseMetas }));
-metas.set("ListItem", {
- ...baseMetas.ListItem,
- constraints: {
- relation: "parent",
- component: { $eq: "List" },
- },
-});
-
-metas.set("NoTextItem", {
- ...baseMetas.Box,
- constraints: {
- relation: "child",
- text: false,
- },
-});
-
-// Solutions added as a quick workaround
-describe("Fast workaround tests", () => {
- // For simplicity, we don’t check the relation=child and text=false constraints during tree validation.
- // These are only used to prevent text editing of container components.
- test("Child text=false constraints does not affect matching", () => {
- expect(
- isTreeMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.NoTextItem ws:id="notextitem">AnyText</$.NoTextItem>
- </$.Body>
- ),
- metas,
- instanceSelector: ["notextitem", "body"],
- })
- ).toBeTruthy();
- });
-});
-
-describe("is instance matching", () => {
- test("matches self with self matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: {
- relation: "self",
- component: { $eq: "ListItem" },
- },
- })
- ).toBeTruthy();
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: {
- relation: "self",
- component: { $in: ["ListItem", "ListBox"] },
- },
- })
- ).toBeTruthy();
- });
-
- test("matches self with negated self matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: {
- relation: "self",
- component: { $neq: "Box" },
- },
- })
- ).toBeTruthy();
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: {
- relation: "self",
- component: { $nin: ["Box", "List"] },
- },
- })
- ).toBeTruthy();
- });
-
- test("matches parent with parent matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: {
- relation: "parent",
- component: { $eq: "List" },
- },
- })
- ).toBeTruthy();
- });
-
- test("not matches ancestor with parent matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.Box ws:id="box">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Box>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "box", "list", "body"],
- query: {
- relation: "parent",
- component: { $eq: "List" },
- },
- })
- ).toBeFalsy();
- });
-
- test("not matches another parent with parent matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Body>
- ),
- instanceSelector: ["listitem", "body"],
- query: {
- relation: "parent",
- component: { $eq: "List" },
- },
- })
- ).toBeFalsy();
- });
-
- test("matches parent with negated parent matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Body>
- ),
- instanceSelector: ["listitem", "body"],
- query: {
- relation: "parent",
- component: { $neq: "List" },
- },
- })
- ).toBeTruthy();
- });
-
- test("not matches parent with negated parent matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: {
- relation: "parent",
- component: { $neq: "List" },
- },
- })
- ).toBeFalsy();
- });
-
- test("matches parent with ancestor matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: {
- relation: "ancestor",
- component: { $eq: "List" },
- },
- })
- ).toBeTruthy();
- });
-
- test("matches parent with ancestor matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.Box ws:id="box">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Box>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "box", "list", "body"],
- query: {
- relation: "ancestor",
- component: { $eq: "List" },
- },
- })
- ).toBeTruthy();
- });
-
- test("not matches another ancestor with ancestor matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Box>
- </$.Body>
- ),
- instanceSelector: ["listitem", "box", "body"],
- query: {
- relation: "ancestor",
- component: { $eq: "List" },
- },
- })
- ).toBeFalsy();
- });
-
- test("matches ancestor with negated ancestor matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Box>
- </$.Body>
- ),
- instanceSelector: ["listitem", "box", "body"],
- query: {
- relation: "ancestor",
- component: { $neq: "List" },
- },
- })
- ).toBeTruthy();
- });
-
- test("not matches ancestor with negated ancestor matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: {
- relation: "ancestor",
- component: { $neq: "List" },
- },
- })
- ).toBeFalsy();
- });
-
- test("combines self, parent and ancestor matchers", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- instanceSelector: ["listitem", "list", "body"],
- query: [
- {
- relation: "self",
- component: { $eq: "ListItem" },
- },
- {
- relation: "parent",
- component: { $eq: "List" },
- },
- {
- relation: "ancestor",
- component: { $eq: "Body" },
- },
- ],
- })
- ).toBeTruthy();
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Box>
- </$.Body>
- ),
- instanceSelector: ["listitem", "box", "body"],
- query: [
- {
- relation: "self",
- component: { $eq: "ListItem" },
- },
- {
- relation: "parent",
- component: { $eq: "List" },
- },
- {
- relation: "ancestor",
- component: { $eq: "Body" },
- },
- ],
- })
- ).toBeFalsy();
- });
-
- test("negated ancestor matcher should not interfere with self relation", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list"></$.List>
- </$.Body>
- ),
- instanceSelector: ["list", "body"],
- query: {
- relation: "ancestor",
- component: { $neq: "List" },
- },
- })
- ).toBeTruthy();
- });
-
- test("combines multiple ancestor matchers", () => {
- const query: Matcher[] = [
- {
- relation: "ancestor",
- component: { $eq: "Body" },
- },
- {
- relation: "ancestor",
- component: { $in: ["Box"] },
- },
- ];
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box">
- <$.List ws:id="list"></$.List>
- </$.Box>
- </$.Body>
- ),
- instanceSelector: ["list", "box", "body"],
- query,
- })
- ).toBeTruthy();
- expect(
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list"></$.List>
- </$.Body>
- ),
- instanceSelector: ["list", "body"],
- query,
- })
- ).toBeFalsy();
- });
-
- test("matches a child with child matcher", () => {
- expect(
- isInstanceMatching({
- ...renderData(
- <$.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({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list"></$.List>
- </$.Body>
- ),
- instanceSelector: ["list", "body"],
- query: {
- relation: "child",
- component: { $neq: "ListItem" },
- },
- })
- ).toBeTruthy();
- expect(
- isInstanceMatching({
- ...renderData(
- <$.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({
- ...renderData(
- <$.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({
- ...renderData(
- <$.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({
- ...renderData(
- <$.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({
- ...renderData(
- <$.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({
- ...renderData(
- <$.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({
- ...renderData(
- <$.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({
- ...renderData(
- <$.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();
- });
-
- test("provide error message when negated matcher is failed", () => {
- const onError = vi.fn();
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box"></$.Box>
- </$.Body>
- ),
- instanceSelector: ["box", "body"],
- query: {
- relation: "self",
- component: { $nin: ["Box", "Text"] },
- },
- onError,
- });
- expect(onError).toHaveBeenLastCalledWith("Box or Text is not acceptable");
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Box>
- </$.Body>
- ),
- instanceSelector: ["listitem", "box", "body"],
- query: {
- relation: "ancestor",
- component: { $nin: ["Box", "Text"] },
- },
- onError,
- });
- expect(onError).toHaveBeenLastCalledWith("Box or Text is not acceptable");
- });
-
- test("provide error message when positive matcher is failed", () => {
- const onError = vi.fn();
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Body>
- ),
- instanceSelector: ["box", "body"],
- query: {
- relation: "self",
- component: { $in: ["Box", "Text"] },
- },
- onError,
- });
- expect(onError).toHaveBeenLastCalledWith("Box or Text is missing");
- isInstanceMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Body>
- ),
- instanceSelector: ["box", "body"],
- query: {
- relation: "ancestor",
- component: { $in: ["Box", "Text"] },
- },
- onError,
- });
- expect(onError).toHaveBeenLastCalledWith("Box or Text is missing");
- });
-});
-
-describe("is tree matching", () => {
- const metas = new Map<string, WsComponentMeta>([
- [
- "ListItem",
- {
- icon: "",
- constraints: {
- relation: "parent",
- component: { $eq: "List" },
- },
- },
- ],
- [
- "Tabs",
- {
- icon: "",
- constraints: {
- relation: "descendant",
- component: { $eq: "TabsTrigger" },
- },
- },
- ],
- ]);
-
- test("match selected instance", () => {
- expect(
- isTreeMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- metas,
- instanceSelector: ["listitem", "list", "body"],
- })
- ).toBeTruthy();
- expect(
- isTreeMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.Body>
- ),
- metas,
- instanceSelector: ["listitem", "body"],
- })
- ).toBeFalsy();
- });
-
- test("match all descendants", () => {
- expect(
- isTreeMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.List ws:id="list">
- <$.ListItem ws:id="listitem"></$.ListItem>
- </$.List>
- </$.Body>
- ),
- metas,
- instanceSelector: ["list", "body"],
- })
- ).toBeTruthy();
- expect(
- isTreeMatching({
- ...renderData(
- <$.Body ws:id="body">
- <$.ListItem ws:id="listitem"></$.ListItem>
- <$.Box ws:id="box"></$.Box>
- </$.Body>
- ),
- metas,
- instanceSelector: ["body"],
- })
- ).toBeFalsy();
- });
-
- test("match ancestors", () => {
- expect(
- isTreeMatching({
- ...renderData(
- <$.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({
- ...renderData(
- <$.Body ws:id="body">
- <$.Tabs ws:id="tabs">
- <$.Box ws:id="box"></$.Box>
- </$.Tabs>
- </$.Body>
- ),
- metas,
- instanceSelector: ["box", "tabs", "body"],
- })
- ).toBeFalsy();
- });
-});
-
-describe("is instance detachable", () => {
- const metas = new Map(Object.entries(baseMetas));
- const radix = createProxy("@webstudio-is/sdk-components-react-radix:");
- for (const [component, meta] of Object.entries(radixMetas)) {
- metas.set(`@webstudio-is/sdk-components-react-radix:${component}`, meta);
- }
-
- test("allow deleting one of matching instances", () => {
- expect(
- isInstanceDetachable({
- ...renderData(
- <$.Body ws:id="body">
- <radix.Tabs ws:id="tabs">
- <radix.TabsList ws:id="list">
- <radix.TabsTrigger ws:id="trigger1"></radix.TabsTrigger>
- <radix.TabsTrigger ws:id="trigger2"></radix.TabsTrigger>
- </radix.TabsList>
- <radix.TabsContent ws:id="content1"></radix.TabsContent>
- <radix.TabsContent ws:id="content2"></radix.TabsContent>
- </radix.Tabs>
- </$.Body>
- ),
- metas,
- instanceSelector: ["trigger1", "list", "tabs", "body"],
- })
- ).toBeTruthy();
- });
-
- test("allow deleting when siblings not matching", () => {
- expect(
- isInstanceDetachable({
- ...renderData(
- <$.Body ws:id="body">
- <radix.Tabs ws:id="tabs"></radix.Tabs>
- <$.Box ws:id="box"></$.Box>
- </$.Body>
- ),
- metas,
- instanceSelector: ["box", "body"],
- })
- ).toBeTruthy();
- });
-});
describe("find closest instance matching fragment", () => {
test("finds closest list with list item fragment", () => {
@@ -920,6 +99,8 @@ describe("find closest instance matching fragment", () => {
fragment,
onError,
});
- expect(onError).toHaveBeenLastCalledWith("List is missing");
+ expect(onError).toHaveBeenLastCalledWith(
+ "Placing <li> element inside a <body> violates HTML spec."
+ );
});
});
diff --git a/apps/builder/app/shared/matcher.ts b/apps/builder/app/shared/matcher.ts
index 22319d544a..a918b5bc30 100644
--- a/apps/builder/app/shared/matcher.ts
+++ b/apps/builder/app/shared/matcher.ts
@@ -1,309 +1,12 @@
-import {
- parseComponentName,
+import type {
Props,
- type Instance,
- type Instances,
- type Matcher,
- type MatcherOperation,
- type MatcherRelation,
- type WebstudioFragment,
- type WsComponentMeta,
+ Instances,
+ WebstudioFragment,
+ WsComponentMeta,
} from "@webstudio-is/sdk";
import type { InstanceSelector } from "./tree-utils";
import { isTreeSatisfyingContentModel } from "./content-model";
-const isNegated = (operation?: MatcherOperation) => {
- return operation?.$neq !== undefined || operation?.$nin !== undefined;
-};
-
-const isMatching = (
- value: undefined | string,
- operation: undefined | MatcherOperation
-) => {
- if (operation?.$eq) {
- return operation.$eq === value;
- }
- if (operation?.$neq) {
- return operation.$neq === value;
- }
- if (operation?.$in && value) {
- return operation.$in.includes(value);
- }
- if (operation?.$nin && value) {
- return operation.$nin.includes(value);
- }
- return false;
-};
-
-const isDepthMatchingRelation = (depth: number, relation: MatcherRelation) => {
- return (
- (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)
- );
-};
-
-const formatList = (operation: MatcherOperation) => {
- const listFormat = new Intl.ListFormat("en", {
- type: "disjunction",
- });
- const list: string[] = [];
- if (operation.$eq) {
- list.push(operation.$eq);
- }
- if (operation.$in) {
- list.push(...operation.$in);
- }
- if (operation.$neq) {
- list.push(operation.$neq);
- }
- if (operation.$nin) {
- list.push(...operation.$nin);
- }
- return listFormat.format(
- list.map((component) => {
- const [_namespace, name] = parseComponentName(component);
- return name;
- })
- );
-};
-
-/**
- * @todo following features are missing
- * - tag matcher
- */
-const isInstanceMatching = ({
- instances,
- instanceSelector,
- query,
- onError,
-}: {
- instances: Instances;
- instanceSelector: InstanceSelector;
- query: undefined | Matcher | Matcher[];
- onError?: (message: string) => void;
-}): boolean => {
- query = filterConstraints(query);
-
- // fast path to the lack of constraints
- if (query === undefined) {
- return true;
- }
-
- 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;
- if (matcher.component) {
- onError?.(`${formatList(matcher.component)} is not acceptable`);
- }
- 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) {
- if (isDepthMatchingRelation(index, matcher.relation) && instance) {
- matchInstance(instance, matcher);
- }
- }
- index += 1;
- }
- 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;
- }
- for (const matcher of queries) {
- const matches = matchesByMatcher.get(matcher) ?? false;
- if (matches === false) {
- if (matcher.component) {
- onError?.(`${formatList(matcher.component)} is missing`);
- }
- return false;
- }
- }
- return true;
-};
-
-/**
- * Added as a quick workaround!!!
- *
- * Some constraints don’t make much sense to check in this module, like relation=child and text=false.
- * They’re only used to prevent text editing of container instances.
- */
-const filterConstraints = (
- constraints: Matcher | Matcher[] | undefined
-): undefined | Matcher[] => {
- if (constraints === undefined) {
- return undefined;
- }
-
- const result = (
- Array.isArray(constraints) ? constraints : [constraints]
- ).filter(
- (constraint) => constraint.relation !== "child" || constraint.text !== false
- );
- if (result.length === 0) {
- return undefined;
- }
- return result;
-};
-
-export const isTreeMatching = ({
- instances,
- metas,
- instanceSelector,
- onError,
- level = 0,
-}: {
- instances: Instances;
- metas: Map<string, WsComponentMeta>;
- instanceSelector: InstanceSelector;
- onError?: (message: string) => void;
- level?: number;
-}): boolean => {
- const [instanceId] = instanceSelector;
- const instance = instances.get(instanceId);
- // collection item can be undefined
- if (instance === undefined) {
- return true;
- }
- const meta = metas.get(instance.component);
- // check self
- let matches = isInstanceMatching({
- instances,
- instanceSelector,
- query: filterConstraints(meta?.constraints),
- onError,
- });
- // 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: filterConstraints(meta?.constraints),
- onError,
- });
- if (matches === false) {
- return false;
- }
- }
- }
- if (matches === false) {
- return false;
- }
- for (const child of instance.children) {
- if (child.type === "id") {
- matches = isTreeMatching({
- instances,
- metas,
- instanceSelector: [child.value, ...instanceSelector],
- level: level + 1,
- onError,
- });
- if (matches === false) {
- return false;
- }
- }
- }
- return matches;
-};
-
-export const isInstanceDetachable = ({
- instances,
- metas,
- instanceSelector,
-}: {
- instances: Instances;
- metas: Map<string, WsComponentMeta>;
- instanceSelector: 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);
- }
- // skip self
- for (let index = 1; index < instanceSelector.length; index += 1) {
- const instance = newInstances.get(instanceSelector[index]);
- if (instance === undefined) {
- continue;
- }
- const meta = metas.get(instance.component);
- const matches = isInstanceMatching({
- instances: newInstances,
- instanceSelector: instanceSelector.slice(index),
- query: filterConstraints(meta?.constraints),
- });
- if (matches === false) {
- return false;
- }
- }
- return true;
-};
-
export const findClosestInstanceMatchingFragment = ({
instances,
props,
@@ -347,16 +50,6 @@ export const findClosestInstanceMatchingFragment = ({
child.value,
...instanceSelector.slice(index),
];
- matches &&= isTreeMatching({
- instances: mergedInstances,
- metas,
- instanceSelector: childInstanceSelector,
- onError: (message) => {
- if (firstError === "") {
- firstError = message;
- }
- },
- });
matches &&= isTreeSatisfyingContentModel({
instances: mergedInstances,
props: mergedProps,
@@ -377,7 +70,3 @@ export const findClosestInstanceMatchingFragment = ({
onError?.(firstError);
return -1;
};
-
-export const __testing__ = {
- isInstanceMatching,
-};
diff --git a/packages/sdk/src/core-metas.ts b/packages/sdk/src/core-metas.ts
index 07f2fa7d10..2acba9318f 100644
--- a/packages/sdk/src/core-metas.ts
+++ b/packages/sdk/src/core-metas.ts
@@ -11,6 +11,7 @@ import type {
WsComponentMeta,
WsComponentPropsMeta,
} from "./schema/component-meta";
+import type { Instance } from "./schema/instances";
export const rootComponent = "ws:root";
@@ -152,10 +153,15 @@ export const corePropsMetas = {
// components with custom implementation
// should not be imported as react component
-export const isCoreComponent = (component: string) =>
+export const isCoreComponent = (component: Instance["component"]) =>
component === rootComponent ||
component === elementComponent ||
component === collectionComponent ||
component === descendantComponent ||
component === blockComponent ||
component === blockTemplateComponent;
+
+export const isComponentDetachable = (component: Instance["component"]) =>
+ component !== rootComponent &&
+ component !== blockTemplateComponent &&
+ component !== descendantComponent;
diff --git a/packages/sdk/src/schema/component-meta.ts b/packages/sdk/src/schema/component-meta.ts
index 285e89e207..8a334bedc3 100644
--- a/packages/sdk/src/schema/component-meta.ts
+++ b/packages/sdk/src/schema/component-meta.ts
@@ -3,7 +3,6 @@ import type { HtmlTags } from "html-tags";
import type { Simplify } from "type-fest";
import { StyleValue, type CssProperty } from "@webstudio-is/css-engine";
import { PropMeta } from "./prop-meta";
-import { Matchers } from "./instances";
export const PresetStyleDecl = z.object({
// State selector, e.g. :hover
@@ -98,7 +97,6 @@ export const WsComponentMeta = z.object({
* also signals to not insert components inside unless dropped explicitly
*/
placeholder: z.string().optional(),
- constraints: Matchers.optional(),
contentModel: ContentModel.optional(),
// when this field is specified component receives
// prop with index of same components withiin specified ancestor
diff --git a/packages/sdk/src/schema/instances.ts b/packages/sdk/src/schema/instances.ts
index adc69f457d..7e8db4a486 100644
--- a/packages/sdk/src/schema/instances.ts
+++ b/packages/sdk/src/schema/instances.ts
@@ -38,43 +38,3 @@ export type Instance = z.infer<typeof Instance>;
export const Instances = z.map(InstanceId, Instance);
export type Instances = z.infer<typeof Instances>;
-
-export const MatcherRelation = z.union([
- z.literal("ancestor"),
- z.literal("parent"),
- z.literal("self"),
- z.literal("child"),
- z.literal("descendant"),
-]);
-
-export type MatcherRelation = z.infer<typeof MatcherRelation>;
-
-export const MatcherOperation = z.object({
- $eq: z.string().optional(),
- $neq: z.string().optional(),
- $in: z.array(z.string()).optional(),
- $nin: z.array(z.string()).optional(),
-});
-
-export type MatcherOperation = z.infer<typeof MatcherOperation>;
-
-export const Matcher = z.object({
- relation: MatcherRelation,
- component: MatcherOperation.optional(),
- tag: MatcherOperation.optional(),
- text: z
- .literal(false)
- .describe(
- `
- To disallow text editing on a container instance,
- use: { relation: 'child', text: false }
- `
- )
- .optional(),
-});
-
-export type Matcher = z.infer<typeof Matcher>;
-
-export const Matchers = z.union([Matcher, z.array(Matcher)]);
-
-export type Matchers = z.infer<typeof Matchers>;