import { Head, router } from '@inertiajs/react'; import { CircleCheckIcon, PlusIcon, RotateCcwIcon, ShirtIcon, SlidersHorizontalIcon, TrashIcon, UploadIcon, XIcon, } from 'lucide-react'; import { useState } from 'react'; import type { SavedView } from '@/components/saved-views'; import { SearchInput } from '@/components/search-input'; import { BulkActionBar, BulkSetMenu } from '@/components/table/bulk-action-bar'; import { useColumnChoice } from '@/components/table/column-menu'; import { ConfirmDialog } from '@/components/table/confirm-dialog'; import { DataTable, RowIdentity, TableEmptyState, } from '@/components/table/data-table'; import { FilterChip } from '@/components/table/filter-chip'; import { useFilterPanel } from '@/components/table/filter-toggle'; import { ImportDialog } from '@/components/table/import-dialog'; import { RealtimeBanner } from '@/components/table/realtime-banner'; import { RowActions } from '@/components/table/row-actions'; import { SelectAllBanner } from '@/components/table/select-all-banner'; import { StatusTabs } from '@/components/table/status-tabs'; import { OverflowColumnsMenu, OverflowExportMenu, OverflowItem, OverflowViewsMenu, TableOverflow, } from '@/components/table/table-overflow'; import { TablePagination } from '@/components/table-pagination'; import { Button } from '@/components/ui/button'; import { DropdownMenuSeparator } from '@/components/ui/dropdown-menu'; import { useBulkActions } from '@/hooks/use-bulk-actions'; import { useChangedRows } from '@/hooks/use-changed-rows'; import { useListQuery } from '@/hooks/use-list-query'; import { useModuleSignal } from '@/hooks/use-module-signal'; import { useNavigating } from '@/hooks/use-navigating'; import { useRowSelection } from '@/hooks/use-row-selection'; import { useLiveUpdates } from '@/hooks/use-ui-preferences'; import { enumLabel } from '@/lib/format'; import { toQuery } from '@/lib/query'; import { moduleLabel, t } from '@/lib/ui-text'; import { index as routeIndex, show, destroy, exportMethod as exportRoute, exportExcel, importMethod as importRoute, importPreview as importPreviewRoute, importTemplate as importTemplateRoute, bulkDestroy, bulkStatus, restore as restoreRoute, forceDelete as forceDeleteRoute, bulkRestore as bulkRestoreRoute, bulkForceDelete as bulkForceDeleteRoute, } from '@/routes/product'; import type { Paginated } from '@/types'; import { PRODUCT_COLUMNS, REVEAL_CLASS, SECONDARY_COLUMNS } from './columns'; import { ProductFilterChips, ProductFilterPanel } from './filters'; // One statement, not two. Split across separate imports from the same path, // eslint orders them by BINDING NAME — and one of those names carries the model // name, so where the type import lands depends on what the module is called. // eslint re-splits this line, but positionally, which is name-independent. import { ProductFormModal } from './form-modal'; import type { FormTarget } from './form-modal'; import type { ProductRow, Filters, TagsOption } from './types'; type Props = { items: Paginated; /** * Rows matching the current filters — the same number `items.total` * already carries. Sent as its own prop so this page reads the same way * a --pagination=cursor module does, whose paginator carries no total. */ total: number; filters: Filters; /** Realtime channel for this viewer, decided server-side. Null = feature off. */ realtimeChannel: string | null; savedViews: SavedView[]; /** What this viewer may do here, decided by the module's policy on the server. */ abilities: { export: boolean; create: boolean; import: boolean; update: boolean; updateRestricted: boolean; delete: boolean; restore: boolean; forceDelete: boolean; }; statusOptions: string[]; tagsOptions: TagsOption[]; fkOptionsUrl: string; stats: { total: number; draft: number; active: number; archived: number }; }; export default function ProductIndex({ items, total, filters, realtimeChannel, savedViews, abilities, statusOptions, tagsOptions, fkOptionsUrl, stats, }: Props) { // This module's name, in the app's language — the `:label` the chrome // strings carry. The schema's label is the fallback, so a module nobody has // added to the dictionary still reads correctly in the project's language. const label = moduleLabel('product', 'Product'); const labels = moduleLabel('product', 'Products', true); const [itemToDelete, setItemToDelete] = useState(null); const [itemToForceDelete, setItemToForceDelete] = useState(null); const [forceDeleting, setForceDeleting] = useState(false); const [deleting, setDeleting] = useState(false); const [showBulkDelete, setShowBulkDelete] = useState(false); const [showBulkRestore, setShowBulkRestore] = useState(false); const [showBulkForceDelete, setShowBulkForceDelete] = useState(false); // The create/edit form, as a dialog over this list. Null while closed, so // none of its controls exist in the tree until someone asks for them. // A cross-module link can open this page straight into a create form: // `?new=1`, plus any foreign key it wants pre-selected. Read once, in the // initialiser, because it is a starting state and not something that should // reopen on every render. const [formTarget, setFormTarget] = useState(() => { const params = new URLSearchParams(window.location.search); if (params.get('new') !== '1') { return null; } const categoryId = params.get('category_id'); return { mode: 'create' as const, prefill: { ...(categoryId ? { category_id: Number(categoryId) } : {}), }, }; }); const [importing, setImporting] = useState(false); const filterPanel = useFilterPanel('product'); const list = useListQuery(routeIndex.url(), filters); const navigating = useNavigating(); // The reader's own column preferences, on top of the module's defaults. // SECONDARY_COLUMNS is what the schema says to hide; this is what this // person said about it, and only where they disagreed. const columnChoice = useColumnChoice('product', SECONDARY_COLUMNS); // Every column that may be switched off. A `key: null` column is the one // carrying the link to the record, so it is not on offer. const toggleableColumns = PRODUCT_COLUMNS.filter( (col) => col.key !== null, ).map((col) => ({ key: col.key as string, label: col.label })); // One list drives the header, the body and the loading placeholder, so they // can never fall out of step. A column with `key: null` is always shown. const visibleColumns = PRODUCT_COLUMNS.filter( (col) => col.key === null || columnChoice.isVisible(col.key), ); // A column the reader asked for by name ignores its breakpoint — see // `isPinned`. Everything else still appears when the card is wide enough. const revealClass = (col: (typeof PRODUCT_COLUMNS)[number]): string => col.reveal && !(col.key !== null && columnChoice.isPinned(col.key)) ? REVEAL_CLASS[col.reveal] : ''; const canEdit = abilities.update; const canDelete = abilities.delete; const canCreate = abilities.create; const canBulk = canEdit || canDelete; const canEditRestricted = abilities.updateRestricted; // Who may open the trash and act in it, as the module's policy says. const canRestore = abilities.restore; const canForceDelete = abilities.forceDelete; const canUseTrash = canRestore || canForceDelete; const isTrash = filters.trash === 'only'; const pageIds = items.data.map((item) => item.id); const rowSelection = useRowSelection({ pageIds, total, signature: `${items.current_page}|${filters.search}|${filters.trash}|${filters.category}|${filters.status}|${filters.is_featured}|${filters.publishedByRef}|${filters.price_min}|${filters.price_max}|${filters.tags}|${filters.sort}|${filters.direction}|${filters.per_page}`, }); const { selectAllMatching, clear: clearSelection, count: bulkCount, } = rowSelection; // Rows that differ from the previous render — computed here, not sent by // the server. See use-changed-rows.ts. const changedRows = useChangedRows(items.data); // Refreshes itself when someone else changes this module — unless doing so // would disturb something the reader is in the middle of. `blocked` is the // whole safety argument: a bulk selection being assembled, or an open // dialog, means the banner appears and the reader decides instead. const { liveUpdates } = useLiveUpdates(); const realtime = useModuleSignal(realtimeChannel, { enabled: liveUpdates === 'on', blocked: bulkCount > 0 || showBulkDelete || itemToDelete !== null, }); const activeFilterParams = { search: filters.search, trash: filters.trash, category: filters.category, status: filters.status, is_featured: filters.is_featured, publishedByRef: filters.publishedByRef, price_min: filters.price_min, price_max: filters.price_max, tags: filters.tags, }; const filterProps = { filters, onChange: list.navigate, tagsOptions }; // CSV/Excel export honours the active filters + current sort. Built through // the same converter the page navigates with, so a download can never be // filtered differently from the table it was started from. const exportQuery = { query: toQuery({ ...activeFilterParams, sort: filters.sort, direction: filters.direction, }), }; // What a bulk action applies to: the rows ticked, or — once the reader // has asked for it — every row the filters match, named by the filters. const bulk = useBulkActions( () => selectAllMatching ? { all: true, ...activeFilterParams } : { ids: [...rowSelection.selected] }, clearSelection, ); // Whether anything narrows the list. The trash is a different list, not a // narrower one, so it has its own marker rather than a filter chip. const hasActiveFilters = Object.entries(activeFilterParams).some( ([key, value]) => key !== 'trash' && value !== '', ); /** * How many filters the collapsed panel is hiding the controls for. * * Counted off `activeFilterParams` rather than from a second list of * filter names: the panel's contents are generated, and a hand-kept * list beside them would drift the first time a column gained or lost * a filter — a badge that undercounts is worse than no badge. * * Search and status are excluded because neither collapses: one has * its own box and the other its own tabs, both always on screen. */ const activeFilterCount = Object.entries(activeFilterParams).filter( ([key, value]) => value !== '' && key !== 'search' && key !== 'status', ).length; function confirmDelete() { if (!itemToDelete) { return; } router.delete(destroy.url(itemToDelete.id), { onStart: () => setDeleting(true), onFinish: () => { setDeleting(false); setItemToDelete(null); }, }); } function restoreRow(id: number) { router.patch(restoreRoute.url(id), {}, { preserveScroll: true }); } function confirmForceDelete() { if (!itemToForceDelete) { return; } router.delete(forceDeleteRoute.url(itemToForceDelete.id), { onStart: () => setForceDeleting(true), onFinish: () => { setForceDeleting(false); setItemToForceDelete(null); }, }); } return ( <> {/* One screen: the table card takes whatever the header and the toolbar leave, so the scrollbars belong to the card and the window keeps still. The height is stated because the shell above only sets a floor (`min-h-svh`); `svh` because the smaller of a phone's two viewports is the one that must not clip; and `min-h-0` at every step down to the scrollport, because a flex child will not shrink below its content unless told. `py-4` rather than `p-6`: every pixel above the title is one the table does not get. */}
{/* The header states what the page is; every control that acts on the list sits on the toolbar below, and the total is in the pagination footer, so neither appears twice. */}

{labels}

{/* Plural: the page is the whole list. */} {t('subtitle', { label: labels })}

{/* Toolbar — search, status tabs, and everything else pushed right. */}
({ key: s, label: enumLabel(s), })), ]} onChange={(status) => list.navigate({ status })} />
{abilities.import && ( setImporting(true)} > {t('import')} )} {abilities.export && ( )} {t('filters')} {canUseTrash && ( list.navigate({ trash: isTrash ? '' : 'only', }) } > {t('trash')} )} {canCreate && ( )}
{filterPanel.open && ( )} {/* The trash marker. Rows in this view are deleted, and a listing that looks like the live one is how the wrong record gets destroyed permanently. A chip, like every other narrowing on this screen; closing it goes back to the live list. */} {isTrash && (
list.navigate({ trash: '' })} />
)} {hasActiveFilters && ( )} {/* The table card claims the height the page has left and keeps every scrollbar inside itself. `@container` so the columns hide and show against the card's width rather than the window's — see REVEAL_CLASS. */}
items.data.length } selectAllMatching={selectAllMatching} pageCount={pageIds.length} total={total} label={label} onSelectAll={rowSelection.selectAllMatchingRows} onClear={clearSelection} /> String(item.name), cell: (item) => ( ), }} selection={canBulk ? rowSelection : undefined} changedRows={changedRows} actions={(item) => ( setFormTarget({ mode: 'edit', id: item.id, }) } onDuplicate={() => setFormTarget({ mode: 'duplicate', id: item.id, }) } onDelete={() => setItemToDelete(item)} onRestore={() => restoreRow(item.id)} onForceDelete={() => setItemToForceDelete(item) } /> )} empty={ // `labels` (plural) on the heading, `label` // (singular) on the hint: the two sentences // need different numbers in English. An empty // trash is its own state — nothing is hidden, // so there is no filter to point at. {!isTrash && stats.total === 0 && canCreate && ( )} {hasActiveFilters && ( )} } /> {/* Inside the card but outside the scrollport, so the pager stays pinned where the rows run out. */}
{canBulk && bulkCount > 0 && ( {!isTrash && ( <> {canEdit && ( ({ value: status, label: enumLabel(status), }))} onSelect={(to) => bulk.apply(bulkStatus.url(), { to }) } /> )}{' '} {canDelete && ( )} )} {isTrash && ( <> {canRestore && ( )} {canForceDelete && ( )} )} )} !open && setItemToDelete(null)} title={t('deleteTitle', { name: String(itemToDelete?.name ?? ''), })} description={t('deleteBody', { name: String(itemToDelete?.slug ?? ''), })} confirmLabel={t('deleteOf', { label })} onConfirm={confirmDelete} pending={deleting} /> !open && setItemToForceDelete(null)} title={t('forceDeleteTitle', { name: String(itemToForceDelete?.name ?? ''), })} description={t('forceDeleteBody', { label })} confirmLabel={t('deletePermanently')} onConfirm={confirmForceDelete} pending={forceDeleting} /> bulk.confirm(bulkDestroy.url(), () => setShowBulkDelete(false), ) } pending={bulk.processing} /> {/* Bulk restore confirmation */} bulk.confirm(bulkRestoreRoute.url(), () => setShowBulkRestore(false), ) } pending={bulk.processing} /> {/* Bulk permanent delete confirmation */} bulk.confirm(bulkForceDeleteRoute.url(), () => setShowBulkForceDelete(false), ) } pending={bulk.processing} /> {/* Mounted only while open, and remounted per target via `key`, so `useForm` is initialised with the record rather than patched after it arrives. */} {formTarget && ( !next && setFormTarget(null)} target={formTarget} options={{ statusOptions, fkOptionsUrl, tagsOptions, canEditRestricted, }} /> )} ); } ProductIndex.layout = () => ({ // A function, not an object: `t()` / `moduleLabel()` must run at render // time, after `withApp` has set the page's language. Evaluated at module // load, it would run before the server knows the page's language, and the // server-rendered breadcrumbs would not match the browser's. breadcrumbs: [ { title: moduleLabel('product', 'Products', true), href: routeIndex(), }, ], });