@vendure-io/ui 3.0.0-next.0 → 3.0.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/package.json +2 -2
  2. package/src/components/atoms/alert.tsx +13 -6
  3. package/src/components/atoms/avatar.tsx +11 -3
  4. package/src/components/atoms/breadcrumb.tsx +467 -53
  5. package/src/components/atoms/button.tsx +1 -1
  6. package/src/components/atoms/calendar.tsx +11 -2
  7. package/src/components/atoms/combobox.tsx +220 -17
  8. package/src/components/atoms/command.tsx +51 -130
  9. package/src/components/atoms/dialog.tsx +23 -1
  10. package/src/components/atoms/empty.tsx +1 -1
  11. package/src/components/atoms/field.tsx +4 -1
  12. package/src/components/atoms/input-group.tsx +2 -2
  13. package/src/components/atoms/label-swap.tsx +59 -3
  14. package/src/components/atoms/popover.tsx +6 -1
  15. package/src/components/atoms/sheet.tsx +18 -1
  16. package/src/components/atoms/sidebar.tsx +73 -1
  17. package/src/components/atoms/sonner.tsx +1 -1
  18. package/src/components/atoms/table.tsx +133 -10
  19. package/src/components/atoms/tooltip.tsx +3 -3
  20. package/src/components/molecules/chip.tsx +43 -4
  21. package/src/components/molecules/confirm-dialog.tsx +9 -0
  22. package/src/components/molecules/count-badge.tsx +115 -0
  23. package/src/components/molecules/data-table/data-table-filters.tsx +61 -21
  24. package/src/components/molecules/data-table/data-table-helpers.tsx +26 -1
  25. package/src/components/molecules/data-table/data-table-types.tsx +66 -2
  26. package/src/components/molecules/data-table/data-table.tsx +190 -35
  27. package/src/components/molecules/direction-link.tsx +1 -1
  28. package/src/components/molecules/format-provider.tsx +12 -2
  29. package/src/components/molecules/page-header.tsx +1 -1
  30. package/src/components/molecules/search-trigger.tsx +2 -18
  31. package/src/components/molecules/secret-value.tsx +6 -3
  32. package/src/components/molecules/state-views/loading-state.tsx +37 -7
  33. package/src/components/molecules/state-views/skeleton-parts.tsx +245 -0
  34. package/src/components/molecules/status-badge.tsx +2 -2
  35. package/src/components/molecules/timeline.tsx +1 -1
  36. package/src/hooks/use-active-label-size.ts +39 -5
  37. package/src/hooks/use-apple-platform.ts +26 -0
  38. package/src/lib/utils.ts +0 -7
@@ -15,7 +15,7 @@ import {
15
15
  InputGroupButton,
16
16
  InputGroupInput,
17
17
  } from "@vendure-io/ui/components/atoms/input-group"
18
- import { ChevronDownIcon, XIcon } from "lucide-react"
18
+ import { ChevronDownIcon, Loader2Icon, XIcon } from "lucide-react"
19
19
  import { usePopupDir } from "../../lib/popup-direction.ts"
20
20
  import { usePopupAlign } from "../../lib/popup-align.ts"
21
21
  import { hasName, nameFrom, useRegisteredRef } from "../../lib/control-name.ts"
@@ -35,15 +35,116 @@ type ComboboxControls = {
35
35
 
36
36
  const ComboboxControlsContext = React.createContext<ComboboxControls | null>(null)
37
37
 
38
- function Combobox<Value, Multiple extends boolean | undefined = false, Item = Value>(
39
- props: ComboboxPrimitive.Root.Props<Value, Multiple, Item>
40
- ) {
38
+ type ComboboxPagingProps = {
39
+ /**
40
+ * Asks for the next page of a server-searched list. Called once when the
41
+ * list scrolls near its end, or the arrow keys reach its last option, while
42
+ * `hasMore` is set and `loading` is not. It is called again once the
43
+ * options change, the search changes, the list reopens, or the list
44
+ * scrolls away from its end and back: a failed fetch is retried by
45
+ * scrolling, never in a loop.
46
+ */
47
+ onLoadMore?: () => void
48
+ /** There is a next page for `onLoadMore` to fetch. */
49
+ hasMore?: boolean
50
+ /**
51
+ * A page is loading: the list shows a loading row at its end, is busy for
52
+ * assistive technology and announces `loadingLabel`. With no options yet,
53
+ * the loading row takes the place of ComboboxEmpty.
54
+ */
55
+ loading?: boolean
56
+ /** Announced to screen readers while `loading` is set. */
57
+ loadingLabel?: string
58
+ }
59
+
60
+ /**
61
+ * The paging state of the nearest Combobox, for its list and its empty state.
62
+ * Null when the Combobox takes none of the paging props.
63
+ */
64
+ type ComboboxPaging = {
65
+ loading: boolean
66
+ loadingLabel: string
67
+ canLoadMore: boolean
68
+ list: HTMLElement | null
69
+ setList: (list: HTMLElement | null) => void
70
+ /** Calls `onLoadMore` once per set of options. */
71
+ requestMore: () => void
72
+ /** Lets the next request through: the options or the search changed. */
73
+ rearm: () => void
74
+ }
75
+
76
+ const ComboboxPagingContext = React.createContext<ComboboxPaging | null>(null)
77
+
78
+ function Combobox<Value, Multiple extends boolean | undefined = false, Item = Value>({
79
+ onLoadMore,
80
+ hasMore = false,
81
+ loading,
82
+ loadingLabel = "Loading…",
83
+ onItemHighlighted,
84
+ onInputValueChange,
85
+ ...props
86
+ }: ComboboxPrimitive.Root.Props<Value, Multiple, Item> & ComboboxPagingProps) {
41
87
  const [trigger, setTrigger] = React.useState<HTMLElement | null>(null)
42
88
  const [input, setInput] = React.useState<HTMLElement | null>(null)
89
+ const [list, setList] = React.useState<HTMLElement | null>(null)
43
90
  const controls = React.useMemo(() => ({ trigger, input, setTrigger, setInput }), [trigger, input])
91
+
92
+ // Read at call time, so an observer set up on an earlier render sees the
93
+ // current flags.
94
+ const latest = React.useRef({ onLoadMore, hasMore, loading })
95
+ React.useLayoutEffect(() => {
96
+ latest.current = { onLoadMore, hasMore, loading }
97
+ })
98
+ // Set once a page is asked for. Scrolling fires many events before the
99
+ // consumer's `loading` flag turns on; the latch keeps that to one call.
100
+ const latched = React.useRef(false)
101
+ const requestMore = React.useCallback(() => {
102
+ const current = latest.current
103
+ if (!current.onLoadMore || !current.hasMore || current.loading || latched.current) return
104
+ latched.current = true
105
+ current.onLoadMore()
106
+ }, [])
107
+ const rearm = React.useCallback(() => {
108
+ latched.current = false
109
+ }, [])
110
+
111
+ const canLoadMore = onLoadMore !== undefined
112
+ const enabled = canLoadMore || loading !== undefined
113
+ const paging = React.useMemo(
114
+ () =>
115
+ enabled
116
+ ? {
117
+ loading: !!loading,
118
+ loadingLabel,
119
+ canLoadMore,
120
+ list,
121
+ setList,
122
+ requestMore,
123
+ rearm,
124
+ }
125
+ : null,
126
+ [enabled, loading, loadingLabel, canLoadMore, list, requestMore, rearm]
127
+ )
128
+
44
129
  return (
45
130
  <ComboboxControlsContext.Provider value={controls}>
46
- <ComboboxPrimitive.Root {...props} />
131
+ <ComboboxPagingContext.Provider value={paging}>
132
+ <ComboboxPrimitive.Root
133
+ {...props}
134
+ onInputValueChange={(value, details) => {
135
+ rearm()
136
+ onInputValueChange?.(value, details)
137
+ }}
138
+ onItemHighlighted={(value, details) => {
139
+ onItemHighlighted?.(value, details)
140
+ // The arrow keys reached the last option: load the next page, as
141
+ // scrolling there would. Counted from the DOM, so groups and rows
142
+ // that are not part of the page line up.
143
+ if (details.reason !== "keyboard" || !list) return
144
+ if (details.index === list.querySelectorAll("[role=option]").length - 1) requestMore()
145
+ }}
146
+ />
147
+ </ComboboxPagingContext.Provider>
47
148
  </ComboboxControlsContext.Provider>
48
149
  )
49
150
  }
@@ -248,18 +349,111 @@ function ComboboxContent({
248
349
  )
249
350
  }
250
351
 
251
- function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
352
+ /** How near the end of the list, in pixels, the next page starts to load. */
353
+ const LOAD_MORE_THRESHOLD = 64
354
+
355
+ /**
356
+ * Asks for the next page when the end of the list is in view or near it:
357
+ * when the list opens, when it scrolls (the arrow keys scroll it too), and
358
+ * when its options change, so a page shorter than the list fills it. A new
359
+ * set of options, a reopened list, or a scroll away from the end lets the
360
+ * next request through.
361
+ */
362
+ function useLoadMore(paging: ComboboxPaging | null, end: React.RefObject<HTMLElement | null>) {
363
+ const list = paging?.list ?? null
364
+ const canLoadMore = !!paging?.canLoadMore
365
+ const requestMore = paging?.requestMore
366
+ const rearm = paging?.rearm
367
+ React.useEffect(() => {
368
+ if (!list || !canLoadMore || !requestMore || !rearm) return
369
+ const check = () => {
370
+ const marker = end.current
371
+ if (!marker || !list.isConnected) return
372
+ if (marker.getBoundingClientRect().top - list.getBoundingClientRect().bottom <= LOAD_MORE_THRESHOLD) {
373
+ requestMore()
374
+ } else {
375
+ rearm()
376
+ }
377
+ }
378
+ const options = () => list.querySelectorAll("[role=option]").length
379
+ let count = options()
380
+ // A page may have landed while the list was closed.
381
+ rearm()
382
+ const observer = new MutationObserver(() => {
383
+ const next = options()
384
+ if (next === count) return
385
+ count = next
386
+ rearm()
387
+ check()
388
+ })
389
+ observer.observe(list, { childList: true, subtree: true })
390
+ list.addEventListener("scroll", check, { passive: true })
391
+ // After the popup has its size.
392
+ const frame = requestAnimationFrame(check)
393
+ return () => {
394
+ cancelAnimationFrame(frame)
395
+ observer.disconnect()
396
+ list.removeEventListener("scroll", check)
397
+ }
398
+ }, [list, canLoadMore, requestMore, rearm, end])
399
+ }
400
+
401
+ function ComboboxList({ className, children, ref, ...props }: ComboboxPrimitive.List.Props) {
252
402
  const name = useComboboxName()
403
+ const paging = React.useContext(ComboboxPagingContext)
404
+ const listRef = useRegisteredRef(ref, paging?.setList)
405
+ const endRef = React.useRef<HTMLDivElement | null>(null)
406
+ useLoadMore(paging, endRef)
407
+ // A paged list adds rows after the options, so a render function is
408
+ // wrapped in the Collection the primitive would wrap it in.
409
+ const items =
410
+ paging && typeof children === "function" ? (
411
+ <ComboboxPrimitive.Collection>{children}</ComboboxPrimitive.Collection>
412
+ ) : (
413
+ children
414
+ )
253
415
  return (
254
- <ComboboxPrimitive.List
255
- {...(hasName(props) ? {} : name)}
256
- data-slot="combobox-list"
257
- className={cn(
258
- "no-scrollbar max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",
259
- className
416
+ <>
417
+ <ComboboxPrimitive.List
418
+ {...(hasName(props) ? {} : name)}
419
+ ref={listRef}
420
+ data-slot="combobox-list"
421
+ aria-busy={paging?.loading || undefined}
422
+ className={cn(
423
+ "no-scrollbar max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",
424
+ className
425
+ )}
426
+ {...props}
427
+ >
428
+ {paging ? (
429
+ <>
430
+ {items}
431
+ {/* Decorative: a listbox holds only options and groups, so the
432
+ row is hidden from assistive technology. The list is busy
433
+ and the status below announces the load. */}
434
+ {paging.loading && (
435
+ <div
436
+ data-slot="combobox-loading"
437
+ aria-hidden="true"
438
+ className="text-muted-foreground flex min-h-8.5 items-center justify-center"
439
+ >
440
+ <Loader2Icon className="size-4 motion-safe:animate-spin" />
441
+ </div>
442
+ )}
443
+ {paging.canLoadMore && <div ref={endRef} data-slot="combobox-list-end" aria-hidden="true" />}
444
+ </>
445
+ ) : (
446
+ children
447
+ )}
448
+ </ComboboxPrimitive.List>
449
+ {/* Stays mounted, so screen readers announce the change. Outside the
450
+ listbox, which may hold only options and groups. */}
451
+ {paging && (
452
+ <ComboboxPrimitive.Status data-slot="combobox-status" className="sr-only">
453
+ {paging.loading ? paging.loadingLabel : null}
454
+ </ComboboxPrimitive.Status>
260
455
  )}
261
- {...props}
262
- />
456
+ </>
263
457
  )
264
458
  }
265
459
 
@@ -321,12 +515,16 @@ function ComboboxCollection({ ...props }: ComboboxPrimitive.Collection.Props) {
321
515
  )
322
516
  }
323
517
 
518
+ // While a page loads, the list's loading row stands in for the empty state:
519
+ // a new search has no options yet, but it is not empty.
324
520
  function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
521
+ const loading = !!React.useContext(ComboboxPagingContext)?.loading
325
522
  return (
326
523
  <ComboboxPrimitive.Empty
327
524
  data-slot="combobox-empty"
328
525
  className={cn(
329
526
  "text-muted-foreground hidden w-full justify-center py-2 text-center text-sm group-data-empty/combobox-content:flex",
527
+ loading && "group-data-empty/combobox-content:hidden",
330
528
  className
331
529
  )}
332
530
  {...props}
@@ -357,7 +555,7 @@ function ComboboxChips({
357
555
  data-slot="combobox-chips"
358
556
  className={cn(
359
557
  fieldSurfaceWithin,
360
- "flex min-h-8.5 flex-wrap items-center gap-1.5 px-2.5 py-1.5 text-sm has-data-[slot=combobox-chip]:px-1.5",
558
+ "flex min-h-8.5 flex-wrap items-center gap-1.5 px-2.5 py-1.5 text-sm has-data-[slot=combobox-chip]:p-1.25",
361
559
  className
362
560
  )}
363
561
  {...props}
@@ -367,6 +565,11 @@ function ComboboxChips({
367
565
 
368
566
  // A chip is the v3 look's grey chip: the accent fill, one step above the
369
567
  // muted field it sits on, with a grey outline, so each value stands out.
568
+ // It has the Chip height, 24px, and is denser than a standalone Chip: the
569
+ // label is 8px from the edge, so a field fits more of them. In the 34px
570
+ // field it sits 5px from the edge, so its corner is the field's 6px minus that
571
+ // 5px, 1px. The remove button sits 4px inside the chip, so its corner is the
572
+ // chip's 1px minus 4px, which is square.
370
573
  function ComboboxChip({
371
574
  className,
372
575
  children,
@@ -382,7 +585,7 @@ function ComboboxChip({
382
585
  <ComboboxPrimitive.Chip
383
586
  data-slot="combobox-chip"
384
587
  className={cn(
385
- "bg-accent [--status-tone:var(--neutral-text)]", statusChipRing, "text-foreground flex h-[calc(--spacing(5.5))] w-fit items-center justify-center gap-1 rounded-sm px-1.5 text-xs font-medium whitespace-nowrap has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pe-0",
588
+ "bg-accent [--status-tone:var(--neutral-text)]", statusChipRing, "text-foreground flex h-6 w-fit items-center justify-center gap-1.5 rounded-[calc(var(--radius-lg)-5px)] ps-2 pe-2 text-xs font-medium whitespace-nowrap has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pe-1",
386
589
  className
387
590
  )}
388
591
  {...props}
@@ -391,7 +594,7 @@ function ComboboxChip({
391
594
  {showRemove && (
392
595
  <ComboboxPrimitive.ChipRemove
393
596
  render={<Button variant="ghost" size="icon-xs" />}
394
- className="-ms-1 opacity-50 hover:opacity-100"
597
+ className="size-4 rounded-none [--button-box:--spacing(4)] opacity-50 hover:opacity-100"
395
598
  data-slot="combobox-chip-remove"
396
599
  aria-label={removeLabel}
397
600
  >
@@ -64,7 +64,7 @@ function CommandDialog({
64
64
  <DialogContent
65
65
  data-command-palette=""
66
66
  className={cn(
67
- "shadow-overlay top-[12vh] translate-y-0 gap-0 overflow-hidden rounded-3xl! p-0 ring-0 sm:max-w-150 origin-top transition-[opacity,scale,translate] duration-[var(--transition-duration-palette-enter),var(--transition-duration-palette-move),var(--transition-duration-palette-move)] motion-safe:data-starting-style:-translate-y-1.5 motion-safe:data-starting-style:scale-98 data-ending-style:duration-palette-exit data-ending-style:ease-[var(--ease-soft),var(--ease-out),var(--ease-out)] motion-safe:data-ending-style:scale-98 motion-reduce:transition-opacity motion-reduce:duration-palette-tint motion-reduce:ease-soft",
67
+ "shadow-overlay top-[12vh] translate-y-0 gap-0 overflow-hidden rounded-3xl! p-0 ring-0 sm:max-w-150 origin-top transition-[opacity,scale,translate] duration-[var(--transition-duration-palette-enter),var(--transition-duration-palette-move),var(--transition-duration-palette-move)] motion-safe:data-starting-style:-translate-y-1.5 motion-safe:data-starting-style:scale-98 data-ending-style:duration-palette-exit data-ending-style:ease-[var(--ease-soft),var(--ease-out),var(--ease-out)] motion-safe:data-ending-style:scale-98 motion-reduce:transition-opacity motion-reduce:duration-quick motion-reduce:ease-soft",
68
68
  className
69
69
  )}
70
70
  showCloseButton={showCloseButton}
@@ -80,8 +80,15 @@ function CommandDialog({
80
80
 
81
81
  function CommandInput({
82
82
  className,
83
+ end,
83
84
  ...props
84
- }: React.ComponentProps<typeof CommandPrimitive.Input>) {
85
+ }: React.ComponentProps<typeof CommandPrimitive.Input> & {
86
+ /**
87
+ * Content at the end of the field, such as a `Kbd` with the key that closes
88
+ * the palette. It sits in an end addon, so the input never runs under it.
89
+ */
90
+ end?: React.ReactNode
91
+ }) {
85
92
  return (
86
93
  // Unboxed: the input runs edge to edge above a hairline, with no field
87
94
  // border, fill or ring. 54px with 16px text in the palette dialog.
@@ -98,23 +105,22 @@ function CommandInput({
98
105
  <InputGroupAddon>
99
106
  <SearchIcon className="size-4 shrink-0 opacity-50" />
100
107
  </InputGroupAddon>
108
+ {end != null && (
109
+ <InputGroupAddon align="inline-end" className="pe-0">
110
+ {end}
111
+ </InputGroupAddon>
112
+ )}
101
113
  </InputGroup>
102
114
  </div>
103
115
  )
104
116
  }
105
117
 
106
- // In the palette, results that appear after the first render (a new query)
107
- // fade in from a 3px blur, 50ms after the old results start to leave. Rows that
108
- // stay are not touched: cmdk re-inserts them when it sorts, so the ghost marks
109
- // every shown result data-result-seen before the query changes. The colour
110
- // transition is the palette item's own (see CommandItem). Reduced motion drops
111
- // the blur.
112
- const ENTERING_RESULTS =
113
- "[&[data-results-ready]_:is([cmdk-item],[cmdk-group-heading],[cmdk-empty]):not([data-result-seen],[data-slot=command-results-ghost]_*)]:transition-[color,opacity,filter] [&[data-results-ready]_:is([cmdk-item],[cmdk-group-heading],[cmdk-empty]):not([data-result-seen],[data-slot=command-results-ghost]_*)]:duration-[var(--transition-duration-palette-tint),var(--transition-duration-normal),var(--transition-duration-palette-result-blur)] [&[data-results-ready]_:is([cmdk-item],[cmdk-group-heading],[cmdk-empty]):not([data-result-seen],[data-slot=command-results-ghost]_*)]:delay-[var(--transition-duration-instant),var(--transition-duration-palette-result-delay),var(--transition-duration-palette-result-delay)] [&[data-results-ready]_:is([cmdk-item],[cmdk-group-heading],[cmdk-empty]):not([data-result-seen],[data-slot=command-results-ghost]_*)]:ease-[var(--ease-soft),var(--ease-soft),var(--ease-out)] [&[data-results-ready]_:is([cmdk-item],[cmdk-group-heading],[cmdk-empty]):not([data-result-seen],[data-slot=command-results-ghost]_*)]:starting:opacity-0 motion-safe:[&[data-results-ready]_:is([cmdk-item],[cmdk-group-heading],[cmdk-empty]):not([data-result-seen],[data-slot=command-results-ghost]_*)]:starting:blur-[3px]"
114
-
115
118
  // cmdk measures the list's content and writes it to --cmdk-list-height, so the
116
119
  // list eases to its new height as results change. The first measure is not
117
120
  // animated (the height starts as auto). Reduced motion drops the animation.
121
+ // The palette list has no motion: a search is typed fast, and each keystroke
122
+ // must show its results at once. It takes its content's height (capped by
123
+ // max-h) in the same frame, not cmdk's measure, which lands a frame later.
118
124
  function CommandList({
119
125
  className,
120
126
  slidingHighlight = false,
@@ -123,8 +129,9 @@ function CommandList({
123
129
  }: React.ComponentProps<typeof CommandPrimitive.List> & {
124
130
  /**
125
131
  * Draws the selected item's highlight as one fill that follows the
126
- * selection from item to item, and eases the list's scroll with it. Off by
127
- * default: each item then fills itself.
132
+ * selection from item to item, and eases the list's scroll with it. In the
133
+ * palette it jumps to the selected item in the same frame. Off by default:
134
+ * each item then fills itself.
128
135
  */
129
136
  slidingHighlight?: boolean
130
137
  }) {
@@ -133,120 +140,17 @@ function CommandList({
133
140
  data-slot="command-list"
134
141
  data-highlight={slidingHighlight ? "slide" : undefined}
135
142
  className={cn(
136
- "no-scrollbar h-(--cmdk-list-height) max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto overscroll-contain outline-none transition-[height] duration-normal ease-height in-data-command-palette:max-h-95 motion-reduce:transition-none *:[[cmdk-list-sizer]]:relative *:[[cmdk-list-sizer]]:p-1",
137
- ENTERING_RESULTS,
143
+ "no-scrollbar h-(--cmdk-list-height) max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto overscroll-contain outline-none transition-[height] duration-normal ease-height in-data-command-palette:h-auto in-data-command-palette:max-h-95 in-data-command-palette:transition-none motion-reduce:transition-none *:[[cmdk-list-sizer]]:relative *:[[cmdk-list-sizer]]:p-1",
138
144
  className
139
145
  )}
140
146
  {...props}
141
147
  >
142
148
  {slidingHighlight && <CommandHighlight />}
143
- <CommandResultsGhost />
144
149
  {children}
145
150
  </CommandPrimitive.List>
146
151
  )
147
152
  }
148
153
 
149
- // The palette's results crossfade. Just before the query changes (beforeinput),
150
- // a copy of the current results goes into this layer, at the place they were
151
- // shown, and fades out with a 3px blur (opacity 140ms, blur 160ms) while the
152
- // new results fade in under it. Only in the palette (a CommandList in
153
- // CommandDialog). Reduced motion skips the copy: new results only fade in.
154
- function CommandResultsGhost() {
155
- const ref = React.useRef<HTMLDivElement>(null)
156
-
157
- React.useLayoutEffect(() => {
158
- const ghost = ref.current
159
- const sizer = ghost?.parentElement
160
- const list = sizer?.closest<HTMLElement>("[cmdk-list]")
161
- const root = sizer?.closest("[cmdk-root]")
162
- if (
163
- !ghost ||
164
- !sizer ||
165
- !list ||
166
- !root ||
167
- !list.closest("[data-command-palette]")
168
- ) {
169
- return
170
- }
171
- const reduced = window.matchMedia("(prefers-reduced-motion: reduce)")
172
- let timer = 0
173
-
174
- // Results rendered from now on are new: they fade in.
175
- const frame = requestAnimationFrame(() => {
176
- list.dataset.resultsReady = ""
177
- })
178
-
179
- const onBeforeInput = (event: Event) => {
180
- if (!(event.target instanceof HTMLInputElement)) {
181
- return
182
- }
183
- // Results shown now stay still if the new query keeps them.
184
- for (const result of Array.from(
185
- sizer.querySelectorAll<HTMLElement>(
186
- "[cmdk-item],[cmdk-group-heading],[cmdk-empty]"
187
- )
188
- )) {
189
- if (ghost.contains(result)) {
190
- continue
191
- }
192
- if (result.offsetParent) {
193
- result.dataset.resultSeen = ""
194
- } else {
195
- delete result.dataset.resultSeen
196
- }
197
- }
198
- if (reduced.matches) {
199
- return
200
- }
201
- const copies: Node[] = []
202
- for (const child of Array.from(sizer.children)) {
203
- if (
204
- child === ghost ||
205
- child.getAttribute("data-slot") === "command-highlight"
206
- ) {
207
- continue
208
- }
209
- const copy = child.cloneNode(true) as HTMLElement
210
- // The copy must not answer cmdk's or the highlight's item queries.
211
- for (const node of [copy, ...Array.from(copy.querySelectorAll("*"))]) {
212
- node.removeAttribute("id")
213
- node.removeAttribute("cmdk-item")
214
- node.removeAttribute("cmdk-empty")
215
- node.removeAttribute("data-result-seen")
216
- }
217
- copies.push(copy)
218
- }
219
- ghost.replaceChildren(...copies)
220
- // A new query scrolls the list to the top: keep the copy where it was.
221
- ghost.style.top = `${-list.scrollTop}px`
222
- delete ghost.dataset.leaving
223
- void ghost.offsetHeight
224
- ghost.dataset.leaving = ""
225
- window.clearTimeout(timer)
226
- timer = window.setTimeout(() => ghost.replaceChildren(), 220)
227
- }
228
- root.addEventListener("beforeinput", onBeforeInput, true)
229
-
230
- return () => {
231
- cancelAnimationFrame(frame)
232
- window.clearTimeout(timer)
233
- root.removeEventListener("beforeinput", onBeforeInput, true)
234
- delete list.dataset.resultsReady
235
- }
236
- }, [])
237
-
238
- return (
239
- <div
240
- ref={ref}
241
- aria-hidden="true"
242
- role="none"
243
- inert
244
- data-slot="command-results-ghost"
245
- className="pointer-events-none absolute inset-x-0 top-0 z-10 p-1 empty:hidden data-leaving:*:opacity-0 data-leaving:*:blur-[3px] data-leaving:*:transition-[opacity,filter] data-leaving:*:duration-[var(--transition-duration-palette-result-exit),var(--transition-duration-palette-enter)] data-leaving:*:ease-soft"
246
- />
247
- )
248
- }
249
-
250
154
  // The follower's time constant. Each frame closes 1 - e^(-dt/42ms) of the
251
155
  // distance: about 95% in 130ms, with no overshoot.
252
156
  const FOLLOW_MS = 42
@@ -270,6 +174,10 @@ const NAVIGATION_KEYS = new Set([
270
174
  // instead of restarting. cmdk scrolls the selected item into view at once;
271
175
  // after a key press the follower takes that scroll back and eases to it.
272
176
  // Wheel and pointer scrolling stay native. Reduced motion jumps.
177
+ //
178
+ // In the palette the highlight and the scroll jump too, in the same frame as
179
+ // the selection: arrow keys repeat and searches are typed fast, and a
180
+ // highlight that eases there trails behind the row the user reads.
273
181
  function CommandHighlight() {
274
182
  const ref = React.useRef<HTMLDivElement>(null)
275
183
 
@@ -281,6 +189,8 @@ function CommandHighlight() {
281
189
  return
282
190
  }
283
191
  const reduced = window.matchMedia("(prefers-reduced-motion: reduce)")
192
+ const inPalette = list.closest("[data-command-palette]") !== null
193
+ const jumps = () => inPalette || reduced.matches
284
194
 
285
195
  // y and h are shown, ty and th are the target. scroll is the list's
286
196
  // shown scroll position, scrollTo its target while the follower scrolls.
@@ -305,7 +215,7 @@ function CommandHighlight() {
305
215
  const tick = (time: number) => {
306
216
  const dt = f.last ? Math.min(time - f.last, 48) : 16
307
217
  f.last = time
308
- const k = reduced.matches ? 1 : 1 - Math.exp(-dt / FOLLOW_MS)
218
+ const k = jumps() ? 1 : 1 - Math.exp(-dt / FOLLOW_MS)
309
219
  f.y = Math.abs(f.ty - f.y) < 0.25 ? f.ty : f.y + (f.ty - f.y) * k
310
220
  f.h = Math.abs(f.th - f.h) < 0.25 ? f.th : f.h + (f.th - f.h) * k
311
221
  draw()
@@ -352,7 +262,7 @@ function CommandHighlight() {
352
262
  highlight.style.width = `${selected.offsetWidth}px`
353
263
  f.ty = top
354
264
  f.th = selected.offsetHeight
355
- if (!f.placed) {
265
+ if (!f.placed || jumps()) {
356
266
  f.placed = true
357
267
  f.y = f.ty
358
268
  f.h = f.th
@@ -361,7 +271,7 @@ function CommandHighlight() {
361
271
  highlight.dataset.shown = ""
362
272
  // cmdk has already scrolled the item into view. Show the old position
363
273
  // and let the follower ease to cmdk's.
364
- if (f.byKey && list.scrollTop !== f.scroll && !reduced.matches) {
274
+ if (f.byKey && list.scrollTop !== f.scroll && !jumps()) {
365
275
  f.scrollTo = list.scrollTop
366
276
  list.scrollTop = f.scroll
367
277
  }
@@ -426,7 +336,7 @@ function CommandHighlight() {
426
336
  aria-hidden="true"
427
337
  role="none"
428
338
  data-slot="command-highlight"
429
- className="bg-muted pointer-events-none absolute top-0 left-0 rounded-sm opacity-0 will-change-transform forced-colors:outline-2 forced-colors:-outline-offset-2 forced-colors:outline-solid forced-colors:outline-[Highlight] in-data-command-palette:rounded-xl data-shown:opacity-100 data-ready:transition-opacity data-ready:duration-fast data-ready:ease-soft"
339
+ className="bg-muted pointer-events-none absolute top-0 left-0 rounded-sm opacity-0 will-change-transform forced-colors:outline-2 forced-colors:-outline-offset-2 forced-colors:outline-solid forced-colors:outline-[Highlight] in-data-command-palette:rounded-xl data-shown:opacity-100 data-ready:transition-opacity data-ready:duration-fast data-ready:ease-soft in-data-command-palette:transition-none!"
430
340
  />
431
341
  )
432
342
  }
@@ -493,7 +403,9 @@ function CommandSeparator({
493
403
  // highlight is a Highlight outline. Palette items are 40px tall and quiet at
494
404
  // rest: foreground-secondary text, with the label (CommandItemLabel) in medium
495
405
  // weight. The highlighted row has the muted fill, turns its text to
496
- // foreground and its leading icon to the brand indicator.
406
+ // foreground and its leading icon to the brand indicator, all at once: the
407
+ // selection moves on every arrow key and keystroke, so a tint that eases
408
+ // would trail behind it.
497
409
  function isChecked(value: unknown) {
498
410
  return value === true || value === "true"
499
411
  }
@@ -507,7 +419,7 @@ function CommandItem({
507
419
  <CommandPrimitive.Item
508
420
  data-slot="command-item"
509
421
  className={cn(
510
- "group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[selected=true]:bg-muted not-in-data-command-palette:data-[selected=true]:text-accent-foreground not-in-data-command-palette:data-[selected=true]:**:[svg]:text-accent-foreground in-data-[highlight=slide]:data-[selected=true]:bg-transparent! not-in-data-[highlight=slide]:data-[selected=true]:forced-colors:outline-2 not-in-data-[highlight=slide]:data-[selected=true]:forced-colors:-outline-offset-2 not-in-data-[highlight=slide]:data-[selected=true]:forced-colors:outline-solid not-in-data-[highlight=slide]:data-[selected=true]:forced-colors:outline-[Highlight] in-data-command-palette:h-10 in-data-command-palette:gap-3 in-data-command-palette:rounded-xl in-data-command-palette:px-2.5 in-data-command-palette:text-foreground-secondary in-data-command-palette:data-[selected=true]:text-foreground in-data-command-palette:transition-[color] in-data-command-palette:duration-palette-tint in-data-command-palette:ease-soft data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='stroke-'])]:stroke-[1.75] [&>svg:not([class*='opacity-'])]:opacity-55 [&>svg:not([class*='opacity-'])]:transition-[opacity,color] [&>svg:not([class*='opacity-'])]:duration-moderate not-in-data-command-palette:data-[selected=true]:[&>svg:not([class*='opacity-'])]:opacity-85 in-data-command-palette:[&>svg:not([class*='opacity-'])]:duration-palette-tint in-data-command-palette:[&>svg:not([class*='opacity-'])]:ease-soft in-data-command-palette:data-[selected=true]:[&>svg:not([class*='opacity-'])]:opacity-100 in-data-command-palette:data-[selected=true]:[&>svg:not([class*='opacity-'])]:text-brand-indicator",
422
+ "group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[selected=true]:bg-muted not-in-data-command-palette:data-[selected=true]:text-accent-foreground not-in-data-command-palette:data-[selected=true]:**:[svg]:text-accent-foreground in-data-[highlight=slide]:data-[selected=true]:bg-transparent! not-in-data-[highlight=slide]:data-[selected=true]:forced-colors:outline-2 not-in-data-[highlight=slide]:data-[selected=true]:forced-colors:-outline-offset-2 not-in-data-[highlight=slide]:data-[selected=true]:forced-colors:outline-solid not-in-data-[highlight=slide]:data-[selected=true]:forced-colors:outline-[Highlight] in-data-command-palette:h-10 in-data-command-palette:gap-3 in-data-command-palette:rounded-xl in-data-command-palette:px-2.5 in-data-command-palette:text-foreground-secondary in-data-command-palette:data-[selected=true]:text-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='stroke-'])]:stroke-[1.75] [&>svg:not([class*='opacity-'])]:opacity-55 [&>svg:not([class*='opacity-'])]:transition-[opacity,color] [&>svg:not([class*='opacity-'])]:duration-moderate not-in-data-command-palette:data-[selected=true]:[&>svg:not([class*='opacity-'])]:opacity-85 in-data-command-palette:[&>svg:not([class*='opacity-'])]:transition-none! in-data-command-palette:data-[selected=true]:[&>svg:not([class*='opacity-'])]:opacity-100 in-data-command-palette:data-[selected=true]:[&>svg:not([class*='opacity-'])]:text-brand-indicator",
511
423
  className
512
424
  )}
513
425
  {...props}
@@ -559,9 +471,9 @@ function CommandShortcut({
559
471
  }
560
472
 
561
473
  // Where an item lives, such as "Production · Acme", at the end of the row. It
562
- // shows on the highlighted item only: repeated on every row it is noise. It
563
- // slides in 4px from a 1px blur as the highlight arrives (opacity 180ms,
564
- // transform 220ms, after 40ms) and leaves in 90ms. Reduced motion fades only.
474
+ // shows on every row, so the results can be scanned without moving the
475
+ // selection through them. It stays muted and small so the label is read
476
+ // first, and it truncates before the label does (at most 45% of the row).
565
477
  function CommandItemDetail({
566
478
  className,
567
479
  ...props
@@ -570,7 +482,7 @@ function CommandItemDetail({
570
482
  <span
571
483
  data-slot="command-item-detail"
572
484
  className={cn(
573
- "text-muted-foreground ms-auto max-w-[55%] shrink-0 truncate ps-3 text-xs opacity-0 -translate-x-1 rtl:translate-x-1 blur-[1px] transition-[opacity,translate,filter] duration-palette-detail-exit ease-soft group-data-[selected=true]/command-item:translate-x-0 group-data-[selected=true]/command-item:opacity-100 group-data-[selected=true]/command-item:blur-none group-data-[selected=true]/command-item:delay-(--transition-duration-palette-detail-delay) group-data-[selected=true]/command-item:duration-[var(--transition-duration-palette-move),var(--transition-duration-palette-detail-move),var(--transition-duration-palette-move)] group-data-[selected=true]/command-item:ease-out motion-reduce:translate-x-0 motion-reduce:blur-none",
485
+ "text-muted-foreground ms-auto max-w-[45%] min-w-0 truncate ps-3 text-xs",
574
486
  className
575
487
  )}
576
488
  {...props}
@@ -579,8 +491,14 @@ function CommandItemDetail({
579
491
  }
580
492
 
581
493
  // Key hints under the list. Each direct child is one hint: Kbd keys and a
582
- // label. The keys render at 18px here.
583
- function CommandFooter({ className, ...props }: React.ComponentProps<"div">) {
494
+ // label. The keys render at 18px here. `end` is a hint set apart at the right
495
+ // end of the footer, such as the key that toggles the palette.
496
+ function CommandFooter({
497
+ className,
498
+ children,
499
+ end,
500
+ ...props
501
+ }: React.ComponentProps<"div"> & { end?: React.ReactNode }) {
584
502
  return (
585
503
  <div
586
504
  data-slot="command-footer"
@@ -589,7 +507,10 @@ function CommandFooter({ className, ...props }: React.ComponentProps<"div">) {
589
507
  className
590
508
  )}
591
509
  {...props}
592
- />
510
+ >
511
+ {children}
512
+ {end != null && <span data-slot="command-footer-end" className="ms-auto">{end}</span>}
513
+ </div>
593
514
  )
594
515
  }
595
516