Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Improve the Dashboard Command+K menu (#14465)
Damian Legawiecba21b97e0e1c
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex ac87adcf82..4017bdc989 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -59,6 +59,7 @@ export * from './hooks/use-host-form'export * from './hooks/use-import'export * from './hooks/use-resource-mutation'export * from './hooks/use-switch-admin-locale'+export * from './lib/create-action-registry'// ---------------------------------------------------------------------------// Registries — pluggable extension points (nav, route, slot, table,// settings-nav, form fields, custom field components)diff --git a/packages/dashboard-core/src/lib/create-action-registry.ts b/packages/dashboard-core/src/lib/create-action-registry.tsnew file mode 100644index 0000000000..1cf0f65f6b--- /dev/null+++ b/packages/dashboard-core/src/lib/create-action-registry.ts@@ -0,0 +1,278 @@+import type { LucideIcon } from 'lucide-react'+import { useSyncExternalStore } from 'react'+import type { SubjectName } from './permissions'++/**+ * Registry for the command palette's create actions — the rows that turn+ * "add product" or "new order" into a jump to the matching create page.+ *+ * Mirrors `search-registry.ts` and `nav-registry.ts`: a module-singleton+ * populated at app boot by side-effect modules, read reactively via+ * `useCreateActions`. Plugins register their own create pages the same way.+ *+ * Matching is a concern of `matchCreateActions` below, not of the entry: an+ * entry only declares what it is called and where it goes.+ */++export interface CreateActionEntry {+ /** Stable identifier — register/remove key, React key, and result-value prefix. */+ key: string+ /**+ * i18n key for the singular resource noun, as the merchant would type it+ * ("Product", "Customer"). Resolved with `t` at match time so typing the+ * noun works in the merchant's own language.+ */+ labelKey: string+ /**+ * Extra i18n keys for words that should also match this action — plurals,+ * synonyms, and abbreviations ("SKU" for a product). Optional.+ */+ aliasKeys?: string[]+ /** Row icon. */+ icon?: LucideIcon+ /** CanCanCan subject gating the action. Checked with `create`, not `read`. */+ subject?: SubjectName+ /** Lower numbers render first among equally-good matches. */+ position?: number+ /**+ * Destination, given the active store. Either a dedicated create route+ * (`/${storeId}/products/new`) or an index page with the create sheet open+ * (`/${storeId}/customers?new=true`).+ */+ getRoute: (storeId: string) => { to: string; search?: Record<string, unknown> }+}++interface CreateActionMutator {+ /** Register an action. Throws if the key is already registered. */+ add(entry: CreateActionEntry): void+ /** Remove an action by key. No-op when missing. */+ remove(key: string): void+ /** Patch an existing action. Throws if the key is missing. */+ update(key: string, patch: Partial<Omit<CreateActionEntry, 'key'>>): void+}++const entries: CreateActionEntry[] = []+const listeners = new Set<() => void>()+let snapshotCache: CreateActionEntry[] | null = null++function notify() {+ snapshotCache = null+ for (const l of listeners) l()+}++/**+ * The create-action registry. Every mutation notifies subscribers, so a page+ * rendered through `useCreateActions` reflects it immediately — which is how a+ * plugin can register its create pages after the app has booted.+ *+ * `add` throws on a duplicate key and `update` throws on an unknown one, so a+ * plugin colliding with a built-in fails loudly instead of silently shadowing+ * it. `remove` is tolerant, letting teardown run unconditionally.+ */+export const createActionRegistry: CreateActionMutator = {+ add(entry) {+ if (entries.some((e) => e.key === entry.key)) {+ throw new Error(+ `Create action "${entry.key}" already registered. Use createActionRegistry.update().`,+ )+ }+ entries.push(entry)+ notify()+ },+ remove(key) {+ const i = entries.findIndex((e) => e.key === key)+ if (i === -1) return+ entries.splice(i, 1)+ notify()+ },+ update(key, patch) {+ const e = entries.find((x) => x.key === key)+ if (!e) throw new Error(`Create action "${key}" not found.`)+ Object.assign(e, patch)+ notify()+ },+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener)+ return () => {+ listeners.delete(listener)+ }+}++function getSnapshot(): CreateActionEntry[] {+ if (!snapshotCache) {+ snapshotCache = [...entries].sort((a, b) => (a.position ?? 100) - (b.position ?? 100))+ }+ return snapshotCache+}++/** Reactively read the sorted create actions. Re-renders on registry mutation. */+export function useCreateActions(): CreateActionEntry[] {+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)+}++/** Test-only: clear the registry. */+export function __resetCreateActionRegistry(): void {+ entries.length = 0+ notify()+}++// ---------------------------------------------------------------------------+// Matching+// ---------------------------------------------------------------------------++/**+ * i18n key holding the create verbs for the active language, as a+ * comma-separated list ("add,new,create"). A list rather than one word because+ * merchants reach for whichever verb comes to mind, and several languages have+ * more than one natural phrasing.+ */+export const CREATE_VERBS_KEY = 'admin.components.command_palette.create.verbs'++export interface CreateActionMatch {+ entry: CreateActionEntry+ /** The resolved noun that matched, for rendering the row's label. */+ noun: string+ /** Lower sorts first: an exact noun match beats a prefix beats a substring. */+ rank: number+}++/**+ * Scripts written without spaces between words. Restricting the unspaced verb+ * match to these keeps it from firing on space-delimited languages, where+ * "address" would otherwise read as the verb "add" plus a noun "ress".+ */+const UNSPACED_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u++/**+ * Strip a leading or trailing verb from an unspaced query, returning the noun+ * that remains (`''` when the query is just the verb). Returns `null` when the+ * query carries no verb or isn't written in an unspaced script.+ */+function stripUnspacedVerb(query: string, verbs: Set<string>): string | null {+ if (!UNSPACED_SCRIPT.test(query)) return null++ // Longest first, so a verb that is a prefix of another ("新" vs "新建")+ // can't strip the shorter match and leave the rest of the verb in the noun.+ const byLength = [...verbs].sort((a, b) => b.length - a.length)++ for (const verb of byLength) {+ if (query === verb) return ''+ if (query.startsWith(verb)) return query.slice(verb.length)+ if (query.endsWith(verb)) return query.slice(0, -verb.length)+ }+ return null+}++/** Fold case and strip accents so "Rückgabe" matches "ruckgabe". */+function normalize(value: string): string {+ return value+ .toLowerCase()+ .normalize('NFD')+ .replace(/\p{Diacritic}/gu, '')+ .trim()+}++/**+ * Turn a raw palette query into the create actions it names.+ *+ * Matches "<verb> <noun>" in either order, since languages disagree on which+ * comes first — English puts the verb first ("add product"), while a merchant+ * typing Polish or German may not. A bare verb ("new") lists everything+ * creatable, which doubles as discovery of what this dashboard can create.+ *+ * Returns an empty array when the query names no verb, so ordinary searches are+ * unaffected.+ */+/**+ * The create actions a query names, narrowed to those the signed-in user may+ * actually create.+ *+ * Create is gated on the `create` action rather than `read`: a user who can+ * list products but not add one should never be offered "New product". Entries+ * without a subject are ungated.+ */+export function permittedCreateActions({+ query,+ entries,+ t,+ can,+}: {+ query: string+ entries: CreateActionEntry[]+ t: (key: string) => string+ can: (action: string, subject: string) => boolean+}): CreateActionMatch[] {+ return matchCreateActions({ query, entries, t }).filter(+ ({ entry }) => !entry.subject || can('create', entry.subject),+ )+}++export function matchCreateActions({+ query,+ entries,+ t,+}: {+ query: string+ entries: CreateActionEntry[]+ t: (key: string) => string+}): CreateActionMatch[] {+ const words = normalize(query).split(/\s+/).filter(Boolean)+ if (words.length === 0) return []++ const verbs = new Set(+ t(CREATE_VERBS_KEY)+ .split(',')+ .map((verb) => normalize(verb))+ .filter(Boolean),+ )++ // The verb may lead or trail; strip whichever end carries it and treat the+ // rest as the noun. Checking the last word only when the first didn't match+ // keeps "add" + "add-on"-style nouns unambiguous.+ let noun: string+ if (verbs.has(words[0])) {+ noun = words.slice(1).join(' ')+ } else if (words.length > 1 && verbs.has(words[words.length - 1])) {+ noun = words.slice(0, -1).join(' ')+ } else {+ // Languages that don't put spaces between words — Chinese, Japanese —+ // arrive as one token ("新建商品"), so word equality never matches. Fall+ // back to stripping the verb as a prefix or suffix of the whole query.+ const unspaced = stripUnspacedVerb(normalize(query), verbs)+ if (unspaced === null) return []+ noun = unspaced+ }+ const matches: CreateActionMatch[] = []++ for (const entry of entries) {+ const labels = [entry.labelKey, ...(entry.aliasKeys ?? [])].map((key) => t(key))+ let best: { rank: number; noun: string } | null = null++ for (const label of labels) {+ const candidate = normalize(label)+ // A bare verb lists everything; otherwise rank by how squarely the typed+ // noun lands on this label.+ const rank = !noun+ ? 3+ : candidate === noun+ ? 0+ : candidate.startsWith(noun)+ ? 1+ : candidate.includes(noun)+ ? 2+ : -1+ if (rank === -1) continue+ // Always report the primary label, so a row found via an alias still+ // reads as the resource's real name.+ if (!best || rank < best.rank) best = { rank, noun: labels[0] }+ }++ if (best) matches.push({ entry, noun: best.noun, rank: best.rank })+ }++ return matches.sort(+ (a, b) => a.rank - b.rank || (a.entry.position ?? 100) - (b.entry.position ?? 100),+ )+}diff --git a/packages/dashboard-core/src/lib/search-registry.ts b/packages/dashboard-core/src/lib/search-registry.tsindex c6c71491ca..2406b18b97 100644--- a/packages/dashboard-core/src/lib/search-registry.ts+++ b/packages/dashboard-core/src/lib/search-registry.ts@@ -48,8 +48,12 @@ export interface SearchEntry<T = unknown> {getKey: (item: T) => string/** Render one result row's inner content (icon/thumbnail + label + badges). */renderRow: (item: T) => ReactNode- /** Resolve the destination for a clicked result, given the active store. */- getRoute: (item: T, storeId: string) => { to: string }+ /**+ * Resolve the destination for a clicked result, given the active store.+ * `search` carries route search params — needed by resources edited in a+ * deep-linked sheet rather than on a page of their own.+ */+ getRoute: (item: T, storeId: string) => { to: string; search?: Record<string, unknown> }}interface SearchMutator {diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex b8a9641cce..faaabc7041 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -412,7 +412,50 @@"no_results": "لا توجد نتائج لـ \"{{query}}\".","empty_hint": "اكتب للبحث، أو اختر أمرًا أدناه.","goto": "انتقل إلى",- "goto_label": "انتقل إلى {{label}}"+ "goto_label": "انتقل إلى {{label}}",+ "hints": {+ "navigate": "التنقل",+ "select": "اختيار",+ "close": "إغلاق",+ "esc_key": "esc"+ },+ "create": {+ "heading": "إنشاء",+ "label": "إنشاء {{noun}}",+ "verbs": "إضافة,جديد,جديدة,أضف,إنشاء,انشاء",+ "nouns": {+ "category": "فئة",+ "category_plural": "الفئات",+ "collection": "مجموعة",+ "collection_plural": "المجموعات",+ "company": "شركة",+ "company_plural": "الشركات",+ "customer": "عميل",+ "customer_group": "مجموعة عملاء",+ "customer_group_plural": "مجموعات العملاء",+ "customer_plural": "العملاء",+ "discount": "خصم",+ "discount_plural": "الخصومات",+ "gift_card": "بطاقة هدايا",+ "gift_card_plural": "بطاقات الهدايا",+ "option_type": "خيار",+ "option_type_plural": "الخيارات",+ "order": "طلب",+ "order_plural": "الطلبات",+ "price_list": "قائمة أسعار",+ "price_list_plural": "قوائم الأسعار",+ "product": "منتج",+ "product_plural": "المنتجات",+ "promotion": "عرض ترويجي",+ "promotion_plural": "العروض الترويجية",+ "seller": "بائع",+ "seller_plural": "البائعون",+ "stock_location": "مستودع",+ "stock_location_plural": "المستودعات",+ "stock_transfer": "تحويل",+ "stock_transfer_plural": "التحويلات"+ }+ }},"bulk_action_bar": {"selected": "تم تحديد {{count}}",diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex 72431746cd..a9f95e1bbb 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -412,7 +412,50 @@"no_results": "Keine Ergebnisse für \"{{query}}\".","empty_hint": "Zum Suchen tippen oder unten einen Befehl auswählen.","goto": "Gehe zu",- "goto_label": "Gehe zu {{label}}"+ "goto_label": "Gehe zu {{label}}",+ "hints": {+ "navigate": "navigieren",+ "select": "auswählen",+ "close": "schließen",+ "esc_key": "Esc"+ },+ "create": {+ "heading": "Erstellen",+ "label": "Neu: {{noun}}",+ "verbs": "neu,neue,neuer,neues,neuen,hinzufügen,erstellen,anlegen",+ "nouns": {+ "category": "Kategorie",+ "category_plural": "Kategorien",+ "collection": "Kollektion",+ "collection_plural": "Kollektionen",+ "company": "Unternehmen",+ "company_plural": "Unternehmen",+ "customer": "Kunde",+ "customer_group": "Kundengruppe",+ "customer_group_plural": "Kundengruppen",+ "customer_plural": "Kunden",+ "discount": "Rabatt",+ "discount_plural": "Rabatte",+ "gift_card": "Geschenkkarte",+ "gift_card_plural": "Geschenkkarten",+ "option_type": "Option",+ "option_type_plural": "Optionen",+ "order": "Bestellung",+ "order_plural": "Bestellungen",+ "price_list": "Preisliste",+ "price_list_plural": "Preislisten",+ "product": "Produkt",+ "product_plural": "Produkte",+ "promotion": "Aktion",+ "promotion_plural": "Aktionen",+ "seller": "Verkäufer",+ "seller_plural": "Verkäufer",+ "stock_location": "Lager",+ "stock_location_plural": "Lager",+ "stock_transfer": "Umlagerung",+ "stock_transfer_plural": "Umlagerungen"+ }+ }},"bulk_action_bar": {"selected": "{{count}} ausgewählt",diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex 0d37b304cd..e580784575 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -412,7 +412,50 @@"no_results": "No results for \"{{query}}\".","empty_hint": "Type to search, or pick a command below.","goto": "Go to",- "goto_label": "Go to {{label}}"+ "goto_label": "Go to {{label}}",+ "hints": {+ "navigate": "navigate",+ "select": "select",+ "close": "close",+ "esc_key": "esc"+ },+ "create": {+ "heading": "Create",+ "label": "New {{noun}}",+ "verbs": "add,new,create",+ "nouns": {+ "category": "Category",+ "category_plural": "Categories",+ "collection": "Collection",+ "collection_plural": "Collections",+ "company": "Company",+ "company_plural": "Companies",+ "customer": "Customer",+ "customer_group": "Customer group",+ "customer_group_plural": "Customer groups",+ "customer_plural": "Customers",+ "discount": "Discount",+ "discount_plural": "Discounts",+ "gift_card": "Gift card",+ "gift_card_plural": "Gift cards",+ "option_type": "Option",+ "option_type_plural": "Options",+ "order": "Order",+ "order_plural": "Orders",+ "price_list": "Price list",+ "price_list_plural": "Price lists",+ "product": "Product",+ "product_plural": "Products",+ "promotion": "Promotion",+ "promotion_plural": "Promotions",+ "seller": "Seller",+ "seller_plural": "Sellers",+ "stock_location": "Location",+ "stock_location_plural": "Locations",+ "stock_transfer": "Transfer",+ "stock_transfer_plural": "Transfers"+ }+ }},"bulk_action_bar": {"selected": "{{count}} selected",diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex 32ff1122de..c7782ca82e 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -412,7 +412,50 @@"no_results": "Aucun résultat pour « {{query}} ».","empty_hint": "Saisissez du texte pour rechercher, ou choisissez une commande ci-dessous.","goto": "Aller à",- "goto_label": "Aller à {{label}}"+ "goto_label": "Aller à {{label}}",+ "hints": {+ "navigate": "naviguer",+ "select": "sélectionner",+ "close": "fermer",+ "esc_key": "échap"+ },+ "create": {+ "heading": "Créer",+ "label": "Créer : {{noun}}",+ "verbs": "nouveau,nouvelle,ajouter,créer",+ "nouns": {+ "category": "Catégorie",+ "category_plural": "Catégories",+ "collection": "Collection",+ "collection_plural": "Collections",+ "company": "Entreprise",+ "company_plural": "Entreprises",+ "customer": "Client",+ "customer_group": "Groupe de clients",+ "customer_group_plural": "Groupes de clients",+ "customer_plural": "Clients",+ "discount": "Remise",+ "discount_plural": "Remises",+ "gift_card": "Carte cadeau",+ "gift_card_plural": "Cartes cadeaux",+ "option_type": "Option",+ "option_type_plural": "Options",+ "order": "Commande",+ "order_plural": "Commandes",+ "price_list": "Liste de prix",+ "price_list_plural": "Listes de prix",+ "product": "Produit",+ "product_plural": "Produits",+ "promotion": "Promotion",+ "promotion_plural": "Promotions",+ "seller": "Vendeur",+ "seller_plural": "Vendeurs",+ "stock_location": "Entrepôt",+ "stock_location_plural": "Entrepôts",+ "stock_transfer": "Transfert",+ "stock_transfer_plural": "Transferts"+ }+ }},"bulk_action_bar": {"selected": "{{count}} sélectionné(s)",diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex abe55e14c5..517318d4a9 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -412,7 +412,50 @@"no_results": "Brak wyników dla „{{query}}”.","empty_hint": "Zacznij pisać, aby wyszukać, lub wybierz polecenie poniżej.","goto": "Przejdź do",- "goto_label": "Przejdź do {{label}}"+ "goto_label": "Przejdź do {{label}}",+ "hints": {+ "navigate": "nawiguj",+ "select": "wybierz",+ "close": "zamknij",+ "esc_key": "esc"+ },+ "create": {+ "heading": "Utwórz",+ "label": "Utwórz: {{noun}}",+ "verbs": "nowy,nowa,nowe,dodaj,utwórz,stwórz",+ "nouns": {+ "category": "Kategoria",+ "category_plural": "Kategorie",+ "collection": "Kolekcja",+ "collection_plural": "Kolekcje",+ "company": "Firma",+ "company_plural": "Firmy",+ "customer": "Klient",+ "customer_group": "Grupa klientów",+ "customer_group_plural": "Grupy klientów",+ "customer_plural": "Klienci",+ "discount": "Rabat",+ "discount_plural": "Rabaty",+ "gift_card": "Karta podarunkowa",+ "gift_card_plural": "Karty podarunkowe",+ "option_type": "Opcja",+ "option_type_plural": "Opcje",+ "order": "Zamówienie",+ "order_plural": "Zamówienia",+ "price_list": "Cennik",+ "price_list_plural": "Cenniki",+ "product": "Produkt",+ "product_plural": "Produkty",+ "promotion": "Promocja",+ "promotion_plural": "Promocje",+ "seller": "Sprzedawca",+ "seller_plural": "Sprzedawcy",+ "stock_location": "Magazyn",+ "stock_location_plural": "Magazyny",+ "stock_transfer": "Transfer",+ "stock_transfer_plural": "Transfery"+ }+ }},"bulk_action_bar": {"selected": "Wybrano: {{count}}",diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex 7c7b194e65..e378478c46 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -412,7 +412,50 @@"no_results": "未找到与“{{query}}”相关的结果。","empty_hint": "输入以搜索,或从下方选择命令。","goto": "前往",- "goto_label": "前往 {{label}}"+ "goto_label": "前往 {{label}}",+ "hints": {+ "navigate": "导航",+ "select": "选择",+ "close": "关闭",+ "esc_key": "esc"+ },+ "create": {+ "heading": "创建",+ "label": "新建{{noun}}",+ "verbs": "新建,添加,创建,新增",+ "nouns": {+ "category": "分类",+ "category_plural": "分类",+ "collection": "系列",+ "collection_plural": "系列",+ "company": "公司",+ "company_plural": "公司",+ "customer": "客户",+ "customer_group": "客户组",+ "customer_group_plural": "客户组",+ "customer_plural": "客户",+ "discount": "折扣",+ "discount_plural": "折扣",+ "gift_card": "礼品卡",+ "gift_card_plural": "礼品卡",+ "option_type": "选项",+ "option_type_plural": "选项",+ "order": "订单",+ "order_plural": "订单",+ "price_list": "价目表",+ "price_list_plural": "价目表",+ "product": "商品",+ "product_plural": "商品",+ "promotion": "促销",+ "promotion_plural": "促销",+ "seller": "卖家",+ "seller_plural": "卖家",+ "stock_location": "仓库",+ "stock_location_plural": "仓库",+ "stock_transfer": "调拨",+ "stock_transfer_plural": "调拨"+ }+ }},"bulk_action_bar": {"selected": "已选择 {{count}} 项",diff --git a/packages/dashboard-core/tests/create-action-matching.test.ts b/packages/dashboard-core/tests/create-action-matching.test.tsnew file mode 100644index 0000000000..01bf538ba9--- /dev/null+++ b/packages/dashboard-core/tests/create-action-matching.test.ts@@ -0,0 +1,227 @@+import { beforeEach, describe, expect, it } from 'vitest'+import {+ __resetCreateActionRegistry,+ type CreateActionEntry,+ createActionRegistry,+ matchCreateActions,+ permittedCreateActions,+} from '../src/lib/create-action-registry'++// A stand-in translator: keys map to their last segment, title-cased, except+// the verb list and the two-word nouns declared here.+const DICT: Record<string, string> = {+ 'admin.components.command_palette.create.verbs': 'add,new,create',+ 'nouns.product': 'Product',+ 'nouns.product_plural': 'Products',+ 'nouns.customer': 'Customer',+ 'nouns.customer_plural': 'Customers',+ 'nouns.customer_group': 'Customer group',+ 'nouns.promotion': 'Promotion',+ 'nouns.discount': 'Discount',+ 'nouns.discount_plural': 'Discounts',+}+const t = (key: string) => DICT[key] ?? key++function entry(key: string, labelKey: string, aliasKeys?: string[]): CreateActionEntry {+ return { key, labelKey, aliasKeys, getRoute: () => ({ to: `/${key}` }) }+}++const ENTRIES = [+ entry('product', 'nouns.product', ['nouns.product_plural']),+ entry('customer', 'nouns.customer', ['nouns.customer_plural']),+ entry('customer_group', 'nouns.customer_group'),+ entry('promotion', 'nouns.promotion', ['nouns.discount', 'nouns.discount_plural']),+]++const match = (query: string) =>+ matchCreateActions({ query, entries: ENTRIES, t }).map((m) => m.entry.key)++describe('matchCreateActions', () => {+ it('maps "<verb> <noun>" to the matching action', () => {+ expect(match('add product')).toEqual(['product'])+ expect(match('new customer group')).toEqual(['customer_group'])+ expect(match('create promotion')).toEqual(['promotion'])+ })++ it('accepts every registered verb', () => {+ for (const verb of ['add', 'new', 'create']) {+ expect(match(`${verb} product`)).toEqual(['product'])+ }+ })++ it('ignores queries that name no verb, so plain search is unaffected', () => {+ expect(match('product')).toEqual([])+ expect(match('blue running shoe')).toEqual([])+ expect(match('')).toEqual([])+ })++ it('matches the plural the merchant may type', () => {+ expect(match('add products')).toEqual(['product'])+ })++ it('matches an alias but reports the resource under its real name', () => {+ const matches = matchCreateActions({ query: 'new discount', entries: ENTRIES, t })+ expect(matches.map((m) => m.entry.key)).toEqual(['promotion'])+ expect(matches[0].noun).toBe('Promotion')+ })++ it('matches a plural alias', () => {+ expect(match('add discounts')).toEqual(['promotion'])+ })++ it('accepts a trailing verb, for languages that put it last', () => {+ expect(match('product add')).toEqual(['product'])+ })++ it('lists everything creatable for a bare verb', () => {+ expect(match('new')).toEqual(['product', 'customer', 'customer_group', 'promotion'])+ })++ it('ranks an exact noun above a merely-prefixed one', () => {+ // "customer" is exact for Customer and a prefix of "Customer group".+ expect(match('add customer')).toEqual(['customer', 'customer_group'])+ })++ it('is case- and accent-insensitive', () => {+ expect(match('ADD Prödüct')).toEqual(['product'])+ })++ it('tolerates extra whitespace', () => {+ expect(match(' add product ')).toEqual(['product'])+ })++ it('does not read a verb out of the middle of an ordinary word', () => {+ // "address" starts with the verb "add" — matching it would hijack search.+ expect(match('address')).toEqual([])+ expect(match('newsletter')).toEqual([])+ })+})++// Chinese and Japanese are written without spaces between words, so the whole+// query arrives as a single token and word-equality never finds the verb.+describe('matchCreateActions — unspaced scripts', () => {+ const CJK: Record<string, string> = {+ 'admin.components.command_palette.create.verbs': '新建,添加,创建,新增',+ 'nouns.product': '商品',+ 'nouns.order': '订单',+ }+ const tCjk = (key: string) => CJK[key] ?? key+ const cjkEntries = [entry('product', 'nouns.product'), entry('order', 'nouns.order')]+ const matchCjk = (query: string) =>+ matchCreateActions({ query, entries: cjkEntries, t: tCjk }).map((m) => m.entry.key)++ it('matches a verb prefixed onto the noun with no space', () => {+ expect(matchCjk('新建商品')).toEqual(['product'])+ expect(matchCjk('添加订单')).toEqual(['order'])+ })++ it('matches a verb appended after the noun with no space', () => {+ expect(matchCjk('商品新建')).toEqual(['product'])+ expect(matchCjk('订单添加')).toEqual(['order'])+ })++ // Katakana nouns must work as well as kanji — the guard keys off script, not+ // off any one language.+ it('matches a katakana noun', () => {+ const jp: Record<string, string> = {+ 'admin.components.command_palette.create.verbs': '新規,追加',+ 'nouns.customer': 'カスタマー',+ }+ const matches = matchCreateActions({+ query: '追加カスタマー',+ entries: [entry('customer', 'nouns.customer')],+ t: (key) => jp[key] ?? key,+ })+ expect(matches.map((m) => m.entry.key)).toEqual(['customer'])+ })++ it('still matches when a space is typed', () => {+ expect(matchCjk('新建 商品')).toEqual(['product'])+ })++ it('lists everything creatable for a bare verb', () => {+ expect(matchCjk('新建')).toEqual(['product', 'order'])+ })++ it('ignores a query naming no verb', () => {+ expect(matchCjk('商品')).toEqual([])+ })+})++describe('createActionRegistry', () => {+ beforeEach(() => {+ __resetCreateActionRegistry()+ })++ it('rejects a duplicate key rather than silently shadowing', () => {+ createActionRegistry.add(entry('product', 'nouns.product'))+ expect(() => createActionRegistry.add(entry('product', 'nouns.product'))).toThrow(+ /already registered/,+ )+ })++ it('throws when updating an action that was never registered', () => {+ expect(() => createActionRegistry.update('ghost', { position: 1 })).toThrow(/not found/)+ })++ it('removes a registered action and ignores a missing one', () => {+ createActionRegistry.add(entry('product', 'nouns.product'))+ createActionRegistry.remove('product')+ expect(() => createActionRegistry.remove('product')).not.toThrow()+ })+})++describe('permittedCreateActions', () => {+ // Entries mirroring the real registry: a subject-gated one and an ungated one.+ const GATED: CreateActionEntry[] = [+ {+ key: 'product',+ labelKey: 'nouns.product',+ subject: 'Spree::Product',+ getRoute: () => ({ to: '/products/new' }),+ },+ {+ key: 'customer',+ labelKey: 'nouns.customer',+ subject: 'Spree::Customer',+ getRoute: (storeId) => ({ to: `/${storeId}/customers`, search: { new: true } }),+ },+ { key: 'ungated', labelKey: 'nouns.promotion', getRoute: () => ({ to: '/promotions/new' }) },+ ]+ const permitted = (query: string, can: (action: string, subject: string) => boolean) =>+ permittedCreateActions({ query, entries: GATED, t, can }).map((m) => m.entry.key)++ it('hides an action the user may not create', () => {+ expect(permitted('add product', () => false)).toEqual([])+ })++ it('keeps an action the user may create', () => {+ expect(permitted('add product', () => true)).toEqual(['product'])+ })++ it('gates on create rather than read', () => {+ // A user who can list products but not add one must not be offered the row.+ const readOnly = (action: string) => action === 'read'+ expect(permitted('add product', readOnly)).toEqual([])+ })++ it('checks each entry against its own subject', () => {+ const onlyCustomers = (_action: string, subject: string) => subject === 'Spree::Customer'+ expect(permitted('new', onlyCustomers)).toEqual(['customer', 'ungated'])+ })++ it('never gates an entry that declares no subject', () => {+ expect(permitted('new', () => false)).toEqual(['ungated'])+ })++ // Two destination shapes ship: a dedicated `/new` route, and an index page+ // whose create sheet opens from a search param. Both must survive matching.+ it('carries the route through, search params included', () => {+ const matches = permittedCreateActions({ query: 'new', entries: GATED, t, can: () => true })+ const routes = Object.fromEntries(+ matches.map((m) => [m.entry.key, m.entry.getRoute('store_1')]),+ )+ expect(routes.product).toEqual({ to: '/products/new' })+ expect(routes.customer).toEqual({ to: '/store_1/customers', search: { new: true } })+ })+})diff --git a/packages/dashboard-ui/src/ui/checkbox.tsx b/packages/dashboard-ui/src/ui/checkbox.tsxindex 804bea4d5b..1eee541db8 100644--- a/packages/dashboard-ui/src/ui/checkbox.tsx+++ b/packages/dashboard-ui/src/ui/checkbox.tsx@@ -25,7 +25,7 @@ function Checkbox({disabled={disabled}name={name}className={cn(- 'peer relative inline-block size-4 shrink-0 rounded-[4px] border border-input align-[-3px] shadow-xs outline-none transition-shadow',+ 'peer relative inline-block size-4 shrink-0 cursor-pointer rounded-[4px] border border-input align-[-3px] shadow-xs outline-none transition-shadow','focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50','disabled:cursor-not-allowed disabled:opacity-50','aria-invalid:border-destructive aria-invalid:ring-destructive/20',diff --git a/packages/dashboard-ui/src/ui/combobox.tsx b/packages/dashboard-ui/src/ui/combobox.tsxindex c4f4c58584..f1efac2535 100644--- a/packages/dashboard-ui/src/ui/combobox.tsx+++ b/packages/dashboard-ui/src/ui/combobox.tsx@@ -138,7 +138,7 @@ function ComboboxItem({ className, children, ...props }: ComboboxPrimitive.Item.// Padding + font sized to match `<Input>` (`py-1.5 px-2.5 text-base// leading-normal`) so the dropdown rows feel like a continuation of// the trigger field. `pr-8` keeps room for the check indicator.- "relative flex w-full cursor-default items-center gap-2 rounded-md py-1.5 pr-8 pl-2.5 text-base font-normal leading-normal outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex w-full cursor-pointer items-center gap-2 rounded-md py-1.5 pr-8 pl-2.5 text-base font-normal leading-normal outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}{...props}diff --git a/packages/dashboard-ui/src/ui/command.tsx b/packages/dashboard-ui/src/ui/command.tsxindex 33c6ccf29b..3dbb234a8c 100644--- a/packages/dashboard-ui/src/ui/command.tsx+++ b/packages/dashboard-ui/src/ui/command.tsx@@ -1,17 +1,23 @@import { Command as CommandPrimitive } from 'cmdk'import i18n from 'i18next'-import { CheckIcon, SearchIcon } from 'lucide-react'+import {+ CheckIcon,+ CornerDownLeftIcon,+ Loader2Icon,+ MoveDownIcon,+ MoveUpIcon,+ SearchIcon,+} from 'lucide-react'import * as React from 'react'import { cn } from '../lib/utils'import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './dialog'-import { InputGroup, InputGroupAddon } from './input-group'function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) {return (<CommandPrimitivedata-slot="command"className={cn(- 'flex size-full flex-col overflow-hidden rounded-2xl! bg-popover p-1 text-popover-foreground',+ 'flex size-full flex-col overflow-hidden rounded-2xl! bg-popover text-popover-foreground',className,)}{...props}@@ -48,38 +54,66 @@ function CommandDialog({)}+/**+ * The palette's search field — the top edge of the panel, spanning its full+ * width above a single hairline.+ *+ * While `loading` is set, a spinner sits at the end of the field rather than in+ * the results list, so rows don't shift down when a search starts and back up+ * when it lands. The state is announced to screen readers as well as drawn.+ */function CommandInput({className,+ loading = false,...props-}: React.ComponentProps<typeof CommandPrimitive.Input>) {+}: React.ComponentProps<typeof CommandPrimitive.Input> & {+ /** Shows a spinner at the end of the field while results are in flight. */+ loading?: boolean+}) {return (- <div data-slot="command-input-wrapper" className="p-1 pb-0">- {/* One step inside the dialog's own radius, so the field's corners stay- concentric with the panel's rather than reading as a tighter shape- floating in the padding. */}- <InputGroup className="h-8! rounded-xl! border-input/30 bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!">- <CommandPrimitive.Input- data-slot="command-input"- className={cn(- 'w-full text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50',- className,- )}- {...props}+ <div+ data-slot="command-input-wrapper"+ className="flex h-14 shrink-0 items-center gap-3 border-b border-border px-5"+ >+ <SearchIcon className="size-5 shrink-0 text-muted-foreground" />+ <CommandPrimitive.Input+ data-slot="command-input"+ aria-busy={loading || undefined}+ className={cn(+ 'h-full w-full bg-transparent text-base outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50',+ className,+ )}+ {...props}+ />+ {loading && (+ <Loader2Icon+ data-slot="command-input-loading"+ aria-hidden="true"+ className="size-4 shrink-0 animate-spin text-muted-foreground"/>- <InputGroupAddon>- <SearchIcon className="size-4 shrink-0 opacity-50" />- </InputGroupAddon>- </InputGroup>+ )}+ {/* The spinner is decorative, so the progress a sighted user reads from it+ is announced here instead. Polite: it must not cut off the row count+ the listbox announces when results land. */}+ <span role="status" aria-live="polite" className="sr-only">+ {loading ? i18n.t('admin.common.searching') : ''}+ </span></div>)}+/**+ * The results area. Its height is fixed rather than content-driven, so the+ * panel stays put as results arrive instead of resizing under the cursor on+ * every keystroke. Pass `className="h-…"` to change it, or `h-auto max-h-…`+ * for the shrink-to-fit behaviour a short static menu wants.+ */function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) {return (<CommandPrimitive.Listdata-slot="command-list"className={cn(- 'no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none',+ 'h-80 min-h-0 scroll-py-2 overflow-x-hidden overflow-y-auto p-2 outline-none',className,)}{...props}@@ -94,7 +128,7 @@ function CommandEmpty({return (<CommandPrimitive.Emptydata-slot="command-empty"- className={cn('py-6 text-center text-sm', className)}+ className={cn('py-10 text-center text-sm text-muted-foreground', className)}{...props}/>)@@ -108,7 +142,7 @@ function CommandGroup({<CommandPrimitive.Groupdata-slot="command-group"className={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',+ 'overflow-hidden text-foreground not-last:pb-2 **:[[cmdk-group-heading]]:px-3 **:[[cmdk-group-heading]]:pt-2 **:[[cmdk-group-heading]]:pb-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground',className,)}{...props}@@ -123,7 +157,7 @@ function CommandSeparator({return (<CommandPrimitive.Separatordata-slot="command-separator"- className={cn('-mx-1 h-px bg-border', className)}+ className={cn('-mx-2 my-1 h-px bg-border-subtle', className)}{...props}/>)@@ -138,7 +172,7 @@ function CommandItem({<CommandPrimitive.Itemdata-slot="command-item"className={cn(- "group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none in-data-[slot=dialog-content]:rounded-lg! data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground",+ "group/command-item relative flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-selected:*:[svg]:text-foreground",className,)}{...props}@@ -162,13 +196,93 @@ function CommandShortcut({ className, ...props }: React.ComponentProps<'span'>))}+/** A single key cap — used for the palette's footer hints and inline shortcuts. */+function CommandKey({ className, ...props }: React.ComponentProps<'kbd'>) {+ return (+ <kbd+ data-slot="command-key"+ className={cn(+ 'inline-flex h-6 min-w-6 items-center justify-center rounded-md bg-card border border-border-subtle px-1.5 font-sans text-xs text-muted-foreground',+ className,+ )}+ {...props}+ />+ )+}++/** One key cap (or a pair) followed by the action it performs. */+function CommandHint({+ keys,+ label,+ className,+ ...props+}: Omit<React.ComponentProps<'div'>, 'children'> & {+ keys: React.ReactNode[]+ label: React.ReactNode+}) {+ return (+ <div data-slot="command-hint" className={cn('flex items-center gap-1.5', className)} {...props}>+ <span className="flex items-center gap-1">+ {keys.map((key, index) => (+ // Hints are static, ordered, and never reordered — index is a stable key.+ // biome-ignore lint/suspicious/noArrayIndexKey: static list+ <CommandKey key={index}>{key}</CommandKey>+ ))}+ </span>+ <span className="text-xs text-muted-foreground">{label}</span>+ </div>+ )+}++/**+ * Bottom bar of the palette. Renders the default navigate/select/close hints+ * when given no children, so callers only pass children to replace them.+ */+function CommandFooter({ className, children, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="command-footer"+ className={cn(+ 'flex shrink-0 items-center justify-between gap-4 border-t border-border-subtle bg-muted text-muted-foreground px-4 py-2.5',+ className,+ )}+ {...props}+ >+ {children ?? (+ <>+ <div className="flex items-center gap-4">+ <CommandHint+ keys={[+ <MoveUpIcon key="up" className="size-3.5" />,+ <MoveDownIcon key="down" className="size-3.5" />,+ ]}+ label={i18n.t('admin.components.command_palette.hints.navigate')}+ />+ <CommandHint+ keys={[<CornerDownLeftIcon key="enter" className="size-3.5" />]}+ label={i18n.t('admin.components.command_palette.hints.select')}+ />+ </div>+ <CommandHint+ keys={[i18n.t('admin.components.command_palette.hints.esc_key')]}+ label={i18n.t('admin.components.command_palette.hints.close')}+ />+ </>+ )}+ </div>+ )+}+export {Command,CommandDialog,CommandEmpty,+ CommandFooter,CommandGroup,+ CommandHint,CommandInput,CommandItem,+ CommandKey,CommandList,CommandSeparator,CommandShortcut,diff --git a/packages/dashboard-ui/src/ui/dropdown-menu.tsx b/packages/dashboard-ui/src/ui/dropdown-menu.tsxindex ac8e2f7ca0..2acf664e04 100644--- a/packages/dashboard-ui/src/ui/dropdown-menu.tsx+++ b/packages/dashboard-ui/src/ui/dropdown-menu.tsx@@ -119,7 +119,7 @@ function DropdownMenuItem({data-variant={variant}render={children}className={cn(- "group/dropdown-menu-item relative flex cursor-default items-center gap-3 rounded-xl px-2 py-1.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group/dropdown-menu-item relative flex cursor-pointer items-center gap-3 rounded-xl px-2 py-1.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}{...props}@@ -133,7 +133,7 @@ function DropdownMenuItem({data-inset={inset}data-variant={variant}className={cn(- "group/dropdown-menu-item relative flex cursor-default items-center gap-3 rounded-xl px-2 py-1.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group/dropdown-menu-item relative flex cursor-pointer items-center gap-3 rounded-xl px-2 py-1.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}{...props}@@ -160,7 +160,7 @@ function DropdownMenuCheckboxItem({data-slot="dropdown-menu-checkbox-item"data-inset={inset}className={cn(- "relative flex cursor-default items-center gap-3 rounded-xl py-1.5 pr-8 pl-2.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-pointer items-center gap-3 rounded-xl py-1.5 pr-8 pl-2.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}checked={checked}@@ -199,7 +199,7 @@ function DropdownMenuRadioItem({data-slot="dropdown-menu-radio-item"data-inset={inset}className={cn(- "relative flex cursor-default items-center gap-3 rounded-xl py-1.5 pr-8 pl-2.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-pointer items-center gap-3 rounded-xl py-1.5 pr-8 pl-2.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}{...props}@@ -294,7 +294,7 @@ function DropdownMenuSubTrigger({data-slot="dropdown-menu-sub-trigger"data-inset={inset}className={cn(- "flex cursor-default items-center gap-3 rounded-xl px-2 py-1.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[popup-open]:bg-accent data-[popup-open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex cursor-pointer items-center gap-3 rounded-xl px-2 py-1.5 text-sm outline-hidden select-none transition-colors duration-75 focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[popup-open]:bg-accent data-[popup-open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}{...props}diff --git a/packages/dashboard-ui/src/ui/radio-group.tsx b/packages/dashboard-ui/src/ui/radio-group.tsxindex aaaee783f0..dea67e5616 100644--- a/packages/dashboard-ui/src/ui/radio-group.tsx+++ b/packages/dashboard-ui/src/ui/radio-group.tsx@@ -18,7 +18,7 @@ function RadioGroupItem({ className, ...props }: React.ComponentProps<typeof Rad<RadioPrimitive.Rootdata-slot="radio-group-item"className={cn(- 'peer relative inline-block size-4 shrink-0 rounded-full border border-input align-[-3px] shadow-xs outline-none transition-shadow',+ 'peer relative inline-block size-4 shrink-0 cursor-pointer rounded-full border border-input align-[-3px] shadow-xs outline-none transition-shadow','focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50','disabled:cursor-not-allowed disabled:opacity-50','aria-invalid:border-destructive aria-invalid:ring-destructive/20',diff --git a/packages/dashboard-ui/src/ui/select.tsx b/packages/dashboard-ui/src/ui/select.tsxindex 561fa65904..2d6fab751f 100644--- a/packages/dashboard-ui/src/ui/select.tsx+++ b/packages/dashboard-ui/src/ui/select.tsx@@ -59,7 +59,7 @@ function SelectTrigger({// doesn't collapse to chevron-height when the SelectValue render-prop// returns an empty string (e.g., when value is unset and the// placeholder isn't surfaced through the render-prop).- "flex w-full min-h-8.5 items-center justify-between gap-1.5 rounded-lg border border-border bg-card py-1.5 pr-2 pl-2.5 text-base font-normal leading-normal text-foreground shadow-xs transition-all duration-100 ease-in-out outline-none select-none focus:border-blue-500 focus:shadow-[0_0_0_3px_color-mix(in_srgb,var(--ring)_15%,transparent)] disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-muted disabled:border-border disabled:text-muted-foreground disabled:shadow-none aria-invalid:border-destructive data-[placeholder]:text-muted-foreground data-[size=sm]:py-1 data-[size=sm]:px-2 data-[size=sm]:text-sm data-[size=sm]:min-h-[1.9375rem] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex w-full min-h-8.5 cursor-pointer items-center justify-between gap-1.5 rounded-lg border border-border bg-card py-1.5 pr-2 pl-2.5 text-base font-normal leading-normal text-foreground shadow-xs transition-all duration-100 ease-in-out outline-none select-none focus:border-blue-500 focus:shadow-[0_0_0_3px_color-mix(in_srgb,var(--ring)_15%,transparent)] disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-muted disabled:border-border disabled:text-muted-foreground disabled:shadow-none aria-invalid:border-destructive data-[placeholder]:text-muted-foreground data-[size=sm]:py-1 data-[size=sm]:px-2 data-[size=sm]:text-sm data-[size=sm]:min-h-[1.9375rem] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}{...props}@@ -137,7 +137,7 @@ function SelectItem({// Padding + font sized to match `<Input>` and `<SelectTrigger>` so// the dropdown rows feel like a continuation of the trigger field.// `pr-8` reserves room for the absolute-positioned check indicator.- "relative flex w-full cursor-default items-center gap-2 rounded-md py-1.5 pr-8 pl-2.5 text-base font-normal leading-normal outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",+ "relative flex w-full cursor-pointer items-center gap-2 rounded-md py-1.5 pr-8 pl-2.5 text-base font-normal leading-normal outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",className,)}{...props}diff --git a/packages/dashboard/e2e/command-palette.spec.ts b/packages/dashboard/e2e/command-palette.spec.tsnew file mode 100644index 0000000000..7d56fb97a7--- /dev/null+++ b/packages/dashboard/e2e/command-palette.spec.ts@@ -0,0 +1,87 @@+import { expect, type Page, test } from '@playwright/test'+import { login } from './helpers'++// The palette is reachable from every page, so each spec opens it from the+// store home rather than navigating somewhere specific first.+async function openPalette(page: Page, storeId: string) {+ await page.goto(`/${storeId}`)+ await page.getByRole('button', { name: /search products, orders, customers/i }).click()+ // Scoped to the dialog: the top-bar trigger carries the same placeholder text.+ const input = page.getByRole('dialog').getByRole('combobox')+ await expect(input).toBeVisible({ timeout: 15_000 })+ return input+}++test.describe('command palette', () => {+ test('opens with the keyboard shortcut', async ({ page }) => {+ const creds = await login(page)+ await page.goto(`/${creds.store_id}`)+ // The shortcut is bound after the shell mounts, so wait for the trigger to+ // appear — pressing earlier lands before the listener exists.+ await expect(+ page.getByRole('button', { name: /search products, orders, customers/i }),+ ).toBeVisible({ timeout: 15_000 })++ // The binding is `Mod+K`, which the hotkey library resolves against the+ // browser's platform rather than the host's. Try both modifiers so the+ // spec passes on a Linux CI runner and a macOS workstation alike.+ const palette = page.getByRole('dialog').getByRole('combobox')+ await page.keyboard.press('Control+k')+ if (!(await palette.isVisible().catch(() => false))) {+ await page.keyboard.press('Meta+k')+ }++ await expect(palette).toBeVisible({ timeout: 15_000 })+ })++ test('"add product" opens the product create page', async ({ page }) => {+ const creds = await login(page)+ const input = await openPalette(page, creds.store_id)++ await input.fill('add product')+ await page.getByRole('option', { name: /new product/i }).click()++ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/products/new`))+ await expect(page.getByRole('heading', { name: /new product/i })).toBeVisible({+ timeout: 15_000,+ })+ })++ // Resources without a dedicated `/new` route open a create sheet on their+ // index page instead, which the action reaches via a `?new=true` search param.+ test('"new customer" opens the create sheet on the customers page', async ({ page }) => {+ const creds = await login(page)+ const input = await openPalette(page, creds.store_id)++ await input.fill('new customer')+ await page.getByRole('option', { name: /^new customer$/i }).click()++ await expect(page).toHaveURL(/[?&]new=true/)+ await expect(page.getByRole('heading', { name: /new customer/i })).toBeVisible({+ timeout: 15_000,+ })+ })++ // A bare verb lists every resource the signed-in user may create, which is+ // also how the palette advertises what this dashboard can create at all.+ test('a bare verb lists the create actions', async ({ page }) => {+ const creds = await login(page)+ const input = await openPalette(page, creds.store_id)++ await input.fill('new')++ await expect(page.getByRole('option', { name: /new product/i })).toBeVisible({+ timeout: 15_000,+ })+ await expect(page.getByRole('option', { name: /^new order$/i })).toBeVisible()+ })++ test('reports when a query matches nothing', async ({ page }) => {+ const creds = await login(page)+ const input = await openPalette(page, creds.store_id)++ await input.fill('zzzznotathing')++ await expect(page.getByText(/no results for/i)).toBeVisible({ timeout: 15_000 })+ })+})diff --git a/packages/dashboard/src/components/spree/command-palette/command-palette.tsx b/packages/dashboard/src/components/spree/command-palette/command-palette.tsxindex a035cf3336..cfde8c2c12 100644--- a/packages/dashboard/src/components/spree/command-palette/command-palette.tsx+++ b/packages/dashboard/src/components/spree/command-palette/command-palette.tsx@@ -1,10 +1,12 @@import {type NavEntry,type Permissions,+ permittedCreateActions,type SearchGroup,type SettingsNavEntry,useAuth,useCommandPalette,+ useCreateActions,useGlobalSearch,useNavEntries,usePermissions,@@ -14,6 +16,7 @@ import {import {Command,CommandEmpty,+ CommandFooter,CommandGroup,CommandInput,CommandItem,@@ -26,7 +29,7 @@ import {DialogTitle,} from '@spree/dashboard-ui'import { useNavigate, useParams } from '@tanstack/react-router'-import { Loader2Icon, LogOutIcon, type LucideIcon, PackageIcon, SettingsIcon } from 'lucide-react'+import { LogOutIcon, type LucideIcon, PackageIcon, PlusIcon, SettingsIcon } from 'lucide-react'import { type ReactNode, useMemo, useState } from 'react'export function CommandPalette() {@@ -66,6 +69,20 @@ function CommandPaletteContent({ setOpen }: { setOpen: (open: boolean) => void }[main, bottom, settingsNav, permissions, storeId, t],)+ // "add product" / "new customer" — matched against the registered create+ // actions, permission-checked with `create` rather than `read`.+ const createActions = useCreateActions()+ const createMatches = useMemo(+ () =>+ permittedCreateActions({+ query: input,+ entries: createActions,+ t,+ can: (action, subject) => permissions.can(action, subject),+ }),+ [input, createActions, permissions, t],+ )+const q = input.trim().toLowerCase()const matches = (label: string) => !q || label.toLowerCase().includes(q)const gotoItems = gotoCommands.filter((c) =>@@ -99,26 +116,54 @@ function CommandPaletteContent({ setOpen }: { setOpen: (open: boolean) => void }value={input}onValueChange={setInput}placeholder={t('admin.components.command_palette.placeholder')}+ loading={isLoading}/><CommandList><SearchStatusisEnabled={isEnabled}isLoading={isLoading}- // "No results" must account for goto/logout commands too, not just- // resource search — a query can match a nav command while the API- // search returns nothing.- hasResults={hasResults || gotoItems.length > 0 || showLogout}+ // "No results" must account for goto/create/logout commands too,+ // not just resource search — a query can match a nav command while+ // the API search returns nothing.+ hasResults={+ hasResults || createMatches.length > 0 || gotoItems.length > 0 || showLogout+ }query={input}/>+ {/* Create actions lead: "add product" states an intent, so burying+ it under products matching the word "add" would be wrong. */}+ {createMatches.length > 0 && (+ <CommandGroup heading={t('admin.components.command_palette.create.heading')}>+ {createMatches.map(({ entry, noun }) => (+ <CommandItem+ key={`create-${entry.key}`}+ value={`create-${entry.key}`}+ onSelect={() => {+ close()+ const route = entry.getRoute(storeId)+ navigate({ to: route.to, search: route.search })+ }}+ >+ {entry.icon ? <entry.icon /> : <PlusIcon />}+ {t('admin.components.command_palette.create.label', { noun })}+ </CommandItem>+ ))}+ </CommandGroup>+ )}++ {createMatches.length > 0 && (hasResults || gotoItems.length > 0) && (+ <CommandSeparator />+ )}+{groups.map((group) => (<ResourceGroupkey={group.entry.key}group={group}storeId={storeId}- onNavigate={(to) => {+ onNavigate={(route) => {close()- navigate({ to })+ navigate({ to: route.to, search: route.search })}}/>))}@@ -160,6 +205,7 @@ function CommandPaletteContent({ setOpen }: { setOpen: (open: boolean) => void }</CommandGroup>)}</CommandList>+ <CommandFooter /></Command></DialogContent></Dialog>@@ -270,7 +316,7 @@ function ResourceGroup({}: {group: SearchGroupstoreId: string- onNavigate: (to: string) => void+ onNavigate: (route: { to: string; search?: Record<string, unknown> }) => void}): ReactNode {const { t } = useTranslation()const { entry, items } = group@@ -280,7 +326,7 @@ function ResourceGroup({<CommandItemkey={`${entry.key}-${entry.getKey(item)}`}value={`${entry.key}-${entry.getKey(item)}`}- onSelect={() => onNavigate(entry.getRoute(item, storeId).to)}+ onSelect={() => onNavigate(entry.getRoute(item, storeId))}>{entry.renderRow(item)}</CommandItem>@@ -301,14 +347,9 @@ function SearchStatus({query: string}): ReactNode {const { t } = useTranslation()- if (isEnabled && isLoading) {- return (- <div className="flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground">- <Loader2Icon className="size-4 animate-spin" />- {t('admin.common.searching')}- </div>- )- }+ // A search in flight shows the spinner in the input, not a row here. Bail out+ // so the list stays empty rather than claiming "no results" mid-request.+ if (isEnabled && isLoading) return nullif (isEnabled && !hasResults) {return (<CommandEmpty>{t('admin.components.command_palette.no_results', { query })}</CommandEmpty>diff --git a/packages/dashboard/src/dashboard.tsx b/packages/dashboard/src/dashboard.tsxindex 1497a06252..16a904b470 100644--- a/packages/dashboard/src/dashboard.tsx+++ b/packages/dashboard/src/dashboard.tsx@@ -10,6 +10,7 @@ import { StrictMode } from 'react'import './i18n-setup'import './nav/default'import './nav/settings'+import './search/create-actions'import './search/default'/**diff --git a/packages/dashboard/src/search/create-actions.ts b/packages/dashboard/src/search/create-actions.tsnew file mode 100644index 0000000000..9bb446a44c--- /dev/null+++ b/packages/dashboard/src/search/create-actions.ts@@ -0,0 +1,165 @@+import { createActionRegistry, Subject } from '@spree/dashboard-core'+import {+ BoxesIcon,+ Building2Icon,+ FolderTreeIcon,+ GiftIcon,+ LayersIcon,+ PackageIcon,+ ShoppingCartIcon,+ SlidersHorizontalIcon,+ StoreIcon,+ TagIcon,+ TicketPercentIcon,+ UserIcon,+ UsersRoundIcon,+} from 'lucide-react'++// Each entry teaches the command palette that one resource can be created, so+// "add product" or "new customer" jumps straight to the right page. Destinations+// come in two shapes, matching how the dashboard creates things: a dedicated+// `/new` route, or an index page whose create sheet opens from `?new=true`.+// Plugins register their own the same way (import `createActionRegistry`).++/** Resolves to the singular noun key; `${name}_plural` holds the plural form. */+const noun = (name: string) => `admin.components.command_palette.create.nouns.${name}`++createActionRegistry.add({+ key: 'product',+ labelKey: noun('product'),+ aliasKeys: [noun('product_plural')],+ icon: TagIcon,+ subject: Subject.Product,+ position: 100,+ getRoute: (storeId) => ({ to: `/${storeId}/products/new` }),+})++createActionRegistry.add({+ key: 'category',+ labelKey: noun('category'),+ aliasKeys: [noun('category_plural')],+ icon: FolderTreeIcon,+ subject: Subject.Category,+ position: 110,+ getRoute: (storeId) => ({ to: `/${storeId}/products/categories/new` }),+})++createActionRegistry.add({+ key: 'collection',+ labelKey: noun('collection'),+ aliasKeys: [noun('collection_plural')],+ icon: LayersIcon,+ subject: Subject.Collection,+ position: 120,+ getRoute: (storeId) => ({ to: `/${storeId}/products/collections/new` }),+})++createActionRegistry.add({+ key: 'price_list',+ labelKey: noun('price_list'),+ aliasKeys: [noun('price_list_plural')],+ icon: TagIcon,+ subject: Subject.PriceList,+ position: 130,+ getRoute: (storeId) => ({ to: `/${storeId}/products/price-lists/new` }),+})++createActionRegistry.add({+ key: 'order',+ labelKey: noun('order'),+ aliasKeys: [noun('order_plural')],+ icon: ShoppingCartIcon,+ subject: Subject.Order,+ position: 200,+ getRoute: (storeId) => ({ to: `/${storeId}/orders/new` }),+})++createActionRegistry.add({+ key: 'customer',+ labelKey: noun('customer'),+ aliasKeys: [noun('customer_plural')],+ icon: UserIcon,+ subject: Subject.Customer,+ position: 300,+ getRoute: (storeId) => ({ to: `/${storeId}/customers`, search: { new: true } }),+})++createActionRegistry.add({+ key: 'customer_group',+ labelKey: noun('customer_group'),+ aliasKeys: [noun('customer_group_plural')],+ icon: UsersRoundIcon,+ subject: Subject.CustomerGroup,+ position: 310,+ getRoute: (storeId) => ({ to: `/${storeId}/customers/groups`, search: { new: true } }),+})++createActionRegistry.add({+ key: 'company',+ labelKey: noun('company'),+ aliasKeys: [noun('company_plural')],+ icon: Building2Icon,+ subject: Subject.Company,+ position: 320,+ getRoute: (storeId) => ({ to: `/${storeId}/companies`, search: { new: true } }),+})++createActionRegistry.add({+ key: 'seller',+ labelKey: noun('seller'),+ aliasKeys: [noun('seller_plural')],+ icon: StoreIcon,+ subject: Subject.Seller,+ position: 330,+ getRoute: (storeId) => ({ to: `/${storeId}/sellers`, search: { new: true } }),+})++createActionRegistry.add({+ key: 'promotion',+ labelKey: noun('promotion'),+ aliasKeys: [noun('promotion_plural'), noun('discount'), noun('discount_plural')],+ icon: TicketPercentIcon,+ subject: Subject.Promotion,+ position: 400,+ getRoute: (storeId) => ({ to: `/${storeId}/promotions/new` }),+})++createActionRegistry.add({+ key: 'gift_card',+ labelKey: noun('gift_card'),+ aliasKeys: [noun('gift_card_plural')],+ icon: GiftIcon,+ subject: Subject.GiftCard,+ position: 410,+ getRoute: (storeId) => ({ to: `/${storeId}/promotions/gift-cards`, search: { new: true } }),+})++createActionRegistry.add({+ key: 'option_type',+ labelKey: noun('option_type'),+ aliasKeys: [noun('option_type_plural')],+ icon: SlidersHorizontalIcon,+ subject: Subject.OptionType,+ position: 500,+ getRoute: (storeId) => ({ to: `/${storeId}/products/options`, search: { new: true } }),+})++createActionRegistry.add({+ key: 'stock_transfer',+ labelKey: noun('stock_transfer'),+ aliasKeys: [noun('stock_transfer_plural')],+ icon: BoxesIcon,+ subject: Subject.StockTransfer,+ position: 510,+ getRoute: (storeId) => ({ to: `/${storeId}/products/transfers`, search: { new: true } }),+})++createActionRegistry.add({+ key: 'stock_location',+ labelKey: noun('stock_location'),+ aliasKeys: [noun('stock_location_plural')],+ icon: PackageIcon,+ subject: Subject.StockLocation,+ position: 520,+ getRoute: (storeId) => ({ to: `/${storeId}/settings/stock-locations`, search: { new: true } }),+})diff --git a/packages/dashboard/src/search/default.tsx b/packages/dashboard/src/search/default.tsxindex bd8a39166d..ca94a09777 100644--- a/packages/dashboard/src/search/default.tsx+++ b/packages/dashboard/src/search/default.tsx@@ -1,15 +1,26 @@-import type { Category, Collection, Customer, Order, Product, Promotion } from '@spree/admin-sdk'+import type {+ Category,+ Collection,+ Company,+ Customer,+ CustomerGroup,+ Order,+ Product,+ Promotion,+ Seller,+} from '@spree/admin-sdk'import { adminClient, defineSearchEntry, Subject, searchRegistry } from '@spree/dashboard-core'-import { cn, StatusBadge } from '@spree/dashboard-ui'+import { StatusBadge, Thumbnail } from '@spree/dashboard-ui'import {+ Building2Icon,FolderTreeIcon,LayersIcon,ShoppingCartIcon,- TagIcon,+ StoreIcon,TicketPercentIcon,- UsersIcon,+ UserIcon,+ UsersRoundIcon,} from 'lucide-react'-import type { ReactNode } from 'react'import { useTranslation } from 'react-i18next'// Each entry teaches the command palette how to search one resource: how to@@ -31,10 +42,10 @@ searchRegistry.add(// duplicates ("… 18V" / "… 25V") differ only in stock and price.renderRow: (p) => (<>- <IconOrThumbnail- thumbnailUrl={p.primary_media?.mini_url ?? p.thumbnail_url ?? null}- icon={<TagIcon />}- size="lg"+ <Thumbnail+ src={p.primary_media?.mini_url ?? p.thumbnail_url}+ size="sm"+ className="self-start"/><span className="flex min-w-0 flex-1 flex-col gap-0.5"><span className="flex items-center gap-2">@@ -65,9 +76,10 @@ searchRegistry.add(getRoute: (c, storeId) => ({ to: `/${storeId}/products/categories/${c.id}` }),renderRow: (c) => (<>- <IconOrThumbnail- thumbnailUrl={c.square_image_url ?? c.image_url ?? null}- icon={<FolderTreeIcon />}+ <Thumbnail+ src={c.square_image_url ?? c.image_url}+ size="xs"+ fallback={<FolderTreeIcon />}/><span className="flex-1 truncate">{c.pretty_name}</span></>@@ -87,10 +99,7 @@ searchRegistry.add(getRoute: (c, storeId) => ({ to: `/${storeId}/products/collections/${c.id}` }),renderRow: (c) => (<>- <IconOrThumbnail- thumbnailUrl={c.square_image_url ?? c.image_url ?? null}- icon={<LayersIcon />}- />+ <Thumbnail src={c.square_image_url ?? c.image_url} size="xs" fallback={<LayersIcon />} /><span className="flex-1 truncate">{c.name}</span></>),@@ -108,7 +117,7 @@ searchRegistry.add(getRoute: (o, storeId) => ({ to: `/${storeId}/orders/${o.id}` }),renderRow: (o) => (<>- <ShoppingCartIcon />+ <Thumbnail size="xs" fallback={<ShoppingCartIcon />} /><span className="flex-1 truncate"><span className="font-mono">{o.number}</span>{o.email && <span className="ml-2 text-muted-foreground">{o.email}</span>}@@ -130,7 +139,7 @@ searchRegistry.add(getRoute: (c, storeId) => ({ to: `/${storeId}/customers/${c.id}` }),renderRow: (c) => (<>- <UsersIcon />+ <Thumbnail size="xs" shape="circle" fallback={<UserIcon />} /><span className="flex-1 truncate">{c.full_name || c.email}{c.full_name && <span className="ml-2 text-muted-foreground">{c.email}</span>}@@ -140,6 +149,68 @@ searchRegistry.add(}),)+searchRegistry.add(+ defineSearchEntry<CustomerGroup>({+ key: 'customer_groups',+ headingKey: 'admin.nav.customer_groups',+ subject: Subject.CustomerGroup,+ position: 310,+ fetch: (search, limit) =>+ adminClient.customerGroups+ .list({ name_cont: search, limit, sort: 'name' })+ .then((r) => r.data),+ getKey: (g) => g.id,+ // Groups have no detail page — they are edited in a sheet on the groups+ // page, which `?edit=` opens directly.+ getRoute: (g, storeId) => ({ to: `/${storeId}/customers/groups`, search: { edit: g.id } }),+ renderRow: (g) => (+ <>+ <Thumbnail size="xs" fallback={<UsersRoundIcon />} />+ <span className="flex-1 truncate">{g.name}</span>+ </>+ ),+ }),+)++searchRegistry.add(+ defineSearchEntry<Company>({+ key: 'companies',+ headingKey: 'admin.nav.companies',+ subject: Subject.Company,+ position: 320,+ fetch: (search, limit) =>+ adminClient.companies.list({ name_cont: search, limit, sort: 'name' }).then((r) => r.data),+ getKey: (c) => c.id,+ getRoute: (c, storeId) => ({ to: `/${storeId}/companies/${c.id}` }),+ renderRow: (c) => (+ <>+ <Thumbnail size="xs" fallback={<Building2Icon />} />+ <span className="flex-1 truncate">{c.name}</span>+ </>+ ),+ }),+)++searchRegistry.add(+ defineSearchEntry<Seller>({+ key: 'sellers',+ headingKey: 'admin.nav.sellers',+ subject: Subject.Seller,+ position: 330,+ fetch: (search, limit) =>+ adminClient.sellers.list({ name_cont: search, limit, sort: 'name' }).then((r) => r.data),+ getKey: (s) => s.id,+ getRoute: (s, storeId) => ({ to: `/${storeId}/sellers/${s.id}` }),+ renderRow: (s) => (+ <>+ <Thumbnail src={s.square_logo_url ?? s.logo_url} size="xs" fallback={<StoreIcon />} />+ <span className="flex-1 truncate">{s.name}</span>+ <StatusBadge status={s.status} />+ </>+ ),+ }),+)+searchRegistry.add(defineSearchEntry<Promotion>({key: 'promotions',@@ -154,7 +225,7 @@ searchRegistry.add(getRoute: (p, storeId) => ({ to: `/${storeId}/promotions/${p.id}` }),renderRow: (p) => (<>- <TicketPercentIcon />+ <Thumbnail size="xs" fallback={<TicketPercentIcon />} /><span className="flex-1 truncate">{p.name}</span>{p.code && (<span className="ml-2 shrink-0 font-mono text-xs text-muted-foreground">{p.code}</span>@@ -164,40 +235,6 @@ searchRegistry.add(}),)-/**- * A result row's thumbnail, falling back to the resource's own icon.- *- * Deliberately not `Thumbnail`: search results without an image show a bare- * glyph rather than an empty framed box, so a category or a page does not look- * like a product whose photo failed to load.- */-function IconOrThumbnail({- thumbnailUrl,- icon,- size = 'sm',-}: {- thumbnailUrl: string | null- icon: ReactNode- /** `lg` for the two-line product row, whose taller row a 20px image floats in. */- size?: 'sm' | 'lg'-}) {- if (!thumbnailUrl) {- // Keep the icon on the first line rather than centred against two.- return size === 'lg' ? <span className="self-start pt-0.5">{icon}</span> : icon- }- return (- <img- src={thumbnailUrl}- alt=""- className={cn(- 'shrink-0 rounded object-cover',- size === 'lg' ? 'size-8 self-start' : 'size-5',- )}- loading="lazy"- />- )-}-/** Stock and price beneath a product's name — the pair that tells near-identical* variants apart. Renders nothing when neither is known. */function ProductMeta({ product }: { product: Product }) {