mirror of
https://github.com/SigNoz/signoz.git
synced 2026-04-14 07:50:28 +01:00
Compare commits
17 Commits
infraM/v2_
...
refactor/t
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d8c8e3d7d | ||
|
|
5eae936ab4 | ||
|
|
091d61045a | ||
|
|
ed1217e5d0 | ||
|
|
0389b46836 | ||
|
|
284d6f72d4 | ||
|
|
66abfa3be4 | ||
|
|
64be13db85 | ||
|
|
349b98c073 | ||
|
|
19f079dc82 | ||
|
|
926bf1d6e2 | ||
|
|
e19b9e689d | ||
|
|
70b08112f8 | ||
|
|
72ce8768b3 | ||
|
|
7c1fe82043 | ||
|
|
d4dbbceab7 | ||
|
|
918cf4dfe5 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -51,6 +51,8 @@ ee/query-service/tests/test-deploy/data/
|
||||
# local data
|
||||
*.backup
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
**/db
|
||||
/deploy/docker/clickhouse-setup/data/
|
||||
/deploy/docker-swarm/clickhouse-setup/data/
|
||||
|
||||
@@ -190,7 +190,7 @@ services:
|
||||
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
|
||||
signoz:
|
||||
!!merge <<: *db-depend
|
||||
image: signoz/signoz:v0.117.1
|
||||
image: signoz/signoz:v0.118.0
|
||||
ports:
|
||||
- "8080:8080" # signoz port
|
||||
# - "6060:6060" # pprof port
|
||||
|
||||
@@ -117,7 +117,7 @@ services:
|
||||
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
|
||||
signoz:
|
||||
!!merge <<: *db-depend
|
||||
image: signoz/signoz:v0.117.1
|
||||
image: signoz/signoz:v0.118.0
|
||||
ports:
|
||||
- "8080:8080" # signoz port
|
||||
volumes:
|
||||
|
||||
@@ -181,7 +181,7 @@ services:
|
||||
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
|
||||
signoz:
|
||||
!!merge <<: *db-depend
|
||||
image: signoz/signoz:${VERSION:-v0.117.1}
|
||||
image: signoz/signoz:${VERSION:-v0.118.0}
|
||||
container_name: signoz
|
||||
ports:
|
||||
- "8080:8080" # signoz port
|
||||
|
||||
@@ -109,7 +109,7 @@ services:
|
||||
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
|
||||
signoz:
|
||||
!!merge <<: *db-depend
|
||||
image: signoz/signoz:${VERSION:-v0.117.1}
|
||||
image: signoz/signoz:${VERSION:-v0.118.0}
|
||||
container_name: signoz
|
||||
ports:
|
||||
- "8080:8080" # signoz port
|
||||
|
||||
@@ -1098,148 +1098,6 @@ components:
|
||||
enabled:
|
||||
type: boolean
|
||||
type: object
|
||||
InframonitoringtypesHostRecord:
|
||||
properties:
|
||||
cpu:
|
||||
format: double
|
||||
type: number
|
||||
diskUsage:
|
||||
format: double
|
||||
type: number
|
||||
hostName:
|
||||
type: string
|
||||
load15:
|
||||
format: double
|
||||
type: number
|
||||
memory:
|
||||
format: double
|
||||
type: number
|
||||
meta:
|
||||
additionalProperties: {}
|
||||
nullable: true
|
||||
type: object
|
||||
status:
|
||||
type: string
|
||||
wait:
|
||||
format: double
|
||||
type: number
|
||||
type: object
|
||||
InframonitoringtypesHostStatus:
|
||||
enum:
|
||||
- active
|
||||
- inactive
|
||||
- ""
|
||||
type: string
|
||||
InframonitoringtypesHostsListRequest:
|
||||
properties:
|
||||
end:
|
||||
format: int64
|
||||
type: integer
|
||||
filter:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5Filter'
|
||||
filterByStatus:
|
||||
$ref: '#/components/schemas/InframonitoringtypesHostStatus'
|
||||
groupBy:
|
||||
items:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5GroupByKey'
|
||||
nullable: true
|
||||
type: array
|
||||
limit:
|
||||
type: integer
|
||||
offset:
|
||||
type: integer
|
||||
orderBy:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5OrderBy'
|
||||
start:
|
||||
format: int64
|
||||
type: integer
|
||||
type: object
|
||||
InframonitoringtypesHostsListResponse:
|
||||
properties:
|
||||
endTimeBeforeRetention:
|
||||
type: boolean
|
||||
records:
|
||||
items:
|
||||
$ref: '#/components/schemas/InframonitoringtypesHostRecord'
|
||||
nullable: true
|
||||
type: array
|
||||
sentAnyMetricsData:
|
||||
type: boolean
|
||||
total:
|
||||
type: integer
|
||||
type:
|
||||
type: string
|
||||
type: object
|
||||
InframonitoringtypesPodRecord:
|
||||
properties:
|
||||
meta:
|
||||
additionalProperties: {}
|
||||
nullable: true
|
||||
type: object
|
||||
podAge:
|
||||
format: int64
|
||||
type: integer
|
||||
podCPU:
|
||||
format: double
|
||||
type: number
|
||||
podCPULimit:
|
||||
format: double
|
||||
type: number
|
||||
podCPURequest:
|
||||
format: double
|
||||
type: number
|
||||
podMemory:
|
||||
format: double
|
||||
type: number
|
||||
podMemoryLimit:
|
||||
format: double
|
||||
type: number
|
||||
podMemoryRequest:
|
||||
format: double
|
||||
type: number
|
||||
podPhase:
|
||||
type: string
|
||||
podUID:
|
||||
type: string
|
||||
type: object
|
||||
InframonitoringtypesPodsListRequest:
|
||||
properties:
|
||||
end:
|
||||
format: int64
|
||||
type: integer
|
||||
filter:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5Filter'
|
||||
groupBy:
|
||||
items:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5GroupByKey'
|
||||
nullable: true
|
||||
type: array
|
||||
limit:
|
||||
type: integer
|
||||
offset:
|
||||
type: integer
|
||||
orderBy:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5OrderBy'
|
||||
start:
|
||||
format: int64
|
||||
type: integer
|
||||
type: object
|
||||
InframonitoringtypesPodsListResponse:
|
||||
properties:
|
||||
endTimeBeforeRetention:
|
||||
type: boolean
|
||||
records:
|
||||
items:
|
||||
$ref: '#/components/schemas/InframonitoringtypesPodRecord'
|
||||
nullable: true
|
||||
type: array
|
||||
sentAnyMetricsData:
|
||||
type: boolean
|
||||
total:
|
||||
type: integer
|
||||
type:
|
||||
type: string
|
||||
type: object
|
||||
MetricsexplorertypesInspectMetricsRequest:
|
||||
properties:
|
||||
end:
|
||||
@@ -7322,122 +7180,6 @@ paths:
|
||||
summary: Health check
|
||||
tags:
|
||||
- health
|
||||
/api/v2/infra-monitoring/hosts/list:
|
||||
post:
|
||||
deprecated: false
|
||||
description: This endpoint returns a list of hosts along with other information
|
||||
for each of them
|
||||
operationId: HostsList
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/InframonitoringtypesHostsListRequest'
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
$ref: '#/components/schemas/InframonitoringtypesHostsListResponse'
|
||||
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 Hosts for Infra Monitoring
|
||||
tags:
|
||||
- infra-monitoring
|
||||
/api/v2/infra-monitoring/pods/list:
|
||||
post:
|
||||
deprecated: false
|
||||
description: This endpoint returns a list of pods along with metrics and metadata
|
||||
for each of them
|
||||
operationId: PodsList
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/InframonitoringtypesPodsListRequest'
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
$ref: '#/components/schemas/InframonitoringtypesPodsListResponse'
|
||||
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 Pods for Infra Monitoring
|
||||
tags:
|
||||
- infra-monitoring
|
||||
/api/v2/livez:
|
||||
get:
|
||||
deprecated: false
|
||||
|
||||
@@ -49,7 +49,6 @@ func NewAnomalyRule(
|
||||
logger *slog.Logger,
|
||||
opts ...baserules.RuleOption,
|
||||
) (*AnomalyRule, error) {
|
||||
|
||||
logger.Info("creating new AnomalyRule", slog.String("rule.id", id))
|
||||
|
||||
opts = append(opts, baserules.WithLogger(logger))
|
||||
@@ -59,44 +58,44 @@ func NewAnomalyRule(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
t := AnomalyRule{
|
||||
r := AnomalyRule{
|
||||
BaseRule: baseRule,
|
||||
querier: querier,
|
||||
version: p.Version,
|
||||
logger: logger.With(slog.String("rule.id", id)),
|
||||
}
|
||||
|
||||
switch p.RuleCondition.Seasonality {
|
||||
case ruletypes.SeasonalityHourly:
|
||||
t.seasonality = anomaly.SeasonalityHourly
|
||||
r.seasonality = anomaly.SeasonalityHourly
|
||||
case ruletypes.SeasonalityDaily:
|
||||
t.seasonality = anomaly.SeasonalityDaily
|
||||
r.seasonality = anomaly.SeasonalityDaily
|
||||
case ruletypes.SeasonalityWeekly:
|
||||
t.seasonality = anomaly.SeasonalityWeekly
|
||||
r.seasonality = anomaly.SeasonalityWeekly
|
||||
default:
|
||||
t.seasonality = anomaly.SeasonalityDaily
|
||||
r.seasonality = anomaly.SeasonalityDaily
|
||||
}
|
||||
|
||||
logger.Info("using seasonality", slog.String("rule.id", id), slog.String("rule.seasonality", t.seasonality.StringValue()))
|
||||
r.logger.Info("using seasonality", slog.String("rule.seasonality", r.seasonality.StringValue()))
|
||||
|
||||
if t.seasonality == anomaly.SeasonalityHourly {
|
||||
t.provider = anomaly.NewHourlyProvider(
|
||||
if r.seasonality == anomaly.SeasonalityHourly {
|
||||
r.provider = anomaly.NewHourlyProvider(
|
||||
anomaly.WithQuerier[*anomaly.HourlyProvider](querier),
|
||||
anomaly.WithLogger[*anomaly.HourlyProvider](logger),
|
||||
anomaly.WithLogger[*anomaly.HourlyProvider](r.logger),
|
||||
)
|
||||
} else if t.seasonality == anomaly.SeasonalityDaily {
|
||||
t.provider = anomaly.NewDailyProvider(
|
||||
} else if r.seasonality == anomaly.SeasonalityDaily {
|
||||
r.provider = anomaly.NewDailyProvider(
|
||||
anomaly.WithQuerier[*anomaly.DailyProvider](querier),
|
||||
anomaly.WithLogger[*anomaly.DailyProvider](logger),
|
||||
anomaly.WithLogger[*anomaly.DailyProvider](r.logger),
|
||||
)
|
||||
} else if t.seasonality == anomaly.SeasonalityWeekly {
|
||||
t.provider = anomaly.NewWeeklyProvider(
|
||||
} else if r.seasonality == anomaly.SeasonalityWeekly {
|
||||
r.provider = anomaly.NewWeeklyProvider(
|
||||
anomaly.WithQuerier[*anomaly.WeeklyProvider](querier),
|
||||
anomaly.WithLogger[*anomaly.WeeklyProvider](logger),
|
||||
anomaly.WithLogger[*anomaly.WeeklyProvider](r.logger),
|
||||
)
|
||||
}
|
||||
|
||||
t.querier = querier
|
||||
t.version = p.Version
|
||||
t.logger = logger
|
||||
return &t, nil
|
||||
return &r, nil
|
||||
}
|
||||
|
||||
func (r *AnomalyRule) Type() ruletypes.RuleType {
|
||||
@@ -104,8 +103,11 @@ func (r *AnomalyRule) Type() ruletypes.RuleType {
|
||||
}
|
||||
|
||||
func (r *AnomalyRule) prepareQueryRange(ctx context.Context, ts time.Time) *qbtypes.QueryRangeRequest {
|
||||
|
||||
r.logger.InfoContext(ctx, "prepare query range request", slog.String("rule.id", r.ID()), slog.Int64("ts", ts.UnixMilli()), slog.Int64("eval.window_ms", r.EvalWindow().Milliseconds()), slog.Int64("eval.delay_ms", r.EvalDelay().Milliseconds()))
|
||||
r.logger.InfoContext(
|
||||
ctx, "prepare query range request", slog.Int64("ts", ts.UnixMilli()),
|
||||
slog.Int64("eval.window_ms", r.EvalWindow().Milliseconds()),
|
||||
slog.Int64("eval.delay_ms", r.EvalDelay().Milliseconds()),
|
||||
)
|
||||
|
||||
startTs, endTs := r.Timestamps(ts)
|
||||
start, end := startTs.UnixMilli(), endTs.UnixMilli()
|
||||
@@ -145,7 +147,7 @@ func (r *AnomalyRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID, t
|
||||
}
|
||||
|
||||
if queryResult == nil {
|
||||
r.logger.WarnContext(ctx, "nil qb result", slog.String("rule.id", r.ID()), slog.Int64("ts", ts.UnixMilli()))
|
||||
r.logger.WarnContext(ctx, "nil qb result", slog.Int64("ts", ts.UnixMilli()))
|
||||
return ruletypes.Vector{}, nil
|
||||
}
|
||||
|
||||
@@ -156,7 +158,7 @@ func (r *AnomalyRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID, t
|
||||
if missingDataAlert := r.HandleMissingDataAlert(ctx, ts, hasData); missingDataAlert != nil {
|
||||
return ruletypes.Vector{*missingDataAlert}, nil
|
||||
} else if !hasData {
|
||||
r.logger.WarnContext(ctx, "no anomaly result", slog.String("rule.id", r.ID()))
|
||||
r.logger.WarnContext(ctx, "no anomaly result")
|
||||
return ruletypes.Vector{}, nil
|
||||
}
|
||||
|
||||
@@ -164,7 +166,7 @@ func (r *AnomalyRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID, t
|
||||
|
||||
scoresJSON, _ := json.Marshal(queryResult.Aggregations[0].AnomalyScores)
|
||||
// TODO(srikanthccv): this could be noisy but we do this to answer false alert requests
|
||||
r.logger.InfoContext(ctx, "anomaly scores", slog.String("rule.id", r.ID()), slog.String("anomaly.scores", string(scoresJSON)))
|
||||
r.logger.InfoContext(ctx, "anomaly scores", slog.String("anomaly.scores", string(scoresJSON)))
|
||||
|
||||
// Filter out new series if newGroupEvalDelay is configured
|
||||
seriesToProcess := queryResult.Aggregations[0].AnomalyScores
|
||||
@@ -172,7 +174,7 @@ func (r *AnomalyRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID, t
|
||||
filteredSeries, filterErr := r.BaseRule.FilterNewSeries(ctx, ts, seriesToProcess)
|
||||
// In case of error we log the error and continue with the original series
|
||||
if filterErr != nil {
|
||||
r.logger.ErrorContext(ctx, "error filtering new series", slog.String("rule.id", r.ID()), errors.Attr(filterErr))
|
||||
r.logger.ErrorContext(ctx, "error filtering new series", errors.Attr(filterErr))
|
||||
} else {
|
||||
seriesToProcess = filteredSeries
|
||||
}
|
||||
@@ -180,7 +182,11 @@ func (r *AnomalyRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID, t
|
||||
|
||||
for _, series := range seriesToProcess {
|
||||
if !r.Condition().ShouldEval(series) {
|
||||
r.logger.InfoContext(ctx, "not enough data points to evaluate series, skipping", slog.String("rule.id", r.ID()), slog.Int("series.num_points", len(series.Values)), slog.Int("series.required_points", r.Condition().RequiredNumPoints))
|
||||
r.logger.InfoContext(
|
||||
ctx, "not enough data points to evaluate series, skipping",
|
||||
slog.Int("series.num_points", len(series.Values)),
|
||||
slog.Int("series.required_points", r.Condition().RequiredNumPoints),
|
||||
)
|
||||
continue
|
||||
}
|
||||
results, err := r.Threshold.Eval(series, r.Unit(), ruletypes.EvalData{
|
||||
@@ -204,7 +210,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
var res ruletypes.Vector
|
||||
var err error
|
||||
|
||||
r.logger.InfoContext(ctx, "running query", slog.String("rule.id", r.ID()))
|
||||
r.logger.InfoContext(ctx, "running query")
|
||||
res, err = r.buildAndRunQuery(ctx, r.OrgID(), ts)
|
||||
|
||||
if err != nil {
|
||||
@@ -230,7 +236,10 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
}
|
||||
value := valueFormatter.Format(smpl.V, r.Unit())
|
||||
threshold := valueFormatter.Format(smpl.Target, smpl.TargetUnit)
|
||||
r.logger.DebugContext(ctx, "alert template data for rule", slog.String("rule.id", r.ID()), slog.String("formatter.name", valueFormatter.Name()), slog.String("alert.value", value), slog.String("alert.threshold", threshold))
|
||||
r.logger.DebugContext(
|
||||
ctx, "alert template data for rule", slog.String("formatter.name", valueFormatter.Name()),
|
||||
slog.String("alert.value", value), slog.String("alert.threshold", threshold),
|
||||
)
|
||||
|
||||
tmplData := ruletypes.AlertTemplateData(l, value, threshold)
|
||||
// Inject some convenience variables that are easier to remember for users
|
||||
@@ -250,7 +259,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
result, err := tmpl.Expand()
|
||||
if err != nil {
|
||||
result = fmt.Sprintf("<error expanding template: %s>", err)
|
||||
r.logger.ErrorContext(ctx, "expanding alert template failed", slog.String("rule.id", r.ID()), errors.Attr(err), slog.Any("alert.template_data", tmplData))
|
||||
r.logger.ErrorContext(ctx, "expanding alert template failed", errors.Attr(err), slog.Any("alert.template_data", tmplData))
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -280,7 +289,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
resultFPs[h] = struct{}{}
|
||||
|
||||
if _, ok := alerts[h]; ok {
|
||||
r.logger.ErrorContext(ctx, "the alert query returns duplicate records", slog.String("rule.id", r.ID()), slog.Any("alert", alerts[h]))
|
||||
r.logger.ErrorContext(ctx, "the alert query returns duplicate records", slog.Any("alert", alerts[h]))
|
||||
err = errors.NewInternalf(errors.CodeInternal, "duplicate alert found, vector contains metrics with the same labelset after applying alert labels")
|
||||
return 0, err
|
||||
}
|
||||
@@ -299,7 +308,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
}
|
||||
}
|
||||
|
||||
r.logger.InfoContext(ctx, "number of alerts found", slog.String("rule.id", r.ID()), slog.Int("alert.count", len(alerts)))
|
||||
r.logger.InfoContext(ctx, "number of alerts found", slog.Int("alert.count", len(alerts)))
|
||||
// alerts[h] is ready, add or update active list now
|
||||
for h, a := range alerts {
|
||||
// Check whether we already have alerting state for the identifying label set.
|
||||
@@ -326,7 +335,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
for fp, a := range r.Active {
|
||||
labelsJSON, err := json.Marshal(a.QueryResultLabels)
|
||||
if err != nil {
|
||||
r.logger.ErrorContext(ctx, "error marshaling labels", slog.String("rule.id", r.ID()), errors.Attr(err), slog.Any("alert.labels", a.Labels))
|
||||
r.logger.ErrorContext(ctx, "error marshaling labels", errors.Attr(err), slog.Any("alert.labels", a.Labels))
|
||||
}
|
||||
if _, ok := resultFPs[fp]; !ok {
|
||||
// If the alert was previously firing, keep it around for a given
|
||||
@@ -381,7 +390,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
state = ruletypes.StateFiring
|
||||
}
|
||||
a.State = state
|
||||
r.logger.DebugContext(ctx, "converting alert state", slog.String("rule.id", r.ID()), slog.Any("alert.state", state))
|
||||
r.logger.DebugContext(ctx, "converting alert state", slog.Any("alert.state", state))
|
||||
itemsToAdd = append(itemsToAdd, rulestatehistorytypes.RuleStateHistory{
|
||||
RuleID: r.ID(),
|
||||
RuleName: r.Name(),
|
||||
@@ -404,7 +413,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
itemsToAdd[idx] = item
|
||||
}
|
||||
|
||||
r.RecordRuleStateHistory(ctx, prevState, currentState, itemsToAdd)
|
||||
_ = r.RecordRuleStateHistory(ctx, itemsToAdd)
|
||||
|
||||
return len(r.Active), nil
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReactChild, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { ReactChild, useCallback, useMemo } from 'react';
|
||||
import { matchPath, Redirect, useLocation } from 'react-router-dom';
|
||||
import getLocalStorageApi from 'api/browser/localstorage/get';
|
||||
import setLocalStorageApi from 'api/browser/localstorage/set';
|
||||
@@ -8,12 +8,10 @@ import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { ORG_PREFERENCES } from 'constants/orgPreferences';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import history from 'lib/history';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
|
||||
import { OrgPreference } from 'types/api/preferences/preference';
|
||||
import { Organization } from 'types/api/user/getOrganization';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { routePermission } from 'utils/permission';
|
||||
|
||||
@@ -25,6 +23,7 @@ import routes, {
|
||||
SUPPORT_ROUTE,
|
||||
} from './routes';
|
||||
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
const location = useLocation();
|
||||
const { pathname } = location;
|
||||
@@ -57,7 +56,12 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
const currentRoute = mapRoutes.get('current');
|
||||
const { isCloudUser: isCloudUserVal } = useGetTenantLicense();
|
||||
|
||||
const [orgData, setOrgData] = useState<Organization | undefined>(undefined);
|
||||
const orgData = useMemo(() => {
|
||||
if (org && org.length > 0 && org[0].id !== undefined) {
|
||||
return org[0];
|
||||
}
|
||||
return undefined;
|
||||
}, [org]);
|
||||
|
||||
const { data: usersData, isFetching: isFetchingUsers } = useListUsers({
|
||||
query: {
|
||||
@@ -75,214 +79,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
return remainingUsers.length === 1;
|
||||
}, [usersData?.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
isCloudUserVal &&
|
||||
!isFetchingOrgPreferences &&
|
||||
orgPreferences &&
|
||||
!isFetchingUsers &&
|
||||
usersData &&
|
||||
usersData.data
|
||||
) {
|
||||
const isOnboardingComplete = orgPreferences?.find(
|
||||
(preference: OrgPreference) =>
|
||||
preference.name === ORG_PREFERENCES.ORG_ONBOARDING,
|
||||
)?.value;
|
||||
|
||||
// Don't redirect to onboarding if workspace has issues (blocked, suspended, or restricted)
|
||||
// User needs access to settings/billing to fix payment issues
|
||||
const isWorkspaceBlocked = trialInfo?.workSpaceBlock;
|
||||
const isWorkspaceSuspended = activeLicense?.state === LicenseState.DEFAULTED;
|
||||
const isWorkspaceAccessRestricted =
|
||||
activeLicense?.state === LicenseState.TERMINATED ||
|
||||
activeLicense?.state === LicenseState.EXPIRED ||
|
||||
activeLicense?.state === LicenseState.CANCELLED;
|
||||
|
||||
const hasWorkspaceIssue =
|
||||
isWorkspaceBlocked || isWorkspaceSuspended || isWorkspaceAccessRestricted;
|
||||
|
||||
if (hasWorkspaceIssue) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isFirstUser = checkFirstTimeUser();
|
||||
if (
|
||||
isFirstUser &&
|
||||
!isOnboardingComplete &&
|
||||
// if the current route is allowed to be overriden by org onboarding then only do the same
|
||||
!ROUTES_NOT_TO_BE_OVERRIDEN.includes(pathname)
|
||||
) {
|
||||
history.push(ROUTES.ONBOARDING);
|
||||
}
|
||||
}
|
||||
}, [
|
||||
checkFirstTimeUser,
|
||||
isCloudUserVal,
|
||||
isFetchingOrgPreferences,
|
||||
isFetchingUsers,
|
||||
orgPreferences,
|
||||
usersData,
|
||||
pathname,
|
||||
trialInfo?.workSpaceBlock,
|
||||
activeLicense?.state,
|
||||
]);
|
||||
|
||||
const navigateToWorkSpaceBlocked = useCallback((): void => {
|
||||
const isRouteEnabledForWorkspaceBlockedState =
|
||||
isAdmin &&
|
||||
(pathname === ROUTES.SETTINGS ||
|
||||
pathname === ROUTES.ORG_SETTINGS ||
|
||||
pathname === ROUTES.MEMBERS_SETTINGS ||
|
||||
pathname === ROUTES.BILLING ||
|
||||
pathname === ROUTES.MY_SETTINGS);
|
||||
|
||||
if (
|
||||
pathname &&
|
||||
pathname !== ROUTES.WORKSPACE_LOCKED &&
|
||||
!isRouteEnabledForWorkspaceBlockedState
|
||||
) {
|
||||
history.push(ROUTES.WORKSPACE_LOCKED);
|
||||
}
|
||||
}, [isAdmin, pathname]);
|
||||
|
||||
const navigateToWorkSpaceAccessRestricted = useCallback((): void => {
|
||||
if (pathname && pathname !== ROUTES.WORKSPACE_ACCESS_RESTRICTED) {
|
||||
history.push(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
}
|
||||
}, [pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isFetchingActiveLicense && activeLicense) {
|
||||
const isTerminated = activeLicense.state === LicenseState.TERMINATED;
|
||||
const isExpired = activeLicense.state === LicenseState.EXPIRED;
|
||||
const isCancelled = activeLicense.state === LicenseState.CANCELLED;
|
||||
|
||||
const isWorkspaceAccessRestricted = isTerminated || isExpired || isCancelled;
|
||||
|
||||
const { platform } = activeLicense;
|
||||
|
||||
if (isWorkspaceAccessRestricted && platform === LicensePlatform.CLOUD) {
|
||||
navigateToWorkSpaceAccessRestricted();
|
||||
}
|
||||
}
|
||||
}, [
|
||||
isFetchingActiveLicense,
|
||||
activeLicense,
|
||||
navigateToWorkSpaceAccessRestricted,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isFetchingActiveLicense) {
|
||||
const shouldBlockWorkspace = trialInfo?.workSpaceBlock;
|
||||
|
||||
if (
|
||||
shouldBlockWorkspace &&
|
||||
activeLicense?.platform === LicensePlatform.CLOUD
|
||||
) {
|
||||
navigateToWorkSpaceBlocked();
|
||||
}
|
||||
}
|
||||
}, [
|
||||
isFetchingActiveLicense,
|
||||
trialInfo?.workSpaceBlock,
|
||||
activeLicense?.platform,
|
||||
navigateToWorkSpaceBlocked,
|
||||
]);
|
||||
|
||||
const navigateToWorkSpaceSuspended = useCallback((): void => {
|
||||
if (pathname && pathname !== ROUTES.WORKSPACE_SUSPENDED) {
|
||||
history.push(ROUTES.WORKSPACE_SUSPENDED);
|
||||
}
|
||||
}, [pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isFetchingActiveLicense && activeLicense) {
|
||||
const shouldSuspendWorkspace =
|
||||
activeLicense.state === LicenseState.DEFAULTED;
|
||||
|
||||
if (
|
||||
shouldSuspendWorkspace &&
|
||||
activeLicense.platform === LicensePlatform.CLOUD
|
||||
) {
|
||||
navigateToWorkSpaceSuspended();
|
||||
}
|
||||
}
|
||||
}, [isFetchingActiveLicense, activeLicense, navigateToWorkSpaceSuspended]);
|
||||
|
||||
useEffect(() => {
|
||||
if (org && org.length > 0 && org[0].id !== undefined) {
|
||||
setOrgData(org[0]);
|
||||
}
|
||||
}, [org]);
|
||||
|
||||
// if the feature flag is enabled and the current route is /get-started then redirect to /get-started-with-signoz-cloud
|
||||
useEffect(() => {
|
||||
if (
|
||||
currentRoute?.path === ROUTES.GET_STARTED &&
|
||||
featureFlags?.find((e) => e.name === FeatureKeys.ONBOARDING_V3)?.active
|
||||
) {
|
||||
history.push(ROUTES.GET_STARTED_WITH_CLOUD);
|
||||
}
|
||||
}, [currentRoute, featureFlags]);
|
||||
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
useEffect(() => {
|
||||
// if it is an old route navigate to the new route
|
||||
if (isOldRoute) {
|
||||
// this will be handled by the redirect component below
|
||||
return;
|
||||
}
|
||||
|
||||
// if the current route is public dashboard then don't redirect to login
|
||||
const isPublicDashboard = currentRoute?.path === ROUTES.PUBLIC_DASHBOARD;
|
||||
|
||||
if (isPublicDashboard) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if the current route
|
||||
if (currentRoute) {
|
||||
const { isPrivate, key } = currentRoute;
|
||||
if (isPrivate) {
|
||||
if (isLoggedInState) {
|
||||
const route = routePermission[key];
|
||||
if (route && route.find((e) => e === user.role) === undefined) {
|
||||
history.push(ROUTES.UN_AUTHORIZED);
|
||||
}
|
||||
} else {
|
||||
setLocalStorageApi(LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT, pathname);
|
||||
history.push(ROUTES.LOGIN);
|
||||
}
|
||||
} else if (isLoggedInState) {
|
||||
const fromPathname = getLocalStorageApi(
|
||||
LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT,
|
||||
);
|
||||
if (fromPathname) {
|
||||
history.push(fromPathname);
|
||||
setLocalStorageApi(LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT, '');
|
||||
} else if (pathname !== ROUTES.SOMETHING_WENT_WRONG) {
|
||||
history.push(ROUTES.HOME);
|
||||
}
|
||||
} else {
|
||||
// do nothing as the unauthenticated routes are LOGIN and SIGNUP and the LOGIN container takes care of routing to signup if
|
||||
// setup is not completed
|
||||
}
|
||||
} else if (isLoggedInState) {
|
||||
const fromPathname = getLocalStorageApi(
|
||||
LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT,
|
||||
);
|
||||
if (fromPathname) {
|
||||
history.push(fromPathname);
|
||||
setLocalStorageApi(LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT, '');
|
||||
} else {
|
||||
history.push(ROUTES.HOME);
|
||||
}
|
||||
} else {
|
||||
setLocalStorageApi(LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT, pathname);
|
||||
history.push(ROUTES.LOGIN);
|
||||
}
|
||||
}, [isLoggedInState, pathname, user, isOldRoute, currentRoute, location]);
|
||||
|
||||
// Handle old routes - redirect to new routes
|
||||
if (isOldRoute) {
|
||||
const redirectUrl = oldNewRoutesMapping[pathname];
|
||||
return (
|
||||
@@ -296,7 +93,143 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
);
|
||||
}
|
||||
|
||||
// NOTE: disabling this rule as there is no need to have div
|
||||
// Public dashboard - no redirect needed
|
||||
const isPublicDashboard = currentRoute?.path === ROUTES.PUBLIC_DASHBOARD;
|
||||
if (isPublicDashboard) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
// Check for workspace access restriction (cloud only)
|
||||
const isCloudPlatform = activeLicense?.platform === LicensePlatform.CLOUD;
|
||||
|
||||
if (!isFetchingActiveLicense && activeLicense && isCloudPlatform) {
|
||||
const isTerminated = activeLicense.state === LicenseState.TERMINATED;
|
||||
const isExpired = activeLicense.state === LicenseState.EXPIRED;
|
||||
const isCancelled = activeLicense.state === LicenseState.CANCELLED;
|
||||
const isWorkspaceAccessRestricted = isTerminated || isExpired || isCancelled;
|
||||
|
||||
if (
|
||||
isWorkspaceAccessRestricted &&
|
||||
pathname !== ROUTES.WORKSPACE_ACCESS_RESTRICTED
|
||||
) {
|
||||
return <Redirect to={ROUTES.WORKSPACE_ACCESS_RESTRICTED} />;
|
||||
}
|
||||
|
||||
// Check for workspace suspended (DEFAULTED)
|
||||
const shouldSuspendWorkspace = activeLicense.state === LicenseState.DEFAULTED;
|
||||
if (shouldSuspendWorkspace && pathname !== ROUTES.WORKSPACE_SUSPENDED) {
|
||||
return <Redirect to={ROUTES.WORKSPACE_SUSPENDED} />;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for workspace blocked (trial expired)
|
||||
if (!isFetchingActiveLicense && isCloudPlatform && trialInfo?.workSpaceBlock) {
|
||||
const isRouteEnabledForWorkspaceBlockedState =
|
||||
isAdmin &&
|
||||
(pathname === ROUTES.SETTINGS ||
|
||||
pathname === ROUTES.ORG_SETTINGS ||
|
||||
pathname === ROUTES.MEMBERS_SETTINGS ||
|
||||
pathname === ROUTES.BILLING ||
|
||||
pathname === ROUTES.MY_SETTINGS);
|
||||
|
||||
if (
|
||||
pathname !== ROUTES.WORKSPACE_LOCKED &&
|
||||
!isRouteEnabledForWorkspaceBlockedState
|
||||
) {
|
||||
return <Redirect to={ROUTES.WORKSPACE_LOCKED} />;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for onboarding redirect (cloud users, first user, onboarding not complete)
|
||||
if (
|
||||
isCloudUserVal &&
|
||||
!isFetchingOrgPreferences &&
|
||||
orgPreferences &&
|
||||
!isFetchingUsers &&
|
||||
usersData &&
|
||||
usersData.data
|
||||
) {
|
||||
const isOnboardingComplete = orgPreferences?.find(
|
||||
(preference: OrgPreference) =>
|
||||
preference.name === ORG_PREFERENCES.ORG_ONBOARDING,
|
||||
)?.value;
|
||||
|
||||
// Don't redirect to onboarding if workspace has issues
|
||||
const isWorkspaceBlocked = trialInfo?.workSpaceBlock;
|
||||
const isWorkspaceSuspended = activeLicense?.state === LicenseState.DEFAULTED;
|
||||
const isWorkspaceAccessRestricted =
|
||||
activeLicense?.state === LicenseState.TERMINATED ||
|
||||
activeLicense?.state === LicenseState.EXPIRED ||
|
||||
activeLicense?.state === LicenseState.CANCELLED;
|
||||
|
||||
const hasWorkspaceIssue =
|
||||
isWorkspaceBlocked || isWorkspaceSuspended || isWorkspaceAccessRestricted;
|
||||
|
||||
if (!hasWorkspaceIssue) {
|
||||
const isFirstUser = checkFirstTimeUser();
|
||||
if (
|
||||
isFirstUser &&
|
||||
!isOnboardingComplete &&
|
||||
!ROUTES_NOT_TO_BE_OVERRIDEN.includes(pathname) &&
|
||||
pathname !== ROUTES.ONBOARDING
|
||||
) {
|
||||
return <Redirect to={ROUTES.ONBOARDING} />;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for GET_STARTED → GET_STARTED_WITH_CLOUD redirect (feature flag)
|
||||
if (
|
||||
currentRoute?.path === ROUTES.GET_STARTED &&
|
||||
featureFlags?.find((e) => e.name === FeatureKeys.ONBOARDING_V3)?.active
|
||||
) {
|
||||
return <Redirect to={ROUTES.GET_STARTED_WITH_CLOUD} />;
|
||||
}
|
||||
|
||||
// Main routing logic
|
||||
if (currentRoute) {
|
||||
const { isPrivate, key } = currentRoute;
|
||||
if (isPrivate) {
|
||||
if (isLoggedInState) {
|
||||
const route = routePermission[key];
|
||||
if (route && route.find((e) => e === user.role) === undefined) {
|
||||
return <Redirect to={ROUTES.UN_AUTHORIZED} />;
|
||||
}
|
||||
} else {
|
||||
// Save current path and redirect to login
|
||||
setLocalStorageApi(LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT, pathname);
|
||||
return <Redirect to={ROUTES.LOGIN} />;
|
||||
}
|
||||
} else if (isLoggedInState) {
|
||||
// Non-private route, but user is logged in
|
||||
const fromPathname = getLocalStorageApi(
|
||||
LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT,
|
||||
);
|
||||
if (fromPathname) {
|
||||
setLocalStorageApi(LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT, '');
|
||||
return <Redirect to={fromPathname} />;
|
||||
}
|
||||
if (pathname !== ROUTES.SOMETHING_WENT_WRONG) {
|
||||
return <Redirect to={ROUTES.HOME} />;
|
||||
}
|
||||
}
|
||||
// Non-private route, user not logged in - let login/signup pages handle it
|
||||
} else if (isLoggedInState) {
|
||||
// Unknown route, logged in
|
||||
const fromPathname = getLocalStorageApi(
|
||||
LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT,
|
||||
);
|
||||
if (fromPathname) {
|
||||
setLocalStorageApi(LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT, '');
|
||||
return <Redirect to={fromPathname} />;
|
||||
}
|
||||
return <Redirect to={ROUTES.HOME} />;
|
||||
} else {
|
||||
// Unknown route, not logged in
|
||||
setLocalStorageApi(LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT, pathname);
|
||||
return <Redirect to={ROUTES.LOGIN} />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import { FeatureKeys } from 'constants/features';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { ORG_PREFERENCES } from 'constants/orgPreferences';
|
||||
import ROUTES from 'constants/routes';
|
||||
import history from 'lib/history';
|
||||
import { AppContext } from 'providers/App/App';
|
||||
import { IAppContext, IUser } from 'providers/App/types';
|
||||
import {
|
||||
@@ -22,19 +21,6 @@ import { ROLES, USER_ROLES } from 'types/roles';
|
||||
|
||||
import PrivateRoute from '../Private';
|
||||
|
||||
// Mock history module
|
||||
jest.mock('lib/history', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
push: jest.fn(),
|
||||
location: { pathname: '/', search: '', hash: '' },
|
||||
listen: jest.fn(),
|
||||
createHref: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockHistoryPush = history.push as jest.Mock;
|
||||
|
||||
// Mock localStorage APIs
|
||||
const mockLocalStorage: Record<string, string> = {};
|
||||
jest.mock('api/browser/localstorage/get', () => ({
|
||||
@@ -239,20 +225,18 @@ function renderPrivateRoute(options: RenderPrivateRouteOptions = {}): void {
|
||||
}
|
||||
|
||||
// Generic assertion helpers for navigation behavior
|
||||
// Using these allows easier refactoring when switching from history.push to Redirect component
|
||||
// Using location-based assertions since Private.tsx now uses Redirect component
|
||||
|
||||
async function assertRedirectsTo(targetRoute: string): Promise<void> {
|
||||
await waitFor(() => {
|
||||
expect(mockHistoryPush).toHaveBeenCalledWith(targetRoute);
|
||||
expect(screen.getByTestId('location-display')).toHaveTextContent(targetRoute);
|
||||
});
|
||||
}
|
||||
|
||||
function assertNoRedirect(): void {
|
||||
expect(mockHistoryPush).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
function assertDoesNotRedirectTo(targetRoute: string): void {
|
||||
expect(mockHistoryPush).not.toHaveBeenCalledWith(targetRoute);
|
||||
function assertStaysOnRoute(expectedRoute: string): void {
|
||||
expect(screen.getByTestId('location-display')).toHaveTextContent(
|
||||
expectedRoute,
|
||||
);
|
||||
}
|
||||
|
||||
function assertRendersChildren(): void {
|
||||
@@ -350,7 +334,7 @@ describe('PrivateRoute', () => {
|
||||
});
|
||||
|
||||
assertRendersChildren();
|
||||
assertNoRedirect();
|
||||
assertStaysOnRoute('/public/dashboard/abc123');
|
||||
});
|
||||
|
||||
it('should render children for public dashboard route when logged in without redirecting', () => {
|
||||
@@ -362,7 +346,7 @@ describe('PrivateRoute', () => {
|
||||
assertRendersChildren();
|
||||
// Critical: without the isPublicDashboard early return, logged-in users
|
||||
// would be redirected to HOME due to the non-private route handling
|
||||
assertNoRedirect();
|
||||
assertStaysOnRoute('/public/dashboard/abc123');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -420,7 +404,7 @@ describe('PrivateRoute', () => {
|
||||
});
|
||||
|
||||
assertRendersChildren();
|
||||
assertNoRedirect();
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('should redirect to unauthorized when VIEWER tries to access admin-only route /alerts/new', async () => {
|
||||
@@ -529,7 +513,7 @@ describe('PrivateRoute', () => {
|
||||
appContext: { isLoggedIn: true },
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.HOME);
|
||||
assertStaysOnRoute(ROUTES.SOMETHING_WENT_WRONG);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -541,7 +525,7 @@ describe('PrivateRoute', () => {
|
||||
});
|
||||
|
||||
// Should not redirect - login page handles its own routing
|
||||
assertNoRedirect();
|
||||
assertStaysOnRoute(ROUTES.LOGIN);
|
||||
});
|
||||
|
||||
it('should not redirect when not logged in user visits signup page', () => {
|
||||
@@ -550,7 +534,7 @@ describe('PrivateRoute', () => {
|
||||
appContext: { isLoggedIn: false },
|
||||
});
|
||||
|
||||
assertNoRedirect();
|
||||
assertStaysOnRoute(ROUTES.SIGN_UP);
|
||||
});
|
||||
|
||||
it('should not redirect when not logged in user visits password reset page', () => {
|
||||
@@ -559,7 +543,7 @@ describe('PrivateRoute', () => {
|
||||
appContext: { isLoggedIn: false },
|
||||
});
|
||||
|
||||
assertNoRedirect();
|
||||
assertStaysOnRoute(ROUTES.PASSWORD_RESET);
|
||||
});
|
||||
|
||||
it('should not redirect when not logged in user visits forgot password page', () => {
|
||||
@@ -568,7 +552,7 @@ describe('PrivateRoute', () => {
|
||||
appContext: { isLoggedIn: false },
|
||||
});
|
||||
|
||||
assertNoRedirect();
|
||||
assertStaysOnRoute(ROUTES.FORGOT_PASSWORD);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -657,7 +641,7 @@ describe('PrivateRoute', () => {
|
||||
});
|
||||
|
||||
// Admin should be able to access settings even when workspace is blocked
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.SETTINGS);
|
||||
});
|
||||
|
||||
it('should allow ADMIN to access /settings/billing when workspace is blocked', () => {
|
||||
@@ -673,7 +657,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.BILLING);
|
||||
});
|
||||
|
||||
it('should allow ADMIN to access /settings/org-settings when workspace is blocked', () => {
|
||||
@@ -689,7 +673,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
|
||||
});
|
||||
|
||||
it('should allow ADMIN to access /settings/members when workspace is blocked', () => {
|
||||
@@ -705,7 +689,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.MEMBERS_SETTINGS);
|
||||
});
|
||||
|
||||
it('should allow ADMIN to access /settings/my-settings when workspace is blocked', () => {
|
||||
@@ -721,7 +705,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.MY_SETTINGS);
|
||||
});
|
||||
|
||||
it('should redirect VIEWER to workspace locked even when trying to access settings', async () => {
|
||||
@@ -832,7 +816,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.WORKSPACE_LOCKED);
|
||||
});
|
||||
|
||||
it('should not redirect self-hosted users to workspace locked even when workSpaceBlock is true', () => {
|
||||
@@ -849,7 +833,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: false,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -919,7 +903,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
assertStaysOnRoute(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
});
|
||||
|
||||
it('should not redirect self-hosted users to workspace access restricted when license is terminated', () => {
|
||||
@@ -936,7 +920,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: false,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('should not redirect when license is ACTIVE', () => {
|
||||
@@ -953,7 +937,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('should not redirect when license is EVALUATING', () => {
|
||||
@@ -970,7 +954,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1006,7 +990,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_SUSPENDED);
|
||||
assertStaysOnRoute(ROUTES.WORKSPACE_SUSPENDED);
|
||||
});
|
||||
|
||||
it('should not redirect self-hosted users to workspace suspended when license is defaulted', () => {
|
||||
@@ -1023,7 +1007,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: false,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_SUSPENDED);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1043,6 +1027,11 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
// Wait for the users query to complete and trigger re-render
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
await assertRedirectsTo(ROUTES.ONBOARDING);
|
||||
});
|
||||
|
||||
@@ -1058,7 +1047,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when onboarding is already complete', async () => {
|
||||
@@ -1084,7 +1073,7 @@ describe('PrivateRoute', () => {
|
||||
|
||||
// Critical: if isOnboardingComplete check is broken (always false),
|
||||
// this test would fail because all other conditions for redirect ARE met
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding for non-cloud users', () => {
|
||||
@@ -1099,7 +1088,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: false,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when on /workspace-locked route', () => {
|
||||
@@ -1114,7 +1103,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
assertStaysOnRoute(ROUTES.WORKSPACE_LOCKED);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when on /workspace-suspended route', () => {
|
||||
@@ -1129,7 +1118,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
assertStaysOnRoute(ROUTES.WORKSPACE_SUSPENDED);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when workspace is blocked and accessing billing', async () => {
|
||||
@@ -1156,7 +1145,7 @@ describe('PrivateRoute', () => {
|
||||
});
|
||||
|
||||
// Should NOT redirect to onboarding - user needs to access billing to fix payment
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
assertStaysOnRoute(ROUTES.BILLING);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when workspace is blocked and accessing settings', async () => {
|
||||
@@ -1180,7 +1169,7 @@ describe('PrivateRoute', () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
assertStaysOnRoute(ROUTES.SETTINGS);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when workspace is suspended (DEFAULTED)', async () => {
|
||||
@@ -1207,7 +1196,7 @@ describe('PrivateRoute', () => {
|
||||
});
|
||||
|
||||
// Should redirect to WORKSPACE_SUSPENDED, not ONBOARDING
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_SUSPENDED);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when workspace is access restricted (TERMINATED)', async () => {
|
||||
@@ -1234,7 +1223,7 @@ describe('PrivateRoute', () => {
|
||||
});
|
||||
|
||||
// Should redirect to WORKSPACE_ACCESS_RESTRICTED, not ONBOARDING
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when workspace is access restricted (EXPIRED)', async () => {
|
||||
@@ -1260,7 +1249,7 @@ describe('PrivateRoute', () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.ONBOARDING);
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1302,7 +1291,7 @@ describe('PrivateRoute', () => {
|
||||
},
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.GET_STARTED_WITH_CLOUD);
|
||||
assertStaysOnRoute(ROUTES.GET_STARTED);
|
||||
});
|
||||
|
||||
it('should not redirect when on GET_STARTED and ONBOARDING_V3 feature flag is not present', () => {
|
||||
@@ -1314,7 +1303,7 @@ describe('PrivateRoute', () => {
|
||||
},
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.GET_STARTED_WITH_CLOUD);
|
||||
assertStaysOnRoute(ROUTES.GET_STARTED);
|
||||
});
|
||||
|
||||
it('should not redirect when on different route even if ONBOARDING_V3 is active', () => {
|
||||
@@ -1334,7 +1323,7 @@ describe('PrivateRoute', () => {
|
||||
},
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.GET_STARTED_WITH_CLOUD);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1350,7 +1339,7 @@ describe('PrivateRoute', () => {
|
||||
},
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('should not fetch users when org data is not available', () => {
|
||||
@@ -1393,9 +1382,7 @@ describe('PrivateRoute', () => {
|
||||
},
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_SUSPENDED);
|
||||
assertDoesNotRedirectTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1436,22 +1423,40 @@ describe('PrivateRoute', () => {
|
||||
await assertRedirectsTo(ROUTES.UN_AUTHORIZED);
|
||||
});
|
||||
|
||||
it('should allow all roles to access /services route', () => {
|
||||
const roles = [USER_ROLES.ADMIN, USER_ROLES.EDITOR, USER_ROLES.VIEWER];
|
||||
|
||||
roles.forEach((role) => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.APPLICATION,
|
||||
appContext: {
|
||||
isLoggedIn: true,
|
||||
user: createMockUser({ role: role as ROLES }),
|
||||
},
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.UN_AUTHORIZED);
|
||||
it('should allow ADMIN to access /services route', () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.APPLICATION,
|
||||
appContext: {
|
||||
isLoggedIn: true,
|
||||
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
|
||||
},
|
||||
});
|
||||
|
||||
assertStaysOnRoute(ROUTES.APPLICATION);
|
||||
});
|
||||
|
||||
it('should allow EDITOR to access /services route', () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.APPLICATION,
|
||||
appContext: {
|
||||
isLoggedIn: true,
|
||||
user: createMockUser({ role: USER_ROLES.EDITOR as ROLES }),
|
||||
},
|
||||
});
|
||||
|
||||
assertStaysOnRoute(ROUTES.APPLICATION);
|
||||
});
|
||||
|
||||
it('should allow VIEWER to access /services route', () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.APPLICATION,
|
||||
appContext: {
|
||||
isLoggedIn: true,
|
||||
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
|
||||
},
|
||||
});
|
||||
|
||||
assertStaysOnRoute(ROUTES.APPLICATION);
|
||||
});
|
||||
|
||||
it('should redirect VIEWER from /onboarding route (admin only)', async () => {
|
||||
@@ -1481,7 +1486,7 @@ describe('PrivateRoute', () => {
|
||||
});
|
||||
|
||||
assertRendersChildren();
|
||||
assertDoesNotRedirectTo(ROUTES.UN_AUTHORIZED);
|
||||
assertStaysOnRoute(ROUTES.CHANNELS_NEW);
|
||||
});
|
||||
|
||||
it('should allow EDITOR to access /get-started route', () => {
|
||||
@@ -1493,7 +1498,7 @@ describe('PrivateRoute', () => {
|
||||
},
|
||||
});
|
||||
|
||||
assertDoesNotRedirectTo(ROUTES.UN_AUTHORIZED);
|
||||
assertStaysOnRoute(ROUTES.GET_STARTED);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
/**
|
||||
* ! Do not edit manually
|
||||
* * The file has been auto-generated using Orval for SigNoz
|
||||
* * regenerate with 'yarn generate:api'
|
||||
* SigNoz
|
||||
*/
|
||||
import type {
|
||||
MutationFunction,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
} from 'react-query';
|
||||
import { useMutation } from 'react-query';
|
||||
|
||||
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
|
||||
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
|
||||
import type {
|
||||
HostsList200,
|
||||
InframonitoringtypesHostsListRequestDTO,
|
||||
RenderErrorResponseDTO,
|
||||
} from '../sigNoz.schemas';
|
||||
|
||||
/**
|
||||
* This endpoint returns a list of hosts along with other information for each of them
|
||||
* @summary List Hosts for Infra Monitoring
|
||||
*/
|
||||
export const hostsList = (
|
||||
inframonitoringtypesHostsListRequestDTO: BodyType<InframonitoringtypesHostsListRequestDTO>,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<HostsList200>({
|
||||
url: `/api/v2/infra-monitoring/hosts/list`,
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: inframonitoringtypesHostsListRequestDTO,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getHostsListMutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof hostsList>>,
|
||||
TError,
|
||||
{ data: BodyType<InframonitoringtypesHostsListRequestDTO> },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof hostsList>>,
|
||||
TError,
|
||||
{ data: BodyType<InframonitoringtypesHostsListRequestDTO> },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['hostsList'];
|
||||
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 hostsList>>,
|
||||
{ data: BodyType<InframonitoringtypesHostsListRequestDTO> }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return hostsList(data);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type HostsListMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof hostsList>>
|
||||
>;
|
||||
export type HostsListMutationBody = BodyType<InframonitoringtypesHostsListRequestDTO>;
|
||||
export type HostsListMutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List Hosts for Infra Monitoring
|
||||
*/
|
||||
export const useHostsList = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof hostsList>>,
|
||||
TError,
|
||||
{ data: BodyType<InframonitoringtypesHostsListRequestDTO> },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof hostsList>>,
|
||||
TError,
|
||||
{ data: BodyType<InframonitoringtypesHostsListRequestDTO> },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getHostsListMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions);
|
||||
};
|
||||
@@ -1330,112 +1330,6 @@ export interface GlobaltypesTokenizerConfigDTO {
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @nullable
|
||||
*/
|
||||
export type InframonitoringtypesHostRecordDTOMeta = {
|
||||
[key: string]: unknown;
|
||||
} | null;
|
||||
|
||||
export interface InframonitoringtypesHostRecordDTO {
|
||||
/**
|
||||
* @type number
|
||||
* @format double
|
||||
*/
|
||||
cpu?: number;
|
||||
/**
|
||||
* @type number
|
||||
* @format double
|
||||
*/
|
||||
diskUsage?: number;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
hostName?: string;
|
||||
/**
|
||||
* @type number
|
||||
* @format double
|
||||
*/
|
||||
load15?: number;
|
||||
/**
|
||||
* @type number
|
||||
* @format double
|
||||
*/
|
||||
memory?: number;
|
||||
/**
|
||||
* @type object
|
||||
* @nullable true
|
||||
*/
|
||||
meta?: InframonitoringtypesHostRecordDTOMeta;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status?: string;
|
||||
/**
|
||||
* @type number
|
||||
* @format double
|
||||
*/
|
||||
wait?: number;
|
||||
}
|
||||
|
||||
export enum InframonitoringtypesHostStatusDTO {
|
||||
active = 'active',
|
||||
inactive = 'inactive',
|
||||
'' = '',
|
||||
}
|
||||
export interface InframonitoringtypesHostsListRequestDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
*/
|
||||
end?: number;
|
||||
filter?: Querybuildertypesv5FilterDTO;
|
||||
filterByStatus?: InframonitoringtypesHostStatusDTO;
|
||||
/**
|
||||
* @type array
|
||||
* @nullable true
|
||||
*/
|
||||
groupBy?: Querybuildertypesv5GroupByKeyDTO[] | null;
|
||||
/**
|
||||
* @type integer
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* @type integer
|
||||
*/
|
||||
offset?: number;
|
||||
orderBy?: Querybuildertypesv5OrderByDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
*/
|
||||
start?: number;
|
||||
}
|
||||
|
||||
export interface InframonitoringtypesHostsListResponseDTO {
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
endTimeBeforeRetention?: boolean;
|
||||
/**
|
||||
* @type array
|
||||
* @nullable true
|
||||
*/
|
||||
records?: InframonitoringtypesHostRecordDTO[] | null;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
sentAnyMetricsData?: boolean;
|
||||
/**
|
||||
* @type integer
|
||||
*/
|
||||
total?: number;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
type?: string;
|
||||
}
|
||||
|
||||
export interface MetricsexplorertypesInspectMetricsRequestDTO {
|
||||
/**
|
||||
* @type integer
|
||||
@@ -4298,14 +4192,6 @@ export type Healthz503 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type HostsList200 = {
|
||||
data: InframonitoringtypesHostsListResponseDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type Livez200 = {
|
||||
data: FactoryResponseDTO;
|
||||
/**
|
||||
|
||||
@@ -14,6 +14,8 @@ import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schem
|
||||
import { AxiosError } from 'axios';
|
||||
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
|
||||
import { parseAsBoolean, useQueryState } from 'nuqs';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import './CreateServiceAccountModal.styles.scss';
|
||||
|
||||
@@ -28,6 +30,8 @@ function CreateServiceAccountModal(): JSX.Element {
|
||||
parseAsBoolean.withDefault(false),
|
||||
);
|
||||
|
||||
const { showErrorModal, isErrorModalVisible } = useErrorModal();
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
@@ -54,13 +58,10 @@ function CreateServiceAccountModal(): JSX.Element {
|
||||
await invalidateListServiceAccounts(queryClient);
|
||||
},
|
||||
onError: (err) => {
|
||||
const errMessage =
|
||||
convertToApiError(
|
||||
err as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
)?.getErrorMessage() || 'An error occurred';
|
||||
toast.error(`Failed to create service account: ${errMessage}`, {
|
||||
richColors: true,
|
||||
});
|
||||
const errMessage = convertToApiError(
|
||||
err as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
);
|
||||
showErrorModal(errMessage as APIError);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -90,7 +91,7 @@ function CreateServiceAccountModal(): JSX.Element {
|
||||
showCloseButton
|
||||
width="narrow"
|
||||
className="create-sa-modal"
|
||||
disableOutsideClick={false}
|
||||
disableOutsideClick={isErrorModalVisible}
|
||||
>
|
||||
<div className="create-sa-modal__content">
|
||||
<form
|
||||
|
||||
@@ -11,6 +11,16 @@ jest.mock('@signozhq/sonner', () => ({
|
||||
|
||||
const mockToast = jest.mocked(toast);
|
||||
|
||||
const showErrorModal = jest.fn();
|
||||
jest.mock('providers/ErrorModalProvider', () => ({
|
||||
__esModule: true,
|
||||
...jest.requireActual('providers/ErrorModalProvider'),
|
||||
useErrorModal: jest.fn(() => ({
|
||||
showErrorModal,
|
||||
isErrorModalVisible: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
const SERVICE_ACCOUNTS_ENDPOINT = '*/api/v1/service_accounts';
|
||||
|
||||
function renderModal(): ReturnType<typeof render> {
|
||||
@@ -92,10 +102,13 @@ describe('CreateServiceAccountModal', () => {
|
||||
await user.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast.error).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/Failed to create service account/i),
|
||||
expect.anything(),
|
||||
expect(showErrorModal).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
getErrorMessage: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
const passedError = showErrorModal.mock.calls[0][0] as any;
|
||||
expect(passedError.getErrorMessage()).toBe('Internal Server Error');
|
||||
});
|
||||
|
||||
expect(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import { Badge } from '@signozhq/badge';
|
||||
import { Button } from '@signozhq/button';
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
useMemberRoleManager,
|
||||
} from 'hooks/member/useMemberRoleManager';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import APIError from 'types/api/error';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
@@ -90,8 +91,11 @@ function EditMemberDrawer({
|
||||
const [linkType, setLinkType] = useState<'invite' | 'reset' | null>(null);
|
||||
|
||||
const isInvited = member?.status === MemberStatus.Invited;
|
||||
const isDeleted = member?.status === MemberStatus.Deleted;
|
||||
const isSelf = !!member?.id && member.id === currentUser?.id;
|
||||
|
||||
const { showErrorModal } = useErrorModal();
|
||||
|
||||
const {
|
||||
data: fetchedUser,
|
||||
isLoading: isFetchingUser,
|
||||
@@ -111,26 +115,39 @@ function EditMemberDrawer({
|
||||
refetch: refetchRoles,
|
||||
} = useRoles();
|
||||
|
||||
const { fetchedRoleIds, applyDiff } = useMemberRoleManager(
|
||||
member?.id ?? '',
|
||||
open && !!member?.id,
|
||||
);
|
||||
const {
|
||||
fetchedRoleIds,
|
||||
isLoading: isMemberRolesLoading,
|
||||
applyDiff,
|
||||
} = useMemberRoleManager(member?.id ?? '', open && !!member?.id);
|
||||
|
||||
const fetchedDisplayName =
|
||||
fetchedUser?.data?.displayName ?? member?.name ?? '';
|
||||
const fetchedUserId = fetchedUser?.data?.id;
|
||||
const fetchedUserDisplayName = fetchedUser?.data?.displayName;
|
||||
|
||||
const roleSessionRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetchedUserId) {
|
||||
setLocalDisplayName(fetchedUserDisplayName ?? member?.name ?? '');
|
||||
}
|
||||
setSaveErrors([]);
|
||||
}, [fetchedUserId, fetchedUserDisplayName, member?.name]);
|
||||
|
||||
useEffect(() => {
|
||||
setLocalRole(fetchedRoleIds[0] ?? '');
|
||||
}, [fetchedRoleIds]);
|
||||
if (fetchedUserId) {
|
||||
setSaveErrors([]);
|
||||
}
|
||||
}, [fetchedUserId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!member?.id) {
|
||||
roleSessionRef.current = null;
|
||||
} else if (member.id !== roleSessionRef.current && !isMemberRolesLoading) {
|
||||
setLocalRole(fetchedRoleIds[0] ?? '');
|
||||
roleSessionRef.current = member.id;
|
||||
}
|
||||
}, [member?.id, fetchedRoleIds, isMemberRolesLoading]);
|
||||
|
||||
const isDirty =
|
||||
member !== null &&
|
||||
@@ -153,17 +170,10 @@ function EditMemberDrawer({
|
||||
onClose();
|
||||
},
|
||||
onError: (err): void => {
|
||||
const errMessage =
|
||||
convertToApiError(
|
||||
err as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
)?.getErrorMessage() || 'An error occurred';
|
||||
const prefix = isInvited
|
||||
? 'Failed to revoke invite'
|
||||
: 'Failed to delete member';
|
||||
toast.error(`${prefix}: ${errMessage}`, {
|
||||
richColors: true,
|
||||
position: 'top-right',
|
||||
});
|
||||
const errMessage = convertToApiError(
|
||||
err as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
);
|
||||
showErrorModal(errMessage as APIError);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -344,15 +354,15 @@ function EditMemberDrawer({
|
||||
position: 'top-right',
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
toast.error('Failed to generate password reset link', {
|
||||
richColors: true,
|
||||
position: 'top-right',
|
||||
});
|
||||
} catch (err) {
|
||||
const errMsg = convertToApiError(
|
||||
err as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
);
|
||||
showErrorModal(errMsg as APIError);
|
||||
} finally {
|
||||
setIsGeneratingLink(false);
|
||||
}
|
||||
}, [member, isInvited, onClose]);
|
||||
}, [member, isInvited, onClose, showErrorModal]);
|
||||
|
||||
const [copyState, copyToClipboard] = useCopyToClipboard();
|
||||
const handleCopyResetLink = useCallback((): void => {
|
||||
@@ -419,7 +429,7 @@ function EditMemberDrawer({
|
||||
}}
|
||||
className="edit-member-drawer__input"
|
||||
placeholder="Enter name"
|
||||
disabled={isRootUser}
|
||||
disabled={isRootUser || isDeleted}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
@@ -440,9 +450,15 @@ function EditMemberDrawer({
|
||||
<label className="edit-member-drawer__label" htmlFor="member-role">
|
||||
Roles
|
||||
</label>
|
||||
{isSelf || isRootUser ? (
|
||||
{isSelf || isRootUser || isDeleted ? (
|
||||
<Tooltip
|
||||
title={isRootUser ? ROOT_USER_TOOLTIP : 'You cannot modify your own role'}
|
||||
title={
|
||||
isRootUser
|
||||
? ROOT_USER_TOOLTIP
|
||||
: isDeleted
|
||||
? undefined
|
||||
: 'You cannot modify your own role'
|
||||
}
|
||||
>
|
||||
<div className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled">
|
||||
<div className="edit-member-drawer__disabled-roles">
|
||||
@@ -467,7 +483,7 @@ function EditMemberDrawer({
|
||||
onRefetch={refetchRoles}
|
||||
value={localRole}
|
||||
onChange={(role): void => {
|
||||
setLocalRole(role);
|
||||
setLocalRole(role ?? '');
|
||||
setSaveErrors((prev) =>
|
||||
prev.filter(
|
||||
(err) =>
|
||||
@@ -476,6 +492,7 @@ function EditMemberDrawer({
|
||||
);
|
||||
}}
|
||||
placeholder="Select role"
|
||||
allowClear={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -487,6 +504,10 @@ function EditMemberDrawer({
|
||||
<Badge color="forest" variant="outline">
|
||||
ACTIVE
|
||||
</Badge>
|
||||
) : member?.status === MemberStatus.Deleted ? (
|
||||
<Badge color="cherry" variant="outline">
|
||||
DELETED
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge color="amber" variant="outline">
|
||||
INVITED
|
||||
@@ -525,55 +546,57 @@ function EditMemberDrawer({
|
||||
<div className="edit-member-drawer__layout">
|
||||
<div className="edit-member-drawer__body">{drawerBody}</div>
|
||||
|
||||
<div className="edit-member-drawer__footer">
|
||||
<div className="edit-member-drawer__footer-left">
|
||||
<Tooltip title={getDeleteTooltip(isRootUser, isSelf)}>
|
||||
<span className="edit-member-drawer__tooltip-wrapper">
|
||||
<Button
|
||||
className="edit-member-drawer__footer-btn edit-member-drawer__footer-btn--danger"
|
||||
onClick={(): void => setShowDeleteConfirm(true)}
|
||||
disabled={isRootUser || isSelf}
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
{isInvited ? 'Revoke Invite' : 'Delete Member'}
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
{!isDeleted && (
|
||||
<div className="edit-member-drawer__footer">
|
||||
<div className="edit-member-drawer__footer-left">
|
||||
<Tooltip title={getDeleteTooltip(isRootUser, isSelf)}>
|
||||
<span className="edit-member-drawer__tooltip-wrapper">
|
||||
<Button
|
||||
className="edit-member-drawer__footer-btn edit-member-drawer__footer-btn--danger"
|
||||
onClick={(): void => setShowDeleteConfirm(true)}
|
||||
disabled={isRootUser || isSelf}
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
{isInvited ? 'Revoke Invite' : 'Delete Member'}
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
|
||||
<div className="edit-member-drawer__footer-divider" />
|
||||
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
|
||||
<span className="edit-member-drawer__tooltip-wrapper">
|
||||
<Button
|
||||
className="edit-member-drawer__footer-btn edit-member-drawer__footer-btn--warning"
|
||||
onClick={handleGenerateResetLink}
|
||||
disabled={isGeneratingLink || isRootUser}
|
||||
>
|
||||
<RefreshCw size={12} />
|
||||
{isGeneratingLink && 'Generating...'}
|
||||
{!isGeneratingLink && isInvited && 'Copy Invite Link'}
|
||||
{!isGeneratingLink && !isInvited && 'Generate Password Reset Link'}
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
<div className="edit-member-drawer__footer-divider" />
|
||||
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
|
||||
<span className="edit-member-drawer__tooltip-wrapper">
|
||||
<Button
|
||||
className="edit-member-drawer__footer-btn edit-member-drawer__footer-btn--warning"
|
||||
onClick={handleGenerateResetLink}
|
||||
disabled={isGeneratingLink || isRootUser}
|
||||
>
|
||||
<RefreshCw size={12} />
|
||||
{isGeneratingLink && 'Generating...'}
|
||||
{!isGeneratingLink && isInvited && 'Copy Invite Link'}
|
||||
{!isGeneratingLink && !isInvited && 'Generate Password Reset Link'}
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div className="edit-member-drawer__footer-right">
|
||||
<Button variant="solid" color="secondary" size="sm" onClick={handleClose}>
|
||||
<X size={14} />
|
||||
Cancel
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
disabled={!isDirty || isSaving || isRootUser}
|
||||
onClick={handleSave}
|
||||
>
|
||||
{isSaving ? 'Saving...' : 'Save Member Details'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="edit-member-drawer__footer-right">
|
||||
<Button variant="solid" color="secondary" size="sm" onClick={handleClose}>
|
||||
<X size={14} />
|
||||
Cancel
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
disabled={!isDirty || isSaving || isRootUser}
|
||||
onClick={handleSave}
|
||||
>
|
||||
{isSaving ? 'Saving...' : 'Save Member Details'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
|
||||
@@ -84,6 +84,16 @@ const ROLES_ENDPOINT = '*/api/v1/roles';
|
||||
const mockDeleteMutate = jest.fn();
|
||||
const mockGetResetPasswordToken = jest.mocked(getResetPasswordToken);
|
||||
|
||||
const showErrorModal = jest.fn();
|
||||
jest.mock('providers/ErrorModalProvider', () => ({
|
||||
__esModule: true,
|
||||
...jest.requireActual('providers/ErrorModalProvider'),
|
||||
useErrorModal: jest.fn(() => ({
|
||||
showErrorModal,
|
||||
isErrorModalVisible: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockFetchedUser = {
|
||||
data: {
|
||||
id: 'user-1',
|
||||
@@ -147,6 +157,7 @@ function renderDrawer(
|
||||
describe('EditMemberDrawer', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
showErrorModal.mockClear();
|
||||
server.use(
|
||||
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
|
||||
@@ -459,7 +470,6 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('shows API error message when deleteUser fails for active member', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const mockToast = jest.mocked(toast);
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutate: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -477,16 +487,20 @@ describe('EditMemberDrawer', () => {
|
||||
await user.click(confirmBtns[confirmBtns.length - 1]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast.error).toHaveBeenCalledWith(
|
||||
'Failed to delete member: Something went wrong on server',
|
||||
expect.anything(),
|
||||
expect(showErrorModal).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
getErrorMessage: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
const passedError = showErrorModal.mock.calls[0][0] as any;
|
||||
expect(passedError.getErrorMessage()).toBe(
|
||||
'Something went wrong on server',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('shows API error message when deleteUser fails for invited member', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const mockToast = jest.mocked(toast);
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutate: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -504,9 +518,14 @@ describe('EditMemberDrawer', () => {
|
||||
await user.click(confirmBtns[confirmBtns.length - 1]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast.error).toHaveBeenCalledWith(
|
||||
'Failed to revoke invite: Something went wrong on server',
|
||||
expect.anything(),
|
||||
expect(showErrorModal).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
getErrorMessage: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
const passedError = showErrorModal.mock.calls[0][0] as any;
|
||||
expect(passedError.getErrorMessage()).toBe(
|
||||
'Something went wrong on server',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Select } from 'antd';
|
||||
import inviteUsers from 'api/v1/invite/bulk/create';
|
||||
import sendInvite from 'api/v1/invite/create';
|
||||
import { cloneDeep, debounce } from 'lodash-es';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
import { ROLES } from 'types/roles';
|
||||
import { EMAIL_REGEX } from 'utils/app';
|
||||
@@ -40,6 +41,8 @@ function InviteMembersModal({
|
||||
onClose,
|
||||
onComplete,
|
||||
}: InviteMembersModalProps): JSX.Element {
|
||||
const { showErrorModal, isErrorModalVisible } = useErrorModal();
|
||||
|
||||
const [rows, setRows] = useState<InviteRow[]>(() => [
|
||||
EMPTY_ROW(),
|
||||
EMPTY_ROW(),
|
||||
@@ -204,13 +207,11 @@ function InviteMembersModal({
|
||||
resetAndClose();
|
||||
onComplete?.();
|
||||
} catch (err) {
|
||||
const apiErr = err as APIError;
|
||||
const errorMessage = apiErr?.getErrorMessage?.() ?? 'An error occurred';
|
||||
toast.error(errorMessage, { richColors: true, position: 'top-right' });
|
||||
showErrorModal(err as APIError);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}, [rows, onComplete, resetAndClose, validateAllUsers]);
|
||||
}, [validateAllUsers, rows, resetAndClose, onComplete, showErrorModal]);
|
||||
|
||||
const touchedRows = rows.filter(isRowTouched);
|
||||
const isSubmitDisabled = isSubmitting || touchedRows.length === 0;
|
||||
@@ -227,7 +228,7 @@ function InviteMembersModal({
|
||||
showCloseButton
|
||||
width="wide"
|
||||
className="invite-members-modal"
|
||||
disableOutsideClick={false}
|
||||
disableOutsideClick={isErrorModalVisible}
|
||||
>
|
||||
<div className="invite-members-modal__content">
|
||||
<div className="invite-members-modal__table">
|
||||
@@ -329,6 +330,7 @@ function InviteMembersModal({
|
||||
size="sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitDisabled}
|
||||
loading={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Inviting...' : 'Invite Team Members'}
|
||||
</Button>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { toast } from '@signozhq/sonner';
|
||||
import inviteUsers from 'api/v1/invite/bulk/create';
|
||||
import sendInvite from 'api/v1/invite/create';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
@@ -22,6 +21,16 @@ jest.mock('@signozhq/sonner', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const showErrorModal = jest.fn();
|
||||
jest.mock('providers/ErrorModalProvider', () => ({
|
||||
__esModule: true,
|
||||
...jest.requireActual('providers/ErrorModalProvider'),
|
||||
useErrorModal: jest.fn(() => ({
|
||||
showErrorModal,
|
||||
isErrorModalVisible: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockSendInvite = jest.mocked(sendInvite);
|
||||
const mockInviteUsers = jest.mocked(inviteUsers);
|
||||
|
||||
@@ -34,6 +43,7 @@ const defaultProps = {
|
||||
describe('InviteMembersModal', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
showErrorModal.mockClear();
|
||||
mockSendInvite.mockResolvedValue({
|
||||
httpStatusCode: 200,
|
||||
data: { data: 'test', status: 'success' },
|
||||
@@ -154,9 +164,10 @@ describe('InviteMembersModal', () => {
|
||||
describe('error handling', () => {
|
||||
it('shows BE message on single invite 409', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
mockSendInvite.mockRejectedValue(
|
||||
makeApiError('An invite already exists for this email: single@signoz.io'),
|
||||
const error = makeApiError(
|
||||
'An invite already exists for this email: single@signoz.io',
|
||||
);
|
||||
mockSendInvite.mockRejectedValue(error);
|
||||
|
||||
render(<InviteMembersModal {...defaultProps} />);
|
||||
|
||||
@@ -171,18 +182,16 @@ describe('InviteMembersModal', () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith(
|
||||
'An invite already exists for this email: single@signoz.io',
|
||||
expect.anything(),
|
||||
);
|
||||
expect(showErrorModal).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
||||
it('shows BE message on bulk invite 409', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
mockInviteUsers.mockRejectedValue(
|
||||
makeApiError('An invite already exists for this email: alice@signoz.io'),
|
||||
const error = makeApiError(
|
||||
'An invite already exists for this email: alice@signoz.io',
|
||||
);
|
||||
mockInviteUsers.mockRejectedValue(error);
|
||||
|
||||
render(<InviteMembersModal {...defaultProps} />);
|
||||
|
||||
@@ -201,18 +210,17 @@ describe('InviteMembersModal', () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith(
|
||||
'An invite already exists for this email: alice@signoz.io',
|
||||
expect.anything(),
|
||||
);
|
||||
expect(showErrorModal).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
||||
it('shows BE message on generic error', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
mockSendInvite.mockRejectedValue(
|
||||
makeApiError('Internal server error', StatusCodes.INTERNAL_SERVER_ERROR),
|
||||
const error = makeApiError(
|
||||
'Internal server error',
|
||||
StatusCodes.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
mockSendInvite.mockRejectedValue(error);
|
||||
|
||||
render(<InviteMembersModal {...defaultProps} />);
|
||||
|
||||
@@ -227,10 +235,7 @@ describe('InviteMembersModal', () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith(
|
||||
'Internal server error',
|
||||
expect.anything(),
|
||||
);
|
||||
expect(showErrorModal).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,17 +28,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
// In table/column view, keep action buttons visible at the viewport's right edge
|
||||
.log-line-action-buttons.table-view-log-actions {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 8px;
|
||||
left: auto;
|
||||
transform: translateY(-50%);
|
||||
margin: 0;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
.lightMode {
|
||||
.log-line-action-buttons {
|
||||
border: 1px solid var(--bg-vanilla-400);
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
.log-state-indicator {
|
||||
padding-left: 8px;
|
||||
|
||||
.line {
|
||||
margin: 0 8px;
|
||||
min-height: 24px;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
|
||||
import { LogType } from './LogStateIndicator';
|
||||
|
||||
export function getRowBackgroundColor(
|
||||
isDarkMode: boolean,
|
||||
logType?: string,
|
||||
): string {
|
||||
if (isDarkMode) {
|
||||
switch (logType) {
|
||||
case LogType.INFO:
|
||||
return `${Color.BG_ROBIN_500}40`;
|
||||
case LogType.WARN:
|
||||
return `${Color.BG_AMBER_500}40`;
|
||||
case LogType.ERROR:
|
||||
return `${Color.BG_CHERRY_500}40`;
|
||||
case LogType.TRACE:
|
||||
return `${Color.BG_FOREST_400}40`;
|
||||
case LogType.DEBUG:
|
||||
return `${Color.BG_AQUA_500}40`;
|
||||
case LogType.FATAL:
|
||||
return `${Color.BG_SAKURA_500}40`;
|
||||
default:
|
||||
return `${Color.BG_ROBIN_500}40`;
|
||||
}
|
||||
}
|
||||
switch (logType) {
|
||||
case LogType.INFO:
|
||||
return Color.BG_ROBIN_100;
|
||||
case LogType.WARN:
|
||||
return Color.BG_AMBER_100;
|
||||
case LogType.ERROR:
|
||||
return Color.BG_CHERRY_100;
|
||||
case LogType.TRACE:
|
||||
return Color.BG_FOREST_200;
|
||||
case LogType.DEBUG:
|
||||
return Color.BG_AQUA_100;
|
||||
case LogType.FATAL:
|
||||
return Color.BG_SAKURA_100;
|
||||
default:
|
||||
return Color.BG_VANILLA_300;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
.logBodyCell {
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.07px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--tanstack-plain-cell-font-size, 14px);
|
||||
line-height: var(--tanstack-plain-cell-line-height, 18px);
|
||||
line-clamp: var(--tanstack-plain-body-line-clamp, 1);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
117
frontend/src/components/Logs/TableView/useLogsTableColumns.tsx
Normal file
117
frontend/src/components/Logs/TableView/useLogsTableColumns.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import { getSanitizedLogBody } from 'container/LogDetailedView/utils';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { FlatLogData } from 'lib/logs/flatLogData';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import { IField } from 'types/api/logs/fields';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
import type { TableColumnDef } from '../../TanStackTableView/types';
|
||||
import LogStateIndicator from '../LogStateIndicator/LogStateIndicator';
|
||||
|
||||
import styles from './useLogsTableColumns.module.scss';
|
||||
|
||||
type UseLogsTableColumnsProps = {
|
||||
fields: IField[];
|
||||
linesPerRow: number;
|
||||
fontSize: FontSize;
|
||||
appendTo?: 'center' | 'end';
|
||||
};
|
||||
|
||||
export function useLogsTableColumns({
|
||||
fields,
|
||||
fontSize,
|
||||
appendTo = 'center',
|
||||
}: UseLogsTableColumnsProps): TableColumnDef<ILog>[] {
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
|
||||
return useMemo<TableColumnDef<ILog>[]>(() => {
|
||||
const stateIndicatorCol: TableColumnDef<ILog> = {
|
||||
id: 'state-indicator',
|
||||
header: '',
|
||||
pin: 'left',
|
||||
enableMove: false,
|
||||
enableResize: false,
|
||||
enableRemove: false,
|
||||
width: { fixed: 32 },
|
||||
cell: ({ row }): ReactElement => (
|
||||
<LogStateIndicator
|
||||
fontSize={fontSize}
|
||||
severityText={row.severity_text as string}
|
||||
severityNumber={row.severity_number as number}
|
||||
/>
|
||||
),
|
||||
};
|
||||
|
||||
const fieldColumns: TableColumnDef<ILog>[] = fields
|
||||
.filter((f): boolean => !['id', 'body', 'timestamp'].includes(f.name))
|
||||
.map(
|
||||
(f): TableColumnDef<ILog> => ({
|
||||
id: f.name,
|
||||
header: f.name,
|
||||
accessorFn: (log): unknown => FlatLogData(log)[f.name],
|
||||
enableRemove: true,
|
||||
width: { min: 192 },
|
||||
cell: ({ value }): ReactElement => (
|
||||
<TanStackTable.Text>{String(value ?? '')}</TanStackTable.Text>
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const timestampCol: TableColumnDef<ILog> | null = fields.some(
|
||||
(f) => f.name === 'timestamp',
|
||||
)
|
||||
? {
|
||||
id: 'timestamp',
|
||||
header: 'Timestamp',
|
||||
accessorFn: (log): unknown => log.timestamp,
|
||||
width: { min: 200 },
|
||||
cell: ({ value }): ReactElement => {
|
||||
const ts = value as string | number;
|
||||
const formatted =
|
||||
typeof ts === 'string'
|
||||
? formatTimezoneAdjustedTimestamp(ts, DATE_TIME_FORMATS.ISO_DATETIME_MS)
|
||||
: formatTimezoneAdjustedTimestamp(
|
||||
ts / 1e6,
|
||||
DATE_TIME_FORMATS.ISO_DATETIME_MS,
|
||||
);
|
||||
return <TanStackTable.Text>{formatted}</TanStackTable.Text>;
|
||||
},
|
||||
}
|
||||
: null;
|
||||
|
||||
const bodyCol: TableColumnDef<ILog> | null = fields.some(
|
||||
(f) => f.name === 'body',
|
||||
)
|
||||
? {
|
||||
id: 'body',
|
||||
header: 'Body',
|
||||
accessorFn: (log): string => log.body,
|
||||
width: { min: 640 },
|
||||
cell: ({ value, isActive }): ReactElement => (
|
||||
<div
|
||||
// eslint-disable-next-line react/no-danger
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: getSanitizedLogBody(value as string, {
|
||||
shouldEscapeHtml: true,
|
||||
}),
|
||||
}}
|
||||
data-active={isActive}
|
||||
className={styles.logBodyCell}
|
||||
/>
|
||||
),
|
||||
}
|
||||
: null;
|
||||
|
||||
return [
|
||||
stateIndicatorCol,
|
||||
...(timestampCol ? [timestampCol] : []),
|
||||
...(appendTo === 'center' ? fieldColumns : []),
|
||||
...(bodyCol ? [bodyCol] : []),
|
||||
...(appendTo === 'end' ? fieldColumns : []),
|
||||
];
|
||||
}, [fields, appendTo, fontSize, formatTimezoneAdjustedTimestamp]);
|
||||
}
|
||||
@@ -210,7 +210,7 @@ function MembersTable({
|
||||
index % 2 === 0 ? 'members-table-row--tinted' : ''
|
||||
}
|
||||
onRow={(record): React.HTMLAttributes<HTMLElement> => {
|
||||
const isClickable = onRowClick && record.status !== MemberStatus.Deleted;
|
||||
const isClickable = !!onRowClick;
|
||||
return {
|
||||
onClick: (): void => {
|
||||
if (isClickable) {
|
||||
|
||||
@@ -86,7 +86,7 @@ describe('MembersTable', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('renders DELETED badge and does not call onRowClick when a deleted member row is clicked', async () => {
|
||||
it('renders DELETED badge and calls onRowClick when a deleted member row is clicked', async () => {
|
||||
const onRowClick = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const deletedMember: MemberRow = {
|
||||
@@ -108,7 +108,7 @@ describe('MembersTable', () => {
|
||||
|
||||
expect(screen.getByText('DELETED')).toBeInTheDocument();
|
||||
await user.click(screen.getByText('Dave Deleted'));
|
||||
expect(onRowClick).not.toHaveBeenCalledWith(
|
||||
expect(onRowClick).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'user-del' }),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -85,7 +85,8 @@ interface BaseProps {
|
||||
interface SingleProps extends BaseProps {
|
||||
mode?: 'single';
|
||||
value?: string;
|
||||
onChange?: (role: string) => void;
|
||||
onChange?: (role: string | undefined) => void;
|
||||
allowClear?: boolean;
|
||||
}
|
||||
|
||||
interface MultipleProps extends BaseProps {
|
||||
@@ -154,13 +155,14 @@ function RolesSelect(props: RolesSelectProps): JSX.Element {
|
||||
);
|
||||
}
|
||||
|
||||
const { value, onChange } = props as SingleProps;
|
||||
const { value, onChange, allowClear = true } = props as SingleProps;
|
||||
return (
|
||||
<Select
|
||||
id={id}
|
||||
value={value || undefined}
|
||||
onChange={onChange}
|
||||
placeholder={placeholder}
|
||||
allowClear={allowClear}
|
||||
className={cx('roles-single-select', className)}
|
||||
loading={loading}
|
||||
notFoundContent={notFoundContent}
|
||||
|
||||
@@ -17,6 +17,8 @@ import { AxiosError } from 'axios';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
|
||||
import { parseAsBoolean, useQueryState } from 'nuqs';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import KeyCreatedPhase from './KeyCreatedPhase';
|
||||
import KeyFormPhase from './KeyFormPhase';
|
||||
@@ -27,6 +29,7 @@ import './AddKeyModal.styles.scss';
|
||||
|
||||
function AddKeyModal(): JSX.Element {
|
||||
const queryClient = useQueryClient();
|
||||
const { showErrorModal, isErrorModalVisible } = useErrorModal();
|
||||
const [accountId] = useQueryState(SA_QUERY_PARAMS.ACCOUNT);
|
||||
const [isAddKeyOpen, setIsAddKeyOpen] = useQueryState(
|
||||
SA_QUERY_PARAMS.ADD_KEY,
|
||||
@@ -81,11 +84,11 @@ function AddKeyModal(): JSX.Element {
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const errMessage =
|
||||
showErrorModal(
|
||||
convertToApiError(
|
||||
error as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
)?.getErrorMessage() || 'Failed to create key';
|
||||
toast.error(errMessage, { richColors: true });
|
||||
) as APIError,
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -151,7 +154,7 @@ function AddKeyModal(): JSX.Element {
|
||||
width="base"
|
||||
className="add-key-modal"
|
||||
showCloseButton
|
||||
disableOutsideClick={false}
|
||||
disableOutsideClick={isErrorModalVisible}
|
||||
>
|
||||
{phase === Phase.FORM && (
|
||||
<KeyFormPhase
|
||||
|
||||
@@ -16,9 +16,12 @@ import type {
|
||||
import { AxiosError } from 'axios';
|
||||
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
|
||||
import { parseAsBoolean, useQueryState } from 'nuqs';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
function DeleteAccountModal(): JSX.Element {
|
||||
const queryClient = useQueryClient();
|
||||
const { showErrorModal, isErrorModalVisible } = useErrorModal();
|
||||
const [accountId, setAccountId] = useQueryState(SA_QUERY_PARAMS.ACCOUNT);
|
||||
const [isDeleteOpen, setIsDeleteOpen] = useQueryState(
|
||||
SA_QUERY_PARAMS.DELETE_SA,
|
||||
@@ -45,11 +48,11 @@ function DeleteAccountModal(): JSX.Element {
|
||||
await invalidateListServiceAccounts(queryClient);
|
||||
},
|
||||
onError: (error) => {
|
||||
const errMessage =
|
||||
showErrorModal(
|
||||
convertToApiError(
|
||||
error as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
)?.getErrorMessage() || 'Failed to delete service account';
|
||||
toast.error(errMessage, { richColors: true });
|
||||
) as APIError,
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -79,7 +82,7 @@ function DeleteAccountModal(): JSX.Element {
|
||||
width="narrow"
|
||||
className="alert-dialog sa-delete-dialog"
|
||||
showCloseButton={false}
|
||||
disableOutsideClick={false}
|
||||
disableOutsideClick={isErrorModalVisible}
|
||||
>
|
||||
<p className="sa-delete-dialog__body">
|
||||
Are you sure you want to delete <strong>{accountName}</strong>? This action
|
||||
|
||||
@@ -17,7 +17,9 @@ import { AxiosError } from 'axios';
|
||||
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
|
||||
import dayjs from 'dayjs';
|
||||
import { parseAsString, useQueryState } from 'nuqs';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import { RevokeKeyContent } from '../RevokeKeyModal';
|
||||
import EditKeyForm from './EditKeyForm';
|
||||
@@ -41,6 +43,7 @@ function EditKeyModal({ keyItem }: EditKeyModalProps): JSX.Element {
|
||||
const open = !!editKeyId && !!selectedAccountId;
|
||||
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
const { showErrorModal, isErrorModalVisible } = useErrorModal();
|
||||
const [isRevokeConfirmOpen, setIsRevokeConfirmOpen] = useState(false);
|
||||
|
||||
const {
|
||||
@@ -78,11 +81,11 @@ function EditKeyModal({ keyItem }: EditKeyModalProps): JSX.Element {
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const errMessage =
|
||||
showErrorModal(
|
||||
convertToApiError(
|
||||
error as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
)?.getErrorMessage() || 'Failed to update key';
|
||||
toast.error(errMessage, { richColors: true });
|
||||
) as APIError,
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -102,12 +105,13 @@ function EditKeyModal({ keyItem }: EditKeyModalProps): JSX.Element {
|
||||
});
|
||||
}
|
||||
},
|
||||
// eslint-disable-next-line sonarjs/no-identical-functions
|
||||
onError: (error) => {
|
||||
const errMessage =
|
||||
showErrorModal(
|
||||
convertToApiError(
|
||||
error as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
)?.getErrorMessage() || 'Failed to revoke key';
|
||||
toast.error(errMessage, { richColors: true });
|
||||
) as APIError,
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -160,7 +164,7 @@ function EditKeyModal({ keyItem }: EditKeyModalProps): JSX.Element {
|
||||
isRevokeConfirmOpen ? 'alert-dialog delete-dialog' : 'edit-key-modal'
|
||||
}
|
||||
showCloseButton={!isRevokeConfirmOpen}
|
||||
disableOutsideClick={false}
|
||||
disableOutsideClick={isErrorModalVisible}
|
||||
>
|
||||
{isRevokeConfirmOpen ? (
|
||||
<RevokeKeyContent
|
||||
|
||||
@@ -17,7 +17,7 @@ interface OverviewTabProps {
|
||||
localName: string;
|
||||
onNameChange: (v: string) => void;
|
||||
localRole: string;
|
||||
onRoleChange: (v: string) => void;
|
||||
onRoleChange: (v: string | undefined) => void;
|
||||
isDisabled: boolean;
|
||||
availableRoles: AuthtypesRoleDTO[];
|
||||
rolesLoading?: boolean;
|
||||
|
||||
@@ -16,6 +16,8 @@ import type {
|
||||
import { AxiosError } from 'axios';
|
||||
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
|
||||
import { parseAsString, useQueryState } from 'nuqs';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
export interface RevokeKeyContentProps {
|
||||
isRevoking: boolean;
|
||||
@@ -56,6 +58,7 @@ export function RevokeKeyContent({
|
||||
|
||||
function RevokeKeyModal(): JSX.Element {
|
||||
const queryClient = useQueryClient();
|
||||
const { showErrorModal, isErrorModalVisible } = useErrorModal();
|
||||
const [accountId] = useQueryState(SA_QUERY_PARAMS.ACCOUNT);
|
||||
const [revokeKeyId, setRevokeKeyId] = useQueryState(
|
||||
SA_QUERY_PARAMS.REVOKE_KEY,
|
||||
@@ -83,11 +86,11 @@ function RevokeKeyModal(): JSX.Element {
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const errMessage =
|
||||
showErrorModal(
|
||||
convertToApiError(
|
||||
error as AxiosError<RenderErrorResponseDTO, unknown> | null,
|
||||
)?.getErrorMessage() || 'Failed to revoke key';
|
||||
toast.error(errMessage, { richColors: true });
|
||||
) as APIError,
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -115,7 +118,7 @@ function RevokeKeyModal(): JSX.Element {
|
||||
width="narrow"
|
||||
className="alert-dialog delete-dialog"
|
||||
showCloseButton={false}
|
||||
disableOutsideClick={false}
|
||||
disableOutsideClick={isErrorModalVisible}
|
||||
>
|
||||
<RevokeKeyContent
|
||||
isRevoking={isRevoking}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import { Button } from '@signozhq/button';
|
||||
import { DrawerWrapper } from '@signozhq/drawer';
|
||||
@@ -8,7 +8,9 @@ import { ToggleGroup, ToggleGroupItem } from '@signozhq/toggle-group';
|
||||
import { Pagination, Skeleton } from 'antd';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import {
|
||||
getGetServiceAccountRolesQueryKey,
|
||||
getListServiceAccountsQueryKey,
|
||||
useDeleteServiceAccountRole,
|
||||
useGetServiceAccount,
|
||||
useListServiceAccountKeys,
|
||||
useUpdateServiceAccount,
|
||||
@@ -23,7 +25,10 @@ import {
|
||||
ServiceAccountStatus,
|
||||
toServiceAccountRow,
|
||||
} from 'container/ServiceAccountsSettings/utils';
|
||||
import { useServiceAccountRoleManager } from 'hooks/serviceAccount/useServiceAccountRoleManager';
|
||||
import {
|
||||
RoleUpdateFailure,
|
||||
useServiceAccountRoleManager,
|
||||
} from 'hooks/serviceAccount/useServiceAccountRoleManager';
|
||||
import {
|
||||
parseAsBoolean,
|
||||
parseAsInteger,
|
||||
@@ -32,7 +37,7 @@ import {
|
||||
useQueryState,
|
||||
} from 'nuqs';
|
||||
import APIError from 'types/api/error';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
import { retryOn429, toAPIError } from 'utils/errorUtils';
|
||||
|
||||
import AddKeyModal from './AddKeyModal';
|
||||
import DeleteAccountModal from './DeleteAccountModal';
|
||||
@@ -49,6 +54,13 @@ export interface ServiceAccountDrawerProps {
|
||||
|
||||
const PAGE_SIZE = 15;
|
||||
|
||||
function toSaveApiError(err: unknown): APIError {
|
||||
return (
|
||||
convertToApiError(err as AxiosError<RenderErrorResponseDTO>) ??
|
||||
toAPIError(err as AxiosError<RenderErrorResponseDTO>)
|
||||
);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
function ServiceAccountDrawer({
|
||||
onSuccess,
|
||||
@@ -103,21 +115,35 @@ function ServiceAccountDrawer({
|
||||
[accountData],
|
||||
);
|
||||
|
||||
const { currentRoles, applyDiff } = useServiceAccountRoleManager(
|
||||
selectedAccountId ?? '',
|
||||
);
|
||||
const {
|
||||
currentRoles,
|
||||
isLoading: isRolesLoading,
|
||||
applyDiff,
|
||||
} = useServiceAccountRoleManager(selectedAccountId ?? '');
|
||||
|
||||
const roleSessionRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (account?.id) {
|
||||
setLocalName(account?.name ?? '');
|
||||
setKeysPage(1);
|
||||
}
|
||||
setSaveErrors([]);
|
||||
}, [account?.id, account?.name, setKeysPage]);
|
||||
|
||||
useEffect(() => {
|
||||
setLocalRole(currentRoles[0]?.id ?? '');
|
||||
}, [currentRoles]);
|
||||
if (account?.id) {
|
||||
setSaveErrors([]);
|
||||
}
|
||||
}, [account?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!account?.id) {
|
||||
roleSessionRef.current = null;
|
||||
} else if (account.id !== roleSessionRef.current && !isRolesLoading) {
|
||||
setLocalRole(currentRoles[0]?.id ?? '');
|
||||
roleSessionRef.current = account.id;
|
||||
}
|
||||
}, [account?.id, currentRoles, isRolesLoading]);
|
||||
|
||||
const isDeleted =
|
||||
account?.status?.toUpperCase() === ServiceAccountStatus.Deleted;
|
||||
@@ -153,12 +179,26 @@ function ServiceAccountDrawer({
|
||||
|
||||
// the retry for this mutation is safe due to the api being idempotent on backend
|
||||
const { mutateAsync: updateMutateAsync } = useUpdateServiceAccount();
|
||||
const { mutateAsync: deleteRole } = useDeleteServiceAccountRole({
|
||||
mutation: {
|
||||
retry: retryOn429,
|
||||
},
|
||||
});
|
||||
|
||||
const toSaveApiError = useCallback(
|
||||
(err: unknown): APIError =>
|
||||
convertToApiError(err as AxiosError<RenderErrorResponseDTO>) ??
|
||||
toAPIError(err as AxiosError<RenderErrorResponseDTO>),
|
||||
[],
|
||||
const executeRolesOperation = useCallback(
|
||||
async (accountId: string): Promise<RoleUpdateFailure[]> => {
|
||||
if (localRole === '' && currentRoles[0]?.id) {
|
||||
await deleteRole({
|
||||
pathParams: { id: accountId, rid: currentRoles[0].id },
|
||||
});
|
||||
await queryClient.invalidateQueries(
|
||||
getGetServiceAccountRolesQueryKey({ id: accountId }),
|
||||
);
|
||||
return [];
|
||||
}
|
||||
return applyDiff([localRole].filter(Boolean), availableRoles);
|
||||
},
|
||||
[localRole, currentRoles, availableRoles, applyDiff, deleteRole, queryClient],
|
||||
);
|
||||
|
||||
const retryNameUpdate = useCallback(async (): Promise<void> => {
|
||||
@@ -180,14 +220,7 @@ function ServiceAccountDrawer({
|
||||
),
|
||||
);
|
||||
}
|
||||
}, [
|
||||
account,
|
||||
localName,
|
||||
updateMutateAsync,
|
||||
refetchAccount,
|
||||
queryClient,
|
||||
toSaveApiError,
|
||||
]);
|
||||
}, [account, localName, updateMutateAsync, refetchAccount, queryClient]);
|
||||
|
||||
const handleNameChange = useCallback((name: string): void => {
|
||||
setLocalName(name);
|
||||
@@ -210,29 +243,39 @@ function ServiceAccountDrawer({
|
||||
);
|
||||
}
|
||||
},
|
||||
[toSaveApiError],
|
||||
[],
|
||||
);
|
||||
|
||||
const clearRoleErrors = useCallback((): void => {
|
||||
setSaveErrors((prev) =>
|
||||
prev.filter(
|
||||
(e) => e.context !== 'Roles update' && !e.context.startsWith("Role '"),
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const failuresToSaveErrors = useCallback(
|
||||
(failures: RoleUpdateFailure[]): SaveError[] =>
|
||||
failures.map((f) => {
|
||||
const ctx = `Role '${f.roleName}'`;
|
||||
return {
|
||||
context: ctx,
|
||||
apiError: toSaveApiError(f.error),
|
||||
onRetry: makeRoleRetry(ctx, f.onRetry),
|
||||
};
|
||||
}),
|
||||
[makeRoleRetry],
|
||||
);
|
||||
|
||||
const retryRolesUpdate = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
const failures = await applyDiff(
|
||||
[localRole].filter(Boolean),
|
||||
availableRoles,
|
||||
);
|
||||
const failures = await executeRolesOperation(selectedAccountId ?? '');
|
||||
if (failures.length === 0) {
|
||||
setSaveErrors((prev) => prev.filter((e) => e.context !== 'Roles update'));
|
||||
} else {
|
||||
setSaveErrors((prev) => {
|
||||
const rest = prev.filter((e) => e.context !== 'Roles update');
|
||||
const roleErrors = failures.map((f) => {
|
||||
const ctx = `Role '${f.roleName}'`;
|
||||
return {
|
||||
context: ctx,
|
||||
apiError: toSaveApiError(f.error),
|
||||
onRetry: makeRoleRetry(ctx, f.onRetry),
|
||||
};
|
||||
});
|
||||
return [...rest, ...roleErrors];
|
||||
return [...rest, ...failuresToSaveErrors(failures)];
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -242,7 +285,7 @@ function ServiceAccountDrawer({
|
||||
),
|
||||
);
|
||||
}
|
||||
}, [localRole, availableRoles, applyDiff, toSaveApiError, makeRoleRetry]);
|
||||
}, [selectedAccountId, executeRolesOperation, failuresToSaveErrors]);
|
||||
|
||||
const handleSave = useCallback(async (): Promise<void> => {
|
||||
if (!account || !isDirty) {
|
||||
@@ -261,7 +304,7 @@ function ServiceAccountDrawer({
|
||||
|
||||
const [nameResult, rolesResult] = await Promise.allSettled([
|
||||
namePromise,
|
||||
applyDiff([localRole].filter(Boolean), availableRoles),
|
||||
executeRolesOperation(account.id),
|
||||
]);
|
||||
|
||||
const errors: SaveError[] = [];
|
||||
@@ -281,14 +324,7 @@ function ServiceAccountDrawer({
|
||||
onRetry: retryRolesUpdate,
|
||||
});
|
||||
} else {
|
||||
for (const failure of rolesResult.value) {
|
||||
const context = `Role '${failure.roleName}'`;
|
||||
errors.push({
|
||||
context,
|
||||
apiError: toSaveApiError(failure.error),
|
||||
onRetry: makeRoleRetry(context, failure.onRetry),
|
||||
});
|
||||
}
|
||||
errors.push(...failuresToSaveErrors(rolesResult.value));
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
@@ -310,17 +346,14 @@ function ServiceAccountDrawer({
|
||||
account,
|
||||
isDirty,
|
||||
localName,
|
||||
localRole,
|
||||
availableRoles,
|
||||
updateMutateAsync,
|
||||
applyDiff,
|
||||
executeRolesOperation,
|
||||
refetchAccount,
|
||||
onSuccess,
|
||||
queryClient,
|
||||
toSaveApiError,
|
||||
retryNameUpdate,
|
||||
makeRoleRetry,
|
||||
retryRolesUpdate,
|
||||
failuresToSaveErrors,
|
||||
]);
|
||||
|
||||
const handleClose = useCallback((): void => {
|
||||
@@ -413,7 +446,10 @@ function ServiceAccountDrawer({
|
||||
localName={localName}
|
||||
onNameChange={handleNameChange}
|
||||
localRole={localRole}
|
||||
onRoleChange={setLocalRole}
|
||||
onRoleChange={(role): void => {
|
||||
setLocalRole(role ?? '');
|
||||
clearRoleErrors();
|
||||
}}
|
||||
isDisabled={isDeleted}
|
||||
availableRoles={availableRoles}
|
||||
rolesLoading={rolesLoading}
|
||||
|
||||
@@ -390,6 +390,42 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('role add retries on 429 then succeeds without showing an error', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
let roleAddCallCount = 0;
|
||||
|
||||
// First call → 429, second call → 200
|
||||
server.use(
|
||||
rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) => {
|
||||
roleAddCallCount += 1;
|
||||
if (roleAddCallCount === 1) {
|
||||
return res(ctx.status(429), ctx.json({ message: 'Too Many Requests' }));
|
||||
}
|
||||
return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
|
||||
}),
|
||||
);
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
await user.click(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-viewer'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
await waitFor(() => expect(saveBtn).not.toBeDisabled());
|
||||
await user.click(saveBtn);
|
||||
|
||||
// Retried after 429 — at least 2 calls, no error shown
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(roleAddCallCount).toBeGreaterThanOrEqual(2);
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(screen.queryByText(/role assign failed/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking Retry on a name-update error re-triggers the request; on success the error item is removed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
|
||||
101
frontend/src/components/TanStackTableView/RowHoverContext.tsx
Normal file
101
frontend/src/components/TanStackTableView/RowHoverContext.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
/* eslint-disable no-restricted-imports */
|
||||
import {
|
||||
createContext,
|
||||
ReactNode,
|
||||
useCallback,
|
||||
useContext,
|
||||
useRef,
|
||||
} from 'react';
|
||||
/* eslint-enable no-restricted-imports */
|
||||
import { createStore, StoreApi, useStore } from 'zustand';
|
||||
|
||||
const CLEAR_HOVER_DELAY_MS = 100;
|
||||
|
||||
type RowHoverState = {
|
||||
hoveredRowId: string | null;
|
||||
clearTimeoutId: ReturnType<typeof setTimeout> | null;
|
||||
setHoveredRowId: (id: string | null) => void;
|
||||
scheduleClearHover: (rowId: string) => void;
|
||||
};
|
||||
|
||||
const createRowHoverStore = (): StoreApi<RowHoverState> =>
|
||||
createStore<RowHoverState>((set, get) => ({
|
||||
hoveredRowId: null,
|
||||
clearTimeoutId: null,
|
||||
setHoveredRowId: (id: string | null): void => {
|
||||
const { clearTimeoutId } = get();
|
||||
if (clearTimeoutId) {
|
||||
clearTimeout(clearTimeoutId);
|
||||
set({ clearTimeoutId: null });
|
||||
}
|
||||
set({ hoveredRowId: id });
|
||||
},
|
||||
scheduleClearHover: (rowId: string): void => {
|
||||
const { clearTimeoutId } = get();
|
||||
if (clearTimeoutId) {
|
||||
clearTimeout(clearTimeoutId);
|
||||
}
|
||||
const timeoutId = setTimeout(() => {
|
||||
const current = get().hoveredRowId;
|
||||
if (current === rowId) {
|
||||
set({ hoveredRowId: null, clearTimeoutId: null });
|
||||
}
|
||||
}, CLEAR_HOVER_DELAY_MS);
|
||||
set({ clearTimeoutId: timeoutId });
|
||||
},
|
||||
}));
|
||||
|
||||
type RowHoverStore = StoreApi<RowHoverState>;
|
||||
|
||||
const RowHoverContext = createContext<RowHoverStore | null>(null);
|
||||
|
||||
export function RowHoverProvider({
|
||||
children,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
}): JSX.Element {
|
||||
const storeRef = useRef<RowHoverStore | null>(null);
|
||||
if (!storeRef.current) {
|
||||
storeRef.current = createRowHoverStore();
|
||||
}
|
||||
return (
|
||||
<RowHoverContext.Provider value={storeRef.current}>
|
||||
{children}
|
||||
</RowHoverContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const defaultStore = createRowHoverStore();
|
||||
|
||||
export const useIsRowHovered = (rowId: string): boolean => {
|
||||
const store = useContext(RowHoverContext);
|
||||
// Selector returns true only if this specific row is hovered
|
||||
const isHovered = useStore(
|
||||
store ?? defaultStore,
|
||||
(s) => s.hoveredRowId === rowId,
|
||||
);
|
||||
return store ? isHovered : false;
|
||||
};
|
||||
|
||||
export const useSetRowHovered = (rowId: string): (() => void) => {
|
||||
const store = useContext(RowHoverContext);
|
||||
return useCallback(() => {
|
||||
if (store) {
|
||||
const current = store.getState().hoveredRowId;
|
||||
if (current !== rowId) {
|
||||
store.getState().setHoveredRowId(rowId);
|
||||
}
|
||||
}
|
||||
}, [store, rowId]);
|
||||
};
|
||||
|
||||
export const useClearRowHovered = (rowId: string): (() => void) => {
|
||||
const store = useContext(RowHoverContext);
|
||||
return useCallback(() => {
|
||||
if (store) {
|
||||
store.getState().scheduleClearHover(rowId);
|
||||
}
|
||||
}, [store, rowId]);
|
||||
};
|
||||
|
||||
export default RowHoverContext;
|
||||
@@ -0,0 +1,111 @@
|
||||
import { ComponentProps, memo } from 'react';
|
||||
import { TableComponents } from 'react-virtuoso';
|
||||
import cx from 'classnames';
|
||||
|
||||
import { useClearRowHovered, useSetRowHovered } from './RowHoverContext';
|
||||
import { FlatItem, TableRowContext } from './types';
|
||||
|
||||
import tableStyles from './TanStackTable.module.scss';
|
||||
|
||||
type VirtuosoTableRowProps<TData> = ComponentProps<
|
||||
NonNullable<
|
||||
TableComponents<FlatItem<TData>, TableRowContext<TData>>['TableRow']
|
||||
>
|
||||
>;
|
||||
|
||||
function TanStackCustomTableRow<TData>({
|
||||
children,
|
||||
item,
|
||||
context,
|
||||
...props
|
||||
}: VirtuosoTableRowProps<TData>): JSX.Element {
|
||||
const rowId = item.row.id;
|
||||
const rowData = item.row.original;
|
||||
|
||||
// Stable callbacks for hover state management
|
||||
const setHovered = useSetRowHovered(rowId);
|
||||
const clearHovered = useClearRowHovered(rowId);
|
||||
|
||||
if (item.kind === 'expansion') {
|
||||
return (
|
||||
<tr {...props} className={tableStyles.tableRowExpansion}>
|
||||
{children}
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
const isActive = context?.isRowActive?.(rowData) ?? false;
|
||||
const extraClass = context?.getRowClassName?.(rowData) ?? '';
|
||||
const rowStyle = context?.getRowStyle?.(rowData);
|
||||
|
||||
const rowClassName = cx(
|
||||
tableStyles.tableRow,
|
||||
isActive && tableStyles.tableRowActive,
|
||||
extraClass,
|
||||
);
|
||||
|
||||
return (
|
||||
<tr
|
||||
{...props}
|
||||
className={rowClassName}
|
||||
style={rowStyle}
|
||||
onMouseEnter={setHovered}
|
||||
onMouseLeave={clearHovered}
|
||||
>
|
||||
{children}
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
// Custom comparison - only re-render when row identity or computed values change
|
||||
function areTableRowPropsEqual<TData>(
|
||||
prev: Readonly<VirtuosoTableRowProps<TData>>,
|
||||
next: Readonly<VirtuosoTableRowProps<TData>>,
|
||||
): boolean {
|
||||
// Different row = must re-render
|
||||
if (prev.item.row.id !== next.item.row.id) {
|
||||
return false;
|
||||
}
|
||||
// Different kind (row vs expansion) = must re-render
|
||||
if (prev.item.kind !== next.item.kind) {
|
||||
return false;
|
||||
}
|
||||
// Same row, same kind - check if computed values would differ
|
||||
// We compare the context callbacks and row data to determine this
|
||||
const prevData = prev.item.row.original;
|
||||
const nextData = next.item.row.original;
|
||||
|
||||
// Row data reference changed = potential re-render needed
|
||||
if (prevData !== nextData) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Context callbacks changed = computed values may differ
|
||||
if (prev.context !== next.context) {
|
||||
// If context changed, check if the actual computed values differ
|
||||
const prevActive = prev.context?.isRowActive?.(prevData) ?? false;
|
||||
const nextActive = next.context?.isRowActive?.(nextData) ?? false;
|
||||
if (prevActive !== nextActive) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const prevClass = prev.context?.getRowClassName?.(prevData) ?? '';
|
||||
const nextClass = next.context?.getRowClassName?.(nextData) ?? '';
|
||||
if (prevClass !== nextClass) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const prevStyle = prev.context?.getRowStyle?.(prevData);
|
||||
const nextStyle = next.context?.getRowStyle?.(nextData);
|
||||
if (prevStyle !== nextStyle) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export default memo(
|
||||
TanStackCustomTableRow,
|
||||
areTableRowPropsEqual,
|
||||
) as typeof TanStackCustomTableRow;
|
||||
@@ -1,4 +1,4 @@
|
||||
.tanstack-header-cell {
|
||||
.tanstackHeaderCell {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
@@ -10,16 +10,21 @@
|
||||
);
|
||||
transition: var(--tanstack-header-transition, none);
|
||||
|
||||
&.is-dragging {
|
||||
&.isDragging {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
&.is-resizing {
|
||||
&.isResizing {
|
||||
background: var(--l2-background-hover);
|
||||
}
|
||||
|
||||
&:last-child .cursorColResize {
|
||||
display: none;
|
||||
border-right: 1px solid var(--l2-border);
|
||||
}
|
||||
}
|
||||
|
||||
.tanstack-header-content {
|
||||
.tanstackHeaderContent {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
@@ -28,20 +33,20 @@
|
||||
cursor: default;
|
||||
max-width: 100%;
|
||||
|
||||
&.has-resize-control {
|
||||
&.hasResizeControl {
|
||||
max-width: calc(100% - 5px);
|
||||
}
|
||||
|
||||
&.has-action-control {
|
||||
&.hasActionControl {
|
||||
max-width: calc(100% - 5px);
|
||||
}
|
||||
|
||||
&.has-resize-control.has-action-control {
|
||||
&.hasResizeControl.hasActionControl {
|
||||
max-width: calc(100% - 10px);
|
||||
}
|
||||
}
|
||||
|
||||
.tanstack-grip-slot {
|
||||
.tanstackGripSlot {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -51,7 +56,7 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.tanstack-grip-activator {
|
||||
.tanstackGripActivator {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -63,7 +68,7 @@
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.tanstack-header-action-trigger {
|
||||
.tanstackHeaderActionTrigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -72,9 +77,11 @@
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
color: var(--l2-foreground);
|
||||
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.tanstack-column-actions-content {
|
||||
.tanstackColumnActionsContent {
|
||||
width: 140px;
|
||||
padding: 0;
|
||||
background: var(--l2-background);
|
||||
@@ -83,7 +90,7 @@
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.tanstack-remove-column-action {
|
||||
.tanstackRemoveColumnAction {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
@@ -105,19 +112,19 @@
|
||||
background: var(--l2-background-hover);
|
||||
color: var(--l2-foreground);
|
||||
|
||||
.tanstack-remove-column-action-icon {
|
||||
.tanstackRemoveColumnActionIcon {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tanstack-remove-column-action-icon {
|
||||
.tanstackRemoveColumnActionIcon {
|
||||
font-size: 11px;
|
||||
color: var(--l2-foreground);
|
||||
opacity: 0.95;
|
||||
}
|
||||
|
||||
.tanstack-header-cell .cursor-col-resize {
|
||||
.tanstackHeaderCell .cursorColResize {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
@@ -129,11 +136,11 @@
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.tanstack-header-cell.is-resizing .cursor-col-resize {
|
||||
.tanstackHeaderCell.isResizing .cursorColResize {
|
||||
background: var(--bg-robin-300);
|
||||
}
|
||||
|
||||
.tanstack-resize-handle-line {
|
||||
.tanstackResizeHandleLine {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
@@ -146,7 +153,7 @@
|
||||
transition: background 120ms ease, width 120ms ease;
|
||||
}
|
||||
|
||||
.tanstack-header-cell.is-resizing .tanstack-resize-handle-line {
|
||||
.tanstackHeaderCell.isResizing .tanstackResizeHandleLine {
|
||||
width: 2px;
|
||||
background: var(--bg-robin-500);
|
||||
transition: none;
|
||||
@@ -8,51 +8,46 @@ import { CloseOutlined, MoreOutlined } from '@ant-design/icons';
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@signozhq/popover';
|
||||
import { flexRender, Header as TanStackHeader } from '@tanstack/react-table';
|
||||
import cx from 'classnames';
|
||||
import { GripVertical } from 'lucide-react';
|
||||
|
||||
import { TableHeaderCellStyled } from '../InfinityTableView/styles';
|
||||
import { InfinityTableProps } from '../InfinityTableView/types';
|
||||
import { OrderedColumn, TanStackTableRowData } from './types';
|
||||
import { getColumnId } from './utils';
|
||||
import { TableColumnDef } from './types';
|
||||
|
||||
import './styles/TanStackHeaderRow.styles.scss';
|
||||
import headerStyles from './TanStackHeaderRow.module.scss';
|
||||
import tableStyles from './TanStackTable.module.scss';
|
||||
|
||||
type TanStackHeaderRowProps = {
|
||||
column: OrderedColumn;
|
||||
header?: TanStackHeader<TanStackTableRowData, unknown>;
|
||||
type TanStackHeaderRowProps<TData = unknown> = {
|
||||
column: TableColumnDef<TData>;
|
||||
header?: TanStackHeader<TData, unknown>;
|
||||
isDarkMode: boolean;
|
||||
fontSize: InfinityTableProps['tableViewProps']['fontSize'];
|
||||
hasSingleColumn: boolean;
|
||||
canRemoveColumn?: boolean;
|
||||
onRemoveColumn?: (columnKey: string) => void;
|
||||
onRemoveColumn?: (columnId: string) => void;
|
||||
};
|
||||
|
||||
const GRIP_ICON_SIZE = 12;
|
||||
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
function TanStackHeaderRow({
|
||||
function TanStackHeaderRow<TData>({
|
||||
column,
|
||||
header,
|
||||
isDarkMode,
|
||||
fontSize,
|
||||
hasSingleColumn,
|
||||
canRemoveColumn = false,
|
||||
onRemoveColumn,
|
||||
}: TanStackHeaderRowProps): JSX.Element {
|
||||
const columnId = getColumnId(column);
|
||||
const isDragColumn =
|
||||
column.key !== 'expand' && column.key !== 'state-indicator';
|
||||
const isResizableColumn = Boolean(header?.column.getCanResize());
|
||||
}: TanStackHeaderRowProps<TData>): JSX.Element {
|
||||
const columnId = column.id;
|
||||
const isDragColumn = column.enableMove !== false && column.pin == null;
|
||||
const isResizableColumn =
|
||||
column.enableResize !== false && Boolean(header?.column.getCanResize());
|
||||
const isColumnRemovable = Boolean(
|
||||
canRemoveColumn &&
|
||||
onRemoveColumn &&
|
||||
column.key !== 'expand' &&
|
||||
column.key !== 'state-indicator',
|
||||
canRemoveColumn && onRemoveColumn && column.enableRemove,
|
||||
);
|
||||
const isResizing = Boolean(header?.column.getIsResizing());
|
||||
const resizeHandler = header?.getResizeHandler();
|
||||
const headerText =
|
||||
typeof column.title === 'string' && column.title
|
||||
? column.title
|
||||
typeof column.header === 'string' && column.header
|
||||
? column.header
|
||||
: String(header?.id ?? columnId);
|
||||
const headerTitleAttr = headerText.replace(/^\w/, (c) => c.toUpperCase());
|
||||
const handleResizeStart = (
|
||||
@@ -83,54 +78,57 @@ function TanStackHeaderRow({
|
||||
} as CSSProperties),
|
||||
[isResizing, transform?.x, transform?.y, transition],
|
||||
);
|
||||
const headerCellClassName = [
|
||||
'tanstack-header-cell',
|
||||
isDragging ? 'is-dragging' : '',
|
||||
isResizing ? 'is-resizing' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
const headerContentClassName = [
|
||||
'tanstack-header-content',
|
||||
isResizableColumn ? 'has-resize-control' : '',
|
||||
isColumnRemovable ? 'has-action-control' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
const headerCellClassName = cx(
|
||||
headerStyles.tanstackHeaderCell,
|
||||
isDragging && headerStyles.isDragging,
|
||||
isResizing && headerStyles.isResizing,
|
||||
);
|
||||
const headerContentClassName = cx(
|
||||
headerStyles.tanstackHeaderContent,
|
||||
isResizableColumn && headerStyles.hasResizeControl,
|
||||
isColumnRemovable && headerStyles.hasActionControl,
|
||||
);
|
||||
|
||||
const thClassName = cx(
|
||||
tableStyles.tableHeaderCell,
|
||||
headerCellClassName,
|
||||
column.id,
|
||||
);
|
||||
|
||||
return (
|
||||
<TableHeaderCellStyled
|
||||
<th
|
||||
ref={setNodeRef}
|
||||
$isLogIndicator={column.key === 'state-indicator'}
|
||||
$isDarkMode={isDarkMode}
|
||||
$isDragColumn={false}
|
||||
className={headerCellClassName}
|
||||
className={thClassName}
|
||||
key={columnId}
|
||||
fontSize={fontSize}
|
||||
$hasSingleColumn={hasSingleColumn}
|
||||
style={headerCellStyle}
|
||||
data-dark-mode={isDarkMode}
|
||||
data-single-column={hasSingleColumn || undefined}
|
||||
>
|
||||
<span className={headerContentClassName}>
|
||||
{isDragColumn ? (
|
||||
<span className="tanstack-grip-slot">
|
||||
<span className={headerStyles.tanstackGripSlot}>
|
||||
<span
|
||||
ref={setActivatorNodeRef}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
role="button"
|
||||
aria-label={`Drag ${String(
|
||||
column.title || header?.id || columnId,
|
||||
(typeof column.header === 'string' && column.header) ||
|
||||
header?.id ||
|
||||
columnId,
|
||||
)} column`}
|
||||
className="tanstack-grip-activator"
|
||||
className={headerStyles.tanstackGripActivator}
|
||||
>
|
||||
<GripVertical size={GRIP_ICON_SIZE} />
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
<span className="tanstack-header-title" title={headerTitleAttr}>
|
||||
{header
|
||||
{header?.column?.columnDef
|
||||
? flexRender(header.column.columnDef.header, header.getContext())
|
||||
: String(column.title || '').replace(/^\w/, (c) => c.toUpperCase())}
|
||||
: typeof column.header === 'function'
|
||||
? column.header()
|
||||
: String(column.header || '').replace(/^\w/, (c) => c.toUpperCase())}
|
||||
</span>
|
||||
{isColumnRemovable && (
|
||||
<Popover>
|
||||
@@ -138,7 +136,7 @@ function TanStackHeaderRow({
|
||||
<span
|
||||
role="button"
|
||||
aria-label={`Column actions for ${headerTitleAttr}`}
|
||||
className="tanstack-header-action-trigger"
|
||||
className={headerStyles.tanstackHeaderActionTrigger}
|
||||
onMouseDown={(event): void => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
@@ -149,18 +147,20 @@ function TanStackHeaderRow({
|
||||
<PopoverContent
|
||||
align="end"
|
||||
sideOffset={6}
|
||||
className="tanstack-column-actions-content"
|
||||
className={headerStyles.tanstackColumnActionsContent}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="tanstack-remove-column-action"
|
||||
className={headerStyles.tanstackRemoveColumnAction}
|
||||
onClick={(event): void => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onRemoveColumn?.(String(column.key));
|
||||
onRemoveColumn?.(column.id);
|
||||
}}
|
||||
>
|
||||
<CloseOutlined className="tanstack-remove-column-action-icon" />
|
||||
<CloseOutlined
|
||||
className={headerStyles.tanstackRemoveColumnActionIcon}
|
||||
/>
|
||||
Remove column
|
||||
</button>
|
||||
</PopoverContent>
|
||||
@@ -170,7 +170,7 @@ function TanStackHeaderRow({
|
||||
{isResizableColumn && (
|
||||
<span
|
||||
role="presentation"
|
||||
className="cursor-col-resize"
|
||||
className={headerStyles.cursorColResize}
|
||||
title="Drag to resize column"
|
||||
onClick={(event): void => {
|
||||
event.preventDefault();
|
||||
@@ -183,10 +183,10 @@ function TanStackHeaderRow({
|
||||
handleResizeStart(event);
|
||||
}}
|
||||
>
|
||||
<span className="tanstack-resize-handle-line" />
|
||||
<span className={headerStyles.tanstackResizeHandleLine} />
|
||||
</span>
|
||||
)}
|
||||
</TableHeaderCellStyled>
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
105
frontend/src/components/TanStackTableView/TanStackRow.tsx
Normal file
105
frontend/src/components/TanStackTableView/TanStackRow.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import { memo, useCallback } from 'react';
|
||||
import { Row as TanStackRowModel } from '@tanstack/react-table';
|
||||
|
||||
import { useIsRowHovered } from './RowHoverContext';
|
||||
import { TanStackRowCell } from './TanStackRowCell';
|
||||
import { TableRowContext } from './types';
|
||||
|
||||
import tableStyles from './TanStackTable.module.scss';
|
||||
|
||||
type TanStackRowCellsProps<TData> = {
|
||||
row: TanStackRowModel<TData>;
|
||||
context: TableRowContext<TData> | undefined;
|
||||
itemKind: 'row' | 'expansion';
|
||||
hasSingleColumn: boolean;
|
||||
};
|
||||
|
||||
function TanStackRowCellsInner<TData>({
|
||||
row,
|
||||
context,
|
||||
itemKind,
|
||||
hasSingleColumn,
|
||||
}: TanStackRowCellsProps<TData>): JSX.Element {
|
||||
// Only re-render this row when ITS hover state changes
|
||||
const hasHovered = useIsRowHovered(row.id);
|
||||
const rowData = row.original;
|
||||
const visibleCells = row.getVisibleCells();
|
||||
const lastCellIndex = visibleCells.length - 1;
|
||||
|
||||
// Stable references via destructuring
|
||||
const onRowClick = context?.onRowClick;
|
||||
const onRowDeactivate = context?.onRowDeactivate;
|
||||
const isRowActive = context?.isRowActive;
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
const isActive = isRowActive?.(rowData) ?? false;
|
||||
if (isActive && onRowDeactivate) {
|
||||
onRowDeactivate();
|
||||
} else {
|
||||
onRowClick?.(rowData);
|
||||
}
|
||||
}, [isRowActive, onRowDeactivate, onRowClick, rowData]);
|
||||
|
||||
if (itemKind === 'expansion') {
|
||||
return (
|
||||
<td
|
||||
colSpan={context?.colCount ?? 1}
|
||||
className={tableStyles.tableCellExpansion}
|
||||
>
|
||||
{context?.renderExpandedRow?.(rowData)}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{visibleCells.map((cell, index) => {
|
||||
const isLastCell = index === lastCellIndex;
|
||||
return (
|
||||
<TanStackRowCell
|
||||
key={cell.id}
|
||||
cell={cell}
|
||||
hasSingleColumn={hasSingleColumn}
|
||||
isLastCell={isLastCell}
|
||||
hasHovered={hasHovered}
|
||||
rowData={rowData}
|
||||
onClick={handleClick}
|
||||
renderRowActions={context?.renderRowActions}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Custom comparison - only re-render when row data changes
|
||||
function areRowCellsPropsEqual<TData>(
|
||||
prev: Readonly<TanStackRowCellsProps<TData>>,
|
||||
next: Readonly<TanStackRowCellsProps<TData>>,
|
||||
): boolean {
|
||||
return (
|
||||
// Row identity
|
||||
prev.row.id === next.row.id &&
|
||||
// Row kind (row vs expansion)
|
||||
prev.itemKind === next.itemKind &&
|
||||
// Row data reference
|
||||
prev.row.original === next.row.original &&
|
||||
// Layout
|
||||
prev.hasSingleColumn === next.hasSingleColumn &&
|
||||
// Context callbacks for click handlers and row actions
|
||||
prev.context?.onRowClick === next.context?.onRowClick &&
|
||||
prev.context?.onRowDeactivate === next.context?.onRowDeactivate &&
|
||||
prev.context?.isRowActive === next.context?.isRowActive &&
|
||||
prev.context?.renderRowActions === next.context?.renderRowActions &&
|
||||
prev.context?.renderExpandedRow === next.context?.renderExpandedRow &&
|
||||
prev.context?.colCount === next.context?.colCount
|
||||
);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const TanStackRowCells = memo(
|
||||
TanStackRowCellsInner,
|
||||
areRowCellsPropsEqual as any,
|
||||
) as <T>(props: TanStackRowCellsProps<T>) => JSX.Element;
|
||||
|
||||
export default TanStackRowCells;
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { memo } from 'react';
|
||||
import type { Cell } from '@tanstack/react-table';
|
||||
import { flexRender } from '@tanstack/react-table';
|
||||
import cx from 'classnames';
|
||||
|
||||
import tableStyles from './TanStackTable.module.scss';
|
||||
|
||||
export type TanStackRowCellProps<TData> = {
|
||||
cell: Cell<TData, unknown>;
|
||||
hasSingleColumn: boolean;
|
||||
isLastCell: boolean;
|
||||
hasHovered: boolean;
|
||||
rowData: TData;
|
||||
onClick: () => void;
|
||||
renderRowActions?: (row: TData) => ReactNode;
|
||||
};
|
||||
|
||||
function TanStackRowCellInner<TData>({
|
||||
cell,
|
||||
hasSingleColumn,
|
||||
isLastCell,
|
||||
hasHovered,
|
||||
rowData,
|
||||
onClick,
|
||||
renderRowActions,
|
||||
}: TanStackRowCellProps<TData>): JSX.Element {
|
||||
return (
|
||||
<td
|
||||
className={cx(tableStyles.tableCell, 'tanstack-cell-' + cell.column.id)}
|
||||
data-single-column={hasSingleColumn || undefined}
|
||||
onClick={onClick}
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
{isLastCell && hasHovered && renderRowActions && (
|
||||
<span className={tableStyles.tableViewRowActions}>
|
||||
{renderRowActions(rowData)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
function areTanStackRowCellPropsEqual<TData>(
|
||||
prev: Readonly<TanStackRowCellProps<TData>>,
|
||||
next: Readonly<TanStackRowCellProps<TData>>,
|
||||
): boolean {
|
||||
return (
|
||||
prev.cell.id === next.cell.id &&
|
||||
prev.cell.column.id === next.cell.column.id &&
|
||||
Object.is(prev.cell.getValue(), next.cell.getValue()) &&
|
||||
prev.hasSingleColumn === next.hasSingleColumn &&
|
||||
prev.isLastCell === next.isLastCell &&
|
||||
prev.hasHovered === next.hasHovered &&
|
||||
prev.onClick === next.onClick &&
|
||||
prev.renderRowActions === next.renderRowActions &&
|
||||
prev.rowData === next.rowData
|
||||
);
|
||||
}
|
||||
|
||||
const TanStackRowCellMemo = memo(
|
||||
TanStackRowCellInner,
|
||||
areTanStackRowCellPropsEqual,
|
||||
);
|
||||
|
||||
TanStackRowCellMemo.displayName = 'TanStackRowCell';
|
||||
|
||||
export const TanStackRowCell = TanStackRowCellMemo as typeof TanStackRowCellInner;
|
||||
@@ -0,0 +1,105 @@
|
||||
.tanStackTable {
|
||||
width: 100%;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
table-layout: fixed;
|
||||
min-width: 100%;
|
||||
max-width: 100%;
|
||||
|
||||
& td,
|
||||
& th {
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
vertical-align: middle;
|
||||
}
|
||||
}
|
||||
|
||||
.tableCellText {
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.07px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
width: auto;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: var(--tanstack-plain-body-line-clamp, 1);
|
||||
line-clamp: var(--tanstack-plain-body-line-clamp, 1);
|
||||
font-size: var(--tanstack-plain-cell-font-size, 14px);
|
||||
line-height: var(--tanstack-plain-cell-line-height, 18px);
|
||||
color: var(--l2-foreground);
|
||||
max-width: 100%;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.tableViewRowActions {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 8px;
|
||||
left: auto;
|
||||
transform: translateY(-50%);
|
||||
margin: 0;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
.tableCell {
|
||||
padding: 0.3rem;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.07px;
|
||||
font-size: var(--tanstack-plain-cell-font-size, 14px);
|
||||
line-height: var(--tanstack-plain-cell-line-height, 18px);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.tableRow {
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
|
||||
&:hover {
|
||||
.tableCell {
|
||||
background-color: var(--row-hover-bg) !important;
|
||||
}
|
||||
}
|
||||
|
||||
&.tableRowActive {
|
||||
.tableCell {
|
||||
background-color: var(--row-active-bg) !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tableHeaderCell {
|
||||
padding: 0.3rem;
|
||||
height: 36px;
|
||||
text-align: left;
|
||||
font-size: 14px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.07px;
|
||||
border-top: 1px solid var(--l2-border);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
border-left: 1px solid var(--l2-border);
|
||||
box-shadow: inset 0 -1px 0 var(--l2-border);
|
||||
color: var(--l1-foreground);
|
||||
|
||||
// TODO: Remove this once background color (l1) is matching the actual background color of the page
|
||||
&[data-dark-mode='true'] {
|
||||
background: #0b0c0d;
|
||||
}
|
||||
|
||||
&[data-dark-mode='false'] {
|
||||
background: #fdfdfd;
|
||||
}
|
||||
}
|
||||
|
||||
.tableRowExpansion {
|
||||
display: table-row;
|
||||
}
|
||||
|
||||
.tableCellExpansion {
|
||||
padding: 0.5rem;
|
||||
vertical-align: top;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import cx from 'classnames';
|
||||
|
||||
import tableStyles from './TanStackTable.module.scss';
|
||||
|
||||
export type TanStackTableTextProps = {
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function TanStackTableText({
|
||||
children,
|
||||
className,
|
||||
}: TanStackTableTextProps): JSX.Element {
|
||||
return (
|
||||
<span className={cx(tableStyles.tableCellText, className)}>{children}</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default TanStackTableText;
|
||||
@@ -0,0 +1,135 @@
|
||||
.tanstackTableViewWrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.tanstackFixedCol {
|
||||
width: 32px;
|
||||
min-width: 32px;
|
||||
max-width: 32px;
|
||||
}
|
||||
|
||||
.tanstackFillerCol {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tanstackActionsCol {
|
||||
width: 0;
|
||||
min-width: 0;
|
||||
max-width: 0;
|
||||
}
|
||||
|
||||
.tanstackLoadMoreContainer {
|
||||
width: 100%;
|
||||
min-height: 56px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 8px 0 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.tanstackTableVirtuoso {
|
||||
width: 100%;
|
||||
overflow-x: scroll;
|
||||
}
|
||||
|
||||
.tanstackTableFootLoaderCell {
|
||||
text-align: center;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.tanstackTableVirtuosoScroll {
|
||||
width: 100%;
|
||||
overflow-x: scroll;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--bg-slate-300) transparent;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-corner {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-slate-300);
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--bg-slate-200);
|
||||
}
|
||||
|
||||
&.cellTypographySmall {
|
||||
--tanstack-plain-cell-font-size: 11px;
|
||||
--tanstack-plain-cell-line-height: 16px;
|
||||
|
||||
:global(table tr td),
|
||||
:global(table thead th) {
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
|
||||
&.cellTypographyMedium {
|
||||
--tanstack-plain-cell-font-size: 13px;
|
||||
--tanstack-plain-cell-line-height: 20px;
|
||||
|
||||
:global(table tr td),
|
||||
:global(table thead th) {
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
|
||||
&.cellTypographyLarge {
|
||||
--tanstack-plain-cell-font-size: 14px;
|
||||
--tanstack-plain-cell-line-height: 24px;
|
||||
|
||||
:global(table tr td),
|
||||
:global(table thead th) {
|
||||
font-size: 14px;
|
||||
line-height: 24px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tanstackLoadingOverlay {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 2rem;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
pointer-events: none;
|
||||
z-index: 3;
|
||||
border-radius: 8px;
|
||||
padding: 8px 16px;
|
||||
}
|
||||
|
||||
:global(.lightMode) .tanstackTableVirtuosoScroll {
|
||||
scrollbar-color: var(--bg-vanilla-300) transparent;
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-vanilla-300);
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--bg-vanilla-100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Table } from '@tanstack/react-table';
|
||||
|
||||
import type { TableColumnDef, TanStackTableProps } from './types';
|
||||
import { getColumnMinWidthPx } from './utils';
|
||||
|
||||
import viewStyles from './TanStackTableView.module.scss';
|
||||
|
||||
export function VirtuosoTableColGroup<TData>({
|
||||
columns,
|
||||
columnSizingProp,
|
||||
table,
|
||||
}: {
|
||||
columns: TableColumnDef<TData>[];
|
||||
columnSizingProp: TanStackTableProps<TData>['columnSizing'];
|
||||
table: Table<TData>;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<colgroup>
|
||||
{columns.map((column, colIndex) => {
|
||||
const columnId = column.id;
|
||||
const isFixedColumn = column.width?.fixed != null;
|
||||
const minWidthPx = getColumnMinWidthPx(column);
|
||||
const persistedWidth = columnSizingProp?.[columnId];
|
||||
const computedWidth = table.getColumn(columnId)?.getSize();
|
||||
const effectiveWidth = persistedWidth ?? computedWidth;
|
||||
if (isFixedColumn) {
|
||||
return <col key={columnId} className={viewStyles.tanstackFixedCol} />;
|
||||
}
|
||||
const isLastColumn = colIndex === columns.length - 1;
|
||||
if (isLastColumn) {
|
||||
return (
|
||||
<col
|
||||
key={columnId}
|
||||
style={{ width: '100%', minWidth: `${minWidthPx}px` }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const widthPx =
|
||||
effectiveWidth != null ? Math.max(effectiveWidth, minWidthPx) : minWidthPx;
|
||||
return (
|
||||
<col
|
||||
key={columnId}
|
||||
style={{
|
||||
width: `${widthPx}px`,
|
||||
minWidth: `${minWidthPx}px`,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</colgroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
jest.mock('../TanStackTable.module.scss', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
tableRow: 'tableRow',
|
||||
tableRowActive: 'tableRowActive',
|
||||
tableRowExpansion: 'tableRowExpansion',
|
||||
},
|
||||
}));
|
||||
|
||||
import { render, screen } from '@testing-library/react';
|
||||
|
||||
import TanStackCustomTableRow from '../TanStackCustomTableRow';
|
||||
import type { FlatItem, TableRowContext } from '../types';
|
||||
|
||||
const makeItem = (id: string): FlatItem<{ id: string }> => ({
|
||||
kind: 'row',
|
||||
row: { original: { id } } as never,
|
||||
});
|
||||
|
||||
const virtuosoAttrs = {
|
||||
'data-index': 0,
|
||||
'data-item-index': 0,
|
||||
'data-known-size': 40,
|
||||
} as const;
|
||||
|
||||
describe('TanStackCustomTableRow', () => {
|
||||
it('renders children', async () => {
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
{...virtuosoAttrs}
|
||||
item={makeItem('1')}
|
||||
context={undefined}
|
||||
>
|
||||
<td>cell</td>
|
||||
</TanStackCustomTableRow>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(await screen.findByText('cell')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies active class when isRowActive returns true', () => {
|
||||
const ctx: TableRowContext<{ id: string }> = {
|
||||
isRowActive: (row) => row.id === '1',
|
||||
colCount: 1,
|
||||
};
|
||||
const { container } = render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
{...virtuosoAttrs}
|
||||
item={makeItem('1')}
|
||||
context={ctx as never}
|
||||
>
|
||||
<td>x</td>
|
||||
</TanStackCustomTableRow>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(container.querySelector('tr')).toHaveClass('tableRowActive');
|
||||
});
|
||||
|
||||
it('does not apply active class when isRowActive returns false', () => {
|
||||
const ctx: TableRowContext<{ id: string }> = {
|
||||
isRowActive: (row) => row.id === 'other',
|
||||
colCount: 1,
|
||||
};
|
||||
const { container } = render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
{...virtuosoAttrs}
|
||||
item={makeItem('1')}
|
||||
context={ctx as never}
|
||||
>
|
||||
<td>x</td>
|
||||
</TanStackCustomTableRow>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(container.querySelector('tr')).not.toHaveClass('tableRowActive');
|
||||
});
|
||||
|
||||
it('renders expansion row without RowHoverContext when kind is expansion', () => {
|
||||
const item: FlatItem<{ id: string }> = {
|
||||
kind: 'expansion',
|
||||
row: { original: { id: '1' } } as never,
|
||||
};
|
||||
const { container } = render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow {...virtuosoAttrs} item={item} context={undefined}>
|
||||
<td>expanded content</td>
|
||||
</TanStackCustomTableRow>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(container.querySelector('tr')).toHaveClass('tableRowExpansion');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
import TanStackHeaderRow from '../TanStackHeaderRow';
|
||||
import type { TableColumnDef } from '../types';
|
||||
|
||||
jest.mock('@dnd-kit/sortable', () => ({
|
||||
useSortable: (): any => ({
|
||||
attributes: {},
|
||||
listeners: {},
|
||||
setNodeRef: jest.fn(),
|
||||
setActivatorNodeRef: jest.fn(),
|
||||
transform: null,
|
||||
transition: null,
|
||||
isDragging: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
const col = (
|
||||
id: string,
|
||||
overrides?: Partial<TableColumnDef<unknown>>,
|
||||
): TableColumnDef<unknown> => ({
|
||||
id,
|
||||
header: id,
|
||||
cell: (): null => null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const header = {
|
||||
id: 'col',
|
||||
column: {
|
||||
getCanResize: () => true,
|
||||
getIsResizing: () => false,
|
||||
columnDef: { header: 'col' },
|
||||
},
|
||||
getResizeHandler: () => jest.fn(),
|
||||
getContext: () => ({}),
|
||||
} as never;
|
||||
|
||||
describe('TanStackHeaderRow', () => {
|
||||
it('renders column title', () => {
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={col('timestamp', { header: 'timestamp' })}
|
||||
header={header}
|
||||
isDarkMode={false}
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
expect(screen.getByTitle('Timestamp')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows grip icon when enableMove is not false and pin is not set', () => {
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={col('body')}
|
||||
header={header}
|
||||
isDarkMode={false}
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /drag body/i }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does NOT show grip icon when pin is set', () => {
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={col('indicator', { pin: 'left' })}
|
||||
header={header}
|
||||
isDarkMode={false}
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /drag/i }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows remove button when enableRemove and canRemoveColumn are true', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onRemoveColumn = jest.fn();
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={col('name', { enableRemove: true })}
|
||||
header={header}
|
||||
isDarkMode={false}
|
||||
hasSingleColumn={false}
|
||||
canRemoveColumn
|
||||
onRemoveColumn={onRemoveColumn}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
await user.click(screen.getByRole('button', { name: /column actions/i }));
|
||||
await user.click(await screen.findByText(/remove column/i));
|
||||
expect(onRemoveColumn).toHaveBeenCalledWith('name');
|
||||
});
|
||||
|
||||
it('does NOT show remove button when enableRemove is absent', () => {
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={col('name')}
|
||||
header={header}
|
||||
isDarkMode={false}
|
||||
hasSingleColumn={false}
|
||||
canRemoveColumn
|
||||
onRemoveColumn={jest.fn()}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /column actions/i }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
import TanStackRowCells from '../TanStackRow';
|
||||
import type { TableRowContext } from '../types';
|
||||
|
||||
const flexRenderMock = jest.fn((def: unknown) =>
|
||||
typeof def === 'function' ? def({}) : def,
|
||||
);
|
||||
jest.mock('@tanstack/react-table', () => ({
|
||||
flexRender: (def: unknown, _ctx?: unknown): unknown => flexRenderMock(def),
|
||||
}));
|
||||
|
||||
type Row = { id: string };
|
||||
|
||||
function buildMockRow(
|
||||
cells: { id: string }[],
|
||||
rowData: Row = { id: 'r1' },
|
||||
): Parameters<typeof TanStackRowCells>[0]['row'] {
|
||||
return {
|
||||
original: rowData,
|
||||
getVisibleCells: () =>
|
||||
cells.map((c, i) => ({
|
||||
id: `cell-${i}`,
|
||||
column: {
|
||||
id: c.id,
|
||||
columnDef: { cell: (): string => `content-${c.id}` },
|
||||
},
|
||||
getContext: (): Record<string, unknown> => ({}),
|
||||
getValue: (): string => `content-${c.id}`,
|
||||
})),
|
||||
} as never;
|
||||
}
|
||||
|
||||
describe('TanStackRowCells', () => {
|
||||
beforeEach(() => flexRenderMock.mockClear());
|
||||
|
||||
it('renders a cell per visible column', () => {
|
||||
const row = buildMockRow([{ id: 'col-a' }, { id: 'col-b' }]);
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells<Row>
|
||||
row={row as never}
|
||||
context={undefined}
|
||||
itemKind="row"
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(screen.getAllByRole('cell')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('calls onRowClick when a cell is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onRowClick = jest.fn();
|
||||
const ctx: TableRowContext<Row> = { colCount: 1, onRowClick };
|
||||
const row = buildMockRow([{ id: 'body' }]);
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells<Row>
|
||||
row={row as never}
|
||||
context={ctx}
|
||||
itemKind="row"
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
await user.click(screen.getAllByRole('cell')[0]);
|
||||
expect(onRowClick).toHaveBeenCalledWith({ id: 'r1' });
|
||||
});
|
||||
|
||||
it('calls onRowDeactivate instead of onRowClick when row is active', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onRowClick = jest.fn();
|
||||
const onRowDeactivate = jest.fn();
|
||||
const ctx: TableRowContext<Row> = {
|
||||
colCount: 1,
|
||||
onRowClick,
|
||||
onRowDeactivate,
|
||||
isRowActive: () => true,
|
||||
};
|
||||
const row = buildMockRow([{ id: 'body' }]);
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells<Row>
|
||||
row={row as never}
|
||||
context={ctx}
|
||||
itemKind="row"
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
await user.click(screen.getAllByRole('cell')[0]);
|
||||
expect(onRowDeactivate).toHaveBeenCalled();
|
||||
expect(onRowClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not render renderRowActions before hover', () => {
|
||||
const ctx: TableRowContext<Row> = {
|
||||
colCount: 1,
|
||||
renderRowActions: () => <button type="button">action</button>,
|
||||
};
|
||||
const row = buildMockRow([{ id: 'body' }]);
|
||||
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells<Row>
|
||||
row={row as never}
|
||||
context={ctx}
|
||||
itemKind="row"
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
// Row actions are not rendered until hover (useIsRowHovered returns false by default)
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'action' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders expansion cell with renderExpandedRow content', async () => {
|
||||
const row = {
|
||||
original: { id: 'r1' },
|
||||
getVisibleCells: () => [],
|
||||
} as never;
|
||||
const ctx: TableRowContext<Row> = {
|
||||
colCount: 3,
|
||||
renderExpandedRow: (r) => <div>expanded-{r.id}</div>,
|
||||
};
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells<Row>
|
||||
row={row as never}
|
||||
context={ctx}
|
||||
itemKind="expansion"
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(await screen.findByText('expanded-r1')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { forwardRef } from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
|
||||
import TanStackTable from '../index';
|
||||
import type { TableColumnDef, TanStackTableProps } from '../types';
|
||||
|
||||
jest.mock('react-virtuoso', () => ({
|
||||
TableVirtuoso: forwardRef<unknown, { fixedHeaderContent?: () => JSX.Element }>(
|
||||
function MockVirtuoso({ fixedHeaderContent }, _ref) {
|
||||
return <div data-testid="virtuoso">{fixedHeaderContent?.()}</div>;
|
||||
},
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock('../useTableParams', () => ({
|
||||
useTableParams: (): Record<string, unknown> => ({
|
||||
page: 1,
|
||||
limit: 50,
|
||||
orderBy: null,
|
||||
setPage: jest.fn(),
|
||||
setLimit: jest.fn(),
|
||||
setOrderBy: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../../Spinner', () => ({
|
||||
__esModule: true,
|
||||
default: ({ tip }: { tip: string }): JSX.Element => (
|
||||
<div data-testid="spinner">{tip}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useDarkMode', () => ({
|
||||
useIsDarkMode: (): boolean => false,
|
||||
}));
|
||||
|
||||
type Row = { id: string };
|
||||
|
||||
const col = (): TableColumnDef<Row> => ({
|
||||
id: 'id',
|
||||
header: 'ID',
|
||||
cell: ({ row }): string => row.id,
|
||||
accessorKey: 'id',
|
||||
});
|
||||
|
||||
const baseProps: TanStackTableProps<Row> = {
|
||||
data: [{ id: '1' }],
|
||||
columns: [col()],
|
||||
};
|
||||
|
||||
describe('TanStackTable', () => {
|
||||
it('renders virtuoso when not loading', () => {
|
||||
render(<TanStackTable {...baseProps} />);
|
||||
expect(screen.getByTestId('virtuoso')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows loading spinner overlay when isLoading is true', () => {
|
||||
render(<TanStackTable {...baseProps} isLoading />);
|
||||
expect(screen.getByTestId('spinner')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('passes loadingTip to spinner', () => {
|
||||
render(
|
||||
<TanStackTable {...baseProps} isLoading loadingTip="Fetching hosts" />,
|
||||
);
|
||||
expect(screen.getByTestId('spinner')).toHaveTextContent('Fetching hosts');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
|
||||
import type { TableColumnDef } from '../types';
|
||||
import { useTableColumns } from '../useTableColumns';
|
||||
|
||||
const mockGet = jest.fn();
|
||||
const mockSet = jest.fn();
|
||||
|
||||
jest.mock('api/browser/localstorage/get', () => ({
|
||||
__esModule: true,
|
||||
default: (key: string): string | null => mockGet(key),
|
||||
}));
|
||||
|
||||
jest.mock('api/browser/localstorage/set', () => ({
|
||||
__esModule: true,
|
||||
default: (key: string, value: string): void => mockSet(key, value),
|
||||
}));
|
||||
|
||||
type Row = { id: string; name: string };
|
||||
|
||||
const col = (id: string, pin?: 'left' | 'right'): TableColumnDef<Row> => ({
|
||||
id,
|
||||
header: id,
|
||||
cell: ({ value }): string => String(value),
|
||||
...(pin ? { pin } : {}),
|
||||
});
|
||||
|
||||
describe('useTableColumns', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockGet.mockReturnValue(null);
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
jest.runOnlyPendingTimers();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('returns definitions in original order when no persisted state', () => {
|
||||
const defs = [col('timestamp'), col('body'), col('name')];
|
||||
const { result } = renderHook(() => useTableColumns(defs));
|
||||
expect(result.current.tableProps.columns.map((c) => c.id)).toEqual([
|
||||
'timestamp',
|
||||
'body',
|
||||
'name',
|
||||
]);
|
||||
});
|
||||
|
||||
it('restores column order from localStorage', () => {
|
||||
mockGet.mockReturnValue(
|
||||
JSON.stringify({
|
||||
columnOrder: ['name', 'body', 'timestamp'],
|
||||
columnSizing: {},
|
||||
removedColumnIds: [],
|
||||
}),
|
||||
);
|
||||
const defs = [col('timestamp'), col('body'), col('name')];
|
||||
const { result } = renderHook(() =>
|
||||
useTableColumns(defs, { storageKey: 'test_table' }),
|
||||
);
|
||||
expect(result.current.tableProps.columns.map((c) => c.id)).toEqual([
|
||||
'name',
|
||||
'body',
|
||||
'timestamp',
|
||||
]);
|
||||
});
|
||||
|
||||
it('pinned columns always stay first regardless of persisted order', () => {
|
||||
mockGet.mockReturnValue(
|
||||
JSON.stringify({
|
||||
columnOrder: ['body', 'indicator'],
|
||||
columnSizing: {},
|
||||
removedColumnIds: [],
|
||||
}),
|
||||
);
|
||||
const defs = [col('indicator', 'left'), col('body')];
|
||||
const { result } = renderHook(() =>
|
||||
useTableColumns(defs, { storageKey: 'test_table' }),
|
||||
);
|
||||
expect(result.current.tableProps.columns[0].id).toBe('indicator');
|
||||
});
|
||||
|
||||
it('excludes removed columns from tableProps.columns', () => {
|
||||
mockGet.mockReturnValue(
|
||||
JSON.stringify({
|
||||
columnOrder: [],
|
||||
columnSizing: {},
|
||||
removedColumnIds: ['name'],
|
||||
}),
|
||||
);
|
||||
const defs = [col('body'), col('name')];
|
||||
const { result } = renderHook(() =>
|
||||
useTableColumns(defs, { storageKey: 'test_table' }),
|
||||
);
|
||||
expect(result.current.tableProps.columns.map((c) => c.id)).toEqual(['body']);
|
||||
expect(result.current.activeColumnIds).toEqual(['body']);
|
||||
});
|
||||
|
||||
it('activeColumnIds reflects only currently visible columns', () => {
|
||||
const defs = [col('body'), col('timestamp'), col('name')];
|
||||
const { result } = renderHook(() => useTableColumns(defs));
|
||||
expect(result.current.activeColumnIds).toEqual(['body', 'timestamp', 'name']);
|
||||
});
|
||||
|
||||
it('onRemoveColumn removes column and persists after debounce', () => {
|
||||
const defs = [col('body'), col('name')];
|
||||
const { result } = renderHook(() =>
|
||||
useTableColumns(defs, { storageKey: 'test_table' }),
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.tableProps.onRemoveColumn('body');
|
||||
});
|
||||
|
||||
expect(result.current.tableProps.columns.map((c) => c.id)).toEqual(['name']);
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
expect(mockSet).toHaveBeenCalledWith(
|
||||
'test_table',
|
||||
expect.stringContaining('"removedColumnIds":["body"]'),
|
||||
);
|
||||
});
|
||||
|
||||
it('onColumnOrderChange updates column order', () => {
|
||||
const defs = [col('a'), col('b'), col('c')];
|
||||
const { result } = renderHook(() => useTableColumns(defs));
|
||||
|
||||
act(() => {
|
||||
result.current.tableProps.onColumnOrderChange([
|
||||
col('c'),
|
||||
col('b'),
|
||||
col('a'),
|
||||
]);
|
||||
});
|
||||
|
||||
expect(result.current.tableProps.columns.map((c) => c.id)).toEqual([
|
||||
'c',
|
||||
'b',
|
||||
'a',
|
||||
]);
|
||||
});
|
||||
|
||||
it('restores column sizing from localStorage', () => {
|
||||
mockGet.mockReturnValue(
|
||||
JSON.stringify({
|
||||
columnOrder: [],
|
||||
columnSizing: { body: 400 },
|
||||
removedColumnIds: [],
|
||||
}),
|
||||
);
|
||||
const defs = [col('body')];
|
||||
const { result } = renderHook(() =>
|
||||
useTableColumns(defs, { storageKey: 'test_table' }),
|
||||
);
|
||||
expect(result.current.tableProps.columnSizing).toEqual({ body: 400 });
|
||||
});
|
||||
|
||||
it('debounces sizing writes to localStorage', () => {
|
||||
const defs = [col('body')];
|
||||
const { result } = renderHook(() =>
|
||||
useTableColumns(defs, { storageKey: 'test_table' }),
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.tableProps.onColumnSizingChange({ body: 500 });
|
||||
});
|
||||
expect(mockSet).not.toHaveBeenCalled();
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(250);
|
||||
});
|
||||
expect(mockSet).toHaveBeenCalledWith(
|
||||
'test_table',
|
||||
expect.stringContaining('"body":500'),
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to definitions order when localStorage is corrupt', () => {
|
||||
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mockGet.mockReturnValue('not-json');
|
||||
const defs = [col('a'), col('b')];
|
||||
const { result } = renderHook(() =>
|
||||
useTableColumns(defs, { storageKey: 'test_table' }),
|
||||
);
|
||||
expect(result.current.tableProps.columns.map((c) => c.id)).toEqual([
|
||||
'a',
|
||||
'b',
|
||||
]);
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
|
||||
import { useTableParams } from '../useTableParams';
|
||||
|
||||
jest.mock('utils/nuqsParsers', () => ({
|
||||
parseAsJsonNoValidate: (): any => ({
|
||||
withDefault: (d: unknown): any => ({
|
||||
withOptions: (): any => ({ _default: d }),
|
||||
_default: d,
|
||||
}),
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('nuqs', () => ({
|
||||
parseAsInteger: {
|
||||
withDefault: (d: number): any => ({
|
||||
withOptions: (): any => ({ _default: d }),
|
||||
_default: d,
|
||||
}),
|
||||
},
|
||||
parseAsJson: (): any => ({
|
||||
withDefault: (d: unknown): any => ({
|
||||
withOptions: (): any => ({ _default: d }),
|
||||
_default: d,
|
||||
}),
|
||||
}),
|
||||
useQueryState: jest
|
||||
.fn()
|
||||
.mockImplementation((_key: string, parser: { _default: unknown }) => {
|
||||
const [val, setVal] = (jest.requireActual(
|
||||
'react',
|
||||
) as typeof import('react')).useState(parser?._default);
|
||||
return [val, setVal];
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('useTableParams (local mode — enableQueryParams not set)', () => {
|
||||
it('returns default page=1 and limit=50', () => {
|
||||
const { result } = renderHook(() => useTableParams());
|
||||
expect(result.current.page).toBe(1);
|
||||
expect(result.current.limit).toBe(50);
|
||||
expect(result.current.orderBy).toBeNull();
|
||||
});
|
||||
|
||||
it('respects custom defaults', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useTableParams(undefined, { page: 2, limit: 25 }),
|
||||
);
|
||||
expect(result.current.page).toBe(2);
|
||||
expect(result.current.limit).toBe(25);
|
||||
});
|
||||
|
||||
it('setPage updates page', () => {
|
||||
const { result } = renderHook(() => useTableParams());
|
||||
act(() => {
|
||||
result.current.setPage(3);
|
||||
});
|
||||
expect(result.current.page).toBe(3);
|
||||
});
|
||||
|
||||
it('setLimit updates limit', () => {
|
||||
const { result } = renderHook(() => useTableParams());
|
||||
act(() => {
|
||||
result.current.setLimit(100);
|
||||
});
|
||||
expect(result.current.limit).toBe(100);
|
||||
});
|
||||
|
||||
it('setOrderBy updates orderBy', () => {
|
||||
const { result } = renderHook(() => useTableParams());
|
||||
act(() => {
|
||||
result.current.setOrderBy({ columnId: 'cpu', desc: true });
|
||||
});
|
||||
expect(result.current.orderBy).toEqual({ columnId: 'cpu', desc: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('useTableParams (URL mode — enableQueryParams set)', () => {
|
||||
it('uses nuqs state when enableQueryParams=true', () => {
|
||||
const { result } = renderHook(() => useTableParams(true));
|
||||
expect(result.current.page).toBe(1);
|
||||
act(() => {
|
||||
result.current.setPage(5);
|
||||
});
|
||||
expect(result.current.page).toBe(5);
|
||||
});
|
||||
|
||||
it('uses prefixed keys when enableQueryParams is a string', () => {
|
||||
const { result } = renderHook(() => useTableParams('pods', { page: 2 }));
|
||||
expect(result.current.page).toBe(2);
|
||||
act(() => {
|
||||
result.current.setPage(4);
|
||||
});
|
||||
expect(result.current.page).toBe(4);
|
||||
});
|
||||
|
||||
it('local state is ignored when enableQueryParams is set', () => {
|
||||
const { result: local } = renderHook(() => useTableParams());
|
||||
const { result: url } = renderHook(() => useTableParams(true));
|
||||
act(() => {
|
||||
local.current.setPage(99);
|
||||
});
|
||||
expect(url.current.page).toBe(1);
|
||||
});
|
||||
});
|
||||
618
frontend/src/components/TanStackTableView/index.tsx
Normal file
618
frontend/src/components/TanStackTableView/index.tsx
Normal file
@@ -0,0 +1,618 @@
|
||||
import type { ComponentProps, CSSProperties, Ref } from 'react';
|
||||
import {
|
||||
forwardRef,
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import type { TableComponents } from 'react-virtuoso';
|
||||
import { TableVirtuoso, TableVirtuosoHandle } from 'react-virtuoso';
|
||||
import {
|
||||
DndContext,
|
||||
DragEndEvent,
|
||||
PointerSensor,
|
||||
pointerWithin,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
arrayMove,
|
||||
horizontalListSortingStrategy,
|
||||
SortableContext,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { TooltipProvider } from '@signozhq/ui';
|
||||
import type { Row } from '@tanstack/react-table';
|
||||
import {
|
||||
ColumnDef,
|
||||
ColumnPinningState,
|
||||
ExpandedState,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
} from '@tanstack/react-table';
|
||||
import { Pagination } from 'antd';
|
||||
import cx from 'classnames';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
|
||||
import Spinner from '../Spinner';
|
||||
import { RowHoverProvider } from './RowHoverContext';
|
||||
import TanStackCustomTableRow from './TanStackCustomTableRow';
|
||||
import TanStackHeaderRow from './TanStackHeaderRow';
|
||||
import TanStackRowCells from './TanStackRow';
|
||||
import TanStackTableText from './TanStackTableText';
|
||||
import {
|
||||
FlatItem,
|
||||
TableRowContext,
|
||||
TanStackTableHandle,
|
||||
TanStackTableProps,
|
||||
} from './types';
|
||||
import { useTableParams } from './useTableParams';
|
||||
import { buildTanstackColumnDef } from './utils';
|
||||
import { VirtuosoTableColGroup } from './VirtuosoTableColGroup';
|
||||
|
||||
import tableStyles from './TanStackTable.module.scss';
|
||||
import viewStyles from './TanStackTableView.module.scss';
|
||||
|
||||
const COLUMN_DND_AUTO_SCROLL = {
|
||||
layoutShiftCompensation: false as const,
|
||||
threshold: { x: 0.2, y: 0 },
|
||||
};
|
||||
|
||||
const INCREASE_VIEWPORT_BY = { top: 500, bottom: 500 };
|
||||
|
||||
const PAGINATION_STYLE: CSSProperties = { marginTop: 12, textAlign: 'right' };
|
||||
|
||||
const noopColumnSizing = (): void => {};
|
||||
|
||||
function TanStackTableInner<TData>(
|
||||
{
|
||||
data,
|
||||
columns,
|
||||
columnSizing: columnSizingProp,
|
||||
onColumnSizingChange,
|
||||
onColumnOrderChange,
|
||||
onRemoveColumn,
|
||||
isLoading = false,
|
||||
loadingTip = 'Loading',
|
||||
enableQueryParams,
|
||||
pagination,
|
||||
onEndReached,
|
||||
getRowStyle,
|
||||
getRowClassName,
|
||||
isRowActive,
|
||||
renderRowActions,
|
||||
onRowClick,
|
||||
onRowDeactivate,
|
||||
activeRowIndex,
|
||||
renderExpandedRow,
|
||||
getRowCanExpand,
|
||||
tableScrollerProps,
|
||||
plainTextCellLineClamp,
|
||||
cellTypographySize,
|
||||
}: TanStackTableProps<TData>,
|
||||
forwardedRef: React.ForwardedRef<TanStackTableHandle>,
|
||||
): JSX.Element {
|
||||
const virtuosoRef = useRef<TableVirtuosoHandle | null>(null);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
const { page, limit, setPage, setLimit } = useTableParams(enableQueryParams, {
|
||||
page: pagination?.defaultPage,
|
||||
limit: pagination?.defaultLimit,
|
||||
});
|
||||
|
||||
const [expanded, setExpanded] = useState<ExpandedState>({});
|
||||
|
||||
const columnPinning = useMemo<ColumnPinningState>(
|
||||
() => ({
|
||||
left: columns.filter((c) => c.pin === 'left').map((c) => c.id),
|
||||
right: columns.filter((c) => c.pin === 'right').map((c) => c.id),
|
||||
}),
|
||||
[columns],
|
||||
);
|
||||
|
||||
const tanstackColumns = useMemo<ColumnDef<TData>[]>(
|
||||
() => columns.map((colDef) => buildTanstackColumnDef(colDef, isRowActive)),
|
||||
[columns, isRowActive],
|
||||
);
|
||||
|
||||
const getRowId = useCallback((row: TData, index: number): string => {
|
||||
const r = row as Record<string, unknown>;
|
||||
if (r != null && typeof r.id !== 'undefined') {
|
||||
return String(r.id);
|
||||
}
|
||||
return String(index);
|
||||
}, []);
|
||||
|
||||
const tableGetRowCanExpand = useCallback(
|
||||
(row: Row<TData>): boolean =>
|
||||
getRowCanExpand ? getRowCanExpand(row.original) : true,
|
||||
[getRowCanExpand],
|
||||
);
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns: tanstackColumns,
|
||||
enableColumnResizing: true,
|
||||
enableColumnPinning: true,
|
||||
columnResizeMode: 'onChange',
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getRowId,
|
||||
enableExpanding: Boolean(renderExpandedRow),
|
||||
getRowCanExpand: renderExpandedRow ? tableGetRowCanExpand : undefined,
|
||||
onColumnSizingChange: onColumnSizingChange ?? noopColumnSizing,
|
||||
onExpandedChange: setExpanded,
|
||||
state: {
|
||||
columnSizing: columnSizingProp ?? {},
|
||||
columnPinning,
|
||||
expanded,
|
||||
},
|
||||
});
|
||||
|
||||
const tableRows = table.getRowModel().rows;
|
||||
|
||||
const flatItems = useMemo<FlatItem<TData>[]>(() => {
|
||||
const result: FlatItem<TData>[] = [];
|
||||
for (const row of tableRows) {
|
||||
result.push({ kind: 'row', row });
|
||||
if (renderExpandedRow && row.getIsExpanded()) {
|
||||
result.push({ kind: 'expansion', row });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}, [tableRows, renderExpandedRow]);
|
||||
|
||||
const flatIndexForActiveRow = useMemo(() => {
|
||||
if (activeRowIndex == null || activeRowIndex < 0) {
|
||||
return -1;
|
||||
}
|
||||
for (let i = 0; i < flatItems.length; i++) {
|
||||
const item = flatItems[i];
|
||||
if (item.kind === 'row' && item.row.index === activeRowIndex) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}, [activeRowIndex, flatItems]);
|
||||
|
||||
useEffect(() => {
|
||||
if (flatIndexForActiveRow < 0) {
|
||||
return;
|
||||
}
|
||||
virtuosoRef.current?.scrollToIndex({
|
||||
index: flatIndexForActiveRow,
|
||||
align: 'center',
|
||||
behavior: 'auto',
|
||||
});
|
||||
}, [flatIndexForActiveRow]);
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
|
||||
);
|
||||
|
||||
const columnIds = useMemo(() => columns.map((c) => c.id), [columns]);
|
||||
|
||||
const handleDragEnd = useCallback(
|
||||
(event: DragEndEvent): void => {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id || !onColumnOrderChange) {
|
||||
return;
|
||||
}
|
||||
const activeCol = columns.find((c) => c.id === String(active.id));
|
||||
const overCol = columns.find((c) => c.id === String(over.id));
|
||||
if (
|
||||
!activeCol ||
|
||||
!overCol ||
|
||||
activeCol.pin != null ||
|
||||
overCol.pin != null ||
|
||||
activeCol.enableMove === false
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const oldIndex = columns.findIndex((c) => c.id === String(active.id));
|
||||
const newIndex = columns.findIndex((c) => c.id === String(over.id));
|
||||
if (oldIndex === -1 || newIndex === -1) {
|
||||
return;
|
||||
}
|
||||
onColumnOrderChange(arrayMove(columns, oldIndex, newIndex));
|
||||
},
|
||||
[columns, onColumnOrderChange],
|
||||
);
|
||||
|
||||
const hasSingleColumn = useMemo(
|
||||
() => columns.filter((c) => !c.pin && c.enableRemove !== false).length <= 1,
|
||||
[columns],
|
||||
);
|
||||
|
||||
const canRemoveColumn = !hasSingleColumn;
|
||||
|
||||
const flatHeaders = useMemo(
|
||||
() => table.getFlatHeaders().filter((header) => !header.isPlaceholder),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[tanstackColumns, columnPinning],
|
||||
);
|
||||
|
||||
const columnsById = useMemo(
|
||||
() => new Map(columns.map((c) => [c.id, c] as const)),
|
||||
[columns],
|
||||
);
|
||||
|
||||
const virtuosoContext = useMemo<TableRowContext<TData>>(
|
||||
() => ({
|
||||
getRowStyle,
|
||||
getRowClassName,
|
||||
isRowActive,
|
||||
renderRowActions,
|
||||
onRowClick,
|
||||
onRowDeactivate,
|
||||
renderExpandedRow,
|
||||
colCount: columns.length,
|
||||
isDarkMode,
|
||||
plainTextCellLineClamp,
|
||||
}),
|
||||
[
|
||||
getRowStyle,
|
||||
getRowClassName,
|
||||
isRowActive,
|
||||
renderRowActions,
|
||||
onRowClick,
|
||||
onRowDeactivate,
|
||||
renderExpandedRow,
|
||||
columns.length,
|
||||
isDarkMode,
|
||||
plainTextCellLineClamp,
|
||||
],
|
||||
);
|
||||
|
||||
const itemContent = useCallback(
|
||||
(_index: number, item: FlatItem<TData>): JSX.Element => (
|
||||
<TanStackRowCells
|
||||
row={item.row}
|
||||
itemKind={item.kind}
|
||||
context={virtuosoContext}
|
||||
hasSingleColumn={hasSingleColumn}
|
||||
/>
|
||||
),
|
||||
[virtuosoContext, hasSingleColumn],
|
||||
);
|
||||
|
||||
const tableHeader = useCallback(() => {
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={pointerWithin}
|
||||
onDragEnd={handleDragEnd}
|
||||
autoScroll={COLUMN_DND_AUTO_SCROLL}
|
||||
>
|
||||
<SortableContext items={columnIds} strategy={horizontalListSortingStrategy}>
|
||||
<tr>
|
||||
{flatHeaders.map((header) => {
|
||||
const column = columnsById.get(header.id);
|
||||
if (!column) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<TanStackHeaderRow
|
||||
key={header.id}
|
||||
column={column}
|
||||
header={header}
|
||||
isDarkMode={isDarkMode}
|
||||
hasSingleColumn={hasSingleColumn}
|
||||
onRemoveColumn={onRemoveColumn}
|
||||
canRemoveColumn={canRemoveColumn}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
);
|
||||
}, [
|
||||
sensors,
|
||||
handleDragEnd,
|
||||
columnIds,
|
||||
flatHeaders,
|
||||
columnsById,
|
||||
isDarkMode,
|
||||
hasSingleColumn,
|
||||
onRemoveColumn,
|
||||
canRemoveColumn,
|
||||
]);
|
||||
|
||||
const handleEndReached = useCallback(
|
||||
(index: number): void => {
|
||||
onEndReached?.(index);
|
||||
},
|
||||
[onEndReached],
|
||||
);
|
||||
|
||||
useImperativeHandle(
|
||||
forwardedRef,
|
||||
(): TanStackTableHandle =>
|
||||
new Proxy(
|
||||
{
|
||||
goToPage: (p: number): void => {
|
||||
setPage(p);
|
||||
virtuosoRef.current?.scrollToIndex({
|
||||
index: 0,
|
||||
align: 'start',
|
||||
});
|
||||
},
|
||||
} as TanStackTableHandle,
|
||||
{
|
||||
get(target, prop): unknown {
|
||||
if (prop in target) {
|
||||
return Reflect.get(target, prop);
|
||||
}
|
||||
const v = (virtuosoRef.current as unknown) as Record<string, unknown>;
|
||||
const value = v?.[prop as string];
|
||||
if (typeof value === 'function') {
|
||||
return (value as (...a: unknown[]) => unknown).bind(virtuosoRef.current);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
},
|
||||
),
|
||||
[setPage],
|
||||
);
|
||||
|
||||
const showPagination = Boolean(pagination && !onEndReached);
|
||||
|
||||
const { className: tableScrollerClassName, ...restTableScrollerProps } =
|
||||
tableScrollerProps ?? {};
|
||||
|
||||
const cellTypographyClass = useMemo((): string | undefined => {
|
||||
if (cellTypographySize === 'small') {
|
||||
return viewStyles.cellTypographySmall;
|
||||
}
|
||||
if (cellTypographySize === 'medium') {
|
||||
return viewStyles.cellTypographyMedium;
|
||||
}
|
||||
if (cellTypographySize === 'large') {
|
||||
return viewStyles.cellTypographyLarge;
|
||||
}
|
||||
return undefined;
|
||||
}, [cellTypographySize]);
|
||||
|
||||
const virtuosoClassName = useMemo(
|
||||
() =>
|
||||
cx(
|
||||
viewStyles.tanstackTableVirtuosoScroll,
|
||||
cellTypographyClass,
|
||||
tableScrollerClassName,
|
||||
),
|
||||
[cellTypographyClass, tableScrollerClassName],
|
||||
);
|
||||
|
||||
const virtuosoTableStyle = useMemo(
|
||||
() =>
|
||||
({
|
||||
'--tanstack-plain-body-line-clamp': plainTextCellLineClamp,
|
||||
} as CSSProperties),
|
||||
[plainTextCellLineClamp],
|
||||
);
|
||||
|
||||
type VirtuosoTableComponentProps = ComponentProps<
|
||||
NonNullable<TableComponents<FlatItem<TData>, TableRowContext<TData>>['Table']>
|
||||
>;
|
||||
|
||||
const virtuosoComponents = useMemo(
|
||||
() => ({
|
||||
Table: ({ style, children }: VirtuosoTableComponentProps): JSX.Element => (
|
||||
<table className={tableStyles.tanStackTable} style={style}>
|
||||
<VirtuosoTableColGroup
|
||||
columns={columns}
|
||||
columnSizingProp={columnSizingProp}
|
||||
table={table}
|
||||
/>
|
||||
{children}
|
||||
</table>
|
||||
),
|
||||
TableRow: TanStackCustomTableRow,
|
||||
}),
|
||||
[columns, columnSizingProp, table],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={viewStyles.tanstackTableViewWrapper}>
|
||||
<RowHoverProvider>
|
||||
<TooltipProvider>
|
||||
<TableVirtuoso<FlatItem<TData>, TableRowContext<TData>>
|
||||
className={virtuosoClassName}
|
||||
ref={virtuosoRef}
|
||||
{...restTableScrollerProps}
|
||||
data={flatItems}
|
||||
totalCount={flatItems.length}
|
||||
context={virtuosoContext}
|
||||
increaseViewportBy={INCREASE_VIEWPORT_BY}
|
||||
initialTopMostItemIndex={
|
||||
flatIndexForActiveRow >= 0 ? flatIndexForActiveRow : 0
|
||||
}
|
||||
fixedHeaderContent={tableHeader}
|
||||
itemContent={itemContent}
|
||||
style={virtuosoTableStyle}
|
||||
components={virtuosoComponents}
|
||||
endReached={onEndReached ? handleEndReached : undefined}
|
||||
/>
|
||||
{isLoading && (
|
||||
<div className={viewStyles.tanstackLoadingOverlay}>
|
||||
<Spinner height="35px" tip={loadingTip} />
|
||||
</div>
|
||||
)}
|
||||
{showPagination && pagination && (
|
||||
<Pagination
|
||||
style={PAGINATION_STYLE}
|
||||
current={page}
|
||||
pageSize={limit}
|
||||
total={pagination.total}
|
||||
showSizeChanger
|
||||
onChange={(p, ps): void => {
|
||||
setPage(p);
|
||||
if (ps != null && ps !== limit) {
|
||||
setLimit(ps);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
</RowHoverProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const TanStackTableForward = forwardRef(TanStackTableInner) as <TData>(
|
||||
props: TanStackTableProps<TData> & {
|
||||
ref?: React.Ref<TanStackTableHandle>;
|
||||
},
|
||||
) => JSX.Element;
|
||||
|
||||
const TanStackTableBase = memo(
|
||||
TanStackTableForward,
|
||||
) as typeof TanStackTableForward;
|
||||
|
||||
/**
|
||||
* Virtualized data table built on TanStack Table and `react-virtuoso`: resizable and pinnable columns,
|
||||
* optional drag-to-reorder headers, expandable rows, and Ant Design pagination or infinite scroll.
|
||||
*
|
||||
* @example Minimal usage
|
||||
* ```tsx
|
||||
* import TanStackTable from 'components/TanStackTableView';
|
||||
* import type { TableColumnDef } from 'components/TanStackTableView/types';
|
||||
*
|
||||
* type Row = { id: string; name: string };
|
||||
*
|
||||
* const columns: TableColumnDef<Row>[] = [
|
||||
* {
|
||||
* id: 'name',
|
||||
* header: 'Name',
|
||||
* accessorKey: 'name',
|
||||
* cell: ({ value }) => <TanStackTable.Text>{String(value ?? '')}</TanStackTable.Text>,
|
||||
* },
|
||||
* ];
|
||||
*
|
||||
* function Example(): JSX.Element {
|
||||
* return <TanStackTable<Row> data={rows} columns={columns} />;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @example Column definitions — `accessorFn`, custom header, pinned column
|
||||
* ```tsx
|
||||
* const columns: TableColumnDef<Row>[] = [
|
||||
* {
|
||||
* id: 'id',
|
||||
* header: 'ID',
|
||||
* accessorKey: 'id',
|
||||
* pin: 'left',
|
||||
* width: { min: 80, default: 120 },
|
||||
* cell: ({ value }) => <TanStackTable.Text>{String(value)}</TanStackTable.Text>,
|
||||
* },
|
||||
* {
|
||||
* id: 'computed',
|
||||
* header: () => <span>Computed</span>,
|
||||
* accessorFn: (row) => row.first + row.last,
|
||||
* enableMove: false,
|
||||
* cell: ({ value }) => <TanStackTable.Text>{String(value)}</TanStackTable.Text>,
|
||||
* },
|
||||
* ];
|
||||
* ```
|
||||
*
|
||||
* @example Controlled column sizing and reorder (persist in parent state)
|
||||
* ```tsx
|
||||
* import type { ColumnSizingState } from '@tanstack/react-table';
|
||||
*
|
||||
* const [columnSizing, setColumnSizing] = useState<ColumnSizingState>({});
|
||||
*
|
||||
* <TanStackTable
|
||||
* data={data}
|
||||
* columns={columns}
|
||||
* columnSizing={columnSizing}
|
||||
* onColumnSizingChange={setColumnSizing}
|
||||
* onColumnOrderChange={setColumns}
|
||||
* onRemoveColumn={(id) => setColumns((cols) => cols.filter((c) => c.id !== id))}
|
||||
* />
|
||||
* ```
|
||||
*
|
||||
* @example Pagination (Ant Design). Omit `onEndReached` so the footer pager is shown.
|
||||
* ```tsx
|
||||
* <TanStackTable
|
||||
* data={pageRows}
|
||||
* columns={columns}
|
||||
* pagination={{ total: totalCount, defaultPage: 1, defaultLimit: 20 }}
|
||||
* enableQueryParams
|
||||
* />
|
||||
* ```
|
||||
*
|
||||
* @example Infinite scroll — use `onEndReached` instead of `pagination` (pagination UI is hidden when `onEndReached` is set).
|
||||
* ```tsx
|
||||
* <TanStackTable
|
||||
* data={accumulatedRows}
|
||||
* columns={columns}
|
||||
* onEndReached={(lastIndex) => fetchMore(lastIndex)}
|
||||
* />
|
||||
* ```
|
||||
*
|
||||
* @example Loading overlay and typography for plain string/number cells
|
||||
* ```tsx
|
||||
* <TanStackTable
|
||||
* data={data}
|
||||
* columns={columns}
|
||||
* isLoading={isFetching}
|
||||
* loadingTip="Loading logs…"
|
||||
* cellTypographySize="small"
|
||||
* plainTextCellLineClamp={2}
|
||||
* />
|
||||
* ```
|
||||
*
|
||||
* @example Row styling, selection, and actions
|
||||
* ```tsx
|
||||
* <TanStackTable
|
||||
* data={data}
|
||||
* columns={columns}
|
||||
* isRowActive={(row) => row.id === selectedId}
|
||||
* activeRowIndex={selectedIndex}
|
||||
* onRowClick={(row) => setSelectedId(row.id)}
|
||||
* onRowDeactivate={() => setSelectedId(undefined)}
|
||||
* getRowClassName={(row) => (row.severity === 'error' ? 'row-error' : '')}
|
||||
* getRowStyle={(row) => (row.dimmed ? { opacity: 0.5 } : {})}
|
||||
* renderRowActions={(row) => <Button size="small">Open</Button>}
|
||||
* />
|
||||
* ```
|
||||
*
|
||||
* @example Expandable rows
|
||||
* ```tsx
|
||||
* <TanStackTable
|
||||
* data={data}
|
||||
* columns={columns}
|
||||
* renderExpandedRow={(row) => <pre>{JSON.stringify(row.raw, null, 2)}</pre>}
|
||||
* getRowCanExpand={(row) => Boolean(row.raw)}
|
||||
* />
|
||||
* ```
|
||||
*
|
||||
* @example Imperative handle — `goToPage` plus Virtuoso methods (e.g. `scrollToIndex`)
|
||||
* ```tsx
|
||||
* import type { TanStackTableHandle } from 'components/TanStackTableView/types';
|
||||
*
|
||||
* const ref = useRef<TanStackTableHandle>(null);
|
||||
*
|
||||
* <TanStackTable ref={ref} data={data} columns={columns} pagination={{ total, defaultLimit: 20 }} />;
|
||||
*
|
||||
* ref.current?.goToPage(2);
|
||||
* ref.current?.scrollToIndex({ index: 0, align: 'start' });
|
||||
* ```
|
||||
*
|
||||
* @example Scroll container props (className, `data-testid`, etc.). `data` is reserved by Virtuoso and cannot be passed here.
|
||||
* ```tsx
|
||||
* <TanStackTable
|
||||
* data={data}
|
||||
* columns={columns}
|
||||
* tableScrollerProps={{ className: 'my-table-scroll', 'data-testid': 'logs-table' }}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
const TanStackTable = Object.assign(TanStackTableBase, {
|
||||
Text: TanStackTableText,
|
||||
});
|
||||
|
||||
export default TanStackTable;
|
||||
112
frontend/src/components/TanStackTableView/types.ts
Normal file
112
frontend/src/components/TanStackTableView/types.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
CSSProperties,
|
||||
Dispatch,
|
||||
HTMLAttributes,
|
||||
ReactNode,
|
||||
SetStateAction,
|
||||
} from 'react';
|
||||
import type { TableVirtuosoHandle } from 'react-virtuoso';
|
||||
import type {
|
||||
ColumnSizingState,
|
||||
Row as TanStackRowType,
|
||||
} from '@tanstack/react-table';
|
||||
|
||||
export type SortState = { columnId: string; desc: boolean };
|
||||
|
||||
/** Sets `--tanstack-plain-cell-*` on the scroll root via CSS module classes (no data attributes). */
|
||||
export type CellTypographySize = 'small' | 'medium' | 'large';
|
||||
|
||||
export type TableCellContext<TData> = {
|
||||
row: TData;
|
||||
value: unknown;
|
||||
isActive: boolean;
|
||||
rowIndex: number;
|
||||
isExpanded: boolean;
|
||||
canExpand: boolean;
|
||||
toggleExpanded: () => void;
|
||||
};
|
||||
|
||||
export type TableColumnDef<TData> = {
|
||||
id: string;
|
||||
header: string | (() => ReactNode);
|
||||
cell: (context: TableCellContext<TData>) => ReactNode;
|
||||
accessorKey?: keyof TData & string;
|
||||
accessorFn?: (row: TData) => unknown;
|
||||
pin?: 'left' | 'right';
|
||||
enableMove?: boolean;
|
||||
enableResize?: boolean;
|
||||
enableRemove?: boolean;
|
||||
enableSort?: boolean;
|
||||
width?: {
|
||||
fixed?: number;
|
||||
min?: number;
|
||||
default?: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type FlatItem<TData> =
|
||||
| { kind: 'row'; row: TanStackRowType<TData> }
|
||||
| { kind: 'expansion'; row: TanStackRowType<TData> };
|
||||
|
||||
export type TableRowContext<TData> = {
|
||||
getRowStyle?: (row: TData) => CSSProperties;
|
||||
getRowClassName?: (row: TData) => string;
|
||||
isRowActive?: (row: TData) => boolean;
|
||||
renderRowActions?: (row: TData) => ReactNode;
|
||||
onRowClick?: (row: TData) => void;
|
||||
onRowDeactivate?: () => void;
|
||||
renderExpandedRow?: (row: TData) => ReactNode;
|
||||
colCount: number;
|
||||
isDarkMode?: boolean;
|
||||
/** When set, primitive cell output (string/number/boolean) is wrapped with typography + line-clamp (see `plainTextCellLineClamp` on the table). */
|
||||
plainTextCellLineClamp?: number;
|
||||
};
|
||||
|
||||
export type PaginationProps = {
|
||||
total: number;
|
||||
defaultPage?: number;
|
||||
defaultLimit?: number;
|
||||
};
|
||||
|
||||
export type TanStackTableProps<TData> = {
|
||||
data: TData[];
|
||||
columns: TableColumnDef<TData>[];
|
||||
columnSizing?: ColumnSizingState;
|
||||
onColumnSizingChange?: Dispatch<SetStateAction<ColumnSizingState>>;
|
||||
onColumnOrderChange?: (cols: TableColumnDef<TData>[]) => void;
|
||||
onRemoveColumn?: (id: string) => void;
|
||||
isLoading?: boolean;
|
||||
loadingTip?: string;
|
||||
enableQueryParams?: boolean | string;
|
||||
pagination?: PaginationProps;
|
||||
onEndReached?: (index: number) => void;
|
||||
getRowStyle?: (row: TData) => CSSProperties;
|
||||
getRowClassName?: (row: TData) => string;
|
||||
isRowActive?: (row: TData) => boolean;
|
||||
renderRowActions?: (row: TData) => ReactNode;
|
||||
onRowClick?: (row: TData) => void;
|
||||
onRowDeactivate?: () => void;
|
||||
activeRowIndex?: number;
|
||||
renderExpandedRow?: (row: TData) => ReactNode;
|
||||
getRowCanExpand?: (row: TData) => boolean;
|
||||
/**
|
||||
* Primitive cell values use `--tanstack-plain-cell-*` from the scroll container when `cellTypographySize` is set.
|
||||
*/
|
||||
plainTextCellLineClamp?: number;
|
||||
/** Optional CSS-module typography tier for the scroll root (`--tanstack-plain-cell-font-size` / line-height + header `th`). */
|
||||
cellTypographySize?: CellTypographySize;
|
||||
/** Spread onto the Virtuoso scroll container. `data` is omitted — reserved by Virtuoso. */
|
||||
tableScrollerProps?: Omit<HTMLAttributes<HTMLDivElement>, 'data'>;
|
||||
};
|
||||
|
||||
export type TanStackTableHandle = TableVirtuosoHandle & {
|
||||
goToPage: (page: number) => void;
|
||||
};
|
||||
|
||||
export type TableColumnsState<TData> = {
|
||||
columns: TableColumnDef<TData>[];
|
||||
columnSizing: ColumnSizingState;
|
||||
onColumnSizingChange: Dispatch<SetStateAction<ColumnSizingState>>;
|
||||
onColumnOrderChange: (cols: TableColumnDef<TData>[]) => void;
|
||||
onRemoveColumn: (id: string) => void;
|
||||
};
|
||||
200
frontend/src/components/TanStackTableView/useTableColumns.ts
Normal file
200
frontend/src/components/TanStackTableView/useTableColumns.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
import {
|
||||
Dispatch,
|
||||
SetStateAction,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { ColumnSizingState } from '@tanstack/react-table';
|
||||
import getFromLocalstorage from 'api/browser/localstorage/get';
|
||||
import setToLocalstorage from 'api/browser/localstorage/set';
|
||||
|
||||
import { TableColumnDef, TableColumnsState } from './types';
|
||||
|
||||
const DEBOUNCE_MS = 250;
|
||||
|
||||
type PersistedState = {
|
||||
columnOrder: string[];
|
||||
columnSizing: ColumnSizingState;
|
||||
removedColumnIds: string[];
|
||||
};
|
||||
|
||||
const EMPTY: PersistedState = {
|
||||
columnOrder: [],
|
||||
columnSizing: {},
|
||||
removedColumnIds: [],
|
||||
};
|
||||
|
||||
function readStorage(storageKey: string): PersistedState {
|
||||
const raw = getFromLocalstorage(storageKey);
|
||||
if (!raw) {
|
||||
return EMPTY;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as PersistedState;
|
||||
return {
|
||||
columnOrder: Array.isArray(parsed.columnOrder) ? parsed.columnOrder : [],
|
||||
columnSizing:
|
||||
parsed.columnSizing && typeof parsed.columnSizing === 'object'
|
||||
? Object.fromEntries(
|
||||
Object.entries(parsed.columnSizing).filter(
|
||||
([, v]) => typeof v === 'number' && Number.isFinite(v) && v > 0,
|
||||
),
|
||||
)
|
||||
: {},
|
||||
removedColumnIds: Array.isArray(parsed.removedColumnIds)
|
||||
? parsed.removedColumnIds
|
||||
: [],
|
||||
};
|
||||
} catch (e) {
|
||||
console.error('useTableColumns: failed to parse storage', e);
|
||||
return EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
type UseTableColumnsOptions = { storageKey?: string };
|
||||
|
||||
type UseTableColumnsResult<TData> = {
|
||||
tableProps: TableColumnsState<TData>;
|
||||
activeColumnIds: string[];
|
||||
};
|
||||
|
||||
export function useTableColumns<TData>(
|
||||
definitions: TableColumnDef<TData>[],
|
||||
options?: UseTableColumnsOptions,
|
||||
): UseTableColumnsResult<TData> {
|
||||
const { storageKey } = options ?? {};
|
||||
|
||||
const [persisted, setPersisted] = useState<PersistedState>(() =>
|
||||
storageKey ? readStorage(storageKey) : EMPTY,
|
||||
);
|
||||
|
||||
const [columnSizing, setColumnSizing] = useState<ColumnSizingState>(
|
||||
() => persisted.columnSizing,
|
||||
);
|
||||
|
||||
const pendingRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const persistedRef = useRef(persisted);
|
||||
persistedRef.current = persisted;
|
||||
const columnSizingRef = useRef(columnSizing);
|
||||
columnSizingRef.current = columnSizing;
|
||||
|
||||
const scheduleWrite = useCallback(() => {
|
||||
if (!storageKey) {
|
||||
return;
|
||||
}
|
||||
if (pendingRef.current !== null) {
|
||||
clearTimeout(pendingRef.current);
|
||||
}
|
||||
pendingRef.current = setTimeout(() => {
|
||||
setToLocalstorage(
|
||||
storageKey,
|
||||
JSON.stringify({
|
||||
...persistedRef.current,
|
||||
columnSizing: columnSizingRef.current,
|
||||
}),
|
||||
);
|
||||
}, DEBOUNCE_MS);
|
||||
}, [storageKey]);
|
||||
|
||||
useEffect(() => {
|
||||
scheduleWrite();
|
||||
return (): void => {
|
||||
if (pendingRef.current !== null) {
|
||||
clearTimeout(pendingRef.current);
|
||||
}
|
||||
};
|
||||
}, [columnSizing, scheduleWrite]);
|
||||
|
||||
const handleColumnSizingChange: Dispatch<
|
||||
SetStateAction<ColumnSizingState>
|
||||
> = useCallback((updater) => {
|
||||
setColumnSizing((prev) =>
|
||||
typeof updater === 'function' ? updater(prev) : updater,
|
||||
);
|
||||
}, []);
|
||||
|
||||
const handleColumnOrderChange = useCallback(
|
||||
(updated: TableColumnDef<TData>[]) => {
|
||||
const newOrder = updated.map((c) => c.id);
|
||||
setPersisted((prev) => {
|
||||
const next = { ...prev, columnOrder: newOrder };
|
||||
if (storageKey) {
|
||||
setToLocalstorage(
|
||||
storageKey,
|
||||
JSON.stringify({
|
||||
...next,
|
||||
columnSizing: columnSizingRef.current,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[storageKey],
|
||||
);
|
||||
|
||||
const handleRemoveColumn = useCallback(
|
||||
(id: string) => {
|
||||
setPersisted((prev) => {
|
||||
if (prev.removedColumnIds.includes(id)) {
|
||||
return prev;
|
||||
}
|
||||
const next = {
|
||||
...prev,
|
||||
removedColumnIds: [...prev.removedColumnIds, id],
|
||||
};
|
||||
if (storageKey) {
|
||||
if (pendingRef.current !== null) {
|
||||
clearTimeout(pendingRef.current);
|
||||
}
|
||||
pendingRef.current = setTimeout(() => {
|
||||
setToLocalstorage(
|
||||
storageKey,
|
||||
JSON.stringify({
|
||||
...next,
|
||||
columnSizing: columnSizingRef.current,
|
||||
}),
|
||||
);
|
||||
}, DEBOUNCE_MS);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[storageKey],
|
||||
);
|
||||
|
||||
const columns = useMemo<TableColumnDef<TData>[]>(() => {
|
||||
const removedSet = new Set(persisted.removedColumnIds);
|
||||
const active = definitions.filter((d) => !removedSet.has(d.id));
|
||||
|
||||
if (persisted.columnOrder.length === 0) {
|
||||
return active;
|
||||
}
|
||||
|
||||
const orderMap = new Map(persisted.columnOrder.map((id, i) => [id, i]));
|
||||
const pinned = active.filter((c) => c.pin != null);
|
||||
const rest = active.filter((c) => c.pin == null);
|
||||
const sortedRest = [...rest].sort((a, b) => {
|
||||
const ai = orderMap.get(a.id) ?? Infinity;
|
||||
const bi = orderMap.get(b.id) ?? Infinity;
|
||||
return ai - bi;
|
||||
});
|
||||
return [...pinned, ...sortedRest];
|
||||
}, [definitions, persisted]);
|
||||
|
||||
const activeColumnIds = useMemo(() => columns.map((c) => c.id), [columns]);
|
||||
|
||||
return {
|
||||
tableProps: {
|
||||
columns,
|
||||
columnSizing,
|
||||
onColumnSizingChange: handleColumnSizingChange,
|
||||
onColumnOrderChange: handleColumnOrderChange,
|
||||
onRemoveColumn: handleRemoveColumn,
|
||||
},
|
||||
activeColumnIds,
|
||||
};
|
||||
}
|
||||
72
frontend/src/components/TanStackTableView/useTableParams.ts
Normal file
72
frontend/src/components/TanStackTableView/useTableParams.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useState } from 'react';
|
||||
import { parseAsInteger, useQueryState } from 'nuqs';
|
||||
import { parseAsJsonNoValidate } from 'utils/nuqsParsers';
|
||||
|
||||
import { SortState } from './types';
|
||||
|
||||
const NUQS_OPTIONS = { history: 'push' as const };
|
||||
const DEFAULT_PAGE = 1;
|
||||
const DEFAULT_LIMIT = 50;
|
||||
|
||||
type Defaults = { page?: number; limit?: number; orderBy?: SortState | null };
|
||||
|
||||
type TableParamsResult = {
|
||||
page: number;
|
||||
limit: number;
|
||||
orderBy: SortState | null;
|
||||
setPage: (p: number) => void;
|
||||
setLimit: (l: number) => void;
|
||||
setOrderBy: (s: SortState | null) => void;
|
||||
};
|
||||
|
||||
export function useTableParams(
|
||||
enableQueryParams?: boolean | string,
|
||||
defaults?: Defaults,
|
||||
): TableParamsResult {
|
||||
const prefix = typeof enableQueryParams === 'string' ? enableQueryParams : '';
|
||||
const sep = prefix ? '_' : '';
|
||||
const pageDefault = defaults?.page ?? DEFAULT_PAGE;
|
||||
const limitDefault = defaults?.limit ?? DEFAULT_LIMIT;
|
||||
const orderByDefault = defaults?.orderBy ?? null;
|
||||
|
||||
const [localPage, setLocalPage] = useState(pageDefault);
|
||||
const [localLimit, setLocalLimit] = useState(limitDefault);
|
||||
const [localOrderBy, setLocalOrderBy] = useState<SortState | null>(
|
||||
orderByDefault,
|
||||
);
|
||||
|
||||
const [urlPage, setUrlPage] = useQueryState(
|
||||
`${prefix}${sep}page`,
|
||||
parseAsInteger.withDefault(pageDefault).withOptions(NUQS_OPTIONS),
|
||||
);
|
||||
const [urlLimit, setUrlLimit] = useQueryState(
|
||||
`${prefix}${sep}limit`,
|
||||
parseAsInteger.withDefault(limitDefault).withOptions(NUQS_OPTIONS),
|
||||
);
|
||||
const [urlOrderBy, setUrlOrderBy] = useQueryState(
|
||||
`${prefix}${sep}order_by`,
|
||||
parseAsJsonNoValidate<SortState | null>()
|
||||
.withDefault(orderByDefault as never)
|
||||
.withOptions(NUQS_OPTIONS),
|
||||
);
|
||||
|
||||
if (enableQueryParams) {
|
||||
return {
|
||||
page: urlPage,
|
||||
limit: urlLimit,
|
||||
orderBy: urlOrderBy as SortState | null,
|
||||
setPage: setUrlPage,
|
||||
setLimit: setUrlLimit,
|
||||
setOrderBy: setUrlOrderBy,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
page: localPage,
|
||||
limit: localLimit,
|
||||
orderBy: localOrderBy,
|
||||
setPage: setLocalPage,
|
||||
setLimit: setLocalLimit,
|
||||
setOrderBy: setLocalOrderBy,
|
||||
};
|
||||
}
|
||||
67
frontend/src/components/TanStackTableView/utils.ts
Normal file
67
frontend/src/components/TanStackTableView/utils.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
|
||||
import { TableColumnDef } from './types';
|
||||
|
||||
export const getColumnId = <TData>(column: TableColumnDef<TData>): string =>
|
||||
column.id;
|
||||
|
||||
const REM_PX = 16;
|
||||
const MIN_WIDTH_DEFAULT_REM = 12;
|
||||
|
||||
export const getColumnMinWidthPx = <TData>(
|
||||
column: TableColumnDef<TData>,
|
||||
): number => {
|
||||
if (column.width?.fixed != null) {
|
||||
return column.width.fixed;
|
||||
}
|
||||
if (column.width?.min != null) {
|
||||
return column.width.min;
|
||||
}
|
||||
return MIN_WIDTH_DEFAULT_REM * REM_PX;
|
||||
};
|
||||
|
||||
export function buildTanstackColumnDef<TData>(
|
||||
colDef: TableColumnDef<TData>,
|
||||
isRowActive?: (row: TData) => boolean,
|
||||
): ColumnDef<TData> {
|
||||
const isFixed = colDef.width?.fixed != null;
|
||||
const fixedWidth = colDef.width?.fixed;
|
||||
const minWidthPx = getColumnMinWidthPx(colDef);
|
||||
return {
|
||||
id: colDef.id,
|
||||
header:
|
||||
typeof colDef.header === 'string'
|
||||
? colDef.header
|
||||
: (): ReactNode =>
|
||||
typeof colDef.header === 'function' ? colDef.header() : null,
|
||||
accessorFn: (row: TData): unknown => {
|
||||
if (colDef.accessorFn) {
|
||||
return colDef.accessorFn(row);
|
||||
}
|
||||
if (colDef.accessorKey) {
|
||||
return (row as Record<string, unknown>)[colDef.accessorKey];
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
enableResizing: colDef.enableResize !== false && !isFixed,
|
||||
enableSorting: colDef.enableSort === true,
|
||||
minSize: fixedWidth ?? minWidthPx,
|
||||
size: colDef.width?.default ?? fixedWidth,
|
||||
maxSize: fixedWidth,
|
||||
cell: ({ row, getValue }): ReactNode => {
|
||||
const rowData = row.original;
|
||||
return colDef.cell({
|
||||
row: rowData,
|
||||
value: getValue(),
|
||||
isActive: isRowActive?.(rowData) ?? false,
|
||||
rowIndex: row.index,
|
||||
isExpanded: row.getIsExpanded(),
|
||||
canExpand: row.getCanExpand(),
|
||||
toggleExpanded: (): void => {
|
||||
row.toggleExpanded();
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import uPlot from 'uplot';
|
||||
|
||||
import { ChartProps } from '../types';
|
||||
|
||||
const TOOLTIP_WIDTH_PADDING = 60;
|
||||
const TOOLTIP_WIDTH_PADDING = 120;
|
||||
const TOOLTIP_MIN_WIDTH = 200;
|
||||
|
||||
export default function ChartWrapper({
|
||||
|
||||
@@ -264,20 +264,22 @@ export default function Home(): JSX.Element {
|
||||
|
||||
return (
|
||||
<div className="home-container">
|
||||
<PersistedAnnouncementBanner
|
||||
type="info"
|
||||
storageKey={LOCALSTORAGE.DISMISSED_API_KEYS_DEPRECATION_BANNER}
|
||||
action={{
|
||||
label: 'Go to Service Accounts',
|
||||
onClick: (): void => history.push(ROUTES.SERVICE_ACCOUNTS_SETTINGS),
|
||||
}}
|
||||
>
|
||||
<>
|
||||
<strong>API keys</strong> have been deprecated in favour of{' '}
|
||||
<strong>Service accounts</strong>. The existing API Keys have been migrated
|
||||
to service accounts.
|
||||
</>
|
||||
</PersistedAnnouncementBanner>
|
||||
{user?.role === USER_ROLES.ADMIN && (
|
||||
<PersistedAnnouncementBanner
|
||||
type="info"
|
||||
storageKey={LOCALSTORAGE.DISMISSED_API_KEYS_DEPRECATION_BANNER}
|
||||
action={{
|
||||
label: 'Go to Service Accounts',
|
||||
onClick: (): void => history.push(ROUTES.SERVICE_ACCOUNTS_SETTINGS),
|
||||
}}
|
||||
>
|
||||
<>
|
||||
<strong>API keys</strong> have been deprecated in favour of{' '}
|
||||
<strong>Service accounts</strong>. The existing API Keys have been
|
||||
migrated to service accounts.
|
||||
</>
|
||||
</PersistedAnnouncementBanner>
|
||||
)}
|
||||
|
||||
<div className="sticky-header">
|
||||
<Header
|
||||
|
||||
@@ -1,21 +1,34 @@
|
||||
import type { CSSProperties, MouseEvent, ReactNode } from 'react';
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import { toast } from '@signozhq/sonner';
|
||||
import { Card, Typography } from 'antd';
|
||||
import LogDetail from 'components/LogDetail';
|
||||
import { VIEW_TYPES } from 'components/LogDetail/constants';
|
||||
import ListLogView from 'components/Logs/ListLogView';
|
||||
import LogLinesActionButtons from 'components/Logs/LogLinesActionButtons/LogLinesActionButtons';
|
||||
import { getRowBackgroundColor } from 'components/Logs/LogStateIndicator/getRowBackgroundColor';
|
||||
import { getLogIndicatorType } from 'components/Logs/LogStateIndicator/utils';
|
||||
import RawLogView from 'components/Logs/RawLogView';
|
||||
import { useLogsTableColumns } from 'components/Logs/TableView/useLogsTableColumns';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import type { TanStackTableHandle } from 'components/TanStackTableView/types';
|
||||
import { useTableColumns } from 'components/TanStackTableView/useTableColumns';
|
||||
import { CARD_BODY_STYLE } from 'constants/card';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { OptionFormatTypes } from 'constants/optionsFormatTypes';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { InfinityWrapperStyled } from 'container/LogsExplorerList/styles';
|
||||
import TanStackTableView from 'container/LogsExplorerList/TanStackTableView';
|
||||
import { convertKeysToColumnFields } from 'container/LogsExplorerList/utils';
|
||||
import { useOptionsMenu } from 'container/OptionsMenu';
|
||||
import { defaultLogsSelectedColumns } from 'container/OptionsMenu/constants';
|
||||
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
|
||||
import useLogDetailHandlers from 'hooks/logs/useLogDetailHandlers';
|
||||
import useScrollToLog from 'hooks/logs/useScrollToLog';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useEventSource } from 'providers/EventSource';
|
||||
// interfaces
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
@@ -30,7 +43,10 @@ function LiveLogsList({
|
||||
isLoading,
|
||||
handleChangeSelectedView,
|
||||
}: LiveLogsListProps): JSX.Element {
|
||||
const ref = useRef<VirtuosoHandle>(null);
|
||||
const ref = useRef<TanStackTableHandle | VirtuosoHandle | null>(null);
|
||||
const { pathname } = useLocation();
|
||||
const [, setCopy] = useCopyToClipboard();
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
const { isConnectionLoading } = useEventSource();
|
||||
|
||||
@@ -66,9 +82,46 @@ function LiveLogsList({
|
||||
...options.selectColumns,
|
||||
]);
|
||||
|
||||
const logsColumns = useLogsTableColumns({
|
||||
fields: selectedFields,
|
||||
linesPerRow: options.maxLines,
|
||||
fontSize: options.fontSize,
|
||||
appendTo: 'end',
|
||||
});
|
||||
|
||||
const { tableProps } = useTableColumns(logsColumns, {
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_COLUMNS,
|
||||
});
|
||||
|
||||
const handleRemoveColumn = useCallback(
|
||||
(columnId: string): void => {
|
||||
tableProps.onRemoveColumn(columnId);
|
||||
config.addColumn?.onRemove?.(columnId);
|
||||
},
|
||||
[tableProps, config.addColumn],
|
||||
);
|
||||
|
||||
const makeOnLogCopy = useCallback(
|
||||
(log: ILog) => (event: MouseEvent<HTMLElement>): void => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const urlQuery = new URLSearchParams(window.location.search);
|
||||
urlQuery.delete(QueryParams.activeLogId);
|
||||
urlQuery.delete(QueryParams.relativeTime);
|
||||
urlQuery.set(QueryParams.activeLogId, `"${log.id}"`);
|
||||
const link = `${window.location.origin}${pathname}?${urlQuery.toString()}`;
|
||||
setCopy(link);
|
||||
toast.success('Copied to clipboard', { position: 'top-right' });
|
||||
},
|
||||
[pathname, setCopy],
|
||||
);
|
||||
|
||||
const handleScrollToLog = useScrollToLog({
|
||||
logs: formattedLogs,
|
||||
virtuosoRef: ref,
|
||||
virtuosoRef: ref as React.RefObject<Pick<
|
||||
VirtuosoHandle,
|
||||
'scrollToIndex'
|
||||
> | null>,
|
||||
});
|
||||
|
||||
const getItemContent = useCallback(
|
||||
@@ -158,29 +211,48 @@ function LiveLogsList({
|
||||
{formattedLogs.length !== 0 && (
|
||||
<InfinityWrapperStyled>
|
||||
{options.format === OptionFormatTypes.TABLE ? (
|
||||
<TanStackTableView
|
||||
ref={ref}
|
||||
<TanStackTable
|
||||
ref={ref as React.Ref<TanStackTableHandle>}
|
||||
{...tableProps}
|
||||
plainTextCellLineClamp={options.maxLines}
|
||||
cellTypographySize={options.fontSize}
|
||||
onRemoveColumn={handleRemoveColumn}
|
||||
data={formattedLogs}
|
||||
isLoading={false}
|
||||
tableViewProps={{
|
||||
logs: formattedLogs,
|
||||
fields: selectedFields,
|
||||
linesPerRow: options.maxLines,
|
||||
fontSize: options.fontSize,
|
||||
appendTo: 'end',
|
||||
activeLogIndex,
|
||||
isRowActive={(log): boolean => log.id === activeLog?.id}
|
||||
getRowStyle={(log): CSSProperties =>
|
||||
({
|
||||
'--row-active-bg': getRowBackgroundColor(
|
||||
isDarkMode,
|
||||
getLogIndicatorType(log),
|
||||
),
|
||||
'--row-hover-bg': getRowBackgroundColor(
|
||||
isDarkMode,
|
||||
getLogIndicatorType(log),
|
||||
),
|
||||
} as CSSProperties)
|
||||
}
|
||||
onRowClick={(log): void => {
|
||||
handleSetActiveLog(log);
|
||||
}}
|
||||
handleChangeSelectedView={handleChangeSelectedView}
|
||||
logs={formattedLogs}
|
||||
onSetActiveLog={handleSetActiveLog}
|
||||
onClearActiveLog={handleCloseLogDetail}
|
||||
activeLog={activeLog}
|
||||
onRemoveColumn={config.addColumn?.onRemove}
|
||||
onRowDeactivate={handleCloseLogDetail}
|
||||
activeRowIndex={activeLogIndex}
|
||||
renderRowActions={(log): ReactNode => (
|
||||
<LogLinesActionButtons
|
||||
handleShowContext={(e): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleSetActiveLog(log, VIEW_TYPES.CONTEXT);
|
||||
}}
|
||||
onLogCopy={makeOnLogCopy(log)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<Card style={{ width: '100%' }} bodyStyle={CARD_BODY_STYLE}>
|
||||
<OverlayScrollbar isVirtuoso>
|
||||
<Virtuoso
|
||||
ref={ref}
|
||||
ref={ref as React.Ref<VirtuosoHandle>}
|
||||
initialTopMostItemIndex={activeLogIndex !== -1 ? activeLogIndex : 0}
|
||||
data={formattedLogs}
|
||||
totalCount={formattedLogs.length}
|
||||
|
||||
@@ -221,7 +221,7 @@ function ColumnView({
|
||||
onColumnOrderChange(formattedColumns);
|
||||
};
|
||||
|
||||
const handleRowClick = (row: Row<Record<string, unknown>>): void => {
|
||||
const handleRowClick = (row: Row<Record<string, string>>): void => {
|
||||
const currentLog = logs.find(({ id }) => id === row.original.id);
|
||||
|
||||
setShowActiveLog(true);
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
const RowHoverContext = createContext(false);
|
||||
|
||||
export const useRowHover = (): boolean => useContext(RowHoverContext);
|
||||
|
||||
export default RowHoverContext;
|
||||
@@ -1,84 +0,0 @@
|
||||
import { ComponentProps, memo, useCallback, useState } from 'react';
|
||||
import { TableComponents } from 'react-virtuoso';
|
||||
import {
|
||||
getLogIndicatorType,
|
||||
getLogIndicatorTypeForTable,
|
||||
} from 'components/Logs/LogStateIndicator/utils';
|
||||
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
import { TableRowStyled } from '../InfinityTableView/styles';
|
||||
import RowHoverContext from '../RowHoverContext';
|
||||
import { TanStackTableRowData } from './types';
|
||||
|
||||
export type TableRowContext = {
|
||||
activeLog?: ILog | null;
|
||||
activeContextLog?: ILog | null;
|
||||
logsById: Map<string, ILog>;
|
||||
};
|
||||
|
||||
type VirtuosoTableRowProps = ComponentProps<
|
||||
NonNullable<TableComponents<TanStackTableRowData, TableRowContext>['TableRow']>
|
||||
>;
|
||||
|
||||
type TanStackCustomTableRowProps = VirtuosoTableRowProps;
|
||||
|
||||
function TanStackCustomTableRow({
|
||||
children,
|
||||
item,
|
||||
context,
|
||||
...props
|
||||
}: TanStackCustomTableRowProps): JSX.Element {
|
||||
const { isHighlighted } = useCopyLogLink(item.currentLog.id);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const [hasHovered, setHasHovered] = useState(false);
|
||||
const rowId = String(item.currentLog.id ?? '');
|
||||
const activeLog = context?.activeLog;
|
||||
const activeContextLog = context?.activeContextLog;
|
||||
const logsById = context?.logsById;
|
||||
const rowLog = logsById?.get(rowId) || item.currentLog;
|
||||
const logType = rowLog
|
||||
? getLogIndicatorType(rowLog)
|
||||
: getLogIndicatorTypeForTable(item.log);
|
||||
|
||||
const handleMouseEnter = useCallback(() => {
|
||||
if (!hasHovered) {
|
||||
setHasHovered(true);
|
||||
}
|
||||
}, [hasHovered]);
|
||||
|
||||
return (
|
||||
<RowHoverContext.Provider value={hasHovered}>
|
||||
<TableRowStyled
|
||||
{...props}
|
||||
$isDarkMode={isDarkMode}
|
||||
$isActiveLog={
|
||||
isHighlighted ||
|
||||
rowId === String(activeLog?.id ?? '') ||
|
||||
rowId === String(activeContextLog?.id ?? '')
|
||||
}
|
||||
$logType={logType}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
>
|
||||
{children}
|
||||
</TableRowStyled>
|
||||
</RowHoverContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(TanStackCustomTableRow, (prev, next) => {
|
||||
const prevId = String(prev.item.currentLog.id ?? '');
|
||||
const nextId = String(next.item.currentLog.id ?? '');
|
||||
if (prevId !== nextId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const prevIsActive =
|
||||
prevId === String(prev.context?.activeLog?.id ?? '') ||
|
||||
prevId === String(prev.context?.activeContextLog?.id ?? '');
|
||||
const nextIsActive =
|
||||
nextId === String(next.context?.activeLog?.id ?? '') ||
|
||||
nextId === String(next.context?.activeContextLog?.id ?? '');
|
||||
return prevIsActive === nextIsActive;
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
import {
|
||||
MouseEvent as ReactMouseEvent,
|
||||
MouseEventHandler,
|
||||
useCallback,
|
||||
} from 'react';
|
||||
import { flexRender, Row as TanStackRowModel } from '@tanstack/react-table';
|
||||
import { VIEW_TYPES } from 'components/LogDetail/constants';
|
||||
import LogLinesActionButtons from 'components/Logs/LogLinesActionButtons/LogLinesActionButtons';
|
||||
|
||||
import { TableCellStyled } from '../InfinityTableView/styles';
|
||||
import { InfinityTableProps } from '../InfinityTableView/types';
|
||||
import { useRowHover } from '../RowHoverContext';
|
||||
import { TanStackTableRowData } from './types';
|
||||
|
||||
type TanStackRowCellsProps = {
|
||||
row: TanStackRowModel<TanStackTableRowData>;
|
||||
fontSize: InfinityTableProps['tableViewProps']['fontSize'];
|
||||
onSetActiveLog?: InfinityTableProps['onSetActiveLog'];
|
||||
onClearActiveLog?: InfinityTableProps['onClearActiveLog'];
|
||||
isActiveLog?: boolean;
|
||||
isDarkMode: boolean;
|
||||
onLogCopy: (logId: string, event: ReactMouseEvent<HTMLElement>) => void;
|
||||
isLogsExplorerPage: boolean;
|
||||
};
|
||||
|
||||
function TanStackRowCells({
|
||||
row,
|
||||
fontSize,
|
||||
onSetActiveLog,
|
||||
onClearActiveLog,
|
||||
isActiveLog = false,
|
||||
isDarkMode,
|
||||
onLogCopy,
|
||||
isLogsExplorerPage,
|
||||
}: TanStackRowCellsProps): JSX.Element {
|
||||
const { currentLog } = row.original;
|
||||
const hasHovered = useRowHover();
|
||||
|
||||
const handleShowContext: MouseEventHandler<HTMLElement> = useCallback(
|
||||
(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onSetActiveLog?.(currentLog, VIEW_TYPES.CONTEXT);
|
||||
},
|
||||
[currentLog, onSetActiveLog],
|
||||
);
|
||||
|
||||
const handleShowLogDetails = useCallback(() => {
|
||||
if (!currentLog) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isActiveLog && onClearActiveLog) {
|
||||
onClearActiveLog();
|
||||
return;
|
||||
}
|
||||
|
||||
onSetActiveLog?.(currentLog);
|
||||
}, [currentLog, isActiveLog, onClearActiveLog, onSetActiveLog]);
|
||||
|
||||
const visibleCells = row.getVisibleCells();
|
||||
const lastCellIndex = visibleCells.length - 1;
|
||||
|
||||
return (
|
||||
<>
|
||||
{visibleCells.map((cell, index) => {
|
||||
const columnKey = cell.column.id;
|
||||
const isLastCell = index === lastCellIndex;
|
||||
return (
|
||||
<TableCellStyled
|
||||
$isDragColumn={false}
|
||||
$isLogIndicator={columnKey === 'state-indicator'}
|
||||
$hasSingleColumn={visibleCells.length <= 2}
|
||||
$isDarkMode={isDarkMode}
|
||||
key={cell.id}
|
||||
fontSize={fontSize}
|
||||
className={columnKey}
|
||||
onClick={handleShowLogDetails}
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
{isLastCell && isLogsExplorerPage && hasHovered && (
|
||||
<LogLinesActionButtons
|
||||
handleShowContext={handleShowContext}
|
||||
onLogCopy={(event): void => onLogCopy(currentLog.id, event)}
|
||||
customClassName="table-view-log-actions"
|
||||
/>
|
||||
)}
|
||||
</TableCellStyled>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default TanStackRowCells;
|
||||
@@ -1,105 +0,0 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
|
||||
import TanStackCustomTableRow, {
|
||||
TableRowContext,
|
||||
} from '../TanStackCustomTableRow';
|
||||
import type { TanStackTableRowData } from '../types';
|
||||
|
||||
jest.mock('../../InfinityTableView/styles', () => ({
|
||||
TableRowStyled: 'tr',
|
||||
}));
|
||||
|
||||
jest.mock('hooks/logs/useCopyLogLink', () => ({
|
||||
useCopyLogLink: (): { isHighlighted: boolean } => ({ isHighlighted: false }),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useDarkMode', () => ({
|
||||
useIsDarkMode: (): boolean => false,
|
||||
}));
|
||||
|
||||
jest.mock('components/Logs/LogStateIndicator/utils', () => ({
|
||||
getLogIndicatorType: (): string => 'info',
|
||||
getLogIndicatorTypeForTable: (): string => 'info',
|
||||
}));
|
||||
|
||||
const item: TanStackTableRowData = {
|
||||
log: {},
|
||||
currentLog: { id: 'row-1' } as TanStackTableRowData['currentLog'],
|
||||
rowIndex: 0,
|
||||
};
|
||||
|
||||
const virtuosoTableRowAttrs = {
|
||||
'data-index': 0,
|
||||
'data-item-index': 0,
|
||||
'data-known-size': 40,
|
||||
} as const;
|
||||
|
||||
const defaultContext: TableRowContext = {
|
||||
activeLog: null,
|
||||
activeContextLog: null,
|
||||
logsById: new Map(),
|
||||
};
|
||||
|
||||
describe('TanStackCustomTableRow', () => {
|
||||
it('renders children inside TableRowStyled', () => {
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
{...virtuosoTableRowAttrs}
|
||||
item={item}
|
||||
context={defaultContext}
|
||||
>
|
||||
<td>cell</td>
|
||||
</TanStackCustomTableRow>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('cell')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('marks row active when activeLog matches item id', () => {
|
||||
const { container } = render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
{...virtuosoTableRowAttrs}
|
||||
item={item}
|
||||
context={{
|
||||
...defaultContext,
|
||||
activeLog: { id: 'row-1' } as never,
|
||||
}}
|
||||
>
|
||||
<td>x</td>
|
||||
</TanStackCustomTableRow>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
|
||||
const row = container.querySelector('tr');
|
||||
expect(row).toBeTruthy();
|
||||
});
|
||||
|
||||
it('uses logsById entry when present for indicator type', () => {
|
||||
const logFromMap = { id: 'row-1', severity_text: 'error' } as never;
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
{...virtuosoTableRowAttrs}
|
||||
item={item}
|
||||
context={{
|
||||
...defaultContext,
|
||||
logsById: new Map([['row-1', logFromMap]]),
|
||||
}}
|
||||
>
|
||||
<td>x</td>
|
||||
</TanStackCustomTableRow>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('x')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,152 +0,0 @@
|
||||
import type { Header } from '@tanstack/react-table';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
import TanStackHeaderRow from '../TanStackHeaderRow';
|
||||
import type { OrderedColumn, TanStackTableRowData } from '../types';
|
||||
|
||||
jest.mock('../../InfinityTableView/styles', () => ({
|
||||
TableHeaderCellStyled: 'th',
|
||||
}));
|
||||
|
||||
const mockUseSortable = jest.fn((_args?: unknown) => ({
|
||||
attributes: {},
|
||||
listeners: {},
|
||||
setNodeRef: jest.fn(),
|
||||
setActivatorNodeRef: jest.fn(),
|
||||
transform: null,
|
||||
transition: undefined,
|
||||
isDragging: false,
|
||||
}));
|
||||
|
||||
jest.mock('@dnd-kit/sortable', () => ({
|
||||
useSortable: (args: unknown): ReturnType<typeof mockUseSortable> =>
|
||||
mockUseSortable(args),
|
||||
}));
|
||||
|
||||
jest.mock('@tanstack/react-table', () => ({
|
||||
flexRender: (def: unknown, ctx: unknown): unknown => {
|
||||
if (typeof def === 'string') {
|
||||
return def;
|
||||
}
|
||||
if (typeof def === 'function') {
|
||||
return (def as (c: unknown) => unknown)(ctx);
|
||||
}
|
||||
return def;
|
||||
},
|
||||
}));
|
||||
|
||||
const column = (key: string): OrderedColumn =>
|
||||
({ key, title: key } as OrderedColumn);
|
||||
|
||||
const mockHeader = (
|
||||
id: string,
|
||||
canResize = true,
|
||||
): Header<TanStackTableRowData, unknown> =>
|
||||
(({
|
||||
id,
|
||||
column: {
|
||||
getCanResize: (): boolean => canResize,
|
||||
getIsResizing: (): boolean => false,
|
||||
columnDef: { header: id },
|
||||
},
|
||||
getContext: (): unknown => ({}),
|
||||
getResizeHandler: (): (() => void) => jest.fn(),
|
||||
flexRender: undefined,
|
||||
} as unknown) as Header<TanStackTableRowData, unknown>);
|
||||
|
||||
describe('TanStackHeaderRow', () => {
|
||||
beforeEach(() => {
|
||||
mockUseSortable.mockClear();
|
||||
});
|
||||
|
||||
it('renders column title when header is undefined', () => {
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={column('timestamp')}
|
||||
isDarkMode={false}
|
||||
fontSize={FontSize.SMALL}
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Timestamp')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('enables useSortable for draggable columns', () => {
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={column('body')}
|
||||
header={mockHeader('body')}
|
||||
isDarkMode={false}
|
||||
fontSize={FontSize.SMALL}
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
|
||||
expect(mockUseSortable).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'body',
|
||||
disabled: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('disables sortable for expand column', () => {
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={column('expand')}
|
||||
header={mockHeader('expand', false)}
|
||||
isDarkMode={false}
|
||||
fontSize={FontSize.SMALL}
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
|
||||
expect(mockUseSortable).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
disabled: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows drag grip for draggable columns', () => {
|
||||
render(
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<TanStackHeaderRow
|
||||
column={column('body')}
|
||||
header={mockHeader('body')}
|
||||
isDarkMode={false}
|
||||
fontSize={FontSize.SMALL}
|
||||
hasSingleColumn={false}
|
||||
/>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /Drag body column/i }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,193 +0,0 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import RowHoverContext from 'container/LogsExplorerList/RowHoverContext';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
import TanStackRowCells from '../TanStackRow';
|
||||
import type { TanStackTableRowData } from '../types';
|
||||
|
||||
jest.mock('../../InfinityTableView/styles', () => ({
|
||||
TableCellStyled: 'td',
|
||||
}));
|
||||
|
||||
jest.mock(
|
||||
'components/Logs/LogLinesActionButtons/LogLinesActionButtons',
|
||||
() => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
onLogCopy,
|
||||
}: {
|
||||
onLogCopy: (e: React.MouseEvent) => void;
|
||||
}): JSX.Element => (
|
||||
<button type="button" data-testid="copy-btn" onClick={onLogCopy}>
|
||||
copy
|
||||
</button>
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const flexRenderMock = jest.fn((def: unknown, _ctx?: unknown) =>
|
||||
typeof def === 'function' ? def({}) : def,
|
||||
);
|
||||
|
||||
jest.mock('@tanstack/react-table', () => ({
|
||||
flexRender: (def: unknown, ctx: unknown): unknown => flexRenderMock(def, ctx),
|
||||
}));
|
||||
|
||||
function buildMockRow(
|
||||
visibleCells: Array<{ columnId: string }>,
|
||||
): Parameters<typeof TanStackRowCells>[0]['row'] {
|
||||
return {
|
||||
original: {
|
||||
currentLog: { id: 'log-1' } as TanStackTableRowData['currentLog'],
|
||||
log: {},
|
||||
rowIndex: 0,
|
||||
},
|
||||
getVisibleCells: () =>
|
||||
visibleCells.map((cell, index) => ({
|
||||
id: `cell-${index}`,
|
||||
column: {
|
||||
id: cell.columnId,
|
||||
columnDef: {
|
||||
cell: (): string => `content-${cell.columnId}`,
|
||||
},
|
||||
},
|
||||
getContext: (): Record<string, unknown> => ({}),
|
||||
})),
|
||||
} as never;
|
||||
}
|
||||
|
||||
describe('TanStackRowCells', () => {
|
||||
beforeEach(() => {
|
||||
flexRenderMock.mockClear();
|
||||
});
|
||||
|
||||
it('renders a cell per visible column and calls flexRender', () => {
|
||||
const row = buildMockRow([
|
||||
{ columnId: 'state-indicator' },
|
||||
{ columnId: 'body' },
|
||||
]);
|
||||
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells
|
||||
row={row}
|
||||
fontSize={FontSize.SMALL}
|
||||
isDarkMode={false}
|
||||
onLogCopy={jest.fn()}
|
||||
isLogsExplorerPage={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
|
||||
expect(screen.getAllByRole('cell')).toHaveLength(2);
|
||||
expect(flexRenderMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies state-indicator styling class on the indicator cell', () => {
|
||||
const row = buildMockRow([{ columnId: 'state-indicator' }]);
|
||||
|
||||
const { container } = render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells
|
||||
row={row}
|
||||
fontSize={FontSize.SMALL}
|
||||
isDarkMode={false}
|
||||
onLogCopy={jest.fn()}
|
||||
isLogsExplorerPage={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
|
||||
expect(container.querySelector('td.state-indicator')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders row actions on logs explorer page after hover', () => {
|
||||
const row = buildMockRow([{ columnId: 'body' }]);
|
||||
|
||||
render(
|
||||
<RowHoverContext.Provider value>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells
|
||||
row={row}
|
||||
fontSize={FontSize.SMALL}
|
||||
isDarkMode={false}
|
||||
onLogCopy={jest.fn()}
|
||||
isLogsExplorerPage
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</RowHoverContext.Provider>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('copy-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('click on a data cell calls onSetActiveLog with current log', () => {
|
||||
const onSetActiveLog = jest.fn();
|
||||
const row = buildMockRow([{ columnId: 'body' }]);
|
||||
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells
|
||||
row={row}
|
||||
fontSize={FontSize.SMALL}
|
||||
isDarkMode={false}
|
||||
onSetActiveLog={onSetActiveLog}
|
||||
onLogCopy={jest.fn()}
|
||||
isLogsExplorerPage={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getAllByRole('cell')[0]);
|
||||
|
||||
expect(onSetActiveLog).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'log-1' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('when row is active log, click on cell clears active log', () => {
|
||||
const onSetActiveLog = jest.fn();
|
||||
const onClearActiveLog = jest.fn();
|
||||
const row = buildMockRow([{ columnId: 'body' }]);
|
||||
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<TanStackRowCells
|
||||
row={row}
|
||||
fontSize={FontSize.SMALL}
|
||||
isDarkMode={false}
|
||||
isActiveLog
|
||||
onSetActiveLog={onSetActiveLog}
|
||||
onClearActiveLog={onClearActiveLog}
|
||||
onLogCopy={jest.fn()}
|
||||
isLogsExplorerPage={false}
|
||||
/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getAllByRole('cell')[0]);
|
||||
|
||||
expect(onClearActiveLog).toHaveBeenCalled();
|
||||
expect(onSetActiveLog).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,104 +0,0 @@
|
||||
import { forwardRef } from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
import type { InfinityTableProps } from '../../InfinityTableView/types';
|
||||
import TanStackTableView from '../index';
|
||||
|
||||
jest.mock('react-virtuoso', () => ({
|
||||
TableVirtuoso: forwardRef<
|
||||
unknown,
|
||||
{
|
||||
fixedHeaderContent?: () => JSX.Element;
|
||||
itemContent: (i: number) => JSX.Element;
|
||||
}
|
||||
>(function MockVirtuoso({ fixedHeaderContent, itemContent }, _ref) {
|
||||
return (
|
||||
<div data-testid="virtuoso">
|
||||
{fixedHeaderContent?.()}
|
||||
{itemContent(0)}
|
||||
</div>
|
||||
);
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('components/Logs/TableView/useTableView', () => ({
|
||||
useTableView: (): {
|
||||
dataSource: Record<string, string>[];
|
||||
columns: unknown[];
|
||||
} => ({
|
||||
dataSource: [{ id: '1' }],
|
||||
columns: [
|
||||
{ key: 'body', title: 'body', render: (): string => 'x' },
|
||||
{ key: 'state-indicator', title: 's', render: (): string => 'y' },
|
||||
],
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useDragColumns', () => ({
|
||||
__esModule: true,
|
||||
default: (): {
|
||||
draggedColumns: unknown[];
|
||||
onColumnOrderChange: () => void;
|
||||
} => ({
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/logs/useActiveLog', () => ({
|
||||
useActiveLog: (): { activeLog: null } => ({ activeLog: null }),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/logs/useCopyLogLink', () => ({
|
||||
useCopyLogLink: (): { activeLogId: null } => ({ activeLogId: null }),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useDarkMode', () => ({
|
||||
useIsDarkMode: (): boolean => false,
|
||||
}));
|
||||
|
||||
jest.mock('react-router-dom', () => ({
|
||||
useLocation: (): { pathname: string } => ({ pathname: '/logs' }),
|
||||
}));
|
||||
|
||||
jest.mock('react-use', () => ({
|
||||
useCopyToClipboard: (): [unknown, () => void] => [null, jest.fn()],
|
||||
}));
|
||||
|
||||
jest.mock('@signozhq/sonner', () => ({
|
||||
toast: { success: jest.fn() },
|
||||
}));
|
||||
|
||||
jest.mock('components/Spinner', () => ({
|
||||
__esModule: true,
|
||||
default: ({ tip }: { tip: string }): JSX.Element => (
|
||||
<div data-testid="spinner">{tip}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const baseProps: InfinityTableProps = {
|
||||
isLoading: false,
|
||||
tableViewProps: {
|
||||
logs: [{ id: '1' } as never],
|
||||
fields: [],
|
||||
linesPerRow: 3,
|
||||
fontSize: FontSize.SMALL,
|
||||
appendTo: 'end',
|
||||
activeLogIndex: 0,
|
||||
},
|
||||
};
|
||||
|
||||
describe('TanStackTableView', () => {
|
||||
it('shows spinner while loading', () => {
|
||||
render(<TanStackTableView {...baseProps} isLoading />);
|
||||
|
||||
expect(screen.getByTestId('spinner')).toHaveTextContent('Getting Logs');
|
||||
});
|
||||
|
||||
it('renders virtuoso when not loading', () => {
|
||||
render(<TanStackTableView {...baseProps} />);
|
||||
|
||||
expect(screen.getByTestId('virtuoso')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,173 +0,0 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
|
||||
import type { OrderedColumn } from '../types';
|
||||
import { useColumnSizingPersistence } from '../useColumnSizingPersistence';
|
||||
|
||||
const mockGet = jest.fn();
|
||||
const mockSet = jest.fn();
|
||||
|
||||
jest.mock('api/browser/localstorage/get', () => ({
|
||||
__esModule: true,
|
||||
default: (key: string): string | null => mockGet(key),
|
||||
}));
|
||||
|
||||
jest.mock('api/browser/localstorage/set', () => ({
|
||||
__esModule: true,
|
||||
default: (key: string, value: string): void => {
|
||||
mockSet(key, value);
|
||||
},
|
||||
}));
|
||||
|
||||
const col = (key: string): OrderedColumn =>
|
||||
({ key, title: key } as OrderedColumn);
|
||||
|
||||
describe('useColumnSizingPersistence', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockGet.mockReturnValue(null);
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.runOnlyPendingTimers();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('initializes with empty sizing when localStorage is empty', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useColumnSizingPersistence([col('body'), col('timestamp')]),
|
||||
);
|
||||
|
||||
expect(result.current.columnSizing).toEqual({});
|
||||
});
|
||||
|
||||
it('parses flat ColumnSizingState from localStorage', () => {
|
||||
mockGet.mockReturnValue(JSON.stringify({ body: 400, timestamp: 180 }));
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useColumnSizingPersistence([col('body'), col('timestamp')]),
|
||||
);
|
||||
|
||||
expect(result.current.columnSizing).toEqual({ body: 400, timestamp: 180 });
|
||||
});
|
||||
|
||||
it('parses PersistedColumnSizing wrapper with sizing + columnIdsSignature', () => {
|
||||
mockGet.mockReturnValue(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
columnIdsSignature: 'body|timestamp',
|
||||
sizing: { body: 300 },
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useColumnSizingPersistence([col('body'), col('timestamp')]),
|
||||
);
|
||||
|
||||
expect(result.current.columnSizing).toEqual({ body: 300 });
|
||||
});
|
||||
|
||||
it('drops invalid numeric entries when reading from localStorage', () => {
|
||||
mockGet.mockReturnValue(
|
||||
JSON.stringify({
|
||||
body: 200,
|
||||
bad: NaN,
|
||||
zero: 0,
|
||||
neg: -1,
|
||||
str: 'wide',
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useColumnSizingPersistence([col('body'), col('bad'), col('zero')]),
|
||||
);
|
||||
|
||||
expect(result.current.columnSizing).toEqual({ body: 200 });
|
||||
});
|
||||
|
||||
it('returns empty sizing when JSON is invalid', () => {
|
||||
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mockGet.mockReturnValue('not-json');
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useColumnSizingPersistence([col('body')]),
|
||||
);
|
||||
|
||||
expect(result.current.columnSizing).toEqual({});
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('prunes sizing for columns not in orderedColumns and strips fixed columns', () => {
|
||||
mockGet.mockReturnValue(JSON.stringify({ body: 400, expand: 32, gone: 100 }));
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ columns }: { columns: OrderedColumn[] }) =>
|
||||
useColumnSizingPersistence(columns),
|
||||
{
|
||||
initialProps: {
|
||||
columns: [
|
||||
col('body'),
|
||||
col('expand'),
|
||||
col('state-indicator'),
|
||||
] as OrderedColumn[],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.current.columnSizing).toEqual({ body: 400 });
|
||||
|
||||
act(() => {
|
||||
rerender({
|
||||
columns: [col('body'), col('expand'), col('state-indicator')],
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.columnSizing).toEqual({ body: 400 });
|
||||
});
|
||||
|
||||
it('updates setColumnSizing manually', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useColumnSizingPersistence([col('body')]),
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.setColumnSizing({ body: 500 });
|
||||
});
|
||||
|
||||
expect(result.current.columnSizing).toEqual({ body: 500 });
|
||||
});
|
||||
|
||||
it('debounces writes to localStorage', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useColumnSizingPersistence([col('body')]),
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.setColumnSizing({ body: 600 });
|
||||
});
|
||||
|
||||
expect(mockSet).not.toHaveBeenCalled();
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
expect(mockSet).toHaveBeenCalledWith(
|
||||
LOCALSTORAGE.LOGS_LIST_COLUMN_SIZING,
|
||||
expect.stringContaining('"body":600'),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not persist when ordered columns signature effect runs with empty ids early — still debounces empty sizing', () => {
|
||||
const { result } = renderHook(() => useColumnSizingPersistence([]));
|
||||
|
||||
expect(result.current.columnSizing).toEqual({});
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
expect(mockSet).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,222 +0,0 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
|
||||
import type { OrderedColumn } from '../types';
|
||||
import { useOrderedColumns } from '../useOrderedColumns';
|
||||
|
||||
const mockGetDraggedColumns = jest.fn();
|
||||
|
||||
jest.mock('hooks/useDragColumns/utils', () => ({
|
||||
getDraggedColumns: <T,>(current: unknown[], dragged: unknown[]): T[] =>
|
||||
mockGetDraggedColumns(current, dragged) as T[],
|
||||
}));
|
||||
|
||||
const col = (key: string, title?: string): OrderedColumn =>
|
||||
({ key, title: title ?? key } as OrderedColumn);
|
||||
|
||||
describe('useOrderedColumns', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('returns columns from getDraggedColumns filtered to keys with string or number', () => {
|
||||
mockGetDraggedColumns.mockReturnValue([
|
||||
col('body'),
|
||||
col('timestamp'),
|
||||
{ title: 'no-key' },
|
||||
]);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange: jest.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current.orderedColumns).toEqual([
|
||||
col('body'),
|
||||
col('timestamp'),
|
||||
]);
|
||||
expect(result.current.orderedColumnIds).toEqual(['body', 'timestamp']);
|
||||
});
|
||||
|
||||
it('hasSingleColumn is true when exactly one column is not state-indicator', () => {
|
||||
mockGetDraggedColumns.mockReturnValue([col('state-indicator'), col('body')]);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange: jest.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current.hasSingleColumn).toBe(true);
|
||||
});
|
||||
|
||||
it('hasSingleColumn is false when more than one non-state-indicator column exists', () => {
|
||||
mockGetDraggedColumns.mockReturnValue([
|
||||
col('state-indicator'),
|
||||
col('body'),
|
||||
col('timestamp'),
|
||||
]);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange: jest.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current.hasSingleColumn).toBe(false);
|
||||
});
|
||||
|
||||
it('handleDragEnd reorders columns and calls onColumnOrderChange', () => {
|
||||
const onColumnOrderChange = jest.fn();
|
||||
mockGetDraggedColumns.mockReturnValue([col('a'), col('b'), col('c')]);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange,
|
||||
}),
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.handleDragEnd({
|
||||
active: { id: 'a' },
|
||||
over: { id: 'c' },
|
||||
} as never);
|
||||
});
|
||||
|
||||
expect(onColumnOrderChange).toHaveBeenCalledWith([
|
||||
expect.objectContaining({ key: 'b' }),
|
||||
expect.objectContaining({ key: 'c' }),
|
||||
expect.objectContaining({ key: 'a' }),
|
||||
]);
|
||||
|
||||
// Derived-only: orderedColumns should remain until draggedColumns (URL/localStorage) updates.
|
||||
expect(result.current.orderedColumns.map((c) => c.key)).toEqual([
|
||||
'a',
|
||||
'b',
|
||||
'c',
|
||||
]);
|
||||
});
|
||||
|
||||
it('handleDragEnd no-ops when over is null', () => {
|
||||
const onColumnOrderChange = jest.fn();
|
||||
mockGetDraggedColumns.mockReturnValue([col('a'), col('b')]);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange,
|
||||
}),
|
||||
);
|
||||
|
||||
const before = result.current.orderedColumns;
|
||||
|
||||
act(() => {
|
||||
result.current.handleDragEnd({
|
||||
active: { id: 'a' },
|
||||
over: null,
|
||||
} as never);
|
||||
});
|
||||
|
||||
expect(result.current.orderedColumns).toBe(before);
|
||||
expect(onColumnOrderChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handleDragEnd no-ops when active.id equals over.id', () => {
|
||||
const onColumnOrderChange = jest.fn();
|
||||
mockGetDraggedColumns.mockReturnValue([col('a'), col('b')]);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange,
|
||||
}),
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.handleDragEnd({
|
||||
active: { id: 'a' },
|
||||
over: { id: 'a' },
|
||||
} as never);
|
||||
});
|
||||
|
||||
expect(onColumnOrderChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handleDragEnd no-ops when indices cannot be resolved', () => {
|
||||
const onColumnOrderChange = jest.fn();
|
||||
mockGetDraggedColumns.mockReturnValue([col('a'), col('b')]);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange,
|
||||
}),
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.handleDragEnd({
|
||||
active: { id: 'missing' },
|
||||
over: { id: 'a' },
|
||||
} as never);
|
||||
});
|
||||
|
||||
expect(onColumnOrderChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('exposes sensors from useSensors', () => {
|
||||
mockGetDraggedColumns.mockReturnValue([col('a')]);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns: [],
|
||||
onColumnOrderChange: jest.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current.sensors).toBeDefined();
|
||||
});
|
||||
|
||||
it('syncs ordered columns when base order changes externally (e.g. URL / localStorage)', () => {
|
||||
mockGetDraggedColumns.mockReturnValue([col('a'), col('b'), col('c')]);
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ draggedColumns }: { draggedColumns: unknown[] }) =>
|
||||
useOrderedColumns({
|
||||
columns: [],
|
||||
draggedColumns,
|
||||
onColumnOrderChange: jest.fn(),
|
||||
}),
|
||||
{ initialProps: { draggedColumns: [] as unknown[] } },
|
||||
);
|
||||
|
||||
expect(result.current.orderedColumns.map((column) => column.key)).toEqual([
|
||||
'a',
|
||||
'b',
|
||||
'c',
|
||||
]);
|
||||
|
||||
mockGetDraggedColumns.mockReturnValue([col('c'), col('b'), col('a')]);
|
||||
|
||||
act(() => {
|
||||
rerender({ draggedColumns: [{ title: 'from-url' }] as unknown[] });
|
||||
});
|
||||
|
||||
expect(result.current.orderedColumns.map((column) => column.key)).toEqual([
|
||||
'c',
|
||||
'b',
|
||||
'a',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,433 +0,0 @@
|
||||
import {
|
||||
forwardRef,
|
||||
memo,
|
||||
MouseEvent as ReactMouseEvent,
|
||||
ReactElement,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import { TableVirtuoso, TableVirtuosoHandle } from 'react-virtuoso';
|
||||
import { DndContext, pointerWithin } from '@dnd-kit/core';
|
||||
import {
|
||||
horizontalListSortingStrategy,
|
||||
SortableContext,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { toast } from '@signozhq/sonner';
|
||||
import {
|
||||
ColumnDef,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
} from '@tanstack/react-table';
|
||||
import { VIEW_TYPES } from 'components/LogDetail/constants';
|
||||
import { ColumnTypeRender } from 'components/Logs/TableView/types';
|
||||
import { useTableView } from 'components/Logs/TableView/useTableView';
|
||||
import Spinner from 'components/Spinner';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useActiveLog } from 'hooks/logs/useActiveLog';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import useDragColumns from 'hooks/useDragColumns';
|
||||
|
||||
import { infinityDefaultStyles } from '../InfinityTableView/config';
|
||||
import { TanStackTableStyled } from '../InfinityTableView/styles';
|
||||
import { InfinityTableProps } from '../InfinityTableView/types';
|
||||
import TanStackCustomTableRow from './TanStackCustomTableRow';
|
||||
import TanStackHeaderRow from './TanStackHeaderRow';
|
||||
import TanStackRowCells from './TanStackRow';
|
||||
import { TableRecord, TanStackTableRowData } from './types';
|
||||
import { useColumnSizingPersistence } from './useColumnSizingPersistence';
|
||||
import { useOrderedColumns } from './useOrderedColumns';
|
||||
import {
|
||||
getColumnId,
|
||||
getColumnMinWidthPx,
|
||||
resolveColumnTypeRender,
|
||||
} from './utils';
|
||||
|
||||
import '../logsTableVirtuosoScrollbar.scss';
|
||||
import './styles/TanStackTableView.styles.scss';
|
||||
|
||||
const COLUMN_DND_AUTO_SCROLL = {
|
||||
layoutShiftCompensation: false as const,
|
||||
threshold: { x: 0.2, y: 0 },
|
||||
};
|
||||
|
||||
const TanStackTableView = forwardRef<TableVirtuosoHandle, InfinityTableProps>(
|
||||
function TanStackTableView(
|
||||
{
|
||||
isLoading,
|
||||
isFetching,
|
||||
onRemoveColumn,
|
||||
tableViewProps,
|
||||
infitiyTableProps,
|
||||
onSetActiveLog,
|
||||
onClearActiveLog,
|
||||
activeLog,
|
||||
}: InfinityTableProps,
|
||||
forwardedRef,
|
||||
): JSX.Element {
|
||||
const { pathname } = useLocation();
|
||||
const virtuosoRef = useRef<TableVirtuosoHandle | null>(null);
|
||||
// could avoid this if directly use forwardedRef in TableVirtuoso, but need to verify if it causes any issue with react-virtuoso internal ref handling
|
||||
useImperativeHandle(
|
||||
forwardedRef,
|
||||
() => virtuosoRef.current as TableVirtuosoHandle,
|
||||
[],
|
||||
);
|
||||
const [, setCopy] = useCopyToClipboard();
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const isLogsExplorerPage = pathname === ROUTES.LOGS_EXPLORER;
|
||||
const { activeLog: activeContextLog } = useActiveLog();
|
||||
|
||||
// Column definitions (shared with existing logs table)
|
||||
const { dataSource, columns } = useTableView({
|
||||
...tableViewProps,
|
||||
onClickExpand: onSetActiveLog,
|
||||
onOpenLogsContext: (log): void => onSetActiveLog?.(log, VIEW_TYPES.CONTEXT),
|
||||
});
|
||||
|
||||
// Column order (drag + persisted order)
|
||||
const { draggedColumns, onColumnOrderChange } = useDragColumns<TableRecord>(
|
||||
LOCALSTORAGE.LOGS_LIST_COLUMNS,
|
||||
);
|
||||
const {
|
||||
orderedColumns,
|
||||
orderedColumnIds,
|
||||
hasSingleColumn,
|
||||
handleDragEnd,
|
||||
sensors,
|
||||
} = useOrderedColumns({
|
||||
columns,
|
||||
draggedColumns,
|
||||
onColumnOrderChange: onColumnOrderChange as (columns: unknown[]) => void,
|
||||
});
|
||||
|
||||
// Column sizing (persisted). stored to localStorage.
|
||||
const { columnSizing, setColumnSizing } = useColumnSizingPersistence(
|
||||
orderedColumns,
|
||||
);
|
||||
|
||||
// don't allow "remove column" when only state-indicator + one data col remain
|
||||
const isAtMinimumRemovableColumns = useMemo(
|
||||
() =>
|
||||
orderedColumns.filter(
|
||||
(column) => column.key !== 'state-indicator' && column.key !== 'expand',
|
||||
).length <= 1,
|
||||
[orderedColumns],
|
||||
);
|
||||
|
||||
// Table data (TanStack row data shape)
|
||||
// useTableView sends flattened log data. this would not be needed once we move to new log details view
|
||||
const tableData = useMemo<TanStackTableRowData[]>(
|
||||
() =>
|
||||
dataSource
|
||||
.map((log, rowIndex) => {
|
||||
const currentLog = tableViewProps.logs[rowIndex];
|
||||
if (!currentLog) {
|
||||
return null;
|
||||
}
|
||||
return { log, currentLog, rowIndex };
|
||||
})
|
||||
.filter(Boolean) as TanStackTableRowData[],
|
||||
[dataSource, tableViewProps.logs],
|
||||
);
|
||||
|
||||
// TanStack columns + table instance
|
||||
const tanstackColumns = useMemo<ColumnDef<TanStackTableRowData>[]>(
|
||||
() =>
|
||||
orderedColumns.map((column, index) => {
|
||||
const isStateIndicator = column.key === 'state-indicator';
|
||||
const isExpand = column.key === 'expand';
|
||||
const isFixedColumn = isStateIndicator || isExpand;
|
||||
const fixedWidth = isFixedColumn ? 32 : undefined;
|
||||
const minWidthPx = getColumnMinWidthPx(column, orderedColumns);
|
||||
const headerTitle = String(column.title || '');
|
||||
|
||||
return {
|
||||
id: getColumnId(column),
|
||||
header: headerTitle.replace(/^\w/, (character) =>
|
||||
character.toUpperCase(),
|
||||
),
|
||||
accessorFn: (row): unknown => row.log[column.key as keyof TableRecord],
|
||||
enableResizing: !isFixedColumn && index !== orderedColumns.length - 1,
|
||||
minSize: fixedWidth ?? minWidthPx,
|
||||
size: fixedWidth, // last column gets remaining space, so don't set initial size to avoid conflict with resizing
|
||||
maxSize: fixedWidth,
|
||||
cell: ({ row, getValue }): ReactElement | string | number | null => {
|
||||
if (!column.render) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return resolveColumnTypeRender(
|
||||
column.render(
|
||||
getValue(),
|
||||
row.original.log,
|
||||
row.original.rowIndex,
|
||||
) as ColumnTypeRender<Record<string, unknown>>,
|
||||
);
|
||||
},
|
||||
};
|
||||
}),
|
||||
[orderedColumns],
|
||||
);
|
||||
const table = useReactTable({
|
||||
data: tableData,
|
||||
columns: tanstackColumns,
|
||||
enableColumnResizing: true,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
columnResizeMode: 'onChange',
|
||||
onColumnSizingChange: setColumnSizing,
|
||||
state: {
|
||||
columnSizing,
|
||||
},
|
||||
});
|
||||
const tableRows = table.getRowModel().rows;
|
||||
|
||||
// Infinite-scroll footer UI state
|
||||
const [loadMoreState, setLoadMoreState] = useState<{
|
||||
active: boolean;
|
||||
startCount: number;
|
||||
}>({
|
||||
active: false,
|
||||
startCount: 0,
|
||||
});
|
||||
|
||||
// Map to resolve full log object by id (row highlighting + indicator)
|
||||
const logsById = useMemo(
|
||||
() => new Map(tableViewProps.logs.map((log) => [String(log.id), log])),
|
||||
[tableViewProps.logs],
|
||||
);
|
||||
|
||||
// this is already written in parent. Check if this is needed.
|
||||
useEffect(() => {
|
||||
const activeLogIndex = tableViewProps.activeLogIndex ?? -1;
|
||||
if (activeLogIndex < 0 || activeLogIndex >= tableRows.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
virtuosoRef.current?.scrollToIndex({
|
||||
index: activeLogIndex,
|
||||
align: 'center',
|
||||
behavior: 'auto',
|
||||
});
|
||||
}, [tableRows.length, tableViewProps.activeLogIndex]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loadMoreState.active) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isFetching || tableRows.length > loadMoreState.startCount) {
|
||||
setLoadMoreState((prev) =>
|
||||
prev.active ? { active: false, startCount: prev.startCount } : prev,
|
||||
);
|
||||
}
|
||||
}, [isFetching, loadMoreState, tableRows.length]);
|
||||
|
||||
const handleLogCopy = useCallback(
|
||||
(logId: string, event: ReactMouseEvent<HTMLElement>): void => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const urlQuery = new URLSearchParams(window.location.search);
|
||||
urlQuery.delete(QueryParams.activeLogId);
|
||||
urlQuery.delete(QueryParams.relativeTime);
|
||||
urlQuery.set(QueryParams.activeLogId, `"${logId}"`);
|
||||
const link = `${window.location.origin}${pathname}?${urlQuery.toString()}`;
|
||||
|
||||
setCopy(link);
|
||||
toast.success('Copied to clipboard', { position: 'top-right' });
|
||||
},
|
||||
[pathname, setCopy],
|
||||
);
|
||||
|
||||
const itemContent = useCallback(
|
||||
(index: number): JSX.Element | null => {
|
||||
const row = tableRows[index];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<TanStackRowCells
|
||||
row={row}
|
||||
fontSize={tableViewProps.fontSize}
|
||||
onSetActiveLog={onSetActiveLog}
|
||||
onClearActiveLog={onClearActiveLog}
|
||||
isActiveLog={
|
||||
String(activeLog?.id ?? '') === String(row.original.currentLog.id ?? '')
|
||||
}
|
||||
isDarkMode={isDarkMode}
|
||||
onLogCopy={handleLogCopy}
|
||||
isLogsExplorerPage={isLogsExplorerPage}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
activeLog?.id,
|
||||
handleLogCopy,
|
||||
isDarkMode,
|
||||
isLogsExplorerPage,
|
||||
onClearActiveLog,
|
||||
onSetActiveLog,
|
||||
tableRows,
|
||||
tableViewProps.fontSize,
|
||||
],
|
||||
);
|
||||
|
||||
const flatHeaders = useMemo(
|
||||
() => table.getFlatHeaders().filter((header) => !header.isPlaceholder),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[tanstackColumns],
|
||||
);
|
||||
|
||||
const tableHeader = useCallback(() => {
|
||||
const orderedColumnsById = new Map(
|
||||
orderedColumns.map((column) => [getColumnId(column), column] as const),
|
||||
);
|
||||
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={pointerWithin}
|
||||
onDragEnd={handleDragEnd}
|
||||
autoScroll={COLUMN_DND_AUTO_SCROLL}
|
||||
>
|
||||
<SortableContext
|
||||
items={orderedColumnIds}
|
||||
strategy={horizontalListSortingStrategy}
|
||||
>
|
||||
<tr>
|
||||
{flatHeaders.map((header) => {
|
||||
const column = orderedColumnsById.get(header.id);
|
||||
if (!column) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<TanStackHeaderRow
|
||||
key={header.id}
|
||||
column={column}
|
||||
header={header}
|
||||
isDarkMode={isDarkMode}
|
||||
fontSize={tableViewProps.fontSize}
|
||||
hasSingleColumn={hasSingleColumn}
|
||||
onRemoveColumn={onRemoveColumn}
|
||||
canRemoveColumn={!isAtMinimumRemovableColumns}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
);
|
||||
}, [
|
||||
flatHeaders,
|
||||
handleDragEnd,
|
||||
hasSingleColumn,
|
||||
isDarkMode,
|
||||
orderedColumnIds,
|
||||
orderedColumns,
|
||||
onRemoveColumn,
|
||||
isAtMinimumRemovableColumns,
|
||||
sensors,
|
||||
tableViewProps.fontSize,
|
||||
]);
|
||||
|
||||
const handleEndReached = useCallback(
|
||||
(index: number): void => {
|
||||
if (!infitiyTableProps?.onEndReached) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadMoreState({
|
||||
active: true,
|
||||
startCount: tableRows.length,
|
||||
});
|
||||
infitiyTableProps.onEndReached(index);
|
||||
},
|
||||
[infitiyTableProps, tableRows.length],
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
return <Spinner height="35px" tip="Getting Logs" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="tanstack-table-view-wrapper">
|
||||
<TableVirtuoso
|
||||
className="logs-table-virtuoso-scroll"
|
||||
ref={virtuosoRef}
|
||||
style={infinityDefaultStyles}
|
||||
data={tableData}
|
||||
totalCount={tableRows.length}
|
||||
increaseViewportBy={{ top: 500, bottom: 500 }}
|
||||
initialTopMostItemIndex={
|
||||
tableViewProps.activeLogIndex !== -1 ? tableViewProps.activeLogIndex : 0
|
||||
}
|
||||
context={{ activeLog, activeContextLog, logsById }}
|
||||
fixedHeaderContent={tableHeader}
|
||||
itemContent={itemContent}
|
||||
components={{
|
||||
Table: ({ style, children }): JSX.Element => (
|
||||
<TanStackTableStyled style={style}>
|
||||
<colgroup>
|
||||
{orderedColumns.map((column, colIndex) => {
|
||||
const columnId = getColumnId(column);
|
||||
const isFixedColumn =
|
||||
column.key === 'expand' || column.key === 'state-indicator';
|
||||
const minWidthPx = getColumnMinWidthPx(column, orderedColumns);
|
||||
const persistedWidth = columnSizing[columnId];
|
||||
const computedWidth = table.getColumn(columnId)?.getSize();
|
||||
const effectiveWidth = persistedWidth ?? computedWidth;
|
||||
if (isFixedColumn) {
|
||||
return <col key={columnId} className="tanstack-fixed-col" />;
|
||||
}
|
||||
// Last data column should stretch to fill remaining space
|
||||
const isLastColumn = colIndex === orderedColumns.length - 1;
|
||||
if (isLastColumn) {
|
||||
return (
|
||||
<col
|
||||
key={columnId}
|
||||
style={{ width: '100%', minWidth: `${minWidthPx}px` }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const widthPx =
|
||||
effectiveWidth != null
|
||||
? Math.max(effectiveWidth, minWidthPx)
|
||||
: minWidthPx;
|
||||
return (
|
||||
<col
|
||||
key={columnId}
|
||||
style={{ width: `${widthPx}px`, minWidth: `${minWidthPx}px` }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</colgroup>
|
||||
{children}
|
||||
</TanStackTableStyled>
|
||||
),
|
||||
TableRow: TanStackCustomTableRow,
|
||||
}}
|
||||
{...(infitiyTableProps?.onEndReached
|
||||
? { endReached: handleEndReached }
|
||||
: {})}
|
||||
/>
|
||||
{loadMoreState.active && (
|
||||
<div className="tanstack-load-more-container">
|
||||
<Spinner height="20px" tip="Getting Logs" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export default memo(TanStackTableView);
|
||||
@@ -1,55 +0,0 @@
|
||||
.tanstack-table-view-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.tanstack-fixed-col {
|
||||
width: 32px;
|
||||
min-width: 32px;
|
||||
max-width: 32px;
|
||||
}
|
||||
|
||||
.tanstack-filler-col {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tanstack-actions-col {
|
||||
width: 0;
|
||||
min-width: 0;
|
||||
max-width: 0;
|
||||
}
|
||||
|
||||
.tanstack-load-more-container {
|
||||
width: 100%;
|
||||
min-height: 56px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 8px 0 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.tanstack-table-virtuoso {
|
||||
width: 100%;
|
||||
overflow-x: scroll;
|
||||
}
|
||||
|
||||
.tanstack-fontSize-small {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.tanstack-fontSize-medium {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.tanstack-fontSize-large {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.tanstack-table-foot-loader-cell {
|
||||
text-align: center;
|
||||
padding: 8px 0;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { ColumnSizingState } from '@tanstack/react-table';
|
||||
import { ColumnTypeRender } from 'components/Logs/TableView/types';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
export type TableRecord = Record<string, unknown>;
|
||||
|
||||
export type LogsTableColumnDef = {
|
||||
key?: string | number;
|
||||
title?: string;
|
||||
render?: (
|
||||
value: unknown,
|
||||
record: TableRecord,
|
||||
index: number,
|
||||
) => ColumnTypeRender<Record<string, unknown>>;
|
||||
};
|
||||
|
||||
export type OrderedColumn = LogsTableColumnDef & {
|
||||
key: string | number;
|
||||
};
|
||||
|
||||
export type TanStackTableRowData = {
|
||||
log: TableRecord;
|
||||
currentLog: ILog;
|
||||
rowIndex: number;
|
||||
};
|
||||
|
||||
export type PersistedColumnSizing = {
|
||||
sizing: ColumnSizingState;
|
||||
};
|
||||
@@ -1,111 +0,0 @@
|
||||
import { Dispatch, SetStateAction, useEffect, useMemo, useState } from 'react';
|
||||
import { ColumnSizingState } from '@tanstack/react-table';
|
||||
import getFromLocalstorage from 'api/browser/localstorage/get';
|
||||
import setToLocalstorage from 'api/browser/localstorage/set';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
|
||||
import { OrderedColumn, PersistedColumnSizing } from './types';
|
||||
import { getColumnId } from './utils';
|
||||
|
||||
const COLUMN_SIZING_PERSIST_DEBOUNCE_MS = 250;
|
||||
|
||||
const sanitizeSizing = (input: unknown): ColumnSizingState => {
|
||||
if (!input || typeof input !== 'object') {
|
||||
return {};
|
||||
}
|
||||
return Object.entries(
|
||||
input as Record<string, unknown>,
|
||||
).reduce<ColumnSizingState>((acc, [key, value]) => {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
|
||||
return acc;
|
||||
}
|
||||
acc[key] = value;
|
||||
return acc;
|
||||
}, {});
|
||||
};
|
||||
|
||||
const readPersistedColumnSizing = (): ColumnSizingState => {
|
||||
const rawSizing = getFromLocalstorage(LOCALSTORAGE.LOGS_LIST_COLUMN_SIZING);
|
||||
if (!rawSizing) {
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawSizing) as
|
||||
| PersistedColumnSizing
|
||||
| ColumnSizingState;
|
||||
const sizing = ('sizing' in parsed
|
||||
? parsed.sizing
|
||||
: parsed) as ColumnSizingState;
|
||||
return sanitizeSizing(sizing);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse persisted log column sizing', error);
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
type UseColumnSizingPersistenceResult = {
|
||||
columnSizing: ColumnSizingState;
|
||||
setColumnSizing: Dispatch<SetStateAction<ColumnSizingState>>;
|
||||
};
|
||||
|
||||
export const useColumnSizingPersistence = (
|
||||
orderedColumns: OrderedColumn[],
|
||||
): UseColumnSizingPersistenceResult => {
|
||||
const [columnSizing, setColumnSizing] = useState<ColumnSizingState>(() =>
|
||||
readPersistedColumnSizing(),
|
||||
);
|
||||
const orderedColumnIds = useMemo(
|
||||
() => orderedColumns.map((column) => getColumnId(column)),
|
||||
[orderedColumns],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (orderedColumnIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const validColumnIds = new Set(orderedColumnIds);
|
||||
const nonResizableColumnIds = new Set(
|
||||
orderedColumns
|
||||
.filter(
|
||||
(column) => column.key === 'expand' || column.key === 'state-indicator',
|
||||
)
|
||||
.map((column) => getColumnId(column)),
|
||||
);
|
||||
|
||||
setColumnSizing((previousSizing) => {
|
||||
const nextSizing = Object.entries(previousSizing).reduce<ColumnSizingState>(
|
||||
(acc, [columnId, size]) => {
|
||||
if (!validColumnIds.has(columnId) || nonResizableColumnIds.has(columnId)) {
|
||||
return acc;
|
||||
}
|
||||
acc[columnId] = size;
|
||||
return acc;
|
||||
},
|
||||
{},
|
||||
);
|
||||
const hasChanged =
|
||||
Object.keys(nextSizing).length !== Object.keys(previousSizing).length ||
|
||||
Object.entries(nextSizing).some(
|
||||
([columnId, size]) => previousSizing[columnId] !== size,
|
||||
);
|
||||
|
||||
return hasChanged ? nextSizing : previousSizing;
|
||||
});
|
||||
}, [orderedColumnIds, orderedColumns]);
|
||||
|
||||
useEffect(() => {
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
const persistedSizing = { sizing: columnSizing };
|
||||
setToLocalstorage(
|
||||
LOCALSTORAGE.LOGS_LIST_COLUMN_SIZING,
|
||||
JSON.stringify(persistedSizing),
|
||||
);
|
||||
}, COLUMN_SIZING_PERSIST_DEBOUNCE_MS);
|
||||
|
||||
return (): void => window.clearTimeout(timeoutId);
|
||||
}, [columnSizing]);
|
||||
|
||||
return { columnSizing, setColumnSizing };
|
||||
};
|
||||
@@ -1,108 +0,0 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import {
|
||||
DragEndEvent,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from '@dnd-kit/core';
|
||||
import { arrayMove } from '@dnd-kit/sortable';
|
||||
import { getDraggedColumns } from 'hooks/useDragColumns/utils';
|
||||
|
||||
import { OrderedColumn, TableRecord } from './types';
|
||||
import { getColumnId } from './utils';
|
||||
|
||||
type UseOrderedColumnsProps = {
|
||||
columns: unknown[];
|
||||
draggedColumns: unknown[];
|
||||
onColumnOrderChange: (columns: unknown[]) => void;
|
||||
};
|
||||
|
||||
type UseOrderedColumnsResult = {
|
||||
orderedColumns: OrderedColumn[];
|
||||
orderedColumnIds: string[];
|
||||
hasSingleColumn: boolean;
|
||||
handleDragEnd: (event: DragEndEvent) => void;
|
||||
sensors: ReturnType<typeof useSensors>;
|
||||
};
|
||||
|
||||
export const useOrderedColumns = ({
|
||||
columns,
|
||||
draggedColumns,
|
||||
onColumnOrderChange,
|
||||
}: UseOrderedColumnsProps): UseOrderedColumnsResult => {
|
||||
const baseColumns = useMemo<OrderedColumn[]>(
|
||||
() =>
|
||||
getDraggedColumns<TableRecord>(
|
||||
columns as never[],
|
||||
draggedColumns as never[],
|
||||
).filter(
|
||||
(column): column is OrderedColumn =>
|
||||
typeof column.key === 'string' || typeof column.key === 'number',
|
||||
),
|
||||
[columns, draggedColumns],
|
||||
);
|
||||
|
||||
const orderedColumns = useMemo(() => {
|
||||
const stateIndicatorIndex = baseColumns.findIndex(
|
||||
(column) => column.key === 'state-indicator',
|
||||
);
|
||||
if (stateIndicatorIndex <= 0) {
|
||||
return baseColumns;
|
||||
}
|
||||
const pinned = baseColumns[stateIndicatorIndex];
|
||||
const rest = baseColumns.filter((_, i) => i !== stateIndicatorIndex);
|
||||
return [pinned, ...rest];
|
||||
}, [baseColumns]);
|
||||
|
||||
const handleDragEnd = useCallback(
|
||||
(event: DragEndEvent): void => {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't allow moving the state-indicator column
|
||||
if (String(active.id) === 'state-indicator') {
|
||||
return;
|
||||
}
|
||||
|
||||
const oldIndex = orderedColumns.findIndex(
|
||||
(column) => getColumnId(column) === String(active.id),
|
||||
);
|
||||
const newIndex = orderedColumns.findIndex(
|
||||
(column) => getColumnId(column) === String(over.id),
|
||||
);
|
||||
if (oldIndex === -1 || newIndex === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextColumns = arrayMove(orderedColumns, oldIndex, newIndex);
|
||||
onColumnOrderChange(nextColumns as unknown[]);
|
||||
},
|
||||
[onColumnOrderChange, orderedColumns],
|
||||
);
|
||||
|
||||
const orderedColumnIds = useMemo(
|
||||
() => orderedColumns.map((column) => getColumnId(column)),
|
||||
[orderedColumns],
|
||||
);
|
||||
const hasSingleColumn = useMemo(
|
||||
() =>
|
||||
orderedColumns.filter((column) => column.key !== 'state-indicator')
|
||||
.length === 1,
|
||||
[orderedColumns],
|
||||
);
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: { distance: 4 },
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
orderedColumns,
|
||||
orderedColumnIds,
|
||||
hasSingleColumn,
|
||||
handleDragEnd,
|
||||
sensors,
|
||||
};
|
||||
};
|
||||
@@ -1,61 +0,0 @@
|
||||
import { cloneElement, isValidElement, ReactElement } from 'react';
|
||||
import { ColumnTypeRender } from 'components/Logs/TableView/types';
|
||||
|
||||
import { OrderedColumn } from './types';
|
||||
|
||||
export const getColumnId = (column: OrderedColumn): string =>
|
||||
String(column.key);
|
||||
|
||||
/** Browser default root font size; TanStack column sizing uses px. */
|
||||
const REM_PX = 16;
|
||||
const MIN_WIDTH_OTHER_REM = 12;
|
||||
const MIN_WIDTH_BODY_REM = 40;
|
||||
|
||||
/** When total column count is below this, body column min width is doubled (more horizontal space for few columns). */
|
||||
export const FEW_COLUMNS_BODY_MIN_WIDTH_THRESHOLD = 4;
|
||||
|
||||
/**
|
||||
* Minimum width (px) for TanStack column defs + colgroup.
|
||||
* Design: state/expand 32px; body min 40rem (doubled when fewer than
|
||||
* {@link FEW_COLUMNS_BODY_MIN_WIDTH_THRESHOLD} total columns); other columns use rem→px (16px root).
|
||||
*/
|
||||
export const getColumnMinWidthPx = (
|
||||
column: OrderedColumn,
|
||||
orderedColumns?: OrderedColumn[],
|
||||
): number => {
|
||||
const key = String(column.key);
|
||||
if (key === 'state-indicator' || key === 'expand') {
|
||||
return 32;
|
||||
}
|
||||
if (key === 'body') {
|
||||
const base = MIN_WIDTH_BODY_REM * REM_PX;
|
||||
const fewColumns =
|
||||
orderedColumns != null &&
|
||||
orderedColumns.length < FEW_COLUMNS_BODY_MIN_WIDTH_THRESHOLD;
|
||||
return fewColumns ? base * 1.5 : base;
|
||||
}
|
||||
return MIN_WIDTH_OTHER_REM * REM_PX;
|
||||
};
|
||||
|
||||
export const resolveColumnTypeRender = (
|
||||
rendered: ColumnTypeRender<Record<string, unknown>>,
|
||||
): ReactElement | string | number | null => {
|
||||
if (
|
||||
rendered &&
|
||||
typeof rendered === 'object' &&
|
||||
'children' in rendered &&
|
||||
isValidElement(rendered.children)
|
||||
) {
|
||||
const { children, props } = rendered as {
|
||||
children: ReactElement;
|
||||
props?: Record<string, unknown>;
|
||||
};
|
||||
return cloneElement(children, props || {});
|
||||
}
|
||||
if (rendered && typeof rendered === 'object' && isValidElement(rendered)) {
|
||||
return rendered;
|
||||
}
|
||||
return typeof rendered === 'string' || typeof rendered === 'number'
|
||||
? rendered
|
||||
: null;
|
||||
};
|
||||
@@ -1,16 +1,28 @@
|
||||
import type { CSSProperties, MouseEvent, ReactNode } from 'react';
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import { toast } from '@signozhq/sonner';
|
||||
import { Card } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
|
||||
import LogDetail from 'components/LogDetail';
|
||||
// components
|
||||
import { VIEW_TYPES } from 'components/LogDetail/constants';
|
||||
import ListLogView from 'components/Logs/ListLogView';
|
||||
import LogLinesActionButtons from 'components/Logs/LogLinesActionButtons/LogLinesActionButtons';
|
||||
import { getRowBackgroundColor } from 'components/Logs/LogStateIndicator/getRowBackgroundColor';
|
||||
import { getLogIndicatorType } from 'components/Logs/LogStateIndicator/utils';
|
||||
import RawLogView from 'components/Logs/RawLogView';
|
||||
import { useLogsTableColumns } from 'components/Logs/TableView/useLogsTableColumns';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import Spinner from 'components/Spinner';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import type { TanStackTableHandle } from 'components/TanStackTableView/types';
|
||||
import { useTableColumns } from 'components/TanStackTableView/useTableColumns';
|
||||
import { CARD_BODY_STYLE } from 'constants/card';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import EmptyLogsSearch from 'container/EmptyLogsSearch/EmptyLogsSearch';
|
||||
import { LogsLoading } from 'container/LogsLoading/LogsLoading';
|
||||
import { useOptionsMenu } from 'container/OptionsMenu';
|
||||
@@ -19,6 +31,7 @@ import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
|
||||
import useLogDetailHandlers from 'hooks/logs/useLogDetailHandlers';
|
||||
import useScrollToLog from 'hooks/logs/useScrollToLog';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import APIError from 'types/api/error';
|
||||
// interfaces
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
@@ -27,7 +40,6 @@ import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
import NoLogs from '../NoLogs/NoLogs';
|
||||
import { LogsExplorerListProps } from './LogsExplorerList.interfaces';
|
||||
import { InfinityWrapperStyled } from './styles';
|
||||
import TanStackTableView from './TanStackTableView';
|
||||
import {
|
||||
convertKeysToColumnFields,
|
||||
getEmptyLogsListConfig,
|
||||
@@ -50,7 +62,10 @@ function LogsExplorerList({
|
||||
isFilterApplied,
|
||||
handleChangeSelectedView,
|
||||
}: LogsExplorerListProps): JSX.Element {
|
||||
const ref = useRef<VirtuosoHandle>(null);
|
||||
const ref = useRef<TanStackTableHandle | VirtuosoHandle | null>(null);
|
||||
const { pathname } = useLocation();
|
||||
const [, setCopy] = useCopyToClipboard();
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const { activeLogId } = useCopyLogLink();
|
||||
|
||||
const {
|
||||
@@ -84,9 +99,46 @@ function LogsExplorerList({
|
||||
[options],
|
||||
);
|
||||
|
||||
const logsColumns = useLogsTableColumns({
|
||||
fields: selectedFields,
|
||||
linesPerRow: options.maxLines,
|
||||
fontSize: options.fontSize,
|
||||
appendTo: 'end',
|
||||
});
|
||||
|
||||
const { tableProps } = useTableColumns(logsColumns, {
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_COLUMNS,
|
||||
});
|
||||
|
||||
const handleRemoveColumn = useCallback(
|
||||
(columnId: string): void => {
|
||||
tableProps.onRemoveColumn(columnId);
|
||||
config.addColumn?.onRemove?.(columnId);
|
||||
},
|
||||
[tableProps, config.addColumn],
|
||||
);
|
||||
|
||||
const makeOnLogCopy = useCallback(
|
||||
(log: ILog) => (event: MouseEvent<HTMLElement>): void => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const urlQuery = new URLSearchParams(window.location.search);
|
||||
urlQuery.delete(QueryParams.activeLogId);
|
||||
urlQuery.delete(QueryParams.relativeTime);
|
||||
urlQuery.set(QueryParams.activeLogId, `"${log.id}"`);
|
||||
const link = `${window.location.origin}${pathname}?${urlQuery.toString()}`;
|
||||
setCopy(link);
|
||||
toast.success('Copied to clipboard', { position: 'top-right' });
|
||||
},
|
||||
[pathname, setCopy],
|
||||
);
|
||||
|
||||
const handleScrollToLog = useScrollToLog({
|
||||
logs,
|
||||
virtuosoRef: ref,
|
||||
virtuosoRef: ref as React.RefObject<Pick<
|
||||
VirtuosoHandle,
|
||||
'scrollToIndex'
|
||||
> | null>,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -155,25 +207,46 @@ function LogsExplorerList({
|
||||
|
||||
if (options.format === 'table') {
|
||||
return (
|
||||
<TanStackTableView
|
||||
ref={ref}
|
||||
isLoading={isLoading}
|
||||
isFetching={isFetching}
|
||||
tableViewProps={{
|
||||
logs,
|
||||
fields: selectedFields,
|
||||
linesPerRow: options.maxLines,
|
||||
fontSize: options.fontSize,
|
||||
appendTo: 'end',
|
||||
activeLogIndex,
|
||||
<TanStackTable
|
||||
ref={ref as React.Ref<TanStackTableHandle>}
|
||||
{...tableProps}
|
||||
plainTextCellLineClamp={options.maxLines}
|
||||
cellTypographySize={options.fontSize}
|
||||
onRemoveColumn={handleRemoveColumn}
|
||||
data={logs}
|
||||
isLoading={isLoading || isFetching}
|
||||
loadingTip="Getting Logs"
|
||||
onEndReached={onEndReached}
|
||||
isRowActive={(log): boolean =>
|
||||
log.id === activeLog?.id || log.id === activeLogId
|
||||
}
|
||||
getRowStyle={(log): CSSProperties =>
|
||||
({
|
||||
'--row-active-bg': getRowBackgroundColor(
|
||||
isDarkMode,
|
||||
getLogIndicatorType(log),
|
||||
),
|
||||
'--row-hover-bg': getRowBackgroundColor(
|
||||
isDarkMode,
|
||||
getLogIndicatorType(log),
|
||||
),
|
||||
} as CSSProperties)
|
||||
}
|
||||
onRowClick={(log): void => {
|
||||
handleSetActiveLog(log);
|
||||
}}
|
||||
infitiyTableProps={{ onEndReached }}
|
||||
handleChangeSelectedView={handleChangeSelectedView}
|
||||
logs={logs}
|
||||
onSetActiveLog={handleSetActiveLog}
|
||||
onClearActiveLog={handleCloseLogDetail}
|
||||
activeLog={activeLog}
|
||||
onRemoveColumn={config.addColumn?.onRemove}
|
||||
onRowDeactivate={handleCloseLogDetail}
|
||||
activeRowIndex={activeLogIndex}
|
||||
renderRowActions={(log): ReactNode => (
|
||||
<LogLinesActionButtons
|
||||
handleShowContext={(e): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleSetActiveLog(log, VIEW_TYPES.CONTEXT);
|
||||
}}
|
||||
onLogCopy={makeOnLogCopy(log)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -198,7 +271,7 @@ function LogsExplorerList({
|
||||
<OverlayScrollbar isVirtuoso>
|
||||
<Virtuoso
|
||||
key={activeLogIndex || 'logs-virtuoso'}
|
||||
ref={ref}
|
||||
ref={ref as React.Ref<VirtuosoHandle>}
|
||||
initialTopMostItemIndex={activeLogIndex !== -1 ? activeLogIndex : 0}
|
||||
data={logs}
|
||||
endReached={onEndReached}
|
||||
@@ -219,12 +292,13 @@ function LogsExplorerList({
|
||||
onEndReached,
|
||||
getItemContent,
|
||||
isFetching,
|
||||
selectedFields,
|
||||
handleChangeSelectedView,
|
||||
handleSetActiveLog,
|
||||
handleCloseLogDetail,
|
||||
activeLog,
|
||||
config.addColumn?.onRemove,
|
||||
tableProps,
|
||||
handleRemoveColumn,
|
||||
isDarkMode,
|
||||
makeOnLogCopy,
|
||||
]);
|
||||
|
||||
const isTraceToLogsNavigation = useMemo(() => {
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
.logs-table-virtuoso-scroll {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--bg-slate-300) transparent;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-corner {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-slate-300);
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--bg-slate-200);
|
||||
}
|
||||
}
|
||||
|
||||
.lightMode .logs-table-virtuoso-scroll {
|
||||
scrollbar-color: var(--bg-vanilla-300) transparent;
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-vanilla-300);
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--bg-vanilla-100);
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,8 @@ function MembersSettings(): JSX.Element {
|
||||
|
||||
if (filterMode === FilterMode.Invited) {
|
||||
result = result.filter((m) => m.status === MemberStatus.Invited);
|
||||
} else if (filterMode === FilterMode.Deleted) {
|
||||
result = result.filter((m) => m.status === MemberStatus.Deleted);
|
||||
}
|
||||
|
||||
if (searchQuery.trim()) {
|
||||
@@ -89,6 +91,9 @@ function MembersSettings(): JSX.Element {
|
||||
const pendingCount = allMembers.filter(
|
||||
(m) => m.status === MemberStatus.Invited,
|
||||
).length;
|
||||
const deletedCount = allMembers.filter(
|
||||
(m) => m.status === MemberStatus.Deleted,
|
||||
).length;
|
||||
const totalCount = allMembers.length;
|
||||
|
||||
const filterMenuItems: MenuProps['items'] = [
|
||||
@@ -118,12 +123,27 @@ function MembersSettings(): JSX.Element {
|
||||
setPage(1);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: FilterMode.Deleted,
|
||||
label: (
|
||||
<div className="members-filter-option">
|
||||
<span>Deleted ⎯ {deletedCount}</span>
|
||||
{filterMode === FilterMode.Deleted && <Check size={14} />}
|
||||
</div>
|
||||
),
|
||||
onClick: (): void => {
|
||||
setFilterMode(FilterMode.Deleted);
|
||||
setPage(1);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const filterLabel =
|
||||
filterMode === FilterMode.All
|
||||
? `All members ⎯ ${totalCount}`
|
||||
: `Pending invites ⎯ ${pendingCount}`;
|
||||
: filterMode === FilterMode.Invited
|
||||
? `Pending invites ⎯ ${pendingCount}`
|
||||
: `Deleted ⎯ ${deletedCount}`;
|
||||
|
||||
const handleInviteComplete = useCallback((): void => {
|
||||
refetchUsers();
|
||||
|
||||
@@ -117,14 +117,14 @@ describe('MembersSettings (integration)', () => {
|
||||
await screen.findByText('Member Details');
|
||||
});
|
||||
|
||||
it('does not open EditMemberDrawer when a deleted member row is clicked', async () => {
|
||||
it('opens EditMemberDrawer when a deleted member row is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
render(<MembersSettings />);
|
||||
|
||||
await user.click(await screen.findByText('Dave Deleted'));
|
||||
|
||||
expect(screen.queryByText('Member Details')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Member Details')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens InviteMembersModal when "Invite member" button is clicked', async () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export enum FilterMode {
|
||||
All = 'all',
|
||||
Invited = 'invited',
|
||||
Deleted = 'deleted',
|
||||
}
|
||||
|
||||
export enum MemberStatus {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
.display-name-form {
|
||||
.form-field {
|
||||
margin-bottom: var(--spacing-8);
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: var(--spacing-4);
|
||||
}
|
||||
}
|
||||
|
||||
.field-error {
|
||||
color: var(--destructive);
|
||||
margin-top: var(--spacing-2);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { toast } from '@signozhq/sonner';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import DisplayName from '../index';
|
||||
|
||||
jest.mock('@signozhq/sonner', () => ({
|
||||
toast: {
|
||||
success: jest.fn(),
|
||||
error: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const ORG_ME_ENDPOINT = '*/api/v2/orgs/me';
|
||||
|
||||
const defaultProps = { index: 0, id: 'does-not-matter-id' };
|
||||
|
||||
describe('DisplayName', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('renders form pre-filled with org displayName from context', async () => {
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByRole('textbox');
|
||||
expect(input).toHaveValue('Pentagon');
|
||||
|
||||
expect(screen.getByRole('button', { name: /submit/i })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables submit and calls PUT when display name is changed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
server.use(rest.put(ORG_ME_ENDPOINT, (_, res, ctx) => res(ctx.status(200))));
|
||||
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'New Org Name');
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /submit/i });
|
||||
expect(submitBtn).toBeEnabled();
|
||||
|
||||
await user.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.success).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows validation error when display name is cleared and submitted', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.clear(input);
|
||||
|
||||
const form = input.closest('form') as HTMLFormElement;
|
||||
fireEvent.submit(form);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/missing display name/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,21 +1,57 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from '@signozhq/sonner';
|
||||
import { Button, Form, Input } from 'antd';
|
||||
import { Button, Input } from 'antd';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import { useUpdateMyOrganization } from 'api/generated/services/orgs';
|
||||
import {
|
||||
useGetMyOrganization,
|
||||
useUpdateMyOrganization,
|
||||
} from 'api/generated/services/orgs';
|
||||
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { AxiosError } from 'axios';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { IUser } from 'providers/App/types';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { requireErrorMessage } from 'utils/form/requireErrorMessage';
|
||||
|
||||
function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
const [form] = Form.useForm<FormValues>();
|
||||
const orgName = Form.useWatch('displayName', form);
|
||||
import './DisplayName.styles.scss';
|
||||
|
||||
function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
const { t } = useTranslation(['organizationsettings', 'common']);
|
||||
const { org, updateOrg } = useAppContext();
|
||||
const { displayName } = (org || [])[index];
|
||||
const { showErrorModal } = useErrorModal();
|
||||
const { org, updateOrg, user } = useAppContext();
|
||||
const currentOrg = (org || [])[index];
|
||||
const isAdmin = user.role === USER_ROLES.ADMIN;
|
||||
|
||||
const { data: orgData } = useGetMyOrganization({
|
||||
query: {
|
||||
enabled: isAdmin && !currentOrg?.displayName,
|
||||
},
|
||||
});
|
||||
|
||||
const displayName =
|
||||
currentOrg?.displayName ?? orgData?.data?.displayName ?? '';
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
watch,
|
||||
getValues,
|
||||
setValue,
|
||||
} = useForm<FormValues>({
|
||||
defaultValues: { displayName },
|
||||
});
|
||||
|
||||
const orgName = watch('displayName');
|
||||
|
||||
useEffect(() => {
|
||||
if (displayName && !getValues('displayName')) {
|
||||
setValue('displayName', displayName);
|
||||
}
|
||||
}, [displayName, getValues, setValue]);
|
||||
|
||||
const {
|
||||
mutateAsync: updateMyOrganization,
|
||||
@@ -30,20 +66,16 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
updateOrg(orgId, data.displayName ?? '');
|
||||
},
|
||||
onError: (error) => {
|
||||
const apiError = convertToApiError(
|
||||
error as AxiosError<RenderErrorResponseDTO>,
|
||||
);
|
||||
toast.error(
|
||||
apiError?.getErrorMessage() ?? t('something_went_wrong', { ns: 'common' }),
|
||||
{ richColors: true, position: 'top-right' },
|
||||
showErrorModal(
|
||||
convertToApiError(error as AxiosError<RenderErrorResponseDTO>) as APIError,
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (values: FormValues): Promise<void> => {
|
||||
const { displayName } = values;
|
||||
await updateMyOrganization({ data: { id: orgId, displayName } });
|
||||
const { displayName: name } = values;
|
||||
await updateMyOrganization({ data: { id: orgId, displayName: name } });
|
||||
};
|
||||
|
||||
if (!org) {
|
||||
@@ -53,21 +85,34 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
const isDisabled = isLoading || orgName === displayName || !orgName;
|
||||
|
||||
return (
|
||||
<Form
|
||||
initialValues={{ displayName }}
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onFinish={onSubmit}
|
||||
<form
|
||||
className="display-name-form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
autoComplete="off"
|
||||
>
|
||||
<Form.Item
|
||||
name="displayName"
|
||||
label="Display name"
|
||||
rules={[{ required: true, message: requireErrorMessage('Display name') }]}
|
||||
>
|
||||
<Input size="large" placeholder={t('signoz')} />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<div className="form-field">
|
||||
<label htmlFor="displayName">Display name</label>
|
||||
<Controller
|
||||
name="displayName"
|
||||
control={control}
|
||||
rules={{ required: requireErrorMessage('Display name') }}
|
||||
render={({ field, fieldState }): JSX.Element => (
|
||||
<>
|
||||
<Input
|
||||
{...field}
|
||||
id="displayName"
|
||||
size="large"
|
||||
placeholder={t('signoz')}
|
||||
status={fieldState.error ? 'error' : ''}
|
||||
/>
|
||||
{fieldState.error && (
|
||||
<div className="field-error">{fieldState.error.message}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
loading={isLoading}
|
||||
disabled={isDisabled}
|
||||
@@ -76,8 +121,8 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useCallback } from 'react';
|
||||
import type { VirtuosoHandle } from 'react-virtuoso';
|
||||
|
||||
type ScrollToIndexHandle = Pick<VirtuosoHandle, 'scrollToIndex'>;
|
||||
|
||||
type UseScrollToLogParams = {
|
||||
logs: Array<{ id: string }>;
|
||||
virtuosoRef: React.RefObject<VirtuosoHandle | null>;
|
||||
virtuosoRef: React.RefObject<ScrollToIndexHandle | null>;
|
||||
};
|
||||
|
||||
function useScrollToLog({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import type { AuthtypesRoleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useGetUser, useSetRoleByUserID } from 'api/generated/services/users';
|
||||
import { retryOn429 } from 'utils/errorUtils';
|
||||
|
||||
export interface MemberRoleUpdateFailure {
|
||||
roleName: string;
|
||||
@@ -38,7 +39,9 @@ export function useMemberRoleManager(
|
||||
[currentUserRoles],
|
||||
);
|
||||
|
||||
const { mutateAsync: setRole } = useSetRoleByUserID();
|
||||
const { mutateAsync: setRole } = useSetRoleByUserID({
|
||||
mutation: { retry: retryOn429 },
|
||||
});
|
||||
|
||||
const applyDiff = useCallback(
|
||||
async (
|
||||
|
||||
@@ -6,6 +6,12 @@ import {
|
||||
useGetServiceAccountRoles,
|
||||
} from 'api/generated/services/serviceaccount';
|
||||
import type { AuthtypesRoleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { retryOn429 } from 'utils/errorUtils';
|
||||
|
||||
const enum PromiseStatus {
|
||||
Fulfilled = 'fulfilled',
|
||||
Rejected = 'rejected',
|
||||
}
|
||||
|
||||
export interface RoleUpdateFailure {
|
||||
roleName: string;
|
||||
@@ -34,7 +40,9 @@ export function useServiceAccountRoleManager(
|
||||
]);
|
||||
|
||||
// the retry for these mutations is safe due to being idempotent on backend
|
||||
const { mutateAsync: createRole } = useCreateServiceAccountRole();
|
||||
const { mutateAsync: createRole } = useCreateServiceAccountRole({
|
||||
mutation: { retry: retryOn429 },
|
||||
});
|
||||
|
||||
const invalidateRoles = useCallback(
|
||||
() =>
|
||||
@@ -73,11 +81,16 @@ export function useServiceAccountRoleManager(
|
||||
allOperations.map((op) => op.run()),
|
||||
);
|
||||
|
||||
await invalidateRoles();
|
||||
const successCount = results.filter(
|
||||
(r) => r.status === PromiseStatus.Fulfilled,
|
||||
).length;
|
||||
if (successCount > 0) {
|
||||
await invalidateRoles();
|
||||
}
|
||||
|
||||
const failures: RoleUpdateFailure[] = [];
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
if (result.status === PromiseStatus.Rejected) {
|
||||
const { role, run } = allOperations[index];
|
||||
failures.push({
|
||||
roleName: role.name ?? 'unknown',
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
.uplot-tooltip-container {
|
||||
font-family: 'Inter';
|
||||
font-size: 12px;
|
||||
background: var(--bg-ink-300);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
color: var(--bg-vanilla-100);
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--bg-ink-100);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
&.lightMode {
|
||||
background: var(--bg-vanilla-100);
|
||||
color: var(--bg-ink-500);
|
||||
border: 1px solid var(--bg-vanilla-300);
|
||||
|
||||
.uplot-tooltip-list {
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-vanilla-400);
|
||||
}
|
||||
}
|
||||
|
||||
.uplot-tooltip-divider {
|
||||
background-color: var(--bg-vanilla-300);
|
||||
}
|
||||
}
|
||||
|
||||
.uplot-tooltip-header-container {
|
||||
padding: 1rem 1rem 0 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
&:last-child {
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
|
||||
.uplot-tooltip-header {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.uplot-tooltip-divider {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background-color: var(--bg-ink-100);
|
||||
}
|
||||
|
||||
.uplot-tooltip-list {
|
||||
// Virtuoso absolutely positions its item rows; left: 0 prevents accidental
|
||||
// horizontal offset when the scroller has padding or transform applied.
|
||||
div[data-viewport-type='element'] {
|
||||
left: 0;
|
||||
padding: 4px 8px 4px 16px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 0.3rem;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-slate-100);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
.uplot-tooltip-container {
|
||||
font-family: 'Inter';
|
||||
font-size: 12px;
|
||||
background: var(--bg-ink-300);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
color: var(--bg-vanilla-100);
|
||||
border-radius: 6px;
|
||||
padding: 1rem 0.5rem 0.5rem 1rem;
|
||||
border: 1px solid var(--bg-ink-100);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
&.lightMode {
|
||||
background: var(--bg-vanilla-100);
|
||||
color: var(--bg-ink-500);
|
||||
border: 1px solid var(--bg-vanilla-300);
|
||||
|
||||
.uplot-tooltip-list {
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-vanilla-400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.uplot-tooltip-header {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.uplot-tooltip-list-container {
|
||||
overflow-y: auto;
|
||||
max-height: 330px;
|
||||
|
||||
.uplot-tooltip-list {
|
||||
&::-webkit-scrollbar {
|
||||
width: 0.3rem;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-slate-100);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.uplot-tooltip-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
|
||||
.uplot-tooltip-item-marker {
|
||||
border-radius: 50%;
|
||||
border-width: 2px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.uplot-tooltip-item-content {
|
||||
white-space: wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,14 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
|
||||
import { TooltipProps } from '../types';
|
||||
import TooltipItem from './components/TooltipItem/TooltipItem';
|
||||
|
||||
import './Tooltip.styles.scss';
|
||||
import Styles from './Tooltip.module.scss';
|
||||
|
||||
const TOOLTIP_LIST_MAX_HEIGHT = 330;
|
||||
// Fallback per-item height used for the initial size estimate before
|
||||
// Virtuoso reports the real total height via totalListHeightChanged.
|
||||
const TOOLTIP_ITEM_HEIGHT = 38;
|
||||
const TOOLTIP_LIST_PADDING = 10;
|
||||
const LIST_MAX_HEIGHT = 300;
|
||||
|
||||
export default function Tooltip({
|
||||
uPlotInstance,
|
||||
@@ -21,27 +23,26 @@ export default function Tooltip({
|
||||
showTooltipHeader = true,
|
||||
}: TooltipProps): JSX.Element {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const [listHeight, setListHeight] = useState(0);
|
||||
const tooltipContent = content ?? [];
|
||||
const { timezone: userTimezone } = useTimezone();
|
||||
const [totalListHeight, setTotalListHeight] = useState(0);
|
||||
|
||||
const resolvedTimezone = useMemo(() => {
|
||||
if (!timezone) {
|
||||
return userTimezone.value;
|
||||
}
|
||||
return timezone.value;
|
||||
}, [timezone, userTimezone]);
|
||||
const tooltipContent = useMemo(() => content ?? [], [content]);
|
||||
|
||||
const resolvedTimezone = timezone?.value ?? userTimezone.value;
|
||||
|
||||
const headerTitle = useMemo(() => {
|
||||
if (!showTooltipHeader) {
|
||||
return null;
|
||||
}
|
||||
const data = uPlotInstance.data;
|
||||
const cursorIdx = uPlotInstance.cursor.idx;
|
||||
if (cursorIdx == null) {
|
||||
return null;
|
||||
}
|
||||
return dayjs(data[0][cursorIdx] * 1000)
|
||||
const timestamp = uPlotInstance.data[0]?.[cursorIdx];
|
||||
if (timestamp == null) {
|
||||
return null;
|
||||
}
|
||||
return dayjs(timestamp * 1000)
|
||||
.tz(resolvedTimezone)
|
||||
.format(DATE_TIME_FORMATS.MONTH_DATETIME_SECONDS);
|
||||
}, [
|
||||
@@ -51,60 +52,68 @@ export default function Tooltip({
|
||||
showTooltipHeader,
|
||||
]);
|
||||
|
||||
const virtuosoStyle = useMemo(() => {
|
||||
return {
|
||||
height:
|
||||
listHeight > 0
|
||||
? Math.min(listHeight + TOOLTIP_LIST_PADDING, TOOLTIP_LIST_MAX_HEIGHT)
|
||||
: Math.min(
|
||||
tooltipContent.length * TOOLTIP_ITEM_HEIGHT,
|
||||
TOOLTIP_LIST_MAX_HEIGHT,
|
||||
),
|
||||
width: '100%',
|
||||
};
|
||||
}, [listHeight, tooltipContent.length]);
|
||||
const activeItem = useMemo(
|
||||
() => tooltipContent.find((item) => item.isActive) ?? null,
|
||||
[tooltipContent],
|
||||
);
|
||||
|
||||
// Use the measured height from Virtuoso when available; fall back to a
|
||||
// per-item estimate on the first render. Math.ceil prevents a 1 px
|
||||
// subpixel rounding gap from triggering a spurious scrollbar.
|
||||
const virtuosoHeight = useMemo(() => {
|
||||
return totalListHeight > 0
|
||||
? Math.ceil(Math.min(totalListHeight, LIST_MAX_HEIGHT))
|
||||
: Math.min(tooltipContent.length * TOOLTIP_ITEM_HEIGHT, LIST_MAX_HEIGHT);
|
||||
}, [totalListHeight, tooltipContent.length]);
|
||||
|
||||
const showHeader = showTooltipHeader || activeItem != null;
|
||||
// With a single series the active item is fully represented in the header —
|
||||
// hide the divider and list to avoid showing a duplicate row.
|
||||
const showList = tooltipContent.length > 1;
|
||||
const showDivider = showList && showHeader;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'uplot-tooltip-container',
|
||||
isDarkMode ? 'darkMode' : 'lightMode',
|
||||
)}
|
||||
className={cx(Styles.uplotTooltipContainer, !isDarkMode && Styles.lightMode)}
|
||||
data-testid="uplot-tooltip-container"
|
||||
>
|
||||
{showTooltipHeader && (
|
||||
<div className="uplot-tooltip-header" data-testid="uplot-tooltip-header">
|
||||
<span>{headerTitle}</span>
|
||||
{showHeader && (
|
||||
<div className={Styles.uplotTooltipHeaderContainer}>
|
||||
{showTooltipHeader && headerTitle && (
|
||||
<div
|
||||
className={Styles.uplotTooltipHeader}
|
||||
data-testid="uplot-tooltip-header"
|
||||
>
|
||||
<span>{headerTitle}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeItem && (
|
||||
<TooltipItem
|
||||
item={activeItem}
|
||||
isItemActive={true}
|
||||
containerTestId="uplot-tooltip-pinned"
|
||||
markerTestId="uplot-tooltip-pinned-marker"
|
||||
contentTestId="uplot-tooltip-pinned-content"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="uplot-tooltip-list-container">
|
||||
{tooltipContent.length > 0 ? (
|
||||
<Virtuoso
|
||||
className="uplot-tooltip-list"
|
||||
data-testid="uplot-tooltip-list"
|
||||
data={tooltipContent}
|
||||
style={virtuosoStyle}
|
||||
totalListHeightChanged={setListHeight}
|
||||
itemContent={(_, item): JSX.Element => (
|
||||
<div className="uplot-tooltip-item" data-testid="uplot-tooltip-item">
|
||||
<div
|
||||
className="uplot-tooltip-item-marker"
|
||||
style={{ borderColor: item.color }}
|
||||
data-is-legend-marker={true}
|
||||
data-testid="uplot-tooltip-item-marker"
|
||||
/>
|
||||
<div
|
||||
className="uplot-tooltip-item-content"
|
||||
style={{ color: item.color, fontWeight: item.isActive ? 700 : 400 }}
|
||||
data-testid="uplot-tooltip-item-content"
|
||||
>
|
||||
{item.label}: {item.tooltipValue}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{showDivider && <span className={Styles.uplotTooltipDivider} />}
|
||||
|
||||
{showList && (
|
||||
<Virtuoso
|
||||
className={Styles.uplotTooltipList}
|
||||
data-testid="uplot-tooltip-list"
|
||||
data={tooltipContent}
|
||||
style={{ height: virtuosoHeight, width: '100%' }}
|
||||
totalListHeightChanged={setTotalListHeight}
|
||||
itemContent={(_, item): JSX.Element => (
|
||||
<TooltipItem item={item} isItemActive={false} />
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -133,46 +133,30 @@ describe('Tooltip', () => {
|
||||
expect(screen.queryByText(unexpectedTitle)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders lightMode class when dark mode is disabled', () => {
|
||||
it('renders single active item in header only, without a list', () => {
|
||||
const uPlotInstance = createUPlotInstance(null);
|
||||
mockUseIsDarkMode.mockReturnValue(false);
|
||||
|
||||
renderTooltip({ uPlotInstance });
|
||||
|
||||
const container = screen.getByTestId('uplot-tooltip-container');
|
||||
|
||||
expect(container).toHaveClass('lightMode');
|
||||
expect(container).not.toHaveClass('darkMode');
|
||||
});
|
||||
|
||||
it('renders darkMode class when dark mode is enabled', () => {
|
||||
const uPlotInstance = createUPlotInstance(null);
|
||||
mockUseIsDarkMode.mockReturnValue(true);
|
||||
|
||||
renderTooltip({ uPlotInstance });
|
||||
|
||||
const container = screen.getByTestId('uplot-tooltip-container');
|
||||
|
||||
expect(container).toHaveClass('darkMode');
|
||||
expect(container).not.toHaveClass('lightMode');
|
||||
});
|
||||
|
||||
it('renders tooltip items when content is provided', () => {
|
||||
const uPlotInstance = createUPlotInstance(null);
|
||||
const content = [createTooltipContent()];
|
||||
const content = [createTooltipContent({ isActive: true })];
|
||||
|
||||
renderTooltip({ uPlotInstance, content });
|
||||
|
||||
const list = screen.queryByTestId('uplot-tooltip-list');
|
||||
// Active item is shown in the header, not duplicated in a list
|
||||
expect(screen.queryByTestId('uplot-tooltip-list')).toBeNull();
|
||||
expect(screen.getByTestId('uplot-tooltip-pinned')).toBeInTheDocument();
|
||||
const pinnedContent = screen.getByTestId('uplot-tooltip-pinned-content');
|
||||
expect(pinnedContent).toHaveTextContent('Series A');
|
||||
expect(pinnedContent).toHaveTextContent('10');
|
||||
});
|
||||
|
||||
expect(list).not.toBeNull();
|
||||
it('renders list when multiple series are present', () => {
|
||||
const uPlotInstance = createUPlotInstance(null);
|
||||
const content = [
|
||||
createTooltipContent({ isActive: true }),
|
||||
createTooltipContent({ label: 'Series B', isActive: false }),
|
||||
];
|
||||
|
||||
const marker = screen.getByTestId('uplot-tooltip-item-marker');
|
||||
const itemContent = screen.getByTestId('uplot-tooltip-item-content');
|
||||
renderTooltip({ uPlotInstance, content });
|
||||
|
||||
expect(marker).toHaveStyle({ borderColor: '#ff0000' });
|
||||
expect(itemContent).toHaveStyle({ color: '#ff0000', fontWeight: '700' });
|
||||
expect(itemContent).toHaveTextContent('Series A: 10');
|
||||
expect(screen.getByTestId('uplot-tooltip-list')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render tooltip list when content is empty', () => {
|
||||
@@ -192,7 +176,7 @@ describe('Tooltip', () => {
|
||||
renderTooltip({ uPlotInstance, content });
|
||||
|
||||
const list = screen.getByTestId('uplot-tooltip-list');
|
||||
expect(list).toHaveStyle({ height: '210px' });
|
||||
expect(list).toHaveStyle({ height: '200px' });
|
||||
});
|
||||
|
||||
it('sets tooltip list height based on content length when Virtuoso reports 0 height', () => {
|
||||
|
||||
@@ -189,7 +189,7 @@ describe('Tooltip utils', () => {
|
||||
];
|
||||
}
|
||||
|
||||
it('builds tooltip content with active series first', () => {
|
||||
it('builds tooltip content in series-index order with isActive flag set correctly', () => {
|
||||
const data: AlignedData = [[0], [10], [20], [30]];
|
||||
const series = createSeriesConfig();
|
||||
const dataIndexes = [null, 0, 0, 0];
|
||||
@@ -206,21 +206,21 @@ describe('Tooltip utils', () => {
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
// Active (series index 2) should come first
|
||||
// Series are returned in series-index order (A=index 1 before B=index 2)
|
||||
expect(result[0]).toMatchObject<Partial<TooltipContentItem>>({
|
||||
label: 'B',
|
||||
value: 20,
|
||||
tooltipValue: 'formatted-20',
|
||||
color: 'color-2',
|
||||
isActive: true,
|
||||
});
|
||||
expect(result[1]).toMatchObject<Partial<TooltipContentItem>>({
|
||||
label: 'A',
|
||||
value: 10,
|
||||
tooltipValue: 'formatted-10',
|
||||
color: '#ff0000',
|
||||
isActive: false,
|
||||
});
|
||||
expect(result[1]).toMatchObject<Partial<TooltipContentItem>>({
|
||||
label: 'B',
|
||||
value: 20,
|
||||
tooltipValue: 'formatted-20',
|
||||
color: 'color-2',
|
||||
isActive: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('skips series with null data index or non-finite values', () => {
|
||||
@@ -273,5 +273,31 @@ describe('Tooltip utils', () => {
|
||||
expect(result[0].value).toBe(30);
|
||||
expect(result[1].value).toBe(30);
|
||||
});
|
||||
|
||||
it('returns items in series-index order', () => {
|
||||
// Series values in non-sorted order: 3, 1, 4, 2
|
||||
const data: AlignedData = [[0], [3], [1], [4], [2]];
|
||||
const series: Series[] = [
|
||||
{ label: 'x', show: true } as Series,
|
||||
{ label: 'C', show: true, stroke: '#aaaaaa' } as Series,
|
||||
{ label: 'A', show: true, stroke: '#bbbbbb' } as Series,
|
||||
{ label: 'D', show: true, stroke: '#cccccc' } as Series,
|
||||
{ label: 'B', show: true, stroke: '#dddddd' } as Series,
|
||||
];
|
||||
const dataIndexes = [null, 0, 0, 0, 0];
|
||||
const u = createUPlotInstance();
|
||||
|
||||
const result = buildTooltipContent({
|
||||
data,
|
||||
series,
|
||||
dataIndexes,
|
||||
activeSeriesIndex: null,
|
||||
uPlotInstance: u,
|
||||
yAxisUnit,
|
||||
decimalPrecision,
|
||||
});
|
||||
|
||||
expect(result.map((item) => item.value)).toEqual([3, 1, 4, 2]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
.uplot-tooltip-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 0;
|
||||
|
||||
.uplot-tooltip-item-marker {
|
||||
border-radius: 50%;
|
||||
border-style: solid;
|
||||
border-width: 2px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.uplot-tooltip-item-content {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
justify-content: space-between;
|
||||
|
||||
.uplot-tooltip-item-label {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
&-separator {
|
||||
flex: 1;
|
||||
border-width: 0.5px;
|
||||
border-style: dashed;
|
||||
min-width: 24px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { TooltipContentItem } from '../../../types';
|
||||
|
||||
import Styles from './TooltipItem.module.scss';
|
||||
|
||||
interface TooltipItemProps {
|
||||
item: TooltipContentItem;
|
||||
isItemActive: boolean;
|
||||
containerTestId?: string;
|
||||
markerTestId?: string;
|
||||
contentTestId?: string;
|
||||
}
|
||||
|
||||
export default function TooltipItem({
|
||||
item,
|
||||
isItemActive,
|
||||
containerTestId = 'uplot-tooltip-item',
|
||||
markerTestId = 'uplot-tooltip-item-marker',
|
||||
contentTestId = 'uplot-tooltip-item-content',
|
||||
}: TooltipItemProps): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
className={Styles.uplotTooltipItem}
|
||||
style={{
|
||||
opacity: isItemActive ? 1 : 0.7,
|
||||
fontWeight: isItemActive ? 700 : 400,
|
||||
}}
|
||||
data-testid={containerTestId}
|
||||
>
|
||||
<div
|
||||
className={Styles.uplotTooltipItemMarker}
|
||||
style={{ borderColor: item.color }}
|
||||
data-is-legend-marker={true}
|
||||
data-testid={markerTestId}
|
||||
/>
|
||||
<div
|
||||
className={Styles.uplotTooltipItemContent}
|
||||
style={{ color: item.color }}
|
||||
data-testid={contentTestId}
|
||||
>
|
||||
<span className={Styles.uplotTooltipItemLabel}>{item.label}</span>
|
||||
<span
|
||||
className={Styles.uplotTooltipItemContentSeparator}
|
||||
style={{ borderColor: item.color }}
|
||||
/>
|
||||
<span>{item.tooltipValue}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -38,16 +38,16 @@ export function getTooltipBaseValue({
|
||||
// When series are hidden, we must use the next *visible* series, not index+1,
|
||||
// since hidden series keep raw values and would produce negative/wrong results.
|
||||
if (isStackedBarChart && baseValue !== null && series) {
|
||||
let nextVisibleIdx = -1;
|
||||
for (let j = index + 1; j < series.length; j++) {
|
||||
if (series[j]?.show) {
|
||||
nextVisibleIdx = j;
|
||||
let nextVisibleSeriesIdx = -1;
|
||||
for (let seriesIdx = index + 1; seriesIdx < series.length; seriesIdx++) {
|
||||
if (series[seriesIdx]?.show) {
|
||||
nextVisibleSeriesIdx = seriesIdx;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (nextVisibleIdx >= 1) {
|
||||
const nextValue = data[nextVisibleIdx][dataIndex] ?? 0;
|
||||
baseValue = baseValue - nextValue;
|
||||
if (nextVisibleSeriesIdx >= 1) {
|
||||
const nextStackedValue = data[nextVisibleSeriesIdx][dataIndex] ?? 0;
|
||||
baseValue = baseValue - nextStackedValue;
|
||||
}
|
||||
}
|
||||
return baseValue;
|
||||
@@ -72,16 +72,15 @@ export function buildTooltipContent({
|
||||
decimalPrecision?: PrecisionOption;
|
||||
isStackedBarChart?: boolean;
|
||||
}): TooltipContentItem[] {
|
||||
const active: TooltipContentItem[] = [];
|
||||
const rest: TooltipContentItem[] = [];
|
||||
const items: TooltipContentItem[] = [];
|
||||
|
||||
for (let index = 1; index < series.length; index += 1) {
|
||||
const s = series[index];
|
||||
if (!s?.show) {
|
||||
for (let seriesIndex = 1; seriesIndex < series.length; seriesIndex += 1) {
|
||||
const seriesItem = series[seriesIndex];
|
||||
if (!seriesItem?.show) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const dataIndex = dataIndexes[index];
|
||||
const dataIndex = dataIndexes[seriesIndex];
|
||||
// Skip series with no data at the current cursor position
|
||||
if (dataIndex === null) {
|
||||
continue;
|
||||
@@ -89,30 +88,22 @@ export function buildTooltipContent({
|
||||
|
||||
const baseValue = getTooltipBaseValue({
|
||||
data,
|
||||
index,
|
||||
index: seriesIndex,
|
||||
dataIndex,
|
||||
isStackedBarChart,
|
||||
series,
|
||||
});
|
||||
|
||||
const isActive = index === activeSeriesIndex;
|
||||
|
||||
if (Number.isFinite(baseValue) && baseValue !== null) {
|
||||
const item: TooltipContentItem = {
|
||||
label: String(s.label ?? ''),
|
||||
items.push({
|
||||
label: String(seriesItem.label ?? ''),
|
||||
value: baseValue,
|
||||
tooltipValue: getToolTipValue(baseValue, yAxisUnit, decimalPrecision),
|
||||
color: resolveSeriesColor(s.stroke, uPlotInstance, index),
|
||||
isActive,
|
||||
};
|
||||
|
||||
if (isActive) {
|
||||
active.push(item);
|
||||
} else {
|
||||
rest.push(item);
|
||||
}
|
||||
color: resolveSeriesColor(seriesItem.stroke, uPlotInstance, seriesIndex),
|
||||
isActive: seriesIndex === activeSeriesIndex,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [...active, ...rest];
|
||||
return items;
|
||||
}
|
||||
|
||||
@@ -36,8 +36,8 @@ const HOVER_DISMISS_DELAY_MS = 100;
|
||||
export default function TooltipPlugin({
|
||||
config,
|
||||
render,
|
||||
maxWidth = 300,
|
||||
maxHeight = 400,
|
||||
maxWidth = 450,
|
||||
maxHeight = 600,
|
||||
syncMode = DashboardCursorSync.None,
|
||||
syncKey = '_tooltip_sync_global_',
|
||||
pinnedTooltipElement,
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
import { useQuery } from 'react-query';
|
||||
import getLocalStorageApi from 'api/browser/localstorage/get';
|
||||
import setLocalStorageApi from 'api/browser/localstorage/set';
|
||||
import { useGetMyOrganization } from 'api/generated/services/orgs';
|
||||
import { useGetMyUser } from 'api/generated/services/users';
|
||||
import listOrgPreferences from 'api/v1/org/preferences/list';
|
||||
import listUserPreferences from 'api/v1/user/preferences/list';
|
||||
@@ -85,14 +84,6 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
|
||||
query: { enabled: isLoggedIn },
|
||||
});
|
||||
|
||||
const {
|
||||
data: orgData,
|
||||
isFetching: isFetchingOrgData,
|
||||
error: orgFetchDataError,
|
||||
} = useGetMyOrganization({
|
||||
query: { enabled: isLoggedIn },
|
||||
});
|
||||
|
||||
const {
|
||||
permissions: permissionsResult,
|
||||
isFetching: isFetchingPermissions,
|
||||
@@ -102,10 +93,8 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
|
||||
enabled: isLoggedIn,
|
||||
});
|
||||
|
||||
const isFetchingUser =
|
||||
isFetchingUserData || isFetchingOrgData || isFetchingPermissions;
|
||||
const userFetchError =
|
||||
userFetchDataError || orgFetchDataError || errorOnPermissions;
|
||||
const isFetchingUser = isFetchingUserData || isFetchingPermissions;
|
||||
const userFetchError = userFetchDataError || errorOnPermissions;
|
||||
|
||||
const userRole = useMemo(() => {
|
||||
if (permissionsResult?.[IsAdminPermission]?.isGranted) {
|
||||
@@ -145,39 +134,40 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
|
||||
createdAt: toISOString(userData.data.createdAt) ?? prev.createdAt,
|
||||
updatedAt: toISOString(userData.data.updatedAt) ?? prev.updatedAt,
|
||||
}));
|
||||
}
|
||||
}, [userData, isFetchingUserData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isFetchingOrgData && orgData?.data) {
|
||||
const { id: orgId, displayName: orgDisplayName } = orgData.data;
|
||||
setOrg((prev) => {
|
||||
// todo: we need to update the org name as well, we should have the [admin only role restriction on the get org api call] - BE input needed
|
||||
setOrg((prev): any => {
|
||||
if (!prev) {
|
||||
return [{ createdAt: 0, id: orgId, displayName: orgDisplayName ?? '' }];
|
||||
return [
|
||||
{
|
||||
createdAt: 0,
|
||||
id: userData.data.orgId,
|
||||
},
|
||||
];
|
||||
}
|
||||
const orgIndex = prev.findIndex((e) => e.id === orgId);
|
||||
const orgIndex = prev.findIndex((e) => e.id === userData.data.orgId);
|
||||
|
||||
if (orgIndex === -1) {
|
||||
return [
|
||||
...prev,
|
||||
{ createdAt: 0, id: orgId, displayName: orgDisplayName ?? '' },
|
||||
{
|
||||
createdAt: 0,
|
||||
id: userData.data.orgId,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const updatedOrg: Organization[] = [
|
||||
return [
|
||||
...prev.slice(0, orgIndex),
|
||||
{ createdAt: 0, id: orgId, displayName: orgDisplayName ?? '' },
|
||||
{
|
||||
createdAt: 0,
|
||||
id: userData.data.orgId,
|
||||
},
|
||||
...prev.slice(orgIndex + 1),
|
||||
];
|
||||
return updatedOrg;
|
||||
});
|
||||
|
||||
setDefaultUser((prev) => ({
|
||||
...prev,
|
||||
organization: orgDisplayName ?? prev.organization,
|
||||
}));
|
||||
}
|
||||
}, [orgData, isFetchingOrgData]);
|
||||
}, [userData, isFetchingUserData]);
|
||||
|
||||
// fetcher for licenses v3
|
||||
const {
|
||||
|
||||
@@ -281,48 +281,6 @@ describe('AppProvider user and org data from v2 APIs', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('populates org state from GET /api/v2/orgs/me', async () => {
|
||||
server.use(
|
||||
rest.get(MY_ORG_URL, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
data: {
|
||||
id: 'org-abc',
|
||||
displayName: 'My Org',
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
rest.get(MY_USER_URL, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({ data: { id: 'u-default', email: 'default@signoz.io' } }),
|
||||
),
|
||||
),
|
||||
rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(authzMockResponse(payload, [false, false, false])),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const wrapper = createWrapper();
|
||||
const { result } = renderHook(() => useAppContext(), { wrapper });
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(result.current.org).not.toBeNull();
|
||||
const org = result.current.org?.[0];
|
||||
expect(org?.id).toBe('org-abc');
|
||||
expect(org?.displayName).toBe('My Org');
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
});
|
||||
|
||||
it('sets isFetchingUser false once both user and org calls complete', async () => {
|
||||
server.use(
|
||||
rest.get(MY_USER_URL, (_, res, ctx) =>
|
||||
|
||||
@@ -14,6 +14,7 @@ import APIError from 'types/api/error';
|
||||
interface ErrorModalContextType {
|
||||
showErrorModal: (error: APIError) => void;
|
||||
hideErrorModal: () => void;
|
||||
isErrorModalVisible: boolean;
|
||||
}
|
||||
|
||||
const ErrorModalContext = createContext<ErrorModalContextType | undefined>(
|
||||
@@ -38,10 +39,10 @@ export function ErrorModalProvider({
|
||||
setIsVisible(false);
|
||||
}, []);
|
||||
|
||||
const value = useMemo(() => ({ showErrorModal, hideErrorModal }), [
|
||||
showErrorModal,
|
||||
hideErrorModal,
|
||||
]);
|
||||
const value = useMemo(
|
||||
() => ({ showErrorModal, hideErrorModal, isErrorModalVisible: isVisible }),
|
||||
[showErrorModal, hideErrorModal, isVisible],
|
||||
);
|
||||
|
||||
return (
|
||||
<ErrorModalContext.Provider value={value}>
|
||||
|
||||
45
frontend/src/utils/errorUtils.test.ts
Normal file
45
frontend/src/utils/errorUtils.test.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { AxiosError } from 'axios';
|
||||
|
||||
import { retryOn429 } from './errorUtils';
|
||||
|
||||
describe('retryOn429', () => {
|
||||
const make429 = (): AxiosError =>
|
||||
Object.assign(new AxiosError('Too Many Requests'), {
|
||||
response: { status: 429 },
|
||||
}) as AxiosError;
|
||||
|
||||
it('returns true on first failure (failureCount=0) for 429', () => {
|
||||
expect(retryOn429(0, make429())).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true on second failure (failureCount=1) for 429', () => {
|
||||
expect(retryOn429(1, make429())).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false on third failure (failureCount=2) for 429 — max retries reached', () => {
|
||||
expect(retryOn429(2, make429())).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for non-429 axios errors', () => {
|
||||
const err = Object.assign(new AxiosError('Server Error'), {
|
||||
response: { status: 500 },
|
||||
}) as AxiosError;
|
||||
expect(retryOn429(0, err)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for 401 axios errors', () => {
|
||||
const err = Object.assign(new AxiosError('Unauthorized'), {
|
||||
response: { status: 401 },
|
||||
}) as AxiosError;
|
||||
expect(retryOn429(0, err)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for non-axios errors', () => {
|
||||
expect(retryOn429(0, new Error('network error'))).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for null/undefined errors', () => {
|
||||
expect(retryOn429(0, null)).toBe(false);
|
||||
expect(retryOn429(0, undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ErrorResponseHandlerForGeneratedAPIs } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { ErrorType } from 'api/generatedAPIInstance';
|
||||
import { AxiosError } from 'axios';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
/**
|
||||
@@ -66,3 +67,10 @@ export function handleApiError(
|
||||
showErrorFunction(apiError as APIError);
|
||||
}
|
||||
}
|
||||
|
||||
export const retryOn429 = (failureCount: number, error: unknown): boolean => {
|
||||
if (error instanceof AxiosError && error.response?.status === 429) {
|
||||
return failureCount < 2;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -97,6 +97,9 @@ export default defineConfig(
|
||||
javascriptEnabled: true,
|
||||
},
|
||||
},
|
||||
modules: {
|
||||
localsConvention: 'camelCaseOnly',
|
||||
},
|
||||
},
|
||||
define: {
|
||||
// TODO: Remove this in favor of import.meta.env
|
||||
|
||||
@@ -278,7 +278,8 @@ func (d *Dispatcher) processAlert(alert *types.Alert, route *dispatch.Route) {
|
||||
ruleId := getRuleIDFromAlert(alert)
|
||||
config, err := d.notificationManager.GetNotificationConfig(d.orgID, ruleId)
|
||||
if err != nil {
|
||||
d.logger.ErrorContext(d.ctx, "error getting alert notification config", slog.String("rule_id", ruleId), errors.Attr(err))
|
||||
//nolint:sloglint
|
||||
d.logger.ErrorContext(d.ctx, "error getting alert notification config", slog.String("rule.id", ruleId), errors.Attr(err))
|
||||
return
|
||||
}
|
||||
renotifyInterval := config.Renotify.RenotifyInterval
|
||||
@@ -328,7 +329,12 @@ func (d *Dispatcher) processAlert(alert *types.Alert, route *dispatch.Route) {
|
||||
go ag.run(func(ctx context.Context, alerts ...*types.Alert) bool {
|
||||
_, _, err := d.stage.Exec(ctx, d.logger, alerts...)
|
||||
if err != nil {
|
||||
logger := d.logger.With(slog.Int("num_alerts", len(alerts)), errors.Attr(err))
|
||||
receiverName, _ := notify.ReceiverName(ctx)
|
||||
logger := d.logger.With(
|
||||
slog.String("receiver", receiverName),
|
||||
slog.Int("num_alerts", len(alerts)),
|
||||
errors.Attr(err),
|
||||
)
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
// It is expected for the context to be canceled on
|
||||
// configuration reload or shutdown. In this case, the
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
package signozapiserver
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/http/handler"
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/types/inframonitoringtypes"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func (provider *provider) addInfraMonitoringRoutes(router *mux.Router) error {
|
||||
if err := router.Handle("/api/v2/infra-monitoring/hosts/list", handler.New(
|
||||
provider.authZ.ViewAccess(provider.infraMonitoringHandler.HostsList),
|
||||
handler.OpenAPIDef{
|
||||
ID: "HostsList",
|
||||
Tags: []string{"infra-monitoring"},
|
||||
Summary: "List Hosts for Infra Monitoring",
|
||||
Description: "This endpoint returns a list of hosts along with other information for each of them",
|
||||
Request: new(inframonitoringtypes.HostsListRequest),
|
||||
RequestContentType: "application/json",
|
||||
Response: new(inframonitoringtypes.HostsListResponse),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusInternalServerError},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/infra-monitoring/pods/list", handler.New(
|
||||
provider.authZ.ViewAccess(provider.infraMonitoringHandler.PodsList),
|
||||
handler.OpenAPIDef{
|
||||
ID: "PodsList",
|
||||
Tags: []string{"infra-monitoring"},
|
||||
Summary: "List Pods for Infra Monitoring",
|
||||
Description: "This endpoint returns a list of pods along with metrics and metadata for each of them",
|
||||
Request: new(inframonitoringtypes.PodsListRequest),
|
||||
RequestContentType: "application/json",
|
||||
Response: new(inframonitoringtypes.PodsListResponse),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusInternalServerError},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user