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
Add component tokens support (#2147)
Bogdan Chadkin5e900ff2e8d2
diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.test.ts b/apps/builder/app/builder/features/style-panel/style-source-section.test.tsnew file mode 100644index 0000000000..7d9357f8d9--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/style-source-section.test.ts@@ -0,0 +1,96 @@+import { expect, test } from "@jest/globals";+import type { Breakpoint } from "@webstudio-is/project-build";+import type { WsComponentMeta } from "@webstudio-is/react-sdk";+import {+ breakpointsStore,+ registeredComponentMetasStore,+} from "~/shared/nano-states";+import { $presetTokens } from "./style-source-section";++test("generate Styles from preset tokens", () => {+ breakpointsStore.set(+ new Map<Breakpoint["id"], Breakpoint>([+ ["base", { id: "base", label: "Base" }],+ ])+ );+ registeredComponentMetasStore.set(+ new Map<string, WsComponentMeta>([+ [+ "Box",+ {+ icon: "",+ type: "container",+ presetTokens: {+ boxBright: {+ styles: [+ {+ property: "color",+ value: { type: "keyword", value: "black" },+ },+ ],+ },+ },+ },+ ],+ [+ "Button",+ {+ icon: "",+ type: "container",+ presetTokens: {+ buttonPrimary: {+ styles: [+ {+ property: "backgroundColor",+ value: { type: "keyword", value: "black" },+ },+ ],+ },+ },+ },+ ],+ ])+ );+ expect($presetTokens.get()).toEqual(+ new Map([+ [+ "Box:boxBright",+ {+ component: "Box",+ styleSource: {+ type: "token",+ id: "Box:boxBright",+ name: "Box Bright",+ },+ styles: [+ {+ breakpointId: "base",+ styleSourceId: "Box:boxBright",+ property: "color",+ value: { type: "keyword", value: "black" },+ },+ ],+ },+ ],+ [+ "Button:buttonPrimary",+ {+ component: "Button",+ styleSource: {+ type: "token",+ id: "Button:buttonPrimary",+ name: "Button Primary",+ },+ styles: [+ {+ breakpointId: "base",+ styleSourceId: "Button:buttonPrimary",+ property: "backgroundColor",+ value: { type: "keyword", value: "black" },+ },+ ],+ },+ ],+ ])+ );+});diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsxindex 81a7fed52f..2ff12d1e8b 100644--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx@@ -9,6 +9,7 @@ import {type StyleSourceToken,type StyleSourceSelections,getStyleDeclKey,+ StyleDecl,} from "@webstudio-is/project-build";import {Flex,@@ -22,7 +23,8 @@ import {} from "@webstudio-is/design-system";import { type ItemSource, StyleSourceInput } from "./style-source";import {- availableStyleSourcesStore,+ breakpointsStore,+ instancesStore,registeredComponentMetasStore,selectedInstanceSelectorStore,selectedInstanceStatesByStyleSourceIdStore,@@ -36,6 +38,9 @@ import {} from "~/shared/nano-states";import { removeByMutable } from "~/shared/array-utils";import { cloneStyles } from "~/shared/tree-utils";+import { humanizeString } from "~/shared/string-utils";+import { isBaseBreakpoint } from "~/shared/breakpoints";+import { shallowComputed } from "~/shared/store-utils";const getOrCreateStyleSourceSelectionMutable = (styleSourceSelections: StyleSourceSelections,@@ -81,7 +86,60 @@ const createLocalStyleSourceIfNotExists = ();};-const createStyleSource = (name: string) => {+const $baseBreakpointId = computed(breakpointsStore, (breakpoints) => {+ const breakpointValues = Array.from(breakpoints.values());+ const baseBreakpoint = breakpointValues.find(isBaseBreakpoint);+ return baseBreakpoint?.id;+});++// metas are rarely change so keep preset token styles computing+// in separate store+export const $presetTokens = computed(+ [registeredComponentMetasStore, $baseBreakpointId],+ (metas, baseBreakpointId) => {+ const presetTokens = new Map<+ StyleSource["id"],+ {+ component: Instance["component"];+ styleSource: StyleSourceToken;+ styles: StyleDecl[];+ }+ >();+ if (baseBreakpointId === undefined) {+ return presetTokens;+ }+ for (const [component, meta] of metas) {+ if (meta.presetTokens === undefined) {+ continue;+ }+ for (const [name, tokenValue] of Object.entries(meta.presetTokens)) {+ const styleSourceId = `${component}:${name}`;+ const styles: StyleDecl[] = [];+ for (const styleDecl of tokenValue.styles) {+ styles.push({+ breakpointId: baseBreakpointId,+ styleSourceId,+ state: styleDecl.state,+ property: styleDecl.property,+ value: styleDecl.value,+ });+ }+ presetTokens.set(styleSourceId, {+ component,+ styleSource: {+ type: "token",+ id: styleSourceId,+ name: humanizeString(name),+ },+ styles,+ });+ }+ }+ return presetTokens;+ }+);++const createStyleSource = (id: StyleSource["id"], name: string) => {const selectedInstanceSelector = selectedInstanceSelectorStore.get();if (selectedInstanceSelector === undefined) {return;@@ -89,18 +147,27 @@ const createStyleSource = (name: string) => {const [selectedInstanceId] = selectedInstanceSelector;const newStyleSource: StyleSource = {type: "token",- id: nanoid(),+ id,name,};+ const presetTokens = $presetTokens.get();store.createTransaction(- [styleSourcesStore, styleSourceSelectionsStore],- (styleSources, styleSourceSelections) => {+ [styleSourcesStore, stylesStore, styleSourceSelectionsStore],+ (styleSources, styles, styleSourceSelections) => {const styleSourceSelection = getOrCreateStyleSourceSelectionMutable(styleSourceSelections,selectedInstanceId);styleSourceSelection.values.push(newStyleSource.id);styleSources.set(newStyleSource.id, newStyleSource);++ // populate preset token styles+ const presetToken = presetTokens.get(id);+ if (presetToken) {+ for (const styleDecl of presetToken.styles) {+ styles.set(getStyleDeclKey(styleDecl), styleDecl);+ }+ }});selectedStyleSourceSelectorStore.set({ styleSourceId: newStyleSource.id });@@ -336,15 +403,63 @@ const convertToInputItem = (};};+const $selectedInstancePresetTokens = shallowComputed(+ [selectedInstanceSelectorStore, instancesStore, $presetTokens],+ (selectedInstanceSelector, instances, presetTokens) => {+ const selectedInstancePresetTokens: StyleSourceToken[] = [];+ if (selectedInstanceSelector === undefined) {+ return selectedInstancePresetTokens;+ }+ const [instanceId] = selectedInstanceSelector;+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ return selectedInstancePresetTokens;+ }+ for (const presetToken of presetTokens.values()) {+ if (presetToken.component === instance.component) {+ selectedInstancePresetTokens.push(presetToken.styleSource);+ }+ }+ return selectedInstancePresetTokens;+ }+);++/**+ * find all non-local and component style sources+ */+const $availableStyleSources = computed(+ [styleSourcesStore, $selectedInstancePresetTokens],+ (styleSources, presetTokens) => {+ const availableStylesSources: StyleSourceInputItem[] = [];+ for (const styleSource of styleSources.values()) {+ if (styleSource.type === "local") {+ continue;+ }+ availableStylesSources.push(convertToInputItem(styleSource, []));+ }+ for (const styleSource of presetTokens) {+ // skip if already present in global tokens+ if (styleSources.has(styleSource.id)) {+ continue;+ }+ availableStylesSources.push({+ id: styleSource.id,+ label: styleSource.name,+ disabled: false,+ source: "componentToken",+ states: [],+ });+ }+ return availableStylesSources;+ }+);+export const StyleSourcesSection = () => {const componentStates = useStore(componentStatesStore);- const availableStyleSources = useStore(availableStyleSourcesStore);+ const availableStyleSources = useStore($availableStyleSources);const selectedInstanceStyleSources = useStore(selectedInstanceStyleSourcesStore);- const items = availableStyleSources.map((styleSource) =>- convertToInputItem(styleSource, [])- );const selectedInstanceStatesByStyleSourceId = useStore(selectedInstanceStatesByStyleSourceIdStore);@@ -367,7 +482,7 @@ export const StyleSourcesSection = () => {return (<><StyleSourceInput- items={items}+ items={availableStyleSources}value={value}selectedItemSelector={selectedOrLastStyleSourceSelector}componentStates={componentStates}diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-badge.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-badge.tsxindex 483c5acd82..92dbebe78f 100644--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-badge.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-badge.tsx@@ -18,6 +18,9 @@ export const StyleSourceBadge = styled(Text, {token: {backgroundColor: theme.colors.backgroundStyleSourceToken,},+ componentToken: {+ backgroundColor: theme.colors.backgroundStyleSourceToken,+ },tag: {backgroundColor: theme.colors.backgroundStyleSourceTag,},diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsxindex a4c91c1c55..154b02b2ab 100644--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx@@ -12,6 +12,7 @@* - Hit Backspace to delete the last Source item when you are in the input*/+import { nanoid } from "nanoid";import {Box,ComboboxListbox,@@ -32,6 +33,7 @@ import {theme,styled,} from "@webstudio-is/design-system";+import { CheckMarkIcon, DotIcon } from "@webstudio-is/icons";import {forwardRef,useState,@@ -47,7 +49,6 @@ import { type ItemSource, menuCssVars, StyleSource } from "./style-source";import { useSortable } from "./use-sortable";import { matchSorter } from "match-sorter";import { StyleSourceBadge } from "./style-source-badge";-import { CheckMarkIcon, DotIcon } from "@webstudio-is/icons";import { humanizeString } from "~/shared/string-utils";type IntermediateItem = {@@ -192,6 +193,7 @@ const TextFieldBase: ForwardRefRenderFunction<type={type}onClick={onClick}ref={mergeRefs(internalInputRef, inputRef ?? null)}+ spellCheck={false}aria-label="New Style Source Input"/>)}@@ -214,7 +216,7 @@ type StyleSourceInputProps<Item extends IntermediateItem> = {onClearStyles?: (id: Item["id"]) => void;onDuplicateItem?: (id: Item["id"]) => void;onConvertToToken?: (id: Item["id"]) => void;- onCreateItem?: (label: string) => void;+ onCreateItem?: (id: Item["id"], label: string) => void;onChangeItem?: (item: Item) => void;onSelectItem?: (item: ItemSelector) => void;onEditItem?: (id?: Item["id"]) => void;@@ -234,6 +236,10 @@ const matchOrSuggestToCreate = (const matched = matchSorter(items, search, {keys: [itemToString],});+ const order: ItemSource[] = ["token", "componentToken"];+ matched.sort((leftItem, rightItem) => {+ return order.indexOf(leftItem.source) - order.indexOf(rightItem.source);+ });if (search.trim() !== "" &&itemToString(matched[0]).toLocaleLowerCase() !==@@ -411,7 +417,9 @@ export const StyleSourceInput = (onItemSelect(item) {setLabel("");if (item.id === newItemId) {- props.onCreateItem?.(item.label);+ props.onCreateItem?.(nanoid(), item.label);+ } else if (item.source === "componentToken") {+ props.onCreateItem?.(item.id, item.label);} else {props.onSelectAutocompleteItem?.(item);}@@ -437,6 +445,8 @@ export const StyleSourceInput = (});let hasNewTokenItem = false;+ let hasGlobalTokenItem = false;+ let hasComponentTokenItem = false;const states = props.componentStates ?? [];@@ -479,6 +489,10 @@ export const StyleSourceInput = (<ComboboxListbox {...getMenuProps()}>{isOpen &&items.map((item, index) => {+ if (item.source === "local") {+ return;+ }+if (item.id === newItemId) {hasNewTokenItem = true;return (@@ -499,15 +513,30 @@ export const StyleSourceInput = ();}- const firstExistingItemIndex = hasNewTokenItem ? 1 : 0;- const label = index === firstExistingItemIndex && (- <>- {hasNewTokenItem && <ComboboxSeparator />}- <ComboboxLabel>Existing Tokens</ComboboxLabel>- </>- );- if (item.source === "local") {- return;+ let label = null;+ if (item.source === "token" && hasGlobalTokenItem === false) {+ hasGlobalTokenItem = true;+ label = (+ <>+ {hasNewTokenItem && <ComboboxSeparator />}+ <ComboboxLabel>Global Tokens</ComboboxLabel>+ </>+ );+ }++ if (+ item.source === "componentToken" &&+ hasComponentTokenItem === false+ ) {+ hasComponentTokenItem = true;+ label = (+ <>+ {(hasNewTokenItem || hasGlobalTokenItem) && (+ <ComboboxSeparator />+ )}+ <ComboboxLabel>Component Tokens</ComboboxLabel>+ </>+ );}return (<Fragment key={index}>diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source.tsxindex 42c77c4086..a60a261f8e 100644--- a/apps/builder/app/builder/features/style-panel/style-source/style-source.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source.tsx@@ -100,7 +100,7 @@ const Menu = (props: MenuProps) => {);};-export type ItemSource = "token" | "tag" | "local";+export type ItemSource = "token" | "componentToken" | "tag" | "local";type EditableTextProps = {label: string;@@ -163,6 +163,11 @@ const StyleSourceContainer = styled(Box, {[menuTriggerGradientVar]:theme.colors.backgroundStyleSourceGradientToken,},+ componentToken: {+ backgroundColor: theme.colors.backgroundStyleSourceToken,+ [menuTriggerGradientVar]:+ theme.colors.backgroundStyleSourceGradientToken,+ },tag: {backgroundColor: theme.colors.backgroundStyleSourceTag,[menuTriggerGradientVar]: theme.colors.backgroundStyleSourceGradientTag,diff --git a/apps/builder/app/shared/copy-paste/plugin-embed-template.ts b/apps/builder/app/shared/copy-paste/plugin-embed-template.tsindex 48215bff44..cc0fc00749 100644--- a/apps/builder/app/shared/copy-paste/plugin-embed-template.ts+++ b/apps/builder/app/shared/copy-paste/plugin-embed-template.ts@@ -51,11 +51,12 @@ export const onPaste = (clipboardData: string): boolean => {if (baseBreakpoint === undefined) {return false;}+ const metas = registeredComponentMetasStore.get();const templateData = generateDataFromEmbedTemplate(template,+ metas,baseBreakpoint.id);- const metas = registeredComponentMetasStore.get();const newInstances = new Map(templateData.instances.map((instance) => [instance.id, instance]));diff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.tsindex 6a857db963..be6003c682 100644--- a/apps/builder/app/shared/instance-utils.test.ts+++ b/apps/builder/app/shared/instance-utils.test.ts@@ -1,3 +1,4 @@+import { enableMapSet } from "immer";import { describe, test, expect } from "@jest/globals";import type { WsComponentMeta } from "@webstudio-is/react-sdk";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";@@ -7,8 +8,19 @@ import {findClosestDroppableComponentIndex,findClosestDroppableTarget,findClosestEditableInstanceSelector,+ insertTemplateData,type InsertConstraints,} from "./instance-utils";+import {+ instancesStore,+ styleSourceSelectionsStore,+ styleSourcesStore,+ stylesStore,+} from "./nano-states";+import { registerContainers } from "./sync";++enableMapSet();+registerContainers();const defaultMetasMap = new Map(Object.entries(defaultMetas));@@ -317,3 +329,91 @@ describe("find closest droppable target", () => {});});});++test("insert template data with only new style sources", () => {+ instancesStore.set(new Map([createInstancePair("body", "Body", [])]));+ styleSourceSelectionsStore.set(new Map());+ styleSourcesStore.set(+ new Map([["1", { type: "token", id: "1", name: "Zero" }]])+ );+ stylesStore.set(+ new Map([+ [+ "1:base:color:",+ {+ breakpointId: "base",+ styleSourceId: "1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ ])+ );+ insertTemplateData(+ {+ children: [{ type: "id", value: "box1" }],+ instances: [+ { type: "instance", id: "box1", component: "Box", children: [] },+ ],+ props: [],+ dataSources: [],+ styleSourceSelections: [{ instanceId: "box1", values: ["1", "2"] }],+ styleSources: [+ { type: "token", id: "1", name: "One" },+ { type: "token", id: "2", name: "Two" },+ ],+ styles: [+ {+ breakpointId: "base",+ styleSourceId: "1",+ property: "color",+ value: { type: "keyword", value: "black" },+ },+ {+ breakpointId: "base",+ styleSourceId: "1",+ property: "backgroundColor",+ value: { type: "keyword", value: "purple" },+ },+ {+ breakpointId: "base",+ styleSourceId: "2",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ],+ },+ { parentSelector: ["body"], position: "end" }+ );+ expect(styleSourceSelectionsStore.get()).toEqual(+ new Map([["box1", { instanceId: "box1", values: ["1", "2"] }]])+ );+ expect(styleSourcesStore.get()).toEqual(+ new Map([+ ["1", { type: "token", id: "1", name: "Zero" }],+ ["2", { type: "token", id: "2", name: "Two" }],+ ])+ );+ expect(stylesStore.get()).toEqual(+ new Map([+ [+ "1:base:color:",+ {+ breakpointId: "base",+ styleSourceId: "1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "2:base:color:",+ {+ breakpointId: "base",+ styleSourceId: "2",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ],+ ])+ );+});diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex c315a1e24f..d8aa84eff3 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -3,7 +3,9 @@ import { toast } from "@webstudio-is/design-system";import {type Instance,type Instances,+ type StyleSource,findTreeInstanceIdsExcludingSlotDescendants,+ getStyleDeclKey,} from "@webstudio-is/project-build";import {type WsComponentMeta,@@ -31,9 +33,6 @@ import {reparentInstanceMutable,getAncestorInstanceSelector,insertPropsCopyMutable,- insertStyleSourcesCopyMutable,- insertStyleSourceSelectionsCopyMutable,- insertStylesCopyMutable,} from "./tree-utils";import { removeByMutable } from "./array-utils";import { isBaseBreakpoint } from "./breakpoints";@@ -264,9 +263,6 @@ export const insertTemplateData = (instances: insertedInstances,props: insertedProps,dataSources: insertedDataSources,- styleSourceSelections: insertedStyleSourceSelections,- styleSources: insertedStyleSources,- styles: insertedStyles,} = templateData;const rootInstanceId = insertedInstances[0].id;store.createTransaction(@@ -298,18 +294,29 @@ export const insertTemplateData = (for (const dataSource of insertedDataSources) {dataSources.set(dataSource.id, dataSource);}- insertStyleSourcesCopyMutable(- styleSources,- insertedStyleSources,- new Set()- );- insertStyleSourceSelectionsCopyMutable(- styleSourceSelections,- insertedStyleSourceSelections,- new Map(),- new Map()- );- insertStylesCopyMutable(styles, insertedStyles, new Map(), new Map());++ // insert only new style sources and their styles to support+ // embed template tokens which have persistent id+ // so when user changes these styles and then again add component with token+ // nothing breaks visually+ const insertedStyleSources = new Set<StyleSource["id"]>();+ for (const styleSource of templateData.styleSources) {+ if (styleSources.has(styleSource.id) === false) {+ insertedStyleSources.add(styleSource.id);+ styleSources.set(styleSource.id, styleSource);+ }+ }+ for (const styleDecl of templateData.styles) {+ if (insertedStyleSources.has(styleDecl.styleSourceId)) {+ styles.set(getStyleDeclKey(styleDecl), styleDecl);+ }+ }+ for (const styleSourceSelection of templateData.styleSourceSelections) {+ styleSourceSelections.set(+ styleSourceSelection.instanceId,+ styleSourceSelection+ );+ }});@@ -337,7 +344,7 @@ export const getComponentTemplateData = (component: string) => {if (baseBreakpoint === undefined) {return;}- return generateDataFromEmbedTemplate(template, baseBreakpoint.id);+ return generateDataFromEmbedTemplate(template, metas, baseBreakpoint.id);};export const reparentInstance = (diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.tsindex 76dbe1074f..f81d6c4647 100644--- a/apps/builder/app/shared/nano-states/nano-states.ts+++ b/apps/builder/app/shared/nano-states/nano-states.ts@@ -157,23 +157,6 @@ export const useInstanceStyles = (instanceId: undefined | Instance["id"]) => {};export const styleSourcesStore = atom<StyleSources>(new Map());-/**- * find all non-local style sources- * scoped to current tree or whole project- */-export const availableStyleSourcesStore = shallowComputed(- [styleSourcesStore],- (styleSources) => {- const availableStylesSources: StyleSource[] = [];- for (const styleSource of styleSources.values()) {- if (styleSource.type === "local") {- continue;- }- availableStylesSources.push(styleSource);- }- return availableStylesSources;- }-);export const useSetStyleSources = (styleSources: [StyleSource["id"], StyleSource][]diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.jsonindex bd9ad2058f..caf3fcc88c 100644--- a/packages/react-sdk/package.json+++ b/packages/react-sdk/package.json@@ -48,7 +48,9 @@"jsep": "^1.3.8","nanoevents": "^8.0.0","nanoid": "^4.0.2",- "nanostores": "^0.9.3"+ "nanostores": "^0.9.3",+ "no-case": "^3.0.4",+ "title-case": "^3.0.3"},"exports": {".": {diff --git a/packages/react-sdk/src/component-renderer.tsx b/packages/react-sdk/src/component-renderer.tsxindex edb76f512e..3cac268c4d 100644--- a/packages/react-sdk/src/component-renderer.tsx+++ b/packages/react-sdk/src/component-renderer.tsx@@ -56,7 +56,7 @@ export const renderComponentTemplate = ({});}- const data = generateDataFromEmbedTemplate(template, "base");+ const data = generateDataFromEmbedTemplate(template, metas, "base");const instances: [Instance["id"], Instance][] = [[diff --git a/packages/react-sdk/src/components/component-meta.ts b/packages/react-sdk/src/components/component-meta.tsindex eae22bf2f9..453bca8bb9 100644--- a/packages/react-sdk/src/components/component-meta.ts+++ b/packages/react-sdk/src/components/component-meta.ts@@ -36,6 +36,11 @@ export const ComponentState = z.object({export type ComponentState = z.infer<typeof ComponentState>;+const ComponentToken = z.object({+ variant: z.optional(z.string()),+ styles: z.array(EmbedTemplateStyleDecl),+});+export const defaultStates: ComponentState[] = [{ selector: ":hover", label: "Hover" },{ selector: ":active", label: "Active" },@@ -67,6 +72,7 @@ const WsComponentMeta = z.object({description: z.string().optional(),icon: z.string(),presetStyle: z.optional(z.record(z.string(), EmbedTemplateStyleDecl)),+ presetTokens: z.optional(z.record(z.string(), ComponentToken)),states: z.optional(z.array(ComponentState)),template: z.optional(WsEmbedTemplate),order: z.number().optional(),diff --git a/packages/react-sdk/src/embed-template.test.ts b/packages/react-sdk/src/embed-template.test.tsindex 34390d9ab3..59268a95ce 100644--- a/packages/react-sdk/src/embed-template.test.ts+++ b/packages/react-sdk/src/embed-template.test.ts@@ -1,6 +1,7 @@import { expect, test } from "@jest/globals";import { generateDataFromEmbedTemplate, namespaceMeta } from "./embed-template";import { showAttribute } from "./tree";+import type { WsComponentMeta } from "./components/component-meta";const expectString = expect.any(String);@@ -20,6 +21,7 @@ test("generate data for embedding from instances and text", () => {],},],+ new Map(),defaultBreakpointId)).toEqual({@@ -73,6 +75,7 @@ test("generate data for embedding from props", () => {],},],+ new Map(),defaultBreakpointId)).toEqual({@@ -147,6 +150,7 @@ test("generate data for embedding from styles", () => {],},],+ new Map(),defaultBreakpointId)).toEqual({@@ -245,6 +249,7 @@ test("generate data for embedding from props bound to data source variables", ()children: [],},],+ new Map(),defaultBreakpointId)).toEqual({@@ -326,6 +331,7 @@ test("generate data for embedding from props bound to data source expressions",children: [],},],+ new Map(),defaultBreakpointId)).toEqual({@@ -422,6 +428,7 @@ test("generate data for embedding from action props", () => {],},],+ new Map(),defaultBreakpointId)).toEqual({@@ -488,6 +495,93 @@ test("generate data for embedding from action props", () => {});});+test("generate styles from tokens", () => {+ const presetTokens: WsComponentMeta["presetTokens"] = {+ box: {+ styles: [+ {+ property: "width",+ value: { type: "keyword", value: "max-content" },+ },+ {+ property: "height",+ value: { type: "keyword", value: "max-content" },+ },+ ],+ },+ boxBright: {+ styles: [+ {+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ property: "backgroundColor",+ value: { type: "keyword", value: "pink" },+ },+ ],+ },+ boxNone: {+ styles: [+ {+ property: "color",+ value: { type: "keyword", value: "transparent" },+ },+ {+ property: "backgroundColor",+ value: { type: "keyword", value: "transparent" },+ },+ ],+ },+ };+ const { styleSourceSelections, styleSources, styles } =+ generateDataFromEmbedTemplate(+ [+ {+ type: "instance",+ component: "Box",+ tokens: ["box", "boxBright"],+ children: [],+ },+ ],+ new Map([["Box", { type: "container", icon: "", presetTokens }]]),+ defaultBreakpointId+ );+ expect(styleSources).toEqual([+ { id: "Box:box", name: "Box", type: "token" },+ { id: "Box:boxBright", name: "Box Bright", type: "token" },+ ]);+ expect(styleSourceSelections).toEqual([+ { instanceId: expectString, values: ["Box:box", "Box:boxBright"] },+ ]);+ expect(styles).toEqual([+ {+ breakpointId: "base",+ property: "width",+ styleSourceId: "Box:box",+ value: { type: "keyword", value: "max-content" },+ },+ {+ breakpointId: "base",+ property: "height",+ styleSourceId: "Box:box",+ value: { type: "keyword", value: "max-content" },+ },+ {+ breakpointId: "base",+ property: "color",+ styleSourceId: "Box:boxBright",+ value: { type: "keyword", value: "red" },+ },+ {+ breakpointId: "base",+ property: "backgroundColor",+ styleSourceId: "Box:boxBright",+ value: { type: "keyword", value: "pink" },+ },+ ]);+});+test("add namespace to selected components in embed template", () => {expect(namespaceMeta(@@ -498,10 +592,16 @@ test("add namespace to selected components in embed template", () => {requiredAncestors: ["Button", "Box"],invalidAncestors: ["Tooltip"],indexWithinAncestor: "Tooltip",+ presetTokens: {+ base: { styles: [] },+ small: { styles: [] },+ large: { styles: [] },+ },template: [{type: "instance",component: "Tooltip",+ tokens: ["base", "small"],children: [{ type: "text", value: "Some text" },{@@ -529,10 +629,16 @@ test("add namespace to selected components in embed template", () => {requiredAncestors: ["my-namespace:Button", "Box"],invalidAncestors: ["my-namespace:Tooltip"],indexWithinAncestor: "my-namespace:Tooltip",+ presetTokens: {+ base: { styles: [] },+ small: { styles: [] },+ large: { styles: [] },+ },template: [{type: "instance",component: "my-namespace:Tooltip",+ tokens: ["base", "small"],children: [{ type: "text", value: "Some text" },{diff --git a/packages/react-sdk/src/embed-template.ts b/packages/react-sdk/src/embed-template.tsindex 452fe43194..e6e8c3028b 100644--- a/packages/react-sdk/src/embed-template.ts+++ b/packages/react-sdk/src/embed-template.ts@@ -1,5 +1,7 @@import { z } from "zod";import { nanoid } from "nanoid";+import { titleCase } from "title-case";+import { noCase } from "no-case";import {Instance,type InstancesList,@@ -103,6 +105,7 @@ export type EmbedTemplateInstance = {label?: string;dataSources?: Record<string, EmbedTemplateDataSource>;props?: EmbedTemplateProp[];+ tokens?: string[];styles?: EmbedTemplateStyleDecl[];children: Array<EmbedTemplateInstance | EmbedTemplateText>;};@@ -115,6 +118,7 @@ export const EmbedTemplateInstance: z.ZodType<EmbedTemplateInstance> = z.lazy(label: z.optional(z.string()),dataSources: z.optional(z.record(z.string(), EmbedTemplateDataSource)),props: z.optional(z.array(EmbedTemplateProp)),+ tokens: z.optional(z.array(z.string())),styles: z.optional(z.array(EmbedTemplateStyleDecl)),children: WsEmbedTemplate,})@@ -153,6 +157,7 @@ const createInstancesFromTemplate = (styleSourceSelections: StyleSourceSelectionsList,styleSources: StyleSourcesList,styles: StylesList,+ metas: Map<Instance["component"], WsComponentMeta>,defaultBreakpointId: Breakpoint["id"]) => {const parentChildren: Instance["children"] = [];@@ -243,6 +248,39 @@ const createInstancesFromTemplate = (}}+ // convert tokens into style sources and styles+ if (item.tokens) {+ const meta = metas.get(item.component);+ if (meta?.presetTokens) {+ const styleSourceIds: string[] = [];+ for (const name of item.tokens) {+ const tokenValue = meta.presetTokens[name];+ if (tokenValue) {+ const styleSourceId = `${item.component}:${name}`;+ styleSourceIds.push(styleSourceId);+ styleSources.push({+ type: "token",+ id: styleSourceId,+ name: titleCase(noCase(name)),+ });+ for (const styleDecl of tokenValue.styles) {+ styles.push({+ breakpointId: defaultBreakpointId,+ styleSourceId,+ state: styleDecl.state,+ property: styleDecl.property,+ value: styleDecl.value,+ });+ }+ }+ }+ styleSourceSelections.push({+ instanceId,+ values: styleSourceIds,+ });+ }+ }+// populate stylesif (item.styles) {const styleSourceId = nanoid();@@ -283,6 +321,7 @@ const createInstancesFromTemplate = (styleSourceSelections,styleSources,styles,+ metas,defaultBreakpointId);parentChildren.push({@@ -303,6 +342,7 @@ const createInstancesFromTemplate = (export const generateDataFromEmbedTemplate = (treeTemplate: WsEmbedTemplate,+ metas: Map<Instance["component"], WsComponentMeta>,defaultBreakpointId: Breakpoint["id"]) => {const instances: InstancesList = [];@@ -320,6 +360,7 @@ export const generateDataFromEmbedTemplate = (styleSourceSelections,styleSources,styles,+ metas,defaultBreakpointId);diff --git a/packages/sdk-components-react-radix/src/button.stories.ts b/packages/sdk-components-react-radix/src/button.stories.tsindex 190596b225..bcd7be8e0f 100644--- a/packages/sdk-components-react-radix/src/button.stories.ts+++ b/packages/sdk-components-react-radix/src/button.stories.ts@@ -9,19 +9,6 @@ import * as radixMetas from "./metas";export default {title: "Components/Button",component: ButtonPrimitive,- argTypes: {- variant: {- options: [- "default",- "destructive",- "outline",- "secondary",- "ghost",- "link",- ],- control: { type: "select" },- },- },} satisfies Meta<typeof ButtonPrimitive>;export const Button: StoryObj<typeof ButtonPrimitive> = {diff --git a/packages/sdk-components-react-radix/src/button.tsx b/packages/sdk-components-react-radix/src/button.tsxindex f649e1a975..ea3fe967d7 100644--- a/packages/sdk-components-react-radix/src/button.tsx+++ b/packages/sdk-components-react-radix/src/button.tsx@@ -3,23 +3,9 @@import { forwardRef, type ComponentPropsWithoutRef } from "react";-type ButtonVariants = {- variant:- | "default"- | "destructive"- | "outline"- | "secondary"- | "ghost"- | "link";-- size: "default" | "sm" | "lg" | "icon";-};-export const Button = forwardRef<HTMLButtonElement,- ComponentPropsWithoutRef<"button"> & ButtonVariants->(({ variant = "default", size = "default", ...props }, ref) => {- return (- <button ref={ref} data-size={size} data-variant={variant} {...props} />- );+ ComponentPropsWithoutRef<"button">+>((props, ref) => {+ return <button ref={ref} {...props} />;});diff --git a/packages/sdk-components-react-radix/src/button.ws.ts b/packages/sdk-components-react-radix/src/button.ws.tsindex 599299e9a6..dd867dd0cb 100644--- a/packages/sdk-components-react-radix/src/button.ws.ts+++ b/packages/sdk-components-react-radix/src/button.ws.ts@@ -21,93 +21,7 @@ export const template = (props?: {{type: "instance",component: "Button",- styles: [- // 'inline-flex items-center justify-center rounded-md text-sm font-medium- // ring-offset-background transition-colors- // focus-visible:outline-none focus-visible:ring-2- // focus-visible:ring-ring focus-visible:ring-offset-2- // disabled:pointer-events-none disabled:opacity-50'- tc.border(0),- tc.bg("transparent"),- tc.inlineFlex(),- tc.items("center"),- tc.justify("center"),- tc.rounded("md"),- tc.text("sm"),- tc.font("medium"),- tc.focusVisible(- [tc.outline("none"), tc.ring("ring", 2, "background", 2)].flat()- ),- tc.state([tc.pointerEvents("none"), tc.opacity(50)].flat(), ":disabled"),-- // VARIANT- // default: 'bg-primary text-primary-foreground hover:bg-primary/90',- tc.state(- [tc.bg("primary"), tc.text("primaryForeground")].flat(),- "[data-variant=default]"- ),- tc.state(- [[tc.bg("primary", 90)].flat()].flat(),- "[data-variant=default]:hover"- ),-- // destructive:'bg-destructive text-destructive-foreground hover:bg-destructive/90',- tc.state(- [tc.bg("destructive"), tc.text("destructiveForeground")].flat(),- "[data-variant=destructive]"- ),- tc.state(- [[tc.bg("destructive", 90)].flat()].flat(),- "[data-variant=destructive]:hover"- ),-- // outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',- tc.state(- [tc.border(), tc.border("input"), tc.bg("background")].flat(),- "[data-variant=outline]"- ),- tc.state(- [[tc.bg("accent", 90), tc.text("accentForeground")].flat()].flat(),- "[data-variant=outline]:hover"- ),-- // secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',- tc.state(- [tc.bg("secondary"), tc.text("secondaryForeground")].flat(),- "[data-variant=secondary]"- ),- tc.state(- [[tc.bg("secondary", 80)].flat()].flat(),- "[data-variant=secondary]:hover"- ),-- // ghost: 'hover:bg-accent hover:text-accent-foreground',- tc.state(- [[tc.bg("accent"), tc.text("accentForeground")].flat()].flat(),- "[data-variant=ghost]:hover"- ),-- // link: 'text-primary underline-offset-4 hover:underline',- tc.state(- [tc.text("primary"), tc.underlineOffset(4)].flat(),- "[data-variant=link]"- ),- tc.state([[tc.underline()].flat()].flat(), "[data-variant=link]:hover"),-- // SIZE- // default: 'h-10 px-4 py-2',- tc.state([tc.h(10), tc.px(4), tc.py(2)].flat(), "[data-size=default]"),-- // sm: 'h-9 rounded-md px-3',- tc.state([tc.h(10), tc.px(3)].flat(), "[data-size=sm]"),-- // lg: 'h-11 rounded-md px-8',- tc.state([tc.h(11), tc.px(8)].flat(), "[data-size=lg]"),-- // icon: 'h-10 w-10',- tc.state([tc.h(10), tc.w(10)].flat(), "[data-size=icon]"),- ].flat(),-+ tokens: ["button", "buttonPrimary", "buttonMd"],children: props?.children ?? [{ type: "text", value: "Button" }],props: props?.props,},@@ -119,33 +33,134 @@ export const meta: WsComponentMeta = {type: "container",invalidAncestors: ["Button"],icon: ButtonElementIcon,- presetStyle,states: [...defaultStates,{ selector: ":disabled", label: "Disabled" },{ selector: ":enabled", label: "Enabled" },-- { selector: "[data-variant=default]", label: "Default" },- { selector: "[data-variant=default]:hover", label: "Default Hover" },-- { selector: "[data-variant=destructive]", label: "Destructive" },- {- selector: "[data-variant=destructive]:hover",- label: "Destructive Hover",+ ],+ presetStyle,+ presetTokens: {+ button: {+ styles: [+ // 'inline-flex items-center justify-center rounded-md text-sm font-medium+ // ring-offset-background transition-colors+ // focus-visible:outline-none focus-visible:ring-2+ // focus-visible:ring-ring focus-visible:ring-offset-2+ // disabled:pointer-events-none disabled:opacity-50'+ tc.border(0),+ tc.bg("transparent"),+ tc.inlineFlex(),+ tc.items("center"),+ tc.justify("center"),+ tc.rounded("md"),+ tc.text("sm"),+ tc.font("medium"),+ tc.focusVisible(+ [tc.outline("none"), tc.ring("ring", 2, "background", 2)].flat()+ ),+ tc.state(+ [tc.pointerEvents("none"), tc.opacity(50)].flat(),+ ":disabled"+ ),+ ].flat(),},- { selector: "[data-variant=outline]", label: "Outline" },- { selector: "[data-variant=outline]:hover", label: "Outline Hover" },-- { selector: "[data-variant=secondary]", label: "Secondary" },- { selector: "[data-variant=secondary]:hover", label: "Secondary Hover" },-- { selector: "[data-variant=ghost]", label: "Ghost" },- { selector: "[data-variant=ghost]:hover", label: "Ghost Hover" },+ // VARIANT+ buttonPrimary: {+ variant: "variant",+ styles: [+ // default: 'bg-primary text-primary-foreground hover:bg-primary/90',+ tc.bg("primary"),+ tc.text("primaryForeground"),+ tc.state([tc.bg("primary", 90)].flat(), ":hover"),+ ].flat(),+ },+ buttonDestructive: {+ variant: "variant",+ styles: [+ // destructive:'bg-destructive text-destructive-foreground hover:bg-destructive/90',+ tc.bg("destructive"),+ tc.text("destructiveForeground"),+ tc.state([tc.bg("destructive", 90)].flat(), ":hover"),+ ].flat(),+ },+ buttonOutline: {+ variant: "variant",+ styles: [+ // outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',+ tc.border(),+ tc.border("input"),+ tc.bg("background"),+ tc.state(+ [tc.bg("accent", 90), tc.text("accentForeground")].flat(),+ ":hover"+ ),+ ].flat(),+ },+ buttonSecondary: {+ variant: "variant",+ styles: [+ // secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',+ tc.bg("secondary"),+ tc.text("secondaryForeground"),+ tc.state([tc.bg("secondary", 80)].flat(), ":hover"),+ ].flat(),+ },+ buttonGhost: {+ variant: "variant",+ styles: [+ // ghost: 'hover:bg-accent hover:text-accent-foreground',+ tc.state(+ [tc.bg("accent"), tc.text("accentForeground")].flat(),+ ":hover"+ ),+ ].flat(),+ },+ buttonLink: {+ variant: "variant",+ styles: [+ // link: 'text-primary underline-offset-4 hover:underline',+ tc.text("primary"),+ tc.underlineOffset(4),+ tc.state([tc.underline()].flat(), ":hover"),+ ].flat(),+ },- { selector: "[data-variant=link]", label: "Link" },- { selector: "[data-variant=link]:hover", label: "Link Hover" },- ],+ // SIZE+ buttonMd: {+ variant: "size",+ styles: [+ // default: 'h-10 px-4 py-2',+ tc.h(10),+ tc.px(4),+ tc.py(2),+ ].flat(),+ },+ buttonSm: {+ variant: "size",+ styles: [+ // sm: 'h-9 rounded-md px-3',+ tc.h(10),+ tc.px(3),+ ].flat(),+ },+ buttonLg: {+ variant: "size",+ styles: [+ // lg: 'h-11 rounded-md px-8',+ tc.h(11),+ tc.px(8),+ ].flat(),+ },+ buttonIcon: {+ variant: "size",+ styles: [+ // icon: 'h-10 w-10',+ tc.h(10),+ tc.w(10),+ ].flat(),+ },+ },template: template(),};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 867f17c7d3..f8b212ff0f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1239,6 +1239,12 @@ importers:nanostores:specifier: ^0.9.3version: 0.9.3+ no-case:+ specifier: ^3.0.4+ version: 3.0.4+ title-case:+ specifier: ^3.0.3+ version: 3.0.3devDependencies:'@jest/globals':specifier: ^29.6.2