@open-mercato/ui 0.11.1-develop.8298.1.5323e2aa15 → 0.11.1-develop.8317.1.dde3d38b64

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/backend/inputs/LookupSelect.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Check, Loader2, Search, X } from 'lucide-react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { Button } from '../../primitives/button'\nimport { IconButton } from '../../primitives/icon-button'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('ui').child({ component: 'LookupSelect' })\n\nexport type LookupSelectItem = {\n id: string\n title: string\n subtitle?: string | null\n badge?: string | null\n icon?: React.ReactNode\n disabled?: boolean\n rightLabel?: string | null\n description?: string | null\n}\n\ntype LookupSelectProps = {\n value: string | null\n onChange: (next: string | null) => void\n fetchItems?: (query: string) => Promise<LookupSelectItem[]>\n fetchOptions?: (query?: string) => Promise<LookupSelectItem[]>\n options?: LookupSelectItem[]\n minQuery?: number\n actionSlot?: React.ReactNode\n onReady?: (controls: { setQuery: (value: string) => void }) => void\n searchPlaceholder?: string\n placeholder?: string\n clearLabel?: string\n emptyLabel?: string\n loadingLabel?: string\n selectLabel?: string\n selectedLabel?: string\n minQueryHintLabel?: string\n startTypingLabel?: string\n selectedHintLabel?: (id: string) => string\n disabled?: boolean\n loading?: boolean\n defaultOpen?: boolean\n}\n\nfunction keepSelectedItem(\n result: LookupSelectItem[],\n selected: LookupSelectItem | null,\n value: string | null,\n): LookupSelectItem[] {\n if (!value || !selected || selected.id !== value) return result\n if (result.some((item) => item.id === value)) return result\n return [selected, ...result]\n}\n\nexport function LookupSelect({\n value,\n onChange,\n fetchItems,\n fetchOptions,\n options,\n minQuery = 2,\n actionSlot,\n onReady,\n placeholder,\n searchPlaceholder,\n clearLabel,\n emptyLabel,\n loadingLabel,\n selectLabel,\n selectedLabel,\n minQueryHintLabel,\n startTypingLabel,\n selectedHintLabel,\n disabled = false,\n loading: loadingProp = false,\n defaultOpen = false,\n}: LookupSelectProps) {\n const t = useT()\n const resolvedSearchPlaceholder = searchPlaceholder ?? placeholder ?? t('ui.lookupSelect.searchPlaceholder', 'Search\u2026')\n const resolvedClearLabel = clearLabel ?? t('ui.lookupSelect.clearSelection', 'Clear selection')\n const resolvedEmptyLabel = emptyLabel ?? t('ui.lookupSelect.noResults', 'No results')\n const resolvedLoadingLabel = loadingLabel ?? t('ui.lookupSelect.searching', 'Searching\u2026')\n const resolvedSelectLabel = selectLabel ?? t('ui.lookupSelect.select', 'Select')\n const resolvedSelectedLabel = selectedLabel ?? t('ui.lookupSelect.selected', 'Selected')\n const resolvedChangeLabel = t('ui.lookupSelect.change', 'Change')\n const resolvedStartTypingLabel = startTypingLabel ?? t('ui.lookupSelect.startTyping', 'Start typing to search.')\n const resolvedMinQueryHintLabel = minQueryHintLabel ?? t(\n 'ui.lookupSelect.minQueryHint',\n 'Type at least {minQuery} characters or paste an id to search.',\n { minQuery: String(minQuery) }\n )\n const [query, setQuery] = React.useState('')\n const [items, setItems] = React.useState<LookupSelectItem[]>(options ?? [])\n const [loading, setLoading] = React.useState(false)\n // Escape collapses the list without clearing the selection. Derived state is not\n // enough here: Escape empties the query but the fetched `items` linger, so the\n // list would stay open and the collapsed summary \u2014 the branch that keeps a raw\n // record id out of the DOM (TC-EUDR-013) \u2014 would never render.\n // A value that is already there when the lookup mounts (hydrated, or seeded by the host,\n // e.g. the deal owner defaulting to the current user) is a finished selection: it starts\n // collapsed on the summary instead of an open list with one row checked (#5109).\n // `defaultOpen` keeps the list on screen regardless (pickers that browse a short list).\n const [collapsed, setCollapsed] = React.useState(() => Boolean(value) && !defaultOpen)\n const [hasTyped, setHasTyped] = React.useState(defaultOpen)\n const [error, setError] = React.useState<string | null>(null)\n const [fetchKey, setFetchKey] = React.useState(0)\n const [activeIndex, setActiveIndex] = React.useState(-1)\n const [selectedItem, setSelectedItem] = React.useState<LookupSelectItem | null>(null)\n const listboxId = React.useId()\n const fetchItemsRef = React.useRef(fetchItems ?? fetchOptions)\n const setQueryRef = React.useRef(setQuery)\n const onReadyRef = React.useRef(onReady)\n const optionsWasArrayRef = React.useRef(Array.isArray(options))\n const valueRef = React.useRef(value)\n const selectedItemRef = React.useRef<LookupSelectItem | null>(null)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const pendingCommitRef = React.useRef<string | null>(null)\n const changeButtonRef = React.useRef<HTMLButtonElement>(null)\n const focusSummaryRef = React.useRef(false)\n\n React.useEffect(() => {\n fetchItemsRef.current = fetchItems ?? fetchOptions\n }, [fetchItems, fetchOptions])\n\n React.useEffect(() => {\n valueRef.current = value\n }, [value])\n\n React.useEffect(() => {\n onReadyRef.current = onReady\n }, [onReady])\n\n React.useEffect(() => {\n if (Array.isArray(options)) {\n optionsWasArrayRef.current = true\n setItems(options)\n } else if (optionsWasArrayRef.current) {\n optionsWasArrayRef.current = false\n setFetchKey((k) => k + 1)\n }\n }, [options])\n\n React.useEffect(() => {\n setQueryRef.current = setQuery\n if (onReadyRef.current) onReadyRef.current({ setQuery })\n }, [setQuery])\n\n // A set `value` keeps the lookup live: the list (or, once collapsed after a\n // pick, the summary) is where the selection, its checkmark and the clear control\n // render, so a selection is never invisible. This used to also require an\n // `options` prop, which left every caller that resolves its selection through\n // `fetchItems` blind whenever minQuery kept the list shut.\n const shouldSearch = defaultOpen || query.trim().length >= minQuery || Boolean(value)\n\n React.useEffect(() => {\n setActiveIndex(-1)\n }, [items])\n\n const optionDomId = React.useCallback(\n (index: number) => `${listboxId}-option-${index}`,\n [listboxId],\n )\n\n const isInteractiveItem = React.useCallback(\n (item: LookupSelectItem) => !disabled && (!item.disabled || value === item.id),\n [disabled, value],\n )\n\n const moveActiveIndex = React.useCallback((direction: 1 | -1) => {\n setActiveIndex((current) => {\n if (!items.length) return -1\n let next = current\n for (let step = 0; step < items.length; step += 1) {\n next = (next + direction + items.length) % items.length\n if (isInteractiveItem(items[next])) return next\n }\n return current\n })\n }, [isInteractiveItem, items])\n\n React.useEffect(() => {\n if (activeIndex < 0) return\n const activeElement = typeof document !== 'undefined'\n ? document.getElementById(optionDomId(activeIndex))\n : null\n if (typeof activeElement?.scrollIntoView === 'function') {\n activeElement.scrollIntoView({ block: 'nearest' })\n }\n }, [activeIndex, optionDomId])\n\n const listboxVisible = shouldSearch && !disabled && !collapsed\n\n const finishSelection = React.useCallback(() => {\n pendingCommitRef.current = null\n focusSummaryRef.current = true\n setCollapsed(true)\n setQuery('')\n setHasTyped(false)\n setActiveIndex(-1)\n }, [])\n\n // Picking a result ends the interaction (#6196): the list closes and the collapsed\n // summary takes over, but only once the parent has adopted the id. A host that keeps\n // `value` at null and collects picks itself (multi-add pickers) keeps browsing.\n const commitSelection = React.useCallback((item: LookupSelectItem) => {\n selectedItemRef.current = item\n setSelectedItem(item)\n if (valueRef.current === item.id) {\n finishSelection()\n return\n }\n pendingCommitRef.current = item.id\n onChange(item.id)\n }, [finishSelection, onChange])\n\n React.useEffect(() => {\n if (pendingCommitRef.current) {\n if (value === pendingCommitRef.current) finishSelection()\n else if (value) pendingCommitRef.current = null\n return\n }\n // The host adopted a value the user never picked here (seeded after mount): treat it\n // like a finished pick as long as the user is not mid-search.\n if (value && !hasTyped && query.length === 0) setCollapsed(true)\n }, [finishSelection, hasTyped, query, value])\n\n // The search box is not in the DOM while the summary row stands in for it, so the focus\n // moves once the box has mounted again.\n const focusAfterReopenRef = React.useRef(false)\n const reopenList = React.useCallback(() => {\n focusAfterReopenRef.current = true\n focusSummaryRef.current = false\n setCollapsed(false)\n }, [])\n const clearSelection = React.useCallback(() => {\n focusAfterReopenRef.current = true\n focusSummaryRef.current = false\n onChange(null)\n }, [onChange])\n\n // With nothing selected there is no summary to collapse onto, so the browse list comes back.\n React.useEffect(() => {\n if (!value) setCollapsed(false)\n }, [value])\n\n const handleInputKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {\n if (!listboxVisible) return\n if (event.key === 'ArrowDown') {\n event.preventDefault()\n moveActiveIndex(1)\n return\n }\n if (event.key === 'ArrowUp') {\n event.preventDefault()\n moveActiveIndex(-1)\n return\n }\n if (event.key === 'Enter') {\n if (activeIndex < 0 || activeIndex >= items.length) return\n const item = items[activeIndex]\n if (!isInteractiveItem(item)) return\n event.preventDefault()\n commitSelection(item)\n return\n }\n if (event.key === 'Escape') {\n if (query.length === 0 && activeIndex < 0) return\n event.preventDefault()\n event.stopPropagation()\n setQuery('')\n setActiveIndex(-1)\n focusSummaryRef.current = Boolean(value)\n setCollapsed(true)\n }\n }, [activeIndex, commitSelection, items, isInteractiveItem, listboxVisible, moveActiveIndex, query, value])\n React.useEffect(() => {\n if (disabled) {\n setItems(options ?? [])\n setLoading(false)\n return\n }\n let cancelled = false\n let timer: ReturnType<typeof setTimeout> | null = null\n if (!shouldSearch) {\n setItems(options ?? [])\n setLoading(false)\n setError(null)\n return () => { cancelled = true }\n }\n setLoading(true)\n setError(null)\n timer = setTimeout(() => {\n const requestId = Date.now()\n const fetcher = fetchItemsRef.current\n const loader = fetcher ?? (() => Promise.resolve(options ?? []))\n const trimmedQuery = query.trim()\n loader(trimmedQuery)\n .then((result) => {\n if (cancelled) return\n // A set `value` opens the list with an empty query, and that browse\n // fetch returns an arbitrary first page. Without this the stored\n // selection vanished from the list whenever it fell outside that page,\n // while the form still held its id. A typed query stays a pure search.\n setItems(\n trimmedQuery\n ? result\n : keepSelectedItem(result, selectedItemRef.current, valueRef.current),\n )\n })\n .catch((err) => {\n if (cancelled) return\n logger.error('Failed to fetch lookup items', { err })\n setError('error')\n })\n .finally(() => {\n if (!cancelled) setLoading(false)\n })\n return requestId\n }, 220)\n return () => {\n cancelled = true\n if (timer) clearTimeout(timer)\n }\n }, [query, shouldSearch, fetchKey])\n\n React.useEffect(() => {\n if (!value) {\n selectedItemRef.current = null\n setSelectedItem(null)\n return\n }\n const match = items.find((item) => item.id === value)\n if (match) {\n selectedItemRef.current = match\n setSelectedItem(match)\n }\n }, [items, value])\n\n /*\n * The collapsed summary needs a label it can trust: the consumer's\n * `selectedHintLabel` when it resolves to a name, otherwise the title of the\n * item that was actually fetched or picked. A resolver that falls back to the\n * id (`known.get(id) ?? id`) or embeds it (\"Selected customer: <id>\") is\n * treated as unresolved \u2014 a record id must never reach the DOM as a label.\n * With neither (a hydrated value whose lookup returned nothing) there is no\n * summary, so consumers rendering their own label never get a second one.\n */\n const collapsedSelectionLabel = React.useMemo(() => {\n if (!value) return null\n const hinted = selectedHintLabel?.(value)\n if (hinted && hinted !== value && !hinted.includes(value)) return hinted\n const fetchedTitle = selectedItem && selectedItem.id === value ? selectedItem.title : null\n return fetchedTitle && fetchedTitle !== value ? fetchedTitle : null\n }, [selectedHintLabel, selectedItem, value])\n const collapsedSelectionSubtitle = selectedItem && selectedItem.id === value ? selectedItem.subtitle ?? null : null\n // Once collapsed on a resolved selection the summary row IS the control: the search box\n // comes back only when the user asks to change the pick, so the field stays one row tall\n // and fits a narrow column (#5109).\n const showSummaryOnly = collapsed && Boolean(collapsedSelectionLabel)\n\n // The search box and the summary row replace each other, so whichever held the focus is\n // gone from the DOM: keyboard users continue on the control that took its place.\n React.useEffect(() => {\n if (showSummaryOnly) {\n if (!focusSummaryRef.current) return\n focusSummaryRef.current = false\n changeButtonRef.current?.focus()\n return\n }\n if (!focusAfterReopenRef.current) return\n focusAfterReopenRef.current = false\n inputRef.current?.focus()\n }, [showSummaryOnly])\n\n return (\n <div className=\"space-y-3\">\n {showSummaryOnly ? null : (\n <div className=\"flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3\">\n <div className=\"relative flex-1\">\n <Search className=\"pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground\" />\n <input\n ref={inputRef}\n className=\"w-full h-9 rounded-lg border border-input bg-background pl-10 pr-3 text-sm shadow-xs transition-colors outline-none placeholder:text-muted-foreground hover:border-foreground/20 focus-visible:shadow-focus focus-visible:border-foreground disabled:bg-bg-disabled disabled:border-border-disabled disabled:text-muted-foreground disabled:cursor-not-allowed\"\n value={query}\n onChange={(event) => {\n setQuery(event.target.value)\n setHasTyped(true)\n setCollapsed(false)\n }}\n onKeyDown={handleInputKeyDown}\n placeholder={resolvedSearchPlaceholder}\n disabled={disabled}\n role=\"combobox\"\n aria-expanded={listboxVisible}\n aria-controls={listboxId}\n aria-autocomplete=\"list\"\n aria-activedescendant={activeIndex >= 0 ? optionDomId(activeIndex) : undefined}\n />\n </div>\n {actionSlot && !disabled ? <div className=\"sm:self-start\">{actionSlot}</div> : null}\n </div>\n )}\n {/*\n * `shouldSearch` decides whether to FETCH; this decides whether to RENDER a\n * list. They differ for a set value whose lookup comes back empty: develop's\n * #5248 work needs the list (and its selected option) whenever items exist,\n * while the collapsed summary \u2014 which keeps a selection visible after the\n * search box reverts to its placeholder, and keeps a raw record id out of the\n * DOM (TC-EUDR-013) \u2014 is only reachable when they do not. Falling through on\n * an empty result satisfies both. A non-empty query still renders the list so\n * its spinner and empty-state are reachable while the user is searching.\n */}\n {shouldSearch && !collapsed && (items.length > 0 || query.trim().length > 0) ? (\n <div className=\"space-y-2\">\n {loading || loadingProp ? (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Loader2 className=\"h-4 w-4 animate-spin\" />\n {resolvedLoadingLabel}\n </div>\n ) : null}\n {!loading && !loadingProp && !items.length ? (\n <p className=\"text-xs text-muted-foreground\">{resolvedEmptyLabel}</p>\n ) : null}\n <div\n id={listboxId}\n role=\"listbox\"\n className=\"flex flex-col gap-1.5 max-h-80 overflow-y-auto -mx-0.5 px-0.5 py-0.5\"\n >\n {items.map((item, index) => {\n const isSelected = value === item.id\n const isInteractive = isInteractiveItem(item)\n const isActive = index === activeIndex\n return (\n <div\n key={item.id}\n id={optionDomId(index)}\n className={cn(\n 'group flex items-center gap-3 rounded-lg border px-3 py-2 transition-all duration-150 focus-visible:outline-none focus-visible:shadow-focus',\n isInteractive ? 'cursor-pointer' : 'cursor-not-allowed opacity-60',\n isSelected\n ? 'border-accent-indigo bg-accent-indigo/5'\n : 'border-input bg-card hover:border-foreground/20 hover:bg-muted/30',\n isActive && !isSelected ? 'border-foreground/20 bg-muted/30 shadow-sm' : null\n )}\n role=\"option\"\n tabIndex={isInteractive ? 0 : -1}\n onClick={() => {\n if (!isInteractive) return\n commitSelection(item)\n }}\n onKeyDown={(event) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault()\n if (!isInteractive) return\n commitSelection(item)\n }\n }}\n aria-selected={isSelected}\n aria-disabled={isInteractive ? undefined : true}\n title={isSelected ? resolvedSelectedLabel : isInteractive ? resolvedSelectLabel : undefined}\n >\n {item.icon ? (\n <div className=\"flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden [&>svg]:size-5 [&_svg]:text-muted-foreground\">\n {item.icon}\n </div>\n ) : (\n <div className={cn(\n 'flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-md border transition-colors',\n isSelected\n ? 'border-accent-indigo/40 bg-accent-indigo/10 text-accent-indigo'\n : 'border-input bg-muted text-muted-foreground group-hover:border-foreground/20'\n )}>\n <span className=\"text-sm font-medium uppercase\">{item.title.slice(0, 1)}</span>\n </div>\n )}\n <div className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <div className=\"flex items-center justify-between gap-3\">\n <div className=\"truncate text-sm font-medium text-foreground\">{item.title}</div>\n {item.rightLabel ? (\n <div className=\"shrink-0 text-overline font-medium uppercase tracking-wider text-muted-foreground\">\n {item.rightLabel}\n </div>\n ) : null}\n </div>\n {item.subtitle ? (\n <div className=\"text-xs text-muted-foreground truncate\">{item.subtitle}</div>\n ) : null}\n {item.description ? (\n <div className=\"text-xs text-muted-foreground/70 truncate\">{item.description}</div>\n ) : null}\n </div>\n <div className=\"flex shrink-0 items-center justify-center gap-1.5\">\n {isSelected ? (\n <>\n <span className=\"text-xs font-medium text-foreground\">{resolvedSelectedLabel}</span>\n <Check className=\"size-4 text-accent-indigo\" aria-hidden=\"true\" />\n </>\n ) : (\n <div className=\"size-5\" aria-hidden=\"true\" />\n )}\n </div>\n </div>\n )\n })}\n </div>\n {value && !disabled ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"w-fit gap-1 text-sm font-normal\"\n onClick={() => onChange(null)}\n >\n <X className=\"h-4 w-4\" />\n {resolvedClearLabel}\n </Button>\n ) : null}\n </div>\n ) : collapsedSelectionLabel ? (\n /*\n * The selection as a single row: the name is the control that reopens the\n * search (Change), the icon clears. No second search box above it.\n */\n <div\n className={cn(\n 'flex h-9 items-center gap-1 rounded-lg border border-accent-indigo bg-accent-indigo/5 pl-1 pr-1',\n disabled && 'border-border-disabled bg-bg-disabled',\n )}\n data-testid=\"lookup-select-selected\"\n >\n {disabled ? (\n <span className=\"flex h-7 min-w-0 flex-1 items-center gap-2 px-2 text-muted-foreground\">\n <Check className=\"size-4 shrink-0\" aria-hidden=\"true\" />\n <span className=\"truncate text-sm\">{collapsedSelectionLabel}</span>\n {collapsedSelectionSubtitle ? (\n <span className=\"hidden truncate text-xs sm:inline\">{collapsedSelectionSubtitle}</span>\n ) : null}\n </span>\n ) : (\n <Button\n ref={changeButtonRef}\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-7 min-w-0 flex-1 justify-start gap-2 px-2 text-left font-normal hover:bg-accent-indigo/10 hover:text-accent-indigo\"\n onClick={reopenList}\n aria-label={resolvedChangeLabel}\n title={resolvedChangeLabel}\n >\n <Check className=\"size-4 shrink-0 text-accent-indigo\" aria-hidden=\"true\" />\n <span className=\"truncate text-sm text-foreground\">{collapsedSelectionLabel}</span>\n {collapsedSelectionSubtitle ? (\n <span className=\"hidden truncate text-xs text-muted-foreground sm:inline\">{collapsedSelectionSubtitle}</span>\n ) : null}\n </Button>\n )}\n {disabled ? null : (\n <IconButton\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"shrink-0 text-muted-foreground hover:bg-accent-indigo/10 hover:text-accent-indigo\"\n onClick={clearSelection}\n aria-label={resolvedClearLabel}\n title={resolvedClearLabel}\n >\n <X className=\"size-4\" aria-hidden=\"true\" />\n </IconButton>\n )}\n </div>\n ) : hasTyped ? (\n <p className=\"text-xs text-muted-foreground\">\n {resolvedMinQueryHintLabel}\n </p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">{resolvedStartTypingLabel}</p>\n )}\n {error ? <p className=\"text-xs text-status-error-text\" role=\"alert\">{resolvedEmptyLabel}</p> : null}\n </div>\n )\n}\n"],
5
- "mappings": ";AA6XQ,SAmHc,UAlHZ,KADF;AA3XR,YAAY,WAAW;AACvB,SAAS,OAAO,SAAS,QAAQ,SAAS;AAC1C,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,UAAU;AACnB,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,IAAI,EAAE,MAAM,EAAE,WAAW,eAAe,CAAC;AAqCrE,SAAS,iBACP,QACA,UACA,OACoB;AACpB,MAAI,CAAC,SAAS,CAAC,YAAY,SAAS,OAAO,MAAO,QAAO;AACzD,MAAI,OAAO,KAAK,CAAC,SAAS,KAAK,OAAO,KAAK,EAAG,QAAO;AACrD,SAAO,CAAC,UAAU,GAAG,MAAM;AAC7B;AAEO,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,SAAS,cAAc;AAAA,EACvB,cAAc;AAChB,GAAsB;AACpB,QAAM,IAAI,KAAK;AACf,QAAM,4BAA4B,qBAAqB,eAAe,EAAE,qCAAqC,cAA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F;AAAA,QAAC;AAAA;AAAA,UACC,WAAW;AAAA,YACT;AAAA,YACA,YAAY;AAAA,UACd;AAAA,UACA,eAAY;AAAA,UAEX;AAAA,uBACC,qBAAC,UAAK,WAAU,yEACd;AAAA,kCAAC,SAAM,WAAU,mBAAkB,eAAY,QAAO;AAAA,cACtD,oBAAC,UAAK,WAAU,oBAAoB,mCAAwB;AAAA,cAC3D,6BACC,oBAAC,UAAK,WAAU,qCAAqC,sCAA2B,IAC9E;AAAA,eACN,IAEA;AAAA,cAAC;AAAA;AAAA,gBACC,KAAK;AAAA,gBACL,MAAK;AAAA,gBACL,SAAQ;AAAA,gBACR,MAAK;AAAA,gBACL,WAAU;AAAA,gBACV,SAAS;AAAA,gBACT,cAAY;AAAA,gBACZ,OAAO;AAAA,gBAEP;AAAA,sCAAC,SAAM,WAAU,sCAAqC,eAAY,QAAO;AAAA,kBACzE,oBAAC,UAAK,WAAU,oCAAoC,mCAAwB;AAAA,kBAC3E,6BACC,oBAAC,UAAK,WAAU,2DAA2D,sCAA2B,IACpG;AAAA;AAAA;AAAA,YACN;AAAA,YAED,WAAW,OACV;AAAA,cAAC;AAAA;AAAA,gBACC,MAAK;AAAA,gBACL,SAAQ;AAAA,gBACR,MAAK;AAAA,gBACL,WAAU;AAAA,gBACV,SAAS;AAAA,gBACT,cAAY;AAAA,gBACZ,OAAO;AAAA,gBAEP,8BAAC,KAAE,WAAU,UAAS,eAAY,QAAO;AAAA;AAAA,YAC3C;AAAA;AAAA;AAAA,MAEJ;AAAA,QACE,WACF,oBAAC,OAAE,WAAU,iCACV,qCACH,IAEA,oBAAC,OAAE,WAAU,iCAAiC,oCAAyB;AAAA,IAExE,QAAQ,oBAAC,OAAE,WAAU,kCAAiC,MAAK,SAAS,8BAAmB,IAAO;AAAA,KACjG;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Check, Loader2, Search, X } from 'lucide-react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { Button } from '../../primitives/button'\nimport { IconButton } from '../../primitives/icon-button'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('ui').child({ component: 'LookupSelect' })\n\nexport type LookupSelectItem = {\n id: string\n title: string\n subtitle?: string | null\n badge?: string | null\n icon?: React.ReactNode\n disabled?: boolean\n rightLabel?: string | null\n description?: string | null\n}\n\ntype LookupSelectProps = {\n value: string | null\n onChange: (next: string | null) => void\n fetchItems?: (query: string) => Promise<LookupSelectItem[]>\n fetchOptions?: (query?: string) => Promise<LookupSelectItem[]>\n options?: LookupSelectItem[]\n minQuery?: number\n actionSlot?: React.ReactNode\n onReady?: (controls: { setQuery: (value: string) => void }) => void\n searchPlaceholder?: string\n placeholder?: string\n clearLabel?: string\n emptyLabel?: string\n loadingLabel?: string\n selectLabel?: string\n selectedLabel?: string\n minQueryHintLabel?: string\n startTypingLabel?: string\n selectedHintLabel?: (id: string) => string\n disabled?: boolean\n loading?: boolean\n defaultOpen?: boolean\n}\n\nfunction keepSelectedItem(\n result: LookupSelectItem[],\n selected: LookupSelectItem | null,\n value: string | null,\n): LookupSelectItem[] {\n if (!value || !selected || selected.id !== value) return result\n if (result.some((item) => item.id === value)) return result\n return [selected, ...result]\n}\n\nexport function LookupSelect({\n value,\n onChange,\n fetchItems,\n fetchOptions,\n options,\n minQuery = 2,\n actionSlot,\n onReady,\n placeholder,\n searchPlaceholder,\n clearLabel,\n emptyLabel,\n loadingLabel,\n selectLabel,\n selectedLabel,\n minQueryHintLabel,\n startTypingLabel,\n selectedHintLabel,\n disabled = false,\n loading: loadingProp = false,\n defaultOpen = false,\n}: LookupSelectProps) {\n const t = useT()\n const resolvedSearchPlaceholder = searchPlaceholder ?? placeholder ?? t('ui.lookupSelect.searchPlaceholder', 'Search\u2026')\n const resolvedClearLabel = clearLabel ?? t('ui.lookupSelect.clearSelection', 'Clear selection')\n const resolvedEmptyLabel = emptyLabel ?? t('ui.lookupSelect.noResults', 'No results')\n const resolvedLoadingLabel = loadingLabel ?? t('ui.lookupSelect.searching', 'Searching\u2026')\n const resolvedSelectLabel = selectLabel ?? t('ui.lookupSelect.select', 'Select')\n const resolvedSelectedLabel = selectedLabel ?? t('ui.lookupSelect.selected', 'Selected')\n const resolvedChangeLabel = t('ui.lookupSelect.change', 'Change')\n const resolvedStartTypingLabel = startTypingLabel ?? t('ui.lookupSelect.startTyping', 'Start typing to search.')\n const resolvedMinQueryHintLabel = minQueryHintLabel ?? t(\n 'ui.lookupSelect.minQueryHint',\n 'Minimum characters to search: {minQuery}. You can also paste an id.',\n { minQuery: String(minQuery) }\n )\n const [query, setQuery] = React.useState('')\n const [items, setItems] = React.useState<LookupSelectItem[]>(options ?? [])\n const [loading, setLoading] = React.useState(false)\n // Escape collapses the list without clearing the selection. Derived state is not\n // enough here: Escape empties the query but the fetched `items` linger, so the\n // list would stay open and the collapsed summary \u2014 the branch that keeps a raw\n // record id out of the DOM (TC-EUDR-013) \u2014 would never render.\n // A value that is already there when the lookup mounts (hydrated, or seeded by the host,\n // e.g. the deal owner defaulting to the current user) is a finished selection: it starts\n // collapsed on the summary instead of an open list with one row checked (#5109).\n // `defaultOpen` keeps the list on screen regardless (pickers that browse a short list).\n const [collapsed, setCollapsed] = React.useState(() => Boolean(value) && !defaultOpen)\n const [hasTyped, setHasTyped] = React.useState(defaultOpen)\n const [error, setError] = React.useState<string | null>(null)\n const [fetchKey, setFetchKey] = React.useState(0)\n const [activeIndex, setActiveIndex] = React.useState(-1)\n const [selectedItem, setSelectedItem] = React.useState<LookupSelectItem | null>(null)\n const listboxId = React.useId()\n const fetchItemsRef = React.useRef(fetchItems ?? fetchOptions)\n const setQueryRef = React.useRef(setQuery)\n const onReadyRef = React.useRef(onReady)\n const optionsWasArrayRef = React.useRef(Array.isArray(options))\n const valueRef = React.useRef(value)\n const selectedItemRef = React.useRef<LookupSelectItem | null>(null)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const pendingCommitRef = React.useRef<string | null>(null)\n const changeButtonRef = React.useRef<HTMLButtonElement>(null)\n const focusSummaryRef = React.useRef(false)\n\n React.useEffect(() => {\n fetchItemsRef.current = fetchItems ?? fetchOptions\n }, [fetchItems, fetchOptions])\n\n React.useEffect(() => {\n valueRef.current = value\n }, [value])\n\n React.useEffect(() => {\n onReadyRef.current = onReady\n }, [onReady])\n\n React.useEffect(() => {\n if (Array.isArray(options)) {\n optionsWasArrayRef.current = true\n setItems(options)\n } else if (optionsWasArrayRef.current) {\n optionsWasArrayRef.current = false\n setFetchKey((k) => k + 1)\n }\n }, [options])\n\n React.useEffect(() => {\n setQueryRef.current = setQuery\n if (onReadyRef.current) onReadyRef.current({ setQuery })\n }, [setQuery])\n\n // A set `value` keeps the lookup live: the list (or, once collapsed after a\n // pick, the summary) is where the selection, its checkmark and the clear control\n // render, so a selection is never invisible. This used to also require an\n // `options` prop, which left every caller that resolves its selection through\n // `fetchItems` blind whenever minQuery kept the list shut.\n const shouldSearch = defaultOpen || query.trim().length >= minQuery || Boolean(value)\n\n React.useEffect(() => {\n setActiveIndex(-1)\n }, [items])\n\n const optionDomId = React.useCallback(\n (index: number) => `${listboxId}-option-${index}`,\n [listboxId],\n )\n\n const isInteractiveItem = React.useCallback(\n (item: LookupSelectItem) => !disabled && (!item.disabled || value === item.id),\n [disabled, value],\n )\n\n const moveActiveIndex = React.useCallback((direction: 1 | -1) => {\n setActiveIndex((current) => {\n if (!items.length) return -1\n let next = current\n for (let step = 0; step < items.length; step += 1) {\n next = (next + direction + items.length) % items.length\n if (isInteractiveItem(items[next])) return next\n }\n return current\n })\n }, [isInteractiveItem, items])\n\n React.useEffect(() => {\n if (activeIndex < 0) return\n const activeElement = typeof document !== 'undefined'\n ? document.getElementById(optionDomId(activeIndex))\n : null\n if (typeof activeElement?.scrollIntoView === 'function') {\n activeElement.scrollIntoView({ block: 'nearest' })\n }\n }, [activeIndex, optionDomId])\n\n const listboxVisible = shouldSearch && !disabled && !collapsed\n\n const finishSelection = React.useCallback(() => {\n pendingCommitRef.current = null\n focusSummaryRef.current = true\n setCollapsed(true)\n setQuery('')\n setHasTyped(false)\n setActiveIndex(-1)\n }, [])\n\n // Picking a result ends the interaction (#6196): the list closes and the collapsed\n // summary takes over, but only once the parent has adopted the id. A host that keeps\n // `value` at null and collects picks itself (multi-add pickers) keeps browsing.\n const commitSelection = React.useCallback((item: LookupSelectItem) => {\n selectedItemRef.current = item\n setSelectedItem(item)\n if (valueRef.current === item.id) {\n finishSelection()\n return\n }\n pendingCommitRef.current = item.id\n onChange(item.id)\n }, [finishSelection, onChange])\n\n React.useEffect(() => {\n if (pendingCommitRef.current) {\n if (value === pendingCommitRef.current) finishSelection()\n else if (value) pendingCommitRef.current = null\n return\n }\n // The host adopted a value the user never picked here (seeded after mount): treat it\n // like a finished pick as long as the user is not mid-search.\n if (value && !hasTyped && query.length === 0) setCollapsed(true)\n }, [finishSelection, hasTyped, query, value])\n\n // The search box is not in the DOM while the summary row stands in for it, so the focus\n // moves once the box has mounted again.\n const focusAfterReopenRef = React.useRef(false)\n const reopenList = React.useCallback(() => {\n focusAfterReopenRef.current = true\n focusSummaryRef.current = false\n setCollapsed(false)\n }, [])\n const clearSelection = React.useCallback(() => {\n focusAfterReopenRef.current = true\n focusSummaryRef.current = false\n onChange(null)\n }, [onChange])\n\n // With nothing selected there is no summary to collapse onto, so the browse list comes back.\n React.useEffect(() => {\n if (!value) setCollapsed(false)\n }, [value])\n\n const handleInputKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {\n if (!listboxVisible) return\n if (event.key === 'ArrowDown') {\n event.preventDefault()\n moveActiveIndex(1)\n return\n }\n if (event.key === 'ArrowUp') {\n event.preventDefault()\n moveActiveIndex(-1)\n return\n }\n if (event.key === 'Enter') {\n if (activeIndex < 0 || activeIndex >= items.length) return\n const item = items[activeIndex]\n if (!isInteractiveItem(item)) return\n event.preventDefault()\n commitSelection(item)\n return\n }\n if (event.key === 'Escape') {\n if (query.length === 0 && activeIndex < 0) return\n event.preventDefault()\n event.stopPropagation()\n setQuery('')\n setActiveIndex(-1)\n focusSummaryRef.current = Boolean(value)\n setCollapsed(true)\n }\n }, [activeIndex, commitSelection, items, isInteractiveItem, listboxVisible, moveActiveIndex, query, value])\n React.useEffect(() => {\n if (disabled) {\n setItems(options ?? [])\n setLoading(false)\n return\n }\n let cancelled = false\n let timer: ReturnType<typeof setTimeout> | null = null\n if (!shouldSearch) {\n setItems(options ?? [])\n setLoading(false)\n setError(null)\n return () => { cancelled = true }\n }\n setLoading(true)\n setError(null)\n timer = setTimeout(() => {\n const requestId = Date.now()\n const fetcher = fetchItemsRef.current\n const loader = fetcher ?? (() => Promise.resolve(options ?? []))\n const trimmedQuery = query.trim()\n loader(trimmedQuery)\n .then((result) => {\n if (cancelled) return\n // A set `value` opens the list with an empty query, and that browse\n // fetch returns an arbitrary first page. Without this the stored\n // selection vanished from the list whenever it fell outside that page,\n // while the form still held its id. A typed query stays a pure search.\n setItems(\n trimmedQuery\n ? result\n : keepSelectedItem(result, selectedItemRef.current, valueRef.current),\n )\n })\n .catch((err) => {\n if (cancelled) return\n logger.error('Failed to fetch lookup items', { err })\n setError('error')\n })\n .finally(() => {\n if (!cancelled) setLoading(false)\n })\n return requestId\n }, 220)\n return () => {\n cancelled = true\n if (timer) clearTimeout(timer)\n }\n }, [query, shouldSearch, fetchKey])\n\n React.useEffect(() => {\n if (!value) {\n selectedItemRef.current = null\n setSelectedItem(null)\n return\n }\n const match = items.find((item) => item.id === value)\n if (match) {\n selectedItemRef.current = match\n setSelectedItem(match)\n }\n }, [items, value])\n\n /*\n * The collapsed summary needs a label it can trust: the consumer's\n * `selectedHintLabel` when it resolves to a name, otherwise the title of the\n * item that was actually fetched or picked. A resolver that falls back to the\n * id (`known.get(id) ?? id`) or embeds it (\"Selected customer: <id>\") is\n * treated as unresolved \u2014 a record id must never reach the DOM as a label.\n * With neither (a hydrated value whose lookup returned nothing) there is no\n * summary, so consumers rendering their own label never get a second one.\n */\n const collapsedSelectionLabel = React.useMemo(() => {\n if (!value) return null\n const hinted = selectedHintLabel?.(value)\n if (hinted && hinted !== value && !hinted.includes(value)) return hinted\n const fetchedTitle = selectedItem && selectedItem.id === value ? selectedItem.title : null\n return fetchedTitle && fetchedTitle !== value ? fetchedTitle : null\n }, [selectedHintLabel, selectedItem, value])\n const collapsedSelectionSubtitle = selectedItem && selectedItem.id === value ? selectedItem.subtitle ?? null : null\n // Once collapsed on a resolved selection the summary row IS the control: the search box\n // comes back only when the user asks to change the pick, so the field stays one row tall\n // and fits a narrow column (#5109).\n const showSummaryOnly = collapsed && Boolean(collapsedSelectionLabel)\n\n // The search box and the summary row replace each other, so whichever held the focus is\n // gone from the DOM: keyboard users continue on the control that took its place.\n React.useEffect(() => {\n if (showSummaryOnly) {\n if (!focusSummaryRef.current) return\n focusSummaryRef.current = false\n changeButtonRef.current?.focus()\n return\n }\n if (!focusAfterReopenRef.current) return\n focusAfterReopenRef.current = false\n inputRef.current?.focus()\n }, [showSummaryOnly])\n\n return (\n <div className=\"space-y-3\">\n {showSummaryOnly ? null : (\n <div className=\"flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3\">\n <div className=\"relative flex-1\">\n <Search className=\"pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground\" />\n <input\n ref={inputRef}\n className=\"w-full h-9 rounded-lg border border-input bg-background pl-10 pr-3 text-sm shadow-xs transition-colors outline-none placeholder:text-muted-foreground hover:border-foreground/20 focus-visible:shadow-focus focus-visible:border-foreground disabled:bg-bg-disabled disabled:border-border-disabled disabled:text-muted-foreground disabled:cursor-not-allowed\"\n value={query}\n onChange={(event) => {\n setQuery(event.target.value)\n setHasTyped(true)\n setCollapsed(false)\n }}\n onKeyDown={handleInputKeyDown}\n placeholder={resolvedSearchPlaceholder}\n disabled={disabled}\n role=\"combobox\"\n aria-expanded={listboxVisible}\n aria-controls={listboxId}\n aria-autocomplete=\"list\"\n aria-activedescendant={activeIndex >= 0 ? optionDomId(activeIndex) : undefined}\n />\n </div>\n {actionSlot && !disabled ? <div className=\"sm:self-start\">{actionSlot}</div> : null}\n </div>\n )}\n {/*\n * `shouldSearch` decides whether to FETCH; this decides whether to RENDER a\n * list. They differ for a set value whose lookup comes back empty: develop's\n * #5248 work needs the list (and its selected option) whenever items exist,\n * while the collapsed summary \u2014 which keeps a selection visible after the\n * search box reverts to its placeholder, and keeps a raw record id out of the\n * DOM (TC-EUDR-013) \u2014 is only reachable when they do not. Falling through on\n * an empty result satisfies both. A non-empty query still renders the list so\n * its spinner and empty-state are reachable while the user is searching.\n */}\n {shouldSearch && !collapsed && (items.length > 0 || query.trim().length > 0) ? (\n <div className=\"space-y-2\">\n {loading || loadingProp ? (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Loader2 className=\"h-4 w-4 animate-spin\" />\n {resolvedLoadingLabel}\n </div>\n ) : null}\n {!loading && !loadingProp && !items.length ? (\n <p className=\"text-xs text-muted-foreground\">{resolvedEmptyLabel}</p>\n ) : null}\n <div\n id={listboxId}\n role=\"listbox\"\n className=\"flex flex-col gap-1.5 max-h-80 overflow-y-auto -mx-0.5 px-0.5 py-0.5\"\n >\n {items.map((item, index) => {\n const isSelected = value === item.id\n const isInteractive = isInteractiveItem(item)\n const isActive = index === activeIndex\n return (\n <div\n key={item.id}\n id={optionDomId(index)}\n className={cn(\n 'group flex items-center gap-3 rounded-lg border px-3 py-2 transition-all duration-150 focus-visible:outline-none focus-visible:shadow-focus',\n isInteractive ? 'cursor-pointer' : 'cursor-not-allowed opacity-60',\n isSelected\n ? 'border-accent-indigo bg-accent-indigo/5'\n : 'border-input bg-card hover:border-foreground/20 hover:bg-muted/30',\n isActive && !isSelected ? 'border-foreground/20 bg-muted/30 shadow-sm' : null\n )}\n role=\"option\"\n tabIndex={isInteractive ? 0 : -1}\n onClick={() => {\n if (!isInteractive) return\n commitSelection(item)\n }}\n onKeyDown={(event) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault()\n if (!isInteractive) return\n commitSelection(item)\n }\n }}\n aria-selected={isSelected}\n aria-disabled={isInteractive ? undefined : true}\n title={isSelected ? resolvedSelectedLabel : isInteractive ? resolvedSelectLabel : undefined}\n >\n {item.icon ? (\n <div className=\"flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden [&>svg]:size-5 [&_svg]:text-muted-foreground\">\n {item.icon}\n </div>\n ) : (\n <div className={cn(\n 'flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-md border transition-colors',\n isSelected\n ? 'border-accent-indigo/40 bg-accent-indigo/10 text-accent-indigo'\n : 'border-input bg-muted text-muted-foreground group-hover:border-foreground/20'\n )}>\n <span className=\"text-sm font-medium uppercase\">{item.title.slice(0, 1)}</span>\n </div>\n )}\n <div className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <div className=\"flex items-center justify-between gap-3\">\n <div className=\"truncate text-sm font-medium text-foreground\">{item.title}</div>\n {item.rightLabel ? (\n <div className=\"shrink-0 text-overline font-medium uppercase tracking-wider text-muted-foreground\">\n {item.rightLabel}\n </div>\n ) : null}\n </div>\n {item.subtitle ? (\n <div className=\"text-xs text-muted-foreground truncate\">{item.subtitle}</div>\n ) : null}\n {item.description ? (\n <div className=\"text-xs text-muted-foreground/70 truncate\">{item.description}</div>\n ) : null}\n </div>\n <div className=\"flex shrink-0 items-center justify-center gap-1.5\">\n {isSelected ? (\n <>\n <span className=\"text-xs font-medium text-foreground\">{resolvedSelectedLabel}</span>\n <Check className=\"size-4 text-accent-indigo\" aria-hidden=\"true\" />\n </>\n ) : (\n <div className=\"size-5\" aria-hidden=\"true\" />\n )}\n </div>\n </div>\n )\n })}\n </div>\n {value && !disabled ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"w-fit gap-1 text-sm font-normal\"\n onClick={() => onChange(null)}\n >\n <X className=\"h-4 w-4\" />\n {resolvedClearLabel}\n </Button>\n ) : null}\n </div>\n ) : collapsedSelectionLabel ? (\n /*\n * The selection as a single row: the name is the control that reopens the\n * search (Change), the icon clears. No second search box above it.\n */\n <div\n className={cn(\n 'flex h-9 items-center gap-1 rounded-lg border border-accent-indigo bg-accent-indigo/5 pl-1 pr-1',\n disabled && 'border-border-disabled bg-bg-disabled',\n )}\n data-testid=\"lookup-select-selected\"\n >\n {disabled ? (\n <span className=\"flex h-7 min-w-0 flex-1 items-center gap-2 px-2 text-muted-foreground\">\n <Check className=\"size-4 shrink-0\" aria-hidden=\"true\" />\n <span className=\"truncate text-sm\">{collapsedSelectionLabel}</span>\n {collapsedSelectionSubtitle ? (\n <span className=\"hidden truncate text-xs sm:inline\">{collapsedSelectionSubtitle}</span>\n ) : null}\n </span>\n ) : (\n <Button\n ref={changeButtonRef}\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-7 min-w-0 flex-1 justify-start gap-2 px-2 text-left font-normal hover:bg-accent-indigo/10 hover:text-accent-indigo\"\n onClick={reopenList}\n aria-label={resolvedChangeLabel}\n title={resolvedChangeLabel}\n >\n <Check className=\"size-4 shrink-0 text-accent-indigo\" aria-hidden=\"true\" />\n <span className=\"truncate text-sm text-foreground\">{collapsedSelectionLabel}</span>\n {collapsedSelectionSubtitle ? (\n <span className=\"hidden truncate text-xs text-muted-foreground sm:inline\">{collapsedSelectionSubtitle}</span>\n ) : null}\n </Button>\n )}\n {disabled ? null : (\n <IconButton\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"shrink-0 text-muted-foreground hover:bg-accent-indigo/10 hover:text-accent-indigo\"\n onClick={clearSelection}\n aria-label={resolvedClearLabel}\n title={resolvedClearLabel}\n >\n <X className=\"size-4\" aria-hidden=\"true\" />\n </IconButton>\n )}\n </div>\n ) : hasTyped && minQuery > 0 ? (\n <p className=\"text-xs text-muted-foreground\">\n {resolvedMinQueryHintLabel}\n </p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">{resolvedStartTypingLabel}</p>\n )}\n {error ? <p className=\"text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AAA;AAAA,gBACC,KAAK;AAAA,gBACL,MAAK;AAAA,gBACL,SAAQ;AAAA,gBACR,MAAK;AAAA,gBACL,WAAU;AAAA,gBACV,SAAS;AAAA,gBACT,cAAY;AAAA,gBACZ,OAAO;AAAA,gBAEP;AAAA,sCAAC,SAAM,WAAU,sCAAqC,eAAY,QAAO;AAAA,kBACzE,oBAAC,UAAK,WAAU,oCAAoC,mCAAwB;AAAA,kBAC3E,6BACC,oBAAC,UAAK,WAAU,2DAA2D,sCAA2B,IACpG;AAAA;AAAA;AAAA,YACN;AAAA,YAED,WAAW,OACV;AAAA,cAAC;AAAA;AAAA,gBACC,MAAK;AAAA,gBACL,SAAQ;AAAA,gBACR,MAAK;AAAA,gBACL,WAAU;AAAA,gBACV,SAAS;AAAA,gBACT,cAAY;AAAA,gBACZ,OAAO;AAAA,gBAEP,8BAAC,KAAE,WAAU,UAAS,eAAY,QAAO;AAAA;AAAA,YAC3C;AAAA;AAAA;AAAA,MAEJ;AAAA,QACE,YAAY,WAAW,IACzB,oBAAC,OAAE,WAAU,iCACV,qCACH,IAEA,oBAAC,OAAE,WAAU,iCAAiC,oCAAyB;AAAA,IAExE,QAAQ,oBAAC,OAAE,WAAU,kCAAiC,MAAK,SAAS,8BAAmB,IAAO;AAAA,KACjG;AAEJ;",
6
6
  "names": []
7
7
  }
package/jest.config.cjs CHANGED
@@ -26,6 +26,7 @@ module.exports = {
26
26
  rootDir: '.',
27
27
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
28
28
  moduleNameMapper: {
29
+ '^@open-mercato/telemetry/browser$': '<rootDir>/../telemetry/src/browser/index.ts',
29
30
  '^@open-mercato/ui/(.*)$': '<rootDir>/src/$1',
30
31
  '^@open-mercato/core/(.*)$': '<rootDir>/../core/src/$1',
31
32
  '^@open-mercato/shared/(.*)$': '<rootDir>/../shared/src/$1',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/ui",
3
- "version": "0.11.1-develop.8298.1.5323e2aa15",
3
+ "version": "0.11.1-develop.8317.1.dde3d38b64",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -156,14 +156,14 @@
156
156
  "remark-gfm": "^4.0.1"
157
157
  },
158
158
  "peerDependencies": {
159
- "@open-mercato/shared": "0.11.1-develop.8298.1.5323e2aa15",
159
+ "@open-mercato/shared": "0.11.1-develop.8317.1.dde3d38b64",
160
160
  "react": ">=18.0.0",
161
161
  "react-dom": ">=18.0.0",
162
162
  "react-is": ">=18.0.0"
163
163
  },
164
164
  "devDependencies": {
165
165
  "@figma/code-connect": "^1.3.4",
166
- "@open-mercato/shared": "0.11.1-develop.8298.1.5323e2aa15",
166
+ "@open-mercato/shared": "0.11.1-develop.8317.1.dde3d38b64",
167
167
  "@testing-library/dom": "^10.4.1",
168
168
  "@testing-library/jest-dom": "^7.0.1",
169
169
  "@testing-library/react": "^16.3.3",
@@ -340,7 +340,7 @@ export type CrudFormProps<TValues extends Record<string, unknown>> = {
340
340
  formId?: string
341
341
  customFieldsLoadingMessage?: string
342
342
  cancelHref?: string
343
- successRedirect?: string
343
+ successRedirect?: string | ((values: TValues, result: void | CrudFormSubmitResult) => string | undefined)
344
344
  deleteRedirect?: string
345
345
  onSubmit?: (values: TValues, context?: CrudFormSubmitContext) => Promise<void | CrudFormSubmitResult> | void | CrudFormSubmitResult
346
346
  onSubmitSuccess?: (values: TValues, result: void | CrudFormSubmitResult) => Promise<void> | void
@@ -3385,7 +3385,10 @@ function CrudFormImpl<TValues extends Record<string, unknown>>({
3385
3385
  logger.error('Error in onSubmitSuccess', { err })
3386
3386
  getTelemetryRuntime()?.reportError(err, { module: 'ui', code: 'ui.form_submit_success_failed' })
3387
3387
  }
3388
- if (successRedirect) redirectNavigationStarted = await navigateWithGuard(successRedirect)
3388
+ const successRedirectTarget = typeof successRedirect === 'function'
3389
+ ? successRedirect(coreSubmitValues, submitResult)
3390
+ : successRedirect
3391
+ if (successRedirectTarget) redirectNavigationStarted = await navigateWithGuard(successRedirectTarget)
3389
3392
  } catch (err: unknown) {
3390
3393
  clearSubmitNavigationBypass()
3391
3394
  try {
@@ -98,7 +98,10 @@ describe('CrudForm double-submit protection (issue #1539)', () => {
98
98
  await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2))
99
99
  })
100
100
 
101
- it('ignores a second submit after a successful save that redirects, before the route unmounts the form (issue #8645)', async () => {
101
+ it.each([
102
+ '/somewhere',
103
+ () => '/somewhere',
104
+ ])('ignores a second submit after a successful save that redirects, before the route unmounts the form (issue #8645)', async (successRedirect) => {
102
105
  let resolveSubmit: (() => void) | null = null
103
106
  const onSubmit = jest.fn(
104
107
  () =>
@@ -113,7 +116,7 @@ describe('CrudForm double-submit protection (issue #1539)', () => {
113
116
  fields={fields}
114
117
  initialValues={{ name: 'alpha' }}
115
118
  onSubmit={onSubmit}
116
- successRedirect="/somewhere"
119
+ successRedirect={successRedirect}
117
120
  />,
118
121
  )
119
122
 
@@ -140,7 +143,10 @@ describe('CrudForm double-submit protection (issue #1539)', () => {
140
143
  expect(onSubmit).toHaveBeenCalledTimes(1)
141
144
  })
142
145
 
143
- it('releases the lock when onBeforeNavigate blocks the success redirect, so the next submit proceeds normally', async () => {
146
+ it.each([
147
+ '/somewhere',
148
+ () => '/somewhere',
149
+ ])('releases the lock when onBeforeNavigate blocks the success redirect, so the next submit proceeds normally', async (successRedirect) => {
144
150
  triggerInjectionEventMock.mockImplementation(async (eventName: unknown) =>
145
151
  eventName === 'onBeforeNavigate' ? { ok: false, message: 'blocked' } : { ok: true },
146
152
  )
@@ -153,7 +159,7 @@ describe('CrudForm double-submit protection (issue #1539)', () => {
153
159
  fields={fields}
154
160
  initialValues={{ name: 'alpha' }}
155
161
  onSubmit={onSubmit}
156
- successRedirect="/somewhere"
162
+ successRedirect={successRedirect}
157
163
  injectionSpotId="test:crudform-nav-guard"
158
164
  />,
159
165
  )
@@ -175,4 +181,36 @@ describe('CrudForm double-submit protection (issue #1539)', () => {
175
181
  await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2))
176
182
  })
177
183
 
184
+ it('resolves the redirect with the saved result after the success lifecycle completes', async () => {
185
+ const onSubmitSuccess = jest.fn()
186
+ const successRedirect = jest.fn(() => '/created/123')
187
+ const { container } = renderWithProviders(
188
+ <CrudForm
189
+ fields={fields}
190
+ initialValues={{ name: 'alpha' }}
191
+ onSubmit={() => ({ resourceId: '123' })}
192
+ onSubmitSuccess={onSubmitSuccess}
193
+ successRedirect={successRedirect}
194
+ />,
195
+ )
196
+
197
+ await act(async () => { fireEvent.submit(container.querySelector('form')!) })
198
+
199
+ await waitFor(() => expect(successRedirect).toHaveBeenCalledWith({ name: 'alpha' }, { resourceId: '123' }))
200
+ expect(onSubmitSuccess.mock.invocationCallOrder[0]).toBeLessThan(successRedirect.mock.invocationCallOrder[0])
201
+ })
202
+
203
+ it('releases the lock when the redirect resolver returns no destination', async () => {
204
+ const onSubmit = jest.fn(() => Promise.resolve())
205
+ const { container } = renderWithProviders(
206
+ <CrudForm fields={fields} onSubmit={onSubmit} successRedirect={() => undefined} />,
207
+ )
208
+ const form = container.querySelector('form')!
209
+
210
+ await act(async () => { fireEvent.submit(form) })
211
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
212
+ await act(async () => { fireEvent.submit(form) })
213
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2))
214
+ })
215
+
178
216
  })
@@ -155,7 +155,7 @@ export function KpiCard({
155
155
  <BadgeDelta direction={trend.direction} value={trend.value} />
156
156
  )}
157
157
  </div>
158
- {trend && comparisonLabel && (
158
+ {comparisonLabel && (
159
159
  <p className="mt-1 text-xs text-muted-foreground">{comparisonLabel}</p>
160
160
  )}
161
161
  {footer != null && <div className="mt-3">{footer}</div>}
@@ -7,6 +7,25 @@ import { render, screen } from '@testing-library/react'
7
7
  import { KpiCard } from '../KpiCard'
8
8
 
9
9
  describe('KpiCard', () => {
10
+ it.each([
11
+ 'target 8:00 — 6:00 to go',
12
+ 'of 40:00',
13
+ '21 working days',
14
+ '16.7% of the month',
15
+ ])('shows the comparison caption without a trend: %s', (comparisonLabel) => {
16
+ render(<KpiCard title="Today" value={120} comparisonLabel={comparisonLabel} />)
17
+
18
+ expect(screen.getByText(comparisonLabel)).toBeVisible()
19
+ expect(screen.queryByTitle('Compared to previous period')).toBeNull()
20
+ })
21
+
22
+ it('shows the comparison caption alongside a supplied trend', () => {
23
+ render(<KpiCard title="Orders" value={3} comparisonLabel="last month" trend={{ value: 10, direction: 'up' }} />)
24
+
25
+ expect(screen.getByText('last month')).toBeVisible()
26
+ expect(screen.getByText('10%')).toBeVisible()
27
+ })
28
+
10
29
  it('keeps the footer when there is no value, because the footer is what explains the dash', () => {
11
30
  render(<KpiCard title="Latest NPS" value={null} footer={<span>Never answered a survey</span>} />)
12
31
  expect(screen.getByText('--')).toBeTruthy()
@@ -256,14 +256,14 @@ export function AddressEditor<C = unknown>({
256
256
  disabled={disabled}
257
257
  aria-invalid={errors.name ? 'true' : undefined}
258
258
  />
259
- <div className="flex gap-2">
259
+ <div className="flex min-w-0 gap-2">
260
260
  <Select
261
261
  value={current.purpose || undefined}
262
262
  onValueChange={(next) => update('purpose', next ?? '')}
263
263
  disabled={disabled}
264
264
  >
265
265
  <SelectTrigger
266
- className={errors.purpose ? 'border-destructive' : undefined}
266
+ className={cn('min-w-0 flex-1', errors.purpose && 'border-status-error-border')}
267
267
  aria-invalid={errors.purpose ? 'true' : undefined}
268
268
  >
269
269
  <SelectValue
@@ -6,9 +6,10 @@ import { Button } from '@open-mercato/ui/primitives/button'
6
6
  import { flash } from '@open-mercato/ui/backend/FlashMessages'
7
7
  import { TabEmptyState } from '@open-mercato/ui/backend/detail'
8
8
  import { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'
9
+ import { reportTelemetryError } from '@open-mercato/shared/lib/telemetry/runtime'
9
10
  import { normalizeCoordinateInput, validateCoordinateInput } from '@open-mercato/shared/lib/location/coordinates'
10
11
  import { AddressView, type AddressFormatStrategy } from './addressFormat'
11
- import AddressEditor, { type AddressTypesAdapter } from './AddressEditor'
12
+ import AddressEditor, { type AddressTypeOption, type AddressTypesAdapter } from './AddressEditor'
12
13
  import {
13
14
  Dialog,
14
15
  DialogContent,
@@ -198,6 +199,7 @@ export function AddressTiles<C = unknown>({
198
199
  const [fieldErrors, setFieldErrors] = React.useState<Partial<Record<DraftFieldKey, string>>>({})
199
200
  const [format, setFormat] = React.useState<AddressFormatStrategy>('line_first')
200
201
  const [formatLoading, setFormatLoading] = React.useState(false)
202
+ const [addressTypes, setAddressTypes] = React.useState<AddressTypeOption[]>([])
201
203
 
202
204
  const label = React.useCallback(
203
205
  (suffix: string, fallback?: string, params?: Record<string, string | number>) =>
@@ -205,6 +207,30 @@ export function AddressTiles<C = unknown>({
205
207
  [labelPrefix, t],
206
208
  )
207
209
 
210
+ React.useEffect(() => {
211
+ let cancelled = false
212
+ setAddressTypes([])
213
+ if (!addressTypesAdapter) return
214
+ async function loadAddressTypes(adapter: AddressTypesAdapter<C>) {
215
+ try {
216
+ const options = await adapter.list(addressTypesContext)
217
+ if (!cancelled) setAddressTypes(Array.isArray(options) ? options : [])
218
+ } catch (error) {
219
+ try {
220
+ reportTelemetryError(error, {
221
+ module: 'ui',
222
+ code: 'ui.address_types_load_failed',
223
+ })
224
+ } catch {}
225
+ if (!cancelled) flash(label('types.loadError', 'Failed to load address types'), 'error')
226
+ }
227
+ }
228
+ void loadAddressTypes(addressTypesAdapter)
229
+ return () => {
230
+ cancelled = true
231
+ }
232
+ }, [addressTypesAdapter, addressTypesContext, label, scopeVersion])
233
+
208
234
  const fieldLabels = React.useMemo(
209
235
  () => ({
210
236
  name: label('fields.label', 'Label'),
@@ -430,7 +456,7 @@ export function AddressTiles<C = unknown>({
430
456
  (key: string) => (
431
457
  <div
432
458
  key={key}
433
- className="rounded-lg border-2 border-dashed border-muted-foreground/50 bg-muted/30 p-4 text-sm"
459
+ className="col-span-full min-w-0 rounded-lg border-2 border-dashed border-muted-foreground/50 bg-muted/30 p-4 text-sm"
434
460
  onKeyDown={(event) => {
435
461
  if (event.defaultPrevented) return
436
462
  if (event.key === 'Escape') {
@@ -572,7 +598,7 @@ export function AddressTiles<C = unknown>({
572
598
  </div>
573
599
  {address.purpose ? (
574
600
  <p className="text-xs text-muted-foreground">
575
- {address.purpose}
601
+ {addressTypes.find((option) => option.value === address.purpose)?.label ?? address.purpose}
576
602
  </p>
577
603
  ) : null}
578
604
  <AddressView address={address} format={format} className="text-sm text-foreground" />
@@ -0,0 +1,115 @@
1
+ import * as React from 'react'
2
+ import { TextEncoder } from 'node:util'
3
+ import { act, screen, waitFor } from '@testing-library/react'
4
+ import type { ReadableSpan } from '@opentelemetry/sdk-trace-base'
5
+ import { BrowserTelemetry, type BrowserTelemetryConfig } from '@open-mercato/telemetry/browser'
6
+ import { resetBrowserTelemetryBootstrap } from '../../../../../telemetry/src/browser/BrowserTelemetry'
7
+ import { renderWithProviders } from '@open-mercato/shared/lib/testing/renderWithProviders'
8
+ import { createFallbackTranslator } from '@open-mercato/shared/lib/i18n/translate'
9
+ import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
10
+ import customerPolish from '@open-mercato/core/modules/customers/i18n/pl.json'
11
+ import { flash } from '@open-mercato/ui/backend/FlashMessages'
12
+ import { AddressTiles } from '../AddressTiles'
13
+
14
+ Object.defineProperty(globalThis, 'TextEncoder', { value: TextEncoder, configurable: true })
15
+
16
+ const mockExportedSpans: ReadableSpan[] = []
17
+ const mockExporterCreated = jest.fn()
18
+
19
+ jest.mock('next/navigation', () => ({
20
+ usePathname: () => '/backend/customers/people/person-1',
21
+ useSearchParams: () => new URLSearchParams(),
22
+ }))
23
+ jest.mock('@open-mercato/ui/backend/FlashMessages', () => ({ flash: jest.fn() }))
24
+ jest.mock('@open-mercato/ui/backend/detail', () => ({ TabEmptyState: () => null }))
25
+ jest.mock('@opentelemetry/instrumentation', () => ({
26
+ ...jest.requireActual<typeof import('@opentelemetry/instrumentation')>('@opentelemetry/instrumentation'),
27
+ registerInstrumentations: () => undefined,
28
+ }))
29
+ jest.mock('@opentelemetry/exporter-trace-otlp-http', () => ({
30
+ OTLPTraceExporter: class {
31
+ constructor(config: { url: string }) {
32
+ mockExporterCreated(config)
33
+ }
34
+ export(spans: ReadableSpan[], callback: (result: { code: number }) => void) {
35
+ mockExportedSpans.push(...spans)
36
+ callback({ code: 0 })
37
+ }
38
+ async shutdown() {}
39
+ },
40
+ }))
41
+
42
+ const config: BrowserTelemetryConfig = {
43
+ endpoint: '/api/telemetry/browser-traces',
44
+ serviceName: 'address-browser-test',
45
+ environment: 'test',
46
+ samplingRatio: 1,
47
+ }
48
+ const translator = createFallbackTranslator(customerPolish)
49
+
50
+ function renderAddresses(telemetry: BrowserTelemetryConfig | null, failure: Error) {
51
+ return renderWithProviders(
52
+ <>
53
+ <AddressTiles
54
+ addresses={[{ id: 'address-1', name: 'Biuro', purpose: 'office', addressLine1: 'Długa 1' }]}
55
+ onCreate={async () => undefined}
56
+ t={translator}
57
+ emptyLabel="Brak adresów"
58
+ addressTypesAdapter={{ list: async () => { throw failure } }}
59
+ />
60
+ <BrowserTelemetry config={telemetry} />
61
+ </>,
62
+ )
63
+ }
64
+
65
+ describe('address errors through the normal BrowserTelemetry entry', () => {
66
+ beforeEach(() => {
67
+ resetBrowserTelemetryBootstrap()
68
+ mockExportedSpans.length = 0
69
+ mockExporterCreated.mockClear()
70
+ jest.mocked(flash).mockClear()
71
+ })
72
+
73
+ afterEach(() => resetBrowserTelemetryBootstrap())
74
+
75
+ it('keeps the localized readable fallback without starting an exporter while browser telemetry is off', async () => {
76
+ renderAddresses(null, new Error('[internal] dictionary unavailable'))
77
+ await waitFor(() => expect(flash).toHaveBeenCalledWith('Nie udało się wczytać typów adresów', 'error'))
78
+ expect(screen.getByText('office')).toBeInTheDocument()
79
+ expect(mockExporterCreated).not.toHaveBeenCalled()
80
+ expect(mockExportedSpans).toEqual([])
81
+ })
82
+
83
+ it('exports an initial dictionary rejection through the real browser SDK and shared reporter registration', async () => {
84
+ const failure = new Error('[internal] dictionary unavailable')
85
+ expect(getTelemetryRuntime()).toBeUndefined()
86
+ renderAddresses(config, failure)
87
+ expect(mockExporterCreated).not.toHaveBeenCalled()
88
+ await waitFor(() => expect(flash).toHaveBeenCalledWith('Nie udało się wczytać typów adresów', 'error'))
89
+ expect(screen.getByText('Biuro')).toBeInTheDocument()
90
+ expect(screen.getByText('office')).toBeInTheDocument()
91
+ await waitFor(() => expect(mockExporterCreated).toHaveBeenCalledWith({ url: config.endpoint }))
92
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
93
+ await act(async () => { window.dispatchEvent(new Event('pagehide')) })
94
+ await waitFor(() => expect(mockExportedSpans).toHaveLength(1))
95
+ expect(mockExportedSpans[0]).toMatchObject({
96
+ name: 'browser.error',
97
+ attributes: { module: 'ui', 'error.code': 'ui.address_types_load_failed' },
98
+ status: { code: 2 },
99
+ events: [{ name: 'exception', attributes: {
100
+ 'exception.type': failure.name,
101
+ 'exception.message': failure.message,
102
+ 'exception.stacktrace': failure.stack,
103
+ } }],
104
+ })
105
+ })
106
+
107
+ it('keeps feedback and fallback when browser SDK initialization fails without retrying', async () => {
108
+ mockExporterCreated.mockImplementationOnce(() => { throw new Error('[internal] exporter unavailable') })
109
+ renderAddresses(config, new Error('[internal] dictionary unavailable'))
110
+ await waitFor(() => expect(flash).toHaveBeenCalledWith('Nie udało się wczytać typów adresów', 'error'))
111
+ await waitFor(() => expect(mockExporterCreated).toHaveBeenCalledTimes(1))
112
+ expect(screen.getByText('office')).toBeInTheDocument()
113
+ expect(mockExportedSpans).toEqual([])
114
+ })
115
+ })