diff --git a/docs-manifest.json b/docs-manifest.json index e61f12412..d9a6dc18b 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -404,6 +404,9 @@ "examples": "docs-src/components/data-table.docs.examples.tsx", "sources": [ "packages/core/src/components/data-table/**", + "packages/core/src/components/internals/table-core/column-types.ts", + "packages/core/src/components/internals/table-core/cell-edit-error.ts", + "packages/core/src/components/internals/table-core/editing/date.tsx", "packages/core/src/hooks/use-collection-variables.ts", "packages/core/src/lib/collection-url-state.ts", "packages/core/src/contexts/collection-control-context.tsx", @@ -476,10 +479,10 @@ "withURLCollectionState" ], "hashes": { - "typeSurface": "413c66caec0a0bf8", - "outline": "7591217822d0183b", + "typeSurface": "8ada983257d51646", + "outline": "1bcf784b4b500873", "snapshot": "a97e067c66e46ef6", - "outputMd": "36bb587b7088fb1c", + "outputMd": "f0e28c3045e5bb2d", "examples": "8adc119ac0d7152c" } }, @@ -1840,7 +1843,7 @@ "packages/core/skills/app-shell-patterns/references/components/combobox.md": "c79cd0fe175187e3", "packages/core/skills/app-shell-patterns/references/components/command-palette.md": "7e5bc675a593791a", "packages/core/skills/app-shell-patterns/references/components/csv-importer.md": "10c04c78bb846c9a", - "packages/core/skills/app-shell-patterns/references/components/data-table.md": "36bb587b7088fb1c", + "packages/core/skills/app-shell-patterns/references/components/data-table.md": "f0e28c3045e5bb2d", "packages/core/skills/app-shell-patterns/references/components/date-picker.md": "376e7d4ad14c2934", "packages/core/skills/app-shell-patterns/references/components/default-header.md": "375e55f4b12fa2be", "packages/core/skills/app-shell-patterns/references/components/default-sidebar.md": "9b1672c71b6db3ff", diff --git a/docs-src/components/data-table.docs.outline.md b/docs-src/components/data-table.docs.outline.md index 2ccdfb808..d1142e280 100644 --- a/docs-src/components/data-table.docs.outline.md +++ b/docs-src/components/data-table.docs.outline.md @@ -5,6 +5,9 @@ title: DataTable description: Compound data table component with sortable columns, filter chips, cursor-based pagination, row actions, and multi-row selection sources: - packages/core/src/components/data-table/** + - packages/core/src/components/internals/table-core/column-types.ts + - packages/core/src/components/internals/table-core/cell-edit-error.ts + - packages/core/src/components/internals/table-core/editing/date.tsx - packages/core/src/hooks/use-collection-variables.ts - packages/core/src/lib/collection-url-state.ts - packages/core/src/contexts/collection-control-context.tsx @@ -41,8 +44,8 @@ import { type NumberCellEditOptions, type BadgeCellEditOptions, type DateCellEditOptions, - type CellEditState, type DateTimeDraft, + type CellEditState, type FooterRenderContext, } from "@tailor-platform/app-shell"; ``` diff --git a/docs/components/data-table.md b/docs/components/data-table.md index 54b7d0df7..e3d3b761d 100644 --- a/docs/components/data-table.md +++ b/docs/components/data-table.md @@ -35,8 +35,8 @@ import { type NumberCellEditOptions, type BadgeCellEditOptions, type DateCellEditOptions, - type CellEditState, type DateTimeDraft, + type CellEditState, type FooterRenderContext, } from "@tailor-platform/app-shell"; ``` diff --git a/examples/vite-app/src/App.tsx b/examples/vite-app/src/App.tsx index 035b50f91..4d33163f4 100644 --- a/examples/vite-app/src/App.tsx +++ b/examples/vite-app/src/App.tsx @@ -85,6 +85,7 @@ const AppInner = () => { + diff --git a/examples/vite-app/src/pages/showcase/line-items/page.tsx b/examples/vite-app/src/pages/showcase/line-items/page.tsx new file mode 100644 index 000000000..ca2d043c6 --- /dev/null +++ b/examples/vite-app/src/pages/showcase/line-items/page.tsx @@ -0,0 +1,204 @@ +import { + Button, + CellEditError, + Layout, + LineItems, + Tabs, + useLineItems, + type AppShellPageProps, + type LineItemsColumn, +} from "@tailor-platform/app-shell"; +import { ListIcon, XIcon } from "lucide-react"; +import { useCallback, useState } from "react"; + +type OrderLine = { + id?: string; + item: string | null; + quantity: number | null; + unitPrice: number | null; + status: string | null; + dueDate: string | null; +}; + +const validateQuantity = (_row: Readonly, value: number | null) => { + if (value === null || value <= 0) { + throw new CellEditError("Quantity must be greater than zero."); + } +}; + +const LineItemsPage = () => { + const [editable, setEditable] = useState(true); + const canEdit = useCallback(() => editable, [editable]); + const lineItems = useLineItems({ + orderer: editable, + defaultLines: [ + { + id: "line-1", + item: "Notebook", + quantity: 2, + unitPrice: 5, + status: "open", + dueDate: "2026-11-16", + }, + { + id: "line-2", + item: "Pen", + quantity: 3, + unitPrice: 1.5, + status: "closed", + dueDate: "2026-11-17", + }, + { + id: "line-3", + item: "Pencil", + quantity: 4, + unitPrice: 1, + status: "open", + dueDate: "2026-11-18", + }, + { + id: "line-4", + item: "Eraser", + quantity: 2, + unitPrice: 0.75, + status: "open", + dueDate: "2026-11-19", + }, + { + id: "line-5", + item: "Ruler", + quantity: 1, + unitPrice: 2, + status: "closed", + dueDate: "2026-11-20", + }, + ], + columns: [ + { accessorKey: "item", label: "Item", edit: { editorType: "text", canEdit } }, + { + accessorKey: "quantity", + label: "Quantity", + type: "number", + typeOptions: { maxDecimals: 2 }, + edit: { editorType: "number", canEdit, onValueCommitted: validateQuantity }, + }, + { + accessorKey: "unitPrice", + label: "Unit price", + type: "money", + edit: { editorType: "number", canEdit }, + }, + { + id: "total", + label: "Total", + type: "money", + accessor: (line) => (line.quantity ?? 0) * (line.unitPrice ?? 0), + }, + { + accessorKey: "status", + label: "Status", + edit: { + editorType: "combobox", + canEdit, + editorOptions: { + options: [ + { value: "open", label: "Open" }, + { value: "closed", label: "Closed" }, + ], + }, + }, + }, + { + accessorKey: "dueDate", + label: "Due date", + type: "date", + edit: { editorType: "date", canEdit }, + }, + ...(editable + ? [ + { + id: "actions", + label: "Actions", + width: 64, + align: "center", + headerProps: () => ({ className: "first:pl-2! last:pr-2!" }), + cellProps: () => ({ className: "py-1! first:pl-2! last:pr-2!" }), + render: (line) => ( + lineItems.removeLine(lineItems.getLineKey(line))} + > + + + ), + } satisfies LineItemsColumn, + ] + : []), + ], + }); + + return ( + + + + setEditable(value === "editable")} + > + + Editable + Readonly + + + {editable && ( + + Clear Quantity or enter zero or a negative number, then press Enter to see a validation + error. + + )} + + + + {editable && ( + + + lineItems.addLine({ + item: "New item", + quantity: 1, + unitPrice: 1, + status: "open", + dueDate: null, + }) + } + > + Add line + + + Discard changes + + + )} + + + ); +}; + +LineItemsPage.appShellPageProps = { + meta: { + title: "Line Items", + icon: , + }, +} satisfies AppShellPageProps; + +export default LineItemsPage; diff --git a/examples/vite-app/src/routes.generated.ts b/examples/vite-app/src/routes.generated.ts index dfc93c810..60455dd82 100644 --- a/examples/vite-app/src/routes.generated.ts +++ b/examples/vite-app/src/routes.generated.ts @@ -44,6 +44,7 @@ export type GeneratedRouteParams = { "/showcase/grid": {}; "/showcase/item-list": {}; "/showcase/layouts": {}; + "/showcase/line-items": {}; "/showcase/metric-card": {}; "/showcase/primitives": {}; "/showcase/spinner": {}; diff --git a/packages/core/src/components/data-table/cell-renderer-adapter.test.tsx b/packages/core/src/components/data-table/cell-renderer-adapter.test.tsx new file mode 100644 index 000000000..0703cbed7 --- /dev/null +++ b/packages/core/src/components/data-table/cell-renderer-adapter.test.tsx @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import * as tableCore from "@/components/internals/table-core"; +import { cleanup, render, renderHook, screen } from "@testing-library/react"; +import { createAppShellWrapper } from "../../../tests/test-utils"; +import { useEditorProps } from "./editing/cell/shared"; +import { createCellEditNavigation } from "./editing/use-navigation"; +import { MemoryRouter } from "react-router"; +import { + createTypedCellRenderer, + createTypedValueRenderer, + getCellValue, + renderTypedValue, +} from "./cell-renderers"; +import type { Column } from "./types"; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe("DataTable renderer adapter compatibility", () => { + const row = { id: "A", status: "open", name: "Raw name" }; + + it("retains accessor/id lookup precedence without treating render output as raw data", () => { + expect(getCellValue(row, { id: "name" })).toBe("Raw name"); + expect(getCellValue(row, { id: "name", accessor: (value) => value.status })).toBe("open"); + expect(getCellValue(row, { render: () => "Display only" })).toBeUndefined(); + }); + + it.each([false, true])( + "resolves an editable value once with a prepared renderer (custom display: %s)", + (custom) => { + const accessor = vi.fn((value: typeof row) => value.name); + const col = { + id: "name", + type: "text", + accessor, + render: custom ? () => "Custom" : undefined, + edit: { onValueCommitted: () => {} }, + } satisfies Column; + const valueRenderer = vi.fn(createTypedValueRenderer(col, { timeZone: "UTC" })); + const { result } = renderHook( + () => + useEditorProps({ + row, + col, + valueRenderer, + rowKey: row.id, + colKey: "name", + label: "Name", + align: "left", + navigation: createCellEditNavigation(), + cellProps: {}, + }), + { wrapper: createAppShellWrapper() }, + ); + expect(accessor).toHaveBeenCalledExactlyOnceWith(row); + expect(result.current.current).toBe("Raw name"); + expect(result.current.display).toBe(custom ? "Custom" : "Raw name"); + if (custom) expect(valueRenderer).not.toHaveBeenCalled(); + else expect(valueRenderer).toHaveBeenCalledExactlyOnceWith("Raw name", row); + }, + ); + + it("keeps edit-choice labels in legacy text rendering", () => { + const col: Column = { + id: "status", + type: "text", + edit: { + options: [{ value: "open", label: "Open label" }], + onValueCommitted: () => {}, + }, + }; + expect(createTypedCellRenderer(col, "UTC")(row)).toBe("Open label"); + }); + + it.each(["number", "money"] as const)( + "prepares a %s renderer once rather than recreating it for each row", + (type) => { + const createRenderer = vi.spyOn(tableCore, "createValueRenderer"); + const col: Column<{ value: number }> = { id: "value", type }; + const renderer = createTypedCellRenderer(col, "UTC"); + expect(createRenderer).toHaveBeenCalledExactlyOnceWith(col, { timeZone: "UTC" }); + renderer({ value: 1 }); + renderer({ value: 2 }); + renderer({ value: 3 }); + expect(createRenderer).toHaveBeenCalledOnce(); + }, + ); + + it("resolves legacy link labels and plaintext editor display outside table-core", () => { + const col: Column = { + id: "status", + type: "link", + typeOptions: { href: (value) => `/rows/${value.id}` }, + edit: { + options: [{ value: "open", label: "Open label" }], + onValueCommitted: () => {}, + }, + }; + const readonly = createTypedCellRenderer(col, "UTC"); + const editable = createTypedCellRenderer(col, "UTC", { linkAsText: true }); + expect(editable(row)).toBe("Open label"); + expect(renderTypedValue(row, col, row.status, { linkAsText: true })).toBe("Open label"); + render({readonly(row)}); + expect(screen.getByRole("link", { name: "Open label" }).getAttribute("href")).toBe("/rows/A"); + }); +}); diff --git a/packages/core/src/components/data-table/cell-renderers.tsx b/packages/core/src/components/data-table/cell-renderers.tsx index c6b91dcf5..4e0fe3268 100644 --- a/packages/core/src/components/data-table/cell-renderers.tsx +++ b/packages/core/src/components/data-table/cell-renderers.tsx @@ -1,38 +1,11 @@ import type { ReactNode } from "react"; -import { parseDate } from "@internationalized/date"; -import { Link } from "react-router"; -import { BadgeList, toValueArray } from "@/components/badge-list"; -import type { SelectOption } from "@/types/collection"; +import { + createValueRenderer, + type ValueRenderer, + type ValueRendererContext, +} from "@/components/internals/table-core"; import { optionLabel, resolveBadgeOptions } from "./cell-values"; -import { normalizeTemporalFilterValue } from "@/lib/temporal-filter-values"; -import type { - BadgeCellOptions, - Column, - DateCellOptions, - LinkCellOptions, - MoneyCellOptions, - NumberCellOptions, -} from "./types"; - -function resolveDateFormatOptions(format: string): Intl.DateTimeFormatOptions { - if (format === "long") return { month: "long", day: "numeric", year: "numeric" }; - if (format === "datetime") { - return { - month: "short", - day: "numeric", - year: "numeric", - hour: "numeric", - minute: "2-digit", - }; - } - return { month: "short", day: "numeric", year: "numeric" }; -} - -const PLACEHOLDER = ( - - — - -); +import type { Column } from "./types"; /** * Read the raw cell value for a column. Used by the built-in `type` @@ -51,145 +24,36 @@ export function getCellValue>( return undefined; } -function isEmpty(value: unknown): boolean { - return value == null || value === ""; -} - -function renderText(value: unknown): ReactNode { - switch (true) { - case isEmpty(value): - return PLACEHOLDER; - case typeof value === "boolean": - return value ? "✓" : "✗"; - case value instanceof Date: - return value.toLocaleDateString(); - case typeof value === "object": - return JSON.stringify(value); +/** Bind DataTable's choice-label and editable-link policies before rendering rows. */ +export function createTypedValueRenderer>( + col: Column, + context: ValueRendererContext, + options?: { linkAsText?: boolean }, +): ValueRenderer { + switch (col.type) { + case "badge": { + const choices = col.edit + ? resolveBadgeOptions(col.edit.options, col.typeOptions, col.filter) + : undefined; + return createValueRenderer(col, { + ...context, + resolveBadgeLabel: choices ? (item) => String(optionLabel(choices, item)) : undefined, + }); + } + case "link": + case "text": { + const descriptor = + col.type === "link" && options?.linkAsText ? ({ type: "text" } as const) : col; + const renderValue = createValueRenderer(descriptor, context); + return (value, row) => renderValue(optionLabel(col.edit?.options, value), row); + } default: - return String(value); - } -} - -function renderNumber(value: unknown, options: NumberCellOptions | undefined): ReactNode { - if (isEmpty(value)) return PLACEHOLDER; - const num = Number(value); - if (Number.isNaN(num)) return PLACEHOLDER; - const min = options?.minDecimals ?? 0; - const formatted = new Intl.NumberFormat(options?.locale, { - minimumFractionDigits: min, - maximumFractionDigits: options?.maxDecimals ?? min, - }).format(num); - return {formatted}; -} - -function renderMoney>( - value: unknown, - row: TRow, - options: MoneyCellOptions | undefined, -): ReactNode { - if (isEmpty(value)) return PLACEHOLDER; - const num = Number(value); - if (Number.isNaN(num)) return PLACEHOLDER; - const currency = - (typeof options?.currency === "function" ? options.currency(row) : options?.currency) || "USD"; - - // `maxDecimals` raises the cap above the currency default while keeping the - // minimum at the currency default (e.g. 2 for USD). Lets a JPY column stay - // at 0 decimals while a USD price-detail column shows up to 4. - const formatOptions: Intl.NumberFormatOptions = { - style: "currency", - currency, - }; - if (options?.maxDecimals != null) { - formatOptions.maximumFractionDigits = options.maxDecimals; - } - let formatted: string; - try { - formatted = new Intl.NumberFormat(options?.locale, formatOptions).format(num); - } catch { - // Fall back to USD if the currency code is invalid — Intl throws on bad ISO codes. - formatted = new Intl.NumberFormat(options?.locale, { - style: "currency", - currency: "USD", - }).format(num); + return createValueRenderer(col, context); } - return {formatted}; -} - -function createDateRenderer( - options: DateCellOptions | undefined, - timeZone: string, -): (value: unknown) => ReactNode { - const formatOptions = resolveDateFormatOptions(options?.dateFormat ?? "short"); - let dateOnlyFormatter: Intl.DateTimeFormat | undefined; - let datetimeFormatter: Intl.DateTimeFormat | undefined; - - return (value) => { - if (isEmpty(value)) return PLACEHOLDER; - const dateOnly = typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value.trim()); - let date: Date; - if (dateOnly) { - // Calendar dates have no instant, even when a timezone skips an entire day. - try { - date = parseDate(value.trim()).toDate("UTC"); - } catch { - return PLACEHOLDER; - } - } else { - const normalized = normalizeTemporalFilterValue("datetime", value, timeZone); - if (!normalized) return PLACEHOLDER; - date = new Date(normalized); - } - const formatter = dateOnly - ? (dateOnlyFormatter ??= new Intl.DateTimeFormat(options?.locale, { - ...formatOptions, - timeZone: "UTC", - })) - : (datetimeFormatter ??= new Intl.DateTimeFormat(options?.locale, { - ...formatOptions, - timeZone, - })); - return formatter.format(date); - }; -} - -function renderBadge( - value: unknown, - options: BadgeCellOptions | undefined, - choices: readonly SelectOption[] | undefined, -): ReactNode { - const items = toValueArray(value); - const nonEmpty = items.filter((v) => v != null && v !== ""); - if (nonEmpty.length === 0) return PLACEHOLDER; - return ( - String(optionLabel(choices, v)) : undefined} - /> - ); -} - -function renderLink>( - value: unknown, - row: TRow, - options: LinkCellOptions, -): ReactNode { - if (isEmpty(value)) return PLACEHOLDER; - const label = String(value); - const href = options.href(row); - if (!href) return label; - return ( - - {label} - - ); } /** - * Create a column renderer that reuses date formatters across rows. + * Prepare a column's built-in renderer once and reuse it across rows. * Callers should prefer `col.render` when it is defined. * * @internal @@ -197,12 +61,10 @@ function renderLink>( export function createTypedCellRenderer>( col: Column, timeZone: string, + options?: { linkAsText?: boolean }, ): (row: TRow) => ReactNode { - if (col.type === "date") { - const renderDate = createDateRenderer(col.typeOptions, timeZone); - return (row) => renderDate(getCellValue(row, col)); - } - return (row) => renderTypedValue(row, col, getCellValue(row, col)); + const renderValue = createTypedValueRenderer(col, { timeZone }, options); + return (row) => renderValue(getCellValue(row, col), row); } /** @@ -218,30 +80,9 @@ export function renderTypedValue>( value: unknown, options?: { linkAsText?: boolean; timeZone?: string }, ): ReactNode { - switch (col.type) { - case "number": - return renderNumber(value, col.typeOptions); - case "money": - return renderMoney(value, row, col.typeOptions); - case "date": - return createDateRenderer( - col.typeOptions, - options?.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone, - )(value); - case "badge": - return renderBadge( - value, - col.typeOptions, - col.edit ? resolveBadgeOptions(col.edit.options, col.typeOptions, col.filter) : undefined, - ); - case "link": { - // A column with dropdown choices stores an option's value and shows its label. - const label = optionLabel(col.edit?.options, value); - return options?.linkAsText ? renderText(label) : renderLink(label, row, col.typeOptions); - } - case "text": - return renderText(optionLabel(col.edit?.options, value)); - default: - return renderText(value); - } + return createTypedValueRenderer( + col, + { timeZone: options?.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone }, + options, + )(value, row); } diff --git a/packages/core/src/components/data-table/cell-values.test.ts b/packages/core/src/components/data-table/cell-values.test.ts index e6bf9eaa0..be0983555 100644 --- a/packages/core/src/components/data-table/cell-values.test.ts +++ b/packages/core/src/components/data-table/cell-values.test.ts @@ -1,102 +1,5 @@ import { describe, expect, it } from "vitest"; -import { - isIsoDate, - optionLabel, - resolveBadgeOptions, - sameDate, - toCalendarDate, - toIsoDateTime, - toTimeText, - normalizeNumberText, - parseNumberText, - sameNumber, - toNumberEditText, - toNumberValue, - toTextValue, -} from "./cell-values"; - -describe("typed text that isn't a number", () => { - it("is reported as not a number, not silently accepted", () => { - for (const text of ["e", "1e5", "+5", "0x1f", "12a", "1,5"]) { - expect(parseNumberText(normalizeNumberText(text))).toBeUndefined(); - } - }); -}); - -describe("normalizeNumberText", () => { - it("drops strict thousands grouping", () => { - expect(normalizeNumberText("1,234.5")).toBe("1234.5"); - expect(normalizeNumberText("-1,234,567")).toBe("-1234567"); - }); - - it("leaves a decimal comma alone so it fails instead of becoming 15", () => { - expect(normalizeNumberText("1,5")).toBe("1,5"); - expect(parseNumberText(normalizeNumberText("1,5"))).toBeUndefined(); - }); - - it("converts full-width digits and signs", () => { - expect(normalizeNumberText("12.5")).toBe("12.5"); - expect(normalizeNumberText("-3")).toBe("-3"); - expect(normalizeNumberText("−3")).toBe("-3"); - }); - - it("strips whitespace and currency symbols", () => { - expect(normalizeNumberText(" $1,234.50 ")).toBe("1234.50"); - expect(normalizeNumberText("¥ 1 200")).toBe("1200"); - }); -}); - -describe("parseNumberText", () => { - it("treats an empty draft as null", () => { - expect(parseNumberText("")).toBeNull(); - expect(parseNumberText(" ")).toBeNull(); - }); - - it("parses partial but complete-enough numbers without business constraints", () => { - expect(parseNumberText("-3.5678")).toBe(-3.5678); - expect(parseNumberText("500.0001")).toBe(500.0001); - expect(parseNumberText("5.")).toBe(5); - expect(parseNumberText(".5")).toBe(0.5); - expect(parseNumberText("-0")).toBe(0); - expect(Object.is(parseNumberText("-0"), -0)).toBe(false); - }); - - it("rejects half-typed and non-numeric drafts", () => { - for (const text of ["-", ".", "-.", "abc", "1,5", String(Number.MAX_SAFE_INTEGER * 2)]) { - expect(parseNumberText(text)).toBeUndefined(); - } - }); -}); - -describe("value helpers", () => { - it("compares parsed numbers without silently rounding distinct values", () => { - expect(sameNumber(10, 10)).toBe(true); - expect(sameNumber(0.1 + 0.2, 0.3)).toBe(false); - expect(sameNumber(1234567890123456, 1234567890123457)).toBe(false); - expect(sameNumber(null, null)).toBe(true); - expect(sameNumber(0, null)).toBe(false); - expect(sameNumber(10, 10.01)).toBe(false); - }); - - it("reads raw values the way the renderers do", () => { - expect(toNumberValue("10.00")).toBe(10); - expect(toNumberValue("")).toBeNull(); - expect(toNumberValue("abc")).toBeNull(); - expect(toTextValue("")).toBeNull(); - expect(toTextValue(42)).toBe("42"); - }); - - it("formats numbers without grouping, exponents, or precision loss", () => { - expect(toNumberEditText(1234567.5)).toBe("1234567.5"); - expect(toNumberEditText(0.1 + 0.2)).toBe("0.30000000000000004"); - expect(toNumberEditText(1234567890123456)).toBe("1234567890123456"); - expect(toNumberEditText(1e21)).toBe("1000000000000000000000"); - expect(toNumberEditText(null)).toBe(""); - for (const value of [Number.MAX_SAFE_INTEGER, Number.MIN_VALUE, 1e-30, 1.2345678901234567]) { - expect(parseNumberText(toNumberEditText(value))).toBe(value); - } - }); -}); +import { optionLabel, resolveBadgeOptions } from "./cell-values"; describe("choices", () => { const choices = [ @@ -130,70 +33,3 @@ describe("choices", () => { ); }); }); - -describe("dates", () => { - it("recognises date-only strings", () => { - expect(isIsoDate("2026-10-02")).toBe(true); - expect(isIsoDate("2026-10-02T09:00:00Z")).toBe(false); - expect(isIsoDate(20261002)).toBe(false); - }); - - it("converts cell values to the calendar day and local time they show", () => { - expect(toCalendarDate("2026-10-02")?.toString()).toBe("2026-10-02"); - expect(toCalendarDate(new Date(2026, 9, 2, 23, 30))?.toString()).toBe("2026-10-02"); - expect(toCalendarDate(null)).toBeNull(); - expect(toTimeText(new Date(2026, 9, 2, 9, 5))).toBe("09:05"); - expect(toTimeText("2026-10-02")).toBe(""); - expect(toTimeText(undefined)).toBe(""); - }); - - it("builds an ISO timestamp from a day and a local time", () => { - const day = toCalendarDate("2026-10-20")!; - expect(toIsoDateTime(day, "14:30")).toBe(new Date(2026, 9, 20, 14, 30).toISOString()); - expect(toIsoDateTime(day, "")).toBeUndefined(); - }); - - it("does not fill or coerce an incomplete or invalid time", () => { - const day = toCalendarDate("2026-10-20")!; - for (const time of ["", "14:", "9:05", "24:00", "12:60", "-1:00", "abc"]) { - expect(toIsoDateTime(day, time)).toBeUndefined(); - } - expect(toIsoDateTime(day, "00:00", "Asia/Tokyo")).toBe("2026-10-19T15:00:00.000Z"); - }); - - it("initializes and commits date-times in the configured timezone", () => { - const zone = "America/New_York"; - const value = "2026-10-09T00:00:00Z"; - expect(toCalendarDate(value, zone)?.toString()).toBe("2026-10-08"); - expect(toTimeText(value, zone)).toBe("20:00"); - expect(toCalendarDate("2026-10-09", zone)?.toString()).toBe("2026-10-09"); - expect(toIsoDateTime(toCalendarDate("2026-10-08")!, "20:00", zone)).toBe( - "2026-10-09T00:00:00.000Z", - ); - expect(sameDate(value, "2026-10-08", false, zone)).toBe(true); - expect(sameDate("2026-10-08T20:00", value, true, zone)).toBe(true); - expect(toIsoDateTime(toCalendarDate("2026-12-08")!, "20:00", zone)).toBe( - "2026-12-09T01:00:00.000Z", - ); - }); - - it("distinguishes incomplete date-only data from explicit midnight in datetime comparisons", () => { - const day = "2026-10-02"; - const midnight = "2026-10-01T15:00:00.000Z"; - expect(sameDate(day, midnight, true, "Asia/Tokyo")).toBe(false); - expect(sameDate(midnight, day, true, "Asia/Tokyo")).toBe(false); - expect(sameDate(day, null, true, "Asia/Tokyo")).toBe(false); - expect(sameDate(day, day, true, "Asia/Tokyo")).toBe(true); - expect(sameDate(day, midnight, false, "Asia/Tokyo")).toBe(true); - }); - - it("compares by day for dates and by minute for date-times", () => { - expect(sameDate("2026-10-02", new Date(2026, 9, 2, 18), false)).toBe(true); - expect(sameDate("2026-10-02", "2026-10-03", false)).toBe(false); - const at = new Date(2026, 9, 2, 14, 30, 5); - expect(sameDate(at.toISOString(), new Date(2026, 9, 2, 14, 30, 50), true)).toBe(true); - expect(sameDate(at.toISOString(), new Date(2026, 9, 2, 14, 31), true)).toBe(false); - expect(sameDate(null, undefined, false)).toBe(true); - expect(sameDate(null, "2026-10-02", false)).toBe(false); - }); -}); diff --git a/packages/core/src/components/data-table/cell-values.ts b/packages/core/src/components/data-table/cell-values.ts index 086ef8975..53ee0a081 100644 --- a/packages/core/src/components/data-table/cell-values.ts +++ b/packages/core/src/components/data-table/cell-values.ts @@ -1,90 +1,13 @@ -/** - * Pure helpers behind DataTable's inline cell editing: how typed or pasted text - * becomes a value and whether a draft is a real change or a cosmetic one - * (`10` vs `10.00`). Business validation belongs to the consumer. - * - * @internal - */ - -import { - CalendarDate, - CalendarDateTime, - getLocalTimeZone, - parseDate, - toZoned, -} from "@internationalized/date"; -import { localDateTimeParts, normalizeTemporalFilterValue } from "@/lib/temporal-filter-values"; import type { SelectOption } from "@/types/collection"; import type { BadgeCellOptions, DataTableFilterConfig } from "./types"; -// Thousands grouping with commas, e.g. "1,234,567.89". -const GROUPED_NUMBER = /^-?\d{1,3}(?:,\d{3})+(?:\.\d*)?$/; - -/** - * Cleans number text before it's checked: full-width digits and signs become - * ASCII, whitespace and currency symbols are dropped, and commas are removed - * only when they form strict thousands groups — so "1,234.5" becomes "1234.5", - * while "1,5" is left alone to fail as "not a number" instead of silently - * turning into 15. - */ -export function normalizeNumberText(text: string): string { - const compact = text - .normalize("NFKC") - .replace(/[\s\p{Sc}]/gu, "") - .replace(/^−/, "-"); - return GROUPED_NUMBER.test(compact) ? compact.replace(/,/g, "") : compact; -} - -/** `""` → `null`, `"5."` → `5`; `"-"`, `"."` and anything non-numeric → `undefined`. */ -export function parseNumberText(text: string): number | null | undefined { - const trimmed = text.trim(); - if (trimmed === "") return null; - if (!/^-?(?:\d+\.?\d*|\.\d+)$/.test(trimmed)) return undefined; - const value = Number(trimmed); - if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER) return undefined; - // `+ 0` folds -0 into 0 so "-0" doesn't read as a change from 0. - return value + 0; -} - -/** Reads a raw cell value as a number the way the `number` renderer does. */ -export function toNumberValue(raw: unknown): number | null { - if (raw == null || raw === "") return null; - const value = typeof raw === "number" ? raw : Number(raw); - return Number.isFinite(value) ? value : null; -} - -/** Reads a raw cell value as text; `null`, `undefined` and `""` are all empty. */ -export function toTextValue(raw: unknown): string | null { - if (raw == null || raw === "") return null; - return String(raw); -} - -/** Compare parsed values exactly; rounding belongs to the consumer. */ -export function sameNumber(a: number | null, b: number | null): boolean { - return a === b; -} - -/** Plain edit text preserves the value without grouping or exponent notation. */ -export function toNumberEditText(value: number | null): string { - if (value === null) return ""; - return value.toLocaleString("en-US", { - useGrouping: false, - maximumSignificantDigits: 21, - }); -} - -// ── Choices (dropdown and badge editors) ───────────────────────────────────── - /** The label a choice shows, or the raw value when it isn't one of the choices. */ export function optionLabel(options: readonly SelectOption[] | undefined, value: unknown): unknown { if (!options || value == null || value === "") return value; return options.find((option) => option.value === String(value))?.label ?? value; } -/** - * The choices a badge column offers: `edit.options`, else the entries of - * `typeOptions.badgeLabelMap`, else the column's enum filter options. - */ +/** Choices retain DataTable's edit options, badge labels, then enum-filter fallback. */ export function resolveBadgeOptions( options: readonly SelectOption[] | undefined, typeOptions: BadgeCellOptions | undefined, @@ -96,71 +19,3 @@ export function resolveBadgeOptions( if (filter?.type === "enum") return filter.options; return []; } - -// ── Dates ──────────────────────────────────────────────────────────────────── - -const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; - -/** Whether `value` is a date-only ISO string (`"YYYY-MM-DD"`). */ -export function isIsoDate(value: unknown): value is string { - return typeof value === "string" && ISO_DATE.test(value); -} - -/** A raw date cell value as the calendar day it shows. */ -export function toCalendarDate(raw: unknown, timeZone = getLocalTimeZone()): CalendarDate | null { - const date = normalizeTemporalFilterValue("date", raw, timeZone); - if (!date) return null; - try { - return parseDate(date); - } catch { - return null; - } -} - -/** The zoned time of a raw date cell value as `"HH:mm"`; `""` when there is none. */ -export function toTimeText(raw: unknown, timeZone = getLocalTimeZone()): string { - if (isIsoDate(raw)) return ""; - const datetime = normalizeTemporalFilterValue("datetime", raw, timeZone); - return datetime ? localDateTimeParts(datetime, timeZone).time : ""; -} - -/** A calendar day plus a zoned `"HH:mm"` as an ISO 8601 timestamp. */ -export function toIsoDateTime( - day: CalendarDate, - time: string, - timeZone = getLocalTimeZone(), -): string | undefined { - if (!/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)) return undefined; - const [hours, minutes] = time.split(":").map(Number); - return toZoned(new CalendarDateTime(day.year, day.month, day.day, hours, minutes), timeZone) - .toDate() - .toISOString(); -} - -/** - * Whether two raw date values mean the same thing: the same day for a date - * column, the same minute for a date-time one — so `"2026-10-02"` equals a - * `Date` for that day, and string formatting differences don't count. - */ -export function sameDate( - a: unknown, - b: unknown, - withTime: boolean, - timeZone = getLocalTimeZone(), -): boolean { - if (!withTime) { - const left = toCalendarDate(a, timeZone); - const right = toCalendarDate(b, timeZone); - return left && right ? left.compare(right) === 0 : left === right; - } - // Date-only data is incomplete in a datetime editor, not implicit midnight. - if (isIsoDate(a) || isIsoDate(b)) return a === b; - const asInstant = (raw: unknown) => { - const normalized = normalizeTemporalFilterValue("datetime", raw, timeZone); - return normalized ? new Date(normalized) : null; - }; - const left = asInstant(a); - const right = asInstant(b); - if (!left || !right) return left === right; - return Math.floor(left.getTime() / 60_000) === Math.floor(right.getTime() / 60_000); -} diff --git a/packages/core/src/components/data-table/column-layout.ts b/packages/core/src/components/data-table/column-layout.ts index c1f1b8d6e..34dc41fea 100644 --- a/packages/core/src/components/data-table/column-layout.ts +++ b/packages/core/src/components/data-table/column-layout.ts @@ -1,14 +1,11 @@ import type { CSSProperties } from "react"; import { cn } from "@/lib/utils"; +import { getDisplayCellAdapter } from "@/components/internals/table-core"; import type { Column } from "./types"; -// Resolve the effective horizontal alignment for a column. Numeric `type` -// values default to `"right"` so digits line up along their decimal place; -// everything else defaults to `"left"`. Explicit `col.align` always wins. +// Explicit alignment overrides the display adapter's default, shared by header, body, and footer. function resolveAlign>(col: Column): "left" | "right" { - if (col.align) return col.align; - if (col.type === "number" || col.type === "money") return "right"; - return "left"; + return col.align ?? getDisplayCellAdapter(col.type).defaultAlign; } // Fallback widths of the built-in selection / row-actions columns, used as the diff --git a/packages/core/src/components/data-table/date-time-draft.test-d.ts b/packages/core/src/components/data-table/date-time-draft.test-d.ts new file mode 100644 index 000000000..c3f268cd3 --- /dev/null +++ b/packages/core/src/components/data-table/date-time-draft.test-d.ts @@ -0,0 +1,21 @@ +import { expectTypeOf, test } from "vitest"; +import type { DateCellEditOptions, DateTimeDraft } from "@/index"; +import type { DateTimeDraft as DataTableDateTimeDraft } from "./index"; +import type { DateTimeDraft as InternalDateTimeDraft } from "@/components/internals/table-core/editing/date"; + +type Row = { id: string; date: string | null }; + +test("DateTimeDraft remains available through the public entrypoints", () => { + expectTypeOf().toEqualTypeOf<{ + day: string | null; + time: string | null; + }>(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); +}); + +test("date change callbacks use the same public DateTimeDraft", () => { + type Draft = Parameters["onValueChange"]>>[1]; + expectTypeOf().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); +}); diff --git a/packages/core/src/components/data-table/editing/cell/choice.tsx b/packages/core/src/components/data-table/editing/cell/choice.tsx index 99655f1f0..a0739334b 100644 --- a/packages/core/src/components/data-table/editing/cell/choice.tsx +++ b/packages/core/src/components/data-table/editing/cell/choice.tsx @@ -1,29 +1,9 @@ -import { - useMemo, - useRef, - useState, - type ComponentProps, - type FocusEvent, - type MouseEvent, - type TouchEvent, -} from "react"; -import { Combobox as BaseCombobox } from "@base-ui/react/combobox"; -import { ChevronDown } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { isComposing } from "@/lib/is-composing"; import { BadgeList } from "@/components/badge-list"; -import { ComboboxParts } from "@/components/combobox"; -import { toTextValue } from "../../cell-values"; -import { useDataTableT } from "../../i18n"; -import { useCellEditSession } from "../use-session"; +import { EditableCell } from "@/components/internals/table-core/editing/cell"; +import { choiceEditor } from "@/components/internals/table-core/editing/choice"; import { - CELL_ERROR_CLASS_NAME, - ICON_INPUT_CLASS_NAME, - INPUT_CLASS_NAME, - EditableCellFrame, columnChoices, - useCellValue, - useNavigationRef, + useEditorProps, type EditableColumn, type DataTableEditableCellProps, } from "./shared"; @@ -33,353 +13,24 @@ type ChoiceColumn> = Extract< { type: "text" | "link" | "badge" } >; -/** One dropdown choice; `value: null` is "None". */ -interface Choice { - value: string | null; - label: string; -} - -type ChoiceDraft = Choice & { notified?: boolean }; - -// Case- and width-insensitive searching: full-width letters and half-width -// katakana match their usual forms. -const searchable = (text: string) => text.normalize("NFKC").toLocaleLowerCase().trim(); - -const isChoiceEqual = (a: Choice, b: Choice) => a.value === b.value; - -const choiceLabel = (choice: Choice) => choice.label; - -export function ChoiceEditCell>({ - row, - col, - rowKey, - colKey, - label, - align, - navigation, - cellProps, - tooltipLabel, -}: DataTableEditableCellProps>) { - const t = useDataTableT(); - const session = useCellEditSession(col.edit?.error !== false); - const { state } = session; - const { current, display, change, commit, callbackError, containsErrorTarget } = useCellValue( - row, - col, - state.status === "failed" ? state : undefined, - ); - const register = useNavigationRef(navigation, rowKey, colKey); - const value = toTextValue(current); - const noneLabel = t("editNone"); - const choices = columnChoices(col); - // Keyed on content: rebuilding columns must not reset the highlight mid-search. - const choicesKey = (choices ?? []).map((c) => `${c.value}\u0000${c.label}`).join("\u0001"); - const items = useMemo( - () => [ - { value: null, label: noneLabel }, - ...(choices ?? []).map((c) => ({ value: c.value, label: String(c.label) })), - ], - // eslint-disable-next-line react-hooks/exhaustive-deps -- `choicesKey` stands for `choices`. - [choicesKey, noneLabel], - ); - - const selected = items.find((item) => item.value === value) ?? null; - const [open, setOpen] = useState(false); - const [focused, setFocused] = useState(false); - const editing = state.status !== "idle"; - const activeChoice = state.status === "idle" ? selected : state.draft; - // The displayed search text is local while editing, even if consumer data changes. - const [query, setQuery] = useState(null); - // Keep the closing list filtered until its animation completes. - const [listQuery, setListQuery] = useState(null); - const highlightedRef = useRef(undefined); - const explicitHighlightRef = useRef(undefined); - const composingRef = useRef(false); - const selectOnMouseUpRef = useRef(false); - const from = { rowKey, colKey }; - - const filtered = useMemo(() => { - const search = searchable(listQuery ?? ""); - if (!search) return items; - const rank = (item: Choice) => { - const text = searchable(item.label); - if (text === search) return 0; - return text.startsWith(search) ? 1 : 2; - }; - return ( - items - .filter((item) => item.value !== null && searchable(item.label).includes(search)) - // Sorting is stable, preserving the original order within each rank. - .toSorted((left, right) => rank(left) - rank(right)) - ); - }, [items, listQuery]); - - const startEditing = () => { - session.begin(selected ?? { value, label: value ?? noneLabel }); - setQuery(selected?.label ?? ""); - setListQuery(null); - highlightedRef.current = undefined; - explicitHighlightRef.current = undefined; - }; - - const closeEditor = () => { - setQuery(null); - explicitHighlightRef.current = undefined; - setOpen(false); - }; - - const cancelEditing = () => { - const active = session.getState(); - session.cancel( - active.status !== "idle" && active.draft.notified && active.draft.value !== value - ? () => change(value) - : undefined, - ); - closeEditor(); - }; - - const leaveEditor = () => { - const active = session.getState(); - if (active.status === "failed" || active.status === "confirming") closeEditor(); - else cancelEditing(); - }; - - const pick = (item: Choice) => { - const active = session.getState(); - if (active.status === "confirming" && active.draft.value === item.value) return; - session.change( - { ...item, notified: item.value !== value }, - item.value !== value ? () => change(item.value) : undefined, - ); - setQuery(item.label); - session.confirm(() => (item.value !== value ? commit(item.value) : undefined), closeEditor); - }; - - const explicitCandidate = () => { - const item = explicitHighlightRef.current; - return item && filtered.includes(item) ? item : undefined; - }; - - const keyboardCandidate = () => { - const highlighted = highlightedRef.current; - return ( - explicitCandidate() ?? - (highlighted && filtered.includes(highlighted) ? highlighted : filtered[0]) - ); - }; - - const handleKeyDown: NonNullable["onKeyDown"]> = ( - event, - ) => { - if (isComposing(event.nativeEvent, composingRef.current)) { - event.preventBaseUIHandler(); - return; - } - switch (event.key) { - case "Enter": { - event.preventDefault(); - event.preventBaseUIHandler(); - const active = session.getState(); - if (active.status === "confirming") return; - if (!open) { - if (active.status === "failed" && active.source === "commit") { - session.confirm( - () => (active.draft.value !== value ? commit(active.draft.value) : undefined), - closeEditor, - ); - return; - } - if (active.status === "idle") startEditing(); - setOpen(true); - return; - } - const item = keyboardCandidate(); - if (item) pick(item); - else leaveEditor(); - return; - } - case "Tab": { - event.preventBaseUIHandler(); - const item = - session.getState().status !== "idle" && open - ? (explicitCandidate() ?? - (searchable(listQuery ?? "") ? keyboardCandidate() : undefined)) - : undefined; - if (item) pick(item); - else leaveEditor(); - if (navigation.move(from, event.shiftKey ? "prev" : "next")) event.preventDefault(); - return; - } - case "Escape": - if (session.getState().status === "idle" && !open) return; - event.preventDefault(); - event.stopPropagation(); - event.preventBaseUIHandler(); - cancelEditing(); - return; - } - }; - - const handleFocus = (event: FocusEvent) => { - const withinCell = focused || containsErrorTarget(event.relatedTarget); - setFocused(true); - if (withinCell) return; - if (session.getState().status === "idle") startEditing(); - event.currentTarget.select(); - }; - - const handleBlur = () => { - setFocused(false); - leaveEditor(); - }; - - const handleMouseDown = (event: MouseEvent) => { - if (event.button === 2 && session.getState().status === "idle") { - event.preventDefault(); - return; - } - if (session.getState().status === "idle") { - startEditing(); - setOpen(true); - } - if (!focused) selectOnMouseUpRef.current = true; - }; - - const handleMouseUp = (event: MouseEvent) => { - if (!selectOnMouseUpRef.current) return; - selectOnMouseUpRef.current = false; - event.preventDefault(); - }; - - const stopWhileEditing = (event: MouseEvent | TouchEvent) => { - if (session.getState().status !== "idle") event.stopPropagation(); - }; - - const renderChoice = (item: Choice) => { - if (item.value === null) - return {item.label}; - if (col.type !== "badge") return item.label; - return ( - item.label} /> - ); - }; - +export function ChoiceEditCell>( + props: DataTableEditableCellProps>, +) { + const coreProps = useEditorProps(props); + const { col } = props; return ( - } - tooltipLabel={tooltipLabel} - editing={editing} - callbackError={callbackError} - label={label} - onEditorLeave={handleBlur} - onEditorCancel={cancelEditing} - getFailure={session.getFailure} - confirming={state.status === "confirming"} - > - - items={items} - filteredItems={filtered} - value={activeChoice} - onValueChange={(item, details) => { - if (details.reason === "item-press" && item) pick(item); - }} - inputValue={query ?? activeChoice?.label ?? ""} - onInputValueChange={(next, details) => { - if (details.reason === "input-change" || details.reason === "input-clear") { - const active = session.getState(); - session.change( - active.status === "idle" - ? (selected ?? { value, label: value ?? noneLabel }) - : active.draft, - ); - setQuery(next); - setListQuery(next); - explicitHighlightRef.current = undefined; - } - }} - open={open} - onOpenChange={(next, details) => { - if (next) { - if (session.getState().status === "idle") startEditing(); - setOpen(true); - if (details.reason !== "input-change") setListQuery(null); - return; - } - if ( - containsErrorTarget(details.event.target) || - ("relatedTarget" in details.event && - containsErrorTarget(details.event.relatedTarget as EventTarget | null)) - ) { - details.cancel(); - return; - } - // Clearing search text is not selection or cancellation. - if (details.reason === "input-clear") { - setOpen(false); - return; - } - if (details.reason === "escape-key") cancelEditing(); - else leaveEditor(); - }} - onOpenChangeComplete={(isOpen) => { - if (!isOpen) setListQuery(null); - }} - onItemHighlighted={(item, details) => { - // Hover is visual feedback, not a keyboard confirmation candidate. - if (details.reason === "pointer") return; - highlightedRef.current = item; - if (item && details.reason === "keyboard") explicitHighlightRef.current = item; - }} - autoHighlight - itemToStringLabel={choiceLabel} - isItemEqualToValue={isChoiceEqual} - > - { - composingRef.current = true; - }} - onCompositionEnd={() => { - composingRef.current = false; - }} - /> - {/* At least as wide as the cell, and wide enough that choices don't wrap. */} - - {t("editNoMatches")} - - {(item: Choice) => ( - - {renderChoice(item)} - - )} - - - - + ( + label} /> + ) + : undefined, + }} + /> ); } diff --git a/packages/core/src/components/data-table/editing/cell/date.tsx b/packages/core/src/components/data-table/editing/cell/date.tsx index 5b707f05a..4701678fb 100644 --- a/packages/core/src/components/data-table/editing/cell/date.tsx +++ b/packages/core/src/components/data-table/editing/cell/date.tsx @@ -1,246 +1,23 @@ -import { useState, type KeyboardEvent } from "react"; -import { Popover } from "@base-ui/react/popover"; -import type { CalendarDate } from "@internationalized/date"; -import { CalendarDays } from "lucide-react"; -import { cn } from "@/lib/utils"; import { useTimeZone } from "@/contexts/appshell-context"; -import { Button } from "@/components/button"; -import { Calendar } from "@/components/calendar"; -import { Input } from "@/components/input"; -import type { DateTimeDraft } from "../../types"; -import { sameDate, toCalendarDate, toIsoDateTime, toTimeText } from "../../cell-values"; -import { useDataTableT } from "../../i18n"; -import type { CellEditNavigation } from "../use-navigation"; -import { useCellEditSession } from "../use-session"; -import { - OVERLAY_CLASS_NAME, - CELL_FOCUS_CLASS_NAME, - CELL_ERROR_CLASS_NAME, - POPUP_CLASS_NAME, - EditableCellFrame, - useCellValue, - useNavigationRef, - type EditableColumn, - type DataTableEditableCellProps, -} from "./shared"; +import { EditableCell } from "@/components/internals/table-core/editing/cell"; +import { dateEditor } from "@/components/internals/table-core/editing/date"; +import { useEditorProps, type EditableColumn, type DataTableEditableCellProps } from "./shared"; type DateColumn> = Extract< EditableColumn, { type: "date" } >; -// Date cells: a transparent button over the cell's own display, with a pointer. -const TRIGGER_CLASS_NAME = cn( - OVERLAY_CLASS_NAME, - CELL_FOCUS_CLASS_NAME, - "astw:cursor-pointer", - "astw:data-popup-open:ring-2 astw:data-popup-open:ring-inset astw:data-popup-open:ring-primary", -); - -// Tab / Shift+Tab from a closed calendar moves between editable cells, the -// same way it does from a typing cell. -function tabBetweenCells( - event: KeyboardEvent, - open: boolean, - navigation: CellEditNavigation, - from: { rowKey: string; colKey: string }, +export function DateEditCell>( + props: DataTableEditableCellProps>, ) { - if (event.key !== "Tab" || open) return; - if (navigation.move(from, event.shiftKey ? "prev" : "next")) event.preventDefault(); -} - -export function DateEditCell>({ - row, - col, - rowKey, - colKey, - label, - navigation, - cellProps, - tooltipLabel, - dateRenderer, -}: DataTableEditableCellProps>) { - const t = useDataTableT(); + const coreProps = useEditorProps(props); const { value: timeZone } = useTimeZone(); - const withTime = col.typeOptions?.dateFormat === "datetime"; - const session = useCellEditSession(col.edit?.error !== false); - const { state } = session; - const { current, display, change, commit, callbackError, containsErrorTarget } = useCellValue( - row, - col, - state.status === "failed" ? state : undefined, - dateRenderer, - ); - const register = useNavigationRef(navigation, rowKey, colKey); - const baseline: DateTimeDraft = { - day: toCalendarDate(current, timeZone)?.toString() ?? null, - time: toTimeText(current, timeZone) || null, - }; - const [open, setOpen] = useState(false); - const differs = (a: DateTimeDraft, b: DateTimeDraft) => - a.day !== b.day || (withTime && a.time !== b.time); - const notifyDraft = (next: DateTimeDraft) => change(withTime ? { ...next } : next.day); - const setDraft = (next: DateTimeDraft) => { - const active = session.getState(); - const previous = active.status === "idle" ? baseline : active.draft; - if (!differs(previous, next)) { - session.begin(next); - return; - } - session.change(next, () => notifyDraft(next)); - }; - const cancelEditing = () => { - const active = session.getState(); - session.cancel( - active.status !== "idle" && differs(active.draft, baseline) - ? () => notifyDraft(baseline) - : undefined, - ); - setOpen(false); - }; - const finish = (next: string | null) => { - session.confirm( - () => (sameDate(next, current, withTime, timeZone) ? undefined : commit(next)), - () => setOpen(false), - ); - }; - const activeDraft = state.status === "idle" ? baseline : state.draft; - const pickedDay = toCalendarDate(activeDraft.day, timeZone); - const timestamp = - withTime && pickedDay && activeDraft.time - ? toIsoDateTime(pickedDay, activeDraft.time, timeZone) - : undefined; - const draftDisplay = withTime - ? `${activeDraft.day ?? "—"} ${activeDraft.time ?? "—"}` - : (activeDraft.day ?? "—"); - const visibleDisplay = state.status === "idle" ? display : draftDisplay; - // The trigger's accessible name carries the date hidden in the visual display. - const accessibleName = typeof visibleDisplay === "string" ? `${label}, ${visibleDisplay}` : label; - - const handleOpenChange = (next: boolean, details?: Popover.Root.ChangeEventDetails) => { - if ( - !next && - details && - (containsErrorTarget(details.event.target) || - ("relatedTarget" in details.event && - containsErrorTarget(details.event.relatedTarget as EventTarget | null))) - ) { - details.cancel(); - return; - } - if (next) { - session.begin(baseline); - } else { - const active = session.getState(); - if ( - details?.reason === "escape-key" || - (active.status !== "failed" && active.status !== "confirming") - ) { - cancelEditing(); - return; - } - } - setOpen(next); - }; - - const handlePick = (day: CalendarDate) => { - const active = session.getState(); - setDraft({ ...(active.status === "idle" ? baseline : active.draft), day: day.toString() }); - if (!withTime) finish(day.toString()); - }; - return ( - } - tooltipLabel={tooltipLabel} - editing={open} - callbackError={callbackError} - label={label} - onEditorCancel={cancelEditing} - getFailure={session.getFailure} - confirming={state.status === "confirming"} - > - - { - if (event.key === "Escape" && !open && session.getState().status !== "idle") { - event.preventDefault(); - event.stopPropagation(); - cancelEditing(); - return; - } - if (event.key === "ArrowDown" && !open) { - event.preventDefault(); - handleOpenChange(true); - return; - } - tabBetweenCells(event, open, navigation, { rowKey, colKey }); - }} - /> - - - event.stopPropagation()} - onTouchStart={(event) => event.stopPropagation()} - > - - {withTime && ( - - setDraft({ - ...activeDraft, - time: event.target.value || null, - }) - } - className="astw:h-8 astw:text-body-md" - /> - )} - - { - setDraft({ day: null, time: null }); - finish(null); - }} - > - {t("editClear")} - - {withTime && ( - { - if (timestamp !== undefined) finish(timestamp); - }} - > - {t("editDone")} - - )} - - - - - - + ); } diff --git a/packages/core/src/components/data-table/editing/cell/drafts.test.tsx b/packages/core/src/components/data-table/editing/cell/drafts.test.tsx index 0348a39c5..5d2fccd34 100644 --- a/packages/core/src/components/data-table/editing/cell/drafts.test.tsx +++ b/packages/core/src/components/data-table/editing/cell/drafts.test.tsx @@ -5,10 +5,10 @@ import type { BadgeCellEditOptions, CellEditState, DateCellEditOptions, - DateTimeDraft, NumberCellEditOptions, TextCellEditOptions, } from "@/index"; +import type { DateTimeDraft } from "@/components/internals/table-core/editing/date"; import { createAppShellWrapper } from "../../../../../tests/test-utils"; import { DataTable } from "../../data-table"; import { useDataTable } from "../../use-data-table"; diff --git a/packages/core/src/components/data-table/editing/cell/errors.test.tsx b/packages/core/src/components/data-table/editing/cell/errors.test.tsx index 81b958a1d..051b4b208 100644 --- a/packages/core/src/components/data-table/editing/cell/errors.test.tsx +++ b/packages/core/src/components/data-table/editing/cell/errors.test.tsx @@ -17,6 +17,12 @@ afterEach(() => { type Row = { id: string; value: string | null }; const ROWS: Row[] = [{ id: "1", value: "Original" }]; const noop = () => {}; +const descriptionText = (input: HTMLElement) => + input + .getAttribute("aria-describedby") + ?.split(/\s+/) + .map((id) => document.getElementById(id)?.textContent) + .join(" "); function Harness({ edit, rows = ROWS }: { edit: TextCellEditOptions; rows?: Row[] }) { const columns: Column[] = [{ id: "value", label: "Value", type: "text", edit }]; @@ -129,9 +135,7 @@ describe("DataTable callback error presentation", () => { if (source === "commit") fireEvent.keyDown(input, { key: "Enter" }); expect(input.getAttribute("aria-invalid")).toBe("true"); - expect( - document.getElementById(input.getAttribute("aria-describedby")!)?.textContent, - ).toContain(failure.message); + expect(descriptionText(input)).toContain(failure.message); const popup = await screen.findByRole("dialog", { name: "Error in Value" }); expect(within(popup).getByText(failure.message)).toBeDefined(); expect(within(popup).getByRole("button", { name: "Close error details" })).toBeDefined(); @@ -355,8 +359,8 @@ describe("DataTable callback error presentation", () => { change(input); const popup = await screen.findByRole("dialog", { name: "Error in Value" }); expect(within(popup).getByText("Could not confirm this change")).toBeDefined(); - expect(document.getElementById(input.getAttribute("aria-describedby")!)?.textContent).toBe( - "Could not confirm this change. Press Alt+ArrowDown for error details", + expect(descriptionText(input)).toBe( + "Could not confirm this change Press Alt+ArrowDown for error details", ); expect(popup.textContent).toBe("Could not confirm this change"); expect(input.value).toBe("Changed"); @@ -376,8 +380,8 @@ describe("DataTable callback error presentation", () => { await rejectRequest(request, new Error("Internal server details")); const popup = await screen.findByRole("dialog", { name: "Error in Value" }); expect(popup.textContent).toBe("Could not confirm this change"); - expect(document.getElementById(input.getAttribute("aria-describedby")!)?.textContent).toBe( - "Could not confirm this change. Press Alt+ArrowDown for error details", + expect(descriptionText(input)).toBe( + "Could not confirm this change Press Alt+ArrowDown for error details", ); expect(input.value).toBe("Changed"); expect(input.getAttribute("aria-invalid")).toBe("true"); @@ -398,8 +402,8 @@ describe("DataTable callback error presentation", () => { const popup = await screen.findByRole("dialog", { name: "Error in Value" }); expect(popup.textContent).toBe("Custom feedback"); expect(renderError).toHaveBeenCalledWith({ row: ROWS[0], error: failure }); - expect(document.getElementById(input.getAttribute("aria-describedby")!)?.textContent).toBe( - "Could not confirm this change. Press Alt+ArrowDown for error details", + expect(descriptionText(input)).toBe( + "Could not confirm this change Press Alt+ArrowDown for error details", ); }); @@ -420,9 +424,7 @@ describe("DataTable callback error presentation", () => { const popup = await screen.findByRole("dialog", { name: "Valueのエラー" }); expect(within(popup).getByText(message)).toBeDefined(); expect(within(popup).getByRole("button", { name: "エラーの詳細を閉じる" })).toBeDefined(); - expect(document.getElementById(input.getAttribute("aria-describedby")!)?.textContent).toBe( - `${message}. Alt+↓キーでエラーの詳細を表示できます`, - ); + expect(descriptionText(input)).toBe(`${message} Alt+↓キーでエラーの詳細を表示できます`); }); it("clears an error on a newer successful input and ignores older rejection results", async () => { @@ -441,9 +443,7 @@ describe("DataTable callback error presentation", () => { await rejectRequest(current, new CellEditError("Current failure")); expect(input.getAttribute("aria-invalid")).toBe("true"); await rejectRequest(old, new Error("Outdated failure")); - expect(document.getElementById(input.getAttribute("aria-describedby")!)?.textContent).toContain( - "Current failure", - ); + expect(descriptionText(input)).toContain("Current failure"); fireEvent.change(input, { target: { value: "Newer" } }); expect(queryErrorTrigger()).toBeNull(); expect(input.getAttribute("aria-invalid")).toBeNull(); @@ -532,9 +532,7 @@ describe("DataTable callback error presentation", () => { await user.click(outside); expect(input.value).toBe("Changed"); expect(input.getAttribute("aria-invalid")).toBe("true"); - expect(document.getElementById(input.getAttribute("aria-describedby")!)?.textContent).toContain( - "Temporary save failure", - ); + expect(descriptionText(input)).toContain("Temporary save failure"); expect(queryErrorTrigger()).not.toBeNull(); expect(onValueCommitted).toHaveBeenCalledTimes(1); await user.click(input); @@ -583,9 +581,7 @@ describe("DataTable callback error presentation", () => { expect(input.getAttribute("aria-invalid")).toBe("true"); expect(input.closest("td")?.getAttribute("aria-busy")).toBeNull(); expect(queryErrorTrigger()).not.toBeNull(); - expect( - document.getElementById(input.getAttribute("aria-describedby")!)?.textContent, - ).toContain("Save failed"); + expect(descriptionText(input)).toContain("Save failed"); expect(screen.queryByRole("dialog")).toBeNull(); await user.click(input); @@ -709,9 +705,7 @@ describe("DataTable callback error presentation", () => { change(input); await user.keyboard("{Enter}"); expect(input.getAttribute("aria-keyshortcuts")).toBe("Alt+ArrowDown"); - expect(document.getElementById(input.getAttribute("aria-describedby")!)?.textContent).toContain( - "Press Alt+ArrowDown for error details", - ); + expect(descriptionText(input)).toContain("Press Alt+ArrowDown for error details"); await user.keyboard("{Alt>}{ArrowDown}{/Alt}"); const popup = await screen.findByRole("dialog", { name: "Error in Value" }); expect(within(popup).getByText("Not accepted")).toBeDefined(); diff --git a/packages/core/src/components/data-table/editing/cell/shared.tsx b/packages/core/src/components/data-table/editing/cell/shared.tsx index 713ed68eb..d275c85d0 100644 --- a/packages/core/src/components/data-table/editing/cell/shared.tsx +++ b/packages/core/src/components/data-table/editing/cell/shared.tsx @@ -1,39 +1,19 @@ -import { - useCallback, - useId, - useLayoutEffect, - useRef, - useState, - type ComponentProps, - type ReactNode, - type RefObject, -} from "react"; -import { Popover } from "@base-ui/react/popover"; -import { CircleAlert, X } from "lucide-react"; -import { cn } from "@/lib/utils"; +import type { ComponentProps, ReactNode } from "react"; import { useTimeZone } from "@/contexts/appshell-context"; -import { Button } from "@/components/button"; -import { Table } from "@/components/table"; -import { Tooltip } from "@/components/tooltip"; +import type { Table } from "@/components/table"; +import type { EditableCellOwnerProps } from "@/components/internals/table-core/editing/cell"; +import type { ValueRenderer } from "@/components/internals/table-core"; import type { Column } from "../../types"; import { getCellValue, renderTypedValue } from "../../cell-renderers"; -import { CellEditError } from "../../cell-edit-error"; import { resolveBadgeOptions } from "../../cell-values"; -import type { CellEditNavigation } from "../use-navigation"; import { useDataTableT } from "../../i18n"; -import type { CellEditFailure } from "../use-session"; +import type { CellEditNavigation } from "../use-navigation"; -/** - * A column whose cells can be edited in place. - * - * @internal - */ export type EditableColumn> = Extract< Column, { type: "text" | "number" | "money" | "date" | "badge" | "link" } >; -// The dropdown choices a column offers, or `undefined` when it's typed into. export function columnChoices>(col: Column) { if (col.type === "badge") return resolveBadgeOptions(col.edit?.options, col.typeOptions, col.filter); @@ -41,381 +21,54 @@ export function columnChoices>(col: Column< return undefined; } -/** - * Room for the icon a dropdown or date cell shows at its right edge (a chevron - * or a calendar; 14px plus a gap), so a value ends — or truncates — before it - * instead of running underneath. Read-only cells of the same column keep it - * too, so the column's width doesn't change as rows become editable or not. - * - * @internal - */ -export const ICON_SPACE_CLASS_NAME = "astw:pr-5"; - -// Editors cover the whole cell, end to end, instead of taking part in layout, -// so a cell becoming editable — or being edited — never changes row height or -// column width. They inherit the cell's padding (they're its direct children), -// so their text lines up exactly with the cell's own display underneath. -export const OVERLAY_CLASS_NAME = - "astw:absolute astw:inset-0 astw:h-full astw:w-full astw:p-[inherit] astw:rounded-none astw:border-0 astw:shadow-none astw:bg-transparent astw:dark:bg-transparent"; - -// Spreadsheet-style: the cell being edited outlines its edges (an inset ring, -// so it never spills onto neighbouring cells). -export const CELL_FOCUS_CLASS_NAME = cn( - "astw:outline-none astw:focus:ring-2 astw:focus:ring-inset astw:focus:ring-primary", - "astw:focus-visible:ring-2 astw:focus-visible:ring-inset astw:focus-visible:ring-primary", -); - -// Parsing and callback errors share the cell's error outline. -export const CELL_ERROR_CLASS_NAME = - "astw:ring-[1.5px] astw:ring-inset astw:ring-danger-solid astw:focus:ring-[1.5px] astw:focus:ring-danger-solid astw:focus-visible:ring-[1.5px] astw:focus-visible:ring-danger-solid"; - -// An editable cell says so at rest with a subtle tint instead of an icon. It's -// a background *image* layered over whatever colour the cell already has (the -// row's hover / selected fade, a pinned cell's opaque card), so it never -// replaces them and stays a step darker than its read-only neighbours. The -// cell being edited drops it: an untinted cell with a ring reads as "active". -// (Written out in full: Tailwind only generates classes it finds as literals.) -const EDITABLE_CELL_CLASS_NAME = cn( - "astw:[background-image:linear-gradient(color-mix(in_srgb,var(--foreground)_4%,transparent),color-mix(in_srgb,var(--foreground)_4%,transparent))]", - "astw:hover:[background-image:linear-gradient(color-mix(in_srgb,var(--foreground)_7%,transparent),color-mix(in_srgb,var(--foreground)_7%,transparent))]", - "astw:focus-within:[background-image:none]", -); - -// Text, number and dropdown cells are typed into: the whole cell shows a text -// cursor. -export const INPUT_CLASS_NAME = cn( - OVERLAY_CLASS_NAME, - CELL_FOCUS_CLASS_NAME, - "astw:text-body-md astw:cursor-text", -); - -// A dropdown's text stops before its chevron. -export const ICON_INPUT_CLASS_NAME = "astw:pr-7 astw:[td:last-child>&]:pr-11"; - -// The icon that says how a cell is edited: shown while the cell is hovered or -// being edited (the cell's tint says it's editable at rest). -// Decoration only: a click anywhere in the cell goes to the editor underneath. -const CELL_ICON_CLASS_NAME = cn( - "astw:pointer-events-none astw:absolute astw:inset-y-0 astw:right-2 astw:flex astw:items-center astw:[td:last-child>&]:right-6", - "astw:text-muted-foreground astw:opacity-0 astw:transition-opacity", - "astw:group-hover/cell:opacity-30 astw:group-focus-within/cell:opacity-30", - "astw:[&_svg]:size-3.5", -); - -export const POPUP_CLASS_NAME = cn( - "astw:bg-popover astw:text-popover-foreground astw:z-(--z-portal) astw:flex astw:flex-col astw:gap-3 astw:rounded-md astw:border astw:border-border astw:p-3 astw:shadow-md", - "astw:animate-in astw:fade-in-0 astw:zoom-in-95 astw:data-ending-style:animate-out astw:data-ending-style:fade-out-0 astw:data-ending-style:zoom-out-95", -); - -interface CellErrorUI { - failure: CellEditFailure; - id: string; - message: string; - content: ReactNode; - triggerRef: RefObject; - popupRef: RefObject; - containsTarget: (target: EventTarget | null) => boolean; -} - -// The standard popover body: the alert icon makes it read as an error rather -// than a tooltip. -function DefaultCellErrorContent({ message }: { message: string }) { - return ( - - {/* One line-height tall, so the icon centres on the first line of text. */} - - - - {message} - - ); -} - -export function useCellValue>( - row: TRow, - col: EditableColumn, - failure: CellEditFailure | undefined, - dateRenderer?: (row: TRow) => ReactNode, -) { +/** Bind collection-owned values, callbacks, formatting and localization to neutral cell UI. */ +export function useEditorProps>({ + row, + col, + valueRenderer, + ...props +}: DataTableEditableCellProps): EditableCellOwnerProps { const { value: timeZone } = useTimeZone(); - const current = getCellValue(row, col); - const render = col.render ?? dateRenderer; - const display = render - ? render(row) - : renderTypedValue(row, col, current, { linkAsText: true, timeZone }); const t = useDataTableT(); - const errorId = useId(); - const triggerRef = useRef(null); - const popupRef = useRef(null); - const containsErrorTarget = (target: EventTarget | null) => - target instanceof Node && - !!(triggerRef.current?.contains(target) || popupRef.current?.contains(target)); - const change = (value: unknown) => - (col.edit?.onValueChange as ((row: TRow, value: unknown) => unknown) | undefined)?.(row, value); - const commit = (value: unknown) => - (col.edit?.onValueCommitted as ((row: TRow, value: unknown) => unknown) | undefined)?.( - row, - value, - ); - const errorConfig = col.edit?.error; - const renderError = errorConfig && errorConfig.render; - const message = - failure?.error instanceof CellEditError && failure.error.message - ? failure.error.message - : t("editCallbackError"); - const callbackError: CellErrorUI | undefined = - failure && failure.source !== "parse" - ? { - failure, - id: errorId, - message: renderError ? t("editCallbackError") : message, - content: renderError ? ( - renderError({ row, error: failure.error }) - ) : ( - - ), - triggerRef, - popupRef, - containsTarget: containsErrorTarget, - } - : undefined; - return { current, display, change, commit, callbackError, containsErrorTarget }; -} - -/** - * Registers the cell's focusable element with the table's Tab - * navigation. Unregisters on every detach instead of returning a ref cleanup: - * `Input` and `Combobox.Input` merge refs with a plain callback that calls ours - * with `null` and drops any cleanup we return. - */ -export function useNavigationRef( - navigation: CellEditNavigation, - rowKey: string, - colKey: string, -) { - const unregisterRef = useRef<(() => void) | null>(null); - return useCallback( - (element: T | null) => { - unregisterRef.current?.(); - unregisterRef.current = element ? navigation.register(rowKey, colKey, element) : null; + const current = getCellValue(row, col); + const renderError = col.edit?.error && col.edit.error.render; + let display: ReactNode; + if (col.render) display = col.render(row); + else if (valueRenderer) display = valueRenderer(current, row); + else display = renderTypedValue(row, col, current, { linkAsText: true, timeZone }); + return { + ...props, + current, + display, + change: (value) => + (col.edit?.onValueChange as ((row: TRow, value: unknown) => unknown) | undefined)?.( + row, + value, + ), + commit: (value) => + (col.edit?.onValueCommitted as ((row: TRow, value: unknown) => unknown) | undefined)?.( + row, + value, + ), + renderError: renderError ? (error) => renderError({ row, error }) : undefined, + interceptErrors: col.edit?.error !== false, + truncate: col.truncate, + slotPrefix: "data-table", + labels: { + notANumber: t("editNotANumber"), + revertHint: t("editRevertHint"), + callbackError: t("editCallbackError"), + errorHint: t("editErrorHint"), + showError: t("editShowError", { label: props.label }), + errorDialog: t("editErrorDialog", { label: props.label }), + closeError: t("editCloseError"), + none: t("editNone"), + noMatches: t("editNoMatches"), + chooseTime: t("chooseTime"), + clear: t("editClear"), + done: t("editDone"), }, - [navigation, rowKey, colKey], - ); -} - -export function EditableCellFrame({ - cellProps, - display, - truncate, - hideDisplay, - icon, - tooltipLabel, - editing, - callbackError, - label, - onEditorLeave, - onEditorCancel, - getFailure, - confirming, - children, -}: { - cellProps: ComponentProps; - display: ReactNode; - truncate?: boolean; - tooltipLabel?: string; - editing: boolean; - callbackError?: CellErrorUI; - label: string; - onEditorLeave?: () => void; - onEditorCancel: () => void; - getFailure: () => CellEditFailure | undefined; - confirming: boolean; - /** Typed-into cells hide the display while the input shows the text. */ - hideDisplay?: "focused" | "forced-colors"; - /** Shown on hover or focus; the cell's tint marks editability at rest. */ - icon?: ReactNode; - children: ReactNode; -}) { - const t = useDataTableT(); - const [tooltipOpen, setTooltipOpen] = useState(false); - const [dismissedFailure, setDismissedFailure] = useState(null); - const [manuallyOpenedFailure, setManuallyOpenedFailure] = useState(null); - const [navigationDismissedFailure, setNavigationDismissedFailure] = - useState(null); - const errorActionsRef = useRef(null); - const tabNavigationRef = useRef(false); - const errorOpen = !!callbackError && dismissedFailure !== callbackError.failure; - const showTooltip = tooltipLabel !== undefined && !editing && !callbackError; - const dismissForNavigation = () => { - const failure = getFailure(); - if (!failure || failure.source === "parse") return; - setNavigationDismissedFailure(failure); - setDismissedFailure(failure); }; - useLayoutEffect(() => { - // Remove closing focus guards before native Tab chooses its destination. - if (!errorOpen && navigationDismissedFailure === callbackError?.failure) - errorActionsRef.current?.unmount(); - }, [errorOpen, callbackError?.failure, navigationDismissedFailure]); - const cell = ( - { - if ( - event.currentTarget.contains(event.relatedTarget) || - callbackError?.containsTarget(event.relatedTarget) - ) - return; - if (tabNavigationRef.current) dismissForNavigation(); - onEditorLeave?.(); - }} - onKeyDown={(event) => { - if ( - event.key === "Tab" && - !event.defaultPrevented && - event.currentTarget.contains(event.target as Node) - ) - dismissForNavigation(); - tabNavigationRef.current = false; - }} - onKeyDownCapture={(event) => { - tabNavigationRef.current = - event.key === "Tab" && event.currentTarget.contains(event.target as Node); - if ( - callbackError && - event.key === "Escape" && - !callbackError.popupRef.current?.contains(event.target as Node) - ) { - event.preventDefault(); - event.stopPropagation(); - if (errorOpen) setDismissedFailure(callbackError.failure); - else onEditorCancel(); - return; - } - if (callbackError && event.altKey && event.key === "ArrowDown") { - event.preventDefault(); - event.stopPropagation(); - setNavigationDismissedFailure(null); - setManuallyOpenedFailure(callbackError.failure); - setDismissedFailure(null); - if (errorOpen) callbackError.popupRef.current?.focus({ preventScroll: true }); - } - }} - // Editing a cell must never fire `onClickRow`. - onClick={(event) => event.stopPropagation()} - > - - {display} - - {children} - {callbackError && ( - <> - - {callbackError.message}. {t("editErrorHint")} - - { - setDismissedFailure(open ? null : callbackError.failure); - if (open) { - setNavigationDismissedFailure(null); - setManuallyOpenedFailure(callbackError.failure); - } - }} - > - event.stopPropagation()} - > - - - - {/* Opens directly under the cell, not under the small icon trigger. */} - callbackError.triggerRef.current?.closest("td") ?? null} - sideOffset={2} - side="bottom" - align="start" - > - event.stopPropagation()} - onTouchStart={(event) => event.stopPropagation()} - onKeyDown={(event) => { - if (event.key === "Escape") event.stopPropagation(); - }} - > - - {callbackError.content} - } - > - - - - - - - - > - )} - {icon !== undefined && !callbackError && ( - - {icon} - - )} - - ); - return ( - - - {tooltipLabel} - - ); } export interface DataTableEditableCellProps< @@ -431,8 +84,8 @@ export interface DataTableEditableCellProps< align: "left" | "right"; tooltipLabel?: string; navigation: CellEditNavigation; - /** Reuses the table's column-level date formatter cache. */ - dateRenderer?: (row: TRow) => ReactNode; + /** Reuses column-level preparation with the editor's already-resolved current value. */ + valueRenderer?: ValueRenderer; /** `data-slot`, style, class and context-menu handlers shared with static cells. */ cellProps: ComponentProps; } diff --git a/packages/core/src/components/data-table/editing/cell/typing.test.tsx b/packages/core/src/components/data-table/editing/cell/typing.test.tsx index de0433a12..ac6eed566 100644 --- a/packages/core/src/components/data-table/editing/cell/typing.test.tsx +++ b/packages/core/src/components/data-table/editing/cell/typing.test.tsx @@ -18,7 +18,11 @@ afterEach(() => { }); const errorText = (input: HTMLElement) => - document.getElementById(input.getAttribute("aria-describedby") ?? "")?.textContent; + input + .getAttribute("aria-describedby") + ?.split(/\s+/) + .map((id) => document.getElementById(id)?.textContent) + .join(" "); describe("DataTable inline editing", () => { describe("keyboard", () => { @@ -204,7 +208,7 @@ describe("DataTable inline editing", () => { expect(input.getAttribute("aria-invalid")).toBeNull(); await user.keyboard("{Enter}"); expect(input.getAttribute("aria-invalid")).toBe("true"); - expect(errorText(input)).toBe("Enter a number. Press Esc to undo"); + expect(errorText(input)).toBe("Enter a number Press Esc to undo"); expect(document.activeElement).toBe(input); await user.tab(); expect(document.activeElement).toBe(input); @@ -249,7 +253,7 @@ describe("DataTable inline editing", () => { ); const [input] = screen.getAllByRole("textbox", { name: "Received" }); await retype(user, input, "abc{Enter}"); - expect(errorText(input)).toBe("数値を入力してください. Escキーで元に戻せます"); + expect(errorText(input)).toBe("数値を入力してください Escキーで元に戻せます"); }); }); diff --git a/packages/core/src/components/data-table/editing/cell/typing.tsx b/packages/core/src/components/data-table/editing/cell/typing.tsx index 90e39553e..f4a87c123 100644 --- a/packages/core/src/components/data-table/editing/cell/typing.tsx +++ b/packages/core/src/components/data-table/editing/cell/typing.tsx @@ -1,261 +1,15 @@ -import { - useId, - useRef, - useState, - type ChangeEvent, - type FocusEvent, - type KeyboardEvent, - type MouseEvent, - type TouchEvent, -} from "react"; -import { cn } from "@/lib/utils"; -import { isComposing } from "@/lib/is-composing"; -import { Input } from "@/components/input"; -import { Tooltip } from "@/components/tooltip"; -import { - normalizeNumberText, - parseNumberText, - sameNumber, - toNumberEditText, - toNumberValue, - toTextValue, -} from "../../cell-values"; -import { useDataTableT } from "../../i18n"; -import { useCellEditSession } from "../use-session"; -import { - CELL_ERROR_CLASS_NAME, - ICON_INPUT_CLASS_NAME, - INPUT_CLASS_NAME, - EditableCellFrame, - useCellValue, - useNavigationRef, - type DataTableEditableCellProps, -} from "./shared"; - -export function TypingEditCell>({ - row, - col, - rowKey, - colKey, - label, - align, - navigation, - cellProps, - tooltipLabel, -}: DataTableEditableCellProps) { - const t = useDataTableT(); - const errorId = useId(); - const session = useCellEditSession(col.edit?.error !== false); - const { state } = session; - const failure = state.status === "failed" ? state : undefined; - const { current, display, change, commit, callbackError, containsErrorTarget } = useCellValue( - row, - col, - failure, - ); - const register = useNavigationRef(navigation, rowKey, colKey); - const editing = state.status !== "idle"; - const [focused, setFocused] = useState(false); - const [hovered, setHovered] = useState(false); - const composingRef = useRef(false); - const selectOnMouseUpRef = useRef(false); - - const numeric = col.type === "number" || col.type === "money"; - const baselineText = numeric - ? toNumberEditText(toNumberValue(current)) - : (toTextValue(current) ?? ""); - const text = state.status === "idle" ? baselineText : state.draft; - const message = failure?.source === "parse" ? t("editNotANumber") : undefined; - - const revert = (notify = false) => { - const previous = session.getState(); - session.cancel( - notify && previous.status !== "idle" && previous.draft !== baselineText - ? () => change(baselineText) - : undefined, - ); - }; - - const commitDraft = (): boolean => { - const active = session.getState(); - if (active.status === "idle" || active.status === "confirming") return true; - const draftText = active.draft; - const value = numeric - ? parseNumberText(normalizeNumberText(draftText)) - : toTextValue(draftText); - if (value === undefined) { - session.fail(undefined, "parse"); - return false; - } - const unchanged = - draftText === baselineText || - (numeric - ? sameNumber(value as number | null, toNumberValue(current)) - : value === toTextValue(current)); - session.confirm(() => (unchanged ? undefined : commit(value))); - return true; - }; - - const handleChange = (event: ChangeEvent) => { - const next = event.target.value; - const active = session.getState(); - const previous = active.status === "idle" ? baselineText : active.draft; - if (next !== previous) session.change(next, () => change(next)); - }; - - // Keep IME output raw until cell confirmation, just like other draft changes. - const handleCompositionEnd = () => { - composingRef.current = false; - }; - - const handleKeyDown = (event: KeyboardEvent) => { - // While an IME is composing, Enter confirms the conversion, not the cell. - if (isComposing(event.nativeEvent, composingRef.current)) return; - const from = { rowKey, colKey }; - switch (event.key) { - case "Enter": - event.preventDefault(); - if (session.getState().status === "idle") { - session.begin(baselineText); - event.currentTarget.select(); - } else { - commitDraft(); - } - return; - case "Tab": { - const active = session.getState(); - const failedCommit = active.status === "failed" && active.source === "commit"; - if (!failedCommit && !commitDraft()) { - event.preventDefault(); - return; - } - // At the first / last editable cell, native Tab leaves the table. - if (navigation.move(from, event.shiftKey ? "prev" : "next")) event.preventDefault(); - return; - } - case "Escape": - if (session.getState().status === "idle") return; - // Handled here, so an enclosing dialog doesn't also close on this Esc. - event.preventDefault(); - event.stopPropagation(); - revert(true); - return; - } - }; - - const handleFocus = (event: FocusEvent) => { - const withinCell = focused || containsErrorTarget(event.relatedTarget); - setFocused(true); - if (withinCell) return; - session.begin(baselineText); - event.currentTarget.select(); - }; - - const handleBlur = () => { - setFocused(false); - const active = session.getState(); - if (active.status === "failed") { - // Preserve callback failures; malformed numeric blur still cancels the edit. - if (active.source === "parse") revert(true); - return; - } - if (!commitDraft()) revert(true); - }; - - const handleMouseDown = (event: MouseEvent) => { - if (editing) return; - // A right-click on a resting cell opens DataTable's cell menu instead of editing. - if (event.button === 2) { - event.preventDefault(); - return; - } - session.begin(baselineText); - if (focused) event.currentTarget.select(); - selectOnMouseUpRef.current = true; - }; - - // The click that focuses the cell keeps the select-all from `handleFocus`; - // otherwise mouseup would collapse it to a caret. - const handleMouseUp = (event: MouseEvent) => { - if (!selectOnMouseUpRef.current) return; - selectOnMouseUpRef.current = false; - event.preventDefault(); - }; - - // While editing, the browser's own menu and long-press (paste, select) win - // over DataTable's cell menu. - const stopWhileEditing = (event: MouseEvent | TouchEvent) => { - if (editing) event.stopPropagation(); - }; - - const hint = t("editRevertHint"); - - return ( - revert(true)} - getFailure={session.getFailure} - confirming={state.status === "confirming"} - > - {message !== undefined && ( - - {message}. {hint} - - )} - - { - composingRef.current = true; - }} - onCompositionEnd={handleCompositionEnd} - onMouseDown={handleMouseDown} - onMouseUp={handleMouseUp} - onPointerEnter={() => setHovered(true)} - onPointerLeave={() => setHovered(false)} - onContextMenu={stopWhileEditing} - onTouchStart={stopWhileEditing} - /> - } - /> - - {message} - {hint} - - - +import { EditableCell } from "@/components/internals/table-core/editing/cell"; +import { numberEditor, textEditor } from "@/components/internals/table-core/editing/typing"; +import { useEditorProps, type DataTableEditableCellProps } from "./shared"; + +export function TypingEditCell>( + props: DataTableEditableCellProps, +) { + const coreProps = useEditorProps(props); + const numeric = props.col.type === "number" || props.col.type === "money"; + return numeric ? ( + + ) : ( + ); } diff --git a/packages/core/src/components/data-table/editing/use-session.ts b/packages/core/src/components/data-table/editing/use-session.ts deleted file mode 100644 index 0c1991406..000000000 --- a/packages/core/src/components/data-table/editing/use-session.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { useEffect, useRef, useState } from "react"; - -/** @internal */ -export interface CellEditFailure { - error: unknown; - source: "parse" | "change" | "commit"; -} - -/** @internal */ -export type CellEditSessionState = - | { status: "idle" } - | { status: "editing"; draft: TDraft } - | { status: "confirming"; draft: TDraft } - | ({ status: "failed"; draft: TDraft } & CellEditFailure); - -function isPromiseLike(value: unknown): value is PromiseLike { - return typeof (value as PromiseLike | null | undefined)?.then === "function"; -} - -/** Owns the draft and its failure together; consumer data remains authoritative. @internal */ -export function useCellEditSession(enabled: boolean) { - const [state, setState] = useState>({ status: "idle" }); - const { current: session } = useRef({ - state, - revision: 0, - mounted: false, - pendingChange: null as Promise | null, - }); - const transition = (next: CellEditSessionState) => { - session.state = next; - setState(next); - }; - const isCurrent = (revision: number) => session.mounted && session.revision === revision; - - useEffect(() => { - session.mounted = true; - return () => { - session.mounted = false; - session.revision++; - session.pendingChange = null; - }; - }, [enabled, session]); - - const begin = (draft: TDraft) => { - if (session.state.status !== "idle") return; - session.revision++; - transition({ status: "editing", draft }); - }; - - const change = (draft: TDraft, callback?: () => unknown) => { - const revision = ++session.revision; - session.pendingChange = null; - transition({ status: "editing", draft }); - if (!callback) return; - if (!enabled) { - callback(); - return; - } - const reject = (error: unknown) => { - if (isCurrent(revision)) transition({ status: "failed", draft, error, source: "change" }); - }; - try { - const result = callback(); - if (isPromiseLike(result)) { - const pending = Promise.resolve(result).then( - () => { - if (isCurrent(revision) && session.pendingChange === pending) - session.pendingChange = null; - return true; - }, - (error: unknown) => { - if (isCurrent(revision) && session.pendingChange === pending) - session.pendingChange = null; - reject(error); - return false; - }, - ); - if (isCurrent(revision)) session.pendingChange = pending; - } - } catch (error) { - reject(error); - } - }; - - const discard = () => { - session.revision++; - session.pendingChange = null; - transition({ status: "idle" }); - }; - - const confirm = (callback: () => unknown, onSuccess?: () => void) => { - const current = session.state; - if ( - current.status === "idle" || - current.status === "confirming" || - (current.status === "failed" && current.source !== "commit") - ) - return; - if (!enabled) { - discard(); - onSuccess?.(); - callback(); - return; - } - const { draft } = current; - const revision = session.revision; - const pendingChange = session.pendingChange; - transition({ status: "confirming", draft }); - const isConfirming = () => isCurrent(revision) && session.state.status === "confirming"; - const complete = () => { - if (!isConfirming()) return; - transition({ status: "idle" }); - onSuccess?.(); - }; - const reject = (error: unknown) => { - if (isConfirming()) transition({ status: "failed", draft, error, source: "commit" }); - }; - const run = () => { - if (!isConfirming()) return; - try { - const result = callback(); - if (isPromiseLike(result)) { - void Promise.resolve(result).then(complete, reject); - return; - } - } catch (error) { - reject(error); - return; - } - complete(); - }; - if (pendingChange) { - void pendingChange.then((valid) => { - if (valid) run(); - }); - } else { - run(); - } - }; - - const fail = (error: unknown, source: "parse") => { - const current = session.state; - if (current.status === "idle") return; - session.revision++; - session.pendingChange = null; - transition({ status: "failed", draft: current.draft, error, source }); - }; - - const cancel = (callback?: () => unknown) => { - discard(); - if (!callback) return; - if (!enabled) { - callback(); - return; - } - // Restoration failures have no draft to attach to and must not recreate an orphan error. - try { - const result = callback(); - if (isPromiseLike(result)) void Promise.resolve(result).catch(() => {}); - } catch { - // The edit has already been cancelled. - } - }; - - const getFailure = () => { - const current = session.state; - return current.status === "failed" ? current : undefined; - }; - - return { state, getState: () => session.state, getFailure, begin, change, confirm, fail, cancel }; -} diff --git a/packages/core/src/components/data-table/index.ts b/packages/core/src/components/data-table/index.ts index de84bd250..23f847285 100644 --- a/packages/core/src/components/data-table/index.ts +++ b/packages/core/src/components/data-table/index.ts @@ -1,7 +1,7 @@ // DataTable compound component export { DataTable, type DataTablePaginationProps, type DataTableRootProps } from "./data-table"; -export { CellEditError } from "./cell-edit-error"; +export { CellEditError } from "@/components/internals/table-core/cell-edit-error"; export { useDataTable } from "./use-data-table"; export { useDataTableContext, type DataTableContextValue } from "./context"; @@ -24,8 +24,8 @@ export type { DataTableFilterConfig, DataTableTreeRow, DateCellEditOptions, - DateTimeDraft, DateCellOptions, + DateTimeDraft, LinkCellOptions, MetadataFieldOptions, MoneyCellOptions, diff --git a/packages/core/src/components/data-table/rows.tsx b/packages/core/src/components/data-table/rows.tsx index e85b80c5f..9d51d5e8d 100644 --- a/packages/core/src/components/data-table/rows.tsx +++ b/packages/core/src/components/data-table/rows.tsx @@ -9,11 +9,11 @@ import { Menu } from "@/components/menu"; import { Tooltip } from "@/components/tooltip"; import type { DataTableTreeRow, RowAction, RowExpansionOptions } from "./types"; import { SubRowsCellContent } from "./sub-rows-cell"; -import { getCellValue, createTypedCellRenderer } from "./cell-renderers"; +import { getCellValue, createTypedValueRenderer } from "./cell-renderers"; import { DataTableCellContextMenu, getCellContextValue } from "./context-menu"; import { useCellContextMenu } from "./use-cell-context-menu"; import { DataTableEditableCell, hasEditorIcon, isEditableColumn } from "./editing/cell/root"; -import { ICON_SPACE_CLASS_NAME } from "./editing/cell/shared"; +import { ICON_SPACE_CLASS_NAME } from "@/components/internals/table-core/editing/shared"; import { useCellEditNavigation } from "./editing/use-navigation"; import { RowExpandToggle, DataTableExpandedRow } from "./expanded-row"; import { useDataTableT } from "./i18n"; @@ -83,7 +83,15 @@ function DataTableRows>({ new Map( ordered .filter((col) => !col.render) - .map((col) => [col, createTypedCellRenderer(col, timeZone)]), + .map((col) => { + const context = { timeZone }; + const readonly = createTypedValueRenderer(col, context); + const editable = + col.type === "link" + ? createTypedValueRenderer(col, context, { linkAsText: true }) + : readonly; + return [col, { readonly, editable }]; + }), ), [ordered, timeZone], ); @@ -221,7 +229,10 @@ function DataTableRows>({ (col.edit?.canEdit?.(row, { selected }) ?? true); // An editable cell renders its own display; skip rendering it twice. let content: ReactNode; - if (!editable) content = col.render ? col.render(row) : cellRenderers.get(col)?.(row); + if (!editable) + content = col.render + ? col.render(row) + : cellRenderers.get(col)?.readonly(getCellValue(row, col), row); const customCellProps = col.cellProps?.(row); const { style: cellStyle, className: cellClassName } = pinCellProps( @@ -333,7 +344,7 @@ function DataTableRows>({ label={headerLabel} align={resolveAlign(col)} navigation={navigation} - dateRenderer={col.type === "date" ? cellRenderers.get(col) : undefined} + valueRenderer={cellRenderers.get(col)?.editable} tooltipLabel={tooltipLabel} cellProps={cellProps} /> diff --git a/packages/core/src/components/data-table/types.ts b/packages/core/src/components/data-table/types.ts index af0904cac..b355a4c6b 100644 --- a/packages/core/src/components/data-table/types.ts +++ b/packages/core/src/components/data-table/types.ts @@ -1,6 +1,22 @@ import type { ComponentProps, ReactNode } from "react"; import type { TreeSelectionBehaviorProps } from "@/lib/tree/types"; -import type { BadgeOptions } from "@/components/badge-list"; +import type { DateTimeDraft } from "@/components/internals/table-core/editing/date"; +export type { DateTimeDraft } from "@/components/internals/table-core/editing/date"; +import type { + BadgeCellOptions, + DateCellOptions, + LinkCellOptions, + MoneyCellOptions, + NumberCellOptions, +} from "@/components/internals/table-core/column-types"; +export type { + BadgeCellOptions, + ColumnCellType, + DateCellOptions, + LinkCellOptions, + MoneyCellOptions, + NumberCellOptions, +} from "@/components/internals/table-core/column-types"; import type { CollectionControl, Filter, @@ -16,76 +32,8 @@ import type { // Column Definitions // ============================================================================= -/** - * Built-in cell renderer types for `Column.type`. - * - * Each type produces a default render based on the value returned by - * `accessor`. Pass `render` to override the built-in renderer. - * - * - `text` — `String(value)` with `—` placeholder for null/undefined. - * - `number` — locale-formatted number with `—` for null/undefined. - * - `money` — `Intl.NumberFormat` currency. See `MoneyOptions`. - * - `date` — `Intl.DateTimeFormat`. Accepts `Date`, ISO string, or epoch ms. - * - `badge` — `` keyed off the value. See `BadgeOptions`. - * - `link` — app-shell `` with `href` from `LinkOptions`. - */ -export type ColumnCellType = "text" | "number" | "money" | "date" | "badge" | "link"; - export type { BadgeVariant } from "@/components/badge-list"; -/** Options for `type: "number"` cells. */ -export interface NumberCellOptions { - /** Minimum decimal places. Default: `0`. */ - minDecimals?: number; - /** Maximum decimal places. Default: `minDecimals` (or `0`). */ - maxDecimals?: number; - /** BCP 47 locale tag. Defaults to the runtime locale. */ - locale?: string; -} - -/** Options for `type: "money"` cells. */ -export interface MoneyCellOptions> { - /** - * ISO 4217 currency code. Pass a string for a static currency or a function - * to read it from the row. Default: `"USD"`. - */ - currency?: string | ((row: TRow) => string); - /** - * Maximum decimals. Raises the cap above the currency default while keeping - * the minimum at the currency default (e.g. USD stays at ≥2, but a price - * column can show up to 4). - */ - maxDecimals?: number; - /** BCP 47 locale tag. Defaults to the runtime locale. */ - locale?: string; -} - -/** Options for `type: "date"` cells. */ -export interface DateCellOptions { - /** - * Format style. `"short"` → `Apr 9, 2026`; `"long"` → `April 9, 2026`; - * `"datetime"` → `Apr 9, 2026, 3:45 PM`. Default: `"short"`. - */ - dateFormat?: "short" | "long" | "datetime"; - /** BCP 47 locale tag. Defaults to the runtime locale. */ - locale?: string; -} - -/** Options for `type: "badge"` cells. */ -export interface BadgeCellOptions extends BadgeOptions { - /** Maximum number of badges to display before showing a "+N" overflow indicator */ - maxVisible?: number; -} - -/** Options for `type: "link"` cells. `href` is required. */ -export interface LinkCellOptions> { - /** - * Extracts the link target. Returning `null` / `undefined` renders the cell - * value as plain text instead of a link. - */ - href: (row: TRow) => string | null | undefined; -} - // ============================================================================= // Inline editing // ============================================================================= @@ -96,12 +44,6 @@ export interface CellEditState { selected: boolean; } -/** Incomplete date-time editor state, interpreted in the AppShell timezone. */ -export interface DateTimeDraft { - day: string | null; - time: string | null; -} - interface CellEditBase, TValue, TDraft = TValue | null> { /** * Decides, per row, whether the cell can be edited. Receives the row and diff --git a/packages/core/src/components/data-table/cell-edit-error.ts b/packages/core/src/components/internals/table-core/cell-edit-error.ts similarity index 100% rename from packages/core/src/components/data-table/cell-edit-error.ts rename to packages/core/src/components/internals/table-core/cell-edit-error.ts diff --git a/packages/core/src/components/internals/table-core/cell-renderers.test-d.ts b/packages/core/src/components/internals/table-core/cell-renderers.test-d.ts new file mode 100644 index 000000000..52ed81f30 --- /dev/null +++ b/packages/core/src/components/internals/table-core/cell-renderers.test-d.ts @@ -0,0 +1,75 @@ +import type { ReactNode } from "react"; +import { expectTypeOf, test } from "vitest"; +import { createValueRenderer, type ValueRendererContext } from "./cell-renderers"; +import { displayCellAdapters } from "./display-cell-adapters"; +import type { ColumnCellType, TypedColumnDisplay } from "./column-types"; + +type Row = { id: string; currency: string }; +const context: ValueRendererContext = { timeZone: "Asia/Tokyo" }; + +test("the exhaustive display catalog shares one preparation contract", () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf(displayCellAdapters.number.defaultAlign).toEqualTypeOf<"right">(); + expectTypeOf(displayCellAdapters.text.defaultAlign).toEqualTypeOf<"left">(); + expectTypeOf(displayCellAdapters.date.createRenderer).parameters.toEqualTypeOf< + [TypedColumnDisplay, ValueRendererContext] + >(); + expectTypeOf(displayCellAdapters.money.createRenderer).parameters.toEqualTypeOf< + [TypedColumnDisplay, ValueRendererContext] + >(); + expectTypeOf(displayCellAdapters.text.createRenderer).parameters.toEqualTypeOf< + [TypedColumnDisplay, ValueRendererContext] + >(); + + createValueRenderer({ type: "date" }, context); + createValueRenderer({ type: "number" }, context); + // @ts-expect-error Every display kind requires its owner-resolved context. + createValueRenderer({ type: "number" }); + // @ts-expect-error Date preparation uses the same required context. + createValueRenderer({ type: "date" }); + // @ts-expect-error The display environment must include its timezone. + createValueRenderer({ type: "date" }, {}); + // @ts-expect-error Renderer dependencies are passed as a context object. + createValueRenderer({ type: "number" }, "UTC"); + // @ts-expect-error Adapters also require the shared preparation context. + displayCellAdapters.text.createRenderer({ type: "text" }); +}); + +test("renderer creation preserves row-dependent currency and link contracts", () => { + const money = displayCellAdapters.money.createRenderer( + { type: "money", typeOptions: { currency: (row) => row.currency } }, + context, + ); + const link = displayCellAdapters.link.createRenderer( + { type: "link", typeOptions: { href: (row) => `/rows/${row.id}` } }, + context, + ); + const dispatched = createValueRenderer( + { type: "money", typeOptions: { currency: (row) => row.currency } }, + context, + ); + expectTypeOf(money).toEqualTypeOf<(value: unknown, row: Row) => ReactNode>(); + expectTypeOf(link).toEqualTypeOf<(value: unknown, row: Row) => ReactNode>(); + expectTypeOf(dispatched).toEqualTypeOf<(value: unknown, row: Row) => ReactNode>(); + + displayCellAdapters.money.createRenderer( + { + type: "money", + typeOptions: { + // @ts-expect-error A currency callback cannot require a different row shape. + currency: (row: { other: string }) => row.other, + }, + }, + context, + ); + displayCellAdapters.link.createRenderer( + { + type: "link", + typeOptions: { + // @ts-expect-error A link callback cannot require a different row shape. + href: (row: { other: string }) => row.other, + }, + }, + context, + ); +}); diff --git a/packages/core/src/components/internals/table-core/cell-renderers.test.tsx b/packages/core/src/components/internals/table-core/cell-renderers.test.tsx new file mode 100644 index 000000000..50efd3cdd --- /dev/null +++ b/packages/core/src/components/internals/table-core/cell-renderers.test.tsx @@ -0,0 +1,55 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createValueRenderer, getDisplayCellAdapter } from "./cell-renderers"; +import { displayCellAdapters } from "./display-cell-adapters"; +import type { ColumnCellType, ValueDisplayDescriptor } from "./column-types"; + +const context = { timeZone: "Asia/Tokyo" }; +const descriptors = { + text: { type: "text" }, + number: { type: "number", typeOptions: { minDecimals: 2 } }, + money: { type: "money", typeOptions: { currency: (row) => row.currency } }, + date: { type: "date", typeOptions: { locale: "en-US" } }, + badge: { type: "badge" }, + link: { type: "link", typeOptions: { href: (row) => `/rows/${row.id}` } }, +} satisfies Record>; + +afterEach(() => vi.restoreAllMocks()); + +describe("display renderer dispatch", () => { + it.each(Object.values(descriptors))( + "passes the descriptor and context unchanged to the $type adapter", + (descriptor) => { + const renderer = vi.fn(() => "Rendered"); + const prepare = vi + .spyOn(displayCellAdapters[descriptor.type], "createRenderer") + .mockReturnValue(renderer); + const renderValue = createValueRenderer(descriptor, context); + expect(prepare).toHaveBeenCalledExactlyOnceWith(descriptor, context); + expect(renderValue).toBe(renderer); + const row = { id: "A", currency: "EUR" }; + expect(renderValue("Raw value", row)).toBe("Rendered"); + expect(renderer).toHaveBeenCalledExactlyOnceWith("Raw value", row); + }, + ); + + it("looks up metadata without creating a renderer", () => { + const prepare = vi.spyOn(displayCellAdapters.date, "createRenderer"); + expect(getDisplayCellAdapter("date")).toBe(displayCellAdapters.date); + expect(getDisplayCellAdapter(undefined)).toBe(displayCellAdapters.text); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("uses the text fallback when a display kind is omitted", () => { + expect(createValueRenderer({}, context)("Raw value", {})).toBe("Raw value"); + }); + + it.each(["custom", "constructor", "__proto__", Object("number"), { toString: () => "number" }])( + "retains the text fallback for unsupported runtime type %s", + (type: unknown) => { + // @ts-expect-error Exercise malformed JavaScript configuration outside the typed contract. + expect(getDisplayCellAdapter(type)).toBe(displayCellAdapters.text); + // @ts-expect-error Exercise malformed JavaScript configuration outside the typed contract. + expect(createValueRenderer({ type }, context)("Raw value", {})).toBe("Raw value"); + }, + ); +}); diff --git a/packages/core/src/components/internals/table-core/cell-renderers.ts b/packages/core/src/components/internals/table-core/cell-renderers.ts new file mode 100644 index 000000000..3f36ec538 --- /dev/null +++ b/packages/core/src/components/internals/table-core/cell-renderers.ts @@ -0,0 +1,51 @@ +import type { ReactNode } from "react"; +import type { ColumnCellType, TypedColumnDisplay, ValueDisplayDescriptor } from "./column-types"; +import { displayCellAdapters } from "./display-cell-adapters"; + +export type ValueRenderer> = ( + value: unknown, + row: TRow, +) => ReactNode; + +export interface ValueRendererContext { + /** Display environment resolved by the owning table, not by the shared dispatcher. */ + timeZone: string; + /** Optional, already-resolved display label policy for individual badge values. */ + resolveBadgeLabel?: (value: string) => string; +} + +export interface DisplayCellAdapter { + defaultAlign: "left" | "right"; + createRenderer>( + display: TypedColumnDisplay, + context: ValueRendererContext, + ): ValueRenderer; +} + +/** Read presentation metadata without constructing a renderer; unknown runtime kinds retain the text fallback. */ +export function getDisplayCellAdapter(type: ColumnCellType | undefined) { + return typeof type === "string" && Object.hasOwn(displayCellAdapters, type) + ? displayCellAdapters[type] + : displayCellAdapters.text; +} + +/** Keep keyed selection correlated with its descriptor and row-dependent options. */ +function createTypedValueRenderer, K extends ColumnCellType>( + type: K, + descriptor: TypedColumnDisplay, + context: ValueRendererContext, +): ValueRenderer { + const adapters: { [P in ColumnCellType]: DisplayCellAdapter } = displayCellAdapters; + return adapters[type].createRenderer(descriptor, context); +} + +/** Prepare a built-in renderer without interpreting its settings or environment dependencies. */ +export function createValueRenderer>( + descriptor: ValueDisplayDescriptor, + context: ValueRendererContext, +): ValueRenderer { + if (typeof descriptor.type !== "string" || !Object.hasOwn(displayCellAdapters, descriptor.type)) { + return displayCellAdapters.text.createRenderer({ type: "text" }, context); + } + return createTypedValueRenderer(descriptor.type, descriptor, context); +} diff --git a/packages/core/src/components/internals/table-core/cell-session.test.ts b/packages/core/src/components/internals/table-core/cell-session.test.ts new file mode 100644 index 000000000..746d8f65f --- /dev/null +++ b/packages/core/src/components/internals/table-core/cell-session.test.ts @@ -0,0 +1,279 @@ +// @vitest-environment node +import { describe, expect, it, vi } from "vitest"; +import { createCellEditSession } from "./cell-session"; + +function deferred() { + let resolve!: () => void; + let reject!: (error: unknown) => void; + const promise = new Promise((success, failure) => { + resolve = success; + reject = failure; + }); + return { promise, resolve, reject }; +} + +async function settle(request: ReturnType, failure?: { error: unknown }) { + if (failure) request.reject(failure.error); + else request.resolve(); + await request.promise.catch(() => undefined); +} + +describe("React-independent cell edit sessions", () => { + it("separates stale-adoption revisions from explicit popup cancellation", () => { + const session = createCellEditSession(); + const cancellation = session.getCancellationRevision(); + const initial = session.getRevision(); + session.begin("Memo"); + session.change("Changed"); + expect(session.getRevision()).toBeGreaterThan(initial); + expect(session.getCancellationRevision()).toBe(cancellation); + session.cancel(); + expect(session.getCancellationRevision()).toBe(cancellation + 1); + }); + + it("caches its state and publishes adopted snapshots, not reads or no-ops", () => { + const session = createCellEditSession(); + const initial = session.getState(); + const listener = vi.fn(() => { + expect(session.getState()).toEqual({ status: "editing", draft: "Memo" }); + }); + const detach = session.subscribe(listener); + expect(session.getState()).toBe(initial); + expect(session.getFailure()).toBeUndefined(); + session.fail("No draft", "parse"); + const commit = vi.fn(); + expect(session.confirm(commit)).toBeUndefined(); + expect(commit).not.toHaveBeenCalled(); + expect(listener).not.toHaveBeenCalled(); + const begin = session.begin; + begin("Memo"); + const editing = session.getState(); + expect(editing).not.toBe(initial); + begin("Must not replace Memo"); + expect(session.getState()).toBe(editing); + expect(listener).toHaveBeenCalledTimes(1); + detach(); + detach(); + session.cancel(); + expect(listener).toHaveBeenCalledTimes(1); + }); + + it("retains a draft and its failure when a view detaches and resubscribes", () => { + const session = createCellEditSession(); + const firstView = vi.fn(); + const detach = session.subscribe(firstView); + session.change("-"); + session.fail("Not a number", "parse"); + const failed = session.getState(); + detach(); + const secondView = vi.fn(); + session.subscribe(secondView); + expect(session.getState()).toBe(failed); + expect(session.getFailure()).toBe(failed); + const commit = vi.fn(); + session.confirm(commit); + expect(commit).not.toHaveBeenCalled(); + session.change("2"); + session.confirm(commit); + expect(session.getState()).toEqual({ status: "idle" }); + expect(commit).toHaveBeenCalledTimes(1); + expect(firstView).toHaveBeenCalledTimes(2); + expect(secondView).toHaveBeenCalledTimes(3); + }); + + it("retains error dismissal without invalidating the edit and resets it for a new failure", () => { + const session = createCellEditSession(); + const error = new Error("Rejected"); + const check = () => { + throw error; + }; + session.change("Retained"); + session.confirm(check); + const failure = session.getFailure()!; + const revision = session.getRevision(); + const listener = vi.fn(); + const detach = session.subscribe(listener); + const dismissed = session.setErrorDetailsOpen(failure, false)!; + expect(dismissed.detailsDismissed).toBe(true); + expect(session.getFailure()).toBe(dismissed); + expect(session.getRevision()).toBe(revision); + expect(listener).toHaveBeenCalledTimes(1); + session.setErrorDetailsOpen(dismissed, false); + expect(listener).toHaveBeenCalledTimes(1); + detach(); + expect(session.getFailure()?.detailsDismissed).toBe(true); + const reopened = session.setErrorDetailsOpen(dismissed, true)!; + expect(reopened.detailsDismissed).toBe(false); + session.confirm(check); + const retried = session.getFailure()!; + expect(retried.error).toBe(error); + expect(retried.detailsDismissed).toBeUndefined(); + expect(session.setErrorDetailsOpen(failure, false)).toBeUndefined(); + expect(session.getFailure()).toBe(retried); + session.deactivate(); + expect(session.setErrorDetailsOpen(retried, false)).toBeUndefined(); + expect(session.getFailure()).toBe(retried); + }); + + it("uses the current listener set for each notification when subscriptions change", () => { + const session = createCellEditSession(); + const late = vi.fn(); + const second = vi.fn(); + let detachSecond!: () => void; + const first = vi.fn(() => { + detachSecond(); + session.subscribe(late); + }); + session.subscribe(first); + detachSecond = session.subscribe(second); + session.begin("Memo"); + expect(first).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenCalledTimes(1); + expect(late).not.toHaveBeenCalled(); + session.change("Changed"); + expect(second).toHaveBeenCalledTimes(1); + expect(late).toHaveBeenCalledTimes(1); + }); + + it.each(["resolve", "reject"] as const)( + "does not cancel a request when its view disappears before a %s", + async (outcome) => { + const session = createCellEditSession(); + const request = deferred(); + const listener = vi.fn(); + const detach = session.subscribe(listener); + const complete = vi.fn(); + session.begin("Memo"); + session.confirm(() => request.promise, complete); + detach(); + const error = new Error("Save failed"); + await settle(request, outcome === "reject" ? { error } : undefined); + expect(session.getState()).toEqual( + outcome === "resolve" + ? { status: "idle" } + : { status: "failed", draft: "Memo", error, source: "commit" }, + ); + expect(complete).toHaveBeenCalledTimes(outcome === "resolve" ? 1 : 0); + expect(listener).toHaveBeenCalledTimes(2); + }, + ); + + it("keeps synchronous confirmation synchronous and preserves its void result", () => { + const session = createCellEditSession(); + session.begin("Memo"); + const complete = vi.fn(() => expect(session.getState()).toEqual({ status: "idle" })); + expect(session.confirm(() => false, complete)).toBeUndefined(); + expect(complete).toHaveBeenCalledTimes(1); + expect(session.getState()).toEqual({ status: "idle" }); + }); + + it("waits for a change check before committing and deduplicates confirmation", async () => { + const session = createCellEditSession(); + const check = deferred(); + const save = deferred(); + const commit = vi.fn(() => save.promise); + const duplicate = vi.fn(); + session.change("Memo", () => check.promise); + session.confirm(commit); + session.confirm(duplicate); + expect(commit).not.toHaveBeenCalled(); + await settle(check); + expect(commit).toHaveBeenCalledTimes(1); + expect(session.getState()).toEqual({ status: "confirming", draft: "Memo" }); + session.confirm(duplicate); + await settle(save); + expect(session.getState()).toEqual({ status: "idle" }); + expect(duplicate).not.toHaveBeenCalled(); + }); + + it.each(["check", "commit"] as const)( + "retains a rejected %s draft and retries only a commit failure", + async (phase) => { + const session = createCellEditSession(); + const request = deferred(); + session.change("Memo", phase === "check" ? () => request.promise : undefined); + const commit = vi.fn(() => (phase === "commit" ? request.promise : undefined)); + session.confirm(commit); + const error = new Error("Rejected"); + await settle(request, { error }); + expect(session.getState()).toEqual({ + status: "failed", + draft: "Memo", + error, + source: phase === "check" ? "change" : "commit", + }); + const retry = vi.fn(); + session.confirm(retry); + expect(retry).toHaveBeenCalledTimes(phase === "commit" ? 1 : 0); + if (phase === "check") session.change("Corrected"); + else expect(session.getState()).toEqual({ status: "idle" }); + }, + ); + + it.each(["cancel", "deactivate"] as const)( + "does not start a waiting commit after %s", + async (action) => { + const session = createCellEditSession(); + const check = deferred(); + const commit = vi.fn(); + session.change("Memo", () => check.promise); + session.confirm(commit); + session[action](); + const retained = session.getState(); + await settle(check); + expect(commit).not.toHaveBeenCalled(); + expect(session.getState()).toBe(retained); + }, + ); + + it.each(["check", "commit"] as const)( + "reactivates an invalidated %s with its draft intact for explicit retry", + async (phase) => { + const session = createCellEditSession(); + const request = deferred(); + const complete = vi.fn(); + const commit = vi.fn(() => (phase === "commit" ? request.promise : undefined)); + session.change("Memo", phase === "check" ? () => request.promise : undefined); + session.confirm(commit, complete); + session.deactivate(); + session.activate(true); + expect(session.getState()).toEqual({ status: "editing", draft: "Memo" }); + const retry = deferred(); + session.confirm(() => retry.promise); + await settle(request); + expect(session.getState()).toEqual({ status: "confirming", draft: "Memo" }); + expect(commit).toHaveBeenCalledTimes(phase === "commit" ? 1 : 0); + expect(complete).not.toHaveBeenCalled(); + await settle(retry); + expect(session.getState()).toEqual({ status: "idle" }); + }, + ); + + it("does not reset a live confirmation when an active owner activates again", async () => { + const session = createCellEditSession(); + const request = deferred(); + session.begin("Memo"); + session.confirm(() => request.promise); + const confirming = session.getState(); + session.activate(true); + expect(session.getState()).toBe(confirming); + await settle(request); + expect(session.getState()).toEqual({ status: "idle" }); + }); + + it("ignores retained commands after deactivation without notifying", () => { + const session = createCellEditSession(); + session.begin("Memo"); + const retained = session.getState(); + const listener = vi.fn(); + session.subscribe(listener); + session.deactivate(); + session.begin("Detached"); + session.change("Detached", listener); + session.fail("Detached", "parse"); + session.cancel(listener); + session.confirm(listener); + expect(session.getState()).toBe(retained); + expect(listener).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/components/internals/table-core/cell-session.ts b/packages/core/src/components/internals/table-core/cell-session.ts new file mode 100644 index 000000000..d5a88bf2d --- /dev/null +++ b/packages/core/src/components/internals/table-core/cell-session.ts @@ -0,0 +1,209 @@ +// Retain reachable session declarations in the bundle; package entrypoints do not export them. +/** A failure belongs to its draft, not to the control displaying it. */ +export interface CellEditFailure { + error: unknown; + source: "parse" | "change" | "commit"; + /** Retained owners keep dismissal with this failure, not with a mounted cell. */ + detailsDismissed?: boolean; +} + +/** The cached view of one logical edit; committed row values remain owned by the caller. */ +export type CellEditSessionState = + | { status: "idle" } + | { status: "editing"; draft: TDraft } + | { status: "confirming"; draft: TDraft } + | ({ status: "failed"; draft: TDraft } & CellEditFailure); + +function isPromiseLike(value: unknown): value is PromiseLike { + return typeof (value as PromiseLike | null | undefined)?.then === "function"; +} + +/** + * Owns one edit's draft, failure, and in-flight callback checks without React or row state. + * getState returns a cached snapshot suitable for useSyncExternalStore. A transition adopts + * that snapshot before notifying subscribers synchronously; reads do not notify. + * + * The caller owns the lifetime: detaching a subscriber leaves the edit intact, whereas + * deactivate invalidates pending callbacks and blocks commands. activate resumes the same + * draft with the caller's error-interception policy. Returned methods do not depend on this. + */ +export function createCellEditSession(interceptErrors = true) { + let state: CellEditSessionState = { status: "idle" }; + let revision = 0; + let cancellationRevision = 0; + let active = true; + let enabled = interceptErrors; + let pendingChange: Promise | null = null; + const listeners = new Set<() => void>(); + + function transition(next: CellEditSessionState) { + state = next; + // oxlint-disable-next-line unicorn/no-useless-spread -- Subscriptions can change during notification. + for (const listener of [...listeners]) listener(); + } + function invalidate() { + revision++; + pendingChange = null; + } + const isCurrent = (candidate: number) => active && revision === candidate; + + function begin(draft: TDraft) { + if (!active || state.status !== "idle") return; + invalidate(); + transition({ status: "editing", draft }); + } + + function change(draft: TDraft, callback?: () => unknown) { + if (!active) return; + invalidate(); + const candidate = revision; + transition({ status: "editing", draft }); + if (!callback) return; + if (!enabled) { + callback(); + return; + } + function reject(error: unknown) { + if (isCurrent(candidate)) transition({ status: "failed", draft, error, source: "change" }); + } + try { + const result = callback(); + if (isPromiseLike(result)) { + const pending = Promise.resolve(result).then( + () => { + if (isCurrent(candidate) && pendingChange === pending) pendingChange = null; + return true; + }, + (error: unknown) => { + if (isCurrent(candidate) && pendingChange === pending) pendingChange = null; + reject(error); + return false; + }, + ); + if (isCurrent(candidate)) pendingChange = pending; + } + } catch (error) { + reject(error); + } + } + + function discard() { + cancellationRevision++; + invalidate(); + transition({ status: "idle" }); + } + + /** Waits for an outstanding change check; repeated confirmation does not repeat callbacks. */ + function confirm(callback: () => unknown, onSuccess?: () => void) { + const current = state; + if ( + !active || + current.status === "idle" || + current.status === "confirming" || + (current.status === "failed" && current.source !== "commit") + ) + return; + if (!enabled) { + discard(); + onSuccess?.(); + callback(); + return; + } + const { draft } = current; + const candidate = revision; + const waiting = pendingChange; + transition({ status: "confirming", draft }); + const isConfirming = () => isCurrent(candidate) && state.status === "confirming"; + function complete() { + if (!isConfirming()) return; + transition({ status: "idle" }); + onSuccess?.(); + } + function reject(error: unknown) { + if (isConfirming()) transition({ status: "failed", draft, error, source: "commit" }); + } + function run() { + if (!isConfirming()) return; + try { + const result = callback(); + if (isPromiseLike(result)) { + void Promise.resolve(result).then(complete, reject); + return; + } + } catch (error) { + reject(error); + return; + } + complete(); + } + if (waiting) { + void waiting.then((valid) => { + if (valid) run(); + }); + } else run(); + } + + function fail(error: unknown, source: "parse") { + if (!active || state.status === "idle") return; + const { draft } = state; + invalidate(); + transition({ status: "failed", draft, error, source }); + } + + function cancel(callback?: () => unknown) { + if (!active) return; + discard(); + if (!callback) return; + if (!enabled) { + callback(); + return; + } + // Restoration failures cannot recreate an error for a draft that has been discarded. + try { + const result = callback(); + if (isPromiseLike(result)) void Promise.resolve(result).catch(() => {}); + } catch { + // There is no longer a draft to attach a restoration error to. + } + } + + return { + getRevision: () => revision, + /** Explicit discard also retires local popup/search state in retained editor controls. */ + getCancellationRevision: () => cancellationRevision, + getState: () => state, + getFailure: () => (state.status === "failed" ? state : undefined), + setErrorDetailsOpen(failure: CellEditFailure, open: boolean): CellEditFailure | undefined { + if (!active || state.status !== "failed" || state !== failure) return undefined; + if (!!state.detailsDismissed === !open) return state; + const next = { ...state, detailsDismissed: !open }; + transition(next); + return next; + }, + /** Registers a listener without invoking it; cleanup is idempotent and does not cancel. */ + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + begin, + change, + confirm, + fail, + cancel, + /** Resumes the retained draft; an invalidated confirmation requires an explicit retry. */ + activate(intercept: boolean) { + const resuming = !active; + enabled = intercept; + active = true; + if (resuming && state.status === "confirming") + transition({ status: "editing", draft: state.draft }); + }, + /** Invalidates async work without changing the retained draft or notifying subscribers. */ + deactivate() { + active = false; + invalidate(); + }, + }; +} diff --git a/packages/core/src/components/internals/table-core/column-types.test-d.ts b/packages/core/src/components/internals/table-core/column-types.test-d.ts new file mode 100644 index 000000000..542f0c0c0 --- /dev/null +++ b/packages/core/src/components/internals/table-core/column-types.test-d.ts @@ -0,0 +1,44 @@ +import { expectTypeOf, test } from "vitest"; +import type { Column, ColumnBase, TextCellEditOptions } from "@/components/data-table/types"; +import type { ValueDisplayDescriptor } from "./column-types"; + +type Row = { id: string; amount: number; status: string }; + +test("DataTable columns remain compatible with the neutral display descriptor", () => { + expectTypeOf>().toExtend>(); + expectTypeOf["width"]>().toEqualTypeOf(); + expectTypeOf["align"]>().toEqualTypeOf<"left" | "right" | undefined>(); + expectTypeOf["onValueCommitted"]>>().toEqualTypeOf< + (row: Row, value: string | null) => void + >(); +}); + +test("display descriptors retain the existing type/options contracts", () => { + const link: ValueDisplayDescriptor = { + type: "link", + typeOptions: { + href: (row) => { + expectTypeOf(row).toEqualTypeOf(); + return `/rows/${row.id}`; + }, + }, + }; + const money: ValueDisplayDescriptor = { + type: "money", + typeOptions: { currency: (row) => row.status }, + }; + // @ts-expect-error Links still require an href. + const missingHref: ValueDisplayDescriptor = { type: "link" }; + // @ts-expect-error Text columns do not accept typeOptions. + const textOptions: ValueDisplayDescriptor = { type: "text", typeOptions: {} }; + const numberOptions: ValueDisplayDescriptor = { + type: "number", + // @ts-expect-error Number columns do not accept currency options. + typeOptions: { currency: "USD" }, + }; + void link; + void money; + void missingHref; + void textOptions; + void numberOptions; +}); diff --git a/packages/core/src/components/internals/table-core/column-types.ts b/packages/core/src/components/internals/table-core/column-types.ts new file mode 100644 index 000000000..3d59e76a5 --- /dev/null +++ b/packages/core/src/components/internals/table-core/column-types.ts @@ -0,0 +1,91 @@ +import type { BadgeOptions } from "@/components/badge-list"; + +/** Built-in display renderers, independent of how a component obtains or edits a value. */ +export type ColumnCellType = "text" | "number" | "money" | "date" | "badge" | "link"; + +/** Options for `type: "number"` cells. */ +export interface NumberCellOptions { + /** Minimum decimal places. Default: `0`. */ + minDecimals?: number; + /** Maximum decimal places. Default: `minDecimals` (or `0`). */ + maxDecimals?: number; + /** BCP 47 locale tag. Defaults to the runtime locale. */ + locale?: string; +} + +/** Options for `type: "money"` cells. */ +export interface MoneyCellOptions> { + /** + * ISO 4217 currency code. Pass a string for a static currency or a function + * to read it from the row. Default: `"USD"`. + */ + currency?: string | ((row: TRow) => string); + /** + * Maximum decimals. Raises the cap above the currency default while keeping + * the minimum at the currency default (e.g. USD stays at ≥2, but a price + * column can show up to 4). + */ + maxDecimals?: number; + /** BCP 47 locale tag. Defaults to the runtime locale. */ + locale?: string; +} + +/** Options for `type: "date"` cells. */ +export interface DateCellOptions { + /** + * Format style. `"short"` → `Apr 9, 2026`; `"long"` → `April 9, 2026`; + * `"datetime"` → `Apr 9, 2026, 3:45 PM`. Default: `"short"`. + */ + dateFormat?: "short" | "long" | "datetime"; + /** BCP 47 locale tag. Defaults to the runtime locale. */ + locale?: string; +} + +/** Options for `type: "badge"` cells. */ +export interface BadgeCellOptions extends BadgeOptions { + /** Maximum number of badges to display before showing a "+N" overflow indicator */ + maxVisible?: number; +} + +/** Options for `type: "link"` cells. `href` is required. */ +export interface LinkCellOptions> { + /** + * Extracts the link target. Returning `null` / `undefined` renders the cell + * value as plain text instead of a link. + */ + href: (row: TRow) => string | null | undefined; +} + +/** Resolved presentation only: no accessor, edit choices, filters, or table state. */ +export type ValueDisplayDescriptor> = + | { type?: undefined; typeOptions?: never } + | { type: "text"; typeOptions?: never } + | { type: "number"; typeOptions?: NumberCellOptions } + | { type: "money"; typeOptions?: MoneyCellOptions } + | { type: "date"; typeOptions?: DateCellOptions } + | { type: "badge"; typeOptions?: BadgeCellOptions } + | { type: "link"; typeOptions: LinkCellOptions }; + +/** Values accepted by each built-in display renderer. */ +export interface ColumnDisplayValues { + text: string | number | boolean | bigint | null | undefined; + number: number | null | undefined; + money: number | null | undefined; + date: Date | string | number | null | undefined; + badge: string | string[] | number | boolean | null | undefined; + link: string | number | boolean | null | undefined; +} + +export type TypedColumnDisplay< + TRow extends Record, + K extends ColumnCellType, +> = Extract, { type: K }>; + +/** A display type must accept the value produced by its column's source. */ +export type ColumnDisplay, TValue> = + | { type?: undefined; typeOptions?: never } + | { + [K in ColumnCellType]: [TValue] extends [ColumnDisplayValues[K]] + ? TypedColumnDisplay + : never; + }[ColumnCellType]; diff --git a/packages/core/src/components/internals/table-core/display-cell-adapters.test.tsx b/packages/core/src/components/internals/table-core/display-cell-adapters.test.tsx new file mode 100644 index 000000000..ccd06acae --- /dev/null +++ b/packages/core/src/components/internals/table-core/display-cell-adapters.test.tsx @@ -0,0 +1,205 @@ +import type { ReactNode } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { cleanup, render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router"; +import { createValueRenderer } from "./cell-renderers"; +import { displayCellAdapters } from "./display-cell-adapters"; +import type { ColumnCellType } from "./column-types"; + +const context = { timeZone: "America/New_York" }; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const adapterCases: Record< + ColumnCellType, + { + adapter: { defaultAlign: "left" | "right" }; + align: "left" | "right"; + renderValue: () => ReactNode; + text: string; + href?: string; + } +> = { + text: { + adapter: displayCellAdapters.text, + align: "left", + renderValue: () => + displayCellAdapters.text.createRenderer({ type: "text" }, context)("Text", {}), + text: "Text", + }, + number: { + adapter: displayCellAdapters.number, + align: "right", + renderValue: () => + displayCellAdapters.number.createRenderer( + { type: "number", typeOptions: { locale: "en-US", minDecimals: 2, maxDecimals: 2 } }, + context, + )(12.5, {}), + text: "12.50", + }, + money: { + adapter: displayCellAdapters.money, + align: "right", + renderValue: () => + displayCellAdapters.money.createRenderer<{ currency: string }>( + { type: "money", typeOptions: { locale: "en-US", currency: (row) => row.currency } }, + context, + )(12.5, { currency: "EUR" }), + text: "€12.50", + }, + date: { + adapter: displayCellAdapters.date, + align: "left", + renderValue: () => + displayCellAdapters.date.createRenderer( + { type: "date", typeOptions: { locale: "en-US" } }, + context, + )("2026-10-09T00:00:00Z", {}), + text: "Oct 8, 2026", + }, + badge: { + adapter: displayCellAdapters.badge, + align: "left", + renderValue: () => + displayCellAdapters.badge.createRenderer( + { type: "badge", typeOptions: { badgeLabelMap: { open: "Open" } } }, + context, + )("open", {}), + text: "Open", + }, + link: { + adapter: displayCellAdapters.link, + align: "left", + renderValue: () => + displayCellAdapters.link.createRenderer<{ id: string }>( + { type: "link", typeOptions: { href: (row) => `/rows/${row.id}` } }, + context, + )("Resolved", { id: "A" }), + text: "Resolved", + href: "/rows/A", + }, +}; + +describe("display cell adapters", () => { + it.each(Object.entries(adapterCases))( + "pairs %s rendering with its default alignment", + (_kind, { adapter, align, renderValue, text, href }) => { + expect(adapter.defaultAlign).toBe(align); + render({renderValue()}); + expect(screen.getByText(text)).toBeDefined(); + if (href) expect(screen.getByRole("link").getAttribute("href")).toBe(href); + }, + ); + + it.each([undefined, { timeZone: "" }])( + "rejects date preparation without a timezone at runtime (%j)", + (invalidContext) => { + expect(() => + displayCellAdapters.date.createRenderer( + { type: "date" }, + // @ts-expect-error Exercise JavaScript configuration outside the typed contract. + invalidContext, + ), + ).toThrow("Date rendering requires a timezone."); + }, + ); +}); + +describe("neutral value rendering", () => { + it("renders the supplied value without looking up row properties or edit choices", () => { + const descriptor = { + type: "text" as const, + id: "status", + edit: { options: [{ value: "open", label: "Choice label" }] }, + }; + const renderer = createValueRenderer(descriptor, context); + expect(renderer("open", { status: "different" })).toBe("open"); + expect(renderer(false, { status: "different" })).toBe("✗"); + expect(createValueRenderer({}, context)({ count: 2 }, {})).toBe('{"count":2}'); + }); + + it("formats display precision without changing a supplied number", () => { + const value = 12.345; + const renderer = createValueRenderer( + { type: "number", typeOptions: { locale: "en-US", minDecimals: 2, maxDecimals: 2 } }, + context, + ); + render(<>{renderer(value, {})}>); + expect(screen.getByText("12.35")).toBeDefined(); + expect(value).toBe(12.345); + }); + + it("resolves currency from each row and retains the invalid-currency fallback", () => { + const renderer = createValueRenderer<{ currency: string }>( + { type: "money", typeOptions: { locale: "en-US", currency: (row) => row.currency } }, + context, + ); + const view = render(<>{renderer(12.5, { currency: "EUR" })}>); + expect(screen.getByText("€12.50")).toBeDefined(); + view.rerender(<>{renderer(12.5, { currency: "invalid currency" })}>); + expect(screen.getByText("$12.50")).toBeDefined(); + }); + + it("applies only the explicitly supplied badge display policy", () => { + const descriptor = { type: "badge" as const, typeOptions: { badgeLabelMap: { open: "Open" } } }; + const normal = createValueRenderer(descriptor, context); + const resolved = createValueRenderer(descriptor, { + ...context, + resolveBadgeLabel: (value) => `Resolved ${value}`, + }); + const view = render(<>{normal("open", {})}>); + expect(screen.getByText("Open")).toBeDefined(); + view.rerender(<>{resolved("open", {})}>); + expect(screen.getByText("Resolved open")).toBeDefined(); + expect(screen.queryByText("Open")).toBeNull(); + }); + + it("renders links from the supplied label and row-dependent href, or plain text without href", () => { + const renderer = createValueRenderer<{ id?: string }>( + { type: "link", typeOptions: { href: (row) => (row.id ? `/rows/${row.id}` : null) } }, + context, + ); + const view = render({renderer("Resolved label", { id: "A" })}); + expect(screen.getByRole("link", { name: "Resolved label" }).getAttribute("href")).toBe( + "/rows/A", + ); + view.rerender({renderer("Resolved label", {})}); + expect(screen.queryByRole("link")).toBeNull(); + expect(screen.getByText("Resolved label")).toBeDefined(); + }); + + it("keeps independent date-only and zoned formatter caches across rows", () => { + const DateTimeFormat = Intl.DateTimeFormat; + const spy = vi.spyOn(Intl, "DateTimeFormat").mockImplementation(function (locale, options) { + return new DateTimeFormat(locale, options); + }); + const renderer = createValueRenderer( + { type: "date", typeOptions: { locale: "en-US" } }, + context, + ); + for (let index = 0; index < 3; index++) { + expect(renderer("2026-10-09", {})).toBe("Oct 9, 2026"); + expect(renderer("2026-10-09T00:00:00Z", {})).toBe("Oct 8, 2026"); + } + expect( + spy.mock.calls + .filter(([locale, options]) => locale === "en-US" && options?.month === "short") + .map(([, options]) => options?.timeZone), + ).toEqual(["UTC", "America/New_York"]); + }); + + it("preserves a skipped calendar date and placeholders without constructing invalid formatters", () => { + const renderer = createValueRenderer( + { type: "date", typeOptions: { locale: "en-US" } }, + { timeZone: "Pacific/Apia" }, + ); + expect(renderer("2011-12-30", {})).toBe("Dec 30, 2011"); + const view = render(<>{renderer("2026-02-30", {})}>); + expect(screen.getByText("—")).toBeDefined(); + view.rerender(<>{createValueRenderer({ type: "badge" }, context)([null, ""], {})}>); + expect(screen.getByText("—")).toBeDefined(); + }); +}); diff --git a/packages/core/src/components/internals/table-core/display-cell-adapters.tsx b/packages/core/src/components/internals/table-core/display-cell-adapters.tsx new file mode 100644 index 000000000..285aa1cb3 --- /dev/null +++ b/packages/core/src/components/internals/table-core/display-cell-adapters.tsx @@ -0,0 +1,224 @@ +import type { ReactNode } from "react"; +import { parseDate } from "@internationalized/date"; +import { Link } from "react-router"; +import { BadgeList, toValueArray } from "@/components/badge-list"; +import { normalizeTemporalFilterValue } from "@/lib/temporal-filter-values"; +import type { + BadgeCellOptions, + ColumnCellType, + DateCellOptions, + LinkCellOptions, + MoneyCellOptions, + NumberCellOptions, + TypedColumnDisplay, +} from "./column-types"; +import type { DisplayCellAdapter, ValueRenderer, ValueRendererContext } from "./cell-renderers"; + +const PLACEHOLDER = ( + + — + +); + +function isEmpty(value: unknown): boolean { + return value == null || value === ""; +} + +function renderText(value: unknown): ReactNode { + switch (true) { + case isEmpty(value): + return PLACEHOLDER; + case typeof value === "boolean": + return value ? "✓" : "✗"; + case value instanceof Date: + return value.toLocaleDateString(); + case typeof value === "object": + return JSON.stringify(value); + default: + return String(value); + } +} + +function renderNumber(value: unknown, options: NumberCellOptions | undefined): ReactNode { + if (isEmpty(value)) return PLACEHOLDER; + const num = Number(value); + if (Number.isNaN(num)) return PLACEHOLDER; + const min = options?.minDecimals ?? 0; + const formatted = new Intl.NumberFormat(options?.locale, { + minimumFractionDigits: min, + maximumFractionDigits: options?.maxDecimals ?? min, + }).format(num); + return {formatted}; +} + +function renderMoney>( + value: unknown, + row: TRow, + options: MoneyCellOptions | undefined, +): ReactNode { + if (isEmpty(value)) return PLACEHOLDER; + const num = Number(value); + if (Number.isNaN(num)) return PLACEHOLDER; + const currency = + (typeof options?.currency === "function" ? options.currency(row) : options?.currency) || "USD"; + + // `maxDecimals` raises the cap above the currency default while retaining its minimum. + const formatOptions: Intl.NumberFormatOptions = { style: "currency", currency }; + if (options?.maxDecimals != null) formatOptions.maximumFractionDigits = options.maxDecimals; + let formatted: string; + try { + formatted = new Intl.NumberFormat(options?.locale, formatOptions).format(num); + } catch { + // Invalid currency codes retain the existing USD fallback. + formatted = new Intl.NumberFormat(options?.locale, { + style: "currency", + currency: "USD", + }).format(num); + } + return {formatted}; +} + +function resolveDateFormatOptions(format: string): Intl.DateTimeFormatOptions { + if (format === "long") return { month: "long", day: "numeric", year: "numeric" }; + if (format === "datetime") { + return { + month: "short", + day: "numeric", + year: "numeric", + hour: "numeric", + minute: "2-digit", + }; + } + return { month: "short", day: "numeric", year: "numeric" }; +} + +/** Bind date-only and datetime formatting to a timezone once, retaining independent formatter caches. */ +function createDateRenderer( + options: DateCellOptions | undefined, + timeZone: string, +): (value: unknown) => ReactNode { + const formatOptions = resolveDateFormatOptions(options?.dateFormat ?? "short"); + let dateOnlyFormatter: Intl.DateTimeFormat | undefined; + let datetimeFormatter: Intl.DateTimeFormat | undefined; + return (value) => { + if (isEmpty(value)) return PLACEHOLDER; + const dateOnly = typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value.trim()); + let date: Date; + if (dateOnly) { + // Calendar dates have no instant, even when a timezone skips an entire day. + try { + date = parseDate(value.trim()).toDate("UTC"); + } catch { + return PLACEHOLDER; + } + } else { + const normalized = normalizeTemporalFilterValue("datetime", value, timeZone); + if (!normalized) return PLACEHOLDER; + date = new Date(normalized); + } + const formatter = dateOnly + ? (dateOnlyFormatter ??= new Intl.DateTimeFormat(options?.locale, { + ...formatOptions, + timeZone: "UTC", + })) + : (datetimeFormatter ??= new Intl.DateTimeFormat(options?.locale, { + ...formatOptions, + timeZone, + })); + return formatter.format(date); + }; +} + +function renderBadge( + value: unknown, + options: BadgeCellOptions | undefined, + resolveLabel: ((value: string) => string) | undefined, +): ReactNode { + if (toValueArray(value).filter((item) => item != null && item !== "").length === 0) + return PLACEHOLDER; + return ( + + ); +} + +function renderLink>( + value: unknown, + row: TRow, + options: LinkCellOptions, +): ReactNode { + if (isEmpty(value)) return PLACEHOLDER; + const label = String(value); + const href = options.href(row); + if (!href) return label; + return ( + + {label} + + ); +} + +/** Each display kind owns its formatting, dependencies, and default presentation policy. */ +export const displayCellAdapters = { + text: { + defaultAlign: "left", + createRenderer: >( + _display: TypedColumnDisplay, + _context: ValueRendererContext, + ): ValueRenderer => renderText, + }, + number: { + defaultAlign: "right", + createRenderer: + >( + display: TypedColumnDisplay, + _context: ValueRendererContext, + ): ValueRenderer => + (value) => + renderNumber(value, display.typeOptions), + }, + money: { + defaultAlign: "right", + createRenderer: + >( + display: TypedColumnDisplay, + _context: ValueRendererContext, + ): ValueRenderer => + (value, row) => + renderMoney(value, row, display.typeOptions), + }, + date: { + defaultAlign: "left", + createRenderer: >( + display: TypedColumnDisplay, + context: ValueRendererContext, + ): ValueRenderer => { + if (!context?.timeZone) throw new Error("Date rendering requires a timezone."); + return createDateRenderer(display.typeOptions, context.timeZone); + }, + }, + badge: { + defaultAlign: "left", + createRenderer: + >( + display: TypedColumnDisplay, + context: ValueRendererContext, + ): ValueRenderer => + (value) => + renderBadge(value, display.typeOptions, context.resolveBadgeLabel), + }, + link: { + defaultAlign: "left", + createRenderer: + >( + display: TypedColumnDisplay, + _context: ValueRendererContext, + ): ValueRenderer => + (value, row) => + renderLink(value, row, display.typeOptions), + }, +} satisfies { [K in ColumnCellType]: DisplayCellAdapter }; diff --git a/packages/core/src/components/internals/table-core/editing/cell.test-d.ts b/packages/core/src/components/internals/table-core/editing/cell.test-d.ts new file mode 100644 index 000000000..e996ea977 --- /dev/null +++ b/packages/core/src/components/internals/table-core/editing/cell.test-d.ts @@ -0,0 +1,128 @@ +import type { ComponentProps } from "react"; +import { expectTypeOf, test } from "vitest"; +import { EditableCell, type EditableCellOwnerProps } from "./cell"; +import { choiceEditor } from "./choice"; +import { dateEditor } from "./date"; +import { numberEditor, textEditor } from "./typing"; +import type { CellEditorOptions, CellEditorOutput, CellEditorProps } from "./props"; + +declare const ownerProps: EditableCellOwnerProps; + +test("injected editors retain required options without a kind discriminator", () => { + type ChoiceOptions = CellEditorOptions; + type DateOptions = CellEditorOptions; + expectTypeOf().toEqualTypeOf< + readonly { value: string; label: string }[] + >(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf<"options" | "renderOption">(); + expectTypeOf().toEqualTypeOf< + "withTime" | "timeZone" | "minValue" | "maxValue" | "isDateUnavailable" + >(); + expectTypeOf, "timeZone">>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + + EditableCell({ + ...ownerProps, + editor: choiceEditor, + options: { + options: [{ value: "open", label: "Open" }], + renderOption: (value, label) => { + expectTypeOf(value).toEqualTypeOf(); + expectTypeOf(label).toEqualTypeOf(); + return label; + }, + }, + }); + EditableCell({ ...ownerProps, editor: dateEditor, options: { withTime: true, timeZone: "UTC" } }); + EditableCell({ ...ownerProps, editor: dateEditor, options: { timeZone: "UTC" } }); + EditableCell({ ...ownerProps, editor: textEditor, options: {} }); + EditableCell({ ...ownerProps, editor: numberEditor, options: {} }); +}); + +test("editor implementations expose their confirmed output types", () => { + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf(); + + const commitNumber: ComponentProps["commit"] = (value) => { + expectTypeOf(value).toEqualTypeOf(); + }; + commitNumber(12.5); + commitNumber(null); + // @ts-expect-error The numeric input cannot confirm text. + commitNumber("12.5"); + + const commitText: ComponentProps["commit"] = (value) => { + expectTypeOf(value).toEqualTypeOf(); + }; + commitText("text"); + commitText(null); + // @ts-expect-error The text input cannot confirm a numeric value. + commitText(12.5); +}); + +test("cell confirmation types are inferred only from the selected editor", () => { + EditableCell({ + ...ownerProps, + editor: numberEditor, + options: {}, + commit: (value) => { + expectTypeOf(value).toEqualTypeOf(); + }, + }); + EditableCell({ + ...ownerProps, + editor: choiceEditor, + options: { options: [] }, + commit: (value) => { + expectTypeOf(value).toEqualTypeOf(); + }, + }); + EditableCell({ + ...ownerProps, + editor: numberEditor, + options: {}, + // @ts-expect-error A callback cannot widen a number editor's output to text. + commit: (_value: string | null) => {}, + }); + EditableCell({ + ...ownerProps, + editor: numberEditor, + options: {}, + // @ts-expect-error A number editor can confirm null on clear. + commit: (_value: number) => {}, + }); + EditableCell({ + ...ownerProps, + editor: dateEditor, + options: { timeZone: "UTC" }, + // @ts-expect-error A callback cannot change the confirmed output of a date editor. + commit: (_value: number | null) => {}, + }); +}); + +test("options cannot widen or disagree with the injected editor", () => { + // @ts-expect-error Choice options remain required. + EditableCell({ ...ownerProps, editor: choiceEditor }); + // @ts-expect-error A choice editor requires its fixed choices. + EditableCell({ ...ownerProps, editor: choiceEditor, options: {} }); + // @ts-expect-error Date options cannot substitute for choice options. + EditableCell({ ...ownerProps, editor: choiceEditor, options: { withTime: true } }); + // @ts-expect-error Fixed candidates use options, not a second choices shape. + EditableCell({ ...ownerProps, editor: choiceEditor, options: { choices: [] } }); + // @ts-expect-error A date editor cannot receive choice options. + EditableCell({ ...ownerProps, editor: dateEditor, options: { timeZone: "UTC", options: [] } }); + // @ts-expect-error The date adapter must resolve its timezone before rendering. + EditableCell({ ...ownerProps, editor: dateEditor, options: { withTime: true } }); + // @ts-expect-error A timezone is not part of the generic cell contract. + EditableCell({ ...ownerProps, editor: numberEditor, options: {}, timeZone: "UTC" }); + // @ts-expect-error A number editor has no date options. + EditableCell({ ...ownerProps, editor: numberEditor, options: { withTime: true } }); + // @ts-expect-error Options describe the selected editor, not another kind. + EditableCell({ ...ownerProps, editor: textEditor, options: { type: "number" } }); +}); diff --git a/packages/core/src/components/internals/table-core/editing/cell.tsx b/packages/core/src/components/internals/table-core/editing/cell.tsx new file mode 100644 index 000000000..982f83ed7 --- /dev/null +++ b/packages/core/src/components/internals/table-core/editing/cell.tsx @@ -0,0 +1,78 @@ +import type { ComponentProps, ReactNode } from "react"; +import type { Table } from "@/components/table"; +import { EditableCellFrame } from "./shared"; +import type { CellEditor, CellEditorProps, CellEditorView } from "./props"; + +/** + * Table-owned values, callbacks, session lifetime, and cell presentation. + * Editor settings and render-time composition are supplied separately by EditableCell. + * + * @see CellEditorProps for the inherited input and confirmation contract. + */ +export type EditableCellOwnerProps = Omit< + CellEditorProps, + "children" | "options" | "valueLabel" +> & { + /** Owner-formatted adopted value, including custom content or null; an editor may supply a draft preview instead. */ + display: ReactNode; + /** Underlying table-cell props; the frame merges className and owns editing/error attributes and handlers. */ + cellProps: ComponentProps; + /** Ellipsizes the display preview without changing the value passed to the input. */ + truncate?: boolean; + /** Tooltip text for the resting display; suppressed during active editing or callback errors. */ + tooltipLabel?: string; +}; + +/** + * Shared boundary between table-owned data/presentation and an injected input editor. + * The cell composes the editor with its frame; it neither selects an editor kind nor owns row data. + * Options and confirmed output are inferred from editor alone, so settings and callbacks cannot widen its contract. + * + * @typeParam TOptions - Settings accepted by the selected editor, without a kind discriminator. + * @typeParam TOutput - Complete confirmed value type, including null when the editor can clear its value. + * @see EditableCellOwnerProps for owner-supplied values, callbacks, and presentation. + */ +export type EditableCellProps = EditableCellOwnerProps> & { + /** Concrete input implementation and its icon/preview policy; also the source of options and output types. */ + editor: CellEditor; + /** Required settings of this editor, such as fixed options or date-time mode; cannot select another editor kind. */ + options: NoInfer; +}; + +/** Owns cell presentation; the injected editor supplies input behavior without mirrored state. */ +export function EditableCell({ + editor, + options, + display, + cellProps, + truncate, + tooltipLabel, + ...props +}: EditableCellProps) { + const { labels, slotPrefix } = props; + const { Editor, icon, hideDisplay } = editor; + const renderEditor = ({ input, draftPreview, ...interaction }: CellEditorView) => ( + + {input} + + ); + return ( + + {renderEditor} + + ); +} diff --git a/packages/core/src/components/internals/table-core/editing/choice.tsx b/packages/core/src/components/internals/table-core/editing/choice.tsx new file mode 100644 index 000000000..cd631c3e5 --- /dev/null +++ b/packages/core/src/components/internals/table-core/editing/choice.tsx @@ -0,0 +1,403 @@ +import { + useMemo, + useRef, + useState, + type ComponentProps, + type FocusEvent, + type MouseEvent, + type ReactNode, + type TouchEvent, +} from "react"; +import { Combobox as BaseCombobox } from "@base-ui/react/combobox"; +import { ChevronDown } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { isComposing } from "@/lib/is-composing"; +import { ComboboxParts } from "@/components/combobox"; +import { toTextValue } from "../input-values"; +import { useCellEditSession } from "./use-session"; +import { + CELL_ERROR_CLASS_NAME, + ICON_INPUT_CLASS_NAME, + INPUT_CLASS_NAME, + INPUT_DISPLAY, + useCellError, + useDraftStatus, + useNavigationRef, +} from "./shared"; +import type { CellEditor, CellEditorProps } from "./props"; + +/** One dropdown choice; `value: null` is "None". */ +interface Choice { + value: string | null; + label: string; +} + +type ChoiceDraft = Choice & { notified?: boolean }; + +// Case- and width-insensitive searching: full-width letters and half-width +// katakana match their usual forms. +const searchable = (text: string) => text.normalize("NFKC").toLocaleLowerCase().trim(); + +const isChoiceEqual = (a: Choice, b: Choice) => a.value === b.value; + +const choiceLabel = (choice: Choice) => choice.label; + +type ChoiceEditorOptions = { + options: readonly { value: string; label: string }[]; + renderOption?: (value: string, label: string) => ReactNode; +}; + +function ChoiceEditor({ + options: { options, renderOption }, + current, + allowClear = true, + change = () => undefined, + commit, + renderError, + labels, + interceptErrors = true, + session: external, + rowKey, + colKey, + label, + align, + navigation, + children, +}: CellEditorProps) { + const session = useCellEditSession(interceptErrors, external); + const { state } = session; + const { callbackError, containsErrorTarget } = useCellError( + { labels, renderError }, + state.status === "failed" ? state : undefined, + ); + const register = useNavigationRef(navigation, rowKey, colKey); + const value = toTextValue(current); + const shouldCommit = (next: string | null) => next !== value || (!!external && next === null); + const noneLabel = labels.none; + // Keyed on content: rebuilding columns must not reset the highlight mid-search. + const optionsKey = (options ?? []).map((c) => `${c.value}\u0000${c.label}`).join("\u0001"); + const items = useMemo( + () => [ + ...(allowClear ? [{ value: null, label: noneLabel }] : []), + ...(options ?? []).map((c) => ({ value: c.value, label: String(c.label) })), + ], + // eslint-disable-next-line react-hooks/exhaustive-deps -- `optionsKey` stands for `options`. + [optionsKey, noneLabel, allowClear], + ); + + const selected = items.find((item) => item.value === value) ?? null; + const [open, setOpen] = useState(false); + const [focused, setFocused] = useState(false); + const editing = state.status !== "idle"; + const activeChoice = state.status === "idle" ? selected : state.draft; + const draftStatus = useDraftStatus( + labels, + !!external, + activeChoice?.value !== value, + state.status, + ); + // The displayed search text is local while editing, even if consumer data changes. + const [query, setQuery] = useState(null); + // Keep the closing list filtered until its animation completes. + const [listQuery, setListQuery] = useState(null); + const highlightedRef = useRef(undefined); + const explicitHighlightRef = useRef(undefined); + const composingRef = useRef(false); + const selectOnMouseUpRef = useRef(false); + const from = { rowKey, colKey }; + const cancellation = session.getCancellationRevision(); + const [seenCancellation, setSeenCancellation] = useState(cancellation); + if (external && seenCancellation !== cancellation) { + setSeenCancellation(cancellation); + setOpen(false); + setQuery(null); + setListQuery(null); + highlightedRef.current = undefined; + explicitHighlightRef.current = undefined; + } + + const filtered = useMemo(() => { + const search = searchable(listQuery ?? ""); + if (!search) return items; + const rank = (item: Choice) => { + const text = searchable(item.label); + if (text === search) return 0; + return text.startsWith(search) ? 1 : 2; + }; + return ( + items + .filter((item) => item.value !== null && searchable(item.label).includes(search)) + // Sorting is stable, preserving the original order within each rank. + .toSorted((left, right) => rank(left) - rank(right)) + ); + }, [items, listQuery]); + + const startEditing = () => { + session.begin(selected ?? { value, label: value ?? noneLabel }); + setQuery(selected?.label ?? ""); + setListQuery(null); + highlightedRef.current = undefined; + explicitHighlightRef.current = undefined; + }; + + const closeEditor = () => { + setQuery(null); + explicitHighlightRef.current = undefined; + setOpen(false); + }; + + const cancelEditing = () => { + const active = session.getState(); + session.cancel( + active.status !== "idle" && active.draft.notified && active.draft.value !== value + ? () => change(value) + : undefined, + ); + closeEditor(); + }; + + const leaveEditor = () => { + const active = session.getState(); + if (active.status === "failed" || active.status === "confirming") closeEditor(); + else cancelEditing(); + }; + + const pick = (item: Choice) => { + const active = session.getState(); + if (active.status === "confirming" && active.draft.value === item.value) return; + session.change( + { ...item, notified: item.value !== value }, + item.value !== value ? () => change(item.value) : undefined, + ); + setQuery(item.label); + session.confirm(() => (shouldCommit(item.value) ? commit(item.value) : undefined), closeEditor); + }; + + const explicitCandidate = () => { + const item = explicitHighlightRef.current; + return item && filtered.includes(item) ? item : undefined; + }; + + const keyboardCandidate = () => { + const highlighted = highlightedRef.current; + return ( + explicitCandidate() ?? + (highlighted && filtered.includes(highlighted) ? highlighted : filtered[0]) + ); + }; + + const handleKeyDown: NonNullable["onKeyDown"]> = ( + event, + ) => { + if (isComposing(event.nativeEvent, composingRef.current)) { + event.preventBaseUIHandler(); + return; + } + switch (event.key) { + case "Enter": { + event.preventDefault(); + event.preventBaseUIHandler(); + const active = session.getState(); + if (active.status === "confirming") return; + if (!open) { + if (active.status === "failed" && active.source === "commit") { + session.confirm( + () => (shouldCommit(active.draft.value) ? commit(active.draft.value) : undefined), + closeEditor, + ); + return; + } + if (active.status === "idle") startEditing(); + setOpen(true); + return; + } + const item = keyboardCandidate(); + if (item) pick(item); + else leaveEditor(); + return; + } + case "Tab": { + event.preventBaseUIHandler(); + const item = + session.getState().status !== "idle" && open + ? (explicitCandidate() ?? + (searchable(listQuery ?? "") ? keyboardCandidate() : undefined)) + : undefined; + if (item) pick(item); + else leaveEditor(); + if (navigation?.move(from, event.shiftKey ? "prev" : "next")) event.preventDefault(); + return; + } + case "Escape": + if (session.getState().status === "idle" && !open) return; + event.preventDefault(); + event.stopPropagation(); + event.preventBaseUIHandler(); + cancelEditing(); + return; + } + }; + + const handleFocus = (event: FocusEvent) => { + const withinCell = focused || containsErrorTarget(event.relatedTarget); + setFocused(true); + if (withinCell) return; + if (session.getState().status === "idle") startEditing(); + event.currentTarget.select(); + }; + + const handleBlur = () => { + setFocused(false); + leaveEditor(); + }; + + const handleMouseDown = (event: MouseEvent
+ Clear Quantity or enter zero or a negative number, then press Enter to see a validation + error. +
{message}
} = displayCellAdapters; + return adapters[type].createRenderer(descriptor, context); +} + +/** Prepare a built-in renderer without interpreting its settings or environment dependencies. */ +export function createValueRenderer>( + descriptor: ValueDisplayDescriptor, + context: ValueRendererContext, +): ValueRenderer { + if (typeof descriptor.type !== "string" || !Object.hasOwn(displayCellAdapters, descriptor.type)) { + return displayCellAdapters.text.createRenderer({ type: "text" }, context); + } + return createTypedValueRenderer(descriptor.type, descriptor, context); +} diff --git a/packages/core/src/components/internals/table-core/cell-session.test.ts b/packages/core/src/components/internals/table-core/cell-session.test.ts new file mode 100644 index 000000000..746d8f65f --- /dev/null +++ b/packages/core/src/components/internals/table-core/cell-session.test.ts @@ -0,0 +1,279 @@ +// @vitest-environment node +import { describe, expect, it, vi } from "vitest"; +import { createCellEditSession } from "./cell-session"; + +function deferred() { + let resolve!: () => void; + let reject!: (error: unknown) => void; + const promise = new Promise((success, failure) => { + resolve = success; + reject = failure; + }); + return { promise, resolve, reject }; +} + +async function settle(request: ReturnType, failure?: { error: unknown }) { + if (failure) request.reject(failure.error); + else request.resolve(); + await request.promise.catch(() => undefined); +} + +describe("React-independent cell edit sessions", () => { + it("separates stale-adoption revisions from explicit popup cancellation", () => { + const session = createCellEditSession(); + const cancellation = session.getCancellationRevision(); + const initial = session.getRevision(); + session.begin("Memo"); + session.change("Changed"); + expect(session.getRevision()).toBeGreaterThan(initial); + expect(session.getCancellationRevision()).toBe(cancellation); + session.cancel(); + expect(session.getCancellationRevision()).toBe(cancellation + 1); + }); + + it("caches its state and publishes adopted snapshots, not reads or no-ops", () => { + const session = createCellEditSession(); + const initial = session.getState(); + const listener = vi.fn(() => { + expect(session.getState()).toEqual({ status: "editing", draft: "Memo" }); + }); + const detach = session.subscribe(listener); + expect(session.getState()).toBe(initial); + expect(session.getFailure()).toBeUndefined(); + session.fail("No draft", "parse"); + const commit = vi.fn(); + expect(session.confirm(commit)).toBeUndefined(); + expect(commit).not.toHaveBeenCalled(); + expect(listener).not.toHaveBeenCalled(); + const begin = session.begin; + begin("Memo"); + const editing = session.getState(); + expect(editing).not.toBe(initial); + begin("Must not replace Memo"); + expect(session.getState()).toBe(editing); + expect(listener).toHaveBeenCalledTimes(1); + detach(); + detach(); + session.cancel(); + expect(listener).toHaveBeenCalledTimes(1); + }); + + it("retains a draft and its failure when a view detaches and resubscribes", () => { + const session = createCellEditSession(); + const firstView = vi.fn(); + const detach = session.subscribe(firstView); + session.change("-"); + session.fail("Not a number", "parse"); + const failed = session.getState(); + detach(); + const secondView = vi.fn(); + session.subscribe(secondView); + expect(session.getState()).toBe(failed); + expect(session.getFailure()).toBe(failed); + const commit = vi.fn(); + session.confirm(commit); + expect(commit).not.toHaveBeenCalled(); + session.change("2"); + session.confirm(commit); + expect(session.getState()).toEqual({ status: "idle" }); + expect(commit).toHaveBeenCalledTimes(1); + expect(firstView).toHaveBeenCalledTimes(2); + expect(secondView).toHaveBeenCalledTimes(3); + }); + + it("retains error dismissal without invalidating the edit and resets it for a new failure", () => { + const session = createCellEditSession(); + const error = new Error("Rejected"); + const check = () => { + throw error; + }; + session.change("Retained"); + session.confirm(check); + const failure = session.getFailure()!; + const revision = session.getRevision(); + const listener = vi.fn(); + const detach = session.subscribe(listener); + const dismissed = session.setErrorDetailsOpen(failure, false)!; + expect(dismissed.detailsDismissed).toBe(true); + expect(session.getFailure()).toBe(dismissed); + expect(session.getRevision()).toBe(revision); + expect(listener).toHaveBeenCalledTimes(1); + session.setErrorDetailsOpen(dismissed, false); + expect(listener).toHaveBeenCalledTimes(1); + detach(); + expect(session.getFailure()?.detailsDismissed).toBe(true); + const reopened = session.setErrorDetailsOpen(dismissed, true)!; + expect(reopened.detailsDismissed).toBe(false); + session.confirm(check); + const retried = session.getFailure()!; + expect(retried.error).toBe(error); + expect(retried.detailsDismissed).toBeUndefined(); + expect(session.setErrorDetailsOpen(failure, false)).toBeUndefined(); + expect(session.getFailure()).toBe(retried); + session.deactivate(); + expect(session.setErrorDetailsOpen(retried, false)).toBeUndefined(); + expect(session.getFailure()).toBe(retried); + }); + + it("uses the current listener set for each notification when subscriptions change", () => { + const session = createCellEditSession(); + const late = vi.fn(); + const second = vi.fn(); + let detachSecond!: () => void; + const first = vi.fn(() => { + detachSecond(); + session.subscribe(late); + }); + session.subscribe(first); + detachSecond = session.subscribe(second); + session.begin("Memo"); + expect(first).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenCalledTimes(1); + expect(late).not.toHaveBeenCalled(); + session.change("Changed"); + expect(second).toHaveBeenCalledTimes(1); + expect(late).toHaveBeenCalledTimes(1); + }); + + it.each(["resolve", "reject"] as const)( + "does not cancel a request when its view disappears before a %s", + async (outcome) => { + const session = createCellEditSession(); + const request = deferred(); + const listener = vi.fn(); + const detach = session.subscribe(listener); + const complete = vi.fn(); + session.begin("Memo"); + session.confirm(() => request.promise, complete); + detach(); + const error = new Error("Save failed"); + await settle(request, outcome === "reject" ? { error } : undefined); + expect(session.getState()).toEqual( + outcome === "resolve" + ? { status: "idle" } + : { status: "failed", draft: "Memo", error, source: "commit" }, + ); + expect(complete).toHaveBeenCalledTimes(outcome === "resolve" ? 1 : 0); + expect(listener).toHaveBeenCalledTimes(2); + }, + ); + + it("keeps synchronous confirmation synchronous and preserves its void result", () => { + const session = createCellEditSession(); + session.begin("Memo"); + const complete = vi.fn(() => expect(session.getState()).toEqual({ status: "idle" })); + expect(session.confirm(() => false, complete)).toBeUndefined(); + expect(complete).toHaveBeenCalledTimes(1); + expect(session.getState()).toEqual({ status: "idle" }); + }); + + it("waits for a change check before committing and deduplicates confirmation", async () => { + const session = createCellEditSession(); + const check = deferred(); + const save = deferred(); + const commit = vi.fn(() => save.promise); + const duplicate = vi.fn(); + session.change("Memo", () => check.promise); + session.confirm(commit); + session.confirm(duplicate); + expect(commit).not.toHaveBeenCalled(); + await settle(check); + expect(commit).toHaveBeenCalledTimes(1); + expect(session.getState()).toEqual({ status: "confirming", draft: "Memo" }); + session.confirm(duplicate); + await settle(save); + expect(session.getState()).toEqual({ status: "idle" }); + expect(duplicate).not.toHaveBeenCalled(); + }); + + it.each(["check", "commit"] as const)( + "retains a rejected %s draft and retries only a commit failure", + async (phase) => { + const session = createCellEditSession(); + const request = deferred(); + session.change("Memo", phase === "check" ? () => request.promise : undefined); + const commit = vi.fn(() => (phase === "commit" ? request.promise : undefined)); + session.confirm(commit); + const error = new Error("Rejected"); + await settle(request, { error }); + expect(session.getState()).toEqual({ + status: "failed", + draft: "Memo", + error, + source: phase === "check" ? "change" : "commit", + }); + const retry = vi.fn(); + session.confirm(retry); + expect(retry).toHaveBeenCalledTimes(phase === "commit" ? 1 : 0); + if (phase === "check") session.change("Corrected"); + else expect(session.getState()).toEqual({ status: "idle" }); + }, + ); + + it.each(["cancel", "deactivate"] as const)( + "does not start a waiting commit after %s", + async (action) => { + const session = createCellEditSession(); + const check = deferred(); + const commit = vi.fn(); + session.change("Memo", () => check.promise); + session.confirm(commit); + session[action](); + const retained = session.getState(); + await settle(check); + expect(commit).not.toHaveBeenCalled(); + expect(session.getState()).toBe(retained); + }, + ); + + it.each(["check", "commit"] as const)( + "reactivates an invalidated %s with its draft intact for explicit retry", + async (phase) => { + const session = createCellEditSession(); + const request = deferred(); + const complete = vi.fn(); + const commit = vi.fn(() => (phase === "commit" ? request.promise : undefined)); + session.change("Memo", phase === "check" ? () => request.promise : undefined); + session.confirm(commit, complete); + session.deactivate(); + session.activate(true); + expect(session.getState()).toEqual({ status: "editing", draft: "Memo" }); + const retry = deferred(); + session.confirm(() => retry.promise); + await settle(request); + expect(session.getState()).toEqual({ status: "confirming", draft: "Memo" }); + expect(commit).toHaveBeenCalledTimes(phase === "commit" ? 1 : 0); + expect(complete).not.toHaveBeenCalled(); + await settle(retry); + expect(session.getState()).toEqual({ status: "idle" }); + }, + ); + + it("does not reset a live confirmation when an active owner activates again", async () => { + const session = createCellEditSession(); + const request = deferred(); + session.begin("Memo"); + session.confirm(() => request.promise); + const confirming = session.getState(); + session.activate(true); + expect(session.getState()).toBe(confirming); + await settle(request); + expect(session.getState()).toEqual({ status: "idle" }); + }); + + it("ignores retained commands after deactivation without notifying", () => { + const session = createCellEditSession(); + session.begin("Memo"); + const retained = session.getState(); + const listener = vi.fn(); + session.subscribe(listener); + session.deactivate(); + session.begin("Detached"); + session.change("Detached", listener); + session.fail("Detached", "parse"); + session.cancel(listener); + session.confirm(listener); + expect(session.getState()).toBe(retained); + expect(listener).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/components/internals/table-core/cell-session.ts b/packages/core/src/components/internals/table-core/cell-session.ts new file mode 100644 index 000000000..d5a88bf2d --- /dev/null +++ b/packages/core/src/components/internals/table-core/cell-session.ts @@ -0,0 +1,209 @@ +// Retain reachable session declarations in the bundle; package entrypoints do not export them. +/** A failure belongs to its draft, not to the control displaying it. */ +export interface CellEditFailure { + error: unknown; + source: "parse" | "change" | "commit"; + /** Retained owners keep dismissal with this failure, not with a mounted cell. */ + detailsDismissed?: boolean; +} + +/** The cached view of one logical edit; committed row values remain owned by the caller. */ +export type CellEditSessionState = + | { status: "idle" } + | { status: "editing"; draft: TDraft } + | { status: "confirming"; draft: TDraft } + | ({ status: "failed"; draft: TDraft } & CellEditFailure); + +function isPromiseLike(value: unknown): value is PromiseLike { + return typeof (value as PromiseLike | null | undefined)?.then === "function"; +} + +/** + * Owns one edit's draft, failure, and in-flight callback checks without React or row state. + * getState returns a cached snapshot suitable for useSyncExternalStore. A transition adopts + * that snapshot before notifying subscribers synchronously; reads do not notify. + * + * The caller owns the lifetime: detaching a subscriber leaves the edit intact, whereas + * deactivate invalidates pending callbacks and blocks commands. activate resumes the same + * draft with the caller's error-interception policy. Returned methods do not depend on this. + */ +export function createCellEditSession(interceptErrors = true) { + let state: CellEditSessionState = { status: "idle" }; + let revision = 0; + let cancellationRevision = 0; + let active = true; + let enabled = interceptErrors; + let pendingChange: Promise | null = null; + const listeners = new Set<() => void>(); + + function transition(next: CellEditSessionState) { + state = next; + // oxlint-disable-next-line unicorn/no-useless-spread -- Subscriptions can change during notification. + for (const listener of [...listeners]) listener(); + } + function invalidate() { + revision++; + pendingChange = null; + } + const isCurrent = (candidate: number) => active && revision === candidate; + + function begin(draft: TDraft) { + if (!active || state.status !== "idle") return; + invalidate(); + transition({ status: "editing", draft }); + } + + function change(draft: TDraft, callback?: () => unknown) { + if (!active) return; + invalidate(); + const candidate = revision; + transition({ status: "editing", draft }); + if (!callback) return; + if (!enabled) { + callback(); + return; + } + function reject(error: unknown) { + if (isCurrent(candidate)) transition({ status: "failed", draft, error, source: "change" }); + } + try { + const result = callback(); + if (isPromiseLike(result)) { + const pending = Promise.resolve(result).then( + () => { + if (isCurrent(candidate) && pendingChange === pending) pendingChange = null; + return true; + }, + (error: unknown) => { + if (isCurrent(candidate) && pendingChange === pending) pendingChange = null; + reject(error); + return false; + }, + ); + if (isCurrent(candidate)) pendingChange = pending; + } + } catch (error) { + reject(error); + } + } + + function discard() { + cancellationRevision++; + invalidate(); + transition({ status: "idle" }); + } + + /** Waits for an outstanding change check; repeated confirmation does not repeat callbacks. */ + function confirm(callback: () => unknown, onSuccess?: () => void) { + const current = state; + if ( + !active || + current.status === "idle" || + current.status === "confirming" || + (current.status === "failed" && current.source !== "commit") + ) + return; + if (!enabled) { + discard(); + onSuccess?.(); + callback(); + return; + } + const { draft } = current; + const candidate = revision; + const waiting = pendingChange; + transition({ status: "confirming", draft }); + const isConfirming = () => isCurrent(candidate) && state.status === "confirming"; + function complete() { + if (!isConfirming()) return; + transition({ status: "idle" }); + onSuccess?.(); + } + function reject(error: unknown) { + if (isConfirming()) transition({ status: "failed", draft, error, source: "commit" }); + } + function run() { + if (!isConfirming()) return; + try { + const result = callback(); + if (isPromiseLike(result)) { + void Promise.resolve(result).then(complete, reject); + return; + } + } catch (error) { + reject(error); + return; + } + complete(); + } + if (waiting) { + void waiting.then((valid) => { + if (valid) run(); + }); + } else run(); + } + + function fail(error: unknown, source: "parse") { + if (!active || state.status === "idle") return; + const { draft } = state; + invalidate(); + transition({ status: "failed", draft, error, source }); + } + + function cancel(callback?: () => unknown) { + if (!active) return; + discard(); + if (!callback) return; + if (!enabled) { + callback(); + return; + } + // Restoration failures cannot recreate an error for a draft that has been discarded. + try { + const result = callback(); + if (isPromiseLike(result)) void Promise.resolve(result).catch(() => {}); + } catch { + // There is no longer a draft to attach a restoration error to. + } + } + + return { + getRevision: () => revision, + /** Explicit discard also retires local popup/search state in retained editor controls. */ + getCancellationRevision: () => cancellationRevision, + getState: () => state, + getFailure: () => (state.status === "failed" ? state : undefined), + setErrorDetailsOpen(failure: CellEditFailure, open: boolean): CellEditFailure | undefined { + if (!active || state.status !== "failed" || state !== failure) return undefined; + if (!!state.detailsDismissed === !open) return state; + const next = { ...state, detailsDismissed: !open }; + transition(next); + return next; + }, + /** Registers a listener without invoking it; cleanup is idempotent and does not cancel. */ + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + begin, + change, + confirm, + fail, + cancel, + /** Resumes the retained draft; an invalidated confirmation requires an explicit retry. */ + activate(intercept: boolean) { + const resuming = !active; + enabled = intercept; + active = true; + if (resuming && state.status === "confirming") + transition({ status: "editing", draft: state.draft }); + }, + /** Invalidates async work without changing the retained draft or notifying subscribers. */ + deactivate() { + active = false; + invalidate(); + }, + }; +} diff --git a/packages/core/src/components/internals/table-core/column-types.test-d.ts b/packages/core/src/components/internals/table-core/column-types.test-d.ts new file mode 100644 index 000000000..542f0c0c0 --- /dev/null +++ b/packages/core/src/components/internals/table-core/column-types.test-d.ts @@ -0,0 +1,44 @@ +import { expectTypeOf, test } from "vitest"; +import type { Column, ColumnBase, TextCellEditOptions } from "@/components/data-table/types"; +import type { ValueDisplayDescriptor } from "./column-types"; + +type Row = { id: string; amount: number; status: string }; + +test("DataTable columns remain compatible with the neutral display descriptor", () => { + expectTypeOf>().toExtend>(); + expectTypeOf["width"]>().toEqualTypeOf(); + expectTypeOf["align"]>().toEqualTypeOf<"left" | "right" | undefined>(); + expectTypeOf["onValueCommitted"]>>().toEqualTypeOf< + (row: Row, value: string | null) => void + >(); +}); + +test("display descriptors retain the existing type/options contracts", () => { + const link: ValueDisplayDescriptor = { + type: "link", + typeOptions: { + href: (row) => { + expectTypeOf(row).toEqualTypeOf(); + return `/rows/${row.id}`; + }, + }, + }; + const money: ValueDisplayDescriptor = { + type: "money", + typeOptions: { currency: (row) => row.status }, + }; + // @ts-expect-error Links still require an href. + const missingHref: ValueDisplayDescriptor = { type: "link" }; + // @ts-expect-error Text columns do not accept typeOptions. + const textOptions: ValueDisplayDescriptor = { type: "text", typeOptions: {} }; + const numberOptions: ValueDisplayDescriptor = { + type: "number", + // @ts-expect-error Number columns do not accept currency options. + typeOptions: { currency: "USD" }, + }; + void link; + void money; + void missingHref; + void textOptions; + void numberOptions; +}); diff --git a/packages/core/src/components/internals/table-core/column-types.ts b/packages/core/src/components/internals/table-core/column-types.ts new file mode 100644 index 000000000..3d59e76a5 --- /dev/null +++ b/packages/core/src/components/internals/table-core/column-types.ts @@ -0,0 +1,91 @@ +import type { BadgeOptions } from "@/components/badge-list"; + +/** Built-in display renderers, independent of how a component obtains or edits a value. */ +export type ColumnCellType = "text" | "number" | "money" | "date" | "badge" | "link"; + +/** Options for `type: "number"` cells. */ +export interface NumberCellOptions { + /** Minimum decimal places. Default: `0`. */ + minDecimals?: number; + /** Maximum decimal places. Default: `minDecimals` (or `0`). */ + maxDecimals?: number; + /** BCP 47 locale tag. Defaults to the runtime locale. */ + locale?: string; +} + +/** Options for `type: "money"` cells. */ +export interface MoneyCellOptions> { + /** + * ISO 4217 currency code. Pass a string for a static currency or a function + * to read it from the row. Default: `"USD"`. + */ + currency?: string | ((row: TRow) => string); + /** + * Maximum decimals. Raises the cap above the currency default while keeping + * the minimum at the currency default (e.g. USD stays at ≥2, but a price + * column can show up to 4). + */ + maxDecimals?: number; + /** BCP 47 locale tag. Defaults to the runtime locale. */ + locale?: string; +} + +/** Options for `type: "date"` cells. */ +export interface DateCellOptions { + /** + * Format style. `"short"` → `Apr 9, 2026`; `"long"` → `April 9, 2026`; + * `"datetime"` → `Apr 9, 2026, 3:45 PM`. Default: `"short"`. + */ + dateFormat?: "short" | "long" | "datetime"; + /** BCP 47 locale tag. Defaults to the runtime locale. */ + locale?: string; +} + +/** Options for `type: "badge"` cells. */ +export interface BadgeCellOptions extends BadgeOptions { + /** Maximum number of badges to display before showing a "+N" overflow indicator */ + maxVisible?: number; +} + +/** Options for `type: "link"` cells. `href` is required. */ +export interface LinkCellOptions> { + /** + * Extracts the link target. Returning `null` / `undefined` renders the cell + * value as plain text instead of a link. + */ + href: (row: TRow) => string | null | undefined; +} + +/** Resolved presentation only: no accessor, edit choices, filters, or table state. */ +export type ValueDisplayDescriptor> = + | { type?: undefined; typeOptions?: never } + | { type: "text"; typeOptions?: never } + | { type: "number"; typeOptions?: NumberCellOptions } + | { type: "money"; typeOptions?: MoneyCellOptions } + | { type: "date"; typeOptions?: DateCellOptions } + | { type: "badge"; typeOptions?: BadgeCellOptions } + | { type: "link"; typeOptions: LinkCellOptions }; + +/** Values accepted by each built-in display renderer. */ +export interface ColumnDisplayValues { + text: string | number | boolean | bigint | null | undefined; + number: number | null | undefined; + money: number | null | undefined; + date: Date | string | number | null | undefined; + badge: string | string[] | number | boolean | null | undefined; + link: string | number | boolean | null | undefined; +} + +export type TypedColumnDisplay< + TRow extends Record, + K extends ColumnCellType, +> = Extract, { type: K }>; + +/** A display type must accept the value produced by its column's source. */ +export type ColumnDisplay, TValue> = + | { type?: undefined; typeOptions?: never } + | { + [K in ColumnCellType]: [TValue] extends [ColumnDisplayValues[K]] + ? TypedColumnDisplay + : never; + }[ColumnCellType]; diff --git a/packages/core/src/components/internals/table-core/display-cell-adapters.test.tsx b/packages/core/src/components/internals/table-core/display-cell-adapters.test.tsx new file mode 100644 index 000000000..ccd06acae --- /dev/null +++ b/packages/core/src/components/internals/table-core/display-cell-adapters.test.tsx @@ -0,0 +1,205 @@ +import type { ReactNode } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { cleanup, render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router"; +import { createValueRenderer } from "./cell-renderers"; +import { displayCellAdapters } from "./display-cell-adapters"; +import type { ColumnCellType } from "./column-types"; + +const context = { timeZone: "America/New_York" }; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const adapterCases: Record< + ColumnCellType, + { + adapter: { defaultAlign: "left" | "right" }; + align: "left" | "right"; + renderValue: () => ReactNode; + text: string; + href?: string; + } +> = { + text: { + adapter: displayCellAdapters.text, + align: "left", + renderValue: () => + displayCellAdapters.text.createRenderer({ type: "text" }, context)("Text", {}), + text: "Text", + }, + number: { + adapter: displayCellAdapters.number, + align: "right", + renderValue: () => + displayCellAdapters.number.createRenderer( + { type: "number", typeOptions: { locale: "en-US", minDecimals: 2, maxDecimals: 2 } }, + context, + )(12.5, {}), + text: "12.50", + }, + money: { + adapter: displayCellAdapters.money, + align: "right", + renderValue: () => + displayCellAdapters.money.createRenderer<{ currency: string }>( + { type: "money", typeOptions: { locale: "en-US", currency: (row) => row.currency } }, + context, + )(12.5, { currency: "EUR" }), + text: "€12.50", + }, + date: { + adapter: displayCellAdapters.date, + align: "left", + renderValue: () => + displayCellAdapters.date.createRenderer( + { type: "date", typeOptions: { locale: "en-US" } }, + context, + )("2026-10-09T00:00:00Z", {}), + text: "Oct 8, 2026", + }, + badge: { + adapter: displayCellAdapters.badge, + align: "left", + renderValue: () => + displayCellAdapters.badge.createRenderer( + { type: "badge", typeOptions: { badgeLabelMap: { open: "Open" } } }, + context, + )("open", {}), + text: "Open", + }, + link: { + adapter: displayCellAdapters.link, + align: "left", + renderValue: () => + displayCellAdapters.link.createRenderer<{ id: string }>( + { type: "link", typeOptions: { href: (row) => `/rows/${row.id}` } }, + context, + )("Resolved", { id: "A" }), + text: "Resolved", + href: "/rows/A", + }, +}; + +describe("display cell adapters", () => { + it.each(Object.entries(adapterCases))( + "pairs %s rendering with its default alignment", + (_kind, { adapter, align, renderValue, text, href }) => { + expect(adapter.defaultAlign).toBe(align); + render({renderValue()}); + expect(screen.getByText(text)).toBeDefined(); + if (href) expect(screen.getByRole("link").getAttribute("href")).toBe(href); + }, + ); + + it.each([undefined, { timeZone: "" }])( + "rejects date preparation without a timezone at runtime (%j)", + (invalidContext) => { + expect(() => + displayCellAdapters.date.createRenderer( + { type: "date" }, + // @ts-expect-error Exercise JavaScript configuration outside the typed contract. + invalidContext, + ), + ).toThrow("Date rendering requires a timezone."); + }, + ); +}); + +describe("neutral value rendering", () => { + it("renders the supplied value without looking up row properties or edit choices", () => { + const descriptor = { + type: "text" as const, + id: "status", + edit: { options: [{ value: "open", label: "Choice label" }] }, + }; + const renderer = createValueRenderer(descriptor, context); + expect(renderer("open", { status: "different" })).toBe("open"); + expect(renderer(false, { status: "different" })).toBe("✗"); + expect(createValueRenderer({}, context)({ count: 2 }, {})).toBe('{"count":2}'); + }); + + it("formats display precision without changing a supplied number", () => { + const value = 12.345; + const renderer = createValueRenderer( + { type: "number", typeOptions: { locale: "en-US", minDecimals: 2, maxDecimals: 2 } }, + context, + ); + render(<>{renderer(value, {})}>); + expect(screen.getByText("12.35")).toBeDefined(); + expect(value).toBe(12.345); + }); + + it("resolves currency from each row and retains the invalid-currency fallback", () => { + const renderer = createValueRenderer<{ currency: string }>( + { type: "money", typeOptions: { locale: "en-US", currency: (row) => row.currency } }, + context, + ); + const view = render(<>{renderer(12.5, { currency: "EUR" })}>); + expect(screen.getByText("€12.50")).toBeDefined(); + view.rerender(<>{renderer(12.5, { currency: "invalid currency" })}>); + expect(screen.getByText("$12.50")).toBeDefined(); + }); + + it("applies only the explicitly supplied badge display policy", () => { + const descriptor = { type: "badge" as const, typeOptions: { badgeLabelMap: { open: "Open" } } }; + const normal = createValueRenderer(descriptor, context); + const resolved = createValueRenderer(descriptor, { + ...context, + resolveBadgeLabel: (value) => `Resolved ${value}`, + }); + const view = render(<>{normal("open", {})}>); + expect(screen.getByText("Open")).toBeDefined(); + view.rerender(<>{resolved("open", {})}>); + expect(screen.getByText("Resolved open")).toBeDefined(); + expect(screen.queryByText("Open")).toBeNull(); + }); + + it("renders links from the supplied label and row-dependent href, or plain text without href", () => { + const renderer = createValueRenderer<{ id?: string }>( + { type: "link", typeOptions: { href: (row) => (row.id ? `/rows/${row.id}` : null) } }, + context, + ); + const view = render({renderer("Resolved label", { id: "A" })}); + expect(screen.getByRole("link", { name: "Resolved label" }).getAttribute("href")).toBe( + "/rows/A", + ); + view.rerender({renderer("Resolved label", {})}); + expect(screen.queryByRole("link")).toBeNull(); + expect(screen.getByText("Resolved label")).toBeDefined(); + }); + + it("keeps independent date-only and zoned formatter caches across rows", () => { + const DateTimeFormat = Intl.DateTimeFormat; + const spy = vi.spyOn(Intl, "DateTimeFormat").mockImplementation(function (locale, options) { + return new DateTimeFormat(locale, options); + }); + const renderer = createValueRenderer( + { type: "date", typeOptions: { locale: "en-US" } }, + context, + ); + for (let index = 0; index < 3; index++) { + expect(renderer("2026-10-09", {})).toBe("Oct 9, 2026"); + expect(renderer("2026-10-09T00:00:00Z", {})).toBe("Oct 8, 2026"); + } + expect( + spy.mock.calls + .filter(([locale, options]) => locale === "en-US" && options?.month === "short") + .map(([, options]) => options?.timeZone), + ).toEqual(["UTC", "America/New_York"]); + }); + + it("preserves a skipped calendar date and placeholders without constructing invalid formatters", () => { + const renderer = createValueRenderer( + { type: "date", typeOptions: { locale: "en-US" } }, + { timeZone: "Pacific/Apia" }, + ); + expect(renderer("2011-12-30", {})).toBe("Dec 30, 2011"); + const view = render(<>{renderer("2026-02-30", {})}>); + expect(screen.getByText("—")).toBeDefined(); + view.rerender(<>{createValueRenderer({ type: "badge" }, context)([null, ""], {})}>); + expect(screen.getByText("—")).toBeDefined(); + }); +}); diff --git a/packages/core/src/components/internals/table-core/display-cell-adapters.tsx b/packages/core/src/components/internals/table-core/display-cell-adapters.tsx new file mode 100644 index 000000000..285aa1cb3 --- /dev/null +++ b/packages/core/src/components/internals/table-core/display-cell-adapters.tsx @@ -0,0 +1,224 @@ +import type { ReactNode } from "react"; +import { parseDate } from "@internationalized/date"; +import { Link } from "react-router"; +import { BadgeList, toValueArray } from "@/components/badge-list"; +import { normalizeTemporalFilterValue } from "@/lib/temporal-filter-values"; +import type { + BadgeCellOptions, + ColumnCellType, + DateCellOptions, + LinkCellOptions, + MoneyCellOptions, + NumberCellOptions, + TypedColumnDisplay, +} from "./column-types"; +import type { DisplayCellAdapter, ValueRenderer, ValueRendererContext } from "./cell-renderers"; + +const PLACEHOLDER = ( + + — + +); + +function isEmpty(value: unknown): boolean { + return value == null || value === ""; +} + +function renderText(value: unknown): ReactNode { + switch (true) { + case isEmpty(value): + return PLACEHOLDER; + case typeof value === "boolean": + return value ? "✓" : "✗"; + case value instanceof Date: + return value.toLocaleDateString(); + case typeof value === "object": + return JSON.stringify(value); + default: + return String(value); + } +} + +function renderNumber(value: unknown, options: NumberCellOptions | undefined): ReactNode { + if (isEmpty(value)) return PLACEHOLDER; + const num = Number(value); + if (Number.isNaN(num)) return PLACEHOLDER; + const min = options?.minDecimals ?? 0; + const formatted = new Intl.NumberFormat(options?.locale, { + minimumFractionDigits: min, + maximumFractionDigits: options?.maxDecimals ?? min, + }).format(num); + return {formatted}; +} + +function renderMoney>( + value: unknown, + row: TRow, + options: MoneyCellOptions | undefined, +): ReactNode { + if (isEmpty(value)) return PLACEHOLDER; + const num = Number(value); + if (Number.isNaN(num)) return PLACEHOLDER; + const currency = + (typeof options?.currency === "function" ? options.currency(row) : options?.currency) || "USD"; + + // `maxDecimals` raises the cap above the currency default while retaining its minimum. + const formatOptions: Intl.NumberFormatOptions = { style: "currency", currency }; + if (options?.maxDecimals != null) formatOptions.maximumFractionDigits = options.maxDecimals; + let formatted: string; + try { + formatted = new Intl.NumberFormat(options?.locale, formatOptions).format(num); + } catch { + // Invalid currency codes retain the existing USD fallback. + formatted = new Intl.NumberFormat(options?.locale, { + style: "currency", + currency: "USD", + }).format(num); + } + return {formatted}; +} + +function resolveDateFormatOptions(format: string): Intl.DateTimeFormatOptions { + if (format === "long") return { month: "long", day: "numeric", year: "numeric" }; + if (format === "datetime") { + return { + month: "short", + day: "numeric", + year: "numeric", + hour: "numeric", + minute: "2-digit", + }; + } + return { month: "short", day: "numeric", year: "numeric" }; +} + +/** Bind date-only and datetime formatting to a timezone once, retaining independent formatter caches. */ +function createDateRenderer( + options: DateCellOptions | undefined, + timeZone: string, +): (value: unknown) => ReactNode { + const formatOptions = resolveDateFormatOptions(options?.dateFormat ?? "short"); + let dateOnlyFormatter: Intl.DateTimeFormat | undefined; + let datetimeFormatter: Intl.DateTimeFormat | undefined; + return (value) => { + if (isEmpty(value)) return PLACEHOLDER; + const dateOnly = typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value.trim()); + let date: Date; + if (dateOnly) { + // Calendar dates have no instant, even when a timezone skips an entire day. + try { + date = parseDate(value.trim()).toDate("UTC"); + } catch { + return PLACEHOLDER; + } + } else { + const normalized = normalizeTemporalFilterValue("datetime", value, timeZone); + if (!normalized) return PLACEHOLDER; + date = new Date(normalized); + } + const formatter = dateOnly + ? (dateOnlyFormatter ??= new Intl.DateTimeFormat(options?.locale, { + ...formatOptions, + timeZone: "UTC", + })) + : (datetimeFormatter ??= new Intl.DateTimeFormat(options?.locale, { + ...formatOptions, + timeZone, + })); + return formatter.format(date); + }; +} + +function renderBadge( + value: unknown, + options: BadgeCellOptions | undefined, + resolveLabel: ((value: string) => string) | undefined, +): ReactNode { + if (toValueArray(value).filter((item) => item != null && item !== "").length === 0) + return PLACEHOLDER; + return ( + + ); +} + +function renderLink>( + value: unknown, + row: TRow, + options: LinkCellOptions, +): ReactNode { + if (isEmpty(value)) return PLACEHOLDER; + const label = String(value); + const href = options.href(row); + if (!href) return label; + return ( + + {label} + + ); +} + +/** Each display kind owns its formatting, dependencies, and default presentation policy. */ +export const displayCellAdapters = { + text: { + defaultAlign: "left", + createRenderer: >( + _display: TypedColumnDisplay, + _context: ValueRendererContext, + ): ValueRenderer => renderText, + }, + number: { + defaultAlign: "right", + createRenderer: + >( + display: TypedColumnDisplay, + _context: ValueRendererContext, + ): ValueRenderer => + (value) => + renderNumber(value, display.typeOptions), + }, + money: { + defaultAlign: "right", + createRenderer: + >( + display: TypedColumnDisplay, + _context: ValueRendererContext, + ): ValueRenderer => + (value, row) => + renderMoney(value, row, display.typeOptions), + }, + date: { + defaultAlign: "left", + createRenderer: >( + display: TypedColumnDisplay, + context: ValueRendererContext, + ): ValueRenderer => { + if (!context?.timeZone) throw new Error("Date rendering requires a timezone."); + return createDateRenderer(display.typeOptions, context.timeZone); + }, + }, + badge: { + defaultAlign: "left", + createRenderer: + >( + display: TypedColumnDisplay, + context: ValueRendererContext, + ): ValueRenderer => + (value) => + renderBadge(value, display.typeOptions, context.resolveBadgeLabel), + }, + link: { + defaultAlign: "left", + createRenderer: + >( + display: TypedColumnDisplay, + _context: ValueRendererContext, + ): ValueRenderer => + (value, row) => + renderLink(value, row, display.typeOptions), + }, +} satisfies { [K in ColumnCellType]: DisplayCellAdapter }; diff --git a/packages/core/src/components/internals/table-core/editing/cell.test-d.ts b/packages/core/src/components/internals/table-core/editing/cell.test-d.ts new file mode 100644 index 000000000..e996ea977 --- /dev/null +++ b/packages/core/src/components/internals/table-core/editing/cell.test-d.ts @@ -0,0 +1,128 @@ +import type { ComponentProps } from "react"; +import { expectTypeOf, test } from "vitest"; +import { EditableCell, type EditableCellOwnerProps } from "./cell"; +import { choiceEditor } from "./choice"; +import { dateEditor } from "./date"; +import { numberEditor, textEditor } from "./typing"; +import type { CellEditorOptions, CellEditorOutput, CellEditorProps } from "./props"; + +declare const ownerProps: EditableCellOwnerProps; + +test("injected editors retain required options without a kind discriminator", () => { + type ChoiceOptions = CellEditorOptions; + type DateOptions = CellEditorOptions; + expectTypeOf().toEqualTypeOf< + readonly { value: string; label: string }[] + >(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf<"options" | "renderOption">(); + expectTypeOf().toEqualTypeOf< + "withTime" | "timeZone" | "minValue" | "maxValue" | "isDateUnavailable" + >(); + expectTypeOf, "timeZone">>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + + EditableCell({ + ...ownerProps, + editor: choiceEditor, + options: { + options: [{ value: "open", label: "Open" }], + renderOption: (value, label) => { + expectTypeOf(value).toEqualTypeOf(); + expectTypeOf(label).toEqualTypeOf(); + return label; + }, + }, + }); + EditableCell({ ...ownerProps, editor: dateEditor, options: { withTime: true, timeZone: "UTC" } }); + EditableCell({ ...ownerProps, editor: dateEditor, options: { timeZone: "UTC" } }); + EditableCell({ ...ownerProps, editor: textEditor, options: {} }); + EditableCell({ ...ownerProps, editor: numberEditor, options: {} }); +}); + +test("editor implementations expose their confirmed output types", () => { + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf(); + + const commitNumber: ComponentProps["commit"] = (value) => { + expectTypeOf(value).toEqualTypeOf(); + }; + commitNumber(12.5); + commitNumber(null); + // @ts-expect-error The numeric input cannot confirm text. + commitNumber("12.5"); + + const commitText: ComponentProps["commit"] = (value) => { + expectTypeOf(value).toEqualTypeOf(); + }; + commitText("text"); + commitText(null); + // @ts-expect-error The text input cannot confirm a numeric value. + commitText(12.5); +}); + +test("cell confirmation types are inferred only from the selected editor", () => { + EditableCell({ + ...ownerProps, + editor: numberEditor, + options: {}, + commit: (value) => { + expectTypeOf(value).toEqualTypeOf(); + }, + }); + EditableCell({ + ...ownerProps, + editor: choiceEditor, + options: { options: [] }, + commit: (value) => { + expectTypeOf(value).toEqualTypeOf(); + }, + }); + EditableCell({ + ...ownerProps, + editor: numberEditor, + options: {}, + // @ts-expect-error A callback cannot widen a number editor's output to text. + commit: (_value: string | null) => {}, + }); + EditableCell({ + ...ownerProps, + editor: numberEditor, + options: {}, + // @ts-expect-error A number editor can confirm null on clear. + commit: (_value: number) => {}, + }); + EditableCell({ + ...ownerProps, + editor: dateEditor, + options: { timeZone: "UTC" }, + // @ts-expect-error A callback cannot change the confirmed output of a date editor. + commit: (_value: number | null) => {}, + }); +}); + +test("options cannot widen or disagree with the injected editor", () => { + // @ts-expect-error Choice options remain required. + EditableCell({ ...ownerProps, editor: choiceEditor }); + // @ts-expect-error A choice editor requires its fixed choices. + EditableCell({ ...ownerProps, editor: choiceEditor, options: {} }); + // @ts-expect-error Date options cannot substitute for choice options. + EditableCell({ ...ownerProps, editor: choiceEditor, options: { withTime: true } }); + // @ts-expect-error Fixed candidates use options, not a second choices shape. + EditableCell({ ...ownerProps, editor: choiceEditor, options: { choices: [] } }); + // @ts-expect-error A date editor cannot receive choice options. + EditableCell({ ...ownerProps, editor: dateEditor, options: { timeZone: "UTC", options: [] } }); + // @ts-expect-error The date adapter must resolve its timezone before rendering. + EditableCell({ ...ownerProps, editor: dateEditor, options: { withTime: true } }); + // @ts-expect-error A timezone is not part of the generic cell contract. + EditableCell({ ...ownerProps, editor: numberEditor, options: {}, timeZone: "UTC" }); + // @ts-expect-error A number editor has no date options. + EditableCell({ ...ownerProps, editor: numberEditor, options: { withTime: true } }); + // @ts-expect-error Options describe the selected editor, not another kind. + EditableCell({ ...ownerProps, editor: textEditor, options: { type: "number" } }); +}); diff --git a/packages/core/src/components/internals/table-core/editing/cell.tsx b/packages/core/src/components/internals/table-core/editing/cell.tsx new file mode 100644 index 000000000..982f83ed7 --- /dev/null +++ b/packages/core/src/components/internals/table-core/editing/cell.tsx @@ -0,0 +1,78 @@ +import type { ComponentProps, ReactNode } from "react"; +import type { Table } from "@/components/table"; +import { EditableCellFrame } from "./shared"; +import type { CellEditor, CellEditorProps, CellEditorView } from "./props"; + +/** + * Table-owned values, callbacks, session lifetime, and cell presentation. + * Editor settings and render-time composition are supplied separately by EditableCell. + * + * @see CellEditorProps for the inherited input and confirmation contract. + */ +export type EditableCellOwnerProps = Omit< + CellEditorProps, + "children" | "options" | "valueLabel" +> & { + /** Owner-formatted adopted value, including custom content or null; an editor may supply a draft preview instead. */ + display: ReactNode; + /** Underlying table-cell props; the frame merges className and owns editing/error attributes and handlers. */ + cellProps: ComponentProps; + /** Ellipsizes the display preview without changing the value passed to the input. */ + truncate?: boolean; + /** Tooltip text for the resting display; suppressed during active editing or callback errors. */ + tooltipLabel?: string; +}; + +/** + * Shared boundary between table-owned data/presentation and an injected input editor. + * The cell composes the editor with its frame; it neither selects an editor kind nor owns row data. + * Options and confirmed output are inferred from editor alone, so settings and callbacks cannot widen its contract. + * + * @typeParam TOptions - Settings accepted by the selected editor, without a kind discriminator. + * @typeParam TOutput - Complete confirmed value type, including null when the editor can clear its value. + * @see EditableCellOwnerProps for owner-supplied values, callbacks, and presentation. + */ +export type EditableCellProps = EditableCellOwnerProps> & { + /** Concrete input implementation and its icon/preview policy; also the source of options and output types. */ + editor: CellEditor; + /** Required settings of this editor, such as fixed options or date-time mode; cannot select another editor kind. */ + options: NoInfer; +}; + +/** Owns cell presentation; the injected editor supplies input behavior without mirrored state. */ +export function EditableCell({ + editor, + options, + display, + cellProps, + truncate, + tooltipLabel, + ...props +}: EditableCellProps) { + const { labels, slotPrefix } = props; + const { Editor, icon, hideDisplay } = editor; + const renderEditor = ({ input, draftPreview, ...interaction }: CellEditorView) => ( + + {input} + + ); + return ( + + {renderEditor} + + ); +} diff --git a/packages/core/src/components/internals/table-core/editing/choice.tsx b/packages/core/src/components/internals/table-core/editing/choice.tsx new file mode 100644 index 000000000..cd631c3e5 --- /dev/null +++ b/packages/core/src/components/internals/table-core/editing/choice.tsx @@ -0,0 +1,403 @@ +import { + useMemo, + useRef, + useState, + type ComponentProps, + type FocusEvent, + type MouseEvent, + type ReactNode, + type TouchEvent, +} from "react"; +import { Combobox as BaseCombobox } from "@base-ui/react/combobox"; +import { ChevronDown } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { isComposing } from "@/lib/is-composing"; +import { ComboboxParts } from "@/components/combobox"; +import { toTextValue } from "../input-values"; +import { useCellEditSession } from "./use-session"; +import { + CELL_ERROR_CLASS_NAME, + ICON_INPUT_CLASS_NAME, + INPUT_CLASS_NAME, + INPUT_DISPLAY, + useCellError, + useDraftStatus, + useNavigationRef, +} from "./shared"; +import type { CellEditor, CellEditorProps } from "./props"; + +/** One dropdown choice; `value: null` is "None". */ +interface Choice { + value: string | null; + label: string; +} + +type ChoiceDraft = Choice & { notified?: boolean }; + +// Case- and width-insensitive searching: full-width letters and half-width +// katakana match their usual forms. +const searchable = (text: string) => text.normalize("NFKC").toLocaleLowerCase().trim(); + +const isChoiceEqual = (a: Choice, b: Choice) => a.value === b.value; + +const choiceLabel = (choice: Choice) => choice.label; + +type ChoiceEditorOptions = { + options: readonly { value: string; label: string }[]; + renderOption?: (value: string, label: string) => ReactNode; +}; + +function ChoiceEditor({ + options: { options, renderOption }, + current, + allowClear = true, + change = () => undefined, + commit, + renderError, + labels, + interceptErrors = true, + session: external, + rowKey, + colKey, + label, + align, + navigation, + children, +}: CellEditorProps) { + const session = useCellEditSession(interceptErrors, external); + const { state } = session; + const { callbackError, containsErrorTarget } = useCellError( + { labels, renderError }, + state.status === "failed" ? state : undefined, + ); + const register = useNavigationRef(navigation, rowKey, colKey); + const value = toTextValue(current); + const shouldCommit = (next: string | null) => next !== value || (!!external && next === null); + const noneLabel = labels.none; + // Keyed on content: rebuilding columns must not reset the highlight mid-search. + const optionsKey = (options ?? []).map((c) => `${c.value}\u0000${c.label}`).join("\u0001"); + const items = useMemo( + () => [ + ...(allowClear ? [{ value: null, label: noneLabel }] : []), + ...(options ?? []).map((c) => ({ value: c.value, label: String(c.label) })), + ], + // eslint-disable-next-line react-hooks/exhaustive-deps -- `optionsKey` stands for `options`. + [optionsKey, noneLabel, allowClear], + ); + + const selected = items.find((item) => item.value === value) ?? null; + const [open, setOpen] = useState(false); + const [focused, setFocused] = useState(false); + const editing = state.status !== "idle"; + const activeChoice = state.status === "idle" ? selected : state.draft; + const draftStatus = useDraftStatus( + labels, + !!external, + activeChoice?.value !== value, + state.status, + ); + // The displayed search text is local while editing, even if consumer data changes. + const [query, setQuery] = useState(null); + // Keep the closing list filtered until its animation completes. + const [listQuery, setListQuery] = useState(null); + const highlightedRef = useRef(undefined); + const explicitHighlightRef = useRef(undefined); + const composingRef = useRef(false); + const selectOnMouseUpRef = useRef(false); + const from = { rowKey, colKey }; + const cancellation = session.getCancellationRevision(); + const [seenCancellation, setSeenCancellation] = useState(cancellation); + if (external && seenCancellation !== cancellation) { + setSeenCancellation(cancellation); + setOpen(false); + setQuery(null); + setListQuery(null); + highlightedRef.current = undefined; + explicitHighlightRef.current = undefined; + } + + const filtered = useMemo(() => { + const search = searchable(listQuery ?? ""); + if (!search) return items; + const rank = (item: Choice) => { + const text = searchable(item.label); + if (text === search) return 0; + return text.startsWith(search) ? 1 : 2; + }; + return ( + items + .filter((item) => item.value !== null && searchable(item.label).includes(search)) + // Sorting is stable, preserving the original order within each rank. + .toSorted((left, right) => rank(left) - rank(right)) + ); + }, [items, listQuery]); + + const startEditing = () => { + session.begin(selected ?? { value, label: value ?? noneLabel }); + setQuery(selected?.label ?? ""); + setListQuery(null); + highlightedRef.current = undefined; + explicitHighlightRef.current = undefined; + }; + + const closeEditor = () => { + setQuery(null); + explicitHighlightRef.current = undefined; + setOpen(false); + }; + + const cancelEditing = () => { + const active = session.getState(); + session.cancel( + active.status !== "idle" && active.draft.notified && active.draft.value !== value + ? () => change(value) + : undefined, + ); + closeEditor(); + }; + + const leaveEditor = () => { + const active = session.getState(); + if (active.status === "failed" || active.status === "confirming") closeEditor(); + else cancelEditing(); + }; + + const pick = (item: Choice) => { + const active = session.getState(); + if (active.status === "confirming" && active.draft.value === item.value) return; + session.change( + { ...item, notified: item.value !== value }, + item.value !== value ? () => change(item.value) : undefined, + ); + setQuery(item.label); + session.confirm(() => (shouldCommit(item.value) ? commit(item.value) : undefined), closeEditor); + }; + + const explicitCandidate = () => { + const item = explicitHighlightRef.current; + return item && filtered.includes(item) ? item : undefined; + }; + + const keyboardCandidate = () => { + const highlighted = highlightedRef.current; + return ( + explicitCandidate() ?? + (highlighted && filtered.includes(highlighted) ? highlighted : filtered[0]) + ); + }; + + const handleKeyDown: NonNullable["onKeyDown"]> = ( + event, + ) => { + if (isComposing(event.nativeEvent, composingRef.current)) { + event.preventBaseUIHandler(); + return; + } + switch (event.key) { + case "Enter": { + event.preventDefault(); + event.preventBaseUIHandler(); + const active = session.getState(); + if (active.status === "confirming") return; + if (!open) { + if (active.status === "failed" && active.source === "commit") { + session.confirm( + () => (shouldCommit(active.draft.value) ? commit(active.draft.value) : undefined), + closeEditor, + ); + return; + } + if (active.status === "idle") startEditing(); + setOpen(true); + return; + } + const item = keyboardCandidate(); + if (item) pick(item); + else leaveEditor(); + return; + } + case "Tab": { + event.preventBaseUIHandler(); + const item = + session.getState().status !== "idle" && open + ? (explicitCandidate() ?? + (searchable(listQuery ?? "") ? keyboardCandidate() : undefined)) + : undefined; + if (item) pick(item); + else leaveEditor(); + if (navigation?.move(from, event.shiftKey ? "prev" : "next")) event.preventDefault(); + return; + } + case "Escape": + if (session.getState().status === "idle" && !open) return; + event.preventDefault(); + event.stopPropagation(); + event.preventBaseUIHandler(); + cancelEditing(); + return; + } + }; + + const handleFocus = (event: FocusEvent) => { + const withinCell = focused || containsErrorTarget(event.relatedTarget); + setFocused(true); + if (withinCell) return; + if (session.getState().status === "idle") startEditing(); + event.currentTarget.select(); + }; + + const handleBlur = () => { + setFocused(false); + leaveEditor(); + }; + + const handleMouseDown = (event: MouseEvent