@open-mercato/ui 0.10.1-develop.8159.1.71854b31a8 → 0.10.1-develop.8164.1.f12a3857ee

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/detail/AddressesSection.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { surfaceRecordConflict } from '../conflicts'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { createTranslatorWithFallback } from '@open-mercato/shared/lib/i18n/translate'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport AddressTiles, { type AddressInput, type AddressValue } from './AddressTiles'\nimport type { AddressTypesAdapter } from './AddressEditor'\nimport type { AddressFormatStrategy } from './addressFormat'\nimport { ComponentReplacementHandles } from '@open-mercato/shared/modules/widgets/component-registry'\nimport { useRegisteredComponent } from '../injection/useRegisteredComponent'\n\ntype Translator = (key: string, fallback?: string, params?: Record<string, string | number>) => string\n\nexport type SectionAction = {\n label: React.ReactNode\n onClick: () => void\n disabled?: boolean\n icon?: React.ReactNode\n}\n\nexport type TabEmptyStateConfig = {\n title: string\n actionLabel: string\n description?: string\n}\n\nexport type AddressSummary = {\n id: string\n name?: string | null\n purpose?: string | null\n companyName?: string | null\n addressLine1: string\n addressLine2?: string | null\n buildingNumber?: string | null\n flatNumber?: string | null\n city?: string | null\n region?: string | null\n postalCode?: string | null\n country?: string | null\n latitude?: number | null\n longitude?: number | null\n isPrimary?: boolean\n updatedAt?: string | null\n}\n\nexport type AddressDataAdapter<C = unknown> = {\n list: (params: { entityId: string | null; context?: C }) => Promise<AddressSummary[]>\n create: (params: { entityId: string; payload: AddressInput; context?: C }) => Promise<{ id?: string } | void>\n update: (params: { id: string; payload: AddressInput; updatedAt?: string | null; context?: C }) => Promise<void>\n delete: (params: { id: string; updatedAt?: string | null; context?: C }) => Promise<void>\n}\n\nexport type AddressesSectionProps<C = unknown> = {\n entityId: string | null\n emptyLabel: string\n addActionLabel: string\n emptyState: TabEmptyStateConfig\n onActionChange?: (action: SectionAction | null) => void\n translator?: Translator\n onLoadingChange?: (isLoading: boolean) => void\n dataAdapter: AddressDataAdapter<C>\n dataContext?: C\n addressTypesAdapter?: AddressTypesAdapter<C>\n addressTypesContext?: C\n loadFormat?: (context?: C) => Promise<AddressFormatStrategy>\n formatContext?: C\n labelPrefix?: string\n showCoordinateFields?: boolean\n}\n\nfunction generateTempId() {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()\n return `tmp_${Math.random().toString(36).slice(2)}`\n}\n\nfunction AddressesSectionImpl<C = unknown>({\n entityId,\n emptyLabel,\n addActionLabel,\n emptyState,\n onActionChange,\n translator,\n onLoadingChange,\n dataAdapter,\n dataContext,\n addressTypesAdapter,\n addressTypesContext,\n loadFormat,\n formatContext,\n labelPrefix = 'customers.people.detail.addresses',\n showCoordinateFields = false,\n}: AddressesSectionProps<C>) {\n const tHook = useT()\n const fallbackTranslator = React.useMemo<Translator>(() => createTranslatorWithFallback(tHook), [tHook])\n const t = translator ?? fallbackTranslator\n\n const label = React.useCallback(\n (suffix: string, fallback?: string, params?: Record<string, string | number>) =>\n t(`${labelPrefix}.${suffix}`, fallback, params),\n [labelPrefix, t],\n )\n\n const normalizedEntityId = React.useMemo(() => {\n if (typeof entityId !== 'string') return null\n const trimmed = entityId.trim()\n return trimmed.length ? trimmed : null\n }, [entityId])\n const [addresses, setAddresses] = React.useState<AddressSummary[]>([])\n const [isSubmitting, setIsSubmitting] = React.useState(false)\n const [isLoading, setIsLoading] = React.useState<boolean>(() => Boolean(normalizedEntityId))\n\n const loadingCounterRef = React.useRef(0)\n const pushLoading = React.useCallback(() => {\n loadingCounterRef.current += 1\n if (loadingCounterRef.current === 1) {\n onLoadingChange?.(true)\n }\n }, [onLoadingChange])\n const popLoading = React.useCallback(() => {\n loadingCounterRef.current = Math.max(0, loadingCounterRef.current - 1)\n if (loadingCounterRef.current === 0) {\n onLoadingChange?.(false)\n }\n }, [onLoadingChange])\n\n const loadAddresses = React.useCallback(async () => {\n if (!normalizedEntityId) {\n setAddresses([])\n setIsLoading(false)\n return\n }\n setIsLoading(true)\n pushLoading()\n try {\n const items = await dataAdapter.list({ entityId: normalizedEntityId, context: dataContext })\n setAddresses(items)\n } catch (err) {\n const message =\n err instanceof Error && err.message\n ? err.message\n : label('error', 'Failed to load addresses.')\n flash(message, 'error')\n setAddresses([])\n } finally {\n setIsLoading(false)\n popLoading()\n }\n }, [dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading])\n\n React.useEffect(() => {\n void loadAddresses()\n }, [loadAddresses])\n\n const handleCreate = React.useCallback(\n async (payload: AddressInput) => {\n if (!normalizedEntityId) {\n throw new Error(label('error', 'Failed to save address.'))\n }\n pushLoading()\n setIsSubmitting(true)\n try {\n const response = await dataAdapter.create({\n entityId: normalizedEntityId,\n payload,\n context: dataContext,\n })\n const newAddress: AddressSummary = {\n id: typeof response === 'object' && response && typeof response.id === 'string' ? response.id : generateTempId(),\n name: payload.name ?? null,\n purpose: payload.purpose ?? null,\n companyName: payload.companyName ?? null,\n addressLine1: payload.addressLine1,\n addressLine2: payload.addressLine2 ?? null,\n buildingNumber: payload.buildingNumber ?? null,\n flatNumber: payload.flatNumber ?? null,\n city: payload.city ?? null,\n region: payload.region ?? null,\n postalCode: payload.postalCode ?? null,\n country: payload.country ? payload.country.toUpperCase() : null,\n latitude: payload.latitude ?? null,\n longitude: payload.longitude ?? null,\n isPrimary: payload.isPrimary ?? false,\n }\n setAddresses((prev) => {\n const existing = payload.isPrimary ? prev.map((addr) => ({ ...addr, isPrimary: false })) : prev\n return [newAddress, ...existing]\n })\n flash(label('success', 'Address saved.'), 'success')\n } catch (err) {\n const message =\n err instanceof Error && err.message ? err.message : label('error', 'Failed to save address.')\n const error = new Error(message) as Error & { details?: unknown }\n if (err && typeof err === 'object' && (err as { details?: unknown }).details) {\n error.details = (err as { details?: unknown }).details\n }\n throw error\n } finally {\n setIsSubmitting(false)\n popLoading()\n }\n },\n [dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading],\n )\n\n const handleUpdate = React.useCallback(\n async (id: string, payload: AddressInput) => {\n if (!normalizedEntityId) {\n throw new Error(label('error', 'Failed to save address.'))\n }\n pushLoading()\n setIsSubmitting(true)\n try {\n const addressUpdatedAt = addresses.find((address) => address.id === id)?.updatedAt ?? null\n await dataAdapter.update({ id, payload, updatedAt: addressUpdatedAt, context: dataContext })\n setAddresses((prev) => {\n return prev.map((address) => {\n if (address.id !== id) {\n return payload.isPrimary ? { ...address, isPrimary: false } : address\n }\n return {\n ...address,\n name: payload.name ?? null,\n purpose: payload.purpose ?? null,\n companyName: payload.companyName ?? null,\n addressLine1: payload.addressLine1,\n addressLine2: payload.addressLine2 ?? null,\n buildingNumber: payload.buildingNumber ?? null,\n flatNumber: payload.flatNumber ?? null,\n city: payload.city ?? null,\n region: payload.region ?? null,\n postalCode: payload.postalCode ?? null,\n country: payload.country ? payload.country.toUpperCase() : null,\n latitude: payload.latitude ?? null,\n longitude: payload.longitude ?? null,\n isPrimary: payload.isPrimary ?? false,\n }\n })\n })\n flash(label('success', 'Address saved.'), 'success')\n } catch (err) {\n surfaceRecordConflict(err, t)\n const message =\n err instanceof Error && err.message ? err.message : label('error', 'Failed to save address.')\n const error = new Error(message) as Error & { details?: unknown }\n if (err && typeof err === 'object' && (err as { details?: unknown }).details) {\n error.details = (err as { details?: unknown }).details\n }\n throw error\n } finally {\n setIsSubmitting(false)\n popLoading()\n }\n },\n [addresses, dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading, t],\n )\n\n const handleDelete = React.useCallback(\n async (id: string) => {\n if (!normalizedEntityId) {\n throw new Error(label('error', 'Failed to delete address.'))\n }\n pushLoading()\n setIsSubmitting(true)\n try {\n const addressUpdatedAt = addresses.find((address) => address.id === id)?.updatedAt ?? null\n await dataAdapter.delete({ id, updatedAt: addressUpdatedAt, context: dataContext })\n setAddresses((prev) => prev.filter((address) => address.id !== id))\n flash(label('deleted', 'Address deleted.'), 'success')\n } catch (err) {\n const message =\n err instanceof Error && err.message ? err.message : label('error', 'Failed to delete address.')\n if (!surfaceRecordConflict(err, t)) flash(message, 'error')\n throw err\n } finally {\n setIsSubmitting(false)\n popLoading()\n }\n },\n [addresses, dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading, t],\n )\n\n const displayAddresses = React.useMemo<AddressValue[]>(() => {\n return addresses.map((address) => ({\n id: address.id,\n name: address.name ?? undefined,\n purpose: address.purpose ?? undefined,\n companyName: address.companyName ?? undefined,\n addressLine1: address.addressLine1,\n addressLine2: address.addressLine2 ?? undefined,\n buildingNumber: address.buildingNumber ?? undefined,\n flatNumber: address.flatNumber ?? undefined,\n city: address.city ?? undefined,\n region: address.region ?? undefined,\n postalCode: address.postalCode ?? undefined,\n country: address.country ?? undefined,\n latitude: address.latitude ?? undefined,\n longitude: address.longitude ?? undefined,\n isPrimary: address.isPrimary ?? false,\n }))\n }, [addresses])\n\n const [addAction, setAddAction] = React.useState<{\n openCreateForm: () => void\n addDisabled: boolean\n } | null>(null)\n\n const handleAddActionChange = React.useCallback(\n (action: { openCreateForm: () => void; addDisabled: boolean } | null) => {\n setAddAction(action)\n },\n [],\n )\n\n React.useEffect(() => {\n if (!onActionChange) return\n if (!addAction || addresses.length === 0) {\n onActionChange(null)\n return\n }\n onActionChange({\n label: addActionLabel,\n onClick: addAction.openCreateForm,\n disabled: addAction.addDisabled,\n })\n }, [addAction, addActionLabel, addresses.length, onActionChange])\n\n return (\n <div className=\"mt-4\">\n {isLoading ? (\n <div className=\"flex justify-center\">\n <LoadingMessage\n label={label('loading', 'Loading addresses\u2026')}\n className=\"min-h-[120px] w-full justify-center border-0 bg-transparent p-0\"\n />\n </div>\n ) : (\n <AddressTiles\n addresses={displayAddresses}\n onCreate={handleCreate}\n onUpdate={handleUpdate}\n onDelete={handleDelete}\n isSubmitting={isSubmitting}\n emptyLabel={emptyLabel}\n t={t}\n hideAddButton\n onAddActionChange={handleAddActionChange}\n emptyStateTitle={emptyState.title}\n emptyStateActionLabel={emptyState.actionLabel}\n labelPrefix={labelPrefix}\n showCoordinateFields={showCoordinateFields}\n addressTypesAdapter={addressTypesAdapter}\n addressTypesContext={addressTypesContext}\n loadFormat={loadFormat}\n formatContext={formatContext}\n />\n )}\n </div>\n )\n}\n\nexport function AddressesSection<C = unknown>(props: AddressesSectionProps<C>) {\n const handle = ComponentReplacementHandles.section('ui.detail', 'AddressesSection')\n const Resolved = useRegisteredComponent<AddressesSectionProps<C>>(\n handle,\n AddressesSectionImpl as React.ComponentType<AddressesSectionProps<C>>,\n )\n\n return (\n <div data-component-handle={handle}>\n <Resolved {...props} />\n </div>\n )\n}\n\nexport default AddressesSection\n"],
5
- "mappings": ";AA6UU;AA3UV,YAAY,WAAW;AACvB,SAAS,aAAa;AACtB,SAAS,6BAA6B;AACtC,SAAS,sBAAsB;AAC/B,SAAS,oCAAoC;AAC7C,SAAS,YAAY;AACrB,OAAO,kBAA4D;AAGnE,SAAS,mCAAmC;AAC5C,SAAS,8BAA8B;AA6DvC,SAAS,iBAAiB;AACxB,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,WAAY,QAAO,OAAO,WAAW;AACvG,SAAO,OAAO,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC;AACnD;AAEA,SAAS,qBAAkC;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,uBAAuB;AACzB,GAA6B;AAC3B,QAAM,QAAQ,KAAK;AACnB,QAAM,qBAAqB,MAAM,QAAoB,MAAM,6BAA6B,KAAK,GAAG,CAAC,K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B;AACrB,QAAI,CAAC,aAAa,UAAU,WAAW,GAAG;AACxC,qBAAe,IAAI;AACnB;AAAA,IACF;AACA,mBAAe;AAAA,MACb,OAAO;AAAA,MACP,SAAS,UAAU;AAAA,MACnB,UAAU,UAAU;AAAA,IACtB,CAAC;AAAA,EACH,GAAG,CAAC,WAAW,gBAAgB,UAAU,QAAQ,cAAc,CAAC;AAEhE,SACE,oBAAC,SAAI,WAAU,QACZ,sBACC,oBAAC,SAAI,WAAU,uBACb;AAAA,IAAC;AAAA;AAAA,MACC,OAAO,MAAM,WAAW,yBAAoB;AAAA,MAC5C,WAAU;AAAA;AAAA,EACZ,GACF,IAEA;AAAA,IAAC;AAAA;AAAA,MACC,WAAW;AAAA,MACX,UAAU;AAAA,MACV,UAAU;AAAA,MACV,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAa;AAAA,MACb,mBAAmB;AAAA,MACnB,iBAAiB,WAAW;AAAA,MAC5B,uBAAuB,WAAW;AAAA,MAClC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA;AAAA,EACF,GAEJ;AAEJ;AAEO,SAAS,iBAA8B,OAAiC;AAC7E,QAAM,SAAS,4BAA4B,QAAQ,aAAa,kBAAkB;AAClF,QAAM,WAAW;AAAA,IACf;AAAA,IACA;AAAA,EACF;AAEA,SACE,oBAAC,SAAI,yBAAuB,QAC1B,8BAAC,YAAU,GAAG,OAAO,GACvB;AAEJ;AAEA,IAAO,2BAAQ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { surfaceRecordConflict } from '../conflicts'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { createTranslatorWithFallback } from '@open-mercato/shared/lib/i18n/translate'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport AddressTiles, { type AddressInput, type AddressValue } from './AddressTiles'\nimport type { AddressTypesAdapter } from './AddressEditor'\nimport type { AddressFormatStrategy } from './addressFormat'\nimport { ComponentReplacementHandles } from '@open-mercato/shared/modules/widgets/component-registry'\nimport { useRegisteredComponent } from '../injection/useRegisteredComponent'\n\ntype Translator = (key: string, fallback?: string, params?: Record<string, string | number>) => string\n\nexport type SectionAction = {\n label: React.ReactNode\n onClick: () => void\n disabled?: boolean\n icon?: React.ReactNode\n}\n\nexport type TabEmptyStateConfig = {\n title: string\n actionLabel: string\n description?: string\n}\n\nexport type AddressSummary = {\n id: string\n name?: string | null\n purpose?: string | null\n companyName?: string | null\n addressLine1: string\n addressLine2?: string | null\n buildingNumber?: string | null\n flatNumber?: string | null\n city?: string | null\n region?: string | null\n postalCode?: string | null\n country?: string | null\n latitude?: number | null\n longitude?: number | null\n isPrimary?: boolean\n updatedAt?: string | null\n}\n\nexport type AddressDataAdapter<C = unknown> = {\n list: (params: { entityId: string | null; context?: C }) => Promise<AddressSummary[]>\n create: (params: { entityId: string; payload: AddressInput; context?: C }) => Promise<{ id?: string } | void>\n update: (params: { id: string; payload: AddressInput; updatedAt?: string | null; context?: C }) => Promise<void>\n delete: (params: { id: string; updatedAt?: string | null; context?: C }) => Promise<void>\n}\n\nexport type AddressesSectionProps<C = unknown> = {\n entityId: string | null\n emptyLabel: string\n addActionLabel: string\n emptyState: TabEmptyStateConfig\n onActionChange?: (action: SectionAction | null) => void\n translator?: Translator\n onLoadingChange?: (isLoading: boolean) => void\n dataAdapter: AddressDataAdapter<C>\n dataContext?: C\n addressTypesAdapter?: AddressTypesAdapter<C>\n addressTypesContext?: C\n loadFormat?: (context?: C) => Promise<AddressFormatStrategy>\n formatContext?: C\n labelPrefix?: string\n showCoordinateFields?: boolean\n}\n\nfunction generateTempId() {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()\n return `tmp_${Math.random().toString(36).slice(2)}`\n}\n\nfunction AddressesSectionImpl<C = unknown>({\n entityId,\n emptyLabel,\n addActionLabel,\n emptyState,\n onActionChange,\n translator,\n onLoadingChange,\n dataAdapter,\n dataContext,\n addressTypesAdapter,\n addressTypesContext,\n loadFormat,\n formatContext,\n labelPrefix = 'customers.people.detail.addresses',\n showCoordinateFields = false,\n}: AddressesSectionProps<C>) {\n const tHook = useT()\n const fallbackTranslator = React.useMemo<Translator>(() => createTranslatorWithFallback(tHook), [tHook])\n const t = translator ?? fallbackTranslator\n\n const label = React.useCallback(\n (suffix: string, fallback?: string, params?: Record<string, string | number>) =>\n t(`${labelPrefix}.${suffix}`, fallback, params),\n [labelPrefix, t],\n )\n\n const normalizedEntityId = React.useMemo(() => {\n if (typeof entityId !== 'string') return null\n const trimmed = entityId.trim()\n return trimmed.length ? trimmed : null\n }, [entityId])\n const [addresses, setAddresses] = React.useState<AddressSummary[]>([])\n const [isSubmitting, setIsSubmitting] = React.useState(false)\n const [isLoading, setIsLoading] = React.useState<boolean>(() => Boolean(normalizedEntityId))\n\n const loadingCounterRef = React.useRef(0)\n const pushLoading = React.useCallback(() => {\n loadingCounterRef.current += 1\n if (loadingCounterRef.current === 1) {\n onLoadingChange?.(true)\n }\n }, [onLoadingChange])\n const popLoading = React.useCallback(() => {\n loadingCounterRef.current = Math.max(0, loadingCounterRef.current - 1)\n if (loadingCounterRef.current === 0) {\n onLoadingChange?.(false)\n }\n }, [onLoadingChange])\n\n const loadAddresses = React.useCallback(async () => {\n if (!normalizedEntityId) {\n setAddresses([])\n setIsLoading(false)\n return\n }\n setIsLoading(true)\n pushLoading()\n try {\n const items = await dataAdapter.list({ entityId: normalizedEntityId, context: dataContext })\n setAddresses(items)\n } catch (err) {\n const message =\n err instanceof Error && err.message\n ? err.message\n : label('error', 'Failed to load addresses.')\n flash(message, 'error')\n setAddresses([])\n } finally {\n setIsLoading(false)\n popLoading()\n }\n }, [dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading])\n\n React.useEffect(() => {\n void loadAddresses()\n }, [loadAddresses])\n\n const handleCreate = React.useCallback(\n async (payload: AddressInput) => {\n if (!normalizedEntityId) {\n throw new Error(label('error', 'Failed to save address.'))\n }\n pushLoading()\n setIsSubmitting(true)\n try {\n const response = await dataAdapter.create({\n entityId: normalizedEntityId,\n payload,\n context: dataContext,\n })\n const newAddress: AddressSummary = {\n id: typeof response === 'object' && response && typeof response.id === 'string' ? response.id : generateTempId(),\n name: payload.name ?? null,\n purpose: payload.purpose ?? null,\n companyName: payload.companyName ?? null,\n addressLine1: payload.addressLine1,\n addressLine2: payload.addressLine2 ?? null,\n buildingNumber: payload.buildingNumber ?? null,\n flatNumber: payload.flatNumber ?? null,\n city: payload.city ?? null,\n region: payload.region ?? null,\n postalCode: payload.postalCode ?? null,\n country: payload.country ? payload.country.toUpperCase() : null,\n latitude: payload.latitude ?? null,\n longitude: payload.longitude ?? null,\n isPrimary: payload.isPrimary ?? false,\n }\n setAddresses((prev) => {\n const existing = payload.isPrimary ? prev.map((addr) => ({ ...addr, isPrimary: false })) : prev\n return [newAddress, ...existing]\n })\n flash(label('success', 'Address saved.'), 'success')\n await loadAddresses()\n } catch (err) {\n const message =\n err instanceof Error && err.message ? err.message : label('error', 'Failed to save address.')\n const error = new Error(message) as Error & { details?: unknown }\n if (err && typeof err === 'object' && (err as { details?: unknown }).details) {\n error.details = (err as { details?: unknown }).details\n }\n throw error\n } finally {\n setIsSubmitting(false)\n popLoading()\n }\n },\n [dataAdapter, dataContext, label, loadAddresses, normalizedEntityId, popLoading, pushLoading],\n )\n\n const handleUpdate = React.useCallback(\n async (id: string, payload: AddressInput) => {\n if (!normalizedEntityId) {\n throw new Error(label('error', 'Failed to save address.'))\n }\n pushLoading()\n setIsSubmitting(true)\n try {\n const addressUpdatedAt = addresses.find((address) => address.id === id)?.updatedAt ?? null\n await dataAdapter.update({ id, payload, updatedAt: addressUpdatedAt, context: dataContext })\n setAddresses((prev) => {\n return prev.map((address) => {\n if (address.id !== id) {\n return payload.isPrimary ? { ...address, isPrimary: false } : address\n }\n return {\n ...address,\n name: payload.name ?? null,\n purpose: payload.purpose ?? null,\n companyName: payload.companyName ?? null,\n addressLine1: payload.addressLine1,\n addressLine2: payload.addressLine2 ?? null,\n buildingNumber: payload.buildingNumber ?? null,\n flatNumber: payload.flatNumber ?? null,\n city: payload.city ?? null,\n region: payload.region ?? null,\n postalCode: payload.postalCode ?? null,\n country: payload.country ? payload.country.toUpperCase() : null,\n latitude: payload.latitude ?? null,\n longitude: payload.longitude ?? null,\n isPrimary: payload.isPrimary ?? false,\n }\n })\n })\n flash(label('success', 'Address saved.'), 'success')\n await loadAddresses()\n } catch (err) {\n const isConflict = surfaceRecordConflict(err, t)\n const message = isConflict\n ? t('ui.forms.flash.recordModified')\n : err instanceof Error && err.message ? err.message : label('error', 'Failed to save address.')\n const error = new Error(message) as Error & { details?: unknown }\n if (err && typeof err === 'object' && (err as { details?: unknown }).details) {\n error.details = (err as { details?: unknown }).details\n }\n throw error\n } finally {\n setIsSubmitting(false)\n popLoading()\n }\n },\n [addresses, dataAdapter, dataContext, label, loadAddresses, normalizedEntityId, popLoading, pushLoading, t],\n )\n\n const handleDelete = React.useCallback(\n async (id: string) => {\n if (!normalizedEntityId) {\n throw new Error(label('error', 'Failed to delete address.'))\n }\n pushLoading()\n setIsSubmitting(true)\n try {\n const addressUpdatedAt = addresses.find((address) => address.id === id)?.updatedAt ?? null\n await dataAdapter.delete({ id, updatedAt: addressUpdatedAt, context: dataContext })\n setAddresses((prev) => prev.filter((address) => address.id !== id))\n flash(label('deleted', 'Address deleted.'), 'success')\n } catch (err) {\n const message =\n err instanceof Error && err.message ? err.message : label('error', 'Failed to delete address.')\n if (surfaceRecordConflict(err, t)) {\n throw new Error(t('ui.forms.flash.recordModified'))\n }\n flash(message, 'error')\n throw err\n } finally {\n setIsSubmitting(false)\n popLoading()\n }\n },\n [addresses, dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading, t],\n )\n\n const displayAddresses = React.useMemo<AddressValue[]>(() => {\n return addresses.map((address) => ({\n id: address.id,\n name: address.name ?? undefined,\n purpose: address.purpose ?? undefined,\n companyName: address.companyName ?? undefined,\n addressLine1: address.addressLine1,\n addressLine2: address.addressLine2 ?? undefined,\n buildingNumber: address.buildingNumber ?? undefined,\n flatNumber: address.flatNumber ?? undefined,\n city: address.city ?? undefined,\n region: address.region ?? undefined,\n postalCode: address.postalCode ?? undefined,\n country: address.country ?? undefined,\n latitude: address.latitude ?? undefined,\n longitude: address.longitude ?? undefined,\n isPrimary: address.isPrimary ?? false,\n }))\n }, [addresses])\n\n const [addAction, setAddAction] = React.useState<{\n openCreateForm: () => void\n addDisabled: boolean\n } | null>(null)\n\n const handleAddActionChange = React.useCallback(\n (action: { openCreateForm: () => void; addDisabled: boolean } | null) => {\n setAddAction(action)\n },\n [],\n )\n\n React.useEffect(() => {\n if (!onActionChange) return\n if (!addAction || addresses.length === 0) {\n onActionChange(null)\n return\n }\n onActionChange({\n label: addActionLabel,\n onClick: addAction.openCreateForm,\n disabled: addAction.addDisabled,\n })\n }, [addAction, addActionLabel, addresses.length, onActionChange])\n\n return (\n <div className=\"mt-4\">\n {isLoading ? (\n <div className=\"flex justify-center\">\n <LoadingMessage\n label={label('loading', 'Loading addresses\u2026')}\n className=\"min-h-[120px] w-full justify-center border-0 bg-transparent p-0\"\n />\n </div>\n ) : (\n <AddressTiles\n addresses={displayAddresses}\n onCreate={handleCreate}\n onUpdate={handleUpdate}\n onDelete={handleDelete}\n isSubmitting={isSubmitting}\n emptyLabel={emptyLabel}\n t={t}\n hideAddButton\n onAddActionChange={handleAddActionChange}\n emptyStateTitle={emptyState.title}\n emptyStateActionLabel={emptyState.actionLabel}\n labelPrefix={labelPrefix}\n showCoordinateFields={showCoordinateFields}\n addressTypesAdapter={addressTypesAdapter}\n addressTypesContext={addressTypesContext}\n loadFormat={loadFormat}\n formatContext={formatContext}\n />\n )}\n </div>\n )\n}\n\nexport function AddressesSection<C = unknown>(props: AddressesSectionProps<C>) {\n const handle = ComponentReplacementHandles.section('ui.detail', 'AddressesSection')\n const Resolved = useRegisteredComponent<AddressesSectionProps<C>>(\n handle,\n AddressesSectionImpl as React.ComponentType<AddressesSectionProps<C>>,\n )\n\n return (\n <div data-component-handle={handle}>\n <Resolved {...props} />\n </div>\n )\n}\n\nexport default AddressesSection\n"],
5
+ "mappings": ";AAmVU;AAjVV,YAAY,WAAW;AACvB,SAAS,aAAa;AACtB,SAAS,6BAA6B;AACtC,SAAS,sBAAsB;AAC/B,SAAS,oCAAoC;AAC7C,SAAS,YAAY;AACrB,OAAO,kBAA4D;AAGnE,SAAS,mCAAmC;AAC5C,SAAS,8BAA8B;AA6DvC,SAAS,iBAAiB;AACxB,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,WAAY,QAAO,OAAO,WAAW;AACvG,SAAO,OAAO,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC;AACnD;AAEA,SAAS,qBAAkC;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,uBAAuB;AACzB,GAA6B;AAC3B,QAAM,QAAQ,KAAK;AACnB,QAAM,qBAAqB,MAAM,QAAoB,MAAM,6BAA6B,KAAK,GAAG,CAAC,KAAK,CAAC;AACvG,QAAM,IAAI,cAAc;AAExB,QAAM,QAAQ,MAAM;AAAA,IAClB,CAAC,QAAgB,UAAmB,WAClC,EAAE,GAAG,WAAW,IAAI,MAAM,IAAI,UAAU,MAAM;AAAA,IAChD,CAAC,aAAa,CAAC;AAAA,EACjB;AAEA,QAAM,qBAAqB,MAAM,QAAQ,MAAM;AAC7C,QAAI,OAAO,aAAa,SAAU,QAAO;AACzC,UAAM,UAAU,SAAS,KAAK;AAC9B,WAAO,QAAQ,SAAS,UAAU;AAAA,EACpC,GAAG,CAAC,QAAQ,CAAC;AACb,QAAM,CAAC,WAAW,YAAY,IAAI,MAAM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AU,QACZ,sBACC,oBAAC,SAAI,WAAU,uBACb;AAAA,IAAC;AAAA;AAAA,MACC,OAAO,MAAM,WAAW,yBAAoB;AAAA,MAC5C,WAAU;AAAA;AAAA,EACZ,GACF,IAEA;AAAA,IAAC;AAAA;AAAA,MACC,WAAW;AAAA,MACX,UAAU;AAAA,MACV,UAAU;AAAA,MACV,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAa;AAAA,MACb,mBAAmB;AAAA,MACnB,iBAAiB,WAAW;AAAA,MAC5B,uBAAuB,WAAW;AAAA,MAClC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA;AAAA,EACF,GAEJ;AAEJ;AAEO,SAAS,iBAA8B,OAAiC;AAC7E,QAAM,SAAS,4BAA4B,QAAQ,aAAa,kBAAkB;AAClF,QAAM,WAAW;AAAA,IACf;AAAA,IACA;AAAA,EACF;AAEA,SACE,oBAAC,SAAI,yBAAuB,QAC1B,8BAAC,YAAU,GAAG,OAAO,GACvB;AAEJ;AAEA,IAAO,2BAAQ;",
6
6
  "names": []
7
7
  }
@@ -31,6 +31,7 @@ function areOptionsEqual(a, b) {
31
31
  });
32
32
  }
33
33
  function ComboboxInput({
34
+ id,
34
35
  value,
35
36
  onChange,
36
37
  placeholder,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/backend/inputs/ComboboxInput.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { 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 { Popover, PopoverAnchor, PopoverContent } from '../../primitives/popover'\n\nexport type ComboboxOption = {\n value: string\n label: string\n description?: string | null\n}\n\nexport type ComboboxInputProps = {\n value: string\n onChange: (next: string) => void\n placeholder?: string\n suggestions?: Array<string | ComboboxOption>\n // Options to hydrate the option map up front (typically the linked entity's\n // display fields, already present in a record-detail payload). Merged with\n // `suggestions` so a pre-selected value renders its label without interaction.\n seedOptions?: ComboboxOption[]\n loadSuggestions?: (query?: string) => Promise<Array<string | ComboboxOption>>\n // Eagerly resolve a pre-selected `value` to a human label when it is not\n // covered by `suggestions`/`seedOptions`/`loadSuggestions` results. Runs once\n // per value, before any user interaction. May be sync or async.\n resolveLabel?: (value: string) => string | Promise<string>\n resolveDescription?: (value: string) => string | null | undefined\n autoFocus?: boolean\n disabled?: boolean\n allowCustomValues?: boolean\n clearable?: boolean\n clearLabel?: string\n 'aria-describedby'?: string\n 'aria-invalid'?: boolean\n 'aria-required'?: boolean\n}\n\nfunction normalizeOptions(input?: Array<string | ComboboxOption>): ComboboxOption[] {\n if (!Array.isArray(input)) return []\n return input\n .map((option) => {\n if (typeof option === 'string') {\n const trimmed = option.trim()\n if (!trimmed) return null\n return { value: trimmed, label: trimmed }\n }\n const value = typeof option.value === 'string' ? option.value.trim() : ''\n if (!value) return null\n return {\n value,\n label: option.label?.trim() || value,\n description: option.description ?? null,\n }\n })\n .filter((option): option is ComboboxOption => !!option)\n}\n\nfunction areOptionsEqual(a: ComboboxOption[], b: ComboboxOption[]): boolean {\n if (a.length !== b.length) return false\n return a.every((option, index) => {\n const next = b[index]\n return option.value === next.value\n && option.label === next.label\n && (option.description ?? null) === (next.description ?? null)\n })\n}\n\nexport function ComboboxInput({\n value,\n onChange,\n placeholder,\n suggestions,\n seedOptions,\n loadSuggestions,\n resolveLabel,\n resolveDescription,\n autoFocus,\n disabled = false,\n allowCustomValues = true,\n clearable = false,\n clearLabel,\n 'aria-describedby': ariaDescribedBy,\n 'aria-invalid': ariaInvalid,\n 'aria-required': ariaRequired,\n}: ComboboxInputProps) {\n const t = useT()\n const resolvedPlaceholder = placeholder ?? t('ui.inputs.comboboxInput.placeholder', 'Type to search...')\n const loadingLabel = t('ui.inputs.comboboxInput.loading', 'Loading suggestions\u2026')\n const noMatchesLabel = t('ui.inputs.comboboxInput.noMatches', 'No matches found')\n const resolvedClearLabel = clearLabel ?? t('ui.inputs.comboboxInput.clear', 'Clear value')\n const blurCloseDelayMs = 250\n const blurCloseMaxDelayMs = 1000\n const [input, setInput] = React.useState('')\n const [asyncOptions, setAsyncOptions] = React.useState<ComboboxOption[]>([])\n const [resolvedOptions, setResolvedOptions] = React.useState<ComboboxOption[]>([])\n const [loading, setLoading] = React.useState(false)\n const [touched, setTouched] = React.useState(false)\n const [showSuggestions, setShowSuggestions] = React.useState(false)\n const [selectedIndex, setSelectedIndex] = React.useState(-1)\n const listboxId = React.useId()\n const inputRef = React.useRef<HTMLInputElement>(null)\n const loadingRef = React.useRef(false)\n const blurCloseTimerRef = React.useRef<number | null>(null)\n const blurClosePendingRef = React.useRef(false)\n const suppressOpenOnFocusRef = React.useRef(Boolean(autoFocus && !disabled))\n const eagerFallbackLoadedValueRef = React.useRef<string | null>(null)\n // Tracks whether the user actually typed into the field during the current focus\n // session. `touched` cannot serve this purpose because it is set by `onFocus`,\n // which `autoFocus` triggers before the user does anything at all.\n const userTypedRef = React.useRef(false)\n\n const staticOptions = React.useMemo(\n () => normalizeOptions([...(seedOptions ?? []), ...(suggestions ?? [])]),\n [seedOptions, suggestions]\n )\n\n // Single pass over all option sources to build both coverage sets at once.\n // knownLabelValues: values with a genuine label (not a self-mapping placeholder) \u2014\n // used to decide whether eager resolution still needs to run.\n // coveredOptionValues: all values present in any source (even self-mapped).\n const { knownLabelValues, coveredOptionValues } = React.useMemo(() => {\n const known = new Set<string>()\n const covered = new Set<string>()\n for (const opt of [...staticOptions, ...asyncOptions, ...resolvedOptions]) {\n covered.add(opt.value)\n if (opt.label && opt.label !== opt.value) known.add(opt.value)\n }\n return { knownLabelValues: known, coveredOptionValues: covered }\n }, [staticOptions, asyncOptions, resolvedOptions])\n\n const optionMap = React.useMemo(() => {\n const map = new Map<string, ComboboxOption>()\n const register = (option: ComboboxOption) => {\n const existing = map.get(option.value)\n // Prefer an entry that carries a real label over a self-mapping placeholder.\n if (!existing || (existing.label === existing.value && option.label !== option.value)) {\n map.set(option.value, option)\n }\n }\n staticOptions.forEach(register)\n asyncOptions.forEach(register)\n resolvedOptions.forEach(register)\n if (value) {\n const existing = map.get(value)\n if (!existing) {\n map.set(value, {\n value,\n label: value,\n description: resolveDescription?.(value) ?? null,\n })\n }\n }\n return map\n }, [asyncOptions, resolvedOptions, resolveDescription, staticOptions, value])\n\n const availableOptions = React.useMemo(() => {\n return Array.from(optionMap.values())\n }, [optionMap])\n\n React.useEffect(() => {\n loadingRef.current = loading\n }, [loading])\n\n const clearBlurCloseTimer = React.useCallback(() => {\n if (blurCloseTimerRef.current === null) return\n window.clearTimeout(blurCloseTimerRef.current)\n blurCloseTimerRef.current = null\n }, [])\n\n const resetBlurCloseState = React.useCallback(() => {\n blurClosePendingRef.current = false\n clearBlurCloseTimer()\n }, [clearBlurCloseTimer])\n\n React.useEffect(() => resetBlurCloseState, [resetBlurCloseState])\n\n const filteredSuggestions = React.useMemo(() => {\n const query = input.toLowerCase().trim()\n if (!query) return availableOptions\n return availableOptions.filter((option) => {\n const labelMatch = option.label.toLowerCase().includes(query)\n const descMatch = option.description?.toLowerCase().includes(query)\n return labelMatch || Boolean(descMatch)\n })\n }, [availableOptions, input])\n\n React.useEffect(() => {\n if (!loadSuggestions || !touched || disabled) return\n const query = input.trim()\n let cancelled = false\n const handle = window.setTimeout(() => {\n setLoading(true)\n Promise.resolve()\n .then(() => loadSuggestions(query))\n .then((items) => {\n if (!cancelled) {\n const normalized = normalizeOptions(items)\n setAsyncOptions((prev) => areOptionsEqual(prev, normalized) ? prev : normalized)\n }\n })\n .catch(() => {})\n .finally(() => {\n if (!cancelled) setLoading(false)\n })\n }, 200)\n return () => {\n cancelled = true\n window.clearTimeout(handle)\n }\n }, [disabled, input, loadSuggestions, touched])\n\n // Eagerly resolve a pre-selected value to its label without requiring the user\n // to focus the field. Runs once per value when it is not already covered.\n const eagerResolveLabel = typeof resolveLabel === 'function' ? resolveLabel : undefined\n React.useEffect(() => {\n if (!value) return\n let cancelled = false\n const apply = (label?: string | null, description?: string | null) => {\n const clean = typeof label === 'string' ? label.trim() : ''\n if (cancelled || !clean || clean === value) return\n setResolvedOptions((prev) => {\n if (prev.some((option) => option.value === value && option.label === clean)) return prev\n return [...prev.filter((option) => option.value !== value), { value, label: clean, description: description ?? null }]\n })\n }\n if (eagerResolveLabel) {\n if (knownLabelValues.has(value)) return\n Promise.resolve()\n .then(() => eagerResolveLabel(value))\n .then((label) => apply(label, resolveDescription?.(value)))\n .catch(() => {})\n return () => { cancelled = true }\n }\n if (coveredOptionValues.has(value)) return\n if (eagerFallbackLoadedValueRef.current === value) return\n eagerFallbackLoadedValueRef.current = value\n // Fallback: pull the first page of async suggestions so a remount that lost\n // its option cache can still recover the label without user interaction.\n // Note: if the loader is paginated and the value falls outside the first page,\n // the fallback silently fails and the raw value remains visible.\n if (loadSuggestions) {\n setLoading(true)\n Promise.resolve()\n .then(() => loadSuggestions())\n .then((items) => {\n if (cancelled) return\n const normalized = normalizeOptions(items)\n setAsyncOptions((prev) => areOptionsEqual(prev, normalized) ? prev : normalized)\n })\n .catch(() => {})\n .finally(() => { if (!cancelled) setLoading(false) })\n }\n return () => { cancelled = true }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- resolveDescription intentionally excluded:\n // including it would re-run the effect on every render when the prop is an inline function\n }, [value, knownLabelValues, coveredOptionValues, eagerResolveLabel, loadSuggestions])\n\n // Sync input with a value that changed outside the component. A focused field is\n // synced too, because `autoFocus` can focus the control before an async default value\n // arrives and a focus-only guard then leaves the control rendering an empty label for\n // a value the form has already committed. Two conditions still block the sync:\n // - the user is typing, so their query is never clobbered mid-keystroke;\n // - `optionMap` only holds the self-mapping placeholder it synthesises for an\n // uncovered value, which would paint the raw record id over a label the user just\n // picked (`asyncOptions` is replaced on every load, so any follow-up load that\n // misses the picked entry \u2014 a failed request, a debounce race, a composite label\n // the route's `?search=` cannot match \u2014 drops it back to the placeholder).\n React.useEffect(() => {\n const option = optionMap.get(value)\n const hasRealLabel = Boolean(option && option.label !== option.value)\n if (document.activeElement === inputRef.current && (userTypedRef.current || !hasRealLabel)) return\n setInput(option?.label ?? value ?? '')\n }, [value, optionMap])\n\n const selectValue = React.useCallback(\n (nextValue: string) => {\n if (disabled) return\n resetBlurCloseState()\n const trimmed = nextValue.trim()\n onChange(trimmed)\n const option = optionMap.get(trimmed)\n setInput(option?.label ?? trimmed)\n setShowSuggestions(false)\n setSelectedIndex(-1)\n userTypedRef.current = false\n },\n [disabled, onChange, optionMap, resetBlurCloseState]\n )\n\n const findOptionForInput = React.useCallback(\n (raw: string): ComboboxOption | null => {\n const query = raw.trim().toLowerCase()\n if (!query) return null\n for (const option of optionMap.values()) {\n if (option.value === raw.trim()) return option\n if (option.label.toLowerCase() === query) return option\n }\n return null\n },\n [optionMap]\n )\n\n const confirmSelection = React.useCallback(\n (raw: string) => {\n if (disabled) return\n if (clearable && raw.trim() === '') {\n selectValue('')\n return\n }\n const option = findOptionForInput(raw)\n if (option) {\n selectValue(option.value)\n return\n }\n if (!allowCustomValues) {\n // Revert to the current value's label \u2014 but only if we actually know it.\n // Baking the raw value back in while eager resolution is still pending\n // would freeze a placeholder (e.g. a UUID) into the visible input.\n setShowSuggestions(false)\n const currentOption = optionMap.get(value)\n if (currentOption && currentOption.label !== currentOption.value) {\n setInput(currentOption.label)\n } else if (!value) {\n setInput('')\n }\n return\n }\n selectValue(raw)\n },\n [allowCustomValues, clearable, disabled, findOptionForInput, optionMap, selectValue, value]\n )\n\n const handleClear = React.useCallback(() => {\n if (disabled) return\n selectValue('')\n inputRef.current?.focus()\n }, [disabled, selectValue])\n\n const closeAfterBlur = React.useCallback(() => {\n blurCloseTimerRef.current = null\n if (disabled) return\n blurClosePendingRef.current = false\n confirmSelection(input)\n setShowSuggestions(false)\n setSelectedIndex(-1)\n }, [confirmSelection, disabled, input])\n\n const attemptBlurClose = React.useCallback(() => {\n blurCloseTimerRef.current = null\n if (disabled) return\n if (loadingRef.current) {\n blurCloseTimerRef.current = window.setTimeout(closeAfterBlur, blurCloseMaxDelayMs)\n return\n }\n closeAfterBlur()\n }, [blurCloseMaxDelayMs, closeAfterBlur, disabled])\n\n React.useEffect(() => {\n if (!blurClosePendingRef.current) return\n if (loading) return\n clearBlurCloseTimer()\n closeAfterBlur()\n }, [clearBlurCloseTimer, closeAfterBlur, loading])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLInputElement>) => {\n if (disabled) return\n\n if (event.key === 'ArrowDown') {\n event.preventDefault()\n if (!showSuggestions) {\n setShowSuggestions(true)\n setSelectedIndex(0)\n } else {\n setSelectedIndex((prev) => Math.min(prev + 1, filteredSuggestions.length - 1))\n }\n } else if (event.key === 'ArrowUp') {\n event.preventDefault()\n setSelectedIndex((prev) => Math.max(prev - 1, -1))\n } else if (event.key === 'Enter') {\n event.preventDefault()\n if (selectedIndex >= 0 && filteredSuggestions[selectedIndex]) {\n selectValue(filteredSuggestions[selectedIndex].value)\n } else {\n confirmSelection(input)\n }\n } else if (event.key === 'Escape') {\n if (!showSuggestions) return\n event.preventDefault()\n event.stopPropagation()\n setShowSuggestions(false)\n setSelectedIndex(-1)\n }\n },\n [confirmSelection, disabled, filteredSuggestions, input, selectValue, selectedIndex, showSuggestions]\n )\n\n const optionDomId = React.useCallback(\n (index: number) => `${listboxId}-option-${index}`,\n [listboxId],\n )\n\n React.useEffect(() => {\n if (selectedIndex < 0 || !showSuggestions) return\n const activeElement = typeof document !== 'undefined'\n ? document.getElementById(optionDomId(selectedIndex))\n : null\n if (typeof activeElement?.scrollIntoView === 'function') {\n activeElement.scrollIntoView({ block: 'nearest' })\n }\n }, [optionDomId, selectedIndex, showSuggestions])\n\n const showClearButton = clearable && !disabled && (value !== '' || input !== '')\n const listboxVisible = showSuggestions\n && !disabled\n && (loading || filteredSuggestions.length > 0 || (touched && input.trim().length > 0))\n\n return (\n // The suggestion list goes through the DS Popover so it is portaled out of any\n // scrolling ancestor. Rendered in place it was clipped by a Dialog's\n // `overflow-y-auto`, where z-index cannot help. `open` stays fully controlled\n // (no `onOpenChange`) so the blur timer, Escape and selection keep owning\n // dismissal exactly as before.\n <Popover open={listboxVisible}>\n <PopoverAnchor asChild>\n <div className=\"relative w-full\">\n {/* Use raw <input> here instead of the DS Input primitive: ComboboxInput's\n focus / suggestions-popup interplay relies on the trigger being a plain\n input element. The DS wrapper introduces a <div> that desyncs autocomplete\n on this specific surface. Keeps the rest of the form on Input primitive. */}\n <input\n ref={inputRef}\n id={id}\n type=\"text\"\n className={[\n 'w-full h-9 rounded-md border border-input bg-background px-3 text-sm shadow-xs transition-colors outline-none placeholder:text-muted-foreground 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 showClearButton ? 'pr-9' : '',\n ]\n .filter(Boolean)\n .join(' ')}\n value={input}\n placeholder={resolvedPlaceholder}\n autoFocus={autoFocus}\n data-crud-focus-target=\"\"\n disabled={disabled}\n role=\"combobox\"\n aria-expanded={listboxVisible}\n aria-controls={listboxVisible && !loading && filteredSuggestions.length > 0 ? listboxId : undefined}\n // The listbox is portaled out of the input's subtree, so `aria-owns` is what\n // makes it a logical descendant and keeps `aria-activedescendant` below valid.\n aria-owns={listboxVisible && !loading && filteredSuggestions.length > 0 ? listboxId : undefined}\n aria-autocomplete=\"list\"\n aria-describedby={ariaDescribedBy}\n aria-invalid={ariaInvalid}\n aria-required={ariaRequired}\n aria-activedescendant={listboxVisible && selectedIndex >= 0 ? optionDomId(selectedIndex) : undefined}\n onFocus={() => {\n setTouched(true)\n if (suppressOpenOnFocusRef.current) {\n suppressOpenOnFocusRef.current = false\n return\n }\n resetBlurCloseState()\n if (loadSuggestions && availableOptions.length === 0) {\n setLoading(true)\n }\n setShowSuggestions(true)\n }}\n onChange={(event) => {\n setTouched(true)\n userTypedRef.current = true\n setInput(event.target.value)\n setShowSuggestions(true)\n setSelectedIndex(-1)\n }}\n onKeyDown={handleKeyDown}\n onBlur={() => {\n // Delay closing so clicks on the popup can resolve first. If async\n // suggestions are still loading, keep the dropdown open instead of\n // closing before the first payload arrives.\n userTypedRef.current = false\n blurClosePendingRef.current = true\n clearBlurCloseTimer()\n if (loadingRef.current) {\n blurCloseTimerRef.current = window.setTimeout(closeAfterBlur, blurCloseMaxDelayMs)\n return\n }\n blurCloseTimerRef.current = window.setTimeout(attemptBlurClose, blurCloseDelayMs)\n }}\n />\n\n {showClearButton ? (\n <IconButton\n type=\"button\"\n variant=\"ghost\"\n size=\"xs\"\n aria-label={resolvedClearLabel}\n className=\"absolute right-1 top-1/2 -translate-y-1/2\"\n onMouseDown={(event) => event.preventDefault()}\n onClick={handleClear}\n >\n <X className=\"size-3\" />\n </IconButton>\n ) : null}\n </div>\n </PopoverAnchor>\n\n {/* Unmount the content outright rather than leaning on Radix's exit animation:\n a closing-but-still-mounted layer keeps swallowing Escape, which would\n strand the popup's host (see AdvancedFilterPanel for that failure mode). */}\n {listboxVisible ? (\n <PopoverContent\n // Radix hardcodes `role=\"dialog\"` on popover content. This popup is a\n // positioning shell around the listbox below, and a second dialog node\n // would both misdescribe it and break `getByRole('dialog')` for anything\n // that queries while suggestions happen to be open.\n role=\"presentation\"\n // Focus must stay in the input: the blur-close timer and\n // aria-activedescendant model depend on it, and Radix would otherwise\n // move focus into the list on open and back to the trigger on close.\n onOpenAutoFocus={(event) => event.preventDefault()}\n onCloseAutoFocus={(event) => event.preventDefault()}\n // A modal Dialog locks scrolling through `react-remove-scroll`, which\n // cancels document-level `wheel` and `touchmove` outside its own content\n // node. The portaled list is not part of that exemption, so without these\n // a long list inside a dialog cannot be scrolled by wheel or by touch.\n // `overscroll-contain` stops the scroll chaining to the page at the ends.\n onWheel={(event) => event.stopPropagation()}\n onTouchMove={(event) => event.stopPropagation()}\n className=\"w-[var(--radix-popover-trigger-width)] min-w-0 max-h-48 sm:max-h-60 overflow-auto overscroll-contain border-input p-2\"\n >\n {loading && touched ? (\n <div className=\"px-2 py-1.5 text-xs text-muted-foreground\" role=\"status\">{loadingLabel}</div>\n ) : touched && !filteredSuggestions.length ? (\n <div className=\"px-2 py-1.5 text-xs text-muted-foreground\" role=\"status\">{noMatchesLabel}</div>\n ) : (\n <div id={listboxId} role=\"listbox\" className=\"flex flex-col gap-1\">\n {filteredSuggestions.map((option, index) => (\n <Button\n key={option.value}\n id={optionDomId(index)}\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n role=\"option\"\n aria-selected={index === selectedIndex}\n className={[\n 'w-full h-auto justify-start font-normal text-left flex flex-col items-start rounded-lg p-2',\n index === selectedIndex ? 'bg-muted' : '',\n ]\n .filter(Boolean)\n .join(' ')}\n onMouseDown={(event) => event.preventDefault()}\n onClick={() => {\n resetBlurCloseState()\n selectValue(option.value)\n }}\n onMouseEnter={() => setSelectedIndex(index)}\n >\n <span className=\"font-medium text-foreground\">{option.label}</span>\n {option.description ? (\n <span className=\"text-xs text-muted-foreground\">{option.description}</span>\n ) : null}\n </Button>\n ))}\n </div>\n )}\n </PopoverContent>\n ) : null}\n </Popover>\n )\n}\n"],
5
- "mappings": ";AA4aQ,SAKE,KALF;AA1aR,YAAY,WAAW;AACvB,SAAS,SAAS;AAClB,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,SAAS,eAAe,sBAAsB;AAiCvD,SAAS,iBAAiB,OAA0D;AAClF,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MACJ,IAAI,CAAC,WAAW;AACf,QAAI,OAAO,WAAW,UAAU;AAC9B,YAAM,UAAU,OAAO,KAAK;AAC5B,UAAI,CAAC,QAAS,QAAO;AACrB,aAAO,EAAE,OAAO,SAAS,OAAO,QAAQ;AAAA,IAC1C;AACA,UAAM,QAAQ,OAAO,OAAO,UAAU,WAAW,OAAO,MAAM,KAAK,IAAI;AACvE,QAAI,CAAC,MAAO,QAAO;AACnB,WAAO;AAAA,MACL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AAU,MAAM,eAAe;AAAA,UAMlD,SAAS,CAAC,UAAU,MAAM,gBAAgB;AAAA,UAC1C,aAAa,CAAC,UAAU,MAAM,gBAAgB;AAAA,UAC9C,WAAU;AAAA,UAET,qBAAW,UACV,oBAAC,SAAI,WAAU,6CAA4C,MAAK,UAAU,wBAAa,IACrF,WAAW,CAAC,oBAAoB,SAClC,oBAAC,SAAI,WAAU,6CAA4C,MAAK,UAAU,0BAAe,IAEzF,oBAAC,SAAI,IAAI,WAAW,MAAK,WAAU,WAAU,uBAC1C,8BAAoB,IAAI,CAAC,QAAQ,UAChC;AAAA,YAAC;AAAA;AAAA,cAEC,IAAI,YAAY,KAAK;AAAA,cACrB,MAAK;AAAA,cACL,SAAQ;AAAA,cACR,MAAK;AAAA,cACL,MAAK;AAAA,cACL,iBAAe,UAAU;AAAA,cACzB,WAAW;AAAA,gBACT;AAAA,gBACA,UAAU,gBAAgB,aAAa;AAAA,cACzC,EACG,OAAO,OAAO,EACd,KAAK,GAAG;AAAA,cACX,aAAa,CAAC,UAAU,MAAM,eAAe;AAAA,cAC7C,SAAS,MAAM;AACb,oCAAoB;AACpB,4BAAY,OAAO,KAAK;AAAA,cAC1B;AAAA,cACA,cAAc,MAAM,iBAAiB,KAAK;AAAA,cAE1C;AAAA,oCAAC,UAAK,WAAU,+BAA+B,iBAAO,OAAM;AAAA,gBAC3D,OAAO,cACN,oBAAC,UAAK,WAAU,iCAAiC,iBAAO,aAAY,IAClE;AAAA;AAAA;AAAA,YAvBC,OAAO;AAAA,UAwBd,CACD,GACH;AAAA;AAAA,MAEJ,IACE;AAAA,OACN;AAAA;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { 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 { Popover, PopoverAnchor, PopoverContent } from '../../primitives/popover'\n\nexport type ComboboxOption = {\n value: string\n label: string\n description?: string | null\n}\n\nexport type ComboboxInputProps = {\n id?: string\n value: string\n onChange: (next: string) => void\n placeholder?: string\n suggestions?: Array<string | ComboboxOption>\n // Options to hydrate the option map up front (typically the linked entity's\n // display fields, already present in a record-detail payload). Merged with\n // `suggestions` so a pre-selected value renders its label without interaction.\n seedOptions?: ComboboxOption[]\n loadSuggestions?: (query?: string) => Promise<Array<string | ComboboxOption>>\n // Eagerly resolve a pre-selected `value` to a human label when it is not\n // covered by `suggestions`/`seedOptions`/`loadSuggestions` results. Runs once\n // per value, before any user interaction. May be sync or async.\n resolveLabel?: (value: string) => string | Promise<string>\n resolveDescription?: (value: string) => string | null | undefined\n autoFocus?: boolean\n disabled?: boolean\n allowCustomValues?: boolean\n clearable?: boolean\n clearLabel?: string\n 'aria-describedby'?: string\n 'aria-invalid'?: boolean\n 'aria-required'?: boolean\n}\n\nfunction normalizeOptions(input?: Array<string | ComboboxOption>): ComboboxOption[] {\n if (!Array.isArray(input)) return []\n return input\n .map((option) => {\n if (typeof option === 'string') {\n const trimmed = option.trim()\n if (!trimmed) return null\n return { value: trimmed, label: trimmed }\n }\n const value = typeof option.value === 'string' ? option.value.trim() : ''\n if (!value) return null\n return {\n value,\n label: option.label?.trim() || value,\n description: option.description ?? null,\n }\n })\n .filter((option): option is ComboboxOption => !!option)\n}\n\nfunction areOptionsEqual(a: ComboboxOption[], b: ComboboxOption[]): boolean {\n if (a.length !== b.length) return false\n return a.every((option, index) => {\n const next = b[index]\n return option.value === next.value\n && option.label === next.label\n && (option.description ?? null) === (next.description ?? null)\n })\n}\n\nexport function ComboboxInput({\n id,\n value,\n onChange,\n placeholder,\n suggestions,\n seedOptions,\n loadSuggestions,\n resolveLabel,\n resolveDescription,\n autoFocus,\n disabled = false,\n allowCustomValues = true,\n clearable = false,\n clearLabel,\n 'aria-describedby': ariaDescribedBy,\n 'aria-invalid': ariaInvalid,\n 'aria-required': ariaRequired,\n}: ComboboxInputProps) {\n const t = useT()\n const resolvedPlaceholder = placeholder ?? t('ui.inputs.comboboxInput.placeholder', 'Type to search...')\n const loadingLabel = t('ui.inputs.comboboxInput.loading', 'Loading suggestions\u2026')\n const noMatchesLabel = t('ui.inputs.comboboxInput.noMatches', 'No matches found')\n const resolvedClearLabel = clearLabel ?? t('ui.inputs.comboboxInput.clear', 'Clear value')\n const blurCloseDelayMs = 250\n const blurCloseMaxDelayMs = 1000\n const [input, setInput] = React.useState('')\n const [asyncOptions, setAsyncOptions] = React.useState<ComboboxOption[]>([])\n const [resolvedOptions, setResolvedOptions] = React.useState<ComboboxOption[]>([])\n const [loading, setLoading] = React.useState(false)\n const [touched, setTouched] = React.useState(false)\n const [showSuggestions, setShowSuggestions] = React.useState(false)\n const [selectedIndex, setSelectedIndex] = React.useState(-1)\n const listboxId = React.useId()\n const inputRef = React.useRef<HTMLInputElement>(null)\n const loadingRef = React.useRef(false)\n const blurCloseTimerRef = React.useRef<number | null>(null)\n const blurClosePendingRef = React.useRef(false)\n const suppressOpenOnFocusRef = React.useRef(Boolean(autoFocus && !disabled))\n const eagerFallbackLoadedValueRef = React.useRef<string | null>(null)\n // Tracks whether the user actually typed into the field during the current focus\n // session. `touched` cannot serve this purpose because it is set by `onFocus`,\n // which `autoFocus` triggers before the user does anything at all.\n const userTypedRef = React.useRef(false)\n\n const staticOptions = React.useMemo(\n () => normalizeOptions([...(seedOptions ?? []), ...(suggestions ?? [])]),\n [seedOptions, suggestions]\n )\n\n // Single pass over all option sources to build both coverage sets at once.\n // knownLabelValues: values with a genuine label (not a self-mapping placeholder) \u2014\n // used to decide whether eager resolution still needs to run.\n // coveredOptionValues: all values present in any source (even self-mapped).\n const { knownLabelValues, coveredOptionValues } = React.useMemo(() => {\n const known = new Set<string>()\n const covered = new Set<string>()\n for (const opt of [...staticOptions, ...asyncOptions, ...resolvedOptions]) {\n covered.add(opt.value)\n if (opt.label && opt.label !== opt.value) known.add(opt.value)\n }\n return { knownLabelValues: known, coveredOptionValues: covered }\n }, [staticOptions, asyncOptions, resolvedOptions])\n\n const optionMap = React.useMemo(() => {\n const map = new Map<string, ComboboxOption>()\n const register = (option: ComboboxOption) => {\n const existing = map.get(option.value)\n // Prefer an entry that carries a real label over a self-mapping placeholder.\n if (!existing || (existing.label === existing.value && option.label !== option.value)) {\n map.set(option.value, option)\n }\n }\n staticOptions.forEach(register)\n asyncOptions.forEach(register)\n resolvedOptions.forEach(register)\n if (value) {\n const existing = map.get(value)\n if (!existing) {\n map.set(value, {\n value,\n label: value,\n description: resolveDescription?.(value) ?? null,\n })\n }\n }\n return map\n }, [asyncOptions, resolvedOptions, resolveDescription, staticOptions, value])\n\n const availableOptions = React.useMemo(() => {\n return Array.from(optionMap.values())\n }, [optionMap])\n\n React.useEffect(() => {\n loadingRef.current = loading\n }, [loading])\n\n const clearBlurCloseTimer = React.useCallback(() => {\n if (blurCloseTimerRef.current === null) return\n window.clearTimeout(blurCloseTimerRef.current)\n blurCloseTimerRef.current = null\n }, [])\n\n const resetBlurCloseState = React.useCallback(() => {\n blurClosePendingRef.current = false\n clearBlurCloseTimer()\n }, [clearBlurCloseTimer])\n\n React.useEffect(() => resetBlurCloseState, [resetBlurCloseState])\n\n const filteredSuggestions = React.useMemo(() => {\n const query = input.toLowerCase().trim()\n if (!query) return availableOptions\n return availableOptions.filter((option) => {\n const labelMatch = option.label.toLowerCase().includes(query)\n const descMatch = option.description?.toLowerCase().includes(query)\n return labelMatch || Boolean(descMatch)\n })\n }, [availableOptions, input])\n\n React.useEffect(() => {\n if (!loadSuggestions || !touched || disabled) return\n const query = input.trim()\n let cancelled = false\n const handle = window.setTimeout(() => {\n setLoading(true)\n Promise.resolve()\n .then(() => loadSuggestions(query))\n .then((items) => {\n if (!cancelled) {\n const normalized = normalizeOptions(items)\n setAsyncOptions((prev) => areOptionsEqual(prev, normalized) ? prev : normalized)\n }\n })\n .catch(() => {})\n .finally(() => {\n if (!cancelled) setLoading(false)\n })\n }, 200)\n return () => {\n cancelled = true\n window.clearTimeout(handle)\n }\n }, [disabled, input, loadSuggestions, touched])\n\n // Eagerly resolve a pre-selected value to its label without requiring the user\n // to focus the field. Runs once per value when it is not already covered.\n const eagerResolveLabel = typeof resolveLabel === 'function' ? resolveLabel : undefined\n React.useEffect(() => {\n if (!value) return\n let cancelled = false\n const apply = (label?: string | null, description?: string | null) => {\n const clean = typeof label === 'string' ? label.trim() : ''\n if (cancelled || !clean || clean === value) return\n setResolvedOptions((prev) => {\n if (prev.some((option) => option.value === value && option.label === clean)) return prev\n return [...prev.filter((option) => option.value !== value), { value, label: clean, description: description ?? null }]\n })\n }\n if (eagerResolveLabel) {\n if (knownLabelValues.has(value)) return\n Promise.resolve()\n .then(() => eagerResolveLabel(value))\n .then((label) => apply(label, resolveDescription?.(value)))\n .catch(() => {})\n return () => { cancelled = true }\n }\n if (coveredOptionValues.has(value)) return\n if (eagerFallbackLoadedValueRef.current === value) return\n eagerFallbackLoadedValueRef.current = value\n // Fallback: pull the first page of async suggestions so a remount that lost\n // its option cache can still recover the label without user interaction.\n // Note: if the loader is paginated and the value falls outside the first page,\n // the fallback silently fails and the raw value remains visible.\n if (loadSuggestions) {\n setLoading(true)\n Promise.resolve()\n .then(() => loadSuggestions())\n .then((items) => {\n if (cancelled) return\n const normalized = normalizeOptions(items)\n setAsyncOptions((prev) => areOptionsEqual(prev, normalized) ? prev : normalized)\n })\n .catch(() => {})\n .finally(() => { if (!cancelled) setLoading(false) })\n }\n return () => { cancelled = true }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- resolveDescription intentionally excluded:\n // including it would re-run the effect on every render when the prop is an inline function\n }, [value, knownLabelValues, coveredOptionValues, eagerResolveLabel, loadSuggestions])\n\n // Sync input with a value that changed outside the component. A focused field is\n // synced too, because `autoFocus` can focus the control before an async default value\n // arrives and a focus-only guard then leaves the control rendering an empty label for\n // a value the form has already committed. Two conditions still block the sync:\n // - the user is typing, so their query is never clobbered mid-keystroke;\n // - `optionMap` only holds the self-mapping placeholder it synthesises for an\n // uncovered value, which would paint the raw record id over a label the user just\n // picked (`asyncOptions` is replaced on every load, so any follow-up load that\n // misses the picked entry \u2014 a failed request, a debounce race, a composite label\n // the route's `?search=` cannot match \u2014 drops it back to the placeholder).\n React.useEffect(() => {\n const option = optionMap.get(value)\n const hasRealLabel = Boolean(option && option.label !== option.value)\n if (document.activeElement === inputRef.current && (userTypedRef.current || !hasRealLabel)) return\n setInput(option?.label ?? value ?? '')\n }, [value, optionMap])\n\n const selectValue = React.useCallback(\n (nextValue: string) => {\n if (disabled) return\n resetBlurCloseState()\n const trimmed = nextValue.trim()\n onChange(trimmed)\n const option = optionMap.get(trimmed)\n setInput(option?.label ?? trimmed)\n setShowSuggestions(false)\n setSelectedIndex(-1)\n userTypedRef.current = false\n },\n [disabled, onChange, optionMap, resetBlurCloseState]\n )\n\n const findOptionForInput = React.useCallback(\n (raw: string): ComboboxOption | null => {\n const query = raw.trim().toLowerCase()\n if (!query) return null\n for (const option of optionMap.values()) {\n if (option.value === raw.trim()) return option\n if (option.label.toLowerCase() === query) return option\n }\n return null\n },\n [optionMap]\n )\n\n const confirmSelection = React.useCallback(\n (raw: string) => {\n if (disabled) return\n if (clearable && raw.trim() === '') {\n selectValue('')\n return\n }\n const option = findOptionForInput(raw)\n if (option) {\n selectValue(option.value)\n return\n }\n if (!allowCustomValues) {\n // Revert to the current value's label \u2014 but only if we actually know it.\n // Baking the raw value back in while eager resolution is still pending\n // would freeze a placeholder (e.g. a UUID) into the visible input.\n setShowSuggestions(false)\n const currentOption = optionMap.get(value)\n if (currentOption && currentOption.label !== currentOption.value) {\n setInput(currentOption.label)\n } else if (!value) {\n setInput('')\n }\n return\n }\n selectValue(raw)\n },\n [allowCustomValues, clearable, disabled, findOptionForInput, optionMap, selectValue, value]\n )\n\n const handleClear = React.useCallback(() => {\n if (disabled) return\n selectValue('')\n inputRef.current?.focus()\n }, [disabled, selectValue])\n\n const closeAfterBlur = React.useCallback(() => {\n blurCloseTimerRef.current = null\n if (disabled) return\n blurClosePendingRef.current = false\n confirmSelection(input)\n setShowSuggestions(false)\n setSelectedIndex(-1)\n }, [confirmSelection, disabled, input])\n\n const attemptBlurClose = React.useCallback(() => {\n blurCloseTimerRef.current = null\n if (disabled) return\n if (loadingRef.current) {\n blurCloseTimerRef.current = window.setTimeout(closeAfterBlur, blurCloseMaxDelayMs)\n return\n }\n closeAfterBlur()\n }, [blurCloseMaxDelayMs, closeAfterBlur, disabled])\n\n React.useEffect(() => {\n if (!blurClosePendingRef.current) return\n if (loading) return\n clearBlurCloseTimer()\n closeAfterBlur()\n }, [clearBlurCloseTimer, closeAfterBlur, loading])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLInputElement>) => {\n if (disabled) return\n\n if (event.key === 'ArrowDown') {\n event.preventDefault()\n if (!showSuggestions) {\n setShowSuggestions(true)\n setSelectedIndex(0)\n } else {\n setSelectedIndex((prev) => Math.min(prev + 1, filteredSuggestions.length - 1))\n }\n } else if (event.key === 'ArrowUp') {\n event.preventDefault()\n setSelectedIndex((prev) => Math.max(prev - 1, -1))\n } else if (event.key === 'Enter') {\n event.preventDefault()\n if (selectedIndex >= 0 && filteredSuggestions[selectedIndex]) {\n selectValue(filteredSuggestions[selectedIndex].value)\n } else {\n confirmSelection(input)\n }\n } else if (event.key === 'Escape') {\n if (!showSuggestions) return\n event.preventDefault()\n event.stopPropagation()\n setShowSuggestions(false)\n setSelectedIndex(-1)\n }\n },\n [confirmSelection, disabled, filteredSuggestions, input, selectValue, selectedIndex, showSuggestions]\n )\n\n const optionDomId = React.useCallback(\n (index: number) => `${listboxId}-option-${index}`,\n [listboxId],\n )\n\n React.useEffect(() => {\n if (selectedIndex < 0 || !showSuggestions) return\n const activeElement = typeof document !== 'undefined'\n ? document.getElementById(optionDomId(selectedIndex))\n : null\n if (typeof activeElement?.scrollIntoView === 'function') {\n activeElement.scrollIntoView({ block: 'nearest' })\n }\n }, [optionDomId, selectedIndex, showSuggestions])\n\n const showClearButton = clearable && !disabled && (value !== '' || input !== '')\n const listboxVisible = showSuggestions\n && !disabled\n && (loading || filteredSuggestions.length > 0 || (touched && input.trim().length > 0))\n\n return (\n // The suggestion list goes through the DS Popover so it is portaled out of any\n // scrolling ancestor. Rendered in place it was clipped by a Dialog's\n // `overflow-y-auto`, where z-index cannot help. `open` stays fully controlled\n // (no `onOpenChange`) so the blur timer, Escape and selection keep owning\n // dismissal exactly as before.\n <Popover open={listboxVisible}>\n <PopoverAnchor asChild>\n <div className=\"relative w-full\">\n {/* Use raw <input> here instead of the DS Input primitive: ComboboxInput's\n focus / suggestions-popup interplay relies on the trigger being a plain\n input element. The DS wrapper introduces a <div> that desyncs autocomplete\n on this specific surface. Keeps the rest of the form on Input primitive. */}\n <input\n ref={inputRef}\n id={id}\n type=\"text\"\n className={[\n 'w-full h-9 rounded-md border border-input bg-background px-3 text-sm shadow-xs transition-colors outline-none placeholder:text-muted-foreground 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 showClearButton ? 'pr-9' : '',\n ]\n .filter(Boolean)\n .join(' ')}\n value={input}\n placeholder={resolvedPlaceholder}\n autoFocus={autoFocus}\n data-crud-focus-target=\"\"\n disabled={disabled}\n role=\"combobox\"\n aria-expanded={listboxVisible}\n aria-controls={listboxVisible && !loading && filteredSuggestions.length > 0 ? listboxId : undefined}\n // The listbox is portaled out of the input's subtree, so `aria-owns` is what\n // makes it a logical descendant and keeps `aria-activedescendant` below valid.\n aria-owns={listboxVisible && !loading && filteredSuggestions.length > 0 ? listboxId : undefined}\n aria-autocomplete=\"list\"\n aria-describedby={ariaDescribedBy}\n aria-invalid={ariaInvalid}\n aria-required={ariaRequired}\n aria-activedescendant={listboxVisible && selectedIndex >= 0 ? optionDomId(selectedIndex) : undefined}\n onFocus={() => {\n setTouched(true)\n if (suppressOpenOnFocusRef.current) {\n suppressOpenOnFocusRef.current = false\n return\n }\n resetBlurCloseState()\n if (loadSuggestions && availableOptions.length === 0) {\n setLoading(true)\n }\n setShowSuggestions(true)\n }}\n onChange={(event) => {\n setTouched(true)\n userTypedRef.current = true\n setInput(event.target.value)\n setShowSuggestions(true)\n setSelectedIndex(-1)\n }}\n onKeyDown={handleKeyDown}\n onBlur={() => {\n // Delay closing so clicks on the popup can resolve first. If async\n // suggestions are still loading, keep the dropdown open instead of\n // closing before the first payload arrives.\n userTypedRef.current = false\n blurClosePendingRef.current = true\n clearBlurCloseTimer()\n if (loadingRef.current) {\n blurCloseTimerRef.current = window.setTimeout(closeAfterBlur, blurCloseMaxDelayMs)\n return\n }\n blurCloseTimerRef.current = window.setTimeout(attemptBlurClose, blurCloseDelayMs)\n }}\n />\n\n {showClearButton ? (\n <IconButton\n type=\"button\"\n variant=\"ghost\"\n size=\"xs\"\n aria-label={resolvedClearLabel}\n className=\"absolute right-1 top-1/2 -translate-y-1/2\"\n onMouseDown={(event) => event.preventDefault()}\n onClick={handleClear}\n >\n <X className=\"size-3\" />\n </IconButton>\n ) : null}\n </div>\n </PopoverAnchor>\n\n {/* Unmount the content outright rather than leaning on Radix's exit animation:\n a closing-but-still-mounted layer keeps swallowing Escape, which would\n strand the popup's host (see AdvancedFilterPanel for that failure mode). */}\n {listboxVisible ? (\n <PopoverContent\n // Radix hardcodes `role=\"dialog\"` on popover content. This popup is a\n // positioning shell around the listbox below, and a second dialog node\n // would both misdescribe it and break `getByRole('dialog')` for anything\n // that queries while suggestions happen to be open.\n role=\"presentation\"\n // Focus must stay in the input: the blur-close timer and\n // aria-activedescendant model depend on it, and Radix would otherwise\n // move focus into the list on open and back to the trigger on close.\n onOpenAutoFocus={(event) => event.preventDefault()}\n onCloseAutoFocus={(event) => event.preventDefault()}\n // A modal Dialog locks scrolling through `react-remove-scroll`, which\n // cancels document-level `wheel` and `touchmove` outside its own content\n // node. The portaled list is not part of that exemption, so without these\n // a long list inside a dialog cannot be scrolled by wheel or by touch.\n // `overscroll-contain` stops the scroll chaining to the page at the ends.\n onWheel={(event) => event.stopPropagation()}\n onTouchMove={(event) => event.stopPropagation()}\n className=\"w-[var(--radix-popover-trigger-width)] min-w-0 max-h-48 sm:max-h-60 overflow-auto overscroll-contain border-input p-2\"\n >\n {loading && touched ? (\n <div className=\"px-2 py-1.5 text-xs text-muted-foreground\" role=\"status\">{loadingLabel}</div>\n ) : touched && !filteredSuggestions.length ? (\n <div className=\"px-2 py-1.5 text-xs text-muted-foreground\" role=\"status\">{noMatchesLabel}</div>\n ) : (\n <div id={listboxId} role=\"listbox\" className=\"flex flex-col gap-1\">\n {filteredSuggestions.map((option, index) => (\n <Button\n key={option.value}\n id={optionDomId(index)}\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n role=\"option\"\n aria-selected={index === selectedIndex}\n className={[\n 'w-full h-auto justify-start font-normal text-left flex flex-col items-start rounded-lg p-2',\n index === selectedIndex ? 'bg-muted' : '',\n ]\n .filter(Boolean)\n .join(' ')}\n onMouseDown={(event) => event.preventDefault()}\n onClick={() => {\n resetBlurCloseState()\n selectValue(option.value)\n }}\n onMouseEnter={() => setSelectedIndex(index)}\n >\n <span className=\"font-medium text-foreground\">{option.label}</span>\n {option.description ? (\n <span className=\"text-xs text-muted-foreground\">{option.description}</span>\n ) : null}\n </Button>\n ))}\n </div>\n )}\n </PopoverContent>\n ) : null}\n </Popover>\n )\n}\n"],
5
+ "mappings": ";AA8aQ,SAKE,KALF;AA5aR,YAAY,WAAW;AACvB,SAAS,SAAS;AAClB,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,SAAS,eAAe,sBAAsB;AAkCvD,SAAS,iBAAiB,OAA0D;AAClF,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MACJ,IAAI,CAAC,WAAW;AACf,QAAI,OAAO,WAAW,UAAU;AAC9B,YAAM,UAAU,OAAO,KAAK;AAC5B,UAAI,CAAC,QAAS,QAAO;AACrB,aAAO,EAAE,OAAO,SAAS,OAAO,QAAQ;AAAA,I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3
- "version": "0.10.1-develop.8159.1.71854b31a8",
3
+ "version": "0.10.1-develop.8164.1.f12a3857ee",
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.10.1-develop.8159.1.71854b31a8",
159
+ "@open-mercato/shared": "0.10.1-develop.8164.1.f12a3857ee",
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.10.1-develop.8159.1.71854b31a8",
166
+ "@open-mercato/shared": "0.10.1-develop.8164.1.f12a3857ee",
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",
@@ -229,6 +229,14 @@ function FlashMessagesInner() {
229
229
  // isPrimaryHost below), silently swallowing the toast. Leaving the params
230
230
  // in the URL for a non-primary host means the eventually-primary host's
231
231
  // own effect re-runs and consumes them once isPrimaryHost flips true.
232
+ //
233
+ // Delivering the message through `flash()` — instead of this host's own
234
+ // local `showFlash` — broadcasts it to every currently listening host, the
235
+ // same way a programmatic flash already reaches all of them. That is what
236
+ // lets a non-primary host that later takes over (its own primary host
237
+ // unmounted while the toast was still visible) already be holding the
238
+ // message and its own still-ticking dismiss timer, instead of finding the
239
+ // URL params already stripped and rendering nothing.
232
240
  React.useEffect(() => {
233
241
  if (typeof window === 'undefined') return
234
242
  if (!isPrimaryHost) return
@@ -243,10 +251,10 @@ function FlashMessagesInner() {
243
251
  url.searchParams.delete('type')
244
252
  window.history.replaceState({}, '', url.toString())
245
253
  if (trusted) {
246
- showFlash(message, type)
254
+ flash(message, type)
247
255
  }
248
256
  }
249
- }, [locationKey, showFlash, isPrimaryHost])
257
+ }, [locationKey, isPrimaryHost])
250
258
 
251
259
  // Listen for programmatic flash events
252
260
  React.useEffect(() => {
@@ -263,6 +263,47 @@ describe('FlashMessages', () => {
263
263
  jest.useFakeTimers()
264
264
  })
265
265
 
266
+ /**
267
+ * Regression for #8701: unlike a programmatic flash, a URL-sourced one used
268
+ * to be delivered only to the primary host's own local state. When that
269
+ * host unmounted mid-display, the survivor took over the primary role but
270
+ * had never received the message (and the URL params were already
271
+ * stripped), so the still-visible toast vanished instead of handing over.
272
+ */
273
+ it('hands a displayed URL flash over when the primary host unmounts, preserving its original expiry', () => {
274
+ window.history.replaceState({}, '', 'http://localhost/backend/checkout/pay-links?flash=Saved&type=success')
275
+
276
+ function Hosts({ withPrimary }: { withPrimary: boolean }) {
277
+ return (
278
+ <>
279
+ {withPrimary ? <FlashMessages /> : null}
280
+ <FlashMessages />
281
+ </>
282
+ )
283
+ }
284
+
285
+ const { rerender } = renderWithProviders(<Hosts withPrimary />)
286
+
287
+ expect(screen.getAllByText('Saved')).toHaveLength(1)
288
+ expect(window.location.search).toBe('')
289
+
290
+ act(() => {
291
+ jest.advanceTimersByTime(1500)
292
+ })
293
+
294
+ act(() => {
295
+ rerender(<Hosts withPrimary={false} />)
296
+ })
297
+
298
+ expect(screen.getAllByText('Saved')).toHaveLength(1)
299
+
300
+ act(() => {
301
+ jest.advanceTimersByTime(1500)
302
+ })
303
+
304
+ expect(screen.queryByText('Saved')).not.toBeInTheDocument()
305
+ })
306
+
266
307
  it('auto-dismisses programmatic flashes', () => {
267
308
  renderWithProviders(<FlashMessages />)
268
309
 
@@ -176,11 +176,20 @@ export function AddressEditor<C = unknown>({
176
176
  isPrimary: value.isPrimary ?? false,
177
177
  }
178
178
 
179
+ // Tracks the latest merged draft outside of props so two field edits dispatched in the same
180
+ // render batch (e.g. a Radix Select commit immediately followed by typing into another field)
181
+ // always merge onto each other instead of two independent `{ ...current, [key]: value }` snapshots
182
+ // racing for `onChange` — the caller only keeps the last one, silently dropping the other's edit.
183
+ const currentRef = React.useRef(current)
184
+ currentRef.current = current
185
+
179
186
  const update = React.useCallback(
180
187
  (key: keyof AddressEditorDraft, nextValue: string | boolean) => {
181
- onChange({ ...current, [key]: nextValue })
188
+ const next = { ...currentRef.current, [key]: nextValue }
189
+ currentRef.current = next
190
+ onChange(next)
182
191
  },
183
- [current, onChange],
192
+ [onChange],
184
193
  )
185
194
 
186
195
  const filteredCountryOptions = React.useMemo(() => {
@@ -432,6 +432,13 @@ export function AddressTiles<C = unknown>({
432
432
  key={key}
433
433
  className="rounded-lg border-2 border-dashed border-muted-foreground/50 bg-muted/30 p-4 text-sm"
434
434
  onKeyDown={(event) => {
435
+ if (event.defaultPrevented) return
436
+ if (event.key === 'Escape') {
437
+ if (disableActions) return
438
+ event.preventDefault()
439
+ handleCancel()
440
+ return
441
+ }
435
442
  if (!(event.metaKey || event.ctrlKey)) return
436
443
  if (event.key !== 'Enter') return
437
444
  event.preventDefault()
@@ -189,6 +189,7 @@ function AddressesSectionImpl<C = unknown>({
189
189
  return [newAddress, ...existing]
190
190
  })
191
191
  flash(label('success', 'Address saved.'), 'success')
192
+ await loadAddresses()
192
193
  } catch (err) {
193
194
  const message =
194
195
  err instanceof Error && err.message ? err.message : label('error', 'Failed to save address.')
@@ -202,7 +203,7 @@ function AddressesSectionImpl<C = unknown>({
202
203
  popLoading()
203
204
  }
204
205
  },
205
- [dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading],
206
+ [dataAdapter, dataContext, label, loadAddresses, normalizedEntityId, popLoading, pushLoading],
206
207
  )
207
208
 
208
209
  const handleUpdate = React.useCallback(
@@ -240,10 +241,12 @@ function AddressesSectionImpl<C = unknown>({
240
241
  })
241
242
  })
242
243
  flash(label('success', 'Address saved.'), 'success')
244
+ await loadAddresses()
243
245
  } catch (err) {
244
- surfaceRecordConflict(err, t)
245
- const message =
246
- err instanceof Error && err.message ? err.message : label('error', 'Failed to save address.')
246
+ const isConflict = surfaceRecordConflict(err, t)
247
+ const message = isConflict
248
+ ? t('ui.forms.flash.recordModified')
249
+ : err instanceof Error && err.message ? err.message : label('error', 'Failed to save address.')
247
250
  const error = new Error(message) as Error & { details?: unknown }
248
251
  if (err && typeof err === 'object' && (err as { details?: unknown }).details) {
249
252
  error.details = (err as { details?: unknown }).details
@@ -254,7 +257,7 @@ function AddressesSectionImpl<C = unknown>({
254
257
  popLoading()
255
258
  }
256
259
  },
257
- [addresses, dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading, t],
260
+ [addresses, dataAdapter, dataContext, label, loadAddresses, normalizedEntityId, popLoading, pushLoading, t],
258
261
  )
259
262
 
260
263
  const handleDelete = React.useCallback(
@@ -272,7 +275,10 @@ function AddressesSectionImpl<C = unknown>({
272
275
  } catch (err) {
273
276
  const message =
274
277
  err instanceof Error && err.message ? err.message : label('error', 'Failed to delete address.')
275
- if (!surfaceRecordConflict(err, t)) flash(message, 'error')
278
+ if (surfaceRecordConflict(err, t)) {
279
+ throw new Error(t('ui.forms.flash.recordModified'))
280
+ }
281
+ flash(message, 'error')
276
282
  throw err
277
283
  } finally {
278
284
  setIsSubmitting(false)
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ // Regression for #8080: TC-CRM-006 intermittently saved a company address with
6
+ // `addressLine1` empty even though the test had just typed into it. The CI trace showed
7
+ // every OTHER field correctly filled (label, type, city, region, postal, primary) while
8
+ // `addressLine1` — edited between the type select and the city fill — was blank and
9
+ // `aria-invalid`, which blocks `AddressTiles`'s client-side `validate()` and hangs the
10
+ // Save click forever (the observed 20s timeout, with no request ever sent).
11
+ //
12
+ // `AddressEditor.update()` builds the next draft from a `current` object derived from the
13
+ // `value` prop at render time. If the host (`AddressTiles`) has not yet re-rendered with an
14
+ // earlier edit's result — e.g. two field changes land in the same render batch — a second
15
+ // `update()` call used the SAME stale `current`, so its `onChange` call silently dropped the
16
+ // first edit when the host replaced `draft` wholesale. This reproduces that scenario directly
17
+ // (fire two field edits without an intervening re-render) rather than relying on Radix Select's
18
+ // exact async timing, which is incidental to the underlying race.
19
+
20
+ import * as React from 'react'
21
+ import { fireEvent, screen } from '@testing-library/react'
22
+ import { renderWithProviders } from '@open-mercato/shared/lib/testing/renderWithProviders'
23
+ import { AddressEditor, type AddressEditorDraft } from '../AddressEditor'
24
+
25
+ jest.mock('next/navigation', () => ({
26
+ usePathname: () => '/backend/customers/companies/1',
27
+ useSearchParams: () => new URLSearchParams(),
28
+ }))
29
+
30
+ const t = (_key: string, fallback?: string) => fallback ?? ''
31
+
32
+ const emptyDraft: AddressEditorDraft = {
33
+ name: '',
34
+ purpose: '',
35
+ companyName: '',
36
+ addressLine1: '',
37
+ addressLine2: '',
38
+ buildingNumber: '',
39
+ flatNumber: '',
40
+ city: '',
41
+ region: '',
42
+ postalCode: '',
43
+ country: '',
44
+ isPrimary: false,
45
+ }
46
+
47
+ describe('AddressEditor — field edits in the same render batch do not clobber each other', () => {
48
+ it('keeps an earlier edit when a later edit fires before the host re-renders with it', () => {
49
+ const calls: AddressEditorDraft[] = []
50
+ renderWithProviders(
51
+ <AddressEditor
52
+ value={emptyDraft}
53
+ onChange={(next) => calls.push(next)}
54
+ format="line_first"
55
+ t={t}
56
+ />,
57
+ )
58
+
59
+ // Note: the host never re-renders `value` between these two edits — this is the exact
60
+ // condition under which the pre-fix `update()` recomputed `next` from the SAME stale
61
+ // `current` for both calls.
62
+ fireEvent.change(screen.getByPlaceholderText('Label'), { target: { value: 'HQ' } })
63
+ fireEvent.change(screen.getByPlaceholderText('Address line 1'), {
64
+ target: { value: '100 Main Street' },
65
+ })
66
+
67
+ expect(calls).toHaveLength(2)
68
+ const last = calls[calls.length - 1]
69
+ expect(last.addressLine1).toBe('100 Main Street')
70
+ expect(last.name).toBe('HQ')
71
+ })
72
+ })
@@ -0,0 +1,62 @@
1
+ import * as React from 'react'
2
+ import { fireEvent, screen, waitFor } from '@testing-library/react'
3
+ import { renderWithProviders } from '@open-mercato/shared/lib/testing/renderWithProviders'
4
+ import { AddressTiles } from '../AddressTiles'
5
+ import type { AddressEditorDraft } from '../AddressEditor'
6
+
7
+ jest.mock('@open-mercato/ui/backend/detail', () => ({
8
+ TabEmptyState: ({ action }: { action: { label: string; onClick: () => void } }) => (
9
+ <button onClick={action.onClick}>{action.label}</button>
10
+ ),
11
+ }))
12
+
13
+ jest.mock('../AddressEditor', () => ({
14
+ __esModule: true,
15
+ default: ({ value, onChange }: { value: AddressEditorDraft; onChange: (next: AddressEditorDraft) => void }) => (
16
+ <>
17
+ <input aria-label="Label" value={value.name} onChange={(event) => onChange({ ...value, name: event.target.value })} />
18
+ <input aria-label="Street" value={value.addressLine1} onChange={(event) => onChange({ ...value, addressLine1: event.target.value })} />
19
+ <input aria-label="Nested selector" onKeyDown={(event) => event.preventDefault()} />
20
+ </>
21
+ ),
22
+ }))
23
+
24
+ function renderTiles() {
25
+ const onCreate = jest.fn(async () => undefined)
26
+ renderWithProviders(
27
+ <AddressTiles
28
+ addresses={[]}
29
+ onCreate={onCreate}
30
+ t={(_key, fallback) => fallback ?? ''}
31
+ emptyLabel="No addresses"
32
+ />,
33
+ )
34
+ fireEvent.click(screen.getByRole('button', { name: 'Add address' }))
35
+ return onCreate
36
+ }
37
+
38
+ describe('AddressTiles keyboard actions', () => {
39
+ it('cancels and discards an unsaved draft with Escape', () => {
40
+ const onCreate = renderTiles()
41
+ fireEvent.change(screen.getByRole('textbox', { name: 'Label' }), { target: { value: 'Unsaved' } })
42
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Label' }), { key: 'Escape' })
43
+ expect(screen.queryByRole('textbox', { name: 'Label' })).not.toBeInTheDocument()
44
+ expect(onCreate).not.toHaveBeenCalled()
45
+ fireEvent.click(screen.getByRole('button', { name: 'Add address' }))
46
+ expect(screen.getByRole('textbox', { name: 'Label' })).toHaveValue('')
47
+ })
48
+
49
+ it('keeps the form open when a nested layer handled Escape', () => {
50
+ renderTiles()
51
+ fireEvent.change(screen.getByRole('textbox', { name: 'Label' }), { target: { value: 'Keep draft' } })
52
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Nested selector' }), { key: 'Escape' })
53
+ expect(screen.getByRole('textbox', { name: 'Label' })).toHaveValue('Keep draft')
54
+ })
55
+
56
+ it('still submits a valid draft with Ctrl+Enter', async () => {
57
+ const onCreate = renderTiles()
58
+ fireEvent.change(screen.getByRole('textbox', { name: 'Street' }), { target: { value: '1 Main Street' } })
59
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Street' }), { key: 'Enter', ctrlKey: true })
60
+ await waitFor(() => expect(onCreate).toHaveBeenCalledWith(expect.objectContaining({ addressLine1: '1 Main Street' })))
61
+ })
62
+ })