@schemacast/react 0.0.0-stage → 0.5.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.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +37 -2
  3. package/dist/auto-visual.d.ts +32 -0
  4. package/dist/auto-visual.js +27 -0
  5. package/dist/field-by-key.d.ts +3 -0
  6. package/dist/field-by-key.js +7 -0
  7. package/dist/format-field-value.d.ts +16 -0
  8. package/dist/format-field-value.js +84 -0
  9. package/dist/implemented-archetypes.d.ts +2 -0
  10. package/dist/implemented-archetypes.js +17 -0
  11. package/dist/index.d.ts +12 -0
  12. package/dist/index.js +10 -0
  13. package/dist/use-selected-view-id.d.ts +6 -0
  14. package/dist/use-selected-view-id.js +17 -0
  15. package/dist/view-switcher.d.ts +26 -0
  16. package/dist/view-switcher.js +63 -0
  17. package/dist/views/archetype-view.d.ts +16 -0
  18. package/dist/views/archetype-view.js +71 -0
  19. package/dist/views/bar-chart-options.d.ts +22 -0
  20. package/dist/views/bar-chart-options.js +103 -0
  21. package/dist/views/bar-chart-view.d.ts +17 -0
  22. package/dist/views/bar-chart-view.js +25 -0
  23. package/dist/views/build-hierarchy-tree-data.d.ts +8 -0
  24. package/dist/views/build-hierarchy-tree-data.js +32 -0
  25. package/dist/views/build-node-graph-data.d.ts +20 -0
  26. package/dist/views/build-node-graph-data.js +44 -0
  27. package/dist/views/chart-series-data.d.ts +61 -0
  28. package/dist/views/chart-series-data.js +150 -0
  29. package/dist/views/chart-value-axes.d.ts +45 -0
  30. package/dist/views/chart-value-axes.js +214 -0
  31. package/dist/views/data-table-constants.d.ts +3 -0
  32. package/dist/views/data-table-constants.js +3 -0
  33. package/dist/views/data-table-rows.d.ts +8 -0
  34. package/dist/views/data-table-rows.js +50 -0
  35. package/dist/views/data-table-view.d.ts +16 -0
  36. package/dist/views/data-table-view.js +76 -0
  37. package/dist/views/detail-card-view.d.ts +16 -0
  38. package/dist/views/detail-card-view.js +59 -0
  39. package/dist/views/edge-weight-width.d.ts +23 -0
  40. package/dist/views/edge-weight-width.js +47 -0
  41. package/dist/views/hierarchy-tree-view.d.ts +16 -0
  42. package/dist/views/hierarchy-tree-view.js +58 -0
  43. package/dist/views/json-tree-view.d.ts +15 -0
  44. package/dist/views/json-tree-view.js +115 -0
  45. package/dist/views/kanban-view.d.ts +16 -0
  46. package/dist/views/kanban-view.js +41 -0
  47. package/dist/views/kpi-grid-view.d.ts +16 -0
  48. package/dist/views/kpi-grid-view.js +34 -0
  49. package/dist/views/line-chart-options.d.ts +16 -0
  50. package/dist/views/line-chart-options.js +98 -0
  51. package/dist/views/line-chart-view.d.ts +16 -0
  52. package/dist/views/line-chart-view.js +31 -0
  53. package/dist/views/node-graph-options.d.ts +26 -0
  54. package/dist/views/node-graph-options.js +111 -0
  55. package/dist/views/node-graph-view.d.ts +16 -0
  56. package/dist/views/node-graph-view.js +28 -0
  57. package/dist/views/pie-chart-view.d.ts +16 -0
  58. package/dist/views/pie-chart-view.js +56 -0
  59. package/dist/views/timeline-view.d.ts +16 -0
  60. package/dist/views/timeline-view.js +86 -0
  61. package/dist/views/use-echarts.d.ts +4 -0
  62. package/dist/views/use-echarts.js +233 -0
  63. package/dist/visual-spec-view.d.ts +28 -0
  64. package/dist/visual-spec-view.js +31 -0
  65. package/package.json +56 -3
  66. package/styles.css +688 -0
@@ -0,0 +1,8 @@
1
+ import type { FieldBindings } from '@schemacast/core';
2
+ export interface HierarchyTreeNode {
3
+ readonly name: string;
4
+ readonly children?: HierarchyTreeNode[];
5
+ }
6
+ export declare function buildHierarchyTreeData(root: Record<string, unknown> | undefined, bindings: FieldBindings): HierarchyTreeNode | null;
7
+ export declare function collectHierarchyNames(node: HierarchyTreeNode): string[];
8
+ //# sourceMappingURL=build-hierarchy-tree-data.d.ts.map
@@ -0,0 +1,32 @@
1
+ export function buildHierarchyTreeData(root, bindings) {
2
+ if (root === undefined) {
3
+ return null;
4
+ }
5
+ const titleKey = bindings.title ?? 'name';
6
+ const childrenKey = bindings.groupBy ?? 'children';
7
+ return mapTreeNode(root, titleKey, childrenKey);
8
+ }
9
+ function mapTreeNode(row, titleKey, childrenKey) {
10
+ const node = { name: String(row[titleKey] ?? '') };
11
+ const children = row[childrenKey];
12
+ if (!Array.isArray(children)) {
13
+ return node;
14
+ }
15
+ const mapped = children
16
+ .filter((child) => typeof child === 'object' && child !== null && !Array.isArray(child))
17
+ .map((child) => mapTreeNode(child, titleKey, childrenKey));
18
+ if (mapped.length > 0) {
19
+ return { ...node, children: mapped };
20
+ }
21
+ return node;
22
+ }
23
+ export function collectHierarchyNames(node) {
24
+ const names = [node.name];
25
+ if (node.children !== undefined) {
26
+ for (const child of node.children) {
27
+ names.push(...collectHierarchyNames(child));
28
+ }
29
+ }
30
+ return names;
31
+ }
32
+ //# sourceMappingURL=build-hierarchy-tree-data.js.map
@@ -0,0 +1,20 @@
1
+ import type { FieldBindings, VisualSpec } from '@schemacast/core';
2
+ export interface GraphNodeDatum {
3
+ readonly id: string;
4
+ readonly name: string;
5
+ readonly category?: string;
6
+ }
7
+ export interface GraphLinkDatum {
8
+ readonly source: string;
9
+ readonly target: string;
10
+ readonly label?: string;
11
+ /** Numeric weight from the `edgeWeight` binding; absent when the edge has none */
12
+ readonly weight?: number;
13
+ /** Line width in pixels, set on every link when the graph has an `edgeWeight` binding */
14
+ readonly width?: number;
15
+ }
16
+ export declare function buildNodeGraphData(spec: VisualSpec, bindings: FieldBindings): {
17
+ readonly nodes: GraphNodeDatum[];
18
+ readonly links: GraphLinkDatum[];
19
+ };
20
+ //# sourceMappingURL=build-node-graph-data.d.ts.map
@@ -0,0 +1,44 @@
1
+ import { readEdgeWeight, scaleEdgeWidths } from './edge-weight-width.js';
2
+ export function buildNodeGraphData(spec, bindings) {
3
+ const nodeIdKey = bindings.nodeId ?? 'id';
4
+ const titleKey = bindings.title;
5
+ const sourceKey = bindings.edgeSource ?? 'source';
6
+ const targetKey = bindings.edgeTarget ?? 'target';
7
+ const categoryKey = bindings.color;
8
+ const nodes = spec.data.map((row) => {
9
+ const id = String(row[nodeIdKey] ?? '');
10
+ const name = titleKey !== undefined ? String(row[titleKey] ?? id) : id;
11
+ if (categoryKey === undefined) {
12
+ return { id, name };
13
+ }
14
+ return { id, name, category: formatNodeCategory(row[categoryKey]) };
15
+ });
16
+ const edges = spec.edges ?? [];
17
+ const weightKey = bindings.edgeWeight;
18
+ const weights = edges.map((edge) => weightKey === undefined ? undefined : readEdgeWeight(edge[weightKey]));
19
+ const widths = weightKey === undefined ? undefined : scaleEdgeWidths(weights);
20
+ const links = edges.map((edge, index) => {
21
+ const source = String(edge[sourceKey] ?? '');
22
+ const target = String(edge[targetKey] ?? '');
23
+ const weight = weights[index];
24
+ const width = widths?.[index];
25
+ return {
26
+ source,
27
+ target,
28
+ ...(edge['label'] === undefined ? {} : { label: String(edge['label']) }),
29
+ ...(weight === undefined ? {} : { weight }),
30
+ ...(width === undefined ? {} : { width }),
31
+ };
32
+ });
33
+ return { nodes, links };
34
+ }
35
+ function formatNodeCategory(value) {
36
+ if (typeof value === 'string' && value.trim() !== '') {
37
+ return value;
38
+ }
39
+ if (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) {
40
+ return String(value);
41
+ }
42
+ return 'Uncategorized';
43
+ }
44
+ //# sourceMappingURL=build-node-graph-data.js.map
@@ -0,0 +1,61 @@
1
+ import { type FieldDescriptor, type SemanticType } from '@schemacast/core';
2
+ import type { LegendComponentOption, XAXisComponentOption } from 'echarts';
3
+ /**
4
+ * Rotate category ticks when `(label count) × (longest truncated label length)` exceeds this
5
+ * budget. Below the budget, labels stay upright (`rotate: 0`) with `hideOverlap: true`.
6
+ */
7
+ export declare const CATEGORY_AXIS_ROTATE_DENSITY_BUDGET = 24;
8
+ /** Degrees used when {@link CATEGORY_AXIS_ROTATE_DENSITY_BUDGET} is exceeded. */
9
+ export declare const CATEGORY_AXIS_ROTATE_DEGREES = 35;
10
+ export declare function readNumericSeriesValue(value: unknown, semanticType?: SemanticType): number | null;
11
+ export declare function categoryValues(rows: readonly Record<string, unknown>[], categoryKey: string, fields: readonly FieldDescriptor[]): string[];
12
+ /**
13
+ * True when category labels are dense enough that unrotated ticks would collide.
14
+ *
15
+ * @example
16
+ * shouldRotateCategoryAxisLabels(['North American…', 'Europe']); // true
17
+ */
18
+ export declare function shouldRotateCategoryAxisLabels(labels: readonly string[]): boolean;
19
+ export declare function buildCategoryAxis(rows: readonly Record<string, unknown>[], categoryKey: string, fields: readonly FieldDescriptor[]): XAXisComponentOption;
20
+ /**
21
+ * Legend chrome shared by line and bar charts: hidden for a single series, shown for two or more.
22
+ *
23
+ * @example
24
+ * buildSeriesLegend(['Revenue']); // { show: false }
25
+ */
26
+ export declare function buildSeriesLegend(seriesNames: readonly string[]): LegendComponentOption;
27
+ /**
28
+ * True when a single-series y-axis name would duplicate a chart title that already names the metric.
29
+ * A lone series still keeps its upright y-axis name when there is no such title.
30
+ *
31
+ * @example
32
+ * shouldOmitSingleSeriesYAxisName(['Requests'], 'Requests'); // true
33
+ * shouldOmitSingleSeriesYAxisName(['Requests'], undefined); // false
34
+ */
35
+ export declare function shouldOmitSingleSeriesYAxisName(seriesNames: readonly string[], chartTitle: string | undefined): boolean;
36
+ /**
37
+ * True when the x field is a plain number (a step, epoch or version), so the chart needs a value
38
+ * axis. Dates and categories keep the category axis.
39
+ *
40
+ * @example
41
+ * isNumericAxisField(fieldByKey(spec.fields, 'epoch')); // true
42
+ */
43
+ export declare function isNumericAxisField(field: FieldDescriptor | undefined): boolean;
44
+ /**
45
+ * Builds a value-type x axis for a numeric x field, named after the field.
46
+ *
47
+ * @example
48
+ * const axis = buildNumericXAxis(spec.fields, 'epoch');
49
+ */
50
+ export declare function buildNumericXAxis(fields: readonly FieldDescriptor[], xKey: string): XAXisComponentOption;
51
+ /**
52
+ * Pairs each row's numeric x with its y so a value axis plots at the real x position. Rows whose
53
+ * x is not a number are skipped.
54
+ *
55
+ * @example
56
+ * numericXSeries(rows, 'epoch', 'loss', fields); // [[1, 2.4], [2, 1.9]]
57
+ */
58
+ export declare function numericXSeries(rows: readonly Record<string, unknown>[], xKey: string, yKey: string, fields: readonly FieldDescriptor[]): [number, number | null][];
59
+ export declare function numericSeries(rows: readonly Record<string, unknown>[], valueKey: string, fields?: readonly FieldDescriptor[]): (number | null)[];
60
+ export declare function seriesLabel(fields: readonly FieldDescriptor[], key: string): string;
61
+ //# sourceMappingURL=chart-series-data.d.ts.map
@@ -0,0 +1,150 @@
1
+ import { parseNumericValue } from '@schemacast/core';
2
+ import { fieldByKey } from '../field-by-key.js';
3
+ import { formatFieldValue } from '../format-field-value.js';
4
+ const MAX_CATEGORY_AXIS_LABEL_LENGTH = 16;
5
+ /**
6
+ * Rotate category ticks when `(label count) × (longest truncated label length)` exceeds this
7
+ * budget. Below the budget, labels stay upright (`rotate: 0`) with `hideOverlap: true`.
8
+ */
9
+ export const CATEGORY_AXIS_ROTATE_DENSITY_BUDGET = 24;
10
+ /** Degrees used when {@link CATEGORY_AXIS_ROTATE_DENSITY_BUDGET} is exceeded. */
11
+ export const CATEGORY_AXIS_ROTATE_DEGREES = 35;
12
+ export function readNumericSeriesValue(value, semanticType) {
13
+ return parseNumericValue(value, semanticType);
14
+ }
15
+ export function categoryValues(rows, categoryKey, fields) {
16
+ return rows.map((row) => formatFieldValue(row[categoryKey], fieldByKey(fields, categoryKey)));
17
+ }
18
+ /**
19
+ * True when category labels are dense enough that unrotated ticks would collide.
20
+ *
21
+ * @example
22
+ * shouldRotateCategoryAxisLabels(['North American…', 'Europe']); // true
23
+ */
24
+ export function shouldRotateCategoryAxisLabels(labels) {
25
+ if (labels.length === 0) {
26
+ return false;
27
+ }
28
+ let longest = 0;
29
+ for (const label of labels) {
30
+ const length = Array.from(truncateCategoryAxisLabel(label)).length;
31
+ if (length > longest) {
32
+ longest = length;
33
+ }
34
+ }
35
+ return labels.length * longest > CATEGORY_AXIS_ROTATE_DENSITY_BUDGET;
36
+ }
37
+ export function buildCategoryAxis(rows, categoryKey, fields) {
38
+ const data = categoryValues(rows, categoryKey, fields);
39
+ const rotate = shouldRotateCategoryAxisLabels(data) ? CATEGORY_AXIS_ROTATE_DEGREES : 0;
40
+ return {
41
+ type: 'category',
42
+ data,
43
+ axisLabel: {
44
+ interval: 0,
45
+ hideOverlap: rotate === 0,
46
+ rotate,
47
+ formatter: (value) => truncateCategoryAxisLabel(value),
48
+ },
49
+ };
50
+ }
51
+ /**
52
+ * Legend chrome shared by line and bar charts: hidden for a single series, shown for two or more.
53
+ *
54
+ * @example
55
+ * buildSeriesLegend(['Revenue']); // { show: false }
56
+ */
57
+ export function buildSeriesLegend(seriesNames) {
58
+ if (seriesNames.length <= 1) {
59
+ return { show: false };
60
+ }
61
+ return { show: true, data: [...seriesNames] };
62
+ }
63
+ /**
64
+ * True when a single-series y-axis name would duplicate a chart title that already names the metric.
65
+ * A lone series still keeps its upright y-axis name when there is no such title.
66
+ *
67
+ * @example
68
+ * shouldOmitSingleSeriesYAxisName(['Requests'], 'Requests'); // true
69
+ * shouldOmitSingleSeriesYAxisName(['Requests'], undefined); // false
70
+ */
71
+ export function shouldOmitSingleSeriesYAxisName(seriesNames, chartTitle) {
72
+ if (seriesNames.length !== 1 || chartTitle === undefined) {
73
+ return false;
74
+ }
75
+ const seriesName = seriesNames[0];
76
+ if (seriesName === undefined) {
77
+ return false;
78
+ }
79
+ const normalizedTitle = chartTitle.trim().toLowerCase();
80
+ const normalizedSeries = seriesName.trim().toLowerCase();
81
+ if (normalizedTitle.length === 0 || normalizedSeries.length === 0) {
82
+ return false;
83
+ }
84
+ return normalizedTitle === normalizedSeries || normalizedTitle.includes(normalizedSeries);
85
+ }
86
+ /**
87
+ * True when the x field is a plain number (a step, epoch or version), so the chart needs a value
88
+ * axis. Dates and categories keep the category axis.
89
+ *
90
+ * @example
91
+ * isNumericAxisField(fieldByKey(spec.fields, 'epoch')); // true
92
+ */
93
+ export function isNumericAxisField(field) {
94
+ return field?.semanticType === 'number';
95
+ }
96
+ /**
97
+ * Builds a value-type x axis for a numeric x field, named after the field.
98
+ *
99
+ * @example
100
+ * const axis = buildNumericXAxis(spec.fields, 'epoch');
101
+ */
102
+ export function buildNumericXAxis(fields, xKey) {
103
+ const name = fieldByKey(fields, xKey)?.label ?? xKey;
104
+ return {
105
+ type: 'value',
106
+ scale: true,
107
+ name,
108
+ nameLocation: 'middle',
109
+ nameGap: 28,
110
+ nameRotate: 0,
111
+ };
112
+ }
113
+ /**
114
+ * Pairs each row's numeric x with its y so a value axis plots at the real x position. Rows whose
115
+ * x is not a number are skipped.
116
+ *
117
+ * @example
118
+ * numericXSeries(rows, 'epoch', 'loss', fields); // [[1, 2.4], [2, 1.9]]
119
+ */
120
+ export function numericXSeries(rows, xKey, yKey, fields) {
121
+ const xType = fieldByKey(fields, xKey)?.semanticType;
122
+ const yType = fieldByKey(fields, yKey)?.semanticType;
123
+ const points = [];
124
+ for (const row of rows) {
125
+ const x = readNumericSeriesValue(row[xKey], xType);
126
+ if (x !== null) {
127
+ points.push([x, readNumericSeriesValue(row[yKey], yType)]);
128
+ }
129
+ }
130
+ return points;
131
+ }
132
+ export function numericSeries(rows, valueKey, fields) {
133
+ const semanticType = fields === undefined ? undefined : fieldByKey(fields, valueKey)?.semanticType;
134
+ return rows.map((row) => readNumericSeriesValue(row[valueKey], semanticType));
135
+ }
136
+ export function seriesLabel(fields, key) {
137
+ return fieldByKey(fields, key)?.label ?? key;
138
+ }
139
+ function truncateCategoryAxisLabel(value) {
140
+ const label = String(value);
141
+ const characters = Array.from(label);
142
+ if (characters.length <= MAX_CATEGORY_AXIS_LABEL_LENGTH) {
143
+ return label;
144
+ }
145
+ return `${characters
146
+ .slice(0, MAX_CATEGORY_AXIS_LABEL_LENGTH - 1)
147
+ .join('')
148
+ .trimEnd()}…`;
149
+ }
150
+ //# sourceMappingURL=chart-series-data.js.map
@@ -0,0 +1,45 @@
1
+ import { type FieldDescriptor, type VisualSpec } from '@schemacast/core';
2
+ import type { TooltipComponentFormatterCallbackParams, YAXisComponentOption } from 'echarts';
3
+ /** Identifies the field and side used to render one value axis. */
4
+ export interface ValueAxisDefinition {
5
+ readonly fieldKey: string;
6
+ readonly position: 'left' | 'right';
7
+ }
8
+ /** Contains shared y-axis assignments for bar and line chart series. */
9
+ export interface ValueAxisPlan {
10
+ readonly axes: readonly ValueAxisDefinition[];
11
+ readonly seriesAxisIndexes: readonly number[];
12
+ }
13
+ /**
14
+ * Chooses one or two value axes from field units and series magnitudes. A line chart also
15
+ * splits a 0-1 metric from a larger one (`isLineChart`), see `findSecondaryAxisSeries`.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const axisPlan = buildValueAxisPlan(spec, ['revenue_usd', 'growth_pct']);
20
+ * ```
21
+ */
22
+ export declare function buildValueAxisPlan(spec: VisualSpec, yKeys: readonly string[], rows?: readonly Record<string, unknown>[], isLineChart?: boolean): ValueAxisPlan;
23
+ /**
24
+ * Builds a themed-ready, unit-aware y-axis shared by bar and line charts.
25
+ * Titles stay upright (`nameRotate: 0`). Short 1–2 character names are never rotated either.
26
+ * Pass `omitName` when a chart title already shows the metric (a lone series otherwise keeps its name).
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const axis = buildValueAxis(spec.fields, { fieldKey: 'error_rate', position: 'left' });
31
+ * ```
32
+ */
33
+ export declare function buildValueAxis(fields: readonly FieldDescriptor[], definition: ValueAxisDefinition, options?: {
34
+ readonly omitName?: boolean;
35
+ }): YAXisComponentOption;
36
+ /**
37
+ * Formats a chart tooltip using full precision and field units.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const tooltip = formatChartTooltip(params, spec.fields, ['p95_latency_ms']);
42
+ * ```
43
+ */
44
+ export declare function formatChartTooltip(parameters: TooltipComponentFormatterCallbackParams, fields: readonly FieldDescriptor[], yKeys: readonly string[]): string;
45
+ //# sourceMappingURL=chart-value-axes.d.ts.map
@@ -0,0 +1,214 @@
1
+ import { findSecondaryAxisSeries, measureSeriesMagnitude, } from '@schemacast/core';
2
+ import { fieldByKey } from '../field-by-key.js';
3
+ import { formatFieldValue, isUnitConfirmed } from '../format-field-value.js';
4
+ import { seriesLabel } from './chart-series-data.js';
5
+ /**
6
+ * Chooses one or two value axes from field units and series magnitudes. A line chart also
7
+ * splits a 0-1 metric from a larger one (`isLineChart`), see `findSecondaryAxisSeries`.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const axisPlan = buildValueAxisPlan(spec, ['revenue_usd', 'growth_pct']);
12
+ * ```
13
+ */
14
+ export function buildValueAxisPlan(spec, yKeys, rows = spec.data, isLineChart = false) {
15
+ const firstYKey = yKeys[0];
16
+ if (firstYKey === undefined) {
17
+ return { axes: [], seriesAxisIndexes: [] };
18
+ }
19
+ if (yKeys.length < 2) {
20
+ return {
21
+ axes: [{ fieldKey: firstYKey, position: 'left' }],
22
+ seriesAxisIndexes: yKeys.map(() => 0),
23
+ };
24
+ }
25
+ const firstUnit = unitKey(fieldByKey(spec.fields, firstYKey));
26
+ const differentUnits = yKeys.some((key) => unitKey(fieldByKey(spec.fields, key)) !== firstUnit);
27
+ if (differentUnits) {
28
+ const secondYKey = yKeys.find((key) => unitKey(fieldByKey(spec.fields, key)) !== firstUnit);
29
+ if (secondYKey === undefined) {
30
+ return {
31
+ axes: [{ fieldKey: firstYKey, position: 'left' }],
32
+ seriesAxisIndexes: yKeys.map(() => 0),
33
+ };
34
+ }
35
+ return {
36
+ axes: [
37
+ { fieldKey: firstYKey, position: 'left' },
38
+ { fieldKey: secondYKey, position: 'right' },
39
+ ],
40
+ seriesAxisIndexes: yKeys.map((key) => unitKey(fieldByKey(spec.fields, key)) === firstUnit ? 0 : 1),
41
+ };
42
+ }
43
+ const magnitudes = yKeys.map((key) => measureSeriesMagnitude(rows, key, fieldByKey(spec.fields, key)?.semanticType));
44
+ const rightIndexes = findSecondaryAxisSeries(magnitudes, isLineChart);
45
+ const firstRightIndex = rightIndexes[0];
46
+ const firstLeftIndex = yKeys.findIndex((_, index) => !rightIndexes.includes(index));
47
+ const rightYKey = firstRightIndex === undefined ? undefined : yKeys[firstRightIndex];
48
+ const leftYKey = yKeys[firstLeftIndex];
49
+ if (rightYKey === undefined || leftYKey === undefined) {
50
+ return {
51
+ axes: [{ fieldKey: firstYKey, position: 'left' }],
52
+ seriesAxisIndexes: yKeys.map(() => 0),
53
+ };
54
+ }
55
+ return {
56
+ axes: [
57
+ { fieldKey: leftYKey, position: 'left' },
58
+ { fieldKey: rightYKey, position: 'right' },
59
+ ],
60
+ seriesAxisIndexes: yKeys.map((_, index) => (rightIndexes.includes(index) ? 1 : 0)),
61
+ };
62
+ }
63
+ /**
64
+ * Builds a themed-ready, unit-aware y-axis shared by bar and line charts.
65
+ * Titles stay upright (`nameRotate: 0`). Short 1–2 character names are never rotated either.
66
+ * Pass `omitName` when a chart title already shows the metric (a lone series otherwise keeps its name).
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * const axis = buildValueAxis(spec.fields, { fieldKey: 'error_rate', position: 'left' });
71
+ * ```
72
+ */
73
+ export function buildValueAxis(fields, definition, options = {}) {
74
+ const field = fieldByKey(fields, definition.fieldKey);
75
+ const label = seriesLabel(fields, definition.fieldKey);
76
+ const unit = fieldUnit(field);
77
+ const name = unit === undefined ? label : appendAxisUnit(label, unit);
78
+ const omitName = options.omitName === true;
79
+ return {
80
+ type: 'value',
81
+ ...(omitName ? {} : { name }),
82
+ nameLocation: 'middle',
83
+ nameGap: omitName ? 36 : 56,
84
+ nameRotate: 0,
85
+ position: definition.position,
86
+ splitNumber: 5,
87
+ alignTicks: definition.position === 'right',
88
+ splitLine: { show: definition.position === 'left' },
89
+ axisLabel: {
90
+ formatter: (value) => formatCompactAxisValue(value, field),
91
+ hideOverlap: true,
92
+ margin: 10,
93
+ },
94
+ };
95
+ }
96
+ function appendAxisUnit(label, unit) {
97
+ const normalizedLabel = label.trimEnd().toLowerCase();
98
+ const normalizedSuffix = `(${unit.toLowerCase()})`;
99
+ return normalizedLabel.endsWith(normalizedSuffix) ? label : `${label} (${unit})`;
100
+ }
101
+ /**
102
+ * Formats a chart tooltip using full precision and field units.
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * const tooltip = formatChartTooltip(params, spec.fields, ['p95_latency_ms']);
107
+ * ```
108
+ */
109
+ export function formatChartTooltip(parameters, fields, yKeys) {
110
+ const tooltipParameters = Array.isArray(parameters) ? parameters : [parameters];
111
+ const firstParameter = tooltipParameters[0];
112
+ if (firstParameter === undefined) {
113
+ return '';
114
+ }
115
+ const headingText = firstParameter.name === '' ? readAxisValueLabel(firstParameter) : firstParameter.name;
116
+ const heading = `<strong>${escapeTooltipText(headingText)}</strong>`;
117
+ const values = tooltipParameters.map((parameter) => {
118
+ const seriesKey = parameter.seriesIndex === undefined ? undefined : yKeys[parameter.seriesIndex];
119
+ const field = seriesKey === undefined ? undefined : fieldByKey(fields, seriesKey);
120
+ const label = parameter.seriesName ?? (seriesKey === undefined ? 'Value' : seriesLabel(fields, seriesKey));
121
+ // A numeric x axis feeds [x, y] pairs; the y is the second item.
122
+ const plotted = Array.isArray(parameter.value) ? parameter.value[1] : parameter.value;
123
+ const value = formatTooltipValue(plotted, field);
124
+ return `${escapeTooltipText(label)}: ${escapeTooltipText(value)}`;
125
+ });
126
+ return [heading, ...values].join('<br/>');
127
+ }
128
+ /** A value x axis leaves the point name empty, so the hovered x comes from `axisValueLabel`. */
129
+ function readAxisValueLabel(parameter) {
130
+ if ('axisValueLabel' in parameter && typeof parameter.axisValueLabel === 'string') {
131
+ return parameter.axisValueLabel;
132
+ }
133
+ return '';
134
+ }
135
+ function formatCompactAxisValue(value, field) {
136
+ const numericValue = typeof value === 'number' ? value : Number(value);
137
+ if (!Number.isFinite(numericValue)) {
138
+ return formatFieldValue(value, field);
139
+ }
140
+ const compactNumber = new Intl.NumberFormat('en-US', {
141
+ notation: 'compact',
142
+ maximumFractionDigits: 1,
143
+ });
144
+ const isPercent = field?.formatHint === 'percent' || field?.semanticType === 'percentage';
145
+ if (isPercent && isUnitConfirmed(field)) {
146
+ const normalizedValue = numericValue <= 1 && numericValue >= 0 ? numericValue * 100 : numericValue;
147
+ return `${compactNumber.format(normalizedValue)}%`;
148
+ }
149
+ if (field?.semanticType === 'currency' && isUnitConfirmed(field)) {
150
+ const currencyHint = field.formatHint ?? 'USD';
151
+ if (currencyHint === 'USD') {
152
+ return new Intl.NumberFormat('en-US', {
153
+ style: 'currency',
154
+ currency: currencyHint,
155
+ notation: 'compact',
156
+ maximumFractionDigits: 1,
157
+ }).format(numericValue);
158
+ }
159
+ return `${compactNumber.format(numericValue)} ${currencyHint}`;
160
+ }
161
+ const unit = fieldUnit(field);
162
+ const formattedValue = Math.abs(numericValue) < 1
163
+ ? String(Number(numericValue.toPrecision(2)))
164
+ : compactNumber.format(numericValue);
165
+ return unit === undefined ? formattedValue : `${formattedValue} ${unit}`;
166
+ }
167
+ function formatTooltipValue(value, field) {
168
+ const formattedValue = formatFieldValue(value, field);
169
+ if (field === undefined ||
170
+ field.semanticType === 'currency' ||
171
+ field.semanticType === 'percentage' ||
172
+ field.formatHint === 'percent') {
173
+ return formattedValue;
174
+ }
175
+ const unit = fieldUnit(field);
176
+ const numericValue = typeof value === 'number' ? value : Number(value);
177
+ return unit !== undefined && Number.isFinite(numericValue)
178
+ ? `${formattedValue} ${unit}`
179
+ : formattedValue;
180
+ }
181
+ function fieldUnit(field) {
182
+ if (field === undefined) {
183
+ return undefined;
184
+ }
185
+ const isMoneyOrPercent = field.semanticType === 'currency' || field.semanticType === 'percentage';
186
+ if (isMoneyOrPercent || field.formatHint === 'percent') {
187
+ return isUnitConfirmed(field) ? describeConfirmedUnit(field) : undefined;
188
+ }
189
+ if (field.formatHint !== undefined && field.formatHint !== 'iso-date') {
190
+ return field.formatHint;
191
+ }
192
+ return /_ms$/i.test(field.key) ? 'ms' : undefined;
193
+ }
194
+ function describeConfirmedUnit(field) {
195
+ if (field.semanticType === 'currency') {
196
+ return field.formatHint ?? 'USD';
197
+ }
198
+ return '%';
199
+ }
200
+ function unitKey(field) {
201
+ const semanticType = field?.semanticType ?? 'unknown';
202
+ return `${semanticType}:${fieldUnit(field) ?? 'unitless'}`;
203
+ }
204
+ function escapeTooltipText(text) {
205
+ const entities = {
206
+ '&': '&amp;',
207
+ '<': '&lt;',
208
+ '>': '&gt;',
209
+ '"': '&quot;',
210
+ "'": '&#39;',
211
+ };
212
+ return text.replace(/[&<>"']/g, (character) => entities[character] ?? character);
213
+ }
214
+ //# sourceMappingURL=chart-value-axes.js.map
@@ -0,0 +1,3 @@
1
+ /** Default number of rows shown per data-table page. */
2
+ export declare const DATA_TABLE_PAGE_SIZE = 10;
3
+ //# sourceMappingURL=data-table-constants.d.ts.map
@@ -0,0 +1,3 @@
1
+ /** Default number of rows shown per data-table page. */
2
+ export const DATA_TABLE_PAGE_SIZE = 10;
3
+ //# sourceMappingURL=data-table-constants.js.map
@@ -0,0 +1,8 @@
1
+ import { type FieldDescriptor } from '@schemacast/core';
2
+ export type SortDirection = 'asc' | 'desc';
3
+ export declare function shallowCopyRows(rows: readonly Record<string, unknown>[]): Record<string, unknown>[];
4
+ export declare function resolveTableColumns(columnKeys: readonly string[] | undefined, fields: readonly FieldDescriptor[]): string[];
5
+ export declare function filterRows(rows: readonly Record<string, unknown>[], columns: readonly string[], fields: readonly FieldDescriptor[], searchQuery: string): Record<string, unknown>[];
6
+ export declare function sortRows(rows: readonly Record<string, unknown>[], sortKey: string | undefined, sortDirection: SortDirection, fields: readonly FieldDescriptor[]): Record<string, unknown>[];
7
+ export declare function paginateRows<T>(rows: readonly T[], pageIndex: number, pageSize: number): readonly T[];
8
+ //# sourceMappingURL=data-table-rows.d.ts.map
@@ -0,0 +1,50 @@
1
+ import { parseNumericValue } from '@schemacast/core';
2
+ import { formatFieldValue } from '../format-field-value.js';
3
+ import { fieldByKey } from '../field-by-key.js';
4
+ export function shallowCopyRows(rows) {
5
+ return rows.map((row) => ({ ...row }));
6
+ }
7
+ export function resolveTableColumns(columnKeys, fields) {
8
+ if (columnKeys !== undefined && columnKeys.length > 0) {
9
+ return [...columnKeys];
10
+ }
11
+ return fields.filter((field) => field.semanticType !== 'nested').map((field) => field.key);
12
+ }
13
+ export function filterRows(rows, columns, fields, searchQuery) {
14
+ const normalized = searchQuery.trim().toLowerCase();
15
+ const copied = shallowCopyRows(rows);
16
+ if (normalized.length === 0) {
17
+ return copied;
18
+ }
19
+ return copied.filter((row) => columns.some((column) => {
20
+ const text = formatFieldValue(row[column], fieldByKey(fields, column)).toLowerCase();
21
+ return text.includes(normalized);
22
+ }));
23
+ }
24
+ export function sortRows(rows, sortKey, sortDirection, fields) {
25
+ if (sortKey === undefined) {
26
+ return shallowCopyRows(rows);
27
+ }
28
+ const sorted = shallowCopyRows(rows);
29
+ const field = fieldByKey(fields, sortKey);
30
+ sorted.sort((left, right) => compareRowValues(left[sortKey], right[sortKey], field));
31
+ if (sortDirection === 'desc') {
32
+ sorted.reverse();
33
+ }
34
+ return sorted;
35
+ }
36
+ function compareRowValues(left, right, field) {
37
+ const leftText = formatFieldValue(left, field);
38
+ const rightText = formatFieldValue(right, field);
39
+ const leftNumber = parseNumericValue(left, field?.semanticType);
40
+ const rightNumber = parseNumericValue(right, field?.semanticType);
41
+ if (leftNumber !== null && rightNumber !== null) {
42
+ return leftNumber - rightNumber;
43
+ }
44
+ return leftText.localeCompare(rightText);
45
+ }
46
+ export function paginateRows(rows, pageIndex, pageSize) {
47
+ const start = pageIndex * pageSize;
48
+ return rows.slice(start, start + pageSize);
49
+ }
50
+ //# sourceMappingURL=data-table-rows.js.map
@@ -0,0 +1,16 @@
1
+ import type { FieldBindings, VisualSpec } from '@schemacast/core';
2
+ import type { ReactElement } from 'react';
3
+ export interface DataTableViewProps {
4
+ readonly spec: VisualSpec;
5
+ readonly bindings: FieldBindings;
6
+ }
7
+ /**
8
+ * Sortable, filterable, paginated `data-table` over `VisualSpec.data`.
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * <DataTableView spec={spec} bindings={spec.primaryView.bindings} />
13
+ * ```
14
+ */
15
+ export declare function DataTableView({ spec, bindings }: DataTableViewProps): ReactElement;
16
+ //# sourceMappingURL=data-table-view.d.ts.map