@surfaces-ui/components 0.0.0-stage → 0.2.0
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.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +48 -2
- package/dist/appComponents.d.ts +86 -0
- package/dist/appComponents.js +555 -0
- package/dist/appComponents.js.map +1 -0
- package/dist/chart/BulletGraph.d.ts +44 -0
- package/dist/chart/BulletGraph.js +40 -0
- package/dist/chart/BulletGraph.js.map +1 -0
- package/dist/chart/Chart.d.ts +177 -0
- package/dist/chart/Chart.js +279 -0
- package/dist/chart/Chart.js.map +1 -0
- package/dist/chart/Sparkline.d.ts +35 -0
- package/dist/chart/Sparkline.js +37 -0
- package/dist/chart/Sparkline.js.map +1 -0
- package/dist/chart/advice.d.ts +28 -0
- package/dist/chart/advice.js +39 -0
- package/dist/chart/advice.js.map +1 -0
- package/dist/chart/option.d.ts +90 -0
- package/dist/chart/option.js +252 -0
- package/dist/chart/option.js.map +1 -0
- package/dist/controls/Combobox.d.ts +39 -0
- package/dist/controls/Combobox.js +75 -0
- package/dist/controls/Combobox.js.map +1 -0
- package/dist/controls/ConfirmDialog.d.ts +35 -0
- package/dist/controls/ConfirmDialog.js +84 -0
- package/dist/controls/ConfirmDialog.js.map +1 -0
- package/dist/controls/ItemControls.d.ts +115 -0
- package/dist/controls/ItemControls.js +109 -0
- package/dist/controls/ItemControls.js.map +1 -0
- package/dist/controls/Popover.d.ts +31 -0
- package/dist/controls/Popover.js +114 -0
- package/dist/controls/Popover.js.map +1 -0
- package/dist/controls/ResizeHandle.d.ts +48 -0
- package/dist/controls/ResizeHandle.js +91 -0
- package/dist/controls/ResizeHandle.js.map +1 -0
- package/dist/controls/SegmentedControl.d.ts +27 -0
- package/dist/controls/SegmentedControl.js +17 -0
- package/dist/controls/SegmentedControl.js.map +1 -0
- package/dist/controls/StatusBadge.d.ts +17 -0
- package/dist/controls/StatusBadge.js +10 -0
- package/dist/controls/StatusBadge.js.map +1 -0
- package/dist/controls/context.d.ts +17 -0
- package/dist/controls/context.js +2 -0
- package/dist/controls/context.js.map +1 -0
- package/dist/controls/placement.d.ts +43 -0
- package/dist/controls/placement.js +19 -0
- package/dist/controls/placement.js.map +1 -0
- package/dist/controls/resize.d.ts +23 -0
- package/dist/controls/resize.js +49 -0
- package/dist/controls/resize.js.map +1 -0
- package/dist/data/DataSourceProvider.d.ts +11 -0
- package/dist/data/DataSourceProvider.js +21 -0
- package/dist/data/DataSourceProvider.js.map +1 -0
- package/dist/data/export.d.ts +33 -0
- package/dist/data/export.js +77 -0
- package/dist/data/export.js.map +1 -0
- package/dist/data/format.d.ts +44 -0
- package/dist/data/format.js +127 -0
- package/dist/data/format.js.map +1 -0
- package/dist/data/messages.d.ts +13 -0
- package/dist/data/messages.js +2 -0
- package/dist/data/messages.js.map +1 -0
- package/dist/data/useRowWindow.d.ts +70 -0
- package/dist/data/useRowWindow.js +175 -0
- package/dist/data/useRowWindow.js.map +1 -0
- package/dist/discovery/AskData.d.ts +22 -0
- package/dist/discovery/AskData.js +48 -0
- package/dist/discovery/AskData.js.map +1 -0
- package/dist/discovery/ContextBuilder.d.ts +49 -0
- package/dist/discovery/ContextBuilder.js +167 -0
- package/dist/discovery/ContextBuilder.js.map +1 -0
- package/dist/discovery/DataSearch.d.ts +27 -0
- package/dist/discovery/DataSearch.js +73 -0
- package/dist/discovery/DataSearch.js.map +1 -0
- package/dist/discovery/ObjectDetail.d.ts +38 -0
- package/dist/discovery/ObjectDetail.js +129 -0
- package/dist/discovery/ObjectDetail.js.map +1 -0
- package/dist/discovery/RelationshipGraph.d.ts +19 -0
- package/dist/discovery/RelationshipGraph.js +64 -0
- package/dist/discovery/RelationshipGraph.js.map +1 -0
- package/dist/discovery/shared.d.ts +38 -0
- package/dist/discovery/shared.js +64 -0
- package/dist/discovery/shared.js.map +1 -0
- package/dist/editor/SqlEditor.d.ts +41 -0
- package/dist/editor/SqlEditor.js +181 -0
- package/dist/editor/SqlEditor.js.map +1 -0
- package/dist/explore/Explorer.d.ts +110 -0
- package/dist/explore/Explorer.js +471 -0
- package/dist/explore/Explorer.js.map +1 -0
- package/dist/explore/ModelLineage.d.ts +22 -0
- package/dist/explore/ModelLineage.js +70 -0
- package/dist/explore/ModelLineage.js.map +1 -0
- package/dist/explore/ReportBuilder.d.ts +39 -0
- package/dist/explore/ReportBuilder.js +98 -0
- package/dist/explore/ReportBuilder.js.map +1 -0
- package/dist/explore/SemanticModelEditor.d.ts +60 -0
- package/dist/explore/SemanticModelEditor.js +220 -0
- package/dist/explore/SemanticModelEditor.js.map +1 -0
- package/dist/explore/SemanticRows.d.ts +42 -0
- package/dist/explore/SemanticRows.js +117 -0
- package/dist/explore/SemanticRows.js.map +1 -0
- package/dist/explore/SemanticsProvider.d.ts +31 -0
- package/dist/explore/SemanticsProvider.js +72 -0
- package/dist/explore/SemanticsProvider.js.map +1 -0
- package/dist/explore/model.d.ts +151 -0
- package/dist/explore/model.js +344 -0
- package/dist/explore/model.js.map +1 -0
- package/dist/explore/report.d.ts +60 -0
- package/dist/explore/report.js +92 -0
- package/dist/explore/report.js.map +1 -0
- package/dist/explore/semantic-proposal.d.ts +44 -0
- package/dist/explore/semantic-proposal.js +67 -0
- package/dist/explore/semantic-proposal.js.map +1 -0
- package/dist/explore/semantic.d.ts +44 -0
- package/dist/explore/semantic.js +154 -0
- package/dist/explore/semantic.js.map +1 -0
- package/dist/files/FileBrowser.d.ts +42 -0
- package/dist/files/FileBrowser.js +314 -0
- package/dist/files/FileBrowser.js.map +1 -0
- package/dist/files/files.d.ts +65 -0
- package/dist/files/files.js +165 -0
- package/dist/files/files.js.map +1 -0
- package/dist/filter/FilterBar.d.ts +49 -0
- package/dist/filter/FilterBar.js +153 -0
- package/dist/filter/FilterBar.js.map +1 -0
- package/dist/filter/QueryFilters.d.ts +25 -0
- package/dist/filter/QueryFilters.js +58 -0
- package/dist/filter/QueryFilters.js.map +1 -0
- package/dist/form/Form.d.ts +76 -0
- package/dist/form/Form.js +131 -0
- package/dist/form/Form.js.map +1 -0
- package/dist/graph/NodeGraph.d.ts +30 -0
- package/dist/graph/NodeGraph.js +86 -0
- package/dist/graph/NodeGraph.js.map +1 -0
- package/dist/graph/model.d.ts +68 -0
- package/dist/graph/model.js +122 -0
- package/dist/graph/model.js.map +1 -0
- package/dist/grid/DataGrid.d.ts +98 -0
- package/dist/grid/DataGrid.js +399 -0
- package/dist/grid/DataGrid.js.map +1 -0
- package/dist/index.d.ts +84 -0
- package/dist/index.js +86 -0
- package/dist/index.js.map +1 -0
- package/dist/locale/SurfacesText.d.ts +17 -0
- package/dist/locale/SurfacesText.js +17 -0
- package/dist/locale/SurfacesText.js.map +1 -0
- package/dist/locale/locale.d.ts +305 -0
- package/dist/locale/locale.js +359 -0
- package/dist/locale/locale.js.map +1 -0
- package/dist/menu/ContextMenu.d.ts +31 -0
- package/dist/menu/ContextMenu.js +95 -0
- package/dist/menu/ContextMenu.js.map +1 -0
- package/dist/metric/Metric.d.ts +33 -0
- package/dist/metric/Metric.js +63 -0
- package/dist/metric/Metric.js.map +1 -0
- package/dist/metric/useMeasure.d.ts +23 -0
- package/dist/metric/useMeasure.js +43 -0
- package/dist/metric/useMeasure.js.map +1 -0
- package/dist/model/ModelDiagram.d.ts +142 -0
- package/dist/model/ModelDiagram.js +699 -0
- package/dist/model/ModelDiagram.js.map +1 -0
- package/dist/panzoom/usePanZoom.d.ts +117 -0
- package/dist/panzoom/usePanZoom.js +313 -0
- package/dist/panzoom/usePanZoom.js.map +1 -0
- package/dist/pipeline/DatasetReview.d.ts +48 -0
- package/dist/pipeline/DatasetReview.js +157 -0
- package/dist/pipeline/DatasetReview.js.map +1 -0
- package/dist/pipeline/IngestWizard.d.ts +51 -0
- package/dist/pipeline/IngestWizard.js +79 -0
- package/dist/pipeline/IngestWizard.js.map +1 -0
- package/dist/pipeline/Pipeline.d.ts +171 -0
- package/dist/pipeline/Pipeline.js +203 -0
- package/dist/pipeline/Pipeline.js.map +1 -0
- package/dist/pipeline/PipelineView.d.ts +63 -0
- package/dist/pipeline/PipelineView.js +239 -0
- package/dist/pipeline/PipelineView.js.map +1 -0
- package/dist/pivot/PivotTable.d.ts +94 -0
- package/dist/pivot/PivotTable.js +171 -0
- package/dist/pivot/PivotTable.js.map +1 -0
- package/dist/plan/QueryPlan.d.ts +29 -0
- package/dist/plan/QueryPlan.js +79 -0
- package/dist/plan/QueryPlan.js.map +1 -0
- package/dist/result/QueryResult.d.ts +51 -0
- package/dist/result/QueryResult.js +255 -0
- package/dist/result/QueryResult.js.map +1 -0
- package/dist/review/ActionReceipt.d.ts +52 -0
- package/dist/review/ActionReceipt.js +32 -0
- package/dist/review/ActionReceipt.js.map +1 -0
- package/dist/review/PiiReview.d.ts +37 -0
- package/dist/review/PiiReview.js +29 -0
- package/dist/review/PiiReview.js.map +1 -0
- package/dist/review/PlanReview.d.ts +42 -0
- package/dist/review/PlanReview.js +37 -0
- package/dist/review/PlanReview.js.map +1 -0
- package/dist/review/StepFlow.d.ts +25 -0
- package/dist/review/StepFlow.js +21 -0
- package/dist/review/StepFlow.js.map +1 -0
- package/dist/review/pii.d.ts +21 -0
- package/dist/review/pii.js +67 -0
- package/dist/review/pii.js.map +1 -0
- package/dist/rows/RowList.d.ts +41 -0
- package/dist/rows/RowList.js +71 -0
- package/dist/rows/RowList.js.map +1 -0
- package/dist/schema/ObjectBrowser.d.ts +78 -0
- package/dist/schema/ObjectBrowser.js +467 -0
- package/dist/schema/ObjectBrowser.js.map +1 -0
- package/dist/schema/ObjectInfo.d.ts +25 -0
- package/dist/schema/ObjectInfo.js +69 -0
- package/dist/schema/ObjectInfo.js.map +1 -0
- package/dist/schema/SchemaExplorer.d.ts +32 -0
- package/dist/schema/SchemaExplorer.js +175 -0
- package/dist/schema/SchemaExplorer.js.map +1 -0
- package/dist/schema/refs.d.ts +32 -0
- package/dist/schema/refs.js +65 -0
- package/dist/schema/refs.js.map +1 -0
- package/dist/site/Site.d.ts +191 -0
- package/dist/site/Site.js +138 -0
- package/dist/site/Site.js.map +1 -0
- package/dist/source/ConnectionBuilder.d.ts +54 -0
- package/dist/source/ConnectionBuilder.js +115 -0
- package/dist/source/ConnectionBuilder.js.map +1 -0
- package/dist/source/SourceList.d.ts +17 -0
- package/dist/source/SourceList.js +71 -0
- package/dist/source/SourceList.js.map +1 -0
- package/dist/styles.css +9882 -0
- package/dist/styles.layer.css +9886 -0
- package/dist/table/DataTable.d.ts +72 -0
- package/dist/table/DataTable.js +68 -0
- package/dist/table/DataTable.js.map +1 -0
- package/dist/table/Pagination.d.ts +20 -0
- package/dist/table/Pagination.js +16 -0
- package/dist/table/Pagination.js.map +1 -0
- package/dist/table/SelectionBar.d.ts +43 -0
- package/dist/table/SelectionBar.js +18 -0
- package/dist/table/SelectionBar.js.map +1 -0
- package/dist/text/Markdown.d.ts +71 -0
- package/dist/text/Markdown.js +187 -0
- package/dist/text/Markdown.js.map +1 -0
- package/dist/text/highlight.d.ts +23 -0
- package/dist/text/highlight.js +196 -0
- package/dist/text/highlight.js.map +1 -0
- package/dist/theme/ThemePicker.d.ts +16 -0
- package/dist/theme/ThemePicker.js +49 -0
- package/dist/theme/ThemePicker.js.map +1 -0
- package/dist/theme/ThemeProvider.d.ts +43 -0
- package/dist/theme/ThemeProvider.js +107 -0
- package/dist/theme/ThemeProvider.js.map +1 -0
- package/dist/workspace/NavBar.d.ts +23 -0
- package/dist/workspace/NavBar.js +171 -0
- package/dist/workspace/NavBar.js.map +1 -0
- package/dist/workspace/SideNav.d.ts +61 -0
- package/dist/workspace/SideNav.js +149 -0
- package/dist/workspace/SideNav.js.map +1 -0
- package/dist/workspace/Workspace.d.ts +50 -0
- package/dist/workspace/Workspace.js +243 -0
- package/dist/workspace/Workspace.js.map +1 -0
- package/dist/workspace/icons.d.ts +34 -0
- package/dist/workspace/icons.js +37 -0
- package/dist/workspace/icons.js.map +1 -0
- package/dist/workspace/layout.d.ts +74 -0
- package/dist/workspace/layout.js +276 -0
- package/dist/workspace/layout.js.map +1 -0
- package/package.json +85 -3
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { collect, parseMeasureExpression, writeMeasure } from "@surfaces-ui/data";
|
|
3
|
+
import { AggregateFunction, SortDirection, TimeGrain } from "@surfaces-ui/proto";
|
|
4
|
+
import { defaultTheme, echartsTheme, resolveColors } from "@surfaces-ui/tokens";
|
|
5
|
+
import { BarChart, LineChart, PieChart, ScatterChart } from "echarts/charts";
|
|
6
|
+
import { AriaComponent, DataZoomComponent, DatasetComponent, GridComponent, LegendComponent, TooltipComponent, } from "echarts/components";
|
|
7
|
+
import * as echarts from "echarts/core";
|
|
8
|
+
import { CanvasRenderer } from "echarts/renderers";
|
|
9
|
+
import { useEffect, useMemo, useRef, useState } from "react";
|
|
10
|
+
import { useDataSource } from "../data/DataSourceProvider.js";
|
|
11
|
+
import { chartValue, numericValue } from "../data/format.js";
|
|
12
|
+
import { label as text, numberFormat } from "../locale/locale.js";
|
|
13
|
+
import { messageOf } from "../data/useRowWindow.js";
|
|
14
|
+
import { useOptionalTheme } from "../theme/ThemeProvider.js";
|
|
15
|
+
import { chartAdvice } from "./advice.js";
|
|
16
|
+
import { buildChartOption, isOrdered, niceBinWidth, rowsWithoutX } from "./option.js";
|
|
17
|
+
echarts.use([
|
|
18
|
+
BarChart,
|
|
19
|
+
LineChart,
|
|
20
|
+
PieChart,
|
|
21
|
+
ScatterChart,
|
|
22
|
+
AriaComponent,
|
|
23
|
+
DataZoomComponent,
|
|
24
|
+
DatasetComponent,
|
|
25
|
+
GridComponent,
|
|
26
|
+
LegendComponent,
|
|
27
|
+
TooltipComponent,
|
|
28
|
+
CanvasRenderer,
|
|
29
|
+
]);
|
|
30
|
+
/** The contract's function for each aggregate name. */
|
|
31
|
+
export const AGGREGATE_FUNCTIONS = {
|
|
32
|
+
sum: AggregateFunction.SUM,
|
|
33
|
+
avg: AggregateFunction.AVG,
|
|
34
|
+
count: AggregateFunction.COUNT,
|
|
35
|
+
count_distinct: AggregateFunction.COUNT_DISTINCT,
|
|
36
|
+
min: AggregateFunction.MIN,
|
|
37
|
+
max: AggregateFunction.MAX,
|
|
38
|
+
median: AggregateFunction.MEDIAN,
|
|
39
|
+
stddev: AggregateFunction.STDDEV,
|
|
40
|
+
variance: AggregateFunction.VARIANCE,
|
|
41
|
+
percentile: AggregateFunction.PERCENTILE,
|
|
42
|
+
};
|
|
43
|
+
/** The contract's grain for each grain name. */
|
|
44
|
+
export const TIME_GRAINS = {
|
|
45
|
+
minute: TimeGrain.MINUTE,
|
|
46
|
+
hour: TimeGrain.HOUR,
|
|
47
|
+
day: TimeGrain.DAY,
|
|
48
|
+
week: TimeGrain.WEEK,
|
|
49
|
+
month: TimeGrain.MONTH,
|
|
50
|
+
quarter: TimeGrain.QUARTER,
|
|
51
|
+
year: TimeGrain.YEAR,
|
|
52
|
+
};
|
|
53
|
+
/** Output column and label for each measure. */
|
|
54
|
+
export function measureOutputs(y) {
|
|
55
|
+
return y.map((measure, i) => {
|
|
56
|
+
if (measure.expression)
|
|
57
|
+
return { column: `calc_${i}`, label: measure.label ?? measure.expression, measure };
|
|
58
|
+
if (!measure.aggregate)
|
|
59
|
+
return { column: measure.column ?? "", label: measure.label ?? measure.column ?? "", measure };
|
|
60
|
+
const subject = measure.column ?? "rows";
|
|
61
|
+
const name = measure.aggregate === "percentile" ? `p${Math.round((measure.percentile ?? 0.9) * 100)}` : measure.aggregate.replace("_", " ");
|
|
62
|
+
return {
|
|
63
|
+
column: `${measure.aggregate}_${measure.column ?? "rows"}_${i}`.replace(/\W+/g, "_"),
|
|
64
|
+
label: measure.label ?? (measure.aggregate === "count" && !measure.column ? "count" : `${name} of ${subject}`),
|
|
65
|
+
measure,
|
|
66
|
+
};
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
/** A calculation with each name given a prefix, so its terms are its own. One that cannot be read is sent as it is, and the engine says why. */
|
|
70
|
+
function termExpression(expression, prefix) {
|
|
71
|
+
try {
|
|
72
|
+
return writeMeasure(parseMeasureExpression(expression), { name: (name) => `${prefix}_${name}`, divide: (left, right) => `(${left} / ${right})` });
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return expression;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** The shape of a loaded chart, in the terms `chartAdvice` checks. Nothing drawn gives no advice. */
|
|
79
|
+
export function drawnShape(input) {
|
|
80
|
+
if (input.rows.length === 0)
|
|
81
|
+
return { type: input.type, categories: 0, series: 0 };
|
|
82
|
+
return {
|
|
83
|
+
type: input.type,
|
|
84
|
+
categories: new Set(input.rows.map((row) => row[input.x])).size,
|
|
85
|
+
series: input.type === "pie" ? 1 : input.seriesCount,
|
|
86
|
+
stacked: input.stacked,
|
|
87
|
+
rightAxis: input.y.some((m) => m.axis === "right"),
|
|
88
|
+
orderedX: input.binned || isOrdered(input.fields.find((f) => f.name === input.x)),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** How a chart's categories are ordered when not told: bars by size, everything else along x. */
|
|
92
|
+
export function chartSort(input) {
|
|
93
|
+
if (input.xGrain || input.binWidth)
|
|
94
|
+
return "x";
|
|
95
|
+
return input.sort ?? (input.type === "bar" && input.y.every((m) => (m.type ?? "bar") === "bar") ? "value" : "x");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The query a chart sends. With aggregated measures the engine groups by x
|
|
99
|
+
* (bucketed by time grain or bin width when asked) and by the split column;
|
|
100
|
+
* otherwise it returns a random sample of raw rows.
|
|
101
|
+
*/
|
|
102
|
+
export function buildChartQuery(input) {
|
|
103
|
+
const { sql, type, x, y, splitBy, filters, parameters, limit } = input;
|
|
104
|
+
const outputs = measureOutputs(y);
|
|
105
|
+
const aggregated = outputs.filter((o) => o.measure.aggregate || o.measure.expression);
|
|
106
|
+
if (aggregated.length === 0) {
|
|
107
|
+
const columns = [...new Set([x, ...(splitBy ? [splitBy] : []), ...outputs.map((o) => o.column)])];
|
|
108
|
+
return { baseSql: sql, filters, parameters, columns, sample: { rows: limit } };
|
|
109
|
+
}
|
|
110
|
+
const bucket = input.xGrain
|
|
111
|
+
? { column: x, by: { case: "grain", value: TIME_GRAINS[input.xGrain] } }
|
|
112
|
+
: input.binWidth
|
|
113
|
+
? { column: x, by: { case: "binWidth", value: input.binWidth } }
|
|
114
|
+
: undefined;
|
|
115
|
+
return {
|
|
116
|
+
baseSql: sql,
|
|
117
|
+
filters,
|
|
118
|
+
parameters,
|
|
119
|
+
groupBy: [...(bucket ? [] : [x]), ...(splitBy ? [splitBy] : [])],
|
|
120
|
+
buckets: bucket ? [bucket] : [],
|
|
121
|
+
aggregates: aggregated.flatMap((o) => o.measure.expression
|
|
122
|
+
? // A calculation's terms are aggregates of their own, named after the calculation so two calculations cannot collide.
|
|
123
|
+
Object.entries(o.measure.terms ?? {}).map(([name, term]) => ({
|
|
124
|
+
function: AGGREGATE_FUNCTIONS[term.aggregate],
|
|
125
|
+
column: term.column ?? "",
|
|
126
|
+
alias: `${o.column}_${name}`,
|
|
127
|
+
percentile: term.aggregate === "percentile" ? (term.percentile ?? 0.9) : 0,
|
|
128
|
+
}))
|
|
129
|
+
: [
|
|
130
|
+
{
|
|
131
|
+
function: AGGREGATE_FUNCTIONS[o.measure.aggregate],
|
|
132
|
+
column: o.measure.column ?? "",
|
|
133
|
+
alias: o.column,
|
|
134
|
+
percentile: o.measure.aggregate === "percentile" ? (o.measure.percentile ?? 0.9) : 0,
|
|
135
|
+
},
|
|
136
|
+
]),
|
|
137
|
+
derived: aggregated.filter((o) => o.measure.expression).map((o) => ({ alias: o.column, expression: termExpression(o.measure.expression, o.column) })),
|
|
138
|
+
// By size, the engine keeps the largest when the limit cuts the result; a split chart is put in order from its totals afterwards.
|
|
139
|
+
sorts: type === "pie" || (chartSort(input) === "value" && !splitBy)
|
|
140
|
+
? [{ column: aggregated[0].column, direction: SortDirection.DESC }]
|
|
141
|
+
: [{ column: x, direction: SortDirection.ASC }],
|
|
142
|
+
page: { limit },
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The bin width for `bins` bins over the lowest and highest values the engine
|
|
147
|
+
* found (`lo` and `hi`). Read with the column's type: a DECIMAL arrives as its
|
|
148
|
+
* digits without the point, and read as a plain number it widens the range a
|
|
149
|
+
* hundredfold or more, putting every value in one bin.
|
|
150
|
+
*/
|
|
151
|
+
export function rangeBinWidth(table, bins) {
|
|
152
|
+
const read = (name) => {
|
|
153
|
+
const field = table.schema.fields.find((f) => f.name === name);
|
|
154
|
+
const value = table.getChild(name)?.get(0);
|
|
155
|
+
return field ? numericValue(value, field.type) : null;
|
|
156
|
+
};
|
|
157
|
+
const lo = read("lo");
|
|
158
|
+
const hi = read("hi");
|
|
159
|
+
return lo === null || hi === null ? 1 : niceBinWidth(lo, hi, bins);
|
|
160
|
+
}
|
|
161
|
+
export function Chart(props) {
|
|
162
|
+
const { sourceId, sql, type, x, xGrain, xBinWidth, xBins, y, splitBy, filters, parameters, timeTravel, notBefore, limit = 5000, height = 320 } = props;
|
|
163
|
+
const dataSource = useDataSource(props.dataSource);
|
|
164
|
+
const theme = useOptionalTheme();
|
|
165
|
+
const element = useRef(null);
|
|
166
|
+
const [state, setState] = useState({ loading: true });
|
|
167
|
+
const outputs = useMemo(() => measureOutputs(y), [JSON.stringify(y)]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
168
|
+
const key = JSON.stringify([sourceId, sql, type, x, xGrain, xBinWidth, xBins, y, splitBy, filters, parameters, timeTravel, notBefore, limit, props.sort], (_, v) => typeof v === "bigint" ? `${v}n` : v);
|
|
169
|
+
useEffect(() => {
|
|
170
|
+
const controller = new AbortController();
|
|
171
|
+
const call = { signal: controller.signal };
|
|
172
|
+
setState((previous) => ({ ...previous, loading: true, error: undefined }));
|
|
173
|
+
const aggregated = outputs.some((o) => o.measure.aggregate || o.measure.expression);
|
|
174
|
+
const load = async () => {
|
|
175
|
+
let binWidth = xGrain ? undefined : xBinWidth;
|
|
176
|
+
if (aggregated && !xGrain && !binWidth && xBins) {
|
|
177
|
+
// The bin width comes from the column's range, which the engine works out.
|
|
178
|
+
const range = await collect(dataSource.execute({
|
|
179
|
+
sourceId,
|
|
180
|
+
timeTravel,
|
|
181
|
+
notBefore,
|
|
182
|
+
query: {
|
|
183
|
+
baseSql: sql,
|
|
184
|
+
filters,
|
|
185
|
+
parameters,
|
|
186
|
+
aggregates: [
|
|
187
|
+
{ function: AggregateFunction.MIN, column: x, alias: "lo" },
|
|
188
|
+
{ function: AggregateFunction.MAX, column: x, alias: "hi" },
|
|
189
|
+
],
|
|
190
|
+
},
|
|
191
|
+
}, call));
|
|
192
|
+
binWidth = rangeBinWidth(range.table, xBins);
|
|
193
|
+
}
|
|
194
|
+
const sort = chartSort({ type, xGrain, binWidth, sort: props.sort, y });
|
|
195
|
+
const query = buildChartQuery({ sql, type, x, xGrain, binWidth, y, splitBy, filters, parameters, limit, sort });
|
|
196
|
+
const result = await collect(dataSource.execute({ sourceId, timeTravel, notBefore, query }, call));
|
|
197
|
+
const fields = result.table.schema.fields;
|
|
198
|
+
const columns = fields.map((_, i) => result.table.getChildAt(i));
|
|
199
|
+
const rows = Array.from({ length: result.table.numRows }, (_, r) => Object.fromEntries(fields.map((f, c) => [f.name, chartValue(columns[c].get(r), f.type)])));
|
|
200
|
+
return { fields, rows, sort, cut: rows.length < limit ? undefined : aggregated ? "first" : "sample" };
|
|
201
|
+
};
|
|
202
|
+
load()
|
|
203
|
+
.then((loaded) => {
|
|
204
|
+
if (!controller.signal.aborted)
|
|
205
|
+
setState({ loaded, loading: false });
|
|
206
|
+
})
|
|
207
|
+
.catch((error) => {
|
|
208
|
+
if (!controller.signal.aborted)
|
|
209
|
+
setState({ error: messageOf(error), loading: false });
|
|
210
|
+
});
|
|
211
|
+
return () => controller.abort();
|
|
212
|
+
}, [dataSource, key]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
213
|
+
const onPointClick = useRef(props.onPointClick);
|
|
214
|
+
onPointClick.current = props.onPointClick;
|
|
215
|
+
const mode = theme?.resolvedMode ?? "light";
|
|
216
|
+
const themeDocument = theme?.theme ?? defaultTheme;
|
|
217
|
+
const { stacked, legend, xTitle, yTitle, yRightTitle, yFormat, splitSlots, horizontal } = props;
|
|
218
|
+
const palette = useMemo(() => resolveColors(themeDocument[mode], themeDocument.charts?.[mode]).series, [themeDocument, mode]);
|
|
219
|
+
const slotsKey = JSON.stringify(splitSlots ?? null);
|
|
220
|
+
const option = useMemo(() => {
|
|
221
|
+
if (!state.loaded)
|
|
222
|
+
return undefined;
|
|
223
|
+
const slotColor = (slot) => (slot === undefined ? undefined : palette[slot - 1]);
|
|
224
|
+
const base = buildChartOption({
|
|
225
|
+
type,
|
|
226
|
+
x,
|
|
227
|
+
splitBy,
|
|
228
|
+
series: outputs.map((o) => ({ column: o.column, label: o.label, type: o.measure.type, axis: o.measure.axis, stack: o.measure.stack, color: slotColor(o.measure.slot) })),
|
|
229
|
+
splitColors: splitSlots ? Object.fromEntries(Object.entries(splitSlots).map(([value, slot]) => [value, slotColor(slot) ?? ""]).filter(([, color]) => color !== "")) : undefined,
|
|
230
|
+
fields: state.loaded.fields,
|
|
231
|
+
rows: state.loaded.rows,
|
|
232
|
+
sort: state.loaded.sort,
|
|
233
|
+
stacked,
|
|
234
|
+
legend,
|
|
235
|
+
xTitle,
|
|
236
|
+
yTitle,
|
|
237
|
+
yRightTitle,
|
|
238
|
+
yFormat,
|
|
239
|
+
horizontal,
|
|
240
|
+
});
|
|
241
|
+
// People who ask for less motion get none: the chart appears in place.
|
|
242
|
+
const still = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
243
|
+
const withAria = { aria: { enabled: true }, ...(still ? { animation: false } : {}), ...base };
|
|
244
|
+
return props.option ? props.option(withAria) : withAria;
|
|
245
|
+
}, [state.loaded, type, x, splitBy, outputs, props.option, stacked, legend, xTitle, yTitle, yRightTitle, yFormat, horizontal, palette, slotsKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
246
|
+
const seriesCount = type !== "pie" && Array.isArray(option?.series) ? option.series.length : 0;
|
|
247
|
+
useEffect(() => {
|
|
248
|
+
if (!element.current || !option)
|
|
249
|
+
return;
|
|
250
|
+
const chart = echarts.init(element.current, echartsTheme(themeDocument, mode));
|
|
251
|
+
chart.setOption(option);
|
|
252
|
+
chart.on("click", (event) => {
|
|
253
|
+
const row = event.data !== null && typeof event.data === "object" ? event.data : undefined;
|
|
254
|
+
// Pie slices carry a name; other series carry the dataset row.
|
|
255
|
+
const at = row && x in row ? row[x] : (event.name ?? null);
|
|
256
|
+
const amount = row && typeof row.value === "number" ? row.value : typeof event.value === "number" ? event.value : null;
|
|
257
|
+
onPointClick.current?.({ x: at, series: event.seriesName ?? "", value: amount });
|
|
258
|
+
});
|
|
259
|
+
const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(() => chart.resize());
|
|
260
|
+
observer?.observe(element.current);
|
|
261
|
+
return () => {
|
|
262
|
+
observer?.disconnect();
|
|
263
|
+
chart.dispose();
|
|
264
|
+
};
|
|
265
|
+
}, [option, themeDocument, mode]);
|
|
266
|
+
// Advice is worked out from what was actually drawn, so it follows filters and the data.
|
|
267
|
+
const advice = props.advice === false || !state.loaded ? [] : chartAdvice(drawnShape({ type, x, y, stacked, seriesCount, binned: Boolean(xGrain || xBinWidth || xBins), fields: state.loaded.fields, rows: state.loaded.rows }));
|
|
268
|
+
// Rows a time or number axis cannot place are left out, and the chart says so with what they hold.
|
|
269
|
+
const unplaced = state.loaded ? rowsWithoutX({ type, x, series: outputs.map((o) => ({ column: o.column, label: o.label, type: o.measure.type })), fields: state.loaded.fields, rows: state.loaded.rows }) : [];
|
|
270
|
+
const unplacedDetail = unplaced.length === 1
|
|
271
|
+
? ` (${outputs.map((o) => `${o.label}: ${typeof unplaced[0][o.column] === "number" ? numberFormat().format(unplaced[0][o.column]) : String(unplaced[0][o.column] ?? "–")}`).join(", ")})`
|
|
272
|
+
: "";
|
|
273
|
+
const nothingDrawn = !!state.loaded && state.loaded.rows.length === unplaced.length;
|
|
274
|
+
const description = props.label ?? text("chart.description", { type, measures: outputs.map((o) => o.label).join(", "), x });
|
|
275
|
+
return (_jsxs("figure", { className: ["sf-chart", props.className].filter(Boolean).join(" "), "aria-busy": state.loading, children: [state.error ? (_jsx("p", { className: "sf-chart-message", role: "alert", "data-error": state.error, style: { minHeight: height }, children: props.errorMessage ?? state.error })) : nothingDrawn ? (_jsx("p", { className: "sf-chart-message", style: { minHeight: height }, children: props.emptyMessage ?? text("chart.empty") })) : (_jsx("div", { ref: element, className: "sf-chart-canvas", role: "img", "aria-label": description, style: { height } })), unplaced.length > 0 && _jsx("figcaption", { className: "sf-chart-note", children: text("chart.missingX", { x, detail: unplacedDetail }) }), seriesCount > palette.length && (_jsx("figcaption", { className: "sf-chart-note", children: text("chart.coloursRepeat", { count: seriesCount, colours: palette.length }) })), advice.map((item) => (_jsx("figcaption", { className: "sf-chart-note sf-chart-advice", role: "note", children: text("chart.advice", { message: item.message, instead: item.instead }) }, item.rule))), state.loaded?.cut && (_jsx("figcaption", { className: "sf-chart-note", children: state.loaded.cut === "sample"
|
|
276
|
+
? text("chart.sampleNote", { count: numberFormat().format(limit) })
|
|
277
|
+
: text(state.loaded.sort === "value" ? "chart.largestNote" : "chart.firstNote", { count: numberFormat().format(limit) }) }))] }));
|
|
278
|
+
}
|
|
279
|
+
//# sourceMappingURL=Chart.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Chart.js","sourceRoot":"","sources":["../../src/chart/Chart.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAmB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGnG,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,SAAS,EAAwB,MAAM,oBAAoB,CAAC;AACvG,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EA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easureExpression, writeMeasure } from \"@surfaces-ui/data\";\nimport type { MessageInitShape } from \"@bufbuild/protobuf\";\nimport type { DataType } from \"apache-arrow\";\nimport { AggregateFunction, SortDirection, TimeGrain, type ViewQuerySchema } from \"@surfaces-ui/proto\";\nimport { defaultTheme, echartsTheme, resolveColors } from \"@surfaces-ui/tokens\";\nimport { BarChart, LineChart, PieChart, ScatterChart } from \"echarts/charts\";\nimport {\n AriaComponent,\n DataZoomComponent,\n DatasetComponent,\n GridComponent,\n LegendComponent,\n TooltipComponent,\n} from \"echarts/components\";\nimport * as echarts from \"echarts/core\";\nimport { CanvasRenderer } from \"echarts/renderers\";\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useDataSource } from \"../data/DataSourceProvider.js\";\nimport type { DataMessages } from \"../data/messages.js\";\nimport { chartValue, numericValue } from \"../data/format.js\";\nimport { label as text, numberFormat } from \"../locale/locale.js\";\nimport { type FilterInit, type TimeTravelInit, type ValueInit, messageOf } from \"../data/useRowWindow.js\";\nimport { useOptionalTheme } from \"../theme/ThemeProvider.js\";\nimport { type ChartShape, chartAdvice } from \"./advice.js\";\nimport { type AxisFormat, type ChartOptionInput, type ChartType, type LegendPlacement, type SeriesType, buildChartOption, isOrdered, niceBinWidth, rowsWithoutX } from \"./option.js\";\n\necharts.use([\n BarChart,\n LineChart,\n PieChart,\n ScatterChart,\n AriaComponent,\n DataZoomComponent,\n DatasetComponent,\n GridComponent,\n LegendComponent,\n TooltipComponent,\n CanvasRenderer,\n]);\n\nexport type ChartAggregate =\n | \"sum\"\n | \"avg\"\n | \"count\"\n | \"count_distinct\"\n | \"min\"\n | \"max\"\n | \"median\"\n | \"stddev\"\n | \"variance\"\n | \"percentile\";\n\nexport type ChartGrain = \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"quarter\" | \"year\";\n\nexport interface ChartMeasure {\n /** Column to plot. Optional only for `count`, which then counts rows. */\n column?: string;\n /**\n * Summarise the column per x value in the engine. Without it the chart\n * plots raw rows: all of them when the result is small, otherwise a random\n * sample.\n */\n aggregate?: ChartAggregate;\n /** For `percentile`: a fraction from 0 to 1. Defaults to 0.9. */\n percentile?: number;\n /**\n * A calculation instead of a column: arithmetic over the measures named in\n * `terms`, such as `refunded / revenue`. The engine works it out after\n * summarising, so it is right for any number of rows and can be sorted by.\n */\n expression?: string;\n /** The measures an `expression` names, by the name it uses for them. */\n terms?: Record<string, { column?: string; aggregate: ChartAggregate; percentile?: number }>;\n /** Name for the legend. Defaults to e.g. \"sum of amount\". */\n label?: string;\n /** Draw this series differently from the chart's `type`, e.g. a line over bars. */\n type?: SeriesType;\n /** The y axis this series is measured on. Use \"right\" for a measure on another scale. Defaults to \"left\". */\n axis?: \"left\" | \"right\";\n /** Series with the same stack name are stacked on each other. */\n stack?: string;\n /**\n * Which of the theme's series colours to use, counting from 1. Give a\n * measure the same slot wherever it appears and it keeps its colour across\n * charts. Without it, series take the theme's colours in order.\n */\n slot?: number;\n}\n\nexport interface ChartProps extends DataMessages {\n sourceId: string;\n /** The base SQL. Grouping and aggregation are applied around it by the backend. */\n sql: string;\n /** How series are drawn unless a measure sets its own `type`. */\n type: ChartType;\n /** Column for the x axis, or the slices of a pie. */\n x: string;\n /** Group a date or time x column into buckets of this size, so a time series has one point per bucket. */\n xGrain?: ChartGrain;\n /** Group a numeric x column into bins of this width (a histogram). */\n xBinWidth?: number;\n /** Group a numeric x column into about this many bins; the width is chosen from the column's range. */\n xBins?: number;\n /** One entry per series. */\n y: ChartMeasure[];\n /** Split each measure into one series per distinct value of this column. */\n splitBy?: string;\n /**\n * The theme colour slot for particular values of `splitBy`, by value, e.g.\n * `{ Europe: 1, \"Asia Pacific\": 2 }`. A value then keeps its colour when a\n * filter removes other values.\n */\n splitSlots?: Record<string, number>;\n /** Stack the series. */\n stacked?: boolean;\n /**\n * The order of bars. \"value\" (the default for a bar chart over categories)\n * puts the largest first, and with a row limit keeps the largest. \"x\" keeps\n * the order of the x column. Dates, bins and numbers always keep their own order.\n */\n sort?: \"value\" | \"x\";\n /** Show advice when the chart's shape is one that misleads or cannot be read. Defaults to true. */\n advice?: boolean;\n /** Where the legend goes. Defaults to \"top\" when there is more than one series. */\n legend?: LegendPlacement;\n /** Axis titles. */\n xTitle?: string;\n yTitle?: string;\n yRightTitle?: string;\n /**\n * Turn the bars on their side: categories down the left, largest at the\n * top, values along the bottom. Easier to read with long category names or\n * many of them. Only for bars on one scale; ignored otherwise.\n */\n horizontal?: boolean;\n /** How the left axis writes its numbers: \"percent\" for a rate (6%, not 0.06), \"currency\" for money. Labels only; the values are untouched. */\n yFormat?: AxisFormat;\n filters?: FilterInit[];\n parameters?: ValueInit[];\n timeTravel?: TimeTravelInit;\n /** ISO 8601 time of the run this chart belongs to; see `RowWindowQuery.notBefore`. */\n notBefore?: string;\n /** Most points fetched. Defaults to 5,000; the chart says when it was cut off or sampled. */\n limit?: number;\n /** Height in px. Defaults to 320. */\n height?: number;\n /**\n * Called when a point, bar or slice is clicked, with its x value and\n * series name. Use it to filter other views (cross-filtering).\n */\n onPointClick?(point: { x: string | number | null; series: string; value: number | null }): void;\n /** Adjust the generated ECharts option before it is applied. */\n option?(option: Record<string, unknown>): Record<string, unknown>;\n /** Accessible description of what the chart shows. */\n label?: string;\n dataSource?: DataSource;\n className?: string;\n}\n\n/** The contract's function for each aggregate name. */\nexport const AGGREGATE_FUNCTIONS: Record<ChartAggregate, AggregateFunction> = {\n sum: AggregateFunction.SUM,\n avg: AggregateFunction.AVG,\n count: AggregateFunction.COUNT,\n count_distinct: AggregateFunction.COUNT_DISTINCT,\n min: AggregateFunction.MIN,\n max: AggregateFunction.MAX,\n median: AggregateFunction.MEDIAN,\n stddev: AggregateFunction.STDDEV,\n variance: AggregateFunction.VARIANCE,\n percentile: AggregateFunction.PERCENTILE,\n};\n\n/** The contract's grain for each grain name. */\nexport const TIME_GRAINS: Record<ChartGrain, TimeGrain> = {\n minute: TimeGrain.MINUTE,\n hour: TimeGrain.HOUR,\n day: TimeGrain.DAY,\n week: TimeGrain.WEEK,\n month: TimeGrain.MONTH,\n quarter: TimeGrain.QUARTER,\n year: TimeGrain.YEAR,\n};\n\ninterface Loaded extends Pick<ChartOptionInput, \"fields\" | \"rows\"> {\n /** \"first\": more points existed than the limit. \"sample\": the rows are a random sample. */\n cut: \"first\" | \"sample\" | undefined;\n /** How the categories were ordered, so the drawing and the notes agree with the query. */\n sort: \"value\" | \"x\";\n}\n\n/** Output column and label for each measure. */\nexport function measureOutputs(y: ChartMeasure[]): { column: string; label: string; measure: ChartMeasure }[] {\n return y.map((measure, i) => {\n if (measure.expression) return { column: `calc_${i}`, label: measure.label ?? measure.expression, measure };\n if (!measure.aggregate) return { column: measure.column ?? \"\", label: measure.label ?? measure.column ?? \"\", measure };\n const subject = measure.column ?? \"rows\";\n const name =\n measure.aggregate === \"percentile\" ? `p${Math.round((measure.percentile ?? 0.9) * 100)}` : measure.aggregate.replace(\"_\", \" \");\n return {\n column: `${measure.aggregate}_${measure.column ?? \"rows\"}_${i}`.replace(/\\W+/g, \"_\"),\n label: measure.label ?? (measure.aggregate === \"count\" && !measure.column ? \"count\" : `${name} of ${subject}`),\n measure,\n };\n });\n}\n\n/** A calculation with each name given a prefix, so its terms are its own. One that cannot be read is sent as it is, and the engine says why. */\nfunction termExpression(expression: string, prefix: string): string {\n try {\n return writeMeasure(parseMeasureExpression(expression), { name: (name) => `${prefix}_${name}`, divide: (left, right) => `(${left} / ${right})` });\n } catch {\n return expression;\n }\n}\n\nexport type ChartQueryInput = Pick<ChartProps, \"sql\" | \"type\" | \"x\" | \"xGrain\" | \"y\" | \"splitBy\" | \"filters\" | \"parameters\" | \"sort\"> & {\n /** Bin width for a numeric x, already resolved from `xBinWidth` or `xBins`. */\n binWidth?: number;\n limit: number;\n};\n\n/** The shape of a loaded chart, in the terms `chartAdvice` checks. Nothing drawn gives no advice. */\nexport function drawnShape(input: Pick<ChartProps, \"type\" | \"x\" | \"y\" | \"stacked\"> & Pick<ChartOptionInput, \"fields\" | \"rows\"> & { seriesCount: number; binned: boolean }): ChartShape {\n if (input.rows.length === 0) return { type: input.type, categories: 0, series: 0 };\n return {\n type: input.type,\n categories: new Set(input.rows.map((row) => row[input.x])).size,\n series: input.type === \"pie\" ? 1 : input.seriesCount,\n stacked: input.stacked,\n rightAxis: input.y.some((m) => m.axis === \"right\"),\n orderedX: input.binned || isOrdered(input.fields.find((f) => f.name === input.x)),\n };\n}\n\n/** How a chart's categories are ordered when not told: bars by size, everything else along x. */\nexport function chartSort(input: Pick<ChartQueryInput, \"type\" | \"xGrain\" | \"binWidth\" | \"sort\" | \"y\">): \"value\" | \"x\" {\n if (input.xGrain || input.binWidth) return \"x\";\n return input.sort ?? (input.type === \"bar\" && input.y.every((m) => (m.type ?? \"bar\") === \"bar\") ? \"value\" : \"x\");\n}\n\n/**\n * The query a chart sends. With aggregated measures the engine groups by x\n * (bucketed by time grain or bin width when asked) and by the split column;\n * otherwise it returns a random sample of raw rows.\n */\nexport function buildChartQuery(input: ChartQueryInput): MessageInitShape<typeof ViewQuerySchema> {\n const { sql, type, x, y, splitBy, filters, parameters, limit } = input;\n const outputs = measureOutputs(y);\n const aggregated = outputs.filter((o) => o.measure.aggregate || o.measure.expression);\n if (aggregated.length === 0) {\n const columns = [...new Set([x, ...(splitBy ? [splitBy] : []), ...outputs.map((o) => o.column)])];\n return { baseSql: sql, filters, parameters, columns, sample: { rows: limit } };\n }\n const bucket = input.xGrain\n ? { column: x, by: { case: \"grain\" as const, value: TIME_GRAINS[input.xGrain] } }\n : input.binWidth\n ? { column: x, by: { case: \"binWidth\" as const, value: input.binWidth } }\n : undefined;\n return {\n baseSql: sql,\n filters,\n parameters,\n groupBy: [...(bucket ? [] : [x]), ...(splitBy ? [splitBy] : [])],\n buckets: bucket ? [bucket] : [],\n aggregates: aggregated.flatMap((o) =>\n o.measure.expression\n ? // A calculation's terms are aggregates of their own, named after the calculation so two calculations cannot collide.\n Object.entries(o.measure.terms ?? {}).map(([name, term]) => ({\n function: AGGREGATE_FUNCTIONS[term.aggregate],\n column: term.column ?? \"\",\n alias: `${o.column}_${name}`,\n percentile: term.aggregate === \"percentile\" ? (term.percentile ?? 0.9) : 0,\n }))\n : [\n {\n function: AGGREGATE_FUNCTIONS[o.measure.aggregate!],\n column: o.measure.column ?? \"\",\n alias: o.column,\n percentile: o.measure.aggregate === \"percentile\" ? (o.measure.percentile ?? 0.9) : 0,\n },\n ],\n ),\n derived: aggregated.filter((o) => o.measure.expression).map((o) => ({ alias: o.column, expression: termExpression(o.measure.expression!, o.column) })),\n // By size, the engine keeps the largest when the limit cuts the result; a split chart is put in order from its totals afterwards.\n sorts:\n type === \"pie\" || (chartSort(input) === \"value\" && !splitBy)\n ? [{ column: aggregated[0]!.column, direction: SortDirection.DESC }]\n : [{ column: x, direction: SortDirection.ASC }],\n page: { limit },\n };\n}\n\n/**\n * An ECharts chart bound to a query. With aggregated measures the engine\n * groups the data, so the chart receives one row per point however large the\n * table is. Each measure is a series and can have its own type and y axis,\n * which makes compound charts (bars with a line, two scales). Colours, fonts\n * and radius follow the theme.\n */\n/** The columns a range query returns, as Arrow gives them: each column's values and its type. */\ninterface RangeTable {\n schema: { fields: { name: string; type: DataType }[] };\n getChild(name: string): { get(index: number): unknown } | null;\n}\n\n/**\n * The bin width for `bins` bins over the lowest and highest values the engine\n * found (`lo` and `hi`). Read with the column's type: a DECIMAL arrives as its\n * digits without the point, and read as a plain number it widens the range a\n * hundredfold or more, putting every value in one bin.\n */\nexport function rangeBinWidth(table: RangeTable, bins: number): number {\n const read = (name: string) => {\n const field = table.schema.fields.find((f) => f.name === name);\n const value = table.getChild(name)?.get(0);\n return field ? numericValue(value, field.type) : null;\n };\n const lo = read(\"lo\");\n const hi = read(\"hi\");\n return lo === null || hi === null ? 1 : niceBinWidth(lo, hi, bins);\n}\n\nexport function Chart(props: ChartProps) {\n const { sourceId, sql, type, x, xGrain, xBinWidth, xBins, y, splitBy, filters, parameters, timeTravel, notBefore, limit = 5000, height = 320 } = props;\n const dataSource = useDataSource(props.dataSource);\n const theme = useOptionalTheme();\n const element = useRef<HTMLDivElement>(null);\n const [state, setState] = useState<{ loaded?: Loaded; error?: string; loading: boolean }>({ loading: true });\n\n const outputs = useMemo(() => measureOutputs(y), [JSON.stringify(y)]); // eslint-disable-line react-hooks/exhaustive-deps\n const key = JSON.stringify([sourceId, sql, type, x, xGrain, xBinWidth, xBins, y, splitBy, filters, parameters, timeTravel, notBefore, limit, props.sort], (_, v) =>\n typeof v === \"bigint\" ? `${v}n` : v,\n );\n\n useEffect(() => {\n const controller = new AbortController();\n const call = { signal: controller.signal };\n setState((previous) => ({ ...previous, loading: true, error: undefined }));\n const aggregated = outputs.some((o) => o.measure.aggregate || o.measure.expression);\n const load = async (): Promise<Loaded> => {\n let binWidth = xGrain ? undefined : xBinWidth;\n if (aggregated && !xGrain && !binWidth && xBins) {\n // The bin width comes from the column's range, which the engine works out.\n const range = await collect(\n dataSource.execute(\n {\n sourceId,\n timeTravel,\n notBefore,\n query: {\n baseSql: sql,\n filters,\n parameters,\n aggregates: [\n { function: AggregateFunction.MIN, column: x, alias: \"lo\" },\n { function: AggregateFunction.MAX, column: x, alias: \"hi\" },\n ],\n },\n },\n call,\n ),\n );\n binWidth = rangeBinWidth(range.table, xBins);\n }\n const sort = chartSort({ type, xGrain, binWidth, sort: props.sort, y });\n const query = buildChartQuery({ sql, type, x, xGrain, binWidth, y, splitBy, filters, parameters, limit, sort });\n const result = await collect(dataSource.execute({ sourceId, timeTravel, notBefore, query }, call));\n const fields = result.table.schema.fields;\n const columns = fields.map((_, i) => result.table.getChildAt(i)!);\n const rows = Array.from({ length: result.table.numRows }, (_, r) =>\n Object.fromEntries(fields.map((f, c) => [f.name, chartValue(columns[c]!.get(r), f.type)])),\n );\n return { fields, rows, sort, cut: rows.length < limit ? undefined : aggregated ? \"first\" : \"sample\" };\n };\n load()\n .then((loaded) => {\n if (!controller.signal.aborted) setState({ loaded, loading: false });\n })\n .catch((error: unknown) => {\n if (!controller.signal.aborted) setState({ error: messageOf(error), loading: false });\n });\n return () => controller.abort();\n }, [dataSource, key]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const onPointClick = useRef(props.onPointClick);\n onPointClick.current = props.onPointClick;\n const mode = theme?.resolvedMode ?? \"light\";\n const themeDocument = theme?.theme ?? defaultTheme;\n const { stacked, legend, xTitle, yTitle, yRightTitle, yFormat, splitSlots, horizontal } = props;\n const palette = useMemo(() => resolveColors(themeDocument[mode], themeDocument.charts?.[mode]).series, [themeDocument, mode]);\n const slotsKey = JSON.stringify(splitSlots ?? null);\n const option = useMemo(() => {\n if (!state.loaded) return undefined;\n const slotColor = (slot: number | undefined) => (slot === undefined ? undefined : palette[slot - 1]);\n const base = buildChartOption({\n type,\n x,\n splitBy,\n series: outputs.map((o) => ({ column: o.column, label: o.label, type: o.measure.type, axis: o.measure.axis, stack: o.measure.stack, color: slotColor(o.measure.slot) })),\n splitColors: splitSlots ? Object.fromEntries(Object.entries(splitSlots).map(([value, slot]) => [value, slotColor(slot) ?? \"\"]).filter(([, color]) => color !== \"\")) : undefined,\n fields: state.loaded.fields,\n rows: state.loaded.rows,\n sort: state.loaded.sort,\n stacked,\n legend,\n xTitle,\n yTitle,\n yRightTitle,\n yFormat,\n horizontal,\n });\n // People who ask for less motion get none: the chart appears in place.\n const still = typeof matchMedia === \"function\" && matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n const withAria = { aria: { enabled: true }, ...(still ? { animation: false } : {}), ...base };\n return props.option ? props.option(withAria) : withAria;\n }, [state.loaded, type, x, splitBy, outputs, props.option, stacked, legend, xTitle, yTitle, yRightTitle, yFormat, horizontal, palette, slotsKey]); // eslint-disable-line react-hooks/exhaustive-deps\n const seriesCount = type !== \"pie\" && Array.isArray((option as { series?: unknown[] } | undefined)?.series) ? (option as { series: unknown[] }).series.length : 0;\n\n useEffect(() => {\n if (!element.current || !option) return;\n const chart = echarts.init(element.current, echartsTheme(themeDocument, mode));\n chart.setOption(option);\n chart.on(\"click\", (event: { seriesName?: string; name?: string; data?: unknown; value?: unknown }) => {\n const row = event.data !== null && typeof event.data === \"object\" ? (event.data as Record<string, string | number | null>) : undefined;\n // Pie slices carry a name; other series carry the dataset row.\n const at = row && x in row ? row[x]! : (event.name ?? null);\n const amount = row && typeof row.value === \"number\" ? row.value : typeof event.value === \"number\" ? event.value : null;\n onPointClick.current?.({ x: at, series: event.seriesName ?? \"\", value: amount });\n });\n const observer = typeof ResizeObserver === \"undefined\" ? undefined : new ResizeObserver(() => chart.resize());\n observer?.observe(element.current);\n return () => {\n observer?.disconnect();\n chart.dispose();\n };\n }, [option, themeDocument, mode]);\n\n // Advice is worked out from what was actually drawn, so it follows filters and the data.\n const advice = props.advice === false || !state.loaded ? [] : chartAdvice(drawnShape({ type, x, y, stacked, seriesCount, binned: Boolean(xGrain || xBinWidth || xBins), fields: state.loaded.fields, rows: state.loaded.rows }));\n\n // Rows a time or number axis cannot place are left out, and the chart says so with what they hold.\n const unplaced = state.loaded ? rowsWithoutX({ type, x, series: outputs.map((o) => ({ column: o.column, label: o.label, type: o.measure.type })), fields: state.loaded.fields, rows: state.loaded.rows }) : [];\n const unplacedDetail =\n unplaced.length === 1\n ? ` (${outputs.map((o) => `${o.label}: ${typeof unplaced[0]![o.column] === \"number\" ? numberFormat().format(unplaced[0]![o.column] as number) : String(unplaced[0]![o.column] ?? \"–\")}`).join(\", \")})`\n : \"\";\n const nothingDrawn = !!state.loaded && state.loaded.rows.length === unplaced.length;\n\n const description = props.label ?? text(\"chart.description\", { type, measures: outputs.map((o) => o.label).join(\", \"), x });\n return (\n <figure className={[\"sf-chart\", props.className].filter(Boolean).join(\" \")} aria-busy={state.loading}>\n {state.error ? (\n <p className=\"sf-chart-message\" role=\"alert\" data-error={state.error} style={{ minHeight: height }}>\n {props.errorMessage ?? state.error}\n </p>\n ) : nothingDrawn ? (\n <p className=\"sf-chart-message\" style={{ minHeight: height }}>\n {props.emptyMessage ?? text(\"chart.empty\")}\n </p>\n ) : (\n <div ref={element} className=\"sf-chart-canvas\" role=\"img\" aria-label={description} style={{ height }} />\n )}\n {unplaced.length > 0 && <figcaption className=\"sf-chart-note\">{text(\"chart.missingX\", { x, detail: unplacedDetail })}</figcaption>}\n {seriesCount > palette.length && (\n <figcaption className=\"sf-chart-note\">\n {text(\"chart.coloursRepeat\", { count: seriesCount, colours: palette.length })}\n </figcaption>\n )}\n {advice.map((item) => (\n <figcaption key={item.rule} className=\"sf-chart-note sf-chart-advice\" role=\"note\">\n {text(\"chart.advice\", { message: item.message, instead: item.instead })}\n </figcaption>\n ))}\n {state.loaded?.cut && (\n <figcaption className=\"sf-chart-note\">\n {state.loaded.cut === \"sample\"\n ? text(\"chart.sampleNote\", { count: numberFormat().format(limit) })\n : text(state.loaded.sort === \"value\" ? \"chart.largestNote\" : \"chart.firstNote\", { count: numberFormat().format(limit) })}\n </figcaption>\n )}\n </figure>\n );\n}\n"]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { DataSource } from "@surfaces-ui/data";
|
|
2
|
+
import type { DataMessages } from "../data/messages.js";
|
|
3
|
+
import type { FilterInit } from "../data/useRowWindow.js";
|
|
4
|
+
import { type MetricProps } from "../metric/Metric.js";
|
|
5
|
+
import type { ChartAggregate, ChartGrain } from "./Chart.js";
|
|
6
|
+
export interface SparklineProps extends DataMessages {
|
|
7
|
+
sourceId: string;
|
|
8
|
+
sql: string;
|
|
9
|
+
/** The date or time column the line runs along. */
|
|
10
|
+
x: string;
|
|
11
|
+
grain: ChartGrain;
|
|
12
|
+
column?: string;
|
|
13
|
+
aggregate: ChartAggregate;
|
|
14
|
+
label: string;
|
|
15
|
+
format?: MetricProps["format"];
|
|
16
|
+
currency?: string;
|
|
17
|
+
/** Most recent buckets to draw. Defaults to 30. */
|
|
18
|
+
points?: number;
|
|
19
|
+
filters?: FilterInit[];
|
|
20
|
+
notBefore?: string;
|
|
21
|
+
dataSource?: DataSource;
|
|
22
|
+
className?: string;
|
|
23
|
+
}
|
|
24
|
+
/** Points for a line through `values` in a box, with gaps where a value is missing. */
|
|
25
|
+
export declare function sparklinePoints(values: (number | null)[], width?: number, height?: number, pad?: number): {
|
|
26
|
+
x: number;
|
|
27
|
+
y: number;
|
|
28
|
+
value: number;
|
|
29
|
+
}[];
|
|
30
|
+
/**
|
|
31
|
+
* A word-sized line next to its latest value: the trend without axes, grid
|
|
32
|
+
* or legend. The low and high points are marked, and the same facts are
|
|
33
|
+
* given in words for people who cannot see the line.
|
|
34
|
+
*/
|
|
35
|
+
export declare function Sparkline(props: SparklineProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useDataSource } from "../data/DataSourceProvider.js";
|
|
3
|
+
import { label as text } from "../locale/locale.js";
|
|
4
|
+
import { formatMetric } from "../metric/Metric.js";
|
|
5
|
+
import { useMeasure } from "../metric/useMeasure.js";
|
|
6
|
+
const WIDTH = 120;
|
|
7
|
+
const HEIGHT = 28;
|
|
8
|
+
const PAD = 3;
|
|
9
|
+
/** Points for a line through `values` in a box, with gaps where a value is missing. */
|
|
10
|
+
export function sparklinePoints(values, width = WIDTH, height = HEIGHT, pad = PAD) {
|
|
11
|
+
const known = values.filter((v) => v !== null);
|
|
12
|
+
if (known.length === 0)
|
|
13
|
+
return [];
|
|
14
|
+
const low = Math.min(...known);
|
|
15
|
+
const high = Math.max(...known);
|
|
16
|
+
const span = high - low || 1;
|
|
17
|
+
const step = values.length > 1 ? (width - pad * 2) / (values.length - 1) : 0;
|
|
18
|
+
return values.flatMap((value, i) => (value === null ? [] : [{ x: pad + i * step, y: high === low ? height / 2 : pad + (1 - (value - low) / span) * (height - pad * 2), value }]));
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A word-sized line next to its latest value: the trend without axes, grid
|
|
22
|
+
* or legend. The low and high points are marked, and the same facts are
|
|
23
|
+
* given in words for people who cannot see the line.
|
|
24
|
+
*/
|
|
25
|
+
export function Sparkline(props) {
|
|
26
|
+
const { sourceId, sql, x, grain, column, aggregate, label, format, currency, points = 30, filters, notBefore } = props;
|
|
27
|
+
const dataSource = useDataSource(props.dataSource);
|
|
28
|
+
const state = useMeasure(dataSource, { sourceId, sql, column, aggregate, filters, notBefore, x, grain, points });
|
|
29
|
+
const line = sparklinePoints(state.values ?? []);
|
|
30
|
+
const write = (value) => formatMetric(value, format, currency);
|
|
31
|
+
const last = line.at(-1);
|
|
32
|
+
const low = line.reduce((a, p) => (!a || p.value < a.value ? p : a), undefined);
|
|
33
|
+
const high = line.reduce((a, p) => (!a || p.value > a.value ? p : a), undefined);
|
|
34
|
+
const summary = last && low && high && line[0] ? text("sparkline.summary", { label, now: write(last.value), first: write(line[0].value), low: write(low.value), high: write(high.value), count: line.length, grain }) : props.emptyMessage ? `${label}: ${props.emptyMessage}` : text("sparkline.empty", { label });
|
|
35
|
+
return (_jsxs("span", { className: ["sf-spark", props.className].filter(Boolean).join(" "), "aria-busy": state.loading, children: [_jsx("span", { className: "sf-spark-label", children: label }), state.error ? (_jsx("span", { className: "sf-metric-error", role: "alert", "data-error": state.error, children: props.errorMessage ?? state.error })) : (_jsxs(_Fragment, { children: [_jsxs("svg", { className: "sf-spark-line", viewBox: `0 0 ${WIDTH} ${HEIGHT}`, width: WIDTH, height: HEIGHT, role: "img", "aria-label": summary, children: [line.length > 1 && _jsx("polyline", { points: line.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ") }), low && high && low !== high && (_jsxs(_Fragment, { children: [_jsx("circle", { className: "sf-spark-extreme", cx: low.x, cy: low.y, r: 1.8 }), _jsx("circle", { className: "sf-spark-extreme", cx: high.x, cy: high.y, r: 1.8 })] })), last && _jsx("circle", { className: "sf-spark-last", cx: last.x, cy: last.y, r: 2.4 })] }), _jsx("span", { className: "sf-spark-value", children: last ? write(last.value) : state.loading ? text("metric.loading") : (props.emptyMessage ?? text("metric.none")) })] }))] }));
|
|
36
|
+
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AC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,IAAI,IAAI,CAAC,aAAa,CAAC,CAAC,GAAQ,IACxJ,CACJ,IACI,CACR,CAAC;AACJ,CAAC","sourcesContent":["import type { DataSource } from \"@surfaces-ui/data\";\nimport { useDataSource } from \"../data/DataSourceProvider.js\";\nimport type { DataMessages } from \"../data/messages.js\";\nimport type { FilterInit } from \"../data/useRowWindow.js\";\nimport { label as text } from \"../locale/locale.js\";\nimport { type MetricProps, formatMetric } from \"../metric/Metric.js\";\nimport { useMeasure } from \"../metric/useMeasure.js\";\nimport type { ChartAggregate, ChartGrain } from \"./Chart.js\";\n\nexport interface SparklineProps extends DataMessages {\n sourceId: string;\n sql: string;\n /** The date or time column the line runs along. */\n x: string;\n grain: ChartGrain;\n column?: string;\n aggregate: ChartAggregate;\n label: string;\n format?: MetricProps[\"format\"];\n currency?: string;\n /** Most recent buckets to draw. Defaults to 30. */\n points?: number;\n filters?: FilterInit[];\n notBefore?: string;\n dataSource?: DataSource;\n className?: string;\n}\n\nconst WIDTH = 120;\nconst HEIGHT = 28;\nconst PAD = 3;\n\n/** Points for a line through `values` in a box, with gaps where a value is missing. */\nexport function sparklinePoints(values: (number | null)[], width = WIDTH, height = HEIGHT, pad = PAD): { x: number; y: number; value: number }[] {\n const known = values.filter((v): v is number => v !== null);\n if (known.length === 0) return [];\n const low = Math.min(...known);\n const high = Math.max(...known);\n const span = high - low || 1;\n const step = values.length > 1 ? (width - pad * 2) / (values.length - 1) : 0;\n return values.flatMap((value, i) => (value === null ? [] : [{ x: pad + i * step, y: high === low ? height / 2 : pad + (1 - (value - low) / span) * (height - pad * 2), value }]));\n}\n\n/**\n * A word-sized line next to its latest value: the trend without axes, grid\n * or legend. The low and high points are marked, and the same facts are\n * given in words for people who cannot see the line.\n */\nexport function Sparkline(props: SparklineProps) {\n const { sourceId, sql, x, grain, column, aggregate, label, format, currency, points = 30, filters, notBefore } = props;\n const dataSource = useDataSource(props.dataSource);\n const state = useMeasure(dataSource, { sourceId, sql, column, aggregate, filters, notBefore, x, grain, points });\n const line = sparklinePoints(state.values ?? []);\n const write = (value: number) => formatMetric(value, format, currency);\n const last = line.at(-1);\n const low = line.reduce<(typeof line)[number] | undefined>((a, p) => (!a || p.value < a.value ? p : a), undefined);\n const high = line.reduce<(typeof line)[number] | undefined>((a, p) => (!a || p.value > a.value ? p : a), undefined);\n const summary = last && low && high && line[0] ? text(\"sparkline.summary\", { label, now: write(last.value), first: write(line[0].value), low: write(low.value), high: write(high.value), count: line.length, grain }) : props.emptyMessage ? `${label}: ${props.emptyMessage}` : text(\"sparkline.empty\", { label });\n\n return (\n <span className={[\"sf-spark\", props.className].filter(Boolean).join(\" \")} aria-busy={state.loading}>\n <span className=\"sf-spark-label\">{label}</span>\n {state.error ? (\n <span className=\"sf-metric-error\" role=\"alert\" data-error={state.error}>\n {props.errorMessage ?? state.error}\n </span>\n ) : (\n <>\n <svg className=\"sf-spark-line\" viewBox={`0 0 ${WIDTH} ${HEIGHT}`} width={WIDTH} height={HEIGHT} role=\"img\" aria-label={summary}>\n {line.length > 1 && <polyline points={line.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(\" \")} />}\n {low && high && low !== high && (\n <>\n <circle className=\"sf-spark-extreme\" cx={low.x} cy={low.y} r={1.8} />\n <circle className=\"sf-spark-extreme\" cx={high.x} cy={high.y} r={1.8} />\n </>\n )}\n {last && <circle className=\"sf-spark-last\" cx={last.x} cy={last.y} r={2.4} />}\n </svg>\n <span className=\"sf-spark-value\">{last ? write(last.value) : state.loading ? text(\"metric.loading\") : (props.emptyMessage ?? text(\"metric.none\"))}</span>\n </>\n )}\n </span>\n );\n}\n"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ChartType } from "./option.js";
|
|
2
|
+
/** What a chart is about to draw, in the terms the advice needs. */
|
|
3
|
+
export interface ChartShape {
|
|
4
|
+
type: ChartType;
|
|
5
|
+
/** Distinct values on the x axis (or slices of a pie). */
|
|
6
|
+
categories?: number;
|
|
7
|
+
/** Series drawn, after any split. */
|
|
8
|
+
series?: number;
|
|
9
|
+
stacked?: boolean;
|
|
10
|
+
/** True when a measure is on a second y scale. */
|
|
11
|
+
rightAxis?: boolean;
|
|
12
|
+
/** True when x is a date, time or number, so its order means something. */
|
|
13
|
+
orderedX?: boolean;
|
|
14
|
+
/** True when the value axis has been told to start somewhere other than zero. */
|
|
15
|
+
truncatedAxis?: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface ChartAdvice {
|
|
18
|
+
rule: "pie-slices" | "two-scales" | "bar-baseline" | "line-order" | "too-many-lines" | "stack-depth" | "bar-crowding" | "overlapping-areas";
|
|
19
|
+
message: string;
|
|
20
|
+
/** What to draw instead. */
|
|
21
|
+
instead: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Checks a chart against the working rules of Edward Tufte and Stephen Few:
|
|
25
|
+
* show the data honestly, compare like with like, and spend ink only on
|
|
26
|
+
* data. It returns advice, not errors; a person or an agent decides.
|
|
27
|
+
*/
|
|
28
|
+
export declare function chartAdvice(shape: ChartShape): ChartAdvice[];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks a chart against the working rules of Edward Tufte and Stephen Few:
|
|
3
|
+
* show the data honestly, compare like with like, and spend ink only on
|
|
4
|
+
* data. It returns advice, not errors; a person or an agent decides.
|
|
5
|
+
*/
|
|
6
|
+
export function chartAdvice(shape) {
|
|
7
|
+
const advice = [];
|
|
8
|
+
const { type, categories = 0, series = 1 } = shape;
|
|
9
|
+
if (type === "pie" && categories > 5) {
|
|
10
|
+
advice.push({ rule: "pie-slices", message: `${categories} slices are too many to compare by angle.`, instead: "A bar chart sorted by value." });
|
|
11
|
+
}
|
|
12
|
+
if (shape.rightAxis) {
|
|
13
|
+
advice.push({
|
|
14
|
+
rule: "two-scales",
|
|
15
|
+
message: "Two y scales make heights look comparable when they are not.",
|
|
16
|
+
instead: "Two charts stacked on the same x axis, or both measures indexed to a common start.",
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
if (type === "bar" && shape.truncatedAxis) {
|
|
20
|
+
advice.push({ rule: "bar-baseline", message: "A bar's length is its value, so the axis must start at zero.", instead: "Start at zero, or use a dot or line chart if the differences are small." });
|
|
21
|
+
}
|
|
22
|
+
if ((type === "line" || type === "area") && shape.orderedX === false) {
|
|
23
|
+
advice.push({ rule: "line-order", message: "A line implies order between its points; these categories have none.", instead: "A bar chart." });
|
|
24
|
+
}
|
|
25
|
+
if (type === "line" && series > 5) {
|
|
26
|
+
advice.push({ rule: "too-many-lines", message: `${series} lines cross too often to follow.`, instead: "Small multiples on one shared scale, or highlight one line and grey the rest." });
|
|
27
|
+
}
|
|
28
|
+
if (shape.stacked && series > 5) {
|
|
29
|
+
advice.push({ rule: "stack-depth", message: `Only the bottom of ${series} stacked segments can be compared across bars.`, instead: "Keep the largest four and fold the rest into Other, or use small multiples." });
|
|
30
|
+
}
|
|
31
|
+
if (type === "bar" && !shape.stacked && categories * series > 40) {
|
|
32
|
+
advice.push({ rule: "bar-crowding", message: "Too many bars to read individually.", instead: "The top values sorted by size, or a table." });
|
|
33
|
+
}
|
|
34
|
+
if (type === "area" && !shape.stacked && series > 1) {
|
|
35
|
+
advice.push({ rule: "overlapping-areas", message: "Unstacked areas hide each other.", instead: "Lines, or a stacked area if the total matters." });
|
|
36
|
+
}
|
|
37
|
+
return advice;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=advice.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"advice.js","sourceRoot":"","sources":["../../src/chart/advice.ts"],"names":[],"mappings":"AAyBA;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,KAAiB;IAC3C,MAAM,MAAM,GAAkB,EAAE,CAAC;IACjC,MAAM,EAAE,IAAI,E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AAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,MAAM,gDAAgD,EAAE,OAAO,EAAE,6EAA6E,EAAE,CAAC,CAAC;IACtN,CAAC;IACD,IAAI,IAAI,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,UAAU,GAAG,MAAM,GAAG,EAAE,EAAE,CAAC;QACjE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,qCAAqC,EAAE,OAAO,EAAE,4CAA4C,EAAE,CAAC,CAAC;IAC/I,CAAC;IACD,IAAI,IAAI,KAAK,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;QACpD,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,kCAAkC,EAAE,OAAO,EAAE,gDAAgD,EAAE,CAAC,CAAC;IACrJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { ChartType } from \"./option.js\";\n\n/** What a chart is about to draw, in the terms the advice needs. */\nexport interface ChartShape {\n type: ChartType;\n /** Distinct values on the x axis (or slices of a pie). */\n categories?: number;\n /** Series drawn, after any split. */\n series?: number;\n stacked?: boolean;\n /** True when a measure is on a second y scale. */\n rightAxis?: boolean;\n /** True when x is a date, time or number, so its order means something. */\n orderedX?: boolean;\n /** True when the value axis has been told to start somewhere other than zero. */\n truncatedAxis?: boolean;\n}\n\nexport interface ChartAdvice {\n rule: \"pie-slices\" | \"two-scales\" | \"bar-baseline\" | \"line-order\" | \"too-many-lines\" | \"stack-depth\" | \"bar-crowding\" | \"overlapping-areas\";\n message: string;\n /** What to draw instead. */\n instead: string;\n}\n\n/**\n * Checks a chart against the working rules of Edward Tufte and Stephen Few:\n * show the data honestly, compare like with like, and spend ink only on\n * data. It returns advice, not errors; a person or an agent decides.\n */\nexport function chartAdvice(shape: ChartShape): ChartAdvice[] {\n const advice: ChartAdvice[] = [];\n const { type, categories = 0, series = 1 } = shape;\n if (type === \"pie\" && categories > 5) {\n advice.push({ rule: \"pie-slices\", message: `${categories} slices are too many to compare by angle.`, instead: \"A bar chart sorted by value.\" });\n }\n if (shape.rightAxis) {\n advice.push({\n rule: \"two-scales\",\n message: \"Two y scales make heights look comparable when they are not.\",\n instead: \"Two charts stacked on the same x axis, or both measures indexed to a common start.\",\n });\n }\n if (type === \"bar\" && shape.truncatedAxis) {\n advice.push({ rule: \"bar-baseline\", message: \"A bar's length is its value, so the axis must start at zero.\", instead: \"Start at zero, or use a dot or line chart if the differences are small.\" });\n }\n if ((type === \"line\" || type === \"area\") && shape.orderedX === false) {\n advice.push({ rule: \"line-order\", message: \"A line implies order between its points; these categories have none.\", instead: \"A bar chart.\" });\n }\n if (type === \"line\" && series > 5) {\n advice.push({ rule: \"too-many-lines\", message: `${series} lines cross too often to follow.`, instead: \"Small multiples on one shared scale, or highlight one line and grey the rest.\" });\n }\n if (shape.stacked && series > 5) {\n advice.push({ rule: \"stack-depth\", message: `Only the bottom of ${series} stacked segments can be compared across bars.`, instead: \"Keep the largest four and fold the rest into Other, or use small multiples.\" });\n }\n if (type === \"bar\" && !shape.stacked && categories * series > 40) {\n advice.push({ rule: \"bar-crowding\", message: \"Too many bars to read individually.\", instead: \"The top values sorted by size, or a table.\" });\n }\n if (type === \"area\" && !shape.stacked && series > 1) {\n advice.push({ rule: \"overlapping-areas\", message: \"Unstacked areas hide each other.\", instead: \"Lines, or a stacked area if the total matters.\" });\n }\n return advice;\n}\n"]}
|