diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringCheckStrip.tsx b/web/src/features/Admin/HostMonitoring/Components/MonitoringCheckStrip.tsx index 183f6e5fd..8c41f16c1 100644 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringCheckStrip.tsx +++ b/web/src/features/Admin/HostMonitoring/Components/MonitoringCheckStrip.tsx @@ -1,5 +1,5 @@ -import { CustomTooltip } from '@rentnerkev/tooltips/tooltip' import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import StatusStrip from '@/shared/StatusStrip/index.tsx' import HostAvailabilityBadge from './HostAvailabilityBadge.tsx' import type { MonitoringDialogHandler, @@ -15,58 +15,48 @@ export default function MonitoringCheckStrip({ }) { const { t } = useTranslationStore() return ( -
    - {slots.map(({ id, observation }) => ( -
  1. - {observation ? ( - - - -
    -
    - {t('admin.hostMonitoring.duration')} -
    -
    - {observation.durationMs === null - ? '—' - : `${observation.durationMs} ms`} -
    -
    - {t('admin.hostMonitoring.httpStatus')} -
    -
    - {observation.httpStatus ?? '—'} -
    -
    - - {t(`admin.hostMonitoring.codes.${observation.code}`)} - - - } - > -
  2. - ))} -
+ + observation + ? { + id, + tone: + observation.status === 'healthy' + ? 'positive' + : observation.status === 'unhealthy' + ? 'negative' + : 'neutral', + label: `${formatDate(observation.checkedAt)} · ${t(`admin.hostMonitoring.states.${observation.status}`)}`, + tooltip: ( +
+ + +
+
+ {t('admin.hostMonitoring.duration')} +
+
+ {observation.durationMs === null + ? '—' + : `${observation.durationMs} ms`} +
+
+ {t('admin.hostMonitoring.httpStatus')} +
+
+ {observation.httpStatus ?? '—'} +
+
+ {t(`admin.hostMonitoring.codes.${observation.code}`)} +
+ ), + } + : { id, gap: true }, + )} + /> ) } diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Hooks/useMonitoringDurationChartLogic.ts b/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Hooks/useMonitoringDurationChartLogic.ts index 3118d26a7..624dfe152 100644 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Hooks/useMonitoringDurationChartLogic.ts +++ b/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/Hooks/useMonitoringDurationChartLogic.ts @@ -1,118 +1,71 @@ -import { crosshair, defineChart, lineY } from '@tanstack/charts' -import { scaleLinear } from '@tanstack/charts/scales/linear' -import { tooltip } from '@tanstack/charts/tooltip' -import { portal } from '@tanstack/charts/tooltip/portal' -import { useMemo } from 'react' +import { useCallback, useMemo } from 'react' import { durationSeries } from '@/lib/HostMonitoring/presentation.ts' +import type { HostMonitoringObservationView } from '@/lib/HostMonitoring/Types/host-monitoring-client.types.ts' import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import useTimeSeriesChartDefinition from '@/shared/TimeSeriesChart/Hooks/useTimeSeriesChartDefinition.ts' import type { MonitoringDurationChartProps } from '../Types/duration-chart.types.ts' -const tooltipClassName = String.raw`[--ts-chart-tooltip-background:var(--theme-surface-raised)] [--ts-chart-tooltip-color:var(--theme-ink-soft)] [--ts-chart-tooltip-border:1px_solid_var(--theme-border-strong)] [--ts-chart-tooltip-border-radius:0.75rem] [--ts-chart-tooltip-shadow:var(--shadow-surface)] [--ts-chart-tooltip-padding:0.75rem] [&_.ts-chart-tooltip\_\_rows]:grid [&_.ts-chart-tooltip\_\_rows]:gap-1.5 [&_.ts-chart-tooltip\_\_row:first-child>span:last-child]:font-mono [&_.ts-chart-tooltip\_\_row:first-child>span:last-child]:text-lg [&_.ts-chart-tooltip\_\_row:first-child>span:last-child]:font-bold` +type DurationRow = ReturnType>[number] + +const checkedAt = (row: DurationRow) => row.checkedAt +const duration = (row: DurationRow) => row.durationMs export default function useMonitoringDurationChartLogic( observations: MonitoringDurationChartProps['observations'], ) { const { t, locale } = useTranslationStore() - const definition = useMemo(() => { - const rows = durationSeries(observations) - const first = rows[0]?.checkedAt.getTime() ?? 0 - const last = rows.at(-1)?.checkedAt.getTime() ?? 1 - const maximum = Math.max(1, ...rows.map((row) => row.durationMs ?? 0)) - const time = new Intl.DateTimeFormat(locale, { - ...(last - first > 86_400_000 ? ({ day: 'numeric', month: 'short' } as const) : {}), - hour: '2-digit', - minute: '2-digit', - }) - const date = new Intl.DateTimeFormat(locale, { - dateStyle: 'medium', - timeStyle: 'medium', - }) - const milliseconds = new Intl.NumberFormat(locale, { - style: 'unit', - unit: 'millisecond', - unitDisplay: 'short', - maximumFractionDigits: 0, - }) - return defineChart({ - marks: [ - lineY(rows, { - id: 'monitoring-duration', - key: 'id', - x: (row) => row.checkedAt.getTime(), - y: 'durationMs', - points: true, - stroke: 'var(--color-brand-500)', - strokeWidth: 2, - }), - crosshair({ - x: true, - y: false, - stroke: 'var(--theme-muted)', - strokeDasharray: '3 4', - }), - ], - scales: { - x: { - scale: () => scaleLinear().domain([first, last]), - axis: { ticks: { count: 4, format: (value) => time.format(Number(value)) } }, - }, - y: { - scale: () => scaleLinear().domain([0, maximum]), - nice: true, - grid: true, - axis: { - ticks: { - ...(maximum <= 1 ? { values: [0, 1] } : { count: 4 }), - format: (value) => milliseconds.format(Number(value)), - }, - }, - }, - }, - margin: { left: 65, right: 15, top: 12, bottom: 30 }, - focus: 'nearest-x', - tooltip: { - use: tooltip, - portal, - className: tooltipClassName, - content: (points) => { - const row = points[0]?.datum - if (!row || row.durationMs === null) return { rows: [] } - return { - title: date.format(row.checkedAt), - rows: [ - { - label: t('admin.hostMonitoring.duration'), - value: milliseconds.format(row.durationMs), - color: - row.status === 'unhealthy' - ? 'var(--theme-danger-text)' - : 'var(--color-brand-500)', - }, - { - label: t('admin.hostMonitoring.status'), - value: t(`admin.hostMonitoring.states.${row.status}`), - }, - { - label: t('admin.hostMonitoring.httpStatus'), - value: String(row.httpStatus ?? '—'), - }, - ], - } - }, - }, - focusRing: { - fill: 'var(--theme-surface-raised)', - stroke: 'var(--color-brand-500)', - strokeWidth: 2, - }, - theme: { - foreground: 'var(--theme-ink-soft)', - muted: 'var(--theme-muted)', - grid: 'var(--theme-border)', - background: 'transparent', - }, - }) - }, [observations, locale, t]) + const rows = useMemo(() => durationSeries(observations), [observations]) + const formats = useMemo( + () => ({ + date: new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'medium' }), + milliseconds: new Intl.NumberFormat(locale, { + style: 'unit', + unit: 'millisecond', + unitDisplay: 'short', + maximumFractionDigits: 0, + }), + }), + [locale], + ) + const formatValue = useCallback( + (value: number) => formats.milliseconds.format(value), + [formats], + ) + const tooltip = useCallback( + (row: DurationRow) => + row.durationMs === null + ? null + : { + title: formats.date.format(row.checkedAt), + rows: [ + { + label: t('admin.hostMonitoring.duration'), + value: formats.milliseconds.format(row.durationMs), + color: + row.status === 'unhealthy' + ? 'var(--theme-danger-text)' + : 'var(--color-brand-500)', + }, + { + label: t('admin.hostMonitoring.status'), + value: t(`admin.hostMonitoring.states.${row.status}`), + }, + { + label: t('admin.hostMonitoring.httpStatus'), + value: String(row.httpStatus ?? '—'), + }, + ], + }, + [formats, t], + ) + const definition = useTimeSeriesChartDefinition({ + id: 'monitoring-duration', + rows, + time: checkedAt, + value: duration, + formatValue, + tooltip, + }) return { state: { definition, diff --git a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/index.tsx b/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/index.tsx index 35b1892b7..bc3553086 100644 --- a/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/index.tsx +++ b/web/src/features/Admin/HostMonitoring/Components/MonitoringDurationChart/index.tsx @@ -1,19 +1,15 @@ -import { Chart } from '@tanstack/charts/react' +import TimeSeriesChart from '@/shared/TimeSeriesChart/index.tsx' import useMonitoringDurationChartLogic from './Hooks/useMonitoringDurationChartLogic.ts' import type { MonitoringDurationChartProps } from './Types/duration-chart.types.ts' export default function MonitoringDurationChart({ observations }: MonitoringDurationChartProps) { const { state } = useMonitoringDurationChartLogic(observations) return ( -
-
{state.title}
- -
+ ) } diff --git a/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteDataElements.tsx b/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteDataElements.tsx new file mode 100644 index 000000000..51e4481b6 --- /dev/null +++ b/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteDataElements.tsx @@ -0,0 +1,188 @@ +import { uiKitCatalog } from '@rentnerproxy/app-contracts' +import { useCallback, useMemo } from 'react' + +import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import StatusStrip from '@/shared/StatusStrip/index.tsx' +import type { StatusStripTone } from '@/shared/StatusStrip/Types/status-strip.types.ts' +import DataTable from '@/shared/Table/index.tsx' +import TimeSeriesChart from '@/shared/TimeSeriesChart/index.tsx' +import useTimeSeriesChartDefinition from '@/shared/TimeSeriesChart/Hooks/useTimeSeriesChartDefinition.ts' +import { appUiBadgeClassName, appUiMeasureFormats, appUiTones } from '../../../appUiPresentation.ts' +import useRemoteDataTableLogic from '../Hooks/useRemoteDataTableLogic.ts' +import useRemoteProperties from '../Hooks/useRemoteProperties.ts' +import type { RemoteElementProps } from '../Types/remote-app-view.types.ts' + +type ChartPoint = { + readonly id: string + readonly time: string + readonly value: number | null + readonly tone?: keyof typeof appUiTones | undefined + readonly details?: readonly { readonly label: string; readonly value: string }[] | undefined +} + +const chartHeights = { sm: 120, md: 180, lg: 260 } as const +const stripTones: Record = { + positive: 'positive', + negative: 'negative', + warning: 'warning', + info: 'info', + neutral: 'neutral', + paused: 'neutral', + stale: 'neutral', +} +const pointTime = (point: ChartPoint) => new Date(point.time) +const pointValue = (point: ChartPoint) => point.value + +// A positive or unmarked point keeps the line's brand colour, as in the monitoring chart. +const toneColors: Record = { + positive: 'var(--color-brand-500)', + negative: 'var(--theme-danger-text)', + warning: 'var(--theme-warning-text)', + info: 'var(--theme-info-text)', + neutral: 'var(--theme-muted)', + paused: 'var(--theme-muted)', + stale: 'var(--theme-muted)', +} + +function toneColor(tone: ChartPoint['tone']) { + return tone ? toneColors[tone] : toneColors.positive +} + +/** Label and value pairs in a tooltip, aligned like the platform's own. */ +function DetailList({ details }: { readonly details: ChartPoint['details'] }) { + if (!details?.length) return null + return ( +
+ {details.map((detail) => ( +
+
{detail.label}
+
{detail.value}
+
+ ))} +
+ ) +} + +export function RemoteDataTable({ entry, slots, emit }: RemoteElementProps) { + const { t } = useTranslationStore() + const { props, table, state, handler } = useRemoteDataTableLogic(entry, emit) + const itemLabel = props.itemLabel ?? t('appUi.rows') + return ( + + ) +} + +export function RemoteTimeSeriesChart({ entry }: RemoteElementProps) { + const { label, description, height, unit, points } = useRemoteProperties( + uiKitCatalog['ui-time-series-chart'].properties, + entry, + ) + const { locale } = useTranslationStore() + const formats = useMemo( + () => ({ + date: new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'medium' }), + value: new Intl.NumberFormat(locale, { + ...appUiMeasureFormats[unit], + maximumFractionDigits: unit === 'ms' || unit === 'count' ? 0 : 2, + }), + }), + [locale, unit], + ) + const formatValue = useCallback((value: number) => formats.value.format(value), [formats]) + const tooltip = useCallback( + (point: ChartPoint) => ({ + title: formats.date.format(new Date(point.time)), + rows: [ + { + label, + value: point.value === null ? '—' : formats.value.format(point.value), + color: toneColor(point.tone), + }, + ...(point.details ?? []), + ], + }), + [formats, label], + ) + const definition = useTimeSeriesChartDefinition({ + id: `app-chart-${entry.id}`, + rows: points, + time: pointTime, + value: pointValue, + formatValue, + tooltip, + }) + return ( + + ) +} + +export function RemoteStatusStrip({ entry }: RemoteElementProps) { + const { label, slots, emptyLabel, items } = useRemoteProperties( + uiKitCatalog['ui-status-strip'].properties, + entry, + ) + const { locale } = useTranslationStore() + const strip = useMemo(() => { + const date = new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'medium' }) + const count = slots ?? Math.max(1, items.length) + const shown = items.slice(-count) + return [ + ...Array.from({ length: count - shown.length }, (_, index) => ({ + id: `gap-${index}`, + gap: true as const, + })), + ...shown.map((item) => { + const time = date.format(new Date(item.time)) + const tone = appUiTones[item.tone] + return { + id: item.id, + tone: stripTones[item.tone], + label: `${time} · ${item.label}`, + tooltip: ( +
+ + + + +
+ ), + } + }), + ] + }, [items, locale, slots]) + return +} diff --git a/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteNode.tsx b/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteNode.tsx index d74f3b8b7..bd08c2382 100644 --- a/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteNode.tsx +++ b/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteNode.tsx @@ -24,7 +24,7 @@ import { RemotePageHeader, RemoteStack, } from './RemoteLayoutElements.tsx' -import RemoteUnsupportedElement from './RemoteUnsupportedElement.tsx' +import { RemoteDataTable, RemoteStatusStrip, RemoteTimeSeriesChart } from './RemoteDataElements.tsx' import { RemoteDialog, RemoteTabPanel, RemoteTabs } from './RemoteDialogElements.tsx' import { RemoteNumberField, @@ -60,9 +60,9 @@ const elements: Record> = { 'ui-number-field': RemoteNumberField, 'ui-toggle': RemoteToggle, 'ui-select': RemoteSelect, - 'ui-data-table': RemoteUnsupportedElement, - 'ui-time-series-chart': RemoteUnsupportedElement, - 'ui-status-strip': RemoteUnsupportedElement, + 'ui-data-table': RemoteDataTable, + 'ui-time-series-chart': RemoteTimeSeriesChart, + 'ui-status-strip': RemoteStatusStrip, } function RemoteElement({ entry }: { readonly entry: RemoteUiElementEntry }) { diff --git a/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteTableCell.tsx b/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteTableCell.tsx new file mode 100644 index 000000000..9f8a7666c --- /dev/null +++ b/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteTableCell.tsx @@ -0,0 +1,50 @@ +import HttpStatusBadge from '@/shared/HttpStatusBadge/index.tsx' +import { appUiBadgeClassName, appUiTones } from '../../../appUiPresentation.ts' +import type { RemoteTableCellProps } from '../Types/remote-app-view.types.ts' +import RemoteUiIcon from './RemoteUiIcon.tsx' + +/** One table cell an app sends, drawn by its shape; the column kind decides for plain values. */ +export default function RemoteTableCell({ kind, cell, formats }: RemoteTableCellProps) { + if (cell === undefined || cell === null) return — + if (typeof cell === 'number') { + if (kind === 'http-status') return + return {formats.number.format(cell)} + } + if (typeof cell === 'string') { + if (kind === 'time') + return ( + + ) + return ( + {cell} + ) + } + if ('badge' in cell) { + const tone = appUiTones[cell.badge.tone] + return ( + + {cell.badge.icon ? ( + + ) : ( + + ) + } + if ('time' in cell) + return ( + + ) + if ('measure' in cell) + return ( + + {formats.measure(cell.measure.value, cell.measure.unit)} + + ) + return +} diff --git a/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteUnsupportedElement.tsx b/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteUnsupportedElement.tsx deleted file mode 100644 index fcf7abac7..000000000 --- a/web/src/features/AppUi/Components/RemoteAppView/Components/RemoteUnsupportedElement.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' - -/** A UI kit element this platform version cannot draw yet; its subtree stays out of the page. */ -export default function RemoteUnsupportedElement() { - const { t } = useTranslationStore() - return ( - - {t('appUi.remote.unsupported')} - - ) -} diff --git a/web/src/features/AppUi/Components/RemoteAppView/Hooks/useRemoteDataTableLogic.ts b/web/src/features/AppUi/Components/RemoteAppView/Hooks/useRemoteDataTableLogic.ts new file mode 100644 index 000000000..10f928aea --- /dev/null +++ b/web/src/features/AppUi/Components/RemoteAppView/Hooks/useRemoteDataTableLogic.ts @@ -0,0 +1,248 @@ +import { uiKitCatalog } from '@rentnerproxy/app-contracts' +import { sortFn_datetime } from '@tanstack/react-table' +import type { ColumnDef, FilterFn } from '@tanstack/react-table' +import { createElement, useCallback, useMemo, useState } from 'react' + +import { createDateRangeFilter } from '@/lib/Table/tableFilters.ts' +import { ActionMenu } from '@/shared/ActionMenu/index.tsx' +import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import useClientTable from '@/shared/Table/Hooks/useClientTable.ts' +import type { ClientTableFeatures } from '@/shared/Table/Types/client-table.types.ts' +import type { + ClientTableState, + TableColumnFilterConfigs, +} from '@/shared/Table/Types/table.types.ts' +import type { RemoteUiElementEntry } from '@/lib/AppUi/remote-tree.ts' +import { appUiMeasureFormats } from '../../../appUiPresentation.ts' +import RemoteTableCell from '../Components/RemoteTableCell.tsx' +import type { + RemoteCellFormats, + RemoteElementProps, + RemoteTableCellValue, + RemoteTableColumn, + RemoteTableQuery, + RemoteTableRow, +} from '../Types/remote-app-view.types.ts' +import useRemoteProperties from './useRemoteProperties.ts' + +const getRowId = (row: RemoteTableRow) => row.id +const dateFilter = createDateRangeFilter() + +/** The value a cell sorts and filters by; time columns sort as dates. */ +function sortValue(column: RemoteTableColumn, cell: RemoteTableCellValue | undefined) { + if (cell === undefined || cell === null) return undefined + if (typeof cell === 'string') return column.kind === 'time' ? new Date(cell) : cell + if (typeof cell === 'number') return cell + if ('badge' in cell) return cell.badge.label + if ('time' in cell) return new Date(cell.time) + if ('measure' in cell) return cell.measure.value + return cell.httpStatus +} + +/** The text a user sees in a cell, which search and text filters match against. */ +function cellText( + column: RemoteTableColumn, + cell: RemoteTableCellValue | undefined, + formats: RemoteCellFormats, +) { + if (cell === undefined || cell === null) return '' + // A plain string in a time column shows as a localized time, so it is searched as one. + if (typeof cell === 'string') return column.kind === 'time' ? formats.time(cell) : cell + if (typeof cell === 'number') return formats.number.format(cell) + if ('badge' in cell) return cell.badge.label + if ('time' in cell) return formats.time(cell.time) + if ('measure' in cell) return formats.measure(cell.measure.value, cell.measure.unit) + return String(cell.httpStatus) +} + +/** The value a select filter option names: the plain value, a badge label or an HTTP status. */ +function choiceValue(cell: RemoteTableCellValue | undefined) { + if (cell === undefined || cell === null) return '' + if (typeof cell === 'string' || typeof cell === 'number') return String(cell) + if ('badge' in cell) return cell.badge.label + if ('time' in cell) return cell.time + if ('measure' in cell) return String(cell.measure.value) + return String(cell.httpStatus) +} + +function tableQuery(state: ClientTableState): RemoteTableQuery { + const [sort] = state.sorting + return { + search: typeof state.globalFilter === 'string' ? state.globalFilter : '', + filters: state.columnFilters.map((filter) => ({ column: filter.id, value: filter.value })), + sort: sort ? { column: sort.id, desc: sort.desc } : null, + page: { index: state.pagination.pageIndex, size: state.pagination.pageSize }, + } +} + +/** + * An app table on the platform's table: client mode sorts, filters and pages the rows it has; in + * remote mode every change is a `query` event and the app answers with the rows of that page. + */ +export default function useRemoteDataTableLogic( + entry: RemoteUiElementEntry, + emit: RemoteElementProps['emit'], +) { + const props = useRemoteProperties(uiKitCatalog['ui-data-table'].properties, entry) + const { t, locale } = useTranslationStore() + const [showColumnFilters, setShowColumnFilters] = useState(false) + const { columns: appColumns, rows, rowActions, mode, initialSort, pageSize, rowCount } = props + const remote = mode === 'remote' + const acts = entry.listeners.includes('action') && (rowActions?.length ?? 0) > 0 + const queries = entry.listeners.includes('query') + + const formats = useMemo(() => { + const date = new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'medium' }) + return { + number: new Intl.NumberFormat(locale), + time: (value) => date.format(new Date(value)), + measure: (value, unit) => + new Intl.NumberFormat(locale, appUiMeasureFormats[unit]).format(value), + } + }, [locale]) + + const columns = useMemo>>(() => { + const drawn: Array> = appColumns.map( + (column) => { + const filterFn: FilterFn = + column.filter?.type === 'date-range' + ? dateFilter + : column.filter?.type === 'select' + ? (row, _id, value) => + choiceValue(row.original.cells[column.id]) === String(value) + : (row, _id, value) => + cellText(column, row.original.cells[column.id], formats) + .toLocaleLowerCase(locale) + .includes(String(value).toLocaleLowerCase(locale)) + return { + id: column.id, + accessorFn: (row) => sortValue(column, row.cells[column.id]), + header: column.header, + enableSorting: column.sortable === true, + enableColumnFilter: column.filter !== undefined, + // Search matches the shown text of every column, including times and badges, + // whose sort values are no strings TanStack would search by itself. + enableGlobalFilter: true, + sortUndefined: 'last', + ...(column.kind === 'time' ? { sortFn: sortFn_datetime } : {}), + filterFn, + cell: ({ row }) => + createElement(RemoteTableCell, { + kind: column.kind, + cell: row.original.cells[column.id], + formats, + }), + } + }, + ) + if (!acts || !rowActions) return drawn + return [ + ...drawn, + { + id: 'actions', + header: t('common.actions'), + enableSorting: false, + enableColumnFilter: false, + enableGlobalFilter: false, + cell: ({ row }) => + createElement(ActionMenu, { + items: rowActions.map((action) => ({ + id: action.id, + label: action.label, + ...(action.destructive ? { destructive: true } : {}), + onSelect: () => emit('action', { action: action.id, row: row.id }), + })), + openOnHover: false, + }), + }, + ] + }, [acts, appColumns, emit, formats, locale, rowActions, t]) + + const columnFilterConfigs = useMemo( + () => + Object.fromEntries( + appColumns.flatMap((column): Array<[string, TableColumnFilterConfigs[string]]> => { + const { filter } = column + if (!filter) return [] + const placeholder = filter.placeholder + ? { placeholder: filter.placeholder } + : {} + if (filter.type === 'date-range') return [[column.id, { type: 'dateRange' }]] + if (filter.type === 'select') + return [ + [ + column.id, + { type: 'select', ...placeholder, options: filter.options ?? [] }, + ], + ] + return [[column.id, { type: 'text', ...placeholder, maxLength: 200 }]] + }), + ), + [appColumns], + ) + + const globalFilterFn = useMemo>( + () => (row, _id, value) => { + const search = String(value).trim().toLocaleLowerCase(locale) + return appColumns + .map((column) => cellText(column, row.original.cells[column.id], formats)) + .join(' ') + .toLocaleLowerCase(locale) + .includes(search) + }, + [appColumns, formats, locale], + ) + + const onStateChange = useCallback( + (state: ClientTableState) => { + if (queries) emit('query', { ...tableQuery(state) }) + }, + [emit, queries], + ) + const data = useMemo(() => [...rows], [rows]) + const sorting = initialSort ? [{ id: initialSort.column, desc: initialSort.desc }] : [] + const { table, state, handler } = useClientTable({ + data, + columns, + getRowId, + initialSorting: sorting, + initialPageSize: pageSize ?? 10, + globalFilterFn, + ...(remote + ? { + remote: { + rowCount: rowCount ?? rows.length, + initialState: { + globalFilter: '', + columnFilters: [], + sorting, + pagination: { pageIndex: 0, pageSize: pageSize ?? 10 }, + }, + onStateChange, + }, + } + : {}), + }) + + return { + props, + table, + state: { + searchInput: state.searchInput, + showColumnFilters, + columnFilterConfigs, + filterable: Object.keys(columnFilterConfigs).length > 0, + minWidth: + columns.length <= 3 + ? 'min-w-[30rem]' + : columns.length <= 6 + ? 'min-w-[46rem]' + : 'min-w-[60rem]', + }, + handler: { + handleSearchInputChange: handler.handleSearchInputChange, + handleResetFilters: handler.handleResetFilters, + handleToggleColumnFilters: () => setShowColumnFilters((current) => !current), + }, + } +} diff --git a/web/src/features/AppUi/Components/RemoteAppView/Types/remote-app-view.types.ts b/web/src/features/AppUi/Components/RemoteAppView/Types/remote-app-view.types.ts index 2c5dcace8..e5c94e5a6 100644 --- a/web/src/features/AppUi/Components/RemoteAppView/Types/remote-app-view.types.ts +++ b/web/src/features/AppUi/Components/RemoteAppView/Types/remote-app-view.types.ts @@ -1,4 +1,6 @@ +import type { uiKitCatalog } from '@rentnerproxy/app-contracts' import type { ReactNode } from 'react' +import type { z } from 'zod' import type { RemoteFormStore } from '@/lib/AppUi/remote-forms.ts' import type { RemoteUiElementEntry, RemoteUiEvent, RemoteUiStore } from '@/lib/AppUi/remote-tree.ts' @@ -80,3 +82,30 @@ export interface RemoteFieldBinding { readonly disabled: boolean readonly id: string } + +type DataTableProperties = z.output<(typeof uiKitCatalog)['ui-data-table']['properties']> +export type RemoteTableColumn = DataTableProperties['columns'][number] +export type RemoteTableRow = DataTableProperties['rows'][number] +export type RemoteTableCellValue = RemoteTableRow['cells'][string] +export type RemoteMeasureUnit = 'ms' | 's' | 'percent' | 'count' + +/** Locale formats shared by every cell of one table. */ +export interface RemoteCellFormats { + readonly number: Intl.NumberFormat + readonly time: (value: string) => string + readonly measure: (value: number, unit: RemoteMeasureUnit) => string +} + +export interface RemoteTableCellProps { + readonly kind: RemoteTableColumn['kind'] + readonly cell: RemoteTableCellValue | undefined + readonly formats: RemoteCellFormats +} + +/** What the app hears when a remote table needs other rows. */ +export interface RemoteTableQuery { + readonly search: string + readonly filters: readonly { readonly column: string; readonly value: unknown }[] + readonly sort: { readonly column: string; readonly desc: boolean } | null + readonly page: { readonly index: number; readonly size: number } +} diff --git a/web/src/lib/Language/Locales/de.json b/web/src/lib/Language/Locales/de.json index aae71c6fd..8d8127258 100644 --- a/web/src/lib/Language/Locales/de.json +++ b/web/src/lib/Language/Locales/de.json @@ -407,7 +407,13 @@ "empty": "Noch nichts vorhanden", "error": "Etwas ist schiefgelaufen" }, - "unsupported": "Dieser Teil der App kann in dieser Plattform-Version nicht angezeigt werden.", + "table": { + "title": "Einträge", + "search": "Suchen", + "searchPlaceholder": "Einträge durchsuchen…", + "filteredEmptyTitle": "Keine passenden Einträge", + "filteredEmptyDescription": "Ändere die Filter oder setze sie zurück, um mehr Einträge zu sehen." + }, "form": { "conflict": "Die gespeicherten Werte haben sich inzwischen geändert. Verwirf deine Änderungen, um mit den aktuellen Werten weiterzumachen." } diff --git a/web/src/lib/Language/Locales/en.json b/web/src/lib/Language/Locales/en.json index c1140ef83..c56ea890b 100644 --- a/web/src/lib/Language/Locales/en.json +++ b/web/src/lib/Language/Locales/en.json @@ -407,7 +407,13 @@ "empty": "Nothing here yet", "error": "Something went wrong" }, - "unsupported": "This part of the app cannot be shown on this platform version.", + "table": { + "title": "Entries", + "search": "Search", + "searchPlaceholder": "Search entries…", + "filteredEmptyTitle": "No matching entries", + "filteredEmptyDescription": "Change or reset the filters to see more entries." + }, "form": { "conflict": "The saved values changed in the meantime. Discard your changes to continue with the current values." } diff --git a/web/src/lib/Language/Locales/es.json b/web/src/lib/Language/Locales/es.json index 9dada35e9..3535e5044 100644 --- a/web/src/lib/Language/Locales/es.json +++ b/web/src/lib/Language/Locales/es.json @@ -409,7 +409,13 @@ "empty": "Todavía no hay nada aquí", "error": "Algo salió mal" }, - "unsupported": "Esta parte de la app no se puede mostrar en esta versión de la plataforma.", + "table": { + "title": "Entradas", + "search": "Buscar", + "searchPlaceholder": "Buscar entradas…", + "filteredEmptyTitle": "No hay entradas coincidentes", + "filteredEmptyDescription": "Cambia o restablece los filtros para ver más entradas." + }, "form": { "conflict": "Los valores guardados han cambiado mientras tanto. Descarta tus cambios para continuar con los valores actuales." } diff --git a/web/src/lib/Language/Locales/fr.json b/web/src/lib/Language/Locales/fr.json index a87605a25..592c4c99d 100644 --- a/web/src/lib/Language/Locales/fr.json +++ b/web/src/lib/Language/Locales/fr.json @@ -409,7 +409,13 @@ "empty": "Rien pour l’instant", "error": "Une erreur est survenue" }, - "unsupported": "Cette partie de l’app ne peut pas être affichée dans cette version de la plateforme.", + "table": { + "title": "Entrées", + "search": "Rechercher", + "searchPlaceholder": "Rechercher des entrées…", + "filteredEmptyTitle": "Aucune entrée correspondante", + "filteredEmptyDescription": "Modifie ou réinitialise les filtres pour voir plus d’entrées." + }, "form": { "conflict": "Les valeurs enregistrées ont changé entre-temps. Abandonne tes modifications pour continuer avec les valeurs actuelles." } diff --git a/web/src/lib/Language/Locales/it.json b/web/src/lib/Language/Locales/it.json index 08d8f0991..f6fcb08d2 100644 --- a/web/src/lib/Language/Locales/it.json +++ b/web/src/lib/Language/Locales/it.json @@ -409,7 +409,13 @@ "empty": "Ancora niente qui", "error": "Qualcosa è andato storto" }, - "unsupported": "Questa parte dell’app non può essere mostrata in questa versione della piattaforma.", + "table": { + "title": "Voci", + "search": "Cerca", + "searchPlaceholder": "Cerca voci…", + "filteredEmptyTitle": "Nessuna voce corrispondente", + "filteredEmptyDescription": "Modifica o reimposta i filtri per vedere più voci." + }, "form": { "conflict": "I valori salvati sono cambiati nel frattempo. Annulla le modifiche per continuare con i valori attuali." } diff --git a/web/src/lib/Language/Locales/nl.json b/web/src/lib/Language/Locales/nl.json index 8704895c9..67c22bb97 100644 --- a/web/src/lib/Language/Locales/nl.json +++ b/web/src/lib/Language/Locales/nl.json @@ -388,7 +388,13 @@ "empty": "Hier staat nog niets", "error": "Er is iets misgegaan" }, - "unsupported": "Dit deel van de app kan in deze platformversie niet worden weergegeven.", + "table": { + "title": "Items", + "search": "Zoeken", + "searchPlaceholder": "Items zoeken…", + "filteredEmptyTitle": "Geen overeenkomende items", + "filteredEmptyDescription": "Wijzig of herstel de filters om meer items te zien." + }, "form": { "conflict": "De opgeslagen waarden zijn intussen gewijzigd. Verwerp je wijzigingen om verder te gaan met de huidige waarden." } diff --git a/web/src/lib/Language/Locales/pl.json b/web/src/lib/Language/Locales/pl.json index 352bb2b39..358a9c15a 100644 --- a/web/src/lib/Language/Locales/pl.json +++ b/web/src/lib/Language/Locales/pl.json @@ -411,7 +411,13 @@ "empty": "Na razie nic tu nie ma", "error": "Coś poszło nie tak" }, - "unsupported": "Tej części aplikacji nie można wyświetlić w tej wersji platformy.", + "table": { + "title": "Wpisy", + "search": "Szukaj", + "searchPlaceholder": "Szukaj wpisów…", + "filteredEmptyTitle": "Brak pasujących wpisów", + "filteredEmptyDescription": "Zmień lub zresetuj filtry, aby zobaczyć więcej wpisów." + }, "form": { "conflict": "Zapisane wartości zmieniły się w międzyczasie. Odrzuć zmiany, aby kontynuować z aktualnymi wartościami." } diff --git a/web/src/lib/Language/Locales/pt.json b/web/src/lib/Language/Locales/pt.json index bdae35dc7..c63617566 100644 --- a/web/src/lib/Language/Locales/pt.json +++ b/web/src/lib/Language/Locales/pt.json @@ -409,7 +409,13 @@ "empty": "Ainda não há nada aqui", "error": "Algo correu mal" }, - "unsupported": "Esta parte da app não pode ser apresentada nesta versão da plataforma.", + "table": { + "title": "Entradas", + "search": "Pesquisar", + "searchPlaceholder": "Pesquisar entradas…", + "filteredEmptyTitle": "Nenhuma entrada correspondente", + "filteredEmptyDescription": "Altera ou repõe os filtros para ver mais entradas." + }, "form": { "conflict": "Os valores guardados mudaram entretanto. Descarta as tuas alterações para continuar com os valores atuais." } diff --git a/web/src/shared/StatusStrip/Types/status-strip.types.ts b/web/src/shared/StatusStrip/Types/status-strip.types.ts new file mode 100644 index 000000000..591b8329c --- /dev/null +++ b/web/src/shared/StatusStrip/Types/status-strip.types.ts @@ -0,0 +1,24 @@ +import type { ReactNode } from 'react' + +export type StatusStripTone = 'positive' | 'negative' | 'warning' | 'info' | 'neutral' + +export interface StatusStripItem { + readonly id: string + readonly tone: StatusStripTone + /** Read to screen readers, such as the time and state of a check. */ + readonly label: string + readonly tooltip: ReactNode +} + +/** A slot without an entry yet, such as a check that has not run. */ +export interface StatusStripGap { + readonly id: string + readonly gap: true +} + +export interface StatusStripProps { + readonly label: string + readonly gapLabel: string + /** Ordered from oldest to newest. */ + readonly slots: readonly (StatusStripItem | StatusStripGap)[] +} diff --git a/web/src/shared/StatusStrip/index.tsx b/web/src/shared/StatusStrip/index.tsx new file mode 100644 index 000000000..27f0ba751 --- /dev/null +++ b/web/src/shared/StatusStrip/index.tsx @@ -0,0 +1,36 @@ +import { CustomTooltip } from '@rentnerkev/tooltips/tooltip' + +import type { StatusStripProps, StatusStripTone } from './Types/status-strip.types.ts' + +const tones: Record = { + positive: 'bg-success-text', + negative: 'bg-danger-text', + warning: 'bg-warning-text', + info: 'bg-info-text', + neutral: 'bg-border-strong', +} + +/** A row of status blocks, oldest first, each with its details in a tooltip. */ +export default function StatusStrip({ label, gapLabel, slots }: StatusStripProps) { + return ( +
    + {slots.map((slot) => ( +
  1. + {'gap' in slot ? ( + + {gapLabel} + + ) : ( + +
  2. + ))} +
+ ) +} diff --git a/web/src/shared/Table/Components/TableLayout.tsx b/web/src/shared/Table/Components/TableLayout.tsx index fe833a8ed..c96a98e13 100644 --- a/web/src/shared/Table/Components/TableLayout.tsx +++ b/web/src/shared/Table/Components/TableLayout.tsx @@ -18,10 +18,12 @@ export default function TableLayout({ >
-

- {eyebrow} -

-

+ {eyebrow ? ( +

+ {eyebrow} +

+ ) : null} +

{title}

{description ? ( diff --git a/web/src/shared/Table/Types/table-layout.types.ts b/web/src/shared/Table/Types/table-layout.types.ts index e3242593a..969ff5258 100644 --- a/web/src/shared/Table/Types/table-layout.types.ts +++ b/web/src/shared/Table/Types/table-layout.types.ts @@ -3,7 +3,7 @@ import type { ReactNode } from 'react' export interface TableLayoutProps { readonly titleId: string readonly title: string - readonly eyebrow: string + readonly eyebrow?: string | undefined readonly description?: string | undefined readonly toolbar?: ReactNode readonly filterToggle?: ReactNode diff --git a/web/src/shared/Table/Types/table.types.ts b/web/src/shared/Table/Types/table.types.ts index 2c21b13da..71ca1d6ff 100644 --- a/web/src/shared/Table/Types/table.types.ts +++ b/web/src/shared/Table/Types/table.types.ts @@ -162,12 +162,14 @@ export interface RemoteTablePaginationProps extends Omit< export interface DataTableProps { readonly table: ClientTable - readonly eyebrow: string + readonly eyebrow?: string | undefined readonly title: string readonly description?: string | undefined readonly searchInput: string readonly searchLabel: string readonly searchPlaceholder: string + /** Hides the search field for tables whose rows need no search. */ + readonly enableSearch?: boolean readonly showColumnFilters: boolean readonly enableColumnFilters?: boolean readonly onSearchChange: (value: string) => void diff --git a/web/src/shared/Table/index.tsx b/web/src/shared/Table/index.tsx index f15200fa5..6ef3152fa 100644 --- a/web/src/shared/Table/index.tsx +++ b/web/src/shared/Table/index.tsx @@ -22,6 +22,7 @@ export default function DataTable({ searchInput, searchLabel, searchPlaceholder, + enableSearch = true, showColumnFilters, enableColumnFilters = true, onSearchChange, @@ -47,13 +48,15 @@ export default function DataTable({ description={description} toolbar={
- + {enableSearch ? ( + + ) : null} {action}
} diff --git a/web/src/shared/TimeSeriesChart/Hooks/useTimeSeriesChartDefinition.ts b/web/src/shared/TimeSeriesChart/Hooks/useTimeSeriesChartDefinition.ts new file mode 100644 index 000000000..972283b2b --- /dev/null +++ b/web/src/shared/TimeSeriesChart/Hooks/useTimeSeriesChartDefinition.ts @@ -0,0 +1,99 @@ +import { crosshair, defineChart, lineY } from '@tanstack/charts' +import { scaleLinear } from '@tanstack/charts/scales/linear' +import { tooltip as tooltipExtension } from '@tanstack/charts/tooltip' +import { portal } from '@tanstack/charts/tooltip/portal' +import { useMemo } from 'react' + +import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import type { TimeSeriesChartOptions } from '../Types/time-series-chart.types.ts' + +const tooltipClassName = String.raw`[--ts-chart-tooltip-background:var(--theme-surface-raised)] [--ts-chart-tooltip-color:var(--theme-ink-soft)] [--ts-chart-tooltip-border:1px_solid_var(--theme-border-strong)] [--ts-chart-tooltip-border-radius:0.75rem] [--ts-chart-tooltip-shadow:var(--shadow-surface)] [--ts-chart-tooltip-padding:0.75rem] [&_.ts-chart-tooltip\_\_rows]:grid [&_.ts-chart-tooltip\_\_rows]:gap-1.5 [&_.ts-chart-tooltip\_\_row:first-child>span:last-child]:font-mono [&_.ts-chart-tooltip\_\_row:first-child>span:last-child]:text-lg [&_.ts-chart-tooltip\_\_row:first-child>span:last-child]:font-bold` + +/** + * A line of values over time in the platform's chart style: a zero-based value axis, time ticks that + * show the day once the series spans more than one, a crosshair and a tooltip per point. + */ +export default function useTimeSeriesChartDefinition({ + id, + rows, + time, + value, + formatValue, + tooltip, +}: TimeSeriesChartOptions) { + const { locale } = useTranslationStore() + return useMemo(() => { + const sorted = rows.toSorted((a, b) => time(a).getTime() - time(b).getTime()) + const [firstRow] = sorted + const lastRow = sorted.at(-1) + const first = firstRow ? time(firstRow).getTime() : 0 + const last = lastRow ? time(lastRow).getTime() : 1 + const maximum = Math.max(1, ...sorted.map((row) => value(row) ?? 0)) + const ticks = new Intl.DateTimeFormat(locale, { + ...(last - first > 86_400_000 ? ({ day: 'numeric', month: 'short' } as const) : {}), + hour: '2-digit', + minute: '2-digit', + }) + return defineChart({ + marks: [ + lineY(sorted, { + id, + key: (row) => row.id, + x: (row) => time(row).getTime(), + y: (row) => value(row), + points: true, + stroke: 'var(--color-brand-500)', + strokeWidth: 2, + }), + crosshair({ + x: true, + y: false, + stroke: 'var(--theme-muted)', + strokeDasharray: '3 4', + }), + ], + scales: { + x: { + scale: () => scaleLinear().domain([first, last]), + axis: { ticks: { count: 4, format: (tick) => ticks.format(Number(tick)) } }, + }, + y: { + scale: () => scaleLinear().domain([0, maximum]), + nice: true, + grid: true, + axis: { + ticks: { + ...(maximum <= 1 ? { values: [0, 1] } : { count: 4 }), + format: (tick) => formatValue(Number(tick)), + }, + }, + }, + }, + margin: { left: 65, right: 15, top: 12, bottom: 30 }, + focus: 'nearest-x', + tooltip: { + use: tooltipExtension, + portal, + className: tooltipClassName, + content: (points) => { + const row = points[0]?.datum + const content = row ? tooltip(row) : null + return content + ? { title: content.title, rows: [...content.rows] } + : { rows: [] } + }, + }, + focusRing: { + fill: 'var(--theme-surface-raised)', + stroke: 'var(--color-brand-500)', + strokeWidth: 2, + }, + theme: { + foreground: 'var(--theme-ink-soft)', + muted: 'var(--theme-muted)', + grid: 'var(--theme-border)', + background: 'transparent', + }, + }) + }, [formatValue, id, locale, rows, time, tooltip, value]) +} diff --git a/web/src/shared/TimeSeriesChart/Types/time-series-chart.types.ts b/web/src/shared/TimeSeriesChart/Types/time-series-chart.types.ts new file mode 100644 index 000000000..ffa6e84ea --- /dev/null +++ b/web/src/shared/TimeSeriesChart/Types/time-series-chart.types.ts @@ -0,0 +1,31 @@ +import type { ChartDefinition } from '@tanstack/charts/react' + +export interface TimeSeriesTooltipRow { + readonly label: string + readonly value: string + readonly color?: string +} + +export interface TimeSeriesTooltip { + readonly title: string + readonly rows: readonly TimeSeriesTooltipRow[] +} + +/** How a series of rows becomes a line over time; the functions must be memoized by the caller. */ +export interface TimeSeriesChartOptions { + /** Names the line mark, unique within the page. */ + readonly id: string + readonly rows: readonly Row[] + readonly time: (row: Row) => Date + /** Null leaves a gap, such as a check without a response. */ + readonly value: (row: Row) => number | null + readonly formatValue: (value: number) => string + readonly tooltip: (row: Row) => TimeSeriesTooltip | null +} + +export interface TimeSeriesChartProps { + readonly title: string + readonly description: string + readonly height: number + readonly definition: ChartDefinition +} diff --git a/web/src/shared/TimeSeriesChart/index.tsx b/web/src/shared/TimeSeriesChart/index.tsx new file mode 100644 index 000000000..0cc0e21c5 --- /dev/null +++ b/web/src/shared/TimeSeriesChart/index.tsx @@ -0,0 +1,24 @@ +import { Chart } from '@tanstack/charts/react' + +import type { TimeSeriesChartProps } from './Types/time-series-chart.types.ts' + +/** A captioned time series chart; build its definition with `useTimeSeriesChartDefinition`. */ +export default function TimeSeriesChart({ + title, + description, + height, + definition, +}: TimeSeriesChartProps) { + return ( +
+
{title}
+ +
+ ) +} diff --git a/web/src/tests/features/AppUi/remote-app-data.test.tsx b/web/src/tests/features/AppUi/remote-app-data.test.tsx new file mode 100644 index 000000000..260bfce6a --- /dev/null +++ b/web/src/tests/features/AppUi/remote-app-data.test.tsx @@ -0,0 +1,290 @@ +// oxlint-disable no-await-in-loop -- Waits poll bounded UI transitions after serial React commits. +import { afterEach, expect, mock, test } from 'bun:test' +import { GlobalRegistrator } from '@happy-dom/global-registrator' +import type { ReactElement } from 'react' +import withTestLanguage from '@/tests/Helpers/withTestLanguage.tsx' + +if (!GlobalRegistrator.isRegistered) + GlobalRegistrator.register({ + url: 'https://platform.test/', + settings: { device: { prefersReducedMotion: 'reduce' } }, + }) +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + +const { act } = await import('react') +const { createRoot } = await import('react-dom/client') +const { createRemoteUiStore } = await import('@/lib/AppUi/remote-tree.ts') +const { default: RemoteAppView } = + await import('@/features/AppUi/Components/RemoteAppView/index.tsx') + +type Node = Record +const element = (id: string, name: string, extra: Node = {}): Node => ({ + id, + type: 1, + element: name, + children: [], + ...extra, +}) +const columns = [ + { id: 'name', header: 'Name', kind: 'text', sortable: true, filter: { type: 'text' } }, + { + id: 'status', + header: 'Status', + kind: 'badge', + filter: { + type: 'select', + options: [ + { value: 'Up', label: 'Up' }, + { value: 'Down', label: 'Down' }, + ], + }, + }, + { id: 'checked', header: 'Checked', kind: 'time', sortable: true }, + { id: 'duration', header: 'Duration', kind: 'measure' }, + { id: 'http', header: 'HTTP', kind: 'http-status' }, +] +const rows = Array.from({ length: 12 }, (_, index) => ({ + id: `r${index + 1}`, + cells: { + name: `check-${String(index + 1).padStart(2, '0')}`, + status: { + badge: { + tone: index === 0 ? 'negative' : 'positive', + label: index === 0 ? 'Down' : 'Up', + }, + }, + checked: { time: new Date(Date.UTC(2026, 10, 29, 12, index)).toISOString() }, + duration: { measure: { value: 1_250, unit: 'ms' } }, + http: { httpStatus: index === 0 ? 503 : 200 }, + }, +})) +const onEvent = mock(() => {}) + +let cleanup: (() => Promise) | undefined +afterEach(async () => { + await cleanup?.() + cleanup = undefined + onEvent.mockClear() + document.body.innerHTML = '' +}) + +async function render(node: ReactElement) { + const container = document.createElement('div') + document.body.append(container) + const root = createRoot(container) + await act(async () => root.render(withTestLanguage(node))) + cleanup = async () => act(async () => root.unmount()) + return container +} + +async function mount(tree: Node) { + const store = createRemoteUiStore() + const container = await render() + let accepted = false + await act(async () => { + accepted = store.apply([[0, '~', tree, 0]]) + }) + expect(accepted).toBe(true) + return { container, store } +} + +function bodyRows(container: HTMLElement) { + return [...container.querySelectorAll('tbody tr')] +} + +async function click(target: Element | null | undefined) { + if (!target) throw new Error('Nothing to click.') + await act(async () => { + target.dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }), + ) + await Promise.resolve() + }) +} + +async function waitFor(check: () => boolean) { + for (let attempt = 0; attempt < 40; attempt += 1) { + if (check()) return + await act(async () => { + await Bun.sleep(25) + }) + } + throw new Error('Condition never held.') +} + +test('draws a client table with platform cells, search, pages and row actions', async () => { + const { container } = await mount( + element('1', 'ui-data-table', { + properties: { + heading: 'Checks', + description: 'Recent checks of this host', + columns, + rows, + pageSize: 5, + searchable: true, + searchLabel: 'Search checks', + initialSort: { column: 'checked', desc: true }, + rowActions: [{ id: 'retry', label: 'Retry' }], + itemLabel: 'checks', + }, + eventListeners: { action: true }, + }), + ) + + expect(container.querySelector('section[aria-labelledby] h2')?.textContent).toBe('Checks') + expect(bodyRows(container)).toHaveLength(5) + // Newest first: the last row of the data leads the first page. + expect(bodyRows(container)[0]?.textContent).toContain('check-12') + expect(container.textContent).toContain('1,250 ms') + expect(container.querySelector('th:last-child')?.textContent).toContain('Actions') + + await click(container.querySelector('button[aria-label="Go to next page"]')) + await click(container.querySelector('button[aria-label="Go to last page"]')) + const last = bodyRows(container) + expect(last).toHaveLength(2) + expect(last.at(-1)?.textContent).toContain('Down') + expect(last.at(-1)?.textContent).toContain('503') + + await click(last.at(-1)?.querySelector('button[aria-label="Open actions"]')) + await waitFor(() => document.querySelector('[role="menuitem"]') !== null) + const retry = [...document.querySelectorAll('[role="menuitem"]')].find( + (item) => item.textContent?.trim() === 'Retry', + ) + await act(async () => { + for (const type of ['pointerdown', 'pointerup']) + retry?.dispatchEvent( + new PointerEvent(type, { bubbles: true, button: 0, pointerType: 'mouse' }), + ) + retry?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })) + await Promise.resolve() + }) + expect(onEvent).toHaveBeenLastCalledWith('1', 'action', { action: 'retry', row: 'r1' }) + + const search = container.querySelector('input[type="search"]') + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set + await act(async () => { + setter?.call(search, 'check-03') + search?.dispatchEvent(new Event('input', { bubbles: true })) + }) + await waitFor(() => bodyRows(container).length === 1) + expect(bodyRows(container)[0]?.textContent).toContain('check-03') +}) + +test('asks a remote app for other rows instead of paging the ones it has', async () => { + const { container, store } = await mount( + element('1', 'ui-data-table', { + properties: { + columns, + rows: rows.slice(0, 10), + mode: 'remote', + rowCount: 40, + pageSize: 10, + }, + eventListeners: { query: true }, + }), + ) + expect(bodyRows(container)).toHaveLength(10) + expect(container.querySelector('input[type="search"]')).toBeNull() + + await click(container.querySelector('button[aria-label="Go to next page"]')) + expect(onEvent).toHaveBeenLastCalledWith('1', 'query', { + search: '', + filters: [], + sort: null, + page: { index: 1, size: 10 }, + }) + + // The app answers with the second page; the platform shows it as it is. + await act(async () => { + store.apply([ + [ + 3, + '1', + 'rows', + rows.slice(10).map((row) => ({ id: `${row.id}-page2`, cells: row.cells })), + ], + ]) + }) + expect(bodyRows(container)).toHaveLength(2) + expect(container.textContent).toContain('11–20 of 40') +}) + +test('draws an app chart and status strip with the platform components', async () => { + const { container } = await mount( + element('1', 'ui-stack', { + children: [ + element('2', 'ui-time-series-chart', { + properties: { + label: 'Response time', + unit: 'ms', + height: 'sm', + points: rows.slice(0, 4).map((row, index) => ({ + id: row.id, + time: row.cells.checked.time, + value: index === 2 ? null : 100 + index * 50, + tone: index === 0 ? 'negative' : 'positive', + details: [{ label: 'HTTP', value: '200' }], + })), + }, + }), + element('3', 'ui-status-strip', { + properties: { + label: 'Recent checks', + slots: 5, + emptyLabel: 'Not checked yet', + items: rows.slice(0, 3).map((row, index) => ({ + id: row.id, + tone: index === 1 ? 'negative' : 'positive', + time: row.cells.checked.time, + label: index === 1 ? 'Down' : 'Up', + })), + }, + }), + ], + }), + ) + + expect(container.querySelector('figcaption')?.textContent).toBe('Response time') + expect(container.querySelector('svg')?.getAttribute('aria-label')).toBe('Response time') + + const strip = container.querySelector('ol[aria-label="Recent checks"]') + const slots = [...(strip?.querySelectorAll('li') ?? [])] + expect(slots).toHaveLength(5) + expect(slots.slice(0, 2).map((slot) => slot.textContent)).toEqual([ + 'Not checked yet', + 'Not checked yet', + ]) + const blocks = [...(strip?.querySelectorAll('button') ?? [])] + expect(blocks.map((block) => block.getAttribute('aria-label')?.split(' · ')[1])).toEqual([ + 'Up', + 'Down', + 'Up', + ]) + expect(blocks[1]?.className).toContain('bg-danger-text') +}) + +test('searches plain times as the localized dates the table shows', async () => { + const { container } = await mount( + element('1', 'ui-data-table', { + properties: { + columns: [{ id: 'checked', header: 'Checked', kind: 'time' }], + rows: [ + { id: 'october', cells: { checked: '2026-10-15T12:00:00.000Z' } }, + { id: 'november', cells: { checked: '2026-11-29T12:00:00.000Z' } }, + ], + searchable: true, + }, + }), + ) + expect(bodyRows(container)).toHaveLength(2) + const search = container.querySelector('input[type="search"]') + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set + await act(async () => { + setter?.call(search, 'Nov') + search?.dispatchEvent(new Event('input', { bubbles: true })) + }) + await waitFor(() => bodyRows(container).length === 1) + expect(bodyRows(container)[0]?.querySelector('time')?.getAttribute('dateTime')).toBe( + '2026-11-29T12:00:00.000Z', + ) +}) diff --git a/web/src/tests/features/AppUi/remote-app-view.test.tsx b/web/src/tests/features/AppUi/remote-app-view.test.tsx index c3b86cba1..64a709b50 100644 --- a/web/src/tests/features/AppUi/remote-app-view.test.tsx +++ b/web/src/tests/features/AppUi/remote-app-view.test.tsx @@ -154,8 +154,9 @@ test('draws the app tree with platform components and sends only the events it l expect(container.querySelector('[role="alert"]')?.textContent).toContain('Stale data') expect(container.querySelector('nav')?.getAttribute('aria-label')).toBe('Sections') expect(container.querySelector('[aria-current="page"]')?.textContent).toBe('Overview') - // Elements of a later slice draw an honest placeholder instead of nothing. - expect(container.textContent).toContain('cannot be shown on this platform version') + // A table without a heading or rows draws the platform table with its own empty state. + expect(container.querySelector('section[aria-labelledby] h2')?.textContent).toBe('Entries') + expect(container.textContent).toContain('Nothing here yet') await act(async () => button('Refresh')?.click()) expect(onEvent).toHaveBeenLastCalledWith('3', 'press', {})