mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-16 21:31:05 +00:00
Compare commits
7 Commits
feat/input
...
feat/conde
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7892db471 | ||
|
|
59b8295da0 | ||
|
|
7360d79258 | ||
|
|
9aa7226130 | ||
|
|
573f197161 | ||
|
|
702919dd00 | ||
|
|
aff6346cc5 |
28
.github/workflows/e2eci.yaml
vendored
28
.github/workflows/e2eci.yaml
vendored
@@ -2,50 +2,44 @@ name: e2eci
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
- labeled
|
||||
merge_group:
|
||||
types:
|
||||
- checks_requested
|
||||
|
||||
# Labels other than safe-to-e2e get a group of their own, so they never cancel a running e2e.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event.action == 'labeled' && github.event.label.name != 'safe-to-e2e' && format('-{0}', github.run_id) || '' }}
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
changes:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'safe-to-e2e'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
e2e: ${{ steps.changes.outputs.e2e }}
|
||||
steps:
|
||||
- name: merge-queue-pass
|
||||
if: github.event_name == 'merge_group'
|
||||
run: echo "::notice::Merge queue run. E2E already gated the PR, so the required e2e check auto-passes."
|
||||
- name: changes
|
||||
id: changes
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
FORCE: ${{ github.event_name == 'merge_group' || contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
|
||||
FORCE: ${{ contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
|
||||
run: |
|
||||
if [ "$FORCE" = "true" ]; then
|
||||
echo "e2e=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
CHANGED_FILES=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files" --paginate --jq '.[].filename | select((startswith("tests/integration/") or startswith("frontend/src/api/generated/")) | not)')
|
||||
PATTERN='^(frontend/|tests/|\.github/workflows/e2eci\.yaml$|cmd/enterprise/Dockerfile\.with-web\.integration$)'
|
||||
|
||||
if printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
|
||||
if [ "$FORCE" = "true" ]; then
|
||||
echo "e2e=true" >> "$GITHUB_OUTPUT"
|
||||
elif printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
|
||||
echo "e2e=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "e2e=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
fmtlint:
|
||||
needs: changes
|
||||
if: github.event_name != 'merge_group' && needs.changes.outputs.e2e == 'true'
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
@@ -186,8 +180,6 @@ jobs:
|
||||
retention-days: 5
|
||||
# Required status check. Fails when e2e was needed but did not pass.
|
||||
e2e:
|
||||
# Runs for other labels must not report as e2e, or their pass would hide the real result.
|
||||
name: ${{ github.event.action == 'labeled' && github.event.label.name != 'safe-to-e2e' && 'ignored-label' || 'e2e' }}
|
||||
if: always()
|
||||
needs: [changes, fmtlint, test]
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
23
.github/workflows/jsci.yaml
vendored
23
.github/workflows/jsci.yaml
vendored
@@ -132,26 +132,3 @@ jobs:
|
||||
run: |
|
||||
cd frontend && pnpm generate:config:web-settings
|
||||
git diff --compact-summary --exit-code || (echo; echo "Unexpected difference in generated web settings types. Run pnpm generate:config:web-settings in frontend/ locally and commit."; exit 1)
|
||||
geo-outlines:
|
||||
if: |
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: node-install
|
||||
uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: install-pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- name: install-frontend
|
||||
run: cd frontend && pnpm install
|
||||
- name: generate-geo-outlines
|
||||
run: |
|
||||
cd frontend && pnpm build:geo-outlines
|
||||
git status --short
|
||||
test -z "$(git status --porcelain)" || (echo; echo "Unexpected difference in geo map outlines. Run pnpm build:geo-outlines in frontend/ locally and commit."; exit 1)
|
||||
|
||||
@@ -16,6 +16,14 @@ packages:
|
||||
filename: "maintenance.go"
|
||||
structname: 'Mock{{.InterfaceName}}'
|
||||
pkgname: '{{.SrcPackageName}}test'
|
||||
github.com/SigNoz/signoz/pkg/types/condensedmetertypes:
|
||||
interfaces:
|
||||
Store:
|
||||
config:
|
||||
dir: '{{.InterfaceDir}}/condensedmetertypestest'
|
||||
filename: "store.go"
|
||||
structname: 'Mock{{.InterfaceName}}'
|
||||
pkgname: '{{.SrcPackageName}}test'
|
||||
github.com/SigNoz/signoz/pkg/types/telemetrytypes:
|
||||
interfaces:
|
||||
SchemaMetadataStore:
|
||||
|
||||
35
cmd/authz.go
35
cmd/authz.go
@@ -30,7 +30,7 @@ export default {
|
||||
],
|
||||
relations: {
|
||||
{{- range .Relations }}
|
||||
{{ .FormattedTypes }}
|
||||
{{ .Verb }}: [{{ range $i, $t := .Types }}{{ if $i }}, {{ end }}'{{ $t }}'{{ end }}],
|
||||
{{- end }}
|
||||
},
|
||||
},
|
||||
@@ -38,8 +38,8 @@ export default {
|
||||
`))
|
||||
|
||||
type permissionsTypeRelation struct {
|
||||
Verb string
|
||||
FormattedTypes string
|
||||
Verb string
|
||||
Types []string
|
||||
}
|
||||
|
||||
type permissionsTypeResource struct {
|
||||
@@ -77,29 +77,6 @@ func formatAllowedVerbs(verbs []string, indentLevel int, printWidth int) string
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// formatRelationTypes returns a prettier-compatible formatted `verb: [...]` line, wrapping
|
||||
// one type per line when it exceeds printWidth (tabWidth assumed to be 1).
|
||||
func formatRelationTypes(verb string, types []string, indentLevel int, printWidth int) string {
|
||||
quoted := make([]string, len(types))
|
||||
for i, t := range types {
|
||||
quoted[i] = "'" + t + "'"
|
||||
}
|
||||
indent := strings.Repeat("\t", indentLevel)
|
||||
|
||||
oneLine := indent + verb + ": [" + strings.Join(quoted, ", ") + "],"
|
||||
if len(oneLine) <= printWidth {
|
||||
return oneLine
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString(indent + verb + ": [\n")
|
||||
for _, q := range quoted {
|
||||
b.WriteString(indent + "\t" + q + ",\n")
|
||||
}
|
||||
b.WriteString(indent + "],")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func registerGenerateAuthz(parentCmd *cobra.Command) {
|
||||
authzCmd := &cobra.Command{
|
||||
Use: "authz",
|
||||
@@ -129,8 +106,6 @@ func runGenerateAuthz(_ context.Context) error {
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceQuickFilter).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceSavedView).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceNotificationChannel).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceUser).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorPassword).String(): true,
|
||||
}
|
||||
|
||||
allowedTypes := map[string]bool{}
|
||||
@@ -179,8 +154,8 @@ func runGenerateAuthz(_ context.Context) error {
|
||||
types = append(types, t.StringValue())
|
||||
}
|
||||
relations = append(relations, permissionsTypeRelation{
|
||||
Verb: verb.StringValue(),
|
||||
FormattedTypes: formatRelationTypes(verb.StringValue(), types, 3, 80),
|
||||
Verb: verb.StringValue(),
|
||||
Types: types,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/SigNoz/signoz/pkg/authz/openfgaschema"
|
||||
"github.com/SigNoz/signoz/pkg/authz/openfgaserver"
|
||||
"github.com/SigNoz/signoz/pkg/cache"
|
||||
"github.com/SigNoz/signoz/pkg/condensedmeter"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/flagger"
|
||||
@@ -121,6 +122,9 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
|
||||
func(_ context.Context, _ factory.ProviderSettings, _ flagger.Flagger, _ licensing.Licensing, _ telemetrystore.TelemetryStore, _ retention.Getter, _ organization.Getter, _ zeus.Zeus) (factory.NamedMap[factory.ProviderFactory[meterreporter.Reporter, meterreporter.Config]], string) {
|
||||
return signoz.NewMeterReporterProviderFactories(), "noop"
|
||||
},
|
||||
func(_ flagger.Flagger, _ licensing.Licensing, _ organization.Getter, _ telemetrystore.TelemetryStore, _ sqlstore.SQLStore) factory.NamedMap[factory.ProviderFactory[condensedmeter.Reporter, condensedmeter.Config]] {
|
||||
return signoz.NewCondensedMeterProviderFactories()
|
||||
},
|
||||
func(ps factory.ProviderSettings, q querier.Querier, a analytics.Analytics) querier.Handler {
|
||||
return querier.NewHandler(ps, q, a)
|
||||
},
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/SigNoz/signoz/ee/authz/openfgaauthz"
|
||||
"github.com/SigNoz/signoz/ee/authz/openfgaschema"
|
||||
"github.com/SigNoz/signoz/ee/authz/openfgaserver"
|
||||
"github.com/SigNoz/signoz/ee/condensedmeter/kafkacondensedmeter"
|
||||
"github.com/SigNoz/signoz/ee/gateway/httpgateway"
|
||||
enterpriselicensing "github.com/SigNoz/signoz/ee/licensing"
|
||||
"github.com/SigNoz/signoz/ee/licensing/httplicensing"
|
||||
@@ -38,6 +39,7 @@ import (
|
||||
"github.com/SigNoz/signoz/pkg/authn"
|
||||
"github.com/SigNoz/signoz/pkg/authz"
|
||||
"github.com/SigNoz/signoz/pkg/cache"
|
||||
"github.com/SigNoz/signoz/pkg/condensedmeter"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
pkgflagger "github.com/SigNoz/signoz/pkg/flagger"
|
||||
@@ -176,6 +178,13 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
|
||||
|
||||
return factories, "http"
|
||||
},
|
||||
func(flagger pkgflagger.Flagger, licensing licensing.Licensing, orgGetter organization.Getter, telemetryStore telemetrystore.TelemetryStore, sqlstore sqlstore.SQLStore) factory.NamedMap[factory.ProviderFactory[condensedmeter.Reporter, condensedmeter.Config]] {
|
||||
factories := signoz.NewCondensedMeterProviderFactories()
|
||||
if err := factories.Add(kafkacondensedmeter.NewFactory(flagger, licensing, orgGetter, telemetryStore, sqlstore, version.Info)); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return factories
|
||||
},
|
||||
func(ps factory.ProviderSettings, q querier.Querier, a analytics.Analytics) querier.Handler {
|
||||
communityHandler := querier.NewHandler(ps, q, a)
|
||||
return eequerier.NewHandler(ps, q, communityHandler)
|
||||
|
||||
@@ -522,3 +522,30 @@ meterreporter:
|
||||
# interval - random(0, jitter). Must be between 10m and interval. Defaults to
|
||||
# min(interval, 2h) when unset.
|
||||
jitter: 2h
|
||||
|
||||
##################### Condensed Meter #####################
|
||||
condensedmeter:
|
||||
# Specifies the condensed meter provider to use.
|
||||
# noop: reports nothing (community default).
|
||||
# kafka: sends the hourly count of condensed metric rows to a Kafka topic as OTLP protobuf (enterprise).
|
||||
provider: noop
|
||||
# How often closed hours are looked for. Minimum 10m, maximum 1h.
|
||||
interval: 1h
|
||||
# The meter connector's dimensions. Condensed rows are split by them like every other meter row.
|
||||
dimensions:
|
||||
- service.name
|
||||
- deployment.environment
|
||||
- host.name
|
||||
- signoz.workspace.key.id
|
||||
# The maximum number of data points per Kafka record.
|
||||
batch_size: 100
|
||||
kafka:
|
||||
# The seed broker addresses (host:port) used to discover the cluster.
|
||||
brokers:
|
||||
- localhost:9092
|
||||
# The topic condensed rows are written to. It must already exist.
|
||||
topic: ""
|
||||
# The client id the producer reports to the brokers.
|
||||
client_id: signoz
|
||||
# The compression codec for produced batches: none, gzip, snappy, lz4 or zstd.
|
||||
compression: lz4
|
||||
|
||||
@@ -4318,11 +4318,6 @@ components:
|
||||
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
|
||||
fixed window.'
|
||||
type: object
|
||||
DashboardtypesBubbleRadius:
|
||||
maximum: 64
|
||||
minimum: 1
|
||||
nullable: true
|
||||
type: integer
|
||||
DashboardtypesBuilderQuerySpec:
|
||||
discriminator:
|
||||
mapping:
|
||||
@@ -4555,231 +4550,6 @@ components:
|
||||
minimum: 0
|
||||
nullable: true
|
||||
type: number
|
||||
DashboardtypesGeoMapBubbles:
|
||||
properties:
|
||||
maxRadius:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesBubbleRadius'
|
||||
description: Radius of the largest circle, in CSS pixels from 1 to 64. Null
|
||||
means 8 on the points layer, 28 otherwise.
|
||||
minRadius:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesBubbleRadius'
|
||||
description: Radius of the smallest circle, in CSS pixels from 1 to 64.
|
||||
Null means 2 on the points layer, 3 otherwise.
|
||||
type: object
|
||||
DashboardtypesGeoMapChartAppearance:
|
||||
properties:
|
||||
bubbles:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapBubbles'
|
||||
description: The circle radius range of the bubbles and points layers.
|
||||
colors:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapColors'
|
||||
description: The color scale applied to the colorBy values.
|
||||
labels:
|
||||
description: Shows country and state names once each fits inside its shape.
|
||||
Null shows them.
|
||||
nullable: true
|
||||
type: boolean
|
||||
type: object
|
||||
DashboardtypesGeoMapColors:
|
||||
properties:
|
||||
fill:
|
||||
description: The hex color varied in opacity mode. Empty uses the default
|
||||
fill.
|
||||
type: string
|
||||
max:
|
||||
description: The value mapped to the highest color. Null uses the highest
|
||||
value in the data.
|
||||
nullable: true
|
||||
type: number
|
||||
min:
|
||||
description: The value mapped to the lowest color. Null uses the lowest
|
||||
value in the data. Must not exceed max.
|
||||
nullable: true
|
||||
type: number
|
||||
mode:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesHeatmapColorMode'
|
||||
description: 'How values are colored: palette (default) picks a hue from
|
||||
palette, opacity varies the opacity of fill.'
|
||||
palette:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesHeatmapPalette'
|
||||
description: The named color ramp used in palette mode, such as lava (default),
|
||||
ice or ember.
|
||||
scale:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesHeatmapColorScale'
|
||||
description: 'How values map onto the color range: log (default), sqrt or
|
||||
linear.'
|
||||
steps:
|
||||
description: The number of distinct color steps, 2 to 128. 0 uses the chart
|
||||
default.
|
||||
type: integer
|
||||
type: object
|
||||
DashboardtypesGeoMapCountryFormat:
|
||||
enum:
|
||||
- auto
|
||||
- alpha2
|
||||
- alpha3
|
||||
- name
|
||||
type: string
|
||||
DashboardtypesGeoMapLayer:
|
||||
enum:
|
||||
- regions
|
||||
- bubbles
|
||||
- points
|
||||
type: string
|
||||
DashboardtypesGeoMapLocation:
|
||||
properties:
|
||||
country:
|
||||
description: Group-by key holding the country, for the country and subdivision
|
||||
modes. Empty detects it by name, such as geo.country.iso_code.
|
||||
type: string
|
||||
countryFormat:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapCountryFormat'
|
||||
description: 'How country values are written: auto (default) detects it,
|
||||
alpha2, alpha3 or name.'
|
||||
lat:
|
||||
description: Group-by key holding the latitude, for the coordinates mode.
|
||||
Empty detects it by name.
|
||||
type: string
|
||||
lon:
|
||||
description: Group-by key holding the longitude, for the coordinates mode.
|
||||
Empty detects it by name.
|
||||
type: string
|
||||
mode:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapLocationMode'
|
||||
description: 'How rows are placed: auto (default) detects it from the group-by
|
||||
keys, country, subdivision or coordinates.'
|
||||
region:
|
||||
description: Group-by key holding the ISO 3166-2 region code (e.g. geo.region.iso_code),
|
||||
for the subdivision mode. Empty detects it by name.
|
||||
type: string
|
||||
required:
|
||||
- mode
|
||||
- countryFormat
|
||||
type: object
|
||||
DashboardtypesGeoMapLocationMode:
|
||||
enum:
|
||||
- auto
|
||||
- country
|
||||
- subdivision
|
||||
- coordinates
|
||||
type: string
|
||||
DashboardtypesGeoMapPanelSpec:
|
||||
properties:
|
||||
chartAppearance:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapChartAppearance'
|
||||
description: Color scale, bubble size and labels.
|
||||
formatting:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesTableFormatting'
|
||||
description: Per-column units and decimal precision.
|
||||
legend:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesLegend'
|
||||
description: Legend placement.
|
||||
location:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapLocation'
|
||||
description: The group-by columns that place each row on the map.
|
||||
map:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapSettings'
|
||||
description: Layer, view, projection and the value columns drawn.
|
||||
thresholds:
|
||||
description: Rules that recolor a shape, bubble or point when its value
|
||||
compares to a threshold as specified.
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesGeoMapThreshold'
|
||||
nullable: true
|
||||
type: array
|
||||
visualization:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesBasicVisualization'
|
||||
description: The time range the values are computed over.
|
||||
type: object
|
||||
DashboardtypesGeoMapProjection:
|
||||
enum:
|
||||
- mercator
|
||||
- equal_earth
|
||||
- natural_earth
|
||||
type: string
|
||||
DashboardtypesGeoMapSettings:
|
||||
properties:
|
||||
colorBy:
|
||||
description: Value column key, as in a Table panel, that sets the color.
|
||||
Empty uses the first value column.
|
||||
type: string
|
||||
layer:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapLayer'
|
||||
description: 'What is drawn: regions (default) fills each shape, bubbles
|
||||
draws a circle per region, points a circle per coordinate.'
|
||||
projection:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapProjection'
|
||||
description: 'The map projection: mercator (default), equal_earth or natural_earth.'
|
||||
sizeBy:
|
||||
description: Value column key, as in a Table panel, that sets the bubble
|
||||
or point size. Empty uses colorBy.
|
||||
type: string
|
||||
view:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapView'
|
||||
description: 'The area shown: world (default), fit to the data, a continent,
|
||||
or country with viewCountry.'
|
||||
viewCountry:
|
||||
description: Uppercase ISO 3166-1 alpha-2 code of the country the country
|
||||
view shows.
|
||||
type: string
|
||||
required:
|
||||
- layer
|
||||
- view
|
||||
- projection
|
||||
type: object
|
||||
DashboardtypesGeoMapThreshold:
|
||||
properties:
|
||||
color:
|
||||
description: 'The CSS color of the shape, bubble or point while the threshold
|
||||
is active, for example #F1575F; CSS named colors such as red also work.'
|
||||
type: string
|
||||
operator:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesComparisonOperator'
|
||||
description: 'The comparison that activates the threshold: above (default),
|
||||
below, above_or_equal, below_or_equal, equal or not_equal.'
|
||||
unit:
|
||||
description: The unit id of value, such as ms or percent. Empty means the
|
||||
colorBy column's unit.
|
||||
type: string
|
||||
value:
|
||||
description: The value compared against, in unit.
|
||||
format: double
|
||||
type: number
|
||||
required:
|
||||
- value
|
||||
- color
|
||||
type: object
|
||||
DashboardtypesGeoMapView:
|
||||
enum:
|
||||
- world
|
||||
- fit
|
||||
- africa
|
||||
- asia
|
||||
- europe
|
||||
- north_america
|
||||
- south_america
|
||||
- oceania
|
||||
- country
|
||||
type: string
|
||||
DashboardtypesGettableDashboardV2:
|
||||
properties:
|
||||
createdAt:
|
||||
@@ -5517,7 +5287,6 @@ components:
|
||||
mapping:
|
||||
signoz/AreaChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec'
|
||||
signoz/BarChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
|
||||
signoz/GeoMapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
|
||||
signoz/HeatmapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
|
||||
signoz/HistogramPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
|
||||
signoz/ListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec'
|
||||
@@ -5540,7 +5309,6 @@ components:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
|
||||
type: object
|
||||
DashboardtypesPanelPluginKind:
|
||||
enum:
|
||||
@@ -5555,7 +5323,6 @@ components:
|
||||
- signoz/TextPanel
|
||||
- signoz/HeatmapPanel
|
||||
- signoz/ScatterPlotPanel
|
||||
- signoz/GeoMapPanel
|
||||
type: string
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
|
||||
properties:
|
||||
@@ -5587,21 +5354,6 @@ components:
|
||||
- kind
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec:
|
||||
properties:
|
||||
kind:
|
||||
description: The panel kind.
|
||||
enum:
|
||||
- signoz/GeoMapPanel
|
||||
type: string
|
||||
spec:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesGeoMapPanelSpec'
|
||||
description: The options for this panel kind. {} accepts every default.
|
||||
required:
|
||||
- kind
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec:
|
||||
properties:
|
||||
kind:
|
||||
|
||||
97
ee/condensedmeter/kafkacondensedmeter/clickhouse.go
Normal file
97
ee/condensedmeter/kafkacondensedmeter/clickhouse.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package kafkacondensedmeter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/clickhousesql"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/telemetryschema/metertelemetryschema"
|
||||
"github.com/SigNoz/signoz/pkg/telemetryschema/metricstelemetryschema"
|
||||
"github.com/SigNoz/signoz/pkg/telemetrystore"
|
||||
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes"
|
||||
)
|
||||
|
||||
const metricNameMetricsDataPointsIngestedCount = "signoz.meter.metric.datapoint.ingested.count"
|
||||
|
||||
type clickhouseStore struct {
|
||||
telemetryStore telemetrystore.TelemetryStore
|
||||
}
|
||||
|
||||
func newClickhouseStore(telemetryStore telemetrystore.TelemetryStore) *clickhouseStore {
|
||||
return &clickhouseStore{telemetryStore: telemetryStore}
|
||||
}
|
||||
|
||||
// FirstIngested is the time of the first ingested meter row, zero when there is none yet.
|
||||
func (store *clickhouseStore) FirstIngested(ctx context.Context) (time.Time, error) {
|
||||
query := fmt.Sprintf("SELECT toInt64(ifNull(min(unix_milli), 0)) FROM %s.%s WHERE metric_name = ?", metertelemetryschema.DBName, metertelemetryschema.SamplesTableName)
|
||||
|
||||
var unixMilli int64
|
||||
if err := store.telemetryStore.ClickhouseDB().QueryRow(ctx, query, metricNameMetricsDataPointsIngestedCount).Scan(&unixMilli); err != nil {
|
||||
return time.Time{}, errors.WrapInternalf(err, errors.CodeInternal, "failed to query first ingested meter row")
|
||||
}
|
||||
|
||||
if unixMilli == 0 {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
|
||||
return time.UnixMilli(unixMilli), nil
|
||||
}
|
||||
|
||||
// CondensedRows counts distinct (reduced_fingerprint, minute) in both reduced tables, since the condensing views append each minute several times.
|
||||
// A minute never appears in both tables: gauges go to one and counters to the other.
|
||||
// Dimensions come from the reduced series; a condensed row without its series is still counted, without dimensions.
|
||||
func (store *clickhouseStore) CondensedRows(ctx context.Context, dimensions []string, hour time.Time) ([]condensedmetertypes.Row, error) {
|
||||
aliases := make([]string, len(dimensions))
|
||||
selects := make([]string, len(dimensions))
|
||||
for i, dimension := range dimensions {
|
||||
aliases[i] = clickhousesql.Identifier(fmt.Sprintf("dimension_%d", i))
|
||||
selects[i] = fmt.Sprintf("any(resource_attrs[%s]) AS %s", clickhousesql.StringLiteral(dimension), aliases[i])
|
||||
}
|
||||
|
||||
condensed := func(table string) string {
|
||||
return fmt.Sprintf("SELECT reduced_fingerprint, unix_milli FROM %s.%s WHERE unix_milli >= ? AND unix_milli < ? AND NOT match(metric_name, '^(signoz|otelcol)') GROUP BY reduced_fingerprint, unix_milli", metricstelemetryschema.DBName, table)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
"SELECT %s FROM (%s UNION ALL %s) AS condensed LEFT JOIN (SELECT %s FROM %s.%s WHERE unix_milli >= ? AND unix_milli < ? GROUP BY fingerprint) AS series ON condensed.reduced_fingerprint = series.fingerprint",
|
||||
strings.Join(append(aliases, "toUInt64(count())"), ", "),
|
||||
condensed(metricstelemetryschema.SamplesV4ReducedLastTableName),
|
||||
condensed(metricstelemetryschema.SamplesV4ReducedSumTableName),
|
||||
strings.Join(append([]string{"fingerprint"}, selects...), ", "),
|
||||
metricstelemetryschema.DBName,
|
||||
metricstelemetryschema.TimeseriesV4ReducedTableName,
|
||||
)
|
||||
if len(aliases) > 0 {
|
||||
query += " GROUP BY " + strings.Join(aliases, ", ")
|
||||
}
|
||||
|
||||
start, end := hour.UnixMilli(), hour.Add(time.Hour).UnixMilli()
|
||||
rows, err := store.telemetryStore.ClickhouseDB().Query(ctx, query, start, end, start, end, start, end)
|
||||
if err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to query condensed rows")
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
condensedRows := []condensedmetertypes.Row{}
|
||||
for rows.Next() {
|
||||
row := condensedmetertypes.Row{Values: make([]string, len(dimensions))}
|
||||
dest := make([]any, 0, len(dimensions)+1)
|
||||
for i := range row.Values {
|
||||
dest = append(dest, &row.Values[i])
|
||||
}
|
||||
dest = append(dest, &row.Count)
|
||||
|
||||
if err := rows.Scan(dest...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to scan condensed rows")
|
||||
}
|
||||
|
||||
if row.Count > 0 {
|
||||
condensedRows = append(condensedRows, row)
|
||||
}
|
||||
}
|
||||
|
||||
return condensedRows, rows.Err()
|
||||
}
|
||||
215
ee/condensedmeter/kafkacondensedmeter/provider.go
Normal file
215
ee/condensedmeter/kafkacondensedmeter/provider.go
Normal file
@@ -0,0 +1,215 @@
|
||||
package kafkacondensedmeter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"github.com/twmb/franz-go/plugin/kslog"
|
||||
"go.opentelemetry.io/collector/pdata/pmetric"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/condensedmeter"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/flagger"
|
||||
"github.com/SigNoz/signoz/pkg/licensing"
|
||||
"github.com/SigNoz/signoz/pkg/modules/organization"
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
"github.com/SigNoz/signoz/pkg/telemetrystore"
|
||||
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/featuretypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/SigNoz/signoz/pkg/version"
|
||||
)
|
||||
|
||||
var _ condensedmeter.Reporter = (*provider)(nil)
|
||||
|
||||
type provider struct {
|
||||
settings factory.ScopedProviderSettings
|
||||
config condensedmeter.Config
|
||||
flagger flagger.Flagger
|
||||
licensing licensing.Licensing
|
||||
orgGetter organization.Getter
|
||||
clickhouseStore *clickhouseStore
|
||||
store condensedmetertypes.Store
|
||||
build version.Build
|
||||
marshaler pmetric.ProtoMarshaler
|
||||
client *kgo.Client
|
||||
healthyC chan struct{}
|
||||
stopC chan struct{}
|
||||
}
|
||||
|
||||
func NewFactory(flagger flagger.Flagger, licensing licensing.Licensing, orgGetter organization.Getter, telemetryStore telemetrystore.TelemetryStore, sqlstore sqlstore.SQLStore, build version.Build) factory.ProviderFactory[condensedmeter.Reporter, condensedmeter.Config] {
|
||||
return factory.NewProviderFactory(factory.MustNewName("kafka"), func(ctx context.Context, providerSettings factory.ProviderSettings, config condensedmeter.Config) (condensedmeter.Reporter, error) {
|
||||
return newProvider(ctx, providerSettings, config, flagger, licensing, orgGetter, telemetryStore, newStore(sqlstore), build)
|
||||
})
|
||||
}
|
||||
|
||||
func newProvider(_ context.Context, providerSettings factory.ProviderSettings, config condensedmeter.Config, flagger flagger.Flagger, licensing licensing.Licensing, orgGetter organization.Getter, telemetryStore telemetrystore.TelemetryStore, store condensedmetertypes.Store, build version.Build) (*provider, error) {
|
||||
settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/ee/condensedmeter/kafkacondensedmeter")
|
||||
|
||||
// Acks from all in-sync replicas, idempotent writes and unbounded record retries are franz-go defaults and are kept as is.
|
||||
// A delivery timeout or retry limit lets franz-go < v1.22.2 ack a record that was never written (twmb/franz-go#1484).
|
||||
client, err := kgo.NewClient(
|
||||
kgo.SeedBrokers(config.Kafka.Brokers...),
|
||||
kgo.ClientID(config.Kafka.ClientID),
|
||||
kgo.ProducerBatchCompression(compressionCodec(config.Kafka.Compression)),
|
||||
kgo.ProducerLinger(0),
|
||||
kgo.WithLogger(kslog.New(settings.Logger())),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &provider{
|
||||
settings: settings,
|
||||
config: config,
|
||||
flagger: flagger,
|
||||
licensing: licensing,
|
||||
orgGetter: orgGetter,
|
||||
clickhouseStore: newClickhouseStore(telemetryStore),
|
||||
store: store,
|
||||
build: build,
|
||||
marshaler: pmetric.ProtoMarshaler{},
|
||||
client: client,
|
||||
healthyC: make(chan struct{}),
|
||||
stopC: make(chan struct{}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (provider *provider) Start(ctx context.Context) error {
|
||||
close(provider.healthyC)
|
||||
|
||||
ticker := time.NewTicker(provider.config.Interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
provider.report(ctx)
|
||||
for {
|
||||
select {
|
||||
case <-provider.stopC:
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
provider.report(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (provider *provider) Stop(_ context.Context) error {
|
||||
close(provider.stopC)
|
||||
provider.client.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (provider *provider) Healthy() <-chan struct{} {
|
||||
return provider.healthyC
|
||||
}
|
||||
|
||||
func (provider *provider) report(ctx context.Context) {
|
||||
orgs, err := provider.orgGetter.ListByOwnedKeyRange(ctx)
|
||||
if err != nil {
|
||||
provider.settings.Logger().ErrorContext(ctx, "failed to get orgs data", errors.Attr(err))
|
||||
return
|
||||
}
|
||||
|
||||
for _, org := range orgs {
|
||||
if !provider.flagger.BooleanOrEmpty(ctx, flagger.FeatureEnableMetricsReduction, featuretypes.NewFlaggerEvaluationContext(org.ID)) {
|
||||
continue
|
||||
}
|
||||
|
||||
if _, err := provider.licensing.GetActive(ctx, org.ID); err != nil {
|
||||
if errors.Ast(err, errors.TypeNotFound) {
|
||||
continue
|
||||
}
|
||||
|
||||
provider.settings.Logger().ErrorContext(ctx, "failed to fetch active license for org", errors.Attr(err), slog.String("org_id", org.ID.StringValue()))
|
||||
return
|
||||
}
|
||||
|
||||
if err := provider.reportOrg(ctx, org.ID, time.Now()); err != nil {
|
||||
provider.settings.Logger().ErrorContext(ctx, "failed to report condensed rows", errors.Attr(err), slog.String("org_id", org.ID.StringValue()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (provider *provider) reportOrg(ctx context.Context, orgID valuer.UUID, now time.Time) error {
|
||||
next, err := provider.nextHour(ctx, orgID)
|
||||
if err != nil || next.IsZero() {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, hour := range condensedmetertypes.ClosedHours(next, now) {
|
||||
rows, err := provider.clickhouseStore.CondensedRows(ctx, provider.config.Dimensions, hour)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(rows) > 0 {
|
||||
if err := provider.send(ctx, rows, now); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := provider.store.Upsert(ctx, condensedmetertypes.NewCheckpoint(orgID, hour)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// nextHour is the hour after the checkpoint, or the first hour after the first ingested meter row; zero when there is none yet.
|
||||
func (provider *provider) nextHour(ctx context.Context, orgID valuer.UUID) (time.Time, error) {
|
||||
checkpoint, err := provider.store.Get(ctx, orgID)
|
||||
if err == nil {
|
||||
return checkpoint.LastReportedHour.UTC().Add(time.Hour), nil
|
||||
}
|
||||
|
||||
if !errors.Ast(err, errors.TypeNotFound) {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
firstIngested, err := provider.clickhouseStore.FirstIngested(ctx)
|
||||
if err != nil || firstIngested.IsZero() {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
return condensedmetertypes.FirstHour(firstIngested), nil
|
||||
}
|
||||
|
||||
// send stamps the points with the send time, not the hour they count, so an hour reported after its day is sealed lands in the next day instead of being missed.
|
||||
func (provider *provider) send(ctx context.Context, rows []condensedmetertypes.Row, timestamp time.Time) error {
|
||||
batchSize := provider.config.BatchSize
|
||||
records := make([]*kgo.Record, 0, (len(rows)+batchSize-1)/batchSize)
|
||||
for start := 0; start < len(rows); start += batchSize {
|
||||
metrics := condensedmetertypes.NewPMetrics(rows[start:min(start+batchSize, len(rows))], provider.config.Dimensions, timestamp, "signoz", provider.build.Version())
|
||||
|
||||
value, err := provider.marshaler.MarshalMetrics(metrics)
|
||||
if err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "failed to marshal condensed rows")
|
||||
}
|
||||
|
||||
records = append(records, &kgo.Record{Topic: provider.config.Kafka.Topic, Value: value})
|
||||
}
|
||||
|
||||
if err := provider.client.ProduceSync(ctx, records...).FirstErr(); err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "failed to send condensed rows")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func compressionCodec(name string) kgo.CompressionCodec {
|
||||
switch name {
|
||||
case "gzip":
|
||||
return kgo.GzipCompression()
|
||||
case "snappy":
|
||||
return kgo.SnappyCompression()
|
||||
case "lz4":
|
||||
return kgo.Lz4Compression()
|
||||
case "zstd":
|
||||
return kgo.ZstdCompression()
|
||||
default:
|
||||
return kgo.NoCompression()
|
||||
}
|
||||
}
|
||||
176
ee/condensedmeter/kafkacondensedmeter/provider_test.go
Normal file
176
ee/condensedmeter/kafkacondensedmeter/provider_test.go
Normal file
@@ -0,0 +1,176 @@
|
||||
package kafkacondensedmeter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
cmock "github.com/SigNoz/clickhouse-go-mock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/twmb/franz-go/pkg/kfake"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"go.opentelemetry.io/collector/pdata/pmetric"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/condensedmeter"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
|
||||
"github.com/SigNoz/signoz/pkg/telemetrystore"
|
||||
"github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"
|
||||
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes/condensedmetertypestest"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/SigNoz/signoz/pkg/version"
|
||||
)
|
||||
|
||||
// Polls the topic until it has wantRecords records or the timeout passes.
|
||||
func consumeMetrics(t *testing.T, brokers []string, topic string, wantRecords int, timeout time.Duration) []pmetric.Metrics {
|
||||
t.Helper()
|
||||
|
||||
client, err := kgo.NewClient(
|
||||
kgo.SeedBrokers(brokers...),
|
||||
kgo.ConsumeTopics(topic),
|
||||
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
metrics := []pmetric.Metrics{}
|
||||
for len(metrics) < wantRecords && ctx.Err() == nil {
|
||||
for _, record := range client.PollFetches(ctx).Records() {
|
||||
recordMetrics, err := (&pmetric.ProtoUnmarshaler{}).UnmarshalMetrics(record.Value)
|
||||
require.NoError(t, err)
|
||||
metrics = append(metrics, recordMetrics)
|
||||
}
|
||||
}
|
||||
|
||||
return metrics
|
||||
}
|
||||
|
||||
func TestReportOrg(t *testing.T) {
|
||||
orgID := valuer.GenerateUUID()
|
||||
now := time.Date(2026, 11, 12, 13, 30, 0, 0, time.UTC)
|
||||
checkpointHour := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)
|
||||
// 11:00 is closed at 13:30 (11:00 + 2h = 13:00); 12:00 is not (14:00)
|
||||
reportedHour := time.Date(2026, 11, 12, 11, 0, 0, 0, time.UTC)
|
||||
notFound := errors.New(errors.TypeNotFound, condensedmetertypes.ErrCodeCheckpointNotFound, "no checkpoint")
|
||||
condensedColumns := []cmock.ColumnType{{Name: "dimension_0", Type: "String"}, {Name: "dimension_1", Type: "String"}, {Name: "count", Type: "UInt64"}}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
checkpoint *condensedmetertypes.Checkpoint
|
||||
firstIngestedMs int64
|
||||
condensedRows [][]any
|
||||
condensedErr error
|
||||
expectedUpsert *time.Time
|
||||
expectedRecords int
|
||||
expectedDataPoint []int64
|
||||
expectedErr bool
|
||||
}{
|
||||
{
|
||||
name: "NoCheckpointNoIngestedRows_NothingReported",
|
||||
firstIngestedMs: 0,
|
||||
},
|
||||
{
|
||||
name: "Checkpoint_ClosedHourSentAndCheckpointAdvanced",
|
||||
checkpoint: condensedmetertypes.NewCheckpoint(orgID, checkpointHour),
|
||||
condensedRows: [][]any{{"frontend", "host-1", uint64(31)}, {"checkout", "", uint64(4)}},
|
||||
expectedUpsert: &reportedHour,
|
||||
expectedRecords: 1,
|
||||
expectedDataPoint: []int64{31, 4},
|
||||
},
|
||||
{
|
||||
name: "Checkpoint_LargeHourSplitAcrossRecords",
|
||||
checkpoint: condensedmetertypes.NewCheckpoint(orgID, checkpointHour),
|
||||
condensedRows: [][]any{{"frontend", "host-1", uint64(31)}, {"checkout", "", uint64(4)}, {"cart", "host-2", uint64(9)}},
|
||||
expectedUpsert: &reportedHour,
|
||||
expectedRecords: 2,
|
||||
expectedDataPoint: []int64{31, 4, 9},
|
||||
},
|
||||
{
|
||||
name: "Checkpoint_EmptyHourNotSentCheckpointAdvanced",
|
||||
checkpoint: condensedmetertypes.NewCheckpoint(orgID, checkpointHour),
|
||||
condensedRows: [][]any{},
|
||||
expectedUpsert: &reportedHour,
|
||||
},
|
||||
{
|
||||
name: "Checkpoint_QueryFails_CheckpointNotAdvanced",
|
||||
checkpoint: condensedmetertypes.NewCheckpoint(orgID, checkpointHour),
|
||||
condensedErr: errors.New(errors.TypeInternal, errors.CodeInternal, "clickhouse down"),
|
||||
expectedErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
cluster, err := kfake.NewCluster(kfake.NumBrokers(1), kfake.SeedTopics(1, "tenant_meter"))
|
||||
require.NoError(t, err)
|
||||
defer cluster.Close()
|
||||
|
||||
telemetryStore := telemetrystoretest.New(telemetrystore.Config{}, sqlmock.QueryMatcherRegexp)
|
||||
store := condensedmetertypestest.NewMockStore(t)
|
||||
if testCase.checkpoint != nil {
|
||||
store.EXPECT().Get(mock.Anything, orgID).Return(testCase.checkpoint, nil)
|
||||
} else {
|
||||
store.EXPECT().Get(mock.Anything, orgID).Return(nil, notFound)
|
||||
telemetryStore.Mock().ExpectQueryRow(regexp.QuoteMeta("min(unix_milli)")).
|
||||
WillReturnRow(cmock.NewRow([]cmock.ColumnType{{Name: "min", Type: "Int64"}}, []any{testCase.firstIngestedMs}))
|
||||
}
|
||||
|
||||
if testCase.condensedRows != nil || testCase.condensedErr != nil {
|
||||
query := telemetryStore.Mock().ExpectQuery(regexp.QuoteMeta("distributed_time_series_v4_reduced")).
|
||||
WithArgs(reportedHour.UnixMilli(), reportedHour.Add(time.Hour).UnixMilli(), reportedHour.UnixMilli(), reportedHour.Add(time.Hour).UnixMilli(), reportedHour.UnixMilli(), reportedHour.Add(time.Hour).UnixMilli())
|
||||
if testCase.condensedErr != nil {
|
||||
query.WillReturnError(testCase.condensedErr)
|
||||
} else {
|
||||
query.WillReturnRows(cmock.NewRows(condensedColumns, testCase.condensedRows))
|
||||
}
|
||||
}
|
||||
|
||||
if testCase.expectedUpsert != nil {
|
||||
store.EXPECT().Upsert(mock.Anything, mock.MatchedBy(func(checkpoint *condensedmetertypes.Checkpoint) bool {
|
||||
return checkpoint.OrgID == orgID && checkpoint.LastReportedHour.Equal(*testCase.expectedUpsert)
|
||||
})).Return(nil)
|
||||
}
|
||||
|
||||
config := condensedmeter.Config{
|
||||
Provider: "kafka",
|
||||
Interval: time.Hour,
|
||||
Dimensions: []string{"service.name", "host.name"},
|
||||
BatchSize: 2,
|
||||
Kafka: condensedmeter.KafkaConfig{Brokers: cluster.ListenAddrs(), Topic: "tenant_meter", ClientID: "signoz-test", Compression: "none"},
|
||||
}
|
||||
provider, err := newProvider(context.Background(), instrumentationtest.New().ToProviderSettings(), config, nil, nil, nil, telemetryStore, store, version.Info)
|
||||
require.NoError(t, err)
|
||||
defer provider.client.Close()
|
||||
|
||||
err = provider.reportOrg(context.Background(), orgID, now)
|
||||
if testCase.expectedErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
assert.NoError(t, telemetryStore.Mock().ExpectationsWereMet())
|
||||
|
||||
metrics := consumeMetrics(t, cluster.ListenAddrs(), "tenant_meter", testCase.expectedRecords+1, 500*time.Millisecond)
|
||||
require.Len(t, metrics, testCase.expectedRecords)
|
||||
|
||||
dataPoints := []int64{}
|
||||
for _, recordMetrics := range metrics {
|
||||
points := recordMetrics.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Sum().DataPoints()
|
||||
for i := 0; i < points.Len(); i++ {
|
||||
dataPoints = append(dataPoints, points.At(i).IntValue())
|
||||
assert.Equal(t, now, points.At(i).Timestamp().AsTime())
|
||||
}
|
||||
}
|
||||
assert.ElementsMatch(t, testCase.expectedDataPoint, dataPoints)
|
||||
})
|
||||
}
|
||||
}
|
||||
43
ee/condensedmeter/kafkacondensedmeter/store.go
Normal file
43
ee/condensedmeter/kafkacondensedmeter/store.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package kafkacondensedmeter
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
type store struct {
|
||||
sqlstore sqlstore.SQLStore
|
||||
}
|
||||
|
||||
func newStore(sqlstore sqlstore.SQLStore) condensedmetertypes.Store {
|
||||
return &store{sqlstore: sqlstore}
|
||||
}
|
||||
|
||||
func (store *store) Get(ctx context.Context, orgID valuer.UUID) (*condensedmetertypes.Checkpoint, error) {
|
||||
checkpoint := new(condensedmetertypes.Checkpoint)
|
||||
err := store.sqlstore.
|
||||
BunDBCtx(ctx).
|
||||
NewSelect().
|
||||
Model(checkpoint).
|
||||
Where("org_id = ?", orgID).
|
||||
Scan(ctx)
|
||||
if err != nil {
|
||||
return nil, store.sqlstore.WrapNotFoundErrf(err, condensedmetertypes.ErrCodeCheckpointNotFound, "no condensed meter checkpoint found for org %q", orgID.StringValue())
|
||||
}
|
||||
return checkpoint, nil
|
||||
}
|
||||
|
||||
func (store *store) Upsert(ctx context.Context, checkpoint *condensedmetertypes.Checkpoint) error {
|
||||
_, err := store.sqlstore.
|
||||
BunDBCtx(ctx).
|
||||
NewInsert().
|
||||
Model(checkpoint).
|
||||
On("CONFLICT (org_id) DO UPDATE").
|
||||
Set("last_reported_hour = EXCLUDED.last_reported_hour").
|
||||
Set("updated_at = EXCLUDED.updated_at").
|
||||
Exec(ctx)
|
||||
return err
|
||||
}
|
||||
@@ -8,5 +8,5 @@
|
||||
|
||||
.title {
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--label-large-400-font-size);
|
||||
font-size: var(--font-size-lg);
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -45,8 +45,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`,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -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" />
|
||||
|
||||
|
||||
@@ -192,7 +192,6 @@ const preview: Preview = {
|
||||
'Role Details',
|
||||
'Role Editor',
|
||||
'Members',
|
||||
['Overview', 'Authz'],
|
||||
'Service Accounts',
|
||||
'Ingestion',
|
||||
'Single Sign-on',
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
/*
|
||||
* The four 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 four families `src/styles.scss` imports at
|
||||
* runtime. Inter comes from `src/styles.scss` itself.
|
||||
* 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');
|
||||
|
||||
@@ -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: [
|
||||
{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
# Popover migration analysis
|
||||
|
||||
The new `@signozhq/ui` Popover is click-only. This note maps the current app onto that API so a later migration does not break open state, focus, or the global `.ant-popover` overrides. It does not change any call site.
|
||||
|
||||
The component this describes lives in the design-system repo (`packages/ui/src/popover`). Storybook stories for it are `Playground`, `SaveViewForm`, `ControlledOpen`, `InsideDialog`, `MaxHeightScrolling`, and `AnchoredTypeahead`.
|
||||
|
||||
## The API to migrate onto
|
||||
|
||||
```tsx
|
||||
<Popover
|
||||
nativeButton
|
||||
side="bottom"
|
||||
align="start"
|
||||
trigger={<button type="button">Open</button>}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
{content}
|
||||
</Popover>
|
||||
```
|
||||
|
||||
| Today | New Popover |
|
||||
| --- | --- |
|
||||
| antd `children` (the trigger) | `trigger` (required) |
|
||||
| antd `content`, or Radix `<PopoverContent>` | `children` |
|
||||
| antd `trigger="click"` | the only mode; there is no `openOn` |
|
||||
| antd `trigger="hover"` | not this component; a Tooltip, or a click popover when the body is interactive |
|
||||
| `placement="bottomRight"` | `side="bottom"` `align="end"` |
|
||||
| `placement="bottomLeft"` | `side="bottom"` `align="start"` |
|
||||
| `open` / `onOpenChange` | kept; `onOpenChange` receives Base UI's reason and `details.cancel()` |
|
||||
| `defaultOpen` | removed; nothing in the app starts open |
|
||||
| `overlayClassName`, `overlayStyle`, `overlayInnerStyle`, `className` | rejected on the shell; size is `width` / `maxWidth` / `maxHeight` |
|
||||
| `getPopupContainer` | `container` |
|
||||
| `destroyTooltipOnHide` | the only behavior; the popup unmounts on close |
|
||||
| `arrow` / `showArrow` | rejected; the shell has no arrow |
|
||||
| Radix `PopoverAnchor` | `anchor`, and the trigger is still required |
|
||||
| Radix `withPortal={false}` | `container` (inside a Dialog the popup already portals into the panel) |
|
||||
| Radix `onInteractOutside` | `onOpenChange` + `details.cancel()` when `reason === 'outside-press'` |
|
||||
| `sideOffset` / `alignOffset` | not props; fixed at 4px and 0 |
|
||||
|
||||
`nativeButton` is required. `true` when `trigger` renders a `<button>` (including `Button`). `false` for anything else.
|
||||
|
||||
A node that renders nothing (`null`, `false`, `''`) renders the trigger alone, with no listeners and no portal.
|
||||
|
||||
## What is in the app today
|
||||
|
||||
Counted from `frontend/src` on this branch:
|
||||
|
||||
- **29 files** import `Popover` from `antd`.
|
||||
- **7 files** import `Popover` from `@signozhq/ui` (the Radix wrapper this rework replaces). Those seven break as soon as the package ships, because `children` stops being the trigger.
|
||||
- **18 SCSS files** override `.ant-popover*`.
|
||||
|
||||
antd `Dropdown` is already on `@signozhq/ui/dropdown`. antd `Tooltip` (on the order of 100 importers) is a separate migration.
|
||||
|
||||
### antd files
|
||||
|
||||
`src/components/CustomTimePicker/CustomTimePicker.tsx`
|
||||
`src/components/DownloadOptionsMenu/DownloadOptionsMenu.tsx`
|
||||
`src/components/ErrorPopover/ErrorPopover.tsx`
|
||||
`src/components/ExplorerCard/ExplorerCard.tsx`
|
||||
`src/components/HeaderRightSection/HeaderRightSection.tsx`
|
||||
`src/components/Logs/AddToQueryHOC.tsx`
|
||||
`src/components/LogsFormatOptionsMenu/LogsFormatOptionsMenu.tsx`
|
||||
`src/components/QueryBuilderV2/QueryV2/QueryAggregation/QueryAggregationSelect.tsx`
|
||||
`src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx`
|
||||
`src/components/QueryBuilderV2/QueryV2/TraceOperator/TraceOperatorEditor.tsx`
|
||||
`src/components/TableRenderer/LabelColumn.tsx`
|
||||
`src/components/WarningPopover/WarningPopover.tsx`
|
||||
`src/container/AlertHistory/AlertPopover/AlertPopover.tsx`
|
||||
`src/container/CreateAlertV2/EvaluationSettings/EvaluationSettings.tsx`
|
||||
`src/container/Home/Home.tsx`
|
||||
`src/container/MetricsExplorer/MetricDetails/AllAttributes.tsx`
|
||||
`src/container/MetricsExplorer/MetricDetails/AllAttributesValue.tsx`
|
||||
`src/container/MetricsExplorer/Summary/MetricNameSearch.tsx`
|
||||
`src/container/OptionsMenu/index.tsx`
|
||||
`src/container/TopNav/AutoRefreshV2/index.tsx`
|
||||
`src/pages/DashboardsListPage/components/ListHeader/ListHeader.tsx`
|
||||
`src/pages/MetricsApplication/ApDex/ApDexApplication.tsx`
|
||||
`src/pages/PublicDashboard/PublicDashboardView/PublicAutoRefresh/PublicAutoRefresh.tsx`
|
||||
`src/pages/TraceDetailsV3/SpanDetailsPanel/Events/components/AttributeWithExpandablePopover.tsx`
|
||||
`src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStepPopover.tsx`
|
||||
`src/pages/TracesFunnels/components/FunnelsList/FunnelItemPopover.tsx`
|
||||
`src/pages/TracesFunnels/components/SearchBar/SearchBar.tsx`
|
||||
`src/periscope/components/ContextMenu/index.tsx`
|
||||
`src/periscope/components/SeeMore/SeeMore.tsx`
|
||||
|
||||
### Existing `@signozhq/ui` popovers
|
||||
|
||||
`src/components/ExportMenu/ExportMenu.tsx`
|
||||
`src/components/MarkdownEditor/MarkdownHelp.tsx`
|
||||
`src/components/TanStackTableView/TanStackHeaderRow.tsx`
|
||||
`src/container/AIAssistant/components/ChatInput/ChatInput.tsx`
|
||||
`src/container/ListAlertRules/components/ColumnSelector.tsx`
|
||||
`src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/VariablesPopover.tsx`
|
||||
`src/pages/DashboardsListPage/components/ViewsRail/ViewNamePopover.tsx`
|
||||
|
||||
### SCSS that overrides `.ant-popover`
|
||||
|
||||
`src/components/DownloadOptionsMenu/DownloadOptionsMenu.styles.scss`
|
||||
`src/components/LogsFormatOptionsMenu/LogsFormatOptionsMenu.styles.scss`
|
||||
`src/components/QueryBuilderV2/QueryV2/QueryAggregation/QueryAggregation.styles.scss`
|
||||
`src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss`
|
||||
`src/container/AlertHistory/AlertPopover/AlertPopover.styles.scss`
|
||||
`src/container/AlertHistory/Statistics/TopContributorsCard/TopContributorsCard.styles.scss`
|
||||
`src/container/CreateAlertV2/EvaluationSettings/styles.scss`
|
||||
`src/container/Home/Home.styles.scss`
|
||||
`src/container/MetricsExplorer/MetricDetails/MetricDetails.styles.scss`
|
||||
`src/container/MetricsExplorer/Summary/Summary.styles.scss`
|
||||
`src/container/TopNav/AutoRefreshV2/AutoRefreshV2.styles.scss`
|
||||
`src/container/TopNav/DateTimeSelectionV2/DateTimeSelectionV2.styles.scss`
|
||||
`src/container/WidgetCard/WidgetCard.styles.scss`
|
||||
`src/pages/DashboardsListPage/components/ListHeader/ListHeader.module.scss`
|
||||
`src/pages/TracesFunnels/TracesFunnels.styles.scss`
|
||||
`src/pages/TracesFunnels/components/FunnelsList/FunnelsList.styles.scss`
|
||||
`src/pages/TracesFunnels/components/SearchBar/SearchBar.styles.scss`
|
||||
`src/periscope/components/ContextMenu/styles.scss`
|
||||
|
||||
Three of these are unscoped and restyle every antd popover on the page, not just their own:
|
||||
|
||||
- `src/container/MetricsExplorer/Summary/Summary.styles.scss`
|
||||
- `src/container/CreateAlertV2/EvaluationSettings/styles.scss`
|
||||
- `src/container/AlertHistory/Statistics/TopContributorsCard/TopContributorsCard.styles.scss`
|
||||
|
||||
Scope or delete those three before moving any nearby popover, or a migrated popup and a leftover antd popup will share rules that only one of them understands.
|
||||
|
||||
Most of the other files repeat one recipe: padding 0, 4px radius, a 1px border, a translucent background, the arrow hidden. The new shell already has zero padding, `--radius-2`, and no arrow. Per-site size (fixed widths around 187–500px, max-width 600px, max-height 254px) becomes `width` / `maxWidth` / `maxHeight`. Do not re-apply the recipe as a `className`; the component rejects it.
|
||||
|
||||
## What should not become this Popover
|
||||
|
||||
**Hover descriptions.** `AddToQueryHOC`, `LabelColumn`, the three Query Builder validation popovers, `SeeMore`, and `AttributeWithExpandablePopover` open on hover. Those are Tooltips. `AttributeWithExpandablePopover` shows a value the user copies; if Tooltip cannot hold that, make it a click popover instead of keeping hover.
|
||||
|
||||
**WarningPopover** (imported from about 10 files) is hover today and contains docs links. A tooltip cannot host those links. Either the links move out and the summary becomes a Tooltip, or the wrapper becomes a click Popover with `maxWidth` around 600.
|
||||
|
||||
**Menus.** Funnel item and funnel step action lists, the sort lists in `ListHeader` and Traces Funnels `SearchBar`, `AutoRefreshV2` / `PublicAutoRefresh` interval lists, and `AlertPopover`'s two links are rows that close when one is picked. Those are Dropdowns. `AllAttributes` per-row actions are the same shape.
|
||||
|
||||
**ContextMenu** (`src/periscope/components/ContextMenu/index.tsx`, imported across the dashboard drilldown) opens at chart-click coordinates. There is no trigger element. The new Popover requires `trigger`, so this stays a context menu. Do not fold the phantom span, `position: fixed` overlay, `zIndex: 10000`, or `calculatePopoverPosition.ts` into `anchor`. `anchor` is for a popover that already has a trigger and should position against something else (the typeahead input row).
|
||||
|
||||
**Inspect charts.** `MetricsExplorer/Inspect` `GraphPopover` and `HoverPopover` are absolutely positioned cards, not antd Popover. Leave them until there is a context-menu or anchor design that matches them.
|
||||
|
||||
**PanelStatusPopover** is a Tooltip despite the name.
|
||||
|
||||
## What should become this Popover
|
||||
|
||||
Click panels whose content is a form, a picker, or a composed layout:
|
||||
|
||||
- `CustomTimePicker` — the most visible one. Controlled `open`, `container` for `getPopupContainer`, and it already unmounts on hide. It opens from both input focus and click; that logic stays in the caller, with `onOpenChange`.
|
||||
- `EvaluationSettings` / `EvaluationWindowPopover` — controlled, wide (`width` / `maxWidth`), and sitting on a global `.ant-popover` override. Migrate the override in the same change.
|
||||
- `HeaderRightSection` — three controlled forms (feedback, announcements, share).
|
||||
- `ExplorerCard` save-view form and `ViewNamePopover` — close only after the save succeeds, so `open` stays controlled. `ViewNamePopover` is already on the library and will not compile against the new props.
|
||||
- `ApDex` threshold form.
|
||||
- `Home` welcome checklist — drop the transparent-shell override; the shell is the component's.
|
||||
- `OptionsMenu`, `DownloadOptionsMenu`, `LogsFormatOptionsMenu` — click panels. `LogsFormatOptionsMenu` nests a submenu; the inner popup must be portalled, and the outer `onOpenChange` must `cancel()` an outside press that lands in the inner popup.
|
||||
- `MetricNameSearch` — controlled search panel. Scope the global padding override in `Summary.styles.scss` in the same change.
|
||||
- `AllAttributesValue` — one popover open at a time in a list. That is controlled `open` keyed by row, which the API still allows.
|
||||
- `ChatInput` context picker — already on the library; `side="top"` `align="end"` plus `width`.
|
||||
- `VariablesPopover` — already on the library. Keep `anchor` on the input row, `initialFocus={false}` so the caret stays, and `details.cancel()` when the outside press is the anchor. `withPortal={false}` becomes the default dialog `container`, not an unportalled popup.
|
||||
- `ColumnSelector`, `MarkdownHelp`, `TanStackHeaderRow`, `ExportMenu` — Radix `asChild` trigger plus content. The trigger moves to the `trigger` prop, content moves to `children`, and `className` on the shell becomes `width` / `maxWidth`.
|
||||
|
||||
`ErrorPopover` is a thin wrapper. Re-point it at the new props and its consumer follows.
|
||||
|
||||
## Order
|
||||
|
||||
Before any change: screenshot every current popover, in both themes, so each call site's pattern is on record and a component swap is reviewable against it. Flag the misusages to design as they turn up — links inside hover surfaces above all. Swapping the component during migration is expected where the old call site was on the wrong one; antd call sites stay untouched until their turn.
|
||||
|
||||
1. Scope the three global `.ant-popover` files so later migrations cannot restyle leftover antd popovers.
|
||||
2. Move the seven existing `@signozhq/ui` call sites first. They break at the package bump; the 29 antd files do not, until each one is switched.
|
||||
3. Migrate shared wrappers that are actually popovers (`ErrorPopover`, then `WarningPopover` once the links decision is made). Leave `ContextMenu` on antd until a context menu exists.
|
||||
4. Migrate click forms (`CustomTimePicker`, evaluation window, header menus, save-view, ApDex).
|
||||
5. Send hover descriptions to Tooltip and row menus to Dropdown, instead of forcing them through Popover.
|
||||
6. Delete the matching `.ant-popover` rules in the same change as each call site, so a half-migrated page is not styled twice.
|
||||
|
||||
## Risks
|
||||
|
||||
- **Controlled `open` is load-bearing.** Save forms close from inside the popup only when the mutation succeeds. A list keeps one popover open at a time. Dropping `open` and driving everything from `onOpenChange` alone cannot express either. Keep the controlled prop at those sites.
|
||||
- **Focus moves in.** Click popovers focus the first tabbable child. Typeaheads (`VariablesPopover`, and any filter that must keep the caret) need `initialFocus={false}`.
|
||||
- **Outside press and anchors.** A press on the anchor looks outside. Call `details.cancel()` or the typeahead closes when the user clicks the input it is anchored to.
|
||||
- **Dialogs.** Inside a Dialog or Drawer the popup portals into the panel so the focus trap can reach it. Do not set `container={document.body}` there.
|
||||
- **Z-index.** The shell starts at `--popover-z-index` (50) and lifts above the layer its trigger sits in. A Tooltip inside a row must still paint above the popup. The app ladder today is tooltip 1070, dropdown 1050, popover 1030, modal 1000. Check a truncated row tooltip inside a popover after the first real migration.
|
||||
- **Scroll locking.** Chart popovers measure the wrong box when a modal has locked scroll. This popover does not lock scroll (`modal` is rejected). Re-check Infrastructure Monitoring charts if a surrounding modal is open.
|
||||
- **`nativeButton` mismatches.** Base UI logs an error when the flag does not match the element. Every non-button trigger (a badge, a custom row, an input) needs `nativeButton={false}`.
|
||||
|
||||
## `--popover-foreground` audit
|
||||
|
||||
The shell reads `--popover-background`, `--popover-foreground`, `--popover-border`, and `--popover-shadow`. Those semantic values belong to the token package, not to call sites.
|
||||
|
||||
Two legacy shadcn variables predate those hooks:
|
||||
|
||||
- `--popover-foreground` is the foreground hook the shell uses. It should stay pointed at the same foreground as the rest of the light and dark themes (`--l1-foreground` today).
|
||||
- `--popover` (no suffix) is the old background. `--calendar-select-background` still reads it. Do not repoint `--popover` at `--popover-background` or at `surface-3` until the calendar token is audited, or date selection changes color with the popover shell.
|
||||
|
||||
Call sites that pass antd's `color` (a gradient string on `AlertPopover`, a raw token on `SeeMore`) do not map to a prop. The shell color comes from the tokens. Content that needs its own background paints it inside `children`.
|
||||
@@ -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>
|
||||
|
||||
@@ -56,10 +56,10 @@ const config: Config.InitialOptions = {
|
||||
transformIgnorePatterns: [
|
||||
// @chenglou/pretext is ESM-only; @signozhq/ui pulls it in via text-ellipsis.
|
||||
// Pattern 1: allow .pnpm virtual store through (handled by pattern 2), plus root-level ESM packages.
|
||||
'node_modules/(?!(\\.pnpm|react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|d3-geo|d3-array|internmap|ol|rbush|quickselect|earcut|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|micromark-core-commonmark|micromark-extension-gfm|micromark-extension-gfm-autolink-literal|micromark-extension-gfm-footnote|micromark-extension-gfm-strikethrough|micromark-extension-gfm-table|micromark-extension-gfm-tagfilter|micromark-extension-gfm-task-list-item|micromark-factory-destination|micromark-factory-label|micromark-factory-space|micromark-factory-title|micromark-factory-whitespace|micromark-util-character|micromark-util-chunked|micromark-util-classify-character|micromark-util-combine-extensions|micromark-util-decode-numeric-character-reference|micromark-util-decode-string|micromark-util-encode|micromark-util-html-tag-name|micromark-util-normalize-identifier|micromark-util-resolve-all|micromark-util-sanitize-uri|micromark-util-subtokenize|micromark-util-symbol|micromark-util-types|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)/)',
|
||||
'node_modules/(?!(\\.pnpm|react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|micromark-core-commonmark|micromark-extension-gfm|micromark-extension-gfm-autolink-literal|micromark-extension-gfm-footnote|micromark-extension-gfm-strikethrough|micromark-extension-gfm-table|micromark-extension-gfm-tagfilter|micromark-extension-gfm-task-list-item|micromark-factory-destination|micromark-factory-label|micromark-factory-space|micromark-factory-title|micromark-factory-whitespace|micromark-util-character|micromark-util-chunked|micromark-util-classify-character|micromark-util-combine-extensions|micromark-util-decode-numeric-character-reference|micromark-util-decode-string|micromark-util-encode|micromark-util-html-tag-name|micromark-util-normalize-identifier|micromark-util-resolve-all|micromark-util-sanitize-uri|micromark-util-subtokenize|micromark-util-symbol|micromark-util-types|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)/)',
|
||||
// Pattern 2: pnpm virtual store — ignore everything except ESM-only packages.
|
||||
// pnpm encodes scoped packages as @scope+name@version, so match on scope prefix.
|
||||
'node_modules/\\.pnpm/(?!(react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou|@signozhq|date-fns|d3-interpolate|d3-color|d3-geo|d3-array|internmap|ol|rbush|quickselect|earcut|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)[^/]*/node_modules)',
|
||||
'node_modules/\\.pnpm/(?!(react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)[^/]*/node_modules)',
|
||||
],
|
||||
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
|
||||
testPathIgnorePatterns: ['/node_modules/', '/public/'],
|
||||
|
||||
@@ -30,8 +30,7 @@
|
||||
"test": "jest",
|
||||
"test:changedsince": "jest --changedSince=main --coverage --silent",
|
||||
"generate:api": "orval --config ./orval.config.ts && sh scripts/post-types-generation.sh",
|
||||
"generate:config:web-settings": "json2ts ./src/schemas/generated/webSettings.schema.json -o src/types/generated/webSettings.ts --style.useTabs --style.tabWidth=1 --style.singleQuote --bannerComment '/* AUTO GENERATED FILE - DO NOT EDIT - GENERATED FROM frontend/src/schemas/generated/webSettings.schema.json */'",
|
||||
"build:geo-outlines": "node scripts/geo-outlines/build.mjs"
|
||||
"generate:config:web-settings": "json2ts ./src/schemas/generated/webSettings.schema.json -o src/types/generated/webSettings.ts --style.useTabs --style.tabWidth=1 --style.singleQuote --bannerComment '/* AUTO GENERATED FILE - DO NOT EDIT - GENERATED FROM frontend/src/schemas/generated/webSettings.schema.json */'"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0",
|
||||
@@ -54,9 +53,9 @@
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"@sentry/react": "10.57.0",
|
||||
"@sentry/vite-plugin": "5.3.0",
|
||||
"@signozhq/design-tokens": "2.6.0",
|
||||
"@signozhq/design-tokens": "2.2.1",
|
||||
"@signozhq/icons": "0.4.0",
|
||||
"@signozhq/ui": "0.4.0-rc.3",
|
||||
"@signozhq/ui": "0.2.0",
|
||||
"@tanstack/react-table": "8.21.3",
|
||||
"@tanstack/react-virtual": "3.13.22",
|
||||
"@uiw/codemirror-theme-copilot": "4.23.11",
|
||||
@@ -79,7 +78,6 @@
|
||||
"classnames": "2.3.2",
|
||||
"color": "^4.2.1",
|
||||
"crypto-js": "4.2.0",
|
||||
"d3-geo": "3.1.1",
|
||||
"d3-hierarchy": "3.1.2",
|
||||
"dayjs": "^1.10.7",
|
||||
"dompurify": "3.4.17",
|
||||
@@ -98,7 +96,6 @@
|
||||
"monaco-editor": "0.55.1",
|
||||
"motion": "12.4.13",
|
||||
"nuqs": "2.8.8",
|
||||
"ol": "10.11.0",
|
||||
"overlayscrollbars": "^2.16.0",
|
||||
"overlayscrollbars-react": "^0.5.6",
|
||||
"papaparse": "5.4.1",
|
||||
@@ -133,7 +130,6 @@
|
||||
"rrule": "2.8.1",
|
||||
"styled-components": "^5.3.11",
|
||||
"timestamp-nano": "^1.0.0",
|
||||
"topojson-client": "3.1.0",
|
||||
"translation-resilience": "^0.2.0",
|
||||
"typescript": "5.9.3",
|
||||
"uplot": "1.6.31",
|
||||
@@ -174,10 +170,8 @@
|
||||
"@testing-library/user-event": "14.4.3",
|
||||
"@types/color": "^3.0.3",
|
||||
"@types/crypto-js": "4.2.2",
|
||||
"@types/d3-geo": "3.1.1",
|
||||
"@types/d3-hierarchy": "1.1.11",
|
||||
"@types/event-source-polyfill": "^1.0.0",
|
||||
"@types/geojson": "7946.0.16",
|
||||
"@types/history": "4.7.11",
|
||||
"@types/jest": "30.0.0",
|
||||
"@types/lodash-es": "^4.17.4",
|
||||
@@ -194,8 +188,6 @@
|
||||
"@types/redux-mock-store": "1.0.4",
|
||||
"@types/styled-components": "^5.1.4",
|
||||
"@types/testing-library__jest-dom": "^5.14.5",
|
||||
"@types/topojson-client": "3.1.5",
|
||||
"@types/topojson-specification": "1.0.5",
|
||||
"@typescript/native-preview": "7.0.0-dev.20260430.1",
|
||||
"eslint-plugin-sonarjs": "4.0.2",
|
||||
"husky": "^9.1.7",
|
||||
@@ -217,8 +209,6 @@
|
||||
"storybook": "10.6.3",
|
||||
"stylelint": "17.15.0",
|
||||
"svgo": "4.1.0",
|
||||
"topojson-server": "3.0.1",
|
||||
"topojson-simplify": "3.0.3",
|
||||
"ts-jest": "29.4.15",
|
||||
"typescript-plugin-css-modules": "5.3.0",
|
||||
"use-sync-external-store": "1.6.0",
|
||||
|
||||
@@ -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 },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -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 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -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 \`--\`.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
|
||||
1328
frontend/pnpm-lock.yaml
generated
1328
frontend/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,92 +0,0 @@
|
||||
Copyright (c) 2023 Vercel, in collaboration with basement.studio
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
BIN
frontend/public/fonts/Inter-VariableFont_opsz,wght.ttf
Normal file
BIN
frontend/public/fonts/Inter-VariableFont_opsz,wght.ttf
Normal file
Binary file not shown.
@@ -1,210 +0,0 @@
|
||||
// Builds the Geo Map outlines assets: Natural Earth 50m admin-0 countries, and
|
||||
// 10m admin-1 states/provinces for every country with at least two of them.
|
||||
// Run by hand when bumping Natural Earth or editing regions/aliases; the output is committed.
|
||||
// Usage: pnpm build:geo-outlines
|
||||
//
|
||||
// Nothing is written until every invariant in validate.mjs holds. The assets
|
||||
// are built in a staging folder and swapped in whole, so a failed run leaves
|
||||
// the committed ones as they were.
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { gzipSync } from 'node:zlib';
|
||||
|
||||
import {
|
||||
ASSETS_DIR,
|
||||
COUNTRIES_URL,
|
||||
SUBDIVISION_LIST_FILE,
|
||||
SUBDIVISIONS_URL,
|
||||
} from './config.mjs';
|
||||
import { buildCountries } from './countries.mjs';
|
||||
import { buildSubdivisions } from './subdivisions.mjs';
|
||||
import { validate } from './validate.mjs';
|
||||
|
||||
const DOWNLOAD_TIMEOUT_MS = 120_000;
|
||||
const DOWNLOAD_ATTEMPTS = 3;
|
||||
|
||||
const STAGING_DIR = `${ASSETS_DIR}.staging`;
|
||||
const PREVIOUS_DIR = `${ASSETS_DIR}.previous`;
|
||||
// Everything in the assets folder is generated; anything else would be lost
|
||||
// in the swap, so its presence stops the build.
|
||||
const GENERATED_ENTRIES = new Set([
|
||||
'countries-50m.json',
|
||||
'lookups.json',
|
||||
'subdivisions',
|
||||
]);
|
||||
|
||||
const kb = (bytes) => `${(bytes / 1024).toFixed(0)} KB`;
|
||||
const sizeOf = (json) =>
|
||||
`${kb(Buffer.byteLength(json))} raw / ${kb(gzipSync(json).length)} gzip`;
|
||||
|
||||
async function downloadFeatures(url) {
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
const body = await response.json();
|
||||
if (
|
||||
body?.type !== 'FeatureCollection' ||
|
||||
!Array.isArray(body.features) ||
|
||||
body.features.length === 0
|
||||
) {
|
||||
throw new Error('response is not a non-empty GeoJSON FeatureCollection');
|
||||
}
|
||||
return body;
|
||||
} catch (error) {
|
||||
if (attempt === DOWNLOAD_ATTEMPTS) {
|
||||
throw new Error(
|
||||
`download failed after ${attempt} attempts: ${url}\n ${error.message}`,
|
||||
);
|
||||
}
|
||||
await sleep(attempt * 2_000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function subdivisionListSource(countries) {
|
||||
return `// Generated by scripts/geo-outlines/build.mjs; do not edit.
|
||||
export const SUBDIVISION_COUNTRY_CODES = [
|
||||
${countries.map((country) => `\t'${country}',`).join('\n')}
|
||||
] as const;
|
||||
`;
|
||||
}
|
||||
|
||||
// A run that died mid-swap leaves the assets in the previous folder.
|
||||
function recoverInterruptedSwap() {
|
||||
if (!existsSync(ASSETS_DIR) && existsSync(PREVIOUS_DIR)) {
|
||||
renameSync(PREVIOUS_DIR, ASSETS_DIR);
|
||||
}
|
||||
rmSync(STAGING_DIR, { recursive: true, force: true });
|
||||
rmSync(PREVIOUS_DIR, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function assertOnlyGeneratedEntries() {
|
||||
if (!existsSync(ASSETS_DIR)) {
|
||||
return;
|
||||
}
|
||||
const foreign = readdirSync(ASSETS_DIR).filter(
|
||||
(entry) => !GENERATED_ENTRIES.has(entry),
|
||||
);
|
||||
if (foreign.length > 0) {
|
||||
throw new Error(
|
||||
`${ASSETS_DIR} holds files this build doesn't generate: ${foreign.join(', ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes every output under the staging folder; returns the sizes report. */
|
||||
function stage(outputs) {
|
||||
const subdivisionDir = join(STAGING_DIR, 'subdivisions');
|
||||
mkdirSync(subdivisionDir, { recursive: true });
|
||||
writeFileSync(join(STAGING_DIR, 'countries-50m.json'), outputs.countriesJson);
|
||||
writeFileSync(join(STAGING_DIR, 'lookups.json'), outputs.lookupsJson);
|
||||
const sizes = [];
|
||||
for (const [country, file] of outputs.subdivisionFiles) {
|
||||
const json = JSON.stringify(file);
|
||||
writeFileSync(join(subdivisionDir, `${country}.json`), json);
|
||||
sizes.push({
|
||||
country,
|
||||
shapes: file.objects.subdivisions.geometries.length,
|
||||
gzip: gzipSync(json).length,
|
||||
});
|
||||
}
|
||||
writeFileSync(`${SUBDIVISION_LIST_FILE}.staging`, outputs.subdivisionList);
|
||||
return sizes;
|
||||
}
|
||||
|
||||
/** Swaps the staged assets in; puts the previous ones back if that fails. */
|
||||
function commitStaged() {
|
||||
const hadAssets = existsSync(ASSETS_DIR);
|
||||
if (hadAssets) {
|
||||
renameSync(ASSETS_DIR, PREVIOUS_DIR);
|
||||
}
|
||||
try {
|
||||
renameSync(STAGING_DIR, ASSETS_DIR);
|
||||
// A failed rename leaves the previous list in place.
|
||||
renameSync(`${SUBDIVISION_LIST_FILE}.staging`, SUBDIVISION_LIST_FILE);
|
||||
} catch (error) {
|
||||
rmSync(ASSETS_DIR, { recursive: true, force: true });
|
||||
if (hadAssets) {
|
||||
renameSync(PREVIOUS_DIR, ASSETS_DIR);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
rmSync(PREVIOUS_DIR, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function cleanUpStaging() {
|
||||
rmSync(STAGING_DIR, { recursive: true, force: true });
|
||||
rmSync(`${SUBDIVISION_LIST_FILE}.staging`, { force: true });
|
||||
}
|
||||
|
||||
function report(countries, subdivisions, outputs, sizes) {
|
||||
const totalGzip = sizes.reduce((sum, { gzip }) => sum + gzip, 0);
|
||||
return {
|
||||
countries: {
|
||||
...countries.report,
|
||||
sizes: {
|
||||
'countries-50m.json': sizeOf(outputs.countriesJson),
|
||||
'lookups.json': sizeOf(outputs.lookupsJson),
|
||||
},
|
||||
},
|
||||
subdivisions: {
|
||||
...subdivisions.report,
|
||||
countries: sizes.length,
|
||||
totalGzip: kb(totalGzip),
|
||||
largest: [...sizes]
|
||||
.sort((a, b) => b.gzip - a.gzip)
|
||||
.slice(0, 10)
|
||||
.map(
|
||||
({ country, shapes, gzip }) =>
|
||||
`${country}: ${shapes} shapes, ${kb(gzip)} gzip`,
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
recoverInterruptedSwap();
|
||||
assertOnlyGeneratedEntries();
|
||||
|
||||
const [countrySource, subdivisionSource] = await Promise.all([
|
||||
downloadFeatures(COUNTRIES_URL),
|
||||
downloadFeatures(SUBDIVISIONS_URL),
|
||||
]);
|
||||
const countries = buildCountries(countrySource);
|
||||
const subdivisions = buildSubdivisions(subdivisionSource);
|
||||
validate(countries, subdivisions);
|
||||
|
||||
const outputs = {
|
||||
countriesJson: JSON.stringify(countries.topology),
|
||||
lookupsJson: JSON.stringify(countries.lookups),
|
||||
subdivisionFiles: subdivisions.files,
|
||||
subdivisionList: subdivisionListSource([...subdivisions.files.keys()]),
|
||||
};
|
||||
try {
|
||||
const sizes = stage(outputs);
|
||||
commitStaged();
|
||||
process.stdout.write(
|
||||
`${JSON.stringify(report(countries, subdivisions, outputs, sizes), null, 2)}\n`,
|
||||
);
|
||||
} finally {
|
||||
cleanUpStaging();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
process.stderr.write(`Geo outlines build failed: ${error.message}\n`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -1,181 +0,0 @@
|
||||
// Inputs and tuning for the Geo Map outlines build. Tables only; no logic.
|
||||
// Read by every other module here; not run on its own.
|
||||
//
|
||||
// Edit this file to bump Natural Earth (the pinned version below), retune
|
||||
// simplification, or fix a region, alias or merge; then run
|
||||
// pnpm build:geo-outlines and commit the rebuilt assets.
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const NATURAL_EARTH_BASE =
|
||||
'https://raw.githubusercontent.com/nvkelso/natural-earth-vector/v5.1.2/geojson';
|
||||
export const COUNTRIES_URL = `${NATURAL_EARTH_BASE}/ne_50m_admin_0_countries.geojson`;
|
||||
export const SUBDIVISIONS_URL = `${NATURAL_EARTH_BASE}/ne_10m_admin_1_states_provinces.geojson`;
|
||||
|
||||
const GEO_MAP_DIR = join(
|
||||
dirname(fileURLToPath(import.meta.url)),
|
||||
'../../src/lib/visualization/charts/GeoMap',
|
||||
);
|
||||
export const ASSETS_DIR = join(GEO_MAP_DIR, 'assets');
|
||||
export const SUBDIVISION_LIST_FILE = join(
|
||||
GEO_MAP_DIR,
|
||||
'geo/subdivisionCountries.ts',
|
||||
);
|
||||
|
||||
export const COUNTRY_QUANTIZATION = 1e5;
|
||||
// Simplification drops every point whose triangle with its neighbours is
|
||||
// smaller than this, in square degrees. A fixed size, unlike a share of all
|
||||
// points, still leaves a small island a few points of its own.
|
||||
export const COUNTRY_MIN_WEIGHT = 3e-3;
|
||||
// 10m is street-level detail; a country view needs far less.
|
||||
export const SUBDIVISION_QUANTIZATION = 1e4;
|
||||
export const SUBDIVISION_MIN_WEIGHT = 1e-3;
|
||||
// A shape this many times the minimum weight or smaller could lose every polygon.
|
||||
export const PROTECTED_SHAPE_FACTOR = 10;
|
||||
|
||||
// A country view needs at least this many coded states to be worth drawing.
|
||||
export const MIN_SUBDIVISIONS = 2;
|
||||
|
||||
// ISO 3166-2 codes that changed after Natural Earth v5.1.2, or older spellings
|
||||
// still in GeoIP data, mapped to the code the shape carries.
|
||||
export const SUBDIVISION_ALIASES = {
|
||||
IN: {
|
||||
'IN-CG': 'IN-CT',
|
||||
'IN-UK': 'IN-UT',
|
||||
'IN-TS': 'IN-TG',
|
||||
'IN-OD': 'IN-OR',
|
||||
'IN-DD': 'IN-DH',
|
||||
'IN-DN': 'IN-DH',
|
||||
},
|
||||
// Natural Earth carries Metro Manila under its retired code.
|
||||
PH: { 'PH-00': 'PH-MNL' },
|
||||
};
|
||||
|
||||
// Shapes Natural Earth still splits along retired lines, merged into the codes
|
||||
// GeoIP reports now; the retired codes become aliases. Northern Ireland's 26
|
||||
// districts became 11 councils in 2015, each a union of old districts.
|
||||
// Current code → [current name, retired codes].
|
||||
export const SUBDIVISION_MERGES = {
|
||||
GB: {
|
||||
'GB-ANN': ['Antrim and Newtownabbey', ['GB-ANT', 'GB-NTA']],
|
||||
'GB-AND': ['Ards and North Down', ['GB-ARD', 'GB-NDN']],
|
||||
'GB-ABC': [
|
||||
'Armagh City, Banbridge and Craigavon',
|
||||
['GB-ARM', 'GB-BNB', 'GB-CGV'],
|
||||
],
|
||||
'GB-BFS': ['Belfast', ['GB-BFS']],
|
||||
'GB-CCG': [
|
||||
'Causeway Coast and Glens',
|
||||
['GB-BLY', 'GB-CLR', 'GB-LMV', 'GB-MYL'],
|
||||
],
|
||||
'GB-DRS': ['Derry City and Strabane', ['GB-DRY', 'GB-STB']],
|
||||
'GB-FMO': ['Fermanagh and Omagh', ['GB-FER', 'GB-OMH']],
|
||||
'GB-LBC': ['Lisburn and Castlereagh', ['GB-LSB', 'GB-CSR']],
|
||||
'GB-MEA': ['Mid and East Antrim', ['GB-BLA', 'GB-CKF', 'GB-LRN']],
|
||||
'GB-MUL': ['Mid Ulster', ['GB-CKT', 'GB-DGN', 'GB-MFT']],
|
||||
'GB-NMD': ['Newry, Mourne and Down', ['GB-NYM', 'GB-DOW']],
|
||||
},
|
||||
};
|
||||
|
||||
// Natural Earth puts these islands in "Seven seas (open ocean)".
|
||||
export const OPEN_OCEAN_REGION = {
|
||||
Africa: 'africa',
|
||||
Asia: 'asia',
|
||||
Americas: 'south_america',
|
||||
};
|
||||
export const CONTINENT_REGION = {
|
||||
Africa: 'africa',
|
||||
Asia: 'asia',
|
||||
Europe: 'europe',
|
||||
'North America': 'north_america',
|
||||
'South America': 'south_america',
|
||||
Oceania: 'oceania',
|
||||
};
|
||||
// Transcontinental countries belong to every region they span.
|
||||
export const EXTRA_REGIONS = {
|
||||
RU: ['asia'],
|
||||
TR: ['europe'],
|
||||
KZ: ['europe'],
|
||||
GE: ['europe'],
|
||||
AM: ['europe'],
|
||||
AZ: ['europe'],
|
||||
CY: ['europe'],
|
||||
EG: ['asia'],
|
||||
};
|
||||
|
||||
// ISO codes GeoIP emits for places Natural Earth draws inside another country.
|
||||
export const COUNTRY_ALIASES = {
|
||||
GF: 'FR',
|
||||
GP: 'FR',
|
||||
MQ: 'FR',
|
||||
RE: 'FR',
|
||||
YT: 'FR',
|
||||
BQ: 'NL',
|
||||
SJ: 'NO',
|
||||
BV: 'NO',
|
||||
CX: 'AU',
|
||||
CC: 'AU',
|
||||
HM: 'AU',
|
||||
UM: 'US',
|
||||
TK: 'NZ',
|
||||
AC: 'SH',
|
||||
TA: 'SH',
|
||||
DG: 'IO',
|
||||
CP: 'FR',
|
||||
FX: 'FR',
|
||||
EA: 'ES',
|
||||
IC: 'ES',
|
||||
CQ: 'GB',
|
||||
GI: 'GB',
|
||||
// Retired or reserved codes still seen in older data.
|
||||
UK: 'GB',
|
||||
SU: 'RU',
|
||||
YU: 'RS',
|
||||
CS: 'RS',
|
||||
TP: 'TL',
|
||||
BU: 'MM',
|
||||
ZR: 'CD',
|
||||
DD: 'DE',
|
||||
VD: 'VN',
|
||||
YD: 'YE',
|
||||
RH: 'ZW',
|
||||
NH: 'VU',
|
||||
HV: 'BF',
|
||||
DY: 'BJ',
|
||||
AN: 'CW',
|
||||
};
|
||||
export const COUNTRY_NAME_ALIASES = {
|
||||
usa: 'US',
|
||||
'united states of america': 'US',
|
||||
america: 'US',
|
||||
uk: 'GB',
|
||||
'great britain': 'GB',
|
||||
britain: 'GB',
|
||||
england: 'GB',
|
||||
russia: 'RU',
|
||||
'south korea': 'KR',
|
||||
'north korea': 'KP',
|
||||
czechia: 'CZ',
|
||||
'czech republic': 'CZ',
|
||||
'ivory coast': 'CI',
|
||||
turkiye: 'TR',
|
||||
türkiye: 'TR',
|
||||
burma: 'MM',
|
||||
'cape verde': 'CV',
|
||||
swaziland: 'SZ',
|
||||
macedonia: 'MK',
|
||||
'east timor': 'TL',
|
||||
vatican: 'VA',
|
||||
};
|
||||
|
||||
// Alpha-2 codes Intl names that aren't countries, so none needs a shape.
|
||||
export const NON_COUNTRY_CODES = new Set([
|
||||
'EU',
|
||||
'EZ',
|
||||
'UN',
|
||||
'ZZ',
|
||||
'QO',
|
||||
'XA',
|
||||
'XB',
|
||||
'AQ',
|
||||
]);
|
||||
@@ -1,190 +0,0 @@
|
||||
// Natural Earth admin-0 → the countries topology and the lookup tables.
|
||||
// Called by build.mjs; not run on its own.
|
||||
//
|
||||
// Merges each country's parts into one shape by ISO alpha-2, drops Antarctica,
|
||||
// assigns view regions and builds the alpha-3/name/alias lookups
|
||||
// normalizeCountry reads. Returns the topology, the lookups and a report.
|
||||
import { geoArea, geoBounds } from 'd3-geo';
|
||||
import { feature } from 'topojson-client';
|
||||
|
||||
import {
|
||||
CONTINENT_REGION,
|
||||
COUNTRY_ALIASES,
|
||||
COUNTRY_MIN_WEIGHT,
|
||||
COUNTRY_NAME_ALIASES,
|
||||
COUNTRY_QUANTIZATION,
|
||||
EXTRA_REGIONS,
|
||||
NON_COUNTRY_CODES,
|
||||
OPEN_OCEAN_REGION,
|
||||
} from './config.mjs';
|
||||
import {
|
||||
polygonsOf,
|
||||
round,
|
||||
roundBounds,
|
||||
simplifyAndQuantize,
|
||||
} from './geometry.mjs';
|
||||
|
||||
export const isCountryCode = (value) => /^[A-Z]{2}$/.test(value ?? '');
|
||||
|
||||
function regionsOf(props, iso2) {
|
||||
const base = props.CONTINENT.startsWith('Seven seas')
|
||||
? OPEN_OCEAN_REGION[props.REGION_UN]
|
||||
: CONTINENT_REGION[props.CONTINENT];
|
||||
return [...new Set([base, ...(EXTRA_REGIONS[iso2] ?? [])].filter(Boolean))];
|
||||
}
|
||||
|
||||
// Group features by code so a country's overseas parts (Australia's Indian
|
||||
// Ocean territories) become one shape that one data row colours.
|
||||
function groupByCode(sourceFeatures, report) {
|
||||
const groups = new Map();
|
||||
for (const f of sourceFeatures) {
|
||||
const p = f.properties;
|
||||
if (p.CONTINENT === 'Antarctica') {
|
||||
report.dropped.push(p.NAME);
|
||||
continue;
|
||||
}
|
||||
const iso2 = isCountryCode(p.ISO_A2_EH) ? p.ISO_A2_EH : null;
|
||||
const key = iso2 ?? `uncoded:${p.NAME}`;
|
||||
if (!iso2) {
|
||||
report.uncoded.push(p.NAME);
|
||||
}
|
||||
if (!groups.has(key)) {
|
||||
groups.set(key, []);
|
||||
}
|
||||
groups.get(key).push(f);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function toCountryFeature(key, members, report) {
|
||||
// The sovereign part carries the name, label point and region.
|
||||
const primary =
|
||||
members.find((f) => f.properties.ISO_A2 === f.properties.ISO_A2_EH) ??
|
||||
members.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
|
||||
const p = primary.properties;
|
||||
const iso2 = key.startsWith('uncoded:') ? null : key;
|
||||
if (members.length > 1) {
|
||||
report.merged.push(
|
||||
`${iso2}: ${members.map((f) => f.properties.NAME).join(' + ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
const polygons = members.flatMap((f) => polygonsOf(f.geometry));
|
||||
const geometry = { type: 'MultiPolygon', coordinates: polygons };
|
||||
const mainland = polygons
|
||||
.map((coordinates) => ({ type: 'Polygon', coordinates }))
|
||||
.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
|
||||
|
||||
return {
|
||||
type: 'Feature',
|
||||
id: iso2 ?? p.NAME,
|
||||
properties: {
|
||||
code: iso2,
|
||||
iso3: /^[A-Z]{3}$/.test(p.ISO_A3_EH) ? p.ISO_A3_EH : null,
|
||||
name: p.NAME,
|
||||
label: [round(p.LABEL_X), round(p.LABEL_Y)],
|
||||
mainland: roundBounds(geoBounds(mainland)),
|
||||
bounds: roundBounds(geoBounds(geometry)),
|
||||
regions: regionsOf(p, iso2 ?? ''),
|
||||
},
|
||||
geometry,
|
||||
};
|
||||
}
|
||||
|
||||
/** Alpha-3 codes and English names → alpha-2, for normalising data. */
|
||||
function buildLookups(sourceFeatures) {
|
||||
const alpha3 = {};
|
||||
const names = { ...COUNTRY_NAME_ALIASES };
|
||||
for (const { properties: p } of sourceFeatures) {
|
||||
if (!isCountryCode(p.ISO_A2_EH) || p.CONTINENT === 'Antarctica') {
|
||||
continue;
|
||||
}
|
||||
if (/^[A-Z]{3}$/.test(p.ISO_A3_EH)) {
|
||||
alpha3[p.ISO_A3_EH] = p.ISO_A2_EH;
|
||||
}
|
||||
for (const name of [
|
||||
p.NAME,
|
||||
p.NAME_LONG,
|
||||
p.ADMIN,
|
||||
p.NAME_EN,
|
||||
p.BRK_NAME,
|
||||
p.NAME_SORT,
|
||||
p.NAME_CIAWF,
|
||||
]) {
|
||||
if (name) {
|
||||
names[name.toLowerCase()] ??= p.ISO_A2_EH;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { alpha3, names, aliases: COUNTRY_ALIASES };
|
||||
}
|
||||
|
||||
/** ISO alpha-2 codes Intl knows that neither a shape nor an alias covers. */
|
||||
function findUncoveredCodes(drawn) {
|
||||
const display = new Intl.DisplayNames(['en'], {
|
||||
type: 'region',
|
||||
fallback: 'none',
|
||||
});
|
||||
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
const uncovered = [];
|
||||
for (const a of letters) {
|
||||
for (const b of letters) {
|
||||
const code = a + b;
|
||||
const name = display.of(code);
|
||||
if (
|
||||
name &&
|
||||
!NON_COUNTRY_CODES.has(code) &&
|
||||
!drawn.has(code) &&
|
||||
!COUNTRY_ALIASES[code]
|
||||
) {
|
||||
uncovered.push(`${code} ${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return uncovered;
|
||||
}
|
||||
|
||||
/** Natural Earth admin-0 GeoJSON → `{ topology, lookups, report }`. */
|
||||
export function buildCountries(source) {
|
||||
const report = { dropped: [], uncoded: [], merged: [] };
|
||||
const features = [...groupByCode(source.features, report)]
|
||||
.map(([key, members]) => toCountryFeature(key, members, report))
|
||||
.sort((a, b) => String(a.id).localeCompare(String(b.id)));
|
||||
|
||||
const { topo, flipped, collapsed, emptied } = simplifyAndQuantize(
|
||||
'countries',
|
||||
features,
|
||||
COUNTRY_MIN_WEIGHT,
|
||||
COUNTRY_QUANTIZATION,
|
||||
);
|
||||
const drawn = new Set(features.map((f) => f.properties.code).filter(Boolean));
|
||||
// Lets data be checked against the drawn codes without decoding the outlines.
|
||||
const lookups = { codes: [...drawn].sort(), ...buildLookups(source.features) };
|
||||
|
||||
const regionCounts = {};
|
||||
for (const f of features) {
|
||||
for (const region of f.properties.regions) {
|
||||
regionCounts[region] = (regionCounts[region] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
topology: topo,
|
||||
lookups,
|
||||
report: {
|
||||
features: features.length,
|
||||
decodedFeatures: feature(topo, topo.objects.countries).features.length,
|
||||
droppedFlippedIslands: flipped,
|
||||
droppedCollapsedPolygons: collapsed,
|
||||
emptied: emptied.join(' '),
|
||||
regionCounts,
|
||||
...report,
|
||||
lookupCounts: {
|
||||
alpha3: Object.keys(lookups.alpha3).length,
|
||||
names: Object.keys(lookups.names).length,
|
||||
aliases: Object.keys(lookups.aliases).length,
|
||||
},
|
||||
uncoveredIsoCodes: findUncoveredCodes(drawn),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// Geometry helpers and the simplification shared by countries and states.
|
||||
// Used by countries.mjs and subdivisions.mjs; not run on its own.
|
||||
//
|
||||
// Simplification protects small shapes so islands keep an outline, and drops
|
||||
// polygons that collapse to slivers or flip inside out after quantizing.
|
||||
import { geoArea } from 'd3-geo';
|
||||
import { topology } from 'topojson-server';
|
||||
import { presimplify, simplify } from 'topojson-simplify';
|
||||
import { feature, quantize } from 'topojson-client';
|
||||
|
||||
import { PROTECTED_SHAPE_FACTOR } from './config.mjs';
|
||||
|
||||
export const round = (n) => Math.round(n * 1e3) / 1e3;
|
||||
export const roundBounds = (bounds) =>
|
||||
bounds.map(([x, y]) => [round(x), round(y)]);
|
||||
|
||||
export function polygonsOf(geometry) {
|
||||
if (geometry.type === 'Polygon') {
|
||||
return [geometry.coordinates];
|
||||
}
|
||||
if (geometry.type === 'MultiPolygon') {
|
||||
return geometry.coordinates;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Area of a lon/lat ring in square degrees, the unit of the simplify weights. */
|
||||
function planarRingArea(ring) {
|
||||
let twice = 0;
|
||||
ring.forEach(([x, y], i) => {
|
||||
const [nx, ny] = ring[(i + 1) % ring.length];
|
||||
twice += x * ny - nx * y;
|
||||
});
|
||||
return Math.abs(twice) / 2;
|
||||
}
|
||||
|
||||
// Weights every point of a small shape's largest outline as Infinity, which
|
||||
// simplify never removes, so a city-state or city-sized province (Monaco, a
|
||||
// London borough) still has an outline to colour. Neighbours share those arcs,
|
||||
// so their common border stays in step.
|
||||
function protectSmallShapes(topo, objectName, features, minWeight) {
|
||||
topo.objects[objectName].geometries.forEach((geometry, i) => {
|
||||
const polygons = polygonsOf(features[i].geometry);
|
||||
const areas = polygons.map(([outer]) => planarRingArea(outer));
|
||||
const total = areas.reduce((sum, area) => sum + area, 0);
|
||||
if (polygons.length === 0 || total > minWeight * PROTECTED_SHAPE_FACTOR) {
|
||||
return;
|
||||
}
|
||||
const largest = areas.indexOf(Math.max(...areas));
|
||||
const rings =
|
||||
geometry.type === 'Polygon' ? geometry.arcs : geometry.arcs[largest];
|
||||
rings[0].forEach((index) => {
|
||||
topo.arcs[index < 0 ? ~index : index].forEach((point) => {
|
||||
point[2] = Infinity;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const isCollapsed = ([outer]) =>
|
||||
new Set(outer.map((point) => point.join())).size < 3;
|
||||
|
||||
// Simplifying can collapse a tiny island until its ring runs the other way; d3
|
||||
// then reads it as "the whole globe except this island" and floods the map.
|
||||
const isInverted = (coordinates) =>
|
||||
geoArea({ type: 'Polygon', coordinates }) > 2 * Math.PI;
|
||||
|
||||
/**
|
||||
* One feature collection to a simplified, quantized topology under
|
||||
* `objectName`. Polygons that collapse to a sliver or flip inside out are
|
||||
* dropped and the topology rebuilt without them.
|
||||
*/
|
||||
export function simplifyAndQuantize(
|
||||
objectName,
|
||||
features,
|
||||
minWeight,
|
||||
quantization,
|
||||
) {
|
||||
let topo = presimplify(
|
||||
topology({ [objectName]: { type: 'FeatureCollection', features } }),
|
||||
);
|
||||
protectSmallShapes(topo, objectName, features, minWeight);
|
||||
topo = simplify(topo, minWeight);
|
||||
// presimplify stores each point's weight as a third coordinate and simplify
|
||||
// keeps it, so it is dropped before quantizing (which would carry it through).
|
||||
topo = { ...topo, arcs: topo.arcs.map((arc) => arc.map(([x, y]) => [x, y])) };
|
||||
topo = quantize(topo, quantization);
|
||||
|
||||
let flipped = 0;
|
||||
let collapsed = 0;
|
||||
const cleaned = feature(topo, topo.objects[objectName]).features.map((f) => {
|
||||
const kept = polygonsOf(f.geometry).filter((coordinates) => {
|
||||
if (isCollapsed(coordinates)) {
|
||||
collapsed += 1;
|
||||
return false;
|
||||
}
|
||||
if (isInverted(coordinates)) {
|
||||
flipped += 1;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return { ...f, geometry: { type: 'MultiPolygon', coordinates: kept } };
|
||||
});
|
||||
const emptied = cleaned
|
||||
.filter((f) => f.geometry.coordinates.length === 0)
|
||||
.map((f) => f.properties.code ?? f.properties.name);
|
||||
|
||||
if (flipped > 0 || collapsed > 0) {
|
||||
topo = quantize(
|
||||
topology({
|
||||
[objectName]: { type: 'FeatureCollection', features: cleaned },
|
||||
}),
|
||||
quantization,
|
||||
);
|
||||
}
|
||||
return { topo, flipped, collapsed, emptied };
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
// Natural Earth admin-1 → one states/provinces topology per country.
|
||||
// Called by build.mjs; not run on its own.
|
||||
//
|
||||
// Skips countries with fewer than MIN_SUBDIVISIONS coded states, merges shapes
|
||||
// split along retired lines, and records aliases for renamed codes. Returns one
|
||||
// file per country and a report of what was skipped, merged or dropped.
|
||||
import { geoArea } from 'd3-geo';
|
||||
import { topology } from 'topojson-server';
|
||||
import { merge } from 'topojson-client';
|
||||
|
||||
import {
|
||||
MIN_SUBDIVISIONS,
|
||||
SUBDIVISION_ALIASES,
|
||||
SUBDIVISION_MERGES,
|
||||
SUBDIVISION_MIN_WEIGHT,
|
||||
SUBDIVISION_QUANTIZATION,
|
||||
} from './config.mjs';
|
||||
import { isCountryCode } from './countries.mjs';
|
||||
import { round, simplifyAndQuantize } from './geometry.mjs';
|
||||
|
||||
const SUBDIVISION_CODE = /^[A-Z]{2}-[A-Z0-9]{1,3}$/;
|
||||
|
||||
/** Retired code → `[current code, current name]`, from `SUBDIVISION_MERGES`. */
|
||||
const RECODES = new Map(
|
||||
Object.values(SUBDIVISION_MERGES).flatMap((merges) =>
|
||||
Object.entries(merges).flatMap(([code, [name, retired]]) =>
|
||||
retired.map((old) => [old, [code, name]]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/** A country's aliases: the hand-written ones, then each merge's retired codes. */
|
||||
function aliasesOf(country) {
|
||||
const aliases = { ...SUBDIVISION_ALIASES[country] };
|
||||
for (const [code, [, retired]] of Object.entries(
|
||||
SUBDIVISION_MERGES[country] ?? {},
|
||||
)) {
|
||||
for (const old of retired) {
|
||||
if (old !== code) {
|
||||
aliases[old] = code;
|
||||
}
|
||||
}
|
||||
}
|
||||
return aliases;
|
||||
}
|
||||
|
||||
// Shapes without an ISO 3166-2 code can't be matched to data, and a code under
|
||||
// another country's prefix (Puerto Rico's `US-PR`) belongs to that country's
|
||||
// file. Retired codes are rewritten to the current ones here, so the merge
|
||||
// below dissolves them.
|
||||
function groupByCountry(sourceFeatures) {
|
||||
const byCountry = new Map();
|
||||
const uncoded = {};
|
||||
const recoded = new Set();
|
||||
for (const f of sourceFeatures) {
|
||||
const country = f.properties.iso_a2;
|
||||
if (!isCountryCode(country)) {
|
||||
continue;
|
||||
}
|
||||
const code = f.properties.iso_3166_2;
|
||||
if (!SUBDIVISION_CODE.test(code ?? '') || !code.startsWith(`${country}-`)) {
|
||||
uncoded[country] = (uncoded[country] ?? 0) + 1;
|
||||
continue;
|
||||
}
|
||||
if (!byCountry.has(country)) {
|
||||
byCountry.set(country, []);
|
||||
}
|
||||
const recode = RECODES.get(code);
|
||||
if (recode) {
|
||||
recoded.add(code);
|
||||
}
|
||||
byCountry.get(country).push(
|
||||
recode
|
||||
? {
|
||||
...f,
|
||||
properties: {
|
||||
...f.properties,
|
||||
iso_3166_2: recode[0],
|
||||
name: recode[1],
|
||||
},
|
||||
}
|
||||
: f,
|
||||
);
|
||||
}
|
||||
return { byCountry, uncoded, recoded };
|
||||
}
|
||||
|
||||
// Natural Earth splits some codes across shapes (Dublin's four councils are all
|
||||
// `IE-D`). Merging them through a topology drops the borders between the parts,
|
||||
// so one code is one shape with one outline.
|
||||
function mergeByCode(features) {
|
||||
const byCode = new Map();
|
||||
for (const f of features) {
|
||||
const code = f.properties.iso_3166_2;
|
||||
if (!byCode.has(code)) {
|
||||
byCode.set(code, []);
|
||||
}
|
||||
byCode.get(code).push(f);
|
||||
}
|
||||
const topo = topology({ parts: { type: 'FeatureCollection', features } });
|
||||
const { geometries } = topo.objects.parts;
|
||||
let merged = 0;
|
||||
const shapes = [...byCode].map(([code, members]) => {
|
||||
// The largest part carries the name and label point.
|
||||
const primary = members.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
|
||||
let geometry = primary.geometry;
|
||||
if (members.length > 1) {
|
||||
merged += members.length - 1;
|
||||
geometry = merge(
|
||||
topo,
|
||||
geometries.filter((_, i) => features[i].properties.iso_3166_2 === code),
|
||||
);
|
||||
}
|
||||
return {
|
||||
type: 'Feature',
|
||||
id: code,
|
||||
properties: {
|
||||
code,
|
||||
name: primary.properties.name,
|
||||
label: [
|
||||
round(primary.properties.longitude),
|
||||
round(primary.properties.latitude),
|
||||
],
|
||||
},
|
||||
geometry,
|
||||
};
|
||||
});
|
||||
return { shapes: shapes.sort((a, b) => a.id.localeCompare(b.id)), merged };
|
||||
}
|
||||
|
||||
/**
|
||||
* Lower-cased English names → code, for data that names a state. A main name
|
||||
* outranks a neighbour's alternate spelling of it.
|
||||
*/
|
||||
function namesOf(members) {
|
||||
const names = {};
|
||||
const mainNames = new Set();
|
||||
for (const { properties: p } of members) {
|
||||
const main = p.name?.toLowerCase();
|
||||
if (main && !mainNames.has(main)) {
|
||||
mainNames.add(main);
|
||||
names[main] = p.iso_3166_2;
|
||||
}
|
||||
for (const name of [p.name_en, p.gn_name, p.woe_name]) {
|
||||
if (name) {
|
||||
names[name.toLowerCase()] ??= p.iso_3166_2;
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Natural Earth admin-1 GeoJSON → `{ files, report }`, where `files` maps each
|
||||
* country with enough coded states to its outlines file, in code order.
|
||||
*/
|
||||
export function buildSubdivisions(source) {
|
||||
const { byCountry, uncoded, recoded } = groupByCountry(source.features);
|
||||
const files = new Map();
|
||||
const report = {
|
||||
skippedUnderMinimum: [],
|
||||
mergedParts: {},
|
||||
uncodedShapes: uncoded,
|
||||
droppedFlippedIslands: {},
|
||||
droppedCollapsedPolygons: 0,
|
||||
emptiedShapes: [],
|
||||
// Merge entries whose retired code Natural Earth no longer has.
|
||||
unmatchedRetiredCodes: [...RECODES.keys()].filter(
|
||||
(code) => !recoded.has(code),
|
||||
),
|
||||
};
|
||||
|
||||
const countries = [...byCountry.keys()].sort((a, b) => a.localeCompare(b));
|
||||
for (const country of countries) {
|
||||
const members = byCountry.get(country);
|
||||
const { shapes, merged } = mergeByCode(members);
|
||||
if (shapes.length < MIN_SUBDIVISIONS) {
|
||||
report.skippedUnderMinimum.push(country);
|
||||
continue;
|
||||
}
|
||||
if (merged) {
|
||||
report.mergedParts[country] = merged;
|
||||
}
|
||||
const { topo, flipped, collapsed, emptied } = simplifyAndQuantize(
|
||||
'subdivisions',
|
||||
shapes,
|
||||
SUBDIVISION_MIN_WEIGHT,
|
||||
SUBDIVISION_QUANTIZATION,
|
||||
);
|
||||
if (flipped) {
|
||||
report.droppedFlippedIslands[country] = flipped;
|
||||
}
|
||||
report.droppedCollapsedPolygons += collapsed;
|
||||
report.emptiedShapes.push(...emptied);
|
||||
files.set(country, {
|
||||
...topo,
|
||||
aliases: aliasesOf(country),
|
||||
names: namesOf(members),
|
||||
});
|
||||
}
|
||||
return { files, report };
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
// Invariants the chart relies on, checked before anything is written. A
|
||||
// failure names every problem; the committed assets are left untouched.
|
||||
// Called by build.mjs; not run on its own.
|
||||
//
|
||||
// Checks shape counts, that no shape is emptied or drawn twice, and that every
|
||||
// code, alias and name resolves to a drawn shape.
|
||||
import { feature } from 'topojson-client';
|
||||
|
||||
import { MIN_SUBDIVISIONS } from './config.mjs';
|
||||
|
||||
// Natural Earth v5.1.2 yields 239 countries and 198 countries with states. A
|
||||
// drop below these means a changed or truncated download, not real geography.
|
||||
const MIN_COUNTRIES = 230;
|
||||
const MIN_SUBDIVISION_COUNTRIES = 190;
|
||||
|
||||
function duplicatesOf(values) {
|
||||
const seen = new Set();
|
||||
return values.filter((value) => seen.has(value) || !seen.add(value));
|
||||
}
|
||||
|
||||
function checkCountries({ topology, lookups, report }, problems) {
|
||||
const shapes = feature(topology, topology.objects.countries).features;
|
||||
const codes = shapes.map((shape) => shape.properties.code).filter(Boolean);
|
||||
const drawn = new Set(codes);
|
||||
|
||||
if (shapes.length < MIN_COUNTRIES) {
|
||||
problems.push(
|
||||
`only ${shapes.length} countries (expected ≥ ${MIN_COUNTRIES})`,
|
||||
);
|
||||
}
|
||||
if (report.emptied) {
|
||||
problems.push(`countries left with no outline: ${report.emptied}`);
|
||||
}
|
||||
for (const code of duplicatesOf(codes)) {
|
||||
problems.push(`country code ${code} is drawn twice`);
|
||||
}
|
||||
if (lookups.codes.join() !== [...drawn].sort().join()) {
|
||||
problems.push('lookups.codes differs from the drawn country codes');
|
||||
}
|
||||
for (const [alias, target] of Object.entries(lookups.aliases)) {
|
||||
if (!drawn.has(target)) {
|
||||
problems.push(`country alias ${alias} → ${target}, which has no shape`);
|
||||
}
|
||||
}
|
||||
for (const [alpha3, target] of Object.entries(lookups.alpha3)) {
|
||||
if (!drawn.has(target)) {
|
||||
problems.push(`alpha-3 ${alpha3} → ${target}, which has no shape`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkSubdivisionFile(country, file, problems) {
|
||||
const codes = file.objects.subdivisions.geometries.map(
|
||||
(geometry) => geometry.properties.code,
|
||||
);
|
||||
const known = new Set(codes);
|
||||
|
||||
if (codes.length < MIN_SUBDIVISIONS) {
|
||||
problems.push(
|
||||
`${country}: ${codes.length} states (expected ≥ ${MIN_SUBDIVISIONS})`,
|
||||
);
|
||||
}
|
||||
for (const code of duplicatesOf(codes)) {
|
||||
problems.push(`${country}: state code ${code} is drawn twice`);
|
||||
}
|
||||
for (const code of codes) {
|
||||
if (!code?.startsWith(`${country}-`)) {
|
||||
problems.push(`${country}: state code ${code} is outside the country`);
|
||||
}
|
||||
}
|
||||
for (const [alias, target] of Object.entries(file.aliases)) {
|
||||
if (!known.has(target)) {
|
||||
problems.push(`${country}: alias ${alias} → ${target}, which has no shape`);
|
||||
}
|
||||
}
|
||||
for (const [name, code] of Object.entries(file.names)) {
|
||||
if (!known.has(code)) {
|
||||
problems.push(`${country}: name "${name}" → ${code}, which has no shape`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkSubdivisions({ files, report }, problems) {
|
||||
if (files.size < MIN_SUBDIVISION_COUNTRIES) {
|
||||
problems.push(
|
||||
`only ${files.size} countries with states (expected ≥ ${MIN_SUBDIVISION_COUNTRIES})`,
|
||||
);
|
||||
}
|
||||
if (report.emptiedShapes.length > 0) {
|
||||
problems.push(
|
||||
`states left with no outline: ${report.emptiedShapes.join(' ')}`,
|
||||
);
|
||||
}
|
||||
if (report.unmatchedRetiredCodes.length > 0) {
|
||||
problems.push(
|
||||
`merge codes not found in Natural Earth: ${report.unmatchedRetiredCodes.join(' ')}`,
|
||||
);
|
||||
}
|
||||
for (const [country, file] of files) {
|
||||
checkSubdivisionFile(country, file, problems);
|
||||
}
|
||||
}
|
||||
|
||||
/** Throws one error listing every broken invariant. */
|
||||
export function validate(countries, subdivisions) {
|
||||
const problems = [];
|
||||
checkCountries(countries, problems);
|
||||
checkSubdivisions(subdivisions, problems);
|
||||
if (problems.length > 0) {
|
||||
throw new Error(
|
||||
`${problems.length} problem(s) in the generated outlines:\n- ${problems.join('\n- ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ import { useAppContext } from 'providers/App/App';
|
||||
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
|
||||
import { OrgPreference } from 'types/api/preferences/preference';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { isSignozAdminEmail } from 'utils/app';
|
||||
import {
|
||||
routePermission,
|
||||
routeWithInitialAuthZSupport,
|
||||
@@ -26,8 +25,6 @@ import routes, {
|
||||
ROUTES_NOT_TO_BE_OVERRIDEN,
|
||||
SUPPORT_ROUTE,
|
||||
} from './routes';
|
||||
import { useAuthZ } from '@/lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { UserListPermission } from '@/lib/authz/hooks/useAuthZ/permissions/user.permissions';
|
||||
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
@@ -68,16 +65,9 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
return undefined;
|
||||
}, [org]);
|
||||
|
||||
const { permissions: authzPermission } = useAuthZ([UserListPermission], {
|
||||
enabled: isLoggedInState,
|
||||
});
|
||||
|
||||
const canListUsers = authzPermission?.[UserListPermission]?.isGranted ?? false;
|
||||
|
||||
// Without `list:user` the list isn't fetched, so the onboarding redirect is skipped.
|
||||
const { data: usersData, isFetching: isFetchingUsers } = useListUsers({
|
||||
query: {
|
||||
enabled: !isEmpty(orgData) && canListUsers,
|
||||
enabled: !isEmpty(orgData) && user.role === 'ADMIN',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -85,7 +75,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
const users = usersData?.data || [];
|
||||
|
||||
const remainingUsers = (Array.isArray(users) ? users : []).filter(
|
||||
(u) => !isSignozAdminEmail(u.email),
|
||||
(user) => user.email !== 'admin@signoz.cloud',
|
||||
);
|
||||
|
||||
return remainingUsers.length === 1;
|
||||
@@ -171,9 +161,10 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
const isRouteEnabledForWorkspaceBlockedState =
|
||||
pathname === ROUTES.SETTINGS ||
|
||||
pathname === ROUTES.BILLING ||
|
||||
pathname === ROUTES.MEMBERS_SETTINGS ||
|
||||
(isAdmin &&
|
||||
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
|
||||
(pathname === ROUTES.ORG_SETTINGS ||
|
||||
pathname === ROUTES.MEMBERS_SETTINGS ||
|
||||
pathname === ROUTES.MY_SETTINGS));
|
||||
|
||||
if (
|
||||
pathname !== ROUTES.WORKSPACE_LOCKED &&
|
||||
@@ -212,7 +203,6 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
const isFirstUser = checkFirstTimeUser();
|
||||
if (
|
||||
isFirstUser &&
|
||||
!isSignozAdminEmail(user.email) &&
|
||||
!isOnboardingComplete &&
|
||||
!ROUTES_NOT_TO_BE_OVERRIDEN.includes(pathname) &&
|
||||
pathname !== ROUTES.ONBOARDING
|
||||
|
||||
@@ -2,18 +2,9 @@ import { ReactElement } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import { MemoryRouter, Route, Switch, useLocation } from 'react-router-dom';
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import { useListUsers } from 'api/generated/services/users';
|
||||
import { SIGNOZ_ADMIN_EMAIL } from 'constants/app';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { ORG_PREFERENCES } from 'constants/orgPreferences';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { UserListPermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
|
||||
import {
|
||||
AUTHZ_CHECK_URL,
|
||||
setupAuthzAdmin,
|
||||
setupAuthzDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { AppContext } from 'providers/App/App';
|
||||
import { IAppContext, IUser } from 'providers/App/types';
|
||||
import {
|
||||
@@ -785,7 +776,7 @@ describe('PrivateRoute', () => {
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
|
||||
});
|
||||
|
||||
it('should allow VIEWER to access members settings when workspace is blocked', () => {
|
||||
it('should redirect VIEWER to workspace locked when trying to access members settings', async () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.MEMBERS_SETTINGS,
|
||||
appContext: {
|
||||
@@ -798,7 +789,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertStaysOnRoute(ROUTES.MEMBERS_SETTINGS);
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
|
||||
});
|
||||
|
||||
it('should redirect VIEWER to workspace locked when trying to access my-settings', async () => {
|
||||
@@ -1098,99 +1089,6 @@ describe('PrivateRoute', () => {
|
||||
await assertRedirectsTo(ROUTES.ONBOARDING);
|
||||
});
|
||||
|
||||
it('should not redirect the signoz admin to onboarding while the first user has not completed it', async () => {
|
||||
mockUsersData = [
|
||||
{ email: 'test@example.com' },
|
||||
{ email: SIGNOZ_ADMIN_EMAIL },
|
||||
];
|
||||
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.HOME,
|
||||
appContext: {
|
||||
isLoggedIn: true,
|
||||
isFetchingOrgPreferences: false,
|
||||
orgPreferences: createMockOrgPreferences(false),
|
||||
user: createMockUser({
|
||||
role: USER_ROLES.ADMIN as ROLES,
|
||||
email: SIGNOZ_ADMIN_EMAIL,
|
||||
}),
|
||||
},
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('fetches the user list for a non-admin role that has list:user', async () => {
|
||||
server.use(setupAuthzAdmin());
|
||||
jest.mocked(useListUsers).mockClear();
|
||||
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.HOME,
|
||||
appContext: {
|
||||
isLoggedIn: true,
|
||||
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
|
||||
},
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(useListUsers).toHaveBeenLastCalledWith({
|
||||
query: { enabled: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not check list:user while logged out', async () => {
|
||||
const authzCheck = jest.fn();
|
||||
server.use(
|
||||
rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => {
|
||||
authzCheck();
|
||||
return res(ctx.status(401));
|
||||
}),
|
||||
);
|
||||
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.HOME,
|
||||
appContext: { isLoggedIn: false },
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 50);
|
||||
});
|
||||
});
|
||||
|
||||
expect(authzCheck).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not fetch the user list for an admin without list:user', async () => {
|
||||
server.use(setupAuthzDeny(UserListPermission));
|
||||
jest.mocked(useListUsers).mockClear();
|
||||
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.HOME,
|
||||
appContext: {
|
||||
isLoggedIn: true,
|
||||
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
|
||||
},
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(useListUsers).not.toHaveBeenCalledWith({
|
||||
query: { enabled: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('should not redirect to onboarding when org preferences are still fetching', () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.HOME,
|
||||
|
||||
@@ -5660,13 +5660,6 @@ export interface DashboardtypesBasicVisualizationDTO {
|
||||
timePreference?: DashboardtypesTimePreferenceDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* @minimum 1
|
||||
* @maximum 64
|
||||
* @nullable
|
||||
*/
|
||||
export type DashboardtypesBubbleRadiusDTO = number | null;
|
||||
|
||||
export interface Querybuildertypesv5LogAggregationDTO {
|
||||
/**
|
||||
* @type string
|
||||
@@ -6950,246 +6943,6 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
|
||||
spec: DashboardtypesScatterPlotPanelSpecDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* The panel kind.
|
||||
*/
|
||||
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTOKind {
|
||||
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
|
||||
}
|
||||
/**
|
||||
* Radius of the largest circle, in CSS pixels from 1 to 64. Null means 8 on the points layer, 28 otherwise.
|
||||
*/
|
||||
export type DashboardtypesGeoMapBubblesDTOMaxRadius = DashboardtypesBubbleRadiusDTO | null;
|
||||
|
||||
/**
|
||||
* Radius of the smallest circle, in CSS pixels from 1 to 64. Null means 2 on the points layer, 3 otherwise.
|
||||
*/
|
||||
export type DashboardtypesGeoMapBubblesDTOMinRadius = DashboardtypesBubbleRadiusDTO | null;
|
||||
|
||||
export interface DashboardtypesGeoMapBubblesDTO {
|
||||
/**
|
||||
* @description Radius of the largest circle, in CSS pixels from 1 to 64. Null means 8 on the points layer, 28 otherwise.
|
||||
*/
|
||||
maxRadius?: DashboardtypesGeoMapBubblesDTOMaxRadius;
|
||||
/**
|
||||
* @description Radius of the smallest circle, in CSS pixels from 1 to 64. Null means 2 on the points layer, 3 otherwise.
|
||||
*/
|
||||
minRadius?: DashboardtypesGeoMapBubblesDTOMinRadius;
|
||||
}
|
||||
|
||||
export interface DashboardtypesGeoMapColorsDTO {
|
||||
/**
|
||||
* @type string
|
||||
* @description The hex color varied in opacity mode. Empty uses the default fill.
|
||||
*/
|
||||
fill?: string;
|
||||
/**
|
||||
* @type number,null
|
||||
* @description The value mapped to the highest color. Null uses the highest value in the data.
|
||||
*/
|
||||
max?: number | null;
|
||||
/**
|
||||
* @type number,null
|
||||
* @description The value mapped to the lowest color. Null uses the lowest value in the data. Must not exceed max.
|
||||
*/
|
||||
min?: number | null;
|
||||
/**
|
||||
* @description How values are colored: palette (default) picks a hue from palette, opacity varies the opacity of fill.
|
||||
*/
|
||||
mode?: DashboardtypesHeatmapColorModeDTO;
|
||||
/**
|
||||
* @description The named color ramp used in palette mode, such as lava (default), ice or ember.
|
||||
*/
|
||||
palette?: DashboardtypesHeatmapPaletteDTO;
|
||||
/**
|
||||
* @description How values map onto the color range: log (default), sqrt or linear.
|
||||
*/
|
||||
scale?: DashboardtypesHeatmapColorScaleDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @description The number of distinct color steps, 2 to 128. 0 uses the chart default.
|
||||
*/
|
||||
steps?: number;
|
||||
}
|
||||
|
||||
export interface DashboardtypesGeoMapChartAppearanceDTO {
|
||||
/**
|
||||
* @description The circle radius range of the bubbles and points layers.
|
||||
*/
|
||||
bubbles?: DashboardtypesGeoMapBubblesDTO;
|
||||
/**
|
||||
* @description The color scale applied to the colorBy values.
|
||||
*/
|
||||
colors?: DashboardtypesGeoMapColorsDTO;
|
||||
/**
|
||||
* @type boolean,null
|
||||
* @description Shows country and state names once each fits inside its shape. Null shows them.
|
||||
*/
|
||||
labels?: boolean | null;
|
||||
}
|
||||
|
||||
export enum DashboardtypesGeoMapCountryFormatDTO {
|
||||
auto = 'auto',
|
||||
alpha2 = 'alpha2',
|
||||
alpha3 = 'alpha3',
|
||||
name = 'name',
|
||||
}
|
||||
export enum DashboardtypesGeoMapLocationModeDTO {
|
||||
auto = 'auto',
|
||||
country = 'country',
|
||||
subdivision = 'subdivision',
|
||||
coordinates = 'coordinates',
|
||||
}
|
||||
export interface DashboardtypesGeoMapLocationDTO {
|
||||
/**
|
||||
* @type string
|
||||
* @description Group-by key holding the country, for the country and subdivision modes. Empty detects it by name, such as geo.country.iso_code.
|
||||
*/
|
||||
country?: string;
|
||||
/**
|
||||
* @description How country values are written: auto (default) detects it, alpha2, alpha3 or name.
|
||||
*/
|
||||
countryFormat: DashboardtypesGeoMapCountryFormatDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Group-by key holding the latitude, for the coordinates mode. Empty detects it by name.
|
||||
*/
|
||||
lat?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Group-by key holding the longitude, for the coordinates mode. Empty detects it by name.
|
||||
*/
|
||||
lon?: string;
|
||||
/**
|
||||
* @description How rows are placed: auto (default) detects it from the group-by keys, country, subdivision or coordinates.
|
||||
*/
|
||||
mode: DashboardtypesGeoMapLocationModeDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Group-by key holding the ISO 3166-2 region code (e.g. geo.region.iso_code), for the subdivision mode. Empty detects it by name.
|
||||
*/
|
||||
region?: string;
|
||||
}
|
||||
|
||||
export enum DashboardtypesGeoMapLayerDTO {
|
||||
regions = 'regions',
|
||||
bubbles = 'bubbles',
|
||||
points = 'points',
|
||||
}
|
||||
export enum DashboardtypesGeoMapProjectionDTO {
|
||||
mercator = 'mercator',
|
||||
equal_earth = 'equal_earth',
|
||||
natural_earth = 'natural_earth',
|
||||
}
|
||||
export enum DashboardtypesGeoMapViewDTO {
|
||||
world = 'world',
|
||||
fit = 'fit',
|
||||
africa = 'africa',
|
||||
asia = 'asia',
|
||||
europe = 'europe',
|
||||
north_america = 'north_america',
|
||||
south_america = 'south_america',
|
||||
oceania = 'oceania',
|
||||
country = 'country',
|
||||
}
|
||||
export interface DashboardtypesGeoMapSettingsDTO {
|
||||
/**
|
||||
* @type string
|
||||
* @description Value column key, as in a Table panel, that sets the color. Empty uses the first value column.
|
||||
*/
|
||||
colorBy?: string;
|
||||
/**
|
||||
* @description What is drawn: regions (default) fills each shape, bubbles draws a circle per region, points a circle per coordinate.
|
||||
*/
|
||||
layer: DashboardtypesGeoMapLayerDTO;
|
||||
/**
|
||||
* @description The map projection: mercator (default), equal_earth or natural_earth.
|
||||
*/
|
||||
projection: DashboardtypesGeoMapProjectionDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Value column key, as in a Table panel, that sets the bubble or point size. Empty uses colorBy.
|
||||
*/
|
||||
sizeBy?: string;
|
||||
/**
|
||||
* @description The area shown: world (default), fit to the data, a continent, or country with viewCountry.
|
||||
*/
|
||||
view: DashboardtypesGeoMapViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Uppercase ISO 3166-1 alpha-2 code of the country the country view shows.
|
||||
*/
|
||||
viewCountry?: string;
|
||||
}
|
||||
|
||||
export interface DashboardtypesGeoMapThresholdDTO {
|
||||
/**
|
||||
* @type string
|
||||
* @description The CSS color of the shape, bubble or point while the threshold is active, for example #F1575F; CSS named colors such as red also work.
|
||||
*/
|
||||
color: string;
|
||||
/**
|
||||
* @description The comparison that activates the threshold: above (default), below, above_or_equal, below_or_equal, equal or not_equal.
|
||||
*/
|
||||
operator?: DashboardtypesComparisonOperatorDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description The unit id of value, such as ms or percent. Empty means the colorBy column's unit.
|
||||
*/
|
||||
unit?: string;
|
||||
/**
|
||||
* @type number
|
||||
* @format double
|
||||
* @description The value compared against, in unit.
|
||||
*/
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface DashboardtypesGeoMapPanelSpecDTO {
|
||||
/**
|
||||
* @description Color scale, bubble size and labels.
|
||||
*/
|
||||
chartAppearance?: DashboardtypesGeoMapChartAppearanceDTO;
|
||||
/**
|
||||
* @description Per-column units and decimal precision.
|
||||
*/
|
||||
formatting?: DashboardtypesTableFormattingDTO;
|
||||
/**
|
||||
* @description Legend placement.
|
||||
*/
|
||||
legend?: DashboardtypesLegendDTO;
|
||||
/**
|
||||
* @description The group-by columns that place each row on the map.
|
||||
*/
|
||||
location?: DashboardtypesGeoMapLocationDTO;
|
||||
/**
|
||||
* @description Layer, view, projection and the value columns drawn.
|
||||
*/
|
||||
map?: DashboardtypesGeoMapSettingsDTO;
|
||||
/**
|
||||
* @type array,null
|
||||
* @description Rules that recolor a shape, bubble or point when its value compares to a threshold as specified.
|
||||
*/
|
||||
thresholds?: DashboardtypesGeoMapThresholdDTO[] | null;
|
||||
/**
|
||||
* @description The time range the values are computed over.
|
||||
*/
|
||||
visualization?: DashboardtypesBasicVisualizationDTO;
|
||||
}
|
||||
|
||||
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO {
|
||||
/**
|
||||
* @enum signoz/GeoMapPanel
|
||||
* @type string
|
||||
* @description The panel kind.
|
||||
*/
|
||||
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTOKind;
|
||||
/**
|
||||
* @description The options for this panel kind. {} accepts every default.
|
||||
*/
|
||||
spec: DashboardtypesGeoMapPanelSpecDTO;
|
||||
}
|
||||
|
||||
export type DashboardtypesPanelPluginDTO =
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
|
||||
@@ -7201,8 +6954,7 @@ export type DashboardtypesPanelPluginDTO =
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO;
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO;
|
||||
|
||||
export enum Querybuildertypesv5RequestTypeDTO {
|
||||
scalar = 'scalar',
|
||||
@@ -8489,7 +8241,6 @@ export enum DashboardtypesPanelPluginKindDTO {
|
||||
'signoz/TextPanel' = 'signoz/TextPanel',
|
||||
'signoz/HeatmapPanel' = 'signoz/HeatmapPanel',
|
||||
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
|
||||
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
|
||||
}
|
||||
/**
|
||||
* The RFC 6902 operations, applied in order against the dashboard's postable shape.
|
||||
|
||||
@@ -54,7 +54,6 @@ export function mapPanelTypeToRequestType(panelType: PANEL_TYPES): RequestType {
|
||||
case PANEL_TYPES.SCATTER:
|
||||
case PANEL_TYPES.PIE:
|
||||
case PANEL_TYPES.VALUE:
|
||||
case PANEL_TYPES.GEO_MAP:
|
||||
return 'scalar';
|
||||
case PANEL_TYPES.TRACE:
|
||||
return 'trace';
|
||||
@@ -278,8 +277,7 @@ export function createAggregation(
|
||||
(panelType === PANEL_TYPES.TABLE ||
|
||||
panelType === PANEL_TYPES.SCATTER ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.GEO_MAP);
|
||||
panelType === PANEL_TYPES.VALUE);
|
||||
|
||||
if (queryData.dataSource === DataSource.METRICS) {
|
||||
return [
|
||||
|
||||
@@ -54,9 +54,6 @@ function AddCreditCardModal({
|
||||
updateCreditCard({ url: getBaseUrl() });
|
||||
};
|
||||
|
||||
// TODO: antd stacks at 1000, under `@signozhq/ui` dialogs (1001). Opened from
|
||||
// CustomDomainEditModal's "Contact Support" it renders behind that dialog.
|
||||
// Moving to the `@signozhq/ui` Dialog fixes it.
|
||||
return (
|
||||
<Modal
|
||||
className="add-credit-card-modal"
|
||||
@@ -93,17 +90,10 @@ function AddCreditCardModal({
|
||||
</AuthZTooltip>,
|
||||
]}
|
||||
>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
<Typography.Text className="add-credit-card-text">
|
||||
You're currently on <span className="highlight-text">Trial plan</span>.
|
||||
Add a credit card to access SigNoz chat support to your workspace.
|
||||
</Typography>
|
||||
</Typography.Text>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ function AlertBreadcrumb({
|
||||
items={breadcrumbItems}
|
||||
data-testid={testId}
|
||||
/>
|
||||
{showDivider && <Divider spacing="10px 16px" />}
|
||||
{showDivider && <Divider className={styles.divider} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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';
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
}
|
||||
|
||||
.brand-title {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: var(--l1-foreground); // Primary text
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
// Clears the header of a drawer or dialog panel, 16px from the edge plus 48px or 56px.
|
||||
:global(body):has([data-slot='drawer-popup'], [data-slot='dialog-popup'])
|
||||
.toaster {
|
||||
--toast-viewport-offset-top: var(--spacing-40);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { Toaster } from '@signozhq/ui/toast';
|
||||
|
||||
import styles from './AppToaster.module.scss';
|
||||
|
||||
// The bottom clears the page-size select of a pagination bar, 83px above the bottom strip, and
|
||||
// the 56px footer of a drawer or dialog panel, which sits 16px from the edge of the window.
|
||||
const OFFSET = {
|
||||
top: 24,
|
||||
right: 24,
|
||||
bottom: 'calc(var(--bottom-strip-height, 0px) + 92px)',
|
||||
left: 24,
|
||||
};
|
||||
|
||||
function AppToaster(): JSX.Element {
|
||||
return (
|
||||
<Toaster position="bottom-right" offset={OFFSET} className={styles.toaster} />
|
||||
);
|
||||
}
|
||||
|
||||
export default AppToaster;
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -17,3 +17,8 @@
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.divider {
|
||||
--divider-color: var(--l1-border);
|
||||
--divider-margin: 10px 0 16px 0;
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ function BackHeader({
|
||||
</Button>
|
||||
<div className={styles.title}>{title}</div>
|
||||
</div>
|
||||
<Divider spacing="10px 16px" />
|
||||
<Divider className={styles.divider} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { Row, Select, Spin } from 'antd';
|
||||
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import {
|
||||
@@ -18,7 +17,6 @@ export interface SelectOptionConfig {
|
||||
placeholder: string;
|
||||
queryParam: QueryParams;
|
||||
filterType: string | string[];
|
||||
fieldContext?: TelemetrytypesFieldContextDTO;
|
||||
shouldSetQueryParams?: boolean;
|
||||
onChange?: (value: string | string[]) => void;
|
||||
values?: string | string[];
|
||||
@@ -29,16 +27,13 @@ export function FilterSelect({
|
||||
placeholder,
|
||||
queryParam,
|
||||
filterType,
|
||||
fieldContext,
|
||||
values,
|
||||
shouldSetQueryParams,
|
||||
onChange,
|
||||
isMultiple,
|
||||
}: SelectOptionConfig): JSX.Element {
|
||||
const { handleSearch, isFetching, options } = useCeleryFilterOptions(
|
||||
filterType,
|
||||
fieldContext,
|
||||
);
|
||||
const { handleSearch, isFetching, options } =
|
||||
useCeleryFilterOptions(filterType);
|
||||
|
||||
const urlQuery = useUrlQuery();
|
||||
const location = useAppLocation();
|
||||
@@ -123,7 +118,6 @@ export function FilterSelect({
|
||||
}
|
||||
|
||||
FilterSelect.defaultProps = {
|
||||
fieldContext: undefined,
|
||||
shouldSetQueryParams: true,
|
||||
onChange: (): void => {},
|
||||
values: [],
|
||||
@@ -135,14 +129,12 @@ function CeleryOverviewConfigOptions(): JSX.Element {
|
||||
{
|
||||
placeholder: 'Service Name',
|
||||
queryParam: QueryParams.service,
|
||||
filterType: 'service.name',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.resource,
|
||||
filterType: 'serviceName',
|
||||
},
|
||||
{
|
||||
placeholder: 'Span Name',
|
||||
queryParam: QueryParams.spanName,
|
||||
filterType: 'name',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.span,
|
||||
},
|
||||
{
|
||||
placeholder: 'Msg System',
|
||||
@@ -170,7 +162,6 @@ function CeleryOverviewConfigOptions(): JSX.Element {
|
||||
placeholder={config.placeholder}
|
||||
queryParam={config.queryParam}
|
||||
filterType={config.filterType}
|
||||
fieldContext={config.fieldContext}
|
||||
/>
|
||||
))}
|
||||
</Row>
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import type { GetFieldsValues200 } from 'api/generated/services/sigNoz.schemas';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, waitFor } from 'tests/test-utils';
|
||||
|
||||
import CeleryOverviewConfigOptions from '../CeleryOverviewConfigOptions';
|
||||
|
||||
const emptyValues: GetFieldsValues200 = {
|
||||
status: 'success',
|
||||
data: { complete: true, values: { stringValues: [] } },
|
||||
};
|
||||
|
||||
describe('CeleryOverviewConfigOptions', () => {
|
||||
it('scopes the service and span name lookups to their field context', async () => {
|
||||
const contextByKey = new Map<string, string | null>();
|
||||
server.use(
|
||||
rest.get('*/api/v1/fields/values', (req, res, ctx) => {
|
||||
contextByKey.set(
|
||||
req.url.searchParams.get('name') ?? '',
|
||||
req.url.searchParams.get('fieldContext'),
|
||||
);
|
||||
return res(ctx.status(200), ctx.json(emptyValues));
|
||||
}),
|
||||
);
|
||||
|
||||
render(<CeleryOverviewConfigOptions />);
|
||||
|
||||
await waitFor(() => expect(contextByKey.size).toBe(6));
|
||||
expect(Object.fromEntries(contextByKey)).toStrictEqual({
|
||||
'service.name': 'resource',
|
||||
name: 'span',
|
||||
'messaging.system': null,
|
||||
'messaging.destination.name': null,
|
||||
'messaging.destination': null,
|
||||
kind_string: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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]} — {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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import { useQuery } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import type { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
|
||||
import { FIELD_API_CACHE_TIME } from 'constants/queryCacheTime';
|
||||
import { getAttributesValues } from 'api/queryBuilder/getAttributesValues';
|
||||
import { DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY } from 'constants/queryBuilder';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { toFieldValues } from 'hooks/querySuggestions/useFieldValuesSuggestion';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { DATA_SOURCE_TO_SIGNAL, DataSource } from 'types/common/queryBuilder';
|
||||
import { getValuesForDataType } from 'utils/fieldValues';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
export interface Filters {
|
||||
searchText: string;
|
||||
attributeKey: string | string[];
|
||||
aggregateOperator?: string;
|
||||
dataSource?: DataSource;
|
||||
metricName?: string;
|
||||
aggregateAttribute?: string;
|
||||
filterAttributeKeyDataType?: DataTypes;
|
||||
fieldContext?: TelemetrytypesFieldContextDTO;
|
||||
tagType?: string;
|
||||
}
|
||||
|
||||
export interface GetAllFiltersResponse {
|
||||
@@ -27,41 +29,54 @@ export function useGetAllFilters(props: Filters): GetAllFiltersResponse {
|
||||
const {
|
||||
searchText,
|
||||
attributeKey,
|
||||
aggregateOperator,
|
||||
dataSource,
|
||||
metricName,
|
||||
aggregateAttribute,
|
||||
filterAttributeKeyDataType,
|
||||
fieldContext,
|
||||
tagType,
|
||||
} = props;
|
||||
|
||||
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
|
||||
const { data, isLoading } = useQuery(
|
||||
[
|
||||
REACT_QUERY_KEY.GET_ATTRIBUTE_VALUES,
|
||||
dataSource,
|
||||
metricName,
|
||||
attributeKey,
|
||||
fieldContext,
|
||||
searchText,
|
||||
minTime,
|
||||
maxTime,
|
||||
],
|
||||
async () => {
|
||||
const keys = Array.isArray(attributeKey) ? attributeKey : [attributeKey];
|
||||
|
||||
const responses = await Promise.all(
|
||||
keys.map((key) =>
|
||||
getFieldValueSuggestions({
|
||||
signal: DATA_SOURCE_TO_SIGNAL[dataSource || DataSource.TRACES],
|
||||
name: key,
|
||||
fieldContext,
|
||||
getAttributesValues({
|
||||
aggregateOperator: aggregateOperator || 'noop',
|
||||
dataSource: dataSource || DataSource.TRACES,
|
||||
aggregateAttribute: aggregateAttribute || '',
|
||||
attributeKey: key,
|
||||
searchText: searchText ?? '',
|
||||
metricName,
|
||||
filterAttributeKeyDataType:
|
||||
filterAttributeKeyDataType || DataTypes.String,
|
||||
tagType: tagType || 'tag',
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const uniqueValues = [
|
||||
...new Set(
|
||||
responses.flatMap((response) =>
|
||||
getValuesForDataType(toFieldValues(response), filterAttributeKeyDataType),
|
||||
),
|
||||
responses.flatMap(({ payload }) => {
|
||||
if (!payload) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dataType = filterAttributeKeyDataType || DataTypes.String;
|
||||
const key = DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY[dataType];
|
||||
return key ? payload[key] || [] : [];
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
@@ -70,7 +85,6 @@ export function useGetAllFilters(props: Filters): GetAllFiltersResponse {
|
||||
value: val,
|
||||
}));
|
||||
},
|
||||
{ staleTime: FIELD_API_CACHE_TIME },
|
||||
);
|
||||
|
||||
return { options: data ?? [], isFetching: isLoading };
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -8,9 +8,12 @@ import { CardContainer } from 'container/WidgetCard/styles';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { ChevronDown, ChevronUp } from '@signozhq/icons';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import { CaptureDataProps } from '../CeleryTaskDetail/CeleryTaskDetail';
|
||||
import { useCeleryFilterOptions } from '../useCeleryFilterOptions';
|
||||
import CeleryTaskBar from './CeleryTaskBar';
|
||||
import CeleryTaskGraph from './CeleryTaskGraph';
|
||||
import {
|
||||
@@ -20,7 +23,6 @@ import {
|
||||
celeryTasksByWorkerWidgetData,
|
||||
} from './CeleryTaskGraphUtils';
|
||||
import CeleryTaskLatencyGraph from './CeleryTaskLatencyGraph';
|
||||
import { useCeleryWorkerCount } from './useCeleryWorkerCount';
|
||||
|
||||
import './CeleryTaskGraph.style.scss';
|
||||
|
||||
@@ -69,7 +71,14 @@ export default function CeleryTaskGraphGrid({
|
||||
'Latency by worker',
|
||||
];
|
||||
|
||||
const { data: workerCount } = useCeleryWorkerCount();
|
||||
const { options } = useCeleryFilterOptions(
|
||||
'worker',
|
||||
'rate',
|
||||
DataSource.METRICS,
|
||||
'flower_task_runtime_seconds_sum',
|
||||
DataTypes.String,
|
||||
'tag',
|
||||
);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
const [collapsedSections, setCollapsedSections] = useState<{
|
||||
@@ -104,16 +113,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 +146,14 @@ 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"
|
||||
>
|
||||
{workerCount ?? '-'}
|
||||
</Typography>
|
||||
<Typography.Text className="celery-task-graph-worker-count-text">
|
||||
{options.filter((option) => option.value).length}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -179,16 +164,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 +185,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 && (
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
Querybuildertypesv5ReduceToDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
|
||||
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
|
||||
@@ -1051,34 +1042,3 @@ export const celeryRetryStateCountWidgetData = getWidgetQueryBuilder(
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
// One row per worker that reported in the range; the card counts the rows.
|
||||
export const getCeleryWorkerCountRequest = (
|
||||
startTime: number,
|
||||
endTime: number,
|
||||
): Querybuildertypesv5QueryRangeRequestDTO => ({
|
||||
schemaVersion: 'v1',
|
||||
start: Math.floor(startTime / 1e6),
|
||||
end: Math.floor(endTime / 1e6),
|
||||
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: MetricSignal.metrics,
|
||||
aggregations: [
|
||||
{
|
||||
metricName: 'flower_task_runtime_seconds_sum',
|
||||
timeAggregation: MetrictypesTimeAggregationDTO.count,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
|
||||
reduceTo: Querybuildertypesv5ReduceToDTO.sum,
|
||||
},
|
||||
],
|
||||
groupBy: [{ name: 'worker' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import store from 'store';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import CeleryTaskGraphGrid from '../CeleryTaskGraphGrid';
|
||||
|
||||
const workerCountResponse = (workers: string[]): QueryRangeV5200 => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
columns: [
|
||||
{
|
||||
name: 'worker',
|
||||
queryName: 'A',
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.group,
|
||||
},
|
||||
{
|
||||
name: '__result_0',
|
||||
queryName: 'A',
|
||||
aggregationIndex: 0,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
|
||||
},
|
||||
],
|
||||
data: workers.map((worker) => [worker, 4]),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('CeleryTaskGraphGrid worker count', () => {
|
||||
let requests: Querybuildertypesv5QueryRangeRequestDTO[];
|
||||
|
||||
beforeEach(() => {
|
||||
requests = [];
|
||||
server.use(
|
||||
rest.post('*/api/v5/query_range', async (req, res, ctx) => {
|
||||
requests.push(await req.json());
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(workerCountResponse(['worker-a', 'worker-b', ''])),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('counts the workers that reported in the selected range', async () => {
|
||||
render(<CeleryTaskGraphGrid onClick={jest.fn()} queryEnabled={false} />);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('celery-worker-count')).toHaveTextContent('2'),
|
||||
);
|
||||
|
||||
const { minTime, maxTime } = store.getState().globalTime;
|
||||
expect(requests).toStrictEqual([
|
||||
{
|
||||
schemaVersion: 'v1',
|
||||
start: Math.floor(minTime / 1e6),
|
||||
end: Math.floor(maxTime / 1e6),
|
||||
requestType: 'scalar',
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'metrics',
|
||||
aggregations: [
|
||||
{
|
||||
metricName: 'flower_task_runtime_seconds_sum',
|
||||
timeAggregation: 'count',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: 'sum',
|
||||
},
|
||||
],
|
||||
groupBy: [{ name: 'worker' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,31 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useQuery, UseQueryResult } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { queryRangeV5 } from 'api/generated/services/querier';
|
||||
import type { QueryRangeV5200 } from 'api/generated/services/sigNoz.schemas';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { getScalarResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import { getCeleryWorkerCountRequest } from './CeleryTaskGraphUtils';
|
||||
|
||||
export function useCeleryWorkerCount(): UseQueryResult<number, Error> {
|
||||
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
|
||||
const request = useMemo(
|
||||
() => getCeleryWorkerCountRequest(minTime, maxTime),
|
||||
[minTime, maxTime],
|
||||
);
|
||||
|
||||
return useQuery<QueryRangeV5200, Error, number>({
|
||||
queryKey: [REACT_QUERY_KEY.GET_CELERY_WORKER_COUNT, request],
|
||||
queryFn: ({ signal }) => queryRangeV5(request, signal),
|
||||
select: (response) =>
|
||||
(getScalarResults(response)[0]?.data ?? []).filter(([worker]) => worker)
|
||||
.length,
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,18 @@
|
||||
import { useState } from 'react';
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import type { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import useDebouncedFn from 'hooks/useDebouncedFunction';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { useGetAllFilters } from './CeleryTaskConfigOptions/useGetCeleryFilters';
|
||||
|
||||
export const useCeleryFilterOptions = (
|
||||
type: string | string[],
|
||||
fieldContext?: TelemetrytypesFieldContextDTO,
|
||||
aggregateOperator?: string,
|
||||
dataSource?: DataSource,
|
||||
aggregateAttribute?: string,
|
||||
filterAttributeKeyDataType?: DataTypes,
|
||||
tagType?: string,
|
||||
): {
|
||||
searchText: string;
|
||||
handleSearch: (value: string) => void;
|
||||
@@ -18,7 +23,11 @@ export const useCeleryFilterOptions = (
|
||||
const { isFetching, options } = useGetAllFilters({
|
||||
attributeKey: type,
|
||||
searchText,
|
||||
fieldContext,
|
||||
aggregateOperator,
|
||||
dataSource,
|
||||
aggregateAttribute,
|
||||
filterAttributeKeyDataType,
|
||||
tagType,
|
||||
});
|
||||
const handleDebouncedSearch = useDebouncedFn((searchText): void => {
|
||||
setSearchText(searchText as string);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -97,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')}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { createAppContextMock } from 'tests/fixtures/appContextMock';
|
||||
import { LicensePlatform } from 'types/api/licensesV3/getActive';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { fn } from 'storybook/test';
|
||||
|
||||
import { storyChangelog } from './__story_mockdata__/changelog';
|
||||
import {
|
||||
showsCloudChangelog,
|
||||
showsSelfHostedChangelog,
|
||||
} from './__story_mockdata__/changelogModal.play';
|
||||
|
||||
import ChangelogModal from '../ChangelogModal';
|
||||
|
||||
const { activeLicense } = createAppContextMock(USER_ROLES.ADMIN);
|
||||
|
||||
/** `AppLayout` opens it one second after load, for a version the user has not seen. */
|
||||
const meta = {
|
||||
title: 'Components/Changelog Modal',
|
||||
component: ChangelogModal,
|
||||
tags: ['play'],
|
||||
parameters: { signoz: {} },
|
||||
args: {
|
||||
changelog: storyChangelog,
|
||||
onClose: fn(),
|
||||
},
|
||||
} satisfies Meta<typeof ChangelogModal>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
/** Cloud workspaces update on their own, so the footer has no update actions. */
|
||||
export const Cloud: Story = {
|
||||
play: showsCloudChangelog,
|
||||
};
|
||||
|
||||
/** Self-hosted workspaces get "Skip for now" and "Update my workspace". */
|
||||
export const SelfHosted: Story = {
|
||||
parameters: {
|
||||
signoz: {
|
||||
appContext: {
|
||||
activeLicense: activeLicense && {
|
||||
...activeLicense,
|
||||
platform: LicensePlatform.SELF_HOSTED,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
play: showsSelfHostedChangelog,
|
||||
};
|
||||
@@ -1,62 +0,0 @@
|
||||
import {
|
||||
ChangelogSchema,
|
||||
DeploymentType,
|
||||
} from 'types/api/changelog/getChangelogByVersion';
|
||||
|
||||
const TIMESTAMP = '2026-11-03T12:00:00Z';
|
||||
|
||||
function feature(
|
||||
id: number,
|
||||
title: string,
|
||||
description: string,
|
||||
): ChangelogSchema['features'][number] {
|
||||
return {
|
||||
id,
|
||||
documentId: `feature-${id}`,
|
||||
title,
|
||||
description,
|
||||
media: null,
|
||||
sort_order: id,
|
||||
createdAt: TIMESTAMP,
|
||||
updatedAt: TIMESTAMP,
|
||||
publishedAt: TIMESTAMP,
|
||||
deployment_type: DeploymentType.ALL,
|
||||
};
|
||||
}
|
||||
|
||||
/** Long enough to scroll, so the "Scroll for more" button shows. */
|
||||
export const storyChangelog: ChangelogSchema = {
|
||||
id: 1,
|
||||
documentId: 'changelog-v0.99.0',
|
||||
version: 'v0.99.0',
|
||||
release_date: '2026-11-03',
|
||||
createdAt: TIMESTAMP,
|
||||
updatedAt: TIMESTAMP,
|
||||
publishedAt: TIMESTAMP,
|
||||
features: [
|
||||
feature(
|
||||
1,
|
||||
'Dashboard sections',
|
||||
'Group panels into **sections** you can collapse, rename and drag. Existing dashboards move into a single section the first time you edit them.',
|
||||
),
|
||||
feature(
|
||||
2,
|
||||
'Service accounts',
|
||||
'Create service accounts with their own API keys and roles. Keys can expire, and you can revoke them without touching the account. See the [docs](https://signoz.io/docs/) for the API.',
|
||||
),
|
||||
feature(
|
||||
3,
|
||||
'Faster log search',
|
||||
'Full-text search over log bodies now uses a token index:\n\n- queries over a day of logs return up to 4x faster\n- `has()` and `hasToken()` use the same index\n- the old behaviour stays behind a setting for a release',
|
||||
),
|
||||
feature(
|
||||
4,
|
||||
'Routing policies',
|
||||
'Send an alert to a channel based on its labels instead of picking the channel in every rule. Policies are evaluated in order and the first match wins.',
|
||||
),
|
||||
],
|
||||
bug_fixes:
|
||||
'- Fixed the time picker losing the selected range after a refresh.\n- Fixed trace waterfall rows overlapping when a span name wraps.\n- Fixed CSV export dropping columns with dots in their names.',
|
||||
maintenance:
|
||||
'- Upgraded the OpenTelemetry collector to the latest release.\n- Reduced the memory used by the query service on large dashboards.',
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
import { expect, screen, waitFor } from 'storybook/test';
|
||||
|
||||
const TITLE = /What’s New ⎯ Changelog : November 3, 2026/;
|
||||
|
||||
export const showsCloudChangelog = async (): Promise<void> => {
|
||||
await screen.findByRole('dialog', { name: TITLE });
|
||||
await expect(
|
||||
screen.queryByRole('button', { name: /Skip for now/ }),
|
||||
).not.toBeInTheDocument();
|
||||
};
|
||||
|
||||
export const showsSelfHostedChangelog = async (): Promise<void> => {
|
||||
await screen.findByRole('dialog', { name: TITLE });
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: /Update my workspace/ }),
|
||||
).toBeVisible(),
|
||||
);
|
||||
};
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ $item-spacing: 8px;
|
||||
.timezone-picker {
|
||||
width: 532px;
|
||||
color: var(--l2-foreground);
|
||||
font-family: $font-family;
|
||||
|
||||
&__search {
|
||||
@include flex-center;
|
||||
@@ -35,6 +36,34 @@ $item-spacing: 8px;
|
||||
width: -webkit-fill-available;
|
||||
}
|
||||
|
||||
&__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 {
|
||||
@include text-style-base;
|
||||
font-size: 8px;
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -12,4 +12,5 @@
|
||||
|
||||
.name {
|
||||
color: var(--danger-background);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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%;
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
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';
|
||||
@@ -39,17 +39,6 @@ import DeleteMemberDialog from './DeleteMemberDialog';
|
||||
import ResetLinkDialog from './ResetLinkDialog';
|
||||
|
||||
import './EditMemberDrawer.styles.scss';
|
||||
import { AuthZGuardContent } from '@/lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
import {
|
||||
buildResetPasswordPermission,
|
||||
buildUserDeletePermission,
|
||||
buildUserReadPermission,
|
||||
buildUserUpdatePermission,
|
||||
PasswordListPermission,
|
||||
} from '@/lib/authz/hooks/useAuthZ/permissions/user.permissions';
|
||||
import AuthZButton from '@/lib/authz/components/AuthZButton/AuthZButton';
|
||||
import { useAuthZ } from '@/lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import AuthZTooltip from '@/lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
|
||||
const ROOT_USER_TOOLTIP = 'This operation is not supported for the root user';
|
||||
const SELF_DELETE_TOOLTIP =
|
||||
@@ -70,7 +59,6 @@ function getDeleteTooltip(
|
||||
|
||||
function getInviteButtonLabel(
|
||||
isLoading: boolean,
|
||||
canListPassword: boolean,
|
||||
existingToken: { expiresAt?: string } | undefined,
|
||||
isExpired: boolean,
|
||||
notFound: boolean,
|
||||
@@ -78,9 +66,6 @@ function getInviteButtonLabel(
|
||||
if (isLoading) {
|
||||
return 'Checking invite...';
|
||||
}
|
||||
if (!canListPassword) {
|
||||
return 'Invite Link Unavailable';
|
||||
}
|
||||
if (existingToken && !isExpired) {
|
||||
return 'Copy Invite Link';
|
||||
}
|
||||
@@ -102,6 +87,7 @@ function toSaveApiError(err: unknown): APIError {
|
||||
|
||||
export interface EditMemberDrawerProps {
|
||||
member: MemberRow | null;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onComplete: () => void;
|
||||
}
|
||||
@@ -109,6 +95,7 @@ export interface EditMemberDrawerProps {
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
function EditMemberDrawer({
|
||||
member,
|
||||
open,
|
||||
onClose,
|
||||
onComplete,
|
||||
}: EditMemberDrawerProps): JSX.Element {
|
||||
@@ -132,47 +119,16 @@ function EditMemberDrawer({
|
||||
const isDeleted = member?.status === MemberStatus.Deleted;
|
||||
const isSelf = !!member?.id && member.id === currentUser?.id;
|
||||
|
||||
const requestPermission = useMemo(() => {
|
||||
if (member) {
|
||||
return isInvited
|
||||
? [buildUserReadPermission(member.id), PasswordListPermission]
|
||||
: [buildUserReadPermission(member.id)];
|
||||
}
|
||||
return [];
|
||||
}, [member, isInvited]);
|
||||
|
||||
const {
|
||||
permissions: authZPermission,
|
||||
error: authZError,
|
||||
isLoading: isLoadingAuthZ,
|
||||
} = useAuthZ(requestPermission);
|
||||
|
||||
const canReadUser = member
|
||||
? !!authZError ||
|
||||
(authZPermission?.[buildUserReadPermission(member.id)]?.isGranted ?? false)
|
||||
: false;
|
||||
|
||||
const canListPassword =
|
||||
!!authZError ||
|
||||
(authZPermission?.[PasswordListPermission]?.isGranted ?? false);
|
||||
|
||||
const resetLinkChecks = useMemo(() => {
|
||||
if (!member) {
|
||||
return [];
|
||||
}
|
||||
if (isInvited && !canListPassword) {
|
||||
return [PasswordListPermission];
|
||||
}
|
||||
return buildResetPasswordPermission(member.id);
|
||||
}, [member, isInvited, canListPassword]);
|
||||
|
||||
const { showErrorModal } = useErrorModal();
|
||||
|
||||
const {
|
||||
data: fetchedUser,
|
||||
isLoading: isFetchingUser,
|
||||
refetch: refetchUser,
|
||||
} = useGetUser({ id: member?.id ?? '' }, { query: { enabled: canReadUser } });
|
||||
} = useGetUser(
|
||||
{ id: member?.id ?? '' },
|
||||
{ query: { enabled: open && !!member?.id } },
|
||||
);
|
||||
|
||||
const isRootUser = !!fetchedUser?.data?.isRoot;
|
||||
|
||||
@@ -188,7 +144,7 @@ function EditMemberDrawer({
|
||||
currentRoles: currentMemberRoles,
|
||||
isLoading: isMemberRolesLoading,
|
||||
applyDiff,
|
||||
} = useMemberRoleManager(member?.id ?? '', canReadUser);
|
||||
} = useMemberRoleManager(member?.id ?? '', open && !!member?.id);
|
||||
|
||||
// Token status query for invited users
|
||||
const {
|
||||
@@ -197,7 +153,7 @@ function EditMemberDrawer({
|
||||
isError: tokenNotFound,
|
||||
} = useGetResetPasswordToken(
|
||||
{ id: member?.id ?? '' },
|
||||
{ query: { enabled: !!member?.id && isInvited && canListPassword } },
|
||||
{ query: { enabled: open && !!member?.id && isInvited } },
|
||||
);
|
||||
|
||||
const existingToken = tokenQueryData?.data;
|
||||
@@ -231,17 +187,13 @@ function EditMemberDrawer({
|
||||
useEffect(() => {
|
||||
if (!member?.id) {
|
||||
roleSessionRef.current = null;
|
||||
} else if (
|
||||
canReadUser &&
|
||||
member.id !== roleSessionRef.current &&
|
||||
!isMemberRolesLoading
|
||||
) {
|
||||
} else if (member.id !== roleSessionRef.current && !isMemberRolesLoading) {
|
||||
setLocalRoles(
|
||||
currentMemberRoles.map((r) => r.id).filter(Boolean) as string[],
|
||||
);
|
||||
roleSessionRef.current = member.id;
|
||||
}
|
||||
}, [member?.id, canReadUser, currentMemberRoles, isMemberRolesLoading]);
|
||||
}, [member?.id, currentMemberRoles, isMemberRolesLoading]);
|
||||
|
||||
const isDirty =
|
||||
member !== null &&
|
||||
@@ -258,7 +210,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 +378,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 +409,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 +438,7 @@ function EditMemberDrawer({
|
||||
|
||||
useEffect(() => {
|
||||
if (copyState.error) {
|
||||
toast.danger('Failed to copy link', { action: { label: 'Dismiss' } });
|
||||
toast.error('Failed to copy link');
|
||||
}
|
||||
}, [copyState.error]);
|
||||
|
||||
@@ -516,31 +463,6 @@ function EditMemberDrawer({
|
||||
[formatTimezoneAdjustedTimestamp],
|
||||
);
|
||||
|
||||
const inviteLinkAndResetPasswordText = useMemo(() => {
|
||||
if (isGeneratingLink) {
|
||||
return 'Generating...';
|
||||
}
|
||||
if (isInvited) {
|
||||
return getInviteButtonLabel(
|
||||
isLoadingTokenStatus || isLoadingAuthZ,
|
||||
canListPassword,
|
||||
existingToken,
|
||||
isTokenExpired,
|
||||
tokenNotFound,
|
||||
);
|
||||
}
|
||||
return 'Generate Password Reset Link';
|
||||
}, [
|
||||
isGeneratingLink,
|
||||
isInvited,
|
||||
isLoadingTokenStatus,
|
||||
isLoadingAuthZ,
|
||||
canListPassword,
|
||||
existingToken,
|
||||
isTokenExpired,
|
||||
tokenNotFound,
|
||||
]);
|
||||
|
||||
const drawerBody = isFetchingUser ? (
|
||||
<Skeleton active paragraph={{ rows: 6 }} />
|
||||
) : (
|
||||
@@ -549,11 +471,7 @@ function EditMemberDrawer({
|
||||
<label className="edit-member-drawer__label" htmlFor="member-name">
|
||||
Name
|
||||
</label>
|
||||
|
||||
<AuthZTooltip
|
||||
checks={member && !isSelf ? [buildUserUpdatePermission(member.id)] : []}
|
||||
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
|
||||
>
|
||||
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
|
||||
<Input
|
||||
id="member-name"
|
||||
value={localDisplayName}
|
||||
@@ -565,9 +483,8 @@ function EditMemberDrawer({
|
||||
}}
|
||||
placeholder="Enter name"
|
||||
disabled={isRootUser || isDeleted}
|
||||
disabledTooltip={undefined}
|
||||
/>
|
||||
</AuthZTooltip>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div className="edit-member-drawer__field">
|
||||
@@ -586,12 +503,17 @@ function EditMemberDrawer({
|
||||
<label className="edit-member-drawer__label" htmlFor="member-role">
|
||||
Roles
|
||||
</label>
|
||||
{isRootUser || isDeleted ? (
|
||||
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
|
||||
<div
|
||||
className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled"
|
||||
data-testid="member-roles-locked"
|
||||
>
|
||||
{isSelf || isRootUser || isDeleted ? (
|
||||
<Tooltip
|
||||
title={
|
||||
isRootUser
|
||||
? ROOT_USER_TOOLTIP
|
||||
: isDeleted
|
||||
? undefined
|
||||
: 'You cannot modify your own role'
|
||||
}
|
||||
>
|
||||
<div className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled">
|
||||
<div className="edit-member-drawer__disabled-roles">
|
||||
{localRoles.length > 0 ? (
|
||||
localRoles.map((roleId) => {
|
||||
@@ -618,7 +540,6 @@ function EditMemberDrawer({
|
||||
<RolesSelect
|
||||
id="member-role"
|
||||
mode="multiple"
|
||||
testId="member-roles-select"
|
||||
roles={availableRoles}
|
||||
loading={rolesLoading}
|
||||
isError={rolesError}
|
||||
@@ -694,91 +615,96 @@ 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">
|
||||
<Button
|
||||
disabledTooltip={getDeleteTooltip(isRootUser, isSelf)}
|
||||
size="md"
|
||||
onClick={(): void => setShowDeleteConfirm(true)}
|
||||
testId="member-delete-btn"
|
||||
disabled={isRootUser || isSelf}
|
||||
variant="link"
|
||||
color="danger"
|
||||
prefix={<Trash2 size={12} />}
|
||||
>
|
||||
{isInvited ? 'Revoke Invite' : 'Delete Member'}
|
||||
</Button>
|
||||
|
||||
<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" />
|
||||
<Button
|
||||
disabledTooltip={ROOT_USER_TOOLTIP}
|
||||
size="md"
|
||||
onClick={handleGenerateResetLink}
|
||||
testId="member-reset-link-btn"
|
||||
disabled={isRootUser}
|
||||
loading={isGeneratingLink || isLoadingTokenStatus}
|
||||
variant="link"
|
||||
color="warning"
|
||||
prefix={<RefreshCw size={12} />}
|
||||
>
|
||||
{isGeneratingLink
|
||||
? 'Generating...'
|
||||
: isInvited
|
||||
? getInviteButtonLabel(
|
||||
isLoadingTokenStatus,
|
||||
existingToken,
|
||||
isTokenExpired,
|
||||
tokenNotFound,
|
||||
)
|
||||
: 'Generate Password Reset Link'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="edit-member-drawer__footer-right">
|
||||
<Button
|
||||
size="md"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
onClick={handleClose}
|
||||
prefix={<X size={14} />}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : 'No changes to save'}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
disabled={!isDirty || isRootUser}
|
||||
onClick={handleSave}
|
||||
testId="member-save-btn"
|
||||
loading={isSaving}
|
||||
>
|
||||
{isSaving ? 'Saving...' : 'Save Member Details'}
|
||||
</Button>
|
||||
</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"
|
||||
open={member !== null}
|
||||
onClose={handleClose}
|
||||
<DrawerWrapper
|
||||
open={open}
|
||||
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)] : []}
|
||||
fallbackOnLoading={<Skeleton active paragraph={{ rows: 6 }} />}
|
||||
>
|
||||
{drawerContent}
|
||||
</AuthZGuardContent>
|
||||
</Drawer>
|
||||
{drawerContent}
|
||||
</DrawerWrapper>
|
||||
|
||||
<ResetLinkDialog
|
||||
open={showResetLinkDialog}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -17,16 +17,6 @@ import {
|
||||
managedRoles,
|
||||
} from 'mocks-server/__mockdata__/roles';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
buildUserUpdatePermission,
|
||||
PasswordListPermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
|
||||
import {
|
||||
AUTHZ_CHECK_URL,
|
||||
setupAuthzAdmin,
|
||||
setupAuthzDeny,
|
||||
setupAuthzDenyAll,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import EditMemberDrawer, { EditMemberDrawerProps } from '../EditMemberDrawer';
|
||||
@@ -51,31 +41,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(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -157,6 +168,7 @@ function renderDrawer(
|
||||
return render(
|
||||
<EditMemberDrawer
|
||||
member={activeMember}
|
||||
open
|
||||
onClose={jest.fn()}
|
||||
onComplete={jest.fn()}
|
||||
{...props}
|
||||
@@ -164,16 +176,6 @@ function renderDrawer(
|
||||
);
|
||||
}
|
||||
|
||||
async function clickDeleteButton(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
): Promise<void> {
|
||||
const deleteBtn = await screen.findByTestId('member-delete-btn');
|
||||
await waitFor(() =>
|
||||
expect(deleteBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
await user.click(deleteBtn);
|
||||
}
|
||||
|
||||
describe('EditMemberDrawer', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -184,7 +186,6 @@ describe('EditMemberDrawer', () => {
|
||||
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
|
||||
),
|
||||
setupAuthzAdmin(),
|
||||
);
|
||||
(useGetUser as jest.Mock).mockReturnValue({
|
||||
data: mockFetchedUser,
|
||||
@@ -208,7 +209,7 @@ describe('EditMemberDrawer', () => {
|
||||
isLoading: false,
|
||||
});
|
||||
(useDeleteUser as jest.Mock).mockReturnValue({
|
||||
mutateAsync: mockDeleteMutate,
|
||||
mutate: mockDeleteMutate,
|
||||
isLoading: false,
|
||||
});
|
||||
// Token query: valid token for invited members
|
||||
@@ -242,33 +243,15 @@ describe('EditMemberDrawer', () => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('renders active member details and disables Save when form is not dirty', async () => {
|
||||
it('renders active member details and disables Save when form is not dirty', () => {
|
||||
renderDrawer();
|
||||
|
||||
await expect(
|
||||
screen.findByDisplayValue('Alice Smith'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('Alice Smith')).toBeInTheDocument();
|
||||
expect(screen.getByText('alice@signoz.io')).toBeInTheDocument();
|
||||
expect(screen.getByText('ACTIVE')).toBeInTheDocument();
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('member-save-btn')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('still fetches the member when the permission check fails', async () => {
|
||||
server.use(rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => res(ctx.status(500))));
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(useGetUser).toHaveBeenLastCalledWith(
|
||||
{ id: 'user-1' },
|
||||
{ query: { enabled: true } },
|
||||
),
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save member details/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('enables Save after editing name and calls updateUser on confirm', async () => {
|
||||
@@ -283,8 +266,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ onComplete });
|
||||
|
||||
const nameInput = await screen.findByDisplayValue('Alice Smith');
|
||||
await waitFor(() => expect(nameInput).toBeEnabled());
|
||||
const nameInput = screen.getByDisplayValue('Alice Smith');
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Alice Updated');
|
||||
|
||||
@@ -310,8 +292,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ onClose });
|
||||
|
||||
const nameInput = await screen.findByDisplayValue('Alice Smith');
|
||||
await waitFor(() => expect(nameInput).toBeEnabled());
|
||||
const nameInput = screen.getByDisplayValue('Alice Smith');
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Alice Updated');
|
||||
|
||||
@@ -342,11 +323,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(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-editor'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /save member details/i });
|
||||
await waitFor(() =>
|
||||
@@ -370,11 +348,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 +373,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,
|
||||
@@ -403,7 +381,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ onComplete });
|
||||
|
||||
await clickDeleteButton(user);
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
|
||||
await expect(
|
||||
screen.findByText(/are you sure you want to delete/i),
|
||||
@@ -420,11 +398,9 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('shows revoke invite and copy invite link for invited members; hides Last Modified', async () => {
|
||||
it('shows revoke invite and copy invite link for invited members; hides Last Modified', () => {
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await screen.findByText('Invited On');
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /revoke invite/i }),
|
||||
).toBeInTheDocument();
|
||||
@@ -438,7 +414,7 @@ describe('EditMemberDrawer', () => {
|
||||
expect(screen.queryByText('Last Modified')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "Regenerate Invite Link" when token is expired', async () => {
|
||||
it('shows "Regenerate Invite Link" when token is expired', () => {
|
||||
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
|
||||
data: {
|
||||
data: {
|
||||
@@ -453,12 +429,12 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await expect(
|
||||
screen.findByRole('button', { name: /regenerate invite link/i }),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: /regenerate invite link/i }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "Generate Invite Link" when no token exists', async () => {
|
||||
it('shows "Generate Invite Link" when no token exists', () => {
|
||||
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
@@ -467,88 +443,9 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await expect(
|
||||
screen.findByRole('button', { name: /generate invite link/i }),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('looks up the invite link when factor-password list is granted', async () => {
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
|
||||
{ id: invitedMember.id },
|
||||
{ query: { enabled: true } },
|
||||
),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('member-reset-link-btn')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('skips the invite link lookup and disables the button without factor-password list', async () => {
|
||||
server.use(setupAuthzDeny(PasswordListPermission));
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
PasswordListPermission,
|
||||
),
|
||||
);
|
||||
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(screen.getByTestId('member-reset-link-btn')).toHaveTextContent(
|
||||
'Invite Link Unavailable',
|
||||
);
|
||||
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
|
||||
{ id: invitedMember.id },
|
||||
{ query: { enabled: false } },
|
||||
);
|
||||
});
|
||||
|
||||
it('reports only factor-password list for an invited member who lacks every permission', async () => {
|
||||
server.use(setupAuthzDenyAll());
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
PasswordListPermission,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('still looks up the invite link when the permission check fails', async () => {
|
||||
server.use(rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => res(ctx.status(500))));
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
|
||||
{ id: invitedMember.id },
|
||||
{ query: { enabled: true } },
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the reset link enabled for an active member without factor-password list', async () => {
|
||||
server.use(setupAuthzDeny(PasswordListPermission));
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await screen.findByDisplayValue('Alice Smith');
|
||||
expect(screen.getByTestId('member-reset-link-btn')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /generate invite link/i }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls deleteUser after confirming revoke invite for invited members', async () => {
|
||||
@@ -556,7 +453,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,
|
||||
@@ -564,7 +461,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: invitedMember, onComplete });
|
||||
|
||||
await clickDeleteButton(user);
|
||||
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
|
||||
|
||||
await expect(
|
||||
screen.findByText(/Are you sure you want to revoke the invite/i),
|
||||
@@ -611,8 +508,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: { ...invitedMember, name: 'Bob' }, onComplete });
|
||||
|
||||
const nameInput = await screen.findByDisplayValue('Bob');
|
||||
await waitFor(() => expect(nameInput).toBeEnabled());
|
||||
const nameInput = screen.getByDisplayValue('Bob');
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Bob Updated');
|
||||
|
||||
@@ -650,8 +546,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer();
|
||||
|
||||
const nameInput = await screen.findByDisplayValue('Alice Smith');
|
||||
await waitFor(() => expect(nameInput).toBeEnabled());
|
||||
const nameInput = screen.getByDisplayValue('Alice Smith');
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Alice Updated');
|
||||
|
||||
@@ -672,7 +567,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,
|
||||
@@ -680,7 +575,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await clickDeleteButton(user);
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
const confirmBtns = screen.getAllByRole('button', {
|
||||
name: /delete member/i,
|
||||
});
|
||||
@@ -703,7 +598,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,
|
||||
@@ -711,7 +606,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await clickDeleteButton(user);
|
||||
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
|
||||
const confirmBtns = screen.getAllByRole('button', {
|
||||
name: /revoke invite/i,
|
||||
});
|
||||
@@ -750,86 +645,16 @@ describe('EditMemberDrawer', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps name input enabled when viewing own profile', async () => {
|
||||
it('keeps name input enabled when viewing own profile', () => {
|
||||
renderDrawer({ member: selfMember });
|
||||
await expect(
|
||||
screen.findByDisplayValue('Alice Smith'),
|
||||
).resolves.not.toBeDisabled();
|
||||
expect(screen.getByDisplayValue('Alice Smith')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('keeps Reset Link button enabled when viewing own profile', async () => {
|
||||
it('keeps Reset Link button enabled when viewing own profile', () => {
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
const resetBtn = await screen.findByTestId('member-reset-link-btn');
|
||||
await waitFor(() =>
|
||||
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('self user roles', () => {
|
||||
it('keeps roles editable', async () => {
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
await expect(screen.findByText('Select roles')).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('member-roles-locked')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleted member', () => {
|
||||
const deletedMember = { ...activeMember, status: MemberStatus.Deleted };
|
||||
|
||||
it('is read-only with no footer actions', async () => {
|
||||
renderDrawer({ member: deletedMember });
|
||||
|
||||
const nameInput = await screen.findByDisplayValue('Alice Smith');
|
||||
await waitFor(() =>
|
||||
expect(nameInput).not.toHaveStyle({ cursor: 'not-allowed' }),
|
||||
);
|
||||
expect(nameInput).toBeDisabled();
|
||||
expect(screen.getByTestId('member-roles-locked')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByPlaceholderText('Select roles'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('member-save-btn')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('member-delete-btn')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('member-reset-link-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('self user name update', () => {
|
||||
it('saves through the me API without update:user', async () => {
|
||||
const updateMyUser = jest.fn().mockResolvedValue({});
|
||||
(useUpdateMyUserV2 as jest.Mock).mockReturnValue({
|
||||
mutateAsync: updateMyUser,
|
||||
isLoading: false,
|
||||
});
|
||||
server.use(setupAuthzDeny(buildUserUpdatePermission(selfMember.id)));
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
const input = await screen.findByDisplayValue('Alice Smith');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Alice Cooper');
|
||||
await user.click(screen.getByTestId('member-save-btn'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(updateMyUser).toHaveBeenCalledWith({
|
||||
data: { displayName: 'Alice Cooper' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not gate Save on permissions', async () => {
|
||||
server.use(setupAuthzDenyAll());
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
await screen.findByText(/is not authorized/);
|
||||
expect(screen.getByTestId('member-save-btn')).not.toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
);
|
||||
screen.getByRole('button', { name: /generate password reset link/i }),
|
||||
).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -842,11 +667,9 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('disables name input for root user', async () => {
|
||||
it('disables name input for root user', () => {
|
||||
renderDrawer();
|
||||
await expect(
|
||||
screen.findByDisplayValue('Alice Smith'),
|
||||
).resolves.toBeDisabled();
|
||||
expect(screen.getByDisplayValue('Alice Smith')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables Delete button for root user', () => {
|
||||
@@ -903,11 +726,9 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer();
|
||||
|
||||
const resetBtn = await screen.findByTestId('member-reset-link-btn');
|
||||
await waitFor(() =>
|
||||
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: /generate password reset link/i }),
|
||||
);
|
||||
await user.click(resetBtn);
|
||||
|
||||
const dialog = await screen.findByRole('dialog', {
|
||||
name: /password reset link/i,
|
||||
@@ -926,11 +747,9 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer();
|
||||
|
||||
const resetBtn = await screen.findByTestId('member-reset-link-btn');
|
||||
await waitFor(() =>
|
||||
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: /generate password reset link/i }),
|
||||
);
|
||||
await user.click(resetBtn);
|
||||
|
||||
const dialog = await screen.findByRole('dialog', {
|
||||
name: /password reset link/i,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,72 +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.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>
|
||||
);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user