@perses-dev/components 0.2.0 → 0.3.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 (56) hide show
  1. package/dist/ECharts.d.ts +59 -0
  2. package/dist/ECharts.d.ts.map +1 -0
  3. package/dist/ECharts.js +1 -0
  4. package/dist/GaugeChart.d.ts +14 -0
  5. package/dist/GaugeChart.d.ts.map +1 -0
  6. package/dist/GaugeChart.js +1 -0
  7. package/dist/LineChart.d.ts +22 -0
  8. package/dist/LineChart.d.ts.map +1 -0
  9. package/dist/LineChart.js +1 -0
  10. package/dist/StatChart.d.ts +24 -0
  11. package/dist/StatChart.d.ts.map +1 -0
  12. package/dist/StatChart.js +1 -0
  13. package/dist/cjs/ECharts.js +103 -0
  14. package/dist/cjs/ErrorAlert.js +25 -0
  15. package/dist/cjs/ErrorBoundary.js +18 -0
  16. package/dist/cjs/GaugeChart.js +178 -0
  17. package/dist/cjs/LineChart.js +227 -0
  18. package/dist/cjs/StatChart.js +205 -0
  19. package/dist/cjs/index.js +37 -0
  20. package/dist/cjs/model/graph-model.js +16 -0
  21. package/dist/cjs/model/units.js +211 -0
  22. package/dist/cjs/tooltip/SeriesInfo.js +76 -0
  23. package/dist/cjs/tooltip/SeriesMarker.js +30 -0
  24. package/dist/cjs/tooltip/Tooltip.js +99 -0
  25. package/dist/cjs/tooltip/TooltipContent.js +50 -0
  26. package/dist/cjs/tooltip/focused-series.js +108 -0
  27. package/dist/cjs/tooltip/tooltip-model.js +82 -0
  28. package/dist/cjs/utils/combine-sx.js +30 -0
  29. package/dist/index.d.ts +6 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +1 -1
  32. package/dist/model/graph-model.d.ts +13 -0
  33. package/dist/model/graph-model.d.ts.map +1 -0
  34. package/dist/model/graph-model.js +1 -0
  35. package/dist/model/units.d.ts +25 -0
  36. package/dist/model/units.d.ts.map +1 -0
  37. package/dist/model/units.js +1 -0
  38. package/dist/tooltip/SeriesInfo.d.ts +11 -0
  39. package/dist/tooltip/SeriesInfo.d.ts.map +1 -0
  40. package/dist/tooltip/SeriesInfo.js +1 -0
  41. package/dist/tooltip/SeriesMarker.d.ts +7 -0
  42. package/dist/tooltip/SeriesMarker.d.ts.map +1 -0
  43. package/dist/tooltip/SeriesMarker.js +1 -0
  44. package/dist/tooltip/Tooltip.d.ts +13 -0
  45. package/dist/tooltip/Tooltip.d.ts.map +1 -0
  46. package/dist/tooltip/Tooltip.js +1 -0
  47. package/dist/tooltip/TooltipContent.d.ts +9 -0
  48. package/dist/tooltip/TooltipContent.d.ts.map +1 -0
  49. package/dist/tooltip/TooltipContent.js +1 -0
  50. package/dist/tooltip/focused-series.d.ts +24 -0
  51. package/dist/tooltip/focused-series.d.ts.map +1 -0
  52. package/dist/tooltip/focused-series.js +1 -0
  53. package/dist/tooltip/tooltip-model.d.ts +79 -0
  54. package/dist/tooltip/tooltip-model.d.ts.map +1 -0
  55. package/dist/tooltip/tooltip-model.js +1 -0
  56. package/package.json +7 -3
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.LineChart = void 0;
7
+ const jsx_runtime_1 = require("react/jsx-runtime");
8
+ // Copyright 2021 The Perses Authors
9
+ // Licensed under the Apache License, Version 2.0 (the "License");
10
+ // you may not use this file except in compliance with the License.
11
+ // You may obtain a copy of the License at
12
+ //
13
+ // http://www.apache.org/licenses/LICENSE-2.0
14
+ //
15
+ // Unless required by applicable law or agreed to in writing, software
16
+ // distributed under the License is distributed on an "AS IS" BASIS,
17
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ // See the License for the specific language governing permissions and
19
+ // limitations under the License.
20
+ const react_1 = require("react");
21
+ const material_1 = require("@mui/material");
22
+ const merge_1 = __importDefault(require("lodash/merge"));
23
+ const core_1 = require("echarts/core");
24
+ const charts_1 = require("echarts/charts");
25
+ const components_1 = require("echarts/components");
26
+ const renderers_1 = require("echarts/renderers");
27
+ const ECharts_1 = require("./ECharts");
28
+ const graph_model_1 = require("./model/graph-model");
29
+ const units_1 = require("./model/units");
30
+ const tooltip_model_1 = require("./tooltip/tooltip-model");
31
+ const Tooltip_1 = require("./tooltip/Tooltip");
32
+ (0, core_1.use)([
33
+ charts_1.LineChart,
34
+ components_1.GridComponent,
35
+ components_1.DataZoomComponent,
36
+ components_1.MarkAreaComponent,
37
+ components_1.MarkLineComponent,
38
+ components_1.MarkPointComponent,
39
+ components_1.TitleComponent,
40
+ components_1.ToolboxComponent,
41
+ components_1.TooltipComponent,
42
+ components_1.LegendComponent,
43
+ components_1.VisualMapComponent,
44
+ renderers_1.CanvasRenderer,
45
+ ]);
46
+ const noDataOption = {
47
+ title: {
48
+ show: true,
49
+ textStyle: {
50
+ color: 'grey',
51
+ fontSize: 16,
52
+ fontWeight: 400,
53
+ },
54
+ text: 'No data',
55
+ left: 'center',
56
+ top: 'center',
57
+ },
58
+ xAxis: {
59
+ show: false,
60
+ },
61
+ yAxis: {
62
+ show: false,
63
+ },
64
+ series: [],
65
+ };
66
+ function LineChart(props) {
67
+ const { height, data, grid, legend, toolbox, dataZoomEnabled, onDataZoom } = props;
68
+ const theme = (0, material_1.useTheme)();
69
+ const chartRef = (0, react_1.useRef)();
70
+ const [showTooltip, setShowTooltip] = (0, react_1.useState)(true);
71
+ const handleEvents = (0, react_1.useMemo)(() => {
72
+ return {
73
+ datazoom: (params) => {
74
+ var _a, _b;
75
+ if (onDataZoom === undefined || params.batch[0] === undefined)
76
+ return;
77
+ const startIndex = (_a = params.batch[0].startValue) !== null && _a !== void 0 ? _a : 0;
78
+ const endIndex = (_b = params.batch[0].endValue) !== null && _b !== void 0 ? _b : data.xAxis.length - 1;
79
+ const xAxisStartValue = data.xAxis[startIndex];
80
+ const xAxisEndValue = data.xAxis[endIndex];
81
+ if (xAxisStartValue !== undefined && xAxisEndValue !== undefined) {
82
+ const zoomEvent = {
83
+ start: xAxisStartValue,
84
+ end: xAxisEndValue,
85
+ startIndex,
86
+ endIndex,
87
+ };
88
+ onDataZoom(zoomEvent);
89
+ }
90
+ },
91
+ };
92
+ }, [data, onDataZoom]);
93
+ if (chartRef.current !== undefined && dataZoomEnabled === true) {
94
+ const chart = chartRef.current;
95
+ chart.dispatchAction({
96
+ type: 'takeGlobalCursor',
97
+ key: 'dataZoomSelect',
98
+ dataZoomSelectActive: true,
99
+ });
100
+ }
101
+ const handleOnMouseDown = (event) => {
102
+ // hide tooltip when user drags to zoom, but allow clicking inside tooltip to copy labels
103
+ if (event.target instanceof HTMLCanvasElement) {
104
+ setShowTooltip(false);
105
+ }
106
+ };
107
+ const handleOnMouseUp = () => {
108
+ setShowTooltip(true);
109
+ };
110
+ const handleOnMouseEnter = () => {
111
+ setShowTooltip(true);
112
+ };
113
+ const handleOnMouseLeave = () => {
114
+ setShowTooltip(false);
115
+ };
116
+ const option = (0, react_1.useMemo)(() => {
117
+ if (data.timeSeries === undefined)
118
+ return {};
119
+ if (data.timeSeries === null || data.timeSeries.length === 0)
120
+ return noDataOption;
121
+ const showPointsOnHover = data.timeSeries.length < graph_model_1.PROGRESSIVE_MODE_SERIES_LIMIT;
122
+ const defaultGrid = {
123
+ show: true,
124
+ backgroundColor: theme.palette.mode === 'dark' ? theme.palette.grey[100] : theme.palette.background.paper,
125
+ borderColor: theme.palette.grey['300'],
126
+ top: 10,
127
+ right: 20,
128
+ bottom: 0,
129
+ left: 20,
130
+ containLabel: true,
131
+ };
132
+ const defaultToolbox = {
133
+ show: true,
134
+ top: 10,
135
+ right: 10,
136
+ iconStyle: {
137
+ borderColor: theme.palette.text.primary,
138
+ },
139
+ feature: {
140
+ dataZoom: {
141
+ icon: dataZoomEnabled ? null : undefined,
142
+ yAxisIndex: 'none',
143
+ },
144
+ restore: {},
145
+ },
146
+ emphasis: {
147
+ iconStyle: {
148
+ textFill: theme.palette.text.primary,
149
+ },
150
+ },
151
+ };
152
+ if (dataZoomEnabled === false) {
153
+ delete defaultToolbox.feature.dataZoom.icon;
154
+ }
155
+ const option = {
156
+ title: {
157
+ show: false,
158
+ },
159
+ grid: (0, merge_1.default)(defaultGrid, grid),
160
+ toolbox: (0, merge_1.default)(defaultToolbox, toolbox),
161
+ series: data.timeSeries,
162
+ xAxis: {
163
+ type: 'category',
164
+ data: data.xAxis,
165
+ axisLabel: {
166
+ color: theme.palette.text.primary,
167
+ margin: 12,
168
+ formatter: (value) => {
169
+ return getFormattedDate(value);
170
+ },
171
+ },
172
+ axisTick: {
173
+ show: true,
174
+ length: 6,
175
+ },
176
+ axisLine: {
177
+ lineStyle: {
178
+ color: theme.palette.grey['600'],
179
+ },
180
+ },
181
+ },
182
+ yAxis: {
183
+ type: 'value',
184
+ boundaryGap: ['10%', '10%'],
185
+ axisLabel: {
186
+ showMinLabel: false,
187
+ showMaxLabel: true,
188
+ color: theme.palette.text.primary,
189
+ formatter: (value) => {
190
+ return (0, units_1.abbreviateLargeNumber)(value);
191
+ },
192
+ },
193
+ splitLine: {
194
+ lineStyle: {
195
+ color: theme.palette.grey['300'],
196
+ },
197
+ },
198
+ },
199
+ animation: false,
200
+ tooltip: {
201
+ show: showPointsOnHover,
202
+ trigger: 'axis',
203
+ showContent: false,
204
+ axisPointer: {
205
+ type: 'none',
206
+ },
207
+ },
208
+ legend,
209
+ };
210
+ return option;
211
+ }, [data, theme, grid, legend, toolbox, dataZoomEnabled]);
212
+ return ((0, jsx_runtime_1.jsxs)(material_1.Box, { sx: {
213
+ height,
214
+ }, onMouseDown: handleOnMouseDown, onMouseUp: handleOnMouseUp, onMouseLeave: handleOnMouseLeave, onMouseEnter: handleOnMouseEnter, children: [showTooltip === true && ((0, jsx_runtime_1.jsx)(Tooltip_1.Tooltip, { chartRef: chartRef, tooltipData: tooltip_model_1.emptyTooltipData, chartData: data, wrapLabels: true })), (0, jsx_runtime_1.jsx)(ECharts_1.ECharts, { sx: {
215
+ width: '100%',
216
+ height: '100%',
217
+ }, option: option, onEvents: handleEvents, _instance: chartRef })] }));
218
+ }
219
+ exports.LineChart = LineChart;
220
+ function getFormattedDate(value) {
221
+ const XAXIS_DATE_FORMAT = new Intl.DateTimeFormat(undefined, {
222
+ hour: 'numeric',
223
+ minute: 'numeric',
224
+ hour12: false,
225
+ });
226
+ return XAXIS_DATE_FORMAT.format(value * 1000);
227
+ }
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StatChart = void 0;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ // Copyright 2021 The Perses Authors
6
+ // Licensed under the Apache License, Version 2.0 (the "License");
7
+ // you may not use this file except in compliance with the License.
8
+ // You may obtain a copy of the License at
9
+ //
10
+ // http://www.apache.org/licenses/LICENSE-2.0
11
+ //
12
+ // Unless required by applicable law or agreed to in writing, software
13
+ // distributed under the License is distributed on an "AS IS" BASIS,
14
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ // See the License for the specific language governing permissions and
16
+ // limitations under the License.
17
+ const react_1 = require("react");
18
+ const lodash_es_1 = require("lodash-es");
19
+ const core_1 = require("echarts/core");
20
+ const charts_1 = require("echarts/charts");
21
+ const charts_2 = require("echarts/charts");
22
+ const components_1 = require("echarts/components");
23
+ const renderers_1 = require("echarts/renderers");
24
+ const units_1 = require("./model/units");
25
+ const ECharts_1 = require("./ECharts");
26
+ (0, core_1.use)([
27
+ charts_1.GaugeChart,
28
+ charts_2.LineChart,
29
+ components_1.GridComponent,
30
+ components_1.DatasetComponent,
31
+ components_1.TitleComponent,
32
+ components_1.TooltipComponent,
33
+ renderers_1.CanvasRenderer,
34
+ ]);
35
+ const noDataOption = {
36
+ title: {
37
+ show: true,
38
+ textStyle: {
39
+ color: 'grey',
40
+ fontSize: 16,
41
+ fontWeight: 400,
42
+ },
43
+ text: 'No data',
44
+ left: 'center',
45
+ top: 'center',
46
+ },
47
+ xAxis: {
48
+ show: false,
49
+ },
50
+ yAxis: {
51
+ show: false,
52
+ },
53
+ series: [],
54
+ };
55
+ function StatChart(props) {
56
+ const { width, height, data, unit, backgroundColor, sparkline } = props;
57
+ const option = (0, react_1.useMemo)(() => {
58
+ var _a;
59
+ if (data.seriesData === undefined)
60
+ return {};
61
+ if (data.seriesData === null || data.calculatedValue === undefined)
62
+ return noDataOption;
63
+ const series = data.seriesData;
64
+ const calculatedValue = (_a = data.calculatedValue) !== null && _a !== void 0 ? _a : 0;
65
+ const isLargePanel = width > 250 ? true : false;
66
+ const showName = isLargePanel;
67
+ const name = showName === true ? data.name : '';
68
+ const smallestSide = Math.min(width, height * 1.2);
69
+ const baseFontSize = Math.min((smallestSide / 4) * 0.65, 72);
70
+ const nameFontSize = baseFontSize * 0.5;
71
+ const statSeries = [
72
+ {
73
+ type: 'gauge',
74
+ data: [
75
+ {
76
+ value: calculatedValue,
77
+ name: name,
78
+ },
79
+ ],
80
+ detail: {
81
+ show: true,
82
+ offsetCenter: ['0%', '-65%'],
83
+ formatter: [`{name|${name}}`, `{value|${(0, units_1.formatValue)(calculatedValue, unit)}}`].join('\n'),
84
+ rich: {
85
+ name: {
86
+ padding: showName === true ? [0, 0, 5, 0] : 0,
87
+ fontSize: nameFontSize,
88
+ lineHeight: nameFontSize * 2.5,
89
+ fontWeight: 500,
90
+ },
91
+ value: {},
92
+ },
93
+ },
94
+ center: ['50%', '60%'],
95
+ animation: false,
96
+ silent: true,
97
+ title: { show: false },
98
+ progress: { show: false },
99
+ pointer: { show: false },
100
+ axisLine: { show: false },
101
+ axisTick: { show: false },
102
+ splitLine: { show: false },
103
+ axisLabel: { show: false },
104
+ anchor: { show: false },
105
+ zlevel: 2,
106
+ },
107
+ ];
108
+ if (sparkline !== undefined) {
109
+ const lineSeries = {
110
+ type: 'line',
111
+ data: [...series.values],
112
+ zlevel: 1,
113
+ symbol: 'none',
114
+ animation: false,
115
+ lineStyle: {
116
+ color: '#FFFFFF',
117
+ opacity: 0.6,
118
+ },
119
+ areaStyle: {
120
+ color: '#FFFFFF',
121
+ opacity: 0.3,
122
+ },
123
+ silent: true,
124
+ };
125
+ const mergedSeries = (0, lodash_es_1.merge)(lineSeries, sparkline);
126
+ statSeries.push(mergedSeries);
127
+ }
128
+ const option = {
129
+ title: {
130
+ show: false,
131
+ },
132
+ grid: [
133
+ {
134
+ show: true,
135
+ backgroundColor: backgroundColor,
136
+ top: 0,
137
+ right: 0,
138
+ bottom: 0,
139
+ left: 0,
140
+ containLabel: false,
141
+ borderWidth: 0,
142
+ },
143
+ {
144
+ show: false,
145
+ top: '45%',
146
+ right: 0,
147
+ bottom: 0,
148
+ left: 0,
149
+ containLabel: false,
150
+ },
151
+ ],
152
+ xAxis: {
153
+ type: 'time',
154
+ show: false,
155
+ boundaryGap: false,
156
+ gridIndex: 1, // sparkline grid
157
+ },
158
+ yAxis: {
159
+ type: 'value',
160
+ show: false,
161
+ gridIndex: 1,
162
+ },
163
+ tooltip: {
164
+ show: false,
165
+ },
166
+ series: statSeries,
167
+ textStyle: {
168
+ color: backgroundColor === 'transparent' ? '#000000' : '#FFFFFF',
169
+ fontSize: 25,
170
+ lineHeight: 18,
171
+ fontFamily: '"Lato", sans-serif',
172
+ fontWeight: 'bold',
173
+ },
174
+ media: [
175
+ {
176
+ query: {
177
+ maxWidth: 150,
178
+ },
179
+ option: {
180
+ textStyle: {
181
+ fontSize: 12,
182
+ },
183
+ },
184
+ },
185
+ {
186
+ query: {
187
+ minWidth: 150,
188
+ },
189
+ option: {
190
+ textStyle: {
191
+ fontSize: `max(14px, ${baseFontSize}px)`,
192
+ lineHeight: Math.min(16, baseFontSize * 1.2),
193
+ },
194
+ },
195
+ },
196
+ ],
197
+ };
198
+ return option;
199
+ }, [data, height, unit, width, sparkline, backgroundColor]);
200
+ return ((0, jsx_runtime_1.jsx)(ECharts_1.ECharts, { sx: {
201
+ width: width,
202
+ height: height,
203
+ }, option: option }));
204
+ }
205
+ exports.StatChart = StatChart;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ // Copyright 2021 The Perses Authors
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ var desc = Object.getOwnPropertyDescriptor(m, k);
17
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
18
+ desc = { enumerable: true, get: function() { return m[k]; } };
19
+ }
20
+ Object.defineProperty(o, k2, desc);
21
+ }) : (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ o[k2] = m[k];
24
+ }));
25
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
26
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ __exportStar(require("./ECharts"), exports);
30
+ __exportStar(require("./ErrorAlert"), exports);
31
+ __exportStar(require("./ErrorBoundary"), exports);
32
+ __exportStar(require("./GaugeChart"), exports);
33
+ __exportStar(require("./LineChart"), exports);
34
+ __exportStar(require("./StatChart"), exports);
35
+ __exportStar(require("./utils/combine-sx"), exports);
36
+ __exportStar(require("./model/graph-model"), exports);
37
+ __exportStar(require("./model/units"), exports);
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ // Copyright 2021 The Perses Authors
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.PROGRESSIVE_MODE_SERIES_LIMIT = void 0;
16
+ exports.PROGRESSIVE_MODE_SERIES_LIMIT = 500;
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ // Copyright 2021 The Perses Authors
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SIMPLE_UNITS = exports.removeUnitNamespace = exports.SANCTIONED_UNITS = exports.isSanctionedSimpleUnitIdentifier = exports.abbreviateLargeNumber = exports.formatValue = void 0;
16
+ const date_fns_1 = require("date-fns");
17
+ function formatValue(value, unitOptions) {
18
+ if (unitOptions === undefined) {
19
+ return value.toString();
20
+ }
21
+ if (isTimeUnit(unitOptions)) {
22
+ return formatTime(value, unitOptions);
23
+ }
24
+ if (isPercentUnit(unitOptions)) {
25
+ return formatPercent(value, unitOptions);
26
+ }
27
+ if (isDecimalUnit(unitOptions)) {
28
+ return formatDecimal(value, unitOptions);
29
+ }
30
+ const exhaustive = unitOptions;
31
+ throw new Error(`Unknown unit options ${exhaustive}`);
32
+ }
33
+ exports.formatValue = formatValue;
34
+ const timeUnitKinds = ['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Days', 'Weeks', 'Months', 'Years'];
35
+ const timeUnitKindsSet = new Set(timeUnitKinds);
36
+ function isTimeUnit(unitOptions) {
37
+ return timeUnitKindsSet.has(unitOptions.kind);
38
+ }
39
+ function formatTime(value, unitOptions) {
40
+ // Create a Duration from the value based on what time unit it is
41
+ const duration = {};
42
+ switch (unitOptions.kind) {
43
+ case 'Milliseconds':
44
+ duration.seconds = value / 1000;
45
+ break;
46
+ case 'Seconds':
47
+ duration.seconds = value;
48
+ break;
49
+ case 'Minutes':
50
+ duration.minutes = value;
51
+ break;
52
+ case 'Hours':
53
+ duration.hours = value;
54
+ break;
55
+ case 'Days':
56
+ duration.days = value;
57
+ break;
58
+ case 'Weeks':
59
+ duration.weeks = value;
60
+ break;
61
+ case 'Months':
62
+ duration.months = value;
63
+ break;
64
+ case 'Years':
65
+ duration.years = value;
66
+ break;
67
+ default:
68
+ const exhaustive = unitOptions.kind;
69
+ throw new Error(`Unknown time unit type ${exhaustive}`);
70
+ }
71
+ // Find the largest whole time unit we can display the value in and use it
72
+ const ms = (0, date_fns_1.milliseconds)(duration);
73
+ const seconds = ms / 1000;
74
+ if (seconds < 1) {
75
+ return `${ms.toFixed()} milliseconds`;
76
+ }
77
+ const minutes = seconds / 60;
78
+ if (minutes < 1) {
79
+ return `${seconds.toFixed()} seconds`;
80
+ }
81
+ const hours = minutes / 60;
82
+ if (hours < 1) {
83
+ return `${minutes.toFixed()} minutes`;
84
+ }
85
+ const days = hours / 24;
86
+ if (days < 1) {
87
+ return `${hours.toFixed()} hours`;
88
+ }
89
+ const weeks = days / 7;
90
+ if (weeks < 1) {
91
+ return `${days.toFixed()} days`;
92
+ }
93
+ const years = weeks / 52;
94
+ if (years < 1) {
95
+ return `${weeks.toFixed()} weeks`;
96
+ }
97
+ return `${years.toFixed()} years`;
98
+ }
99
+ const percentUnitKinds = ['Percent', 'PercentDecimal'];
100
+ const percentUnitKindsSet = new Set(percentUnitKinds);
101
+ function isPercentUnit(unitOptions) {
102
+ return percentUnitKindsSet.has(unitOptions.kind);
103
+ }
104
+ function formatPercent(value, unitOptions) {
105
+ if (unitOptions.kind === 'PercentDecimal') {
106
+ value = value * 100;
107
+ }
108
+ return value.toFixed(unitOptions.decimal_places) + '%';
109
+ }
110
+ const decimalUnitKinds = ['Decimal'];
111
+ const decimalUnitKindsSet = new Set(decimalUnitKinds);
112
+ function isDecimalUnit(unitOptions) {
113
+ return decimalUnitKindsSet.has(unitOptions.kind);
114
+ }
115
+ function formatDecimal(value, unitOptions) {
116
+ var _a, _b;
117
+ const maximumFractionDigits = (_a = unitOptions.decimal_places) !== null && _a !== void 0 ? _a : 2;
118
+ if (unitOptions.suffix !== undefined) {
119
+ if (isSanctionedSimpleUnitIdentifier(unitOptions.suffix)) {
120
+ const formatParams = {
121
+ style: 'unit',
122
+ minimumFractionDigits: 0,
123
+ maximumFractionDigits: maximumFractionDigits,
124
+ useGrouping: true,
125
+ unit: unitOptions.suffix,
126
+ unitDisplay: (_b = unitOptions.unitDisplay) !== null && _b !== void 0 ? _b : 'narrow',
127
+ };
128
+ const unitFormatter = new Intl.NumberFormat('en-US', formatParams);
129
+ return unitFormatter.format(value);
130
+ }
131
+ }
132
+ const formatParams = {
133
+ style: 'decimal',
134
+ minimumFractionDigits: 0,
135
+ maximumFractionDigits: maximumFractionDigits,
136
+ useGrouping: true,
137
+ };
138
+ const decimalFormatter = new Intl.NumberFormat('en-US', formatParams);
139
+ return decimalFormatter.format(value);
140
+ }
141
+ // Take a large number and abbreviate appropriate suffix
142
+ // ex) 10000 -> 10k, 1000000 -> 1M
143
+ function abbreviateLargeNumber(num) {
144
+ return num >= 1e12
145
+ ? num / 1e12 + 'T'
146
+ : num >= 1e9
147
+ ? num / 1e9 + 'B'
148
+ : num >= 1e6
149
+ ? num / 1e6 + 'M'
150
+ : num >= 1e3
151
+ ? num / 1e3 + 'k'
152
+ : num;
153
+ }
154
+ exports.abbreviateLargeNumber = abbreviateLargeNumber;
155
+ // Util to check unit name against ECMA standard: https://tc39.es/ecma402/#sec-issanctionedsimpleunitidentifier
156
+ function isSanctionedSimpleUnitIdentifier(unitIdentifier) {
157
+ return exports.SIMPLE_UNITS.indexOf(unitIdentifier) > -1;
158
+ }
159
+ exports.isSanctionedSimpleUnitIdentifier = isSanctionedSimpleUnitIdentifier;
160
+ // https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
161
+ exports.SANCTIONED_UNITS = [
162
+ 'angle-degree',
163
+ 'area-acre',
164
+ 'area-hectare',
165
+ 'concentr-percent',
166
+ 'digital-bit',
167
+ 'digital-byte',
168
+ 'digital-gigabit',
169
+ 'digital-gigabyte',
170
+ 'digital-kilobit',
171
+ 'digital-kilobyte',
172
+ 'digital-megabit',
173
+ 'digital-megabyte',
174
+ 'digital-petabyte',
175
+ 'digital-terabit',
176
+ 'digital-terabyte',
177
+ 'duration-day',
178
+ 'duration-hour',
179
+ 'duration-millisecond',
180
+ 'duration-minute',
181
+ 'duration-month',
182
+ 'duration-second',
183
+ 'duration-week',
184
+ 'duration-year',
185
+ 'length-centimeter',
186
+ 'length-foot',
187
+ 'length-inch',
188
+ 'length-kilometer',
189
+ 'length-meter',
190
+ 'length-mile-scandinavian',
191
+ 'length-mile',
192
+ 'length-millimeter',
193
+ 'length-yard',
194
+ 'mass-gram',
195
+ 'mass-kilogram',
196
+ 'mass-ounce',
197
+ 'mass-pound',
198
+ 'mass-stone',
199
+ 'temperature-celsius',
200
+ 'temperature-fahrenheit',
201
+ 'volume-fluid-ounce',
202
+ 'volume-gallon',
203
+ 'volume-liter',
204
+ 'volume-milliliter',
205
+ ];
206
+ // removes the namespace prefix, ex: duration-hour -> hour
207
+ function removeUnitNamespace(unit) {
208
+ return unit.slice(unit.indexOf('-') + 1);
209
+ }
210
+ exports.removeUnitNamespace = removeUnitNamespace;
211
+ exports.SIMPLE_UNITS = exports.SANCTIONED_UNITS.map(removeUnitNamespace);