@dudousxd/nestjs-catalog-react 0.4.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -92,6 +92,58 @@ export function parseRecords(text) {
92
92
  };
93
93
  }
94
94
  }
95
+ /** The url unless a connection supplies it, plus the sub-path off it if there is one. */
96
+ function httpConfig(draft, viaConnection) {
97
+ return {
98
+ ...(viaConnection ? {} : { url: draft.url }),
99
+ ...(draft.path ? { path: draft.path } : {}),
100
+ };
101
+ }
102
+ /** The query, the url unless a connection supplies it, and the watermark if it is in play. */
103
+ function sqlConfig(draft, viaConnection, incremental) {
104
+ return {
105
+ query: draft.query,
106
+ ...(viaConnection || !draft.url ? {} : { url: draft.url }),
107
+ // Only when it will be used. A watermark column left on a source somebody
108
+ // switched back to full reads as a bound that is being applied, and it is
109
+ // not.
110
+ ...(incremental && draft.watermarkColumn ? { watermarkColumn: draft.watermarkColumn } : {}),
111
+ };
112
+ }
113
+ /** A path on disk — `url` doubles as the path here — and the format if it was picked. */
114
+ function fileConfig(draft) {
115
+ return {
116
+ path: draft.path || draft.url,
117
+ ...(draft.format ? { format: draft.format } : {}),
118
+ };
119
+ }
120
+ /** Bucket and addressing, which a connection can supply, then the per-load narrowing. */
121
+ function s3Config(draft, viaConnection) {
122
+ return {
123
+ ...(viaConnection
124
+ ? {}
125
+ : {
126
+ bucket: draft.bucket,
127
+ ...(draft.endpoint ? { endpoint: draft.endpoint } : {}),
128
+ ...(draft.region ? { region: draft.region } : {}),
129
+ ...(draft.forcePathStyle ? { forcePathStyle: true } : {}),
130
+ }),
131
+ ...(draft.prefix ? { prefix: draft.prefix } : {}),
132
+ ...(draft.suffix ? { suffix: draft.suffix } : {}),
133
+ ...(draft.format ? { format: draft.format } : {}),
134
+ ...(draft.maxObjectsPerRun ? { maxObjectsPerRun: Number(draft.maxObjectsPerRun) } : {}),
135
+ };
136
+ }
137
+ /**
138
+ * The pasted records, or none when the text will not parse.
139
+ *
140
+ * Unparseable text keeps the previous records rather than wiping them: the
141
+ * caller shows the message from `parseRecords` and refuses to save.
142
+ */
143
+ function inlineConfig(draft) {
144
+ const parsed = parseRecords(draft.records);
145
+ return { records: parsed.ok ? parsed.records : [] };
146
+ }
95
147
  /**
96
148
  * The stored config for one kind, and nothing else.
97
149
  *
@@ -100,48 +152,15 @@ export function parseRecords(text) {
100
152
  * stale url on a SQL source, which reads as configuration somebody meant.
101
153
  */
102
154
  export function sourceConfigFrom(kind, draft, { viaConnection, incremental }) {
103
- if (kind === 'http') {
104
- return {
105
- ...(viaConnection ? {} : { url: draft.url }),
106
- ...(draft.path ? { path: draft.path } : {}),
107
- };
108
- }
109
- if (kind === 'sql') {
110
- return {
111
- query: draft.query,
112
- ...(viaConnection || !draft.url ? {} : { url: draft.url }),
113
- // Only when it will be used. A watermark column left on a source somebody
114
- // switched back to full reads as a bound that is being applied, and it is
115
- // not.
116
- ...(incremental && draft.watermarkColumn ? { watermarkColumn: draft.watermarkColumn } : {}),
117
- };
118
- }
119
- if (kind === 'file') {
120
- return {
121
- path: draft.path || draft.url,
122
- ...(draft.format ? { format: draft.format } : {}),
123
- };
124
- }
125
- if (kind === 's3') {
126
- return {
127
- ...(viaConnection
128
- ? {}
129
- : {
130
- bucket: draft.bucket,
131
- ...(draft.endpoint ? { endpoint: draft.endpoint } : {}),
132
- ...(draft.region ? { region: draft.region } : {}),
133
- ...(draft.forcePathStyle ? { forcePathStyle: true } : {}),
134
- }),
135
- ...(draft.prefix ? { prefix: draft.prefix } : {}),
136
- ...(draft.suffix ? { suffix: draft.suffix } : {}),
137
- ...(draft.format ? { format: draft.format } : {}),
138
- ...(draft.maxObjectsPerRun ? { maxObjectsPerRun: Number(draft.maxObjectsPerRun) } : {}),
139
- };
140
- }
141
- const parsed = parseRecords(draft.records);
142
- // Unparseable text keeps the previous records rather than wiping them: the
143
- // caller shows the message from `parseRecords` and refuses to save.
144
- return { records: parsed.ok ? parsed.records : [] };
155
+ if (kind === 'http')
156
+ return httpConfig(draft, viaConnection);
157
+ if (kind === 'sql')
158
+ return sqlConfig(draft, viaConnection, incremental);
159
+ if (kind === 'file')
160
+ return fileConfig(draft);
161
+ if (kind === 's3')
162
+ return s3Config(draft, viaConnection);
163
+ return inlineConfig(draft);
145
164
  }
146
165
  /**
147
166
  * Whether there is enough here to read anything at all.
package/dist/ui/chart.js CHANGED
@@ -53,6 +53,40 @@ ${colorConfig
53
53
  } }));
54
54
  };
55
55
  export const ChartTooltip = RechartsPrimitive.Tooltip;
56
+ /** The swatch to the left of a tooltip row — a dot, a bar, or a dashed rule. */
57
+ function ChartTooltipIndicator({ color, indicator, nestLabel, }) {
58
+ return (_jsx("div", { className: cn('shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)', {
59
+ 'h-2.5 w-2.5': indicator === 'dot',
60
+ 'w-1': indicator === 'line',
61
+ 'w-0 border-[1.5px] border-dashed bg-transparent': indicator === 'dashed',
62
+ 'my-0.5': nestLabel && indicator === 'dashed',
63
+ }), style: {
64
+ '--color-bg': color,
65
+ '--color-border': color,
66
+ } }));
67
+ }
68
+ /**
69
+ * The right-hand side of a tooltip row: the series name, then its value.
70
+ *
71
+ * When the tooltip holds a single non-dot series the shared label is nested in
72
+ * here instead of sitting above the rows, so it reads as part of the one entry
73
+ * rather than as a heading over a list of one.
74
+ */
75
+ function ChartTooltipNameAndValue({ name, value, nestLabel, tooltipLabel, }) {
76
+ return (_jsxs("div", { className: cn('flex flex-1 justify-between leading-none', nestLabel ? 'items-end' : 'items-center'), children: [_jsxs("div", { className: "grid gap-1.5", children: [nestLabel ? tooltipLabel : null, _jsx("span", { className: "text-zinc-500 dark:text-zinc-400", children: name })] }), value !== undefined && (_jsx("span", { className: "font-mono font-medium tabular-nums", children: typeof value === 'number' ? value.toLocaleString() : String(value) }))] }));
77
+ }
78
+ /**
79
+ * One series inside the tooltip: swatch, name, value.
80
+ *
81
+ * A caller's `formatter` replaces the whole row rather than any part of it,
82
+ * which is why it short-circuits everything below it.
83
+ */
84
+ function ChartTooltipRow({ item, index, config, color, formatter, indicator, hideIndicator, nestLabel, nameKey, tooltipLabel, }) {
85
+ const key = `${nameKey || item.name || item.dataKey || 'value'}`;
86
+ const itemConfig = getPayloadConfigFromPayload(config, item, key);
87
+ const indicatorColor = color || item.payload?.fill || item.color;
88
+ return (_jsx("div", { className: cn('flex w-full flex-wrap items-stretch gap-2', '[&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-zinc-400', indicator === 'dot' && 'items-center'), children: formatter && item?.value !== undefined && item.name ? (formatter(item.value, item.name, item, index, item.payload)) : (_jsxs(_Fragment, { children: [itemConfig?.icon ? (_jsx(itemConfig.icon, {})) : (!hideIndicator && (_jsx(ChartTooltipIndicator, { color: indicatorColor, indicator: indicator, nestLabel: nestLabel }))), _jsx(ChartTooltipNameAndValue, { name: itemConfig?.label || item.name, value: item.value, nestLabel: nestLabel, tooltipLabel: tooltipLabel })] })) }));
89
+ }
56
90
  export function ChartTooltipContent({ active, payload, className, indicator = 'dot', hideLabel = false, hideIndicator = false, label, labelFormatter, labelClassName, formatter, color, nameKey, labelKey, }) {
57
91
  const { config } = useChart();
58
92
  const tooltipLabel = React.useMemo(() => {
@@ -74,22 +108,7 @@ export function ChartTooltipContent({ active, payload, className, indicator = 'd
74
108
  if (!active || !payload?.length)
75
109
  return null;
76
110
  const nestLabel = payload.length === 1 && indicator !== 'dot';
77
- return (_jsxs("div", { className: cn('grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-zinc-200 bg-white px-2.5 py-1.5 text-xs shadow-xl', 'dark:border-zinc-800 dark:bg-zinc-900', className), children: [!nestLabel ? tooltipLabel : null, _jsx("div", { className: "grid gap-1.5", children: payload.map((item, index) => {
78
- const key = `${nameKey || item.name || item.dataKey || 'value'}`;
79
- const itemConfig = getPayloadConfigFromPayload(config, item, key);
80
- const indicatorColor = color || item.payload?.fill || item.color;
81
- return (_jsx("div", { className: cn('flex w-full flex-wrap items-stretch gap-2', '[&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-zinc-400', indicator === 'dot' && 'items-center'), children: formatter && item?.value !== undefined && item.name ? (formatter(item.value, item.name, item, index, item.payload)) : (_jsxs(_Fragment, { children: [itemConfig?.icon ? (_jsx(itemConfig.icon, {})) : (!hideIndicator && (_jsx("div", { className: cn('shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)', {
82
- 'h-2.5 w-2.5': indicator === 'dot',
83
- 'w-1': indicator === 'line',
84
- 'w-0 border-[1.5px] border-dashed bg-transparent': indicator === 'dashed',
85
- 'my-0.5': nestLabel && indicator === 'dashed',
86
- }), style: {
87
- '--color-bg': indicatorColor,
88
- '--color-border': indicatorColor,
89
- } }))), _jsxs("div", { className: cn('flex flex-1 justify-between leading-none', nestLabel ? 'items-end' : 'items-center'), children: [_jsxs("div", { className: "grid gap-1.5", children: [nestLabel ? tooltipLabel : null, _jsx("span", { className: "text-zinc-500 dark:text-zinc-400", children: itemConfig?.label || item.name })] }), item.value !== undefined && (_jsx("span", { className: "font-mono font-medium tabular-nums", children: typeof item.value === 'number'
90
- ? item.value.toLocaleString()
91
- : String(item.value) }))] })] })) }, item.dataKey ?? index));
92
- }) })] }));
111
+ return (_jsxs("div", { className: cn('grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-zinc-200 bg-white px-2.5 py-1.5 text-xs shadow-xl', 'dark:border-zinc-800 dark:bg-zinc-900', className), children: [!nestLabel ? tooltipLabel : null, _jsx("div", { className: "grid gap-1.5", children: payload.map((item, index) => (_jsx(ChartTooltipRow, { item: item, index: index, config: config, color: color, formatter: formatter, indicator: indicator, hideIndicator: hideIndicator, nestLabel: nestLabel, nameKey: nameKey, tooltipLabel: tooltipLabel }, item.dataKey ?? index))) })] }));
93
112
  }
94
113
  export const ChartLegend = RechartsPrimitive.Legend;
95
114
  export function ChartLegendContent({ className, hideIcon = false, payload, verticalAlign = 'bottom', nameKey, }) {
@@ -0,0 +1,17 @@
1
+ import type { KeyboardEvent, Ref } from 'react';
2
+ export interface CodeEditorProps {
3
+ value: string;
4
+ onChange: (next: string) => void;
5
+ /** Anything Prism knows: `sql`, `json`, `python`, `tsx`, … */
6
+ language: string;
7
+ /** Required. This is an input, and an unlabelled one is unusable by name. */
8
+ label: string;
9
+ onKeyDown?: (event: KeyboardEvent<HTMLTextAreaElement>) => void;
10
+ textareaRef?: Ref<HTMLTextAreaElement>;
11
+ /** Metrics differ by caller — the query box is roomier than a sample pane. */
12
+ className?: string;
13
+ padding?: string;
14
+ fontSize?: string;
15
+ readOnly?: boolean;
16
+ }
17
+ export declare function CodeEditor({ value, onChange, language, label, onKeyDown, textareaRef, className, padding, fontSize, readOnly, }: CodeEditorProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,81 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Highlight } from 'prism-react-renderer';
3
+ import { cn } from '../cn';
4
+ /**
5
+ * A code editor: a transparent `<textarea>` over a highlighted `<pre>`.
6
+ *
7
+ * Written out once here because it was written out twice — the query console
8
+ * and the transform editor each carried their own copy, with the same two boxes
9
+ * and the same three comments, and only one of them had been taught about JSON.
10
+ *
11
+ * Not CodeMirror, and that is a decision rather than an omission. A textarea is
12
+ * already the best plain-text input the platform has: it has the caret, the
13
+ * selection, undo, IME, autofill and every accessibility affordance for free,
14
+ * and a controlled editor built on a document model has to reimplement the lot
15
+ * — the classic symptom being a caret that jumps to the end whenever the value
16
+ * is updated from outside. What is missing here is autocomplete and bracket
17
+ * matching, which nothing in this console asks for.
18
+ */
19
+ /**
20
+ * The palette, from the console's own surface tokens.
21
+ *
22
+ * The previous copies both passed `themes.github`, which is a LIGHT theme — its
23
+ * plain text is near-black. That was invisible for as long as the console was
24
+ * light, and turned the SQL box into dark-on-dark the day the console became
25
+ * dark. So the theme is defined against the same variables the shell sets
26
+ * rather than picked from a list, and the two cannot drift again.
27
+ */
28
+ const CONSOLE_THEME = {
29
+ plain: { color: 'var(--text, #e7e7ea)', backgroundColor: 'transparent' },
30
+ styles: [
31
+ { types: ['comment', 'prolog', 'doctype', 'cdata'], style: { color: 'var(--muted, #76767f)' } },
32
+ { types: ['punctuation'], style: { color: 'var(--muted, #76767f)' } },
33
+ {
34
+ types: ['keyword', 'operator', 'rule', 'important', 'atrule'],
35
+ style: { color: 'var(--accent, #38bdf8)' },
36
+ },
37
+ { types: ['string', 'char', 'attr-value', 'regex'], style: { color: '#34d399' } },
38
+ { types: ['number', 'boolean', 'constant', 'symbol'], style: { color: '#fbbf24' } },
39
+ { types: ['function', 'class-name', 'builtin'], style: { color: '#a78bfa' } },
40
+ { types: ['variable', 'attr-name', 'property', 'tag'], style: { color: '#7dd3fc' } },
41
+ { types: ['deleted'], style: { color: '#f87171' } },
42
+ ],
43
+ };
44
+ export function CodeEditor({ value, onChange, language, label, onKeyDown, textareaRef, className, padding = 'p-3', fontSize = 'text-[12px]', readOnly, }) {
45
+ // Every property that affects where a glyph lands has to be identical on both
46
+ // layers, or the caret drifts from the text it is supposed to be inside — one
47
+ // character further off with every line.
48
+ //
49
+ // `leading` comes AFTER `fontSize` deliberately: tailwind-merge knows a
50
+ // `text-{size}` utility can carry a line-height, so a `leading-*` written
51
+ // before it is dropped as superseded — silently, and the browser default
52
+ // applies to both layers instead of 1.5.
53
+ const shared = cn('m-0 font-mono whitespace-pre-wrap break-words', padding, fontSize, 'leading-[1.5]');
54
+ return (
55
+ // Two boxes, and the division between them is the whole point.
56
+ //
57
+ // The outer one is the ONLY thing that scrolls. The inner one has no height
58
+ // of its own, so it grows to whatever the highlighted code needs — which is
59
+ // what lets the textarea be `inset-0` and still cover every line rather than
60
+ // only the visible ones. When both scrolled, a long query produced two
61
+ // scrollbars and scrolling the outer one left the caret over the wrong line,
62
+ // because the highlight moved and the input did not.
63
+ _jsx("div", { className: cn('relative overflow-auto', className), children: _jsxs("div", { className: "relative min-h-full w-full", children: [_jsx(Highlight, { code: value, language: language, theme: CONSOLE_THEME, children: ({ style, tokens, getLineProps, getTokenProps }) => (
64
+ // `style` carries the theme's `plain`, which is what anything Prism
65
+ // did NOT tokenise falls back to. Dropping it leaves that text
66
+ // inheriting from whatever is above, which happens to be right on
67
+ // this console and would not be on another.
68
+ _jsx("pre", { style: style, className: cn(shared, 'pointer-events-none min-h-full'), "aria-hidden": true, children: tokens.map((line, i) => (
69
+ // biome-ignore lint/suspicious/noArrayIndexKey: lines have no id
70
+ _jsx("div", { ...getLineProps({ line }), children: line.map((token, key) => (
71
+ // biome-ignore lint/suspicious/noArrayIndexKey: tokens have no id
72
+ _jsx("span", { ...getTokenProps({ token }) }, key))) }, i))) })) }), _jsx("textarea", { ref: textareaRef, value: value, onChange: (event) => onChange(event.target.value), onKeyDown: onKeyDown, spellCheck: false, readOnly: readOnly, "aria-label": label, className: cn(shared,
73
+ // `overflow-hidden`, not `auto`: this layer is as tall as the code
74
+ // it holds, so it has nothing to scroll — and giving it the option
75
+ // back is what produced the second scrollbar.
76
+ 'absolute inset-0 h-full w-full resize-none overflow-hidden bg-transparent',
77
+ // Transparent text over the highlighted copy, but a VISIBLE caret
78
+ // and a visible selection — those are the two things the `<pre>`
79
+ // underneath cannot draw.
80
+ 'text-transparent caret-zinc-900 outline-none dark:caret-zinc-100', 'selection:bg-sky-500/30 selection:text-transparent') })] }) }));
81
+ }
@@ -0,0 +1,92 @@
1
+ import { type RowData, type TableOptions } from '@tanstack/react-table';
2
+ import { type ReactNode } from 'react';
3
+ /**
4
+ * The console's data tables, on TanStack Table v9.
5
+ *
6
+ * Four screens hand-rolled `<table>` markup with the same header row, the same
7
+ * hairlines and the same "numbers go right" rule, each slightly differently.
8
+ * What TanStack owns here is the column model, the header groups and the cell
9
+ * rendering; what it deliberately does NOT own is where the data comes from.
10
+ *
11
+ * **Sorting is a prop, not a row model.** The object explorer sorts, pages and
12
+ * searches on the SERVER — it has to, because it is reading a warehouse table
13
+ * that does not fit in a browser. Handing those columns to
14
+ * `createSortedRowModel` would sort the fifty rows currently on screen and
15
+ * present the result as if it were the whole answer, which is a worse bug than
16
+ * no sorting at all: it looks right. So this component renders the sort
17
+ * affordance and reports clicks, and the caller decides whether that means a
18
+ * refetch or a client-side reorder.
19
+ */
20
+ /** What a header needs to know to draw and drive a sort indicator. */
21
+ export interface DataTableSort {
22
+ /** Column id currently sorted, or null. */
23
+ by: string | null;
24
+ dir: 'asc' | 'desc';
25
+ /** Called with the column id. The caller decides what sorting means. */
26
+ onSort: (columnId: string) => void;
27
+ /** Column ids that can be sorted. Absent means all of them. */
28
+ sortable?: (columnId: string) => boolean;
29
+ }
30
+ export interface DataTableProps<TData extends RowData> {
31
+ data: TData[];
32
+ /**
33
+ * Typed as exactly what `useTable` accepts for THIS feature set, rather than
34
+ * as a hand-written `ColumnDef<...>`. A literal type here widens `TFeatures`
35
+ * to the full `TableFeatures` union at the call below and stops assigning —
36
+ * v9's column type is parameterised by the features in play, which is the
37
+ * whole point of opting into them.
38
+ */
39
+ columns: TableOptions<DataTableFeatures, TData>['columns'];
40
+ /** Stable per row. Falls back to the index, which is right for a SQL result. */
41
+ getRowId?: (row: TData, index: number) => string;
42
+ sort?: DataTableSort;
43
+ /** Rendered instead of the body when there are no rows. */
44
+ empty?: ReactNode;
45
+ /** Right-aligns and tabular-nums a column — numbers read down a column badly otherwise. */
46
+ numeric?: (columnId: string) => boolean;
47
+ className?: string;
48
+ /** `text-sm` for a full screen, `text-[11px]` for a card preview. */
49
+ density?: string;
50
+ /**
51
+ * Per-row classes — a hidden property is dimmed rather than removed, so the
52
+ * screen can say "this exists and is not shown" instead of just not saying.
53
+ */
54
+ rowClassName?: (row: TData) => string | undefined;
55
+ /**
56
+ * Per-column classes. Column WIDTH lives here rather than being derived,
57
+ * because a table of editable fields needs the columns to hold still while
58
+ * you type in them — content-sized columns reflow on every keystroke.
59
+ */
60
+ columnClassName?: (columnId: string) => string | undefined;
61
+ /** Cells, when a column needs `align-top` for multi-line editors. */
62
+ cellClassName?: (columnId: string) => string | undefined;
63
+ }
64
+ /**
65
+ * The v9 feature set, listed once.
66
+ *
67
+ * v9 is opt-in per feature rather than v8's batteries-included table, which is
68
+ * the point of the rewrite — a table that never groups should not ship the
69
+ * grouping code. Everything here is core: this component renders rows and
70
+ * columns and leaves sorting, filtering and pagination to whoever owns the data.
71
+ */
72
+ declare function featureSet(): {
73
+ coreCellsFeature: import("@tanstack/react-table").TableFeature;
74
+ coreColumnsFeature: import("@tanstack/react-table").TableFeature;
75
+ coreHeadersFeature: import("@tanstack/react-table").TableFeature;
76
+ coreRowModelsFeature: import("@tanstack/react-table").TableFeature;
77
+ coreRowsFeature: import("@tanstack/react-table").TableFeature;
78
+ coreTablesFeature: import("@tanstack/react-table").TableFeature;
79
+ coreRowModel: (table: import("@tanstack/react-table").Table<import("@tanstack/react-table").TableFeatures, RowData>) => () => import("@tanstack/react-table").RowModel<import("@tanstack/react-table").TableFeatures, RowData>;
80
+ };
81
+ export type DataTableFeatures = ReturnType<typeof featureSet>;
82
+ export declare function DataTable<TData extends RowData>({ data, columns, getRowId, sort, empty, numeric, className, density, rowClassName, columnClassName, cellClassName, }: DataTableProps<TData>): import("react/jsx-runtime").JSX.Element;
83
+ /**
84
+ * A value from an arbitrary query, as a cell.
85
+ *
86
+ * Exported because two screens render untyped rows and both had their own copy
87
+ * of this ladder — and the interesting case is the one people skip: `null` and
88
+ * `undefined` must render as a visible mark rather than as an empty cell, or
89
+ * "no value" and "a value that happens to be blank" look identical.
90
+ */
91
+ export declare function renderUnknown(value: unknown): ReactNode;
92
+ export {};
@@ -0,0 +1,101 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { coreCellsFeature, coreColumnsFeature, coreHeadersFeature, coreRowModelsFeature, coreRowsFeature, coreTablesFeature, createCoreRowModel, flexRender, useTable, } from '@tanstack/react-table';
3
+ import { ArrowDown, ArrowUp, ChevronsUpDown } from 'lucide-react';
4
+ import { useMemo } from 'react';
5
+ import { cn } from '../cn';
6
+ /**
7
+ * The v9 feature set, listed once.
8
+ *
9
+ * v9 is opt-in per feature rather than v8's batteries-included table, which is
10
+ * the point of the rewrite — a table that never groups should not ship the
11
+ * grouping code. Everything here is core: this component renders rows and
12
+ * columns and leaves sorting, filtering and pagination to whoever owns the data.
13
+ */
14
+ function featureSet() {
15
+ return {
16
+ coreCellsFeature,
17
+ coreColumnsFeature,
18
+ coreHeadersFeature,
19
+ coreRowModelsFeature,
20
+ coreRowsFeature,
21
+ coreTablesFeature,
22
+ // Built here rather than at module scope, and per table rather than once:
23
+ // a row model factory carries a cache, and one shared across every table on
24
+ // the screen is a cache keyed by nothing.
25
+ coreRowModel: createCoreRowModel(),
26
+ };
27
+ }
28
+ const RULE = 'border-zinc-200 dark:border-zinc-800';
29
+ const MUTED = 'text-zinc-400 dark:text-zinc-500';
30
+ export function DataTable({ data, columns, getRowId, sort, empty, numeric, className, density = 'text-sm', rowClassName, columnClassName, cellClassName, }) {
31
+ // Explicit type arguments rather than inference: `columns` and `data` are
32
+ // two inference sites for the same pair, and with a third parameter
33
+ // (`TFeatures`) in play TS gives up and falls back to the constraints —
34
+ // `TableFeatures`/`RowData` — which then refuse the narrower columns.
35
+ const features = useMemo(featureSet, []);
36
+ const table = useTable({
37
+ // The row model factories live INSIDE `features`, not in a sibling option.
38
+ // v9 folded them in so a feature and the row model it needs are registered
39
+ // together; a separate `rowModels` option does not typecheck and would be
40
+ // ignored at runtime.
41
+ features,
42
+ data,
43
+ columns,
44
+ ...(getRowId ? { getRowId } : {}),
45
+ });
46
+ const rows = table.getRowModel().rows;
47
+ if (rows.length === 0 && empty)
48
+ return _jsx(_Fragment, { children: empty });
49
+ return (_jsx("div", { className: cn('overflow-x-auto', className), children: _jsxs("table", { className: cn('w-full min-w-max', density), children: [_jsx("thead", { children: table.getHeaderGroups().map((group) => (_jsx("tr", { className: cn('border-b bg-zinc-50 dark:bg-zinc-950', RULE), children: group.headers.map((header) => (_jsx(HeaderCell, { id: header.column.id, label: flexRender(header.column.columnDef.header, header.getContext()), sort: sort, isNumeric: numeric?.(header.column.id) ?? false, className: columnClassName?.(header.column.id) }, header.id))) }, group.id))) }), _jsx("tbody", { children: rows.map((row) => (_jsx("tr", { className: cn('border-b border-zinc-100 last:border-0 dark:border-zinc-900', rowClassName?.(row.original)), children: row.getAllCells().map((cell) => (_jsx("td", { className: cn('whitespace-nowrap px-3 py-1.5', cellClassName?.(cell.column.id),
50
+ // `tabular-nums` so digits line up down the column; without
51
+ // it a proportional font makes 1,111 narrower than 8,888 and
52
+ // the eye cannot compare magnitudes at a glance.
53
+ (numeric?.(cell.column.id) ?? false) && 'text-right font-mono tabular-nums'), children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id))) }, row.id))) })] }) }));
54
+ }
55
+ /**
56
+ * Three states, not two.
57
+ *
58
+ * A sortable column that is not currently sorted shows a neutral glyph on hover
59
+ * rather than nothing: a header that looks inert until you click it is one
60
+ * people do not think to click.
61
+ */
62
+ function SortIcon({ active, dir }) {
63
+ if (!active) {
64
+ return _jsx(ChevronsUpDown, { size: 11, className: cn('opacity-0 group-hover:opacity-100', MUTED) });
65
+ }
66
+ return dir === 'asc' ? _jsx(ArrowUp, { size: 11 }) : _jsx(ArrowDown, { size: 11 });
67
+ }
68
+ /**
69
+ * A value from an arbitrary query, as a cell.
70
+ *
71
+ * Exported because two screens render untyped rows and both had their own copy
72
+ * of this ladder — and the interesting case is the one people skip: `null` and
73
+ * `undefined` must render as a visible mark rather than as an empty cell, or
74
+ * "no value" and "a value that happens to be blank" look identical.
75
+ */
76
+ export function renderUnknown(value) {
77
+ if (value === null || value === undefined) {
78
+ return _jsx("span", { className: MUTED, children: "\u2014" });
79
+ }
80
+ if (typeof value === 'object')
81
+ return JSON.stringify(value);
82
+ return String(value);
83
+ }
84
+ /**
85
+ * One column header, sortable or not.
86
+ *
87
+ * Its own component because the two shapes barely overlap: a sortable header is
88
+ * a button carrying the label and an indicator, and a plain one is a mono
89
+ * caption. Inlined, the branch pushed `DataTable` past the complexity the lint
90
+ * allows — which was a fair reading, not a technicality.
91
+ */
92
+ function HeaderCell({ id, label, sort, isNumeric, className, }) {
93
+ const canSort = sort ? (sort.sortable?.(id) ?? true) : false;
94
+ const active = sort?.by === id;
95
+ return (_jsx("th", { ...(canSort && active && sort
96
+ ? { 'aria-sort': sort.dir === 'asc' ? 'ascending' : 'descending' }
97
+ : {}), className: cn('whitespace-nowrap px-3 py-2 text-left font-normal', isNumeric && 'text-right', className), children: canSort && sort ? (_jsxs("button", { type: "button", onClick: () => sort.onSort(id),
98
+ // The arrow follows the text to the edge it is aligned to, rather
99
+ // than sitting between the label and the numbers it describes.
100
+ className: cn('group inline-flex items-center gap-1', isNumeric && 'flex-row-reverse'), children: [_jsx("span", { className: cn('text-xs', active ? 'text-zinc-950 dark:text-zinc-50' : 'text-zinc-500 dark:text-zinc-400'), children: label }), _jsx(SortIcon, { active: active, dir: sort.dir })] })) : (_jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.12em]', MUTED), children: label })) }));
101
+ }
@@ -0,0 +1,21 @@
1
+ import { type MarkdownStorage } from 'tiptap-markdown';
2
+ declare module '@tiptap/core' {
3
+ interface Storage {
4
+ markdown: MarkdownStorage;
5
+ }
6
+ }
7
+ export interface RichTextFieldProps {
8
+ /** Markdown. Empty string means "nothing written yet". */
9
+ value: string;
10
+ onSave: (markdown: string) => void;
11
+ /** Announced to assistive tech — this control has no visible label. */
12
+ label: string;
13
+ placeholder?: string;
14
+ className?: string;
15
+ }
16
+ export declare function RichTextField({ value, onSave, label, placeholder, className, }: RichTextFieldProps): import("react/jsx-runtime").JSX.Element;
17
+ /** Read-only, through the same editor, so one parser decides what the text means. */
18
+ export declare function RichTextView({ value, className }: {
19
+ value: string;
20
+ className?: string;
21
+ }): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,133 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { EditorContent, useEditor } from '@tiptap/react';
3
+ import StarterKit from '@tiptap/starter-kit';
4
+ import { Bold, Check, Code, Italic, List, ListOrdered, X } from 'lucide-react';
5
+ import { useEffect, useState } from 'react';
6
+ import { Markdown } from 'tiptap-markdown';
7
+ import { cn } from '../cn';
8
+ import { Button } from './button';
9
+ /**
10
+ * A curated description, edited as rich text and stored as **markdown**.
11
+ *
12
+ * Markdown rather than HTML, and the reason is what happens to everyone who is
13
+ * NOT this editor. `description` is served raw in the `/catalog` snapshot to
14
+ * whatever a host built on top of it, and those consumers were written against
15
+ * plain text. Markdown degrades into something a person can still read —
16
+ * `**bold**` — while HTML degrades into `<strong>bold</strong>`, which is
17
+ * noise, and creates an XSS surface in every consumer that decides to render it
18
+ * after all. One of those failures is cosmetic and the other is a
19
+ * vulnerability.
20
+ *
21
+ * The read view is the same editor with `editable: false` rather than a second
22
+ * markdown renderer. Two parsers for one format is two answers to "what does
23
+ * this text mean", and they diverge on exactly the inputs nobody tests.
24
+ */
25
+ /** Kept out of the toolbar deliberately — see the docblock on {@link RichTextField}. */
26
+ const EXTENSIONS = [
27
+ StarterKit.configure({
28
+ // No headings inside a field that renders in a table cell and a tooltip:
29
+ // an `<h1>` in a 20%-wide column is a line of enormous text, and the
30
+ // affordance would be there purely because the library offers it.
31
+ heading: false,
32
+ // Nor images or horizontal rules, for the same reason.
33
+ horizontalRule: false,
34
+ }),
35
+ Markdown.configure({
36
+ // Round-trip fidelity over prettiness: this text is read by other programs.
37
+ linkify: false,
38
+ breaks: false,
39
+ transformPastedText: true,
40
+ }),
41
+ ];
42
+ /**
43
+ * What the rendered markdown looks like, as utilities rather than as a class
44
+ * the host has to define.
45
+ *
46
+ * A component library that references a `prose-…` class it does not ship is a
47
+ * component library that renders unstyled in somebody else's app — bold text
48
+ * that is not bold, list items with no bullets — and nothing errors, so it
49
+ * reads as a broken component. Arbitrary variants keep the styling inside the
50
+ * class strings Tailwind already scans in `dist`.
51
+ *
52
+ * Deliberately small. These are one-paragraph descriptions in a table cell, not
53
+ * documents.
54
+ */
55
+ const PROSE = cn('[&_p]:my-0 [&_p+p]:mt-2', '[&_strong]:font-semibold', '[&_em]:italic', '[&_code]:rounded [&_code]:bg-zinc-100 [&_code]:px-1 [&_code]:font-mono [&_code]:text-[0.9em]', 'dark:[&_code]:bg-zinc-800', '[&_ul]:my-1 [&_ul]:list-disc [&_ul]:pl-4', '[&_ol]:my-1 [&_ol]:list-decimal [&_ol]:pl-4', '[&_li]:my-0.5');
56
+ export function RichTextField({ value, onSave, label, placeholder = '—', className, }) {
57
+ const [editing, setEditing] = useState(false);
58
+ if (!editing) {
59
+ return (_jsx("button", { type: "button", onClick: () => setEditing(true), "aria-label": `Edit ${label}`, className: cn('w-full rounded-sm px-1.5 py-0.5 text-left', 'hover:bg-zinc-100 dark:hover:bg-zinc-800', className), children: value ? (_jsx(RichTextView, { value: value })) : (_jsx("span", { className: "text-zinc-400 dark:text-zinc-500", children: placeholder })) }));
60
+ }
61
+ return (_jsx(RichTextEditor, { value: value, label: label, className: className, onCancel: () => setEditing(false), onSave: (markdown) => {
62
+ setEditing(false);
63
+ // Only when it actually changed. A save on every blur turns "I clicked
64
+ // into this field and clicked out" into a write, an audit entry, and a
65
+ // publisher's overlay that now shadows the declared description with an
66
+ // identical string.
67
+ if (markdown !== value)
68
+ onSave(markdown);
69
+ } }));
70
+ }
71
+ /** Read-only, through the same editor, so one parser decides what the text means. */
72
+ export function RichTextView({ value, className }) {
73
+ const editor = useEditor({
74
+ extensions: EXTENSIONS,
75
+ content: value,
76
+ editable: false,
77
+ immediatelyRender: false,
78
+ editorProps: { attributes: { class: cn(PROSE, className) } },
79
+ }, [value]);
80
+ return _jsx(EditorContent, { editor: editor });
81
+ }
82
+ function RichTextEditor({ value, label, className, onSave, onCancel, }) {
83
+ const editor = useEditor({
84
+ extensions: EXTENSIONS,
85
+ content: value,
86
+ // `false` because this renders inside an already-mounted client tree; left
87
+ // on, TipTap renders once during the first paint and React reports a
88
+ // hydration mismatch on any host that server-renders the console shell.
89
+ immediatelyRender: false,
90
+ editorProps: {
91
+ attributes: {
92
+ 'aria-label': label,
93
+ class: cn(PROSE, 'min-h-[3lh] rounded-sm border border-sky-500 px-1.5 py-0.5 outline-none', 'ring-2 ring-sky-500/20', className),
94
+ },
95
+ },
96
+ });
97
+ // Focus on open, so opening the editor and typing is one motion rather than
98
+ // two — the plain-text field it replaces did the same.
99
+ useEffect(() => {
100
+ editor?.commands.focus('end');
101
+ }, [editor]);
102
+ if (!editor)
103
+ return null;
104
+ const markdown = () => editor.storage.markdown.getMarkdown();
105
+ return (_jsxs("div", { onKeyDown: (event) => {
106
+ // Escape abandons, Cmd/Ctrl+Enter commits. Plain Enter is a paragraph
107
+ // break here — this is a rich text field, and stealing Enter would make
108
+ // multi-paragraph descriptions impossible to write.
109
+ if (event.key === 'Escape')
110
+ onCancel();
111
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey))
112
+ onSave(markdown());
113
+ }, children: [_jsx(Toolbar, { editor: editor }), _jsx(EditorContent, { editor: editor }), _jsxs("div", { className: "mt-1 flex items-center gap-1", children: [_jsxs(Button, { size: "sm", onClick: () => onSave(markdown()), "aria-label": `Save ${label}`, children: [_jsx(Check, { size: 12 }), " Save"] }), _jsx(Button, { size: "sm", variant: "ghost", onClick: onCancel, "aria-label": `Cancel editing ${label}`, children: _jsx(X, { size: 12 }) }), _jsx("span", { className: "ml-auto font-mono text-[10px] text-zinc-400 dark:text-zinc-500", children: "Stored as markdown" })] })] }));
114
+ }
115
+ /** Editor type is inferred; naming it would pin this file to a TipTap minor. */
116
+ function Toolbar({ editor }) {
117
+ const marks = [
118
+ { name: 'bold', icon: Bold, run: () => editor.chain().focus().toggleBold().run() },
119
+ { name: 'italic', icon: Italic, run: () => editor.chain().focus().toggleItalic().run() },
120
+ { name: 'code', icon: Code, run: () => editor.chain().focus().toggleCode().run() },
121
+ {
122
+ name: 'bulletList',
123
+ icon: List,
124
+ run: () => editor.chain().focus().toggleBulletList().run(),
125
+ },
126
+ {
127
+ name: 'orderedList',
128
+ icon: ListOrdered,
129
+ run: () => editor.chain().focus().toggleOrderedList().run(),
130
+ },
131
+ ];
132
+ return (_jsx("div", { className: "mb-1 flex items-center gap-0.5", children: marks.map(({ name, icon: Icon, run }) => (_jsx(Button, { size: "icon", variant: "ghost", onClick: run, "aria-label": name, "aria-pressed": editor.isActive(name), className: cn(editor.isActive(name) && 'bg-zinc-200 dark:bg-zinc-700'), children: _jsx(Icon, { size: 12 }) }, name))) }));
133
+ }