add command palette

This commit is contained in:
Gregor Vostrak
2026-01-27 18:29:40 +01:00
parent 3fb75ec3d5
commit 672c243c91
24 changed files with 2292 additions and 16 deletions

View File

@@ -0,0 +1,139 @@
<script setup lang="ts">
import { computed, watch } from 'vue';
import { DialogRoot, DialogPortal, DialogOverlay, DialogContent } from 'reka-ui';
import {
Command as CommandRoot,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from '../command';
import { cn } from '../utils/cn';
import type {
CommandPaletteCommand,
CommandPaletteGroup,
EntitySearchResult,
} from './CommandPaletteTypes';
const open = defineModel<boolean>('open', { required: true });
const searchTerm = defineModel<string>('searchTerm', { default: '' });
const props = withDefaults(
defineProps<{
groups: CommandPaletteGroup[];
entityResults?: EntitySearchResult[];
placeholder?: string;
}>(),
{
entityResults: () => [],
placeholder: 'Type a command or search...',
}
);
const emit = defineEmits<{
select: [command: CommandPaletteCommand | EntitySearchResult];
}>();
// Non-empty groups for rendering
const nonEmptyGroups = computed(() => props.groups.filter((g) => g.commands.length > 0));
const hasEntityResults = computed(() => (props.entityResults?.length ?? 0) > 0);
const hasAnyGroups = computed(() => nonEmptyGroups.value.length > 0);
// Handle command selection
async function handleSelect(cmd: CommandPaletteCommand | EntitySearchResult) {
emit('select', cmd);
await cmd.action();
}
// Reset search when dialog closes
watch(open, (isOpen) => {
if (!isOpen) {
searchTerm.value = '';
}
});
</script>
<template>
<DialogRoot v-model:open="open">
<DialogPortal>
<DialogOverlay
class="fixed inset-0 z-50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0">
<div class="absolute inset-0 bg-default-background opacity-30" />
</DialogOverlay>
<div
:class="
cn(
'fixed top-0 left-0 z-50 pointer-events-none w-screen h-screen flex items-start pt-6 md:pt-20 xl:pt-32 justify-center overflow-auto'
)
">
<DialogContent
class="pointer-events-auto bg-default-background w-full max-w-lg border border-border-tertiary shadow-lg sm:rounded-lg outline-none overflow-hidden p-0 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95">
<CommandRoot
v-model:search-term="searchTerm"
class="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
<CommandInput :placeholder="placeholder" />
<CommandList>
<!-- Empty state -->
<div
v-if="searchTerm.length > 0 && !hasEntityResults && !hasAnyGroups"
class="py-6 text-center text-sm text-muted-foreground">
No results found.
</div>
<!-- Command Groups -->
<template v-for="(group, index) in nonEmptyGroups" :key="group.id">
<CommandSeparator v-if="index > 0" />
<CommandGroup :heading="group.heading">
<CommandItem
v-for="cmd in group.commands"
:key="cmd.id"
:value="cmd.id"
class="cursor-pointer"
@select="handleSelect(cmd)">
<component :is="cmd.icon" v-if="cmd.icon" />
<span>{{ cmd.label }}</span>
<span class="sr-only" aria-hidden="true">{{
cmd.keywords.join(' ')
}}</span>
<CommandShortcut v-if="cmd.shortcut">
{{ cmd.shortcut }}
</CommandShortcut>
</CommandItem>
</CommandGroup>
</template>
<!-- Entity Search Results -->
<template v-if="hasEntityResults">
<CommandSeparator v-if="hasAnyGroups" />
<CommandGroup heading="Search Results">
<CommandItem
v-for="cmd in entityResults"
:key="cmd.id"
:value="cmd.id"
class="cursor-pointer"
@select="handleSelect(cmd)">
<component :is="cmd.icon" v-if="cmd.icon" />
<span class="flex-1">{{ cmd.label }}</span>
<span class="sr-only" aria-hidden="true">{{
cmd.keywords.join(' ')
}}</span>
<span
v-if="cmd.badgeClass"
class="ml-2 rounded px-1.5 py-0.5 text-xs font-medium"
:class="cmd.badgeClass">
{{ cmd.entityType }}
</span>
</CommandItem>
</CommandGroup>
</template>
</CommandList>
</CommandRoot>
</DialogContent>
</div>
</DialogPortal>
</DialogRoot>
</template>

View File

@@ -0,0 +1,23 @@
// Use `object` instead of Vue's `Component` to avoid type incompatibility
// between root and UI package Vue runtime-core copies in the monorepo.
// Vue's `<component :is="...">` accepts any object at runtime.
export interface CommandPaletteCommand {
id: string;
label: string;
icon?: object;
keywords: string[];
action: () => void | Promise<void>;
shortcut?: string;
}
export interface CommandPaletteGroup {
id: string;
heading: string;
commands: CommandPaletteCommand[];
}
export interface EntitySearchResult extends CommandPaletteCommand {
entityType: string;
color?: string;
badgeClass?: string;
}

View File

@@ -0,0 +1,6 @@
export { default as CommandPalette } from './CommandPalette.vue';
export type {
CommandPaletteCommand,
CommandPaletteGroup,
EntitySearchResult,
} from './CommandPaletteTypes';

View File

@@ -170,7 +170,8 @@ function onSelectChange(checked: boolean) {
<TimeTrackerStartStop
:active="!!(timeEntry.start && !timeEntry.end)"
class="opacity-20 flex group-hover:opacity-100 focus-visible:opacity-100"
variant="secondary"
class="opacity-60 flex group-hover:opacity-100 focus-visible:opacity-100"
@changed="onStartStopClick(timeEntry)"></TimeTrackerStartStop>
<TimeEntryMoreOptionsDropdown
:show-edit="false"

View File

@@ -0,0 +1,107 @@
<script setup lang="ts">
import type { ListboxRootEmits, ListboxRootProps } from 'reka-ui';
import type { HTMLAttributes } from 'vue';
import { reactiveOmit } from '@vueuse/core';
import { ListboxRoot, useFilter, useForwardPropsEmits } from 'reka-ui';
import { reactive, ref, watch } from 'vue';
import { cn } from '../utils/cn';
import { provideCommandContext } from '.';
const props = withDefaults(
defineProps<ListboxRootProps & { class?: HTMLAttributes['class']; searchTerm?: string }>(),
{
modelValue: '',
searchTerm: '',
}
);
const emits = defineEmits<ListboxRootEmits & { 'update:searchTerm': [value: string] }>();
const delegatedProps = reactiveOmit(props, 'class', 'searchTerm');
const forwarded = useForwardPropsEmits(delegatedProps, emits);
const allItems = ref<Map<string, string>>(new Map());
const allGroups = ref<Map<string, Set<string>>>(new Map());
const { contains } = useFilter({ sensitivity: 'base' });
const filterState = reactive({
search: props.searchTerm || '',
filtered: {
/** The count of all visible items. */
count: 0,
/** Map from visible item id to its search score. */
items: new Map() as Map<string, number>,
/** Set of groups with at least one visible item. */
groups: new Set() as Set<string>,
},
});
function filterItems() {
if (!filterState.search) {
filterState.filtered.count = allItems.value.size;
// Do nothing, each item will know to show itself because search is empty
return;
}
// Reset the groups
filterState.filtered.groups = new Set();
let itemCount = 0;
// Check which items should be included
for (const [id, value] of allItems.value) {
const score = contains(value, filterState.search);
filterState.filtered.items.set(id, score ? 1 : 0);
if (score) itemCount++;
}
// Check which groups have at least 1 item shown
for (const [groupId, group] of allGroups.value) {
for (const itemId of group) {
if (filterState.filtered.items.get(itemId)! > 0) {
filterState.filtered.groups.add(groupId);
break;
}
}
}
filterState.filtered.count = itemCount;
}
watch(
() => filterState.search,
(newSearch) => {
filterItems();
emits('update:searchTerm', newSearch);
}
);
// Sync external searchTerm prop changes to internal state
watch(
() => props.searchTerm,
(newTerm) => {
if (newTerm !== filterState.search) {
filterState.search = newTerm || '';
}
}
);
provideCommandContext({
allItems,
allGroups,
filterState,
});
</script>
<template>
<ListboxRoot
v-bind="forwarded"
:class="
cn(
'flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground',
props.class
)
">
<slot />
</ListboxRoot>
</template>

View File

@@ -0,0 +1,51 @@
<script setup lang="ts">
import type { ListboxGroupProps } from 'reka-ui';
import type { HTMLAttributes } from 'vue';
import { reactiveOmit } from '@vueuse/core';
import { ListboxGroup, ListboxGroupLabel, useId } from 'reka-ui';
import { computed, onMounted, onUnmounted } from 'vue';
import { cn } from '../utils/cn';
import { provideCommandGroupContext, useCommand } from '.';
const props = defineProps<
ListboxGroupProps & {
class?: HTMLAttributes['class'];
heading?: string;
}
>();
const delegatedProps = reactiveOmit(props, 'class');
const { allGroups, filterState } = useCommand();
const id = useId();
const isRender = computed(() => (!filterState.search ? true : filterState.filtered.groups.has(id)));
provideCommandGroupContext({ id });
onMounted(() => {
if (!allGroups.value.has(id)) allGroups.value.set(id, new Set());
});
onUnmounted(() => {
allGroups.value.delete(id);
});
</script>
<template>
<ListboxGroup
v-bind="delegatedProps"
:id="id"
:class="
cn(
'overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground',
props.class
)
"
:hidden="isRender ? undefined : true">
<ListboxGroupLabel
v-if="heading"
class="px-2 py-1.5 text-xs font-medium text-muted-foreground">
{{ heading }}
</ListboxGroupLabel>
<slot />
</ListboxGroup>
</template>

View File

@@ -0,0 +1,41 @@
<script setup lang="ts">
import type { ListboxFilterProps } from 'reka-ui';
import type { HTMLAttributes } from 'vue';
import { reactiveOmit } from '@vueuse/core';
import { Search } from 'lucide-vue-next';
import { ListboxFilter, useForwardProps } from 'reka-ui';
import { cn } from '../utils/cn';
import { useCommand } from '.';
defineOptions({
inheritAttrs: false,
});
const props = defineProps<
ListboxFilterProps & {
class?: HTMLAttributes['class'];
}
>();
const delegatedProps = reactiveOmit(props, 'class');
const forwardedProps = useForwardProps(delegatedProps);
const { filterState } = useCommand();
</script>
<template>
<div class="flex items-center border-b border-border-tertiary px-3" cmdk-input-wrapper>
<Search class="mr-1.5 h-4 w-4 shrink-0 opacity-50" />
<ListboxFilter
v-bind="{ ...forwardedProps, ...$attrs }"
v-model="filterState.search"
auto-focus
:class="
cn(
'flex h-10 w-full rounded-md bg-transparent py-3 text-sm border-none outline-none ring-0 focus:border-none focus:outline-none focus:ring-0 placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50',
props.class
)
" />
</div>
</template>

View File

@@ -0,0 +1,78 @@
<script setup lang="ts">
import type { ListboxItemEmits, ListboxItemProps } from 'reka-ui';
import type { HTMLAttributes } from 'vue';
import { reactiveOmit, useCurrentElement } from '@vueuse/core';
import { ListboxItem, useForwardPropsEmits, useId } from 'reka-ui';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { cn } from '../utils/cn';
import { useCommand, useCommandGroup } from '.';
const props = defineProps<ListboxItemProps & { class?: HTMLAttributes['class'] }>();
const emits = defineEmits<ListboxItemEmits>();
const delegatedProps = reactiveOmit(props, 'class');
const forwarded = useForwardPropsEmits(delegatedProps, emits);
const id = useId();
const { filterState, allItems, allGroups } = useCommand();
const groupContext = useCommandGroup();
const isRender = computed(() => {
if (!filterState.search) {
return true;
} else {
const filteredCurrentItem = filterState.filtered.items.get(id);
// If the filtered items is undefined means not in the all times map yet
// Do the first render to add into the map
if (filteredCurrentItem === undefined) {
return true;
}
// Check with filter
return filteredCurrentItem > 0;
}
});
const itemRef = ref();
const currentElement = useCurrentElement(itemRef);
onMounted(() => {
if (!(currentElement.value instanceof HTMLElement)) return;
// textValue to perform filter
allItems.value.set(id, currentElement.value.textContent ?? props?.value!.toString());
const groupId = groupContext?.id;
if (groupId) {
if (!allGroups.value.has(groupId)) {
allGroups.value.set(groupId, new Set([id]));
} else {
allGroups.value.get(groupId)?.add(id);
}
}
});
onUnmounted(() => {
allItems.value.delete(id);
});
</script>
<template>
<ListboxItem
v-if="isRender"
v-bind="forwarded"
:id="id"
ref="itemRef"
:class="
cn(
'relative flex cursor-default gap-1.5 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground [&_svg]:text-icon-default data-[highlighted]:[&_svg]:text-icon-active data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0',
props.class
)
"
@select="
() => {
filterState.search = '';
}
">
<slot />
</ListboxItem>
</template>

View File

@@ -0,0 +1,23 @@
<script setup lang="ts">
import type { ListboxContentProps } from 'reka-ui';
import type { HTMLAttributes } from 'vue';
import { reactiveOmit } from '@vueuse/core';
import { ListboxContent, useForwardProps } from 'reka-ui';
import { cn } from '../utils/cn';
const props = defineProps<ListboxContentProps & { class?: HTMLAttributes['class'] }>();
const delegatedProps = reactiveOmit(props, 'class');
const forwarded = useForwardProps(delegatedProps);
</script>
<template>
<ListboxContent
v-bind="forwarded"
:class="cn('max-h-[300px] overflow-y-auto overflow-x-hidden', props.class)">
<div role="presentation">
<slot />
</div>
</ListboxContent>
</template>

View File

@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { SeparatorProps } from 'reka-ui';
import type { HTMLAttributes } from 'vue';
import { reactiveOmit } from '@vueuse/core';
import { Separator } from 'reka-ui';
import { cn } from '../utils/cn';
const props = defineProps<SeparatorProps & { class?: HTMLAttributes['class'] }>();
const delegatedProps = reactiveOmit(props, 'class');
</script>
<template>
<Separator v-bind="delegatedProps" :class="cn('-mx-1 h-px bg-border', props.class)">
<slot />
</Separator>
</template>

View File

@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue';
import { cn } from '../utils/cn';
const props = defineProps<{
class?: HTMLAttributes['class'];
}>();
</script>
<template>
<span :class="cn('ml-auto text-xs tracking-widest text-muted-foreground', props.class)">
<slot />
</span>
</template>

View File

@@ -0,0 +1,27 @@
import type { Ref } from 'vue';
import { createContext } from 'reka-ui';
export { default as Command } from './Command.vue';
export { default as CommandGroup } from './CommandGroup.vue';
export { default as CommandInput } from './CommandInput.vue';
export { default as CommandItem } from './CommandItem.vue';
export { default as CommandList } from './CommandList.vue';
export { default as CommandSeparator } from './CommandSeparator.vue';
export { default as CommandShortcut } from './CommandShortcut.vue';
export const [useCommand, provideCommandContext] = createContext<{
allItems: Ref<Map<string, string>>;
allGroups: Ref<Map<string, Set<string>>>;
filterState: {
search: string;
filtered: {
count: number;
items: Map<string, number>;
groups: Set<string>;
};
};
}>('Command');
export const [useCommandGroup, provideCommandGroupContext] = createContext<{
id?: string;
}>('CommandGroup');

View File

@@ -43,7 +43,13 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './tool
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from './accordion/index';
import { Popover, PopoverContent, PopoverTrigger, PopoverAnchor } from './popover/index';
import { RangeCalendar } from './range-calendar/index';
import { CommandPalette } from './CommandPalette/index';
export type { ActivityPeriod } from './FullCalendar/idleStatusPlugin';
export type {
CommandPaletteCommand,
CommandPaletteGroup,
EntitySearchResult,
} from './CommandPalette/index';
export {
money,
@@ -89,4 +95,5 @@ export {
PopoverTrigger,
PopoverAnchor,
RangeCalendar,
CommandPalette,
};