Skip to content

feat(CommandPalette): add custom view [WIP] #4473

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: v3
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 169 additions & 5 deletions playground/app/pages/components/command-palette.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ const open = ref(false)
const searchTerm = ref('')
// const searchTermDebounced = refDebounced(searchTerm, 200)
const selected = ref([])
const commandPalette = useTemplateRef('commandPalette')

const { data: users, status } = await useFetch('https://jsonplaceholder.typicode.com/users', {
const { data: _users, status } = await useFetch('https://jsonplaceholder.typicode.com/users', {
// params: { q: searchTermDebounced },
transform: (data: User[]) => {
return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}` } })) || []
Expand All @@ -22,10 +23,6 @@ const { data: users, status } = await useFetch('https://jsonplaceholder.typicode
const loading = ref(false)

const groups = computed(() => [{
id: 'users',
label: searchTerm.value ? `Users matching β€œ${searchTerm.value}”...` : 'Users',
items: users.value || []
}, {
id: 'actions',
items: [{
label: 'Add new file',
Expand Down Expand Up @@ -74,6 +71,12 @@ const groups = computed(() => [{
toast.add({ title: 'Label added!' })
},
kbds: ['meta', 'L']
}, {
label: 'Set Wallpaper',
suffix: 'Choose from beautiful wallpaper collection.',
icon: 'i-lucide-image',
view: 'wallpaper',
placeholder: 'Search wallpapers...'
}, {
label: 'More actions',
placeholder: 'Search actions...',
Expand Down Expand Up @@ -140,20 +143,137 @@ const labels = [{
}]
const label = ref()

const wallpapers = [
{
id: 1,
name: 'red_distortion_1',
gradient: 'from-red-500 via-orange-500 to-pink-500',
category: 'Abstract',
featured: true
},
{
id: 2,
name: 'blue_distortion_1',
gradient: 'from-blue-600 via-purple-600 to-indigo-600',
category: 'Abstract',
featured: true
},
{
id: 3,
name: 'mono_dark_distortion_1',
gradient: 'from-gray-900 via-gray-700 to-gray-800',
category: 'Monochrome',
featured: false
},
{
id: 4,
name: 'chromatic_dark_1',
gradient: 'from-emerald-600 via-teal-600 to-cyan-600',
category: 'Chromatic',
featured: true
},
{
id: 5,
name: 'red_distortion_2',
gradient: 'from-rose-600 via-red-600 to-orange-600',
category: 'Abstract',
featured: false
},
{
id: 6,
name: 'purple_cosmic_1',
gradient: 'from-violet-700 via-purple-700 to-fuchsia-700',
category: 'Cosmic',
featured: true
},
{
id: 7,
name: 'golden_sunset_1',
gradient: 'from-yellow-500 via-orange-500 to-red-500',
category: 'Nature',
featured: false
},
{
id: 8,
name: 'ocean_deep_1',
gradient: 'from-blue-800 via-blue-900 to-indigo-900',
category: 'Nature',
featured: true
},
{
id: 9,
name: 'mono_light_distortion_1',
gradient: 'from-gray-200 via-gray-300 to-gray-400',
category: 'Monochrome',
featured: false
},
{
id: 10,
name: 'green_matrix_1',
gradient: 'from-green-800 via-emerald-700 to-teal-700',
category: 'Chromatic',
featured: false
},
{
id: 11,
name: 'pink_dreams_1',
gradient: 'from-pink-500 via-rose-500 to-purple-500',
category: 'Abstract',
featured: true
},
{
id: 12,
name: 'midnight_blue_1',
gradient: 'from-slate-900 via-blue-900 to-indigo-900',
category: 'Nature',
featured: false
}
]

const filteredWallpapers = computed(() => {
let filtered = wallpapers

// Filter by search term
if (searchTerm.value.trim()) {
const search = searchTerm.value.toLowerCase()
filtered = filtered.filter(w =>
w.name.toLowerCase().includes(search)
|| w.category.toLowerCase().includes(search)
)
}

return filtered
})

function setWallpaper(wallpaper: any) {
toast.add({
title: `Wallpaper set to ${wallpaper.name}!`,
description: 'Your desktop wallpaper has been updated.',
icon: 'i-lucide-image'
})
}

// function onSelect(item: typeof groups.value[number]['items'][number]) {
function onSelect(item: any) {
console.log('Selected', item)
}

defineShortcuts({
meta_k: () => open.value = !open.value,
meta_shift_a: {
usingInput: true,
handler: () => {
commandPalette.value?.openView('askAI')
}
},
...extractShortcuts(groups.value)
})
</script>

<template>
<DefineTemplate>
<UCommandPalette
ref="commandPalette"
v-model="selected"
v-model:search-term="searchTerm"
:loading="status === 'pending'"
Expand Down Expand Up @@ -186,6 +306,50 @@ defineShortcuts({
</div>
</div>
</template>

<template #wallpaper>
<div class="flex-1 overflow-y-auto p-6">
<div class="grid grid-cols-4 gap-4">
<div
v-for="wallpaper in filteredWallpapers"
:key="wallpaper.id"
class="group relative cursor-pointer"
@click="setWallpaper(wallpaper)"
>
<div
class="aspect-video rounded-lg bg-gradient-to-br shadow-lg ring-1 ring-black/5"
:class="wallpaper.gradient"
/>
<div class="mt-2 px-1">
<div class="flex items-center gap-2">
<h3 class="text-sm font-medium text-highlighted truncate">
{{ wallpaper.name }}
</h3>
<UChip
v-if="wallpaper.featured"
label="β˜…"
size="xs"
color="primary"
class="shrink-0"
/>
</div>
<p class="text-xs text-dimmed">
{{ wallpaper.category }}
</p>
</div>
</div>
</div>
</div>
</template>

<template #askAI>
<div class="flex flex-col items-center justify-center gap-4 p-6">
<UIcon name="i-lucide-sparkles" class="size-8 text-primary" />
<span class="text-lg font-semibold text-highlighted">
Ask me anything...
</span>
</div>
</template>
</UCommandPalette>
</DefineTemplate>

Expand Down
60 changes: 53 additions & 7 deletions src/runtime/components/CommandPalette.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export interface CommandPaletteItem extends Omit<LinkProps, 'type' | 'raw' | 'cu
*/
placeholder?: string
children?: CommandPaletteItem[]
/**
* Custom view to display instead of children items.
* When defined, clicking this item will show the custom view.
*/
view?: string
onSelect?(e?: Event): void
class?: any
ui?: Pick<CommandPalette['slots'], 'item' | 'itemLeadingIcon' | 'itemLeadingAvatarSize' | 'itemLeadingAvatar' | 'itemLeadingChipSize' | 'itemLeadingChip' | 'itemLabel' | 'itemLabelPrefix' | 'itemLabelBase' | 'itemLabelSuffix' | 'itemTrailing' | 'itemTrailingKbds' | 'itemTrailingKbdsSize' | 'itemTrailingHighlightedIcon' | 'itemTrailingIcon'>
Expand Down Expand Up @@ -154,7 +159,7 @@ export type CommandPaletteSlots<G extends CommandPaletteGroup<T> = CommandPalett
'item-leading': SlotProps<T>
'item-label': SlotProps<T>
'item-trailing': SlotProps<T>
} & Record<string, SlotProps<G>> & Record<string, SlotProps<T>>
} & Record<string, SlotProps<G>> & Record<string, SlotProps<T>> & Record<string, (props: { current: any, searchTerm: string, navigateBack: () => void, close: () => void }) => any>

</script>

Expand Down Expand Up @@ -209,12 +214,17 @@ const fuse = computed(() => defu({}, props.fuse, {
matchAllWhenSearchEmpty: true
}))

const history = ref<(CommandPaletteGroup & { placeholder?: string })[]>([])
const history = ref<(CommandPaletteGroup & { placeholder?: string, view?: string })[]>([])

const placeholder = computed(() => history.value[history.value.length - 1]?.placeholder || props.placeholder || t('commandPalette.placeholder'))

const groups = computed(() => history.value?.length ? [history.value[history.value.length - 1] as G] : props.groups)

const currentView = computed(() => {
const current = history.value[history.value.length - 1]
return current?.view ? current : null
})

const items = computed(() => groups.value?.filter((group) => {
if (!group.id) {
console.warn(`[@nuxt/ui] CommandPalette group is missing an \`id\` property`)
Expand Down Expand Up @@ -280,8 +290,33 @@ const filteredGroups = computed(() => {

const listboxRootRef = useTemplateRef('listboxRootRef')

// Exposed methods for programmatic control
function openView(viewName: string) {
history.value.push({
id: `view-${viewName}`,
label: viewName,
view: viewName,
items: []
} as any)

searchTerm.value = ''
listboxRootRef.value?.highlightFirstItem()
}

function closeView() {
if (history.value.length > 0) {
navigateBack()
}
}

defineExpose({
openView,
closeView,
navigateBack
})

function navigate(item: T) {
if (!item.children?.length) {
if (!item.children?.length && !item.view) {
return
}

Expand All @@ -290,7 +325,8 @@ function navigate(item: T) {
label: item.label,
slot: item.slot,
placeholder: item.placeholder,
items: item.children
view: item.view,
items: item.children || []
} as any)

searchTerm.value = ''
Expand All @@ -317,7 +353,7 @@ function onBackspace() {
}

function onSelect(e: Event, item: T) {
if (item.children?.length) {
if (item.children?.length || item.view) {
e.preventDefault()

navigate(item)
Expand Down Expand Up @@ -372,7 +408,17 @@ function onSelect(e: Event, item: T) {
</ListboxFilter>

<ListboxContent :class="ui.content({ class: props.ui?.content })">
<div v-if="filteredGroups?.length" role="presentation" :class="ui.viewport({ class: props.ui?.viewport })">
<div v-if="currentView" :class="ui.viewport({ class: props.ui?.viewport })">
<slot
:name="currentView.view"
:current="currentView"
:search-term="searchTerm"
:navigate-back="navigateBack"
:close="closeView"
/>
</div>

<div v-else-if="filteredGroups?.length" role="presentation" :class="ui.viewport({ class: props.ui?.viewport })">
<ListboxGroup v-for="group in filteredGroups" :key="`group-${group.id}`" :class="ui.group({ class: props.ui?.group })">
<ListboxGroupLabel v-if="get(group, props.labelKey as string)" :class="ui.label({ class: props.ui?.label })">
{{ get(group, props.labelKey as string) }}
Expand Down Expand Up @@ -416,7 +462,7 @@ function onSelect(e: Event, item: T) {
<span :class="ui.itemTrailing({ class: [props.ui?.itemTrailing, item.ui?.itemTrailing] })">
<slot :name="((item.slot ? `${item.slot}-trailing` : group.slot ? `${group.slot}-trailing` : `item-trailing`) as keyof CommandPaletteSlots<G, T>)" :item="(item as any)" :index="index">
<UIcon
v-if="item.children && item.children.length > 0"
v-if="(item.children && item.children.length > 0) || item.view"
:name="trailingIcon || appConfig.ui.icons.chevronRight"
:class="ui.itemTrailingIcon({ class: [props.ui?.itemTrailingIcon, item.ui?.itemTrailingIcon] })"
/>
Expand Down
Loading