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: Commands panel group items counter (#5534)

Oleg Isonenab2c085a9ad1
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 6d74bbd605..7b0243fcd1 100644
--- a/apps/builder/app/builder/features/command-panel/command-panel.tsx
+++ b/apps/builder/app/builder/features/command-panel/command-panel.tsx
@@ -18,6 +18,7 @@ import {
closeCommandPanel,
} from "./command-state";
import { $allOptions, groups, type Option } from "./groups";
+import { useAutoSelectFirstItem } from "./shared/auto-select";
const renderGroup = (type: Option["type"], matches: Option[]): JSX.Element => {
const Group = groups[type];
@@ -28,6 +29,8 @@ const renderGroup = (type: Option["type"], matches: Option[]): JSX.Element => {
const CommandDialogContent = () => {
const search = useStore($commandSearch);
const options = useStore($allOptions);
+ const listRef = useAutoSelectFirstItem(search);
+
let matches = options;
// prevent searching when value is empty
// to preserve original items order
@@ -42,6 +45,7 @@ const CommandDialogContent = () => {
matches,
(match) => match.type
);
+
return (
<>
<CommandInput
@@ -50,7 +54,7 @@ const CommandDialogContent = () => {
/>
<Flex direction="column" css={{ maxHeight: 300 }}>
<ScrollArea>
- <CommandList>
+ <CommandList ref={listRef}>
{Array.from(matchGroups).map(([type, matches]) =>
renderGroup(type, matches)
)}
diff --git a/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx b/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx
index 896ded0428..0dd3e8d484 100644
--- a/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx
@@ -70,8 +70,12 @@ export const BreakpointsGroup = ({
return (
<CommandGroup
name="breakpoint"
- heading={<CommandGroupHeading>Breakpoints</CommandGroupHeading>}
- actions={["select"]}
+ heading={
+ <CommandGroupHeading>
+ Breakpoints ({options.length})
+ </CommandGroupHeading>
+ }
+ actions={[{ name: "select", label: "Select" }]}
>
{options.map(({ breakpoint, keys }) => (
<CommandItem
diff --git a/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx b/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx
index 392efa4db3..7ab4ee023c 100644
--- a/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx
@@ -54,8 +54,10 @@ export const CommandsGroup = ({ options }: { options: CommandOption[] }) => {
return (
<CommandGroup
name="command"
- heading={<CommandGroupHeading>Commands</CommandGroupHeading>}
- actions={["execute"]}
+ heading={
+ <CommandGroupHeading>Commands ({options.length})</CommandGroupHeading>
+ }
+ actions={[{ name: "execute", label: "Execute" }]}
>
{options.map(({ name, label, keys, keepCommandPanelOpen }) => (
<CommandItem
diff --git a/apps/builder/app/builder/features/command-panel/groups/components-group.tsx b/apps/builder/app/builder/features/command-panel/groups/components-group.tsx
index e06e31c817..bdc2fffdb6 100644
--- a/apps/builder/app/builder/features/command-panel/groups/components-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/components-group.tsx
@@ -147,8 +147,10 @@ export const ComponentsGroup = ({
return (
<CommandGroup
name="component"
- heading={<CommandGroupHeading>Components</CommandGroupHeading>}
- actions={["add"]}
+ heading={
+ <CommandGroupHeading>Components ({options.length})</CommandGroupHeading>
+ }
+ actions={[{ name: "add", label: "Add" }]}
>
{options.map(({ component, label, category, icon, firstInstance }) => {
return (
diff --git a/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx b/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx
index 2e05c86e58..fd97c5f1ce 100644
--- a/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx
@@ -1,10 +1,11 @@
import {
CommandGroup,
- CommandGroupFooter,
CommandIcon,
CommandInput,
CommandItem,
CommandList,
+ CommandBackButton,
+ CommandFooter,
Flex,
ScrollArea,
Text,
@@ -30,7 +31,6 @@ import {
openCommandPanel,
} from "../command-state";
import { useState } from "react";
-import { BackButton } from "../shared/back-button";
import { convertInstance } from "~/shared/instance-utils";
type ConvertOption = {
@@ -126,19 +126,19 @@ const ConvertComponentsList = () => {
}
}
+ const goBack = () => {
+ $commandContent.set(undefined);
+ };
+
return (
<>
<CommandInput
- action="convert"
+ action={{ name: "convert", label: "Convert" }}
placeholder="Search components to convert..."
value={search}
onValueChange={setSearch}
- onKeyDown={(event) => {
- if (event.key === "Backspace" && search === "") {
- event.preventDefault();
- $commandContent.set(undefined);
- }
- }}
+ prefix={<CommandBackButton onClick={goBack} />}
+ onBack={goBack}
/>
<Flex direction="column" css={{ maxHeight: 300 }}>
<ScrollArea>
@@ -150,7 +150,10 @@ const ConvertComponentsList = () => {
</Text>
</Flex>
) : (
- <CommandGroup name="convert-components" actions={["convert"]}>
+ <CommandGroup
+ name="convert-components"
+ actions={[{ name: "convert", label: "Convert" }]}
+ >
{matches.map(({ component, tag, label }) => {
const key = tag ? `${component}:${tag}` : component;
return (
@@ -176,11 +179,7 @@ const ConvertComponentsList = () => {
</CommandList>
</ScrollArea>
</Flex>
- <CommandGroupFooter>
- <Flex grow>
- <BackButton />
- </Flex>
- </CommandGroupFooter>
+ <CommandFooter />
</>
);
};
diff --git a/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
index 7bb076d574..572bad1a2a 100644
--- a/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
@@ -100,8 +100,17 @@ export const CssVariablesGroup = ({
<>
<CommandGroup
name="cssVariable"
- heading={<CommandGroupHeading>CSS Variables</CommandGroupHeading>}
- actions={["select", "find usages", "rename", "delete"]}
+ heading={
+ <CommandGroupHeading>
+ CSS Variables ({options.length})
+ </CommandGroupHeading>
+ }
+ actions={[
+ { name: "select", label: "Select" },
+ { name: "findUsages", label: "Find usages" },
+ { name: "rename", label: "Rename" },
+ { name: "delete", label: "Delete" },
+ ]}
>
{options.map(({ property, instanceId, usages, terms }) => {
return (
@@ -111,19 +120,19 @@ export const CssVariablesGroup = ({
// preserve selected state when rerender
value={`${property}-${instanceId}`}
onSelect={() => {
- if (action === "select") {
+ if (action?.name === "select") {
showInstance(instanceId, "style");
closeCommandPanel();
}
- if (action === "find usages") {
+ if (action?.name === "findUsages") {
$commandContent.set(
<CssVariableInstances property={property} />
);
}
- if (action === "rename") {
+ if (action?.name === "rename") {
setVariableDialog({ action: "rename", property });
}
- if (action === "delete") {
+ if (action?.name === "delete") {
setVariableDialog({ action: "delete", property });
}
}}
diff --git a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
index 6c9c88a0e2..8e6b07ef14 100644
--- a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
@@ -102,8 +102,17 @@ export const DataVariablesGroup = ({
<>
<CommandGroup
name="dataVariable"
- heading={<CommandGroupHeading>Data variables</CommandGroupHeading>}
- actions={["select", "find usages", "rename", "delete"]}
+ heading={
+ <CommandGroupHeading>
+ Data variables ({options.length})
+ </CommandGroupHeading>
+ }
+ actions={[
+ { name: "select", label: "Select" },
+ { name: "findUsages", label: "Find usages" },
+ { name: "rename", label: "Rename" },
+ { name: "delete", label: "Delete" },
+ ]}
>
{options.map((option) => {
return (
@@ -112,19 +121,19 @@ export const DataVariablesGroup = ({
key={option.id}
value={option.id}
onSelect={() => {
- if (action === "select") {
+ if (action?.name === "select") {
showInstance(option.instanceId, "settings");
closeCommandPanel();
}
- if (action === "find usages") {
+ if (action?.name === "findUsages") {
$commandContent.set(
<DataVariableInstances variableId={option.id} />
);
}
- if (action === "rename") {
+ if (action?.name === "rename") {
setVariableDialog({ ...option, action: "rename" });
}
- if (action === "delete") {
+ if (action?.name === "delete") {
setVariableDialog({ ...option, action: "delete" });
}
}}
diff --git a/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx b/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx
index 6c16b33d29..3b1be32514 100644
--- a/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx
@@ -5,11 +5,11 @@ import { matchSorter } from "match-sorter";
import {
CommandGroup,
CommandGroupHeading,
- CommandGroupFooter,
CommandFooter,
CommandItem,
CommandInput,
CommandList,
+ CommandBackButton,
Text,
Flex,
ScrollArea,
@@ -34,7 +34,6 @@ import {
} from "../command-state";
import type { BaseOption } from "../shared/types";
import { formatUsageCount, getUsageSearchTerms } from "../shared/usage-utils";
-import { BackButton } from "../shared/back-button";
export type DuplicateTokenOption = BaseOption & {
type: "duplicateToken";
@@ -140,22 +139,22 @@ const DuplicateTokensList = ({
}
}
+ const goBack = () => {
+ // Go back to duplicate tokens view
+ $commandContentKey.set($commandContentKey.get() + 1);
+ $commandContent.set(
+ <DuplicateTokensGroup options={duplicateTokenOptions} />
+ );
+ };
+
return (
<>
<CommandInput
placeholder="Search duplicates..."
value={search}
onValueChange={(value) => setSearch(value)}
- onKeyDown={(event) => {
- if (event.key === "Backspace" && search === "") {
- event.preventDefault();
- // Go back to duplicate tokens view
- $commandContentKey.set($commandContentKey.get() + 1);
- $commandContent.set(
- <DuplicateTokensGroup options={duplicateTokenOptions} />
- );
- }
- }}
+ prefix={<CommandBackButton onClick={goBack} />}
+ onBack={goBack}
/>
<Flex direction="column" css={{ maxHeight: 300 }}>
<ScrollArea>
@@ -167,14 +166,17 @@ const DuplicateTokensList = ({
Duplicates of {tokenName}
</CommandGroupHeading>
}
- actions={["show duplicates", "show instances"]}
+ actions={[
+ { name: "show duplicates", label: "Show duplicates" },
+ { name: "show instances", label: "Show instances" },
+ ]}
>
{matches.map(({ id, token, usages: duplicateUsages }) => (
<CommandItem
key={id}
value={id}
onSelect={() => {
- if (action === "show duplicates" || !action) {
+ if (action?.name === "showDuplicates" || !action) {
// Show duplicates of this duplicate token
const allDuplicates = duplicateTokenOptions.find(
(opt) => opt.token.id === id
@@ -190,9 +192,9 @@ const DuplicateTokensList = ({
}
}
if (
- action === "show instances" ||
- action === "find instances" ||
- action === "find"
+ action?.name === "showInstances" ||
+ action?.name === "findInstances" ||
+ action?.name === "find"
) {
$commandContentKey.set($commandContentKey.get() + 1);
$commandContent.set(<TokenInstances tokenId={id} />);
@@ -211,20 +213,7 @@ const DuplicateTokensList = ({
</CommandList>
</ScrollArea>
</Flex>
- <CommandGroupFooter>
- <Flex align="center" justify="between" css={{ width: "100%" }}>
- <BackButton
- onClick={() => {
- // Go back to duplicate tokens view
- $commandContentKey.set($commandContentKey.get() + 1);
- $commandContent.set(
- <DuplicateTokensGroup options={duplicateTokenOptions} />
- );
- }}
- />
- <CommandFooter />
- </Flex>
- </CommandGroupFooter>
+ <CommandFooter />
</>
);
};
@@ -270,20 +259,20 @@ export const DuplicateTokensGroup = ({
}
}
+ const goBack = () => {
+ // Go back to main command panel
+ $commandContentKey.set($commandContentKey.get() + 1);
+ $commandContent.set(undefined);
+ };
+
return (
<>
<CommandInput
placeholder="Search duplicate tokens..."
value={search}
onValueChange={(value) => setSearch(value)}
- onKeyDown={(event) => {
- if (event.key === "Backspace" && search === "") {
- event.preventDefault();
- // Go back to main command panel
- $commandContentKey.set($commandContentKey.get() + 1);
- $commandContent.set(undefined);
- }
- }}
+ prefix={<CommandBackButton onClick={goBack} />}
+ onBack={goBack}
/>
<Flex direction="column" css={{ maxHeight: 300 }}>
<ScrollArea>
@@ -293,7 +282,10 @@ export const DuplicateTokensGroup = ({
heading={
<CommandGroupHeading>Duplicate tokens</CommandGroupHeading>
}
- actions={["show duplicates", "show instances"]}
+ actions={[
+ { name: "showDuplicates", label: "Show duplicates" },
+ { name: "showInstances", label: "Show instances" },
+ ]}
>
{matches.map(({ token, duplicates, usages }) => (
<CommandItem
@@ -301,7 +293,7 @@ export const DuplicateTokensGroup = ({
// preserve selected state when rerender
value={token.id}
onSelect={() => {
- if (action === "show duplicates" || !action) {
+ if (action?.name === "showDuplicates" || !action) {
$commandContentKey.set($commandContentKey.get() + 1);
$commandContent.set(
<DuplicateTokensList
@@ -311,9 +303,9 @@ export const DuplicateTokensGroup = ({
);
}
if (
- action === "show instances" ||
- action === "find instances" ||
- action === "find"
+ action?.name === "showInstances" ||
+ action?.name === "findInstances" ||
+ action?.name === "find"
) {
$commandContentKey.set($commandContentKey.get() + 1);
$commandContent.set(
@@ -335,18 +327,7 @@ export const DuplicateTokensGroup = ({
</CommandList>
</ScrollArea>
</Flex>
- <CommandGroupFooter>
- <Flex align="center" justify="between" css={{ width: "100%" }}>
- <BackButton
- onClick={() => {
- // Go back to main command panel
- $commandContentKey.set($commandContentKey.get() + 1);
- $commandContent.set(undefined);
- }}
- />
- <CommandFooter />
- </Flex>
- </CommandGroupFooter>
+ <CommandFooter />
</>
);
};
diff --git a/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx b/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx
index 1b6f4601d5..f6644ea962 100644
--- a/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx
@@ -3,6 +3,8 @@ import {
CommandGroupHeading,
CommandItem,
Text,
+ useCommandState,
+ useSetFooterContent,
} from "@webstudio-is/design-system";
import { computed } from "nanostores";
import { parseComponentName } from "@webstudio-is/sdk";
@@ -14,6 +16,8 @@ import { closeCommandPanel, $isCommandPanelOpen } from "../command-state";
import type { BaseOption } from "../shared/types";
import { setActiveSidebarPanel } from "~/builder/shared/nano-states";
import { humanizeString } from "~/shared/string-utils";
+import { useEffect } from "react";
+import { InstancePathFooter } from "../shared/instance-path-footer";
export type InstanceOption = BaseOption & {
type: "instance";
@@ -41,11 +45,24 @@ export const $instanceOptions = computed(
);
export const InstancesGroup = ({ options }: { options: InstanceOption[] }) => {
+ const highlightedValue = useCommandState((state) => state.value);
+ const setFooterContent = useSetFooterContent();
+
+ useEffect(() => {
+ setFooterContent(
+ highlightedValue ? (
+ <InstancePathFooter instanceId={highlightedValue} />
+ ) : undefined
+ );
+ }, [highlightedValue, setFooterContent]);
+
return (
<CommandGroup
name="instance"
- heading={<CommandGroupHeading>Instances</CommandGroupHeading>}
- actions={["select"]}
+ heading={
+ <CommandGroupHeading>Instances ({options.length})</CommandGroupHeading>
+ }
+ actions={[{ name: "select", label: "Select" }]}
>
{options.map(({ instance }) => {
const label = getInstanceLabel(instance);
diff --git a/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx b/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx
index 2a4ab10ba1..85a7c81a73 100644
--- a/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx
@@ -47,8 +47,13 @@ export const PagesGroup = ({ options }: { options: PageOption[] }) => {
return (
<CommandGroup
name="page"
- heading={<CommandGroupHeading>Pages</CommandGroupHeading>}
- actions={["select", "settings"]}
+ heading={
+ <CommandGroupHeading>Pages ({options.length})</CommandGroupHeading>
+ }
+ actions={[
+ { name: "select", label: "Select" },
+ { name: "settings", label: "Settings" },
+ ]}
>
{options.map(({ page }) => (
<CommandItem
@@ -57,12 +62,12 @@ export const PagesGroup = ({ options }: { options: PageOption[] }) => {
value={page.id}
onSelect={() => {
closeCommandPanel();
- if (action === "select") {
+ if (action?.name === "select") {
selectPage(page.id);
setActiveSidebarPanel("auto");
$editingPageId.set(undefined);
}
- if (action === "settings") {
+ if (action?.name === "settings") {
selectPage(page.id);
setActiveSidebarPanel("pages");
$editingPageId.set(page.id);
diff --git a/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
index e26a8ce183..b95a71d626 100644
--- a/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
@@ -81,8 +81,10 @@ export const TagsGroup = ({ options }: { options: TagOption[] }) => {
return (
<CommandGroup
name="tag"
- heading={<CommandGroupHeading>Tags</CommandGroupHeading>}
- actions={["add"]}
+ heading={
+ <CommandGroupHeading>Tags ({options.length})</CommandGroupHeading>
+ }
+ actions={[{ name: "add", label: "Add" }]}
>
{options.map(({ tag }) => {
return (
diff --git a/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
index 790fa339a8..1d292147b8 100644
--- a/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
@@ -97,8 +97,14 @@ export const TokensGroup = ({ options }: { options: TokenOption[] }) => {
<>
<CommandGroup
name="token"
- heading={<CommandGroupHeading>Tokens</CommandGroupHeading>}
- actions={["show instances", "rename", "delete"]}
+ heading={
+ <CommandGroupHeading>Tokens ({options.length})</CommandGroupHeading>
+ }
+ actions={[
+ { name: "showInstances", label: "Show instances" },
+ { name: "rename", label: "Rename" },
+ { name: "delete", label: "Delete" },
+ ]}
>
{options.map(({ token, usages }) => (
<CommandItem
@@ -107,16 +113,16 @@ export const TokensGroup = ({ options }: { options: TokenOption[] }) => {
value={token.id}
onSelect={() => {
if (
- action === "show instances" ||
- action === "find instances" ||
- action === "find"
+ action?.name === "showInstances" ||
+ action?.name === "findInstances" ||
+ action?.name === "find"
) {
$commandContent.set(<TokenInstances tokenId={token.id} />);
}
- if (action === "rename") {
+ if (action?.name === "rename") {
setTokenDialog({ ...token, action: "rename" });
}
- if (action === "delete") {
+ if (action?.name === "delete") {
setTokenDialog({ ...token, action: "delete" });
}
}}
diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx
index c5e028d0df..209f982c94 100644
--- a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx
@@ -1,10 +1,11 @@
import {
CommandGroup,
- CommandGroupFooter,
CommandIcon,
CommandInput,
CommandItem,
CommandList,
+ CommandBackButton,
+ CommandFooter,
Flex,
ScrollArea,
Text,
@@ -36,7 +37,6 @@ import {
openCommandPanel,
} from "../command-state";
import { useState } from "react";
-import { BackButton } from "../shared/back-button";
import { wrapInstance } from "~/shared/instance-utils";
type WrapOption = {
@@ -243,19 +243,19 @@ const WrapComponentsList = () => {
}
}
+ const goBack = () => {
+ $commandContent.set(undefined);
+ };
+
return (
<>
<CommandInput
- action="wrap"
+ action={{ name: "wrap", label: "Wrap" }}
placeholder="Search components to wrap with..."
value={search}
onValueChange={setSearch}
- onKeyDown={(event) => {
- if (event.key === "Backspace" && search === "") {
- event.preventDefault();
- $commandContent.set(undefined);
- }
- }}
+ prefix={<CommandBackButton onClick={goBack} />}
+ onBack={goBack}
/>
<Flex direction="column" css={{ maxHeight: 300 }}>
<ScrollArea>
@@ -267,7 +267,10 @@ const WrapComponentsList = () => {
</Text>
</Flex>
) : (
- <CommandGroup name="wrap-components" actions={["wrap"]}>
+ <CommandGroup
+ name="wrap-components"
+ actions={[{ name: "wrap", label: "Wrap" }]}
+ >
{matches.map(({ component, tag, label }) => {
const key = tag ? `${component}:${tag}` : component;
return (
@@ -293,11 +296,7 @@ const WrapComponentsList = () => {
</CommandList>
</ScrollArea>
</Flex>
- <CommandGroupFooter>
- <Flex grow>
- <BackButton />
- </Flex>
- </CommandGroupFooter>
+ <CommandFooter />
</>
);
};
diff --git a/apps/builder/app/builder/features/command-panel/shared/auto-select.ts b/apps/builder/app/builder/features/command-panel/shared/auto-select.ts
new file mode 100644
index 0000000000..4ed92b35c4
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/shared/auto-select.ts
@@ -0,0 +1,43 @@
+import { useEffect, useRef } from "react";
+
+/**
+ * Auto-selects the first item in a command list when search changes.
+ * Returns a ref that should be attached to the CommandList element.
+ *
+ * Note: This implementation uses keyboard event simulation as a workaround because cmdk
+ * doesn't expose an imperative API for programmatically highlighting items.
+ * The library is designed to work through keyboard/mouse interactions only.
+ */
+export const useAutoSelectFirstItem = (search: string) => {
+ const listRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!listRef.current) {
+ return;
+ }
+
+ requestAnimationFrame(() => {
+ const root = listRef.current?.closest("[cmdk-root]") as HTMLElement;
+ if (!root) {
+ return;
+ }
+
+ // Workaround: Simulate keyboard navigation to select the first item
+ // First press End to go to the last item (ensures we're in a known position)
+ const endEvent = new KeyboardEvent("keydown", {
+ key: "End",
+ bubbles: true,
+ });
+ root.dispatchEvent(endEvent);
+
+ // Then press Home to go to the first item
+ const homeEvent = new KeyboardEvent("keydown", {
+ key: "Home",
+ bubbles: true,
+ });
+ root.dispatchEvent(homeEvent);
+ });
+ }, [search]);
+
+ return listRef;
+};
diff --git a/apps/builder/app/builder/features/command-panel/shared/back-button.tsx b/apps/builder/app/builder/features/command-panel/shared/back-button.tsx
deleted file mode 100644
index 91672be209..0000000000
--- a/apps/builder/app/builder/features/command-panel/shared/back-button.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { Button, Kbd } from "@webstudio-is/design-system";
-import { $commandContent } from "../command-state";
-
-export const BackButton = ({ onClick }: { onClick?: () => void }) => {
- return (
- <Button
- tabIndex={-1}
- color="ghost"
- onClick={() => {
- if (onClick) {
- onClick();
- } else {
- $commandContent.set(undefined);
- }
- }}
- >
- <Kbd value={["backspace"]} /> Back
- </Button>
- );
-};
diff --git a/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx
index 936df196bd..36dac6710c 100644
--- a/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx
+++ b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx
@@ -2,27 +2,33 @@ import { useState } from "react";
import { matchSorter } from "match-sorter";
import {
CommandGroup,
- CommandGroupFooter,
+ CommandFooter,
CommandInput,
CommandItem,
CommandList,
+ CommandBackButton,
Flex,
ScrollArea,
Text,
+ useSelectedAction,
+ useCommandState,
} from "@webstudio-is/design-system";
import type { Instance } from "@webstudio-is/sdk";
import { $instances, $pages } from "~/shared/sync/data-stores";
import { getInstanceLabel } from "~/builder/shared/instance-label";
-import { $awareness, findAwarenessByInstanceId } from "~/shared/awareness";
import { buildInstancePath } from "~/shared/instance-utils";
-import { $commandContent } from "../command-state";
+import { $commandContent } from "~/builder/features/command-panel/command-state";
+import { findAwarenessByInstanceId } from "~/shared/awareness";
+import { $awareness } from "~/shared/awareness";
import { $activeInspectorPanel } from "~/builder/shared/nano-states";
-import { BackButton } from "./back-button";
+import { useAutoSelectFirstItem } from "./auto-select";
+import { InstancePathFooter } from "./instance-path-footer";
export type InstanceOption = {
label: string;
id: string;
path: string[];
+ pageName: string;
};
type InstanceListProps = {
@@ -38,6 +44,8 @@ export const InstanceList = ({
}: InstanceListProps) => {
const instances = $instances.get();
const pages = $pages.get();
+ const action = useSelectedAction();
+ const highlightedValue = useCommandState((state) => state.value);
const usedInInstances: InstanceOption[] = [];
for (const instanceId of instanceIds) {
const instance = instances.get(instanceId);
@@ -45,14 +53,19 @@ export const InstanceList = ({
continue;
}
const path = buildInstancePath(instanceId, pages, instances);
+ const awareness = findAwarenessByInstanceId(pages, instances, instanceId);
+ const page = pages.pages.find((p) => p.id === awareness.pageId);
usedInInstances.push({
label: getInstanceLabel(instance),
id: instance.id,
path,
+ pageName: page?.name ?? "",
});
}
const [search, setSearch] = useState("");
+ const listRef = useAutoSelectFirstItem(search);
+
const goBack = () => {
if (onBack) {
onBack();
@@ -72,45 +85,50 @@ export const InstanceList = ({
}
}
+ const selectedInstance = usedInInstances.find(
+ (instance) => instance.id === highlightedValue
+ );
+
return (
<>
<CommandInput
- action="select"
+ action={{ name: "select", label: "Select" }}
placeholder="Search instances..."
value={search}
onValueChange={setSearch}
- onKeyDown={(event) => {
- if (event.key === "Backspace" && search === "") {
- event.preventDefault();
- goBack();
- }
- }}
+ prefix={<CommandBackButton onClick={goBack} />}
+ onBack={goBack}
/>
<Flex direction="column" css={{ maxHeight: 300 }}>
<ScrollArea>
- <CommandList>
- <CommandGroup name="instance" actions={["select"]}>
+ <CommandList ref={listRef}>
+ <CommandGroup
+ name="instance"
+ actions={[
+ { name: "select", label: "Select" },
+ { name: "settings", label: "Settings" },
+ ]}
+ >
{matches.length === 0 ? (
<Flex justify="center" align="center" css={{ minHeight: 100 }}>
<Text color="subtle">No instances found</Text>
</Flex>
) : (
- matches.map(({ id, label, path }) => (
+ matches.map(({ id, label, pageName }) => (
<CommandItem
key={id}
value={id}
onSelect={() => {
- onSelect(id);
+ if (action?.name === "select" || !action) {
+ onSelect(id);
+ }
+ if (action?.name === "settings") {
+ showInstance(id, "settings");
+ }
}}
>
<Text>{label}</Text>
- <Text
- color="moreSubtle"
- truncate
- css={{ maxWidth: "30ch" }}
- >
- /{path.join("/")}
- </Text>
+ <Text color="moreSubtle">{pageName}</Text>
</CommandItem>
))
)}
@@ -118,11 +136,11 @@ export const InstanceList = ({
</CommandList>
</ScrollArea>
</Flex>
- <CommandGroupFooter>
- <Flex grow>
- <BackButton />
- </Flex>
- </CommandGroupFooter>
+ <CommandFooter>
+ {selectedInstance && (
+ <InstancePathFooter instanceId={selectedInstance.id} />
+ )}
+ </CommandFooter>
</>
);
};
diff --git a/apps/builder/app/builder/features/command-panel/shared/instance-path-footer.tsx b/apps/builder/app/builder/features/command-panel/shared/instance-path-footer.tsx
new file mode 100644
index 0000000000..285f9e5504
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/shared/instance-path-footer.tsx
@@ -0,0 +1,34 @@
+import { useMemo } from "react";
+import { useStore } from "@nanostores/react";
+import { Flex, Text } from "@webstudio-is/design-system";
+import type { Instance } from "@webstudio-is/sdk";
+import { $instances, $pages } from "~/shared/sync/data-stores";
+import { buildInstancePath } from "~/shared/instance-utils";
+
+type InstancePathFooterProps = {
+ instanceId: Instance["id"];
+};
+
+export const InstancePathFooter = ({ instanceId }: InstancePathFooterProps) => {
+ const instances = useStore($instances);
+ const pages = useStore($pages);
+
+ const path = useMemo(() => {
+ if (!pages || !instances || !instances.has(instanceId)) {
+ return;
+ }
+ return buildInstancePath(instanceId, pages, instances);
+ }, [instanceId, pages, instances]);
+
+ if (!path) {
+ return;
+ }
+
+ return (
+ <Flex grow>
+ <Text color="moreSubtle" truncate>
+ /{path.join("/")}
+ </Text>
+ </Flex>
+ );
+};
diff --git a/packages/design-system/src/components/command.stories.tsx b/packages/design-system/src/components/command.stories.tsx
index a2b2527a35..fabda3b3e4 100644
--- a/packages/design-system/src/components/command.stories.tsx
+++ b/packages/design-system/src/components/command.stories.tsx
@@ -28,7 +28,11 @@ const CommandContent = () => {
<CommandGroup
heading={<CommandGroupHeading>Suggestions</CommandGroupHeading>}
name="suggestions"
- actions={["select", "edit", "delete"]}
+ actions={[
+ { name: "select", label: "Select" },
+ { name: "edit", label: "Edit" },
+ { name: "delete", label: "Delete" },
+ ]}
>
<CommandItem>
<Flex gap={2}>
@@ -58,7 +62,7 @@ const CommandContent = () => {
<CommandGroup
heading={<CommandGroupHeading>Settings</CommandGroupHeading>}
name="settings"
- actions={["open"]}
+ actions={[{ name: "open", label: "Open" }]}
>
<CommandItem>
<Flex gap={2}>
diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsx
index 29ab51c6d3..b315220f2d 100644
--- a/packages/design-system/src/components/command.tsx
+++ b/packages/design-system/src/components/command.tsx
@@ -4,9 +4,12 @@ import {
useEffect,
useRef,
useState,
+ useCallback,
type ComponentPropsWithoutRef,
type Dispatch,
type SetStateAction,
+ type ComponentProps,
+ type ReactNode,
} from "react";
import {
Command as CommandPrimitive,
@@ -21,7 +24,7 @@ import {
DialogOverlay,
DialogContent,
} from "@radix-ui/react-dialog";
-import { SearchIcon } from "@webstudio-is/icons";
+import { SearchIcon, ChevronLeftIcon } from "@webstudio-is/icons";
import { styled, theme } from "../stitches.config";
import { Text, textVariants } from "./text";
import { Button } from "./button";
@@ -29,6 +32,8 @@ import { Popover, PopoverContent, PopoverTrigger } from "./popover";
import { Kbd } from "./kbd";
import { useDebounceEffect } from "../utilities";
import { Flex } from "./flex";
+import { InputField } from "./input-field";
+import { SmallIconButton } from "./small-icon-button";
const panelWidth = "500px";
const itemHeight = "32px";
@@ -64,10 +69,16 @@ const lowerCasedFilter: CommandProps["filter"] = (
aliases
);
+export type CommandAction = {
+ name: string;
+ label: string;
+};
+
type CommandState = {
highlightedGroup: string;
- actions: string[];
+ actions: CommandAction[];
actionIndex: number;
+ footerContent: ReactNode;
};
const CommandContext = createContext<
@@ -77,6 +88,7 @@ const CommandContext = createContext<
highlightedGroup: "",
actions: [],
actionIndex: 0,
+ footerContent: undefined,
},
() => {},
]);
@@ -93,11 +105,22 @@ export const useResetActionIndex = () => {
};
};
+const useSetFooterContent = () => {
+ const [, setState] = useContext(CommandContext);
+ return useCallback(
+ (content: ReactNode) => {
+ setState((prev) => ({ ...prev, footerContent: content }));
+ },
+ [setState]
+ );
+};
+
export const Command = (props: CommandProps) => {
const state = useState<CommandState>({
highlightedGroup: "",
actions: [],
actionIndex: 0,
+ footerContent: undefined,
});
return (
<CommandContext.Provider value={state}>
@@ -139,38 +162,32 @@ export const CommandDialog = ({
};
const CommandInputContainer = styled("div", {
- display: "grid",
- gridTemplateColumns: `${itemHeight} 1fr max-content`,
- height: theme.spacing[15],
borderBottom: `var(${inputBorderBottomSize}) solid ${theme.colors.borderMain}`,
});
-const CommandInputIcon = styled(SearchIcon, {
- gridColumn: "1 / 2",
- gridRow: "1 / 2",
- placeSelf: "center",
+export const CommandSearchIcon = styled(SearchIcon, {
+ display: "flex",
+ width: theme.spacing[11],
color: theme.colors.foregroundSubtle,
});
-const CommandInputField = styled(CommandPrimitive.Input, {
- all: "unset",
- gridColumn: "1 / 3",
- gridRow: "1 / 2",
- // add space for icon
- paddingLeft: itemHeight,
- paddingRight: theme.spacing[2],
- color: theme.colors.foregroundMain,
- ...textVariants.regular,
- lineHeight: 1,
- "&::placeholder": {
- color: theme.colors.foregroundSubtle,
- },
+export const CommandBackIcon = styled(ChevronLeftIcon, {
+ display: "flex",
+ width: theme.spacing[11],
+ color: theme.colors.foregroundSubtle,
+});
+
+const CommandInputField = styled(InputField, {
+ "--sizes-controlHeight": theme.spacing[15],
+ border: "none",
+ paddingInline: theme.spacing[4],
});
export const CommandInput = (
- props: ComponentPropsWithoutRef<typeof CommandPrimitive.Input> & {
- action?: string;
- placeholder?: string;
+ props: ComponentProps<typeof InputField> & {
+ action?: CommandAction;
+ onBack?: () => void;
+ onValueChange?: (value: string) => void;
}
) => {
const inputRef = useRef<HTMLInputElement>(null);
@@ -178,17 +195,40 @@ export const CommandInput = (
const {
action = contextAction,
placeholder = "Type a command or search...",
+ prefix,
+ onBack,
+ value,
+ onValueChange,
+ ref,
...inputProps
} = props;
return (
<CommandInputContainer>
- <CommandInputIcon />
<CommandInputField
- ref={inputRef}
+ prefix={prefix ?? <CommandSearchIcon />}
+ suffix={
+ action && (
+ <Text
+ color="moreSubtle"
+ css={{ alignSelf: "center", paddingInline: theme.spacing[5] }}
+ >
+ {action.label} <Kbd value={["enter"]} color="moreSubtle" />
+ </Text>
+ )
+ }
+ inputRef={inputRef}
autoFocus={true}
placeholder={placeholder}
+ value={value}
{...inputProps}
- onValueChange={(value) => {
+ onKeyDown={(event) => {
+ if (onBack && event.key === "Backspace" && value === "") {
+ event.preventDefault();
+ onBack();
+ }
+ inputProps.onKeyDown?.(event);
+ }}
+ onChange={(event) => {
// reset scroll whenever search is changed
requestAnimationFrame(() => {
inputRef.current
@@ -196,23 +236,16 @@ export const CommandInput = (
?.querySelector("[data-radix-scroll-area-viewport]")
?.scrollTo(0, 0);
});
- inputProps.onValueChange?.(value);
+ onValueChange?.(event.target.value);
}}
/>
- <Text
- variant="labelsTitleCase"
- color="moreSubtle"
- css={{ alignSelf: "center", paddingInline: theme.spacing[5] }}
- >
- {action} <Kbd value={["enter"]} color="moreSubtle" />
- </Text>
</CommandInputContainer>
);
};
const ActionsCommand = styled(CommandPrimitive, {});
-export const CommandFooter = () => {
+export const CommandFooter = ({ children }: { children?: ReactNode }) => {
const [isActionOpen, setIsActionOpen] = useState(false);
const scheduleEffect = useDebounceEffect();
@@ -227,14 +260,19 @@ export const CommandFooter = () => {
"[cmdk-group]:has([aria-selected=true])"
);
const highlightedGroup = selectedGroup?.getAttribute("data-value") ?? "";
- const actions =
- selectedGroup?.getAttribute("data-actions")?.split(",") ?? [];
+ const actionsJson = selectedGroup?.getAttribute("data-actions") ?? "[]";
+ let actions: CommandAction[] = [];
+ try {
+ actions = JSON.parse(actionsJson);
+ } catch {
+ // fallback to empty array if parsing fails
+ }
setState((prev) => {
// reset index only when group is changed
if (prev.highlightedGroup === highlightedGroup) {
return prev;
}
- return { highlightedGroup, actions, actionIndex: 0 };
+ return { ...prev, highlightedGroup, actions, actionIndex: 0 };
});
}, [highlightedValue, setState]);
@@ -259,6 +297,7 @@ export const CommandFooter = () => {
return (
<CommandGroupFooter ref={actionsRef}>
+ {children || state.footerContent}
<Popover open={isActionOpen} onOpenChange={setIsActionOpen}>
<PopoverTrigger asChild>
<Button tabIndex={-1} color="ghost" data-action-trigger>
@@ -284,7 +323,7 @@ export const CommandFooter = () => {
<CommandList data-action-list>
{state.actions.map((action, actionIndex) => (
<CommandItem
- key={action}
+ key={action.name}
allowSingleClick
onSelect={() => {
setState((prev) => ({ ...prev, actionIndex }));
@@ -301,7 +340,7 @@ export const CommandFooter = () => {
});
}}
>
- <Text variant="labelsTitleCase">{action}</Text>
+ <Text>{action.label}</Text>
</CommandItem>
))}
</CommandList>
@@ -324,7 +363,7 @@ type CommandGroupProps = Omit<
"value"
> & {
name: string;
- actions: string[];
+ actions: CommandAction[];
hideAfterItemsAmount?: number;
};
@@ -349,7 +388,7 @@ export const CommandGroup = ({
<CommandPrimitive.Group
{...props}
value={name}
- data-actions={actions.join()}
+ data-actions={JSON.stringify(actions)}
>
{
// Show items up to visibleCount
@@ -462,6 +501,18 @@ export const CommandGroupFooter = styled("div", {
borderTop: `1px solid ${theme.colors.borderMain}`,
});
+export const CommandBackButton = ({ onClick }: { onClick?: () => void }) => {
+ return (
+ <SmallIconButton
+ icon={<CommandBackIcon />}
+ tabIndex={-1}
+ onClick={onClick}
+ aria-label="Go back"
+ css={{ display: "flex" }}
+ />
+ );
+};
+
const CommandItemStyled = styled(CommandPrimitive.Item, {
display: "grid",
gridTemplateColumns: `1fr max-content`,
@@ -481,3 +532,5 @@ export const CommandIcon = styled("div", {
height: theme.spacing[9],
placeSelf: "center",
});
+
+export { useCommandState, useSetFooterContent };