Compare commits

..

3 Commits

Author SHA1 Message Date
nityanandagohain
255b6fa1ac feat(trace-details): build the span tree and the overview of the trace inspect endpoint
GET /api/v1/traces/{traceID}/inspect now returns the overview. Like the
  waterfall, each call loads the trace's spans with one narrow query and builds
  the tree in memory, with each span's own time, level and the number of spans
  below it. There is no cache and no cap on the number of spans.

  From the tree it returns:
  - identity, with per-service totals and gen_ai usage
  - the spans where each error started, failures not marked as errors, the
    slowest spans by own time, the most expensive gen_ai spans, span links
  - the tree: the first 50 spans, level by level from the root, in time order;
    a trace of up to 50 spans also carries each span's record when they fit

  Every list pages with its nextCursor, and every item carries the span's
  direct parent. A page loads only what its list needs. Span attributes are
  read from the JSON column when it is filled, without the feature flag.

  spanId, search and allSpans answer 501 until the next PRs.

  Refs SigNoz/nerve-pod#651
2026-11-19 21:49:28 +05:30
nityanandagohain
75686f4004 fix(trace-details): update the trace inspect contract for the tree and the span cap 2026-11-19 21:18:30 +05:30
nityanandagohain
2df97d39e2 feat(trace-details): add the API contract for the trace inspect endpoint
Adds GET /api/v1/traces/{traceID}/inspect to the API spec with its query
  parameters and response types. The handler answers 501 for now; the
  implementation follows in separate PRs (overview, open a span, search).

  The response holds one of three parts, named by :
  - overview: identity, errors, failures not marked as errors, slowest spans,
    most expensive spans, span links and the tree
  - span: one span's summary and full record, with its ancestors and descendants
  - find: the spans matching a search, or every span with allSpans

  Every list has total, items and nextCursor, and every item starts with the
  span and its direct parent.

  Refs SigNoz/nerve-pod#651
2026-11-19 16:42:40 +05:30
1777 changed files with 26700 additions and 44275 deletions

View File

@@ -86,7 +86,7 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
zeus.Config{},
noopzeus.NewProviderFactory(),
licensing.Config{},
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics, _ cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return nooplicensing.NewFactory()
},
func(_ zeus.Zeus, _ licensing.Licensing) subscription.Subscription {

View File

@@ -103,8 +103,8 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
enterprisezeus.Config(),
httpzeus.NewProviderFactory(),
enterpriselicensing.Config(24*time.Hour, 3),
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics, cache)
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics)
},
func(zeus zeus.Zeus, licensing licensing.Licensing) subscription.Subscription {
return httpsubscription.New(zeus, licensing)

View File

@@ -261,8 +261,8 @@ alertmanager:
nflog:
# Interval between garbage collection and snapshotting of the notification logs. The snapshot will be stored in the state store.
maintenance_interval: 15m
# Retention of the notification logs. Must be at least twice the longest repeat interval, which is 8760h for rules with re-notify off.
retention: 17520h
# Retention of the notification logs.
retention: 120h
##################### Emailing #####################
emailing:

View File

@@ -4420,8 +4420,7 @@ components:
description: The dashboard title and description.
duration:
description: The default time range, as a Prometheus duration such as 1h
or 7d. The UI opens the dashboard on it, rounded up to whole minutes,
when neither the URL nor the viewer's last pick sets a time range.
or 7d. Stored, but not applied by the UI.
type: string
layouts:
description: The Grid layouts that place panels, at most 500. Each panel
@@ -12681,6 +12680,19 @@ components:
minimum: 0
type: integer
type: object
SpantypesEventV2:
properties:
attributes:
additionalProperties: {}
type: object
isError:
type: boolean
name:
type: string
timeUnixNano:
minimum: 0
type: integer
type: object
SpantypesFieldContext:
enum:
- attribute
@@ -12793,6 +12805,19 @@ components:
required:
- aggregations
type: object
SpantypesGettableTraceInspection:
properties:
find:
$ref: '#/components/schemas/SpantypesTraceSpanList'
overview:
$ref: '#/components/schemas/SpantypesTraceOverview'
span:
$ref: '#/components/schemas/SpantypesTraceSpanDetail'
type:
$ref: '#/components/schemas/SpantypesInspectType'
required:
- type
type: object
SpantypesGettableTraceSummary:
properties:
ai:
@@ -12873,6 +12898,19 @@ components:
nullable: true
type: array
type: object
SpantypesInspectType:
enum:
- overview
- span
- find
type: string
SpantypesLink:
properties:
spanId:
type: string
traceId:
type: string
type: object
SpantypesOtelSpanRef:
properties:
refType:
@@ -13164,6 +13202,100 @@ components:
nullable: true
type: object
type: object
SpantypesSpanRecord:
properties:
attributes:
additionalProperties: {}
type: object
events:
items:
$ref: '#/components/schemas/SpantypesEventV2'
type: array
links:
items:
$ref: '#/components/schemas/SpantypesLink'
type: array
resource:
additionalProperties:
type: string
type: object
spanId:
type: string
statusCode:
type: string
statusMessage:
type: string
truncated:
items:
$ref: '#/components/schemas/SpantypesTruncatedField'
type: array
required:
- spanId
- statusCode
- statusMessage
- attributes
- resource
- events
- links
- truncated
type: object
SpantypesSpanSummary:
properties:
childCount:
minimum: 0
type: integer
durationNano:
minimum: 0
type: integer
hasError:
type: boolean
kind:
type: string
level:
minimum: 0
type: integer
name:
type: string
ownTimeNano:
minimum: 0
type: integer
parentSpanId:
type: string
responseStatusCode:
type: string
serviceName:
type: string
spanId:
type: string
startOffsetNano:
minimum: 0
type: integer
subtreeSpanCount:
minimum: 0
type: integer
required:
- spanId
- name
- serviceName
- kind
- startOffsetNano
- durationNano
- ownTimeNano
- hasError
- level
- childCount
- subtreeSpanCount
type: object
SpantypesSpanTextMatch:
properties:
field:
type: string
snippet:
type: string
required:
- field
- snippet
type: object
SpantypesThreadSpan:
properties:
attributes:
@@ -13230,6 +13362,23 @@ components:
- formattedOutput
- formatterWarnings
type: object
SpantypesTraceAIIdentity:
properties:
modelCallCount:
minimum: 0
type: integer
tokens:
$ref: '#/components/schemas/SpantypesTraceAITokens'
toolCallCount:
minimum: 0
type: integer
totalCost:
type: number
required:
- modelCallCount
- toolCallCount
- tokens
type: object
SpantypesTraceAISummary:
properties:
tokens:
@@ -13263,6 +13412,379 @@ components:
- cacheWrite
- reasoning
type: object
SpantypesTraceErrorItem:
properties:
errorAncestorCount:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
statusMessage:
type: string
required:
- span
- statusMessage
- errorAncestorCount
type: object
SpantypesTraceErrorList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceErrorItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceExpensiveItem:
properties:
cost:
type: number
inputTokens:
minimum: 0
type: integer
outputTokens:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- inputTokens
- outputTokens
type: object
SpantypesTraceExpensiveList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceExpensiveItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceIdentity:
properties:
ai:
$ref: '#/components/schemas/SpantypesTraceAIIdentity'
durationNano:
minimum: 0
type: integer
errorSpanCount:
minimum: 0
type: integer
hasMissingSpans:
type: boolean
root:
$ref: '#/components/schemas/SpantypesSpanSummary'
rootCount:
minimum: 0
type: integer
serviceCount:
minimum: 0
type: integer
services:
items:
$ref: '#/components/schemas/SpantypesTraceServiceStats'
type: array
spanCount:
minimum: 0
type: integer
startTimestampMillis:
minimum: 0
type: integer
traceId:
type: string
required:
- traceId
- startTimestampMillis
- durationNano
- spanCount
- errorSpanCount
- rootCount
- hasMissingSpans
- serviceCount
- services
type: object
SpantypesTraceLinkItem:
properties:
linkCount:
minimum: 0
type: integer
links:
items:
$ref: '#/components/schemas/SpantypesLink'
type: array
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- linkCount
- links
type: object
SpantypesTraceLinkList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceLinkItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceOverview:
properties:
errors:
$ref: '#/components/schemas/SpantypesTraceErrorList'
expensive:
$ref: '#/components/schemas/SpantypesTraceExpensiveList'
identity:
$ref: '#/components/schemas/SpantypesTraceIdentity'
links:
$ref: '#/components/schemas/SpantypesTraceLinkList'
slowest:
$ref: '#/components/schemas/SpantypesTraceSlowestList'
tree:
$ref: '#/components/schemas/SpantypesTraceTree'
unmarkedFailures:
$ref: '#/components/schemas/SpantypesTraceUnmarkedFailureList'
type: object
SpantypesTraceServiceStats:
properties:
errorSpanCount:
minimum: 0
type: integer
ownTimeNano:
minimum: 0
type: integer
serviceName:
type: string
spanCount:
minimum: 0
type: integer
required:
- serviceName
- spanCount
- errorSpanCount
- ownTimeNano
type: object
SpantypesTraceSlowestItem:
properties:
errorSpanCount:
minimum: 0
type: integer
ownTimeNano:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
spanCount:
minimum: 0
type: integer
required:
- span
- spanCount
- ownTimeNano
- errorSpanCount
type: object
SpantypesTraceSlowestList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceSlowestItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceSpanDetail:
properties:
ancestorCount:
minimum: 0
type: integer
ancestors:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
descendants:
items:
$ref: '#/components/schemas/SpantypesTraceSpanLevel'
type: array
percentile:
$ref: '#/components/schemas/SpantypesTraceSpanPercentile'
record:
$ref: '#/components/schemas/SpantypesSpanRecord'
summary:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- summary
- record
- ancestors
- ancestorCount
- descendants
type: object
SpantypesTraceSpanLevel:
properties:
level:
minimum: 0
type: integer
spans:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
total:
minimum: 0
type: integer
required:
- level
- total
- spans
type: object
SpantypesTraceSpanList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceSpanMatch'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceSpanMatch:
properties:
matches:
items:
$ref: '#/components/schemas/SpantypesSpanTextMatch'
type: array
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- matches
type: object
SpantypesTraceSpanPercentile:
properties:
p50Nano:
minimum: 0
type: integer
p90Nano:
minimum: 0
type: integer
p99Nano:
minimum: 0
type: integer
position:
format: double
type: number
windowMinutes:
minimum: 0
type: integer
required:
- p50Nano
- p90Nano
- p99Nano
- position
- windowMinutes
type: object
SpantypesTraceTree:
properties:
complete:
type: boolean
records:
items:
$ref: '#/components/schemas/SpantypesSpanRecord'
type: array
spans:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
total:
minimum: 0
type: integer
required:
- total
- complete
- spans
type: object
SpantypesTraceUnmarkedFailureItem:
properties:
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
reason:
$ref: '#/components/schemas/SpantypesUnmarkedFailureReason'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- reason
type: object
SpantypesTraceUnmarkedFailureList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceUnmarkedFailureItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTruncatedField:
properties:
field:
type: string
length:
minimum: 0
type: integer
required:
- field
- length
type: object
SpantypesUnmarkedFailureReason:
enum:
- http_4xx
- grpc_status
- exception_event
type: string
SpantypesUpdatableSpanMapper:
properties:
config:
@@ -13655,7 +14177,6 @@ components:
type: string
TelemetrytypesSource:
enum:
- audit
- meter
- ""
type: string
@@ -19286,6 +19807,150 @@ paths:
tags:
- tracedetail
x-signoz-stability: alpha
/api/v1/traces/{traceID}/inspect:
get:
deprecated: false
description: 'Returns one of three parts of a trace of any size, named by type,
each within 50,000 characters. Without spanId or search it returns the overview:
the trace''s identity with per-service totals, the spans where each error
started, the failures not marked as errors (a 4xx response, a gRPC status
other than OK, an exception event), the slowest spans by own time with same-name
spans under one parent taken together, the most expensive gen_ai spans, and
the span tree. The tree holds the first 50 spans of the trace: level by level
from the root, and in time order on the level that does not fit. A trace of
up to 50 spans also returns each span''s full record when they fit in 20,000
characters. With spanId it returns that span''s summary and full record, its
ancestors, and the spans below it level by level, at most 20 per level; values
over 500 characters are cut and listed in truncated. With search it returns
the matching spans, each with where the words were found; allSpans returns
every span instead. Every list carries its total, and every list item the
span''s direct parent. Pass a nextCursor as cursor with the same parameters
to get the next page.'
operationId: InspectTrace
parameters:
- description: Returns this span in full with the spans around it. Cannot be
combined with search.
in: query
name: spanId
schema:
description: Returns this span in full with the spans around it. Cannot
be combined with search.
type: string
- description: 'Returns the spans that match, earliest first: words, a filter
expression, or both, such as worldpay AND has_error = true. Words match
the span name, status message, attribute values and events, ignoring case.'
in: query
name: search
schema:
description: 'Returns the spans that match, earliest first: words, a filter
expression, or both, such as worldpay AND has_error = true. Words match
the span name, status message, attribute values and events, ignoring case.'
type: string
- description: With spanId, the number of levels of ancestors and of descendants
returned, 1 to 10; 2 when not given. The root span is always returned.
in: query
name: depth
schema:
description: With spanId, the number of levels of ancestors and of descendants
returned, 1 to 10; 2 when not given. The root span is always returned.
type: integer
- description: 'Returns a different response: every span of the trace as a short
line, in tree order, or with spanId that span and every span below it. Cannot
be combined with search or depth.'
in: query
name: allSpans
schema:
description: 'Returns a different response: every span of the trace as a
short line, in tree order, or with spanId that span and every span below
it. Cannot be combined with search or depth.'
type: boolean
- description: With spanId, attribute names returned without the 500 character
cut; the record then holds only these attributes.
in: query
name: selectFields
schema:
description: With spanId, attribute names returned without the 500 character
cut; the record then holds only these attributes.
items:
type: string
type: array
- description: Page size for search and for allSpans, at most 1000; when not
given, 20 with search and 400 with allSpans. A page holds fewer spans when
it would pass the 50,000 character limit.
in: query
name: limit
schema:
description: Page size for search and for allSpans, at most 1000; when not
given, 20 with search and 400 with allSpans. A page holds fewer spans
when it would pass the 50,000 character limit.
type: integer
- description: The nextCursor of an earlier response to the same request; returns
the next page.
in: query
name: cursor
schema:
description: The nextCursor of an earlier response to the same request;
returns the next page.
type: string
- in: path
name: traceID
required: true
schema:
type: string
responses:
"200":
content:
application/json:
schema:
properties:
data:
$ref: '#/components/schemas/SpantypesGettableTraceInspection'
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
"404":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Not Found
"500":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Internal Server Error
security:
- api_key:
- VIEWER
- tokenizer:
- VIEWER
summary: Inspect a trace
tags:
- tracedetail
x-signoz-stability: alpha
/api/v1/traces/{traceID}/summary:
get:
deprecated: false

View File

@@ -1,26 +0,0 @@
package httplicensing
import (
"encoding/json"
"time"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
)
const (
activeLicenseCacheKey string = "active_license"
activeLicenseCacheTTL time.Duration = 5 * time.Minute
)
// A nil License means the organization has no active license.
type cachedActiveLicense struct {
License *licensetypes.License
}
func (typ cachedActiveLicense) MarshalBinary() ([]byte, error) {
return json.Marshal(typ)
}
func (typ *cachedActiveLicense) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, typ)
}

View File

@@ -7,7 +7,6 @@ import (
"github.com/SigNoz/signoz/ee/licensing/licensingstore/sqllicensingstore"
"github.com/SigNoz/signoz/pkg/analytics"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/licensing"
@@ -26,17 +25,16 @@ type provider struct {
settings factory.ScopedProviderSettings
orgGetter organization.Getter
analytics analytics.Analytics
cache cache.Cache
stopChan chan struct{}
}
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return factory.NewProviderFactory(factory.MustNewName("http"), func(ctx context.Context, providerSettings factory.ProviderSettings, config licensing.Config) (licensing.Licensing, error) {
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics, cache)
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics)
})
}
func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Config, sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) (licensing.Licensing, error) {
func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Config, sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) (licensing.Licensing, error) {
settings := factory.NewScopedProviderSettings(ps, "github.com/SigNoz/signoz/ee/licensing/httplicensing")
licensestore := sqllicensingstore.New(sqlstore)
return &provider{
@@ -47,7 +45,6 @@ func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Conf
orgGetter: orgGetter,
stopChan: make(chan struct{}),
analytics: analytics,
cache: cache,
}, nil
}
@@ -112,7 +109,6 @@ func (provider *provider) Activate(ctx context.Context, organizationID valuer.UU
return nil, err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return license, nil
}
@@ -154,38 +150,25 @@ func (provider *provider) Delete(ctx context.Context, organizationID valuer.UUID
return errors.WithAdditionalf(err, "license %s cannot be deleted", licenseID.StringValue())
}
if err := provider.store.Delete(ctx, organizationID, licenseID); err != nil {
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return nil
return provider.store.Delete(ctx, organizationID, licenseID)
}
// Caches both an active license and no active license, but never a store error.
func (provider *provider) GetActive(ctx context.Context, organizationID valuer.UUID) (*licensetypes.License, error) {
if cached, ok := provider.getActiveFromCache(ctx, organizationID); ok {
if cached.License == nil {
return nil, licensetypes.ErrActiveLicenseNotFound(organizationID)
}
return cached.License, nil
}
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
if err != nil && !errors.Ast(err, errors.TypeNotFound) {
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
if err != nil {
return nil, err
}
if cacheErr := provider.cache.Set(ctx, organizationID, activeLicenseCacheKey, &cachedActiveLicense{License: activeLicense}, activeLicenseCacheTTL); cacheErr != nil {
provider.settings.Logger().WarnContext(ctx, "failed to write active license to cache", errors.Attr(cacheErr), slog.String("org_id", organizationID.StringValue()))
activeLicense, err := licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, organizationID)
if err != nil {
return nil, err
}
return activeLicense, err
return activeLicense, nil
}
func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUID) error {
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
activeLicense, err := provider.GetActive(ctx, organizationID)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
return nil
@@ -204,7 +187,6 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return nil
}
return err
@@ -221,8 +203,6 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
stats := licensetypes.NewStatsFromLicense(activeLicense)
provider.analytics.Send(ctx,
analyticstypes.Track{
@@ -269,30 +249,3 @@ func (provider *provider) Collect(ctx context.Context, orgID valuer.UUID) (map[s
return licensetypes.NewStatsFromLicense(activeLicense), nil
}
func (provider *provider) getActiveFromCache(ctx context.Context, organizationID valuer.UUID) (*cachedActiveLicense, bool) {
cached := new(cachedActiveLicense)
err := provider.cache.Get(ctx, organizationID, activeLicenseCacheKey, cached)
if err != nil {
if !errors.Ast(err, errors.TypeNotFound) {
provider.settings.Logger().WarnContext(ctx, "failed to read active license from cache", errors.Attr(err), slog.String("org_id", organizationID.StringValue()))
}
return nil, false
}
if cached.License != nil && cached.License.IsExpired() {
return nil, false
}
return cached, true
}
func (provider *provider) getActiveFromStore(ctx context.Context, organizationID valuer.UUID) (*licensetypes.License, error) {
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
if err != nil {
return nil, err
}
return licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, organizationID)
}

View File

@@ -1,214 +0,0 @@
package httplicensing
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/analytics/analyticstest"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/cache/cachetest"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/licensing"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/sqlstore/sqlstoretest"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/SigNoz/signoz/pkg/zeus"
"github.com/SigNoz/signoz/pkg/zeus/noopzeus"
)
var (
testOrganizationID = valuer.MustNewUUID("0196f794-ff30-7bee-a5f4-ef5ad315715e")
testLicenseID = valuer.MustNewUUID("0196360e-90cd-7a74-8313-1aa815ce2a67")
licenseColumns = []string{"id", "created_at", "updated_at", "key", "data", "last_validated_at", "org_id"}
)
const (
selectLicensesQuery = `SELECT (.+) FROM "license"`
updateLicenseQuery = `UPDATE "license"`
deleteLicenseQuery = `DELETE FROM "license"`
)
func newTestLicensing(t *testing.T) (licensing.Licensing, sqlmock.Sqlmock, cache.Cache) {
t.Helper()
sqlStore := sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherRegexp)
licenseCache, err := cachetest.New(cache.Config{Provider: "memory", Memory: cache.Memory{NumCounters: 1000, MaxCost: 1 << 20}})
require.NoError(t, err)
providerSettings := instrumentationtest.New().ToProviderSettings()
noopZeus, err := noopzeus.New(context.Background(), providerSettings, zeus.Config{})
require.NoError(t, err)
licensing, err := New(context.Background(), providerSettings, licensing.Config{PollInterval: time.Hour, FailureThreshold: 3}, sqlStore, noopZeus, nil, analyticstest.New(), licenseCache)
require.NoError(t, err)
return licensing, sqlStore.Mock(), licenseCache
}
func newLicenseRows(lastValidatedAt time.Time) *sqlmock.Rows {
createdAt := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
data := `{"status":"VALID","state":"EVALUATING","platform":"SELF_HOSTED","plan":{"name":"ENTERPRISE"},"valid_from":1732146923,"valid_until":-1,"features":[],"event_queue":{}}`
return sqlmock.
NewRows(licenseColumns).
AddRow(testLicenseID.StringValue(), createdAt, createdAt, "test-license-key", data, lastValidatedAt, testOrganizationID.StringValue())
}
func TestGetActiveServesRepeatReadsFromCache(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
fromStore, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
fromCache, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, licensetypes.NewGettableLicenseWithKey(fromStore), licensetypes.NewGettableLicenseWithKey(fromCache))
assert.Equal(t, fromStore.OrganizationID, fromCache.OrganizationID)
assert.True(t, fromStore.LastValidatedAt.Equal(fromCache.LastValidatedAt))
fromStoreData, err := json.Marshal(fromStore.Data)
require.NoError(t, err)
fromCacheData, err := json.Marshal(fromCache.Data)
require.NoError(t, err)
assert.JSONEq(t, string(fromStoreData), string(fromCacheData))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveCachesNoActiveLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(sqlmock.NewRows(licenseColumns))
for range 2 {
license, err := licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
assert.Nil(t, license)
}
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveDoesNotCacheErrors(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
createdAt := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
licenseRowWithoutStatus := sqlmock.
NewRows(licenseColumns).
AddRow(testLicenseID.StringValue(), createdAt, createdAt, "test-license-key", `{"plan":{"name":"ENTERPRISE"}}`, createdAt, testOrganizationID.StringValue())
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(licenseRowWithoutStatus)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.ErrorContains(t, err, "license status is missing")
license, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, testLicenseID, license.ID)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveReloadsExpiredCachedLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, licenseCache := newTestLicensing(t)
expiredLicense := &licensetypes.License{
ID: valuer.GenerateUUID(),
ValidFrom: time.Now().Add(-2 * time.Hour).Unix(),
ValidUntil: time.Now().Add(-time.Hour).Unix(),
OrganizationID: testOrganizationID,
}
require.NoError(t, licenseCache.Set(ctx, testOrganizationID, activeLicenseCacheKey, &cachedActiveLicense{License: expiredLicense}, activeLicenseCacheTTL))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
license, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, testLicenseID, license.ID)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestDeleteClearsCachedActiveLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
mock.ExpectExec(deleteLicenseQuery).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(sqlmock.NewRows(licenseColumns))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, licensing.Delete(ctx, testOrganizationID, testLicenseID))
_, err = licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestRefreshClearsCachedActiveLicenseOnDowngrade(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
staleLastValidatedAt := time.Now().Add(-4 * time.Hour).UTC()
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectExec(updateLicenseQuery).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, licensing.Refresh(ctx, testOrganizationID))
_, err = licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestRefreshWritesActiveLicenseFromStoreNotCache(t *testing.T) {
ctx := context.Background()
licensing, mock, licenseCache := newTestLicensing(t)
staleLastValidatedAt := time.Now().Add(-4 * time.Hour).UTC()
staleCachedLicense := &licensetypes.License{
ID: testLicenseID,
Key: "stale-cached-license-key",
ValidFrom: 1732146923,
ValidUntil: -1,
LastValidatedAt: staleLastValidatedAt,
OrganizationID: testOrganizationID,
}
require.NoError(t, licenseCache.Set(ctx, testOrganizationID, activeLicenseCacheKey, &cachedActiveLicense{License: staleCachedLicense}, activeLicenseCacheTTL))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectExec(`UPDATE "license" .*'test-license-key'`).WillReturnResult(sqlmock.NewResult(0, 1))
require.NoError(t, licensing.Refresh(ctx, testOrganizationID))
require.NoError(t, mock.ExpectationsWereMet())
}

View File

@@ -8,5 +8,5 @@
.title {
color: var(--l1-foreground);
font-size: var(--label-large-400-font-size);
font-size: var(--font-size-lg);
}

View File

@@ -497,11 +497,7 @@
// Requires final else in if-else-if chains (was disabled)
"signoz/no-conditional-text-nodes-with-siblings": "warn",
// Vendored from eslint-plugin-react-google-translate
"signoz/no-return-text-nodes": "warn",
"signoz/no-text-css": "warn",
// Font and text CSS in style props, CSSProperties objects and styled-components; text style goes through Typography props
"signoz/require-disable-reason": "error"
// A disable of signoz/no-text-css must say why Typography cannot render the text
"signoz/no-return-text-nodes": "warn"
},
"ignorePatterns": [
"src/parser/*.ts",

View File

@@ -40,8 +40,8 @@ const mockAliases = [
},
{
// jest: not replaced, a test asserts on the toast it fires.
find: /^@signozhq\/ui\/toast$/,
replacement: `${srcPath}/storybook/mocks/toast.mock.tsx`,
find: /^@signozhq\/ui\/sonner$/,
replacement: `${srcPath}/storybook/mocks/sonner.mock.tsx`,
},
];

View File

@@ -1,6 +1,8 @@
<!--
Every Google Fonts request the app makes is answered with an empty
stylesheet; the local faces stand in for them.
`index.html` links Inter from Google Fonts here. The link is parsed before the
msw worker has started, so that one request escapes the iframe while every
other font request the app makes is answered with an empty stylesheet; the
local faces stand in for both.
-->
<link rel="stylesheet" href="storybook-fonts.css" />
@@ -74,3 +76,49 @@
Object.defineProperty(window, 'Date', { value: FrozenDate, writable: true });
})();
</script>
<script>
// Storybook has no microphone. Chromium's recognizer asks for one and for
// Google's speech service, and the `not-allowed` or `network` it reports makes
// the assistant hide its mic for the rest of the tab. This one starts
// listening at once and hears only what a story passes to `hear`.
(() => {
class StorySpeechRecognition extends EventTarget {
static listening = null;
lang = 'en-US';
continuous = false;
interimResults = false;
onstart = null;
onresult = null;
onerror = null;
onend = null;
start() {
StorySpeechRecognition.listening = this;
setTimeout(() => this.onstart?.());
}
stop() {
if (StorySpeechRecognition.listening === this) {
StorySpeechRecognition.listening = null;
}
setTimeout(() => this.onend?.());
}
abort() {
this.stop();
}
/** An interim result: the words so far, still listening. */
hear(transcript) {
const result = Object.assign([{ transcript, confidence: 1 }], {
isFinal: false,
});
this.onresult?.({ resultIndex: 0, results: [result] });
}
}
window.SpeechRecognition = StorySpeechRecognition;
window.webkitSpeechRecognition = StorySpeechRecognition;
})();
</script>

View File

@@ -147,7 +147,6 @@ const preview: Preview = {
'Explorer',
['Overview', 'Span Drawer'],
'Trace Details',
['Overview', 'Thread'],
'Funnel Details',
],
'Metrics',

View File

@@ -1,11 +1,22 @@
/*
* The three families the app pulls from Google Fonts, served from the files in
* The five families the app pulls from Google Fonts, served from the files in
* `public/fonts` instead. `msw/appShellHandlers.ts` answers the CDN with an
* empty stylesheet so no request leaves the iframe, which without this left
* every story on a fallback for the three families `src/styles.scss` imports at
* runtime. Inter and Geist Mono come from `src/styles.scss` itself.
* every story on a fallback for the four families `src/styles.scss` imports at
* runtime, and on whatever the Inter link in `index.html` happened to fetch
* before the worker had started.
*/
@font-face {
font-family: 'Inter';
/* The comma is part of the filename and the dev server serves it raw, so it
stays literal inside the quoted url rather than percent-encoded. */
src: url('fonts/Inter-VariableFont_opsz,wght.ttf') format('truetype');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Work Sans';
src: url('fonts/WorkSans-VariableFont_wght.ttf') format('truetype');
@@ -29,3 +40,11 @@
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Geist Mono';
src: url('fonts/GeistMonoVF.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}

View File

@@ -14,23 +14,9 @@ module.exports = {
path.join(__dirname, 'stylelint-rules/css-modules/class-name-pattern.js'),
],
customSyntax: 'postcss-scss',
// Disables of property-disallowed-list must say why after "--"
reportDescriptionlessDisables: [
false,
{ except: ['property-disallowed-list'], severity: 'error' },
],
rules: {
// Applies to all SCSS files
'local/no-unsupported-asset-url': true,
// Text style goes through @signozhq/ui/typography props
'property-disallowed-list': [
['/^font/', '/^text-/', 'line-height', 'letter-spacing'],
{
severity: 'warning',
message: (property) =>
`Do not set "${property}" in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after "--" saying why Typography cannot.`,
},
],
},
overrides: [
{

View File

@@ -191,30 +191,34 @@ You can read the ./node_modules/@signozhq/design-tokens/dist/style.css to find c
### Typography
Text styles are tokens named `--{variant}-{size}-{weight}-{property}`:
- Variant: `label` (line height 1), `paragraph` (line height 18, 20 or 26px), `uppercase` (11 and 13px) or `code` (SF Mono, 11 and 13px).
- Size: `small` (11px), `base` (13px), `medium` (16px) or `large` (18px). Paragraph has no `large`; uppercase and code have only `small` and `base`.
- Weight: `400`, `500` or `600`.
- Property: `font-family`, `font-size`, `font-weight`, `line-height`, `letter-spacing` or `text-transform`.
```scss
// Font sizes (preferred)
.title {
font-family: var(--label-large-500-font-family);
font-size: var(--label-large-500-font-size);
font-weight: var(--label-large-500-font-weight);
line-height: var(--label-large-500-line-height);
letter-spacing: var(--label-large-500-letter-spacing);
font-size: var(--periscope-font-size-large); // 18px
font-size: var(--periscope-font-size-medium); // 16px
font-size: var(--periscope-font-size-base); // 13px
font-size: var(--periscope-font-size-small); // 11px
}
.hint {
font-size: var(--paragraph-small-400-font-size); // 11px
line-height: var(--paragraph-small-400-line-height); // 18px
// Alternative scale (rem-based)
.heading {
font-size: var(--font-size-xl); // 1.25rem
font-size: var(--font-size-lg); // 1.125rem
font-size: var(--font-size-base); // 1rem
font-size: var(--font-size-sm); // 0.875rem
}
.id {
font-family: var(--code-base-400-font-family);
font-size: var(--code-base-400-font-size); // 13px
// Font weights
.bold {
font-weight: var(--font-weight-semibold); // 600
font-weight: var(--font-weight-medium); // 500
font-weight: var(--font-weight-normal); // 400
}
// Line heights
.text {
line-height: var(--line-height-20); // 20px
line-height: var(--line-height-24); // 24px
}
```
@@ -308,7 +312,7 @@ Each component exposes `--<component>-<property>` variables:
--button-background: var(--success-background);
--button-border-radius: var(--radius-2);
--button-padding: var(--spacing-4) var(--spacing-8);
--button-font-size: var(--label-base-400-font-size);
--button-font-size: var(--periscope-font-size-base);
}
// Override Input
@@ -338,7 +342,7 @@ Components use data attributes for variants/states. Target them for state-specif
// Target size
.wrapper :global([data-size="sm"]) {
--button-font-size: var(--label-small-400-font-size);
--button-font-size: var(--periscope-font-size-small);
}
// Target color

View File

@@ -14,6 +14,11 @@
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="preconnect" href="https://cdn.vercel.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap"
rel="stylesheet"
/>
<title data-react-helmet="true">
Open source Observability platform | SigNoz
</title>

View File

@@ -36,8 +36,6 @@ const config: Config.InitialOptions = {
'^test-mocks/(.*)$': '<rootDir>/__mocks__/$1',
'^react-syntax-highlighter/dist/esm/(.*)$':
'<rootDir>/node_modules/react-syntax-highlighter/dist/cjs/$1',
// `antd` resolves to lib/ here; es/ deep imports must share its module instances (contexts).
'^antd/es/(.*)$': '<rootDir>/node_modules/antd/lib/$1',
'^@signozhq/(?!ui(?:/|$))([^/]+)$':
'<rootDir>/node_modules/@signozhq/$1/dist/$1.js',
},

View File

@@ -54,9 +54,9 @@
"@monaco-editor/react": "^4.7.0",
"@sentry/react": "10.57.0",
"@sentry/vite-plugin": "5.3.0",
"@signozhq/design-tokens": "2.8.0",
"@signozhq/design-tokens": "2.2.1",
"@signozhq/icons": "0.4.0",
"@signozhq/ui": "0.4.0-rc.5",
"@signozhq/ui": "0.2.0",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",
"@uiw/codemirror-theme-copilot": "4.23.11",

View File

@@ -1,170 +0,0 @@
import { ruleTester } from './rule-tester.mjs';
const message = (property) =>
`Do not set '${property}' in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after \`--\` saying why Typography cannot.`;
await ruleTester({
rule: 'no-text-css',
valid: [
{
name: 'layout properties in a style prop',
code: 'export const A = () => <div style={{ width: 10, color: "red" }} />;',
},
{
name: 'font properties in an object that is not a style',
code: 'export const options = { fontSize: 12, font: "12px Inter" };',
},
{
name: 'font properties in a prop that is not a style',
code: 'export const A = () => <Chart options={{ fontSize: 12 }} />;',
},
{
name: 'computed key',
code:
'const k = "fontSize";\nexport const A = () => <div style={{ [k]: 12 }} />;',
},
{
name: 'style identifier from a parameter',
code: 'export const A = ({ s }) => <div style={s} />;',
},
{
name: 'template without a styled tag',
code: 'export const s = html`font-size: 12px;`;',
},
{
name: 'styled template with layout only',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\tdisplay: flex;\n\ttext: none;\n`;",
},
{
name: 'custom property that ends in a banned name',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\t--my-font-size: 12px;\n`;",
},
],
invalid: [
{
name: 'inline style',
code: 'export const A = () => <div style={{ fontSize: 12, width: 1 }} />;',
errors: [{ message: message('fontSize'), line: 1, column: 38 }],
},
{
name: 'string key',
code: "export const A = () => <div style={{ 'line-height': 1 }} />;",
errors: [{ message: message('line-height') }],
},
{
name: 'every banned family',
code:
'export const A = () => (\n\t<div\n\t\tstyle={{\n\t\t\tfont: "x",\n\t\t\tfontWeight: 500,\n\t\t\tfontFamily: "x",\n\t\t\ttextAlign: "center",\n\t\t\ttextTransform: "none",\n\t\t\tlineHeight: 1,\n\t\t\tletterSpacing: 1,\n\t\t}}\n\t/>\n);',
errors: [
{ message: message('font') },
{ message: message('fontWeight') },
{ message: message('fontFamily') },
{ message: message('textAlign') },
{ message: message('textTransform') },
{ message: message('lineHeight') },
{ message: message('letterSpacing') },
],
},
{
name: 'conditional, logical and spread',
code:
'export const A = ({ a, b }) => (\n\t<div style={{ ...(a ? { fontSize: 1 } : {}), ...(b && { lineHeight: 1 }) }} />\n);',
errors: [
{ message: message('fontSize') },
{ message: message('lineHeight') },
],
},
{
name: 'style prop with a Style suffix',
code:
'export const A = () => <Card headStyle={{ fontWeight: 600 }} bodyStyle={{ padding: 0 }} />;',
errors: [{ message: message('fontWeight') }],
},
{
name: 'antd semantic styles',
code:
'export const A = () => <Modal styles={{ body: { fontSize: 12 }, header: { padding: 0 } }} />;',
errors: [{ message: message('fontSize') }],
},
{
name: 'identifier resolved to a local object',
code:
'const s = { fontSize: 12 };\nexport const A = () => (\n\t<>\n\t\t<div style={s} />\n\t\t<span style={s} />\n\t</>\n);',
errors: [{ message: message('fontSize'), line: 1, column: 13 }],
},
{
name: 'useMemo style',
code:
"import { useMemo } from 'react';\nexport const A = () => {\n\tconst s = useMemo(() => ({ textAlign: 'left' }), []);\n\treturn <div style={s} />;\n};",
errors: [{ message: message('textAlign') }],
},
{
name: 'object typed CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const s: CSSProperties = { fontStyle: 'italic' };",
errors: [{ message: message('fontStyle') }],
},
{
name:
'object typed React.CSSProperties, reported once when also used as style',
code:
"import React from 'react';\nconst s: React.CSSProperties = { fontSize: 1 };\nexport const A = () => <div style={s} />;",
errors: [{ message: message('fontSize') }],
},
{
name: 'Record of CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const s: Record<string, CSSProperties> = { a: { lineHeight: 1 } };",
errors: [{ message: message('lineHeight') }],
},
{
name: 'as and satisfies CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const a = { fontSize: 1 } as CSSProperties;\nexport const b = { fontWeight: 1 } satisfies CSSProperties;",
errors: [
{ message: message('fontSize') },
{ message: message('fontWeight') },
],
},
{
name: 'styled-components template',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\tdisplay: flex;\n\tfont-size: 12px;\n\tcolor: ${(p) => p.c};\n\ttext-transform: none;line-height: 1;\n`;",
errors: [
{ message: message('font-size'), line: 4, column: 2 },
{ message: message('text-transform'), line: 6, column: 2 },
{ message: message('line-height'), line: 6, column: 23 },
],
},
{
name: 'function returning CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const a = (): CSSProperties => ({ fontSize: 1 });\nexport function b(): CSSProperties {\n\treturn { lineHeight: 1 };\n}",
errors: [
{ message: message('fontSize') },
{ message: message('lineHeight') },
],
},
{
name: 'strings in styled interpolations',
code:
"import styled, { css } from 'styled-components';\nexport const A = styled.div`\n\t${(p) => (p.s ? 'font-size: 11px;' : `line-height: 1;`)}\n\t${(p) => p.b && css`font-weight: 500;`}\n`;",
errors: [
{ message: message('font-size'), line: 3, column: 19 },
{ message: message('line-height'), line: 3, column: 40 },
{ message: message('font-weight'), line: 4, column: 22 },
],
},
{
name: 'styled(Component) and css helper',
code:
"import styled, { css } from 'styled-components';\nexport const A = styled(B)`letter-spacing: 1px;`;\nexport const c = css`\n\tfont-weight: 500;\n`;",
errors: [
{ message: message('letter-spacing'), line: 2, column: 28 },
{ message: message('font-weight'), line: 4, column: 2 },
],
},
],
});

View File

@@ -1,49 +0,0 @@
import { ruleTester } from './rule-tester.mjs';
const message = 'Disabling signoz/no-text-css needs a reason after `--`.';
await ruleTester({
rule: 'require-disable-reason',
valid: [
{
name: 'reason after --',
code:
'// oxlint-disable-next-line signoz/no-text-css -- canvas label\nexport const a = 1;',
},
{
name: 'block comment with a reason',
code:
'/* eslint-disable signoz/no-text-css -- email HTML */\nexport const a = 1;',
},
{
name: 'another rule without a reason',
code: '// oxlint-disable-next-line no-console\nexport const a = 1;',
},
{
name: 'disable of every rule',
code: '// eslint-disable-next-line\nexport const a = 1;',
},
{
name: 'plain comment naming the rule',
code: '// signoz/no-text-css flags font CSS\nexport const a = 1;',
},
],
invalid: [
{
name: 'next-line without a reason',
code: '// oxlint-disable-next-line signoz/no-text-css\nexport const a = 1;',
errors: [{ message, line: 1, column: 1 }],
},
{
name: 'empty reason',
code: '// eslint-disable-line signoz/no-text-css --\nexport const a = 1;',
errors: [{ message }],
},
{
name: 'among other rules',
code:
'/* oxlint-disable no-console, signoz/no-text-css */\nexport const a = 1;',
errors: [{ message }],
},
],
});

View File

@@ -1,324 +0,0 @@
/**
* Rule: no-text-css
*
* Text style (font, line height, letter spacing, case, alignment, overflow)
* belongs to Typography props, not to CSS written in a component.
*
* This rule catches font and text properties in:
* <div style={{ fontSize: 12 }} /> style and *Style props
* <Modal styles={{ body: { fontWeight: 500 } }} />
* const s: CSSProperties = { lineHeight: 1 } objects typed CSSProperties
* ({ ... }) as CSSProperties, satisfies CSSProperties
* (): CSSProperties => ({ ... }) functions returning CSSProperties
* styled.div`font-size: 12px;` styled-components templates,
* ${(p) => p.small && 'font-size: 11px;'} strings in their interpolations
*
* Identifiers passed to a style prop are followed to a local object literal.
* SCSS is covered by the stylelint config.
*/
const MESSAGE = (property) =>
`Do not set '${property}' in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after \`--\` saying why Typography cannot.`;
const BANNED_JS = /^(font([A-Z]\w*)?|text[A-Z]\w*|lineHeight|letterSpacing)$/;
const BANNED_CSS =
/(^|[\s;{])(font(-[a-z]+)*|text-[a-z-]+|line-height|letter-spacing)\s*:/g;
const STYLE_TAGS = new Set(['css', 'createGlobalStyle', 'keyframes']);
const FUNCTIONS = new Set([
'ArrowFunctionExpression',
'FunctionExpression',
'FunctionDeclaration',
]);
const camelCase = (name) =>
name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
function propertyName(property) {
if (property.computed) {
return null;
}
if (property.key.type === 'Identifier') {
return property.key.name;
}
if (
property.key.type === 'Literal' &&
typeof property.key.value === 'string'
) {
return property.key.value;
}
return null;
}
function isCssPropertiesType(typeNode) {
if (!typeNode || typeNode.type !== 'TSTypeReference') {
return false;
}
const name = typeNode.typeName;
if (name.type === 'Identifier') {
return name.name === 'CSSProperties';
}
return name.type === 'TSQualifiedName' && name.right.name === 'CSSProperties';
}
// Record<K, CSSProperties> and { [key: string]: CSSProperties }
function isCssPropertiesMapType(typeNode) {
if (!typeNode) {
return false;
}
if (
typeNode.type === 'TSTypeReference' &&
typeNode.typeName.type === 'Identifier' &&
typeNode.typeName.name === 'Record'
) {
const params = (typeNode.typeArguments ?? typeNode.typeParameters)?.params;
return isCssPropertiesType(params?.[1]);
}
if (typeNode.type === 'TSTypeLiteral') {
return typeNode.members.some(
(member) =>
member.type === 'TSIndexSignature' &&
isCssPropertiesType(member.typeAnnotation?.typeAnnotation),
);
}
return false;
}
function rootIdentifier(node) {
let current = node;
while (current) {
if (current.type === 'Identifier') {
return current.name;
}
if (current.type === 'MemberExpression') {
current = current.object;
} else if (current.type === 'CallExpression') {
current = current.callee;
} else {
return null;
}
}
return null;
}
function isStyleTag(tag) {
if (tag.type === 'Identifier') {
return tag.name === 'styled' || STYLE_TAGS.has(tag.name);
}
return rootIdentifier(tag) === 'styled';
}
export default {
create(context) {
const reported = new Set();
const followed = new Set();
const reportedCss = new Set();
function report(property, name) {
if (reported.has(property)) {
return;
}
reported.add(property);
context.report({ node: property.key, message: MESSAGE(name) });
}
function resolveIdentifier(identifier) {
const scope = context.sourceCode.getScope(identifier);
let current = scope;
while (current) {
const variable = current.set.get(identifier.name);
if (variable) {
const definition = variable.defs[0];
if (
definition?.node?.type === 'VariableDeclarator' &&
definition.node.init
) {
return definition.node.init;
}
return null;
}
current = current.upper;
}
return null;
}
function checkObject(object) {
for (const property of object.properties) {
if (property.type === 'SpreadElement') {
checkStyle(property.argument);
continue;
}
const name = propertyName(property);
if (name && BANNED_JS.test(camelCase(name))) {
report(property, name);
}
}
}
function checkStyle(expression) {
if (!expression) {
return;
}
switch (expression.type) {
case 'ObjectExpression':
checkObject(expression);
return;
case 'ConditionalExpression':
checkStyle(expression.consequent);
checkStyle(expression.alternate);
return;
case 'LogicalExpression':
checkStyle(expression.left);
checkStyle(expression.right);
return;
case 'TSAsExpression':
case 'TSSatisfiesExpression':
case 'TSNonNullExpression':
case 'ParenthesizedExpression':
checkStyle(expression.expression);
return;
case 'CallExpression':
// useMemo(() => ({ ... }), deps)
if (
expression.callee.type === 'Identifier' &&
expression.callee.name === 'useMemo'
) {
checkReturned(expression.arguments[0]);
}
return;
case 'Identifier': {
const init = resolveIdentifier(expression);
if (!init || followed.has(init)) {
return;
}
followed.add(init);
checkStyle(init);
return;
}
default:
}
}
function checkReturned(fn) {
if (!fn || !FUNCTIONS.has(fn.type)) {
return;
}
if (fn.body.type !== 'BlockStatement') {
checkStyle(fn.body);
return;
}
for (const statement of fn.body.body) {
if (statement.type === 'ReturnStatement') {
checkStyle(statement.argument);
}
}
}
function checkStyleMap(expression) {
if (expression?.type !== 'ObjectExpression') {
return;
}
for (const property of expression.properties) {
if (property.type === 'Property') {
checkStyle(property.value);
}
}
}
// `start` is the index of the first character after the opening quote.
function checkCss(text, start) {
for (const match of text.matchAll(BANNED_CSS)) {
const index = start + match.index + match[1].length;
if (reportedCss.has(index)) {
continue;
}
reportedCss.add(index);
context.report({
loc: {
start: context.sourceCode.getLocFromIndex(index),
end: context.sourceCode.getLocFromIndex(index + match[2].length),
},
message: MESSAGE(match[2]),
});
}
}
// CSS returned from interpolations: ${(p) => p.small && 'font-size: 11px;'}
function checkCssStrings(node) {
if (!node || typeof node.type !== 'string') {
return;
}
if (node.type === 'TemplateLiteral') {
for (const quasi of node.quasis) {
checkCss(quasi.value.raw, quasi.range[0] + 1);
}
} else if (node.type === 'Literal' && typeof node.value === 'string') {
checkCss(node.raw.slice(1, -1), node.range[0] + 1);
return;
}
for (const [key, value] of Object.entries(node)) {
if (key === 'parent') {
continue;
}
if (Array.isArray(value)) {
value.forEach(checkCssStrings);
} else if (value && typeof value === 'object') {
checkCssStrings(value);
}
}
}
function checkFunction(node) {
if (isCssPropertiesType(node.returnType?.typeAnnotation)) {
checkReturned(node);
}
}
return {
JSXAttribute(node) {
if (
node.name.type !== 'JSXIdentifier' ||
node.value?.type !== 'JSXExpressionContainer'
) {
return;
}
const name = node.name.name;
if (name === 'styles') {
checkStyleMap(node.value.expression);
} else if (name === 'style' || name.endsWith('Style')) {
checkStyle(node.value.expression);
}
},
VariableDeclarator(node) {
const type = node.id.typeAnnotation?.typeAnnotation;
if (isCssPropertiesType(type)) {
checkStyle(node.init);
} else if (isCssPropertiesMapType(type)) {
checkStyleMap(node.init);
}
},
TSAsExpression(node) {
if (isCssPropertiesType(node.typeAnnotation)) {
checkStyle(node.expression);
}
},
TSSatisfiesExpression(node) {
if (isCssPropertiesType(node.typeAnnotation)) {
checkStyle(node.expression);
} else if (isCssPropertiesMapType(node.typeAnnotation)) {
checkStyleMap(node.expression);
}
},
TaggedTemplateExpression(node) {
if (!isStyleTag(node.tag)) {
return;
}
checkCssStrings(node.quasi);
},
ArrowFunctionExpression: checkFunction,
FunctionExpression: checkFunction,
FunctionDeclaration: checkFunction,
};
},
};

View File

@@ -1,38 +0,0 @@
/**
* Rule: require-disable-reason
*
* A disable directive that names one of RULES must say why after `--`:
* // oxlint-disable-next-line signoz/no-text-css -- canvas text, not DOM
*
* Directives that disable every rule are not checked.
*/
const RULES = new Set(['signoz/no-text-css']);
const DIRECTIVE = /^\s*(?:eslint|oxlint)-disable(?:-next-line|-line)?\s+(.*)$/s;
export default {
create(context) {
return {
Program() {
for (const comment of context.sourceCode.getAllComments()) {
const match = comment.value.match(DIRECTIVE);
if (!match) {
continue;
}
const [rules, reason] = match[1].split(/\s--\s?/);
const named = rules
.split(',')
.map((rule) => rule.trim())
.filter((rule) => RULES.has(rule));
if (named.length > 0 && !reason?.trim()) {
context.report({
node: comment,
message: `Disabling ${named.join(', ')} needs a reason after \`--\`.`,
});
}
}
},
};
},
};

View File

@@ -17,8 +17,6 @@ import noConditionalTextNodesWithSiblings from './rules/no-conditional-text-node
import noReturnTextNodes from './rules/no-return-text-nodes.mjs';
import noMswInStoryFile from './rules/no-msw-in-story-file.mjs';
import noDirectReactRouterImport from './rules/no-direct-react-router-import.mjs';
import noTextCss from './rules/no-text-css.mjs';
import requireDisableReason from './rules/require-disable-reason.mjs';
export default {
meta: {
@@ -37,7 +35,5 @@ export default {
'no-return-text-nodes': noReturnTextNodes,
'no-msw-in-story-file': noMswInStoryFile,
'no-direct-react-router-import': noDirectReactRouterImport,
'no-text-css': noTextCss,
'require-disable-reason': requireDisableReason,
},
};

1187
frontend/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@@ -5284,7 +5284,6 @@ export interface TelemetrytypesTelemetryFieldKeyDTO {
}
export enum TelemetrytypesSourceDTO {
audit = 'audit',
meter = 'meter',
'' = '',
}
@@ -8043,7 +8042,7 @@ export interface DashboardtypesDashboardSpecDTO {
display: DashboardtypesDisplayDTO;
/**
* @type string
* @description The default time range, as a Prometheus duration such as 1h or 7d. The UI opens the dashboard on it, rounded up to whole minutes, when neither the URL nor the viewer's last pick sets a time range.
* @description The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI.
*/
duration?: string;
/**
@@ -13818,6 +13817,28 @@ export interface SpantypesEventDTO {
timeUnixNano?: number;
}
export type SpantypesEventV2DTOAttributes = { [key: string]: unknown };
export interface SpantypesEventV2DTO {
/**
* @type object
*/
attributes?: SpantypesEventV2DTOAttributes;
/**
* @type boolean
*/
isError?: boolean;
/**
* @type string
*/
name?: string;
/**
* @type integer
* @minimum 0
*/
timeUnixNano?: number;
}
export enum SpantypesFieldContextDTO {
attribute = 'attribute',
resource = 'resource',
@@ -14137,6 +14158,168 @@ export interface SpantypesGettableTraceAggregationsDTO {
aggregations: SpantypesSpanAggregationResultDTO[];
}
export interface SpantypesSpanTextMatchDTO {
/**
* @type string
*/
field: string;
/**
* @type string
*/
snippet: string;
}
export interface SpantypesSpanSummaryDTO {
/**
* @type integer
* @minimum 0
*/
childCount: number;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type boolean
*/
hasError: boolean;
/**
* @type string
*/
kind: string;
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type string
*/
name: string;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
parentSpanId?: string;
/**
* @type string
*/
responseStatusCode?: string;
/**
* @type string
*/
serviceName: string;
/**
* @type string
*/
spanId: string;
/**
* @type integer
* @minimum 0
*/
startOffsetNano: number;
/**
* @type integer
* @minimum 0
*/
subtreeSpanCount: number;
}
export interface SpantypesTraceSpanMatchDTO {
/**
* @type array
*/
matches: SpantypesSpanTextMatchDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceSpanListDTO {
/**
* @type array
*/
items: SpantypesTraceSpanMatchDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceErrorItemDTO {
/**
* @type integer
* @minimum 0
*/
errorAncestorCount: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type string
*/
statusMessage: string;
}
export interface SpantypesTraceErrorListDTO {
/**
* @type array
*/
items: SpantypesTraceErrorItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceExpensiveItemDTO {
/**
* @type number
*/
cost?: number;
/**
* @type integer
* @minimum 0
*/
inputTokens: number;
/**
* @type integer
* @minimum 0
*/
outputTokens: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceExpensiveListDTO {
/**
* @type array
*/
items: SpantypesTraceExpensiveItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceAITokensDTO {
/**
* @type integer
@@ -14165,6 +14348,354 @@ export interface SpantypesTraceAITokensDTO {
reasoning: number;
}
export interface SpantypesTraceAIIdentityDTO {
/**
* @type integer
* @minimum 0
*/
modelCallCount: number;
tokens: SpantypesTraceAITokensDTO;
/**
* @type integer
* @minimum 0
*/
toolCallCount: number;
/**
* @type number
*/
totalCost?: number;
}
export interface SpantypesTraceServiceStatsDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
serviceName: string;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceIdentityDTO {
ai?: SpantypesTraceAIIdentityDTO;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type boolean
*/
hasMissingSpans: boolean;
root?: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
rootCount: number;
/**
* @type integer
* @minimum 0
*/
serviceCount: number;
/**
* @type array
*/
services: SpantypesTraceServiceStatsDTO[];
/**
* @type integer
* @minimum 0
*/
spanCount: number;
/**
* @type integer
* @minimum 0
*/
startTimestampMillis: number;
/**
* @type string
*/
traceId: string;
}
export interface SpantypesLinkDTO {
/**
* @type string
*/
spanId?: string;
/**
* @type string
*/
traceId?: string;
}
export interface SpantypesTraceLinkItemDTO {
/**
* @type integer
* @minimum 0
*/
linkCount: number;
/**
* @type array
*/
links: SpantypesLinkDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceLinkListDTO {
/**
* @type array
*/
items: SpantypesTraceLinkItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSlowestItemDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceSlowestListDTO {
/**
* @type array
*/
items: SpantypesTraceSlowestItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTruncatedFieldDTO {
/**
* @type string
*/
field: string;
/**
* @type integer
* @minimum 0
*/
length: number;
}
export type SpantypesSpanRecordDTOAttributes = { [key: string]: unknown };
export type SpantypesSpanRecordDTOResource = { [key: string]: string };
export interface SpantypesSpanRecordDTO {
/**
* @type object
*/
attributes: SpantypesSpanRecordDTOAttributes;
/**
* @type array
*/
events: SpantypesEventV2DTO[];
/**
* @type array
*/
links: SpantypesLinkDTO[];
/**
* @type object
*/
resource: SpantypesSpanRecordDTOResource;
/**
* @type string
*/
spanId: string;
/**
* @type string
*/
statusCode: string;
/**
* @type string
*/
statusMessage: string;
/**
* @type array
*/
truncated: SpantypesTruncatedFieldDTO[];
}
export interface SpantypesTraceTreeDTO {
/**
* @type boolean
*/
complete: boolean;
/**
* @type array
*/
records?: SpantypesSpanRecordDTO[];
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export enum SpantypesUnmarkedFailureReasonDTO {
http_4xx = 'http_4xx',
grpc_status = 'grpc_status',
exception_event = 'exception_event',
}
export interface SpantypesTraceUnmarkedFailureItemDTO {
parent?: SpantypesSpanSummaryDTO;
reason: SpantypesUnmarkedFailureReasonDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceUnmarkedFailureListDTO {
/**
* @type array
*/
items: SpantypesTraceUnmarkedFailureItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceOverviewDTO {
errors?: SpantypesTraceErrorListDTO;
expensive?: SpantypesTraceExpensiveListDTO;
identity?: SpantypesTraceIdentityDTO;
links?: SpantypesTraceLinkListDTO;
slowest?: SpantypesTraceSlowestListDTO;
tree?: SpantypesTraceTreeDTO;
unmarkedFailures?: SpantypesTraceUnmarkedFailureListDTO;
}
export interface SpantypesTraceSpanLevelDTO {
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSpanPercentileDTO {
/**
* @type integer
* @minimum 0
*/
p50Nano: number;
/**
* @type integer
* @minimum 0
*/
p90Nano: number;
/**
* @type integer
* @minimum 0
*/
p99Nano: number;
/**
* @type number
* @format double
*/
position: number;
/**
* @type integer
* @minimum 0
*/
windowMinutes: number;
}
export interface SpantypesTraceSpanDetailDTO {
/**
* @type integer
* @minimum 0
*/
ancestorCount: number;
/**
* @type array
*/
ancestors: SpantypesSpanSummaryDTO[];
/**
* @type array
*/
descendants: SpantypesTraceSpanLevelDTO[];
percentile?: SpantypesTraceSpanPercentileDTO;
record: SpantypesSpanRecordDTO;
summary: SpantypesSpanSummaryDTO;
}
export enum SpantypesInspectTypeDTO {
overview = 'overview',
span = 'span',
find = 'find',
}
export interface SpantypesGettableTraceInspectionDTO {
find?: SpantypesTraceSpanListDTO;
overview?: SpantypesTraceOverviewDTO;
span?: SpantypesTraceSpanDetailDTO;
type: SpantypesInspectTypeDTO;
}
export interface SpantypesTraceAISummaryDTO {
tokens: SpantypesTraceAITokensDTO;
/**
@@ -16036,6 +16567,55 @@ export type GetTraceAggregations200 = {
status: string;
};
export type InspectTracePathParameters = {
traceID: string;
};
export type InspectTraceParams = {
/**
* @type string
* @description Returns this span in full with the spans around it. Cannot be combined with search.
*/
spanId?: string;
/**
* @type string
* @description Returns the spans that match, earliest first: words, a filter expression, or both, such as worldpay AND has_error = true. Words match the span name, status message, attribute values and events, ignoring case.
*/
search?: string;
/**
* @type integer
* @description With spanId, the number of levels of ancestors and of descendants returned, 1 to 10; 2 when not given. The root span is always returned.
*/
depth?: number;
/**
* @type boolean
* @description Returns a different response: every span of the trace as a short line, in tree order, or with spanId that span and every span below it. Cannot be combined with search or depth.
*/
allSpans?: boolean;
/**
* @type array
* @description With spanId, attribute names returned without the 500 character cut; the record then holds only these attributes.
*/
selectFields?: string[];
/**
* @type integer
* @description Page size for search and for allSpans, at most 1000; when not given, 20 with search and 400 with allSpans. A page holds fewer spans when it would pass the 50,000 character limit.
*/
limit?: number;
/**
* @type string
* @description The nextCursor of an earlier response to the same request; returns the next page.
*/
cursor?: string;
};
export type InspectTrace200 = {
data: SpantypesGettableTraceInspectionDTO;
/**
* @type string
*/
status: string;
};
export type GetTraceSummaryPathParameters = {
traceID: string;
};

View File

@@ -29,6 +29,9 @@ import type {
GetTraceThreadPathParameters,
GetWaterfallV4200,
GetWaterfallV4PathParameters,
InspectTrace200,
InspectTraceParams,
InspectTracePathParameters,
RenderErrorResponseDTO,
SpantypesPostableFlamegraphDTO,
SpantypesPostableTraceAggregationsDTO,
@@ -158,6 +161,117 @@ export const useGetTraceAggregations = <
> => {
return useMutation(getGetTraceAggregationsMutationOptions(options));
};
/**
* Returns one of three parts of a trace of any size, named by type, each within 50,000 characters. Without spanId or search it returns the overview: the trace's identity with per-service totals, the spans where each error started, the failures not marked as errors (a 4xx response, a gRPC status other than OK, an exception event), the slowest spans by own time with same-name spans under one parent taken together, the most expensive gen_ai spans, and the span tree. The tree holds the first 50 spans of the trace: level by level from the root, and in time order on the level that does not fit. A trace of up to 50 spans also returns each span's full record when they fit in 20,000 characters. With spanId it returns that span's summary and full record, its ancestors, and the spans below it level by level, at most 20 per level; values over 500 characters are cut and listed in truncated. With search it returns the matching spans, each with where the words were found; allSpans returns every span instead. Every list carries its total, and every list item the span's direct parent. Pass a nextCursor as cursor with the same parameters to get the next page.
* @summary Inspect a trace
*/
export const inspectTrace = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTrace200>({
url: `/api/v1/traces/${traceID}/inspect`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceQueryKey = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getInspectTraceQueryKey({ traceID }, params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof inspectTrace>>> = ({
signal,
}) => inspectTrace({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTrace>>
>;
export type InspectTraceQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Inspect a trace
*/
export function useInspectTrace<
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceQueryOptions({ traceID }, params, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Inspect a trace
*/
export const invalidateInspectTrace = async (
queryClient: QueryClient,
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.
* @summary Get summary for a trace

View File

@@ -0,0 +1,61 @@
import { ApiV3Instance as axios } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import createQueryParams from 'lib/createQueryParams';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
TagKeyProps,
TagKeysPayloadProps,
TagValueProps,
TagValuesPayloadProps,
} from 'types/api/metrics/getResourceAttributes';
import { DataSource, MetricAggregateOperator } from 'types/common/queryBuilder';
export const getResourceAttributesTagKeys = async (
props: TagKeyProps,
): Promise<SuccessResponse<TagKeysPayloadProps> | ErrorResponse> => {
try {
const response = await axios.get(
`/autocomplete/attribute_keys?${createQueryParams({
aggregateOperator: MetricAggregateOperator.RATE,
searchText: props.match,
dataSource: DataSource.METRICS,
aggregateAttribute: props.metricName,
})}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};
export const getResourceAttributesTagValues = async (
props: TagValueProps,
): Promise<SuccessResponse<TagValuesPayloadProps> | ErrorResponse> => {
try {
const response = await axios.get(
`/autocomplete/attribute_values?${createQueryParams({
aggregateOperator: MetricAggregateOperator.RATE,
dataSource: DataSource.METRICS,
aggregateAttribute: props.metricName,
attributeKey: props.tagKey,
searchText: '',
})}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};

View File

@@ -302,10 +302,6 @@ export function createAggregation(
reduceTo: haveReduceTo
? queryData?.aggregations?.[0]?.reduceTo || queryData?.reduceTo
: undefined,
...(queryData?.aggregations?.[0]?.comparisonSpaceAggregationParam && {
comparisonSpaceAggregationParam:
queryData.aggregations[0].comparisonSpaceAggregationParam,
}),
},
];
}

View File

@@ -1,6 +1,5 @@
import { useMutation } from 'react-query';
import { Button } from '@signozhq/ui/button';
import { Dialog } from '@signozhq/ui/dialog';
import { Button, Modal } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import { createSubscription } from 'api/generated/services/subscriptions';
import type { CreateSubscription201 } from 'api/generated/services/sigNoz.schemas';
@@ -56,51 +55,46 @@ function AddCreditCardModal({
};
return (
<Dialog
<Modal
className="add-credit-card-modal"
title={<span className="title">Add Credit Card for Chat Support</span>}
open={open}
onClose={onClose}
title="Add Credit Card for Chat Support"
testId="add-credit-card-modal"
footerSuffix={
<>
closable
onCancel={onClose}
destroyOnClose
footer={[
<Button
key="cancel"
onClick={onClose}
className="cancel-btn"
icon={<X size={16} />}
>
Cancel
</Button>,
<AuthZTooltip
key="submit"
checks={[SubscriptionCreatePermission]}
withPortal={false}
>
<Button
variant="outlined"
color="secondary"
size="md"
prefix={<X size={16} />}
onClick={onClose}
testId="add-credit-card-cancel"
type="primary"
icon={<CreditCard size={16} />}
size="middle"
loading={isLoadingBilling}
disabled={isLoadingBilling}
onClick={handleAddCreditCard}
className="add-credit-card-btn"
>
Cancel
Add Credit Card
</Button>
<AuthZTooltip checks={[SubscriptionCreatePermission]}>
<Button
variant="solid"
color="primary"
size="md"
prefix={<CreditCard size={16} />}
loading={isLoadingBilling}
onClick={handleAddCreditCard}
testId="add-credit-card-submit"
>
Add Credit Card
</Button>
</AuthZTooltip>
</>
}
</AuthZTooltip>,
]}
>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text className="add-credit-card-text">
You&apos;re currently on <span className="highlight-text">Trial plan</span>.
Add a credit card to access SigNoz chat support to your workspace.
</Typography>
</Dialog>
</Typography.Text>
</Modal>
);
}

View File

@@ -1,9 +1,6 @@
.breadcrumb {
padding: var(--spacing-4) 16px var(--spacing-2);
// The antd breadcrumb provides the item spacing.
--button-padding: 0;
ol {
align-items: center;
}
@@ -11,4 +8,13 @@
:global(.ant-breadcrumb-separator) {
color: var(--muted-foreground);
}
[data-slot='button'] {
padding: 0px;
}
}
.divider {
--divider-color: var(--l1-border);
--divider-margin: 10px 0 16px 0;
}

View File

@@ -28,7 +28,7 @@ function AlertBreadcrumb({
items={breadcrumbItems}
data-testid={testId}
/>
{showDivider && <Divider spacing="10px 16px" />}
{showDivider && <Divider className={styles.divider} />}
</>
);
}

View File

@@ -1,4 +1,5 @@
.itemLast {
color: var(--button-secondary-label);
font-size: var(--button-font-size, var(--periscope-font-size-base));
line-height: var(--button-size-line-height, 16px);
}

View File

@@ -1,6 +1,6 @@
import { Copy } from '@signozhq/icons';
import { Badge, type BadgeColorType } from '@signozhq/ui/badge';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { Tooltip } from '@signozhq/ui/tooltip';
import cx from 'classnames';
import { useLayoutEffect, useRef, useState } from 'react';

View File

@@ -1,6 +1,6 @@
import { Copy } from '@signozhq/icons';
import { Badge, type BadgeColorType } from '@signozhq/ui/badge';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { Tooltip } from '@signozhq/ui/tooltip';
import { useCopyToClipboard } from 'react-use';

View File

@@ -26,6 +26,8 @@
}
.brand-title {
font-size: 20px;
font-weight: 600;
color: var(--l1-foreground); // Primary text
margin: 0;
}

View File

@@ -28,29 +28,15 @@ function AppLoading(): JSX.Element {
<div className="brand">
<img src={signozBrandLogoUrl} alt="SigNoz" className="brand-logo" />
<Typography
variant="label"
size="large"
weight="bold"
color="main"
as="h2"
textOverflow="wrap"
>
<Typography.Title level={2} className="brand-title">
SigNoz
</Typography>
</Typography.Title>
</div>
<div className="brand-tagline">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text>
OpenTelemetry-Native Logs, Metrics and Traces in a single pane
</Typography>
</Typography.Text>
</div>
<div className="loader" />

View File

@@ -1,9 +0,0 @@
import { Toaster } from '@signozhq/ui/toast';
const PAGE_INSET = { bottom: 'var(--bottom-strip-height, 0px)' };
function AppToaster(): JSX.Element {
return <Toaster position="bottom-right" pageInset={PAGE_INSET} />;
}
export default AppToaster;

View File

@@ -35,6 +35,7 @@
&__error-code {
color: var(--bg-cherry-100);
font-size: 13px;
font-weight: 500;
line-height: 1;
letter-spacing: -0.065px;
}
@@ -42,6 +43,8 @@
&__error-message {
color: var(--bg-cherry-300);
font-size: 13px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.065px;
}
@@ -72,6 +75,7 @@
&__message-item {
color: var(--bg-cherry-300);
font-size: 13px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.065px;

View File

@@ -45,8 +45,9 @@
}
.auth-footer-text {
font-family: var(--label-small-400-font-family);
font-family: var(--font-family-inter, Inter, sans-serif);
font-size: 11px;
font-weight: 400;
line-height: 1;
color: var(--l2-foreground);
text-align: center;
@@ -56,6 +57,7 @@
display: flex;
align-items: center;
gap: 6px;
text-decoration: none;
transition: opacity 0.2s ease;
&:hover {

View File

@@ -16,6 +16,7 @@
display: flex;
align-items: center;
gap: 4.9px;
text-decoration: none;
}
.auth-header-logo-icon {
@@ -25,7 +26,7 @@
}
.auth-header-logo-text {
font-family: Satoshi, var(--label-medium-500-font-family), sans-serif;
font-family: Satoshi, var(--font-family-inter, Inter), sans-serif;
font-size: 15.4px;
font-weight: 500;
line-height: 17.5px;

View File

@@ -17,3 +17,8 @@
letter-spacing: -0.01em;
color: var(--l1-foreground);
}
.divider {
--divider-color: var(--l1-border);
--divider-margin: 10px 0 16px 0;
}

View File

@@ -44,7 +44,7 @@ function BackHeader({
</Button>
<div className={styles.title}>{title}</div>
</div>
<Divider spacing="10px 16px" />
<Divider className={styles.divider} />
</>
);
}

View File

@@ -1,7 +1,6 @@
import React, { Dispatch, SetStateAction, useState } from 'react';
import { Check, Plus, X } from '@signozhq/icons';
import { Button } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button, Flex } from 'antd';
import { Pill } from '@signozhq/ui/pill';
import Input from 'components/Input';

View File

@@ -1,7 +1,6 @@
import { useCallback, useMemo, useState } from 'react';
import { Select, Spin } from 'antd';
import { Row, Select, Spin } from 'antd';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import Row from 'periscope/components/Row/Row';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import {

View File

@@ -23,6 +23,7 @@
.ant-table {
.ant-table-thead > tr > th {
padding: 12px;
font-weight: 500;
font-size: 12px;
line-height: 18px;
@@ -30,7 +31,10 @@
border-bottom: none;
color: var(--l2-foreground);
font-family: Inter;
font-size: 11px;
font-style: normal;
font-weight: 600;
line-height: 18px; /* 163.636% */
letter-spacing: 0.44px;
@@ -41,6 +45,7 @@
.ant-table-cell {
padding: 12px;
font-size: 13px;
line-height: 20px;
color: var(--l1-foreground);
background: var(--l1-background);
@@ -62,6 +67,12 @@
.ant-table-cell:nth-child(n + 3) {
padding-right: 24px;
}
.column-header-right {
text-align: right;
}
.column-header-left {
text-align: left;
}
.ant-table-tbody > tr > td {
border-bottom: none;
}

View File

@@ -6,15 +6,15 @@ import { Loader, Search } from '@signozhq/icons';
import { Color } from '@signozhq/design-tokens';
import {
Button,
Flex,
Input,
InputRef,
Space,
Spin,
TableColumnsType,
TableColumnType,
Tooltip,
} from 'antd';
import Space from 'periscope/components/Space/Space';
import Flex from 'periscope/components/Flex/Flex';
import { Progress } from '@signozhq/ui/progress';
import { Typography } from '@signozhq/ui/typography';
import type { FilterDropdownProps } from 'antd/lib/table/interface';
@@ -40,27 +40,10 @@ const INITIAL_PAGE_SIZE = 20;
const showPaginationItem = (total: number, range: number[]): JSX.Element => (
<>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text className="numbers">
{range[0]} &#8212; {range[1]}
</Typography>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
{' '}
of {total}
</Typography>
</Typography.Text>
<Typography.Text className="total"> of {total}</Typography.Text>
</>
);
@@ -73,15 +56,22 @@ function ProgressRender(item: string | number): JSX.Element {
const percent = Number(Number(item).toFixed(1));
return (
<div className="progress-container">
<div className="progress-bar">
<Progress
percent={percent}
showInfo
color={
percent >= 90 ? 'highlight-danger' : percent >= 60 ? 'warning' : 'success'
<Progress
percent={percent}
strokeLinecap="butt"
showInfo
strokeColor={((): string => {
const cpuPercent = percent;
if (cpuPercent >= 90) {
return Color.BG_SAKURA_500;
}
/>
</div>
if (cpuPercent >= 60) {
return Color.BG_AMBER_500;
}
return Color.BG_FOREST_500;
})()}
className="progress-bar"
/>
</div>
);
}
@@ -536,18 +526,7 @@ export default function CeleryOverviewTable({
),
}}
locale={{
emptyText: isLoading ? null : (
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
No data
</Typography>
),
emptyText: isLoading ? null : <Typography.Text>No data</Typography.Text>,
}}
scroll={{ x: 'max-content' }}
showSorterTooltip

View File

@@ -24,16 +24,9 @@ function CeleryTaskConfigOptions(): JSX.Element {
return (
<div className="celery-task-filters">
<div className="celery-filters">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="visible"
>
<Typography.Text style={{ whiteSpace: 'nowrap' }}>
Task Name
</Typography>
</Typography.Text>
<Select
data-testid="celery-task-name-select"
placeholder="Task Name"

View File

@@ -49,7 +49,11 @@
.subtitle {
color: var(--l2-foreground);
font-family: Inter;
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
}
}
@@ -60,6 +64,11 @@
.footer-text {
color: var(--l2-foreground);
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
}
}

View File

@@ -65,38 +65,15 @@ export default function CeleryTaskDetail({
width="45%"
title={
<div>
<Typography
variant="label"
size="large"
weight="bold"
color="main"
as="span"
textOverflow="wrap"
>{`Details - ${taskData.entity}`}</Typography>
<Typography.Text className="title">{`Details - ${taskData.entity}`}</Typography.Text>
<div>
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text className="subtitle">
{`${formatTimestamp(startTime)} ${
endTime ? `- ${formatTimestamp(endTime)}` : ''
}`}
</Typography>
<Divider orientation="vertical" />
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
{taskData.value}
</Typography>
</Typography.Text>
<Divider type="vertical" />
<Typography.Text className="subtitle">{taskData.value}</Typography.Text>
</div>
</div>
}
@@ -111,14 +88,7 @@ export default function CeleryTaskDetail({
destroyOnClose
closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
footer={
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>{`Total Task: ${totalTask}`}</Typography>
<Typography.Text className="footer-text">{`Total Task: ${totalTask}`}</Typography.Text>
}
>
<CeleryTaskGraph

View File

@@ -48,11 +48,15 @@
}
.worker-count-text-container {
--typography-font-size: 2.5vw;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.celery-task-graph-worker-count-text {
font-size: 2.5vw;
text-align: center;
}
}
.worker-count-header {
@@ -144,12 +148,14 @@
.configure-option-Info-text {
color: var(--l2-foreground);
font-size: 12px;
font-weight: 400;
}
}
.row-panel {
border-radius: 4px;
background: color-mix(in srgb, var(--surface-2) 40%, transparent);
background: color-mix(in srgb, var(--card) 40%, transparent);
padding: 8px;
display: flex;
gap: 6px;
@@ -211,6 +217,7 @@
}
&__label {
font-family: 'Inter';
font-size: 14px;
color: var(--l2-foreground);
line-height: 20px;
@@ -218,7 +225,7 @@
}
&__value {
font-family: var(--code-base-400-font-family);
font-family: 'Geist Mono';
font-size: 24px;
color: var(--l1-foreground);
line-height: 32px;

View File

@@ -104,16 +104,9 @@ export default function CeleryTaskGraphGrid({
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<div className="row-panel">
<div className="row-panel-section">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text className="section-title">
Flower Metrics
</Typography>
</Typography.Text>
{collapsedSections.metricBasedGraphs ? (
<ChevronDown
size={14}
@@ -144,31 +137,17 @@ export default function CeleryTaskGraphGrid({
/>
<Card className="celery-task-graph-worker-count">
<div className="worker-count-header">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text className="worker-count-header-text">
Worker Online
</Typography>
</Typography.Text>
</div>
<div className="worker-count-text-container">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
display="inline-block"
align="center"
textOverflow="wrap"
testId="celery-worker-count"
<Typography.Text
className="celery-task-graph-worker-count-text"
data-testid="celery-worker-count"
>
{workerCount ?? '-'}
</Typography>
</Typography.Text>
</div>
</Card>
</div>
@@ -179,16 +158,9 @@ export default function CeleryTaskGraphGrid({
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<div className="row-panel">
<div className="row-panel-section">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text className="section-title">
Span Based Stats
</Typography>
</Typography.Text>
{collapsedSections.traceBasedGraphs ? (
<ChevronDown
size={14}
@@ -207,16 +179,9 @@ export default function CeleryTaskGraphGrid({
</CardContainer>
<div className="configure-option-Info">
{configureOptionComponent}
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text className="configure-option-Info-text">
Click on a graph co-ordinate to see more details
</Typography>
</Typography.Text>
</div>
</div>
{!collapsedSections.traceBasedGraphs && (

View File

@@ -1,8 +1,7 @@
import { useCallback, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { Col, Row } from 'antd';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';

View File

@@ -1,6 +1,5 @@
import { Dispatch, SetStateAction, useMemo } from 'react';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { Col, Row } from 'antd';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import useUrlQuery from 'hooks/useUrlQuery';

View File

@@ -11,7 +11,9 @@
justify-content: center;
}
&__label {
font-family: var(--code-base-400-font-family);
font-family: 'Geist Mono';
font-size: 12px;
line-height: normal;
}
&--positive {
.change-percentage-pill {

View File

@@ -1,8 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useMutation } from 'react-query';
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
import { Button, Modal } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button, Flex, Modal } from 'antd';
import updateUserPreference from 'api/v1/user/preferences/name/update';
import cx from 'classnames';
import { USER_PREFERENCES } from 'constants/userPreferences';
@@ -98,10 +97,6 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
}
};
// TODO: antd stacks at 1000, under `@signozhq/ui` dialogs (1001). It opens on
// its own a second after load, so a dialog opened from a deep link
// (`?add-key`, `?invite=true`) covers it. Moving to the `@signozhq/ui` Dialog
// fixes it.
return (
<Modal
className={cx('changelog-modal')}

View File

@@ -1,29 +0,0 @@
import type { ComponentProps } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { fn } from 'storybook/test';
import type { GlobalMockArgs } from '@/storybook/globals';
import ChangelogModal from '../ChangelogModal';
import { changelog } from './__story_mockdata__/changelog';
type ChangelogModalArgs = ComponentProps<typeof ChangelogModal> &
GlobalMockArgs;
const meta = {
title: 'Components/Changelog Modal',
component: ChangelogModal,
args: { changelog, onClose: fn() },
} satisfies Meta<ChangelogModalArgs>;
export default meta;
type Story = StoryObj<ChangelogModalArgs>;
/** A cloud workspace: no upgrade actions, since cloud updates itself. */
export const Default: Story = {};
/** A self-hosted workspace, offered Skip for now and Update my workspace. */
export const SelfHosted: Story = {
args: { license: 'enterprise' },
};

View File

@@ -1,65 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
const PUBLISHED_AT = '2026-08-12T09:00:00.000Z';
const feature = (
id: number,
title: string,
description: string,
): ChangelogSchema['features'][number] => ({
id,
documentId: `feature-${id}`,
title,
sort_order: id,
createdAt: PUBLISHED_AT,
updatedAt: PUBLISHED_AT,
publishedAt: PUBLISHED_AT,
description,
deployment_type: DeploymentType.ALL,
// Media stays null so no story reaches out to the CMS for an image.
media: null,
});
export const changelog: ChangelogSchema = {
id: 1,
documentId: 'changelog-v0-99-0',
version: 'v0.99.0',
release_date: '2026-08-12',
createdAt: PUBLISHED_AT,
updatedAt: PUBLISHED_AT,
publishedAt: PUBLISHED_AT,
features: [
feature(
1,
'Metrics explorer',
'Browse every metric you send, inspect its labels and turn it into a panel without writing a query.\n\n- Search metrics by name, type or unit\n- See cardinality per label before you group by it\n- Open any metric straight in the query builder\n\nRead more in the [metrics explorer docs](https://signoz.io/docs/metrics-management/metrics-explorer/).',
),
feature(
2,
'Trace funnels',
'Measure conversion and drop-off across a multi-service request path. Define each step as a span filter, then compare the latency and error rate between any two steps.',
),
feature(
3,
'Saved views for logs',
'Save a logs query with its columns and time range, share it with your team and pin the ones you open most.',
),
feature(
4,
'Alert history',
'Every alert now keeps a timeline of its state changes, with the value that crossed the threshold and the labels it fired for.',
),
],
bug_fixes:
'- Fixed dashboard variables losing their selection on refresh.\n- Fixed alert history pagination skipping a page.\n- Fixed the logs list jumping to the top after a live tail update.',
maintenance:
'- Upgraded the query service to Go 1.24.\n- Reduced the ClickHouse memory used by trace aggregation queries.',
};

View File

@@ -17,6 +17,10 @@
color: var(--l2-foreground);
/* Bifrost (Ancient)/Content/sm */
font-family: Inter;
font-size: 13px;
font-style: normal;
font-weight: 400;
line-height: 20px; /* 142.857% */
letter-spacing: -0.07px;

View File

@@ -17,13 +17,13 @@
pre {
color: var(--l2-foreground) !important;
font-family: var(--code-small-400-font-family) !important;
font-family: 'Geist Mono' !important;
font-size: 12px !important;
}
code {
color: var(--l1-foreground) !important;
font-family: var(--code-small-400-font-family) !important;
font-family: 'Geist Mono' !important;
font-size: 12px !important;
}
}

View File

@@ -1,3 +1,36 @@
.create-sa-modal {
max-width: 530px;
background: var(--popover);
border: 1px solid var(--secondary);
border-radius: 4px;
box-shadow: 0 4px 9px 0 rgba(0, 0, 0, 0.04);
[data-slot='dialog-header'] {
padding: var(--padding-4);
border-bottom: 1px solid var(--secondary);
flex-shrink: 0;
background: transparent;
margin: 0;
}
[data-slot='dialog-title'] {
font-size: var(--label-base-400-font-size);
font-weight: var(--label-base-400-font-weight);
line-height: var(--label-base-400-line-height);
letter-spacing: -0.065px;
color: var(--l1-foreground);
margin: 0;
}
[data-slot='dialog-description'] {
padding: 0;
.create-sa-modal__content {
padding: var(--padding-4);
}
}
}
.create-sa-form {
display: flex;
flex-direction: column;
@@ -10,11 +43,32 @@
margin-bottom: var(--spacing-4);
> label {
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
color: var(--foreground);
letter-spacing: -0.07px;
}
}
&__input {
height: 32px;
color: var(--l1-foreground);
background-color: var(--l2-background);
border-color: var(--l1-border);
font-size: var(--paragraph-base-400-font-size);
border-radius: 2px;
width: 100%;
&::placeholder {
color: var(--l3-foreground);
}
&:focus {
border-color: var(--primary);
box-shadow: none;
}
}
&__error {
font-size: var(--paragraph-small-400-font-size);
color: var(--destructive);
@@ -23,7 +77,22 @@
}
&__helper {
font-size: var(--paragraph-small-400-font-size);
color: var(--l3-foreground);
margin: calc(var(--spacing-2) * -1) 0 var(--spacing-4) 0;
line-height: var(--paragraph-small-400-line-height);
}
}
.create-sa-modal__footer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
padding: 0 var(--padding-4);
height: 56px;
min-height: 56px;
border-top: 1px solid var(--secondary);
gap: var(--spacing-4);
flex-shrink: 0;
}

View File

@@ -5,9 +5,9 @@ import { Button } from '@signozhq/ui/button';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import { SACreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/service-account.permissions';
import { Dialog } from '@signozhq/ui/dialog';
import { DialogFooter, DialogWrapper } from '@signozhq/ui/dialog';
import { Input } from '@signozhq/ui/input';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import {
invalidateListServiceAccounts,
@@ -35,7 +35,7 @@ function CreateServiceAccountModal(): JSX.Element {
);
const [, setSelectedAccountId] = useQueryState(SA_QUERY_PARAMS.ACCOUNT);
const { showErrorModal } = useErrorModal();
const { showErrorModal, isErrorModalVisible } = useErrorModal();
const {
control,
@@ -82,75 +82,84 @@ function CreateServiceAccountModal(): JSX.Element {
}
return (
<Dialog
<DialogWrapper
title="New Service Account"
open={isOpen}
onClose={handleClose}
width="base"
onOpenChange={(open): void => {
if (!open) {
handleClose();
}
}}
showCloseButton
width="narrow"
className="create-sa-modal"
disableOutsideClick={isErrorModalVisible}
testId="create-service-account-modal"
footerSuffix={
<>
<Button
size="md"
type="button"
variant="solid"
color="secondary"
onClick={handleClose}
testId="create-sa-cancel-btn"
prefix={<X size={12} />}
>
Cancel
</Button>
<AuthZButton
size="md"
checks={[SACreatePermission]}
type="submit"
form="create-sa-form"
variant="solid"
color="primary"
loading={isSubmitting}
disabled={!isValid}
testId="create-sa-submit-btn"
>
Create Service Account
</AuthZButton>
</>
}
>
<AuthZGuardContent
checks={[SACreatePermission]}
fallbackOnLoading={<Skeleton active paragraph={{ rows: 1 }} />}
>
<form
id="create-sa-form"
className="create-sa-form"
onSubmit={handleSubmit(handleCreate)}
<div className="create-sa-modal__content">
<AuthZGuardContent
checks={[SACreatePermission]}
fallbackOnLoading={<Skeleton active paragraph={{ rows: 1 }} />}
>
<div className="create-sa-form__item">
<label htmlFor="sa-name">Name</label>
<Controller
name="name"
control={control}
rules={{ required: 'Name is required' }}
render={({ field }): JSX.Element => (
<Input
id="sa-name"
placeholder="Enter a name"
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
testId="create-sa-name-input"
/>
<form
id="create-sa-form"
className="create-sa-form"
onSubmit={handleSubmit(handleCreate)}
>
<div className="create-sa-form__item">
<label htmlFor="sa-name">Name</label>
<Controller
name="name"
control={control}
rules={{ required: 'Name is required' }}
render={({ field }): JSX.Element => (
<Input
id="sa-name"
placeholder="Enter a name"
className="create-sa-form__input"
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
data-testid="create-sa-name-input"
/>
)}
/>
{errors.name && (
<p className="create-sa-form__error">{errors.name.message}</p>
)}
/>
{errors.name && (
<p className="create-sa-form__error">{errors.name.message}</p>
)}
</div>
</form>
</AuthZGuardContent>
</Dialog>
</div>
</form>
</AuthZGuardContent>
</div>
<DialogFooter className="create-sa-modal__footer">
<Button
size="md"
type="button"
variant="solid"
color="secondary"
onClick={handleClose}
testId="create-sa-cancel-btn"
prefix={<X size={12} />}
>
Cancel
</Button>
<AuthZButton
size="md"
checks={[SACreatePermission]}
type="submit"
form="create-sa-form"
variant="solid"
color="primary"
loading={isSubmitting}
disabled={!isValid}
testId="create-sa-submit-btn"
>
Create Service Account
</AuthZButton>
</DialogFooter>
</DialogWrapper>
);
}

View File

@@ -1,4 +1,4 @@
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import {
setupAuthzAdmin,
setupAuthzDenyAll,
@@ -10,9 +10,9 @@ import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import CreateServiceAccountModal from '../CreateServiceAccountModal';
jest.mock('@signozhq/ui/toast', () => ({
...jest.requireActual('@signozhq/ui/toast'),
toast: { success: jest.fn(), danger: jest.fn() },
jest.mock('@signozhq/ui/sonner', () => ({
...jest.requireActual('@signozhq/ui/sonner'),
toast: { success: jest.fn(), error: jest.fn() },
}));
const mockToast = jest.mocked(toast);
@@ -23,6 +23,7 @@ jest.mock('providers/ErrorModalProvider', () => ({
...jest.requireActual('providers/ErrorModalProvider'),
useErrorModal: jest.fn(() => ({
showErrorModal,
isErrorModalVisible: false,
})),
}));
@@ -57,7 +58,7 @@ describe('CreateServiceAccountModal', () => {
// The form only renders once the create check resolves, and the name field
// registers its `required` rule on mount, so the empty-form invalid state
// settles a tick later.
await screen.findByTestId('create-sa-name-input-field');
await screen.findByTestId('create-sa-name-input');
await waitFor(() =>
expect(screen.getByTestId('create-sa-submit-btn')).toHaveAttribute(
@@ -71,7 +72,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const nameInput = await screen.findByTestId('create-sa-name-input');
const submitBtn = await screen.findByTestId('create-sa-submit-btn');
await user.type(nameInput, 'test');
@@ -89,7 +90,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const nameInput = await screen.findByTestId('create-sa-name-input');
await user.type(nameInput, 'Deploy Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -127,7 +128,7 @@ describe('CreateServiceAccountModal', () => {
renderModal();
const nameInput = await screen.findByTestId<HTMLInputElement>(
'create-sa-name-input-field',
'create-sa-name-input',
);
await user.type(nameInput, 'Deploy Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -159,7 +160,7 @@ describe('CreateServiceAccountModal', () => {
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const nameInput = await screen.findByTestId('create-sa-name-input');
await user.type(nameInput, 'Dupe Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -208,9 +209,7 @@ describe('CreateServiceAccountModal', () => {
screen.findByText(/is not authorized to perform/i),
).resolves.toBeInTheDocument();
expect(
screen.queryByTestId('create-sa-name-input-field'),
).not.toBeInTheDocument();
expect(screen.queryByTestId('create-sa-name-input')).not.toBeInTheDocument();
expect(
screen.getByTestId('create-service-account-modal'),
).toBeInTheDocument();
@@ -245,7 +244,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const nameInput = await screen.findByTestId('create-sa-name-input');
await user.type(nameInput, 'Bot');
await user.clear(nameInput);

View File

@@ -65,6 +65,8 @@
.valid-format-error {
margin-top: 4px;
color: var(--bg-cherry-400) !important;
font-size: 13px !important;
font-weight: 400 !important;
}
.info-text {
@@ -74,6 +76,11 @@
padding: 4px;
cursor: default;
color: var(--l2-foreground) !important;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: normal;
letter-spacing: 0.14px;
}
.info-text:hover {
@@ -97,11 +104,15 @@
gap: 6px;
.timezone__name {
font-size: 12px;
line-height: 16px;
color: var(--bg-robin-400);
font-weight: 500;
}
.timezone__separator {
font-size: 12px;
line-height: 16px;
color: var(--bg-robin-300);
font-weight: 500;
}
@@ -217,6 +228,10 @@
border-radius: 2px;
background: color-mix(in srgb, var(--bg-robin-200) 4%, transparent);
color: var(--l1-foreground);
font-size: 12px;
font-weight: 400;
line-height: 16px;
letter-spacing: -0.06px;
cursor: pointer;
height: 20px;
width: 20px;

View File

@@ -531,7 +531,7 @@ function CustomTimePicker({
// Use setTimeout to wait for React to update the DOM and make input editable
setTimeout(() => {
const inputElement = inputRef.current?.input;
if (inputElement && !document.activeElement?.closest('.timezone-picker')) {
if (inputElement) {
inputElement.focus();
inputElement.select();
}

View File

@@ -21,6 +21,7 @@ $item-spacing: 8px;
.timezone-picker {
width: 532px;
color: var(--l2-foreground);
font-family: $font-family;
&__search {
@include flex-center;
@@ -33,8 +34,34 @@ $item-spacing: 8px;
@include flex-center;
gap: 6px;
width: -webkit-fill-available;
}
--input-hover-border-color: transparent;
&__input {
@include text-style-base;
width: 100%;
background: transparent;
border: none;
border-radius: 0;
box-shadow: none;
outline: none;
height: auto;
color: var(--l1-foreground);
font-size: 14px;
line-height: 20px;
letter-spacing: -0.07px;
padding: 0;
&:focus,
&:focus-visible,
&:hover {
border: none;
box-shadow: none;
outline: none;
}
&::placeholder {
color: var(--l2-foreground);
}
}
&__esc-key {

View File

@@ -65,8 +65,7 @@ function SearchBar({
/>
<Input
type="text"
variant="unstyled"
noFocusRing
className="timezone-picker__input"
placeholder="Search timezones..."
value={value}
onChange={(e): void => onChange(e.target.value)}

View File

@@ -12,4 +12,5 @@
.name {
color: var(--danger-background);
font-weight: var(--font-weight-medium);
}

View File

@@ -1,4 +1,7 @@
.details-header {
// ghost + secondary missing hover bg token in @signozhq/button
--button-ghost-hover-background: var(--l3-background);
box-sizing: border-box;
display: flex;
align-items: center;
@@ -9,6 +12,7 @@
background: var(--l2-background);
&__title {
font-size: 13px;
font-weight: 500;
color: var(--l1-foreground);
flex: 1;

View File

@@ -0,0 +1,17 @@
.drawer {
overflow: hidden;
border-color: var(--l2-border);
background: var(--l2-background);
box-shadow: -4px 10px 16px 2px var(--l1-shadow);
&:focus,
&:focus-visible {
outline: none;
}
}
.body {
display: flex;
flex-direction: column;
height: 100%;
}

View File

@@ -1,46 +1,56 @@
import { ReactNode } from 'react';
import { Drawer } from '@signozhq/ui/drawer';
import { Drawer, DrawerContent } from '@signozhq/ui/drawer';
import cx from 'classnames';
import { AnimatePresence } from 'motion/react';
import styles from './DetailsPanelDrawer.module.scss';
interface DetailsPanelDrawerProps {
isOpen: boolean;
onClose: () => void;
title: string;
children: ReactNode;
headerSuffix?: ReactNode;
loading?: boolean;
children: React.ReactNode;
className?: string;
testId?: string;
}
function DetailsPanelDrawer({
isOpen,
onClose,
title,
children,
headerSuffix,
loading,
className,
testId,
}: DetailsPanelDrawerProps): JSX.Element {
return (
<Drawer
type="inspector"
stack="overlay"
open={isOpen}
onClose={onClose}
title={title}
width="extra-wide"
closePosition="start"
headerSuffix={headerSuffix}
loading={loading}
testId={testId}
onOpenChange={(open): void => {
if (!open) {
onClose();
}
}}
modal={false}
>
{children}
<AnimatePresence>
{isOpen && (
<DrawerContent
forceMount
direction="right"
width="extra-wide"
showOverlay={false}
// Outside presses are left to the page, which knows what counts as inside.
onInteractOutside={(e): void => e.preventDefault()}
className={cx(styles.drawer, className)}
testId={testId}
>
<div className={styles.body}>{children}</div>
</DrawerContent>
)}
</AnimatePresence>
</Drawer>
);
}
DetailsPanelDrawer.defaultProps = {
headerSuffix: undefined,
loading: false,
className: undefined,
testId: undefined,
};

View File

@@ -1,28 +0,0 @@
.dotGrid {
position: relative;
}
.canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
// Read by the snake as its colour on the light page.
color: var(--l1-foreground);
}
// The Snake score line, faint in the grid's bottom-left corner.
.label {
position: absolute;
left: var(--spacing-6);
bottom: var(--spacing-1);
font-family: var(--code-small-400-font-family);
font-size: var(--paragraph-small-400-font-size);
letter-spacing: 0.34em;
text-transform: uppercase;
white-space: nowrap;
color: var(--l3-foreground);
pointer-events: none;
user-select: none;
}

View File

@@ -1,35 +0,0 @@
import { useRef } from 'react';
import cx from 'classnames';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useDotGrid } from './useDotGrid';
import styles from './DotGrid.module.scss';
interface DotGridProps {
/** Sizes and places the grid; it fills whatever box it gets. */
className?: string;
/** Called when a Snake game starts or ends. */
onGameChange?: (isPlaying: boolean) => void;
}
/** Aurora dot grid that drifts on its own and lights up under the cursor. */
export default function DotGrid({
className,
onGameChange,
}: DotGridProps): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null);
const isDarkMode = useIsDarkMode();
const label = useDotGrid(canvasRef, isDarkMode, onGameChange);
return (
<div
className={cx(styles.dotGrid, className)}
data-testid="ai-dot-grid"
aria-hidden
>
<canvas ref={canvasRef} className={styles.canvas} />
{label && <span className={styles.label}>{label}</span>}
</div>
);
}

View File

@@ -1,103 +0,0 @@
import { useRef } from 'react';
import { act, render, screen, userEvent } from 'tests/test-utils';
import DotGrid from '../DotGrid';
import { useDotGrid } from '../useDotGrid';
const KONAMI =
'{ArrowUp}{ArrowUp}{ArrowDown}{ArrowDown}{ArrowLeft}{ArrowRight}{ArrowLeft}{ArrowRight}ba';
function Chat({
onGameChange,
}: {
onGameChange: (isPlaying: boolean) => void;
}): JSX.Element {
return (
<div>
<DotGrid onGameChange={onGameChange} />
<textarea data-testid="chat-textarea" />
</div>
);
}
function ThemedGrid({ isDarkMode }: { isDarkMode: boolean }): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null);
const label = useDotGrid(canvasRef, isDarkMode);
return (
<>
<canvas ref={canvasRef} />
<span data-testid="score-line">{label}</span>
</>
);
}
describe('DotGrid Snake', () => {
beforeEach(() => {
jest.useFakeTimers();
// jsdom has no canvas or layout: a 9 × 7 game grid is enough for a snake.
jest
.spyOn(HTMLCanvasElement.prototype, 'getContext')
.mockReturnValue(
new Proxy({}, { get: () => jest.fn() }) as CanvasRenderingContext2D,
);
jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(120);
jest.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(120);
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
it('quits the game on Esc and hands the keyboard back', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onGameChange = jest.fn();
render(<Chat onGameChange={onGameChange} />);
await user.keyboard(KONAMI);
expect(onGameChange).toHaveBeenLastCalledWith(true);
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent(
'Snake · score 0 · ↑ ↓ ← → · Esc to quit',
);
await user.keyboard('{Escape}');
expect(onGameChange).toHaveBeenLastCalledWith(false);
expect(screen.getByTestId('ai-dot-grid')).not.toHaveTextContent('Snake');
});
it('leaves arrows in the chat input alone after game over', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onGameChange = jest.fn();
render(<Chat onGameChange={onGameChange} />);
await user.keyboard(KONAMI);
// Heading right, the snake reaches the wall within a few steps.
act(() => {
jest.advanceTimersByTime(1500);
});
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent('Game over');
onGameChange.mockClear();
await user.click(screen.getByTestId('chat-textarea'));
await user.keyboard('{ArrowUp}');
expect(onGameChange).not.toHaveBeenCalled();
});
it('drops the score line when the theme changes mid-game', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const { rerender } = render(<ThemedGrid isDarkMode />);
await user.keyboard(KONAMI);
expect(screen.getByTestId('score-line')).toHaveTextContent('Snake · score 0');
rerender(<ThemedGrid isDarkMode={false} />);
expect(screen.getByTestId('score-line')).toBeEmptyDOMElement();
});
});

View File

@@ -1,32 +0,0 @@
import { getSnakeColors } from '../dotGridTheme';
function canvasWithInk(ink: string): HTMLCanvasElement {
const canvas = document.createElement('canvas');
canvas.style.color = ink;
document.body.appendChild(canvas);
return canvas;
}
describe('getSnakeColors', () => {
afterEach(() => {
document.body.innerHTML = '';
});
it('keeps the snake white on the dark page', () => {
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), true)).toStrictEqual({
head: 'rgba(255,255,255,1)',
body: 'rgba(232,238,245,0.92)',
food: 'rgba(255,255,255,0.97)',
});
});
it('draws the snake in the page ink on the light page', () => {
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), false)).toStrictEqual(
{
head: 'rgba(30,31,36,1)',
body: 'rgba(30,31,36,0.85)',
food: 'rgba(30,31,36,0.95)',
},
);
});
});

View File

@@ -1,112 +0,0 @@
import { SnakeGame, startSnake, stepSnake } from '../snakeGame';
const COLS = 10;
const ROWS = 6;
function newGame(): SnakeGame {
const game = startSnake(COLS, ROWS);
if (!game) {
throw new Error('a 10 × 6 grid fits a game');
}
return game;
}
describe('snakeGame', () => {
beforeEach(() => {
// Food lands on the first free cell, the top-left corner.
jest.spyOn(Math, 'random').mockReturnValue(0);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('needs at least an 8 × 6 grid', () => {
expect(startSnake(7, 6)).toBeNull();
expect(startSnake(8, 5)).toBeNull();
});
it('starts four cells long in the middle, heading right', () => {
expect(newGame()).toStrictEqual({
body: [
{ c: 5, r: 3 },
{ c: 4, r: 3 },
{ c: 3, r: 3 },
{ c: 2, r: 3 },
],
dir: { c: 1, r: 0 },
nextDir: { c: 1, r: 0 },
food: { c: 0, r: 0 },
score: 0,
});
});
it('moves one cell in its direction', () => {
const next = stepSnake(newGame(), COLS, ROWS);
expect(next?.body).toStrictEqual([
{ c: 6, r: 3 },
{ c: 5, r: 3 },
{ c: 4, r: 3 },
{ c: 3, r: 3 },
]);
expect(next?.score).toBe(0);
});
it('grows and scores when it eats', () => {
const next = stepSnake({ ...newGame(), food: { c: 6, r: 3 } }, COLS, ROWS);
expect(next?.body).toHaveLength(5);
expect(next?.score).toBe(1);
});
it('ends when it hits a wall', () => {
const atEdge: SnakeGame = {
...newGame(),
body: [
{ c: 9, r: 3 },
{ c: 8, r: 3 },
{ c: 7, r: 3 },
{ c: 6, r: 3 },
],
};
expect(stepSnake(atEdge, COLS, ROWS)).toBeNull();
});
it('ends when it runs into itself', () => {
const coiled: SnakeGame = {
...newGame(),
body: [
{ c: 5, r: 3 },
{ c: 5, r: 4 },
{ c: 6, r: 4 },
{ c: 6, r: 3 },
{ c: 7, r: 3 },
],
};
expect(stepSnake(coiled, COLS, ROWS)).toBeNull();
});
it('moves into the cell its tail is leaving', () => {
const up = { c: 0, r: -1 };
const turnedDownThenLeft: SnakeGame = {
...newGame(),
body: [
{ c: 4, r: 4 },
{ c: 5, r: 4 },
{ c: 5, r: 3 },
{ c: 4, r: 3 },
],
nextDir: up,
};
expect(stepSnake(turnedDownThenLeft, COLS, ROWS)?.body).toStrictEqual([
{ c: 4, r: 3 },
{ c: 4, r: 4 },
{ c: 5, r: 4 },
{ c: 5, r: 3 },
]);
});
});

View File

@@ -1,53 +0,0 @@
export const DOT_SPACING = 12;
export const DOT_RADIUS = 1.15;
export const TRAIL_RADIUS = 72;
export const TRAIL_LIFT = 0.24;
export const TRAIL_MAX_POINTS = 18;
export const TRAIL_LIFE_MS = 1000;
export const TRAIL_MIN_STEP = 7;
// Time the field rests at when motion is reduced.
export const STILL_TIME_MS = 12000;
type Rgb = [number, number, number];
// Green, teal, blue, violet and pink, in the order the field drifts through them.
const AURORA: Rgb[] = [
[64, 224, 150],
[48, 200, 210],
[90, 130, 245],
[170, 110, 245],
[235, 110, 200],
];
/** Brightness of the field at a point, between -1 and 1. */
export function auroraBrightness(x: number, y: number, t: number): number {
return (
(Math.sin(x * 0.009 + t * 0.0006) +
Math.sin(y * 0.015 - t * 0.00085 + x * 0.002) +
Math.sin((x + y) * 0.006 + t * 0.0011) +
Math.sin((x - y) * 0.0048 - t * 0.0007)) /
4
);
}
/** Colour of the field at a point, blended along the aurora palette. */
export function auroraColor(x: number, y: number, t: number): Rgb {
const position =
((Math.sin(x * 0.0035 + t * 0.00018) +
Math.sin(y * 0.005 - t * 0.00026) +
Math.sin((x + y) * 0.0028 + t * 0.0002)) /
3 +
1) /
2;
const scaled = position * (AURORA.length - 1);
const from = AURORA[Math.floor(scaled)];
const to = AURORA[Math.min(Math.floor(scaled) + 1, AURORA.length - 1)];
const mix = scaled - Math.floor(scaled);
return [
from[0] + (to[0] - from[0]) * mix,
from[1] + (to[1] - from[1]) * mix,
from[2] + (to[2] - from[2]) * mix,
];
}

View File

@@ -1,34 +0,0 @@
// Colours for the dot grid that depend on the page behind it.
export interface SnakeColors {
head: string;
body: string;
food: string;
}
const DARK_SNAKE: SnakeColors = {
head: 'rgba(255,255,255,1)',
body: 'rgba(232,238,245,0.92)',
food: 'rgba(255,255,255,0.97)',
};
function withAlpha(rgb: string, alpha: number): string {
const channels = rgb.match(/\d+(\.\d+)?/g)?.slice(0, 3) ?? ['0', '0', '0'];
return `rgba(${channels.join(',')},${alpha})`;
}
/** Snake colours: white on the dark page, the canvas's ink (`color`) on the light one. */
export function getSnakeColors(
canvas: HTMLCanvasElement,
isDarkMode: boolean,
): SnakeColors {
if (isDarkMode) {
return DARK_SNAKE;
}
const ink = getComputedStyle(canvas).color;
return {
head: withAlpha(ink, 1),
body: withAlpha(ink, 0.85),
food: withAlpha(ink, 0.95),
};
}

View File

@@ -1,102 +0,0 @@
// Painting for the dot grid: the aurora field with the cursor's glow, and plain dots.
import {
auroraBrightness,
auroraColor,
DOT_RADIUS,
TRAIL_LIFE_MS,
TRAIL_LIFT,
TRAIL_RADIUS,
} from './dotGridField';
// Coloured dots on white read fainter than lit ones on black.
const LIGHT_ALPHA_BOOST = 1.6;
export interface TrailPoint {
x: number;
y: number;
born: number;
}
interface AuroraFrame {
/** Field time; frozen when motion is reduced. */
t: number;
now: number;
height: number;
trail: TrailPoint[];
isGameOn: boolean;
/** Light adds up on the dark page; on the light one colours sit on the paper instead. */
isDarkMode: boolean;
/** Dots below this stay dark. */
cutoffY: number;
}
/** The faint light that washes up from the bottom while the game is on. */
export function gameFloor(y: number, height: number): number {
return 0.07 + 0.16 * (y / height);
}
export function drawDot(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
radius: number,
fill: string,
): void {
ctx.beginPath();
ctx.fillStyle = fill;
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
/** Paints the aurora dots, brightest at the top and lit along the cursor's trail. */
export function drawAuroraDots(
ctx: CanvasRenderingContext2D,
dots: { x: number; y: number }[],
{ t, now, height, trail, isGameOn, isDarkMode, cutoffY }: AuroraFrame,
): void {
// Overlapping glows add up, as light does.
ctx.globalCompositeOperation = isDarkMode ? 'lighter' : 'source-over';
dots.forEach(({ x, y }) => {
if (y > cutoffY) {
return;
}
// Brightest at the top, fading toward the content below.
const topWeight = 1 - 0.82 * Math.min(1, y / height);
const lum = Math.max(0, auroraBrightness(x, y, t)) ** 1.6;
let intensity = (0.06 + lum * 0.4) * topWeight * (isGameOn ? 0.5 : 1);
if (isGameOn) {
intensity += gameFloor(y, height);
}
let glow = 0;
trail.forEach((point) => {
const distance2 = (x - point.x) ** 2 + (y - point.y) ** 2;
if (distance2 < TRAIL_RADIUS ** 2) {
const life = 1 - (now - point.born) / TRAIL_LIFE_MS;
glow += (1 - distance2 / TRAIL_RADIUS ** 2) ** 3 * life;
}
});
intensity += Math.min(glow, 1.3) * TRAIL_LIFT * topWeight;
if (intensity <= 0.02) {
return;
}
const [red, green, blue] = auroraColor(x, y, t);
// The hottest dots burn toward white on the dark page and deepen on the light one.
const heat = Math.min(1, Math.max(0, intensity - 0.9)) * 0.9;
const toward = isDarkMode ? 255 : 0;
const mix = isDarkMode ? heat : heat * 0.4;
const rgb = `${Math.round(red + (toward - red) * mix)},${Math.round(
green + (toward - green) * mix,
)},${Math.round(blue + (toward - blue) * mix)}`;
const alpha = Math.min(1, intensity * (isDarkMode ? 1 : LIGHT_ALPHA_BOOST));
const radius = DOT_RADIUS + Math.min(intensity, 1.2) * 0.7;
if (intensity > 0.6) {
drawDot(ctx, x, y, radius * 2.6, `rgba(${rgb},${alpha * 0.06})`);
}
drawDot(ctx, x, y, radius, `rgba(${rgb},${alpha})`);
});
ctx.globalCompositeOperation = 'source-over';
}

View File

@@ -1,100 +0,0 @@
// Snake on the dot grid, the easter egg the Konami code unlocks.
interface Cell {
c: number;
r: number;
}
export interface SnakeGame {
body: Cell[];
dir: Cell;
nextDir: Cell;
food: Cell;
score: number;
}
export const SNAKE_STEP_MS = 110;
// Lowercase: keys are lowercased before matching, so B/b and A/a both count.
export const KONAMI_CODE = [
'arrowup',
'arrowup',
'arrowdown',
'arrowdown',
'arrowleft',
'arrowright',
'arrowleft',
'arrowright',
'b',
'a',
];
export const SNAKE_DIRECTIONS: Record<string, Cell> = {
arrowup: { c: 0, r: -1 },
w: { c: 0, r: -1 },
arrowdown: { c: 0, r: 1 },
s: { c: 0, r: 1 },
arrowleft: { c: -1, r: 0 },
a: { c: -1, r: 0 },
arrowright: { c: 1, r: 0 },
d: { c: 1, r: 0 },
};
const isOn = (cells: Cell[], cell: Cell): boolean =>
cells.some(({ c, r }) => c === cell.c && r === cell.r);
/** A free cell for the food, or null when the snake fills the grid. */
function placeFood(body: Cell[], cols: number, rows: number): Cell | null {
const free: Cell[] = [];
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
if (!isOn(body, { c, r })) {
free.push({ c, r });
}
}
}
return free.length ? free[Math.floor(Math.random() * free.length)] : null;
}
/** A four-cell snake in the middle heading right, or null when the grid is too small. */
export function startSnake(cols: number, rows: number): SnakeGame | null {
if (cols < 8 || rows < 6) {
return null;
}
const c = Math.floor(cols / 2);
const r = Math.floor(rows / 2);
const body = [0, 1, 2, 3].map((i) => ({ c: c - i, r }));
const food = placeFood(body, cols, rows);
if (!food) {
return null;
}
const right = { c: 1, r: 0 };
return { body, dir: right, nextDir: right, food, score: 0 };
}
/** Moves the snake one cell; null when it hits a wall, itself, or fills the grid. */
export function stepSnake(
game: SnakeGame,
cols: number,
rows: number,
): SnakeGame | null {
const dir = game.nextDir;
const head = { c: game.body[0].c + dir.c, r: game.body[0].r + dir.r };
const ate = head.c === game.food.c && head.r === game.food.r;
const kept = ate ? game.body : game.body.slice(0, -1);
if (
head.c < 0 ||
head.c >= cols ||
head.r < 0 ||
head.r >= rows ||
isOn(kept, head)
) {
return null;
}
const body = [head, ...kept];
const food = ate ? placeFood(body, cols, rows) : game.food;
if (!food) {
return null;
}
return { ...game, body, dir, food, score: game.score + (ate ? 1 : 0) };
}

View File

@@ -1,320 +0,0 @@
import { RefObject, useEffect, useLayoutEffect, useRef, useState } from 'react';
import {
DOT_RADIUS,
DOT_SPACING,
STILL_TIME_MS,
TRAIL_LIFE_MS,
TRAIL_MAX_POINTS,
TRAIL_MIN_STEP,
TRAIL_RADIUS,
} from './dotGridField';
import { drawAuroraDots, drawDot, gameFloor, TrailPoint } from './drawDots';
import {
KONAMI_CODE,
SNAKE_DIRECTIONS,
SNAKE_STEP_MS,
SnakeGame,
startSnake,
stepSnake,
} from './snakeGame';
import { getSnakeColors } from './dotGridTheme';
const GAME_OVER_LABEL_MS = 4000;
const REPLAY_LABEL = '↑ to replay';
const playingLabel = (score: number): string =>
`Snake · score ${score} · ↑ ↓ ← → · Esc to quit`;
// Unlocked once per page load; after that a click on the dots starts a game.
let isSnakeUnlocked = false;
// Room left under the snake's lowest row for the score line, so the two never touch.
const SCORE_LINE_CLEARANCE = 30;
const isField = (target: EventTarget | null): target is HTMLElement =>
target instanceof HTMLElement &&
Boolean(target.closest('input, textarea, select, [contenteditable="true"]'));
/** Draws the aurora dot grid; the Konami code turns it into Snake. Returns the score line. */
export function useDotGrid(
canvasRef: RefObject<HTMLCanvasElement>,
isDarkMode: boolean,
onGameChange?: (isPlaying: boolean) => void,
): string | null {
const [label, setLabel] = useState<string | null>(null);
const onGameChangeRef = useRef(onGameChange);
useLayoutEffect(() => {
onGameChangeRef.current = onGameChange;
});
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
if (!canvas || !ctx) {
return undefined;
}
const isStill = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const snakeColors = getSnakeColors(canvas, isDarkMode);
let width = 0;
let height = 0;
let cols = 0;
let rows = 0;
let gameRows = 0;
let left = 0;
let dots: { x: number; y: number }[] = [];
const trail: TrailPoint[] = [];
let frame = 0;
let game: SnakeGame | null = null;
let lastStep = 0;
// With reduced motion the field stands still, so frames repaint only after a change.
let needsDraw = true;
let isScoreLineShown = false;
const showScoreLine = (text: string | null): void => {
isScoreLineShown = text !== null;
needsDraw = true;
setLabel(text);
};
const recentKeys: string[] = [];
let labelTimer = 0;
// An arrow key replays while the game over line is up.
let canReplay = false;
const showPlayCursor = (): void => {
canvas.style.cursor = isSnakeUnlocked && !game ? 'pointer' : '';
};
const cellCenter = (c: number, r: number): { x: number; y: number } => ({
x: left + c * DOT_SPACING,
y: DOT_SPACING + r * DOT_SPACING,
});
const play = (): void => {
game = startSnake(cols, gameRows);
lastStep = performance.now();
canReplay = false;
window.clearTimeout(labelTimer);
showScoreLine(game ? playingLabel(0) : null);
showPlayCursor();
onGameChangeRef.current?.(game !== null);
};
const quit = (): void => {
game = null;
canReplay = false;
window.clearTimeout(labelTimer);
showScoreLine(null);
showPlayCursor();
onGameChangeRef.current?.(false);
};
const endGame = (score: number): void => {
game = null;
canReplay = true;
showScoreLine(`Game over · score ${score} · ${REPLAY_LABEL}`);
showPlayCursor();
onGameChangeRef.current?.(false);
labelTimer = window.setTimeout(() => {
canReplay = false;
showScoreLine(null);
}, GAME_OVER_LABEL_MS);
};
const layout = (): void => {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
width = canvas.clientWidth;
height = canvas.clientHeight;
canvas.width = Math.floor(width * dpr);
canvas.height = Math.floor(height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
cols = Math.max(0, Math.floor((width - DOT_SPACING) / DOT_SPACING));
rows = Math.max(0, Math.floor((height - DOT_SPACING) / DOT_SPACING));
gameRows = Math.min(
rows,
Math.max(0, Math.floor((height - SCORE_LINE_CLEARANCE) / DOT_SPACING)),
);
left = (width - cols * DOT_SPACING) / 2 + DOT_SPACING / 2;
dots = [];
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
dots.push(cellCenter(c, r));
}
}
needsDraw = true;
// A game carries on through a resize unless it no longer fits.
if (
game &&
[...game.body, game.food].some(({ c, r }) => c >= cols || r >= gameRows)
) {
play();
}
};
const onPointer = (event: PointerEvent): void => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
if (
x < -TRAIL_RADIUS ||
y < -TRAIL_RADIUS ||
x > width + TRAIL_RADIUS ||
y > height + TRAIL_RADIUS
) {
return;
}
const head = trail[trail.length - 1];
// Barely moved: keep the head lit instead of stacking points.
if (head && Math.hypot(x - head.x, y - head.y) < TRAIL_MIN_STEP) {
head.born = performance.now();
return;
}
trail.push({ x, y, born: performance.now() });
if (trail.length > TRAIL_MAX_POINTS) {
trail.shift();
}
};
// Keys typed into a field outside this chat belong to that field.
const isOtherField = (target: EventTarget | null): boolean => {
if (!isField(target)) {
return false;
}
let chat = canvas.parentElement;
while (chat && !chat.querySelector('textarea')) {
chat = chat.parentElement;
}
return !chat?.contains(target);
};
const onKeyDown = (event: KeyboardEvent): void => {
if (isOtherField(event.target)) {
return;
}
const key = event.key.toLowerCase();
if (game) {
if (key === 'escape') {
event.preventDefault();
quit();
return;
}
const next = SNAKE_DIRECTIONS[key];
if (next) {
// Steering keys drive the snake, not the input; no turning back onto the neck.
event.preventDefault();
if (next.c !== -game.dir.c || next.r !== -game.dir.r) {
game.nextDir = next;
}
}
return;
}
// Arrows in the chat's input move its caret instead.
if (canReplay && key.startsWith('arrow') && !isField(event.target)) {
event.preventDefault();
play();
return;
}
recentKeys.push(key);
if (recentKeys.length > KONAMI_CODE.length) {
recentKeys.shift();
}
if (recentKeys.join() === KONAMI_CODE.join()) {
recentKeys.length = 0;
isSnakeUnlocked = true;
play();
}
};
const onClick = (): void => {
if (isSnakeUnlocked && !game) {
play();
}
};
// The snake and its food: flat white dots the size of their neighbours.
const stepAndDrawSnake = (now: number): void => {
if (game && now - lastStep >= SNAKE_STEP_MS) {
lastStep = now;
const next = stepSnake(game, cols, gameRows);
if (next) {
if (next.score !== game.score) {
showScoreLine(playingLabel(next.score));
}
game = next;
} else {
endGame(game.score);
}
}
if (game) {
const sizeAt = (y: number): number =>
DOT_RADIUS + Math.min(gameFloor(y, height), 1.2) * 0.7;
const food = cellCenter(game.food.c, game.food.r);
drawDot(ctx, food.x, food.y, sizeAt(food.y), snakeColors.food);
game.body.forEach((cell, i) => {
const { x, y } = cellCenter(cell.c, cell.r);
drawDot(
ctx,
x,
y,
sizeAt(y),
i === 0 ? snakeColors.head : snakeColors.body,
);
});
}
};
const draw = (now: number): void => {
const hadTrail = trail.length > 0;
for (let i = trail.length - 1; i >= 0; i -= 1) {
if (now - trail[i].born >= TRAIL_LIFE_MS) {
trail.splice(i, 1);
}
}
if (isStill && !game && !hadTrail && !needsDraw) {
frame = requestAnimationFrame(draw);
return;
}
needsDraw = false;
const t = isStill ? STILL_TIME_MS : now;
ctx.clearRect(0, 0, width, height);
drawAuroraDots(ctx, dots, {
t,
now,
height,
trail,
isGameOn: game !== null,
isDarkMode,
// Keeps the score line's strip clear of dots.
cutoffY: isScoreLineShown ? gameRows * DOT_SPACING : Infinity,
});
stepAndDrawSnake(now);
frame = requestAnimationFrame(draw);
};
const observer = new ResizeObserver(layout);
observer.observe(canvas);
layout();
window.addEventListener('pointermove', onPointer);
window.addEventListener('pointerdown', onPointer);
window.addEventListener('keydown', onKeyDown);
canvas.addEventListener('click', onClick);
showPlayCursor();
frame = requestAnimationFrame(draw);
return (): void => {
cancelAnimationFrame(frame);
observer.disconnect();
window.clearTimeout(labelTimer);
setLabel(null);
if (game) {
onGameChangeRef.current?.(false);
}
window.removeEventListener('pointermove', onPointer);
window.removeEventListener('pointerdown', onPointer);
window.removeEventListener('keydown', onKeyDown);
canvas.removeEventListener('click', onClick);
};
}, [canvasRef, isDarkMode]);
return label;
}

View File

@@ -68,17 +68,7 @@ export default function DownloadOptionsMenu({
aria-modal="true"
>
<div className="export-format">
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
FORMAT
</Typography>
<Typography.Text className="title">FORMAT</Typography.Text>
<RadioGroup
color="primary"
value={exportFormat}
@@ -93,17 +83,7 @@ export default function DownloadOptionsMenu({
<div className="horizontal-line" />
<div className="row-limit">
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
Number of Rows
</Typography>
<Typography.Text className="title">Number of Rows</Typography.Text>
<RadioGroup
color="primary"
value={String(rowLimit)}
@@ -121,17 +101,7 @@ export default function DownloadOptionsMenu({
<div className="horizontal-line" />
<div className="columns-scope">
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
Columns
</Typography>
<Typography.Text className="title">Columns</Typography.Text>
<RadioGroup
color="primary"
value={columnsScope}

View File

@@ -1,5 +1,6 @@
import { Trash2, X } from '@signozhq/icons';
import { AlertDialog } from '@signozhq/ui/alert-dialog';
import { Button } from '@signozhq/ui/button';
import { DialogWrapper } from '@signozhq/ui/dialog';
import { MemberRow } from 'components/MembersTable/MembersTable';
interface DeleteMemberDialogProps {
@@ -8,7 +9,7 @@ interface DeleteMemberDialogProps {
member: MemberRow | null;
isDeleting: boolean;
onClose: () => void;
onConfirm: () => Promise<void>;
onConfirm: () => void;
}
function DeleteMemberDialog({
@@ -35,20 +36,47 @@ function DeleteMemberDialog({
</>
);
const footer = (
<>
<Button
size="md"
variant="solid"
color="secondary"
onClick={onClose}
prefix={<X size={12} />}
>
Cancel
</Button>
<Button
size="md"
variant="solid"
color="danger"
onClick={onConfirm}
testId="member-delete-confirm-btn"
loading={isDeleting}
prefix={<Trash2 size={12} />}
>
{isDeleting ? 'Processing...' : title}
</Button>
</>
);
return (
<AlertDialog
<DialogWrapper
open={open}
onOpenChange={(isOpen): void => {
if (!isOpen) {
onClose();
}
}}
title={title}
color="danger"
confirmText={isDeleting ? 'Processing...' : title}
confirmIcon={<Trash2 size={12} />}
cancelIcon={<X size={12} />}
onConfirm={onConfirm}
onCancel={onClose}
testId="member-delete"
width="narrow"
showCloseButton={false}
disableOutsideClick={false}
footer={footer}
>
{body}
</AlertDialog>
</DialogWrapper>
);
}

View File

@@ -20,9 +20,10 @@
}
&__label {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
font-weight: var(--font-weight-normal);
color: var(--foreground);
line-height: var(--paragraph-base-400-line-height);
line-height: var(--line-height-20);
letter-spacing: -0.07px;
cursor: default;
}
@@ -52,8 +53,10 @@
}
&__email-text {
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
color: var(--foreground);
line-height: var(--paragraph-small-400-line-height);
line-height: var(--line-height-18);
letter-spacing: -0.07px;
white-space: nowrap;
overflow: hidden;
@@ -83,26 +86,41 @@
[data-slot='badge'] {
padding: var(--padding-1) var(--padding-2);
align-items: center;
font-size: var(--uppercase-small-500-font-size);
font-weight: var(--uppercase-small-500-font-weight);
line-height: 100%;
letter-spacing: 0.44px;
}
}
&__meta-label {
font-size: var(--uppercase-small-500-font-size);
font-weight: var(--uppercase-small-500-font-weight);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
color: var(--foreground);
line-height: var(--uppercase-small-500-line-height);
line-height: var(--line-height-20);
letter-spacing: 0.48px;
text-transform: uppercase;
}
&__footer {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
&__footer-left {
display: flex;
align-items: center;
gap: var(--spacing-4);
}
&__footer-right {
display: flex;
align-items: center;
gap: var(--spacing-6);
}
&__footer-divider {
width: 1px;
height: 21px;
@@ -145,6 +163,14 @@
}
.reset-link-dialog {
background: var(--l2-background);
border: 1px solid var(--l1-border);
[data-slot='dialog-header'] {
border-color: var(--l1-border);
color: var(--l1-foreground);
}
&__content {
display: flex;
flex-direction: column;
@@ -152,6 +178,8 @@
}
&__description {
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
color: var(--l2-foreground);
line-height: var(--paragraph-base-400-line-height);
letter-spacing: -0.065px;
@@ -165,8 +193,8 @@
align-items: center;
height: 32px;
overflow: hidden;
background: var(--l3-background);
border: 1px solid var(--l3-border);
background: var(--l2-background);
border: 1px solid var(--l1-border);
border-radius: 2px;
padding-right: var(--spacing-4);
}
@@ -183,8 +211,10 @@
overflow: hidden;
text-overflow: ellipsis;
padding: 0 var(--padding-2);
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
color: var(--l2-foreground);
line-height: var(--paragraph-small-400-line-height);
line-height: var(--line-height-18);
letter-spacing: -0.07px;
}
}

View File

@@ -3,9 +3,9 @@ import { useCopyToClipboard } from 'react-use';
import { LockKeyhole, RefreshCw, Trash2, X } from '@signozhq/icons';
import { Badge } from '@signozhq/ui/badge';
import { Button } from '@signozhq/ui/button';
import { Drawer } from '@signozhq/ui/drawer';
import { DrawerWrapper } from '@signozhq/ui/drawer';
import { Input } from '@signozhq/ui/input';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { Skeleton, Tooltip } from 'antd';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
@@ -258,7 +258,7 @@ function EditMemberDrawer({
const { mutateAsync: updateMyUser } = useUpdateMyUserV2();
const { mutateAsync: updateUser } = useUpdateUser();
const { mutateAsync: deleteUser, isLoading: isDeleting } = useDeleteUser({
const { mutate: deleteUser, isLoading: isDeleting } = useDeleteUser({
mutation: {
onSuccess: (): void => {
toast.success(
@@ -426,15 +426,11 @@ function EditMemberDrawer({
onComplete,
]);
const handleDelete = useCallback(async (): Promise<void> => {
const handleDelete = useCallback((): void => {
if (!member) {
return;
}
try {
await deleteUser({ pathParams: { id: member.id } });
} catch {
// `onError` already shows the error modal, and the confirmation stays open.
}
deleteUser({ pathParams: { id: member.id } });
}, [member, deleteUser]);
const handleGenerateResetLink = useCallback(async (): Promise<void> => {
@@ -461,8 +457,7 @@ function EditMemberDrawer({
setShowResetLinkDialog(true);
onClose();
} else {
toast.danger('Failed to generate password reset link', {
action: { label: 'Dismiss' },
toast.error('Failed to generate password reset link', {
position: 'top-right',
});
}
@@ -491,7 +486,7 @@ function EditMemberDrawer({
useEffect(() => {
if (copyState.error) {
toast.danger('Failed to copy link', { action: { label: 'Dismiss' } });
toast.error('Failed to copy link');
}
}, [copyState.error]);
@@ -565,7 +560,6 @@ function EditMemberDrawer({
}}
placeholder="Enter name"
disabled={isRootUser || isDeleted}
disabledTooltip={undefined}
/>
</AuthZTooltip>
</div>
@@ -618,7 +612,6 @@ function EditMemberDrawer({
<RolesSelect
id="member-role"
mode="multiple"
testId="member-roles-select"
roles={availableRoles}
loading={rolesLoading}
isError={rolesError}
@@ -694,83 +687,91 @@ function EditMemberDrawer({
</div>
);
const footerStart = isDeleted ? null : (
<div className="edit-member-drawer__footer-left">
<AuthZButton
disabledTooltip={getDeleteTooltip(isRootUser, isSelf)}
size="md"
onClick={(): void => setShowDeleteConfirm(true)}
testId="member-delete-btn"
variant="link"
color="danger"
checks={member ? [buildUserDeletePermission(member.id)] : []}
prefix={<Trash2 size={12} />}
>
{isInvited ? 'Revoke Invite' : 'Delete Member'}
</AuthZButton>
const footer = (
<div className="edit-member-drawer__footer">
{!isDeleted && (
<>
<div className="edit-member-drawer__footer-left">
<AuthZButton
disabledTooltip={getDeleteTooltip(isRootUser, isSelf)}
size="md"
onClick={(): void => setShowDeleteConfirm(true)}
testId="member-delete-btn"
variant="link"
color="danger"
checks={member ? [buildUserDeletePermission(member.id)] : []}
prefix={<Trash2 size={12} />}
>
{isInvited ? 'Revoke Invite' : 'Delete Member'}
</AuthZButton>
<div className="edit-member-drawer__footer-divider" />
<AuthZButton
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
size="md"
onClick={handleGenerateResetLink}
testId="member-reset-link-btn"
loading={isGeneratingLink || isLoadingTokenStatus}
variant="link"
color="warning"
checks={resetLinkChecks}
prefix={<RefreshCw size={12} />}
>
{inviteLinkAndResetPasswordText}
</AuthZButton>
<div className="edit-member-drawer__footer-divider" />
<AuthZButton
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
size="md"
onClick={handleGenerateResetLink}
testId="member-reset-link-btn"
loading={isGeneratingLink || isLoadingTokenStatus}
variant="link"
color="warning"
checks={resetLinkChecks}
prefix={<RefreshCw size={12} />}
>
{inviteLinkAndResetPasswordText}
</AuthZButton>
</div>
<div className="edit-member-drawer__footer-right">
<Button
size="md"
variant="outlined"
color="secondary"
onClick={handleClose}
prefix={<X size={14} />}
>
Cancel
</Button>
<AuthZButton
disabledTooltip={
isRootUser
? ROOT_USER_TOOLTIP
: !isDirty
? 'No changes to save'
: undefined
}
size="md"
variant="solid"
color="primary"
disabled={!isDirty || isRootUser}
onClick={handleSave}
checks={[]}
testId="member-save-btn"
loading={isSaving}
>
{isSaving ? 'Saving...' : 'Save Member Details'}
</AuthZButton>
</div>
</>
)}
</div>
);
const footerActions = isDeleted ? null : (
<>
<Button
size="md"
variant="outlined"
color="secondary"
onClick={handleClose}
prefix={<X size={14} />}
>
Cancel
</Button>
<AuthZButton
disabledTooltip={
isRootUser
? ROOT_USER_TOOLTIP
: !isDirty
? 'No changes to save'
: undefined
}
size="md"
variant="solid"
color="primary"
disabled={!isDirty || isRootUser}
onClick={handleSave}
checks={[]}
testId="member-save-btn"
loading={isSaving}
>
{isSaving ? 'Saving...' : 'Save Member Details'}
</AuthZButton>
</>
);
return (
<>
<Drawer
type="task"
stack="overlay"
<DrawerWrapper
open={member !== null}
onClose={handleClose}
onOpenChange={(isOpen): void => {
if (!isOpen) {
handleClose();
}
}}
direction="right"
showCloseButton
showOverlay={false}
title="Member Details"
footer={footer}
width="wide"
footerPrefix={footerStart}
footerSuffix={footerActions}
>
<AuthZGuardContent
checks={member ? [buildUserReadPermission(member?.id)] : []}
@@ -778,7 +779,7 @@ function EditMemberDrawer({
>
{drawerContent}
</AuthZGuardContent>
</Drawer>
</DrawerWrapper>
<ResetLinkDialog
open={showResetLinkDialog}

View File

@@ -1,6 +1,6 @@
import { Check, Copy } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Dialog } from '@signozhq/ui/dialog';
import { DialogWrapper } from '@signozhq/ui/dialog';
interface ResetLinkDialogProps {
open: boolean;
@@ -22,11 +22,17 @@ function ResetLinkDialog({
onCopy,
}: ResetLinkDialogProps): JSX.Element {
return (
<Dialog
<DialogWrapper
open={open}
onClose={onClose}
onOpenChange={(isOpen): void => {
if (!isOpen) {
onClose();
}
}}
title={linkType === 'invite' ? 'Invite Link' : 'Password Reset Link'}
showCloseButton
width="base"
className="reset-link-dialog"
>
<div className="reset-link-dialog__content">
<p className="reset-link-dialog__description">
@@ -59,7 +65,7 @@ function ResetLinkDialog({
</p>
)}
</div>
</Dialog>
</DialogWrapper>
);
}

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import {
useCreateResetPasswordToken,
@@ -51,31 +51,52 @@ jest.mock('api/ErrorResponseHandlerForGeneratedAPIs', () => ({
jest.mock('@signozhq/ui/drawer', () => ({
...jest.requireActual('@signozhq/ui/drawer'),
Drawer: ({
DrawerWrapper: ({
children,
footerPrefix,
footerSuffix,
footer,
open,
}: {
children?: ReactNode;
footerPrefix?: ReactNode;
footerSuffix?: ReactNode;
footer?: ReactNode;
open: boolean;
}): JSX.Element | null =>
open ? (
<div>
{children}
{footerPrefix}
{footerSuffix}
{footer}
</div>
) : null,
}));
jest.mock('@signozhq/ui/toast', () => ({
...jest.requireActual('@signozhq/ui/toast'),
jest.mock('@signozhq/ui/dialog', () => ({
...jest.requireActual('@signozhq/ui/dialog'),
DialogWrapper: ({
children,
footer,
open,
title,
}: {
children?: ReactNode;
footer?: ReactNode;
open: boolean;
title?: string;
}): JSX.Element | null =>
open ? (
<div role="dialog" aria-label={title}>
{children}
{footer}
</div>
) : null,
DialogFooter: ({ children }: { children?: ReactNode }): JSX.Element => (
<div>{children}</div>
),
}));
jest.mock('@signozhq/ui/sonner', () => ({
...jest.requireActual('@signozhq/ui/sonner'),
toast: {
success: jest.fn(),
danger: jest.fn(),
error: jest.fn(),
},
}));
@@ -208,7 +229,7 @@ describe('EditMemberDrawer', () => {
isLoading: false,
});
(useDeleteUser as jest.Mock).mockReturnValue({
mutateAsync: mockDeleteMutate,
mutate: mockDeleteMutate,
isLoading: false,
});
// Token query: valid token for invited members
@@ -342,11 +363,8 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
// signoz-admin is already selected; add signoz-editor on top
await user.click(await screen.findByTestId('member-roles-select'));
await user.type(
await screen.findByTestId('member-roles-select-search'),
`${managedRoles[1].name}{Enter}`,
);
await user.click(await screen.findByLabelText('Roles'));
await user.click(await screen.findByTitle('signoz-editor'));
const saveBtn = screen.getByRole('button', { name: /save member details/i });
await waitFor(() =>
@@ -370,11 +388,11 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
// signoz-admin appears as a selected tag — click its remove button to deselect
await user.click(
await screen.findByTestId(
`member-roles-select-chip-${managedRoles[0].id}-remove`,
),
);
const adminTag = await screen.findByTitle('signoz-admin');
const removeBtn = adminTag.querySelector(
'.ant-select-selection-item-remove',
) as Element;
await user.click(removeBtn);
const saveBtn = screen.getByRole('button', { name: /save member details/i });
await waitFor(() =>
@@ -395,7 +413,7 @@ describe('EditMemberDrawer', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
mutate: mockDeleteMutate.mockImplementation(() => {
options?.mutation?.onSuccess?.();
}),
isLoading: false,
@@ -556,7 +574,7 @@ describe('EditMemberDrawer', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
mutate: mockDeleteMutate.mockImplementation(() => {
options?.mutation?.onSuccess?.();
}),
isLoading: false,
@@ -672,7 +690,7 @@ describe('EditMemberDrawer', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
mutate: mockDeleteMutate.mockImplementation(() => {
options?.mutation?.onError?.({});
}),
isLoading: false,
@@ -703,7 +721,7 @@ describe('EditMemberDrawer', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
mutate: mockDeleteMutate.mockImplementation(() => {
options?.mutation?.onError?.({});
}),
isLoading: false,

View File

@@ -1,16 +1,22 @@
// The mask of the error modal blurs the page and any dialog under it, so a dialog's
// own backdrop would dim the page a second time.
body:has(.error-modal__wrap:not([style*='display: none'])) {
--dialog-backdrop-color: transparent;
--alert-dialog-backdrop-color: transparent;
}
.error-modal {
&__trigger {
width: fit-content;
display: flex;
align-items: center;
gap: 4px;
border-radius: 20px;
background: color-mix(in srgb, var(--danger-background) 20%, transparent);
padding-left: 3px;
padding-right: 8px;
cursor: pointer;
span {
color: var(--danger-background);
font-size: 10px;
font-weight: 500;
line-height: 20px; /* 200% */
letter-spacing: 0.4px;
text-transform: uppercase;
}
}
&__wrap {
background: linear-gradient(
@@ -59,6 +65,7 @@ body:has(.error-modal__wrap:not([style*='display: none'])) {
&__value {
padding: 4px 8px;
font-size: 12px;
font-style: normal;
font-weight: 500;
line-height: 16px;
letter-spacing: 0.48px;

View File

@@ -18,12 +18,6 @@ type Props = {
open?: boolean;
};
// Above every `@signozhq/ui` dialog (`--dialog-z-index: 1001`, plus one per
// nested layer), so the error shows over the dialog whose action failed.
// TODO: temporary. Drop it once this moves to the `@signozhq/ui` Dialog, which
// stacks above the layer that opened it.
const ERROR_MODAL_Z_INDEX = 2000;
const classNames = {
body: 'error-modal__body',
mask: 'error-modal__mask',
@@ -59,13 +53,8 @@ function ErrorModal({
onClick={(): void => setVisible(true)}
onKeyDown={undefined}
>
<Badge
variant="solid"
color="danger"
textTransform="uppercase"
prefix={<CircleAlert size={14} />}
>
error
<Badge variant="solid" color="danger">
<CircleAlert size={14} color={Color.BG_CHERRY_500} /> error
</Badge>
</span>
) : (
@@ -101,7 +90,6 @@ function ErrorModal({
closeIcon={false}
classNames={classNames}
wrapClassName="error-modal__wrap"
zIndex={ERROR_MODAL_Z_INDEX}
>
<ErrorContent error={error} />
</Modal>

View File

@@ -38,6 +38,7 @@
margin: 0;
color: var(--l2-foreground);
font-size: 14px;
font-weight: 400;
line-height: 20px; /* 142.857% */
letter-spacing: -0.07px;
}
@@ -48,6 +49,8 @@
gap: 6px;
padding: 9px 12.5px;
color: var(--l2-foreground);
font-size: 12px;
font-weight: 400;
line-height: 18px; /* 150% */
letter-spacing: 0.12px;
border-radius: 2px;
@@ -76,6 +79,7 @@
color: var(--l2-foreground);
font-size: 12px;
font-weight: 500;
line-height: 18px; /* 150% */
letter-spacing: 0.48px;
pointer-events: none;
}
@@ -94,6 +98,7 @@
color: var(--l1-foreground);
font-size: 10px;
font-weight: 500;
line-height: 18px; /* 180% */
letter-spacing: 0.5px;
}
}
@@ -128,12 +133,16 @@
position: relative;
margin-bottom: 4px;
color: var(--l2-foreground);
font-family: var(--code-base-400-font-family);
font-family: Geist Mono;
font-size: 12px;
font-weight: 400;
line-height: 18px;
padding: 3px 12px;
padding-left: 26px;
}
&__message-item::before {
font-family: unset;
content: '';
position: absolute;
left: 12px;

View File

@@ -1,12 +1,12 @@
.export-menu-popover {
// The popover shell carries no padding of its own, so the content owns it.
padding: var(--spacing-8);
width: 240px;
padding: 0 12px 12px 12px;
.title {
display: flex;
color: var(--l1-foreground);
font-family: Inter;
font-size: var(--uppercase-small-500-font-size);
font-size: var(--periscope-font-size-small);
font-style: normal;
font-weight: 500;
line-height: 18px;
@@ -23,7 +23,7 @@
// radio option labels — radix popover content inherits the root font
// size; pin to the app's 13px base the antd popover used to impose
label {
font-size: var(--label-base-400-font-size);
font-size: var(--periscope-font-size-base);
}
}
}

View File

@@ -1,6 +1,6 @@
import { Download } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Popover, usePopoverHandle } from '@signozhq/ui/popover';
import { Popover, PopoverContent, PopoverTrigger } from '@signozhq/ui/popover';
import { RadioGroup } from '@signozhq/ui/radio-group';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
@@ -36,10 +36,6 @@ export default function ExportMenu({
}: ExportMenuProps): JSX.Element {
const [exportFormat, setExportFormat] = useState<string>(ExportFormat.Csv);
const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false);
// Driven by a handle rather than `trigger`: the button carries a Tooltip, and a Tooltip
// routes every prop it does not recognise to its own popup, so a popover's press handlers
// would never reach the button underneath.
const menu = usePopoverHandle(setIsPopoverOpen);
const { isExporting, handleExport: handleClientExport } = useClientExport({
data,
@@ -49,74 +45,53 @@ export default function ExportMenu({
});
const handleExport = useCallback((): void => {
menu.close();
setIsPopoverOpen(false);
handleClientExport({ format: exportFormat as ExportFormat });
}, [menu, exportFormat, handleClientExport]);
}, [exportFormat, handleClientExport]);
return (
<>
<Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen}>
<Tooltip title="Download">
<Button
variant="ghost"
color="secondary"
size="sm"
icon
aria-label="Download"
aria-haspopup="dialog"
aria-expanded={isPopoverOpen}
testId={`export-menu-${dataSource}`}
loading={isExporting}
onClick={(event): void =>
menu.isOpen ? menu.close() : menu.showAt(event.currentTarget)
}
>
<Download size={14} />
</Button>
</Tooltip>
<Popover
side="bottom"
align="end"
width={240}
handle={menu}
aria-label="Export format"
>
<div className="export-menu-popover">
<div className="export-format">
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
FORMAT
</Typography>
<RadioGroup
color="primary"
value={exportFormat}
onChange={setExportFormat}
items={[
{ value: ExportFormat.Csv, label: 'csv' },
{ value: ExportFormat.Jsonl, label: 'jsonl' },
]}
/>
</div>
<PopoverTrigger asChild>
<Button
size="md"
variant="solid"
color="primary"
width="100%"
onClick={handleExport}
variant="ghost"
color="secondary"
size="sm"
icon
aria-label="Download"
testId={`export-menu-${dataSource}`}
loading={isExporting}
prefix={<Download size={16} />}
>
Export
<Download size={14} />
</Button>
</PopoverTrigger>
</Tooltip>
<PopoverContent align="end" className="export-menu-popover">
<div className="export-format">
<Typography.Text className="title">FORMAT</Typography.Text>
<RadioGroup
color="primary"
value={exportFormat}
onChange={setExportFormat}
items={[
{ value: ExportFormat.Csv, label: 'csv' },
{ value: ExportFormat.Jsonl, label: 'jsonl' },
]}
/>
</div>
</Popover>
</>
<Button
size="md"
variant="solid"
color="primary"
width="100%"
onClick={handleExport}
loading={isExporting}
prefix={<Download size={16} />}
>
Export
</Button>
</PopoverContent>
</Popover>
);
}

View File

@@ -87,17 +87,6 @@ describe('ExportMenu', () => {
expect(screen.queryByText('FORMAT')).not.toBeInTheDocument();
});
it('closes the popover on a second press of the trigger', async () => {
renderMenu();
await userEvent.click(screen.getByTestId(TEST_ID));
expect(screen.getByText('FORMAT')).toBeInTheDocument();
await userEvent.click(screen.getByTestId(TEST_ID));
expect(screen.getByTestId(TEST_ID)).toHaveAttribute('aria-expanded', 'false');
expect(screen.queryByText('FORMAT')).not.toBeInTheDocument();
});
it('disables the trigger while an export is in progress', () => {
mockIsExporting = true;
renderMenu();

View File

@@ -117,16 +117,9 @@ function AddedFields({
<div className={styles.sectionHeader}>
<span>ADDED FIELDS</span>
{maxFields !== undefined && (
<Typography
variant="paragraph"
size="small"
weight="medium"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text size="sm" weight="medium" color="muted">
Max Allowed: {maxFields}
</Typography>
</Typography.Text>
)}
</div>
<div className={styles.addedList}>

View File

@@ -32,15 +32,12 @@
}
}
// Full-bleed search bar: only top/bottom borders, square corners.
// Per-side widths cannot be expressed via --input-border-width.
.searchInput {
--input-border-radius: 0;
[data-slot='input'] {
border-left: none;
border-right: none;
}
background-color: var(--l1-background);
height: 40px;
border-radius: 0;
border-left: none;
border-right: none;
}
.section {

View File

@@ -1,5 +1,5 @@
import { useCallback, useMemo, useState } from 'react';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
import useDebouncedFn from 'hooks/useDebouncedFunction';
@@ -140,10 +140,10 @@ function FieldsSelectorContent({
<X className={styles.closeIcon} size={16} onClick={onClose} />
</div>
<section className={styles.searchInput}>
<section>
<Input
className={styles.searchInput}
type="text"
size="lg"
value={inputValue}
placeholder="Search for a field..."
onChange={handleInputChange}

View File

@@ -13,9 +13,9 @@ jest.mock('hooks/querySuggestions/useFieldKeysSuggestion', () => ({
})),
}));
jest.mock('@signozhq/ui/toast', () => ({
...jest.requireActual('@signozhq/ui/toast'),
toast: { success: jest.fn(), danger: jest.fn() },
jest.mock('@signozhq/ui/sonner', () => ({
...jest.requireActual('@signozhq/ui/sonner'),
toast: { success: jest.fn(), error: jest.fn() },
}));
// FloatingPanel is a react-rnd/portal shell — presentation only. Render its

View File

@@ -4,16 +4,9 @@ function AnnouncementsModal(): JSX.Element {
return (
<div className="announcements-modal-container">
<div className="announcements-modal-container-header">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text className="announcements-modal-title">
Announcements
</Typography>
</Typography.Text>
</div>
</div>
);

View File

@@ -1,9 +1,8 @@
import { useCallback, useEffect, useState } from 'react';
import { useAppLocation } from 'lib/router/useAppLocation';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { Button, Input } from 'antd';
import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { Button as SignozButton } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import { handleContactSupport } from 'container/Integrations/utils';
@@ -40,8 +39,7 @@ function FeedbackModal({ onClose }: { onClose: () => void }): JSX.Element {
})
.catch(() => {
console.error(`Failed to submit ${entityName}`);
toast.danger(`Failed to submit ${entityName}`, {
action: { label: 'Dismiss' },
toast.error(`Failed to submit ${entityName}`, {
position: 'top-right',
});
})
@@ -138,23 +136,14 @@ function FeedbackModal({ onClose }: { onClose: () => void }): JSX.Element {
Submit
</Button>
<div className="feedback-modal-content-footer-info-text">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text>
Have a specific issue?{' '}
<SignozButton
variant="link"
color="primary"
size="sm"
<Typography.Link
className="contact-support-link"
onClick={handleContactSupportClick}
>
Contact Support{' '}
</SignozButton>
</Typography.Link>
or{' '}
<a
href="https://signoz.io/docs/introduction/"
@@ -164,7 +153,7 @@ function FeedbackModal({ onClose }: { onClose: () => void }): JSX.Element {
>
Read our docs
</a>
</Typography>
</Typography.Text>
</div>
</div>
</div>

Some files were not shown because too many files have changed in this diff Show More