Selectores
Business Selector
Selector de negocio y localización del header: agencias a la izquierda, sus localizaciones a la derecha.
Dependencias: lucide-react (y button, command, popover y separator de zasui)
Uso
Notas
Con 0 o 1 localizaciones, elegir la agencia confirma directo; con varias, la localización se elige en el panel derecho. Las localizaciones con isTransient (camiones) llevan icono de camión. Cargar negocios, guardar la selección (cookies) y el modal de confirmación quedan en cada app.
Instalación
Con la CLI de zasui (ver Introducción): instala el componente con sus dependencias y queda listo para usar.
pnpm dlx @medialityc/zasui add business-selectorVer el código
'use client';
import * as React from 'react';
import {
Building2,
CheckIcon,
ChevronRight,
ChevronsUpDownIcon,
Loader2,
MousePointer2,
Truck,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Separator } from '@/components/ui/separator';
// Parte visual del selector de negocio de zasexpress/zas-distributor: los datos, cookies y SSO quedan en cada app.
export type SelectorLocation = { id: string; name: string; isTransient?: boolean };
export type SelectorBusiness = {
id: string;
name: string;
logo?: string;
locations?: SelectorLocation[];
};
interface BusinessSelectorProps {
businesses: SelectorBusiness[];
/** Selección actual; puede no estar en `businesses` (p. ej. viene de una cookie). */
value?: { business?: SelectorBusiness | null; location?: SelectorLocation | null };
onChange: (business: SelectorBusiness, location: SelectorLocation | null) => void;
/** Búsqueda en el servidor; sin ella las agencias se filtran en local. */
onSearch?: (query: string) => void;
/** Se llama al llegar al final de la lista de agencias (paginación). */
onLoadMore?: () => void;
loading?: boolean;
loadingMore?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
placeholder?: string;
className?: string;
}
function BusinessLogo({ business }: { business?: SelectorBusiness }) {
const [error, setError] = React.useState(false);
// Un `src` vacío recarga la página entera: solo se pinta con URL.
return business?.logo && !error ? (
// Sin next/image: la versión optimizada de 32px se ve borrosa con DPR > 1 y las URLs prefirmadas no cachean.
// eslint-disable-next-line @next/next/no-img-element
<img
src={business.logo}
alt={business.name}
className='size-8 rounded-md object-cover not-dark:mix-blend-multiply'
onError={() => setError(true)}
/>
) : (
<Building2 className='mt-0.5 size-3.5' />
);
}
function BusinessSelector({
businesses,
value,
onChange,
onSearch,
onLoadMore,
loading,
loadingMore,
open: openProp,
onOpenChange,
placeholder = 'Selecciona un negocio...',
className,
}: BusinessSelectorProps) {
const [openState, setOpenState] = React.useState(false);
const open = openProp ?? openState;
const setOpen = (o: boolean) => {
setOpenState(o);
onOpenChange?.(o);
if (!o) setPreview(undefined);
};
const [preview, setPreview] = React.useState<SelectorBusiness>();
const current = value?.business ?? undefined;
const currentLocation = value?.location ?? undefined;
// Las localizaciones salen del listado (más fresco que `value`); sin selección, las del primer negocio.
const shown = preview ?? businesses.find((b) => b.id === current?.id) ?? current ?? businesses[0];
const confirm = (business: SelectorBusiness, location: SelectorLocation | null) => {
onChange(business, location);
setOpen(false);
};
const selectBusiness = (business: SelectorBusiness) => {
const locations = business.locations ?? [];
// Con 0 o 1 localizaciones se confirma directo; con varias se elige a la derecha.
if (locations.length <= 1) return confirm(business, locations[0] ?? null);
setPreview(business);
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant='outline'
role='combobox'
aria-expanded={open}
className={cn('group size-auto max-w-[35vw] min-w-0 border-0 p-2 font-normal', className)}
>
{current && <BusinessLogo business={current} />}
<div className='hidden min-w-0 flex-col text-start sm:flex'>
<span className='truncate'>{current?.name ?? placeholder}</span>
{currentLocation && (
<span className='text-foreground/60 flex max-w-full gap-0.5 truncate text-xs'>
{currentLocation.isTransient ? (
<Truck className='mt-0.5 size-3.5 shrink-0' />
) : (
<MousePointer2 className='mt-0.5 size-3.5 shrink-0' />
)}
<span className='truncate'>{currentLocation.name}</span>
</span>
)}
</div>
<ChevronsUpDownIcon className='ml-2 size-4 shrink-0 opacity-50' />
</Button>
</PopoverTrigger>
<PopoverContent
className='mx-2 flex w-[calc(100vw-1rem)] flex-col gap-2 p-0 sm:w-128 sm:flex-row sm:gap-0'
align='start'
>
<Command shouldFilter={!onSearch}>
<CommandInput placeholder='Busca por nombre o código...' onValueChange={onSearch} />
<CommandList
onScroll={(e) => {
const t = e.currentTarget;
if (onLoadMore && !loadingMore && t.scrollHeight - t.scrollTop - t.clientHeight < 50) onLoadMore();
}}
>
<CommandGroup>
<span className='text-muted-foreground px-2 py-1.5 text-xs'>Agencias</span>
<CommandEmpty>
{loading ? (
<span className='flex items-center justify-center gap-1.5'>
<Loader2 className='size-3 animate-spin' />
Buscando...
</span>
) : (
'No se encontraron negocios'
)}
</CommandEmpty>
{businesses.map((business) => (
<CommandItem
key={business.id}
value={`${business.id}-${business.name}`}
onSelect={() => selectBusiness(business)}
onMouseEnter={() => setPreview(business)}
className='justify-between'
>
<div className='flex items-center gap-2 text-wrap'>
<CheckIcon className={cn(current?.id === business.id ? 'opacity-100' : 'opacity-0')} />
{business.name}
</div>
<ChevronRight />
</CommandItem>
))}
</CommandGroup>
{loadingMore && (
<div className='text-muted-foreground flex items-center justify-center gap-1.5 py-2 text-xs'>
<Loader2 className='size-3 animate-spin' />
Cargando más...
</div>
)}
</CommandList>
</Command>
<Separator className='sm:hidden' />
<Command>
<CommandInput placeholder='Busca localizaciones...' />
<CommandList>
<CommandGroup>
<span className='text-muted-foreground px-2 py-1.5 text-xs'>Localizaciones</span>
<CommandEmpty>
{shown
? 'Este negocio no tiene localizaciones'
: 'Selecciona un negocio para ver localizaciones'}
</CommandEmpty>
{shown?.locations?.map((location) => (
<CommandItem
key={location.id}
value={`${location.id}-${location.name}`}
onSelect={() => confirm(shown, location)}
disabled={location.id === currentLocation?.id}
>
<CheckIcon
className={cn(location.id === currentLocation?.id ? 'opacity-100' : 'opacity-0')}
/>
{location.isTransient && <Truck className='mr-1 size-3.5 shrink-0' />}
{location.name}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
export { BusinessSelector };