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
fix: Allow removal of invalid audited selectors (#6074)
Oleg Isonen41c8283a7010
diff --git a/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts b/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.tsindex 46417e6085..53f829cdb0 100644--- a/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts@@ -3,6 +3,7 @@ import { describe, expect, test } from "vitest";import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";import {$selectedBreakpointId,+ $selectedStyleState,$selectedStyleSources,} from "~/shared/nano-states";import { createDefaultPages } from "@webstudio-is/project-build";@@ -50,6 +51,7 @@ const setupBaseStores = () => {selectInstance(["body"]);$breakpoints.set(new Map([["base", { id: "base", label: "Base" }]]));$selectedBreakpointId.set("base");+ $selectedStyleState.set(undefined);$styles.set(new Map());};@@ -75,6 +77,15 @@ const setupSelection = (styleSource: {$selectedStyleSources.set(new Map([["body", styleSource.id]]));};+const invalidState = "::-webkit-search-cancel-button";+const createInvalidStyleDecl = (styleSourceId: string): StyleDecl => ({+ breakpointId: "base",+ styleSourceId,+ property: "color",+ state: invalidState,+ value: { type: "keyword", value: "red" },+});+describe("use-style-data", () => {test("does not write styles for locked tokens", () => {setupSelection({@@ -131,6 +142,35 @@ describe("use-style-data", () => {]);});+ test("deletes an existing token declaration with an invalid state", () => {+ setupSelection({ id: "token1", type: "token", name: "Primary" });+ const styleDecl = createInvalidStyleDecl("token1");+ $styles.set(new Map([[getStyleDeclKey(styleDecl), styleDecl]]));+ $selectedStyleState.set(invalidState);++ deleteProperty("color");++ expect($styles.get().size).toBe(0);+ });++ test("deletes an existing local declaration with an invalid state", () => {+ setupBaseStores();+ const styleDecl = createInvalidStyleDecl("local1");+ $styleSources.set(+ new Map([["local1", { id: "local1", type: "local" as const }]])+ );+ $styleSourceSelections.set(+ new Map([["body", { instanceId: "body", values: ["local1"] }]])+ );+ $selectedStyleSources.set(new Map());+ $styles.set(new Map([[getStyleDeclKey(styleDecl), styleDecl]]));+ $selectedStyleState.set(invalidState);++ deleteProperty("color");++ expect($styles.get().size).toBe(0);+ });+test("writes styles for implicit local source through runtime generated ids", () => {setupBaseStores();$styleSources.set(new Map());diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex a9c5340f1b..b2334a5573 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -62024,6 +62024,9 @@ export const runtimeOperationContractData = [},state: {type: "string",+ minLength: 1,+ description:+ "Exact state selector to delete. An invalid selector is accepted only when it identifies an existing declaration with the same style source, breakpoint, property, and state.",},},required: ["instanceId", "property"],@@ -62162,6 +62165,9 @@ export const runtimeOperationContractData = [},state: {type: "string",+ minLength: 1,+ description:+ "Exact state selector to delete. An invalid selector is accepted only when it identifies an existing declaration with the same style source, breakpoint, property, and state.",},styleSourceId: {type: "string",@@ -62986,6 +62992,9 @@ export const runtimeOperationContractData = [},state: {type: "string",+ minLength: 1,+ description:+ "Exact state selector to delete. An invalid selector is accepted only when it identifies an existing declaration with the same style source, breakpoint, property, and state.",},},required: ["property"],diff --git a/packages/project-build/src/runtime/audit.test.ts b/packages/project-build/src/runtime/audit.test.tsindex e00bc7392a..186eae62a6 100644--- a/packages/project-build/src/runtime/audit.test.ts+++ b/packages/project-build/src/runtime/audit.test.ts@@ -1,10 +1,12 @@import { describe, expect, test } from "vitest";import {+ getStyleDeclKey,type Instance,type Page,type Prop,type StyleDecl,} from "@webstudio-is/sdk";+import type { BuilderRuntimeMutation } from "./mutation";import { executeBuilderRuntimeOperation } from "./registry";import { setImageDescriptions } from "./assets";import { analyzeProject, searchProject } from "./search";@@ -2759,6 +2761,88 @@ describe("project audit and analysis", () => {);});+ test("deletes an invalid design token selector reported by the style audit", () => {+ const invalidState = "::-webkit-search-cancel-button";+ const declaration: StyleDecl = {+ styleSourceId: "token",+ breakpointId: "base",+ property: "color",+ state: invalidState,+ value: { type: "keyword", value: "red" },+ };+ const styles = new Map<string, StyleDecl>(state.styles);+ styles.set(getStyleDeclKey(declaration), declaration);+ const project = {+ ...state,+ styles,+ } satisfies BuilderState;+ const before = audit(+ project,+ { scopes: ["styles"], verbose: true },+ { projectVersion: 1 }+ );+ const finding = before.findings.find(+ ({ ruleId }) => ruleId === "invalid-style-state-selector"+ );+ expect(finding?.location).toMatchObject({+ styleSourceId: "token",+ breakpointId: "base",+ stateSelector: invalidState,+ styleProperty: "color",+ });++ const mutation = executeBuilderRuntimeOperation({+ id: "designTokens.deleteStyles",+ state: project,+ input: {+ designTokenId: "token",+ deletions: [+ {+ breakpoint: "base",+ property: "color",+ state: invalidState,+ },+ ],+ },+ context,+ }) as BuilderRuntimeMutation;+ const { state: updatedProject } = applyBuilderPatchTransactions(project, [+ { id: "delete-invalid-selector", payload: mutation.payload },+ ]);++ expect(+ audit(+ updatedProject,+ { scopes: ["styles"], verbose: true },+ { projectVersion: 2 }+ ).findings+ ).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({ ruleId: "invalid-style-state-selector" }),+ ])+ );++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "designTokens.deleteStyles",+ state: updatedProject,+ input: {+ designTokenId: "token",+ deletions: [+ {+ breakpoint: "base",+ property: "color",+ state: ":not-a-real-selector",+ },+ ],+ },+ context,+ })+ ).toThrow(+ "An invalid state selector can only delete an existing declaration"+ );+ });+test("audits disabled atomic CSS as a performance optimization", () => {const result = audit({diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.tsindex 86fffe92ee..f7204aaf6b 100644--- a/packages/project-build/src/runtime/styles.test.ts+++ b/packages/project-build/src/runtime/styles.test.ts@@ -1068,7 +1068,7 @@ const instance = (id: string): Instance => ({describe("runtime style operations", () => {test.each([":hover, body", ":hover > div", "body:hover"])(- "rejects state selectors that escape the styled element: %s",+ "rejects state selectors that escape the styled element when writing: %s",(state) => {expect(styleUpdateInput.safeParse({@@ -1078,13 +1078,6 @@ describe("runtime style operations", () => {state,})).toMatchObject({ success: false });- expect(- styleDeleteInput.safeParse({- instanceId: "box",- property: "color",- state,- })- ).toMatchObject({ success: false });expect(designTokenCreateInput.safeParse({name: "Primary",@@ -1100,6 +1093,16 @@ describe("runtime style operations", () => {});+ test("accepts an invalid state as an existing declaration deletion coordinate", () => {+ expect(+ styleDeleteInput.safeParse({+ instanceId: "box",+ property: "color",+ state: "::-webkit-search-cancel-button",+ })+ ).toMatchObject({ success: true });+ });+test("preserves an editable compound state through mutation and generated CSS", () => {const state = ":hover:focus-visible";const mutation = updateStyleDeclarations(diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.tsindex 76671f6332..676a13038e 100644--- a/packages/project-build/src/runtime/styles.ts+++ b/packages/project-build/src/runtime/styles.ts@@ -301,6 +301,13 @@ const styleStateInput = z.string().superRefine((state, context) => {}});+const existingStyleStateDeletionInput = z+ .string()+ .min(1)+ .describe(+ "Exact state selector to delete. An invalid selector is accepted only when it identifies an existing declaration with the same style source, breakpoint, property, and state."+ );+const styleValueExample = { type: "keyword", value: "red" } as const;const typedStyleValueInput = z.object({ type: z.string() })@@ -337,7 +344,7 @@ export const styleDeleteInput = z.object({instanceId: z.string(),property: z.string(),breakpoint: z.string().optional(),- state: styleStateInput.optional(),+ state: existingStyleStateDeletionInput.optional(),});const jsonArrayStringInput = (value: unknown) => {@@ -1952,6 +1959,44 @@ export const getStyleDeclKeyFromInput = ({property: normalizeStyleProperty(property),});+const getExistingStyleDeletionKeys = <+ Deletion extends { state?: StyleDecl["state"] },+>({+ deletions,+ styles,+ getStyleKey,+}: {+ deletions: readonly Deletion[];+ styles: Iterable<StyleDecl>;+ getStyleKey: (deletion: Deletion) => string | undefined;+}) => {+ const existingStyleKeys = new Set(+ Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))+ );+ const matchedStyleKeys = new Set<string>();++ for (const deletion of deletions) {+ const styleKey = getStyleKey(deletion);+ const exists =+ styleKey !== undefined && existingStyleKeys.has(styleKey) === true;+ if (+ deletion.state !== undefined &&+ validateSelector(deletion.state).success === false &&+ exists === false+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "An invalid state selector can only delete an existing declaration. Use the exact target, state selector, breakpoint, and property reported by the style audit."+ );+ }+ if (exists) {+ matchedStyleKeys.add(styleKey);+ }+ }++ return Array.from(matchedStyleKeys);+};+export const updateStyleDecl = (declaration: StyleDecl,values: Partial<Omit<StyleDecl, "property" | "value">> & {@@ -2774,17 +2819,16 @@ export const createDesignTokenStyleDeletePayload = ({deletions: Array<Omit<z.infer<typeof styleDeleteInput>, "instanceId">>;styles: Iterable<StyleDecl>;}) => {- const existingStyleKeys = new Set(- Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))- );- const styleKeys = deletions.flatMap((deletion) => {- const key = getStyleDeclKeyFromInput({- styleSourceId: designTokenId,- breakpoint: deletion.breakpoint,- state: deletion.state,- property: deletion.property,- });- return existingStyleKeys.has(key) ? [key] : [];+ const styleKeys = getExistingStyleDeletionKeys({+ deletions,+ styles,+ getStyleKey: (deletion) =>+ getStyleDeclKeyFromInput({+ styleSourceId: designTokenId,+ breakpoint: deletion.breakpoint,+ state: deletion.state,+ property: deletion.property,+ }),});return {@@ -2995,41 +3039,35 @@ export const createStyleDeclarationDeletePayload = ({styleSourceSelections: Iterable<StyleSourceSelection>;styles: Iterable<StyleDecl>;}) => {- const styleKeys = new Set<string>();const styleSourceSelectionByInstanceId = new Map(Array.from(styleSourceSelections, (selection) => [selection.instanceId,selection,]));- const existingStyleKeys = new Set(- Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))- );-- for (const deletion of deletions) {- const styleSourceId = getLocalStyleSourceIdWithCreated({- createdLocalSourceIds: new Map(),- instanceId: deletion.instanceId,- styleSources,- styleSourceSelection: styleSourceSelectionByInstanceId.get(- deletion.instanceId- ),- });- if (styleSourceId === undefined) {- continue;- }- const key = getStyleDeclKeyFromInput({- styleSourceId,- breakpoint: deletion.breakpoint,- state: deletion.state,- property: deletion.property,- });- if (existingStyleKeys.has(key)) {- styleKeys.add(key);- }- }-- const removedStyleKeys = Array.from(styleKeys);+ const removedStyleKeys = getExistingStyleDeletionKeys({+ deletions,+ styles,+ getStyleKey: (deletion) => {+ const styleSourceId = getLocalStyleSourceIdWithCreated({+ createdLocalSourceIds: new Map(),+ instanceId: deletion.instanceId,+ styleSources,+ styleSourceSelection: styleSourceSelectionByInstanceId.get(+ deletion.instanceId+ ),+ });+ if (styleSourceId === undefined) {+ return;+ }+ return getStyleDeclKeyFromInput({+ styleSourceId,+ breakpoint: deletion.breakpoint,+ state: deletion.state,+ property: deletion.property,+ });+ },+ });return {payload: createStyleRemovePayload(removedStyleKeys),styleKeys: removedStyleKeys,@@ -3167,17 +3205,16 @@ export const createSelectedStyleDeclarationDeletePayload = ({>;styles: Iterable<StyleDecl>;}) => {- const existingStyleKeys = new Set(- Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))- );- const styleKeys = deletions.flatMap((deletion) => {- const styleKey = getStyleDeclKeyFromInput({- styleSourceId: deletion.styleSourceId,- breakpoint: deletion.breakpoint,- state: deletion.state,- property: deletion.property,- });- return existingStyleKeys.has(styleKey) ? [styleKey] : [];+ const styleKeys = getExistingStyleDeletionKeys({+ deletions,+ styles,+ getStyleKey: (deletion) =>+ getStyleDeclKeyFromInput({+ styleSourceId: deletion.styleSourceId,+ breakpoint: deletion.breakpoint,+ state: deletion.state,+ property: deletion.property,+ }),});return {payload: createStyleRemovePayload(styleKeys),@@ -3823,11 +3860,12 @@ export const deleteDesignTokenStyles = () => {const styleState = getRequiredStyleState(state);getDesignTokenOrThrow(styleState.styleSources.values(), input.designTokenId);+ const deletions = input.deletions.map((deletion) =>+ withValidatedBreakpoint(deletion, state.breakpoints)+ );const { payload, styleKeys } = createDesignTokenStyleDeletePayload({designTokenId: input.designTokenId,- deletions: input.deletions.map((deletion) =>- withValidatedBreakpoint(deletion, state.breakpoints)- ),+ deletions,styles: styleState.styles.values(),});return createRuntimeMutation({