You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@streampipes.apache.org by ri...@apache.org on 2026/10/28 19:59:24 UTC
(streampipes) 01/01: feat: Harmonize chart options for more consistent layout
This is an automated email from the ASF dual-hosted git repository.
dominikriemer pushed a commit to branch harmonize-chart-options
in repository https://gitbox.apache.org/repos/asf/streampipes.git
commit c6ba690fd6048fff37f4002cee9ba5bf938a4441
Author: Dominik Riemer <do...@gmail.com>
AuthorDate: Wed Oct 28 20:58:58 2026 +0100
feat: Harmonize chart options for more consistent layout
---
ui/deployment/i18n/de.json | 5 +-
ui/deployment/i18n/en.json | 5 +-
ui/deployment/i18n/pl.json | 5 +-
ui/deployment/theme/_custom-variables.scss | 17 ++
.../model/datalake/data-lake-query-config.model.ts | 2 +
.../src/lib/model/types/data-type.ts | 4 +
.../number-format-config.component.html | 8 +-
.../number-format-config.component.ts | 27 ++-
.../time-series-item-config.component.ts | 16 +-
.../base/base-data-explorer-widget.directive.ts | 20 ++
.../charts/base/echarts-widget.component.html | 6 +-
.../charts/base/echarts-widget.component.ts | 63 ++++-
.../no-data/no-data-in-date-range.component.html | 3 +-
.../no-data/no-data-in-date-range.component.ts | 19 +-
.../charts/density/density-renderer.service.ts | 10 +-
.../charts/gauge/gauge-renderer.service.ts | 63 +++--
.../charts/heatmap/heatmap-renderer.service.ts | 31 ++-
.../charts/histogram/histogram-renderer.service.ts | 78 ++++--
.../charts/indicator/indicator-widget.component.ts | 14 +-
.../model/indicator-chart-widget.model.ts | 4 +-
.../config/pie-chart-widget-config.component.ts | 2 +-
.../components/charts/pie/pie-renderer.service.ts | 64 +++--
.../progress-bar/progress-bar-widget.component.ts | 39 +--
.../charts/scatter/scatter-renderer.service.ts | 10 +-
.../status-heatmap-renderer.service.ts | 17 +-
.../charts/status/status-widget.component.html | 2 +-
.../charts/status/status-widget.component.ts | 17 +-
.../charts/table/table-widget.component.html | 9 +-
.../charts/table/table-widget.component.ts | 65 +++--
.../time-series-chart-widget-config.component.ts | 32 +--
.../sp-timeseries-renderer.service.ts | 261 +++++++++++++++------
.../traffic-light-widget.component.ts | 20 +-
.../value-card/value-card-widget.component.ts | 38 ++-
.../value-heatmap-renderer.service.ts | 7 +-
.../echarts-renderer/base-echarts-renderer.ts | 85 ++++---
.../base-single-field-echarts-renderer.ts | 5 +-
.../echarts-basic-options-generator.service.ts | 95 +++++++-
ui/src/app/chart-shared/models/dataset.model.ts | 6 +
.../models/dataview-dashboard.model.ts | 3 +
.../services/chart-colorization.service.ts | 41 +++-
.../services/chart-field-provider.service.ts | 8 +
.../services/chart-palette.service.spec.ts | 60 +++++
.../chart-shared/services/chart-palette.service.ts | 68 ++++++
.../chart-shared/services/chart-theme.service.ts | 47 ++++
.../chart-shared/services/color-mapping.service.ts | 45 ++--
.../formatting/chart-number-format.service.spec.ts | 188 +++++++++++++++
.../formatting/chart-number-format.service.ts | 178 ++++++++++++++
.../formatting/chart-time-format.service.spec.ts | 151 ++++++++++++
.../formatting/chart-time-format.service.ts | 172 ++++++++++++++
.../formatting/index.ts} | 29 +--
.../chart-shared/services/widget-render.utils.ts | 26 --
51 files changed, 1786 insertions(+), 404 deletions(-)
diff --git a/ui/deployment/i18n/de.json b/ui/deployment/i18n/de.json
index 5ef9a32716..330c8657a4 100644
--- a/ui/deployment/i18n/de.json
+++ b/ui/deployment/i18n/de.json
@@ -156,6 +156,7 @@
"Auto-compute number of bins": "Automatische Berechnung der Bins",
"Auto-create password and send to user": "Passwort automatisch generieren und an den Benutzer versenden",
"Auto-scale {{title}}": "{{title}} automatisch skalieren",
+ "Automatic": "Automatisch",
"Available": "Verfügbar",
"Available & Installed": "Verfügbar & Installiert",
"Available Extensions": "Verfügbare Extensions",
@@ -833,11 +834,10 @@
"Open Retention Log": "Aufbewahrungs Log öffnen",
"Open fullscreen": "Vollbild öffnen",
"Open the chart editor to review and save the chart": "Öffnen Sie den Diagramm-Editor, um das Diagramm zu prüfen und zu speichern",
- "Optional override for decimal places. Leave empty to show original values.": "Optionale Überschreibung für Dezimalstellen. Leer lassen, um Originalwerte anzuzeigen.",
+ "Optional fixed number of decimal places. Leave empty for automatic formatting.": "Optionale feste Anzahl an Nachkommastellen. Leer lassen für automatische Formatierung.",
"Options": "Optionen",
"Or move it under another asset.": "Oder ordnen Sie es einem anderen Asset unter.",
"Order": "Sortieren",
- "Original": "Original",
"Original (Parsed)": "Original (geparst)",
"Original event": "Originalereignis",
"Original event display": "Darstellung des Originalereignisses",
@@ -1107,6 +1107,7 @@
"Show legend": "Legende anzeigen",
"Show message on every page": "Meldung auf jeder Seite anzeigen",
"Show only recommended settings": "Nur empfohlene Einstellungen anzeigen",
+ "Show original values without formatting": "Originalwerte ohne Formatierung anzeigen",
"Show progress label": "Fortschrittsbeschriftung anzeigen",
"Show raw data from your data source.": "Zeigen Sie Rohdaten aus Ihrer Datenquelle an.",
"Show single data entry.": "Einzelne Dateneinträge anzeigen.",
diff --git a/ui/deployment/i18n/en.json b/ui/deployment/i18n/en.json
index 5202967aef..0cb6799dc3 100644
--- a/ui/deployment/i18n/en.json
+++ b/ui/deployment/i18n/en.json
@@ -156,6 +156,7 @@
"Auto-compute number of bins": null,
"Auto-create password and send to user": null,
"Auto-scale {{title}}": "Auto-scale {{title}}",
+ "Automatic": null,
"Available": null,
"Available & Installed": null,
"Available Extensions": null,
@@ -833,11 +834,10 @@
"Open Retention Log": null,
"Open fullscreen": null,
"Open the chart editor to review and save the chart": null,
- "Optional override for decimal places. Leave empty to show original values.": null,
+ "Optional fixed number of decimal places. Leave empty for automatic formatting.": null,
"Options": null,
"Or move it under another asset.": "Or move it under another asset.",
"Order": null,
- "Original": null,
"Original (Parsed)": null,
"Original event": null,
"Original event display": null,
@@ -1107,6 +1107,7 @@
"Show legend": null,
"Show message on every page": null,
"Show only recommended settings": null,
+ "Show original values without formatting": null,
"Show progress label": null,
"Show raw data from your data source.": null,
"Show single data entry.": null,
diff --git a/ui/deployment/i18n/pl.json b/ui/deployment/i18n/pl.json
index d75406abbc..d24bb1e2b8 100644
--- a/ui/deployment/i18n/pl.json
+++ b/ui/deployment/i18n/pl.json
@@ -156,6 +156,7 @@
"Auto-compute number of bins": "Automatycznie oblicz liczbę przedziałów",
"Auto-create password and send to user": "Automatycznie utwórz hasło i wyślij je użytkownikowi",
"Auto-scale {{title}}": "Automatycznie skaluj {{title}}",
+ "Automatic": "Automatycznie",
"Available": "Dostępne",
"Available & Installed": "Dostępne i zainstalowane",
"Available Extensions": "Dostępne rozszerzenia",
@@ -833,11 +834,10 @@
"Open Retention Log": "Otwórz dziennik retencji",
"Open fullscreen": "Otwórz pełny ekran",
"Open the chart editor to review and save the chart": "Otwórz edytor wykresów, aby sprawdzić i zapisać wykres",
- "Optional override for decimal places. Leave empty to show original values.": "Opcjonalne nadpisanie liczby miejsc dziesiętnych. Pozostaw puste, aby pokazać wartości oryginalne.",
+ "Optional fixed number of decimal places. Leave empty for automatic formatting.": "Opcjonalna stała liczba miejsc po przecinku. Pozostaw puste, aby formatować automatycznie.",
"Options": "Opcje",
"Or move it under another asset.": "Lub przenieś go pod inny zasób.",
"Order": "Kolejność",
- "Original": "Oryginalne",
"Original (Parsed)": "Oryginał (przetworzony)",
"Original event": "Oryginalne zdarzenie",
"Original event display": "Widok oryginalnego zdarzenia",
@@ -1107,6 +1107,7 @@
"Show legend": "Pokaż legendę",
"Show message on every page": "Pokaż komunikat na każdej stronie",
"Show only recommended settings": "Pokaż tylko zalecane ustawienia",
+ "Show original values without formatting": "Pokaż oryginalne wartości bez formatowania",
"Show progress label": "Pokaż etykietę postępu",
"Show raw data from your data source.": "Pokaż surowe dane ze źródła.",
"Show single data entry.": "Pokaż pojedynczy wpis danych.",
diff --git a/ui/deployment/theme/_custom-variables.scss b/ui/deployment/theme/_custom-variables.scss
index d9d25bf633..3bce6d1e1f 100644
--- a/ui/deployment/theme/_custom-variables.scss
+++ b/ui/deployment/theme/_custom-variables.scss
@@ -44,11 +44,28 @@
--color-toolbar-icon: var(--color-secondary);
--color-toolbar-icon-hover: var(--color-secondary-dark);
--color-toolbar-icon-selected: var(--color-secondary-dark);
+
+ // Categorical palette for chart series (grouped time series, pie slices,
+ // status values). Ordered by assignment: the first group gets chart-1.
+ // Deliberately avoids the semantic success/warning/error hues.
+ --color-chart-1: #4f81bd;
+ --color-chart-2: #f28e2b;
+ --color-chart-3: #7b61ff;
+ --color-chart-4: #2a9d8f;
+ --color-chart-5: #e9c46a;
+ --color-chart-6: #c77dff;
+ --color-chart-7: #577590;
+ --color-chart-8: #f4a261;
+ --color-chart-9: #43aa8b;
+ --color-chart-10: #bc5090;
}
.dark-mode {
--color-primary: var(--color-primary-dark);
--color-secondary: var(--color-secondary-dark);
+ --color-chart-1: #6ea0e0;
+ --color-chart-7: #8da4bf;
+ --color-chart-10: #d67ab1;
--color-menubar-text-menu-group: #120c47;
--color-navigation-bg: #123b28;
--color-navigation-hover: #185236;
diff --git a/ui/projects/streampipes/platform-services/src/lib/model/datalake/data-lake-query-config.model.ts b/ui/projects/streampipes/platform-services/src/lib/model/datalake/data-lake-query-config.model.ts
index 2ab11852ec..cb4e4afe7a 100644
--- a/ui/projects/streampipes/platform-services/src/lib/model/datalake/data-lake-query-config.model.ts
+++ b/ui/projects/streampipes/platform-services/src/lib/model/datalake/data-lake-query-config.model.ts
@@ -22,6 +22,8 @@ export interface DataExplorerFieldCharacteristics {
dimension: boolean;
numeric: boolean;
binary: boolean;
+ /** Integer or long runtime type; absent in configurations saved by older releases. */
+ integer?: boolean;
semanticTypes: string[];
}
diff --git a/ui/projects/streampipes/platform-services/src/lib/model/types/data-type.ts b/ui/projects/streampipes/platform-services/src/lib/model/types/data-type.ts
index 7c14f431bb..57c676c49a 100644
--- a/ui/projects/streampipes/platform-services/src/lib/model/types/data-type.ts
+++ b/ui/projects/streampipes/platform-services/src/lib/model/types/data-type.ts
@@ -38,6 +38,10 @@ export class DataType {
);
}
+ public static isIntegerType(datatype: string): boolean {
+ return datatype === DataType.INTEGER || datatype === DataType.LONG;
+ }
+
public static isBooleanType(datatype: string): boolean {
return datatype === DataType.BOOLEAN;
}
diff --git a/ui/src/app/chart-shared/components/chart-config/number-format-config/number-format-config.component.html b/ui/src/app/chart-shared/components/chart-config/number-format-config/number-format-config.component.html
index 9e738ea003..840c8b44f9 100644
--- a/ui/src/app/chart-shared/components/chart-config/number-format-config/number-format-config.component.html
+++ b/ui/src/app/chart-shared/components/chart-config/number-format-config/number-format-config.component.html
@@ -20,7 +20,7 @@
[level]="3"
[label]="'Decimals' | translate"
[description]="
- 'Optional override for decimal places. Leave empty to show original values.'
+ 'Optional fixed number of decimal places. Leave empty for automatic formatting.'
| translate
"
>
@@ -29,11 +29,15 @@
matInput
type="number"
[ngModel]="decimals"
+ [disabled]="rawValues"
min="0"
max="10"
step="1"
- [placeholder]="'Original' | translate"
+ [placeholder]="'Automatic' | translate"
(ngModelChange)="updateDecimals($event)"
/>
</mat-form-field>
</sp-form-field>
+<mat-checkbox [ngModel]="rawValues" (ngModelChange)="updateRawValues($event)"
+ >{{ 'Show original values without formatting' | translate }}
+</mat-checkbox>
diff --git a/ui/src/app/chart-shared/components/chart-config/number-format-config/number-format-config.component.ts b/ui/src/app/chart-shared/components/chart-config/number-format-config/number-format-config.component.ts
index 35c4b732b4..fcacc0fef5 100644
--- a/ui/src/app/chart-shared/components/chart-config/number-format-config/number-format-config.component.ts
+++ b/ui/src/app/chart-shared/components/chart-config/number-format-config/number-format-config.component.ts
@@ -29,7 +29,9 @@ import { FormFieldComponent } from '@streampipes/shared-ui';
import { FormsModule } from '@angular/forms';
import { MatFormField } from '@angular/material/form-field';
import { MatInput } from '@angular/material/input';
+import { MatCheckbox } from '@angular/material/checkbox';
import { TranslatePipe } from '@ngx-translate/core';
+import { normalizeDecimals } from '../../../services/formatting';
@Component({
selector: 'sp-number-format-config',
@@ -38,6 +40,7 @@ import { TranslatePipe } from '@ngx-translate/core';
imports: [
FormFieldComponent,
FormsModule,
+ MatCheckbox,
MatFormField,
MatInput,
TranslatePipe,
@@ -63,22 +66,26 @@ export class SpNumberFormatConfigComponent implements OnInit {
});
}
+ updateRawValues(rawValues: boolean): void {
+ this.appearanceConfig.numberFormat ??= {};
+ this.appearanceConfig.numberFormat.rawValues = rawValues;
+ this.widgetConfigurationService.notify({
+ refreshView: true,
+ refreshData: false,
+ });
+ }
+
get decimals(): number | null {
return this.appearanceConfig.numberFormat?.decimals ?? null;
}
+ get rawValues(): boolean {
+ return this.appearanceConfig.numberFormat?.rawValues === true;
+ }
+
private normalizeDecimals(
decimals: number | string | null,
): number | undefined {
- if (decimals === null || decimals === '') {
- return undefined;
- }
-
- const parsedDecimals = Number(decimals);
- if (!Number.isFinite(parsedDecimals)) {
- return undefined;
- }
-
- return Math.min(10, Math.max(0, Math.round(parsedDecimals)));
+ return normalizeDecimals(decimals);
}
}
diff --git a/ui/src/app/chart-shared/components/chart-config/select-color-properties-config/time-series-item-config/time-series-item-config.component.ts b/ui/src/app/chart-shared/components/chart-config/select-color-properties-config/time-series-item-config/time-series-item-config.component.ts
index 636e426c21..ce8ecbdc69 100644
--- a/ui/src/app/chart-shared/components/chart-config/select-color-properties-config/time-series-item-config/time-series-item-config.component.ts
+++ b/ui/src/app/chart-shared/components/chart-config/select-color-properties-config/time-series-item-config/time-series-item-config.component.ts
@@ -22,7 +22,9 @@ import {
Input,
Output,
ChangeDetectionStrategy,
+ inject,
} from '@angular/core';
+import { ChartPaletteService } from '../../../../services/chart-palette.service';
import { DataExplorerField } from '@streampipes/platform-services';
import {
TimeSeriesChartWidgetModel,
@@ -78,6 +80,8 @@ import { MatIcon } from '@angular/material/icon';
],
})
export class SpTimeseriesItemConfigComponent {
+ private paletteService = inject(ChartPaletteService);
+
constructor(private resultLabelService: ResultLabelService) {}
@Input()
@@ -95,15 +99,9 @@ export class SpTimeseriesItemConfigComponent {
@Output()
configChangeEmitter: EventEmitter<void> = new EventEmitter<void>();
- presetColors: string[] = [
- '#39B54A',
- '#1B1464',
- '#f44336',
- '#4CAF50',
- '#FFEB3B',
- '#FFFFFF',
- '#000000',
- ];
+ get presetColors(): string[] {
+ return this.paletteService.colors();
+ }
expanded: boolean = false;
diff --git a/ui/src/app/chart-shared/components/charts/base/base-data-explorer-widget.directive.ts b/ui/src/app/chart-shared/components/charts/base/base-data-explorer-widget.directive.ts
index 889f7e200e..35181043a3 100644
--- a/ui/src/app/chart-shared/components/charts/base/base-data-explorer-widget.directive.ts
+++ b/ui/src/app/chart-shared/components/charts/base/base-data-explorer-widget.directive.ts
@@ -140,6 +140,26 @@ export abstract class BaseDataExplorerWidgetDirective<
protected fieldUpdateService = inject(SpFieldUpdateService);
public fieldService = inject(ChartFieldProviderService);
+ /**
+ * Fields stored in a chart configuration may predate newer field
+ * characteristics (such as the integer flag); the field list derived from
+ * the current schema is the authoritative description.
+ */
+ protected resolveField(
+ field: DataExplorerField | undefined,
+ ): DataExplorerField | undefined {
+ if (!field) {
+ return undefined;
+ }
+ return (
+ this.fieldProvider?.allFields.find(
+ candidate =>
+ candidate.fullDbName === field.fullDbName &&
+ candidate.sourceIndex === field.sourceIndex,
+ ) ?? field
+ );
+ }
+
ngOnInit(): void {
this.currentWidth = this.initialSize.width;
this.currentHeight = this.initialSize.height;
diff --git a/ui/src/app/chart-shared/components/charts/base/echarts-widget.component.html b/ui/src/app/chart-shared/components/charts/base/echarts-widget.component.html
index 02753931c0..f58b09d0a4 100644
--- a/ui/src/app/chart-shared/components/charts/base/echarts-widget.component.html
+++ b/ui/src/app/chart-shared/components/charts/base/echarts-widget.component.html
@@ -16,7 +16,11 @@
~
-->
-<div class="main-panel">
+<div
+ class="main-panel"
+ (mouseenter)="setToolboxHovered(true)"
+ (mouseleave)="setToolboxHovered(false)"
+>
@if (showNoDataInDateRange) {
<sp-no-data-in-date-range [viewDateRange]="timeSettings" class="h-100">
</sp-no-data-in-date-range>
diff --git a/ui/src/app/chart-shared/components/charts/base/echarts-widget.component.ts b/ui/src/app/chart-shared/components/charts/base/echarts-widget.component.ts
index ac07166af9..689806d752 100644
--- a/ui/src/app/chart-shared/components/charts/base/echarts-widget.component.ts
+++ b/ui/src/app/chart-shared/components/charts/base/echarts-widget.component.ts
@@ -30,7 +30,7 @@ import {
import { SpEchartsRenderer } from '../../../models/dataview-dashboard.model';
import { BaseDataExplorerWidgetDirective } from './base-data-explorer-widget.directive';
import { ECharts } from 'echarts/core';
-import { EChartsOption } from 'echarts';
+import { EChartsOption, ToolboxComponentOption } from 'echarts';
import { Subject, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { ResizeEchartsService } from '../../../services/resize-echarts.service';
@@ -69,6 +69,7 @@ export class SpEchartsWidgetComponent<T extends DataExplorerWidgetModel>
renderSubject$: Subscription;
resizeEcharts$: Subscription;
renderer: SpEchartsRenderer<T>;
+ toolboxHovered = false;
resizeEchartsService = inject(ResizeEchartsService);
@@ -121,30 +122,36 @@ export class SpEchartsWidgetComponent<T extends DataExplorerWidgetModel>
this.showInvalidConfiguration = false;
const effectiveWidgetConfig =
this.getWidgetConfigWithDashboardOverrides();
- this.option = {
+ const option: EChartsOption = {
...this.renderer.render(spQueryResult, effectiveWidgetConfig, {
width: this.currentWidth,
height: this.currentHeight,
+ toolboxOverlay: this.usesHoverToolbox,
}),
};
if (this.dashboardChartOverrides?.hideToolbox) {
- const toolbox = this.option['toolbox'];
+ const toolbox = option.toolbox;
if (toolbox) {
(Array.isArray(toolbox) ? toolbox : [toolbox]).forEach(
tb => (tb.show = false),
);
}
+ } else if (this.usesHoverToolbox) {
+ option.toolbox = this.makeHoverToolbox(
+ option.toolbox,
+ this.toolboxHovered,
+ );
}
if (this.kioskMode) {
['toolbox', 'visualMap'].forEach(key => {
- const item = this.option[key];
+ const item = option[key];
if (item) {
(Array.isArray(item) ? item : [item]).forEach(
obj => (obj.show = false),
);
}
});
- Object.assign(this.option, {
+ Object.assign(option, {
grid: {
left: 60,
right: 60,
@@ -153,13 +160,57 @@ export class SpEchartsWidgetComponent<T extends DataExplorerWidgetModel>
},
});
}
+ this.option = option;
} else {
this.showInvalidConfiguration = true;
}
}
+ /**
+ * On dashboards the toolbox is not part of the layout: the chart keeps
+ * the space, and the toolbox appears in the top right corner while the
+ * pointer is over the chart. The chart editor keeps it always visible.
+ */
+ setToolboxHovered(hovered: boolean): void {
+ this.toolboxHovered = hovered;
+ if (!this.usesHoverToolbox || !this.option || !this.eChartsInstance) {
+ return;
+ }
+ const toolbox = this.makeHoverToolbox(this.option.toolbox, hovered);
+ // Mutate the bound options instead of replacing them: a new options
+ // object makes ngx-echarts re-apply everything without merging.
+ this.option.toolbox = toolbox;
+ this.eChartsInstance.setOption({ toolbox });
+ }
+
+ private get usesHoverToolbox(): boolean {
+ return (
+ !this.dataViewMode &&
+ !this.kioskMode &&
+ !this.previewMode &&
+ !this.dashboardChartOverrides?.hideToolbox &&
+ this.dataExplorerWidget.baseAppearanceConfig?.chartAppearance
+ ?.showToolbox !== false
+ );
+ }
+
+ /**
+ * The rendered toolbox (features and overlay placement included) with
+ * its visibility set to the hover state.
+ */
+ private makeHoverToolbox(
+ toolbox: EChartsOption['toolbox'],
+ visible: boolean,
+ ): ToolboxComponentOption {
+ const rendered = Array.isArray(toolbox) ? toolbox[0] : toolbox;
+ return { ...rendered, show: visible };
+ }
+
private getWidgetConfigWithDashboardOverrides(): T {
- if (!this.dashboardChartOverrides?.hideToolbox) {
+ if (
+ !this.dashboardChartOverrides?.hideToolbox &&
+ !this.usesHoverToolbox
+ ) {
return this.dataExplorerWidget;
}
diff --git a/ui/src/app/chart-shared/components/charts/base/no-data/no-data-in-date-range.component.html b/ui/src/app/chart-shared/components/charts/base/no-data/no-data-in-date-range.component.html
index f5aa441630..9af7bff8ee 100644
--- a/ui/src/app/chart-shared/components/charts/base/no-data/no-data-in-date-range.component.html
+++ b/ui/src/app/chart-shared/components/charts/base/no-data/no-data-in-date-range.component.html
@@ -31,8 +31,7 @@
{{ 'Found no data in selected time range' | translate }}
</div>
<div class="default-text text-md">
- {{ viewDateRange.startTime | date: 'MM/dd/yyyy HH:mm' }} -
- {{ viewDateRange.endTime | date: 'MM/dd/yyyy HH:mm' }}
+ {{ rangeLabel }}
</div>
</div>
</div>
diff --git a/ui/src/app/chart-shared/components/charts/base/no-data/no-data-in-date-range.component.ts b/ui/src/app/chart-shared/components/charts/base/no-data/no-data-in-date-range.component.ts
index af082c6908..6928f9d715 100644
--- a/ui/src/app/chart-shared/components/charts/base/no-data/no-data-in-date-range.component.ts
+++ b/ui/src/app/chart-shared/components/charts/base/no-data/no-data-in-date-range.component.ts
@@ -16,7 +16,12 @@
*
*/
-import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
+import {
+ Component,
+ Input,
+ ChangeDetectionStrategy,
+ inject,
+} from '@angular/core';
import { TimeSettings } from '@streampipes/platform-services';
import {
FlexDirective,
@@ -24,8 +29,8 @@ import {
LayoutDirective,
LayoutGapDirective,
} from '@ngbracket/ngx-layout/flex';
-import { DatePipe } from '@angular/common';
import { TranslatePipe } from '@ngx-translate/core';
+import { ChartTimeFormatService } from '../../../../services/formatting';
@Component({
selector: 'sp-no-data-in-date-range',
@@ -37,13 +42,19 @@ import { TranslatePipe } from '@ngx-translate/core';
LayoutAlignDirective,
FlexDirective,
LayoutGapDirective,
- DatePipe,
TranslatePipe,
],
})
export class NoDataInDateRangeComponent {
+ private timeFormatService = inject(ChartTimeFormatService);
+
@Input()
public viewDateRange: TimeSettings;
- constructor() {}
+ get rangeLabel(): string {
+ return this.timeFormatService.formatRange(
+ this.viewDateRange?.startTime,
+ this.viewDateRange?.endTime,
+ );
+ }
}
diff --git a/ui/src/app/chart-shared/components/charts/density/density-renderer.service.ts b/ui/src/app/chart-shared/components/charts/density/density-renderer.service.ts
index 065d6e6c80..51c22bdc33 100644
--- a/ui/src/app/chart-shared/components/charts/density/density-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/density/density-renderer.service.ts
@@ -39,9 +39,11 @@ export class SpDensityRendererService extends SpBaseEchartsRenderer<CorrelationC
widgetConfig: CorrelationChartWidgetModel,
widgetSize: WidgetSize,
): void {
- const decimals = this.getDecimals(widgetConfig);
const xField = this.getXField(widgetConfig);
const yField = this.getYField(widgetConfig);
+ const xFormat = this.getAxisNumberFormat(widgetConfig, xField);
+ const yFormat = this.getAxisNumberFormat(widgetConfig, yField);
+ const valueFormat = this.getNumberFormat(widgetConfig);
const dataset = this.datasetUtilsService.findPreparedDataset(
datasets,
xField.sourceIndex,
@@ -72,7 +74,7 @@ export class SpDensityRendererService extends SpBaseEchartsRenderer<CorrelationC
max: Math.ceil(stats.maxX + 1),
axisLabel: {
formatter: (value: number | string) =>
- this.formatNumber(value, decimals),
+ this.formatNumber(value, xFormat),
},
name:
widgetConfig.visualizationConfig.labelX ||
@@ -89,7 +91,7 @@ export class SpDensityRendererService extends SpBaseEchartsRenderer<CorrelationC
max: Math.ceil(stats.maxY + 1),
axisLabel: {
formatter: (value: number | string) =>
- this.formatNumber(value, decimals),
+ this.formatNumber(value, yFormat),
},
name:
widgetConfig.visualizationConfig.labelY ||
@@ -116,7 +118,7 @@ export class SpDensityRendererService extends SpBaseEchartsRenderer<CorrelationC
tooltip: {
...tooltip,
valueFormatter: (value: unknown) =>
- this.formatNumber(value, decimals),
+ this.formatNumber(value, valueFormat),
},
series: [
{
diff --git a/ui/src/app/chart-shared/components/charts/gauge/gauge-renderer.service.ts b/ui/src/app/chart-shared/components/charts/gauge/gauge-renderer.service.ts
index 619c9c3b0d..019a5f7e45 100644
--- a/ui/src/app/chart-shared/components/charts/gauge/gauge-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/gauge/gauge-renderer.service.ts
@@ -32,10 +32,15 @@ import { WidgetSize } from '../../../models/dataset.model';
import { EchartsBasicOptionsGeneratorService } from '../../../echarts-renderer/echarts-basic-options-generator.service';
import { SpFieldUpdateService } from '../../../services/field-update.service';
import { ResultLabelService } from '../../../services/result-label.service';
+import {
+ ChartNumberFormatService,
+ NumberFormatOptions,
+} from '../../../services/formatting';
@Injectable({ providedIn: 'root' })
export class SpGaugeRendererService implements SpEchartsRenderer<GaugeWidgetModel> {
protected fieldUpdateService = inject(SpFieldUpdateService);
+ protected numberFormatService = inject(ChartNumberFormatService);
protected echartsBaseOptionsGenerator = inject(
EchartsBasicOptionsGeneratorService,
);
@@ -45,7 +50,7 @@ export class SpGaugeRendererService implements SpEchartsRenderer<GaugeWidgetMode
seriesName: string,
selectedField: DataExplorerField,
value: number,
- decimals: number | undefined,
+ numberFormat: NumberFormatOptions,
widgetConfig: GaugeWidgetModel,
widgetSize: WidgetSize,
gaugeLayout: GaugeLayout,
@@ -84,7 +89,7 @@ export class SpGaugeRendererService implements SpEchartsRenderer<GaugeWidgetMode
show: true,
valueAnimation: false,
formatter: (currentValue: number) =>
- this.formatNumber(currentValue, decimals),
+ this.formatNumber(currentValue, numberFormat),
fontSize: 14 * clamp,
offsetCenter: [0, gaugeLayout.detailOffsetY],
},
@@ -140,10 +145,11 @@ export class SpGaugeRendererService implements SpEchartsRenderer<GaugeWidgetMode
);
const appearanceConfig =
widgetConfig.baseAppearanceConfig as WidgetEchartsAppearanceConfig;
- const decimals = this.normalizeDecimals(
- appearanceConfig.numberFormat?.decimals,
- );
const selectedField = this.getSelectedField(widgetConfig);
+ const numberFormat = this.numberFormatService.resolveOptions(
+ appearanceConfig,
+ selectedField,
+ );
const sourceIndex = selectedField.sourceIndex;
const dataSeries = queryResult[sourceIndex].allDataSeries[0];
const columnIndex = dataSeries.headers.indexOf(
@@ -166,13 +172,20 @@ export class SpGaugeRendererService implements SpEchartsRenderer<GaugeWidgetMode
);
Object.assign(option, {
- toolbox: {
- ...toolbox,
- left: 10,
- right: 'auto',
- top: 4,
- show: showToolbox,
- },
+ toolbox: widgetSize.toolboxOverlay
+ ? {
+ ...toolbox,
+ ...this.echartsBaseOptionsGenerator.overlayToolboxPlacement(
+ 4,
+ ),
+ }
+ : {
+ ...toolbox,
+ left: 10,
+ right: 'auto',
+ top: 4,
+ show: showToolbox,
+ },
legend: {
...legend,
show: showLegend,
@@ -181,7 +194,7 @@ export class SpGaugeRendererService implements SpEchartsRenderer<GaugeWidgetMode
'',
selectedField,
data,
- decimals,
+ numberFormat,
widgetConfig,
widgetSize,
gaugeLayout,
@@ -191,25 +204,11 @@ export class SpGaugeRendererService implements SpEchartsRenderer<GaugeWidgetMode
return option;
}
- private formatNumber(value: number, decimals?: number): string {
- if (decimals === undefined) {
- return String(value);
- }
-
- return value.toFixed(decimals);
- }
-
- private normalizeDecimals(decimals: unknown): number | undefined {
- if (decimals === null || decimals === undefined || decimals === '') {
- return undefined;
- }
-
- const parsedValue = Number(decimals);
- if (!Number.isFinite(parsedValue)) {
- return undefined;
- }
-
- return Math.min(10, Math.max(0, Math.round(parsedValue)));
+ private formatNumber(
+ value: number,
+ numberFormat: NumberFormatOptions,
+ ): string {
+ return this.numberFormatService.format(value, numberFormat);
}
private makeGaugeLayout(
diff --git a/ui/src/app/chart-shared/components/charts/heatmap/heatmap-renderer.service.ts b/ui/src/app/chart-shared/components/charts/heatmap/heatmap-renderer.service.ts
index b17ed70b86..41ee826e8d 100644
--- a/ui/src/app/chart-shared/components/charts/heatmap/heatmap-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/heatmap/heatmap-renderer.service.ts
@@ -36,9 +36,8 @@ export class SpHeatmapRendererService extends SpBaseEchartsRenderer<HeatmapWidge
widgetConfig: HeatmapWidgetModel,
): void {
this.basicOptions(options, widgetConfig);
- const decimals = this.getDecimals(widgetConfig);
-
const field = widgetConfig.visualizationConfig.selectedHeatProperty;
+ const numberFormat = this.getNumberFormat(widgetConfig, field);
const sourceIndex = field.sourceIndex;
const rawDataset = this.datasetUtilsService.findPreparedDataset(
@@ -60,17 +59,36 @@ export class SpHeatmapRendererService extends SpBaseEchartsRenderer<HeatmapWidge
const transformedDataset = (
rawDataset.rawDataset.source as OptionSourceDataArrayRows
).map((row, index) => {
+ // keep the numeric value: the visual map needs it, labels format it
return [
index,
this.makeTag(rawDataset.rawDataset.dimensions, tags, row),
- this.formatNumber(row[heatIndex], decimals),
+ row[heatIndex],
];
});
+ const formatCellValue = (params: { value?: unknown }) =>
+ this.formatNumber(
+ Array.isArray(params.value) ? params.value[2] : params.value,
+ numberFormat,
+ );
options.dataset = { source: transformedDataset };
- (options.xAxis as any).data = rawDatasetSource.map(s => {
- return new Date(s[0]).toLocaleString();
- });
+ (options.xAxis as any).data = this.timeFormatService.formatTimestamps(
+ rawDatasetSource.map(s => s[0] as number | string),
+ );
+ options.tooltip = {
+ ...(!Array.isArray(options.tooltip) && options.tooltip
+ ? options.tooltip
+ : {}),
+ formatter: params => {
+ const param = Array.isArray(params) ? params[0] : params;
+ const value = formatCellValue(param);
+ const label = Array.isArray(param.value)
+ ? `${param.name ?? ''}${param.value[1] ? ` · ${param.value[1]}` : ''}`
+ : (param.name ?? '');
+ return `${param.marker ?? ''}${label}<br/><b>${value}</b>`;
+ },
+ };
options.series = [
{
name: '',
@@ -82,6 +100,7 @@ export class SpHeatmapRendererService extends SpBaseEchartsRenderer<HeatmapWidge
},
label: {
show: widgetConfig.visualizationConfig.showLabelsProperty,
+ formatter: formatCellValue,
},
emphasis: {
itemStyle: {
diff --git a/ui/src/app/chart-shared/components/charts/histogram/histogram-renderer.service.ts b/ui/src/app/chart-shared/components/charts/histogram/histogram-renderer.service.ts
index 9afe6182d6..fbcfb03318 100644
--- a/ui/src/app/chart-shared/components/charts/histogram/histogram-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/histogram/histogram-renderer.service.ts
@@ -19,16 +19,20 @@
import { BarSeriesOption, EChartsOption } from 'echarts';
import { SpBaseSingleFieldEchartsRenderer } from '../../../echarts-renderer/base-single-field-echarts-renderer';
import type { DataTransformOption } from 'echarts/types/src/data/helper/transform.d.ts';
-import { Injectable } from '@angular/core';
+import { inject, Injectable } from '@angular/core';
import { DataExplorerField } from '@streampipes/platform-services';
import { HistogramChartWidgetModel } from './model/histogram-chart-widget.model';
import { FieldUpdateInfo } from '../../../models/field-update.model';
+import { NumberFormatOptions } from '../../../services/formatting';
+import { ResultLabelService } from '../../../services/result-label.service';
@Injectable({ providedIn: 'root' })
export class SpHistogramRendererService extends SpBaseSingleFieldEchartsRenderer<
HistogramChartWidgetModel,
BarSeriesOption
> {
+ private resultLabelService = inject(ResultLabelService);
+
addAdditionalConfigs(
option: EChartsOption,
widgetConfig?: HistogramChartWidgetModel,
@@ -37,7 +41,14 @@ export class SpHistogramRendererService extends SpBaseSingleFieldEchartsRenderer
return;
}
- const decimals = this.getDecimals(widgetConfig);
+ const valueFormat = this.getNumberFormat(
+ widgetConfig,
+ this.getSelectedField(widgetConfig),
+ );
+ const countFormat: NumberFormatOptions = {
+ ...valueFormat,
+ integer: true,
+ };
const tooltip =
!Array.isArray(option.tooltip) && option.tooltip
? option.tooltip
@@ -45,11 +56,34 @@ export class SpHistogramRendererService extends SpBaseSingleFieldEchartsRenderer
option.tooltip = {
...tooltip,
valueFormatter: (value: unknown) =>
- this.formatNumber(value, decimals),
+ this.formatNumber(value, countFormat),
};
- this.applyAxisLabelFormatting(option.xAxis, decimals);
- this.applyAxisLabelFormatting(option.yAxis, decimals);
+ this.applyAxisLabelFormatting(
+ option.xAxis,
+ this.getAxisNumberFormat(
+ widgetConfig,
+ this.getSelectedField(widgetConfig),
+ ),
+ );
+ this.applyAxisLabelFormatting(option.yAxis, countFormat);
+ this.hideLegendForSingleSeries(option);
+ }
+
+ /** A histogram of one field has nothing to select in a legend. */
+ private hideLegendForSingleSeries(option: EChartsOption): void {
+ const seriesCount = Array.isArray(option.series)
+ ? option.series.length
+ : option.series
+ ? 1
+ : 0;
+ if (seriesCount <= 1) {
+ const legend =
+ !Array.isArray(option.legend) && option.legend
+ ? option.legend
+ : {};
+ option.legend = { ...legend, show: false };
+ }
}
public handleUpdatedFields(
@@ -108,32 +142,30 @@ export class SpHistogramRendererService extends SpBaseSingleFieldEchartsRenderer
}
getDefaultSeriesName(widgetConfig: HistogramChartWidgetModel): string {
- return widgetConfig.visualizationConfig.selectedProperty.fullDbName;
+ const field = this.getSelectedField(widgetConfig);
+ const queryConfig =
+ widgetConfig.dataConfig.sourceConfigs[field.sourceIndex]
+ ?.queryConfig;
+ return queryConfig
+ ? this.resultLabelService.resolveLabel(queryConfig, field)
+ : field.fullDbName;
}
private applyAxisLabelFormatting(
axis: EChartsOption['xAxis'] | EChartsOption['yAxis'] | undefined,
- decimals: number | undefined,
+ numberFormat: NumberFormatOptions,
): void {
if (!axis) {
return;
}
- if (Array.isArray(axis)) {
- axis.forEach(a => {
- (a as any).axisLabel = {
- ...(a as any).axisLabel,
- formatter: (value: number | string) =>
- this.formatNumber(value, decimals),
- };
- });
- return;
- }
-
- (axis as any).axisLabel = {
- ...(axis as any).axisLabel,
- formatter: (value: number | string) =>
- this.formatNumber(value, decimals),
- };
+ const axes = Array.isArray(axis) ? axis : [axis];
+ axes.forEach(a => {
+ (a as any).axisLabel = {
+ ...(a as any).axisLabel,
+ formatter: (value: number | string) =>
+ this.formatNumber(value, numberFormat),
+ };
+ });
}
}
diff --git a/ui/src/app/chart-shared/components/charts/indicator/indicator-widget.component.ts b/ui/src/app/chart-shared/components/charts/indicator/indicator-widget.component.ts
index adbccf4c7b..05eb7aeb49 100644
--- a/ui/src/app/chart-shared/components/charts/indicator/indicator-widget.component.ts
+++ b/ui/src/app/chart-shared/components/charts/indicator/indicator-widget.component.ts
@@ -44,6 +44,7 @@ import {
IndicatorAppearanceConfig,
IndicatorChartWidgetModel,
} from './model/indicator-chart-widget.model';
+import { ChartNumberFormatService } from '../../../services/formatting';
@Component({
selector: 'sp-data-explorer-indicator-widget',
@@ -71,6 +72,7 @@ export class IndicatorWidgetComponent
private latestData: SpQueryResult[] = [];
private readonly locale = inject(LOCALE_ID);
private readonly translateService = inject(TranslateService);
+ private readonly numberFormatService = inject(ChartNumberFormatService);
ngOnInit(): void {
super.ngOnInit();
@@ -452,9 +454,15 @@ export class IndicatorWidgetComponent
private formatValue(value: unknown): string {
if (typeof value === 'number') {
- return new Intl.NumberFormat(this.locale, {
- maximumFractionDigits: 3,
- }).format(value);
+ return this.numberFormatService.format(
+ value,
+ this.numberFormatService.resolveOptions(
+ this.appearanceConfig,
+ this.resolveField(
+ this.dataExplorerWidget.visualizationConfig.valueField,
+ ),
+ ),
+ );
}
if (typeof value === 'boolean') {
diff --git a/ui/src/app/chart-shared/components/charts/indicator/model/indicator-chart-widget.model.ts b/ui/src/app/chart-shared/components/charts/indicator/model/indicator-chart-widget.model.ts
index dc462922fc..e5d4d46560 100644
--- a/ui/src/app/chart-shared/components/charts/indicator/model/indicator-chart-widget.model.ts
+++ b/ui/src/app/chart-shared/components/charts/indicator/model/indicator-chart-widget.model.ts
@@ -23,7 +23,7 @@ import {
} from '@streampipes/platform-services';
import {
DataExplorerVisConfig,
- WidgetBaseAppearanceConfig,
+ WidgetNumberAppearanceConfig,
} from '../../../../models/dataview-dashboard.model';
export interface IndicatorChartVisConfig extends DataExplorerVisConfig {
@@ -34,7 +34,7 @@ export interface IndicatorChartVisConfig extends DataExplorerVisConfig {
description?: string;
}
-export interface IndicatorAppearanceConfig extends WidgetBaseAppearanceConfig {
+export interface IndicatorAppearanceConfig extends WidgetNumberAppearanceConfig {
valueFontSize?: number;
deltaFontSize?: number;
}
diff --git a/ui/src/app/chart-shared/components/charts/pie/config/pie-chart-widget-config.component.ts b/ui/src/app/chart-shared/components/charts/pie/config/pie-chart-widget-config.component.ts
index 4080c06d85..f52f075949 100644
--- a/ui/src/app/chart-shared/components/charts/pie/config/pie-chart-widget-config.component.ts
+++ b/ui/src/app/chart-shared/components/charts/pie/config/pie-chart-widget-config.component.ts
@@ -82,7 +82,7 @@ export class SpPieChartWidgetConfigComponent extends BaseWidgetConfig<
config.minAngle ??= 0;
config.labelMode ??= 'name_percent';
config.labelPosition ??= 'outside';
- config.labelAlignTo ??= 'edge';
+ config.labelAlignTo ??= 'labelLine';
config.avoidLabelOverlap ??= true;
config.showLabelLine ??= true;
config.topNEnabled ??= false;
diff --git a/ui/src/app/chart-shared/components/charts/pie/pie-renderer.service.ts b/ui/src/app/chart-shared/components/charts/pie/pie-renderer.service.ts
index 4b802758ec..f83c49bc83 100644
--- a/ui/src/app/chart-shared/components/charts/pie/pie-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/pie/pie-renderer.service.ts
@@ -27,6 +27,8 @@ import {
import { FieldUpdateInfo } from '../../../models/field-update.model';
import { ZRColor } from 'echarts/types/dist/shared';
import { ColorMappingService } from '../../../services/color-mapping.service';
+import { NumberFormatOptions } from '../../../services/formatting';
+import { WidgetSize } from '../../../models/dataset.model';
@Injectable({ providedIn: 'root' })
export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
@@ -78,6 +80,7 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
addAdditionalConfigs(
option: EChartsOption,
widgetConfig: PieChartWidgetModel,
+ widgetSize?: WidgetSize,
): void {
const config = this.getSafeConfig(widgetConfig);
if (config.selectedProperty.fieldCharacteristics.binary) {
@@ -94,7 +97,10 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
},
};
}
- this.applySinglePieResponsiveLayout(option);
+ this.applySinglePieResponsiveLayout(
+ option,
+ widgetSize?.toolboxOverlay ?? false,
+ );
}
addSeriesItem(
@@ -105,7 +111,7 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
const config = this.getSafeConfig(widgetConfig);
const innerRadius = config.selectedRadius;
const colorMapping = config.colorMappingsPieChart;
- const decimals = this.getDecimals(widgetConfig);
+ const numberFormat = this.getNumberFormat(widgetConfig);
const labelMode = config.labelMode;
const labelPosition = config.labelPosition;
const labelAlignTo = config.labelAlignTo;
@@ -132,7 +138,7 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
params.value[1],
params.percent,
labelMode,
- decimals,
+ numberFormat,
true,
)}`;
},
@@ -154,7 +160,7 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
params.value[1],
params.percent,
labelMode,
- decimals,
+ numberFormat,
);
},
},
@@ -171,8 +177,8 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
return (colorMapping.find(
c => c.value === category.toString(),
)?.color ||
- this.colorMappingService.getDefaultColor(
- params.data[0],
+ this.colorMappingService.getPaletteColor(
+ params.dataIndex,
)) as ZRColor;
},
},
@@ -184,16 +190,22 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
rawValue: unknown,
rawPercent: unknown,
labelMode: PieChartWidgetModel['visualizationConfig']['labelMode'],
- decimals: number | undefined,
+ numberFormat: NumberFormatOptions,
boldValue = false,
): string {
- const value = this.formatNumber(rawValue, decimals);
+ // pie slices are event counts, so the value never has fraction digits
+ const value = this.formatNumber(rawValue, {
+ ...numberFormat,
+ integer: true,
+ });
const valueText = boldValue ? `<b>${value}</b>` : value;
- const percent =
+ const percentText =
typeof rawPercent === 'number'
- ? this.formatNumber(rawPercent, decimals)
- : String(rawPercent ?? '');
- const percentText = `${percent}%`;
+ ? this.numberFormatService.formatPercent(
+ rawPercent / 100,
+ numberFormat,
+ )
+ : `${String(rawPercent ?? '')}%`;
if (labelMode === 'name') {
return mappedLabel;
@@ -262,7 +274,7 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
minAngle: Number.isFinite(config.minAngle) ? config.minAngle : 0,
labelMode: config.labelMode || 'name_percent',
labelPosition: config.labelPosition || 'outside',
- labelAlignTo: config.labelAlignTo || 'edge',
+ labelAlignTo: config.labelAlignTo || 'labelLine',
avoidLabelOverlap:
typeof config.avoidLabelOverlap === 'boolean'
? config.avoidLabelOverlap
@@ -284,7 +296,10 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
};
}
- private applySinglePieResponsiveLayout(option: EChartsOption): void {
+ private applySinglePieResponsiveLayout(
+ option: EChartsOption,
+ toolboxOverlay: boolean,
+ ): void {
const pieSeries = Array.isArray(option.series)
? option.series
: option.series
@@ -316,13 +331,20 @@ export class SpPieRendererService extends SpBaseSingleFieldEchartsRenderer<
const pieTop = topControlsBottom > 0 ? topControlsBottom + 8 : 8;
const pieBottom = 8;
- option.toolbox = {
- ...toolbox,
- show: showToolbox,
- left: 10,
- right: 'auto',
- top: toolboxTop,
- };
+ option.toolbox = toolboxOverlay
+ ? {
+ ...toolbox,
+ ...this.basicOptionsGeneratorService.overlayToolboxPlacement(
+ legendTop + legendHeight + 4,
+ ),
+ }
+ : {
+ ...toolbox,
+ show: showToolbox,
+ left: 10,
+ right: 'auto',
+ top: toolboxTop,
+ };
option.legend = {
...legend,
show: showLegend,
diff --git a/ui/src/app/chart-shared/components/charts/progress-bar/progress-bar-widget.component.ts b/ui/src/app/chart-shared/components/charts/progress-bar/progress-bar-widget.component.ts
index 89646e436a..d03e35aecc 100644
--- a/ui/src/app/chart-shared/components/charts/progress-bar/progress-bar-widget.component.ts
+++ b/ui/src/app/chart-shared/components/charts/progress-bar/progress-bar-widget.component.ts
@@ -19,7 +19,6 @@
import { NgStyle } from '@angular/common';
import {
Component,
- LOCALE_ID,
OnInit,
inject,
ChangeDetectionStrategy,
@@ -41,9 +40,9 @@ import {
} from './model/progress-bar-widget.model';
import {
clampValue,
- formatWidgetNumber,
scaleResponsiveValue,
} from '../../../services/widget-render.utils';
+import { ChartNumberFormatService } from '../../../services/formatting';
interface ProgressBarViewModel {
ratio: number;
@@ -75,8 +74,8 @@ export class ProgressBarWidgetComponent
private hasReceivedData = false;
private latestData: SpQueryResult[] = [];
- private readonly locale = inject(LOCALE_ID);
private readonly chartRegistry = inject(ChartRegistry);
+ private readonly numberFormatService = inject(ChartNumberFormatService);
ngOnInit(): void {
super.ngOnInit();
@@ -288,22 +287,30 @@ export class ProgressBarWidgetComponent
? clampValue(unclampedRatio, 0, 1)
: unclampedRatio;
+ const config = this.dataExplorerWidget.visualizationConfig;
+ const currentFormat = this.numberFormatService.resolveOptions(
+ this.appearanceConfig,
+ this.resolveField(config.currentValueField),
+ );
+ const targetFormat = this.numberFormatService.resolveOptions(
+ this.appearanceConfig,
+ this.resolveField(
+ config.targetSource === 'field'
+ ? config.targetField
+ : config.currentValueField,
+ ),
+ );
+
this.progressView = {
ratio,
- percentLabel: `${formatWidgetNumber(
- ratio * 100,
- this.locale,
- this.appearanceConfig.numberFormat?.decimals,
- )}%`,
- valueLabel: `${formatWidgetNumber(
+ percentLabel: this.numberFormatService.formatPercent(
+ ratio,
+ currentFormat,
+ ),
+ valueLabel: `${this.numberFormatService.format(
currentValue,
- this.locale,
- this.appearanceConfig.numberFormat?.decimals,
- )} / ${formatWidgetNumber(
- targetValue,
- this.locale,
- this.appearanceConfig.numberFormat?.decimals,
- )}`,
+ currentFormat,
+ )} / ${this.numberFormatService.format(targetValue, targetFormat)}`,
statusLabel: inverted ? 'Remaining' : 'Completed',
};
diff --git a/ui/src/app/chart-shared/components/charts/scatter/scatter-renderer.service.ts b/ui/src/app/chart-shared/components/charts/scatter/scatter-renderer.service.ts
index cf6802114e..7998a34233 100644
--- a/ui/src/app/chart-shared/components/charts/scatter/scatter-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/scatter/scatter-renderer.service.ts
@@ -31,9 +31,11 @@ export class SpScatterRendererService extends SpBaseEchartsRenderer<CorrelationC
widgetConfig: CorrelationChartWidgetModel,
_widgetSize: WidgetSize,
): void {
- const decimals = this.getDecimals(widgetConfig);
const xField = this.getXField(widgetConfig);
const yField = this.getYField(widgetConfig);
+ const xFormat = this.getAxisNumberFormat(widgetConfig, xField);
+ const yFormat = this.getAxisNumberFormat(widgetConfig, yField);
+ const valueFormat = this.getNumberFormat(widgetConfig);
const dataset = this.datasetUtilsService.findPreparedDataset(
generatedDataset,
xField.sourceIndex,
@@ -73,7 +75,7 @@ export class SpScatterRendererService extends SpBaseEchartsRenderer<CorrelationC
max: 'dataMax',
axisLabel: {
formatter: (value: number | string) =>
- this.formatNumber(value, decimals),
+ this.formatNumber(value, xFormat),
},
name:
widgetConfig.visualizationConfig.labelX ||
@@ -90,7 +92,7 @@ export class SpScatterRendererService extends SpBaseEchartsRenderer<CorrelationC
max: 'dataMax',
axisLabel: {
formatter: (value: number | string) =>
- this.formatNumber(value, decimals),
+ this.formatNumber(value, yFormat),
},
name:
widgetConfig.visualizationConfig.labelY ||
@@ -105,7 +107,7 @@ export class SpScatterRendererService extends SpBaseEchartsRenderer<CorrelationC
tooltip: {
...tooltip,
valueFormatter: (value: unknown) =>
- this.formatNumber(value, decimals),
+ this.formatNumber(value, valueFormat),
},
});
}
diff --git a/ui/src/app/chart-shared/components/charts/status-heatmap/status-heatmap-renderer.service.ts b/ui/src/app/chart-shared/components/charts/status-heatmap/status-heatmap-renderer.service.ts
index 70bae75502..174f41a64d 100644
--- a/ui/src/app/chart-shared/components/charts/status-heatmap/status-heatmap-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/status-heatmap/status-heatmap-renderer.service.ts
@@ -88,9 +88,12 @@ export class SpStatusHeatmapRendererService extends SpBaseEchartsRenderer<Status
options.dataset = { source: transformedDataset };
- (options.xAxis as any).data = rawDatasetSource.map(s => {
- return new Date(s[0]).toLocaleString();
- });
+ const timestamps = rawDatasetSource.map(
+ s => s[0] as number | string,
+ );
+ const timeSpan = this.timeFormatService.spanOf(timestamps);
+ (options.xAxis as any).data =
+ this.timeFormatService.formatTimestamps(timestamps);
options.tooltip = {
formatter: params => {
@@ -102,8 +105,12 @@ export class SpStatusHeatmapRendererService extends SpBaseEchartsRenderer<Status
colorMapping.find(
c => c.value === originalValue.toString(),
)?.label || originalValue.toString();
+ const timeLabel = this.timeFormatService.formatTimestamp(
+ timestamp as number | string,
+ timeSpan,
+ );
- return `${params.marker} ${new Date(timestamp).toLocaleString()}<br/>Status: <b>${statusLabel}</b>`;
+ return `${params.marker} ${timeLabel}<br/>Status: <b>${statusLabel}</b>`;
},
};
@@ -114,7 +121,7 @@ export class SpStatusHeatmapRendererService extends SpBaseEchartsRenderer<Status
val.toString(),
color:
colorMapping.find(c => c.value === val.toString())?.color ||
- this.colorMappingService.getDefaultColor(val.toString()),
+ this.colorMappingService.getPaletteColor(index),
}));
options.visualMap = {
diff --git a/ui/src/app/chart-shared/components/charts/status/status-widget.component.html b/ui/src/app/chart-shared/components/charts/status/status-widget.component.html
index 52fab8afbc..b70aadb705 100644
--- a/ui/src/app/chart-shared/components/charts/status/status-widget.component.html
+++ b/ui/src/app/chart-shared/components/charts/status/status-widget.component.html
@@ -51,7 +51,7 @@
<div>
<h5>
{{ 'Last seen:' | translate }}
- {{ lastTimestamp | date: 'short' }}
+ {{ lastSeenLabel }}
</h5>
</div>
}
diff --git a/ui/src/app/chart-shared/components/charts/status/status-widget.component.ts b/ui/src/app/chart-shared/components/charts/status/status-widget.component.ts
index dc07de03e2..544e7d5bc0 100644
--- a/ui/src/app/chart-shared/components/charts/status/status-widget.component.ts
+++ b/ui/src/app/chart-shared/components/charts/status/status-widget.component.ts
@@ -16,8 +16,14 @@
*
*/
-import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
+import {
+ Component,
+ OnInit,
+ ChangeDetectionStrategy,
+ inject,
+} from '@angular/core';
import { BaseDataExplorerWidgetDirective } from '../base/base-data-explorer-widget.directive';
+import { ChartTimeFormatService } from '../../../services/formatting';
import { StatusWidgetModel } from './model/status-widget.model';
import {
DataExplorerField,
@@ -28,7 +34,7 @@ import {
LayoutAlignDirective,
LayoutDirective,
} from '@ngbracket/ngx-layout/flex';
-import { DatePipe, NgClass, NgStyle } from '@angular/common';
+import { NgClass, NgStyle } from '@angular/common';
import { ClassDirective, StyleDirective } from '@ngbracket/ngx-layout/extended';
import { NoDataInDateRangeComponent } from '../base/no-data/no-data-in-date-range.component';
import { TranslatePipe } from '@ngx-translate/core';
@@ -47,7 +53,6 @@ import { TranslatePipe } from '@ngx-translate/core';
NoDataInDateRangeComponent,
NgClass,
ClassDirective,
- DatePipe,
TranslatePipe,
],
})
@@ -77,6 +82,12 @@ export class StatusWidgetComponent
lastTimestamp = 0;
active: boolean;
+ private readonly timeFormatService = inject(ChartTimeFormatService);
+
+ get lastSeenLabel(): string {
+ return this.timeFormatService.formatTimestamp(this.lastTimestamp);
+ }
+
ngOnInit(): void {
super.ngOnInit();
this.updateSettings();
diff --git a/ui/src/app/chart-shared/components/charts/table/table-widget.component.html b/ui/src/app/chart-shared/components/charts/table/table-widget.component.html
index 325e93815f..0d6c77cefc 100644
--- a/ui/src/app/chart-shared/components/charts/table/table-widget.component.html
+++ b/ui/src/app/chart-shared/components/charts/table/table-widget.component.html
@@ -88,7 +88,10 @@
>
<span>
@if (column === 'time') {
- {{ 'Time' | translate }}
+ {{
+ timeHeaderLabel ??
+ ('Time' | translate)
+ }}
} @else {
<span
[attr.data-cy]="
@@ -193,9 +196,7 @@
>
@if (column === 'time') {
{{
- asTimestamp(row[column])
- | date
- : 'yyyy-MM-dd HH:mm:ss.SSS'
+ formatTimestamp(row[column])
}}
} @else {
{{
diff --git a/ui/src/app/chart-shared/components/charts/table/table-widget.component.ts b/ui/src/app/chart-shared/components/charts/table/table-widget.component.ts
index 56dac0faba..3efd1b25b5 100644
--- a/ui/src/app/chart-shared/components/charts/table/table-widget.component.ts
+++ b/ui/src/app/chart-shared/components/charts/table/table-widget.component.ts
@@ -16,7 +16,7 @@
*
*/
-import { DatePipe, NgClass, NgStyle } from '@angular/common';
+import { NgClass, NgStyle } from '@angular/common';
import {
CdkDrag,
CdkDragDrop,
@@ -48,6 +48,10 @@ import { TooMuchDataComponent } from '../base/too-much-data/too-much-data.compon
import { TranslatePipe } from '@ngx-translate/core';
import { WidgetNumberAppearanceConfig } from '../../../models/dataview-dashboard.model';
import { ResultLabelService } from '../../../services/result-label.service';
+import {
+ ChartNumberFormatService,
+ ChartTimeFormatService,
+} from '../../../services/formatting';
type SortDirection = 'asc' | 'desc' | '';
@@ -117,13 +121,14 @@ const TIMESTAMP_MASK = 'yyyy-mm-dd HH:mm:ss.SSS';
MatIcon,
MatCheckbox,
FormsModule,
- DatePipe,
TranslatePipe,
],
})
export class TableWidgetComponent extends BaseDataExplorerWidgetDirective<TableWidgetModel> {
private elRef = inject(ElementRef);
private resultLabelService = inject(ResultLabelService);
+ private numberFormatService = inject(ChartNumberFormatService);
+ private timeFormatService = inject(ChartTimeFormatService);
private static readonly DEFAULT_PAGE_SIZE = 20;
@@ -910,7 +915,7 @@ export class TableWidgetComponent extends BaseDataExplorerWidgetDirective<TableW
formatDisplayCellValue(column: string, value: unknown): unknown {
if (this.isNumericColumn(column)) {
- return this.formatNumericValue(value);
+ return this.formatNumericValue(column, value);
}
return this.formatCellValue(column, value);
@@ -951,35 +956,55 @@ export class TableWidgetComponent extends BaseDataExplorerWidgetDirective<TableW
: TableWidgetComponent.DEFAULT_PAGE_SIZE;
}
- private formatNumericValue(value: unknown): unknown {
+ private formatNumericValue(column: string, value: unknown): unknown {
const numericValue = this.toNumber(value);
if (numericValue === undefined) {
return this.formatCellValue('', value);
}
- const decimals = this.getDecimals();
- return decimals === undefined
- ? String(numericValue)
- : numericValue.toFixed(decimals);
+ return this.numberFormatService.format(
+ numericValue,
+ this.numberFormatService.resolveOptions(
+ this.dataExplorerWidget
+ .baseAppearanceConfig as WidgetNumberAppearanceConfig,
+ this.resolveField(this.getFieldByColumnName(column)),
+ ),
+ );
}
- private getDecimals(): number | undefined {
- const appearanceConfig = this.dataExplorerWidget
- .baseAppearanceConfig as WidgetNumberAppearanceConfig;
- return this.normalizeDecimals(appearanceConfig?.numberFormat?.decimals);
+ /** Timestamp cells carry as much detail as the visible time window needs. */
+ formatTimestamp(value: unknown): string {
+ return this.timeFormatService.formatTimestamp(
+ this.asTimestamp(value),
+ this.visibleTimeSpan,
+ );
}
- private normalizeDecimals(decimals: unknown): number | undefined {
- if (decimals === null || decimals === undefined || decimals === '') {
- return undefined;
- }
-
- const parsedValue = Number(decimals);
- if (!Number.isFinite(parsedValue)) {
+ /**
+ * A label configured for the dataset's timestamp field (result label
+ * overrides) replaces the generic "Time" header of the time column.
+ */
+ get timeHeaderLabel(): string | undefined {
+ const sourceConfig =
+ this.dataExplorerWidget.dataConfig.sourceConfigs[0];
+ const timestampRuntimeName = sourceConfig?.measure?.timestampField
+ ?.split('::')
+ .pop();
+ if (!sourceConfig?.queryConfig || !timestampRuntimeName) {
return undefined;
}
+ return this.resultLabelService.getOverride(sourceConfig.queryConfig, {
+ fullDbName: timestampRuntimeName,
+ sourceIndex: 0,
+ });
+ }
- return Math.min(10, Math.max(0, Math.round(parsedValue)));
+ private get visibleTimeSpan(): number | undefined {
+ const settings = this.timeSettings;
+ return settings?.startTime !== undefined &&
+ settings?.endTime !== undefined
+ ? settings.endTime - settings.startTime
+ : undefined;
}
private applyTableState(resetPageIndex: boolean): void {
diff --git a/ui/src/app/chart-shared/components/charts/time-series-chart/config/time-series-chart-widget-config.component.ts b/ui/src/app/chart-shared/components/charts/time-series-chart/config/time-series-chart-widget-config.component.ts
index ca849ec4ab..26766b1a1f 100644
--- a/ui/src/app/chart-shared/components/charts/time-series-chart/config/time-series-chart-widget-config.component.ts
+++ b/ui/src/app/chart-shared/components/charts/time-series-chart/config/time-series-chart-widget-config.component.ts
@@ -16,8 +16,9 @@
*
*/
-import { Component, ChangeDetectionStrategy } from '@angular/core';
+import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
import { BaseWidgetConfig } from '../../base/base-widget-config';
+import { ChartPaletteService } from '../../../../services/chart-palette.service';
import {
TimeSeriesChartVisConfig,
TimeSeriesChartWidgetModel,
@@ -49,23 +50,12 @@ export class TimeSeriesChartWidgetConfigComponent extends BaseWidgetConfig<
TimeSeriesChartWidgetModel,
TimeSeriesChartVisConfig
> {
- presetColors: string[] = [
- '#39B54A',
- '#1B1464',
- '#f44336',
- '#FFEB3B',
- '#000000',
- '#433BFF',
- '#FF00E4',
- '#FD8B00',
- '#FD8B00',
- '#00FFD5',
- '#581845',
- '#767676',
- '#4300BF',
- '#6699D4',
- '#D466A1',
- ];
+ private paletteService = inject(ChartPaletteService);
+
+ /** New fields take their colour from the chart palette, in order. */
+ get presetColors(): string[] {
+ return this.paletteService.colors();
+ }
numericPlusBooleanFields: DataExplorerField[] = [];
@@ -97,7 +87,9 @@ export class TimeSeriesChartWidgetConfigComponent extends BaseWidgetConfig<
this.numericPlusBooleanFields.forEach((field, index) => {
const name = field.fullDbName + field.sourceIndex;
if (!(name in currentColors)) {
- currentColors[name] = this.presetColors[lenBefore + index];
+ currentColors[name] = this.paletteService.color(
+ lenBefore + index,
+ );
currentNames[name] = field.fullDbName;
currentTypes[name] = 'lines';
currentAxis[name] = 'left';
@@ -135,7 +127,7 @@ export class TimeSeriesChartWidgetConfigComponent extends BaseWidgetConfig<
config.chosenColor = this.getConfigOrDefault(
config.chosenColor,
this.numericPlusBooleanFields,
- (field, index) => this.presetColors[index],
+ (field, index) => this.paletteService.color(index),
);
config.displayName = this.getConfigOrDefault(
config.displayName,
diff --git a/ui/src/app/chart-shared/components/charts/time-series-chart/sp-timeseries-renderer.service.ts b/ui/src/app/chart-shared/components/charts/time-series-chart/sp-timeseries-renderer.service.ts
index b094faedd8..6fbca90d19 100644
--- a/ui/src/app/chart-shared/components/charts/time-series-chart/sp-timeseries-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/time-series-chart/sp-timeseries-renderer.service.ts
@@ -42,6 +42,28 @@ import type { ToolboxDataZoomFeatureOption } from 'echarts/types/src/component/t
import { XAXisOption, YAXisOption } from 'echarts/types/dist/shared';
import type { CartesianAxisPosition } from 'echarts/types/src/coord/cartesian/AxisModel.d.ts';
import type { FieldUpdateInfo } from '../../../models/field-update.model';
+import {
+ NumberFormatOptions,
+ TimestampInput,
+} from '../../../services/formatting';
+import { SeriesPosition } from '../../../services/chart-colorization.service';
+import {
+ TOOLBOX_HEIGHT,
+ TOOLBOX_TOP,
+} from '../../../echarts-renderer/echarts-basic-options-generator.service';
+
+/** Height of the single, paged legend row above the plot (ECharts default). */
+const LEGEND_ROW_HEIGHT = 24;
+
+/** The subset of ECharts' axis-trigger tooltip params the renderer reads. */
+interface TooltipSeriesParam {
+ seriesIndex: number;
+ seriesName?: string;
+ marker?: string;
+ axisValue?: number | string;
+ value: unknown;
+ encode?: { y?: number[] };
+}
@Injectable({ providedIn: 'root' })
export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSeriesChartWidgetModel> {
@@ -55,72 +77,81 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
widgetConfig: TimeSeriesChartWidgetModel,
widgetSize: WidgetSize,
): void {
- const decimals = this.getDecimals(widgetConfig);
- this.addAxisOptions(widgetConfig, options, widgetSize, decimals);
+ const axisFormat = this.getAxisNumberFormat(widgetConfig);
+ this.addAxisOptions(widgetConfig, options, widgetSize, axisFormat);
const finalSeries: SeriesOption[] = [];
-
- widgetConfig.visualizationConfig.selectedTimeSeriesChartProperties.forEach(
- field => {
- const sourceIndex = field.sourceIndex;
- const dataset = this.datasetUtilsService.findPreparedDataset(
- generatedDataset,
- sourceIndex,
+ const seriesFormats: NumberFormatOptions[] = [];
+ const plottedFields =
+ widgetConfig.visualizationConfig.selectedTimeSeriesChartProperties;
+
+ plottedFields.forEach((field, plottedFieldIndex) => {
+ const sourceIndex = field.sourceIndex;
+ const dataset = this.datasetUtilsService.findPreparedDataset(
+ generatedDataset,
+ sourceIndex,
+ );
+ for (
+ let i = dataset.meta.preparedDataStartIndex;
+ i <
+ dataset.meta.preparedDataStartIndex +
+ dataset.meta.preparedDataLength;
+ i++
+ ) {
+ const rawDatasetDimensions = dataset.rawDataset.dimensions;
+ const groupIndex = i - dataset.meta.preparedDataStartIndex;
+ const tag = dataset.tagValues[groupIndex];
+ const legacyDisplayName =
+ widgetConfig.visualizationConfig.displayName[
+ field.fullDbName + field.sourceIndex
+ ];
+ const displayName = this.resultLabelService.resolveLabel(
+ widgetConfig.dataConfig.sourceConfigs[field.sourceIndex]
+ .queryConfig,
+ field,
+ legacyDisplayName,
);
- for (
- let i = dataset.meta.preparedDataStartIndex;
- i <
- dataset.meta.preparedDataStartIndex +
- dataset.meta.preparedDataLength;
- i++
- ) {
- const rawDatasetDimensions = dataset.rawDataset.dimensions;
- const groupIndex = i - dataset.meta.preparedDataStartIndex;
- const tag = dataset.tagValues[groupIndex];
- const legacyDisplayName =
- widgetConfig.visualizationConfig.displayName[
- field.fullDbName + field.sourceIndex
- ];
- const displayName = this.resultLabelService.resolveLabel(
- widgetConfig.dataConfig.sourceConfigs[field.sourceIndex]
- .queryConfig,
- field,
- legacyDisplayName,
- );
- const mappedGroupLabel = this.colorizationService.findLabel(
- widgetConfig.visualizationConfig,
+ const mappedGroupLabel = this.colorizationService.findLabel(
+ widgetConfig.visualizationConfig,
+ field,
+ tag,
+ );
+ const seriesName =
+ dataset.groupedDatasets.length > 0
+ ? (mappedGroupLabel ??
+ this.makeGroupedSeriesName(
+ tag,
+ displayName,
+ plottedFields.length,
+ ))
+ : displayName;
+ const fieldIndex = rawDatasetDimensions.indexOf(
+ field.fullDbName,
+ );
+ finalSeries.push(
+ this.makeSeries(
+ widgetConfig,
+ i,
field,
+ fieldIndex,
+ seriesName,
tag,
- );
- const seriesName =
- dataset.groupedDatasets.length > 0
- ? (mappedGroupLabel ??
- this.echartsUtilsService.toTagString(
- tag,
- displayName,
- ))
- : displayName;
- const fieldIndex = rawDatasetDimensions.indexOf(
- field.fullDbName,
- );
- finalSeries.push(
- this.makeSeries(
- widgetConfig,
- i,
- field,
- fieldIndex,
- seriesName,
- tag,
- ),
- );
- }
- },
- );
+ {
+ groupIndex,
+ groupCount: dataset.meta.preparedDataLength,
+ fieldIndex: plottedFieldIndex,
+ },
+ ),
+ );
+ seriesFormats.push(this.getNumberFormat(widgetConfig, field));
+ }
+ });
this.addDataZoomOptions(widgetConfig, options);
this.applyResponsiveLayoutOptions(options, widgetConfig, widgetSize);
const showTooltip =
widgetConfig.baseAppearanceConfig.chartAppearance?.showTooltip;
+ const timeSpan = this.getTimeSpan(generatedDataset);
Object.assign(options, {
series: finalSeries,
@@ -132,8 +163,12 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
tooltip: {
show: showTooltip,
trigger: 'axis',
- valueFormatter: (value: unknown) =>
- this.formatNumber(value, decimals),
+ formatter: (params: unknown) =>
+ this.makeTooltipContent(
+ Array.isArray(params) ? params : [params],
+ seriesFormats,
+ timeSpan,
+ ),
axisPointer: {
type: 'cross',
},
@@ -141,6 +176,61 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
});
}
+ /**
+ * Renders the axis tooltip like ECharts does (time header, one line per
+ * series with marker, name and value) but with the shared formatters.
+ */
+ private makeTooltipContent(
+ params: TooltipSeriesParam[],
+ seriesFormats: NumberFormatOptions[],
+ timeSpan: number | undefined,
+ ): string {
+ if (params.length === 0) {
+ return '';
+ }
+ const header = this.timeFormatService.formatTimestamp(
+ params[0].axisValue,
+ timeSpan,
+ );
+ const lines = params.map(param => {
+ const value = this.formatNumber(
+ this.getTooltipValue(param),
+ seriesFormats[param.seriesIndex] ?? {},
+ );
+ return (
+ `<div style="display:flex;justify-content:space-between;gap:1rem">` +
+ `<span>${param.marker ?? ''}${param.seriesName ?? ''}</span>` +
+ `<b>${value}</b></div>`
+ );
+ });
+ return [header, ...lines].join('');
+ }
+
+ /** The y value of a dataset-backed series row, as ECharts encodes it. */
+ private getTooltipValue(param: TooltipSeriesParam): unknown {
+ if (!Array.isArray(param.value)) {
+ return param.value;
+ }
+ const dimensionIndex = param.encode?.y?.[0] ?? 1;
+ return param.value[dimensionIndex];
+ }
+
+ /** Span of the plotted timestamps, which decides the time label detail. */
+ private getTimeSpan(
+ generatedDataset: GeneratedDataset,
+ ): number | undefined {
+ const timestamps: TimestampInput[] = [];
+ generatedDataset.preparedDatasets.forEach(pd => {
+ const source = pd.rawDataset.source;
+ if (Array.isArray(source)) {
+ (source as unknown[][]).forEach(row =>
+ timestamps.push(row?.[0] as TimestampInput),
+ );
+ }
+ });
+ return this.timeFormatService.spanOf(timestamps);
+ }
+
public handleUpdatedFields(
fieldUpdateInfo: FieldUpdateInfo,
widgetConfig: TimeSeriesChartWidgetModel,
@@ -161,6 +251,7 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
fieldIndex: number,
seriesName: string,
tag?: TagValue,
+ position?: SeriesPosition,
): SeriesOption {
const seriesType = this.makeSeriesType(
widgetConfig.visualizationConfig.displayType,
@@ -170,6 +261,7 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
widgetConfig.visualizationConfig,
field,
tag,
+ position,
);
const series = {
@@ -201,6 +293,22 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
return series;
}
+ /**
+ * Legend entry of a grouped series: with a single plotted field the group
+ * value alone identifies the series ("cnc01"), with several fields the
+ * field label is needed as well ("Spindle load (cnc01)").
+ */
+ private makeGroupedSeriesName(
+ tag: TagValue,
+ displayName: string,
+ plottedFieldCount: number,
+ ): string {
+ if (plottedFieldCount === 1 && tag?.values?.length > 0) {
+ return tag.values.map(value => String(value)).join(', ');
+ }
+ return this.echartsUtilsService.toTagString(tag, displayName);
+ }
+
private makeSeriesType(
displayTypes: Record<string, string>,
field: DataExplorerField,
@@ -291,7 +399,7 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
config: TimeSeriesChartWidgetModel,
options: EChartsOption,
widgetSize: WidgetSize,
- decimals: number | undefined,
+ numberFormat: NumberFormatOptions,
): void {
const xAxisOption = this.axisGeneratorService.makeAxis(
'time',
@@ -332,7 +440,7 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
max: settings.autoScaleActive ? undefined : settings.axisMax,
axisLabel: {
formatter: (value: number | string) =>
- this.formatNumber(value, decimals),
+ this.formatNumber(value, numberFormat),
},
});
axisIndex++;
@@ -367,30 +475,33 @@ export class SpTimeseriesRendererService extends SpBaseEchartsRenderer<TimeSerie
const showLegend = legend.show ?? true;
const showToolbox = toolbox.show ?? true;
const horizontalPadding = isSmallWidget ? 14 : 18;
- const topToolboxTop = 4;
- const toolboxHeight = showToolbox ? 28 : 0;
- const topLegendTop = showToolbox
- ? topToolboxTop + toolboxHeight + 4
- : 6;
- const topLegendHeight = showLegend ? 24 : 0;
+ const topLegendTop = showToolbox ? TOOLBOX_TOP + TOOLBOX_HEIGHT + 4 : 6;
const topControlsBottom = Math.max(
- showToolbox ? topToolboxTop + toolboxHeight : 0,
- showLegend ? topLegendTop + topLegendHeight : 0,
+ showToolbox ? TOOLBOX_TOP + TOOLBOX_HEIGHT : 0,
+ showLegend ? topLegendTop + LEGEND_ROW_HEIGHT : 0,
);
const gridTop = topControlsBottom > 0 ? topControlsBottom + 8 : 16;
- options.toolbox = {
- ...toolbox,
- show: showToolbox,
- left: 10,
- right: 'auto',
- top: topToolboxTop,
- };
+ options.toolbox = widgetSize.toolboxOverlay
+ ? {
+ ...toolbox,
+ ...this.basicOptionsGeneratorService.overlayToolboxPlacement(
+ gridTop,
+ ),
+ }
+ : {
+ ...toolbox,
+ show: showToolbox,
+ left: 10,
+ right: 'auto',
+ top: TOOLBOX_TOP,
+ };
options.legend = {
...legend,
show: showLegend,
orient: 'horizontal',
+ // one paged row keeps the plot height constant however many series there are
type: 'scroll',
left: 'center',
right: 'auto',
diff --git a/ui/src/app/chart-shared/components/charts/traffic-light/traffic-light-widget.component.ts b/ui/src/app/chart-shared/components/charts/traffic-light/traffic-light-widget.component.ts
index 94260cf497..31e9553aba 100644
--- a/ui/src/app/chart-shared/components/charts/traffic-light/traffic-light-widget.component.ts
+++ b/ui/src/app/chart-shared/components/charts/traffic-light/traffic-light-widget.component.ts
@@ -16,8 +16,15 @@
*
*/
-import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
+import {
+ Component,
+ OnInit,
+ ChangeDetectionStrategy,
+ inject,
+} from '@angular/core';
import { BaseDataExplorerWidgetDirective } from '../base/base-data-explorer-widget.directive';
+import { ChartNumberFormatService } from '../../../services/formatting';
+import { WidgetNumberAppearanceConfig } from '../../../models/dataview-dashboard.model';
import { TrafficLightWidgetModel } from './model/traffic-light-widget.model';
import {
DataExplorerField,
@@ -62,6 +69,8 @@ export class TrafficLightWidgetComponent
selectedThreshold: number;
selectedToShowValue: boolean;
+ private readonly numberFormatService = inject(ChartNumberFormatService);
+
activeClass = 'red';
displayed_value: string;
currentValue?: number;
@@ -265,7 +274,14 @@ export class TrafficLightWidgetComponent
return '';
}
- return value.toFixed(2);
+ return this.numberFormatService.format(
+ value,
+ this.numberFormatService.resolveOptions(
+ this.dataExplorerWidget
+ .baseAppearanceConfig as WidgetNumberAppearanceConfig,
+ this.resolveField(this.selectedFieldToObserve),
+ ),
+ );
}
private clamp(value: number, min: number, max: number): number {
diff --git a/ui/src/app/chart-shared/components/charts/value-card/value-card-widget.component.ts b/ui/src/app/chart-shared/components/charts/value-card/value-card-widget.component.ts
index 7ed719d0e7..ada09cd46b 100644
--- a/ui/src/app/chart-shared/components/charts/value-card/value-card-widget.component.ts
+++ b/ui/src/app/chart-shared/components/charts/value-card/value-card-widget.component.ts
@@ -19,7 +19,6 @@
import { NgStyle } from '@angular/common';
import {
Component,
- LOCALE_ID,
OnInit,
inject,
ChangeDetectionStrategy,
@@ -42,10 +41,13 @@ import {
import { ResultLabelService } from '../../../services/result-label.service';
import {
clampValue,
- formatWidgetNumber,
resolveResponsiveFontSize,
scaleResponsiveValue,
} from '../../../services/widget-render.utils';
+import {
+ ChartNumberFormatService,
+ ChartTimeFormatService,
+} from '../../../services/formatting';
interface ValueCardView {
id: string;
@@ -77,9 +79,10 @@ export class ValueCardWidgetComponent
private hasReceivedData = false;
private latestData: SpQueryResult[] = [];
- private readonly locale = inject(LOCALE_ID);
private readonly chartRegistry = inject(ChartRegistry);
private readonly resultLabelService = inject(ResultLabelService);
+ private readonly numberFormatService = inject(ChartNumberFormatService);
+ private readonly timeFormatService = inject(ChartTimeFormatService);
ngOnInit(): void {
super.ngOnInit();
@@ -283,7 +286,7 @@ export class ValueCardWidgetComponent
label: queryConfig
? this.resultLabelService.resolveLabel(queryConfig, field)
: (field.runtimeName ?? field.fullDbName),
- value: this.formatValue(firstRow[fieldIndex]),
+ value: this.formatValue(firstRow[fieldIndex], field),
};
}
@@ -292,16 +295,18 @@ export class ValueCardWidgetComponent
?.rows[0];
}
- private formatValue(value: unknown): string {
+ private formatValue(value: unknown, field: DataExplorerField): string {
if (value === null || value === undefined || value === '') {
return '-';
}
if (typeof value === 'number' && Number.isFinite(value)) {
- return formatWidgetNumber(
+ return this.numberFormatService.format(
value,
- this.locale,
- this.appearanceConfig.numberFormat?.decimals,
+ this.numberFormatService.resolveOptions(
+ this.appearanceConfig,
+ this.resolveField(field),
+ ),
);
}
@@ -326,10 +331,19 @@ export class ValueCardWidgetComponent
return undefined;
}
- return new Intl.DateTimeFormat(this.locale, {
- dateStyle: 'medium',
- timeStyle: 'medium',
- }).format(new Date(firstTimestamp));
+ return this.timeFormatService.formatTimestamp(
+ firstTimestamp,
+ this.visibleTimeSpan,
+ );
+ }
+
+ /** The dashboard or chart time window, which decides how much date detail is shown. */
+ private get visibleTimeSpan(): number | undefined {
+ const settings = this.timeSettings;
+ return settings?.startTime !== undefined &&
+ settings?.endTime !== undefined
+ ? settings.endTime - settings.startTime
+ : undefined;
}
private getFirstTimestamp(queryResult: SpQueryResult): number | undefined {
diff --git a/ui/src/app/chart-shared/components/charts/value-heatmap/value-heatmap-renderer.service.ts b/ui/src/app/chart-shared/components/charts/value-heatmap/value-heatmap-renderer.service.ts
index 18cadbe9b6..2d8dbed74f 100644
--- a/ui/src/app/chart-shared/components/charts/value-heatmap/value-heatmap-renderer.service.ts
+++ b/ui/src/app/chart-shared/components/charts/value-heatmap/value-heatmap-renderer.service.ts
@@ -95,7 +95,7 @@ export class SpValueHeatmapRendererService extends SpBaseSingleFieldEchartsRende
widgetConfig: ValueHeatmapChartWidgetModel,
index: number,
): HeatmapSeriesOption {
- const decimals = this.getDecimals(widgetConfig);
+ const numberFormat = this.getNumberFormat(widgetConfig);
return {
universalTransition: true,
animation: true,
@@ -108,7 +108,10 @@ export class SpValueHeatmapRendererService extends SpBaseSingleFieldEchartsRende
tooltip: {
valueFormatter: value => {
if (typeof value === 'number' && isFinite(value)) {
- return this.formatNumber(value * 100, decimals) + '%';
+ return this.numberFormatService.formatPercent(
+ value,
+ numberFormat,
+ );
} else {
return value as string;
}
diff --git a/ui/src/app/chart-shared/echarts-renderer/base-echarts-renderer.ts b/ui/src/app/chart-shared/echarts-renderer/base-echarts-renderer.ts
index 9868fdd479..aedc53b99d 100644
--- a/ui/src/app/chart-shared/echarts-renderer/base-echarts-renderer.ts
+++ b/ui/src/app/chart-shared/echarts-renderer/base-echarts-renderer.ts
@@ -21,6 +21,7 @@ import {
WidgetEchartsAppearanceConfig,
} from '../models/dataview-dashboard.model';
import {
+ DataExplorerField,
DataExplorerWidgetModel,
SpQueryResult,
} from '@streampipes/platform-services';
@@ -39,6 +40,11 @@ import { EchartsDatasetUtilsService } from './echarts-dataset-utils.service';
import { ChartColorizationService } from '../services/chart-colorization.service';
import { SpFieldUpdateService } from '../services/field-update.service';
import { FieldUpdateInfo } from '../models/field-update.model';
+import {
+ ChartNumberFormatService,
+ ChartTimeFormatService,
+ NumberFormatOptions,
+} from '../services/formatting';
export abstract class SpBaseEchartsRenderer<
T extends DataExplorerWidgetModel,
@@ -57,6 +63,8 @@ export abstract class SpBaseEchartsRenderer<
protected echartsUtilsService = inject(EchartsUtilsService);
protected colorizationService = inject(ChartColorizationService);
protected fieldUpdateService = inject(SpFieldUpdateService);
+ protected numberFormatService = inject(ChartNumberFormatService);
+ protected timeFormatService = inject(ChartTimeFormatService);
public render(
spQueryResult: SpQueryResult[],
@@ -66,6 +74,7 @@ export abstract class SpBaseEchartsRenderer<
const options = this.basicOptionsGeneratorService.makeBaseConfig(
widgetConfig.baseAppearanceConfig as WidgetEchartsAppearanceConfig,
this.getAdditionalToolboxItems(),
+ widgetSize.toolboxOverlay,
);
const datasets = this.datasetGeneratorService.toDataset(
spQueryResult,
@@ -103,38 +112,60 @@ export abstract class SpBaseEchartsRenderer<
return {};
}
- protected getDecimals(widgetConfig: T): number | undefined {
- const appearanceConfig =
- widgetConfig.baseAppearanceConfig as WidgetEchartsAppearanceConfig;
- return this.normalizeDecimals(appearanceConfig?.numberFormat?.decimals);
+ /**
+ * Number formatting rules of the chart, optionally narrowed to one field
+ * so that integer fields and counts are rendered without fraction digits.
+ */
+ protected getNumberFormat(
+ widgetConfig: T,
+ field?: DataExplorerField,
+ ): NumberFormatOptions {
+ return this.numberFormatService.resolveOptions(
+ widgetConfig.baseAppearanceConfig as WidgetEchartsAppearanceConfig,
+ field ? this.resolveField(widgetConfig, field) : undefined,
+ );
}
- protected formatNumber(value: unknown, decimals?: number): string {
- const numericValue = typeof value === 'number' ? value : Number(value);
- if (Number.isFinite(numericValue) && decimals !== undefined) {
- const normalizedDecimals = this.normalizeDecimals(decimals);
- if (normalizedDecimals !== undefined) {
- return numericValue.toFixed(normalizedDecimals);
- }
- }
-
- if (value === null || value === undefined) {
- return '';
- }
-
- return String(value);
+ /**
+ * Axis ticks are nice numbers chosen by ECharts, so they use automatic
+ * formatting even when the chart fixes the decimals of its values.
+ */
+ protected getAxisNumberFormat(
+ widgetConfig: T,
+ field?: DataExplorerField,
+ ): NumberFormatOptions {
+ const { raw, integer } = this.getNumberFormat(widgetConfig, field);
+ return { raw, integer };
}
- private normalizeDecimals(decimals: unknown): number | undefined {
- if (decimals === null || decimals === undefined || decimals === '') {
- return undefined;
- }
-
- const parsedValue = Number(decimals);
- if (!Number.isFinite(parsedValue)) {
- return undefined;
+ /**
+ * Fields stored in a chart configuration may predate newer field
+ * characteristics (such as the integer flag), so they are looked up in
+ * the field list derived from the current schema.
+ */
+ private resolveField(
+ widgetConfig: T,
+ field: DataExplorerField,
+ ): DataExplorerField {
+ const sourceConfigs = widgetConfig.dataConfig?.sourceConfigs;
+ if (!sourceConfigs) {
+ return field;
}
+ return (
+ this.fieldProvider
+ .generateFieldLists(sourceConfigs)
+ .allFields.find(
+ candidate =>
+ candidate.fullDbName === field.fullDbName &&
+ candidate.sourceIndex === field.sourceIndex,
+ ) ?? field
+ );
+ }
- return Math.min(10, Math.max(0, Math.round(parsedValue)));
+ protected formatNumber(
+ value: unknown,
+ options: NumberFormatOptions = {},
+ ): string {
+ return this.numberFormatService.format(value, options);
}
}
diff --git a/ui/src/app/chart-shared/echarts-renderer/base-single-field-echarts-renderer.ts b/ui/src/app/chart-shared/echarts-renderer/base-single-field-echarts-renderer.ts
index 133f658821..46f4ab1fda 100644
--- a/ui/src/app/chart-shared/echarts-renderer/base-single-field-echarts-renderer.ts
+++ b/ui/src/app/chart-shared/echarts-renderer/base-single-field-echarts-renderer.ts
@@ -79,6 +79,7 @@ export abstract class SpBaseSingleFieldEchartsRenderer<
series,
gridOptions,
widgetConfig,
+ widgetSize,
);
}
@@ -170,6 +171,7 @@ export abstract class SpBaseSingleFieldEchartsRenderer<
series: S[],
gridOptions: GridOptions,
widgetConfig: T,
+ widgetSize: WidgetSize,
) {
if (series.length > 1) {
this.echartsUtilsService.addSeriesTitles(
@@ -180,7 +182,7 @@ export abstract class SpBaseSingleFieldEchartsRenderer<
}
options.dataset = dataset;
options.series = series;
- this.addAdditionalConfigs(options, widgetConfig);
+ this.addAdditionalConfigs(options, widgetConfig, widgetSize);
}
showAxes(): boolean {
@@ -192,6 +194,7 @@ export abstract class SpBaseSingleFieldEchartsRenderer<
abstract addAdditionalConfigs(
option: EChartsOption,
widgetConfig?: T,
+ widgetSize?: WidgetSize,
): void;
abstract addSeriesItem(
diff --git a/ui/src/app/chart-shared/echarts-renderer/echarts-basic-options-generator.service.ts b/ui/src/app/chart-shared/echarts-renderer/echarts-basic-options-generator.service.ts
index 6eab87f218..925fa05644 100644
--- a/ui/src/app/chart-shared/echarts-renderer/echarts-basic-options-generator.service.ts
+++ b/ui/src/app/chart-shared/echarts-renderer/echarts-basic-options-generator.service.ts
@@ -17,18 +17,35 @@
*/
import { inject, Injectable } from '@angular/core';
-import { EChartsOption } from 'echarts';
+import { EChartsOption, ToolboxComponentOption } from 'echarts';
import { SpEchartsToolboxService } from '@streampipes/shared-ui';
import type { ToolboxFeatureOption } from 'echarts/types/src/component/toolbox/featureManager.d.ts';
import { WidgetEchartsAppearanceConfig } from '../models/dataview-dashboard.model';
+import { ChartThemeService } from '../services/chart-theme.service';
+
+/**
+ * Toolbox geometry shared by all charts, so that renderers can reserve the
+ * exact space the toolbox occupies above the plot.
+ */
+export const TOOLBOX_TOP = 4;
+export const TOOLBOX_ITEM_SIZE = 15;
+export const TOOLBOX_PADDING = 4;
+export const TOOLBOX_HEIGHT = TOOLBOX_ITEM_SIZE + 2 * TOOLBOX_PADDING;
+/** Distance of the overlay toolbox from the right edge of the chart. */
+export const TOOLBOX_OVERLAY_RIGHT = 8;
+/** Legend geometry of the base configuration. */
+export const LEGEND_TOP = 30;
+export const LEGEND_ROW_HEIGHT = 24;
@Injectable({ providedIn: 'root' })
export class EchartsBasicOptionsGeneratorService {
private echartsToolboxService = inject(SpEchartsToolboxService);
+ private themeService = inject(ChartThemeService);
makeBaseConfig(
appearanceConfig: WidgetEchartsAppearanceConfig,
additionalToolboxItems: Record<string, ToolboxFeatureOption> = {},
+ toolboxOverlay = false,
): EChartsOption {
appearanceConfig.chartAppearance ??= {
showToolbox: true,
@@ -40,7 +57,7 @@ export class EchartsBasicOptionsGeneratorService {
legend: {
type: 'scroll',
orient: 'horizontal',
- top: 30,
+ top: LEGEND_TOP,
show: appearanceConfig.chartAppearance.showLegend,
},
tooltip: {
@@ -48,12 +65,82 @@ export class EchartsBasicOptionsGeneratorService {
},
toolbox: {
left: 10,
+ top: TOOLBOX_TOP,
+ padding: TOOLBOX_PADDING,
+ itemSize: TOOLBOX_ITEM_SIZE,
show: appearanceConfig.chartAppearance.showToolbox,
- feature: {
+ feature: this.withTitleStyle({
...this.echartsToolboxService.getAllToolboxItems(),
...additionalToolboxItems,
- },
+ }),
+ ...(toolboxOverlay
+ ? this.overlayToolboxPlacement(
+ LEGEND_TOP + LEGEND_ROW_HEIGHT + 4,
+ )
+ : {}),
},
};
}
+
+ /**
+ * Placement of the toolbox when it is an overlay shown on hover: a
+ * floating bar in the top right corner, `top` pixels from the top, on
+ * a surface background so that it stays readable over the plot.
+ */
+ overlayToolboxPlacement(top: number): Partial<ToolboxComponentOption> {
+ return {
+ left: 'auto',
+ right: TOOLBOX_OVERLAY_RIGHT,
+ top,
+ backgroundColor: this.themeService.variable(
+ '--color-bg-0',
+ '#ffffff',
+ ),
+ borderRadius: 4,
+ };
+ }
+
+ /**
+ * The title shown while an icon is hovered is drawn as a label below the
+ * icon, where it can cover the legend. Styling it like a tooltip keeps
+ * it readable on top of other chart content.
+ */
+ private withTitleStyle(
+ features: Record<string, ToolboxFeatureOption>,
+ ): Record<string, ToolboxFeatureOption> {
+ const titleStyle = this.makeTitleStyle();
+ return Object.fromEntries(
+ Object.entries(features).map(([name, feature]) => [
+ name,
+ {
+ ...feature,
+ emphasis: {
+ ...feature.emphasis,
+ iconStyle: {
+ ...titleStyle,
+ ...feature.emphasis?.iconStyle,
+ },
+ },
+ },
+ ]),
+ );
+ }
+
+ private makeTitleStyle(): NonNullable<
+ NonNullable<ToolboxFeatureOption['emphasis']>['iconStyle']
+ > {
+ return {
+ textFill: this.themeService.variable(
+ '--color-default-text',
+ '#121212',
+ ),
+ textBackgroundColor: this.themeService.variable(
+ '--color-bg-2',
+ '#ececec',
+ ),
+ textPadding: [4, 8],
+ textBorderRadius: 4,
+ textFontSize: 12,
+ };
+ }
}
diff --git a/ui/src/app/chart-shared/models/dataset.model.ts b/ui/src/app/chart-shared/models/dataset.model.ts
index a29f052d86..d686704c04 100644
--- a/ui/src/app/chart-shared/models/dataset.model.ts
+++ b/ui/src/app/chart-shared/models/dataset.model.ts
@@ -26,6 +26,12 @@ import {
export interface WidgetSize {
width: number;
height: number;
+ /**
+ * True when the toolbox is not part of the layout but an overlay that
+ * the widget shows on hover: renderers reserve no space for it and
+ * place it in the top right corner below their legend.
+ */
+ toolboxOverlay?: boolean;
}
export interface TagValue {
diff --git a/ui/src/app/chart-shared/models/dataview-dashboard.model.ts b/ui/src/app/chart-shared/models/dataview-dashboard.model.ts
index 68b3ce7dc3..4dcb477713 100644
--- a/ui/src/app/chart-shared/models/dataview-dashboard.model.ts
+++ b/ui/src/app/chart-shared/models/dataview-dashboard.model.ts
@@ -103,7 +103,10 @@ export interface WidgetChartAppearanceConfig {
}
export interface WidgetNumberFormatConfig {
+ /** Fixed fraction digits; unset means automatic formatting. */
decimals?: number;
+ /** Show stored values unchanged instead of formatting them. */
+ rawValues?: boolean;
}
export interface WidgetNumberAppearanceConfig extends WidgetBaseAppearanceConfig {
diff --git a/ui/src/app/chart-shared/services/chart-colorization.service.ts b/ui/src/app/chart-shared/services/chart-colorization.service.ts
index eb2a3057b1..b0770adb7d 100644
--- a/ui/src/app/chart-shared/services/chart-colorization.service.ts
+++ b/ui/src/app/chart-shared/services/chart-colorization.service.ts
@@ -16,7 +16,7 @@
*
*/
-import { Injectable } from '@angular/core';
+import { inject, Injectable } from '@angular/core';
import { DataExplorerField } from '@streampipes/platform-services';
import {
TimeSeriesChartVisConfig,
@@ -25,14 +25,33 @@ import {
import { TagValue } from '../models/dataset.model';
import { ColorMappingService } from './color-mapping.service';
+/** Where a grouped series sits among the series of its chart. */
+export interface SeriesPosition {
+ /** Index of the group (tag value) within the field's groups. */
+ groupIndex: number;
+ /** Number of groups of the field. */
+ groupCount: number;
+ /** Index of the field among the chart's plotted fields. */
+ fieldIndex: number;
+}
+
@Injectable({ providedIn: 'root' })
export class ChartColorizationService {
- constructor(private colorMappingService: ColorMappingService) {}
+ private colorMappingService = inject(ColorMappingService);
+ /**
+ * The colour of one series. Fields without grouping keep their configured
+ * colour. Grouped fields use the custom mapping when configured, otherwise
+ * the ordered chart palette: the n-th group gets the n-th palette colour,
+ * and further fields continue after the groups of the previous field, so
+ * every series of a chart is distinct and the same group keeps its colour
+ * across charts of the same dataset.
+ */
makeColor(
visualizationConfig: TimeSeriesChartVisConfig,
field: DataExplorerField,
tag?: TagValue,
+ position?: SeriesPosition,
): string {
const fieldKey = field.fullDbName + field.sourceIndex;
const baseColor = visualizationConfig.chosenColor[fieldKey];
@@ -51,13 +70,11 @@ export class ChartColorizationService {
) {
return (
this.findMapping(fieldMappings, tag, groupKey)?.color ??
- this.colorMappingService.getDefaultColor(groupKey)
+ this.paletteColor(groupKey, position)
);
}
- return this.colorMappingService.getDefaultColor(
- `${fieldKey}:${groupKey}`,
- );
+ return this.paletteColor(groupKey, position);
}
findLabel(
@@ -81,6 +98,18 @@ export class ChartColorizationService {
return mapping?.label?.trim() ? mapping.label : undefined;
}
+ private paletteColor(
+ groupKey: string,
+ position: SeriesPosition | undefined,
+ ): string {
+ if (!position) {
+ return this.colorMappingService.getDefaultColor(groupKey);
+ }
+ return this.colorMappingService.getPaletteColor(
+ position.fieldIndex * position.groupCount + position.groupIndex,
+ );
+ }
+
private findMapping(
mappings: TimeSeriesGroupColorMapping[],
tag: TagValue,
diff --git a/ui/src/app/chart-shared/services/chart-field-provider.service.ts b/ui/src/app/chart-shared/services/chart-field-provider.service.ts
index ae0090ab87..bb2cb5ae9b 100644
--- a/ui/src/app/chart-shared/services/chart-field-provider.service.ts
+++ b/ui/src/app/chart-shared/services/chart-field-provider.service.ts
@@ -117,6 +117,7 @@ export class ChartFieldProviderService {
fieldCharacteristics: {
dimension: this.isDimensionProperty(property),
numeric: this.isNumber(property) || aggregation === 'COUNT',
+ integer: this.isInteger(property) || aggregation === 'COUNT',
binary: this.isBoolean(property),
semanticTypes: [property.semanticType],
},
@@ -156,6 +157,13 @@ export class ChartFieldProviderService {
);
}
+ public isInteger(p: EventPropertyUnion): boolean {
+ return (
+ this.isPrimitive(p) &&
+ DataType.isIntegerType((p as EventPropertyPrimitive).runtimeType)
+ );
+ }
+
public isString(p: EventPropertyUnion): boolean {
return (
this.isPrimitive(p) &&
diff --git a/ui/src/app/chart-shared/services/chart-palette.service.spec.ts b/ui/src/app/chart-shared/services/chart-palette.service.spec.ts
new file mode 100644
index 0000000000..f83e7a3885
--- /dev/null
+++ b/ui/src/app/chart-shared/services/chart-palette.service.spec.ts
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { TestBed } from '@angular/core/testing';
+import {
+ ChartPaletteService,
+ DEFAULT_CHART_PALETTE,
+} from './chart-palette.service';
+
+describe('ChartPaletteService', () => {
+ let service: ChartPaletteService;
+
+ beforeEach(() => {
+ TestBed.configureTestingModule({});
+ service = TestBed.inject(ChartPaletteService);
+ });
+
+ afterEach(() => {
+ document.documentElement.style.removeProperty('--color-chart-1');
+ });
+
+ it('falls back to the default palette without theme variables', () => {
+ expect(service.color(0)).toBe(DEFAULT_CHART_PALETTE[0]);
+ expect(service.colors()).toEqual([...DEFAULT_CHART_PALETTE]);
+ });
+
+ it('wraps around for indices beyond the palette size', () => {
+ expect(service.color(DEFAULT_CHART_PALETTE.length)).toBe(
+ DEFAULT_CHART_PALETTE[0],
+ );
+ expect(service.color(-1)).toBe(
+ DEFAULT_CHART_PALETTE[DEFAULT_CHART_PALETTE.length - 1],
+ );
+ });
+
+ it('prefers the theme variable when the document defines it', () => {
+ document.documentElement.style.setProperty(
+ '--color-chart-1',
+ '#123456',
+ );
+ expect(service.color(0)).toBe('#123456');
+ expect(service.color(1)).toBe(DEFAULT_CHART_PALETTE[1]);
+ });
+});
diff --git a/ui/src/app/chart-shared/services/chart-palette.service.ts b/ui/src/app/chart-shared/services/chart-palette.service.ts
new file mode 100644
index 0000000000..2cb2b2958c
--- /dev/null
+++ b/ui/src/app/chart-shared/services/chart-palette.service.ts
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { inject, Injectable } from '@angular/core';
+import { ChartThemeService } from './chart-theme.service';
+
+/**
+ * Fallback values, identical to the light-mode defaults in
+ * ui/deployment/theme/_custom-variables.scss. The theme variables win
+ * whenever a document is available, so operator themes and dark mode
+ * apply to chart series as well.
+ */
+export const DEFAULT_CHART_PALETTE: readonly string[] = [
+ '#4f81bd',
+ '#f28e2b',
+ '#7b61ff',
+ '#2a9d8f',
+ '#e9c46a',
+ '#c77dff',
+ '#577590',
+ '#f4a261',
+ '#43aa8b',
+ '#bc5090',
+];
+
+/**
+ * The ordered categorical palette for chart series. Canvas-rendered charts
+ * cannot consume CSS variables directly, so the palette is resolved from the
+ * theme variables `--color-chart-1` … `--color-chart-N` at render time.
+ */
+@Injectable({ providedIn: 'root' })
+export class ChartPaletteService {
+ private themeService = inject(ChartThemeService);
+
+ get size(): number {
+ return DEFAULT_CHART_PALETTE.length;
+ }
+
+ /** The colour for the n-th series or category (wraps around). */
+ color(index: number): string {
+ const normalizedIndex =
+ ((Math.round(index) % this.size) + this.size) % this.size;
+ return this.themeService.variable(
+ `--color-chart-${normalizedIndex + 1}`,
+ DEFAULT_CHART_PALETTE[normalizedIndex],
+ );
+ }
+
+ /** The whole palette in assignment order. */
+ colors(): string[] {
+ return DEFAULT_CHART_PALETTE.map((_, index) => this.color(index));
+ }
+}
diff --git a/ui/src/app/chart-shared/services/chart-theme.service.ts b/ui/src/app/chart-shared/services/chart-theme.service.ts
new file mode 100644
index 0000000000..e1c1385bb2
--- /dev/null
+++ b/ui/src/app/chart-shared/services/chart-theme.service.ts
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { DOCUMENT } from '@angular/common';
+import { inject, Injectable } from '@angular/core';
+
+/**
+ * Resolves theme variables for canvas-rendered charts. ECharts draws on a
+ * canvas and cannot consume CSS variables, so colours that must follow the
+ * active theme (operator themes, dark mode) are read from the document root
+ * at render time and fall back to the light-mode defaults otherwise.
+ */
+@Injectable({ providedIn: 'root' })
+export class ChartThemeService {
+ private document = inject(DOCUMENT, { optional: true });
+
+ /** Value of the CSS variable `name` on the document root, or `fallback`. */
+ variable(name: string, fallback: string): string {
+ const root = this.document?.documentElement;
+ if (!root || typeof getComputedStyle !== 'function') {
+ return fallback;
+ }
+ const value = getComputedStyle(root).getPropertyValue(name).trim();
+ return value.length > 0 ? value : fallback;
+ }
+
+ /** Like {@link variable}, but `undefined` when the theme does not define it. */
+ optionalVariable(name: string): string | undefined {
+ const value = this.variable(name, '');
+ return value.length > 0 ? value : undefined;
+ }
+}
diff --git a/ui/src/app/chart-shared/services/color-mapping.service.ts b/ui/src/app/chart-shared/services/color-mapping.service.ts
index e63b995160..5521e04c69 100644
--- a/ui/src/app/chart-shared/services/color-mapping.service.ts
+++ b/ui/src/app/chart-shared/services/color-mapping.service.ts
@@ -16,53 +16,64 @@
*
*/
-import { Injectable } from '@angular/core';
+import { inject, Injectable } from '@angular/core';
+import { ChartPaletteService } from './chart-palette.service';
+
+export interface ColorMapping {
+ value: string;
+ label: string;
+ color: string;
+}
@Injectable({
providedIn: 'root',
})
export class ColorMappingService {
- constructor() {}
+ private paletteService = inject(ChartPaletteService);
- addMapping(
- colorMappings: { value: string; label: string; color: string }[],
- ): void {
+ addMapping(colorMappings: ColorMapping[]): void {
colorMappings.push({
value: '',
label: '',
- color: this.getDefaultColor(Math.random() * 1000),
+ color: this.getPaletteColor(colorMappings.length),
});
}
removeMapping(
- colorMappings: { value: string; label: string; color: string }[],
+ colorMappings: ColorMapping[],
index: number,
- ): { value: string; label: string; color: string }[] {
+ ): ColorMapping[] {
return colorMappings.filter((_, i) => i !== index);
}
updateColor(
- currentMappings: { value: string; label: string; color: string }[],
+ currentMappings: ColorMapping[],
index: number,
newColor: string,
): void {
currentMappings[index].color = newColor;
}
+ /** The palette colour for the n-th series or category of a chart. */
+ getPaletteColor(index: number): string {
+ return this.paletteService.color(index);
+ }
+
+ /**
+ * A palette colour chosen by the value itself, so the same value gets the
+ * same colour wherever no explicit mapping or position is known.
+ */
getDefaultColor(value: string | number): string {
- let hash = 0x811c9dc5;
- const input = String(value);
+ return this.paletteService.color(this.hash(String(value)));
+ }
+ private hash(input: string): number {
+ let hash = 0x811c9dc5;
for (let i = 0; i < input.length; i++) {
hash ^= input.charCodeAt(i);
hash = (hash * 0x5bd1e995) & 0xffffffff;
hash ^= hash >> 15;
}
-
- const hue = Math.abs(hash) % 360;
- const saturation = 50 + (Math.abs(hash >> 8) % 20);
- const lightness = 45 + (Math.abs(hash >> 16) % 20);
-
- return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
+ return Math.abs(hash);
}
}
diff --git a/ui/src/app/chart-shared/services/formatting/chart-number-format.service.spec.ts b/ui/src/app/chart-shared/services/formatting/chart-number-format.service.spec.ts
new file mode 100644
index 0000000000..c302c001ea
--- /dev/null
+++ b/ui/src/app/chart-shared/services/formatting/chart-number-format.service.spec.ts
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import { TestBed } from '@angular/core/testing';
+import { TranslateService } from '@ngx-translate/core';
+import {
+ ChartNumberFormatService,
+ normalizeDecimals,
+} from './chart-number-format.service';
+
+describe('ChartNumberFormatService', () => {
+ let service: ChartNumberFormatService;
+ let currentLang = 'en';
+
+ beforeEach(() => {
+ currentLang = 'en';
+ TestBed.configureTestingModule({
+ providers: [
+ {
+ provide: TranslateService,
+ useValue: {
+ getCurrentLang: () => currentLang,
+ getFallbackLang: () => 'en',
+ },
+ },
+ ],
+ });
+ service = TestBed.inject(ChartNumberFormatService);
+ });
+
+ describe('automatic formatting', () => {
+ it('limits values to two fraction digits', () => {
+ expect(service.format(39.76818268646499)).toBe('39.77');
+ });
+
+ it('drops trailing zeros of integral values', () => {
+ expect(service.format(182)).toBe('182');
+ expect(service.format(182.0)).toBe('182');
+ });
+
+ it('keeps three significant digits for small values', () => {
+ expect(service.format(0.012345)).toBe('0.0123');
+ expect(service.format(-0.5)).toBe('-0.5');
+ });
+
+ it('formats zero as a plain zero', () => {
+ expect(service.format(0)).toBe('0');
+ });
+
+ it('uses the current UI language for separators', () => {
+ currentLang = 'de';
+ expect(service.format(1234.5)).toBe('1.234,5');
+ });
+ });
+
+ describe('explicit decimals', () => {
+ it('renders exactly the configured fraction digits', () => {
+ expect(service.format(3, { decimals: 2 })).toBe('3.00');
+ expect(service.format(3.14159, { decimals: 1 })).toBe('3.1');
+ });
+
+ it('ignores fraction digits for integer fields', () => {
+ expect(service.format(182, { decimals: 2, integer: true })).toBe(
+ '182',
+ );
+ expect(service.format(182.6, { integer: true })).toBe('183');
+ });
+ });
+
+ describe('raw mode', () => {
+ it('returns the stored value unchanged', () => {
+ expect(service.format(39.76818268646499, { raw: true })).toBe(
+ '39.76818268646499',
+ );
+ expect(service.format('12.50', { raw: true })).toBe('12.50');
+ });
+ });
+
+ describe('non-numeric input', () => {
+ it('returns an empty string for missing values', () => {
+ expect(service.format(null)).toBe('');
+ expect(service.format(undefined)).toBe('');
+ expect(service.format('')).toBe('');
+ });
+
+ it('returns text values as they are', () => {
+ expect(service.format('RUNNING')).toBe('RUNNING');
+ });
+
+ it('parses numeric strings', () => {
+ expect(service.format('12.345')).toBe('12.35');
+ });
+ });
+
+ describe('percentages', () => {
+ it('formats ratios with one fraction digit by default', () => {
+ expect(service.formatPercent(0.4932)).toBe('49.3%');
+ });
+
+ it('formats whole percentages without fraction digits', () => {
+ expect(service.formatPercent(1)).toBe('100%');
+ });
+
+ it('honours explicit decimals', () => {
+ expect(service.formatPercent(0.5, { decimals: 2 })).toBe('50.00%');
+ });
+ });
+
+ describe('resolveOptions', () => {
+ it('resolves automatic formatting for configurations without numberFormat', () => {
+ expect(service.resolveOptions(undefined)).toEqual({
+ decimals: undefined,
+ raw: false,
+ integer: false,
+ });
+ });
+
+ it('reads decimals and raw mode from the appearance configuration', () => {
+ expect(
+ service.resolveOptions({
+ backgroundColor: '',
+ textColor: '',
+ widgetTitle: '',
+ numberFormat: { decimals: 3, rawValues: true },
+ }),
+ ).toEqual({ decimals: 3, raw: true, integer: false });
+ });
+
+ it('marks integer fields and count aggregations', () => {
+ const characteristics = {
+ dimension: false,
+ numeric: true,
+ binary: false,
+ semanticTypes: [],
+ };
+ expect(
+ service.resolveOptions(undefined, {
+ fieldCharacteristics: { ...characteristics, integer: true },
+ }).integer,
+ ).toBe(true);
+ expect(
+ service.resolveOptions(undefined, {
+ fieldCharacteristics: characteristics,
+ aggregation: 'COUNT',
+ }).integer,
+ ).toBe(true);
+ expect(
+ service.resolveOptions(undefined, {
+ fieldCharacteristics: characteristics,
+ aggregation: 'MEAN',
+ }).integer,
+ ).toBe(false);
+ });
+ });
+
+ describe('normalizeDecimals', () => {
+ it('clamps and rounds valid input', () => {
+ expect(normalizeDecimals(2)).toBe(2);
+ expect(normalizeDecimals('4')).toBe(4);
+ expect(normalizeDecimals(2.6)).toBe(3);
+ expect(normalizeDecimals(-1)).toBe(0);
+ expect(normalizeDecimals(42)).toBe(10);
+ });
+
+ it('treats empty or invalid input as unset', () => {
+ expect(normalizeDecimals(undefined)).toBeUndefined();
+ expect(normalizeDecimals(null)).toBeUndefined();
+ expect(normalizeDecimals('')).toBeUndefined();
+ expect(normalizeDecimals('abc')).toBeUndefined();
+ });
+ });
+});
diff --git a/ui/src/app/chart-shared/services/formatting/chart-number-format.service.ts b/ui/src/app/chart-shared/services/formatting/chart-number-format.service.ts
new file mode 100644
index 0000000000..53e23a09ac
--- /dev/null
+++ b/ui/src/app/chart-shared/services/formatting/chart-number-format.service.ts
@@ -0,0 +1,178 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { inject, Injectable } from '@angular/core';
+import { TranslateService } from '@ngx-translate/core';
+import { DataExplorerField } from '@streampipes/platform-services';
+import {
+ WidgetNumberAppearanceConfig,
+ WidgetNumberFormatConfig,
+} from '../../models/dataview-dashboard.model';
+
+/**
+ * Resolved formatting rules for one number, derived from the chart's
+ * appearance configuration and the field being rendered.
+ */
+export interface NumberFormatOptions {
+ /** Fixed number of fraction digits; undefined means automatic formatting. */
+ decimals?: number;
+ /** Render the stored value unchanged, without any formatting. */
+ raw?: boolean;
+ /** The value is a count or an integer field: never show fraction digits. */
+ integer?: boolean;
+}
+
+type FieldTypeInfo = Pick<
+ DataExplorerField,
+ 'fieldCharacteristics' | 'aggregation'
+>;
+
+const MAX_DECIMALS = 10;
+const AUTO_MAX_FRACTION_DIGITS = 2;
+const AUTO_MAX_SIGNIFICANT_DIGITS = 3;
+const AUTO_PERCENT_FRACTION_DIGITS = 1;
+
+export function normalizeDecimals(decimals: unknown): number | undefined {
+ if (decimals === null || decimals === undefined || decimals === '') {
+ return undefined;
+ }
+
+ const parsedValue = Number(decimals);
+ if (!Number.isFinite(parsedValue)) {
+ return undefined;
+ }
+
+ return Math.min(MAX_DECIMALS, Math.max(0, Math.round(parsedValue)));
+}
+
+/**
+ * Single place that turns numbers into display strings for charts and
+ * widgets. The rules are the same for ECharts axes and tooltips, tables,
+ * value cards and single-value widgets:
+ *
+ * - raw: the stored value, unchanged (what older releases rendered)
+ * - explicit decimals: exactly that many fraction digits
+ * - automatic (the default): locale-aware, at most two fraction digits, or
+ * three significant digits for values below one, and no fraction digits
+ * for integer fields and counts.
+ */
+@Injectable({ providedIn: 'root' })
+export class ChartNumberFormatService {
+ private translateService = inject(TranslateService);
+ private formatters = new Map<string, Intl.NumberFormat>();
+
+ /**
+ * Derives the formatting rules from a widget's appearance configuration.
+ * Configurations saved by older releases have no numberFormat block and
+ * resolve to automatic formatting.
+ */
+ resolveOptions(
+ appearanceConfig: WidgetNumberAppearanceConfig | undefined,
+ field?: FieldTypeInfo,
+ ): NumberFormatOptions {
+ const numberFormat: WidgetNumberFormatConfig =
+ appearanceConfig?.numberFormat ?? {};
+ return {
+ decimals: normalizeDecimals(numberFormat.decimals),
+ raw: numberFormat.rawValues === true,
+ integer: field ? this.isIntegerField(field) : false,
+ };
+ }
+
+ /** Formats one value; values that are not numbers are returned as text. */
+ format(value: unknown, options: NumberFormatOptions = {}): string {
+ if (value === null || value === undefined || value === '') {
+ return '';
+ }
+ const numericValue = typeof value === 'number' ? value : Number(value);
+ if (!Number.isFinite(numericValue)) {
+ return String(value);
+ }
+ if (options.raw) {
+ return String(value);
+ }
+ return this.getFormatter(numericValue, options).format(numericValue);
+ }
+
+ /**
+ * Formats a ratio (0..1) as a percentage. Without explicit decimals a
+ * percentage carries one fraction digit, or none when it is a whole number.
+ */
+ formatPercent(ratio: number, options: NumberFormatOptions = {}): string {
+ const percentValue = ratio * 100;
+ const percentOptions: NumberFormatOptions = {
+ raw: options.raw,
+ decimals:
+ options.decimals ??
+ (Number.isInteger(percentValue)
+ ? 0
+ : AUTO_PERCENT_FRACTION_DIGITS),
+ };
+ return `${this.format(percentValue, percentOptions)}%`;
+ }
+
+ /** Integer fields and COUNT aggregations never carry fraction digits. */
+ isIntegerField(field: FieldTypeInfo | undefined): boolean {
+ return (
+ field?.fieldCharacteristics?.integer === true ||
+ field?.aggregation === 'COUNT'
+ );
+ }
+
+ private getFormatter(
+ value: number,
+ options: NumberFormatOptions,
+ ): Intl.NumberFormat {
+ const locale = this.currentLocale;
+ const intlOptions = this.toIntlOptions(value, options);
+ const key = `${locale}|${JSON.stringify(intlOptions)}`;
+ let formatter = this.formatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.NumberFormat(locale, intlOptions);
+ this.formatters.set(key, formatter);
+ }
+ return formatter;
+ }
+
+ private toIntlOptions(
+ value: number,
+ options: NumberFormatOptions,
+ ): Intl.NumberFormatOptions {
+ if (options.integer) {
+ return { maximumFractionDigits: 0 };
+ }
+ if (options.decimals !== undefined) {
+ return {
+ minimumFractionDigits: options.decimals,
+ maximumFractionDigits: options.decimals,
+ };
+ }
+ if (value !== 0 && Math.abs(value) < 1) {
+ return { maximumSignificantDigits: AUTO_MAX_SIGNIFICANT_DIGITS };
+ }
+ return { maximumFractionDigits: AUTO_MAX_FRACTION_DIGITS };
+ }
+
+ private get currentLocale(): string {
+ return (
+ this.translateService.getCurrentLang() ||
+ this.translateService.getFallbackLang() ||
+ 'en'
+ );
+ }
+}
diff --git a/ui/src/app/chart-shared/services/formatting/chart-time-format.service.spec.ts b/ui/src/app/chart-shared/services/formatting/chart-time-format.service.spec.ts
new file mode 100644
index 0000000000..6b4ab39030
--- /dev/null
+++ b/ui/src/app/chart-shared/services/formatting/chart-time-format.service.spec.ts
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import { TestBed } from '@angular/core/testing';
+import { TranslateService } from '@ngx-translate/core';
+import { ChartTimeFormatService } from './chart-time-format.service';
+
+const MINUTE = 60 * 1000;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+
+describe('ChartTimeFormatService', () => {
+ let service: ChartTimeFormatService;
+ let currentLang = 'en';
+ // 2026-10-28 16:44:55.938 local time
+ const timestamp = new Date(2026, 9, 28, 16, 44, 55, 938).getTime();
+
+ beforeEach(() => {
+ currentLang = 'en';
+ TestBed.configureTestingModule({
+ providers: [
+ {
+ provide: TranslateService,
+ useValue: {
+ getCurrentLang: () => currentLang,
+ getFallbackLang: () => 'en',
+ },
+ },
+ ],
+ });
+ service = TestBed.inject(ChartTimeFormatService);
+ });
+
+ describe('resolutionForSpan', () => {
+ it('picks the detail level from the visible span', () => {
+ expect(service.resolutionForSpan(30 * 1000)).toBe('milliseconds');
+ expect(service.resolutionForSpan(15 * MINUTE)).toBe('seconds');
+ expect(service.resolutionForSpan(3 * DAY)).toBe('date-time');
+ expect(service.resolutionForSpan(30 * DAY)).toBe('date');
+ });
+
+ it('falls back to date and time when the span is unknown', () => {
+ expect(service.resolutionForSpan(undefined)).toBe('date-time');
+ expect(service.resolutionForSpan(Number.NaN)).toBe('date-time');
+ });
+ });
+
+ describe('formatTimestamp', () => {
+ it('shows the time of day only within a day', () => {
+ expect(service.formatTimestamp(timestamp, 15 * MINUTE)).toBe(
+ '16:44:55',
+ );
+ });
+
+ it('shows milliseconds within a minute', () => {
+ expect(service.formatTimestamp(timestamp, 20 * 1000)).toBe(
+ '16:44:55.938',
+ );
+ });
+
+ it('shows date and time without a span', () => {
+ expect(service.formatTimestamp(timestamp)).toBe(
+ '10/28/2026, 16:44',
+ );
+ });
+
+ it('accepts ISO strings and Date objects', () => {
+ const iso = new Date(timestamp).toISOString();
+ expect(service.formatTimestamp(iso, HOUR)).toBe('16:44:55');
+ expect(service.formatTimestamp(new Date(timestamp), HOUR)).toBe(
+ '16:44:55',
+ );
+ });
+
+ it('passes through values that are not timestamps', () => {
+ expect(service.formatTimestamp('n/a')).toBe('n/a');
+ expect(service.formatTimestamp(null)).toBe('');
+ expect(service.formatTimestamp(undefined)).toBe('');
+ });
+
+ it('uses the current UI language', () => {
+ currentLang = 'de';
+ expect(service.formatTimestamp(timestamp)).toBe(
+ '28.10.2026, 16:44',
+ );
+ });
+ });
+
+ describe('formatTimestamps', () => {
+ it('uses one resolution for the whole list', () => {
+ const labels = service.formatTimestamps([
+ timestamp,
+ timestamp + 5 * MINUTE,
+ timestamp + 10 * MINUTE,
+ ]);
+ expect(labels).toEqual(['16:44:55', '16:49:55', '16:54:55']);
+ });
+
+ it('ignores entries that are not timestamps when deriving the span', () => {
+ const labels = service.formatTimestamps([
+ 'time',
+ timestamp,
+ timestamp + MINUTE,
+ ]);
+ expect(labels).toEqual(['time', '16:44:55', '16:45:55']);
+ });
+ });
+
+ describe('formatRange', () => {
+ it('repeats the date only when the range spans several days', () => {
+ expect(
+ service.formatRange(timestamp, timestamp + 15 * MINUTE),
+ ).toBe('10/28/2026, 16:44 – 16:59');
+ expect(service.formatRange(timestamp, timestamp + 2 * DAY)).toBe(
+ '10/28/2026, 16:44 – 10/30/2026, 16:44',
+ );
+ });
+
+ it('returns an empty string for incomplete ranges', () => {
+ expect(service.formatRange(undefined, timestamp)).toBe('');
+ });
+ });
+
+ describe('spanOf', () => {
+ it('returns the difference between the earliest and latest timestamp', () => {
+ expect(
+ service.spanOf([timestamp + HOUR, timestamp, timestamp + DAY]),
+ ).toBe(DAY);
+ });
+
+ it('returns undefined without valid timestamps', () => {
+ expect(service.spanOf(['time', null])).toBeUndefined();
+ });
+ });
+});
diff --git a/ui/src/app/chart-shared/services/formatting/chart-time-format.service.ts b/ui/src/app/chart-shared/services/formatting/chart-time-format.service.ts
new file mode 100644
index 0000000000..52994dfc2f
--- /dev/null
+++ b/ui/src/app/chart-shared/services/formatting/chart-time-format.service.ts
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { inject, Injectable } from '@angular/core';
+import { TranslateService } from '@ngx-translate/core';
+
+export type TimestampInput = number | string | Date | null | undefined;
+
+/** How much detail a timestamp needs, derived from the visible time span. */
+export type TimeResolution =
+ 'milliseconds' | 'seconds' | 'minutes' | 'date-time' | 'date';
+
+const ONE_SECOND = 1000;
+const ONE_MINUTE = 60 * ONE_SECOND;
+const ONE_DAY = 24 * 60 * ONE_MINUTE;
+const ONE_WEEK = 7 * ONE_DAY;
+
+/**
+ * Single place that turns timestamps into display strings for charts and
+ * widgets (table cells, tooltips, heatmap axes, value cards, empty states).
+ *
+ * The resolution follows the visible span: within a minute milliseconds are
+ * shown, within a day only the time of day, beyond that date and time, so a
+ * live dashboard reads "17:03:12" while a yearly view reads "10/28/2026 17:03".
+ */
+@Injectable({ providedIn: 'root' })
+export class ChartTimeFormatService {
+ private translateService = inject(TranslateService);
+ private formatters = new Map<string, Intl.DateTimeFormat>();
+
+ /** Formats one timestamp with the resolution matching the given span. */
+ formatTimestamp(
+ value: TimestampInput,
+ spanMs?: number,
+ resolution: TimeResolution = this.resolutionForSpan(spanMs),
+ ): string {
+ const date = this.toDate(value);
+ if (!date) {
+ return value === null || value === undefined ? '' : String(value);
+ }
+ return this.getFormatter(resolution).format(date);
+ }
+
+ /** Formats a list of timestamps with one common resolution (axis labels). */
+ formatTimestamps(values: TimestampInput[]): string[] {
+ const resolution = this.resolutionForSpan(this.spanOf(values));
+ return values.map(value =>
+ this.formatTimestamp(value, undefined, resolution),
+ );
+ }
+
+ /** Formats a start/end pair as one range, e.g. for empty states. */
+ formatRange(start: TimestampInput, end: TimestampInput): string {
+ const startDate = this.toDate(start);
+ const endDate = this.toDate(end);
+ if (!startDate || !endDate) {
+ return '';
+ }
+ const sameDay = startDate.toDateString() === endDate.toDateString();
+ const startText = this.getFormatter('date-time').format(startDate);
+ const endText = this.getFormatter(
+ sameDay ? 'minutes' : 'date-time',
+ ).format(endDate);
+ return `${startText} – ${endText}`;
+ }
+
+ /** The span (max - min) of the valid timestamps in the list. */
+ spanOf(values: TimestampInput[]): number | undefined {
+ let min = Number.POSITIVE_INFINITY;
+ let max = Number.NEGATIVE_INFINITY;
+ values.forEach(value => {
+ const time = this.toDate(value)?.getTime();
+ if (time !== undefined) {
+ min = Math.min(min, time);
+ max = Math.max(max, time);
+ }
+ });
+ return max >= min ? max - min : undefined;
+ }
+
+ resolutionForSpan(spanMs: number | undefined): TimeResolution {
+ if (spanMs === undefined || !Number.isFinite(spanMs)) {
+ return 'date-time';
+ }
+ if (spanMs < ONE_MINUTE) {
+ return 'milliseconds';
+ }
+ if (spanMs < ONE_DAY) {
+ return 'seconds';
+ }
+ if (spanMs < ONE_WEEK) {
+ return 'date-time';
+ }
+ return 'date';
+ }
+
+ toDate(value: TimestampInput): Date | undefined {
+ if (value === null || value === undefined || value === '') {
+ return undefined;
+ }
+ const date = value instanceof Date ? value : new Date(value);
+ return Number.isNaN(date.getTime()) ? undefined : date;
+ }
+
+ private getFormatter(resolution: TimeResolution): Intl.DateTimeFormat {
+ const locale = this.currentLocale;
+ const key = `${locale}|${resolution}`;
+ let formatter = this.formatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat(
+ locale,
+ this.toIntlOptions(resolution),
+ );
+ this.formatters.set(key, formatter);
+ }
+ return formatter;
+ }
+
+ private toIntlOptions(
+ resolution: TimeResolution,
+ ): Intl.DateTimeFormatOptions {
+ const time: Intl.DateTimeFormatOptions = {
+ hour: '2-digit',
+ minute: '2-digit',
+ hourCycle: 'h23',
+ };
+ const date: Intl.DateTimeFormatOptions = {
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ };
+ switch (resolution) {
+ case 'milliseconds':
+ return {
+ ...time,
+ second: '2-digit',
+ fractionalSecondDigits: 3,
+ };
+ case 'seconds':
+ return { ...time, second: '2-digit' };
+ case 'minutes':
+ return time;
+ case 'date':
+ return date;
+ default:
+ return { ...date, ...time };
+ }
+ }
+
+ private get currentLocale(): string {
+ return (
+ this.translateService.getCurrentLang() ||
+ this.translateService.getFallbackLang() ||
+ 'en'
+ );
+ }
+}
diff --git a/ui/src/app/chart-shared/components/charts/indicator/model/indicator-chart-widget.model.ts b/ui/src/app/chart-shared/services/formatting/index.ts
similarity index 50%
copy from ui/src/app/chart-shared/components/charts/indicator/model/indicator-chart-widget.model.ts
copy to ui/src/app/chart-shared/services/formatting/index.ts
index dc462922fc..2cf34edba9 100644
--- a/ui/src/app/chart-shared/components/charts/indicator/model/indicator-chart-widget.model.ts
+++ b/ui/src/app/chart-shared/services/formatting/index.ts
@@ -16,30 +16,5 @@
*
*/
-import {
- DataExplorerDataConfig,
- DataExplorerField,
- DataExplorerWidgetModel,
-} from '@streampipes/platform-services';
-import {
- DataExplorerVisConfig,
- WidgetBaseAppearanceConfig,
-} from '../../../../models/dataview-dashboard.model';
-
-export interface IndicatorChartVisConfig extends DataExplorerVisConfig {
- valueField?: DataExplorerField;
- deltaField?: DataExplorerField;
- showDelta?: boolean;
- title?: string;
- description?: string;
-}
-
-export interface IndicatorAppearanceConfig extends WidgetBaseAppearanceConfig {
- valueFontSize?: number;
- deltaFontSize?: number;
-}
-
-export interface IndicatorChartWidgetModel extends DataExplorerWidgetModel {
- dataConfig: DataExplorerDataConfig;
- visualizationConfig: IndicatorChartVisConfig;
-}
+export * from './chart-number-format.service';
+export * from './chart-time-format.service';
diff --git a/ui/src/app/chart-shared/services/widget-render.utils.ts b/ui/src/app/chart-shared/services/widget-render.utils.ts
index 02d8acb9dc..c96fb5aa3d 100644
--- a/ui/src/app/chart-shared/services/widget-render.utils.ts
+++ b/ui/src/app/chart-shared/services/widget-render.utils.ts
@@ -20,32 +20,6 @@ export function clampValue(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
-export function normalizeWidgetDecimals(decimals: unknown): number | undefined {
- if (decimals === null || decimals === undefined || decimals === '') {
- return undefined;
- }
-
- const parsedValue = Number(decimals);
- if (!Number.isFinite(parsedValue)) {
- return undefined;
- }
-
- return Math.min(10, Math.max(0, Math.round(parsedValue)));
-}
-
-export function formatWidgetNumber(
- value: number,
- locale: string,
- decimals: unknown,
-): string {
- const normalizedDecimals = normalizeWidgetDecimals(decimals);
-
- return new Intl.NumberFormat(locale, {
- maximumFractionDigits: normalizedDecimals ?? 20,
- minimumFractionDigits: normalizedDecimals ?? 0,
- }).format(value);
-}
-
export function scaleResponsiveValue(
min: number,
max: number,