# Data Table A guide to composing Forge Table with TanStack Table v9 for sorting, filtering, column visibility, selection and pagination. [Interactive guide](/docs/components/data-table) · Forge 3.2.0 Use the API for your installed version. Run `npx --no-install wss3-forge api --json` inside the project. ## Implementation guidance ### When to use it Use the TanStack composition when a table needs explicit control over how filter, sort, selection and pagination state interact. ### How to compose it Use TanStack row models with Forge Table markup and controls. Choose the root Table data API when its built-in workflow already meets the need. ### What to verify Filter from a later page and change sorting with rows selected. Confirm pagination and selection use record identities and the intended row model. ## Usage ```tsx import { Table, TableHeader, TableHead, TableRow, TableCell, TableBody } from 'wss3-forge' ``` - Copy the working example to get the table, typed columns and controls together. - TanStack computes row models and maintains the relationship between columns, sorting, filtering, pagination and selection. Forge supplies the table markup and interactive controls. The Expandable rows example uses the shared data-driven Table from wss3-forge. Pass getSubRows to reveal child records, getRowLabel for disclosure names and stable IDs for persistent expansion. ```tsx Emailmina@fieldnotes.example
``` ## Guide ### Project structure Keep the Payment type and data access separate from the interactive table. Define column accessors next to their cell renderers and pass stable data and columns to useTable. ```tsx payments/ columns.tsx // Payment and column definitions data-table.tsx // Controls, state and row rendering page.tsx // Fetch and pass payment records ``` ### Set up table features Register each interaction and its row model once, outside the component. The payments example registers filtering, visibility, sorting, pagination and selection. Give each payment a stable row ID. ```tsx const features = tableFeatures({ rowSortingFeature, sortedRowModel: createSortedRowModel(), sortFns: { text: sortFn_text }, }) const helper = createColumnHelper() ``` ### Columns and rows Define an accessor for stored values and display columns for selection and actions. Render table.getHeaderGroups(), table.getRowModel().rows and row.getVisibleCells(). TanStack v9 provides table.FlexRender for headers and cells. ```tsx const columns = helper.columns([helper.accessor('email', { header: 'Email' })]) const table = useTable({ features, columns, data, getRowId: payment => payment.id }) ``` ### Cell formatting Keep amounts numeric in the data model. Format currency only when rendering a cell so comparisons operate on numbers. ```tsx helper.accessor('amount', { header: 'Amount', cell: ({ row }) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(row.original.amount), }) ``` ### Row actions Read the original payment from the row. Use a named menu trigger for each payment. The example copies its ID or opens the selected customer or payment in a Forge dialog. ```tsx helper.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }) ``` ### Pagination Store pageIndex and pageSize together. Bind onPaginationChange to the setter and disable controls at the boundaries. The pagination example uses two rows per page to make page changes visible. ```tsx const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 5 }) // useTable options state: { pagination }, onPaginationChange: setPagination ``` ### Sorting Keep SortingState controlled. Activate the Email header to toggle its sort direction, and reflect the direction with aria-sort on that header. ```tsx email.toggleSorting(email.getIsSorted() === 'asc') ``` ### Filtering Pass the input value to the email column filter and return to the first page. Show an empty row spanning the visible columns when there are no matches. ```tsx email.setFilterValue(value) table.setPageIndex(0) ``` ### Column visibility Build the Columns menu from hideable columns. Use checked menu items to expose visibility, and render visible cells so header and body stay aligned. ```tsx table.getAllColumns().filter(column => column.getCanHide()).map(column => ({ id: column.id, label: column.id, checked: column.getIsVisible(), onClick: () => column.toggleVisibility(), })) ``` ### Row selection Store selection by payment ID so it survives sorting and pagination. The header checkbox acts on the current page and becomes indeterminate for a partial selection. The footer reports the filtered selection. ```tsx table.toggleAllPageRowsSelected(true) table.getFilteredSelectedRowModel().rows.length ``` ### Reusable components Extract the sortable header, column menu and pagination once their behavior is shared by another table. Keep customer and payment actions in the payments module. ## Runnable examples ### Payments ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return {table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` ### Pagination with two rows per page ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return {table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` ### Expandable rows ```tsx import { Table } from 'wss3-forge' type PrintOrder = { id: string; item: string; quantity: number; stage: string; lines?: PrintOrder[] } function ExpandableOrders() { const orders: PrintOrder[] = [ { id: 'spring', item: 'Spring field guide', quantity: 240, stage: 'In production', lines: [ { id: 'spring-cover', item: 'Cover proofs', quantity: 6, stage: 'Approved' }, { id: 'spring-inside', item: 'Interior pages', quantity: 234, stage: 'Printing' }, ] }, { id: 'atlas', item: 'Coastal atlas', quantity: 16, stage: 'Ready' }, ] return row.item} getSubRows={row => row.lines} defaultExpandedKeys={[]} searchable searchPlaceholder="Search print orders" pagination={false} columns={[{ key: 'item', header: 'Print item' }, { key: 'stage', header: 'Stage' }, { key: 'quantity', header: 'Quantity', align: 'right' }]} /> } export default function Example() { return () } ``` ### RTL ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return
{table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` ## Primitive libraries ### Base UI The Base UI entry provides semantic table parts. TanStack supplies the row models and actions. ```sh npm install wss3-forge @tanstack/react-table@^9 @base-ui/react ``` ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/base-ui' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return {table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` #### Pagination with two rows per page ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/base-ui' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return {table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` #### RTL ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/base-ui' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return {table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` ### Radix The Radix entry provides semantic table parts. TanStack supplies the row models and actions. ```sh npm install wss3-forge @tanstack/react-table@^9 radix-ui ``` ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/radix' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return {table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` #### Pagination with two rows per page ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/radix' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return {table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` #### RTL ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/radix' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } type TableParts = Pick & { Table: ComponentType> } const baseParts: TableParts = { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl, parts = baseParts }: GridProps & { parts?: typeof baseParts }) { const { Table, TableHeader, TableHead, TableBody, TableRow, TableCell } = parts const rows = table.getRowModel().rows return {table.getHeaderGroups().map(group => {group.headers.map(header => {header.isPlaceholder ? null : header.column.id === 'actions' ? null : } )} )}{rows.length ? rows.map(row => {row.getVisibleCells().map(cell => )} ) : {rtl ? 'لا نتائج.' : 'No results.'}}
} export default function Example() { return () } ``` ### React Aria React Aria renders a keyboard-navigable grid. TanStack owns the sort and selection state. The first visible data column identifies each row when Email is hidden. ```sh npm install wss3-forge @tanstack/react-table@^9 react-aria-components ``` ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/react-aria' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl }: GridProps) { const keepCheckboxInput = (event: SyntheticEvent) => event.stopPropagation() const checkboxEvents = { onFocus: keepCheckboxInput, onKeyDown: keepCheckboxInput, onKeyUp: keepCheckboxInput, onPointerDown: keepCheckboxInput, onPointerUp: keepCheckboxInput, onClick: keepCheckboxInput } const headers = table.getFlatHeaders() const rows = table.getRowModel().rows const email = table.getColumn('email') const sorted = email?.getIsSorted() const rowHeader = email?.getIsVisible() ? 'email' : headers.find(header => header.column.getCanHide())?.column.id const labels: Record = rtl ? { select: 'تحديد', status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ', actions: 'الإجراءات' } : { select: 'Selection', status: 'Status', email: 'Email', amount: 'Amount', actions: 'Actions' } return row.id)} onSelectionChange={keys => table.setRowSelection(previous => { const updated = { ...previous } for (const row of rows) { if (keys === 'all' || keys.has(row.id)) updated[row.id] = true else delete updated[row.id] } return updated })} sortDescriptor={sorted ? { column: 'email', direction: sorted === 'asc' ? 'ascending' : 'descending' } : undefined} onSortChange={descriptor => table.setSorting([{ id: String(descriptor.column), desc: descriptor.direction === 'descending' }])}> {headers.map(header => {header.column.id === 'email' ? <>{labels.email} )} rtl ? 'لا نتائج.' : 'No results.'}>{rows.map(row => {row.getVisibleCells().map(cell => {cell.column.id === 'select' ? : } )} )}
} export default function Example() { return () } ``` #### Pagination with two rows per page ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/react-aria' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl }: GridProps) { const keepCheckboxInput = (event: SyntheticEvent) => event.stopPropagation() const checkboxEvents = { onFocus: keepCheckboxInput, onKeyDown: keepCheckboxInput, onKeyUp: keepCheckboxInput, onPointerDown: keepCheckboxInput, onPointerUp: keepCheckboxInput, onClick: keepCheckboxInput } const headers = table.getFlatHeaders() const rows = table.getRowModel().rows const email = table.getColumn('email') const sorted = email?.getIsSorted() const rowHeader = email?.getIsVisible() ? 'email' : headers.find(header => header.column.getCanHide())?.column.id const labels: Record = rtl ? { select: 'تحديد', status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ', actions: 'الإجراءات' } : { select: 'Selection', status: 'Status', email: 'Email', amount: 'Amount', actions: 'Actions' } return row.id)} onSelectionChange={keys => table.setRowSelection(previous => { const updated = { ...previous } for (const row of rows) { if (keys === 'all' || keys.has(row.id)) updated[row.id] = true else delete updated[row.id] } return updated })} sortDescriptor={sorted ? { column: 'email', direction: sorted === 'asc' ? 'ascending' : 'descending' } : undefined} onSortChange={descriptor => table.setSorting([{ id: String(descriptor.column), desc: descriptor.direction === 'descending' }])}> {headers.map(header => {header.column.id === 'email' ? <>{labels.email} )} rtl ? 'لا نتائج.' : 'No results.'}>{rows.map(row => {row.getVisibleCells().map(cell => {cell.column.id === 'select' ? : } )} )}
} export default function Example() { return () } ``` #### RTL ```tsx import { createContext, useContext, useState, type ComponentPropsWithoutRef, type ComponentType, type SyntheticEvent } from 'react' import { columnFilteringFeature, columnVisibilityFeature, createColumnHelper, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_text, tableFeatures, useTable, type ColumnFiltersState, type ColumnVisibilityState, type PaginationState, type RowSelectionState, type SortingState } from '@tanstack/react-table' import { ArrowSort16Regular, ChevronDown16Regular, MoreHorizontal16Regular } from '@fluentui/react-icons' import { Box, Button, Checkbox, Dialog, DialogBody, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, Direction, DropdownMenu, HStack, Input, Text, VStack, useContextMenu, type DropdownItem } from 'wss3-forge' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'wss3-forge/react-aria' type Payment = { id: string; amount: number; status: 'pending' | 'processing' | 'success' | 'failed'; email: string } const payments: Payment[] = [ { id: 'pay-fn-1042', amount: 128.50, status: 'success', email: 'mina@fieldnotes.example' }, { id: 'pay-fn-1043', amount: 64, status: 'pending', email: 'ari@fieldnotes.example' }, { id: 'pay-fn-1044', amount: 392.75, status: 'processing', email: 'jo@fieldnotes.example' }, { id: 'pay-fn-1045', amount: 246, status: 'success', email: 'ren@fieldnotes.example' }, { id: 'pay-fn-1046', amount: 85.25, status: 'failed', email: 'tess@fieldnotes.example' }, ] const paymentFeatures = tableFeatures({ columnFilteringFeature, columnVisibilityFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, filteredRowModel: createFilteredRowModel(), paginatedRowModel: createPaginatedRowModel(), sortedRowModel: createSortedRowModel(), filterFns: { includesString: filterFn_includesString }, sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text }, }) const column = createColumnHelper() const statusLabels = { pending: 'Pending', processing: 'Processing', success: 'Success', failed: 'Failed' } const arStatus = { pending: 'قيد الانتظار', processing: 'قيد المعالجة', success: 'ناجح', failed: 'فشل' } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const arabicUsd = new Intl.NumberFormat('ar', { style: 'currency', currency: 'USD' }) type PaymentDetails = { view: 'customer' | 'payment' | 'copy'; payment: Payment } const OpenPaymentDetails = createContext<(details: PaymentDetails) => void>(() => {}) function PaymentActions({ payment, rtl }: { payment: Payment; rtl: boolean }) { const openDetails = useContext(OpenPaymentDetails) const [feedback, setFeedback] = useState('') const { getTriggerProps, ContextMenuComponent } = useContextMenu() const items: DropdownItem[] = [ { id: 'copy', label: rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID', onClick: async () => { try { await navigator.clipboard.writeText(payment.id); setFeedback(rtl ? 'تم النسخ' : 'Payment ID copied') } catch { openDetails({ view: 'copy', payment }) } } }, { id: 'divider', label: '', divider: true }, { id: 'customer', label: rtl ? 'عرض العميل' : 'View customer', onClick: () => openDetails({ view: 'customer', payment }) }, { id: 'payment', label: rtl ? 'عرض تفاصيل الدفعة' : 'View payment details', onClick: () => openDetails({ view: 'payment', payment }) }, ] const trigger = getTriggerProps(items, { openOnClick: true, label: rtl ? 'الإجراءات' : 'Actions' }) // The action button handles its own input inside a keyboard-selectable grid row. const keepButtonInput = (event: SyntheticEvent) => event.stopPropagation() return
{ContextMenuComponent} {feedback}
} function PaymentDialog({ detail, rtl, onClose }: { detail: PaymentDetails; rtl: boolean; onClose: () => void }) { const { view, payment } = detail const title = view === 'copy' ? (rtl ? 'نسخ معرّف الدفعة' : 'Copy payment ID') : view === 'customer' ? (rtl ? 'العميل' : 'Customer') : (rtl ? 'تفاصيل الدفعة' : 'Payment details') return { if (!next) onClose() }}> {title} {view === 'copy' ? : {payment.email}} {view === 'payment' && <> {payment.id} {(rtl ? arabicUsd : usd).format(payment.amount)} {(rtl ? arStatus : statusLabels)[payment.status]} } {rtl ? 'إغلاق' : 'Close'} } function makeColumns(rtl: boolean) { return column.columns([ column.display({ id: 'select', enableHiding: false, enableSorting: false, header: ({ table }) => table.toggleAllPageRowsSelected(checked === true)} />, cell: ({ row }) => row.toggleSelected(checked === true)} /> }), column.accessor('status', { header: rtl ? 'الحالة' : 'Status', cell: ({ row }) => (rtl ? arStatus : statusLabels)[row.original.status] }), column.accessor('email', { header: ({ column: email }) => , cell: ({ row }) => {row.original.email.toLowerCase()} }), column.accessor('amount', { header: rtl ? 'المبلغ' : 'Amount', cell: ({ row }) => (rtl ? arabicUsd : usd).format(row.original.amount) }), column.display({ id: 'actions', enableHiding: false, cell: ({ row }) => }), ]) } const englishColumns = makeColumns(false) const arabicColumns = makeColumns(true) function usePaymentsModel(rtl: boolean, pageSize: number) { const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize }) return useTable({ features: paymentFeatures, data: payments, columns: rtl ? arabicColumns : englishColumns, getRowId: payment => payment.id, state: { sorting, columnFilters, columnVisibility, rowSelection, pagination }, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onPaginationChange: setPagination, }) } type GridProps = { table: ReturnType; rtl: boolean } function PaymentsTable({ rtl = false, pageSize = 5, Grid = SemanticGrid }: { rtl?: boolean; pageSize?: number; Grid?: ComponentType }) { const table = usePaymentsModel(rtl, pageSize) const [detail, setDetail] = useState(null) const labels: Record = rtl ? { status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ' } : { status: 'Status', email: 'Email', amount: 'Amount' } const email = table.getColumn('email') const visibleDataColumns = table.getVisibleLeafColumns().filter(column => column.getCanHide()).length return { email?.setFilterValue(value); table.setPageIndex(0) }} /> }>{rtl ? 'الأعمدة' : 'Columns'}} items={table.getAllColumns().filter(item => item.getCanHide()).map(item => ({ id: item.id, label: labels[item.id], checked: item.getIsVisible(), disabled: item.getIsVisible() && visibleDataColumns === 1, onClick: () => item.toggleVisibility(), }))} /> {rtl ? 'تم تحديد ' + table.getFilteredSelectedRowModel().rows.length + ' من ' + table.getFilteredRowModel().rows.length : table.getFilteredSelectedRowModel().rows.length + ' of ' + table.getFilteredRowModel().rows.length + ' row(s) selected.'} {detail && setDetail(null)} />} } function SemanticGrid({ table, rtl }: GridProps) { const keepCheckboxInput = (event: SyntheticEvent) => event.stopPropagation() const checkboxEvents = { onFocus: keepCheckboxInput, onKeyDown: keepCheckboxInput, onKeyUp: keepCheckboxInput, onPointerDown: keepCheckboxInput, onPointerUp: keepCheckboxInput, onClick: keepCheckboxInput } const headers = table.getFlatHeaders() const rows = table.getRowModel().rows const email = table.getColumn('email') const sorted = email?.getIsSorted() const rowHeader = email?.getIsVisible() ? 'email' : headers.find(header => header.column.getCanHide())?.column.id const labels: Record = rtl ? { select: 'تحديد', status: 'الحالة', email: 'البريد الإلكتروني', amount: 'المبلغ', actions: 'الإجراءات' } : { select: 'Selection', status: 'Status', email: 'Email', amount: 'Amount', actions: 'Actions' } return row.id)} onSelectionChange={keys => table.setRowSelection(previous => { const updated = { ...previous } for (const row of rows) { if (keys === 'all' || keys.has(row.id)) updated[row.id] = true else delete updated[row.id] } return updated })} sortDescriptor={sorted ? { column: 'email', direction: sorted === 'asc' ? 'ascending' : 'descending' } : undefined} onSortChange={descriptor => table.setSorting([{ id: String(descriptor.column), desc: descriptor.direction === 'descending' }])}> {headers.map(header => {header.column.id === 'email' ? <>{labels.email} )} rtl ? 'لا نتائج.' : 'No results.'}>{rows.map(row => {row.getVisibleCells().map(cell => {cell.column.id === 'select' ? : } )} )}
} export default function Example() { return () } ``` ## Root package API ### Table Compose a table from headers, rows and cells, or pass records to a ready-to-use Forge table. Props type: `TableProps> | SimpleTableProps | SemanticTableProps` Native attributes: AriaAttributes, Attributes, DOMAttributes, HTMLAttributes, TableHTMLAttributes **Composition exports** - `TableHeader` (named export) - `TableBody` (named export) - `TableRow` (named export) - `TableHead` (named export) - `TableCell` (named export) - `TableFooter` (named export) - `TableCaption` (named export) - `data?` — `T[]` Array of data objects - `columns?` — `TableColumn[]` Column definitions - `keyField?` — `keyof T` Field used as the unique row key (defaults to "id") - `getRowKey?` — `((row: T) => string | number) | ((row: ReactNode[], index: number) => string | number)` Stable, unique identity for each row. Takes precedence over keyField. - `getRowLabel?` — `(row: T) => string` Label used for each row's selection, actions and expansion controls. - `getSubRows?` — `(row: T) => readonly T[] | null | undefined` Return immediate children of a row. Rows without children have no expand control. - `expandedKeys?` — `readonly string[]` Controlled keys of expanded rows. Uses getRowKey or keyField. - `defaultExpandedKeys?` — `readonly string[]` Initially expanded rows when expandedKeys is omitted. - `onExpandedKeysChange?` — `(keys: string[]) => void` Reports the next set of expanded keys after an expansion action - `remote?` — `TableRemoteState` Use caller-provided rows and emit remote query changes. - `title?` — `string | string | undefined` Table header title - `subtitle?` — `string` Table header subtitle - `aria-label?` — `string` - `searchable?` — `boolean` Enable search - `searchPlaceholder?` — `string` Placeholder for the search input - `searchKeys?` — `(keyof T)[]` Limit local search to these fields. Defaults to the displayed column keys - `filters?` — `TableFilter[]` Filter definitions rendered above the table - `activeFilters?` — `Record` Controlled active-filters state - `defaultFilters?` — `Record` Initial filters when neither activeFilters nor remote is supplied - `onFilterChange?` — `(key: string, value: string | null) => void` Fires when a filter chip is added / cleared - `selectable?` — `boolean` Enable row selection - `selectedKeys?` — `string[]` Controlled selected-row IDs - `defaultSelectedKeys?` — `string[]` Initial selection when selectedKeys is omitted - `onSelectionChange?` — `(keys: string[]) => void` Fires when the selection changes - `sortable?` — `boolean` Enable sorting - `defaultSort?` — `TableSort` Initial sort order - `pagination?` — `boolean` Enable pagination - `pageSize?` — `number` Top-level rows per page. Expanded descendants stay with their parent - `pageSizeOptions?` — `readonly number[]` Show a rows-per-page selector with these choices in the pagination footer. - `onPageSizeChange?` — `(pageSize: number) => void` Fires after the rows-per-page selection changes. The table returns to page 1 - `onRowClick?` — `(row: T) => void` Row click handler - `rowActions?` — `(row: T) => DropdownItem[]` Per-row action menu items - `globalActions?` — `ReactNode` Action buttons displayed in header (right side) - `bulkActions?` — `(selectedKeys: string[]) => ReactNode` Bulk-action bar shown when rows are selected - `loading?` — `boolean` Show skeleton rows while data is loading - `error?` — `string` Replace the rows with an accessible error message - `onRetry?` — `() => void` Offer a retry action in the error state - `striped?` — `boolean` Striped rows - `compact?` — `boolean` Compact row height - `stickyHeader?` — `boolean` Keep the column header fixed while scrolling - `noPadding?` — `boolean` Remove all padding around table - `emptyMessage?` — `string` Message shown when there are no rows - `emptyIcon?` — `ReactNode` Icon shown in the empty state - `headers?` — `string[]` - `rows?` — `ReactNode[][]` - `footer?` — `ReactNode[]` Optional summary cells in column order. - `columnAlign?` — `readonly ('start' | 'center' | 'end')[]` Logical alignment for each column, including its heading and footer. - `caption?` — `string` - `className?` — `string` - `style?` — `React.CSSProperties` - `ref?` — `React.LegacyRef | undefined` #### TableProps - `data` — `T[]` Array of data objects - `columns` — `TableColumn[]` Column definitions - `keyField?` — `keyof T` Field used as the unique row key (defaults to "id") - `getRowKey?` — `(row: T) => string | number` Stable, unique identity for each row. Takes precedence over keyField. - `getRowLabel?` — `(row: T) => string` Label used for each row's selection, actions and expansion controls. - `getSubRows?` — `(row: T) => readonly T[] | null | undefined` Return immediate children of a row. Rows without children have no expand control. - `expandedKeys?` — `readonly string[]` Controlled keys of expanded rows. Uses getRowKey or keyField. - `defaultExpandedKeys?` — `readonly string[]` Initially expanded rows when expandedKeys is omitted. - `onExpandedKeysChange?` — `(keys: string[]) => void` Reports the next set of expanded keys after an expansion action - `remote?` — `TableRemoteState` Use caller-provided rows and emit remote query changes. - `title?` — `string` Table header title - `subtitle?` — `string` Table header subtitle - `aria-label?` — `string` - `searchable?` — `boolean` Enable search - `searchPlaceholder?` — `string` Placeholder for the search input - `searchKeys?` — `(keyof T)[]` Limit local search to these fields. Defaults to the displayed column keys - `filters?` — `TableFilter[]` Filter definitions rendered above the table - `activeFilters?` — `Record` Controlled active-filters state - `defaultFilters?` — `Record` Initial filters when neither activeFilters nor remote is supplied - `onFilterChange?` — `(key: string, value: string | null) => void` Fires when a filter chip is added / cleared - `selectable?` — `boolean` Enable row selection - `selectedKeys?` — `string[]` Controlled selected-row IDs - `defaultSelectedKeys?` — `string[]` Initial selection when selectedKeys is omitted - `onSelectionChange?` — `(keys: string[]) => void` Fires when the selection changes - `sortable?` — `boolean` Enable sorting - `defaultSort?` — `TableSort` Initial sort order - `pagination?` — `boolean` Enable pagination - `pageSize?` — `number` Top-level rows per page. Expanded descendants stay with their parent - `pageSizeOptions?` — `readonly number[]` Show a rows-per-page selector with these choices in the pagination footer. - `onPageSizeChange?` — `(pageSize: number) => void` Fires after the rows-per-page selection changes. The table returns to page 1 - `onRowClick?` — `(row: T) => void` Row click handler - `rowActions?` — `(row: T) => DropdownItem[]` Per-row action menu items - `globalActions?` — `ReactNode` Action buttons displayed in header (right side) - `bulkActions?` — `(selectedKeys: string[]) => ReactNode` Bulk-action bar shown when rows are selected - `loading?` — `boolean` Show skeleton rows while data is loading - `error?` — `string` Replace the rows with an accessible error message - `onRetry?` — `() => void` Offer a retry action in the error state - `striped?` — `boolean` Striped rows - `compact?` — `boolean` Compact row height - `stickyHeader?` — `boolean` Keep the column header fixed while scrolling - `noPadding?` — `boolean` Remove all padding around table - `emptyMessage?` — `string` Message shown when there are no rows - `emptyIcon?` — `ReactNode` Icon shown in the empty state #### SimpleTableProps - `headers` — `string[]` - `rows` — `ReactNode[][]` - `footer?` — `ReactNode[]` Optional summary cells in column order. - `columnAlign?` — `readonly ('start' | 'center' | 'end')[]` Logical alignment for each column, including its heading and footer. - `caption?` — `string` - `aria-label?` — `string` - `getRowKey?` — `(row: ReactNode[], index: number) => string | number` Derive a stable identity when the default id field is unavailable. Takes precedence over keyField - `compact?` — `boolean` Compact row height - `className?` — `string` - `style?` — `React.CSSProperties` #### SemanticTableProps Native attributes: AriaAttributes, Attributes, DOMAttributes, HTMLAttributes, TableHTMLAttributes - `title?` — `string | undefined` Table header title ### TableHeader Props type: `ComponentPropsWithoutRef<'thead'>` Native attributes: AriaAttributes, Attributes, DOMAttributes, HTMLAttributes - `ref?` — `React.LegacyRef | undefined` ### TableHead Props type: `ComponentPropsWithoutRef<'th'>` Native attributes: AriaAttributes, Attributes, DOMAttributes, HTMLAttributes, ThHTMLAttributes - `ref?` — `React.LegacyRef | undefined` ### TableRow Props type: `ComponentPropsWithoutRef<'tr'>` Native attributes: AriaAttributes, Attributes, DOMAttributes, HTMLAttributes - `ref?` — `React.LegacyRef | undefined` ### TableCell Props type: `ComponentPropsWithoutRef<'td'>` Native attributes: AriaAttributes, Attributes, DOMAttributes, HTMLAttributes, TdHTMLAttributes - `ref?` — `React.LegacyRef | undefined` ### TableBody Props type: `ComponentPropsWithoutRef<'tbody'>` Native attributes: AriaAttributes, Attributes, DOMAttributes, HTMLAttributes - `ref?` — `React.LegacyRef | undefined` ## Related types ```ts export interface TableColumn { key: keyof T | string header: string width?: string | number sortable?: boolean render?: (value: any, row: T, index: number) => ReactNode align?: 'left' | 'center' | 'right' filterable?: boolean } export interface TableRemoteState { query: TableQuery onQueryChange: (query: TableQuery) => void /** Total rows for the current query, when the server reports a count. */ totalRows?: number /** Whether another page exists when the total is unknown. */ hasNextPage?: boolean } export interface TableQuery { /** Page index, starting at 1. */ page: number search: string filters: Record sort: TableSort | null } export interface TableSort { key: string direction: 'asc' | 'desc' } export interface TableFilter { key: string label: string options: Array<{ value: string; label: string }> } export interface DropdownItem { id: string label: string /** A boolean makes the item a checked menu choice. Update it in onClick. */ checked?: boolean /** Navigational entries render native links, including modifier-click and context menu support. */ href?: string icon?: ReactNode shortcut?: string // Raccourci clavier (ex: "Ctrl+K") onClick?: () => void disabled?: boolean destructive?: boolean divider?: boolean } export interface TableProps { data: T[] columns: TableColumn[] keyField?: keyof T /** Stable, unique identity for each row. Takes precedence over keyField. */ getRowKey?: (row: T) => string | number /** Label used for each row's selection, actions and expansion controls. */ getRowLabel?: (row: T) => string /** Return immediate children of a row. Rows without children have no expand control. */ getSubRows?: (row: T) => readonly T[] | null | undefined /** Controlled keys of expanded rows. Uses getRowKey or keyField. */ expandedKeys?: readonly string[] /** Initially expanded rows when expandedKeys is omitted. */ defaultExpandedKeys?: readonly string[] onExpandedKeysChange?: (keys: string[]) => void /** Use caller-provided rows and emit remote query changes. */ remote?: TableRemoteState // Header title?: string subtitle?: string 'aria-label'?: string // Search searchable?: boolean searchPlaceholder?: string searchKeys?: (keyof T)[] // Filters filters?: TableFilter[] activeFilters?: Record defaultFilters?: Record onFilterChange?: (key: string, value: string | null) => void // Selection selectable?: boolean selectedKeys?: string[] defaultSelectedKeys?: string[] onSelectionChange?: (keys: string[]) => void // Sorting sortable?: boolean defaultSort?: TableSort // Pagination pagination?: boolean pageSize?: number /** Show a rows-per-page selector with these choices in the pagination footer. */ pageSizeOptions?: readonly number[] onPageSizeChange?: (pageSize: number) => void // Actions onRowClick?: (row: T) => void rowActions?: (row: T) => DropdownItem[] globalActions?: ReactNode bulkActions?: (selectedKeys: string[]) => ReactNode // States loading?: boolean error?: string onRetry?: () => void // Styling striped?: boolean compact?: boolean stickyHeader?: boolean noPadding?: boolean emptyMessage?: string emptyIcon?: ReactNode } export interface SimpleTableProps { headers: string[] rows: ReactNode[][] /** Optional summary cells in column order. */ footer?: ReactNode[] /** Logical alignment for each column, including its heading and footer. */ columnAlign?: readonly ('start' | 'center' | 'end')[] caption?: string 'aria-label'?: string getRowKey?: (row: ReactNode[], index: number) => string | number compact?: boolean className?: string style?: React.CSSProperties } export type SemanticTableProps = ComponentPropsWithoutRef<'table'> ``` ## Optional primitive contracts - [wss3-forge/base-ui · Table contract](/ai/skill/primitive-api/Table.json) - [wss3-forge/radix · Table contract](/ai/skill/primitive-api/Table.json) - [wss3-forge/react-aria · Table contract](/ai/skill/primitive-api/Table.json)