Skip to content

armgit / spree

Public Imported from GitHub
0

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.

15.6 KB
Raw Blame
'use client'

import { Combobox as ComboboxPrimitive } from '@base-ui/react'
import i18n from 'i18next'
import * as React from 'react'
import { cn } from '../lib/utils'
import { CheckIcon, ChevronDownIcon, XIcon } from '../spree/icons'
import { Button } from './button'
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from './input-group'

/**
 * Base UI empties a multi-select when Escape is pressed with its popup closed,
 * and picking a searched result closes the popup, so the Escape meant to
 * dismiss the search silently wiped every chip. Chips are removed only through
 * their own remove button or Backspace, and the Escape passes on to whatever
 * encloses the picker, such as a sheet, as it does for an empty one.
 */
function Combobox<Value, Multiple extends boolean | undefined = false, Item = Value>(
  props: ComboboxPrimitive.Root.Props<Value, Multiple, Item>,
) {
  const { multiple, onValueChange } = props
  if (!multiple) return <ComboboxPrimitive.Root {...props} />

  return (
    <ComboboxPrimitive.Root
      {...props}
      onValueChange={(value, eventDetails) => {
        if (eventDetails.reason === 'escape-key') {
          eventDetails.cancel()
          eventDetails.allowPropagation()
          return
        }
        onValueChange?.(value, eventDetails)
      }}
    />
  )
}

function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {
  return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />
}

function ComboboxTrigger({ className, children, ...props }: ComboboxPrimitive.Trigger.Props) {
  return (
    <ComboboxPrimitive.Trigger
      data-slot="combobox-trigger"
      className={cn("[&_svg:not([class*='size-'])]:size-4", className)}
      {...props}
    >
      {children}
      <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
    </ComboboxPrimitive.Trigger>
  )
}

/**
 * Button-shaped trigger for a searchable picker: the field renders the current
 * selection (flag, formatted label) and the search box lives inside the popup,
 * next to the results it filters.
 *
 * Preferred over the editable-input trigger (`<ComboboxInput>`) whenever the
 * selection has a richer display than the raw query text. A text input has to
 * show the typed query, so it erases the selected label the moment the user
 * types, and the browser's address autofill treats a text field named after a
 * country as part of an address form and covers the list with saved addresses.
 * A button has nothing to autofill into, and the search box inside the popup
 * sits outside the form's field flow where those heuristics don't reach.
 *
 * Deliberately matches `<SelectTrigger>` so a picker sitting beside a plain
 * select is indistinguishable from it until opened.
 */
function ComboboxButtonTrigger({
  className,
  children,
  size = 'default',
  ...props
}: ComboboxPrimitive.Trigger.Props & {
  /** `sm` is the toolbar size — see `SelectTrigger`, which it matches exactly. */
  size?: 'sm' | 'default'
}) {
  return (
    <ComboboxPrimitive.Trigger
      data-slot="combobox-button-trigger"
      data-size={size}
      className={cn(
        "group/combobox-trigger flex w-full min-h-8 cursor-pointer items-center justify-between gap-1.5 rounded-md border border-border shadow-control bg-card py-1.5 pr-2 pl-2.5 text-base font-normal leading-normal text-foreground transition-[color,background-color,border-color,box-shadow] duration-100 ease-out outline-none select-none focus:border-blue-500 focus:shadow-[0_0_0_3px_color-mix(in_srgb,var(--ring)_15%,transparent)] disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground aria-invalid:border-destructive data-[size=sm]:shadow-control data-[size=sm]:h-8 data-[size=sm]:min-h-8 data-[size=sm]:gap-2 data-[size=sm]:px-2 data-[size=sm]:py-1 data-[size=sm]:text-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
        className,
      )}
      {...props}
    >
      <span className="flex min-w-0 items-center gap-2 truncate">{children}</span>
      <ChevronDownIcon className="pointer-events-none size-4 shrink-0 text-muted-foreground group-data-[size=sm]/combobox-trigger:size-3.5" />
    </ComboboxPrimitive.Trigger>
  )
}

/**
 * Placeholder text for a `<ComboboxButtonTrigger>` with nothing selected.
 * A span rather than the trigger's own `data-placeholder`, because the
 * trigger renders arbitrary children (a flag beside a name) rather than a
 * single value string.
 */
function ComboboxTriggerPlaceholder({ className, ...props }: React.ComponentProps<'span'>) {
  return (
    <span
      data-slot="combobox-trigger-placeholder"
      className={cn('truncate text-muted-foreground', className)}
      {...props}
    />
  )
}

/**
 * Search box for a button-triggered picker, rendered at the top of the popup.
 * Autofill and spell-check are turned off across the board: this filters an
 * on-screen list, so a password manager or a saved-address panel covering it
 * is pure interference.
 */
function ComboboxSearch({ className, ...props }: ComboboxPrimitive.Input.Props) {
  return (
    <div className="border-b border-border p-1">
      <ComboboxInput
        data-slot="combobox-search"
        className={cn(
          'min-h-8 border-0 shadow-none has-[[data-slot=input-group-control]:focus-visible]:border-transparent has-[[data-slot=input-group-control]:focus-visible]:shadow-none',
          className,
        )}
        autoComplete="off"
        autoCorrect="off"
        autoCapitalize="off"
        spellCheck={false}
        data-1p-ignore
        data-lpignore="true"
        showTrigger={false}
        {...props}
      />
    </div>
  )
}

function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
  return (
    <ComboboxPrimitive.Clear
      data-slot="combobox-clear"
      render={<InputGroupButton variant="ghost" size="icon-xs" />}
      className={cn(className)}
      {...props}
    >
      <XIcon className="pointer-events-none" />
    </ComboboxPrimitive.Clear>
  )
}

function ComboboxInput({
  className,
  children,
  disabled = false,
  showTrigger = true,
  showClear = false,
  ...props
}: ComboboxPrimitive.Input.Props & {
  showTrigger?: boolean
  showClear?: boolean
}) {
  return (
    <InputGroup className={cn('w-auto', className)}>
      <ComboboxPrimitive.Input render={<InputGroupInput disabled={disabled} />} {...props} />
      <InputGroupAddon align="inline-end">
        {showTrigger && (
          <InputGroupButton
            size="icon-xs"
            variant="ghost"
            asChild
            data-slot="input-group-button"
            className="group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent"
            disabled={disabled}
          >
            <ComboboxTrigger />
          </InputGroupButton>
        )}
        {showClear && <ComboboxClear disabled={disabled} />}
      </InputGroupAddon>
      {children}
    </InputGroup>
  )
}

function ComboboxContent({
  className,
  side = 'bottom',
  sideOffset = 6,
  align = 'start',
  alignOffset = 0,
  anchor,
  ...props
}: ComboboxPrimitive.Popup.Props &
  Pick<
    ComboboxPrimitive.Positioner.Props,
    'side' | 'align' | 'sideOffset' | 'alignOffset' | 'anchor'
  >) {
  return (
    <ComboboxPrimitive.Portal>
      <ComboboxPrimitive.Positioner
        side={side}
        sideOffset={sideOffset}
        align={align}
        alignOffset={alignOffset}
        anchor={anchor}
        className="isolate z-50"
      >
        <ComboboxPrimitive.Popup
          data-slot="combobox-content"
          data-chips={!!anchor}
          className={cn(
            // Deliberately keeps `animate-in`/`animate-out` keyframes where the
            // other floating surfaces use transitions. Converting this one to
            // `data-[starting-style]` transitions broke the multi-select chips
            // picker: the list re-renders as the user filters, and options
            // arriving mid-transition sit at `opacity-0` long enough to be
            // unclickable. The keyframes make the panel opaque immediately.
            'group/combobox-content relative max-h-(--available-height) w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))] origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[chips=true]:min-w-(--anchor-width) data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
            className,
          )}
          {...props}
        />
      </ComboboxPrimitive.Positioner>
    </ComboboxPrimitive.Portal>
  )
}

function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
  return (
    <ComboboxPrimitive.List
      data-slot="combobox-list"
      className={cn(
        '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',
        className,
      )}
      {...props}
    />
  )
}

function ComboboxItem({ className, children, ...props }: ComboboxPrimitive.Item.Props) {
  return (
    <ComboboxPrimitive.Item
      data-slot="combobox-item"
      className={cn(
        // 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-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}
    >
      {children}
      <ComboboxPrimitive.ItemIndicator
        render={
          <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
        }
      >
        <CheckIcon className="pointer-events-none" />
      </ComboboxPrimitive.ItemIndicator>
    </ComboboxPrimitive.Item>
  )
}

function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
  return <ComboboxPrimitive.Group data-slot="combobox-group" className={cn(className)} {...props} />
}

function ComboboxLabel({ className, ...props }: ComboboxPrimitive.GroupLabel.Props) {
  return (
    <ComboboxPrimitive.GroupLabel
      data-slot="combobox-label"
      className={cn('px-2 py-1.5 text-xs text-muted-foreground', className)}
      {...props}
    />
  )
}

function ComboboxCollection({ ...props }: ComboboxPrimitive.Collection.Props) {
  return <ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />
}

function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
  return (
    <ComboboxPrimitive.Empty
      data-slot="combobox-empty"
      className={cn(
        'hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex',
        className,
      )}
      {...props}
    />
  )
}

function ComboboxSeparator({ className, ...props }: ComboboxPrimitive.Separator.Props) {
  return (
    <ComboboxPrimitive.Separator
      data-slot="combobox-separator"
      className={cn('-mx-1 my-1 h-px bg-border', className)}
      {...props}
    />
  )
}

function ComboboxChips({
  className,
  ...props
}: React.ComponentPropsWithRef<typeof ComboboxPrimitive.Chips> & ComboboxPrimitive.Chips.Props) {
  return (
    <ComboboxPrimitive.Chips
      data-slot="combobox-chips"
      className={cn(
        // Keeps `transition-all` where the sibling inputs narrowed theirs: this
        // element is the popup's anchor, and adding a chip reflows it
        // (`flex-wrap`, `has-data-[slot=combobox-chip]:px-1`). Animating that
        // resize lets the positioner follow the anchor smoothly; making it
        // instant jumps the open popup out from under the pointer, so the next
        // option click lands on nothing.
        'flex flex-wrap items-center gap-1.5 rounded-md border border-border shadow-control bg-card text-foreground px-2.5 py-1.5 text-base transition-all duration-100 ease-out focus-within:border-blue-500 focus-within:shadow-[0_0_0_3px_color-mix(in_srgb,var(--ring)_15%,transparent)] has-aria-invalid:border-destructive has-data-[slot=combobox-chip]:p-1.5',
        className,
      )}
      {...props}
    />
  )
}

function ComboboxChip({
  className,
  children,
  showRemove = true,
  ...props
}: ComboboxPrimitive.Chip.Props & {
  showRemove?: boolean
}) {
  return (
    <ComboboxPrimitive.Chip
      data-slot="combobox-chip"
      className={cn(
        // Height comes from the content rather than a fixed 21px: the old value
        // was shorter than the remove button inside it, and left the label with
        // no vertical breathing room at any screen size.
        //
        // Fill matches the highlighted row in the list below (`bg-accent`): a
        // chip and a selected option are the same thing at two moments, so they
        // read as the same thing. `bg-muted` sat within 1.03:1 of the field it
        // sits on, which left the chips barely visible.
        'flex min-h-7 w-fit max-w-full items-center justify-center gap-1 rounded-sm bg-accent py-1 pl-2.5 pr-2 text-sm font-base text-foreground has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-1',
        className,
      )}
      {...props}
    >
      <span className="min-w-0 truncate">{children}</span>
      {showRemove && (
        <ComboboxPrimitive.ChipRemove
          render={<Button variant="ghost" size="icon-sm" />}
          className="size-6 shrink-0 opacity-50 hover:opacity-100"
          data-slot="combobox-chip-remove"
          // Names the chip it clears ("Remove Wholesale") rather than a bare
          // "Remove": several sit side by side, and a dialog's own submit
          // button is often called Remove too. An `aria-label` rather than an
          // `sr-only` span, so the chip's text isn't duplicated as a second
          // text node beside the one already visible.
          aria-label={
            typeof children === 'string'
              ? i18n.t('admin.actions.remove_item', { label: children })
              : i18n.t('admin.actions.remove')
          }
        >
          <XIcon className="pointer-events-none" />
        </ComboboxPrimitive.ChipRemove>
      )}
    </ComboboxPrimitive.Chip>
  )
}

function ComboboxChipsInput({ className, ...props }: ComboboxPrimitive.Input.Props) {
  return (
    <ComboboxPrimitive.Input
      data-slot="combobox-chip-input"
      className={cn('min-w-16 flex-1 outline-none', className)}
      {...props}
    />
  )
}

function useComboboxAnchor() {
  return React.useRef<HTMLDivElement | null>(null)
}

export {
  Combobox,
  ComboboxButtonTrigger,
  ComboboxChip,
  ComboboxChips,
  ComboboxChipsInput,
  ComboboxCollection,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxGroup,
  ComboboxInput,
  ComboboxItem,
  ComboboxLabel,
  ComboboxList,
  ComboboxSearch,
  ComboboxSeparator,
  ComboboxTrigger,
  ComboboxTriggerPlaceholder,
  ComboboxValue,
  useComboboxAnchor,
}