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.

feat: Tokens management via commands & search (#4625)

Bogdan Chadkinb2b423c85cf7
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index 5248544ce3..3499033a6a 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -59,6 +59,7 @@ import { migrateWebstudioDataMutable } from "~/shared/webstudio-data-migrator";
import { Loading, LoadingBackground } from "./shared/loading";
import { mergeRefs } from "@react-aria/utils";
import { CommandPanel } from "./features/command-panel";
+import { DeleteUnusedTokensDialog } from "~/builder/shared/style-source-utils";
import {
initCopyPaste,
@@ -439,6 +440,7 @@ export const Builder = ({
<Loading state={loadingState} />
<BlockingAlerts />
<CommandPanel />
+ <DeleteUnusedTokensDialog />
<RemoteDialog />
</div>
</TooltipProvider>
diff --git a/apps/builder/app/builder/features/command-panel/command-panel.stories.tsx b/apps/builder/app/builder/features/command-panel/command-panel.stories.tsx
index 05cf40c31b..beed546440 100644
--- a/apps/builder/app/builder/features/command-panel/command-panel.stories.tsx
+++ b/apps/builder/app/builder/features/command-panel/command-panel.stories.tsx
@@ -10,10 +10,8 @@ import {
} from "~/shared/nano-states";
import { $awareness } from "~/shared/awareness";
import { registerContainers } from "~/shared/sync";
-import {
- CommandPanel as CommandPanelComponent,
- openCommandPanel,
-} from "./command-panel";
+import { CommandPanel as CommandPanelComponent } from "./command-panel";
+import { openCommandPanel } from "./command-state";
const meta: Meta = {
title: "Command Panel",
diff --git a/apps/builder/app/builder/features/command-panel/command-panel.tsx b/apps/builder/app/builder/features/command-panel/command-panel.tsx
index ee06e75949..6fc3c9e9c2 100644
--- a/apps/builder/app/builder/features/command-panel/command-panel.tsx
+++ b/apps/builder/app/builder/features/command-panel/command-panel.tsx
@@ -1,610 +1,125 @@
-import { atom, computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import { useState } from "react";
import { matchSorter } from "match-sorter";
import {
Command,
CommandDialog,
CommandInput,
CommandList,
- CommandGroup,
- CommandGroupHeading,
- CommandItem,
- CommandIcon,
- useSelectedAction,
ScrollArea,
Flex,
- Kbd,
- Text,
CommandFooter,
- Separator,
} from "@webstudio-is/design-system";
-import { compareMedia } from "@webstudio-is/css-engine";
-import {
- componentCategories,
- collectionComponent,
- elementComponent,
- tags,
-} from "@webstudio-is/sdk";
-import type { Breakpoint, Instance, Page } from "@webstudio-is/sdk";
-import type { TemplateMeta } from "@webstudio-is/template";
-import {
- $breakpoints,
- $editingPageId,
- $instances,
- $pages,
- $props,
- $registeredComponentMetas,
- $registeredTemplates,
- $selectedBreakpoint,
- $selectedBreakpointId,
-} from "~/shared/nano-states";
-import {
- getComponentTemplateData,
- insertWebstudioElementAt,
- insertWebstudioFragmentAt,
-} from "~/shared/instance-utils";
-import { humanizeString } from "~/shared/string-utils";
-import { setCanvasWidth } from "~/builder/features/breakpoints";
-import {
- $selectedInstancePath,
- $selectedPage,
- selectPage,
-} from "~/shared/awareness";
import { mapGroupBy } from "~/shared/shim";
-import { setActiveSidebarPanel } from "~/builder/shared/nano-states";
-import { $commandMetas } from "~/shared/commands-emitter";
-import { emitCommand } from "~/builder/shared/commands";
import {
- getInstanceLabel,
- InstanceIcon,
-} from "~/builder/shared/instance-label";
-import { isTreeSatisfyingContentModel } from "~/shared/content-model";
-
-const $commandPanel = atom<
- | undefined
- | {
- lastFocusedElement: null | HTMLElement;
- }
->();
-
-export const openCommandPanel = () => {
- const activeElement =
- document.activeElement instanceof HTMLElement
- ? document.activeElement
- : null;
- // store last focused element
- $commandPanel.set({
- lastFocusedElement: activeElement,
- });
-};
-
-const closeCommandPanel = ({
- restoreFocus = false,
-}: { restoreFocus?: boolean } = {}) => {
- const commandPanel = $commandPanel.get();
- $commandPanel.set(undefined);
- // restore focus in the next frame
- if (restoreFocus && commandPanel?.lastFocusedElement) {
- requestAnimationFrame(() => {
- commandPanel.lastFocusedElement?.focus();
- });
- }
-};
-
-type ComponentOption = {
- tokens: string[];
- type: "component";
- component: string;
- label: string;
- category: TemplateMeta["category"];
- icon: undefined | string;
- order: undefined | number;
- firstInstance: { component: string };
-};
-
-const getComponentScore = (meta: ComponentOption) => {
- const categoryScore = componentCategories.indexOf(meta.category ?? "hidden");
- const componentScore = meta.order ?? Number.MAX_SAFE_INTEGER;
- // shift category
- return categoryScore * 1000 + componentScore;
-};
-
-const $componentOptions = computed(
- [$registeredComponentMetas, $registeredTemplates, $selectedPage],
- (metas, templates, selectedPage) => {
- const componentOptions: ComponentOption[] = [];
- for (const [name, meta] of metas) {
- const category = meta.category ?? "hidden";
- if (category === "hidden" || category === "internal") {
- continue;
- }
-
- // show only xml category and collection component in xml documents
- if (selectedPage?.meta.documentType === "xml") {
- if (category !== "xml" && name !== collectionComponent) {
- continue;
- }
- } else {
- // show everything except xml category in html documents
- if (category === "xml") {
- continue;
- }
- }
- const label = getInstanceLabel({ component: name }, meta);
- componentOptions.push({
- tokens: ["components", label, category],
- type: "component",
- component: name,
- label,
- category,
- icon: meta.icon,
- order: meta.order,
- firstInstance: { component: name },
- });
- }
- for (const [name, meta] of templates) {
- if (meta.category === "hidden" || meta.category === "internal") {
- continue;
- }
-
- const componentMeta = metas.get(name);
- const label =
- meta.label ??
- componentMeta?.label ??
- getInstanceLabel({ component: name }, meta);
- componentOptions.push({
- tokens: ["components", label, meta.category],
- type: "component",
- component: name,
- label,
- category: meta.category,
- icon: meta.icon ?? componentMeta?.icon,
- order: meta.order,
- firstInstance: meta.template.instances[0],
- });
- }
- componentOptions.sort(
- (leftOption, rightOption) =>
- getComponentScore(leftOption) - getComponentScore(rightOption)
- );
- return componentOptions;
- }
-);
-
-const ComponentOptionsGroup = ({ options }: { options: ComponentOption[] }) => {
- return (
- <CommandGroup
- name="component"
- heading={<CommandGroupHeading>Components</CommandGroupHeading>}
- actions={["add"]}
- >
- {options.map(({ component, label, category, icon, firstInstance }) => {
- return (
- <CommandItem
- key={component}
- // preserve selected state when rerender
- value={component}
- onSelect={() => {
- closeCommandPanel();
- if (component === elementComponent) {
- insertWebstudioElementAt();
- } else {
- const fragment = getComponentTemplateData(component);
- if (fragment) {
- insertWebstudioFragmentAt(fragment);
- }
- }
- }}
- >
- <Flex gap={2}>
- <CommandIcon>
- <InstanceIcon instance={firstInstance} icon={icon} />
- </CommandIcon>
- <Text variant="labelsTitleCase">
- {label}{" "}
- <Text as="span" color="moreSubtle">
- {humanizeString(category)}
- </Text>
- </Text>
- </Flex>
- </CommandItem>
- );
- })}
- </CommandGroup>
- );
-};
-
-type TagOption = {
- tokens: string[];
- type: "tag";
- tag: string;
-};
-
-const $tagOptions = computed(
- [$selectedInstancePath, $instances, $props, $registeredComponentMetas],
- (instancePath, instances, props, metas) => {
- const tagOptions: TagOption[] = [];
- if (instancePath === undefined) {
- return tagOptions;
- }
- const [{ instance, instanceSelector }] = instancePath;
- const childInstance: Instance = {
- type: "instance",
- id: "new_instance",
- component: elementComponent,
- children: [],
- };
- const newInstances = new Map(instances);
- newInstances.set(childInstance.id, childInstance);
- newInstances.set(instance.id, {
- ...instance,
- // avoid preserving original children to not invalidate tag
- // when some descendants do not satisfy content model
- children: [{ type: "id", value: childInstance.id }],
- });
- for (const tag of tags) {
- childInstance.tag = tag;
- const isSatisfying = isTreeSatisfyingContentModel({
- instances: newInstances,
- props,
- metas,
- instanceSelector,
- });
- if (isSatisfying) {
- tagOptions.push({
- tokens: ["tags", tag, `<${tag}>`],
- type: "tag",
- tag,
- });
- }
- }
- return tagOptions;
- }
-);
-
-const TagOptionsGroup = ({ options }: { options: TagOption[] }) => {
- return (
- <CommandGroup
- name="tag"
- heading={<CommandGroupHeading>Tags</CommandGroupHeading>}
- actions={["add"]}
- >
- {options.map(({ tag }) => {
- return (
- <CommandItem
- key={tag}
- // preserve selected state when rerender
- value={tag}
- onSelect={() => {
- closeCommandPanel();
- const newInstance: Instance = {
- type: "instance",
- id: "new_instance",
- component: elementComponent,
- tag,
- children: [],
- };
- insertWebstudioFragmentAt({
- children: [{ type: "id", value: newInstance.id }],
- instances: [newInstance],
- props: [],
- dataSources: [],
- styleSourceSelections: [],
- styleSources: [],
- styles: [],
- breakpoints: [],
- assets: [],
- resources: [],
- });
- }}
- >
- <Flex gap={2}>
- <CommandIcon>
- <InstanceIcon instance={{ component: elementComponent, tag }} />
- </CommandIcon>
- <Text variant="labelsSentenceCase">{`<${tag}>`}</Text>
- </Flex>
- </CommandItem>
- );
- })}
- </CommandGroup>
- );
-};
-
-type BreakpointOption = {
- tokens: string[];
- type: "breakpoint";
- breakpoint: Breakpoint;
- shortcut: string;
-};
-
-const $breakpointOptions = computed(
- [$breakpoints, $selectedBreakpoint],
- (breakpoints, selectedBreakpoint) => {
- const sortedBreakpoints = Array.from(breakpoints.values()).sort(
- compareMedia
- );
- const breakpointOptions: BreakpointOption[] = [];
- for (let index = 0; index < sortedBreakpoints.length; index += 1) {
- const breakpoint = sortedBreakpoints[index];
- if (breakpoint.id === selectedBreakpoint?.id) {
- continue;
- }
- const width =
- (breakpoint.minWidth ?? breakpoint.maxWidth)?.toString() ?? "";
- breakpointOptions.push({
- tokens: ["breakpoints", breakpoint.label, width],
- type: "breakpoint",
- breakpoint,
- shortcut: (index + 1).toString(),
- });
- }
- return breakpointOptions;
- }
-);
-
-const getBreakpointLabel = (breakpoint: Breakpoint) => {
- let label = "All Sizes";
- if (breakpoint.minWidth !== undefined) {
- label = `≥ ${breakpoint.minWidth} PX`;
- }
- if (breakpoint.maxWidth !== undefined) {
- label = `≤ ${breakpoint.maxWidth} PX`;
- }
- return `${breakpoint.label}: ${label}`;
-};
-
-const BreakpointOptionsGroup = ({
- options,
-}: {
- options: BreakpointOption[];
-}) => {
- return (
- <CommandGroup
- name="breakpoint"
- heading={<CommandGroupHeading>Breakpoints</CommandGroupHeading>}
- actions={["select"]}
- >
- {options.map(({ breakpoint, shortcut }) => (
- <CommandItem
- key={breakpoint.id}
- // preserve selected state when rerender
- value={breakpoint.id}
- onSelect={() => {
- closeCommandPanel({ restoreFocus: true });
- $selectedBreakpointId.set(breakpoint.id);
- setCanvasWidth(breakpoint.id);
- }}
- >
- <Text variant="labelsTitleCase">
- {getBreakpointLabel(breakpoint)}
- </Text>
- <Kbd value={[shortcut]} />
- </CommandItem>
- ))}
- </CommandGroup>
- );
-};
-
-type PageOption = {
- tokens: string[];
- type: "page";
- page: Page;
-};
-
-const $pageOptions = computed(
- [$pages, $selectedPage],
- (pages, selectedPage) => {
- const pageOptions: PageOption[] = [];
- if (pages) {
- for (const page of [pages.homePage, ...pages.pages]) {
- if (page.id === selectedPage?.id) {
- continue;
- }
- pageOptions.push({
- tokens: ["pages", page.name],
- type: "page",
- page,
- });
- }
- }
- return pageOptions;
- }
-);
-
-const PageOptionsGroup = ({ options }: { options: PageOption[] }) => {
- const action = useSelectedAction();
- return (
- <CommandGroup
- name="page"
- heading={<CommandGroupHeading>Pages</CommandGroupHeading>}
- actions={["select", "settings"]}
- >
- {options.map(({ page }) => (
- <CommandItem
- key={page.id}
- // preserve selected state when rerender
- value={page.id}
- onSelect={() => {
- closeCommandPanel();
- if (action === "select") {
- selectPage(page.id);
- setActiveSidebarPanel("auto");
- $editingPageId.set(undefined);
- }
- if (action === "settings") {
- selectPage(page.id);
- setActiveSidebarPanel("pages");
- $editingPageId.set(page.id);
- }
- }}
- >
- <Text variant="labelsTitleCase">{page.name}</Text>
- </CommandItem>
- ))}
- </CommandGroup>
- );
-};
-
-type ShortcutOption = {
- tokens: string[];
- type: "shortcut";
- name: string;
- label: string;
- keys?: string[];
-};
-
-const $shortcutOptions = computed([$commandMetas], (commandMetas) => {
- const shortcutOptions: ShortcutOption[] = [];
- for (const [name, meta] of commandMetas) {
- if (!meta.hidden) {
- const label = meta.label ?? humanizeString(name);
- const keys = meta.defaultHotkeys?.[0]?.split("+");
- shortcutOptions.push({
- tokens: ["shortcuts", "commands", label],
- type: "shortcut",
- name,
- label,
- keys,
- });
- }
- }
- shortcutOptions.sort(
- (left, right) => (left.keys ? 0 : 1) - (right.keys ? 0 : 1)
- );
- return shortcutOptions;
-});
-
-const ShortcutOptionsGroup = ({ options }: { options: ShortcutOption[] }) => {
- return (
- <CommandGroup
- name="shortcut"
- heading={<CommandGroupHeading>Shortcuts</CommandGroupHeading>}
- actions={["execute"]}
- >
- {options.map(({ name, label, keys }) => (
- <CommandItem
- key={name}
- // preserve selected state when rerender
- value={name}
- onSelect={() => {
- closeCommandPanel();
- emitCommand(name as never);
- }}
- >
- <Text variant="labelsSentenceCase">{label}</Text>
- {keys && <Kbd value={keys} />}
- </CommandItem>
- ))}
- </CommandGroup>
- );
-};
-
-const $options = computed(
- [
- $componentOptions,
- $breakpointOptions,
- $pageOptions,
- $shortcutOptions,
- $tagOptions,
- ],
- (
- componentOptions,
- breakpointOptions,
- pageOptions,
- commandOptions,
- tagOptions
- ) => [
- ...componentOptions,
- ...breakpointOptions,
- ...pageOptions,
- ...commandOptions,
- ...tagOptions,
- ]
-);
+ $commandContent,
+ $isCommandPanelOpen,
+ $commandSearch,
+ closeCommandPanel,
+} from "./command-state";
+import {
+ $allOptions,
+ groups,
+ type ComponentOption,
+ type TagOption,
+ type BreakpointOption,
+ type PageOption,
+ type CommandOption,
+ type TokenOption,
+} from "./groups";
const CommandDialogContent = () => {
- const [search, setSearch] = useState("");
- const options = useStore($options);
+ const search = useStore($commandSearch);
+ const options = useStore($allOptions);
let matches = options;
// prevent searching when value is empty
// to preserve original items order
if (search.trim().length > 0) {
for (const word of search.trim().split(/\s+/)) {
matches = matchSorter(matches, word, {
- keys: ["tokens"],
+ keys: ["terms"],
});
}
}
- const groups = mapGroupBy(matches, (match) => match.type);
+ const matchGroups = mapGroupBy(matches, (match) => match.type);
return (
<>
- <CommandInput value={search} onValueChange={setSearch} />
+ <CommandInput
+ value={search}
+ onValueChange={(value) => $commandSearch.set(value)}
+ />
<Flex direction="column" css={{ maxHeight: 300 }}>
<ScrollArea>
<CommandList>
- {Array.from(groups).map(([group, matches]) => {
- if (group === "component") {
+ {Array.from(matchGroups).map(([groupType, matches]) => {
+ if (groupType === "component") {
return (
- <ComponentOptionsGroup
- key={group}
+ <groups.component
+ key={groupType}
options={matches as ComponentOption[]}
/>
);
}
- if (group === "tag") {
+ if (groupType === "tag") {
return (
- <TagOptionsGroup
- key={group}
+ <groups.tag
+ key={groupType}
options={matches as TagOption[]}
/>
);
}
- if (group === "breakpoint") {
+ if (groupType === "breakpoint") {
return (
- <BreakpointOptionsGroup
- key={group}
+ <groups.breakpoint
+ key={groupType}
options={matches as BreakpointOption[]}
/>
);
}
- if (group === "page") {
+ if (groupType === "page") {
return (
- <PageOptionsGroup
- key={group}
+ <groups.page
+ key={groupType}
options={matches as PageOption[]}
/>
);
}
- if (group === "shortcut") {
+ if (groupType === "command") {
return (
- <ShortcutOptionsGroup
- key={group}
- options={matches as ShortcutOption[]}
+ <groups.command
+ key={groupType}
+ options={matches as CommandOption[]}
/>
);
}
- group satisfies never;
+ if (groupType === "token") {
+ return (
+ <groups.token
+ key={groupType}
+ options={matches as TokenOption[]}
+ />
+ );
+ }
+ groupType satisfies never;
})}
</CommandList>
</ScrollArea>
</Flex>
- <Separator />
<CommandFooter />
</>
);
};
export const CommandPanel = () => {
- const isOpen = useStore($commandPanel) !== undefined;
+ const isOpen = useStore($isCommandPanelOpen);
+ const commandContent = useStore($commandContent);
+
return (
<CommandDialog
open={isOpen}
onOpenChange={() => closeCommandPanel({ restoreFocus: true })}
>
<Command shouldFilter={false}>
- <CommandDialogContent />
+ {commandContent ?? <CommandDialogContent />}
</Command>
</CommandDialog>
);
diff --git a/apps/builder/app/builder/features/command-panel/command-state.ts b/apps/builder/app/builder/features/command-panel/command-state.ts
new file mode 100644
index 0000000000..6779a45c69
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/command-state.ts
@@ -0,0 +1,44 @@
+import { atom, computed } from "nanostores";
+import type { ReactNode } from "react";
+
+const $commandPanel = atom<
+ | undefined
+ | {
+ lastFocusedElement: null | HTMLElement;
+ }
+>();
+
+export const $isCommandPanelOpen = computed(
+ $commandPanel,
+ (commandPanel) => commandPanel !== undefined
+);
+
+export const openCommandPanel = () => {
+ const activeElement =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null;
+ // store last focused element
+ $commandPanel.set({
+ lastFocusedElement: activeElement,
+ });
+};
+
+export const closeCommandPanel = ({
+ restoreFocus = false,
+}: { restoreFocus?: boolean } = {}) => {
+ const commandPanel = $commandPanel.get();
+ $commandPanel.set(undefined);
+ $commandContent.set(undefined);
+ $commandSearch.set("");
+ // restore focus in the next frame
+ if (restoreFocus && commandPanel?.lastFocusedElement) {
+ requestAnimationFrame(() => {
+ commandPanel.lastFocusedElement?.focus();
+ });
+ }
+};
+
+export const $commandContent = atom<ReactNode>();
+
+export const $commandSearch = atom("");
diff --git a/apps/builder/app/builder/features/command-panel/groups/breakpoint-group.tsx b/apps/builder/app/builder/features/command-panel/groups/breakpoint-group.tsx
new file mode 100644
index 0000000000..d9c8adb1f3
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/breakpoint-group.tsx
@@ -0,0 +1,92 @@
+import {
+ CommandGroup,
+ CommandGroupHeading,
+ CommandItem,
+ Text,
+ Kbd,
+} from "@webstudio-is/design-system";
+import { computed } from "nanostores";
+import { compareMedia } from "@webstudio-is/css-engine";
+import type { Breakpoint } from "@webstudio-is/sdk";
+import {
+ $breakpoints,
+ $selectedBreakpoint,
+ $selectedBreakpointId,
+} from "~/shared/nano-states";
+import { setCanvasWidth } from "~/builder/features/breakpoints";
+import { closeCommandPanel } from "../command-state";
+
+export type BreakpointOption = {
+ terms: string[];
+ type: "breakpoint";
+ breakpoint: Breakpoint;
+ shortcut: string;
+};
+
+export const $breakpointOptions = computed(
+ [$breakpoints, $selectedBreakpoint],
+ (breakpoints, selectedBreakpoint) => {
+ const sortedBreakpoints = Array.from(breakpoints.values()).sort(
+ compareMedia
+ );
+ const breakpointOptions: BreakpointOption[] = [];
+ for (let index = 0; index < sortedBreakpoints.length; index += 1) {
+ const breakpoint = sortedBreakpoints[index];
+ if (breakpoint.id === selectedBreakpoint?.id) {
+ continue;
+ }
+ const width =
+ (breakpoint.minWidth ?? breakpoint.maxWidth)?.toString() ?? "";
+ breakpointOptions.push({
+ terms: ["breakpoints", breakpoint.label, width],
+ type: "breakpoint",
+ breakpoint,
+ shortcut: (index + 1).toString(),
+ });
+ }
+ return breakpointOptions;
+ }
+);
+
+const getBreakpointLabel = (breakpoint: Breakpoint) => {
+ let label = "All Sizes";
+ if (breakpoint.minWidth !== undefined) {
+ label = `≥ ${breakpoint.minWidth} PX`;
+ }
+ if (breakpoint.maxWidth !== undefined) {
+ label = `≤ ${breakpoint.maxWidth} PX`;
+ }
+ return `${breakpoint.label}: ${label}`;
+};
+
+export const BreakpointGroup = ({
+ options,
+}: {
+ options: BreakpointOption[];
+}) => {
+ return (
+ <CommandGroup
+ name="breakpoint"
+ heading={<CommandGroupHeading>Breakpoints</CommandGroupHeading>}
+ actions={["select"]}
+ >
+ {options.map(({ breakpoint, shortcut }) => (
+ <CommandItem
+ key={breakpoint.id}
+ // preserve selected state when rerender
+ value={breakpoint.id}
+ onSelect={() => {
+ closeCommandPanel({ restoreFocus: true });
+ $selectedBreakpointId.set(breakpoint.id);
+ setCanvasWidth(breakpoint.id);
+ }}
+ >
+ <Text variant="labelsTitleCase">
+ {getBreakpointLabel(breakpoint)}
+ </Text>
+ <Kbd value={[shortcut]} />
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ );
+};
diff --git a/apps/builder/app/builder/features/command-panel/groups/command-group.tsx b/apps/builder/app/builder/features/command-panel/groups/command-group.tsx
new file mode 100644
index 0000000000..28fb13df84
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/command-group.tsx
@@ -0,0 +1,66 @@
+import {
+ CommandGroup,
+ CommandGroupHeading,
+ CommandItem,
+ Text,
+ Kbd,
+} from "@webstudio-is/design-system";
+import { computed } from "nanostores";
+import { $commandMetas } from "~/shared/commands-emitter";
+import { emitCommand } from "~/builder/shared/commands";
+import { humanizeString } from "~/shared/string-utils";
+import { closeCommandPanel } from "../command-state";
+
+export type CommandOption = {
+ terms: string[];
+ type: "command";
+ name: string;
+ label: string;
+ keys?: string[];
+};
+
+export const $commandOptions = computed([$commandMetas], (commandMetas) => {
+ const commandOptions: CommandOption[] = [];
+ for (const [name, meta] of commandMetas) {
+ if (!meta.hidden) {
+ const label = meta.label ?? humanizeString(name);
+ const keys = meta.defaultHotkeys?.[0]?.split("+");
+ commandOptions.push({
+ terms: ["shortcuts", "commands", label],
+ type: "command",
+ name,
+ label,
+ keys,
+ });
+ }
+ }
+ commandOptions.sort(
+ (left, right) => (left.keys ? 0 : 1) - (right.keys ? 0 : 1)
+ );
+ return commandOptions;
+});
+
+export const CommandsGroup = ({ options }: { options: CommandOption[] }) => {
+ return (
+ <CommandGroup
+ name="command"
+ heading={<CommandGroupHeading>Commands</CommandGroupHeading>}
+ actions={["execute"]}
+ >
+ {options.map(({ name, label, keys }) => (
+ <CommandItem
+ key={name}
+ // preserve selected state when rerender
+ value={name}
+ onSelect={() => {
+ closeCommandPanel();
+ emitCommand(name as never);
+ }}
+ >
+ <Text variant="labelsSentenceCase">{label}</Text>
+ {keys && <Kbd value={keys} />}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ );
+};
diff --git a/apps/builder/app/builder/features/command-panel/groups/component-group.tsx b/apps/builder/app/builder/features/command-panel/groups/component-group.tsx
new file mode 100644
index 0000000000..108ce3efd8
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/component-group.tsx
@@ -0,0 +1,154 @@
+import {
+ CommandGroup,
+ CommandGroupHeading,
+ CommandItem,
+ CommandIcon,
+ Flex,
+ Text,
+} from "@webstudio-is/design-system";
+import { computed } from "nanostores";
+import type { TemplateMeta } from "@webstudio-is/template";
+import {
+ componentCategories,
+ collectionComponent,
+ elementComponent,
+} from "@webstudio-is/sdk";
+import {
+ $registeredComponentMetas,
+ $registeredTemplates,
+} from "~/shared/nano-states";
+import {
+ getComponentTemplateData,
+ insertWebstudioElementAt,
+ insertWebstudioFragmentAt,
+} from "~/shared/instance-utils";
+import { humanizeString } from "~/shared/string-utils";
+import { $selectedPage } from "~/shared/awareness";
+import {
+ getInstanceLabel,
+ InstanceIcon,
+} from "~/builder/shared/instance-label";
+import { closeCommandPanel } from "../command-state";
+
+export type ComponentOption = {
+ terms: string[];
+ type: "component";
+ component: string;
+ label: string;
+ category: TemplateMeta["category"];
+ icon: undefined | string;
+ order: undefined | number;
+ firstInstance: { component: string };
+};
+
+const getComponentScore = (meta: ComponentOption) => {
+ const categoryScore = componentCategories.indexOf(meta.category ?? "hidden");
+ const componentScore = meta.order ?? Number.MAX_SAFE_INTEGER;
+ // shift category
+ return categoryScore * 1000 + componentScore;
+};
+
+export const $componentOptions = computed(
+ [$registeredComponentMetas, $registeredTemplates, $selectedPage],
+ (metas, templates, selectedPage) => {
+ const componentOptions: ComponentOption[] = [];
+ for (const [name, meta] of metas) {
+ const category = meta.category ?? "hidden";
+ if (category === "hidden" || category === "internal") {
+ continue;
+ }
+
+ // show only xml category and collection component in xml documents
+ if (selectedPage?.meta.documentType === "xml") {
+ if (category !== "xml" && name !== collectionComponent) {
+ continue;
+ }
+ } else {
+ // show everything except xml category in html documents
+ if (category === "xml") {
+ continue;
+ }
+ }
+ const label = getInstanceLabel({ component: name }, meta);
+ componentOptions.push({
+ terms: ["components", label, category],
+ type: "component",
+ component: name,
+ label,
+ category,
+ icon: meta.icon,
+ order: meta.order,
+ firstInstance: { component: name },
+ });
+ }
+ for (const [name, meta] of templates) {
+ if (meta.category === "hidden" || meta.category === "internal") {
+ continue;
+ }
+
+ const componentMeta = metas.get(name);
+ const label =
+ meta.label ??
+ componentMeta?.label ??
+ getInstanceLabel({ component: name }, meta);
+ componentOptions.push({
+ terms: ["components", label, meta.category],
+ type: "component",
+ component: name,
+ label,
+ category: meta.category,
+ icon: meta.icon ?? componentMeta?.icon,
+ order: meta.order,
+ firstInstance: meta.template.instances[0],
+ });
+ }
+ componentOptions.sort(
+ (leftOption, rightOption) =>
+ getComponentScore(leftOption) - getComponentScore(rightOption)
+ );
+ return componentOptions;
+ }
+);
+
+export const ComponentGroup = ({ options }: { options: ComponentOption[] }) => {
+ return (
+ <CommandGroup
+ name="component"
+ heading={<CommandGroupHeading>Components</CommandGroupHeading>}
+ actions={["add"]}
+ >
+ {options.map(({ component, label, category, icon, firstInstance }) => {
+ return (
+ <CommandItem
+ key={component}
+ // preserve selected state when rerender
+ value={component}
+ onSelect={() => {
+ closeCommandPanel();
+ if (component === elementComponent) {
+ insertWebstudioElementAt();
+ } else {
+ const fragment = getComponentTemplateData(component);
+ if (fragment) {
+ insertWebstudioFragmentAt(fragment);
+ }
+ }
+ }}
+ >
+ <Flex gap={2}>
+ <CommandIcon>
+ <InstanceIcon instance={firstInstance} icon={icon} />
+ </CommandIcon>
+ <Text variant="labelsTitleCase">
+ {label}{" "}
+ <Text as="span" color="moreSubtle">
+ {humanizeString(category)}
+ </Text>
+ </Text>
+ </Flex>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ );
+};
diff --git a/apps/builder/app/builder/features/command-panel/groups/index.ts b/apps/builder/app/builder/features/command-panel/groups/index.ts
new file mode 100644
index 0000000000..aabfc8d4c3
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/index.ts
@@ -0,0 +1,80 @@
+import { computed } from "nanostores";
+import {
+ $componentOptions,
+ ComponentGroup,
+ type ComponentOption,
+} from "./component-group";
+import { $tagOptions, TagGroup, type TagOption } from "./tag-group";
+import {
+ $breakpointOptions,
+ BreakpointGroup,
+ type BreakpointOption,
+} from "./breakpoint-group";
+import { $pageOptions, PageGroup, type PageOption } from "./page-group";
+import {
+ $commandOptions,
+ CommandsGroup,
+ type CommandOption,
+} from "./command-group";
+import { $tokenOptions, TokenGroup, type TokenOption } from "./token-group";
+
+export type Option =
+ | ComponentOption
+ | TagOption
+ | BreakpointOption
+ | PageOption
+ | CommandOption
+ | TokenOption;
+
+export const $allOptions = computed(
+ [
+ $componentOptions,
+ $tagOptions,
+ $breakpointOptions,
+ $pageOptions,
+ $commandOptions,
+ $tokenOptions,
+ ],
+ (
+ componentOptions,
+ tagOptions,
+ breakpointOptions,
+ pageOptions,
+ commandOptions,
+ tokenOptions
+ ) => [
+ ...componentOptions,
+ ...tagOptions,
+ ...breakpointOptions,
+ ...pageOptions,
+ ...commandOptions,
+ ...tokenOptions,
+ ]
+);
+
+export const groups = {
+ component: ComponentGroup,
+ tag: TagGroup,
+ breakpoint: BreakpointGroup,
+ page: PageGroup,
+ command: CommandsGroup,
+ token: TokenGroup,
+} as const;
+
+export type {
+ ComponentOption,
+ TagOption,
+ BreakpointOption,
+ PageOption,
+ CommandOption,
+ TokenOption,
+};
+
+export {
+ ComponentGroup,
+ TagGroup,
+ BreakpointGroup,
+ PageGroup,
+ CommandsGroup,
+ TokenGroup,
+};
diff --git a/apps/builder/app/builder/features/command-panel/groups/page-group.tsx b/apps/builder/app/builder/features/command-panel/groups/page-group.tsx
new file mode 100644
index 0000000000..2e9ef16c4a
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/page-group.tsx
@@ -0,0 +1,73 @@
+import {
+ CommandGroup,
+ CommandGroupHeading,
+ CommandItem,
+ Text,
+ useSelectedAction,
+} from "@webstudio-is/design-system";
+import { computed } from "nanostores";
+import type { Page } from "@webstudio-is/sdk";
+import { $pages, $editingPageId } from "~/shared/nano-states";
+import { $selectedPage, selectPage } from "~/shared/awareness";
+import { setActiveSidebarPanel } from "~/builder/shared/nano-states";
+import { closeCommandPanel } from "../command-state";
+
+export type PageOption = {
+ terms: string[];
+ type: "page";
+ page: Page;
+};
+
+export const $pageOptions = computed(
+ [$pages, $selectedPage],
+ (pages, selectedPage) => {
+ const pageOptions: PageOption[] = [];
+ if (pages) {
+ for (const page of [pages.homePage, ...pages.pages]) {
+ if (page.id === selectedPage?.id) {
+ continue;
+ }
+ pageOptions.push({
+ terms: ["pages", page.name],
+ type: "page",
+ page,
+ });
+ }
+ }
+ return pageOptions;
+ }
+);
+
+export const PageGroup = ({ options }: { options: PageOption[] }) => {
+ const action = useSelectedAction();
+ return (
+ <CommandGroup
+ name="page"
+ heading={<CommandGroupHeading>Pages</CommandGroupHeading>}
+ actions={["select", "settings"]}
+ >
+ {options.map(({ page }) => (
+ <CommandItem
+ key={page.id}
+ // preserve selected state when rerender
+ value={page.id}
+ onSelect={() => {
+ closeCommandPanel();
+ if (action === "select") {
+ selectPage(page.id);
+ setActiveSidebarPanel("auto");
+ $editingPageId.set(undefined);
+ }
+ if (action === "settings") {
+ selectPage(page.id);
+ setActiveSidebarPanel("pages");
+ $editingPageId.set(page.id);
+ }
+ }}
+ >
+ <Text variant="labelsTitleCase">{page.name}</Text>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ );
+};
diff --git a/apps/builder/app/builder/features/command-panel/groups/tag-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tag-group.tsx
new file mode 100644
index 0000000000..500ea8de55
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/tag-group.tsx
@@ -0,0 +1,118 @@
+import {
+ CommandGroup,
+ CommandGroupHeading,
+ CommandItem,
+ CommandIcon,
+ Flex,
+ Text,
+} from "@webstudio-is/design-system";
+import { computed } from "nanostores";
+import { elementComponent, tags } from "@webstudio-is/sdk";
+import type { Instance } from "@webstudio-is/sdk";
+import {
+ $instances,
+ $props,
+ $registeredComponentMetas,
+} from "~/shared/nano-states";
+import { insertWebstudioFragmentAt } from "~/shared/instance-utils";
+import { $selectedInstancePath } from "~/shared/awareness";
+import { InstanceIcon } from "~/builder/shared/instance-label";
+import { isTreeSatisfyingContentModel } from "~/shared/content-model";
+import { closeCommandPanel } from "../command-state";
+
+export type TagOption = {
+ terms: string[];
+ type: "tag";
+ tag: string;
+};
+
+export const $tagOptions = computed(
+ [$selectedInstancePath, $instances, $props, $registeredComponentMetas],
+ (instancePath, instances, props, metas) => {
+ const tagOptions: TagOption[] = [];
+ if (instancePath === undefined) {
+ return tagOptions;
+ }
+ const [{ instance, instanceSelector }] = instancePath;
+ const childInstance: Instance = {
+ type: "instance",
+ id: "new_instance",
+ component: elementComponent,
+ children: [],
+ };
+ const newInstances = new Map(instances);
+ newInstances.set(childInstance.id, childInstance);
+ newInstances.set(instance.id, {
+ ...instance,
+ // avoid preserving original children to not invalidate tag
+ // when some descendants do not satisfy content model
+ children: [{ type: "id", value: childInstance.id }],
+ });
+ for (const tag of tags) {
+ childInstance.tag = tag;
+ const isSatisfying = isTreeSatisfyingContentModel({
+ instances: newInstances,
+ props,
+ metas,
+ instanceSelector,
+ });
+ if (isSatisfying) {
+ tagOptions.push({
+ terms: ["tags", tag, `<${tag}>`],
+ type: "tag",
+ tag,
+ });
+ }
+ }
+ return tagOptions;
+ }
+);
+
+export const TagGroup = ({ options }: { options: TagOption[] }) => {
+ return (
+ <CommandGroup
+ name="tag"
+ heading={<CommandGroupHeading>Tags</CommandGroupHeading>}
+ actions={["add"]}
+ >
+ {options.map(({ tag }) => {
+ return (
+ <CommandItem
+ key={tag}
+ // preserve selected state when rerender
+ value={tag}
+ onSelect={() => {
+ closeCommandPanel();
+ const newInstance: Instance = {
+ type: "instance",
+ id: "new_instance",
+ component: elementComponent,
+ tag,
+ children: [],
+ };
+ insertWebstudioFragmentAt({
+ children: [{ type: "id", value: newInstance.id }],
+ instances: [newInstance],
+ props: [],
+ dataSources: [],
+ styleSourceSelections: [],
+ styleSources: [],
+ styles: [],
+ breakpoints: [],
+ assets: [],
+ resources: [],
+ });
+ }}
+ >
+ <Flex gap={2}>
+ <CommandIcon>
+ <InstanceIcon instance={{ component: elementComponent, tag }} />
+ </CommandIcon>
+ <Text variant="labelsSentenceCase">{`<${tag}>`}</Text>
+ </Flex>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ );
+};
diff --git a/apps/builder/app/builder/features/command-panel/groups/token-group.tsx b/apps/builder/app/builder/features/command-panel/groups/token-group.tsx
new file mode 100644
index 0000000000..c0665cc6f7
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/token-group.tsx
@@ -0,0 +1,280 @@
+import { useState } from "react";
+import { matchSorter } from "match-sorter";
+import { computed } from "nanostores";
+import { useStore } from "@nanostores/react";
+import {
+ CommandGroup,
+ CommandGroupHeading,
+ CommandGroupFooter,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ Flex,
+ ScrollArea,
+ Text,
+ toast,
+ useSelectedAction,
+ Button,
+ Kbd,
+} from "@webstudio-is/design-system";
+import type { Instance, Instances, StyleSource } from "@webstudio-is/sdk";
+import {
+ $instances,
+ $pages,
+ $registeredComponentMetas,
+ $selectedStyleSources,
+ $styleSources,
+} from "~/shared/nano-states";
+import {
+ deleteStyleSource,
+ DeleteStyleSourceDialog,
+ RenameStyleSourceDialog,
+ $styleSourceUsages,
+} from "~/builder/shared/style-source-utils";
+import { getInstanceLabel } from "~/builder/shared/instance-label";
+import type { InstanceSelector } from "~/shared/tree-utils";
+import { $awareness } from "~/shared/awareness";
+import { $commandContent, closeCommandPanel } from "../command-state";
+
+export type TokenOption = {
+ terms: string[];
+ type: "token";
+ token: Extract<StyleSource, { type: "token" }>;
+ usages: number;
+};
+
+export const $tokenOptions = computed(
+ [$styleSources, $styleSourceUsages],
+ (styleSources, styleSourceUsages) => {
+ const tokenOptions: TokenOption[] = [];
+ for (const styleSource of styleSources.values()) {
+ if (styleSource.type !== "token") {
+ continue;
+ }
+ tokenOptions.push({
+ terms: ["tokens", styleSource.name],
+ type: "token",
+ token: styleSource,
+ usages: styleSourceUsages.get(styleSource.id)?.size ?? 0,
+ });
+ }
+ return tokenOptions;
+ }
+);
+
+/**
+ * very loose selector finder
+ * will not work properly with collections
+ */
+const findInstanceById = (
+ instances: Instances,
+ instanceSelector: InstanceSelector,
+ targetId: Instance["id"]
+): undefined | InstanceSelector => {
+ const [instanceId] = instanceSelector;
+ if (instanceId === targetId) {
+ return instanceSelector;
+ }
+ const instance = instances.get(instanceId);
+ if (instance) {
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ const matched = findInstanceById(
+ instances,
+ [child.value, ...instanceSelector],
+ targetId
+ );
+ if (matched) {
+ return matched;
+ }
+ }
+ }
+ }
+};
+
+const selectToken = (
+ instanceId: Instance["id"],
+ tokenId: StyleSource["id"]
+) => {
+ const instances = $instances.get();
+ const pagesData = $pages.get();
+ if (pagesData === undefined) {
+ return;
+ }
+ const pages = [pagesData.homePage, ...pagesData.pages];
+ for (const page of pages) {
+ const instanceSelector = findInstanceById(
+ instances,
+ [page.rootInstanceId],
+ instanceId
+ );
+ if (instanceSelector) {
+ $awareness.set({ pageId: page.id, instanceSelector });
+ const selectedStyleSources = new Map($selectedStyleSources.get());
+ selectedStyleSources.set(instanceId, tokenId);
+ $selectedStyleSources.set(selectedStyleSources);
+ break;
+ }
+ }
+};
+
+type InstanceOption = {
+ label: string;
+ id: string;
+};
+
+const TokenInstances = ({ tokenId }: { tokenId: StyleSource["id"] }) => {
+ const usages = useStore($styleSourceUsages);
+ const usedInInstanceIds = usages.get(tokenId) ?? new Set();
+ const instances = $instances.get();
+ const metas = $registeredComponentMetas.get();
+ const usedInInstances: InstanceOption[] = [];
+ for (const instanceId of usedInInstanceIds) {
+ const instance = instances.get(instanceId);
+ const meta = metas.get(instance?.component ?? "");
+ if (instance && meta) {
+ usedInInstances.push({
+ label: getInstanceLabel(instance, meta),
+ id: instance.id,
+ });
+ }
+ }
+ const [search, setSearch] = useState("");
+
+ const goBack = () => {
+ $commandContent.set(undefined);
+ };
+
+ let matches = usedInInstances;
+ // prevent searching when value is empty
+ // to preserve original items order
+ if (search.trim().length > 0) {
+ for (const word of search.trim().split(/\s+/)) {
+ matches = matchSorter(matches, word, {
+ keys: ["label"],
+ });
+ }
+ }
+ return (
+ <>
+ <CommandInput
+ action="select"
+ value={search}
+ onValueChange={setSearch}
+ onKeyDown={(event) => {
+ if (event.key === "Backspace" && search === "") {
+ event.preventDefault();
+ goBack();
+ }
+ }}
+ />
+ <Flex direction="column" css={{ maxHeight: 300 }}>
+ <ScrollArea>
+ <CommandList>
+ <CommandGroup name="instance" actions={["select"]}>
+ {matches.length === 0 ? (
+ <Flex justify="center" align="center" css={{ minHeight: 100 }}>
+ <Text color="subtle">No instances found</Text>
+ </Flex>
+ ) : (
+ matches.map(({ id, label }) => (
+ <CommandItem
+ key={id}
+ // preserve selected state when rerender
+ value={id}
+ onSelect={() => {
+ selectToken(id, tokenId);
+ closeCommandPanel();
+ }}
+ >
+ <Text variant="labelsTitleCase">{label}</Text>
+ </CommandItem>
+ ))
+ )}
+ </CommandGroup>
+ </CommandList>
+ </ScrollArea>
+ </Flex>
+ <CommandGroupFooter>
+ <Flex grow>
+ <Button tabIndex={-1} color="ghost" onClick={goBack}>
+ Back <Kbd value={["backspace"]} />
+ </Button>
+ </Flex>
+ </CommandGroupFooter>
+ </>
+ );
+};
+
+export const TokenGroup = ({ options }: { options: TokenOption[] }) => {
+ const action = useSelectedAction();
+ const [tokenToRename, setTokenToRename] =
+ useState<Extract<StyleSource, { type: "token" }>>();
+ const [tokenToDelete, setTokenToDelete] =
+ useState<Extract<StyleSource, { type: "token" }>>();
+
+ return (
+ <>
+ <CommandGroup
+ name="token"
+ heading={<CommandGroupHeading>Tokens</CommandGroupHeading>}
+ actions={["find", "rename", "delete"]}
+ >
+ {options.map(({ token, usages }) => (
+ <CommandItem
+ key={token.id}
+ // preserve selected state when rerender
+ value={token.id}
+ onSelect={() => {
+ if (action === "find") {
+ if (usages > 0) {
+ $commandContent.set(<TokenInstances tokenId={token.id} />);
+ } else {
+ toast.error("Token is not used in any instance");
+ }
+ }
+ if (action === "rename") {
+ setTokenToRename(token);
+ }
+ if (action === "delete") {
+ setTokenToDelete(token);
+ }
+ }}
+ >
+ <Text variant="labelsTitleCase">
+ {token.name}{" "}
+ <Text as="span" color="moreSubtle">
+ {usages === 0
+ ? "unused"
+ : `${usages} ${usages === 1 ? "usage" : "usages"}`}
+ </Text>
+ </Text>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ <RenameStyleSourceDialog
+ styleSource={tokenToRename}
+ onClose={() => {
+ setTokenToRename(undefined);
+ }}
+ onConfirm={(_styleSourceId, newName) => {
+ toast.success(
+ `Token renamed from "${tokenToRename?.name}" to "${newName}"`
+ );
+ setTokenToRename(undefined);
+ }}
+ />
+ <DeleteStyleSourceDialog
+ styleSource={tokenToDelete}
+ onClose={() => {
+ setTokenToDelete(undefined);
+ }}
+ onConfirm={(styleSourceId) => {
+ deleteStyleSource(styleSourceId);
+ toast.success(`Token "${tokenToDelete?.name}" deleted`);
+ setTokenToDelete(undefined);
+ }}
+ />
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/features/command-panel/index.ts b/apps/builder/app/builder/features/command-panel/index.ts
index 9338251328..feaf2671b8 100644
--- a/apps/builder/app/builder/features/command-panel/index.ts
+++ b/apps/builder/app/builder/features/command-panel/index.ts
@@ -1 +1,2 @@
+export { openCommandPanel } from "./command-state";
export * from "./command-panel";
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.tsx
index 2fb316ab38..30f95a1cda 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
@@ -12,21 +12,13 @@ import {
type StyleSources,
getStyleDeclKey,
} from "@webstudio-is/sdk";
+import { type ItemSource, StyleSourceInput } from "./style-source";
import {
- Flex,
- Dialog,
- DialogContent,
- DialogTitle,
- DialogClose,
- Button,
- Text,
- theme,
-} from "@webstudio-is/design-system";
-import {
- type ItemSource,
- StyleSourceInput,
- type StyleSourceError,
-} from "./style-source";
+ renameStyleSource,
+ type RenameStyleSourceError,
+ deleteStyleSource,
+ DeleteStyleSourceDialog,
+} from "~/builder/shared/style-source-utils";
import {
$registeredComponentMetas,
$selectedInstanceStatesByStyleSourceId,
@@ -180,30 +172,6 @@ const removeStyleSourceFromInstance = (styleSourceId: StyleSource["id"]) => {
deselectMatchingStyleSource(styleSourceId);
};
-const deleteStyleSource = (styleSourceId: StyleSource["id"]) => {
- serverSyncStore.createTransaction(
- [$styleSources, $styleSourceSelections, $styles],
- (styleSources, styleSourceSelections, styles) => {
- styleSources.delete(styleSourceId);
- for (const styleSourceSelection of styleSourceSelections.values()) {
- if (styleSourceSelection.values.includes(styleSourceId)) {
- removeByMutable(
- styleSourceSelection.values,
- (item) => item === styleSourceId
- );
- }
- }
- for (const [styleDeclKey, styleDecl] of styles) {
- if (styleDecl.styleSourceId === styleSourceId) {
- styles.delete(styleDeclKey);
- }
- }
- }
- );
- // reset selected style source if necessary
- deselectMatchingStyleSource(styleSourceId);
-};
-
const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
const instanceId = $selectedInstance.get()?.id;
if (instanceId === undefined) {
@@ -292,31 +260,6 @@ const reorderStyleSources = (styleSourceIds: StyleSource["id"][]) => {
);
};
-const renameStyleSource = (
- id: StyleSource["id"],
- name: string
-): StyleSourceError | undefined => {
- const styleSources = $styleSources.get();
- if (name.trim().length === 0) {
- return { type: "minlength", id };
- }
- for (const styleSource of styleSources.values()) {
- if (
- styleSource.type === "token" &&
- styleSource.name === name &&
- styleSource.id !== id
- ) {
- return { type: "duplicate", id };
- }
- }
- serverSyncStore.createTransaction([$styleSources], (styleSources) => {
- const styleSource = styleSources.get(id);
- if (styleSource?.type === "token") {
- styleSource.name = name;
- }
- });
-};
-
const clearStyles = (styleSourceId: StyleSource["id"]) => {
serverSyncStore.createTransaction([$styles], (styles) => {
for (const [styleDeclKey, styleDecl] of styles) {
@@ -410,7 +353,7 @@ export const StyleSourcesSection = ({
const [editingItemId, setEditingItemId] = useState<StyleSource["id"]>();
const [tokenToDelete, setTokenToDelete] = useState<StyleSourceToken>();
- const [error, setError] = useState<StyleSourceError>();
+ const [error, setError] = useState<RenameStyleSourceError>();
const setEditingItem = (id?: StyleSource["id"]) => {
// User finished editing or started editing a different token
@@ -482,62 +425,16 @@ export const StyleSourcesSection = ({
setError(undefined);
}}
/>
- <DeleteConfirmationDialog
- token={tokenToDelete?.name}
+ <DeleteStyleSourceDialog
+ styleSource={tokenToDelete}
onClose={() => {
setTokenToDelete(undefined);
}}
- onConfirm={() => {
- if (tokenToDelete) {
- deleteStyleSource(tokenToDelete.id);
- }
+ onConfirm={(styleSourceId) => {
+ deleteStyleSource(styleSourceId);
+ setTokenToDelete(undefined);
}}
/>
</>
);
};
-
-type DeleteConfirmationDialogProps = {
- onClose: () => void;
- onConfirm: () => void;
- token?: string;
-};
-
-const DeleteConfirmationDialog = ({
- onClose,
- onConfirm,
- token,
-}: DeleteConfirmationDialogProps) => {
- return (
- <Dialog
- open={token !== undefined}
- onOpenChange={(isOpen) => {
- if (isOpen === false) {
- onClose();
- }
- }}
- >
- <DialogContent>
- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
- <Text>{`Delete "${token}" token from the project including all of its styles?`}</Text>
- <Flex direction="rowReverse" gap="2">
- <DialogClose>
- <Button
- color="destructive"
- onClick={() => {
- onConfirm();
- }}
- >
- Delete
- </Button>
- </DialogClose>
- <DialogClose>
- <Button color="ghost">Cancel</Button>
- </DialogClose>
- </Flex>
- </Flex>
- <DialogTitle>Delete confirmation</DialogTitle>
- </DialogContent>
- </Dialog>
- );
-};
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index bde845903b..061b6fb1ac 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -57,6 +57,7 @@ import { getInstanceLabel } from "./instance-label";
import { $instanceTags } from "../features/style-panel/shared/model";
import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";
import { isSyncIdle } from "./sync/sync-server";
+import { openDeleteUnusedTokensDialog } from "~/builder/shared/style-source-utils";
export const $styleSourceInputElement = atom<HTMLInputElement | undefined>();
@@ -659,5 +660,13 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
}
},
},
+
+ {
+ name: "deleteUnusedTokens",
+ label: "Delete unused tokens",
+ handler: () => {
+ openDeleteUnusedTokensDialog();
+ },
+ },
],
});
diff --git a/apps/builder/app/builder/shared/style-source-utils.tsx b/apps/builder/app/builder/shared/style-source-utils.tsx
new file mode 100644
index 0000000000..8a8f661516
--- /dev/null
+++ b/apps/builder/app/builder/shared/style-source-utils.tsx
@@ -0,0 +1,382 @@
+import { useState, useEffect } from "react";
+import { atom, computed } from "nanostores";
+import { useStore } from "@nanostores/react";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ DialogClose,
+ Button,
+ Text,
+ Flex,
+ theme,
+ InputField,
+ toast,
+} from "@webstudio-is/design-system";
+import type { Instance, StyleSource } from "@webstudio-is/sdk";
+import {
+ $styleSources,
+ $styleSourceSelections,
+ $styles,
+ $selectedStyleSources,
+ $selectedStyleState,
+} from "~/shared/nano-states";
+import { removeByMutable } from "~/shared/array-utils";
+import { serverSyncStore } from "~/shared/sync";
+import { $selectedInstance } from "~/shared/awareness";
+
+const $isDeleteUnusedTokensDialogOpen = atom(false);
+
+export const openDeleteUnusedTokensDialog = () => {
+ $isDeleteUnusedTokensDialogOpen.set(true);
+};
+
+export const $styleSourceUsages = computed(
+ $styleSourceSelections,
+ (styleSourceSelections) => {
+ const styleSourceUsages = new Map<StyleSource["id"], Set<Instance["id"]>>();
+ for (const { instanceId, values } of styleSourceSelections.values()) {
+ for (const styleSourceId of values) {
+ let usages = styleSourceUsages.get(styleSourceId);
+ if (usages === undefined) {
+ usages = new Set();
+ styleSourceUsages.set(styleSourceId, usages);
+ }
+ usages.add(instanceId);
+ }
+ }
+ return styleSourceUsages;
+ }
+);
+
+const deselectMatchingStyleSource = (styleSourceId: StyleSource["id"]) => {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
+ return;
+ }
+ const selectedStyleSources = new Map($selectedStyleSources.get());
+ if (selectedStyleSources.get(instanceId) === styleSourceId) {
+ selectedStyleSources.delete(instanceId);
+ $selectedStyleSources.set(selectedStyleSources);
+ $selectedStyleState.set(undefined);
+ }
+};
+
+export const deleteStyleSource = (styleSourceId: StyleSource["id"]) => {
+ serverSyncStore.createTransaction(
+ [$styleSources, $styleSourceSelections, $styles],
+ (styleSources, styleSourceSelections, styles) => {
+ styleSources.delete(styleSourceId);
+ for (const styleSourceSelection of styleSourceSelections.values()) {
+ if (styleSourceSelection.values.includes(styleSourceId)) {
+ removeByMutable(
+ styleSourceSelection.values,
+ (item) => item === styleSourceId
+ );
+ }
+ }
+ for (const [styleDeclKey, styleDecl] of styles) {
+ if (styleDecl.styleSourceId === styleSourceId) {
+ styles.delete(styleDeclKey);
+ }
+ }
+ }
+ );
+ // reset selected style source if necessary
+ deselectMatchingStyleSource(styleSourceId);
+};
+
+export const deleteUnusedTokens = () => {
+ const styleSources = $styleSources.get();
+ const styleSourceUsages = $styleSourceUsages.get();
+ const unusedTokenIds: StyleSource["id"][] = [];
+
+ for (const styleSource of styleSources.values()) {
+ if (styleSource.type === "token") {
+ const usages = styleSourceUsages.get(styleSource.id);
+ if (usages === undefined || usages.size === 0) {
+ unusedTokenIds.push(styleSource.id);
+ }
+ }
+ }
+
+ if (unusedTokenIds.length === 0) {
+ return 0;
+ }
+
+ serverSyncStore.createTransaction(
+ [$styleSources, $styleSourceSelections, $styles],
+ (styleSources, styleSourceSelections, styles) => {
+ for (const styleSourceId of unusedTokenIds) {
+ styleSources.delete(styleSourceId);
+ for (const styleSourceSelection of styleSourceSelections.values()) {
+ if (styleSourceSelection.values.includes(styleSourceId)) {
+ removeByMutable(
+ styleSourceSelection.values,
+ (item) => item === styleSourceId
+ );
+ }
+ }
+ for (const [styleDeclKey, styleDecl] of styles) {
+ if (styleDecl.styleSourceId === styleSourceId) {
+ styles.delete(styleDeclKey);
+ }
+ }
+ }
+ }
+ );
+
+ return unusedTokenIds.length;
+};
+
+export type RenameStyleSourceError =
+ | { type: "minlength"; id: StyleSource["id"] }
+ | { type: "duplicate"; id: StyleSource["id"] };
+
+export const renameStyleSource = (
+ id: StyleSource["id"],
+ name: string
+): RenameStyleSourceError | undefined => {
+ const styleSources = $styleSources.get();
+ if (name.trim().length === 0) {
+ return { type: "minlength", id };
+ }
+ for (const styleSource of styleSources.values()) {
+ if (
+ styleSource.type === "token" &&
+ styleSource.name === name &&
+ styleSource.id !== id
+ ) {
+ return { type: "duplicate", id };
+ }
+ }
+ serverSyncStore.createTransaction([$styleSources], (styleSources) => {
+ const styleSource = styleSources.get(id);
+ if (styleSource?.type === "token") {
+ styleSource.name = name;
+ }
+ });
+};
+
+type DeleteStyleSourceDialogProps = {
+ styleSource?: { id: StyleSource["id"]; name: string };
+ onClose: () => void;
+ onConfirm: (styleSourceId: StyleSource["id"]) => void;
+};
+
+export const DeleteStyleSourceDialog = ({
+ styleSource,
+ onClose,
+ onConfirm,
+}: DeleteStyleSourceDialogProps) => {
+ return (
+ <Dialog
+ open={styleSource !== undefined}
+ onOpenChange={(isOpen) => {
+ if (isOpen === false) {
+ onClose();
+ }
+ }}
+ >
+ <DialogContent
+ onKeyDown={(event) => {
+ // Prevent command panel from handling keyboard events
+ event.stopPropagation();
+ }}
+ >
+ <DialogTitle>Delete confirmation</DialogTitle>
+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
+ <Text>{`Delete "${styleSource?.name}" token from the project including all of its styles?`}</Text>
+ <Flex direction="rowReverse" gap="2">
+ <Button
+ color="destructive"
+ onClick={() => {
+ onConfirm(styleSource!.id);
+ onClose();
+ }}
+ >
+ Delete
+ </Button>
+ <DialogClose>
+ <Button color="ghost">Cancel</Button>
+ </DialogClose>
+ </Flex>
+ </Flex>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+type RenameStyleSourceDialogProps = {
+ styleSource?: { id: StyleSource["id"]; name: string };
+ onClose: () => void;
+ onConfirm: (styleSourceId: StyleSource["id"], newName: string) => void;
+};
+
+export const RenameStyleSourceDialog = ({
+ styleSource,
+ onClose,
+ onConfirm,
+}: RenameStyleSourceDialogProps) => {
+ const [name, setName] = useState("");
+ const [error, setError] = useState<string>();
+
+ // Reset name and clear error when styleSource changes
+ useEffect(() => {
+ if (styleSource?.name !== undefined) {
+ setName(styleSource.name);
+ setError(undefined);
+ }
+ }, [styleSource?.id, styleSource?.name]);
+
+ const handleConfirm = () => {
+ const renameError = renameStyleSource(styleSource!.id, name);
+ if (renameError) {
+ if (renameError.type === "minlength") {
+ setError("Token name cannot be empty");
+ } else if (renameError.type === "duplicate") {
+ setError("A token with this name already exists");
+ }
+ return;
+ }
+ onConfirm(styleSource!.id, name);
+ onClose();
+ };
+
+ return (
+ <Dialog
+ open={styleSource !== undefined}
+ onOpenChange={(isOpen) => {
+ if (isOpen === false) {
+ onClose();
+ }
+ }}
+ >
+ <DialogContent
+ onKeyDown={(event) => {
+ // Prevent command panel from handling keyboard events
+ event.stopPropagation();
+ if (event.key === "Enter" && !error) {
+ handleConfirm();
+ }
+ }}
+ >
+ <DialogTitle>Rename Token</DialogTitle>
+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
+ <Flex direction="column" gap="1">
+ <InputField
+ value={name}
+ onChange={(event) => {
+ setName(event.target.value);
+ setError(undefined);
+ }}
+ color={error ? "error" : undefined}
+ />
+ {error && (
+ <Text color="destructive" variant="monoBold">
+ {error}
+ </Text>
+ )}
+ </Flex>
+ <Flex direction="rowReverse" gap="2">
+ <Button color="primary" onClick={handleConfirm}>
+ Rename
+ </Button>
+ <DialogClose>
+ <Button color="ghost">Cancel</Button>
+ </DialogClose>
+ </Flex>
+ </Flex>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export const DeleteUnusedTokensDialog = () => {
+ const open = useStore($isDeleteUnusedTokensDialogOpen);
+ const styleSourceUsages = useStore($styleSourceUsages);
+ const styleSources = useStore($styleSources);
+
+ const handleClose = () => {
+ $isDeleteUnusedTokensDialogOpen.set(false);
+ };
+
+ const unusedTokens: Array<{ id: string; name: string }> = [];
+ for (const styleSource of styleSources.values()) {
+ if (styleSource.type === "token") {
+ const usages = styleSourceUsages.get(styleSource.id);
+ if (usages === undefined || usages.size === 0) {
+ unusedTokens.push({ id: styleSource.id, name: styleSource.name });
+ }
+ }
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(isOpen) => {
+ if (isOpen === false) {
+ handleClose();
+ }
+ }}
+ >
+ <DialogContent
+ onKeyDown={(event) => {
+ event.stopPropagation();
+ }}
+ >
+ <DialogTitle>Delete unused tokens</DialogTitle>
+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
+ {unusedTokens.length === 0 ? (
+ <Text>There are no unused tokens to delete.</Text>
+ ) : (
+ <>
+ <Text>
+ Delete {unusedTokens.length} unused{" "}
+ {unusedTokens.length === 1 ? "token" : "tokens"} from the
+ project?
+ </Text>
+ <Text
+ variant="mono"
+ css={{
+ maxHeight: 200,
+ overflowY: "auto",
+ backgroundColor: theme.colors.backgroundPanel,
+ borderRadius: theme.borderRadius[4],
+ wordBreak: "break-word",
+ }}
+ >
+ {unusedTokens.map((token) => token.name).join(", ")}
+ </Text>
+ </>
+ )}
+ <Flex direction="rowReverse" gap="2">
+ {unusedTokens.length > 0 && (
+ <Button
+ color="destructive"
+ onClick={() => {
+ const deletedCount = deleteUnusedTokens();
+ handleClose();
+ if (deletedCount === 0) {
+ toast.info("No unused tokens to delete");
+ } else {
+ toast.success(
+ `Deleted ${deletedCount} unused ${deletedCount === 1 ? "token" : "tokens"}`
+ );
+ }
+ }}
+ >
+ Delete
+ </Button>
+ )}
+ <DialogClose>
+ <Button color="ghost">
+ {unusedTokens.length > 0 ? "Cancel" : "Close"}
+ </Button>
+ </DialogClose>
+ </Flex>
+ </Flex>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsx
index 3d070df57d..50340e926e 100644
--- a/packages/design-system/src/components/command.tsx
+++ b/packages/design-system/src/components/command.tsx
@@ -25,7 +25,6 @@ import {
import { SearchIcon } from "@webstudio-is/icons";
import { styled, theme } from "../stitches.config";
import { Text, textVariants } from "./text";
-import { Flex } from "./flex";
import { Button } from "./button";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
import { Kbd } from "./kbd";
@@ -156,10 +155,13 @@ const CommandInputField = styled(CommandPrimitive.Input, {
});
export const CommandInput = (
- props: ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
+ props: ComponentPropsWithoutRef<typeof CommandPrimitive.Input> & {
+ action?: string;
+ }
) => {
const inputRef = useRef<HTMLInputElement>(null);
- const action = useSelectedAction();
+ const contextAction = useSelectedAction();
+ const { action = contextAction, ...inputProps } = props;
return (
<CommandInputContainer>
<CommandInputIcon />
@@ -167,7 +169,7 @@ export const CommandInput = (
ref={inputRef}
autoFocus={true}
placeholder="Type a command or search..."
- {...props}
+ {...inputProps}
onValueChange={(value) => {
// reset scroll whenever search is changed
requestAnimationFrame(() => {
@@ -176,7 +178,7 @@ export const CommandInput = (
?.querySelector("[data-radix-scroll-area-viewport]")
?.scrollTo(0, 0);
});
- props.onValueChange?.(value);
+ inputProps.onValueChange?.(value);
}}
/>
<Text
@@ -252,12 +254,7 @@ export const CommandFooter = () => {
}, [setState]);
return (
- <Flex
- justify="end"
- align="center"
- css={{ height: itemHeight, paddingInline: theme.spacing[3] }}
- ref={actionsRef}
- >
+ <CommandGroupFooter ref={actionsRef}>
<Popover open={isActionOpen} onOpenChange={setIsActionOpen}>
<PopoverTrigger asChild>
<Button tabIndex={-1} color="ghost" data-action-trigger>
@@ -306,7 +303,7 @@ export const CommandFooter = () => {
</ActionsCommand>
</PopoverContent>
</Popover>
- </Flex>
+ </CommandGroupFooter>
);
};
@@ -344,6 +341,18 @@ export const CommandGroupHeading = styled("div", {
height: itemHeight,
});
+export const CommandGroupFooter = styled("div", {
+ ...textVariants.titles,
+ color: theme.colors.foregroundMoreSubtle,
+ display: "flex",
+ gap: theme.spacing[5],
+ alignItems: "center",
+ paddingInline: theme.spacing[5],
+ height: itemHeight,
+ justifyContent: "end",
+ borderTop: `1px solid ${theme.colors.borderMain}`,
+});
+
export const CommandItem = styled(CommandPrimitive.Item, {
display: "grid",
gridTemplateColumns: `1fr max-content`,