mirror of
https://github.com/SigNoz/signoz.git
synced 2026-06-13 04:10:27 +01:00
Compare commits
29 Commits
issue_5326
...
feat/panel
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9db935fe87 | ||
|
|
a795d7d940 | ||
|
|
ebae086731 | ||
|
|
7bd66a354c | ||
|
|
7db7b4aeb5 | ||
|
|
d17578eb59 | ||
|
|
0f21f0ad46 | ||
|
|
966ca178ba | ||
|
|
d47ac3c836 | ||
|
|
1bf580df72 | ||
|
|
51852fce5c | ||
|
|
20930d666c | ||
|
|
93d2ce40eb | ||
|
|
10d0480754 | ||
|
|
948d94f50c | ||
|
|
7eb0095133 | ||
|
|
df26eb1c1d | ||
|
|
36334309bb | ||
|
|
cfcd58b341 | ||
|
|
45fedefbab | ||
|
|
01ae688b58 | ||
|
|
f4e1465c13 | ||
|
|
b22eef6a65 | ||
|
|
4d3d1ef423 | ||
|
|
c775d7e398 | ||
|
|
27603e09d0 | ||
|
|
7b2882abde | ||
|
|
30f1c2d92d | ||
|
|
446dd4589f |
@@ -1364,8 +1364,6 @@ components:
|
||||
- appservice
|
||||
- containerapp
|
||||
- aks
|
||||
- sqldatabase
|
||||
- sqldatabasemi
|
||||
type: string
|
||||
CloudintegrationtypesServiceMetadata:
|
||||
properties:
|
||||
@@ -2438,13 +2436,6 @@ components:
|
||||
url:
|
||||
type: string
|
||||
type: object
|
||||
DashboardPanelDisplay:
|
||||
properties:
|
||||
description:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
type: object
|
||||
DashboardTextVariableSpec:
|
||||
properties:
|
||||
constant:
|
||||
@@ -2498,10 +2489,17 @@ components:
|
||||
$ref: '#/components/schemas/DashboardtypesTimePreference'
|
||||
type: object
|
||||
DashboardtypesBuilderQuerySpec:
|
||||
discriminator:
|
||||
mapping:
|
||||
logs: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregation'
|
||||
metrics: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregation'
|
||||
traces: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregation'
|
||||
propertyName: signal
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregation'
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregation'
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregation'
|
||||
type: object
|
||||
DashboardtypesComparisonOperator:
|
||||
enum:
|
||||
- above
|
||||
@@ -2565,13 +2563,12 @@ components:
|
||||
$ref: '#/components/schemas/DashboardtypesDatasourceSpec'
|
||||
type: object
|
||||
display:
|
||||
$ref: '#/components/schemas/CommonDisplay'
|
||||
$ref: '#/components/schemas/DashboardtypesDisplay'
|
||||
duration:
|
||||
type: string
|
||||
layouts:
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesLayout'
|
||||
nullable: true
|
||||
type: array
|
||||
links:
|
||||
items:
|
||||
@@ -2580,7 +2577,6 @@ components:
|
||||
panels:
|
||||
additionalProperties:
|
||||
$ref: '#/components/schemas/DashboardtypesPanel'
|
||||
nullable: true
|
||||
type: object
|
||||
refreshInterval:
|
||||
type: string
|
||||
@@ -2588,10 +2584,20 @@ components:
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesVariable'
|
||||
type: array
|
||||
required:
|
||||
- display
|
||||
- variables
|
||||
- panels
|
||||
- layouts
|
||||
type: object
|
||||
DashboardtypesDatasourcePlugin:
|
||||
discriminator:
|
||||
mapping:
|
||||
signoz/Datasource: '#/components/schemas/DashboardtypesDatasourcePluginVariantStruct'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesDatasourcePluginVariantStruct'
|
||||
type: object
|
||||
DashboardtypesDatasourcePluginKind:
|
||||
enum:
|
||||
- signoz/Datasource
|
||||
@@ -2618,6 +2624,15 @@ components:
|
||||
plugin:
|
||||
$ref: '#/components/schemas/DashboardtypesDatasourcePlugin'
|
||||
type: object
|
||||
DashboardtypesDisplay:
|
||||
properties:
|
||||
description:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
type: object
|
||||
DashboardtypesDynamicVariableSpec:
|
||||
properties:
|
||||
name:
|
||||
@@ -2658,7 +2673,7 @@ components:
|
||||
$ref: '#/components/schemas/DashboardtypesDashboardSpec'
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesPostableTag'
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
nullable: true
|
||||
type: array
|
||||
updatedAt:
|
||||
@@ -2735,8 +2750,13 @@ components:
|
||||
- path
|
||||
type: object
|
||||
DashboardtypesLayout:
|
||||
discriminator:
|
||||
mapping:
|
||||
Grid: '#/components/schemas/DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpec'
|
||||
type: object
|
||||
DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpec:
|
||||
properties:
|
||||
kind:
|
||||
@@ -2776,6 +2796,11 @@ components:
|
||||
- solid
|
||||
- dashed
|
||||
type: string
|
||||
DashboardtypesListOrder:
|
||||
enum:
|
||||
- asc
|
||||
- desc
|
||||
type: string
|
||||
DashboardtypesListPanelSpec:
|
||||
properties:
|
||||
selectFields:
|
||||
@@ -2783,6 +2808,12 @@ components:
|
||||
$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'
|
||||
type: array
|
||||
type: object
|
||||
DashboardtypesListSort:
|
||||
enum:
|
||||
- updated_at
|
||||
- created_at
|
||||
- name
|
||||
type: string
|
||||
DashboardtypesListVariableSpec:
|
||||
properties:
|
||||
allowAllValue:
|
||||
@@ -2796,7 +2827,7 @@ components:
|
||||
defaultValue:
|
||||
$ref: '#/components/schemas/VariableDefaultValue'
|
||||
display:
|
||||
$ref: '#/components/schemas/VariableDisplay'
|
||||
$ref: '#/components/schemas/DashboardtypesDisplay'
|
||||
name:
|
||||
type: string
|
||||
plugin:
|
||||
@@ -2804,6 +2835,136 @@ components:
|
||||
sort:
|
||||
nullable: true
|
||||
type: string
|
||||
required:
|
||||
- display
|
||||
type: object
|
||||
DashboardtypesListableDashboardForUserV2:
|
||||
properties:
|
||||
dashboards:
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesListedDashboardForUserV2'
|
||||
type: array
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
type: array
|
||||
total:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- dashboards
|
||||
- total
|
||||
- tags
|
||||
type: object
|
||||
DashboardtypesListableDashboardV2:
|
||||
properties:
|
||||
dashboards:
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesListedDashboardV2'
|
||||
type: array
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
type: array
|
||||
total:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- dashboards
|
||||
- total
|
||||
- tags
|
||||
type: object
|
||||
DashboardtypesListedDashboardForUserV2:
|
||||
properties:
|
||||
createdAt:
|
||||
format: date-time
|
||||
type: string
|
||||
createdBy:
|
||||
type: string
|
||||
id:
|
||||
type: string
|
||||
image:
|
||||
type: string
|
||||
locked:
|
||||
type: boolean
|
||||
name:
|
||||
type: string
|
||||
orgId:
|
||||
type: string
|
||||
pinned:
|
||||
type: boolean
|
||||
schemaVersion:
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/DashboardtypesSource'
|
||||
spec:
|
||||
$ref: '#/components/schemas/DashboardtypesListedDashboardV2Spec'
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
type: array
|
||||
updatedAt:
|
||||
format: date-time
|
||||
type: string
|
||||
updatedBy:
|
||||
type: string
|
||||
required:
|
||||
- id
|
||||
- orgId
|
||||
- locked
|
||||
- source
|
||||
- schemaVersion
|
||||
- name
|
||||
- tags
|
||||
- spec
|
||||
- pinned
|
||||
type: object
|
||||
DashboardtypesListedDashboardV2:
|
||||
properties:
|
||||
createdAt:
|
||||
format: date-time
|
||||
type: string
|
||||
createdBy:
|
||||
type: string
|
||||
id:
|
||||
type: string
|
||||
image:
|
||||
type: string
|
||||
locked:
|
||||
type: boolean
|
||||
name:
|
||||
type: string
|
||||
orgId:
|
||||
type: string
|
||||
schemaVersion:
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/DashboardtypesSource'
|
||||
spec:
|
||||
$ref: '#/components/schemas/DashboardtypesListedDashboardV2Spec'
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
type: array
|
||||
updatedAt:
|
||||
format: date-time
|
||||
type: string
|
||||
updatedBy:
|
||||
type: string
|
||||
required:
|
||||
- id
|
||||
- orgId
|
||||
- locked
|
||||
- source
|
||||
- schemaVersion
|
||||
- name
|
||||
- tags
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesListedDashboardV2Spec:
|
||||
properties:
|
||||
display:
|
||||
$ref: '#/components/schemas/DashboardtypesDisplay'
|
||||
type: object
|
||||
DashboardtypesNumberPanelSpec:
|
||||
properties:
|
||||
@@ -2823,6 +2984,9 @@ components:
|
||||
$ref: '#/components/schemas/DashboardtypesPanelKind'
|
||||
spec:
|
||||
$ref: '#/components/schemas/DashboardtypesPanelSpec'
|
||||
required:
|
||||
- kind
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesPanelFormatting:
|
||||
properties:
|
||||
@@ -2836,6 +3000,16 @@ components:
|
||||
- Panel
|
||||
type: string
|
||||
DashboardtypesPanelPlugin:
|
||||
discriminator:
|
||||
mapping:
|
||||
signoz/BarChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
|
||||
signoz/HistogramPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
|
||||
signoz/ListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec'
|
||||
signoz/NumberPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpec'
|
||||
signoz/PieChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpec'
|
||||
signoz/TablePanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec'
|
||||
signoz/TimeSeriesPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
|
||||
@@ -2844,6 +3018,7 @@ components:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec'
|
||||
type: object
|
||||
DashboardtypesPanelPluginKind:
|
||||
enum:
|
||||
- signoz/TimeSeriesPanel
|
||||
@@ -2941,7 +3116,7 @@ components:
|
||||
DashboardtypesPanelSpec:
|
||||
properties:
|
||||
display:
|
||||
$ref: '#/components/schemas/DashboardPanelDisplay'
|
||||
$ref: '#/components/schemas/DashboardtypesDisplay'
|
||||
links:
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardLink'
|
||||
@@ -2951,7 +3126,12 @@ components:
|
||||
queries:
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesQuery'
|
||||
nullable: true
|
||||
type: array
|
||||
required:
|
||||
- display
|
||||
- plugin
|
||||
- queries
|
||||
type: object
|
||||
DashboardtypesPatchOp:
|
||||
enum:
|
||||
@@ -3020,8 +3200,20 @@ components:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5RequestType'
|
||||
spec:
|
||||
$ref: '#/components/schemas/DashboardtypesQuerySpec'
|
||||
required:
|
||||
- kind
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesQueryPlugin:
|
||||
discriminator:
|
||||
mapping:
|
||||
signoz/BuilderQuery: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpec'
|
||||
signoz/ClickHouseSQL: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5ClickHouseQuery'
|
||||
signoz/CompositeQuery: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5CompositeQuery'
|
||||
signoz/Formula: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5QueryBuilderFormula'
|
||||
signoz/PromQLQuery: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5PromQuery'
|
||||
signoz/TraceOperator: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5QueryBuilderTraceOperator'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5CompositeQuery'
|
||||
@@ -3029,6 +3221,7 @@ components:
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5PromQuery'
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5ClickHouseQuery'
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5QueryBuilderTraceOperator'
|
||||
type: object
|
||||
DashboardtypesQueryPluginKind:
|
||||
enum:
|
||||
- signoz/BuilderQuery
|
||||
@@ -3116,6 +3309,8 @@ components:
|
||||
type: string
|
||||
plugin:
|
||||
$ref: '#/components/schemas/DashboardtypesQueryPlugin'
|
||||
required:
|
||||
- plugin
|
||||
type: object
|
||||
DashboardtypesQueryVariableSpec:
|
||||
properties:
|
||||
@@ -3283,9 +3478,15 @@ components:
|
||||
type: boolean
|
||||
type: object
|
||||
DashboardtypesVariable:
|
||||
discriminator:
|
||||
mapping:
|
||||
ListVariable: '#/components/schemas/DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesListVariableSpec'
|
||||
TextVariable: '#/components/schemas/DashboardtypesVariableEnvelopeGithubComPersesSpecGoDashboardTextVariableSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesListVariableSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesVariableEnvelopeGithubComPersesSpecGoDashboardTextVariableSpec'
|
||||
type: object
|
||||
DashboardtypesVariableEnvelopeGithubComPersesSpecGoDashboardTextVariableSpec:
|
||||
properties:
|
||||
kind:
|
||||
@@ -3311,10 +3512,17 @@ components:
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesVariablePlugin:
|
||||
discriminator:
|
||||
mapping:
|
||||
signoz/CustomVariable: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesCustomVariableSpec'
|
||||
signoz/DynamicVariable: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDynamicVariableSpec'
|
||||
signoz/QueryVariable: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesQueryVariableSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDynamicVariableSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesQueryVariableSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesCustomVariableSpec'
|
||||
type: object
|
||||
DashboardtypesVariablePluginKind:
|
||||
enum:
|
||||
- signoz/DynamicVariable
|
||||
@@ -5517,11 +5725,15 @@ components:
|
||||
$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'
|
||||
type: array
|
||||
signal:
|
||||
$ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
enum:
|
||||
- logs
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/TelemetrytypesSource'
|
||||
stepInterval:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
required:
|
||||
- signal
|
||||
type: object
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregation:
|
||||
properties:
|
||||
@@ -5568,11 +5780,15 @@ components:
|
||||
$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'
|
||||
type: array
|
||||
signal:
|
||||
$ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
enum:
|
||||
- metrics
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/TelemetrytypesSource'
|
||||
stepInterval:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
required:
|
||||
- signal
|
||||
type: object
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregation:
|
||||
properties:
|
||||
@@ -5619,11 +5835,15 @@ components:
|
||||
$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'
|
||||
type: array
|
||||
signal:
|
||||
$ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
enum:
|
||||
- traces
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/TelemetrytypesSource'
|
||||
stepInterval:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
required:
|
||||
- signal
|
||||
type: object
|
||||
Querybuildertypesv5QueryBuilderTraceOperator:
|
||||
properties:
|
||||
@@ -7064,6 +7284,16 @@ components:
|
||||
required:
|
||||
- references
|
||||
type: object
|
||||
TagtypesGettableTag:
|
||||
properties:
|
||||
key:
|
||||
type: string
|
||||
value:
|
||||
type: string
|
||||
required:
|
||||
- key
|
||||
- value
|
||||
type: object
|
||||
TagtypesPostableTag:
|
||||
properties:
|
||||
key:
|
||||
@@ -13099,6 +13329,82 @@ paths:
|
||||
tags:
|
||||
- preferences
|
||||
/api/v2/dashboards:
|
||||
get:
|
||||
deprecated: false
|
||||
description: Returns a page of v2-shape dashboards for the org. This is the
|
||||
pure, user-independent list — it carries no pin state. Use ListDashboardsForUserV2
|
||||
for the personalized, pin-aware list. Supports a filter DSL (`query`), sort
|
||||
(`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based
|
||||
pagination (`limit`/`offset`).
|
||||
operationId: ListDashboardsV2
|
||||
parameters:
|
||||
- in: query
|
||||
name: query
|
||||
schema:
|
||||
type: string
|
||||
- in: query
|
||||
name: sort
|
||||
schema:
|
||||
$ref: '#/components/schemas/DashboardtypesListSort'
|
||||
- in: query
|
||||
name: order
|
||||
schema:
|
||||
$ref: '#/components/schemas/DashboardtypesListOrder'
|
||||
- in: query
|
||||
name: limit
|
||||
schema:
|
||||
type: integer
|
||||
- in: query
|
||||
name: offset
|
||||
schema:
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
$ref: '#/components/schemas/DashboardtypesListableDashboardV2'
|
||||
status:
|
||||
type: string
|
||||
required:
|
||||
- status
|
||||
- data
|
||||
type: object
|
||||
description: OK
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: List dashboards (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
post:
|
||||
deprecated: false
|
||||
description: This endpoint creates a dashboard in the v2 format that follows
|
||||
@@ -13157,6 +13463,62 @@ paths:
|
||||
tags:
|
||||
- dashboard
|
||||
/api/v2/dashboards/{id}:
|
||||
delete:
|
||||
deprecated: false
|
||||
description: This endpoint deletes a v2-shape dashboard along with its tag relations.
|
||||
Locked dashboards are rejected.
|
||||
operationId: DeleteDashboardV2
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
description: No Content
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"404":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Not Found
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
summary: Delete dashboard (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
get:
|
||||
deprecated: false
|
||||
description: This endpoint returns a v2-shape dashboard.
|
||||
@@ -20379,6 +20741,196 @@ paths:
|
||||
summary: Update my user v2
|
||||
tags:
|
||||
- users
|
||||
/api/v2/users/me/dashboards:
|
||||
get:
|
||||
deprecated: false
|
||||
description: 'Same as ListDashboardsV2 but personalized for the calling user:
|
||||
each dashboard carries the caller''s `pinned` state, and pinned dashboards
|
||||
float to the top of the requested ordering. Supports the same filter DSL,
|
||||
sort, order, and pagination.'
|
||||
operationId: ListDashboardsForUserV2
|
||||
parameters:
|
||||
- in: query
|
||||
name: query
|
||||
schema:
|
||||
type: string
|
||||
- in: query
|
||||
name: sort
|
||||
schema:
|
||||
$ref: '#/components/schemas/DashboardtypesListSort'
|
||||
- in: query
|
||||
name: order
|
||||
schema:
|
||||
$ref: '#/components/schemas/DashboardtypesListOrder'
|
||||
- in: query
|
||||
name: limit
|
||||
schema:
|
||||
type: integer
|
||||
- in: query
|
||||
name: offset
|
||||
schema:
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
$ref: '#/components/schemas/DashboardtypesListableDashboardForUserV2'
|
||||
status:
|
||||
type: string
|
||||
required:
|
||||
- status
|
||||
- data
|
||||
type: object
|
||||
description: OK
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: List dashboards for the current user (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
/api/v2/users/me/dashboards/{id}/pins:
|
||||
delete:
|
||||
deprecated: false
|
||||
description: Removes the pin for the calling user. Idempotent — unpinning a
|
||||
dashboard that wasn't pinned still returns 204.
|
||||
operationId: UnpinDashboardV2
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
description: No Content
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: Unpin a dashboard for the current user (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
put:
|
||||
deprecated: false
|
||||
description: Pins the dashboard for the calling user. A user can pin at most
|
||||
10 dashboards; pinning when at the limit returns 409. Re-pinning an already-pinned
|
||||
dashboard is a no-op success.
|
||||
operationId: PinDashboardV2
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
description: No Content
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"404":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Not Found
|
||||
"409":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Conflict
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: Pin a dashboard for the current user (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
/api/v2/users/me/factor_password:
|
||||
put:
|
||||
deprecated: false
|
||||
|
||||
@@ -333,6 +333,50 @@ func (Step) JSONSchema() (jsonschema.Schema, error) {
|
||||
}
|
||||
```
|
||||
|
||||
### `oneOf` with a discriminator
|
||||
|
||||
For a sum type whose variants are keyed by a property (e.g. `kind`), expose the variants via `JSONSchemaOneOf()` and add a discriminator. Without it, code generators intersect the variants (`A & B & C`) instead of producing a clean discriminated union (`A | B | C`).
|
||||
|
||||
The parent keeps its `JSONSchemaOneOf()` (the `oneOf` itself) and *additionally* tags it via `PrepareJSONSchema` with the `x-signoz-discriminator` extension; `signoz.attachDiscriminators` then promotes that marker to a real OpenAPI 3 `discriminator` (and strips the duplicate parent properties) after reflection.
|
||||
|
||||
```go
|
||||
// On the parent: expose the oneOf variants...
|
||||
func (Plugin) JSONSchemaOneOf() []any {
|
||||
return []any{FooVariant{}}
|
||||
}
|
||||
|
||||
// ...and tag that same oneOf with the discriminator marker.
|
||||
func (Plugin) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
if s.ExtraProperties == nil {
|
||||
s.ExtraProperties = map[string]any{}
|
||||
}
|
||||
s.ExtraProperties["x-signoz-discriminator"] = map[string]any{
|
||||
"propertyName": "kind",
|
||||
"mapping": map[string]string{
|
||||
"signoz/Foo": "#/components/schemas/FooVariant",
|
||||
},
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
Each variant must declare the discriminator property (`kind`) and mark it `required`.
|
||||
|
||||
This produces the following in the generated OpenAPI spec:
|
||||
|
||||
```yaml
|
||||
Plugin:
|
||||
discriminator:
|
||||
propertyName: kind
|
||||
mapping:
|
||||
signoz/Foo: '#/components/schemas/FooVariant'
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/FooVariant'
|
||||
type: object
|
||||
```
|
||||
|
||||
Note the discriminator property lives in the variants, not on the parent — the parent is only the union.
|
||||
|
||||
|
||||
## What should I remember?
|
||||
|
||||
|
||||
@@ -229,10 +229,39 @@ func (module *module) PatchV2(ctx context.Context, orgID valuer.UUID, id valuer.
|
||||
return module.pkgDashboardModule.PatchV2(ctx, orgID, id, updatedBy, patch)
|
||||
}
|
||||
|
||||
func (module *module) DeleteV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error {
|
||||
return module.store.RunInTx(ctx, func(ctx context.Context) error {
|
||||
if err := module.store.DeletePublic(ctx, id.String()); err != nil && !errors.Ast(err, errors.TypeNotFound) {
|
||||
return err
|
||||
}
|
||||
return module.pkgDashboardModule.DeleteV2(ctx, orgID, id)
|
||||
})
|
||||
}
|
||||
|
||||
func (module *module) LockUnlockV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, isAdmin bool, lock bool) error {
|
||||
return module.pkgDashboardModule.LockUnlockV2(ctx, orgID, id, updatedBy, isAdmin, lock)
|
||||
}
|
||||
|
||||
func (module *module) ListV2(ctx context.Context, orgID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardV2, error) {
|
||||
return module.pkgDashboardModule.ListV2(ctx, orgID, params)
|
||||
}
|
||||
|
||||
func (module *module) ListForUserV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardForUserV2, error) {
|
||||
return module.pkgDashboardModule.ListForUserV2(ctx, orgID, userID, params)
|
||||
}
|
||||
|
||||
func (module *module) PinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) error {
|
||||
return module.pkgDashboardModule.PinV2(ctx, orgID, userID, id)
|
||||
}
|
||||
|
||||
func (module *module) UnpinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) error {
|
||||
return module.pkgDashboardModule.UnpinV2(ctx, orgID, userID, id)
|
||||
}
|
||||
|
||||
func (module *module) DeletePreferencesForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID) error {
|
||||
return module.pkgDashboardModule.DeletePreferencesForUser(ctx, orgID, userID)
|
||||
}
|
||||
|
||||
func (module *module) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.Dashboard, error) {
|
||||
return module.pkgDashboardModule.Get(ctx, orgID, id)
|
||||
}
|
||||
|
||||
@@ -185,6 +185,7 @@ func (s *Server) createPublicServer(apiHandler *api.APIHandler, web web.Web) (*h
|
||||
s.config.APIServer.Timeout.Default,
|
||||
s.config.APIServer.Timeout.Max,
|
||||
).Wrap)
|
||||
r.Use(middleware.NewResource(s.signoz.Instrumentation.Logger()).Wrap)
|
||||
r.Use(middleware.NewAudit(s.signoz.Instrumentation.Logger(), s.config.APIServer.Logging.ExcludedRoutes, s.signoz.Auditor).Wrap)
|
||||
r.Use(middleware.NewComment().Wrap)
|
||||
|
||||
|
||||
@@ -16,10 +16,11 @@ func newFormatter(dialect schema.Dialect) sqlstore.SQLFormatter {
|
||||
}
|
||||
|
||||
func (f *formatter) JSONExtractString(column, path string) []byte {
|
||||
var sql []byte
|
||||
sql = f.bunf.AppendIdent(sql, column)
|
||||
sql = append(sql, f.convertJSONPathToPostgres(path)...)
|
||||
return sql
|
||||
ops := f.convertJSONPathToPostgres(path)
|
||||
if len(ops) == 0 {
|
||||
return f.bunf.AppendIdent(nil, column)
|
||||
}
|
||||
return append(f.TextToJsonColumn(column), ops...)
|
||||
}
|
||||
|
||||
func (f *formatter) JSONType(column, path string) []byte {
|
||||
|
||||
@@ -18,19 +18,19 @@ func TestJSONExtractString(t *testing.T) {
|
||||
name: "simple path",
|
||||
column: "data",
|
||||
path: "$.field",
|
||||
expected: `"data"->>'field'`,
|
||||
expected: `"data"::jsonb->>'field'`,
|
||||
},
|
||||
{
|
||||
name: "nested path",
|
||||
column: "metadata",
|
||||
path: "$.user.name",
|
||||
expected: `"metadata"->'user'->>'name'`,
|
||||
expected: `"metadata"::jsonb->'user'->>'name'`,
|
||||
},
|
||||
{
|
||||
name: "deeply nested path",
|
||||
column: "json_col",
|
||||
path: "$.level1.level2.level3",
|
||||
expected: `"json_col"->'level1'->'level2'->>'level3'`,
|
||||
expected: `"json_col"::jsonb->'level1'->'level2'->>'level3'`,
|
||||
},
|
||||
{
|
||||
name: "root path",
|
||||
|
||||
@@ -26,6 +26,7 @@ import type {
|
||||
DashboardtypesPostablePublicDashboardDTO,
|
||||
DashboardtypesUpdatableDashboardV2DTO,
|
||||
DashboardtypesUpdatablePublicDashboardDTO,
|
||||
DeleteDashboardV2PathParameters,
|
||||
DeletePublicDashboardPathParameters,
|
||||
GetDashboardV2200,
|
||||
GetDashboardV2PathParameters,
|
||||
@@ -35,11 +36,17 @@ import type {
|
||||
GetPublicDashboardPathParameters,
|
||||
GetPublicDashboardWidgetQueryRange200,
|
||||
GetPublicDashboardWidgetQueryRangePathParameters,
|
||||
ListDashboardsForUserV2200,
|
||||
ListDashboardsForUserV2Params,
|
||||
ListDashboardsV2200,
|
||||
ListDashboardsV2Params,
|
||||
LockDashboardV2PathParameters,
|
||||
PatchDashboardV2200,
|
||||
PatchDashboardV2PathParameters,
|
||||
PinDashboardV2PathParameters,
|
||||
RenderErrorResponseDTO,
|
||||
UnlockDashboardV2PathParameters,
|
||||
UnpinDashboardV2PathParameters,
|
||||
UpdateDashboardV2200,
|
||||
UpdateDashboardV2PathParameters,
|
||||
UpdatePublicDashboardPathParameters,
|
||||
@@ -641,6 +648,103 @@ export const invalidateGetPublicDashboardWidgetQueryRange = async (
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a page of v2-shape dashboards for the org. This is the pure, user-independent list — it carries no pin state. Use ListDashboardsForUserV2 for the personalized, pin-aware list. Supports a filter DSL (`query`), sort (`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`).
|
||||
* @summary List dashboards (v2)
|
||||
*/
|
||||
export const listDashboardsV2 = (
|
||||
params?: ListDashboardsV2Params,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListDashboardsV2200>({
|
||||
url: `/api/v2/dashboards`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListDashboardsV2QueryKey = (
|
||||
params?: ListDashboardsV2Params,
|
||||
) => {
|
||||
return [`/api/v2/dashboards`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getListDashboardsV2QueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
params?: ListDashboardsV2Params,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getListDashboardsV2QueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listDashboardsV2>>> = ({
|
||||
signal,
|
||||
}) => listDashboardsV2(params, signal);
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListDashboardsV2QueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listDashboardsV2>>
|
||||
>;
|
||||
export type ListDashboardsV2QueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List dashboards (v2)
|
||||
*/
|
||||
|
||||
export function useListDashboardsV2<
|
||||
TData = Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
params?: ListDashboardsV2Params,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListDashboardsV2QueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return { ...query, queryKey: queryOptions.queryKey };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List dashboards (v2)
|
||||
*/
|
||||
export const invalidateListDashboardsV2 = async (
|
||||
queryClient: QueryClient,
|
||||
params?: ListDashboardsV2Params,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListDashboardsV2QueryKey(params) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* This endpoint creates a dashboard in the v2 format that follows Perses spec.
|
||||
* @summary Create dashboard (v2)
|
||||
@@ -724,6 +828,85 @@ export const useCreateDashboardV2 = <
|
||||
> => {
|
||||
return useMutation(getCreateDashboardV2MutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* This endpoint deletes a v2-shape dashboard along with its tag relations. Locked dashboards are rejected.
|
||||
* @summary Delete dashboard (v2)
|
||||
*/
|
||||
export const deleteDashboardV2 = (
|
||||
{ id }: DeleteDashboardV2PathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<string>({
|
||||
url: `/api/v2/dashboards/${id}`,
|
||||
method: 'DELETE',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getDeleteDashboardV2MutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: DeleteDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: DeleteDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['deleteDashboardV2'];
|
||||
const { mutation: mutationOptions } = options
|
||||
? options.mutation &&
|
||||
'mutationKey' in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey } };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
{ pathParams: DeleteDashboardV2PathParameters }
|
||||
> = (props) => {
|
||||
const { pathParams } = props ?? {};
|
||||
|
||||
return deleteDashboardV2(pathParams);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type DeleteDashboardV2MutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>
|
||||
>;
|
||||
|
||||
export type DeleteDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Delete dashboard (v2)
|
||||
*/
|
||||
export const useDeleteDashboardV2 = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: DeleteDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: DeleteDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getDeleteDashboardV2MutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* This endpoint returns a v2-shape dashboard.
|
||||
* @summary Get dashboard (v2)
|
||||
@@ -1181,3 +1364,260 @@ export const useLockDashboardV2 = <
|
||||
> => {
|
||||
return useMutation(getLockDashboardV2MutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Same as ListDashboardsV2 but personalized for the calling user: each dashboard carries the caller's `pinned` state, and pinned dashboards float to the top of the requested ordering. Supports the same filter DSL, sort, order, and pagination.
|
||||
* @summary List dashboards for the current user (v2)
|
||||
*/
|
||||
export const listDashboardsForUserV2 = (
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListDashboardsForUserV2200>({
|
||||
url: `/api/v2/users/me/dashboards`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListDashboardsForUserV2QueryKey = (
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
) => {
|
||||
return [`/api/v2/users/me/dashboards`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getListDashboardsForUserV2QueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getListDashboardsForUserV2QueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>
|
||||
> = ({ signal }) => listDashboardsForUserV2(params, signal);
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListDashboardsForUserV2QueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>
|
||||
>;
|
||||
export type ListDashboardsForUserV2QueryError =
|
||||
ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List dashboards for the current user (v2)
|
||||
*/
|
||||
|
||||
export function useListDashboardsForUserV2<
|
||||
TData = Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListDashboardsForUserV2QueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return { ...query, queryKey: queryOptions.queryKey };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List dashboards for the current user (v2)
|
||||
*/
|
||||
export const invalidateListDashboardsForUserV2 = async (
|
||||
queryClient: QueryClient,
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListDashboardsForUserV2QueryKey(params) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes the pin for the calling user. Idempotent — unpinning a dashboard that wasn't pinned still returns 204.
|
||||
* @summary Unpin a dashboard for the current user (v2)
|
||||
*/
|
||||
export const unpinDashboardV2 = (
|
||||
{ id }: UnpinDashboardV2PathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<string>({
|
||||
url: `/api/v2/users/me/dashboards/${id}/pins`,
|
||||
method: 'DELETE',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getUnpinDashboardV2MutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: UnpinDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: UnpinDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['unpinDashboardV2'];
|
||||
const { mutation: mutationOptions } = options
|
||||
? options.mutation &&
|
||||
'mutationKey' in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey } };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
{ pathParams: UnpinDashboardV2PathParameters }
|
||||
> = (props) => {
|
||||
const { pathParams } = props ?? {};
|
||||
|
||||
return unpinDashboardV2(pathParams);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type UnpinDashboardV2MutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>
|
||||
>;
|
||||
|
||||
export type UnpinDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Unpin a dashboard for the current user (v2)
|
||||
*/
|
||||
export const useUnpinDashboardV2 = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: UnpinDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: UnpinDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getUnpinDashboardV2MutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Pins the dashboard for the calling user. A user can pin at most 10 dashboards; pinning when at the limit returns 409. Re-pinning an already-pinned dashboard is a no-op success.
|
||||
* @summary Pin a dashboard for the current user (v2)
|
||||
*/
|
||||
export const pinDashboardV2 = (
|
||||
{ id }: PinDashboardV2PathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<string>({
|
||||
url: `/api/v2/users/me/dashboards/${id}/pins`,
|
||||
method: 'PUT',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getPinDashboardV2MutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: PinDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: PinDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['pinDashboardV2'];
|
||||
const { mutation: mutationOptions } = options
|
||||
? options.mutation &&
|
||||
'mutationKey' in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey } };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
{ pathParams: PinDashboardV2PathParameters }
|
||||
> = (props) => {
|
||||
const { pathParams } = props ?? {};
|
||||
|
||||
return pinDashboardV2(pathParams);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PinDashboardV2MutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>
|
||||
>;
|
||||
|
||||
export type PinDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Pin a dashboard for the current user (v2)
|
||||
*/
|
||||
export const usePinDashboardV2 = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: PinDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: PinDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getPinDashboardV2MutationOptions(options));
|
||||
};
|
||||
|
||||
@@ -2655,8 +2655,6 @@ export enum CloudintegrationtypesServiceIDDTO {
|
||||
appservice = 'appservice',
|
||||
containerapp = 'containerapp',
|
||||
aks = 'aks',
|
||||
sqldatabase = 'sqldatabase',
|
||||
sqldatabasemi = 'sqldatabasemi',
|
||||
}
|
||||
export type CloudintegrationtypesCloudIntegrationServiceDTOAnyOf = {
|
||||
/**
|
||||
@@ -3158,17 +3156,6 @@ export interface DashboardLinkDTO {
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface DashboardPanelDisplayDTO {
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
description?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface VariableDisplayDTO {
|
||||
/**
|
||||
* @type string
|
||||
@@ -3497,6 +3484,9 @@ export interface TelemetrytypesTelemetryFieldKeyDTO {
|
||||
unit?: string;
|
||||
}
|
||||
|
||||
export enum Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal {
|
||||
logs = 'logs',
|
||||
}
|
||||
export enum TelemetrytypesSourceDTO {
|
||||
meter = 'meter',
|
||||
}
|
||||
@@ -3552,7 +3542,11 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
* @type array
|
||||
*/
|
||||
selectFields?: TelemetrytypesTelemetryFieldKeyDTO[];
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @enum logs
|
||||
* @type string
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal;
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
stepInterval?: Querybuildertypesv5StepDTO;
|
||||
}
|
||||
@@ -3618,6 +3612,9 @@ export interface Querybuildertypesv5MetricAggregationDTO {
|
||||
timeAggregation?: MetrictypesTimeAggregationDTO;
|
||||
}
|
||||
|
||||
export enum Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal {
|
||||
metrics = 'metrics',
|
||||
}
|
||||
export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTO {
|
||||
/**
|
||||
* @type array
|
||||
@@ -3670,7 +3667,11 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
* @type array
|
||||
*/
|
||||
selectFields?: TelemetrytypesTelemetryFieldKeyDTO[];
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @enum metrics
|
||||
* @type string
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal;
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
stepInterval?: Querybuildertypesv5StepDTO;
|
||||
}
|
||||
@@ -3686,6 +3687,9 @@ export interface Querybuildertypesv5TraceAggregationDTO {
|
||||
expression?: string;
|
||||
}
|
||||
|
||||
export enum Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal {
|
||||
traces = 'traces',
|
||||
}
|
||||
export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTO {
|
||||
/**
|
||||
* @type array
|
||||
@@ -3738,7 +3742,11 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
* @type array
|
||||
*/
|
||||
selectFields?: TelemetrytypesTelemetryFieldKeyDTO[];
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @enum traces
|
||||
* @type string
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal;
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
stepInterval?: Querybuildertypesv5StepDTO;
|
||||
}
|
||||
@@ -3873,6 +3881,17 @@ export type DashboardtypesDashboardSpecDTODatasources = {
|
||||
export enum DashboardtypesPanelKindDTO {
|
||||
Panel = 'Panel',
|
||||
}
|
||||
export interface DashboardtypesDisplayDTO {
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
description?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
name: string;
|
||||
}
|
||||
|
||||
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTOKind {
|
||||
'signoz/TimeSeriesPanel' = 'signoz/TimeSeriesPanel',
|
||||
}
|
||||
@@ -4421,42 +4440,36 @@ export interface DashboardtypesQuerySpecDTO {
|
||||
* @type string
|
||||
*/
|
||||
name?: string;
|
||||
plugin?: DashboardtypesQueryPluginDTO;
|
||||
plugin: DashboardtypesQueryPluginDTO;
|
||||
}
|
||||
|
||||
export interface DashboardtypesQueryDTO {
|
||||
kind?: Querybuildertypesv5RequestTypeDTO;
|
||||
spec?: DashboardtypesQuerySpecDTO;
|
||||
kind: Querybuildertypesv5RequestTypeDTO;
|
||||
spec: DashboardtypesQuerySpecDTO;
|
||||
}
|
||||
|
||||
export interface DashboardtypesPanelSpecDTO {
|
||||
display?: DashboardPanelDisplayDTO;
|
||||
display: DashboardtypesDisplayDTO;
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
links?: DashboardLinkDTO[];
|
||||
plugin?: DashboardtypesPanelPluginDTO;
|
||||
plugin: DashboardtypesPanelPluginDTO;
|
||||
/**
|
||||
* @type array
|
||||
* @type array,null
|
||||
*/
|
||||
queries?: DashboardtypesQueryDTO[];
|
||||
queries: DashboardtypesQueryDTO[] | null;
|
||||
}
|
||||
|
||||
export interface DashboardtypesPanelDTO {
|
||||
kind?: DashboardtypesPanelKindDTO;
|
||||
spec?: DashboardtypesPanelSpecDTO;
|
||||
kind: DashboardtypesPanelKindDTO;
|
||||
spec: DashboardtypesPanelSpecDTO;
|
||||
}
|
||||
|
||||
export type DashboardtypesDashboardSpecDTOPanelsAnyOf = {
|
||||
export type DashboardtypesDashboardSpecDTOPanels = {
|
||||
[key: string]: DashboardtypesPanelDTO;
|
||||
};
|
||||
|
||||
/**
|
||||
* @nullable
|
||||
*/
|
||||
export type DashboardtypesDashboardSpecDTOPanels =
|
||||
DashboardtypesDashboardSpecDTOPanelsAnyOf | null;
|
||||
|
||||
export enum DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpecDTOKind {
|
||||
Grid = 'Grid',
|
||||
}
|
||||
@@ -4553,7 +4566,7 @@ export interface DashboardtypesListVariableSpecDTO {
|
||||
*/
|
||||
customAllValue?: string;
|
||||
defaultValue?: VariableDefaultValueDTO;
|
||||
display?: VariableDisplayDTO;
|
||||
display: DashboardtypesDisplayDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
@@ -4595,23 +4608,23 @@ export interface DashboardtypesDashboardSpecDTO {
|
||||
* @type object
|
||||
*/
|
||||
datasources?: DashboardtypesDashboardSpecDTODatasources;
|
||||
display?: CommonDisplayDTO;
|
||||
display: DashboardtypesDisplayDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
duration?: string;
|
||||
/**
|
||||
* @type array,null
|
||||
* @type array
|
||||
*/
|
||||
layouts?: DashboardtypesLayoutDTO[] | null;
|
||||
layouts: DashboardtypesLayoutDTO[];
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
links?: DashboardLinkDTO[];
|
||||
/**
|
||||
* @type object,null
|
||||
* @type object
|
||||
*/
|
||||
panels?: DashboardtypesDashboardSpecDTOPanels;
|
||||
panels: DashboardtypesDashboardSpecDTOPanels;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
@@ -4619,13 +4632,13 @@ export interface DashboardtypesDashboardSpecDTO {
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
variables?: DashboardtypesVariableDTO[];
|
||||
variables: DashboardtypesVariableDTO[];
|
||||
}
|
||||
|
||||
export enum DashboardtypesDatasourcePluginKindDTO {
|
||||
'signoz/Datasource' = 'signoz/Datasource',
|
||||
}
|
||||
export interface TagtypesPostableTagDTO {
|
||||
export interface TagtypesGettableTagDTO {
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
@@ -4675,7 +4688,7 @@ export interface DashboardtypesGettableDashboardV2DTO {
|
||||
/**
|
||||
* @type array,null
|
||||
*/
|
||||
tags: TagtypesPostableTagDTO[] | null;
|
||||
tags: TagtypesGettableTagDTO[] | null;
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
@@ -4733,6 +4746,157 @@ export interface DashboardtypesJSONPatchOperationDTO {
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
export enum DashboardtypesListOrderDTO {
|
||||
asc = 'asc',
|
||||
desc = 'desc',
|
||||
}
|
||||
export enum DashboardtypesListSortDTO {
|
||||
updated_at = 'updated_at',
|
||||
created_at = 'created_at',
|
||||
name = 'name',
|
||||
}
|
||||
export interface DashboardtypesListedDashboardV2SpecDTO {
|
||||
display?: DashboardtypesDisplayDTO;
|
||||
}
|
||||
|
||||
export interface DashboardtypesListedDashboardForUserV2DTO {
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
createdAt?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
createdBy?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
image?: string;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
locked: boolean;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
orgId: string;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
pinned: boolean;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
schemaVersion: string;
|
||||
source: DashboardtypesSourceDTO;
|
||||
spec: DashboardtypesListedDashboardV2SpecDTO;
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
tags: TagtypesGettableTagDTO[];
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
updatedAt?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
updatedBy?: string;
|
||||
}
|
||||
|
||||
export interface DashboardtypesListableDashboardForUserV2DTO {
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
dashboards: DashboardtypesListedDashboardForUserV2DTO[];
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
tags: TagtypesGettableTagDTO[];
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
*/
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface DashboardtypesListedDashboardV2DTO {
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
createdAt?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
createdBy?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
image?: string;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
locked: boolean;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
orgId: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
schemaVersion: string;
|
||||
source: DashboardtypesSourceDTO;
|
||||
spec: DashboardtypesListedDashboardV2SpecDTO;
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
tags: TagtypesGettableTagDTO[];
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
updatedAt?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
updatedBy?: string;
|
||||
}
|
||||
|
||||
export interface DashboardtypesListableDashboardV2DTO {
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
dashboards: DashboardtypesListedDashboardV2DTO[];
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
tags: TagtypesGettableTagDTO[];
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
*/
|
||||
total: number;
|
||||
}
|
||||
|
||||
export enum DashboardtypesPanelPluginKindDTO {
|
||||
'signoz/TimeSeriesPanel' = 'signoz/TimeSeriesPanel',
|
||||
'signoz/BarChartPanel' = 'signoz/BarChartPanel',
|
||||
@@ -4749,6 +4913,17 @@ export type DashboardtypesPatchableDashboardV2DTO =
|
||||
| DashboardtypesJSONPatchOperationDTO[]
|
||||
| null;
|
||||
|
||||
export interface TagtypesPostableTagDTO {
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface DashboardtypesPostableDashboardV2DTO {
|
||||
/**
|
||||
* @type boolean
|
||||
@@ -9651,6 +9826,40 @@ export type GetUserPreference200 = {
|
||||
export type UpdateUserPreferencePathParameters = {
|
||||
name: string;
|
||||
};
|
||||
export type ListDashboardsV2Params = {
|
||||
/**
|
||||
* @type string
|
||||
* @description undefined
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @description undefined
|
||||
*/
|
||||
sort?: DashboardtypesListSortDTO;
|
||||
/**
|
||||
* @description undefined
|
||||
*/
|
||||
order?: DashboardtypesListOrderDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @description undefined
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @description undefined
|
||||
*/
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
export type ListDashboardsV2200 = {
|
||||
data: DashboardtypesListableDashboardV2DTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type CreateDashboardV2201 = {
|
||||
data: DashboardtypesGettableDashboardV2DTO;
|
||||
/**
|
||||
@@ -9659,6 +9868,9 @@ export type CreateDashboardV2201 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type DeleteDashboardV2PathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type GetDashboardV2PathParameters = {
|
||||
id: string;
|
||||
};
|
||||
@@ -10491,6 +10703,46 @@ export type GetMyUser200 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListDashboardsForUserV2Params = {
|
||||
/**
|
||||
* @type string
|
||||
* @description undefined
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @description undefined
|
||||
*/
|
||||
sort?: DashboardtypesListSortDTO;
|
||||
/**
|
||||
* @description undefined
|
||||
*/
|
||||
order?: DashboardtypesListOrderDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @description undefined
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @description undefined
|
||||
*/
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
export type ListDashboardsForUserV2200 = {
|
||||
data: DashboardtypesListableDashboardForUserV2DTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type UnpinDashboardV2PathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type PinDashboardV2PathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type GetHosts200 = {
|
||||
data: ZeustypesGettableHostDTO;
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
// TODO: Improve the styling of the query aggregation container and its components. - @YounixM , @H4ad
|
||||
|
||||
$dropdown-base-height: 250px;
|
||||
$recents-header-height: 30px;
|
||||
$recent-row-height: 36px;
|
||||
// how many recents are rendered, this caps how tall the dropdown can grow to fit them.
|
||||
$max-recents-shown: 5;
|
||||
|
||||
.code-mirror-where-clause {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
@@ -117,7 +123,23 @@
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
font-family: 'Space Mono', monospace !important;
|
||||
min-height: 200px !important;
|
||||
max-height: $dropdown-base-height !important;
|
||||
overflow-y: auto !important;
|
||||
|
||||
// Recents render at the top of the dropdown ahead of regular suggestions.
|
||||
// At the base max-height, having recents in view would crowd out the
|
||||
// suggestion list below. This loop grows the dropdown by one row's worth
|
||||
// of height for every recent present (up to $max-recents-shown), plus the
|
||||
// section header. `:has(> li:nth-of-type(N) .cm-completionIcon-recent)`
|
||||
// matches when the Nth child of <ul> is a recent — i.e. there are at
|
||||
// least N recents visible.
|
||||
@for $i from 1 through $max-recents-shown {
|
||||
&:has(> li:nth-of-type(#{$i}) .cm-completionIcon-recent) {
|
||||
max-height: $dropdown-base-height +
|
||||
$recents-header-height +
|
||||
($i * $recent-row-height) !important;
|
||||
}
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 0.3rem;
|
||||
@@ -133,6 +155,19 @@
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
completion-section {
|
||||
display: block;
|
||||
padding: 10px 12px 6px;
|
||||
font-size: 10px !important;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--l3-foreground, var(--l2-foreground));
|
||||
opacity: 0.7;
|
||||
border-bottom: 0;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
li {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
@@ -159,11 +194,78 @@
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cm-completionDetail {
|
||||
margin-left: auto;
|
||||
font-style: normal;
|
||||
font-size: var(--periscope-font-size-small, 11px);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
&[aria-selected='true'] {
|
||||
background: var(--l3-background) !important;
|
||||
font-weight: 600 !important;
|
||||
}
|
||||
}
|
||||
|
||||
li:has(.cm-completionIcon-recent) {
|
||||
&:hover .cm-recent-delete,
|
||||
&[aria-selected='true'] .cm-recent-delete {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
li .cm-completionLabel {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cm-recent-delete {
|
||||
margin-left: 8px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
color: var(--l2-foreground);
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
opacity: 0.5;
|
||||
transition:
|
||||
opacity 0.12s ease,
|
||||
background-color 0.12s ease;
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
background: color-mix(in srgb, var(--l2-foreground) 18%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: '↓↑ to navigate · ↵ to apply · esc to dismiss';
|
||||
display: block;
|
||||
padding: 8px 12px;
|
||||
border-top: 1px solid var(--l1-border);
|
||||
font-family: 'Space Mono', monospace;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--l2-foreground);
|
||||
opacity: 0.6;
|
||||
background: color-mix(in srgb, var(--l1-background) 50%, transparent);
|
||||
border-bottom-left-radius: 4px;
|
||||
border-bottom-right-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,8 +46,15 @@ import {
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
import { unquote } from 'utils/stringUtils';
|
||||
|
||||
import { queryExamples } from './constants';
|
||||
import { combineInitialAndUserExpression } from './utils';
|
||||
import { getRecentQueries } from 'lib/recentQueries/getRecentQueries';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
|
||||
import { queryExamples, SUGGESTIONS_SECTION } from './constants';
|
||||
import {
|
||||
combineInitialAndUserExpression,
|
||||
getRecentOptions,
|
||||
renderRecentDeleteButton,
|
||||
} from './utils';
|
||||
|
||||
import './QuerySearch.styles.scss';
|
||||
|
||||
@@ -1250,6 +1257,41 @@ function QuerySearch({
|
||||
};
|
||||
}
|
||||
|
||||
const signal = dataSource as SignalType;
|
||||
|
||||
function combinedSuggestions(
|
||||
context: CompletionContext,
|
||||
): CompletionResult | null {
|
||||
const fullDoc = context.state.doc.toString();
|
||||
const recentOptions = getRecentOptions(
|
||||
getRecentQueries(signal, signalSource ?? ''),
|
||||
fullDoc,
|
||||
);
|
||||
const result = autoSuggestions(context);
|
||||
|
||||
const suggestionOptions = (result?.options || []).map((opt) => ({
|
||||
...opt,
|
||||
section: SUGGESTIONS_SECTION,
|
||||
}));
|
||||
|
||||
if (recentOptions.length === 0 && suggestionOptions.length === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
return {
|
||||
from: 0,
|
||||
to: fullDoc.length,
|
||||
options: recentOptions,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...result,
|
||||
options: [...recentOptions, ...suggestionOptions],
|
||||
};
|
||||
}
|
||||
|
||||
// Effect to handle focus state and trigger suggestions
|
||||
useEffect(() => {
|
||||
const clearTimeout = toggleSuggestions(10);
|
||||
@@ -1398,11 +1440,12 @@ function QuerySearch({
|
||||
})}
|
||||
extensions={[
|
||||
autocompletion({
|
||||
override: [autoSuggestions],
|
||||
override: [combinedSuggestions],
|
||||
defaultKeymap: true,
|
||||
closeOnBlur: true,
|
||||
activateOnTyping: true,
|
||||
maxRenderedOptions: 50,
|
||||
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
|
||||
}),
|
||||
javascript({ jsx: false, typescript: false }),
|
||||
EditorView.lineWrapping,
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
export const RECENTS_SECTION = { name: 'Recent searches', rank: 1 } as const;
|
||||
export const SUGGESTIONS_SECTION = { name: 'Suggestions', rank: 2 } as const;
|
||||
|
||||
// Custom CodeMirror Completion.type for recent-query entries. Used to discriminate
|
||||
// recents from regular autocomplete completions in renderers and event handlers.
|
||||
export const RECENT_COMPLETION_TYPE = 'recent';
|
||||
|
||||
// Max number of recents rendered in the autocomplete dropdown.
|
||||
// Do change $max-recents-shown: in QuerySearch.styles.scss if you change this.
|
||||
export const RECENTS_DISPLAY_CAP = 5;
|
||||
|
||||
export const queryExamples = [
|
||||
{
|
||||
label: 'Basic Query',
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
import { closeCompletion, startCompletion } from '@codemirror/autocomplete';
|
||||
import type { Completion } from '@codemirror/autocomplete';
|
||||
import type { EditorView } from '@uiw/react-codemirror';
|
||||
import dayjs from 'dayjs';
|
||||
import { normalizeFilterExpression } from 'lib/recentQueries/normalize';
|
||||
import * as recentQueriesStore from 'lib/recentQueries/recentQueriesStore';
|
||||
import type { RecentQueryEntry } from 'lib/recentQueries/types';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
import 'utils/timeUtils';
|
||||
|
||||
import {
|
||||
RECENT_COMPLETION_TYPE,
|
||||
RECENTS_DISPLAY_CAP,
|
||||
RECENTS_SECTION,
|
||||
} from './constants';
|
||||
|
||||
export function combineInitialAndUserExpression(
|
||||
initial: string,
|
||||
user: string,
|
||||
@@ -38,3 +54,106 @@ export function getUserExpressionFromCombined(
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
// Filters and projects a list of recent-query entries into CodeMirror completions.
|
||||
// Entries are supplied by the caller (typically via the useRecents hook) so this
|
||||
// function stays pure and React doesn't have to re-subscribe inside CodeMirror's
|
||||
// autocomplete callback.
|
||||
export function getRecentOptions(
|
||||
entries: RecentQueryEntry[],
|
||||
fullDoc: string,
|
||||
): Completion[] {
|
||||
const normalizedDoc = normalizeFilterExpression(fullDoc);
|
||||
|
||||
const matches = entries
|
||||
.filter((e) => {
|
||||
const normalizedRecent = normalizeFilterExpression(e.filter.expression);
|
||||
if (normalizedRecent === normalizedDoc) {
|
||||
return false;
|
||||
}
|
||||
if (normalizedDoc === '') {
|
||||
return true;
|
||||
}
|
||||
return normalizedRecent.includes(normalizedDoc);
|
||||
})
|
||||
.slice(0, RECENTS_DISPLAY_CAP);
|
||||
|
||||
return matches.map((entry, index) => ({
|
||||
label: entry.filter.expression,
|
||||
type: RECENT_COMPLETION_TYPE,
|
||||
// CodeMirror sorts within a section by boost desc, then label asc. The store
|
||||
// returns entries newest-first, so we mirror that by giving the newest entry
|
||||
// the highest boost — otherwise CM falls back to alphabetical order and the
|
||||
// "most recently used" expectation breaks. Stays within the recents section
|
||||
// because section.rank keeps recents above suggestions regardless of boost.
|
||||
boost: matches.length - index,
|
||||
section: RECENTS_SECTION,
|
||||
detail: dayjs(entry.lastUsedAt).fromNow(),
|
||||
recentId: entry.id,
|
||||
recentSignal: entry.signal,
|
||||
recentSource: entry.source,
|
||||
apply: (view: EditorView): void => {
|
||||
view.dispatch({
|
||||
changes: {
|
||||
from: 0,
|
||||
to: view.state.doc.length,
|
||||
insert: entry.filter.expression,
|
||||
},
|
||||
selection: { anchor: entry.filter.expression.length },
|
||||
});
|
||||
closeCompletion(view);
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function renderRecentDeleteButton(
|
||||
completion: Completion,
|
||||
_state: unknown,
|
||||
view: EditorView | null,
|
||||
): Node | null {
|
||||
if (completion.type !== RECENT_COMPLETION_TYPE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const c = completion as Completion & {
|
||||
recentId?: string;
|
||||
recentSignal?: SignalType;
|
||||
recentSource?: string;
|
||||
};
|
||||
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'cm-recent-delete';
|
||||
btn.setAttribute('aria-label', 'Remove from recent searches');
|
||||
btn.title = 'Remove from recent searches';
|
||||
btn.textContent = '×';
|
||||
queueMicrotask(() => {
|
||||
if (btn.parentElement) {
|
||||
btn.parentElement.title = completion.label;
|
||||
}
|
||||
});
|
||||
|
||||
const stop = (e: Event): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
// CodeMirror's autocomplete closes the popup on pointerdown / mousedown outside
|
||||
// the editor. The delete button lives inside the popup, so we must stop those
|
||||
// events early — otherwise clicking × would dismiss the dropdown before the
|
||||
// click handler fires and the entry wouldn't actually get removed.
|
||||
btn.addEventListener('pointerdown', stop);
|
||||
btn.addEventListener('mousedown', stop);
|
||||
btn.addEventListener('click', (e) => {
|
||||
stop(e);
|
||||
if (!c.recentId || !c.recentSignal) {
|
||||
return;
|
||||
}
|
||||
recentQueriesStore.remove(c.recentId, c.recentSignal, c.recentSource ?? '');
|
||||
if (view) {
|
||||
view.focus();
|
||||
startCompletion(view);
|
||||
}
|
||||
});
|
||||
|
||||
return btn;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export enum QueryParams {
|
||||
interval = 'interval',
|
||||
editPanelId = 'editPanelId',
|
||||
startTime = 'startTime',
|
||||
endTime = 'endTime',
|
||||
service = 'service',
|
||||
|
||||
@@ -40,13 +40,31 @@ type SpeechRecognitionConstructor = new () => ISpeechRecognition;
|
||||
|
||||
// ── Vendor-prefix shim for Safari / older browsers ────────────────────────────
|
||||
|
||||
const SpeechRecognitionAPI: SpeechRecognitionConstructor | null =
|
||||
typeof window !== 'undefined'
|
||||
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
((window as any).SpeechRecognition ??
|
||||
// Some hardened/enterprise browsers install a getter
|
||||
// on window.SpeechRecognition that THROWS on access ("Web Speech API is disabled
|
||||
// due to your security policy") instead of leaving the property undefined.
|
||||
// Because this resolves at module-evaluation time, an uncaught throw here aborts
|
||||
// the entire bundle and the app renders a blank page. Read defensively so a
|
||||
// throwing getter degrades to "unsupported" rather than crashing the app.
|
||||
function resolveSpeechRecognitionAPI(): SpeechRecognitionConstructor | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return (
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(window as any).SpeechRecognition ??
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(window as any).webkitSpeechRecognition ??
|
||||
null)
|
||||
: null;
|
||||
null
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const SpeechRecognitionAPI: SpeechRecognitionConstructor | null =
|
||||
resolveSpeechRecognitionAPI();
|
||||
|
||||
export type SpeechRecognitionError =
|
||||
| 'not-supported'
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import {
|
||||
createColumnsAndDataSource,
|
||||
evaluateThresholdWithConvertedValue,
|
||||
getQueryLegend,
|
||||
sortFunction,
|
||||
} from '../utils';
|
||||
@@ -225,3 +226,30 @@ describe('Table Panel utils with QB v5 aggregations', () => {
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// No units passed, so `convertUnit` is a no-op and the comparison runs against
|
||||
// the raw value — exercising `evaluateCondition`'s operator switch directly.
|
||||
describe('evaluateThresholdWithConvertedValue operators', () => {
|
||||
it('handles ordering operators', () => {
|
||||
expect(evaluateThresholdWithConvertedValue(5, 3, '>')).toBe(true);
|
||||
expect(evaluateThresholdWithConvertedValue(2, 3, '>')).toBe(false);
|
||||
expect(evaluateThresholdWithConvertedValue(2, 3, '<')).toBe(true);
|
||||
expect(evaluateThresholdWithConvertedValue(3, 3, '>=')).toBe(true);
|
||||
expect(evaluateThresholdWithConvertedValue(3, 3, '<=')).toBe(true);
|
||||
});
|
||||
|
||||
it('treats = and == as equality', () => {
|
||||
expect(evaluateThresholdWithConvertedValue(3, 3, '=')).toBe(true);
|
||||
expect(evaluateThresholdWithConvertedValue(3, 3, '==')).toBe(true);
|
||||
expect(evaluateThresholdWithConvertedValue(4, 3, '=')).toBe(false);
|
||||
});
|
||||
|
||||
it('handles != as inequality', () => {
|
||||
expect(evaluateThresholdWithConvertedValue(4, 3, '!=')).toBe(true);
|
||||
expect(evaluateThresholdWithConvertedValue(3, 3, '!=')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for an unknown operator', () => {
|
||||
expect(evaluateThresholdWithConvertedValue(3, 3, '~')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,8 +29,11 @@ function evaluateCondition(
|
||||
return value >= thresholdValue;
|
||||
case '<=':
|
||||
return value <= thresholdValue;
|
||||
case '=':
|
||||
case '==':
|
||||
return value === thresholdValue;
|
||||
case '!=':
|
||||
return value !== thresholdValue;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Dispatch, ReactNode, SetStateAction } from 'react';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { ColumnUnit } from 'types/api/dashboard/getAll';
|
||||
|
||||
export type ThresholdOperators = '>' | '<' | '>=' | '<=' | '=';
|
||||
export type ThresholdOperators = '>' | '<' | '>=' | '<=' | '=' | '!=';
|
||||
|
||||
export type ThresholdProps = {
|
||||
index: string;
|
||||
|
||||
@@ -6,6 +6,8 @@ export const operatorOptions: DefaultOptionType[] = [
|
||||
{ value: '>=', label: '>=' },
|
||||
{ value: '<', label: '<' },
|
||||
{ value: '<=', label: '<=' },
|
||||
{ value: '=', label: '=' },
|
||||
{ value: '!=', label: '≠' },
|
||||
];
|
||||
|
||||
export const showAsOptions: DefaultOptionType[] = [
|
||||
|
||||
@@ -142,6 +142,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
.reset-password-back-action {
|
||||
margin-top: var(--spacing-12);
|
||||
width: 100%;
|
||||
|
||||
button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: 100%;
|
||||
padding: 0 16px;
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { CircleAlert } from '@signozhq/icons';
|
||||
import { ArrowLeft, CircleAlert } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import AuthError from 'components/AuthError/AuthError';
|
||||
import AuthPageContainer from 'components/AuthPageContainer';
|
||||
import ROUTES from 'constants/routes';
|
||||
import history from 'lib/history';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import './ResetPassword.styles.scss';
|
||||
@@ -59,6 +62,16 @@ function TokenError({ error }: TokenErrorProps): JSX.Element {
|
||||
</Typography.Text>
|
||||
</div>
|
||||
{error && <AuthError error={error} />}
|
||||
<div className="reset-password-back-action">
|
||||
<Button
|
||||
variant="solid"
|
||||
data-testid="back-to-login"
|
||||
prefix={<ArrowLeft size={12} />}
|
||||
onClick={(): void => history.push(ROUTES.LOGIN)}
|
||||
>
|
||||
Back to login
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AuthPageContainer>
|
||||
);
|
||||
|
||||
@@ -119,6 +119,10 @@
|
||||
|
||||
border-radius: 0px 4px 4px 0px;
|
||||
background: var(--l3-background);
|
||||
|
||||
&.version-container-standalone {
|
||||
border-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.version {
|
||||
|
||||
@@ -1010,7 +1010,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
|
||||
<img src={signozBrandLogoUrl} alt="SigNoz" />
|
||||
</div>
|
||||
|
||||
{licenseTag && (
|
||||
{(licenseTag || currentVersion) && (
|
||||
<div
|
||||
className={cx(
|
||||
'brand-title-section',
|
||||
@@ -1021,7 +1021,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
|
||||
'version-update-notification',
|
||||
)}
|
||||
>
|
||||
<span className="license-type"> {licenseTag} </span>
|
||||
{licenseTag && <span className="license-type"> {licenseTag} </span>}
|
||||
|
||||
{currentVersion && (
|
||||
<Tooltip
|
||||
@@ -1043,7 +1043,12 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
|
||||
)
|
||||
}
|
||||
>
|
||||
<div className="version-container">
|
||||
<div
|
||||
className={cx(
|
||||
'version-container',
|
||||
!licenseTag && 'version-container-standalone',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cx('version', changelog && 'version-clickable')}
|
||||
onClick={onClickVersionHandler}
|
||||
|
||||
5
frontend/src/lib/recentQueries/constants.ts
Normal file
5
frontend/src/lib/recentQueries/constants.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export const STORAGE_KEY_PREFIX = 'qb_recent_v1';
|
||||
export const STORAGE_VERSION = 1;
|
||||
// Maximum entries kept per (signal, source) bucket. Larger than the UI's
|
||||
// RECENTS_DISPLAY_CAP so deleting a visible entry surfaces an older one.
|
||||
export const MAX_ENTRIES = 10;
|
||||
15
frontend/src/lib/recentQueries/getRecentQueries.ts
Normal file
15
frontend/src/lib/recentQueries/getRecentQueries.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
|
||||
import * as store from './recentQueriesStore';
|
||||
import type { RecentQueryEntry } from './types';
|
||||
|
||||
// Synchronous, non-subscribing read of the recent-queries bucket for a given
|
||||
// (signal, source). Read-on-demand by design — subscribing here would
|
||||
// reconfigure CodeMirror on every store change and close any open completion
|
||||
// popup. Pair with saveQuery() for the write path.
|
||||
export function getRecentQueries(
|
||||
signal: SignalType,
|
||||
source = '',
|
||||
): RecentQueryEntry[] {
|
||||
return store.list(signal, source);
|
||||
}
|
||||
100
frontend/src/lib/recentQueries/normalize.test.ts
Normal file
100
frontend/src/lib/recentQueries/normalize.test.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { normalizeFilterExpression } from './normalize';
|
||||
|
||||
describe('normalizeFilterExpression', () => {
|
||||
it('returns empty string for empty input', () => {
|
||||
expect(normalizeFilterExpression('')).toBe('');
|
||||
});
|
||||
|
||||
it('returns empty string for whitespace-only input', () => {
|
||||
expect(normalizeFilterExpression(' \t ')).toBe('');
|
||||
});
|
||||
|
||||
it('strips whitespace around operators', () => {
|
||||
expect(normalizeFilterExpression(' a = 1 ')).toBe('a=1');
|
||||
expect(normalizeFilterExpression('a = 1')).toBe('a=1');
|
||||
expect(normalizeFilterExpression('a=1')).toBe('a=1');
|
||||
});
|
||||
|
||||
it('lowercases AND / OR / NOT outside quotes', () => {
|
||||
expect(normalizeFilterExpression('A AND B OR NOT C')).toBe('AandBornotC');
|
||||
});
|
||||
|
||||
it('lowercases IN / LIKE / ILIKE / CONTAINS', () => {
|
||||
expect(normalizeFilterExpression('host IN [1, 2] AND name LIKE "foo"')).toBe(
|
||||
'hostin[1,2]andnamelike"foo"',
|
||||
);
|
||||
});
|
||||
|
||||
it('lowercases REGEXP', () => {
|
||||
expect(normalizeFilterExpression('path REGEXP "foo"')).toBe(
|
||||
'pathregexp"foo"',
|
||||
);
|
||||
expect(normalizeFilterExpression('path REGEXP "foo"')).toBe(
|
||||
normalizeFilterExpression('path regexp "foo"'),
|
||||
);
|
||||
});
|
||||
|
||||
it('lowercases HAS / HASANY / HASALL / HASTOKEN function names', () => {
|
||||
expect(normalizeFilterExpression('HAS(tags, "x")')).toBe(
|
||||
normalizeFilterExpression('has(tags, "x")'),
|
||||
);
|
||||
expect(normalizeFilterExpression('HASANY(tags, ["a","b"])')).toBe(
|
||||
normalizeFilterExpression('hasAny(tags, ["a","b"])'),
|
||||
);
|
||||
expect(normalizeFilterExpression('HASALL(tags, ["a","b"])')).toBe(
|
||||
normalizeFilterExpression('hasAll(tags, ["a","b"])'),
|
||||
);
|
||||
expect(normalizeFilterExpression('HASTOKEN(msg, "err")')).toBe(
|
||||
normalizeFilterExpression('hasToken(msg, "err")'),
|
||||
);
|
||||
});
|
||||
|
||||
it('lowercases TRUE / FALSE boolean literals', () => {
|
||||
expect(normalizeFilterExpression('active = TRUE')).toBe(
|
||||
normalizeFilterExpression('active = true'),
|
||||
);
|
||||
expect(normalizeFilterExpression('active = FALSE')).toBe(
|
||||
normalizeFilterExpression('active = false'),
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves whitespace and casing inside single-quoted strings', () => {
|
||||
expect(normalizeFilterExpression("a = 'X Y'")).toBe("a='X Y'");
|
||||
});
|
||||
|
||||
it('preserves whitespace and casing inside double-quoted strings', () => {
|
||||
expect(normalizeFilterExpression('a = "X Y"')).toBe('a="X Y"');
|
||||
});
|
||||
|
||||
it('does not lowercase keyword-looking substrings inside quotes', () => {
|
||||
expect(normalizeFilterExpression("msg = 'AND ERROR'")).toBe(
|
||||
"msg='AND ERROR'",
|
||||
);
|
||||
});
|
||||
|
||||
it('handles escaped quotes inside strings', () => {
|
||||
expect(normalizeFilterExpression("msg = 'a\\'b' AND x = 1")).toBe(
|
||||
"msg='a\\'b'andx=1",
|
||||
);
|
||||
});
|
||||
|
||||
it('treats two formattings of the same expression as identical', () => {
|
||||
const a = normalizeFilterExpression(
|
||||
'service.name = "frontend" AND severity = error',
|
||||
);
|
||||
const b = normalizeFilterExpression(
|
||||
'service.name="frontend" and severity=error',
|
||||
);
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it('preserves unquoted value casing (treats them as identifiers)', () => {
|
||||
expect(normalizeFilterExpression('status = OK')).toBe('status=OK');
|
||||
});
|
||||
|
||||
it('handles mixed quotes in one expression', () => {
|
||||
expect(normalizeFilterExpression(`a = 'X' AND b = "Y"`)).toBe(
|
||||
`a='X'andb="Y"`,
|
||||
);
|
||||
});
|
||||
});
|
||||
56
frontend/src/lib/recentQueries/normalize.ts
Normal file
56
frontend/src/lib/recentQueries/normalize.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import {
|
||||
OPERATORS,
|
||||
QUERY_BUILDER_FUNCTIONS,
|
||||
TRACE_OPERATOR_OPERATORS,
|
||||
} from 'constants/antlrQueryConstants';
|
||||
|
||||
// Reserved keywords sourced from the ANTLR grammar constants so this list stays
|
||||
// in sync with the parser. `\b` prevents partial matches inside identifiers
|
||||
// (e.g. `OR` inside `originator`). `TRUE`/`FALSE` are BOOL literals, included
|
||||
// so case variants of boolean values also dedup.
|
||||
const WORD_KEYWORDS = [
|
||||
...Object.keys(OPERATORS).filter((k) => /^[A-Z]+$/.test(k)),
|
||||
...Object.keys(TRACE_OPERATOR_OPERATORS).filter((k) => /^[A-Z]+$/.test(k)),
|
||||
...Object.values(QUERY_BUILDER_FUNCTIONS),
|
||||
'TRUE',
|
||||
'FALSE',
|
||||
];
|
||||
|
||||
const KEYWORDS_RE = new RegExp(`\\b(${WORD_KEYWORDS.join('|')})\\b`, 'gi');
|
||||
|
||||
// Matches single- or double-quoted string literals, supporting escaped quotes
|
||||
// (e.g. `'it\'s'` or `"a \" b"`). We preserve quoted spans verbatim during
|
||||
// normalisation so user-meaningful whitespace and casing inside string values
|
||||
// stays intact: `name = "Foo Bar"` must not collapse to `name="foobar"`.
|
||||
const QUOTED_RE = /'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g;
|
||||
|
||||
// Lowercases reserved keywords and strips ALL whitespace from the unquoted regions
|
||||
// of the input. Keywords are normalised so casing variants dedup; whitespace is
|
||||
// dropped so formatting variants (`a=1` vs `a = 1`) dedup too.
|
||||
function processOutsideQuotes(s: string): string {
|
||||
return s.replace(KEYWORDS_RE, (m) => m.toLowerCase()).replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
// Produces a canonical form of a filter expression suitable for dedup-key derivation.
|
||||
// Walks the input alternating between unquoted regions (where we normalise keywords
|
||||
// and whitespace) and quoted regions (which we copy verbatim).
|
||||
export function normalizeFilterExpression(input: string): string {
|
||||
if (!input) {
|
||||
return '';
|
||||
}
|
||||
|
||||
let result = '';
|
||||
let lastIndex = 0;
|
||||
QUOTED_RE.lastIndex = 0;
|
||||
|
||||
let match = QUOTED_RE.exec(input);
|
||||
while (match !== null) {
|
||||
result += processOutsideQuotes(input.slice(lastIndex, match.index));
|
||||
result += match[0];
|
||||
lastIndex = QUOTED_RE.lastIndex;
|
||||
match = QUOTED_RE.exec(input);
|
||||
}
|
||||
result += processOutsideQuotes(input.slice(lastIndex));
|
||||
|
||||
return result.trim();
|
||||
}
|
||||
247
frontend/src/lib/recentQueries/recentQueriesStore.test.ts
Normal file
247
frontend/src/lib/recentQueries/recentQueriesStore.test.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { MAX_ENTRIES } from './constants';
|
||||
import * as store from './recentQueriesStore';
|
||||
import type { RecentQueryInput } from './recentQueriesStore';
|
||||
import type { RecentQueryEntry } from './types';
|
||||
|
||||
const baseInput = (
|
||||
overrides: Partial<RecentQueryInput> = {},
|
||||
): RecentQueryInput => ({
|
||||
signal: 'logs',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function saveOrThrow(input: RecentQueryInput): RecentQueryEntry {
|
||||
const saved = store.save(input);
|
||||
if (!saved) {
|
||||
throw new Error('expected save to return an entry');
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
describe('recentQueries store', () => {
|
||||
beforeEach(() => {
|
||||
store.useRecentQueriesStore.setState({ buckets: {} });
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('save + list', () => {
|
||||
it('saves an entry and lists it', () => {
|
||||
store.save(baseInput());
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].filter.expression).toBe("service.name = 'frontend'");
|
||||
expect(entries[0].id).toBeTruthy();
|
||||
expect(entries[0].lastUsedAt).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('does not save when the filter expression is empty', () => {
|
||||
const result = store.save(baseInput({ filter: { expression: '' } }));
|
||||
expect(result).toBeNull();
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not save when the filter expression is whitespace only', () => {
|
||||
const result = store.save(baseInput({ filter: { expression: ' ' } }));
|
||||
expect(result).toBeNull();
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('LRU ordering', () => {
|
||||
it('places the most recently saved entry at the front', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
|
||||
store.save(baseInput({ filter: { expression: 'attempt = 1' } }));
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
|
||||
'attempt = 1',
|
||||
'http.status_code >= 500',
|
||||
"severity_text = 'ERROR'",
|
||||
]);
|
||||
});
|
||||
|
||||
it('re-saving an existing filter bumps it to the front', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(2);
|
||||
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
|
||||
"severity_text = 'ERROR'",
|
||||
'http.status_code >= 500',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dedup', () => {
|
||||
it('treats formatting variations of the same filter as one entry', () => {
|
||||
store.save(
|
||||
baseInput({
|
||||
filter: { expression: "severity_text = 'ERROR' AND attempt = 1" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
filter: { expression: "severity_text='ERROR' and attempt=1" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('signal partitioning', () => {
|
||||
it('saves to the right bucket per signal', () => {
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'logs',
|
||||
filter: { expression: "severity_text = 'ERROR'" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'traces',
|
||||
filter: { expression: "service.name = 'orders-api'" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'metrics',
|
||||
filter: { expression: 'cpu_usage > 80' },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
expect(store.list('traces')).toHaveLength(1);
|
||||
expect(store.list('metrics')).toHaveLength(1);
|
||||
expect(store.list('logs')[0].filter.expression).toBe(
|
||||
"severity_text = 'ERROR'",
|
||||
);
|
||||
expect(store.list('traces')[0].filter.expression).toBe(
|
||||
"service.name = 'orders-api'",
|
||||
);
|
||||
expect(store.list('metrics')[0].filter.expression).toBe('cpu_usage > 80');
|
||||
});
|
||||
|
||||
it('does not leak between signals on dedup', () => {
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'logs',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'traces',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
expect(store.list('traces')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('LRU cap', () => {
|
||||
it('caps the bucket at MAX_ENTRIES and evicts the oldest', () => {
|
||||
const total = MAX_ENTRIES + 1;
|
||||
for (let i = 0; i < total; i += 1) {
|
||||
store.save(baseInput({ filter: { expression: `attempt = ${i}` } }));
|
||||
}
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(MAX_ENTRIES);
|
||||
expect(entries[0].filter.expression).toBe(`attempt = ${total - 1}`);
|
||||
expect(entries.some((e) => e.filter.expression === 'attempt = 0')).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('remove', () => {
|
||||
it('removes an entry by id', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
const saved = saveOrThrow(
|
||||
baseInput({ filter: { expression: 'http.status_code >= 500' } }),
|
||||
);
|
||||
store.remove(saved.id, 'logs');
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].filter.expression).toBe("severity_text = 'ERROR'");
|
||||
});
|
||||
|
||||
it('is a no-op when the id does not exist', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
store.remove('does-not-exist', 'logs');
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not touch other signals', () => {
|
||||
const logsEntry = saveOrThrow(
|
||||
baseInput({
|
||||
signal: 'logs',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'traces',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
}),
|
||||
);
|
||||
|
||||
store.remove(logsEntry.id, 'logs');
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
expect(store.list('traces')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('persistence', () => {
|
||||
it('reads back the same entries after the in-memory state is reset', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
|
||||
|
||||
store.useRecentQueriesStore.setState({ buckets: {} });
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
|
||||
'http.status_code >= 500',
|
||||
"severity_text = 'ERROR'",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reactive subscription via zustand', () => {
|
||||
it('notifies zustand subscribers on save', () => {
|
||||
const cb = jest.fn();
|
||||
const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it('notifies zustand subscribers on remove', () => {
|
||||
const saved = saveOrThrow(
|
||||
baseInput({ filter: { expression: "severity_text = 'ERROR'" } }),
|
||||
);
|
||||
const cb = jest.fn();
|
||||
const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
|
||||
store.remove(saved.id, 'logs');
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it('stops notifying after unsubscribe', () => {
|
||||
const cb = jest.fn();
|
||||
const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
|
||||
unsubscribe();
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
expect(cb).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
144
frontend/src/lib/recentQueries/recentQueriesStore.ts
Normal file
144
frontend/src/lib/recentQueries/recentQueriesStore.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import get from 'api/browser/localstorage/get';
|
||||
import set from 'api/browser/localstorage/set';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { MAX_ENTRIES, STORAGE_VERSION } from './constants';
|
||||
import { normalizeFilterExpression } from './normalize';
|
||||
import type { RecentQueriesStoreShape, RecentQueryEntry } from './types';
|
||||
import { bucketKey, makeId, normalizeSource, storageKeyFor } from './utils';
|
||||
|
||||
// Mirrors parsed localStorage so equal raw strings return the same array ref —
|
||||
// preserves Object.is for zustand selector bail-out.
|
||||
const persistedBucketCache = new Map<
|
||||
string,
|
||||
{ raw: string; parsed: RecentQueryEntry[] }
|
||||
>();
|
||||
|
||||
function loadBucketFromStorage(
|
||||
signal: SignalType,
|
||||
source: string,
|
||||
): RecentQueryEntry[] | null {
|
||||
const key = bucketKey(signal, source);
|
||||
try {
|
||||
const raw = get(storageKeyFor(signal, source));
|
||||
if (!raw) {
|
||||
persistedBucketCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
const cached = persistedBucketCache.get(key);
|
||||
if (cached && cached.raw === raw) {
|
||||
return cached.parsed;
|
||||
}
|
||||
const parsedShape = JSON.parse(raw) as RecentQueriesStoreShape;
|
||||
if (
|
||||
parsedShape?.version !== STORAGE_VERSION ||
|
||||
!Array.isArray(parsedShape.entries)
|
||||
) {
|
||||
persistedBucketCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
persistedBucketCache.set(key, { raw, parsed: parsedShape.entries });
|
||||
return parsedShape.entries;
|
||||
} catch {
|
||||
persistedBucketCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveBucketToStorage(
|
||||
signal: SignalType,
|
||||
source: string,
|
||||
entries: RecentQueryEntry[],
|
||||
): void {
|
||||
try {
|
||||
const raw = JSON.stringify({ version: STORAGE_VERSION, entries });
|
||||
if (set(storageKeyFor(signal, source), raw)) {
|
||||
persistedBucketCache.set(bucketKey(signal, source), {
|
||||
raw,
|
||||
parsed: entries,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Ignore storage errors (e.g. quota exceeded, JSON.stringify failure).
|
||||
}
|
||||
}
|
||||
|
||||
export type RecentQueryInput = Omit<
|
||||
RecentQueryEntry,
|
||||
'id' | 'lastUsedAt' | 'source'
|
||||
> & {
|
||||
source?: string;
|
||||
};
|
||||
|
||||
type RecentQueriesState = {
|
||||
buckets: Record<string, RecentQueryEntry[]>;
|
||||
save: (entry: RecentQueryInput) => RecentQueryEntry | null;
|
||||
remove: (id: string, signal: SignalType, source?: string) => void;
|
||||
};
|
||||
|
||||
export const useRecentQueriesStore = create<RecentQueriesState>()(
|
||||
(set, get) => ({
|
||||
buckets: {},
|
||||
|
||||
save: (entry): RecentQueryEntry | null => {
|
||||
const normalized = normalizeFilterExpression(entry.filter.expression);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const source = normalizeSource(entry.source);
|
||||
const key = bucketKey(entry.signal, source);
|
||||
|
||||
const current =
|
||||
get().buckets[key] ?? loadBucketFromStorage(entry.signal, source) ?? [];
|
||||
const filtered = current.filter(
|
||||
(e) => normalizeFilterExpression(e.filter.expression) !== normalized,
|
||||
);
|
||||
|
||||
const newEntry: RecentQueryEntry = {
|
||||
...entry,
|
||||
source,
|
||||
id: makeId(entry.signal, source, normalized),
|
||||
lastUsedAt: Date.now(),
|
||||
};
|
||||
|
||||
const next = [newEntry, ...filtered].slice(0, MAX_ENTRIES);
|
||||
set({ buckets: { ...get().buckets, [key]: next } });
|
||||
saveBucketToStorage(entry.signal, source, next);
|
||||
return newEntry;
|
||||
},
|
||||
|
||||
remove: (id, signal, source = ''): void => {
|
||||
const key = bucketKey(signal, source);
|
||||
const current = get().buckets[key] ?? loadBucketFromStorage(signal, source);
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
const next = current.filter((e) => e.id !== id);
|
||||
if (next.length === current.length) {
|
||||
return;
|
||||
}
|
||||
set({ buckets: { ...get().buckets, [key]: next } });
|
||||
saveBucketToStorage(signal, source, next);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Plain-function wrappers for non-React callers — same pattern as useColumnStore.ts.
|
||||
export function save(entry: RecentQueryInput): RecentQueryEntry | null {
|
||||
return useRecentQueriesStore.getState().save(entry);
|
||||
}
|
||||
|
||||
export function remove(id: string, signal: SignalType, source = ''): void {
|
||||
useRecentQueriesStore.getState().remove(id, signal, source);
|
||||
}
|
||||
|
||||
// Synchronous bucket read with localStorage fallback for non-React callers.
|
||||
export function list(signal: SignalType, source = ''): RecentQueryEntry[] {
|
||||
const key = bucketKey(signal, source);
|
||||
const state = useRecentQueriesStore.getState();
|
||||
if (state.buckets[key]) {
|
||||
return state.buckets[key];
|
||||
}
|
||||
return loadBucketFromStorage(signal, source) ?? [];
|
||||
}
|
||||
113
frontend/src/lib/recentQueries/saveRecentQuery.test.ts
Normal file
113
frontend/src/lib/recentQueries/saveRecentQuery.test.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
|
||||
import * as store from './recentQueriesStore';
|
||||
import { saveRecentQuery } from './saveRecentQuery';
|
||||
|
||||
jest.mock('utils/queryValidationUtils', () => ({
|
||||
validateQuery: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockedValidateQuery = validateQuery as jest.MockedFunction<
|
||||
typeof validateQuery
|
||||
>;
|
||||
|
||||
const buildComposite = (
|
||||
overrides: Partial<IBuilderQuery>[] = [{}],
|
||||
): { builder: { queryData: IBuilderQuery[] } } => ({
|
||||
builder: {
|
||||
queryData: overrides.map((o, i) => ({
|
||||
queryName: `Q${i}`,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
aggregateAttribute: undefined as never,
|
||||
functions: [],
|
||||
filter: { expression: 'service.name = "frontend"' },
|
||||
groupBy: [],
|
||||
expression: `Q${i}`,
|
||||
disabled: false,
|
||||
having: [],
|
||||
limit: null,
|
||||
stepInterval: null,
|
||||
orderBy: [],
|
||||
legend: '',
|
||||
...o,
|
||||
})) as IBuilderQuery[],
|
||||
},
|
||||
});
|
||||
|
||||
describe('saveRecentQuery', () => {
|
||||
beforeEach(() => {
|
||||
store.useRecentQueriesStore.setState({ buckets: {} });
|
||||
localStorage.clear();
|
||||
mockedValidateQuery.mockReturnValue({
|
||||
isValid: true,
|
||||
message: '',
|
||||
errors: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('saves the composite query when validation passes', () => {
|
||||
saveRecentQuery(buildComposite());
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].filter.expression).toBe('service.name = "frontend"');
|
||||
});
|
||||
|
||||
it('does not save when validateQuery rejects the expression', () => {
|
||||
mockedValidateQuery.mockReturnValue({
|
||||
isValid: false,
|
||||
message: 'bad',
|
||||
errors: [],
|
||||
});
|
||||
|
||||
saveRecentQuery(buildComposite());
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not save a builder query with an empty filter expression', () => {
|
||||
saveRecentQuery(buildComposite([{ filter: { expression: '' } }]));
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('saves each builder query in the composite separately', () => {
|
||||
saveRecentQuery(
|
||||
buildComposite([
|
||||
{
|
||||
dataSource: DataSource.LOGS,
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
},
|
||||
{
|
||||
dataSource: DataSource.TRACES,
|
||||
filter: { expression: "service.name = 'orders-api'" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
expect(store.list('traces')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('skips builder queries whose dataSource is not a supported signal', () => {
|
||||
saveRecentQuery(
|
||||
buildComposite([{ dataSource: 'unknown' as IBuilderQuery['dataSource'] }]),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
expect(store.list('traces')).toHaveLength(0);
|
||||
expect(store.list('metrics')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('is a no-op when the composite is null, undefined, or empty', () => {
|
||||
saveRecentQuery(null);
|
||||
saveRecentQuery(undefined);
|
||||
saveRecentQuery({ builder: { queryData: [] } });
|
||||
saveRecentQuery({});
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
52
frontend/src/lib/recentQueries/saveRecentQuery.ts
Normal file
52
frontend/src/lib/recentQueries/saveRecentQuery.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
|
||||
import * as store from './recentQueriesStore';
|
||||
|
||||
function toSignal(dataSource: IBuilderQuery['dataSource']): SignalType | null {
|
||||
if (
|
||||
dataSource === 'logs' ||
|
||||
dataSource === 'traces' ||
|
||||
dataSource === 'metrics'
|
||||
) {
|
||||
return dataSource;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type CompositeWithBuilder = {
|
||||
builder?: { queryData?: IBuilderQuery[] };
|
||||
};
|
||||
|
||||
// Persists each builder query in the composite as a recent entry. Call this
|
||||
// only from explicit user-driven Run triggers — reacting to stagedQuery or any
|
||||
// other derived state pollutes recents with navigation/refresh/go-to traffic.
|
||||
export function saveRecentQuery(
|
||||
query: CompositeWithBuilder | null | undefined,
|
||||
): void {
|
||||
const queryData = query?.builder?.queryData;
|
||||
if (!Array.isArray(queryData) || queryData.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
queryData.forEach((q) => {
|
||||
const expression = q.filter?.expression?.trim();
|
||||
if (!expression) {
|
||||
return;
|
||||
}
|
||||
const validation = validateQuery(expression);
|
||||
if (!validation.isValid) {
|
||||
return;
|
||||
}
|
||||
const signal = toSignal(q.dataSource);
|
||||
if (!signal) {
|
||||
return;
|
||||
}
|
||||
store.save({
|
||||
signal,
|
||||
source: q.source ?? '',
|
||||
filter: q.filter ?? { expression: '' },
|
||||
});
|
||||
});
|
||||
}
|
||||
14
frontend/src/lib/recentQueries/types.ts
Normal file
14
frontend/src/lib/recentQueries/types.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { Filter, SignalType } from 'types/api/v5/queryRange';
|
||||
|
||||
export interface RecentQueryEntry {
|
||||
id: string;
|
||||
signal: SignalType;
|
||||
source: string;
|
||||
filter: Filter;
|
||||
lastUsedAt: number;
|
||||
}
|
||||
|
||||
export interface RecentQueriesStoreShape {
|
||||
version: 1;
|
||||
entries: RecentQueryEntry[];
|
||||
}
|
||||
24
frontend/src/lib/recentQueries/utils.ts
Normal file
24
frontend/src/lib/recentQueries/utils.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
|
||||
import { STORAGE_KEY_PREFIX } from './constants';
|
||||
|
||||
export function normalizeSource(source: string | undefined): string {
|
||||
return source ?? '';
|
||||
}
|
||||
|
||||
export function bucketKey(signal: SignalType, source: string): string {
|
||||
return `${signal}:${source}`;
|
||||
}
|
||||
|
||||
export function storageKeyFor(signal: SignalType, source: string): string {
|
||||
return `${STORAGE_KEY_PREFIX}:${bucketKey(signal, source)}`;
|
||||
}
|
||||
|
||||
// Same (signal, source, normalized filter) ⇒ same id ⇒ upsert.
|
||||
export function makeId(
|
||||
signal: SignalType,
|
||||
source: string,
|
||||
normalizedFilter: string,
|
||||
): string {
|
||||
return `${signal}|${source}|${normalizedFilter}`;
|
||||
}
|
||||
53
frontend/src/pages/DashboardPage/DashboardPage.tsx
Normal file
53
frontend/src/pages/DashboardPage/DashboardPage.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Modal } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { AxiosError } from 'axios';
|
||||
import NotFound from 'components/NotFound';
|
||||
import Spinner from 'components/Spinner';
|
||||
import DashboardContainer from 'container/DashboardContainer';
|
||||
import { useDashboardBootstrap } from 'hooks/dashboard/useDashboardBootstrap';
|
||||
import { useDashboardStore } from 'providers/Dashboard/store/useDashboardStore';
|
||||
import { ErrorType } from 'types/common';
|
||||
|
||||
function DashboardPage(): JSX.Element {
|
||||
const { dashboardId } = useParams<{ dashboardId: string }>();
|
||||
|
||||
const [onModal, Content] = Modal.useModal();
|
||||
|
||||
const { isLoading, isError, isFetching, error } = useDashboardBootstrap(
|
||||
dashboardId,
|
||||
{ confirm: onModal.confirm },
|
||||
);
|
||||
|
||||
const dashboardTitle = useDashboardStore((s) => s.dashboardData?.data.title);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = dashboardTitle || document.title;
|
||||
}, [dashboardTitle]);
|
||||
|
||||
const errorMessage = isError
|
||||
? (error as AxiosError<{ errorType: string }>)?.response?.data?.errorType
|
||||
: 'Something went wrong';
|
||||
|
||||
if (isError && !isFetching && errorMessage === ErrorType.NotFound) {
|
||||
return <NotFound />;
|
||||
}
|
||||
|
||||
if (isError && errorMessage) {
|
||||
return <Typography>{errorMessage}</Typography>;
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return <Spinner tip="Loading.." />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{Content}
|
||||
<DashboardContainer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DashboardPage;
|
||||
@@ -1,53 +1,15 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Modal } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { AxiosError } from 'axios';
|
||||
import NotFound from 'components/NotFound';
|
||||
import Spinner from 'components/Spinner';
|
||||
import DashboardContainer from 'container/DashboardContainer';
|
||||
import { useDashboardBootstrap } from 'hooks/dashboard/useDashboardBootstrap';
|
||||
import { useDashboardStore } from 'providers/Dashboard/store/useDashboardStore';
|
||||
import { ErrorType } from 'types/common';
|
||||
import { useIsDashboardV2 } from 'hooks/useIsDashboardV2';
|
||||
import DashboardPageV2 from 'pages/DashboardPageV2';
|
||||
|
||||
function DashboardPage(): JSX.Element {
|
||||
const { dashboardId } = useParams<{ dashboardId: string }>();
|
||||
import DashboardPage from './DashboardPage';
|
||||
|
||||
const [onModal, Content] = Modal.useModal();
|
||||
// Serves the V2 dashboard detail page when the `use_dashboard_v2` flag is active;
|
||||
// otherwise the existing V1 page. Lets V2 dark-ship behind the flag without
|
||||
// changing route definitions.
|
||||
function DashboardPageEntry(): JSX.Element {
|
||||
const isDashboardV2 = useIsDashboardV2();
|
||||
|
||||
const { isLoading, isError, isFetching, error } = useDashboardBootstrap(
|
||||
dashboardId,
|
||||
{ confirm: onModal.confirm },
|
||||
);
|
||||
|
||||
const dashboardTitle = useDashboardStore((s) => s.dashboardData?.data.title);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = dashboardTitle || document.title;
|
||||
}, [dashboardTitle]);
|
||||
|
||||
const errorMessage = isError
|
||||
? (error as AxiosError<{ errorType: string }>)?.response?.data?.errorType
|
||||
: 'Something went wrong';
|
||||
|
||||
if (isError && !isFetching && errorMessage === ErrorType.NotFound) {
|
||||
return <NotFound />;
|
||||
}
|
||||
|
||||
if (isError && errorMessage) {
|
||||
return <Typography>{errorMessage}</Typography>;
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return <Spinner tip="Loading.." />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{Content}
|
||||
<DashboardContainer />
|
||||
</>
|
||||
);
|
||||
return isDashboardV2 ? <DashboardPageV2 /> : <DashboardPage />;
|
||||
}
|
||||
|
||||
export default DashboardPage;
|
||||
export default DashboardPageEntry;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
.config {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
padding: 16px;
|
||||
gap: 16px;
|
||||
background-color: var(--l2-background);
|
||||
border-left: 1px solid var(--l2-border);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Input } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import type { PanelDisplayDraft } from '../types';
|
||||
|
||||
import styles from './ConfigPane.module.scss';
|
||||
|
||||
interface ConfigPaneProps {
|
||||
display: PanelDisplayDraft;
|
||||
onChangeDisplay: (next: Partial<PanelDisplayDraft>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Right-hand configuration pane. Milestone 1 exposes only the panel title and
|
||||
* description; later milestones render the data-driven section framework
|
||||
* (Formatting, Axes, Legend, …) below these general fields, keyed off the
|
||||
* panel kind's `SectionConfig[]`.
|
||||
*/
|
||||
function ConfigPane({
|
||||
display,
|
||||
onChangeDisplay,
|
||||
}: ConfigPaneProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.config}>
|
||||
<div className={styles.section}>
|
||||
<Typography.Text>Panel settings</Typography.Text>
|
||||
|
||||
<div className={styles.field}>
|
||||
<Typography.Text>Title</Typography.Text>
|
||||
<Input
|
||||
data-testid="panel-editor-v2-title"
|
||||
value={display.name}
|
||||
placeholder="Panel title"
|
||||
onChange={(e): void => onChangeDisplay({ name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.field}>
|
||||
<Typography.Text>Description</Typography.Text>
|
||||
<Input.TextArea
|
||||
data-testid="panel-editor-v2-description"
|
||||
value={display.description}
|
||||
placeholder="Add a description"
|
||||
rows={3}
|
||||
onChange={(e): void => onChangeDisplay({ description: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ConfigPane;
|
||||
@@ -0,0 +1,22 @@
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
background-color: var(--l2-background);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
}
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { X } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Divider } from '@signozhq/ui/divider';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './Header.module.scss';
|
||||
|
||||
interface HeaderProps {
|
||||
isDirty: boolean;
|
||||
isSaving: boolean;
|
||||
onSave: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function Header({
|
||||
isDirty,
|
||||
isSaving,
|
||||
onSave,
|
||||
onClose,
|
||||
}: HeaderProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.header}>
|
||||
<div className={styles.title}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="icon"
|
||||
suffix={<X size={14} />}
|
||||
data-testid="panel-editor-v2-close"
|
||||
onClick={onClose}
|
||||
/>
|
||||
<Divider type="vertical" />
|
||||
<Typography.Text>Configure panel</Typography.Text>
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
data-testid="panel-editor-v2-save"
|
||||
disabled={!isDirty || isSaving}
|
||||
loading={isSaving}
|
||||
onClick={onSave}
|
||||
>
|
||||
Save changes
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Header;
|
||||
@@ -0,0 +1,17 @@
|
||||
.root {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
.left {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
.preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
gap: 8px;
|
||||
background-image: radial-gradient(var(--l2-border) 1px, transparent 0);
|
||||
background-size: 20px 20px;
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
}
|
||||
|
||||
.header {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.queryType {
|
||||
display: inline-flex;
|
||||
padding: 4px 8px 4px 6px;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border-radius: 4px;
|
||||
background: var(--l3-background);
|
||||
backdrop-filter: blur(6px);
|
||||
width: fit-content;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
padding: 2% 5% 5% 5%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.surface {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
background: var(--l2-background);
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
color: var(--bg-vanilla-400, #8993ae);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports -- seed initial time from global store; never written back
|
||||
import { useSelector } from 'react-redux';
|
||||
import { Spin } from 'antd';
|
||||
import { Loader, Spline } from '@signozhq/icons';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';
|
||||
import QueryTypeTag from 'container/NewWidget/LeftContainer/QueryTypeTag';
|
||||
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
|
||||
import { getPanelDefinition } from 'pages/DashboardPageV2/DashboardContainer/Panels';
|
||||
import {
|
||||
type PanelQueryTimeOverride,
|
||||
usePanelQuery,
|
||||
} from 'pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import PreviewTimePicker, {
|
||||
type PreviewTime,
|
||||
} from '../PreviewTimePicker/PreviewTimePicker';
|
||||
|
||||
import styles from './PreviewPane.module.scss';
|
||||
|
||||
const NS_TO_SEC = 1e9;
|
||||
const SEC_TO_MS = 1e3;
|
||||
|
||||
interface PreviewPaneProps {
|
||||
panelId: string;
|
||||
panel: DashboardtypesPanelDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live preview for the panel editor. Renders the draft panel through the same
|
||||
* registry + query path the dashboard grid uses (`getPanelDefinition` +
|
||||
* `usePanelQuery`), so the preview is byte-for-byte the production renderer —
|
||||
* only the `panelMode` differs (DASHBOARD_EDIT).
|
||||
*
|
||||
* Time is editor-local (`PreviewTimePicker` never touches global Redux time or
|
||||
* the URL), so changing it here neither modifies nor re-runs the dashboard
|
||||
* behind the overlay. Seeded once from the current global selection so the
|
||||
* preview opens matching the dashboard. The local window is resolved to an
|
||||
* absolute `[startMs, endMs]` and handed to `usePanelQuery` as a time override
|
||||
* (the V5 request takes epoch ms; a relative selection is pinned at the moment
|
||||
* it's picked).
|
||||
*/
|
||||
function PreviewPane({ panelId, panel }: PreviewPaneProps): JSX.Element {
|
||||
const fullKind = panel.spec?.plugin?.kind;
|
||||
const panelDef = getPanelDefinition(fullKind);
|
||||
|
||||
const globalTime = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
|
||||
const [previewTime, setPreviewTime] = useState<PreviewTime>(() =>
|
||||
globalTime.selectedTime === 'custom'
|
||||
? {
|
||||
interval: 'custom',
|
||||
range: [
|
||||
Math.floor(globalTime.minTime / NS_TO_SEC),
|
||||
Math.floor(globalTime.maxTime / NS_TO_SEC),
|
||||
],
|
||||
}
|
||||
: { interval: globalTime.selectedTime, range: null },
|
||||
);
|
||||
|
||||
// Resolve the editor-local selection to an absolute epoch-ms window. Custom
|
||||
// uses the picked range; relative is computed now-based (Redux-independent)
|
||||
// and pinned until the user changes the picker — recomputing "now" each
|
||||
// render would churn the query key into an endless refetch loop.
|
||||
const time = useMemo<PanelQueryTimeOverride>(() => {
|
||||
if (previewTime.range) {
|
||||
return {
|
||||
startMs: previewTime.range[0] * SEC_TO_MS,
|
||||
endMs: previewTime.range[1] * SEC_TO_MS,
|
||||
};
|
||||
}
|
||||
const { start, end } = getStartEndRangeTime({
|
||||
type: 'GLOBAL_TIME',
|
||||
interval: previewTime.interval,
|
||||
});
|
||||
return { startMs: Number(start) * SEC_TO_MS, endMs: Number(end) * SEC_TO_MS };
|
||||
}, [previewTime]);
|
||||
|
||||
const { data, isLoading, error } = usePanelQuery({
|
||||
panel,
|
||||
panelId,
|
||||
enabled: !!panelDef,
|
||||
time,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={styles.preview}>
|
||||
<div className={styles.header}>
|
||||
<div className={styles.queryType}>
|
||||
<Spline size={14} />
|
||||
Plotted with <QueryTypeTag queryType={EQueryType.QUERY_BUILDER} />
|
||||
</div>
|
||||
<PreviewTimePicker value={previewTime} onChange={setPreviewTime} />
|
||||
</div>
|
||||
<div className={styles.container}>
|
||||
<div className={styles.surface}>
|
||||
{/* eslint-disable-next-line no-nested-ternary -- 3-way branch on render state */}
|
||||
{!panelDef ? (
|
||||
<div className={styles.state} data-testid="panel-editor-v2-unknown-kind">
|
||||
This panel type is not yet supported in V2.
|
||||
</div>
|
||||
) : isLoading && !data.response ? (
|
||||
<div className={styles.state} data-testid="panel-editor-v2-loading">
|
||||
<Spin indicator={<Loader size={14} className="animate-spin" />} />
|
||||
</div>
|
||||
) : (
|
||||
<panelDef.Renderer
|
||||
panelId={panelId}
|
||||
panel={panel}
|
||||
data={data}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
panelMode={PanelMode.DASHBOARD_EDIT}
|
||||
enableDrillDown={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default PreviewPane;
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import CustomTimePicker from 'components/CustomTimePicker/CustomTimePicker';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import type { DateTimeRangeType } from 'container/TopNav/CustomDateTimeModal';
|
||||
import { getOptions } from 'container/TopNav/DateTimeSelectionV2/constants';
|
||||
import type {
|
||||
CustomTimeType,
|
||||
Time,
|
||||
} from 'container/TopNav/DateTimeSelectionV2/types';
|
||||
import dayjs from 'dayjs';
|
||||
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
|
||||
const MS_TO_NS = 1e6;
|
||||
|
||||
export interface PreviewTime {
|
||||
/** Relative shorthand (e.g. `30m`) or `custom`. */
|
||||
interval: Time | CustomTimeType;
|
||||
/** Custom range `[startSec, endSec]`; null for relative. */
|
||||
range: [number, number] | null;
|
||||
}
|
||||
|
||||
interface PreviewTimePickerProps {
|
||||
value: PreviewTime;
|
||||
onChange: (next: PreviewTime) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time picker for the panel editor preview. Wraps the shared `CustomTimePicker`
|
||||
* with fully-local state — it never reads or writes global Redux time or the
|
||||
* URL, so changing the preview window doesn't touch (or re-run) the dashboard
|
||||
* behind the editor overlay. Selections are emitted via `onChange`; the parent
|
||||
* feeds them to the preview fetch.
|
||||
*/
|
||||
function PreviewTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
}: PreviewTimePickerProps): JSX.Element {
|
||||
const { pathname } = useLocation();
|
||||
const { timezone } = useTimezone();
|
||||
const [open, setOpen] = useState<boolean>(false);
|
||||
const [customVisible, setCustomVisible] = useState<boolean>(false);
|
||||
|
||||
const { interval, range } = value;
|
||||
const options = useMemo(() => getOptions(pathname), [pathname]);
|
||||
|
||||
// Active window in ms — custom uses the picked range; relative is computed
|
||||
// now-based (Redux-independent). Drives the relative-duration pill.
|
||||
const [startMs, endMs] = useMemo<[number, number]>(() => {
|
||||
if (range) {
|
||||
return [range[0] * 1000, range[1] * 1000];
|
||||
}
|
||||
const { start, end } = getStartEndRangeTime({
|
||||
type: 'GLOBAL_TIME',
|
||||
interval,
|
||||
});
|
||||
return [Number(start) * 1000, Number(end) * 1000];
|
||||
}, [interval, range]);
|
||||
|
||||
// Label shown for a custom range; relative selections render their own
|
||||
// "Last …" label from `selectedTime` inside CustomTimePicker.
|
||||
const selectedValue = useMemo(() => {
|
||||
if (!range) {
|
||||
return '';
|
||||
}
|
||||
const fmt = DATE_TIME_FORMATS.UK_DATETIME_SECONDS;
|
||||
const start = dayjs(startMs).tz(timezone.value).format(fmt);
|
||||
const end = dayjs(endMs).tz(timezone.value).format(fmt);
|
||||
return `${start} - ${end}`;
|
||||
}, [range, startMs, endMs, timezone.value]);
|
||||
|
||||
const onSelect = (next: string): void => {
|
||||
if (next === 'custom') {
|
||||
setCustomVisible(true);
|
||||
return;
|
||||
}
|
||||
setOpen(false);
|
||||
onChange({ interval: next as Time, range: null });
|
||||
};
|
||||
|
||||
const onCustomDateHandler = (dateTimeRange: DateTimeRangeType): void => {
|
||||
if (!dateTimeRange) {
|
||||
return;
|
||||
}
|
||||
const [startMoment, endMoment] = dateTimeRange;
|
||||
if (!startMoment || !endMoment) {
|
||||
return;
|
||||
}
|
||||
setCustomVisible(false);
|
||||
setOpen(false);
|
||||
onChange({
|
||||
interval: 'custom',
|
||||
range: [
|
||||
Math.floor(startMoment.toDate().getTime() / 1000),
|
||||
Math.floor(endMoment.toDate().getTime() / 1000),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<CustomTimePicker
|
||||
newPopover
|
||||
open={open}
|
||||
setOpen={setOpen}
|
||||
items={options}
|
||||
selectedTime={interval}
|
||||
selectedValue={selectedValue}
|
||||
minTime={startMs * MS_TO_NS}
|
||||
maxTime={endMs * MS_TO_NS}
|
||||
// Hides the zoom-out button — it mutates global time, which the editor
|
||||
// must not do.
|
||||
isModalTimeSelection
|
||||
onSelect={onSelect}
|
||||
onError={(): void => {}}
|
||||
onCustomDateHandler={onCustomDateHandler}
|
||||
customDateTimeVisible={customVisible}
|
||||
setCustomDTPickerVisible={setCustomVisible}
|
||||
onValidCustomDateChange={({ timeStr }): void => {
|
||||
setOpen(false);
|
||||
onChange({ interval: timeStr as Time, range: null });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default PreviewTimePicker;
|
||||
@@ -0,0 +1,12 @@
|
||||
.placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 30%;
|
||||
margin: 0 16px 16px;
|
||||
border: 1px dashed var(--l2-border);
|
||||
border-radius: 4px;
|
||||
color: var(--l2-foreground);
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Terminal } from '@signozhq/icons';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './QueryBuilderPlaceholder.module.scss';
|
||||
|
||||
/**
|
||||
* Placeholder for the query builder in the panel editor's left pane. Milestone 2
|
||||
* replaces this with the shared `QueryBuilderV2`, wired through `fromPerses` /
|
||||
* `toPerses` so query edits flow into the draft and re-fetch the preview.
|
||||
*/
|
||||
function QueryBuilderPlaceholder(): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
className={styles.placeholder}
|
||||
data-testid="panel-editor-v2-query-placeholder"
|
||||
>
|
||||
<Terminal size={16} />
|
||||
<Typography.Text>Query builder coming soon</Typography.Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default QueryBuilderPlaceholder;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
|
||||
import ConfigPane from '../ConfigPane/ConfigPane';
|
||||
|
||||
describe('ConfigPane', () => {
|
||||
it('renders the seeded title and description', () => {
|
||||
render(
|
||||
<ConfigPane
|
||||
display={{ name: 'CPU', description: 'usage' }}
|
||||
onChangeDisplay={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('panel-editor-v2-title')).toHaveValue('CPU');
|
||||
expect(screen.getByTestId('panel-editor-v2-description')).toHaveValue(
|
||||
'usage',
|
||||
);
|
||||
});
|
||||
|
||||
it('reports title edits via onChangeDisplay', () => {
|
||||
const onChangeDisplay = jest.fn();
|
||||
render(
|
||||
<ConfigPane
|
||||
display={{ name: 'CPU', description: 'usage' }}
|
||||
onChangeDisplay={onChangeDisplay}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByTestId('panel-editor-v2-title'), {
|
||||
target: { value: 'Memory' },
|
||||
});
|
||||
|
||||
expect(onChangeDisplay).toHaveBeenCalledWith({ name: 'Memory' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { usePanelEditorDraft } from '../usePanelEditorDraft';
|
||||
|
||||
function panel(name = 'CPU', description = 'usage'): DashboardtypesPanelDTO {
|
||||
return {
|
||||
kind: 'Panel',
|
||||
spec: {
|
||||
display: { name, description },
|
||||
plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },
|
||||
queries: [],
|
||||
},
|
||||
} as unknown as DashboardtypesPanelDTO;
|
||||
}
|
||||
|
||||
describe('usePanelEditorDraft', () => {
|
||||
it('seeds display from the initial panel and starts clean', () => {
|
||||
const { result } = renderHook(() => usePanelEditorDraft(panel()));
|
||||
|
||||
expect(result.current.display).toStrictEqual({
|
||||
name: 'CPU',
|
||||
description: 'usage',
|
||||
});
|
||||
expect(result.current.isDirty).toBe(false);
|
||||
});
|
||||
|
||||
it('updates display and flags the draft dirty', () => {
|
||||
const { result } = renderHook(() => usePanelEditorDraft(panel()));
|
||||
|
||||
act(() => result.current.setDisplay({ name: 'Memory' }));
|
||||
|
||||
expect(result.current.display.name).toBe('Memory');
|
||||
expect(result.current.display.description).toBe('usage');
|
||||
expect(result.current.isDirty).toBe(true);
|
||||
// draft stays in perses shape so preview + save consume it directly
|
||||
expect(result.current.draft.spec?.display?.name).toBe('Memory');
|
||||
});
|
||||
|
||||
it('reset restores the originally-loaded display', () => {
|
||||
const { result } = renderHook(() => usePanelEditorDraft(panel()));
|
||||
|
||||
act(() => result.current.setDisplay({ name: 'Memory', description: 'new' }));
|
||||
act(() => result.current.reset());
|
||||
|
||||
expect(result.current.display).toStrictEqual({
|
||||
name: 'CPU',
|
||||
description: 'usage',
|
||||
});
|
||||
expect(result.current.isDirty).toBe(false);
|
||||
});
|
||||
|
||||
it('treats a panel without display as empty strings', () => {
|
||||
const bare = {
|
||||
kind: 'Panel',
|
||||
spec: { plugin: { kind: 'signoz/PieChartPanel' } },
|
||||
} as unknown as DashboardtypesPanelDTO;
|
||||
const { result } = renderHook(() => usePanelEditorDraft(bare));
|
||||
|
||||
expect(result.current.display).toStrictEqual({ name: '', description: '' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import {
|
||||
getGetDashboardV2QueryKey,
|
||||
usePatchDashboardV2,
|
||||
} from 'api/generated/services/dashboard';
|
||||
|
||||
import { usePanelEditorSave } from '../usePanelEditorSave';
|
||||
|
||||
const mockInvalidateQueries = jest.fn();
|
||||
jest.mock('react-query', () => ({
|
||||
useQueryClient: (): { invalidateQueries: jest.Mock } => ({
|
||||
invalidateQueries: mockInvalidateQueries,
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('api/generated/services/dashboard', () => ({
|
||||
usePatchDashboardV2: jest.fn(),
|
||||
getGetDashboardV2QueryKey: jest.fn(() => ['/api/v2/dashboards/dash-1']),
|
||||
}));
|
||||
|
||||
const mockUsePatch = usePatchDashboardV2 as unknown as jest.Mock;
|
||||
const mockGetQueryKey = getGetDashboardV2QueryKey as unknown as jest.Mock;
|
||||
|
||||
describe('usePanelEditorSave', () => {
|
||||
const mutateAsync = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockUsePatch.mockReturnValue({
|
||||
mutateAsync,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('emits an add patch for the panel display and invalidates the dashboard query', async () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePanelEditorSave({ dashboardId: 'dash-1', panelId: 'panel-9' }),
|
||||
);
|
||||
|
||||
await result.current.save({ name: 'New title', description: 'desc' });
|
||||
|
||||
expect(mutateAsync).toHaveBeenCalledWith({
|
||||
pathParams: { id: 'dash-1' },
|
||||
data: [
|
||||
{
|
||||
op: 'add',
|
||||
path: '/spec/panels/panel-9/spec/display',
|
||||
value: { name: 'New title', description: 'desc' },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(mockGetQueryKey).toHaveBeenCalledWith({ id: 'dash-1' });
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith([
|
||||
'/api/v2/dashboards/dash-1',
|
||||
]);
|
||||
});
|
||||
|
||||
it('surfaces the mutation loading state as isSaving', () => {
|
||||
mockUsePatch.mockReturnValue({
|
||||
mutateAsync,
|
||||
isLoading: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePanelEditorSave({ dashboardId: 'dash-1', panelId: 'panel-9' }),
|
||||
);
|
||||
|
||||
expect(result.current.isSaving).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useCallback } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import {
|
||||
ResizableHandle,
|
||||
ResizablePanel,
|
||||
ResizablePanelGroup,
|
||||
useDefaultLayout,
|
||||
} from '@signozhq/ui/resizable';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import ConfigPane from './ConfigPane/ConfigPane';
|
||||
import Header from './Header/Header';
|
||||
import layoutStorage from './layoutStorage';
|
||||
import PreviewPane from './PreviewPane/PreviewPane';
|
||||
import QueryBuilderPlaceholder from './QueryBuilderPlaceholder/QueryBuilderPlaceholder';
|
||||
import { usePanelEditorDraft } from './usePanelEditorDraft';
|
||||
import { usePanelEditorSave } from './usePanelEditorSave';
|
||||
|
||||
import styles from './PanelEditor.module.scss';
|
||||
|
||||
interface PanelEditorContainerProps {
|
||||
dashboardId: string;
|
||||
panelId: string;
|
||||
panel: DashboardtypesPanelDTO;
|
||||
/** Dismiss the editor overlay (clears the `editPanelId` query param). */
|
||||
onClose: () => void;
|
||||
/** Called after a successful save so the dashboard can refetch. */
|
||||
onSaved: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* V2 panel editor rendered as a full-screen overlay on top of the dashboard
|
||||
* view (the dashboard stays mounted underneath). A resizable split holds the
|
||||
* live preview + query builder on the left and the configuration pane on the
|
||||
* right. Owns the draft state and the save round-trip.
|
||||
*/
|
||||
function PanelEditorContainer({
|
||||
dashboardId,
|
||||
panelId,
|
||||
panel,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: PanelEditorContainerProps): JSX.Element {
|
||||
const { draft, display, setDisplay, isDirty } = usePanelEditorDraft(panel);
|
||||
const { save, isSaving } = usePanelEditorSave({ dashboardId, panelId });
|
||||
const { defaultLayout, onLayoutChanged } = useDefaultLayout({
|
||||
id: 'panel-editor-v2',
|
||||
storage: layoutStorage,
|
||||
});
|
||||
|
||||
const onSave = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
await save(display);
|
||||
toast.success('Panel saved');
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch {
|
||||
toast.error('Failed to save panel');
|
||||
}
|
||||
}, [save, display, onSaved, onClose]);
|
||||
|
||||
// Portal to <body> so the fixed overlay escapes the dashboard content's
|
||||
// stacking context (AppLayout pins `.app-content` at `z-index: 0`, which
|
||||
// would otherwise trap the overlay below the side nav).
|
||||
return createPortal(
|
||||
<div className={styles.root} data-testid="panel-editor-v2">
|
||||
<Header
|
||||
isDirty={isDirty}
|
||||
isSaving={isSaving}
|
||||
onSave={onSave}
|
||||
onClose={onClose}
|
||||
/>
|
||||
<ResizablePanelGroup
|
||||
id="panel-editor-v2"
|
||||
orientation="horizontal"
|
||||
defaultLayout={defaultLayout}
|
||||
onLayoutChanged={onLayoutChanged}
|
||||
>
|
||||
<ResizablePanel minSize="70%" maxSize="80%" defaultSize="75%">
|
||||
<div className={styles.left}>
|
||||
<PreviewPane panelId={panelId} panel={draft} />
|
||||
<QueryBuilderPlaceholder />
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
<ResizableHandle withHandle />
|
||||
<ResizablePanel minSize="20%" maxSize="30%" defaultSize="25%">
|
||||
<ConfigPane display={display} onChangeDisplay={setDisplay} />
|
||||
</ResizablePanel>
|
||||
</ResizablePanelGroup>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
export default PanelEditorContainer;
|
||||
@@ -0,0 +1,17 @@
|
||||
import getLocalStorageApi from 'api/browser/localstorage/get';
|
||||
import setLocalStorageApi from 'api/browser/localstorage/set';
|
||||
|
||||
/**
|
||||
* `Storage`-shaped adapter (just `getItem`/`setItem`, which is all
|
||||
* `useDefaultLayout` consumes) backed by the scoped localStorage wrappers. The
|
||||
* wrappers prefix keys with the URL base path, so the persisted resizable
|
||||
* layout stays isolated per deployment instead of touching the raw global.
|
||||
*/
|
||||
const layoutStorage: Pick<Storage, 'getItem' | 'setItem'> = {
|
||||
getItem: (key: string): string | null => getLocalStorageApi(key),
|
||||
setItem: (key: string, value: string): void => {
|
||||
setLocalStorageApi(key, value);
|
||||
},
|
||||
};
|
||||
|
||||
export default layoutStorage;
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
/** The panel display fields editable in milestone 1 of the V2 panel editor. */
|
||||
export interface PanelDisplayDraft {
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Local draft state for the panel being edited. The draft is kept as a perses
|
||||
* `DashboardtypesPanelDTO` so the live preview (which feeds the panel renderer)
|
||||
* and the save patch share a single shape — no intermediate translation.
|
||||
*/
|
||||
export interface PanelEditorDraftApi {
|
||||
/** The current (possibly edited) panel. Always a defined object once seeded. */
|
||||
draft: DashboardtypesPanelDTO;
|
||||
/** Read the current display values (name/description) for the config pane. */
|
||||
display: PanelDisplayDraft;
|
||||
/** Patch the panel's display (title/description). */
|
||||
setDisplay: (next: Partial<PanelDisplayDraft>) => void;
|
||||
/** True when the draft diverges from the originally-loaded panel. */
|
||||
isDirty: boolean;
|
||||
/** Restore the draft to the originally-loaded panel. */
|
||||
reset: () => void;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import type { PanelDisplayDraft, PanelEditorDraftApi } from './types';
|
||||
|
||||
function readDisplay(panel: DashboardtypesPanelDTO): PanelDisplayDraft {
|
||||
return {
|
||||
name: panel.spec?.display?.name ?? '',
|
||||
description: panel.spec?.display?.description ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the editable draft of a single panel. Seeded once from the loaded panel
|
||||
* (`useState` initializer), then mutated locally until the user saves. Keeping
|
||||
* the draft in the perses `DashboardtypesPanelDTO` shape lets the preview pane
|
||||
* render it through the same renderer registry the dashboard uses, and lets the
|
||||
* save hook diff/patch it without any conversion.
|
||||
*/
|
||||
export function usePanelEditorDraft(
|
||||
initialPanel: DashboardtypesPanelDTO,
|
||||
): PanelEditorDraftApi {
|
||||
const [draft, setDraft] = useState<DashboardtypesPanelDTO>(initialPanel);
|
||||
|
||||
const setDisplay = useCallback((next: Partial<PanelDisplayDraft>): void => {
|
||||
setDraft((prev) => ({
|
||||
...prev,
|
||||
spec: {
|
||||
...prev.spec,
|
||||
display: {
|
||||
...prev.spec?.display,
|
||||
...next,
|
||||
},
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const reset = useCallback((): void => {
|
||||
setDraft(initialPanel);
|
||||
}, [initialPanel]);
|
||||
|
||||
const display = useMemo(() => readDisplay(draft), [draft]);
|
||||
|
||||
const isDirty = useMemo(() => {
|
||||
const initial = readDisplay(initialPanel);
|
||||
return (
|
||||
initial.name !== display.name || initial.description !== display.description
|
||||
);
|
||||
}, [initialPanel, display]);
|
||||
|
||||
return { draft, display, setDisplay, isDirty, reset };
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import {
|
||||
getGetDashboardV2QueryKey,
|
||||
usePatchDashboardV2,
|
||||
} from 'api/generated/services/dashboard';
|
||||
import {
|
||||
type DashboardtypesJSONPatchOperationDTO,
|
||||
DashboardtypesPatchOpDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import type { PanelDisplayDraft } from './types';
|
||||
|
||||
interface UsePanelEditorSaveArgs {
|
||||
dashboardId: string;
|
||||
panelId: string;
|
||||
}
|
||||
|
||||
interface UsePanelEditorSaveApi {
|
||||
save: (display: PanelDisplayDraft) => Promise<void>;
|
||||
isSaving: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists panel edits for the V2 editor via RFC-6902 JSON Patch.
|
||||
*
|
||||
* Milestone 1 only touches the panel's display (title/description), so it emits
|
||||
* a single `add` op against `/spec/panels/{panelId}/spec/display`. `add` doubles
|
||||
* as create-or-replace for the display object, so panels that loaded without a
|
||||
* display are handled without a separate existence check. Later milestones add
|
||||
* ops for queries and the per-kind plugin spec.
|
||||
*/
|
||||
export function usePanelEditorSave({
|
||||
dashboardId,
|
||||
panelId,
|
||||
}: UsePanelEditorSaveArgs): UsePanelEditorSaveApi {
|
||||
const queryClient = useQueryClient();
|
||||
const { mutateAsync, isLoading, error } = usePatchDashboardV2();
|
||||
|
||||
const save = useCallback(
|
||||
async (display: PanelDisplayDraft): Promise<void> => {
|
||||
const ops: DashboardtypesJSONPatchOperationDTO[] = [
|
||||
{
|
||||
op: DashboardtypesPatchOpDTO.add,
|
||||
path: `/spec/panels/${panelId}/spec/display`,
|
||||
value: { name: display.name, description: display.description },
|
||||
},
|
||||
];
|
||||
|
||||
await mutateAsync({ pathParams: { id: dashboardId }, data: ops });
|
||||
await queryClient.invalidateQueries(
|
||||
getGetDashboardV2QueryKey({ id: dashboardId }),
|
||||
);
|
||||
},
|
||||
[dashboardId, panelId, mutateAsync, queryClient],
|
||||
);
|
||||
|
||||
return { save, isSaving: isLoading, error: (error as Error) ?? null };
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useMemo } from 'react';
|
||||
import type { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import type { BuilderQuery } from 'types/api/v5/queryRange';
|
||||
|
||||
/**
|
||||
* Builds a record keyed by builder-query name to that query's groupBy keys
|
||||
* in the V1 `BaseAutocompleteData` shape — the shape `TimeSeries` and the
|
||||
* tooltip plugin consume. Conversion from v5 `GroupByKey` lives at this one
|
||||
* call site that needs the V1 shape; the rest of V2 panel code stays on
|
||||
* v5 types.
|
||||
*/
|
||||
export function useGroupByPerQuery(
|
||||
builderQueries: BuilderQuery[],
|
||||
): Record<string, BaseAutocompleteData[]> {
|
||||
return useMemo(() => {
|
||||
const result: Record<string, BaseAutocompleteData[]> = {};
|
||||
builderQueries.forEach((q) => {
|
||||
if (!q.name) {
|
||||
return;
|
||||
}
|
||||
result[q.name] = (q.groupBy ?? []).map((g) => ({
|
||||
key: g.name,
|
||||
dataType: g.fieldDataType as BaseAutocompleteData['dataType'],
|
||||
type: (g.fieldContext as BaseAutocompleteData['type']) ?? '',
|
||||
id: '',
|
||||
}));
|
||||
});
|
||||
return result;
|
||||
}, [builderQueries]);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { RefObject, useEffect, useRef, useState } from 'react';
|
||||
|
||||
const MIN_FONT_PX = 16;
|
||||
const MAX_FONT_PX = 60;
|
||||
// The value font is sized to a fraction of the container's smaller dimension so
|
||||
// it scales with the panel without overflowing.
|
||||
const FONT_SCALE_DIVISOR = 5;
|
||||
|
||||
/**
|
||||
* Sizes a single large value to its container, recomputing on resize via a
|
||||
* ResizeObserver. Returns the ref to attach to the container and the current
|
||||
* font size (px) to apply to the value text.
|
||||
*/
|
||||
export function useResponsiveFontSize(): {
|
||||
containerRef: RefObject<HTMLDivElement>;
|
||||
fontSize: string;
|
||||
} {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [fontSize, setFontSize] = useState('2.5vw');
|
||||
|
||||
useEffect(() => {
|
||||
const updateFontSize = (): void => {
|
||||
if (!containerRef.current) {
|
||||
return;
|
||||
}
|
||||
const { width, height } = containerRef.current.getBoundingClientRect();
|
||||
const minDimension = Math.min(width, height);
|
||||
const newSize = Math.max(
|
||||
Math.min(minDimension / FONT_SCALE_DIVISOR, MAX_FONT_PX),
|
||||
MIN_FONT_PX,
|
||||
);
|
||||
setFontSize(`${newSize}px`);
|
||||
};
|
||||
|
||||
updateFontSize();
|
||||
|
||||
const resizeObserver = new ResizeObserver(updateFontSize);
|
||||
if (containerRef.current) {
|
||||
resizeObserver.observe(containerRef.current);
|
||||
}
|
||||
|
||||
return (): void => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { containerRef, fontSize };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { definition as barChart } from './kinds/BarChartPanel/definition';
|
||||
import { definition as histogram } from './kinds/HistogramPanel/definition';
|
||||
import { definition as number } from './kinds/NumberPanel/definition';
|
||||
import { definition as pieChart } from './kinds/PieChartPanel/definition';
|
||||
import { definition as timeSeries } from './kinds/TimeSeriesPanel/definition';
|
||||
import type {
|
||||
PanelRegistry,
|
||||
RenderablePanelDefinition,
|
||||
} from './types/panelDefinition';
|
||||
import type { PanelKind } from './types/panelKind';
|
||||
|
||||
// Pure assembly: each kind owns its own PanelDefinition (see
|
||||
// `kinds/<Kind>/definition.ts`). Registering a new panel = add its folder and a
|
||||
// single entry below — no other central file needs editing.
|
||||
export const PANELS: PanelRegistry = {
|
||||
[timeSeries.kind]: timeSeries,
|
||||
[barChart.kind]: barChart,
|
||||
[histogram.kind]: histogram,
|
||||
[number.kind]: number,
|
||||
[pieChart.kind]: pieChart,
|
||||
};
|
||||
|
||||
export function getPanelDefinition(
|
||||
kind: string | undefined,
|
||||
): RenderablePanelDefinition | undefined {
|
||||
if (!kind) {
|
||||
return undefined;
|
||||
}
|
||||
// The registry is correlated by kind, so a string lookup yields a union over
|
||||
// every kind's exactly-typed definition. The renderer cannot be validated
|
||||
// against that union at the JSX boundary, so widen to the kind-agnostic
|
||||
// surface here — the single, intentional cast for the whole panel system.
|
||||
return PANELS[kind as PanelKind] as unknown as
|
||||
| RenderablePanelDefinition
|
||||
| undefined;
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { useCallback, useMemo, useRef } from 'react';
|
||||
import type { DashboardtypesBarChartPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import BarChart from 'container/DashboardContainer/visualization/charts/BarChart/BarChart';
|
||||
import TooltipFooter from 'container/DashboardContainer/visualization/panels/components/TooltipFooter';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useResizeObserver } from 'hooks/useDimensions';
|
||||
import { IRenderTooltipFooterArgs } from 'lib/uPlotV2/components/types';
|
||||
import {
|
||||
flattenTimeSeries,
|
||||
getExecStats,
|
||||
getTimeSeriesResults,
|
||||
} from 'pages/DashboardPageV2/DashboardContainer/queryV5/v5ResponseData';
|
||||
import { prepareAlignedData } from 'pages/DashboardPageV2/DashboardContainer/queryV5/uplotData';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
import { getTimeRangeFromQueryRangeRequest } from 'utils/getTimeRange';
|
||||
|
||||
import { useGroupByPerQuery } from '../../hooks/useGroupByPerQuery';
|
||||
import PanelStyles from '../../panel.module.scss';
|
||||
import { PanelRendererProps } from '../../types/rendererProps';
|
||||
import {
|
||||
resolveDecimalPrecision,
|
||||
resolveLegendPosition,
|
||||
} from '../../utils/chartAppearanceMappings';
|
||||
import { getBuilderQueries } from '../../utils/getBuilderQueries';
|
||||
|
||||
import { buildBarChartConfig } from './buildConfig';
|
||||
import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
|
||||
function BarPanelRenderer({
|
||||
panelId,
|
||||
panel,
|
||||
data,
|
||||
onClick,
|
||||
onDragSelect,
|
||||
dashboardPreference,
|
||||
panelMode,
|
||||
}: PanelRendererProps<'signoz/BarChartPanel'>): JSX.Element {
|
||||
const graphRef = useRef<HTMLDivElement>(null);
|
||||
const containerDimensions = useResizeObserver(graphRef);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const { timezone } = useTimezone();
|
||||
|
||||
// The registry guarantees this Renderer only runs when
|
||||
// `panel.spec.plugin.kind === 'signoz/BarChartPanel'`, so the cast is a
|
||||
// documented boundary narrowing. Memoized so the `?? {}` fallback doesn't
|
||||
// produce a fresh object on each render.
|
||||
const spec = useMemo<DashboardtypesBarChartPanelSpecDTO>(
|
||||
() => (panel?.spec?.plugin?.spec ?? {}) as DashboardtypesBarChartPanelSpecDTO,
|
||||
[panel?.spec?.plugin?.spec],
|
||||
);
|
||||
|
||||
const builderQueries = useMemo(
|
||||
() => getBuilderQueries(panel?.spec?.queries),
|
||||
[panel?.spec?.queries],
|
||||
);
|
||||
|
||||
// X-scale clamps come from the request that produced the data (falls back
|
||||
// to the global picker inside the helper). The generated request DTO is
|
||||
// structurally the hand-written V5 request; the cast is the boundary.
|
||||
const { minTimeScale, maxTimeScale } = useMemo(() => {
|
||||
const { startTime, endTime } = getTimeRangeFromQueryRangeRequest(
|
||||
data?.requestPayload as unknown as QueryRangeRequestV5 | undefined,
|
||||
);
|
||||
return { minTimeScale: startTime, maxTimeScale: endTime };
|
||||
}, [data?.requestPayload]);
|
||||
|
||||
const groupByPerQuery = useGroupByPerQuery(builderQueries);
|
||||
|
||||
const flatSeries = useMemo(
|
||||
() =>
|
||||
flattenTimeSeries(
|
||||
getTimeSeriesResults(data?.response),
|
||||
data?.legendMap ?? {},
|
||||
),
|
||||
[data?.response, data?.legendMap],
|
||||
);
|
||||
|
||||
const config = useMemo(
|
||||
() =>
|
||||
buildBarChartConfig({
|
||||
panelId,
|
||||
spec,
|
||||
builderQueries,
|
||||
series: flatSeries,
|
||||
stepIntervals: getExecStats(data?.response)?.stepIntervals,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
onDragSelect,
|
||||
}),
|
||||
[
|
||||
panelId,
|
||||
spec,
|
||||
builderQueries,
|
||||
flatSeries,
|
||||
data?.response,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
onDragSelect,
|
||||
// `config` gets mutated by TooltipPlugin (config.setCursor for cursor sync).
|
||||
// Rebuild it on syncMode changes so the new chart instance starts from a
|
||||
// clean config — otherwise switching to "No Sync" would inherit stale sync
|
||||
// settings from the previous mode.
|
||||
dashboardPreference?.syncMode,
|
||||
],
|
||||
);
|
||||
|
||||
const chartData = useMemo(() => prepareAlignedData(flatSeries), [flatSeries]);
|
||||
|
||||
const decimalPrecision = useMemo(
|
||||
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
|
||||
[spec.formatting?.decimalPrecision],
|
||||
);
|
||||
|
||||
const legendPosition = useMemo(() => {
|
||||
return resolveLegendPosition(spec.legend?.position);
|
||||
}, [spec.legend?.position]);
|
||||
|
||||
const renderTooltipFooter = useCallback(
|
||||
({ isPinned, dismiss }: IRenderTooltipFooterArgs) => (
|
||||
<TooltipFooter id={panelId} isPinned={isPinned} dismiss={dismiss} />
|
||||
),
|
||||
[panelId],
|
||||
);
|
||||
|
||||
// The uPlot key prop is the only way to force a full teardown and re-mount
|
||||
// of the chart. Including syncMode/syncFilterMode in the key ensures changes
|
||||
// to these preferences trigger a fresh chart instance, preventing stale
|
||||
// sync wiring from being inherited.
|
||||
const key = `${dashboardPreference?.syncMode}-${dashboardPreference?.syncFilterMode}`;
|
||||
|
||||
const handleChartClick = useCallback(
|
||||
(args: ChartClickData) => {
|
||||
onClick?.(args);
|
||||
},
|
||||
[onClick],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={graphRef}
|
||||
data-testid="bar-panel-renderer"
|
||||
className={PanelStyles.panelContainer}
|
||||
>
|
||||
{containerDimensions.width > 0 && containerDimensions.height > 0 && (
|
||||
<BarChart
|
||||
key={key}
|
||||
config={config}
|
||||
data={chartData}
|
||||
legendConfig={{ position: legendPosition }}
|
||||
groupByPerQuery={groupByPerQuery}
|
||||
canPinTooltip
|
||||
timezone={timezone}
|
||||
yAxisUnit={spec.formatting?.unit}
|
||||
decimalPrecision={decimalPrecision}
|
||||
width={containerDimensions.width}
|
||||
height={containerDimensions.height}
|
||||
syncMode={dashboardPreference?.syncMode}
|
||||
syncFilterMode={dashboardPreference?.syncFilterMode}
|
||||
isStackedBarChart={spec.visualization?.stackedBarChart ?? false}
|
||||
renderTooltipFooter={renderTooltipFooter}
|
||||
onClick={handleChartClick}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default BarPanelRenderer;
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { DashboardtypesBarChartPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { Timezone } from 'components/CustomTimePicker/timezoneUtils';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { getInitialStackedBands } from 'container/DashboardContainer/visualization/charts/utils/stackSeriesUtils';
|
||||
import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';
|
||||
import { buildBaseConfig } from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/baseConfigBuilder';
|
||||
import { resolveSeriesLabelV5 } from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/resolveSeriesLabel';
|
||||
import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
import { toClickPluginPayload } from 'pages/DashboardPageV2/DashboardContainer/queryV5/uplotData';
|
||||
import getLabelName from 'lib/getLabelName';
|
||||
import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';
|
||||
import { DrawStyle } from 'lib/uPlotV2/config/types';
|
||||
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
|
||||
import type { BuilderQuery } from 'types/api/v5/queryRange';
|
||||
|
||||
export interface BuildBarChartConfigArgs {
|
||||
panelId: string;
|
||||
spec: DashboardtypesBarChartPanelSpecDTO;
|
||||
/**
|
||||
* Flat list of builder queries on this panel (see `getBuilderQueries`).
|
||||
* Powers per-query legend resolution; empty for non-builder panels.
|
||||
*/
|
||||
builderQueries: BuilderQuery[];
|
||||
/** Flattened V5 series (see `flattenTimeSeries`). */
|
||||
series: PanelSeries[];
|
||||
/** Per-query step intervals from the response exec stats. */
|
||||
stepIntervals?: Record<string, number>;
|
||||
isDarkMode: boolean;
|
||||
timezone: Timezone;
|
||||
panelMode: PanelMode;
|
||||
onDragSelect?: (start: number, end: number) => void;
|
||||
onClick?: OnClickPluginOpts['onClick'];
|
||||
minTimeScale?: number;
|
||||
maxTimeScale?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a fully-wired `UPlotConfigBuilder` for a Bar chart panel.
|
||||
*
|
||||
* Delegates the panel-agnostic scaffolding (scales, thresholds, axes,
|
||||
* drag-to-zoom, click plugin) to the shared `buildBaseConfig`, then layers
|
||||
* in the Bar-specific concerns: optional stacking via uPlot bands, plus
|
||||
* one bar series per result row.
|
||||
*/
|
||||
export function buildBarChartConfig({
|
||||
panelId,
|
||||
spec,
|
||||
builderQueries,
|
||||
series,
|
||||
stepIntervals,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
onDragSelect,
|
||||
onClick,
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
}: BuildBarChartConfigArgs): UPlotConfigBuilder {
|
||||
const builder = buildBaseConfig({
|
||||
panelId,
|
||||
panelType: PANEL_TYPES.BAR,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
isLogScale: spec.axes?.isLogScale,
|
||||
softMin: spec.axes?.softMin ?? undefined,
|
||||
softMax: spec.axes?.softMax ?? undefined,
|
||||
formatting: spec.formatting,
|
||||
thresholds: spec.thresholds,
|
||||
stepIntervals,
|
||||
clickPayload: toClickPluginPayload(series),
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
onDragSelect,
|
||||
onClick,
|
||||
});
|
||||
|
||||
addSeries({
|
||||
builder,
|
||||
spec,
|
||||
builderQueries,
|
||||
series,
|
||||
stepIntervals,
|
||||
isDarkMode,
|
||||
});
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
interface AddSeriesArgs {
|
||||
builder: UPlotConfigBuilder;
|
||||
spec: DashboardtypesBarChartPanelSpecDTO;
|
||||
builderQueries: BuilderQuery[];
|
||||
series: PanelSeries[];
|
||||
stepIntervals?: Record<string, number>;
|
||||
isDarkMode: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one bar series per flattened V5 series, plus uPlot bands for stacking
|
||||
* when `spec.visualization.stackedBarChart` is set. Each series receives its
|
||||
* own per-query step interval so bar widths line up with the actual
|
||||
* sampling cadence reported by the backend.
|
||||
*
|
||||
* Order must match `prepareAlignedData` — both iterate the same flat list.
|
||||
*/
|
||||
function addSeries({
|
||||
builder,
|
||||
spec,
|
||||
builderQueries,
|
||||
series,
|
||||
stepIntervals,
|
||||
isDarkMode,
|
||||
}: AddSeriesArgs): void {
|
||||
const colorMapping = spec.legend?.customColors ?? {};
|
||||
|
||||
if (spec.visualization?.stackedBarChart) {
|
||||
// uPlot uses 1-based series indices (index 0 is the timestamp axis);
|
||||
// `+1` keeps the band targets aligned with the series we're about to add.
|
||||
builder.setBands(getInitialStackedBands(series.length + 1));
|
||||
}
|
||||
|
||||
series.forEach((s) => {
|
||||
const baseLabel = getLabelName(s.labels, s.queryName, s.legend);
|
||||
const label = resolveSeriesLabelV5(s, builderQueries, baseLabel);
|
||||
const stepInterval = s.queryName ? stepIntervals?.[s.queryName] : undefined;
|
||||
|
||||
builder.addSeries({
|
||||
scaleKey: 'y',
|
||||
drawStyle: DrawStyle.Bar,
|
||||
label,
|
||||
colorMapping,
|
||||
isDarkMode,
|
||||
stepInterval,
|
||||
metric: s.labels,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { PanelDefinition } from '../../types/panelDefinition';
|
||||
import Renderer from './Renderer';
|
||||
import { sections } from './sections';
|
||||
|
||||
export const definition: PanelDefinition<'signoz/BarChartPanel'> = {
|
||||
kind: 'signoz/BarChartPanel',
|
||||
displayName: 'Bar Chart',
|
||||
Renderer,
|
||||
sections,
|
||||
supportedSignals: [DataSource.METRICS, DataSource.LOGS, DataSource.TRACES],
|
||||
actions: { view: true, edit: true, download: false, createAlert: true },
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { SectionConfig } from '../../types/sections';
|
||||
|
||||
export const sections: SectionConfig[] = [
|
||||
{ kind: 'formatting', controls: { unit: true, decimals: true } },
|
||||
{ kind: 'axes', controls: { minMax: true, unit: true, logScale: true } },
|
||||
{ kind: 'legend', controls: { position: true, mode: true } },
|
||||
{ kind: 'thresholds', controls: { list: true } },
|
||||
{ kind: 'chartAppearance', controls: { stacked: true } },
|
||||
];
|
||||
@@ -0,0 +1,139 @@
|
||||
import { useCallback, useMemo, useRef } from 'react';
|
||||
import type { DashboardtypesHistogramPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import Histogram from 'container/DashboardContainer/visualization/charts/Histogram/Histogram';
|
||||
import TooltipFooter from 'container/DashboardContainer/visualization/panels/components/TooltipFooter';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useResizeObserver } from 'hooks/useDimensions';
|
||||
import { IRenderTooltipFooterArgs } from 'lib/uPlotV2/components/types';
|
||||
import {
|
||||
flattenTimeSeries,
|
||||
getTimeSeriesResults,
|
||||
} from 'pages/DashboardPageV2/DashboardContainer/queryV5/v5ResponseData';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import type uPlot from 'uplot';
|
||||
|
||||
import PanelStyles from '../../panel.module.scss';
|
||||
import { PanelRendererProps } from '../../types/rendererProps';
|
||||
import { resolveLegendPosition } from '../../utils/chartAppearanceMappings';
|
||||
import { getBuilderQueries } from '../../utils/getBuilderQueries';
|
||||
|
||||
import { buildHistogramConfig } from './buildConfig';
|
||||
import { prepareHistogramData } from './prepareData';
|
||||
import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
|
||||
function HistogramPanelRenderer({
|
||||
panelId,
|
||||
panel,
|
||||
data,
|
||||
panelMode,
|
||||
onClick,
|
||||
}: PanelRendererProps<'signoz/HistogramPanel'>): JSX.Element {
|
||||
const graphRef = useRef<HTMLDivElement>(null);
|
||||
const containerDimensions = useResizeObserver(graphRef);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const { timezone } = useTimezone();
|
||||
|
||||
// The registry guarantees this Renderer only runs when
|
||||
// `panel.spec.plugin.kind === 'signoz/HistogramPanel'`, so the cast is a
|
||||
// documented boundary narrowing.
|
||||
const spec = useMemo<DashboardtypesHistogramPanelSpecDTO>(
|
||||
() =>
|
||||
(panel?.spec?.plugin?.spec ?? {}) as DashboardtypesHistogramPanelSpecDTO,
|
||||
[panel?.spec?.plugin?.spec],
|
||||
);
|
||||
|
||||
const builderQueries = useMemo(
|
||||
() => getBuilderQueries(panel?.spec?.queries),
|
||||
[panel?.spec?.queries],
|
||||
);
|
||||
|
||||
const flatSeries = useMemo(
|
||||
() =>
|
||||
flattenTimeSeries(
|
||||
getTimeSeriesResults(data?.response),
|
||||
data?.legendMap ?? {},
|
||||
),
|
||||
[data?.response, data?.legendMap],
|
||||
);
|
||||
|
||||
const config = useMemo(
|
||||
() =>
|
||||
buildHistogramConfig({
|
||||
panelId,
|
||||
spec,
|
||||
builderQueries,
|
||||
series: flatSeries,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
}),
|
||||
[panelId, spec, builderQueries, flatSeries, isDarkMode, timezone, panelMode],
|
||||
);
|
||||
|
||||
const chartData = useMemo(
|
||||
() =>
|
||||
prepareHistogramData({
|
||||
series: flatSeries,
|
||||
bucketWidth: spec.histogramBuckets?.bucketWidth ?? undefined,
|
||||
bucketCount: spec.histogramBuckets?.bucketCount ?? undefined,
|
||||
mergeAllActiveQueries: spec.histogramBuckets?.mergeAllActiveQueries,
|
||||
}),
|
||||
[
|
||||
flatSeries,
|
||||
spec.histogramBuckets?.bucketWidth,
|
||||
spec.histogramBuckets?.bucketCount,
|
||||
spec.histogramBuckets?.mergeAllActiveQueries,
|
||||
],
|
||||
);
|
||||
|
||||
const legendPosition = useMemo(
|
||||
() => resolveLegendPosition(spec.legend?.position),
|
||||
[spec.legend?.position],
|
||||
);
|
||||
|
||||
const renderTooltipFooter = useCallback(
|
||||
({ isPinned, dismiss }: IRenderTooltipFooterArgs) => (
|
||||
<TooltipFooter
|
||||
id={panelId}
|
||||
isPinned={isPinned}
|
||||
dismiss={dismiss}
|
||||
canDrilldown={false}
|
||||
/>
|
||||
),
|
||||
[panelId],
|
||||
);
|
||||
|
||||
const isQueriesMerged = spec.histogramBuckets?.mergeAllActiveQueries ?? false;
|
||||
|
||||
const handleChartClick = useCallback(
|
||||
(args: ChartClickData) => {
|
||||
onClick?.(args);
|
||||
},
|
||||
[onClick],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={graphRef}
|
||||
data-testid="histogram-panel-renderer"
|
||||
className={PanelStyles.panelContainer}
|
||||
>
|
||||
{containerDimensions.width > 0 && containerDimensions.height > 0 && (
|
||||
<Histogram
|
||||
key={panelId}
|
||||
config={config}
|
||||
data={chartData as uPlot.AlignedData}
|
||||
legendConfig={{ position: legendPosition }}
|
||||
canPinTooltip
|
||||
isQueriesMerged={isQueriesMerged}
|
||||
width={containerDimensions.width}
|
||||
height={containerDimensions.height}
|
||||
renderTooltipFooter={renderTooltipFooter}
|
||||
onClick={handleChartClick}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default HistogramPanelRenderer;
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { DashboardtypesHistogramPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { Timezone } from 'components/CustomTimePicker/timezoneUtils';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';
|
||||
import { buildBaseConfig } from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/baseConfigBuilder';
|
||||
import { resolveSeriesLabelV5 } from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/resolveSeriesLabel';
|
||||
import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
import getLabelName from 'lib/getLabelName';
|
||||
import { DrawStyle } from 'lib/uPlotV2/config/types';
|
||||
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
|
||||
import type { BuilderQuery } from 'types/api/v5/queryRange';
|
||||
|
||||
const POINT_SIZE = 5;
|
||||
const BAR_WIDTH_FACTOR = 1;
|
||||
// Merged-series colors mirror the V1 default — single histogram bin gets a
|
||||
// fixed blue-ish pair so the merged view looks the same as before.
|
||||
const MERGED_SERIES_LINE_COLOR = '#3f5ecc';
|
||||
const MERGED_SERIES_FILL_COLOR = '#4E74F8';
|
||||
|
||||
export interface BuildHistogramConfigArgs {
|
||||
panelId: string;
|
||||
spec: DashboardtypesHistogramPanelSpecDTO;
|
||||
/** Builder queries on this panel — used to resolve per-series labels. */
|
||||
builderQueries: BuilderQuery[];
|
||||
/** Flattened V5 series (see `flattenTimeSeries`). */
|
||||
series: PanelSeries[];
|
||||
isDarkMode: boolean;
|
||||
timezone: Timezone;
|
||||
panelMode: PanelMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a fully-wired `UPlotConfigBuilder` for a Histogram panel.
|
||||
*
|
||||
* Unlike time-axis panels, histograms have no time scale and no drag-to-zoom.
|
||||
* We still reuse `buildBaseConfig` for the consistent scaffolding (thresholds,
|
||||
* axes, click plugin) but then override the X/Y scales to be auto-linear
|
||||
* (`time: false, auto: true`) and install a histogram-specific cursor that
|
||||
* disables drag-pan and tightens focus proximity.
|
||||
*/
|
||||
export function buildHistogramConfig({
|
||||
panelId,
|
||||
spec,
|
||||
builderQueries,
|
||||
series,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
}: BuildHistogramConfigArgs): UPlotConfigBuilder {
|
||||
// Histograms have no time axis — no stepIntervals, and no click plugin
|
||||
// (the renderer passes no onClick), so the base config needs no response.
|
||||
const builder = buildBaseConfig({
|
||||
panelId,
|
||||
panelType: PANEL_TYPES.HISTOGRAM,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
});
|
||||
|
||||
builder.setCursor({
|
||||
drag: { x: false, y: false, setScale: true },
|
||||
focus: { prox: 1e3 },
|
||||
});
|
||||
|
||||
// Override the time-axis scales from `buildBaseConfig` — histograms are
|
||||
// distribution plots, not time series.
|
||||
builder.addScale({ scaleKey: 'x', time: false, auto: true });
|
||||
builder.addScale({ scaleKey: 'y', time: false, auto: true, min: 0 });
|
||||
|
||||
addSeries({ builder, spec, builderQueries, series, isDarkMode });
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
interface AddSeriesArgs {
|
||||
builder: UPlotConfigBuilder;
|
||||
spec: DashboardtypesHistogramPanelSpecDTO;
|
||||
builderQueries: BuilderQuery[];
|
||||
series: PanelSeries[];
|
||||
isDarkMode: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds histogram bar series to the builder. When `mergeAllActiveQueries` is
|
||||
* set, `prepareHistogramData` produces a single Y column, so we add exactly
|
||||
* one series with the fixed merged-mode colors. Otherwise one series per
|
||||
* result row, with labels resolved via the standard legend matrix.
|
||||
*/
|
||||
function addSeries({
|
||||
builder,
|
||||
spec,
|
||||
builderQueries,
|
||||
series,
|
||||
isDarkMode,
|
||||
}: AddSeriesArgs): void {
|
||||
const colorMapping = spec.legend?.customColors ?? {};
|
||||
const mergeAllActiveQueries =
|
||||
spec.histogramBuckets?.mergeAllActiveQueries ?? false;
|
||||
|
||||
if (mergeAllActiveQueries) {
|
||||
builder.addSeries({
|
||||
scaleKey: 'y',
|
||||
label: '',
|
||||
drawStyle: DrawStyle.Histogram,
|
||||
colorMapping,
|
||||
barWidthFactor: BAR_WIDTH_FACTOR,
|
||||
pointSize: POINT_SIZE,
|
||||
lineColor: MERGED_SERIES_LINE_COLOR,
|
||||
fillColor: MERGED_SERIES_FILL_COLOR,
|
||||
isDarkMode,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
series.forEach((s) => {
|
||||
const baseLabel = getLabelName(s.labels, s.queryName, s.legend);
|
||||
const label = resolveSeriesLabelV5(s, builderQueries, baseLabel);
|
||||
|
||||
builder.addSeries({
|
||||
scaleKey: 'y',
|
||||
label,
|
||||
drawStyle: DrawStyle.Histogram,
|
||||
colorMapping,
|
||||
barWidthFactor: BAR_WIDTH_FACTOR,
|
||||
pointSize: POINT_SIZE,
|
||||
isDarkMode,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { PanelDefinition } from '../../types/panelDefinition';
|
||||
import Renderer from './Renderer';
|
||||
import { sections } from './sections';
|
||||
|
||||
export const definition: PanelDefinition<'signoz/HistogramPanel'> = {
|
||||
kind: 'signoz/HistogramPanel',
|
||||
displayName: 'Histogram',
|
||||
Renderer,
|
||||
sections,
|
||||
supportedSignals: [DataSource.METRICS, DataSource.LOGS, DataSource.TRACES],
|
||||
actions: { view: true, edit: true, download: false, createAlert: true },
|
||||
};
|
||||
@@ -0,0 +1,148 @@
|
||||
import { histogramBucketSizes } from '@grafana/data';
|
||||
import { DEFAULT_BUCKET_COUNT } from 'container/PanelWrapper/constants';
|
||||
import {
|
||||
buildHistogramBuckets,
|
||||
mergeAlignedDataTables,
|
||||
prependNullBinToFirstHistogramSeries,
|
||||
replaceUndefinedWithNullInAlignedData,
|
||||
} from 'container/DashboardContainer/visualization/panels/utils/histogram';
|
||||
import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
import { AlignedData } from 'uplot';
|
||||
import { incrRoundDn, roundDecimals } from 'utils/round';
|
||||
|
||||
export interface PrepareHistogramDataArgs {
|
||||
/** Flattened V5 series (see `flattenTimeSeries`). */
|
||||
series: PanelSeries[];
|
||||
bucketWidth?: number;
|
||||
bucketCount?: number;
|
||||
mergeAllActiveQueries?: boolean;
|
||||
}
|
||||
|
||||
const BUCKET_OFFSET = 0;
|
||||
const sortAscending = (a: number, b: number): number => a - b;
|
||||
|
||||
/**
|
||||
* Bins raw series values into a uPlot-aligned histogram. Picks a bucket size
|
||||
* either from `bucketWidth` (explicit override) or the smallest predefined
|
||||
* Grafana bucket that fits the data's `range / bucketCount` target while
|
||||
* staying ≥ the data's smallest non-zero delta (so we never sub-divide below
|
||||
* the resolution of the input).
|
||||
*
|
||||
* Empty input → `[[]]` (a valid empty AlignedData uPlot accepts).
|
||||
*/
|
||||
export function prepareHistogramData({
|
||||
series,
|
||||
bucketWidth,
|
||||
bucketCount = DEFAULT_BUCKET_COUNT,
|
||||
mergeAllActiveQueries = false,
|
||||
}: PrepareHistogramDataArgs): AlignedData {
|
||||
const values = extractNumericValues(series);
|
||||
if (values.length === 0) {
|
||||
return [[]];
|
||||
}
|
||||
|
||||
const sorted = [...values].sort(sortAscending);
|
||||
const range = sorted[sorted.length - 1] - sorted[0];
|
||||
const smallestDelta = computeSmallestDelta(sorted);
|
||||
let bucketSize = selectBucketSize({
|
||||
range,
|
||||
bucketCount,
|
||||
smallestDelta,
|
||||
bucketWidthOverride: bucketWidth,
|
||||
});
|
||||
if (bucketSize <= 0) {
|
||||
bucketSize = range > 0 ? range / bucketCount : 1;
|
||||
}
|
||||
|
||||
const getBucket = (v: number): number =>
|
||||
roundDecimals(incrRoundDn(v - BUCKET_OFFSET, bucketSize) + BUCKET_OFFSET, 9);
|
||||
|
||||
const frames = buildFrames(series, mergeAllActiveQueries);
|
||||
// Merged mode folds every query into frame 0 and leaves trailing empty
|
||||
// frames — drop those. Per-query mode must keep one column per result row
|
||||
// (even empty queries), or the data column count drifts below the series
|
||||
// count `buildHistogramConfig` adds per row → uPlot renders nothing.
|
||||
const histograms: AlignedData[] = frames
|
||||
.filter((frame) => !mergeAllActiveQueries || frame.length > 0)
|
||||
.map((frame) => buildHistogramBuckets(frame, getBucket, sortAscending));
|
||||
|
||||
if (histograms.length === 0) {
|
||||
return [[]];
|
||||
}
|
||||
|
||||
const merged = mergeAlignedDataTables(histograms);
|
||||
replaceUndefinedWithNullInAlignedData(merged);
|
||||
prependNullBinToFirstHistogramSeries(merged, bucketSize);
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Non-finite samples degrade to 0 (legacy `parseFloat(...) || 0` parity).
|
||||
function toBinnableValue(value: number): number {
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
function extractNumericValues(series: PanelSeries[]): number[] {
|
||||
const values: number[] = [];
|
||||
for (const s of series) {
|
||||
for (const point of s.values) {
|
||||
values.push(toBinnableValue(point.value));
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function computeSmallestDelta(sortedValues: number[]): number {
|
||||
if (sortedValues.length <= 1) {
|
||||
return 0;
|
||||
}
|
||||
let smallest = Infinity;
|
||||
for (let i = 1; i < sortedValues.length; i++) {
|
||||
const delta = sortedValues[i] - sortedValues[i - 1];
|
||||
if (delta > 0) {
|
||||
smallest = Math.min(smallest, delta);
|
||||
}
|
||||
}
|
||||
return smallest === Infinity ? 0 : smallest;
|
||||
}
|
||||
|
||||
function selectBucketSize({
|
||||
range,
|
||||
bucketCount,
|
||||
smallestDelta,
|
||||
bucketWidthOverride,
|
||||
}: {
|
||||
range: number;
|
||||
bucketCount: number;
|
||||
smallestDelta: number;
|
||||
bucketWidthOverride?: number;
|
||||
}): number {
|
||||
if (bucketWidthOverride != null && bucketWidthOverride > 0) {
|
||||
return bucketWidthOverride;
|
||||
}
|
||||
const targetSize = range / bucketCount;
|
||||
for (const candidate of histogramBucketSizes) {
|
||||
if (targetSize < candidate && candidate >= smallestDelta) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// When merging is on, fold all frames into the first; the trailing empty
|
||||
// frames stay in the array so downstream `.filter(length > 0)` drops them.
|
||||
function buildFrames(
|
||||
series: PanelSeries[],
|
||||
mergeAllActiveQueries: boolean,
|
||||
): number[][] {
|
||||
const frames: number[][] = series.map((s) =>
|
||||
s.values.map((point) => toBinnableValue(point.value)),
|
||||
);
|
||||
if (mergeAllActiveQueries && frames.length > 1) {
|
||||
const first = frames[0];
|
||||
for (let i = 1; i < frames.length; i++) {
|
||||
first.push(...frames[i]);
|
||||
frames[i] = [];
|
||||
}
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { SectionConfig } from '../../types/sections';
|
||||
|
||||
export const sections: SectionConfig[] = [
|
||||
{ kind: 'legend', controls: { position: true, mode: true } },
|
||||
{ kind: 'buckets', controls: { count: true } },
|
||||
];
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import type { DashboardtypesNumberPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { prepareScalarTables } from 'pages/DashboardPageV2/DashboardContainer/queryV5/prepareScalarTables';
|
||||
import { getScalarResults } from 'pages/DashboardPageV2/DashboardContainer/queryV5/v5ResponseData';
|
||||
|
||||
import PanelStyles from '../../panel.module.scss';
|
||||
import { PanelRendererProps } from '../../types/rendererProps';
|
||||
import { formatPanelValue } from '../../utils/formatPanelValue';
|
||||
import { resolveDecimalPrecision } from '../../utils/chartAppearanceMappings';
|
||||
|
||||
import { prepareNumberData } from './prepareData';
|
||||
import { mapNumberThresholds } from './utils';
|
||||
import ValueDisplay from './components/ValueDisplay/ValueDisplay';
|
||||
|
||||
function NumberPanelRenderer({
|
||||
panel,
|
||||
data,
|
||||
}: PanelRendererProps<'signoz/NumberPanel'>): JSX.Element {
|
||||
// The registry guarantees this Renderer only runs when
|
||||
// `panel.spec.plugin.kind === 'signoz/NumberPanel'`, so the cast is a
|
||||
// documented boundary narrowing. Memoized so the `?? {}` fallback doesn't
|
||||
// produce a fresh object on each render.
|
||||
const spec = useMemo<DashboardtypesNumberPanelSpecDTO>(
|
||||
() => (panel?.spec?.plugin?.spec ?? {}) as DashboardtypesNumberPanelSpecDTO,
|
||||
[panel?.spec?.plugin?.spec],
|
||||
);
|
||||
|
||||
const value = useMemo(
|
||||
() =>
|
||||
prepareNumberData(
|
||||
prepareScalarTables({
|
||||
results: getScalarResults(data?.response),
|
||||
legendMap: data?.legendMap ?? {},
|
||||
requestPayload: data?.requestPayload,
|
||||
}),
|
||||
),
|
||||
[data?.response, data?.legendMap, data?.requestPayload],
|
||||
);
|
||||
|
||||
const thresholds = useMemo(
|
||||
() => mapNumberThresholds(spec.thresholds),
|
||||
[spec.thresholds],
|
||||
);
|
||||
|
||||
const decimalPrecision = useMemo(
|
||||
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
|
||||
[spec.formatting?.decimalPrecision],
|
||||
);
|
||||
|
||||
const unit = spec.formatting?.unit;
|
||||
|
||||
// Precision is applied regardless of whether a unit is set (see
|
||||
// `formatPanelValue`), so decimal-precision changes always take effect.
|
||||
const formattedValue = useMemo(
|
||||
() => (value === null ? '' : formatPanelValue(value, unit, decimalPrecision)),
|
||||
[value, unit, decimalPrecision],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="number-panel-renderer"
|
||||
className={PanelStyles.panelContainer}
|
||||
>
|
||||
{value === null ? (
|
||||
<Typography.Text data-testid="number-panel-no-data">
|
||||
No Data
|
||||
</Typography.Text>
|
||||
) : (
|
||||
<ValueDisplay
|
||||
value={formattedValue}
|
||||
rawValue={value}
|
||||
thresholds={thresholds}
|
||||
unit={unit}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default NumberPanelRenderer;
|
||||
@@ -0,0 +1,155 @@
|
||||
import {
|
||||
DashboardtypesComparisonOperatorDTO,
|
||||
type DashboardtypesNumberPanelSpecDTO,
|
||||
type DashboardtypesPanelDTO,
|
||||
DashboardtypesThresholdFormatDTO,
|
||||
type QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';
|
||||
import type { PanelQueryData } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
import { render } from 'tests/test-utils';
|
||||
|
||||
import { BaseRendererProps } from '../../../types/rendererProps';
|
||||
import BaseNumberPanelRenderer from '../Renderer';
|
||||
|
||||
// The kind's interaction map is `Record<string, never>`, which makes the strict
|
||||
// `PanelRendererProps<'signoz/NumberPanel'>` intersection impossible to satisfy
|
||||
// with a literal. NumberPanel reads no interaction props, so render it against
|
||||
// the base prop surface.
|
||||
const NumberPanelRenderer =
|
||||
BaseNumberPanelRenderer as React.FC<BaseRendererProps>;
|
||||
|
||||
// ValueDisplay observes its container to size the font.
|
||||
window.ResizeObserver =
|
||||
window.ResizeObserver ||
|
||||
jest.fn().mockImplementation(() => ({
|
||||
disconnect: jest.fn(),
|
||||
observe: jest.fn(),
|
||||
unobserve: jest.fn(),
|
||||
}));
|
||||
|
||||
function panelWith(
|
||||
spec: DashboardtypesNumberPanelSpecDTO,
|
||||
): DashboardtypesPanelDTO {
|
||||
return {
|
||||
kind: 'Panel',
|
||||
spec: { plugin: { kind: 'signoz/NumberPanel', spec } },
|
||||
} as unknown as DashboardtypesPanelDTO;
|
||||
}
|
||||
|
||||
// V5 scalar response: one table per query, value in the aggregation column.
|
||||
function dataWith(value: string | number): PanelQueryData {
|
||||
return {
|
||||
response: {
|
||||
status: 'success',
|
||||
data: {
|
||||
type: 'scalar',
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
queryName: 'A',
|
||||
columns: [
|
||||
{
|
||||
name: '__result',
|
||||
queryName: 'A',
|
||||
columnType: 'aggregation',
|
||||
aggregationIndex: 0,
|
||||
},
|
||||
],
|
||||
data: [[value]],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
} as unknown as QueryRangeV5200,
|
||||
requestPayload: undefined,
|
||||
legendMap: {},
|
||||
};
|
||||
}
|
||||
|
||||
const emptyData: PanelQueryData = {
|
||||
response: {
|
||||
status: 'success',
|
||||
data: { type: 'scalar', data: { results: [] } },
|
||||
} as unknown as QueryRangeV5200,
|
||||
requestPayload: undefined,
|
||||
legendMap: {},
|
||||
};
|
||||
|
||||
// NumberPanel adds no interaction props (its interaction map is
|
||||
// `Record<string, never>`), so the base renderer props fully describe it.
|
||||
function renderPanel(
|
||||
props: Partial<BaseRendererProps>,
|
||||
): ReturnType<typeof render> {
|
||||
const baseProps: BaseRendererProps = {
|
||||
panelId: 'panel-1',
|
||||
panel: panelWith({}),
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
panelMode: PanelMode.DASHBOARD_VIEW,
|
||||
...props,
|
||||
};
|
||||
return render(<NumberPanelRenderer {...baseProps} />);
|
||||
}
|
||||
|
||||
describe('NumberPanelRenderer', () => {
|
||||
it('renders the value with its y-axis unit', () => {
|
||||
const { getByText } = renderPanel({
|
||||
panel: panelWith({ formatting: { unit: 'ms' } }),
|
||||
data: dataWith('295.4299833508185'),
|
||||
});
|
||||
|
||||
expect(getByText('295.43')).toBeInTheDocument();
|
||||
expect(getByText('ms')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Regression: with no unit configured, decimal precision must still apply.
|
||||
// Previously the renderer fell back to `value.toString()` whenever the unit
|
||||
// was empty, so precision changes had no effect on unitless panels.
|
||||
it('applies decimal precision even when no unit is set', () => {
|
||||
const { getByText, queryByText } = renderPanel({
|
||||
panel: panelWith({}),
|
||||
data: dataWith('3.14159'),
|
||||
});
|
||||
|
||||
expect(getByText('3.14')).toBeInTheDocument();
|
||||
expect(queryByText('3.14159')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders No Data when the response has no scalar results', () => {
|
||||
const { getByTestId } = renderPanel({ data: emptyData });
|
||||
|
||||
expect(getByTestId('number-panel-no-data')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders No Data when the response is absent', () => {
|
||||
const { getByTestId } = renderPanel({ data: undefined });
|
||||
|
||||
expect(getByTestId('number-panel-no-data')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('surfaces the conflicting-thresholds indicator when a value matches multiple thresholds', () => {
|
||||
const { getByTestId } = renderPanel({
|
||||
panel: panelWith({
|
||||
thresholds: [
|
||||
{
|
||||
color: '#f00',
|
||||
operator: DashboardtypesComparisonOperatorDTO.above,
|
||||
value: 0,
|
||||
format: DashboardtypesThresholdFormatDTO.background,
|
||||
},
|
||||
{
|
||||
color: '#0f0',
|
||||
operator: DashboardtypesComparisonOperatorDTO.above,
|
||||
value: 100,
|
||||
format: DashboardtypesThresholdFormatDTO.background,
|
||||
},
|
||||
],
|
||||
}),
|
||||
data: dataWith('295.4299833508185'),
|
||||
});
|
||||
|
||||
expect(getByTestId('conflicting-thresholds')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { PanelTable } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
|
||||
import { prepareNumberData } from '../prepareData';
|
||||
|
||||
function tableWith(
|
||||
columns: PanelTable['columns'],
|
||||
rows: PanelTable['rows'],
|
||||
): PanelTable {
|
||||
return { queryName: 'A', legend: '', columns, rows };
|
||||
}
|
||||
|
||||
describe('prepareNumberData', () => {
|
||||
it('returns null for no tables', () => {
|
||||
expect(prepareNumberData([])).toBeNull();
|
||||
});
|
||||
|
||||
it('reads the first row of the value column', () => {
|
||||
const table = tableWith(
|
||||
[
|
||||
{ name: 'group', queryName: 'A', isValueColumn: false, id: 'group' },
|
||||
{ name: 'value', queryName: 'A', isValueColumn: true, id: 'val' },
|
||||
],
|
||||
[
|
||||
{ data: { group: 'prod', val: '295.4299833508185' } },
|
||||
{ data: { group: 'dev', val: '7' } },
|
||||
],
|
||||
);
|
||||
|
||||
expect(prepareNumberData([table])).toBeCloseTo(295.43, 2);
|
||||
});
|
||||
|
||||
it('falls back to the row first value when no column is tagged isValueColumn', () => {
|
||||
const table = tableWith(
|
||||
[{ name: 'value', queryName: 'A', isValueColumn: false, id: 'value' }],
|
||||
[{ data: { value: '7' } }],
|
||||
);
|
||||
|
||||
expect(prepareNumberData([table])).toBe(7);
|
||||
});
|
||||
|
||||
it('skips empty tables and reads the first one with rows', () => {
|
||||
const empty = tableWith(
|
||||
[{ name: 'value', queryName: 'A', isValueColumn: true, id: 'A' }],
|
||||
[],
|
||||
);
|
||||
const filled = tableWith(
|
||||
[{ name: 'value', queryName: 'B', isValueColumn: true, id: 'B' }],
|
||||
[{ data: { B: 42 } }],
|
||||
);
|
||||
|
||||
expect(prepareNumberData([empty, filled])).toBe(42);
|
||||
});
|
||||
|
||||
it('returns null when the value is non-numeric', () => {
|
||||
const table = tableWith(
|
||||
[{ name: 'value', queryName: 'A', isValueColumn: true, id: 'A' }],
|
||||
[{ data: { A: 'n/a' } }],
|
||||
);
|
||||
|
||||
expect(prepareNumberData([table])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import {
|
||||
DashboardtypesComparisonOperatorDTO,
|
||||
DashboardtypesComparisonThresholdDTO,
|
||||
DashboardtypesThresholdFormatDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { mapNumberThresholds } from '../utils';
|
||||
|
||||
describe('mapNumberThresholds', () => {
|
||||
it('returns [] for null / undefined / empty', () => {
|
||||
expect(mapNumberThresholds(null)).toStrictEqual([]);
|
||||
expect(mapNumberThresholds(undefined)).toStrictEqual([]);
|
||||
expect(mapNumberThresholds([])).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('maps comparison operators to symbol operators', () => {
|
||||
const thresholds: DashboardtypesComparisonThresholdDTO[] = [
|
||||
{
|
||||
color: '#f00',
|
||||
operator: DashboardtypesComparisonOperatorDTO.above,
|
||||
value: 1,
|
||||
},
|
||||
{
|
||||
color: '#0f0',
|
||||
operator: DashboardtypesComparisonOperatorDTO.below,
|
||||
value: 2,
|
||||
},
|
||||
{
|
||||
color: '#00f',
|
||||
operator: DashboardtypesComparisonOperatorDTO.above_or_equal,
|
||||
value: 3,
|
||||
},
|
||||
{
|
||||
color: '#ff0',
|
||||
operator: DashboardtypesComparisonOperatorDTO.below_or_equal,
|
||||
value: 4,
|
||||
},
|
||||
{
|
||||
color: '#0ff',
|
||||
operator: DashboardtypesComparisonOperatorDTO.equal,
|
||||
value: 5,
|
||||
},
|
||||
];
|
||||
|
||||
const mapped = mapNumberThresholds(thresholds);
|
||||
|
||||
expect(mapped.map((t) => t.operator)).toStrictEqual([
|
||||
'>',
|
||||
'<',
|
||||
'>=',
|
||||
'<=',
|
||||
'=',
|
||||
]);
|
||||
});
|
||||
|
||||
it('maps not_equal to !=', () => {
|
||||
const mapped = mapNumberThresholds([
|
||||
{
|
||||
color: '#f00',
|
||||
operator: DashboardtypesComparisonOperatorDTO.not_equal,
|
||||
value: 1,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(mapped[0].operator).toBe('!=');
|
||||
});
|
||||
|
||||
it('maps format and carries value/unit/color', () => {
|
||||
const mapped = mapNumberThresholds([
|
||||
{
|
||||
color: '#abcdef',
|
||||
operator: DashboardtypesComparisonOperatorDTO.above,
|
||||
value: 100,
|
||||
unit: 'ms',
|
||||
format: DashboardtypesThresholdFormatDTO.background,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(mapped[0]).toStrictEqual({
|
||||
color: '#abcdef',
|
||||
operator: '>',
|
||||
value: 100,
|
||||
unit: 'ms',
|
||||
format: 'background',
|
||||
});
|
||||
});
|
||||
|
||||
it('maps text format to text', () => {
|
||||
const mapped = mapNumberThresholds([
|
||||
{
|
||||
color: '#000',
|
||||
value: 1,
|
||||
format: DashboardtypesThresholdFormatDTO.text,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(mapped[0].format).toBe('text');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
.container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.textContainer {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: baseline;
|
||||
justify-content: center;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.valueText {
|
||||
text-align: center;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.conflictBackground {
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
bottom: 10px;
|
||||
}
|
||||
|
||||
.conflictText {
|
||||
margin-left: 10px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.conflictIcon {
|
||||
color: var(--warning-background);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Tooltip } from 'antd';
|
||||
import { CircleAlert } from '@signozhq/icons';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import type { PanelThreshold } from '../../../../types/threshold';
|
||||
import { resolveActiveThreshold } from '../../../../utils/evaluateThresholds';
|
||||
|
||||
import { parseFormattedValue } from '../../../../utils/parseFormattedValue';
|
||||
import styles from './ValueDisplay.module.scss';
|
||||
import { useResponsiveFontSize } from '../../../../hooks/useResponsiveFontSize';
|
||||
import ValueUnit from '../ValueUnit/ValueUnit';
|
||||
|
||||
interface ValueDisplayProps {
|
||||
/** The pre-formatted value string (may include a unit label). */
|
||||
value: string;
|
||||
/** The raw numeric value, used for threshold evaluation. */
|
||||
rawValue: number;
|
||||
thresholds: PanelThreshold[];
|
||||
/** The panel's unit, used to convert threshold units before comparison. */
|
||||
unit?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a single large scalar with optional prefix/suffix units and threshold
|
||||
* recoloring (text or background). A V2-native replacement for the V1
|
||||
* `ValueGraph` — depends only on V2 threshold utilities and the shared icon/
|
||||
* typography primitives.
|
||||
*/
|
||||
function ValueDisplay({
|
||||
value,
|
||||
rawValue,
|
||||
thresholds,
|
||||
unit,
|
||||
}: ValueDisplayProps): JSX.Element {
|
||||
const { t } = useTranslation(['valueGraph']);
|
||||
const { containerRef, fontSize } = useResponsiveFontSize();
|
||||
|
||||
const { numericValue, prefixUnit, suffixUnit } = useMemo(
|
||||
() => parseFormattedValue(value),
|
||||
[value],
|
||||
);
|
||||
|
||||
const { threshold, isConflicting } = useMemo(
|
||||
() => resolveActiveThreshold(thresholds, rawValue, unit),
|
||||
[thresholds, rawValue, unit],
|
||||
);
|
||||
|
||||
const isBackground = threshold?.format === 'background';
|
||||
const textColor = threshold?.format === 'text' ? threshold.color : undefined;
|
||||
const backgroundColor = isBackground ? threshold?.color : undefined;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={styles.container}
|
||||
style={{ backgroundColor }}
|
||||
>
|
||||
<div className={styles.textContainer}>
|
||||
{prefixUnit && (
|
||||
<ValueUnit
|
||||
type="prefix"
|
||||
unit={prefixUnit}
|
||||
color={textColor}
|
||||
fontSize={fontSize}
|
||||
/>
|
||||
)}
|
||||
<Typography.Text
|
||||
className={styles.valueText}
|
||||
data-testid="number-panel-value"
|
||||
style={{ color: textColor, fontSize }}
|
||||
>
|
||||
{numericValue}
|
||||
</Typography.Text>
|
||||
{suffixUnit && (
|
||||
<ValueUnit
|
||||
type="suffix"
|
||||
unit={suffixUnit}
|
||||
color={textColor}
|
||||
fontSize={fontSize}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{isConflicting && (
|
||||
<div
|
||||
className={isBackground ? styles.conflictBackground : styles.conflictText}
|
||||
>
|
||||
<Tooltip title={t('this_value_satisfies_multiple_thresholds')}>
|
||||
<CircleAlert
|
||||
className={styles.conflictIcon}
|
||||
data-testid="conflicting-thresholds"
|
||||
size="md"
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ValueDisplay;
|
||||
@@ -0,0 +1,5 @@
|
||||
.unit {
|
||||
margin-left: 4px;
|
||||
font-weight: 300;
|
||||
opacity: 0.8;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './ValueUnit.module.scss';
|
||||
|
||||
interface ValueUnitProps {
|
||||
type: 'prefix' | 'suffix';
|
||||
unit: string;
|
||||
/** Text color, set only when a "text" threshold is active. */
|
||||
color?: string;
|
||||
fontSize: string;
|
||||
}
|
||||
|
||||
/** A prefix/suffix unit label rendered alongside the numeric value. */
|
||||
function ValueUnit({
|
||||
type,
|
||||
unit,
|
||||
color,
|
||||
fontSize,
|
||||
}: ValueUnitProps): JSX.Element {
|
||||
return (
|
||||
<Typography.Text
|
||||
className={styles.unit}
|
||||
data-testid={`value-display-${type}-unit`}
|
||||
style={{ color, fontSize: `calc(${fontSize} * 0.7)` }}
|
||||
>
|
||||
{unit}
|
||||
</Typography.Text>
|
||||
);
|
||||
}
|
||||
|
||||
export default ValueUnit;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { PanelDefinition } from '../../types/panelDefinition';
|
||||
import Renderer from './Renderer';
|
||||
import { sections } from './sections';
|
||||
|
||||
export const definition: PanelDefinition<'signoz/NumberPanel'> = {
|
||||
kind: 'signoz/NumberPanel',
|
||||
displayName: 'Number',
|
||||
Renderer,
|
||||
sections,
|
||||
supportedSignals: [DataSource.METRICS, DataSource.LOGS, DataSource.TRACES],
|
||||
actions: { view: true, edit: true, download: false, createAlert: true },
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { PanelTable } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
|
||||
/**
|
||||
* Reduces the scalar tables of a V5 response to the single number a
|
||||
* NumberPanel renders.
|
||||
*
|
||||
* V2 always issues `requestType: 'scalar'` for VALUE panels, so the response
|
||||
* is a scalar table per query (see `prepareScalarTables`). The value is the
|
||||
* first row's `isValueColumn` cell of the first table that has rows —
|
||||
* falling back to the row's first cell when no column is marked as the
|
||||
* value (mirrors the V1 `formatForWeb` fallback read).
|
||||
*
|
||||
* Returns `null` when there is no numeric value to show, which the renderer
|
||||
* maps to the "No Data" state.
|
||||
*/
|
||||
export function prepareNumberData(tables: PanelTable[]): number | null {
|
||||
for (const table of tables) {
|
||||
if (table.rows.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const row = table.rows[0].data;
|
||||
const valueColumn = table.columns.find((column) => column.isValueColumn);
|
||||
const raw = valueColumn
|
||||
? row[valueColumn.id || valueColumn.name]
|
||||
: Object.values(row)[0];
|
||||
const value = Number(raw);
|
||||
if (Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { SectionConfig } from '../../types/sections';
|
||||
|
||||
// A number panel renders one scalar — no axes, legend, or stacking. Just value
|
||||
// formatting and thresholds that recolor the value/background.
|
||||
export const sections: SectionConfig[] = [
|
||||
{ kind: 'formatting', controls: { unit: true, decimals: true } },
|
||||
{ kind: 'thresholds', controls: { list: true } },
|
||||
];
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
DashboardtypesComparisonOperatorDTO,
|
||||
DashboardtypesComparisonThresholdDTO,
|
||||
DashboardtypesThresholdFormatDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import type {
|
||||
PanelThreshold,
|
||||
ThresholdComparisonOperator,
|
||||
ThresholdDisplayFormat,
|
||||
} from '../../types/threshold';
|
||||
|
||||
// Perses comparison operators → the symbol operators V2 threshold evaluation
|
||||
// uses.
|
||||
const OPERATOR_MAP: Record<
|
||||
DashboardtypesComparisonOperatorDTO,
|
||||
ThresholdComparisonOperator
|
||||
> = {
|
||||
[DashboardtypesComparisonOperatorDTO.above]: '>',
|
||||
[DashboardtypesComparisonOperatorDTO.below]: '<',
|
||||
[DashboardtypesComparisonOperatorDTO.above_or_equal]: '>=',
|
||||
[DashboardtypesComparisonOperatorDTO.below_or_equal]: '<=',
|
||||
[DashboardtypesComparisonOperatorDTO.equal]: '=',
|
||||
[DashboardtypesComparisonOperatorDTO.not_equal]: '!=',
|
||||
};
|
||||
|
||||
const FORMAT_MAP: Record<
|
||||
DashboardtypesThresholdFormatDTO,
|
||||
ThresholdDisplayFormat
|
||||
> = {
|
||||
[DashboardtypesThresholdFormatDTO.text]: 'text',
|
||||
[DashboardtypesThresholdFormatDTO.background]: 'background',
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps the panel-spec threshold shape (`ComparisonThresholdDTO`) onto the
|
||||
* V2-native `PanelThreshold` consumed by `ValueDisplay` / threshold
|
||||
* evaluation. No dependency on the V1 `ThresholdProps` shape.
|
||||
*/
|
||||
export function mapNumberThresholds(
|
||||
thresholds: DashboardtypesComparisonThresholdDTO[] | null | undefined,
|
||||
): PanelThreshold[] {
|
||||
if (!thresholds || thresholds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return thresholds.map((threshold) => ({
|
||||
color: threshold.color,
|
||||
operator: threshold.operator ? OPERATOR_MAP[threshold.operator] : undefined,
|
||||
value: threshold.value,
|
||||
unit: threshold.unit,
|
||||
format: threshold.format ? FORMAT_MAP[threshold.format] : undefined,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import type { DashboardtypesPieChartPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import Pie from 'container/DashboardContainer/visualization/charts/Pie/Pie';
|
||||
import type { PieSlice } from 'container/DashboardContainer/visualization/charts/types';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { prepareScalarTables } from 'pages/DashboardPageV2/DashboardContainer/queryV5/prepareScalarTables';
|
||||
import { getScalarResults } from 'pages/DashboardPageV2/DashboardContainer/queryV5/v5ResponseData';
|
||||
|
||||
import PanelStyles from '../../panel.module.scss';
|
||||
import { PanelRendererProps } from '../../types/rendererProps';
|
||||
import {
|
||||
resolveDecimalPrecision,
|
||||
resolveLegendPosition,
|
||||
} from '../../utils/chartAppearanceMappings';
|
||||
|
||||
import { preparePieData } from './prepareData';
|
||||
|
||||
function PiePanelRenderer({
|
||||
panelId,
|
||||
panel,
|
||||
data,
|
||||
onClick,
|
||||
}: PanelRendererProps<'signoz/PieChartPanel'>): JSX.Element {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
// The registry guarantees this Renderer only runs when
|
||||
// `panel.spec.plugin.kind === 'signoz/PieChartPanel'`, so the cast is a
|
||||
// documented boundary narrowing. Memoized so the `?? {}` fallback doesn't
|
||||
// produce a fresh object on each render.
|
||||
const spec = useMemo<DashboardtypesPieChartPanelSpecDTO>(
|
||||
() => (panel?.spec?.plugin?.spec ?? {}) as DashboardtypesPieChartPanelSpecDTO,
|
||||
[panel?.spec?.plugin?.spec],
|
||||
);
|
||||
|
||||
const slices = useMemo(
|
||||
() =>
|
||||
preparePieData({
|
||||
tables: prepareScalarTables({
|
||||
results: getScalarResults(data?.response),
|
||||
legendMap: data?.legendMap ?? {},
|
||||
requestPayload: data?.requestPayload,
|
||||
}),
|
||||
customColors: spec.legend?.customColors,
|
||||
isDarkMode,
|
||||
}),
|
||||
[
|
||||
data?.response,
|
||||
data?.legendMap,
|
||||
data?.requestPayload,
|
||||
spec.legend?.customColors,
|
||||
isDarkMode,
|
||||
],
|
||||
);
|
||||
|
||||
const decimalPrecision = useMemo(
|
||||
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
|
||||
[spec.formatting?.decimalPrecision],
|
||||
);
|
||||
|
||||
const legendPosition = useMemo(
|
||||
() => resolveLegendPosition(spec.legend?.position),
|
||||
[spec.legend?.position],
|
||||
);
|
||||
|
||||
const handleSliceClick = useCallback(
|
||||
(slice: PieSlice) => {
|
||||
onClick?.({ label: slice.label, value: slice.value });
|
||||
},
|
||||
[onClick],
|
||||
);
|
||||
|
||||
return (
|
||||
<div data-testid="pie-panel-renderer" className={PanelStyles.panelContainer}>
|
||||
<Pie
|
||||
data={slices}
|
||||
yAxisUnit={spec.formatting?.unit}
|
||||
decimalPrecision={decimalPrecision}
|
||||
isDarkMode={isDarkMode}
|
||||
position={legendPosition}
|
||||
id={panelId}
|
||||
onSliceClick={handleSliceClick}
|
||||
data-testid="pie-chart"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default PiePanelRenderer;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { PanelDefinition } from '../../types/panelDefinition';
|
||||
import Renderer from './Renderer';
|
||||
import { sections } from './sections';
|
||||
|
||||
export const definition: PanelDefinition<'signoz/PieChartPanel'> = {
|
||||
kind: 'signoz/PieChartPanel',
|
||||
displayName: 'Pie Chart',
|
||||
Renderer,
|
||||
sections,
|
||||
supportedSignals: [DataSource.METRICS, DataSource.LOGS, DataSource.TRACES],
|
||||
actions: { view: true, edit: true, download: false, createAlert: true },
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import { themeColors } from 'constants/theme';
|
||||
import type { PieSlice } from 'container/DashboardContainer/visualization/charts/types';
|
||||
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
|
||||
import type { PanelTable } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
|
||||
export interface PreparePieDataArgs {
|
||||
/** Scalar tables from the V5 response (see `prepareScalarTables`). */
|
||||
tables: PanelTable[];
|
||||
/** Per-label colour overrides from `spec.legend.customColors`. */
|
||||
customColors?: Record<string, string> | null;
|
||||
isDarkMode: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns the scalar tables of a V5 response into pie slices: one slice per
|
||||
* group row. The aggregation column holds the value, the group column(s)
|
||||
* form the label. Colours honour `customColors` then fall back to a
|
||||
* deterministic palette colour; non-positive / non-numeric values are
|
||||
* dropped.
|
||||
*/
|
||||
export function preparePieData({
|
||||
tables,
|
||||
customColors,
|
||||
isDarkMode,
|
||||
}: PreparePieDataArgs): PieSlice[] {
|
||||
const colorMap = isDarkMode
|
||||
? themeColors.chartcolors
|
||||
: themeColors.lightModeColor;
|
||||
|
||||
const slices: PieSlice[] = [];
|
||||
tables.forEach((table) => {
|
||||
const valueColumn = table.columns.find((column) => column.isValueColumn);
|
||||
if (!valueColumn) {
|
||||
return;
|
||||
}
|
||||
const valueKey = valueColumn.id || valueColumn.name;
|
||||
const labelColumns = table.columns.filter((column) => !column.isValueColumn);
|
||||
|
||||
table.rows.forEach((row) => {
|
||||
const value = Number(row.data[valueKey]);
|
||||
const label =
|
||||
labelColumns
|
||||
.map((column) => row.data[column.id || column.name])
|
||||
.filter((part) => part != null)
|
||||
.map(String)
|
||||
.join(', ') ||
|
||||
table.legend ||
|
||||
table.queryName ||
|
||||
'';
|
||||
const color = customColors?.[label] ?? generateColor(label, colorMap);
|
||||
slices.push({ label, value, color });
|
||||
});
|
||||
});
|
||||
|
||||
return slices.filter(
|
||||
(slice) => Number.isFinite(slice.value) && slice.value > 0,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { SectionConfig } from '../../types/sections';
|
||||
|
||||
// Pie has no axes, thresholds, or stacking — just value formatting and a
|
||||
// legend. `mode` is omitted: the pie legend is always interactive swatches.
|
||||
export const sections: SectionConfig[] = [
|
||||
{ kind: 'formatting', controls: { unit: true, decimals: true } },
|
||||
{ kind: 'legend', controls: { position: true } },
|
||||
];
|
||||
@@ -0,0 +1,180 @@
|
||||
import { useCallback, useMemo, useRef } from 'react';
|
||||
import type { DashboardtypesTimeSeriesPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import TimeSeries from 'container/DashboardContainer/visualization/charts/TimeSeries/TimeSeries';
|
||||
import TooltipFooter from 'container/DashboardContainer/visualization/panels/components/TooltipFooter';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useResizeObserver } from 'hooks/useDimensions';
|
||||
import { IRenderTooltipFooterArgs } from 'lib/uPlotV2/components/types';
|
||||
import {
|
||||
flattenTimeSeries,
|
||||
getExecStats,
|
||||
getTimeSeriesResults,
|
||||
} from 'pages/DashboardPageV2/DashboardContainer/queryV5/v5ResponseData';
|
||||
import { prepareAlignedData } from 'pages/DashboardPageV2/DashboardContainer/queryV5/uplotData';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
import { getTimeRangeFromQueryRangeRequest } from 'utils/getTimeRange';
|
||||
|
||||
import { useGroupByPerQuery } from '../../hooks/useGroupByPerQuery';
|
||||
import PanelStyles from '../../panel.module.scss';
|
||||
import { PanelRendererProps } from '../../types/rendererProps';
|
||||
import {
|
||||
resolveDecimalPrecision,
|
||||
resolveLegendPosition,
|
||||
} from '../../utils/chartAppearanceMappings';
|
||||
import { getBuilderQueries } from '../../utils/getBuilderQueries';
|
||||
|
||||
import { buildTimeSeriesConfig } from './buildConfig';
|
||||
import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
|
||||
function TimeSeriesPanelRenderer({
|
||||
panelId,
|
||||
panel,
|
||||
data,
|
||||
onClick,
|
||||
onDragSelect,
|
||||
dashboardPreference,
|
||||
panelMode,
|
||||
}: PanelRendererProps<'signoz/TimeSeriesPanel'>): JSX.Element {
|
||||
const graphRef = useRef<HTMLDivElement>(null);
|
||||
const containerDimensions = useResizeObserver(graphRef);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const { timezone } = useTimezone();
|
||||
|
||||
// The registry guarantees this Renderer only runs when
|
||||
// `panel.spec.plugin.kind === 'signoz/TimeSeriesPanel'`, so the cast is a
|
||||
// documented boundary narrowing — not a blind assertion. Memoized so the
|
||||
// `?? {}` fallback doesn't produce a fresh object on each render.
|
||||
const spec = useMemo<DashboardtypesTimeSeriesPanelSpecDTO>(
|
||||
() =>
|
||||
(panel?.spec?.plugin?.spec ?? {}) as DashboardtypesTimeSeriesPanelSpecDTO,
|
||||
[panel?.spec?.plugin?.spec],
|
||||
);
|
||||
|
||||
const builderQueries = useMemo(
|
||||
() => getBuilderQueries(panel?.spec?.queries),
|
||||
[panel?.spec?.queries],
|
||||
);
|
||||
|
||||
// X-scale clamps come from the request that produced the data, so each
|
||||
// panel pins to the window it actually fetched — important during
|
||||
// drag-zoom transitions when the time picker has moved but new data
|
||||
// hasn't arrived yet. Falls back to the global picker inside the helper.
|
||||
// The generated request DTO is structurally the hand-written V5 request;
|
||||
// the cast is the documented boundary.
|
||||
const { minTimeScale, maxTimeScale } = useMemo(() => {
|
||||
const { startTime, endTime } = getTimeRangeFromQueryRangeRequest(
|
||||
data?.requestPayload as unknown as QueryRangeRequestV5 | undefined,
|
||||
);
|
||||
return { minTimeScale: startTime, maxTimeScale: endTime };
|
||||
}, [data?.requestPayload]);
|
||||
|
||||
const groupByPerQuery = useGroupByPerQuery(builderQueries);
|
||||
|
||||
const flatSeries = useMemo(
|
||||
() =>
|
||||
flattenTimeSeries(
|
||||
getTimeSeriesResults(data?.response),
|
||||
data?.legendMap ?? {},
|
||||
),
|
||||
[data?.response, data?.legendMap],
|
||||
);
|
||||
|
||||
const config = useMemo(
|
||||
() =>
|
||||
buildTimeSeriesConfig({
|
||||
panelId,
|
||||
spec,
|
||||
builderQueries,
|
||||
series: flatSeries,
|
||||
stepIntervals: getExecStats(data?.response)?.stepIntervals,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
onDragSelect,
|
||||
}),
|
||||
[
|
||||
panelId,
|
||||
spec,
|
||||
builderQueries,
|
||||
flatSeries,
|
||||
data?.response,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
onDragSelect,
|
||||
// `config` gets mutated by TooltipPlugin (config.setCursor for cursor sync).
|
||||
// Rebuild it on syncMode changes so the new chart instance starts from a
|
||||
// clean config — otherwise switching to "No Sync" would inherit stale sync
|
||||
// settings from the previous mode.
|
||||
dashboardPreference?.syncMode,
|
||||
],
|
||||
);
|
||||
|
||||
const chartData = useMemo(() => prepareAlignedData(flatSeries), [flatSeries]);
|
||||
|
||||
const decimalPrecision = useMemo(
|
||||
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
|
||||
[spec.formatting?.decimalPrecision],
|
||||
);
|
||||
|
||||
const legendPosition = useMemo(() => {
|
||||
return resolveLegendPosition(spec.legend?.position);
|
||||
}, [spec.legend?.position]);
|
||||
|
||||
const renderTooltipFooter = useCallback(
|
||||
({ isPinned, dismiss }: IRenderTooltipFooterArgs) => (
|
||||
<TooltipFooter id={panelId} isPinned={isPinned} dismiss={dismiss} />
|
||||
),
|
||||
[panelId],
|
||||
);
|
||||
|
||||
/**
|
||||
* The uPlot key prop is the only way to force a full teardown and re-mount
|
||||
* of the chart. By including the syncMode and syncFilterMode in the key,
|
||||
* we ensure that changes to these preferences trigger a fresh chart instance,
|
||||
* preventing stale sync settings from being inherited.
|
||||
*/
|
||||
const key = `${dashboardPreference?.syncMode}-${dashboardPreference?.syncFilterMode}`;
|
||||
|
||||
const handleChartClick = useCallback(
|
||||
(args: ChartClickData) => {
|
||||
onClick?.(args);
|
||||
},
|
||||
[onClick],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={graphRef}
|
||||
data-testid="time-series-renderer"
|
||||
className={PanelStyles.panelContainer}
|
||||
>
|
||||
{containerDimensions.width > 0 && containerDimensions.height > 0 && (
|
||||
<TimeSeries
|
||||
key={key}
|
||||
config={config}
|
||||
data={chartData}
|
||||
legendConfig={{ position: legendPosition }}
|
||||
groupByPerQuery={groupByPerQuery}
|
||||
canPinTooltip
|
||||
timezone={timezone}
|
||||
yAxisUnit={spec.formatting?.unit}
|
||||
decimalPrecision={decimalPrecision}
|
||||
width={containerDimensions.width}
|
||||
height={containerDimensions.height}
|
||||
syncMode={dashboardPreference?.syncMode}
|
||||
syncFilterMode={dashboardPreference?.syncFilterMode}
|
||||
renderTooltipFooter={renderTooltipFooter}
|
||||
onClick={handleChartClick}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TimeSeriesPanelRenderer;
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { DashboardtypesTimeSeriesPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { Timezone } from 'components/CustomTimePicker/timezoneUtils';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';
|
||||
import { buildBaseConfig } from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/baseConfigBuilder';
|
||||
import {
|
||||
FILL_MODE_MAP,
|
||||
LINE_INTERPOLATION_MAP,
|
||||
LINE_STYLE_MAP,
|
||||
resolveSpanGaps,
|
||||
} from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/chartAppearanceMappings';
|
||||
import { resolveSeriesLabelV5 } from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/resolveSeriesLabel';
|
||||
import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
import {
|
||||
hasSingleVisiblePoint,
|
||||
toClickPluginPayload,
|
||||
} from 'pages/DashboardPageV2/DashboardContainer/queryV5/uplotData';
|
||||
import getLabelName from 'lib/getLabelName';
|
||||
import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';
|
||||
import {
|
||||
DrawStyle,
|
||||
FillMode,
|
||||
LineInterpolation,
|
||||
LineStyle,
|
||||
} from 'lib/uPlotV2/config/types';
|
||||
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
|
||||
import type { BuilderQuery } from 'types/api/v5/queryRange';
|
||||
|
||||
const DEFAULT_POINT_SIZE = 5;
|
||||
|
||||
export interface BuildTimeSeriesConfigArgs {
|
||||
panelId: string;
|
||||
spec: DashboardtypesTimeSeriesPanelSpecDTO;
|
||||
/**
|
||||
* Flat list of builder queries on this panel (see `getBuilderQueries`).
|
||||
* Powers per-query legend resolution; empty for non-builder panels.
|
||||
*/
|
||||
builderQueries: BuilderQuery[];
|
||||
/** Flattened V5 series (see `flattenTimeSeries`). */
|
||||
series: PanelSeries[];
|
||||
/** Per-query step intervals from the response exec stats. */
|
||||
stepIntervals?: Record<string, number>;
|
||||
isDarkMode: boolean;
|
||||
timezone: Timezone;
|
||||
panelMode: PanelMode;
|
||||
onDragSelect?: (start: number, end: number) => void;
|
||||
onClick?: OnClickPluginOpts['onClick'];
|
||||
minTimeScale?: number;
|
||||
maxTimeScale?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a fully-wired `UPlotConfigBuilder` for a TimeSeries panel.
|
||||
*
|
||||
* Delegates the panel-agnostic scaffolding (scales, thresholds, axes,
|
||||
* drag-to-zoom, click plugin) to the shared `buildBaseConfig`, then layers
|
||||
* in the TimeSeries-specific concern: one series per result, with visuals
|
||||
* resolved from `spec.chartAppearance`.
|
||||
*/
|
||||
export function buildTimeSeriesConfig({
|
||||
panelId,
|
||||
spec,
|
||||
builderQueries,
|
||||
series,
|
||||
stepIntervals,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
onDragSelect,
|
||||
onClick,
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
}: BuildTimeSeriesConfigArgs): UPlotConfigBuilder {
|
||||
const builder = buildBaseConfig({
|
||||
panelId,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
isLogScale: spec.axes?.isLogScale,
|
||||
softMin: spec.axes?.softMin ?? undefined,
|
||||
softMax: spec.axes?.softMax ?? undefined,
|
||||
formatting: spec.formatting,
|
||||
thresholds: spec.thresholds,
|
||||
stepIntervals,
|
||||
clickPayload: toClickPluginPayload(series),
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
onDragSelect,
|
||||
onClick,
|
||||
});
|
||||
|
||||
addSeries({ builder, spec, builderQueries, series, isDarkMode });
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
interface AddSeriesArgs {
|
||||
builder: UPlotConfigBuilder;
|
||||
spec: DashboardtypesTimeSeriesPanelSpecDTO;
|
||||
builderQueries: BuilderQuery[];
|
||||
series: PanelSeries[];
|
||||
isDarkMode: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one uPlot series per flattened V5 series to the scaffolded builder.
|
||||
* The visual resolution (line style, interpolation, fill mode, span gaps)
|
||||
* reads from `spec.chartAppearance`; the label is resolved via the legend
|
||||
* matrix in `resolveSeriesLabelV5`. Mutates the builder in place.
|
||||
*
|
||||
* Order must match `prepareAlignedData` — both iterate the same flat list.
|
||||
*/
|
||||
function addSeries({
|
||||
builder,
|
||||
spec,
|
||||
builderQueries,
|
||||
series,
|
||||
isDarkMode,
|
||||
}: AddSeriesArgs): void {
|
||||
const chartAppearance = spec.chartAppearance;
|
||||
// `customColors` is nullable on the spec; coerce so `addSeries` always gets
|
||||
// a defined record (it dereferences keys without a guard).
|
||||
const colorMapping = spec.legend?.customColors ?? {};
|
||||
const spanGaps = resolveSpanGaps(chartAppearance?.spanGaps?.fillLessThan);
|
||||
|
||||
const lineStyle = chartAppearance?.lineStyle
|
||||
? LINE_STYLE_MAP[chartAppearance.lineStyle]
|
||||
: LineStyle.Solid;
|
||||
const lineInterpolation = chartAppearance?.lineInterpolation
|
||||
? LINE_INTERPOLATION_MAP[chartAppearance.lineInterpolation]
|
||||
: LineInterpolation.Spline;
|
||||
const fillMode = chartAppearance?.fillMode
|
||||
? FILL_MODE_MAP[chartAppearance.fillMode]
|
||||
: FillMode.None;
|
||||
|
||||
series.forEach((s) => {
|
||||
const hasSingleValidPoint = hasSingleVisiblePoint(s.values);
|
||||
const baseLabel = getLabelName(s.labels, s.queryName, s.legend);
|
||||
const label = resolveSeriesLabelV5(s, builderQueries, baseLabel);
|
||||
|
||||
builder.addSeries({
|
||||
scaleKey: 'y',
|
||||
// A single visible point can't be drawn as a line — degrade to points
|
||||
// so the user still sees the datum (matches V1 behavior).
|
||||
drawStyle: hasSingleValidPoint ? DrawStyle.Points : DrawStyle.Line,
|
||||
label,
|
||||
colorMapping,
|
||||
spanGaps,
|
||||
lineStyle,
|
||||
lineInterpolation,
|
||||
showPoints: chartAppearance?.showPoints || hasSingleValidPoint,
|
||||
pointSize: DEFAULT_POINT_SIZE,
|
||||
fillMode,
|
||||
isDarkMode,
|
||||
metric: s.labels,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { PanelDefinition } from '../../types/panelDefinition';
|
||||
import Renderer from './Renderer';
|
||||
import { sections } from './sections';
|
||||
|
||||
export const definition: PanelDefinition<'signoz/TimeSeriesPanel'> = {
|
||||
kind: 'signoz/TimeSeriesPanel',
|
||||
displayName: 'Time Series',
|
||||
Renderer,
|
||||
sections,
|
||||
supportedSignals: [DataSource.METRICS, DataSource.LOGS, DataSource.TRACES],
|
||||
actions: { view: true, edit: true, download: false, createAlert: true },
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { SectionConfig } from '../../types/sections';
|
||||
|
||||
export const sections: SectionConfig[] = [
|
||||
{
|
||||
kind: 'formatting',
|
||||
controls: {
|
||||
unit: true,
|
||||
decimals: true,
|
||||
},
|
||||
},
|
||||
{ kind: 'axes', controls: { minMax: true, unit: true, logScale: true } },
|
||||
{ kind: 'legend', controls: { position: true, mode: true } },
|
||||
{ kind: 'thresholds', controls: { list: true } },
|
||||
{ kind: 'chartAppearance', controls: { lineStyle: true, fillOpacity: true } },
|
||||
];
|
||||
@@ -0,0 +1,9 @@
|
||||
.panelContainer {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
|
||||
/**
|
||||
* Source-tagged click events. The three uPlot panels share `ChartClickEvent`;
|
||||
* each non-chart kind carries the context its drill-down needs. The `source`
|
||||
* tag lets a kind-agnostic consumer (the render boundary, a shared drill-down
|
||||
* handler) discriminate without assuming a chart shape.
|
||||
*/
|
||||
export type ChartClickEvent = ChartClickData;
|
||||
export type TableClickEvent = {
|
||||
rowData: Record<string, unknown>;
|
||||
columnId?: string;
|
||||
};
|
||||
export type ListClickEvent = {
|
||||
rowData: Record<string, unknown>;
|
||||
};
|
||||
export type PieClickEvent = { label: string; value: number };
|
||||
|
||||
/** Union of every panel click event — switched on by `source` at the boundary. */
|
||||
export type PanelClickEvent =
|
||||
| ChartClickEvent
|
||||
| TableClickEvent
|
||||
| ListClickEvent
|
||||
| PieClickEvent;
|
||||
|
||||
type DragSelect = (start: number, end: number) => void;
|
||||
|
||||
/**
|
||||
* Per-kind interaction props. Each panel kind exposes ONLY the gestures it
|
||||
* supports: chart panels get a chart-shaped `onClick`, time-axis charts add
|
||||
* `onDragSelect`, histograms have no drag-to-zoom, a NumberPanel has no
|
||||
* interactions at all. Keys mirror `PanelKind`; `PanelRendererProps<K>` in
|
||||
* rendererProps.ts indexes this map, so a missing kind is a compile error there.
|
||||
*/
|
||||
export interface PanelInteractionMap {
|
||||
'signoz/TimeSeriesPanel': {
|
||||
onClick?: (event: ChartClickEvent) => void;
|
||||
onDragSelect?: DragSelect;
|
||||
};
|
||||
'signoz/BarChartPanel': {
|
||||
onClick?: (event: ChartClickEvent) => void;
|
||||
onDragSelect?: DragSelect;
|
||||
};
|
||||
'signoz/HistogramPanel': { onClick?: (event: ChartClickEvent) => void };
|
||||
'signoz/TablePanel': { onClick?: (event: TableClickEvent) => void };
|
||||
'signoz/ListPanel': { onClick?: (event: ListClickEvent) => void };
|
||||
'signoz/PieChartPanel': { onClick?: (event: PieClickEvent) => void };
|
||||
'signoz/NumberPanel': Record<string, never>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Widest interaction surface — used where the panel kind is not known
|
||||
* statically (the registry render boundary; see `getPanelDefinition`). It is
|
||||
* the structural supertype the per-kind shapes are cast to exactly once.
|
||||
*/
|
||||
export interface AnyPanelInteractionProps {
|
||||
onClick?: (event: PanelClickEvent) => void;
|
||||
onDragSelect?: DragSelect;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { ComponentType } from 'react';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { SectionConfig } from './sections';
|
||||
import type { AnyPanelInteractionProps } from './interactions';
|
||||
import type { PanelKind } from './panelKind';
|
||||
import type { BaseRendererProps, PanelRendererProps } from './rendererProps';
|
||||
|
||||
/**
|
||||
* Kind-level action capabilities: which panel actions THIS kind supports.
|
||||
* Declared per-kind in `kinds/<Kind>/definition.ts` — the field is required,
|
||||
* so registering a new kind forces an explicit decision for every action
|
||||
* (mirroring how PanelInteractionMap forces per-kind interaction coverage).
|
||||
*
|
||||
* Chrome actions (move to section, clone, delete) are dashboard-layout
|
||||
* concerns, available for every panel — including kinds V2 can't render —
|
||||
* and are intentionally not declarable here.
|
||||
*/
|
||||
export interface PanelActionCapabilities {
|
||||
/** Kind has a full-screen view — gates the "View" action. */
|
||||
view: boolean;
|
||||
/** Kind is editable in the V2 panel editor — gates the "Edit panel" action. */
|
||||
edit: boolean;
|
||||
/**
|
||||
* Kind's data can be exported as CSV — gates "Download as CSV". V1 parity:
|
||||
* only table panels carry tabular data worth exporting.
|
||||
*/
|
||||
download: boolean;
|
||||
/** Kind's query can seed a new alert — gates "Create Alerts". */
|
||||
createAlert: boolean;
|
||||
}
|
||||
|
||||
export interface PanelDefinition<K extends PanelKind = PanelKind> {
|
||||
kind: K;
|
||||
displayName: string;
|
||||
Renderer: ComponentType<PanelRendererProps<K>>;
|
||||
sections: SectionConfig[];
|
||||
supportedSignals: DataSource[];
|
||||
actions: PanelActionCapabilities;
|
||||
}
|
||||
|
||||
// Keyed registry that preserves the kind ↔ definition correlation: indexing
|
||||
// with a literal kind yields that kind's exactly-typed PanelDefinition.
|
||||
export type PanelRegistry = { [K in PanelKind]?: PanelDefinition<K> };
|
||||
|
||||
// A PanelDefinition whose Renderer is widened to the kind-agnostic prop surface.
|
||||
// At the render boundary the concrete kind isn't known statically (a registry
|
||||
// lookup returns a union over kinds), so getPanelDefinition resolves to this —
|
||||
// concentrating the single unavoidable cast in one place instead of leaking it
|
||||
// to every call site.
|
||||
export interface RenderablePanelDefinition extends Omit<
|
||||
PanelDefinition,
|
||||
'Renderer'
|
||||
> {
|
||||
Renderer: ComponentType<BaseRendererProps & AnyPanelInteractionProps>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
export type PanelKind =
|
||||
| 'signoz/TimeSeriesPanel'
|
||||
| 'signoz/BarChartPanel'
|
||||
| 'signoz/NumberPanel'
|
||||
| 'signoz/PieChartPanel'
|
||||
| 'signoz/TablePanel'
|
||||
| 'signoz/HistogramPanel'
|
||||
| 'signoz/ListPanel';
|
||||
|
||||
export const PANEL_KIND_TO_PANEL_TYPE: Record<PanelKind, PANEL_TYPES> = {
|
||||
'signoz/TimeSeriesPanel': PANEL_TYPES.TIME_SERIES,
|
||||
'signoz/BarChartPanel': PANEL_TYPES.BAR,
|
||||
'signoz/NumberPanel': PANEL_TYPES.VALUE,
|
||||
'signoz/PieChartPanel': PANEL_TYPES.PIE,
|
||||
'signoz/TablePanel': PANEL_TYPES.TABLE,
|
||||
'signoz/HistogramPanel': PANEL_TYPES.HISTOGRAM,
|
||||
'signoz/ListPanel': PANEL_TYPES.LIST,
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type {
|
||||
DashboardCursorSync,
|
||||
SyncTooltipFilterMode,
|
||||
} from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';
|
||||
import type { PanelQueryData } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
|
||||
import type { PanelInteractionMap } from './interactions';
|
||||
import type { PanelKind } from './panelKind';
|
||||
|
||||
/**
|
||||
* Dashboard-wide rendering preferences propagated down to every panel renderer
|
||||
* on the same dashboard. Lets the shell push cross-panel concerns (cursor
|
||||
* sync, tooltip filter mode, dashboard id for scoped state) without each
|
||||
* renderer rediscovering them via hooks. All fields are optional — non-
|
||||
* dashboard render contexts (PanelEditor preview, standalone view) can pass
|
||||
* an empty object and the renderer will fall back to sensible defaults.
|
||||
*/
|
||||
export interface DashboardPreference {
|
||||
/**
|
||||
* Cursor-sync mode for the dashboard. Drives the uPlot tooltip plugin so
|
||||
* hovering one panel highlights the corresponding x on every other panel.
|
||||
*/
|
||||
syncMode?: DashboardCursorSync;
|
||||
/**
|
||||
* Filter applied to the synced tooltip across panels (e.g. only show series
|
||||
* whose label matches the hovered series).
|
||||
*/
|
||||
syncFilterMode?: SyncTooltipFilterMode;
|
||||
/**
|
||||
* Dashboard id — useful for renderers that scope per-dashboard state
|
||||
* (e.g. pinned-tooltip persistence, drill-down history).
|
||||
*/
|
||||
dashboardId?: string;
|
||||
}
|
||||
|
||||
// Kind-agnostic props every renderer receives, regardless of panel kind. The
|
||||
// kind-specific interaction props (onClick payload, onDragSelect) are layered
|
||||
// on per-kind by PanelRendererProps<K>.
|
||||
export interface BaseRendererProps {
|
||||
panelId: string;
|
||||
/**
|
||||
* The whole perses panel — renderers derive their concrete `spec` and the
|
||||
* perses-shaped `queries` from this. Passing the full panel keeps the prop
|
||||
* surface stable as new panel-level fields are added to the wire format.
|
||||
*/
|
||||
panel: DashboardtypesPanelDTO | undefined;
|
||||
/** Raw V5 fetch result — response + the request that produced it. */
|
||||
data?: PanelQueryData;
|
||||
isLoading: boolean;
|
||||
error: Error | null;
|
||||
/** Gate for the drill-down right-click menu. Off by default in V2. */
|
||||
enableDrillDown?: boolean;
|
||||
/**
|
||||
* Render context — varies behavior (e.g. dashboard widget vs. standalone
|
||||
* full-screen vs. inside the editor). See PanelMode for the contract.
|
||||
*/
|
||||
panelMode: PanelMode;
|
||||
/**
|
||||
* Dashboard-level preferences that should propagate to every panel
|
||||
* (cursor sync, tooltip filter mode, dashboard id). The shell owns
|
||||
* resolving these; the renderer just consumes them.
|
||||
*/
|
||||
dashboardPreference?: DashboardPreference;
|
||||
}
|
||||
|
||||
// Renderer props for a specific panel kind: the shared base plus that kind's
|
||||
// interaction surface (PanelInteractionMap[K]). Each renderer annotates with
|
||||
// its own kind — e.g. PanelRendererProps<'signoz/TimeSeriesPanel'> — so it can
|
||||
// only reference the gestures that kind supports. Indexing PanelInteractionMap
|
||||
// here forces the map to cover every PanelKind. The default K = PanelKind
|
||||
// yields the widest surface (a union over all kinds).
|
||||
export type PanelRendererProps<K extends PanelKind = PanelKind> =
|
||||
BaseRendererProps & PanelInteractionMap[K];
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
BarChart,
|
||||
Columns3,
|
||||
Hash,
|
||||
ListEnd,
|
||||
Palette,
|
||||
Ruler,
|
||||
SlidersHorizontal,
|
||||
} from '@signozhq/icons';
|
||||
|
||||
// Derived from an actual icon component so the type stays exact (size is a
|
||||
// constrained IconSize union, not arbitrary strings) and ForwardRef-compatible.
|
||||
export type SectionIcon = typeof Hash;
|
||||
|
||||
export interface SectionMetadata {
|
||||
title: string;
|
||||
icon: SectionIcon;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
// Per-kind control toggles (type-only — runtime metadata is in SECTIONS).
|
||||
// Section components type their controls prop via `SectionControls['axes']`.
|
||||
export type SectionControls = {
|
||||
formatting: { unit?: boolean; decimals?: boolean };
|
||||
axes: { minMax?: boolean; unit?: boolean; logScale?: boolean };
|
||||
legend: { position?: boolean; mode?: boolean };
|
||||
thresholds: { list?: boolean };
|
||||
chartAppearance: {
|
||||
lineStyle?: boolean;
|
||||
fillOpacity?: boolean;
|
||||
stacked?: boolean;
|
||||
};
|
||||
columnUnits: { perColumnUnit?: boolean };
|
||||
buckets: { count?: boolean; min?: boolean; max?: boolean };
|
||||
};
|
||||
|
||||
// Source of truth for sections. Its keys define SectionKind; its values are the
|
||||
// runtime UI metadata (consumed by PanelEditor in 1.8). Adding a new section =
|
||||
// one entry here + one entry in SectionControls.
|
||||
export const SECTIONS = {
|
||||
formatting: { title: 'Formatting', icon: Hash },
|
||||
axes: { title: 'Axes', icon: Ruler },
|
||||
legend: { title: 'Legend', icon: ListEnd },
|
||||
thresholds: { title: 'Thresholds', icon: SlidersHorizontal },
|
||||
chartAppearance: { title: 'Chart appearance', icon: Palette },
|
||||
columnUnits: { title: 'Column units', icon: Columns3 },
|
||||
buckets: { title: 'Buckets', icon: BarChart },
|
||||
} as const satisfies Record<string, SectionMetadata>;
|
||||
|
||||
export type SectionKind = keyof typeof SECTIONS;
|
||||
|
||||
// Discriminated union derived from SectionControls — kept in lockstep automatically.
|
||||
export type SectionConfig = {
|
||||
[K in SectionKind]: { kind: K; controls: SectionControls[K] };
|
||||
}[SectionKind];
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* V2-native threshold model.
|
||||
*
|
||||
* The panel spec carries thresholds as `DashboardtypesComparisonThresholdDTO`
|
||||
* (operator/format expressed as `above`/`below`/`text`/`background`). For
|
||||
* evaluation and rendering we work with the symbol operators and lowercase
|
||||
* display formats, kept here so V2 panels never reach into the V1
|
||||
* `container/NewWidget` `ThresholdProps` shape.
|
||||
*/
|
||||
|
||||
/** Comparison operators a threshold can use, as evaluable symbols. */
|
||||
export type ThresholdComparisonOperator = '>' | '<' | '>=' | '<=' | '=' | '!=';
|
||||
|
||||
/** How a matched threshold recolors the panel. */
|
||||
export type ThresholdDisplayFormat = 'text' | 'background';
|
||||
|
||||
/**
|
||||
* A threshold normalized for evaluation/rendering. `operator`/`format` are
|
||||
* optional because the spec allows partially-configured thresholds; a
|
||||
* threshold with no operator never matches.
|
||||
*/
|
||||
export interface PanelThreshold {
|
||||
color: string;
|
||||
operator?: ThresholdComparisonOperator;
|
||||
value: number;
|
||||
/** Unit the threshold value is expressed in; converted to the panel unit before comparison. */
|
||||
unit?: string;
|
||||
format?: ThresholdDisplayFormat;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { PanelThreshold } from '../../types/threshold';
|
||||
import {
|
||||
doesValueMatchThreshold,
|
||||
resolveActiveThreshold,
|
||||
} from '../evaluateThresholds';
|
||||
|
||||
const threshold = (overrides: Partial<PanelThreshold>): PanelThreshold => ({
|
||||
color: '#f00',
|
||||
value: 100,
|
||||
operator: '>',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('doesValueMatchThreshold', () => {
|
||||
it.each([
|
||||
['>', 150, 100, true],
|
||||
['>', 50, 100, false],
|
||||
['<', 50, 100, true],
|
||||
['>=', 100, 100, true],
|
||||
['<=', 100, 100, true],
|
||||
['=', 100, 100, true],
|
||||
['!=', 150, 100, true],
|
||||
] as const)('evaluates %s (%d vs %d)', (operator, value, target, expected) => {
|
||||
expect(
|
||||
doesValueMatchThreshold(value, threshold({ operator, value: target })),
|
||||
).toBe(expected);
|
||||
});
|
||||
|
||||
it('never matches a threshold without an operator', () => {
|
||||
expect(doesValueMatchThreshold(150, threshold({ operator: undefined }))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('compares the raw value when units are in different categories', () => {
|
||||
// 'bytes' vs 'ms' belong to different categories, so conversion is invalid
|
||||
// and the comparison falls back to the raw value (150 > 100).
|
||||
expect(
|
||||
doesValueMatchThreshold(150, threshold({ value: 100, unit: 'bytes' }), 'ms'),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveActiveThreshold', () => {
|
||||
it('returns no threshold when none match', () => {
|
||||
const result = resolveActiveThreshold([threshold({ value: 1000 })], 10);
|
||||
expect(result.threshold).toBeNull();
|
||||
expect(result.isConflicting).toBe(false);
|
||||
});
|
||||
|
||||
it('flags a conflict and picks the earliest-declared match', () => {
|
||||
const first = threshold({ color: '#aaa', operator: '>', value: 0 });
|
||||
const second = threshold({ color: '#bbb', operator: '>', value: 100 });
|
||||
|
||||
const result = resolveActiveThreshold([first, second], 150);
|
||||
|
||||
expect(result.isConflicting).toBe(true);
|
||||
expect(result.threshold).toBe(first);
|
||||
});
|
||||
|
||||
it('returns the single matching threshold without a conflict', () => {
|
||||
const only = threshold({ color: '#abc', operator: '>', value: 100 });
|
||||
const result = resolveActiveThreshold(
|
||||
[only, threshold({ value: 9999 })],
|
||||
150,
|
||||
);
|
||||
|
||||
expect(result.threshold).toBe(only);
|
||||
expect(result.isConflicting).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { PrecisionOptionsEnum } from 'components/Graph/types';
|
||||
|
||||
import { formatPanelValue } from '../formatPanelValue';
|
||||
|
||||
describe('formatPanelValue', () => {
|
||||
it('applies the configured precision and appends the unit label', () => {
|
||||
// The unit-aware formatter returns value + label as one string; the
|
||||
// ValueDisplay splits it into numeric/suffix parts when rendering.
|
||||
expect(formatPanelValue(295.4299833508185, 'ms', 2)).toBe('295.43 ms');
|
||||
});
|
||||
|
||||
// Regression: precision must apply even with no unit. The old gate
|
||||
// (`unit ? format() : value.toString()`) dropped precision on unitless
|
||||
// panels, so decimal-precision changes had no visible effect.
|
||||
it('applies precision when NO unit is set', () => {
|
||||
expect(formatPanelValue(3.14159, undefined, 2)).toBe('3.14');
|
||||
expect(formatPanelValue(3.14159, '', 2)).toBe('3.14');
|
||||
});
|
||||
|
||||
it('honors full precision without a unit', () => {
|
||||
expect(formatPanelValue(3.14159, undefined, PrecisionOptionsEnum.FULL)).toBe(
|
||||
'3.14159',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the fractional part at precision 0', () => {
|
||||
expect(formatPanelValue(3.14159, undefined, 0)).toBe('3');
|
||||
});
|
||||
|
||||
it('renders whole numbers without a trailing decimal', () => {
|
||||
expect(formatPanelValue(5, undefined, 2)).toBe('5');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
import type { BuilderQuery } from 'types/api/v5/queryRange';
|
||||
|
||||
import { resolveSeriesLabelV5 } from '../resolveSeriesLabel';
|
||||
|
||||
// Fixtures cast at the boundary; the v5 BuilderQuery union is too verbose to
|
||||
// construct field-typed inline.
|
||||
|
||||
function builderQuery(spec: Record<string, unknown>): BuilderQuery {
|
||||
return spec as unknown as BuilderQuery;
|
||||
}
|
||||
|
||||
function panelSeries(overrides: Partial<PanelSeries> = {}): PanelSeries {
|
||||
return {
|
||||
queryName: 'A',
|
||||
legend: '',
|
||||
labels: { host: 'h1' },
|
||||
kind: 'series',
|
||||
values: [],
|
||||
aggregation: { index: 0, alias: '' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('resolveSeriesLabelV5', () => {
|
||||
it('returns baseLabel for panels without builder queries (promql/clickhouse)', () => {
|
||||
expect(resolveSeriesLabelV5(panelSeries(), [], 'base')).toBe('base');
|
||||
});
|
||||
|
||||
it('returns baseLabel when no query matches the series queryName', () => {
|
||||
expect(
|
||||
resolveSeriesLabelV5(
|
||||
panelSeries({ queryName: 'Z' }),
|
||||
[builderQuery({ name: 'A' })],
|
||||
'base',
|
||||
),
|
||||
).toBe('base');
|
||||
});
|
||||
|
||||
it('falls back to baseLabel || queryName when the aggregation has no alias/expression (metrics)', () => {
|
||||
const queries = [
|
||||
builderQuery({ name: 'A', aggregations: [{ metricName: 'cpu' }] }),
|
||||
];
|
||||
expect(resolveSeriesLabelV5(panelSeries(), queries, 'base')).toBe('base');
|
||||
expect(resolveSeriesLabelV5(panelSeries(), queries, '')).toBe('A');
|
||||
});
|
||||
|
||||
it('single query + groupBy + single aggregation → baseLabel', () => {
|
||||
const queries = [
|
||||
builderQuery({
|
||||
name: 'A',
|
||||
groupBy: [{ name: 'host' }],
|
||||
aggregations: [{ expression: 'count()', alias: '' }],
|
||||
}),
|
||||
];
|
||||
expect(resolveSeriesLabelV5(panelSeries(), queries, 'h1')).toBe('h1');
|
||||
});
|
||||
|
||||
it('single query + groupBy + multiple aggregations → "alias-or-expression"-baseLabel', () => {
|
||||
const queries = [
|
||||
builderQuery({
|
||||
name: 'A',
|
||||
groupBy: [{ name: 'host' }],
|
||||
aggregations: [
|
||||
{ expression: 'count()', alias: '' },
|
||||
{ expression: 'avg(x)', alias: 'mean' },
|
||||
],
|
||||
}),
|
||||
];
|
||||
expect(
|
||||
resolveSeriesLabelV5(
|
||||
panelSeries({ aggregation: { index: 1, alias: 'mean' } }),
|
||||
queries,
|
||||
'h1',
|
||||
),
|
||||
).toBe('mean-h1');
|
||||
});
|
||||
|
||||
it('single query, no groupBy, single aggregation → alias || legend || expression', () => {
|
||||
const queries = [
|
||||
builderQuery({
|
||||
name: 'A',
|
||||
legend: 'My legend',
|
||||
aggregations: [{ expression: 'count()', alias: '' }],
|
||||
}),
|
||||
];
|
||||
expect(resolveSeriesLabelV5(panelSeries({ labels: {} }), queries, 'A')).toBe(
|
||||
'My legend',
|
||||
);
|
||||
});
|
||||
|
||||
it('multiple queries, no groupBy, single aggregation → alias || baseLabel', () => {
|
||||
const queries = [
|
||||
builderQuery({ name: 'A', aggregations: [{ expression: 'count()' }] }),
|
||||
builderQuery({ name: 'B', aggregations: [{ expression: 'sum(y)' }] }),
|
||||
];
|
||||
expect(
|
||||
resolveSeriesLabelV5(panelSeries({ labels: {} }), queries, 'base'),
|
||||
).toBe('base');
|
||||
});
|
||||
|
||||
it('resolves via the aggregation index carried on the series', () => {
|
||||
const queries = [
|
||||
builderQuery({
|
||||
name: 'A',
|
||||
aggregations: [
|
||||
{ expression: 'count()', alias: 'hits' },
|
||||
{ expression: 'avg(x)', alias: 'mean' },
|
||||
],
|
||||
}),
|
||||
];
|
||||
expect(
|
||||
resolveSeriesLabelV5(
|
||||
panelSeries({ labels: {}, aggregation: { index: 1, alias: 'mean' } }),
|
||||
queries,
|
||||
'',
|
||||
),
|
||||
).toBe('mean');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import type {
|
||||
DashboardtypesPanelFormattingDTO,
|
||||
DashboardtypesThresholdWithLabelDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { Timezone } from 'components/CustomTimePicker/timezoneUtils';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';
|
||||
import onClickPlugin, {
|
||||
OnClickPluginOpts,
|
||||
} from 'lib/uPlotLib/plugins/onClickPlugin';
|
||||
import {
|
||||
DistributionType,
|
||||
SelectionPreferencesSource,
|
||||
} from 'lib/uPlotV2/config/types';
|
||||
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
|
||||
import { ThresholdsDrawHookOptions } from 'lib/uPlotV2/hooks/types';
|
||||
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
|
||||
import uPlot from 'uplot';
|
||||
|
||||
/**
|
||||
* Inputs for the shared V2 chart pipeline. Mirrors the V1 helper of the same
|
||||
* name but accepts perses-shaped inputs directly (so callers don't translate
|
||||
* once per panel). The series-rendering step is panel-specific and lives in
|
||||
* each panel's `utils.ts` — this helper only wires the scaffolding (scales,
|
||||
* thresholds, axes, drag-to-zoom, click plugin).
|
||||
*/
|
||||
export interface BuildBaseConfigArgs {
|
||||
panelId: string;
|
||||
panelType: PANEL_TYPES;
|
||||
isDarkMode: boolean;
|
||||
timezone: Timezone;
|
||||
panelMode: PanelMode;
|
||||
|
||||
/** From `spec.axes` — drives the Y scale and (when log) both scales' base. */
|
||||
isLogScale?: boolean;
|
||||
softMin?: number;
|
||||
softMax?: number;
|
||||
|
||||
/** From `spec.formatting.unit` — drives Y axis tick formatting + threshold formatting. */
|
||||
formatting?: DashboardtypesPanelFormattingDTO;
|
||||
|
||||
/** From `spec.thresholds` — perses shape, mapped to the draw-hook shape internally. */
|
||||
thresholds?: DashboardtypesThresholdWithLabelDTO[] | null;
|
||||
|
||||
/** Per-query step intervals from the response exec stats. */
|
||||
stepIntervals?: Record<string, number>;
|
||||
/**
|
||||
* Tuple-shaped payload for the shared click plugin (see
|
||||
* `toClickPluginPayload`). Omitted by panels without click interactions.
|
||||
*/
|
||||
clickPayload?: MetricRangePayloadProps;
|
||||
|
||||
/** Time-range clamps for the X scale (typically from `getTimeRange(apiResponse)`). */
|
||||
minTimeScale?: number;
|
||||
maxTimeScale?: number;
|
||||
|
||||
/** Optional — histogram and other non-time panels omit drag-to-zoom. */
|
||||
onDragSelect?: (start: number, end: number) => void;
|
||||
onClick?: OnClickPluginOpts['onClick'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the panel-agnostic scaffolding of a uPlot chart: scales, thresholds,
|
||||
* axes, drag-to-zoom, click plugin. Callers (TimeSeriesPanel, BarPanel, …)
|
||||
* then call `addSeries`/`addPlugin` on the returned builder for their own
|
||||
* panel-specific rendering.
|
||||
*/
|
||||
export function buildBaseConfig({
|
||||
panelId,
|
||||
panelType,
|
||||
isDarkMode,
|
||||
timezone,
|
||||
panelMode,
|
||||
isLogScale,
|
||||
softMin,
|
||||
softMax,
|
||||
formatting,
|
||||
thresholds,
|
||||
stepIntervals,
|
||||
clickPayload,
|
||||
minTimeScale,
|
||||
maxTimeScale,
|
||||
onDragSelect,
|
||||
onClick,
|
||||
}: BuildBaseConfigArgs): UPlotConfigBuilder {
|
||||
const yAxisUnit = formatting?.unit;
|
||||
|
||||
const builder = new UPlotConfigBuilder({
|
||||
id: panelId,
|
||||
onDragSelect,
|
||||
tzDate: makeTzDate(timezone),
|
||||
shouldSaveSelectionPreference: panelMode === PanelMode.DASHBOARD_VIEW,
|
||||
selectionPreferencesSource: resolveSelectionPreferencesSource(panelMode),
|
||||
stepInterval: stepIntervals ? minStepInterval(stepIntervals) : undefined,
|
||||
});
|
||||
|
||||
const thresholdOptions: ThresholdsDrawHookOptions = {
|
||||
scaleKey: 'y',
|
||||
thresholds: mapThresholds(thresholds),
|
||||
yAxisUnit,
|
||||
};
|
||||
|
||||
builder.addThresholds(thresholdOptions);
|
||||
|
||||
builder.addScale({
|
||||
scaleKey: 'x',
|
||||
time: true,
|
||||
min: minTimeScale,
|
||||
max: maxTimeScale,
|
||||
logBase: isLogScale ? 10 : undefined,
|
||||
distribution: isLogScale
|
||||
? DistributionType.Logarithmic
|
||||
: DistributionType.Linear,
|
||||
});
|
||||
|
||||
builder.addScale({
|
||||
scaleKey: 'y',
|
||||
time: false,
|
||||
min: undefined,
|
||||
max: undefined,
|
||||
softMin,
|
||||
softMax,
|
||||
thresholds: thresholdOptions,
|
||||
logBase: isLogScale ? 10 : undefined,
|
||||
distribution: isLogScale
|
||||
? DistributionType.Logarithmic
|
||||
: DistributionType.Linear,
|
||||
});
|
||||
|
||||
if (typeof onClick === 'function') {
|
||||
builder.addPlugin(onClickPlugin({ onClick, apiResponse: clickPayload }));
|
||||
}
|
||||
|
||||
builder.addAxis({
|
||||
scaleKey: 'x',
|
||||
show: true,
|
||||
side: 2,
|
||||
isDarkMode,
|
||||
isLogScale,
|
||||
panelType,
|
||||
});
|
||||
|
||||
builder.addAxis({
|
||||
scaleKey: 'y',
|
||||
show: true,
|
||||
side: 3,
|
||||
isDarkMode,
|
||||
isLogScale,
|
||||
yAxisUnit,
|
||||
panelType,
|
||||
});
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
function makeTzDate(
|
||||
timezone: Timezone,
|
||||
): ((timestamp: number) => Date) | undefined {
|
||||
if (!timezone) {
|
||||
return undefined;
|
||||
}
|
||||
return (timestamp: number): Date =>
|
||||
uPlot.tzDate(new Date(timestamp * 1e3), timezone.value);
|
||||
}
|
||||
|
||||
function resolveSelectionPreferencesSource(
|
||||
panelMode: PanelMode,
|
||||
): SelectionPreferencesSource {
|
||||
return panelMode === PanelMode.DASHBOARD_VIEW ||
|
||||
panelMode === PanelMode.STANDALONE_VIEW
|
||||
? SelectionPreferencesSource.LOCAL_STORAGE
|
||||
: SelectionPreferencesSource.IN_MEMORY;
|
||||
}
|
||||
|
||||
// Perses-shape thresholds → the draw-hook shape uPlotV2 consumes. Exported so
|
||||
// panels that need to feed the same threshold list elsewhere (e.g. to a series
|
||||
// `addSeries` thresholds hook) don't have to redo the mapping.
|
||||
export function mapThresholds(
|
||||
thresholds: DashboardtypesThresholdWithLabelDTO[] | null | undefined,
|
||||
): ThresholdsDrawHookOptions['thresholds'] {
|
||||
if (!thresholds || thresholds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return thresholds.map((t) => ({
|
||||
thresholdValue: t.value,
|
||||
thresholdColor: t.color,
|
||||
thresholdUnit: t.unit,
|
||||
thresholdLabel: t.label,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* V5 backend reports per-query step intervals; we feed the smallest one through
|
||||
* to uPlot so the X-axis tick density matches the densest query. An empty map
|
||||
* yields `Infinity` from `Math.min`, which would corrupt downstream scale math —
|
||||
* fall back to `undefined` (uPlot's "auto") in that case.
|
||||
*/
|
||||
function minStepInterval(
|
||||
stepIntervals: Record<string, number>,
|
||||
): number | undefined {
|
||||
const values = Object.values(stepIntervals);
|
||||
if (values.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const min = Math.min(...values);
|
||||
return Number.isFinite(min) ? min : undefined;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import {
|
||||
DashboardtypesFillModeDTO,
|
||||
DashboardtypesLegendPositionDTO,
|
||||
DashboardtypesLineInterpolationDTO,
|
||||
DashboardtypesLineStyleDTO,
|
||||
DashboardtypesPrecisionOptionDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
|
||||
import { LegendPosition } from 'lib/uPlotV2/components/types';
|
||||
import {
|
||||
FillMode,
|
||||
LineInterpolation,
|
||||
LineStyle,
|
||||
} from 'lib/uPlotV2/config/types';
|
||||
|
||||
/**
|
||||
* Bridges the V2 dashboard wire-format enums (snake_case, generated from Go)
|
||||
* to the uPlotV2 chart enums (PascalCase). String values diverge between the
|
||||
* two — don't coerce, map.
|
||||
*
|
||||
* Kept as a single source of truth so every panel that reads chart-appearance
|
||||
* fields stays in sync as either side's enum evolves.
|
||||
*/
|
||||
|
||||
export const LINE_STYLE_MAP: Record<DashboardtypesLineStyleDTO, LineStyle> = {
|
||||
[DashboardtypesLineStyleDTO.solid]: LineStyle.Solid,
|
||||
[DashboardtypesLineStyleDTO.dashed]: LineStyle.Dashed,
|
||||
};
|
||||
|
||||
export const LINE_INTERPOLATION_MAP: Record<
|
||||
DashboardtypesLineInterpolationDTO,
|
||||
LineInterpolation
|
||||
> = {
|
||||
[DashboardtypesLineInterpolationDTO.linear]: LineInterpolation.Linear,
|
||||
[DashboardtypesLineInterpolationDTO.spline]: LineInterpolation.Spline,
|
||||
[DashboardtypesLineInterpolationDTO.step_after]: LineInterpolation.StepAfter,
|
||||
[DashboardtypesLineInterpolationDTO.step_before]: LineInterpolation.StepBefore,
|
||||
};
|
||||
|
||||
export const FILL_MODE_MAP: Record<DashboardtypesFillModeDTO, FillMode> = {
|
||||
[DashboardtypesFillModeDTO.solid]: FillMode.Solid,
|
||||
[DashboardtypesFillModeDTO.gradient]: FillMode.Gradient,
|
||||
[DashboardtypesFillModeDTO.none]: FillMode.None,
|
||||
};
|
||||
|
||||
export const LEGEND_POSITION_MAP: Record<
|
||||
DashboardtypesLegendPositionDTO,
|
||||
LegendPosition
|
||||
> = {
|
||||
[DashboardtypesLegendPositionDTO.bottom]: LegendPosition.BOTTOM,
|
||||
[DashboardtypesLegendPositionDTO.right]: LegendPosition.RIGHT,
|
||||
};
|
||||
|
||||
/**
|
||||
* `spec.formatting.decimalPrecision` is a stringified-digit enum on the wire
|
||||
* (`'0'`–`'4'` plus the sentinel `'full'`). The chart consumes a numeric
|
||||
* `PrecisionOption` (`0`–`4`) or the same `'full'` sentinel from its own
|
||||
* enum. Missing / unknown → `undefined` (chart uses its default).
|
||||
*/
|
||||
export function resolveDecimalPrecision(
|
||||
precision: DashboardtypesPrecisionOptionDTO | undefined,
|
||||
): PrecisionOption | undefined {
|
||||
if (!precision) {
|
||||
return undefined;
|
||||
}
|
||||
if (precision === DashboardtypesPrecisionOptionDTO.full) {
|
||||
return PrecisionOptionsEnum.FULL;
|
||||
}
|
||||
const parsed = Number(precision);
|
||||
if (
|
||||
parsed === 0 ||
|
||||
parsed === 1 ||
|
||||
parsed === 2 ||
|
||||
parsed === 3 ||
|
||||
parsed === 4
|
||||
) {
|
||||
return parsed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `spec.chartAppearance.spanGaps.fillLessThan` is a stringified number on the
|
||||
* wire. Empty / missing → span all gaps (the chart default). Numeric → forward
|
||||
* the threshold so uPlot only bridges short runs of nulls.
|
||||
*/
|
||||
export function resolveSpanGaps(
|
||||
fillLessThan: string | undefined,
|
||||
): boolean | number {
|
||||
if (!fillLessThan) {
|
||||
return true;
|
||||
}
|
||||
const parsed = Number(fillLessThan);
|
||||
return Number.isFinite(parsed) ? parsed : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the legend position for a panel. Missing / unknown values fall
|
||||
* back to `BOTTOM` to match the chart's default and the V1 behavior.
|
||||
*/
|
||||
export function resolveLegendPosition(
|
||||
position: DashboardtypesLegendPositionDTO | undefined,
|
||||
): LegendPosition {
|
||||
if (position && position in LEGEND_POSITION_MAP) {
|
||||
return LEGEND_POSITION_MAP[position];
|
||||
}
|
||||
return LegendPosition.BOTTOM;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import {
|
||||
UniversalUnitToGrafanaUnit,
|
||||
YAxisCategoryNames,
|
||||
} from 'components/YAxisUnitSelector/constants';
|
||||
import { YAxisSource } from 'components/YAxisUnitSelector/types';
|
||||
import { getYAxisCategories } from 'components/YAxisUnitSelector/utils';
|
||||
import { convertValue } from 'lib/getConvertedValue';
|
||||
|
||||
import type {
|
||||
PanelThreshold,
|
||||
ThresholdComparisonOperator,
|
||||
} from '../types/threshold';
|
||||
|
||||
/**
|
||||
* Threshold evaluation for V2 panels — a self-contained port of the V1
|
||||
* `GridTableComponent`/`ValueGraph` logic that depends only on shared,
|
||||
* non-V1 primitives (`convertValue`, the Y-axis unit catalog). No imports
|
||||
* from `container/NewWidget`, `container/GridTableComponent`, or
|
||||
* `components/ValueGraph`.
|
||||
*/
|
||||
|
||||
/** Resolves which unit category a unit id belongs to, or null if unknown. */
|
||||
function getCategoryName(unitId: string): YAxisCategoryNames | null {
|
||||
const categories = getYAxisCategories(YAxisSource.DASHBOARDS);
|
||||
|
||||
const foundCategory = categories.find((category) =>
|
||||
category.units.some((unit) => {
|
||||
// Category units use universal ids; thresholds/panel units may use
|
||||
// Grafana-style ids. Match either the universal id directly or its
|
||||
// mapped Grafana id.
|
||||
if (unit.id === unitId) {
|
||||
return true;
|
||||
}
|
||||
return UniversalUnitToGrafanaUnit[unit.id] === unitId;
|
||||
}),
|
||||
);
|
||||
|
||||
return foundCategory ? foundCategory.name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts `value` from `fromUnit` to `toUnit`, returning null when the
|
||||
* conversion is invalid (unknown unit, or units in different categories).
|
||||
*/
|
||||
function convertUnit(
|
||||
value: number,
|
||||
fromUnit?: string,
|
||||
toUnit?: string,
|
||||
): number | null {
|
||||
if (!fromUnit || !toUnit) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fromCategory = getCategoryName(fromUnit);
|
||||
const toCategory = getCategoryName(toUnit);
|
||||
|
||||
if (!fromCategory || !toCategory || fromCategory !== toCategory) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return convertValue(value, fromUnit, toUnit);
|
||||
}
|
||||
|
||||
function evaluateCondition(
|
||||
operator: ThresholdComparisonOperator | undefined,
|
||||
value: number,
|
||||
thresholdValue: number,
|
||||
): boolean {
|
||||
switch (operator) {
|
||||
case '>':
|
||||
return value > thresholdValue;
|
||||
case '<':
|
||||
return value < thresholdValue;
|
||||
case '>=':
|
||||
return value >= thresholdValue;
|
||||
case '<=':
|
||||
return value <= thresholdValue;
|
||||
case '=':
|
||||
return value === thresholdValue;
|
||||
case '!=':
|
||||
return value !== thresholdValue;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `value` (expressed in `panelUnit`) satisfies `threshold`. When the
|
||||
* threshold declares its own unit, the panel value is converted into that unit
|
||||
* before comparing; if the conversion is invalid we compare the raw value.
|
||||
*/
|
||||
export function doesValueMatchThreshold(
|
||||
value: number,
|
||||
threshold: PanelThreshold,
|
||||
panelUnit?: string,
|
||||
): boolean {
|
||||
if (threshold.operator === undefined) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const convertedValue = convertUnit(value, panelUnit, threshold.unit);
|
||||
const comparable = convertedValue ?? value;
|
||||
|
||||
return evaluateCondition(threshold.operator, comparable, threshold.value);
|
||||
}
|
||||
|
||||
export interface ActiveThreshold {
|
||||
/** The matched threshold to apply, or null when none match. */
|
||||
threshold: PanelThreshold | null;
|
||||
/** True when more than one threshold matched the value. */
|
||||
isConflicting: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the threshold to apply for `value`. Among matching thresholds the
|
||||
* one declared earliest (lowest index) wins, mirroring V1 precedence; a match
|
||||
* count greater than one flags a conflict.
|
||||
*/
|
||||
export function resolveActiveThreshold(
|
||||
thresholds: PanelThreshold[],
|
||||
value: number,
|
||||
panelUnit?: string,
|
||||
): ActiveThreshold {
|
||||
const matching = thresholds.filter((threshold) =>
|
||||
doesValueMatchThreshold(value, threshold, panelUnit),
|
||||
);
|
||||
|
||||
if (matching.length === 0) {
|
||||
return { threshold: null, isConflicting: false };
|
||||
}
|
||||
|
||||
const highestPrecedence = matching.reduce((winner, candidate) =>
|
||||
thresholds.indexOf(candidate) < thresholds.indexOf(winner)
|
||||
? candidate
|
||||
: winner,
|
||||
);
|
||||
|
||||
return { threshold: highestPrecedence, isConflicting: matching.length > 1 };
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { PrecisionOption } from 'components/Graph/types';
|
||||
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
|
||||
|
||||
/**
|
||||
* Formats a scalar for display in a V2 panel, honoring the configured decimal
|
||||
* precision. The shared, unit-aware `getYAxisFormattedValue` is the single
|
||||
* formatting helper across V2 panels (number/table/list/pie); this wrapper is
|
||||
* the only seam through which panels touch it.
|
||||
*
|
||||
* Precision is applied REGARDLESS of whether a unit is set. When no unit is
|
||||
* configured we format through the `'none'` unit, which still respects
|
||||
* precision — this is the fix for decimal precision being silently dropped on
|
||||
* unitless panels (the old `unit ? format() : value.toString()` gate threw the
|
||||
* precision away whenever the unit was empty).
|
||||
*/
|
||||
export function formatPanelValue(
|
||||
value: number,
|
||||
unit?: string,
|
||||
precision?: PrecisionOption,
|
||||
): string {
|
||||
return getYAxisFormattedValue(String(value), unit || 'none', precision);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { DashboardtypesQueryDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { BuilderQuery } from 'types/api/v5/queryRange';
|
||||
|
||||
/**
|
||||
* Flattens a panel's queries into the list of builder queries it contains —
|
||||
* unwrapping `CompositeQuery` envelopes along the way. Non-builder kinds
|
||||
* (PromQL, ClickHouseSQL, Formula, TraceOperator) are dropped: they don't
|
||||
* carry the legend / groupBy / aggregation context downstream code needs.
|
||||
*
|
||||
* Returns the generated v5 `BuilderQuery` shape directly — no intermediate
|
||||
* summary type — so callers consume the same type the wire format defines.
|
||||
*/
|
||||
export function getBuilderQueries(
|
||||
queries: DashboardtypesQueryDTO[] | null | undefined,
|
||||
): BuilderQuery[] {
|
||||
if (!queries) {
|
||||
return [];
|
||||
}
|
||||
const flattened: BuilderQuery[] = [];
|
||||
queries.forEach((envelope) => {
|
||||
const plugin = envelope?.spec?.plugin;
|
||||
if (!plugin) {
|
||||
return;
|
||||
}
|
||||
if (plugin.kind === 'signoz/BuilderQuery') {
|
||||
flattened.push(plugin.spec as BuilderQuery);
|
||||
return;
|
||||
}
|
||||
if (plugin.kind === 'signoz/CompositeQuery') {
|
||||
(plugin.spec.queries ?? []).forEach((sub) => {
|
||||
if (sub.type === 'builder_query') {
|
||||
flattened.push(sub.spec as BuilderQuery);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
return flattened;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface ParsedFormattedValue {
|
||||
/** The numeric portion (e.g. "295.43", "1.2K"). */
|
||||
numericValue: string;
|
||||
/** A leading unit symbol such as a currency prefix, if any. */
|
||||
prefixUnit: string;
|
||||
/** A trailing unit label such as "ms" or "MB", if any. */
|
||||
suffixUnit: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a formatted value string (e.g. "$ 1.2K", "295.43 ms") into its
|
||||
* numeric core and any prefix/suffix unit so each part can be styled
|
||||
* independently. Falls back to treating the whole string as the numeric value
|
||||
* when it doesn't match the expected shape.
|
||||
*/
|
||||
export function parseFormattedValue(value: string): ParsedFormattedValue {
|
||||
const matches = value.match(
|
||||
/^([^\d.]*)?([\d.]+(?:[eE][+-]?[\d]+)?[KMB]?)([^\d.]*)?$/,
|
||||
);
|
||||
|
||||
return {
|
||||
numericValue: matches?.[2] || value,
|
||||
prefixUnit: matches?.[1]?.trim() || '',
|
||||
suffixUnit: matches?.[3]?.trim() || '',
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user