diff --git a/.changeset/plain-language-errors.md b/.changeset/plain-language-errors.md new file mode 100644 index 00000000..3cb7a3f8 --- /dev/null +++ b/.changeset/plain-language-errors.md @@ -0,0 +1,5 @@ +--- +"@datum-cloud/datum-ui": minor +--- + +Adds `@datum-cloud/datum-ui/error-content`: `ErrorContent`, `describeApiError` and `ErrorDescriptionProvider` for plain-language errors that keep the raw text under Error details. A failed `DataTable.Server` load now shows an error with Retry instead of "No results."; the store has `refetch()` and `DataTable.Content` takes `errorContent`. TaskQueue formats thrown errors (override with `formatError`) and shows the raw text in its summary. Dropzone explains each rejected file and adds `onReject`. diff --git a/apps/storybook/stories/features/dropzone.stories.tsx b/apps/storybook/stories/features/dropzone.stories.tsx index e1e110ec..9733e94e 100644 --- a/apps/storybook/stories/features/dropzone.stories.tsx +++ b/apps/storybook/stories/features/dropzone.stories.tsx @@ -35,13 +35,17 @@ type Story = StoryObj function DefaultStory(args: DropzoneStoryArgs) { const [files, setFiles] = useState(undefined) + const [error, setError] = useState() return (
setFiles(accepted)} - onError={err => alert(err.message)} + onDrop={(accepted) => { + setFiles(accepted) + setError(undefined) + }} + onError={err => setError(err.message)} > + {error &&

{error}

}
) } @@ -68,12 +73,16 @@ export const Default: Story = { function WithConstraintsStory() { const [files, setFiles] = useState(undefined) + const [error, setError] = useState() return (
setFiles(accepted)} - onError={err => alert(err.message)} + onDrop={(accepted) => { + setFiles(accepted) + setError(undefined) + }} + onError={err => setError(err.message)} accept={{ 'image/*': ['.png', '.jpg', '.jpeg', '.gif'] }} maxSize={5 * 1024 * 1024} maxFiles={3} @@ -85,6 +94,7 @@ function WithConstraintsStory() { /> + {error &&

{error}

}
) } diff --git a/apps/storybook/stories/features/error-content.stories.tsx b/apps/storybook/stories/features/error-content.stories.tsx new file mode 100644 index 00000000..162b764d --- /dev/null +++ b/apps/storybook/stories/features/error-content.stories.tsx @@ -0,0 +1,60 @@ +import type { Meta, StoryObj } from 'storybook-react-rsbuild' +import { ErrorContent, ErrorDescriptionProvider } from '@datum-cloud/datum-ui/error-content' + +const RBAC_DENIAL = 'forbidden: User \'jane@example.com\' cannot patch resource "dnsrecordsets" in API group "dns.networking.miloapis.com" in the namespace "default"' + +const meta: Meta = { + title: 'Features/ErrorContent', + component: ErrorContent, + parameters: { + layout: 'centered', + docs: { + description: { + component: + 'Shows an error in plain language: a headline, the next step and actions, with the raw ' + + 'technical text in a collapsed **Error details** section. `describeApiError` writes the ' + + 'headline; wrap the app in `ErrorDescriptionProvider` to change the wording.', + }, + }, + }, + argTypes: { + variant: { control: 'select', options: ['default', 'minimal'] }, + }, + args: { + variant: 'default', + }, +} + +export default meta +type Story = StoryObj + +export const PermissionDenied: Story = { + args: { + error: { kind: 'Status', reason: 'Forbidden', code: 403, message: RBAC_DENIAL, requestId: 'req-7f3a' }, + actions: [{ label: 'Retry', onClick: () => {} }], + }, +} + +export const WithProductAreaLabels: Story = { + render: args => ( + + + + ), + args: { + error: { kind: 'Status', reason: 'Forbidden', code: 403, message: RBAC_DENIAL }, + }, +} + +export const ReadableMessage: Story = { + args: { + error: new Error('Project is not ready: the quota for load balancers is used up.'), + }, +} + +export const SessionExpired: Story = { + args: { + error: { kind: 'Status', reason: 'Unauthorized', code: 401, message: 'Unauthorized' }, + actions: [{ label: 'Sign in', as: 'link', to: '/login' }], + }, +} diff --git a/packages/datum-ui/package.json b/packages/datum-ui/package.json index 25a6a88d..3cb16b8a 100644 --- a/packages/datum-ui/package.json +++ b/packages/datum-ui/package.json @@ -287,6 +287,11 @@ "types": "./dist/components/features/empty-content/index.d.ts", "default": "./dist/empty-content/index.mjs" }, + "./error-content": { + "source": "./src/components/features/error-content/index.ts", + "types": "./dist/components/features/error-content/index.d.ts", + "default": "./dist/error-content/index.mjs" + }, "./form": { "source": "./src/components/features/form/index.ts", "types": "./dist/components/features/form/index.d.ts", diff --git a/packages/datum-ui/scripts/exports-manifest.mjs b/packages/datum-ui/scripts/exports-manifest.mjs index c598685e..e7c4ccaf 100644 --- a/packages/datum-ui/scripts/exports-manifest.mjs +++ b/packages/datum-ui/scripts/exports-manifest.mjs @@ -93,6 +93,7 @@ export const manifest = [ { subpath: './dropdown', source: './src/components/features/dropdown/index.ts' }, { subpath: './dropzone', source: './src/components/features/dropzone/index.ts' }, { subpath: './empty-content', source: './src/components/features/empty-content/index.ts' }, + { subpath: './error-content', source: './src/components/features/error-content/index.ts' }, { subpath: './form', source: './src/components/features/form/index.ts' }, { subpath: './form/adapters/conform', source: './src/components/features/form/adapters/conform/index.ts' }, { subpath: './form/adapters/rhf', source: './src/components/features/form/adapters/rhf/index.ts' }, diff --git a/packages/datum-ui/src/components/features/data-table/__tests__/content.test.tsx b/packages/datum-ui/src/components/features/data-table/__tests__/content.test.tsx index afe0e71a..ea60e649 100644 --- a/packages/datum-ui/src/components/features/data-table/__tests__/content.test.tsx +++ b/packages/datum-ui/src/components/features/data-table/__tests__/content.test.tsx @@ -2,12 +2,14 @@ import type { ColumnDef } from '@tanstack/react-table' import type { ReactNode } from 'react' import type { DataTableFeatures } from '../core/features' -import { render, screen } from '@testing-library/react' +import { render, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' +import { useEffect } from 'react' import { describe, expect, it, vi } from 'vitest' import { DataTableContent } from '../components/content' import { ClientProvider } from '../core/client-provider' -import { DataTableRenderKeyContext, DataTableStoreContext, TableInstanceContext } from '../core/data-table-context' +import { DataTableRenderKeyContext, DataTableStoreContext, TableInstanceContext, useDataTableStore } from '../core/data-table-context' +import { ServerProvider } from '../core/server-provider' import { createDataTableStore } from '../core/store' interface TestRow { @@ -305,3 +307,59 @@ describe('dataTableContent loading state', () => { expect(screen.getByText('No pods found')).toBeInTheDocument() }) }) + +describe('dataTableContent load errors', () => { + interface Row { readonly id: string, readonly name: string } + const columns = [{ accessorKey: 'name' as const, header: 'Name' }] + const transform = (response: { items: Row[] }) => ({ data: response.items, hasNextPage: false }) + const denied = { kind: 'Status', reason: 'NotFound', code: 404, message: 'gone' } + + function renderServer(fetchFn: any, content: ReactNode = ) { + return render({content}) + } + + it('shows the error with Retry instead of No results', async () => { + const { container } = renderServer((vi.fn() as any).mockRejectedValue(denied)) + expect(await screen.findByText('This item no longer exists.')).toBeInTheDocument() + expect(container.querySelector('[data-slot="dt-error"]')).not.toBeNull() + expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument() + expect(screen.queryByText('No results.')).toBeNull() + }) + + it('clears the error and shows rows after a successful retry', async () => { + const fetchFn = (vi.fn() as any).mockRejectedValueOnce(denied).mockResolvedValue({ items: [{ id: '1', name: 'Pod A' }] }) + const { container } = renderServer(fetchFn) + await userEvent.click(await screen.findByRole('button', { name: 'Retry' })) + expect(await screen.findByText('Pod A')).toBeInTheDocument() + await waitFor(() => expect(container.querySelector('[data-slot="dt-error"]')).toBeNull()) + }) + + it('renders errorContent as a node or a function', async () => { + renderServer((vi.fn() as any).mockRejectedValue(denied), ) + expect(await screen.findByText('Custom')).toBeInTheDocument() + }) + + it('passes the error and retry to an errorContent function', async () => { + const fetchFn = (vi.fn() as any).mockRejectedValue(new Error('boom')) + renderServer(fetchFn, } />) + await userEvent.click(await screen.findByRole('button', { name: 'boom' })) + await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(2)) + }) + + it('shows the error without Retry in client mode', async () => { + function FailLocally() { + const store = useDataTableStore() + useEffect(() => store.setError(new Error('local failure')), [store]) + return null + } + const { container } = render( + + + + , + ) + expect(await screen.findByRole('heading', { name: 'local failure' })).toBeInTheDocument() + expect(container.querySelector('[data-slot="dt-error"]')).not.toBeNull() + expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull() + }) +}) diff --git a/packages/datum-ui/src/components/features/data-table/__tests__/store.test.ts b/packages/datum-ui/src/components/features/data-table/__tests__/store.test.ts index 4b6a8fef..9c5219c4 100644 --- a/packages/datum-ui/src/components/features/data-table/__tests__/store.test.ts +++ b/packages/datum-ui/src/components/features/data-table/__tests__/store.test.ts @@ -347,4 +347,24 @@ describe('server mode', () => { store.setData(newData) expect(store.getSnapshot().filteredData).toBe(newData) }) + + it('refetch keeps the current query and notifies', () => { + const store = createDataTableStore({ data: sampleData, mode: 'server' }) + store.setSorting([{ id: 'name', desc: true }]) + store.setFilter('status', 'active') + store.setSearch('ali') + store.setPageIndex(2) + const listener = vi.fn() + store.subscribe(listener) + const before = store.getSnapshot() + store.refetch() + const after = store.getSnapshot() + expect(listener).toHaveBeenCalled() + expect(after._version).toBeGreaterThan(before._version) + expect(after.refetchToken).toBe(before.refetchToken + 1) + expect(after.pageIndex).toBe(before.pageIndex) + expect(after.sorting).toEqual(before.sorting) + expect(after.filters).toEqual(before.filters) + expect(after.search).toBe(before.search) + }) }) diff --git a/packages/datum-ui/src/components/features/data-table/__tests__/use-data-table-server.test.ts b/packages/datum-ui/src/components/features/data-table/__tests__/use-data-table-server.test.ts index 8a1be088..92ecf218 100644 --- a/packages/datum-ui/src/components/features/data-table/__tests__/use-data-table-server.test.ts +++ b/packages/datum-ui/src/components/features/data-table/__tests__/use-data-table-server.test.ts @@ -1,4 +1,4 @@ -import { act, renderHook } from '@testing-library/react' +import { act, renderHook, waitFor } from '@testing-library/react' import { describe, expect, it, vi } from 'vitest' import { useDataTableServer } from '../hooks/use-data-table-server' @@ -155,4 +155,23 @@ describe('useDataTableServer', () => { expect(result.current.store.getSnapshot().filters).toEqual({}) }) + + it('fetches again with the same arguments on refetch', async () => { + const fetchFn = (vi.fn() as any).mockResolvedValue({ items: [{ id: '1', name: 'Pod A' }] }) + const { result } = renderHook(() => useDataTableServer({ columns: testColumns, fetchFn, transform: mockTransform })) + await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1)) + act(() => result.current.store.refetch()) + await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(2)) + expect(fetchFn.mock.calls[1][0]).toEqual(fetchFn.mock.calls[0][0]) + }) + + it('keeps a thrown non-Error value readable and as the cause', async () => { + const thrown = { kind: 'Status', message: 'denied' } + const fetchFn = (vi.fn() as any).mockRejectedValue(thrown) + const { result } = renderHook(() => useDataTableServer({ columns: testColumns, fetchFn, transform: mockTransform })) + await waitFor(() => expect(result.current.store.getSnapshot().error).not.toBeNull()) + const error = result.current.store.getSnapshot().error! + expect(error.message).toBe('denied') + expect(error.cause).toBe(thrown) + }) }) diff --git a/packages/datum-ui/src/components/features/data-table/components/content.tsx b/packages/datum-ui/src/components/features/data-table/components/content.tsx index e9aa38f9..c769bc05 100644 --- a/packages/datum-ui/src/components/features/data-table/components/content.tsx +++ b/packages/datum-ui/src/components/features/data-table/components/content.tsx @@ -1,6 +1,7 @@ 'use client' import type { Cell, Row, RowData } from '@tanstack/react-table' +import type { ReactNode } from 'react' import type { DataTableFeatures } from '../core/features' import type { ContentProps, InlineContentEntry } from '../types' import { flexRender } from '@tanstack/react-table' @@ -15,7 +16,9 @@ import { TableHeader, TableRow, } from '../../../base/table' +import { ErrorContent } from '../../error-content/error-content' import { DEFAULT_LOADING_ROWS } from '../constants' +import { useDataTableStore } from '../core/data-table-context' import { useDataTableInlineContents, useDataTableLoading, useDataTablePagination, useDataTableRows } from '../hooks/use-selectors' /** @@ -92,8 +95,28 @@ function renderInlineContentRow( ) } +/** The body of a table whose load failed: the app's `errorContent`, or ErrorContent with Retry. */ +function renderLoadError( + error: Error, + errorContent: ContentProps['errorContent'], + retry: (() => void) | undefined, +): ReactNode { + if (typeof errorContent === 'function') + return errorContent(error, retry ?? (() => {})) + if (errorContent !== undefined) + return errorContent + return ( + + ) +} + export function DataTableContent>({ emptyMessage, + errorContent, className, tableClassName, headerClassName, @@ -106,7 +129,8 @@ export function DataTableContent>({ onRowClick, }: ContentProps) { const { rows, headerGroups, totalColumns } = useDataTableRows() - const { isLoading, columnCount } = useDataTableLoading() + const { isLoading, columnCount, error, refetch } = useDataTableLoading() + const isServer = useDataTableStore().getSnapshot().mode === 'server' const { pageSize } = useDataTablePagination() const { inlineContents } = useDataTableInlineContents() const openInlineContents = useMemo(() => inlineContents.filter(e => e.open), [inlineContents]) @@ -186,17 +210,25 @@ export function DataTableContent>({ )) ) - : ( - - - {emptyMessage ?? 'No results.'} - - - )} + : error + ? ( + + + {renderLoadError(error, errorContent, isServer ? refetch : undefined)} + + + ) + : ( + + + {emptyMessage ?? 'No results.'} + + + )} diff --git a/packages/datum-ui/src/components/features/data-table/core/store.ts b/packages/datum-ui/src/components/features/data-table/core/store.ts index ee613558..1b753130 100644 --- a/packages/datum-ui/src/components/features/data-table/core/store.ts +++ b/packages/datum-ui/src/components/features/data-table/core/store.ts @@ -68,6 +68,7 @@ export function createDataTableStore( mode: options.mode, isLoading: options.isLoading ?? false, error: null, + refetchToken: 0, inlineContents: [], _version: 0, } @@ -176,6 +177,13 @@ export function createDataTableStore( setState({ ...state, error }) }, + refetch: () => { + // Client tables hold their data already; there is nothing to fetch. + if (state.mode === 'client') + return + setState({ ...state, refetchToken: state.refetchToken + 1 }) + }, + registerFilter: (column, strategy) => { const next = new Map(registeredFilters) next.set(column, strategy) diff --git a/packages/datum-ui/src/components/features/data-table/hooks/use-data-table-server.ts b/packages/datum-ui/src/components/features/data-table/hooks/use-data-table-server.ts index 4737381c..ce4d7361 100644 --- a/packages/datum-ui/src/components/features/data-table/hooks/use-data-table-server.ts +++ b/packages/datum-ui/src/components/features/data-table/hooks/use-data-table-server.ts @@ -66,7 +66,7 @@ export function useServerTable( const hasNextPageRef = useRef(false) // 1. Read store state - const { sorting, filters, search, rowSelection, pageSize, pageIndex } + const { sorting, filters, search, rowSelection, pageSize, pageIndex, refetchToken } = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot) // 2. Fetch on query change — also resets cursors when query params change @@ -132,7 +132,7 @@ export function useServerTable( if (cancelled) return store.setServerData([] as TData[]) - store.setError(error instanceof Error ? error : new Error(String(error))) + store.setError(toError(error)) hasNextPageRef.current = false }) .finally(() => { @@ -143,7 +143,7 @@ export function useServerTable( return () => { cancelled = true } - }, [sorting, filters, search, pageSize, pageIndex, store]) + }, [sorting, filters, search, pageSize, pageIndex, refetchToken, store]) // 3. Resolve columns const resolvedColumns = useMemo( @@ -200,6 +200,20 @@ export function useServerTable( return { table } } +/** + * The store holds an `Error`. A thrown non-Error (a Kubernetes Status object, + * a response body) keeps its own message and travels as `cause`, so an error + * display can still read its reason and status. + */ +function toError(value: unknown): Error { + if (value instanceof Error) + return value + const message = typeof value === 'object' && value !== null && typeof (value as { message?: unknown }).message === 'string' + ? (value as { message: string }).message + : String(value) + return new Error(message, { cause: value }) +} + // ── useDataTableServer (convenience wrapper) ── export function useDataTableServer( diff --git a/packages/datum-ui/src/components/features/data-table/hooks/use-selectors.ts b/packages/datum-ui/src/components/features/data-table/hooks/use-selectors.ts index 5aba6591..91512752 100644 --- a/packages/datum-ui/src/components/features/data-table/hooks/use-selectors.ts +++ b/packages/datum-ui/src/components/features/data-table/hooks/use-selectors.ts @@ -3,7 +3,7 @@ import type { HeaderGroup, Row, RowData } from '@tanstack/react-table' import type { DataTableFeatures } from '../core/features' import type { DataTableStoreState, InlineContentEntry } from '../types' -import { useCallback, useRef, useSyncExternalStore } from 'react' +import { useCallback, useMemo, useRef, useSyncExternalStore } from 'react' import { useDataTableStore, useRenderKey, useTableInstanceOrNull } from '../core/data-table-context' function shallowEqual(a: Record, b: Record): boolean { @@ -150,13 +150,15 @@ export function useDataTableRows() { } export function useDataTableLoading() { - return useSliceSelector( + const store = useDataTableStore() + const slice = useSliceSelector( useCallback((state: DataTableStoreState) => ({ isLoading: state.isLoading, error: state.error, columnCount: state.columnCount, }), []), ) + return useMemo(() => ({ ...slice, refetch: store.refetch }), [slice, store]) } export function useDataTableInlineContents() { diff --git a/packages/datum-ui/src/components/features/data-table/types.ts b/packages/datum-ui/src/components/features/data-table/types.ts index 0ce8cd30..75fbd82a 100644 --- a/packages/datum-ui/src/components/features/data-table/types.ts +++ b/packages/datum-ui/src/components/features/data-table/types.ts @@ -311,6 +311,13 @@ export interface BulkActionsProps { export interface ContentProps> { readonly emptyMessage?: ReactNode + /** + * Shown instead of the empty message when loading failed. A function gets + * the error and a `retry` that fetches the same page again (a no-op for + * client tables). Defaults to `ErrorContent` with a Retry button on server + * tables. + */ + readonly errorContent?: ReactNode | ((error: Error, retry: () => void) => ReactNode) readonly className?: string readonly tableClassName?: string readonly headerClassName?: string @@ -433,6 +440,8 @@ export interface DataTableStoreState { readonly mode: 'client' | 'server' readonly isLoading: boolean readonly error: Error | null + /** Bumped by `refetch()`; a server table fetches again when it changes. */ + readonly refetchToken: number readonly inlineContents: readonly InlineContentEntry[] /** Monotonic counter incremented on every state change. Used by table-dependent selectors to detect updates. */ readonly _version: number @@ -455,6 +464,8 @@ export interface DataTableStore { readonly setPagination: (pageIndex: number, pageSize: number) => void readonly setLoading: (loading: boolean) => void readonly setError: (error: Error | null) => void + /** Fetch the current page again with the same sort, filters and search. No-op in client mode. */ + readonly refetch: () => void readonly registerFilter: (column: string, strategy: FilterStrategy) => void readonly unregisterFilter: (column: string) => void readonly registerInlineContent: (entry: InlineContentEntry) => void diff --git a/packages/datum-ui/src/components/features/dropzone/__tests__/dropzone.test.tsx b/packages/datum-ui/src/components/features/dropzone/__tests__/dropzone.test.tsx index 4c18aa96..47c72b49 100644 --- a/packages/datum-ui/src/components/features/dropzone/__tests__/dropzone.test.tsx +++ b/packages/datum-ui/src/components/features/dropzone/__tests__/dropzone.test.tsx @@ -1,7 +1,8 @@ /// -import { render, screen } from '@testing-library/react' -import { describe, expect, it } from 'vitest' -import { Dropzone, DropzoneEmptyState } from '../dropzone' +import type { FileRejection } from 'react-dropzone' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { Dropzone, DropzoneEmptyState, rejectionMessages } from '../dropzone' describe('dropzone', () => { it('renders empty state when no files', () => { @@ -36,3 +37,60 @@ describe('dropzone', () => { expect(input).toBeDisabled() }) }) + +describe('dropzone rejection messages', () => { + const MB = 1024 * 1024 + const file = (name: string, bytes: number, type = 'image/png') => new File(['x'.repeat(bytes)], name, { type }) + const rejection = (f: File, ...codes: string[]): FileRejection => ({ + file: f as FileRejection['file'], + errors: codes.map(code => ({ code, message: `raw ${code}` })), + }) + + it('explains a file that is too large or too small', () => { + const big = rejection(file('image.png', Math.round(4.2 * MB)), 'file-too-large') + const small = rejection(file('tiny.png', 10), 'file-too-small') + expect(rejectionMessages([big, small], { maxSize: MB, minSize: 1024 }).map(r => r.message)).toEqual([ + 'image.png is 4.20MB; files must be under 1.00MB.', + 'tiny.png is 10.00B; files must be at least 1.00KB.', + ]) + }) + + it('names the accepted types for a wrong type, and leaves them out with no accept list', () => { + const gif = rejection(file('a.gif', 10, 'image/gif'), 'file-invalid-type') + expect(rejectionMessages([gif], { accept: { 'image/png': [], 'image/jpeg': [] } })[0]?.message) + .toBe('a.gif isn\'t a supported file type. Use image/png and image/jpeg.') + expect(rejectionMessages([gif], {})[0]?.message).toBe('a.gif isn\'t a supported file type.') + }) + + it('gives one entry per error and keeps react-dropzone\'s text for an unknown code', () => { + const both = rejection(file('big.gif', 2 * MB, 'image/gif'), 'file-too-large', 'file-invalid-type') + const odd = rejection(file('odd.png', 10), 'custom-check') + const entries = rejectionMessages([both, odd], { maxSize: MB, accept: { 'image/png': [] } }) + expect(entries.map(e => e.code)).toEqual(['file-too-large', 'file-invalid-type', 'custom-check']) + expect(entries[2]?.message).toBe('raw custom-check') + expect(entries[0]?.file.name).toBe('big.gif') + }) + + it('words the file limit for one file and for several', () => { + const one = rejection(file('a.png', 10), 'too-many-files') + expect(rejectionMessages([one], { maxFiles: 1 })[0]?.message).toBe('You can add 1 file at a time.') + expect(rejectionMessages([one], { maxFiles: 3 })[0]?.message).toBe('You can add up to 3 files at a time.') + }) + + it('reports every rejection to onReject and a merged message to onError', async () => { + const onError = vi.fn() + const onReject = vi.fn() + const onDrop = vi.fn() + const { container } = render() + const input = container.querySelector('input[type="file"]')! + fireEvent.change(input, { target: { files: [file('a.png', 10), file('b.png', 10), file('c.png', 10)] } }) + await waitFor(() => expect(onError).toHaveBeenCalled()) + const error = onError.mock.calls[0]![0] as Error + expect(error).toBeInstanceOf(Error) + expect(error.message.split('\n').filter(line => line === 'You can add 1 file at a time.')).toHaveLength(1) + const reported = (onDrop.mock.calls[0]![1] as FileRejection[]).flatMap(r => r.errors) + expect(reported.length).toBeGreaterThanOrEqual(2) + expect(onReject.mock.calls[0]![0]).toHaveLength(reported.length) + expect(error.cause).toEqual(onReject.mock.calls[0]![0]) + }) +}) diff --git a/packages/datum-ui/src/components/features/dropzone/dropzone.tsx b/packages/datum-ui/src/components/features/dropzone/dropzone.tsx index 3594b936..f80bcd84 100644 --- a/packages/datum-ui/src/components/features/dropzone/dropzone.tsx +++ b/packages/datum-ui/src/components/features/dropzone/dropzone.tsx @@ -28,12 +28,73 @@ function renderBytes(bytes: number) { return `${size.toFixed(2)}${units[unitIndex]}` } +/** + * The MIME types an accept option allows. react-dropzone 20 widened `accept` + * from `Accept` to `Accept | AcceptGroup[]`; `Object.keys()` on the array form + * yields "0", "1", so normalise to MIME keys first. Both shapes are in range -- + * the peer is `>=15 <21`. + */ +function acceptedTypeList(accept: DropzoneOptions['accept']): string[] { + return Array.isArray(accept) + ? accept.flatMap(group => Object.keys(group.accept)) + : Object.keys(accept ?? {}) +} + +/** One reason a file was rejected, told plainly. */ +export interface DropzoneRejection { + file: File + /** react-dropzone's error code, e.g. `file-too-large`. */ + code: string + message: string +} + +interface RejectionLimits { + maxSize?: number + minSize?: number + maxFiles?: number + accept?: DropzoneOptions['accept'] +} + +/** One plain sentence per rejection error, using the same sizes and types as the caption. */ +export function rejectionMessages(rejections: FileRejection[], limits: RejectionLimits): DropzoneRejection[] { + return rejections.flatMap(({ file, errors }) => + errors.map(error => ({ file, code: error.code, message: rejectionSentence(file, error, limits) })), + ) +} + +function rejectionSentence(file: File, error: FileRejection['errors'][number], limits: RejectionLimits): string { + const size = renderBytes(file.size) + switch (error.code) { + case 'file-too-large': + return limits.maxSize === undefined + ? error.message + : `${file.name} is ${size}; files must be under ${renderBytes(limits.maxSize)}.` + case 'file-too-small': + return limits.minSize === undefined + ? error.message + : `${file.name} is ${size}; files must be at least ${renderBytes(limits.minSize)}.` + case 'file-invalid-type': { + const types = acceptedTypeList(limits.accept) + const use = types.length > 0 ? ` Use ${new Intl.ListFormat('en').format(types)}.` : '' + return `${file.name} isn't a supported file type.${use}` + } + case 'too-many-files': + return limits.maxFiles === 1 || limits.maxFiles === undefined + ? 'You can add 1 file at a time.' + : `You can add up to ${limits.maxFiles} files at a time.` + default: + return error.message + } +} + const DropzoneContext = createContext(undefined) export type DropzoneProps = Omit & { src?: File[] className?: string onDrop?: (acceptedFiles: File[], fileRejections: FileRejection[], event: DropEvent) => void + /** Every reason files were rejected, one entry per error. */ + onReject?: (rejections: DropzoneRejection[]) => void children?: ReactNode } @@ -44,6 +105,7 @@ export function Dropzone({ minSize, onDrop, onError, + onReject, disabled, src, className, @@ -58,11 +120,14 @@ export function Dropzone({ onError, disabled, onDrop: (acceptedFiles, fileRejections, event) => { - // Surface the first rejection (if any) without discarding accepted files: - // a mixed drop should still deliver the valid files to the consumer. + // Explain every rejection without discarding accepted files: a mixed + // drop should still deliver the valid files to the consumer. if (fileRejections.length > 0) { - const message = fileRejections.at(0)?.errors.at(0)?.message - onError?.(new Error(message)) + const rejections = rejectionMessages(fileRejections, { maxSize, minSize, maxFiles, accept }) + onReject?.(rejections) + // react-dropzone repeats `too-many-files` on every file; say it once. + const message = [...new Set(rejections.map(r => r.message))].join('\n') + onError?.(new Error(message, { cause: rejections })) } onDrop?.(acceptedFiles, fileRejections, event) @@ -198,13 +263,7 @@ export function DropzoneEmptyState({ sizeClause = `less than ${renderBytes(maxSize)}` } - // react-dropzone 20 widened `accept` from `Accept` to `Accept | AcceptGroup[]`. - // `Object.keys()` on the array form yields "0", "1", so normalise to MIME keys - // first. Both shapes are in range -- the peer is `>=15 <21`. - const acceptedTypes = Array.isArray(accept) - ? accept.flatMap(group => Object.keys(group.accept)) - : Object.keys(accept ?? {}) - + const acceptedTypes = acceptedTypeList(accept) if (acceptedTypes.length > 0) { caption = `Accepts ${new Intl.ListFormat('en').format(acceptedTypes)}` if (sizeClause) { diff --git a/packages/datum-ui/src/components/features/empty-content/content-action.tsx b/packages/datum-ui/src/components/features/empty-content/content-action.tsx new file mode 100644 index 00000000..58b27bb8 --- /dev/null +++ b/packages/datum-ui/src/components/features/empty-content/content-action.tsx @@ -0,0 +1,114 @@ +import type { VariantProps } from 'class-variance-authority' +import type { ElementType, ReactNode } from 'react' +import type { ButtonProps } from '../../base/button' +import type { ButtonAction, EmptyContentAction, LinkAction } from './empty-content' +import { cva } from 'class-variance-authority' +import { cn } from '../../../utils/cn' +import { Button } from '../../base/button' +import { Tooltip } from '../../base/tooltip' + +// Action button variants +const actionButtonVariants = cva('flex items-center gap-1', { + variants: { + size: { + xs: 'text-xs', + sm: 'text-xs', + md: 'text-xs', + lg: 'text-sm', + xl: 'text-sm', + }, + }, + defaultVariants: { + size: 'md', + }, +}) + +// Button size back to the nearest container size (for actionButtonVariants text class) +const BUTTON_SIZE_TO_CONTAINER: Record< + NonNullable, + NonNullable['size']> +> = { + xs: 'xs', + small: 'sm', + default: 'lg', + large: 'xl', + icon: 'md', + link: 'md', +} + +interface ContentActionProps { + action: EmptyContentAction + buttonSize: ButtonProps['size'] + /** Link component for link actions. Defaults to . */ + linkComponent?: ElementType +} + +/** One action button or link, shared by EmptyContent and ErrorContent. */ +export function ContentAction({ action, buttonSize, linkComponent: LinkComp = 'a' }: ContentActionProps) { + const renderAsLink + = (action.as === 'link' || action.as === 'external-link') && !action.disabled + + // Strip all non-Button keys (meta + anchor) so only Button props reach + ) + + let control: ReactNode = button + + if (renderAsLink) { + const isExternal = action.as === 'external-link' + const linkHref = LinkComp === 'a' ? { href: to ?? '' } : { to: to ?? '' } + control = ( + + {button} + + ) + } + + if (tooltip) { + control = ( + + {control} + + ) + } + + return control +} diff --git a/packages/datum-ui/src/components/features/empty-content/empty-content.tsx b/packages/datum-ui/src/components/features/empty-content/empty-content.tsx index 88308612..41615213 100644 --- a/packages/datum-ui/src/components/features/empty-content/empty-content.tsx +++ b/packages/datum-ui/src/components/features/empty-content/empty-content.tsx @@ -2,14 +2,12 @@ import type { VariantProps } from 'class-variance-authority' import type { AnchorHTMLAttributes, ReactNode } from 'react' import type { ButtonProps } from '../../base/button' import { cva } from 'class-variance-authority' -import { Fragment } from 'react' import { cn } from '../../../utils/cn' -import { Button } from '../../base/button' -import { Tooltip } from '../../base/tooltip' import miloStamp from './assets/milo-stamp.svg' import scene5 from './assets/scene-5.png' import scene6 from './assets/scene-6.png' import scene7 from './assets/scene-7.png' +import { ContentAction } from './content-action' /** Shared by every action kind: full Button surface + presentation concerns. */ interface BaseAction extends Omit { @@ -118,22 +116,6 @@ const actionsContainerVariants = cva('flex items-center flex-col', { }, }) -// Action button variants -const actionButtonVariants = cva('flex items-center gap-1', { - variants: { - size: { - xs: 'text-xs', - sm: 'text-xs', - md: 'text-xs', - lg: 'text-sm', - xl: 'text-sm', - }, - }, - defaultVariants: { - size: 'md', - }, -}) - // Size to button size mapping const BUTTON_SIZE_MAP = { xs: 'xs', @@ -143,17 +125,9 @@ const BUTTON_SIZE_MAP = { xl: 'default', } as const -// Button size back to the nearest container size (for actionButtonVariants text class) -const BUTTON_SIZE_TO_CONTAINER: Record< - NonNullable, - NonNullable['size']> -> = { - xs: 'xs', - small: 'sm', - default: 'lg', - large: 'xl', - icon: 'md', - link: 'md', +/** A stable key for an action: its kind, label and position (labels can repeat). */ +function actionKey(action: EmptyContentAction, position: number): string { + return `${action.as ?? 'button'}-${action.label}-${position}` } export interface EmptyContentProps extends VariantProps { @@ -184,75 +158,6 @@ export function EmptyContent({ const LinkComp = linkComponent || 'a' const visibleActions = actions.filter(action => !action.hidden) - const renderAction = (action: EmptyContentAction, index: number) => { - const renderAsLink - = (action.as === 'link' || action.as === 'external-link') && !action.disabled - - // Strip all non-Button keys (meta + anchor) so only Button props reach - ) - - let control: ReactNode = button - - if (renderAsLink) { - const isExternal = action.as === 'external-link' - const linkHref = LinkComp === 'a' ? { href: to ?? '' } : { to: to ?? '' } - control = ( - - {button} - - ) - } - - if (tooltip) { - control = ( - - {control} - - ) - } - - return {control} - } - return (
{/* Decorative corner images */} @@ -285,7 +190,14 @@ export function EmptyContent({ {subtitle && {subtitle}} {visibleActions.length > 0 && (
- {visibleActions.map(renderAction)} + {visibleActions.map((action, index) => ( + + ))}
)} diff --git a/packages/datum-ui/src/components/features/error-content/README.md b/packages/datum-ui/src/components/features/error-content/README.md new file mode 100644 index 00000000..1dce1c91 --- /dev/null +++ b/packages/datum-ui/src/components/features/error-content/README.md @@ -0,0 +1,44 @@ +# Error Content + +Shows errors in plain language, with the technical text one click away. `describeApiError` turns common API and Kubernetes errors into a headline and a next step; `ErrorContent` displays one. DataTable, TaskQueue and your own components share the same wording. + +## Usage + +```tsx +import { ErrorContent } from '@datum-cloud/datum-ui/error-content' + + +``` + +It shows the headline, the next step, any actions, and a collapsed **Error details** section with the raw text and request id, which can be copied. Pass `title` or `description` to replace the described ones, and `variant="minimal"` to drop the border. + +## What gets translated + +Known Kubernetes errors get a plain headline: permission denied (`You don't have permission to change dnsrecordsets.`), session expired, not found, already exists, changed by someone else, too many requests, timeouts and network failures. Anything else keeps its own message as the headline, because many errors are already written for people. The raw text is always kept as `detail`. + +`describeApiError` reads Kubernetes `Status` objects, `Error`s, objects with `status`/`statusCode`, cloud-portal's `AppError` (`k8sReason`, `originalMessage`, `requestId`), and one level of `cause`. + +## Customising + +App-wide, wrap the app once: + +```tsx +import { ErrorDescriptionProvider } from '@datum-cloud/datum-ui/error-content' + + myWording(error) ?? base} +> + + +``` + +`ErrorContent`, DataTable's built-in error and TaskQueue all read it. In your own components, `useDescribeError()` returns the same describer. + +Per use: + +- `DataTable.Content`'s `errorContent` replaces the table's error, as a node or `(error, retry) => node`. +- TaskQueue's `formatError`, on the queue config or one `enqueue`, replaces how that task's thrown errors read. +- `ErrorContent`'s `title` and `description` replace the described wording. diff --git a/packages/datum-ui/src/components/features/error-content/__tests__/error-content.test.tsx b/packages/datum-ui/src/components/features/error-content/__tests__/error-content.test.tsx new file mode 100644 index 00000000..2bfcf6e6 --- /dev/null +++ b/packages/datum-ui/src/components/features/error-content/__tests__/error-content.test.tsx @@ -0,0 +1,227 @@ +/// +import type { ErrorDescription } from '../describe-api-error' +import { fireEvent, render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { describeApiError } from '../describe-api-error' +import { ErrorContent } from '../error-content' +import { ErrorDescriptionProvider, useDescribeError } from '../error-description-context' + +const copy = vi.fn() +vi.mock('../../../../hooks/use-copy-to-clipboard', () => ({ useCopyToClipboard: () => [false, copy] })) + +const RBAC = 'forbidden: User \'a@b.c\' cannot patch resource "dnsrecordsets" in API group "dns.networking.miloapis.com" in the namespace "default"' +const status = (reason: string, code: number, message = 'raw text') => ({ kind: 'Status', reason, code, message }) + +describe('describeApiError', () => { + it.each<[string, unknown, string, string | undefined]>([ + ['Unauthorized', status('Unauthorized', 401), 'Your session has expired.', 'Sign in again to continue.'], + ['NotFound', status('NotFound', 404), 'This item no longer exists.', 'It may have been deleted. Refresh to see the latest.'], + ['AlreadyExists', status('AlreadyExists', 409), 'An item with this name already exists.', 'Choose a different name.'], + ['Conflict', status('Conflict', 409), 'Someone else changed this item.', 'Refresh and try again.'], + ['TooManyRequests', status('TooManyRequests', 429), 'Too many requests.', 'Wait a moment and try again.'], + ['Timeout', status('Timeout', 504), 'The service took too long to respond.', 'Try again in a moment.'], + ['ServerTimeout', status('ServerTimeout', 503), 'The service took too long to respond.', 'Try again in a moment.'], + ['503 by status only', { status: 503, message: 'down' }, 'The service took too long to respond.', 'Try again in a moment.'], + ['RBAC Forbidden', status('Forbidden', 403, RBAC), 'You don\'t have permission to change dnsrecordsets.', 'Ask an administrator of this project for access.'], + ])('describes %s', (_name, error, title, description) => { + const described = describeApiError(error) + expect(described.title).toBe(title) + expect(described.description).toBe(description) + }) + + it('keeps the raw text as detail', () => { + expect(describeApiError(status('Forbidden', 403, RBAC)).detail).toBe(RBAC) + }) + + it('keeps the message of an Invalid error as its title', () => { + expect(describeApiError(status('Invalid', 422, 'spec.name: Required value'))).toEqual({ title: 'spec.name: Required value', detail: 'spec.name: Required value' }) + }) + + it('uses a plain title for an Invalid error with no message', () => { + expect(describeApiError({ kind: 'Status', reason: 'Invalid', code: 422 }).title).toBe('Some values aren\'t valid.') + }) + + it('names the product area when the API group has a label', () => { + const labels = { apiGroupLabels: { 'dns.networking.miloapis.com': 'Networking/DNS' } } + expect(describeApiError(status('Forbidden', 403, RBAC), labels).title).toBe('Permission denied for changes to Networking/DNS.') + expect(describeApiError(status('Forbidden', 403, RBAC.replace('patch', 'get')), labels).title).toBe('Permission denied to view Networking/DNS.') + }) + + it('reads single-quoted resources and maps every verb', () => { + const message = (verb: string) => `User 'x' cannot ${verb} resource 'domains' in API group 'networking.datumapis.com'` + expect(describeApiError(status('Forbidden', 403, message('list'))).title).toBe('You don\'t have permission to view domains.') + expect(describeApiError(status('Forbidden', 403, message('create'))).title).toBe('You don\'t have permission to create domains.') + expect(describeApiError(status('Forbidden', 403, message('deletecollection'))).title).toBe('You don\'t have permission to delete domains.') + }) + + it('keeps the message of a 403 that is not an RBAC denial', () => { + expect(describeApiError({ status: 403, message: 'Your organization is suspended.' }).title).toBe('Your organization is suspended.') + }) + + it('keeps the message of an error it does not recognise', () => { + const described = describeApiError(new Error('Project is not ready: quota exceeded')) + expect(described.title).toBe('Project is not ready: quota exceeded') + expect(described.description).toBeUndefined() + }) + + it('reads cloud-portal\'s AppError fields', () => { + const appError = { status: 403, code: 'INTERNAL_ERROR', k8sReason: 'Forbidden', message: 'You don\'t have permission to do this.', originalMessage: RBAC, requestId: 'req-1' } + expect(describeApiError(appError)).toEqual({ + title: 'You don\'t have permission to change dnsrecordsets.', + description: 'Ask an administrator of this project for access.', + detail: RBAC, + requestId: 'req-1', + }) + }) + + it('keeps the message written for people as the title and the original as detail', () => { + const appError = { status: 403, message: 'You don\'t have permission to do this.', originalMessage: 'Forbidden' } + expect(describeApiError(appError)).toEqual({ + title: 'You don\'t have permission to do this.', + detail: 'Forbidden', + }) + }) + + it('does not put a raw non-RBAC denial in the title', () => { + const raw = 'User "jane@example.com" cannot get path "/apis/foo"' + const described = describeApiError({ status: 403, message: 'You don\'t have permission to do this.', originalMessage: raw }) + expect(described.title).toBe('You don\'t have permission to do this.') + expect(described.detail).toBe(raw) + }) + + it('gives a 403 with no text a permission headline', () => { + expect(describeApiError({ status: 403 })).toEqual({ + title: 'You don\'t have permission to do this.', + description: 'Ask an administrator of this project for access.', + }) + }) + + it('reads an RBAC denial and its raw text from the cause of a wrapper', () => { + const wrapped = new Error('Failed to delete record', { cause: status('Forbidden', 403, RBAC) }) + const described = describeApiError(wrapped) + expect(described.title).toBe('You don\'t have permission to change dnsrecordsets.') + expect(described.detail).toBe(RBAC) + }) + + it('recognises a network failure wrapped by an app error', () => { + const appError = { status: 500, message: 'Failed to fetch', cause: new TypeError('Failed to fetch') } + expect(describeApiError(appError).title).toBe('Couldn\'t reach the server.') + }) + + it('recognises Safari\'s network failure and not a code bug that mentions fetch', () => { + expect(describeApiError(new TypeError('Load failed')).title).toBe('Couldn\'t reach the server.') + const bug = 'Cannot read properties of undefined (reading \'fetch\')' + expect(describeApiError(new TypeError(bug)).title).toBe(bug) + }) + + it('reads a 409 whose text says already exists as a name clash', () => { + expect(describeApiError({ status: 409, message: 'project "web" already exists' }).title).toBe('An item with this name already exists.') + }) + + it('reads a request id from an x-request-id header', () => { + expect(describeApiError({ status: 404, message: 'gone', headers: { 'x-request-id': 'req-2' } }).requestId).toBe('req-2') + }) + + it('looks one level into cause', () => { + const wrapped = new Error('wrapped', { cause: status('NotFound', 404, 'x not found') }) + expect(describeApiError(wrapped).title).toBe('This item no longer exists.') + }) + + it('describes a network failure', () => { + expect(describeApiError(new TypeError('Failed to fetch')).title).toBe('Couldn\'t reach the server.') + }) + + it('handles a string, an empty object and undefined', () => { + expect(describeApiError('plain string').title).toBe('plain string') + for (const value of [{}, undefined]) { + expect(describeApiError(value)).toEqual({ + title: 'Something went wrong.', + description: 'Try again. If it keeps happening, contact support.', + }) + } + }) +}) + +function Show({ error }: { error: unknown }) { + const describe = useDescribeError() + return

{describe(error).title}

+} + +describe('errorDescriptionProvider', () => { + it('falls back to describeApiError with no provider', () => { + render() + expect(screen.getByText('This item no longer exists.')).toBeInTheDocument() + }) + + it('passes apiGroupLabels to the default translator', () => { + render( + + + , + ) + expect(screen.getByText('Permission denied for changes to Networking/DNS.')).toBeInTheDocument() + }) + + it('lets describe start from the base description', () => { + render( + ({ ...base, title: `Custom: ${base.title}` })} + > + + , + ) + expect(screen.getByText('Custom: Permission denied for changes to Networking/DNS.')).toBeInTheDocument() + }) +}) + +describe('errorContent', () => { + it('shows the translated title and description with the raw text in closed details', () => { + const { container } = render() + expect(screen.getByRole('alert')).toBeInTheDocument() + expect(screen.getByText('You don\'t have permission to change dnsrecordsets.')).toBeInTheDocument() + expect(screen.getByText('Ask an administrator of this project for access.')).toBeInTheDocument() + const details = container.querySelector('details') + expect(details).not.toBeNull() + expect(details).not.toHaveAttribute('open') + expect(details?.querySelector('summary')).toHaveTextContent('Error details') + expect(details).toHaveTextContent(RBAC) + }) + + it('lets title and description props replace the translated ones', () => { + render() + expect(screen.getByText('Gone')).toBeInTheDocument() + expect(screen.getByText('Pick another')).toBeInTheDocument() + expect(screen.queryByText('This item no longer exists.')).toBeNull() + }) + + it('shows the request id inside the details', () => { + const { container } = render() + expect(container.querySelector('details')).toHaveTextContent('req-9') + }) + + it('copies the raw text', () => { + render() + fireEvent.click(screen.getByRole('button', { name: 'Copy error details' })) + expect(copy).toHaveBeenCalledWith(RBAC) + }) + + it('runs an action', () => { + const onClick = vi.fn() + render() + fireEvent.click(screen.getByRole('button', { name: 'Retry' })) + expect(onClick).toHaveBeenCalled() + }) + + it('shows no details when they would repeat the headline', () => { + const { container } = render() + expect(screen.getByRole('heading', { name: 'Project is not ready' })).toBeInTheDocument() + expect(container.querySelector('details')).toBeNull() + }) + + it('shows no details when there is no raw text', () => { + const { container } = render() + expect(container.querySelector('details')).toBeNull() + expect(screen.getByText('Something went wrong.')).toBeInTheDocument() + }) +}) diff --git a/packages/datum-ui/src/components/features/error-content/describe-api-error.ts b/packages/datum-ui/src/components/features/error-content/describe-api-error.ts new file mode 100644 index 00000000..34533828 --- /dev/null +++ b/packages/datum-ui/src/components/features/error-content/describe-api-error.ts @@ -0,0 +1,194 @@ +/** A plain-language account of an error, with the technical text kept. */ +export interface ErrorDescription { + /** A plain headline. */ + title: string + /** What the person can do next. */ + description?: string + /** The raw technical text, shown under "Error details". */ + detail?: string + requestId?: string +} + +export interface DescribeOptions { + /** + * Product-area names by Kubernetes API group, e.g. + * `{ 'dns.networking.miloapis.com': 'Networking/DNS' }`. A permission error + * on a listed group names the area instead of the raw resource. + */ + apiGroupLabels?: Record +} + +interface ErrorFacts { + reason?: string + status?: number + /** The message written for people, used as the headline when no rule applies. */ + headline?: string + /** The raw technical text, kept as `detail`. */ + raw?: string + /** Every text worth searching for an RBAC denial, most technical first. */ + texts: string[] + requestId?: string + isNetworkError: boolean +} + +type Advice = Pick + +const FALLBACK: Advice = { + title: 'Something went wrong.', + description: 'Try again. If it keeps happening, contact support.', +} + +const NO_ACCESS = 'Ask an administrator of this project for access.' + +const ADVICE_BY_REASON: Record = { + Unauthorized: { title: 'Your session has expired.', description: 'Sign in again to continue.' }, + NotFound: { title: 'This item no longer exists.', description: 'It may have been deleted. Refresh to see the latest.' }, + AlreadyExists: { title: 'An item with this name already exists.', description: 'Choose a different name.' }, + Conflict: { title: 'Someone else changed this item.', description: 'Refresh and try again.' }, + TooManyRequests: { title: 'Too many requests.', description: 'Wait a moment and try again.' }, + Timeout: { title: 'The service took too long to respond.', description: 'Try again in a moment.' }, + ServerTimeout: { title: 'The service took too long to respond.', description: 'Try again in a moment.' }, +} + +const REASON_BY_STATUS: Record = { + 401: 'Unauthorized', + 403: 'Forbidden', + 404: 'NotFound', + 409: 'Conflict', + 422: 'Invalid', + 429: 'TooManyRequests', + 503: 'ServerTimeout', + 504: 'Timeout', +} + +const ACTION_BY_VERB: Record = { + get: 'view', + list: 'view', + watch: 'view', + create: 'create', + update: 'change', + patch: 'change', + delete: 'delete', + deletecollection: 'delete', +} + +// The Kubernetes RBAC denial: `cannot resource "" in API group ""`. +const RBAC_DENIAL = /cannot (\w+) resource ["']([^"']+)["'] in API group ["']([^"']*)["']/ + +/** + * Turns an API or Kubernetes error into a plain headline and next step, + * keeping the raw text as `detail`. Known Kubernetes errors get rewritten; + * any other error keeps its own message as the title, since many are already + * written for people. + */ +export function describeApiError(error: unknown, options: DescribeOptions = {}): ErrorDescription { + const facts = readFacts(error) + const own = facts.headline ?? facts.raw + const advice = adviceFor(facts, options) ?? (own ? { title: own } : FALLBACK) + return { + ...advice, + ...(facts.raw !== undefined && { detail: facts.raw }), + ...(facts.requestId !== undefined && { requestId: facts.requestId }), + } +} + +function adviceFor(facts: ErrorFacts, options: DescribeOptions): Advice | undefined { + if (facts.isNetworkError) + return { title: 'Couldn\'t reach the server.', description: 'Check your connection and try again.' } + const reason = facts.reason ?? (facts.status === undefined ? undefined : REASON_BY_STATUS[facts.status]) + if (reason === 'Forbidden') + return forbiddenAdvice(facts, options) + if (reason === 'Invalid') + return facts.headline || facts.raw ? undefined : { title: 'Some values aren\'t valid.' } + // A REST 409 often carries no Kubernetes reason; its text tells a name clash from an edit conflict. + if (reason === 'Conflict' && facts.texts.some(text => /already exists/i.test(text))) + return ADVICE_BY_REASON.AlreadyExists + return reason === undefined ? undefined : ADVICE_BY_REASON[reason] +} + +function forbiddenAdvice(facts: ErrorFacts, { apiGroupLabels }: DescribeOptions): Advice | undefined { + const match = facts.texts.map(text => text.match(RBAC_DENIAL)).find(Boolean) + if (!match) { + // A policy denial written for people keeps its own words; with none, say what happened. + return facts.headline || facts.raw + ? undefined + : { title: 'You don\'t have permission to do this.', description: NO_ACCESS } + } + const [, verb = '', resource = '', group = ''] = match + const action = ACTION_BY_VERB[verb.toLowerCase()] ?? verb + const label = apiGroupLabels?.[group] + if (label) { + const title = action === 'view' + ? `Permission denied to view ${label}.` + : `Permission denied for changes to ${label}.` + return { title, description: NO_ACCESS } + } + return { title: `You don't have permission to ${action} ${resource}.`, description: NO_ACCESS } +} + +function readFacts(error: unknown): ErrorFacts { + if (typeof error === 'string') { + const text = error || undefined + return { headline: text, raw: text, texts: text ? [text] : [], isNetworkError: false } + } + const own = asRecord(error) + const cause = asRecord(own?.cause) + const reason = reasonOf(own) + const status = statusOf(own) + // Look one level into `cause` for the reason and status only when the error itself says nothing. + const fallback = reason === undefined && status === undefined ? cause : undefined + const headline = stringField(own, 'message') ?? stringField(own, 'body') ?? stringField(own, 'originalMessage') + const causeText = textOf(cause) + // The technical text: an explicit original, else a wrapped cause that says more than the wrapper. + const raw = stringField(own, 'originalMessage') + ?? (causeText !== undefined && causeText !== headline ? causeText : undefined) + ?? headline + return { + reason: reason ?? reasonOf(fallback), + status: status ?? statusOf(fallback), + headline, + raw, + texts: [raw, headline, causeText].filter((text): text is string => text !== undefined), + requestId: requestIdOf(own) ?? requestIdOf(cause), + isNetworkError: isNetworkFailure(error) || isNetworkFailure(own?.cause), + } +} + +// What browsers throw from fetch when the request never reached the server +// (Chrome, Safari, Firefox). Matched exactly, so a code bug that merely +// mentions "fetch" is not mistaken for one. +const NETWORK_FAILURE = /^(?:Failed to fetch|Load failed|NetworkError when attempting to fetch resource\.?)$/ + +function isNetworkFailure(value: unknown): boolean { + return value instanceof TypeError && NETWORK_FAILURE.test(value.message) +} + +function asRecord(value: unknown): Record | undefined { + return typeof value === 'object' && value !== null ? value as Record : undefined +} + +function stringField(source: Record | undefined, key: string): string | undefined { + const value = source?.[key] + return typeof value === 'string' && value !== '' ? value : undefined +} + +function reasonOf(source: Record | undefined): string | undefined { + return stringField(source, 'reason') ?? stringField(source, 'k8sReason') ?? stringField(asRecord(source?.details), 'reason') +} + +function statusOf(source: Record | undefined): number | undefined { + for (const key of ['status', 'statusCode', 'code']) { + const value = source?.[key] + if (typeof value === 'number') + return value + } + return undefined +} + +function textOf(source: Record | undefined): string | undefined { + return stringField(source, 'originalMessage') ?? stringField(source, 'message') ?? stringField(source, 'body') +} + +function requestIdOf(source: Record | undefined): string | undefined { + return stringField(source, 'requestId') ?? stringField(asRecord(source?.headers), 'x-request-id') +} diff --git a/packages/datum-ui/src/components/features/error-content/error-content.tsx b/packages/datum-ui/src/components/features/error-content/error-content.tsx new file mode 100644 index 00000000..ee11124f --- /dev/null +++ b/packages/datum-ui/src/components/features/error-content/error-content.tsx @@ -0,0 +1,79 @@ +'use client' + +import type { EmptyContentAction } from '../empty-content' +import { cva } from 'class-variance-authority' +import { useCopyToClipboard } from '../../../hooks/use-copy-to-clipboard' +import { cn } from '../../../utils/cn' +import { ContentAction } from '../empty-content/content-action' +import { useDescribeError } from './error-description-context' + +const containerVariants = cva('flex flex-col items-center gap-3 text-center', { + variants: { + variant: { + default: 'rounded-lg border border-border px-6 py-7', + minimal: 'px-4 py-6', + }, + }, + defaultVariants: { + variant: 'default', + }, +}) + +export interface ErrorContentProps { + /** The error to describe, with the tree's `useDescribeError()`. */ + error?: unknown + /** Replaces the described title. */ + title?: string + /** Replaces the described next step. */ + description?: string + actions?: EmptyContentAction[] + variant?: 'default' | 'minimal' + className?: string +} + +/** + * An error, told plainly: a headline, what to do next, actions, and the raw + * technical text in a collapsed "Error details" section that can be copied. + */ +export function ErrorContent({ error, title, description, actions = [], variant, className }: ErrorContentProps) { + const described = useDescribeError()(error) + const [, copy] = useCopyToClipboard() + const visibleActions = actions.filter(action => !action.hidden) + const shownTitle = title ?? described.title + const shownDescription = description ?? described.description + // An unrecognised error keeps its message as the title; don't repeat it. + const detail = described.detail === shownTitle ? undefined : described.detail + + return ( +
+

{shownTitle}

+ {shownDescription &&

{shownDescription}

} + {visibleActions.length > 0 && ( +
+ {visibleActions.map(action => ( + + ))} +
+ )} + {detail && ( +
+ Error details +
+
+              {detail}
+              {described.requestId && `\nRequest ID: ${described.requestId}`}
+            
+ +
+
+ )} +
+ ) +} diff --git a/packages/datum-ui/src/components/features/error-content/error-description-context.tsx b/packages/datum-ui/src/components/features/error-content/error-description-context.tsx new file mode 100644 index 00000000..01c61933 --- /dev/null +++ b/packages/datum-ui/src/components/features/error-content/error-description-context.tsx @@ -0,0 +1,35 @@ +'use client' + +import type { ReactNode } from 'react' +import type { ErrorDescription } from './describe-api-error' +import { createContext, use, useCallback } from 'react' +import { describeApiError } from './describe-api-error' + +type Describe = (error: unknown) => ErrorDescription + +const ErrorDescriptionContext = createContext(error => describeApiError(error)) + +export interface ErrorDescriptionProviderProps { + children: ReactNode + /** Product-area names by Kubernetes API group, passed to `describeApiError`. */ + apiGroupLabels?: Record + /** + * Replace or adjust a description app-wide. `base` is what `describeApiError` + * produced (with `apiGroupLabels`); return it, a changed copy, or your own. + */ + describe?: (error: unknown, base: ErrorDescription) => ErrorDescription +} + +/** Sets how every datum-ui error display in the tree describes errors. */ +export function ErrorDescriptionProvider({ children, apiGroupLabels, describe }: ErrorDescriptionProviderProps) { + const value = useCallback((error) => { + const base = describeApiError(error, { apiGroupLabels }) + return describe ? describe(error, base) : base + }, [apiGroupLabels, describe]) + return {children} +} + +/** The tree's error describer: the provider's, or `describeApiError` with none. */ +export function useDescribeError(): Describe { + return use(ErrorDescriptionContext) +} diff --git a/packages/datum-ui/src/components/features/error-content/index.ts b/packages/datum-ui/src/components/features/error-content/index.ts new file mode 100644 index 00000000..f79d1c24 --- /dev/null +++ b/packages/datum-ui/src/components/features/error-content/index.ts @@ -0,0 +1,6 @@ +export { describeApiError } from './describe-api-error' +export type { DescribeOptions, ErrorDescription } from './describe-api-error' +export { ErrorContent } from './error-content' +export type { ErrorContentProps } from './error-content' +export { ErrorDescriptionProvider, useDescribeError } from './error-description-context' +export type { ErrorDescriptionProviderProps } from './error-description-context' diff --git a/packages/datum-ui/src/components/features/task-queue/README.md b/packages/datum-ui/src/components/features/task-queue/README.md index b02c216f..33261d4b 100644 --- a/packages/datum-ui/src/components/features/task-queue/README.md +++ b/packages/datum-ui/src/components/features/task-queue/README.md @@ -80,6 +80,21 @@ enqueue({ }); ``` +### Plain-Language Errors + +An error a processor throws, for a whole task or one item, is described with the app's error describer (see `@datum-cloud/datum-ui/error-content`). The summary shows a plain headline, such as `You don't have permission to delete dnsrecordsets.`, with the raw text under **Error details**. Text you pass to `ctx.fail` is shown as written. + +Change the wording for one task, or for the whole queue through `TaskQueueProvider`'s `config`: + +```tsx +enqueue({ + title: 'Deleting records', + items: records, + formatError: error => ({ title: 'Could not delete this record', detail: String(error) }), + processItem: async record => deleteRecord(record.id), +}); +``` + ### Custom Item ID (for objects) By default, the queue extracts IDs from items automatically (`item.id` → `item.name` → `item.key` → `item.uuid` → `JSON.stringify`). Override when needed: diff --git a/packages/datum-ui/src/components/features/task-queue/core/__tests__/task-summary-dialog.test.tsx b/packages/datum-ui/src/components/features/task-queue/core/__tests__/task-summary-dialog.test.tsx new file mode 100644 index 00000000..2681ba8d --- /dev/null +++ b/packages/datum-ui/src/components/features/task-queue/core/__tests__/task-summary-dialog.test.tsx @@ -0,0 +1,55 @@ +/// +import type { TaskQueue } from '../../engine' +import type { TaskSummaryItem } from '../../types' +import { render, screen } from '@testing-library/react' +import { use } from 'react' +import { describe, expect, it } from 'vitest' +import { ErrorDescriptionProvider } from '../../../error-content/error-description-context' +import { MemoryTaskStorage } from '../../engine/storage/memory-storage' +import { TaskQueueContext, TaskQueueProvider } from '../../provider/task-queue-provider' +import { TaskSummaryDialog } from '../task-summary-dialog' + +function renderDialog(items: TaskSummaryItem[]) { + return render( + + {}} title="Delete records" items={items} /> + , + ) +} + +describe('taskSummaryDialog error details', () => { + it('shows the plain message with the raw text behind closed Error details', () => { + renderDialog([{ id: '1', label: 'web', status: 'failed', message: 'Plain', detail: 'raw' }]) + expect(screen.getByText('Plain')).toBeInTheDocument() + const details = screen.getByText('Error details').closest('details') + expect(details).not.toBeNull() + expect(details).not.toHaveAttribute('open') + expect(details).toHaveTextContent('raw') + }) + + it('shows no details for an item without detail', () => { + renderDialog([{ id: '1', label: 'web', status: 'failed', message: 'Plain' }]) + expect(screen.queryByText('Error details')).toBeNull() + }) +}) + +describe('taskQueueProvider error formatting', () => { + it('describes thrown errors with the tree\'s describer by default', async () => { + let queue: TaskQueue | undefined + function Capture() { + queue = use(TaskQueueContext)?.queue + return null + } + render( + ({ title: 'From provider' })}> + + + + , + ) + const outcome = await queue!.enqueue({ title: 't', processor: async () => { + throw new Error('raw') + } }).promise + expect(outcome.failedItems[0]?.message).toBe('From provider') + }) +}) diff --git a/packages/datum-ui/src/components/features/task-queue/core/task-panel-actions.tsx b/packages/datum-ui/src/components/features/task-queue/core/task-panel-actions.tsx index 392df365..529195ee 100644 --- a/packages/datum-ui/src/components/features/task-queue/core/task-panel-actions.tsx +++ b/packages/datum-ui/src/components/features/task-queue/core/task-panel-actions.tsx @@ -31,6 +31,7 @@ export function TaskPanelActions({ task }: TaskPanelActionsProps) { label: item.id ?? 'Error', status: 'failed', message: item.message, + detail: item.detail, })), )} > @@ -72,7 +73,7 @@ function resolveActions(task: Task): ButtonProps[] { return null const failed = failedMap.get(id) if (failed) - return { id, status: 'failed' as const, message: failed.message, data: item } + return { id, status: 'failed' as const, message: failed.message, detail: failed.detail, data: item } if (succeededSet.has(id)) return { id, status: 'succeeded' as const, data: item } return null diff --git a/packages/datum-ui/src/components/features/task-queue/core/task-summary-dialog.tsx b/packages/datum-ui/src/components/features/task-queue/core/task-summary-dialog.tsx index fb76a44d..da268932 100644 --- a/packages/datum-ui/src/components/features/task-queue/core/task-summary-dialog.tsx +++ b/packages/datum-ui/src/components/features/task-queue/core/task-summary-dialog.tsx @@ -60,6 +60,12 @@ function StatusCell({ item }: { item: TaskSummaryItem }) { {item.message && item.status !== 'success' && ( {item.message} )} + {item.detail && item.detail !== item.message && item.status !== 'success' && ( +
+ Error details +
{item.detail}
+
+ )}
) } @@ -137,6 +143,7 @@ function useTaskSummaryItems( label: getItemLabel(item.id ?? ''), status: 'failed', message: item.message, + detail: item.detail, })) return [...failed, ...succeeded] diff --git a/packages/datum-ui/src/components/features/task-queue/engine/__tests__/queue.test.ts b/packages/datum-ui/src/components/features/task-queue/engine/__tests__/queue.test.ts index efa92c55..e7864601 100644 --- a/packages/datum-ui/src/components/features/task-queue/engine/__tests__/queue.test.ts +++ b/packages/datum-ui/src/components/features/task-queue/engine/__tests__/queue.test.ts @@ -363,3 +363,87 @@ describe('taskQueue multi-tab reconcile (CR-010)', () => { void handle }) }) + +describe('taskQueue error formatting', () => { + const plain = () => ({ title: 'Plain', detail: 'raw' }) + + it('formats an error a processor throws', async () => { + const queue = new TaskQueue({ storage: new MemoryTaskStorage(), formatError: plain }) + const outcome = await queue.enqueue({ title: 't', processor: async () => { + throw new Error('raw') + } }).promise + expect(outcome.failedItems[0]).toEqual({ message: 'Plain', detail: 'raw' }) + }) + + it('formats an error thrown for one item', async () => { + const queue = new TaskQueue({ storage: new MemoryTaskStorage(), formatError: plain }) + const outcome = await queue.enqueue({ + title: 't', + items: [{ id: 'a' }, { id: 'b' }], + processItem: async (item) => { + if (item.id === 'b') + throw new Error('raw') + }, + }).promise + expect(outcome.failedItems).toEqual([{ id: 'b', message: 'Plain', detail: 'raw' }]) + }) + + it('prefers a task\'s own formatError over the config\'s', async () => { + const queue = new TaskQueue({ storage: new MemoryTaskStorage(), formatError: plain }) + const outcome = await queue.enqueue({ + title: 't', + formatError: () => ({ title: 'Per task' }), + processor: async () => { + throw new Error('raw') + }, + }).promise + expect(outcome.failedItems[0]?.message).toBe('Per task') + }) + + it('keeps a message the processor passes to fail as written', async () => { + const queue = new TaskQueue({ storage: new MemoryTaskStorage(), formatError: plain }) + const outcome = await queue.enqueue({ + title: 't', + items: [{ id: 'a' }], + processItem: async (_item, ctx) => ctx.fail('a', 'Written by the processor'), + }).promise + expect(outcome.failedItems).toEqual([{ id: 'a', message: 'Written by the processor' }]) + }) + + it('stores the thrown message with no formatError anywhere', async () => { + const queue = new TaskQueue({ storage: new MemoryTaskStorage() }) + const outcome = await queue.enqueue({ title: 't', processor: async () => { + throw new Error('raw') + } }).promise + expect(outcome.failedItems[0]).toEqual({ message: 'raw' }) + }) + + it('falls back to the raw message when formatError throws, and keeps going', async () => { + const queue = new TaskQueue({ + storage: new MemoryTaskStorage(), + formatError: () => { + throw new Error('formatter broke') + }, + }) + const seen: string[] = [] + const outcome = await queue.enqueue({ + title: 't', + items: [{ id: 'a' }, { id: 'b' }], + processItem: async (item) => { + seen.push(item.id) + if (item.id === 'a') + throw new Error('raw') + }, + }).promise + expect(outcome.failedItems).toEqual([{ id: 'a', message: 'raw' }]) + expect(seen).toEqual(['a', 'b']) + }) + + it('reads a saved failed item that has no detail', () => { + const storage = new MemoryTaskStorage() + storage.set('old', makeStoredTask({ id: 'old', status: 'failed', failed: 1, failedItems: [{ message: 'old' }] })) + const queue = new TaskQueue({ storage }) + const saved = queue.getSnapshot().find(t => t.id === 'old')! + expect(saved.failedItems).toEqual([{ message: 'old' }]) + }) +}) diff --git a/packages/datum-ui/src/components/features/task-queue/engine/executor.ts b/packages/datum-ui/src/components/features/task-queue/engine/executor.ts index c6df5ad1..736f660c 100644 --- a/packages/datum-ui/src/components/features/task-queue/engine/executor.ts +++ b/packages/datum-ui/src/components/features/task-queue/engine/executor.ts @@ -1,7 +1,9 @@ -import type { Task, TaskContext, TaskOutcome, TaskProcessor } from '../types' +import type { FormatTaskError, Task, TaskContext, TaskOutcome, TaskProcessor } from '../types' export interface ExecutorCallbacks { onUpdate: (task: Task) => void + /** Describes an error the processor throws. */ + formatError?: FormatTaskError onCancelReady?: (setCancelled: (v: boolean) => void) => void onTaskComplete?: () => void } @@ -59,12 +61,12 @@ export function createTaskContext( } updateTask() }, - fail(itemId?: string, message?: string) { + fail(itemId?: string, message?: string, detail?: string) { task.failed += 1 if (itemId || message) { task.failedItems = [ ...task.failedItems, - { id: itemId, message: message ?? 'Unknown error' }, + { id: itemId, message: message ?? 'Unknown error', ...(detail !== undefined && { detail }) }, ] } // Check errorStrategy: 'stop' - set flag to stop processing @@ -153,8 +155,7 @@ export async function executeTask( } catch (error) { task.status = 'failed' - const message = error instanceof Error ? error.message : 'Unknown error' - task.failedItems = [...task.failedItems, { message }] + task.failedItems = [...task.failedItems, describeThrown(error, callbacks.formatError)] task.failed += 1 } @@ -172,3 +173,22 @@ export async function executeTask( result: task.result, } } + +/** + * A thrown error as a failed item's message and raw detail. A formatter that + * is missing or itself throws leaves the raw message, so a broken formatter + * never stops the queue. + */ +export function describeThrown(error: unknown, formatError?: FormatTaskError): { message: string, detail?: string } { + const raw = error instanceof Error ? error.message : 'Unknown error' + if (!formatError) + return { message: raw } + try { + const { title, detail } = formatError(error) + return { message: title, ...(detail !== undefined && { detail }) } + } + catch { + // Formatting is best effort; the raw message still tells the person what failed. + return { message: raw } + } +} diff --git a/packages/datum-ui/src/components/features/task-queue/engine/queue.ts b/packages/datum-ui/src/components/features/task-queue/engine/queue.ts index e2b39f0c..41530b19 100644 --- a/packages/datum-ui/src/components/features/task-queue/engine/queue.ts +++ b/packages/datum-ui/src/components/features/task-queue/engine/queue.ts @@ -1,5 +1,6 @@ import type { EnqueueOptions, + FormatTaskError, ItemContext, ProcessItemEnqueueOptions, SummaryRenderContent, @@ -17,7 +18,7 @@ import type { } from '../types' import { TASK_QUEUE_DEFAULTS } from '../constants' import { extractItemId, generateTaskId } from '../utils' -import { executeTask } from './executor' +import { describeThrown, executeTask } from './executor' import { detectStorage } from './storage' import { SummaryStore } from './summary-store' @@ -67,11 +68,15 @@ export class TaskQueue { private readonly instanceId = generateTaskId() /** True when the backend broadcasts writes across tabs (localStorage). */ private sharedStorage = false + /** Describes thrown errors for tasks that do not set their own formatError. */ + private readonly formatError?: FormatTaskError + /** Keepalive that re-stamps this instance's live tasks in shared storage. */ private heartbeatTimer?: ReturnType constructor(config: TaskQueueConfig = {}) { this.concurrency = config.concurrency ?? TASK_QUEUE_DEFAULTS.concurrency + this.formatError = config.formatError this.storage = config.storage ?? detectStorage({ @@ -299,6 +304,7 @@ export class TaskQueue { getItemId, onComplete: options.onComplete as ((outcome: TaskOutcome) => void | Promise) | undefined, timeoutMs, + formatError: options.formatError, }) const promise = new Promise>((resolve) => { @@ -601,6 +607,7 @@ export class TaskQueue { getItemId, errorStrategy = 'continue', } = options + const formatError = options.formatError ?? this.formatError return async (ctx) => { const pending = [...ctx.items] @@ -625,6 +632,7 @@ export class TaskQueue { itemId, processItem, ctx, + formatError, ).finally(() => { // Remove from inFlight when done const idx = inFlight.indexOf(promise) @@ -648,6 +656,7 @@ export class TaskQueue { itemId: string, processItem: (item: TItem, ctx: ItemContext) => Promise, ctx: TaskContext, + formatError?: FormatTaskError, ): Promise { let manuallyHandled = false @@ -675,9 +684,8 @@ export class TaskQueue { catch (error) { // Auto-fail if not manually handled if (!manuallyHandled) { - const message - = error instanceof Error ? error.message : 'Unknown error' - ctx.fail(itemId, message) + const { message, detail } = describeThrown(error, formatError) + ctx.fail(itemId, message, detail) } } } @@ -718,6 +726,7 @@ export class TaskQueue { try { const outcome = await executeTask(task, runtime.processor, { + formatError: runtime.formatError ?? this.formatError, onUpdate: (updated) => { // Drop updates once a timeout has already finalized this task, so the // settling processor cannot overwrite the timeout status. diff --git a/packages/datum-ui/src/components/features/task-queue/provider/task-queue-provider.tsx b/packages/datum-ui/src/components/features/task-queue/provider/task-queue-provider.tsx index 95de7463..5a4d4ef7 100644 --- a/packages/datum-ui/src/components/features/task-queue/provider/task-queue-provider.tsx +++ b/packages/datum-ui/src/components/features/task-queue/provider/task-queue-provider.tsx @@ -1,6 +1,7 @@ import type { ReactNode } from 'react' import type { TaskQueueConfig } from '../types' import { createContext, useEffect, useMemo, useRef } from 'react' +import { useDescribeError } from '../../error-content/error-description-context' import { TaskQueue } from '../engine' export interface TaskQueueContextValue { @@ -17,8 +18,18 @@ interface TaskQueueProviderProps { export function TaskQueueProvider({ children, config }: TaskQueueProviderProps) { const queueRef = useRef(null) + // The queue is built once, so it reads the tree's describer through a ref. + const describe = useDescribeError() + const describeRef = useRef(describe) + useEffect(() => { + describeRef.current = describe + }, [describe]) + if (!queueRef.current) { - queueRef.current = new TaskQueue(config) + queueRef.current = new TaskQueue({ + ...config, + formatError: config?.formatError ?? (error => describeRef.current(error)), + }) } // Cleanup on unmount: fully dispose the queue (cancel running AND pending diff --git a/packages/datum-ui/src/components/features/task-queue/types.ts b/packages/datum-ui/src/components/features/task-queue/types.ts index 79d0916e..3fdb339b 100644 --- a/packages/datum-ui/src/components/features/task-queue/types.ts +++ b/packages/datum-ui/src/components/features/task-queue/types.ts @@ -1,5 +1,6 @@ import type { ReactNode } from 'react' import type { ButtonProps } from '../../base/button' +import type { ErrorDescription } from '../error-content/describe-api-error' // --- Task Status --- @@ -17,8 +18,13 @@ export type ItemStatus = 'succeeded' | 'failed' export interface FailedItem { id?: string message: string + /** The raw technical error, when `message` is a plain-language headline. */ + detail?: string } +/** Turns a thrown error into a plain headline (`title`) and raw text (`detail`). */ +export type FormatTaskError = (error: unknown) => ErrorDescription + // --- Task Metadata --- export interface TaskMetadata { @@ -42,7 +48,7 @@ export interface TaskCompletionInfo { status: TaskStatus completed: number failed: number - items: Array<{ id: string, status: ItemStatus, message?: string, data: TItem }> + items: Array<{ id: string, status: ItemStatus, message?: string, detail?: string, data: TItem }> } // --- Task --- @@ -126,6 +132,8 @@ export interface TaskRuntime { timeoutMs?: number /** Set once a timeout has fired so the settling processor can't overwrite it. */ timedOut?: boolean + /** This task's own formatError, if it set one. */ + formatError?: FormatTaskError } // --- Task Context --- @@ -136,8 +144,8 @@ export interface TaskContext { readonly failedItems: readonly FailedItem[] /** Mark current item as succeeded. Pass itemId to enable retry of remaining items on cancel. */ succeed: (itemId?: string) => void - /** Mark current item as failed. Pass itemId and message for retry support. */ - fail: (itemId?: string, message?: string) => void + /** Mark current item as failed. Pass itemId and message for retry support, and detail for the raw error. */ + fail: (itemId?: string, message?: string, detail?: string) => void setTitle: (title: string) => void setResult: (result: TResult) => void /** Register cleanup function to call on cancel/timeout. Used for watch subscription cleanup. */ @@ -169,6 +177,8 @@ export interface TaskOutcome { interface BaseEnqueueOptions { title: string + /** How to describe an error this task throws. Overrides TaskQueueConfig.formatError. */ + formatError?: FormatTaskError icon?: ReactNode category?: string metadata?: TaskMetadata @@ -274,6 +284,8 @@ export interface TaskQueueConfig { redisClient?: RedisClient | null /** Global custom renderer for TaskSummaryDialog content. Can be overridden per showSummary call. */ summaryRenderContent?: SummaryRenderContent + /** How to describe a thrown error. TaskQueueProvider defaults it to the tree's useDescribeError(). */ + formatError?: FormatTaskError } // --- Storage --- @@ -305,6 +317,8 @@ export interface TaskSummaryItem { label: string status: 'success' | 'failed' message?: string + /** The raw technical error, shown under "Error details". */ + detail?: string } export type SummaryRenderContent = (items: TaskSummaryItem[]) => ReactNode