Compare commits

...

30 Commits

Author SHA1 Message Date
Vinícius Lourenço
0fcaae2a8f chore(web): drop duplicate uPlot stylesheet import from anomaly view 2026-11-27 10:17:38 -03:00
Vinícius Lourenço
05cf64aa34 chore(web): drop past-tense note from uPlot stylesheet comment 2026-11-27 09:17:36 -03:00
Vinícius Lourenço
ca10a4806e perf(web): serve the uPlot stylesheet as a hashed asset 2026-11-26 15:43:02 -03:00
Aditya Singh
b1f271a505 fix(frontend): show the full text of truncated labels in one tooltip (#13735)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Since #13087, `Typography` opens its own tooltip when its text is cut
off. Four places also had an outer tooltip, so hovering cut-off text
showed it twice.
- Quick filter section titles showed the title twice in one stacked
tooltip. Span event attribute keys and values, and query builder search
suggestions, opened two separate popups.
- This PR removes the outer tooltip at those four places. Cut-off text
now shows its full text once, and text that fits shows no tooltip.
- Suggestion value and operator rows did not shrink, so their text was
never cut and only the outer tooltip showed a long value. The row's left
section now shrinks, so a long value ends in "…" and its tooltip opens.
- New stories hover cut-off text in quick filters, span events and the
pipeline filter suggestions, and they fail on `main`. Two jest tests for
the old quick filter tooltip are removed, because jsdom cannot measure
text.

#### Issues closed by this PR

Part of https://github.com/SigNoz/events-pod/issues/306

#### Screenshots / Screen Recordings

Screenshots of the new stories, in dark and light themes:
https://claude.ai/artifact/Lcjn1xBj8qTM9yesjPDmK6

- Quick filters: before and after. On `main` the title shows twice in
one tooltip.
- Span events and the pipeline filter suggestions: after only. Their
plays use a helper this PR adds, so `main` cannot run them.

#### Additional Information

- A long span event value inside the hover popover still opens the
popover and the `Typography` tooltip together. That fix needs a change
in `@signozhq/ui`.
2026-11-26 15:42:49 +00:00
Vinicius Lourenço
c92bb94caf perf(web): load each metrics, meter and messaging queues tab when it opens (#13696)
#### Description

Metrics explorer, Meter and Messaging queues import all of their tabs up
front. Each tab now loads when it opens, using the per-tab loading state
from #13691. Tab URLs and order stay as they are. Infrastructure
monitoring and API monitoring are left alone: their tabs share almost
all of their code, or there is only one.

Opening each page's default tab, entry included: Metrics goes from 11.43
MB to 11.09 MB, Meter from 11.39 MB to 11.14 MB and Messaging queues
from 11.26 MB to 10.96 MB.

The queue details drawer on the messaging queues overview relied on
styles the Celery tab happened to load; it now imports them itself.

Part of #10192

#### Screenshots / Screen Recordings

Switching metrics explorer tabs in Storybook, main on the left, with the
network slowed to 1.6 Mbps so the loading state is visible:


https://github.com/user-attachments/assets/5802c696-680e-4afc-93d7-a59536542af9

Queue details drawer, main on the left:

![Queue details
drawer](https://github.com/user-attachments/assets/b6d0f13d-f7cc-4e0e-b2de-3c7f6af1e5f4)

The 40 metrics, meter and messaging queues stories render the same in
both themes, except the Celery state drawer table, which sits 1px
higher.
2026-11-26 14:44:51 +00:00
ashu8912
8e3a4f8775 fix(list-filter): run a filter tag's removal when its dropdown is closed (#13753)
#### Description

- Removing a Created-by tag with its × only staged the change: the query
runs when the dropdown closes, and the × never opens it. The chip
vanished but the list kept its old results.
- `MultiSelectFilter` now commits any change made with its dropdown
closed (a tag's ×, the clear icon) through `onCommit`; picks in an open
dropdown still stage until it closes.
- Dashboards' Created-by, the service accounts status filter (same bug)
and the alert rules status filter (which had its own copy of this) all
use it.

#### Issues closed by this PR

Closes SigNoz/pulse-pod#789

#### Screenshots / Screen Recordings

[Visual diff](https://claude.ai/artifact/LGAnLu31NHXY5eZ6PLz3Yx)
(sbshot, merge-base vs this branch, dark and light): removing the
Created-by tag on My dashboards and the Deleted status tag on service
accounts now reruns the list. 14 of 22 pairs are pixel-identical; the
other 4 are timestamp and anti-aliasing noise.

#### Additional Information

- The clear icon clicked while the dropdown is open now stages like any
other pick, running on close.
2026-11-26 14:01:25 +00:00
Vinicius Lourenço
a8433ad9e0 perf(web): use CSS variables instead of the design-tokens Style object (#13685)
#### Description

`Style` from `@signozhq/design-tokens` is an object of 817 `var(--...)`
strings, and the bundler keeps all of it once anything imports it. The
side nav did, for one value, so the whole object sat in the entry chunk.
The three values the app used are now written as the CSS variables they
already held, and oxlint rejects importing `Style`. The entry chunk
loses 47.6 kB (7.8 kB gzipped). Colors render the same, since the
strings are identical.

Part of #10192

#### Screenshots / Screen Recordings

Main on the left or top, this branch on the right or below:

![Settings menu in the side
nav](https://github.com/user-attachments/assets/ab0236ba-f10d-48e7-87aa-5612ea4a3dfb)

![OIDC form with claim
mapping](https://github.com/user-attachments/assets/80d7a7b6-1c0c-442b-bd6a-68ce4853573f)

The 46 stories that render these icons are pixel-identical in both
themes, apart from a focus ring left on one form input.
2026-11-26 12:47:49 +00:00
Vinicius Lourenço
d07b0f1d82 perf(integrations): import antd from its ES entry instead of antd/lib (#13683)
#### Description

The cloud integrations page imported `Modal`, `Form`, `Select` and
`Skeleton` from `antd/lib`. That path is antd's CommonJS entry, so it
pulled every antd component into the page's chunk. Importing from `antd`
takes that chunk from 1.30 MB to 108 kB (335 kB to 26 kB gzipped).

It also fixes how the remove-account modal looks. `antd/lib` is a second
copy of antd that the app's `ConfigProvider` does not reach, so that
modal used antd's default theme (larger text, bold title, rounder
buttons). It now picks up the app theme.

#10491 removed these imports once and they came back, so oxlint now
rejects runtime imports from `antd/lib`. Type-only imports stay allowed.

To check, run `pnpm build` on main and on this branch and compare
`build/assets/IntegrationsDetailsPage-*.js`.

Part of #10192

#### Screenshots / Screen Recordings

The remove-account modal, main on the left and this branch on the right:

![Remove account modal, light
theme](https://github.com/user-attachments/assets/c67a3d7b-f7b3-4631-a667-a820f4147b76)

![Remove account modal, dark
theme](https://github.com/user-attachments/assets/37dbf93b-f6f0-41f7-b5a6-d7e28e76b376)

Across the 43 cloud account stories in both themes, the only other
differences are toasts caught mid-fade.
2026-11-26 12:29:45 +00:00
Vinicius Lourenço
a02330438f perf(dashboard): emit logo assets as files instead of inlining them (#13684)
#### Description

Dashboard JSON can point at any logo under `src/assets/Logos`, so the
icon map globs all 240 of them. The glob used `?url`, but Vite still
inlines every file under `assetsInlineLimit` as base64, so the logos
shipped inside the JS whether a dashboard used them or not. With
`?no-inline` they are emitted as files and fetched only when a dashboard
shows one. The chunk that holds the icon map goes from 376 kB to 76 kB
(135 kB to 23 kB gzipped).

To check, on a production build (`pnpm build && pnpm preview`) import a
dashboard whose `image` is `/assets/Logos/redis`: the logo loads as its
own `redis-<hash>.svg` request.

Part of #10192

#### Screenshots / Screen Recordings

Dashboard list with logo images, main on top and this branch below:

![Dashboard list with
logos](https://github.com/user-attachments/assets/783b8889-629b-4e86-9990-5712015e709e)

The logo stories are pixel-identical in both themes. Across the 102
dashboard list, detail and settings stories, the other differences are
toast fades and mock timestamps a second apart.
2026-11-26 12:28:12 +00:00
Ashwin Bhatkal
cb2b3db771 chore(page-story): guard plays on the args their story sets (#13768)
#### Description

- Plays the page-story skill writes now check the args their own story
sets. A story that sets `view: 'mine'` to put a Created-by tag on screen
must still pass when someone flips the view in the panel. This is the
miss from
https://github.com/SigNoz/signoz/pull/13753#discussion_r4706154296.
- The skill now says to go through every control a story exposes, the
page's own as well as the shared ones, before writing a play's early
returns.
- New PR rule: a review fix to a file with the AI-owned banner also adds
the lesson to the skill or agent that made it, so the next run doesn't
write the same bug again.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/786
2026-11-26 12:25:02 +00:00
Ashwin Bhatkal
40ee169d94 fix(query-builder): keep value suggestions open when the editor re-renders (#13760)
#### Description

- The query search value dropdown now stays open when the editor
re-renders. Before, every render handed CodeMirror new extensions. When
the cursor sat on an empty value like `service.name = '`, that closed
the dropdown, for example when key suggestions loaded late.
- The CodeMirror extensions, `onChange` handler and `basicSetup` are now
built once. They read the latest suggestions and run handler through
refs, as `ListFilter/SearchBar` does.
- This fixes the flaky `fetches value suggestions when editing value
context` test. The "keeps the value suggestions open when the key
suggestions load" test now waits past CodeMirror's re-query, so it fails
without this fix. Its old assertion ran before the dropdown closed.
- Stories already cover this: the Traces and Metrics explorer plays type
`service.name = ` and wait for a value suggestion.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/782
2026-11-26 12:05:03 +00:00
hardik-signoz
865e1c97b3 feat(authz): expose ingestion-key and ingestion-limit fga (#13648)
#### Description

- Gates the Ingestion keys page on the new `ingestion-key` and
`ingestion-limit` permissions, so users without them can't trigger
actions that would be rejected.
- Moves limit create/update/delete off the deprecated gateway routes to
`/ingestion_limits`; their permissions are identical.
- Shows both resources in the roles editor.
- Ingestion shows in the settings sidebar for every role. The legacy vs
multi-key page split is unchanged (multi-key when the gateway is on,
legacy for cloud otherwise); only the admin/editor condition is dropped.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#42

#### Screenshots / Screen Recordings

[sbshot diff](https://claude.ai/artifact/FutBFmcA9ERz1GzcrhjYJN) vs the
merge-base, dark and light:
- Ingestion: unchanged for permitted users (30 pairs identical), plus 9
new Authz stories.
- Roles: only the new Ingestion Keys and Limits panels and the viewer's
sidebar link changed.

#### Additional Information

- Open on the ticket: the new `/ingestion_limits` calls are not yet
tested against a real gateway.

---------

Co-authored-by: vikrantgupta25 <vikrant@signoz.io>
2026-11-26 12:03:33 +00:00
ashu8912
5f24193de6 fix(list-views): match the view name placeholder to its list (#13767)
#### Description

- The save/rename view dialog hardcoded "e.g. Prod alerts", so the
dashboards list showed an alerts example.
- `ViewsRail` now takes `viewNamePlaceholder`; alerts keep "e.g. Prod
alerts", dashboards use "e.g. Prod dashboards".
- The dashboards list story already opens this dialog in its play, so no
story change.

Found while testing SigNoz/pulse-pod#775.
2026-11-26 11:58:17 +00:00
Ashwin Bhatkal
3d63ed6353 ci(goci): bump setup-go to v7 to reuse main's module cache (#13744)
#### Description

- `goci` jobs now use the same `setup-go` as the primus jobs (v7.0.0,
pinned), so they restore the Go module cache that `build-staging` saves
on `main`.
- setup-go v5 keys its cache on `go.sum` and v7 keys it on `go.mod`.
`main` only ever gets the v7 key, so `build`, `openapi`, `authz`,
`web-settings`, `transaction-groups` and `semconv-generated` missed it
and downloaded every module from proxy.golang.org on each run.
- Those downloads failed 11 runs since Nov 23 with `stream error: ...
INTERNAL_ERROR; received from peer`, 4 of them in the merge queue. `go`
does not retry a reset download.
- To check: on this PR's run, the `go-install` step of `build` should
log `Cache restored from key: setup-go-...-e68ddbf...`.

<details>
<summary>Failed runs</summary>

- Nov 23 16:36 UTC, PR:
[transaction-groups](https://github.com/SigNoz/signoz/actions/runs/45218336614/job/137845455490)
- Nov 24 14:43 UTC, PR:
[openapi](https://github.com/SigNoz/signoz/actions/runs/45417214716/job/138526593113)
- Nov 24 15:45 UTC, merge queue:
[build](https://github.com/SigNoz/signoz/actions/runs/45429166803/job/138569346003)
- Nov 24 17:03 UTC, merge queue:
[build](https://github.com/SigNoz/signoz/actions/runs/45444178593/job/138623258070)
- Nov 24 17:10 UTC, PR:
[web-settings](https://github.com/SigNoz/signoz/actions/runs/45445506450/job/138628048194)
- Nov 24 17:58 UTC, PR:
[transaction-groups](https://github.com/SigNoz/signoz/actions/runs/45454318875/job/138659559545)
- Nov 24 17:59 UTC, PR:
[web-settings](https://github.com/SigNoz/signoz/actions/runs/45454538375/job/138660328195)
- Nov 24 18:09 UTC, PR:
[openapi](https://github.com/SigNoz/signoz/actions/runs/45456425417/job/138666985974),
[build](https://github.com/SigNoz/signoz/actions/runs/45456425417/job/138666985982)
- Nov 24 18:39 UTC, merge queue:
[authz](https://github.com/SigNoz/signoz/actions/runs/45461964073/job/138686679525),
[build](https://github.com/SigNoz/signoz/actions/runs/45461964073/job/138686679898)
- Nov 24 18:41 UTC, PR:
[build](https://github.com/SigNoz/signoz/actions/runs/45462168844/job/138687411123),
[transaction-groups](https://github.com/SigNoz/signoz/actions/runs/45462168844/job/138687412071)
- Nov 24 19:12 UTC, merge queue:
[build](https://github.com/SigNoz/signoz/actions/runs/45467713142/job/138706955705)

</details>

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/776
2026-11-26 11:34:07 +00:00
hardik-signoz
3af06adabc feat(authz): auth-domains and organization fga (#13706)
#### Description

- Include auth domains and the organization in the generated frontend
permissions, so the role editor offers them.
- Show Organization Settings, and the SSO section in it, to all roles.
Access is decided by authz instead of the legacy admin-only check.
- Gate the auth domain list and delete, and the organization display
name, on their permissions. Saving a domain stays a backend check.
- Add unit tests, SSO stories and E2E specs.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#39

#### Screenshots / Screen Recordings

[Before and after Storybook shots of the settings
pages](https://claude.ai/artifact/1Az85vbiW1RU1rk5JD5zRN), dark and
light. Role editor and role details list the new Auth Domains and
Organization panels. The Display name field and its Submit button use
the `@signozhq/ui` components. The baseline is the merge-base plus a
commit that only retitles the Single Sign-on stories, so old and new
stories pair.
2026-11-26 10:20:43 +00:00
ashu8912
7b20abbeb7 fix(unauthorized): align the contact link with the message text (#13758)
#### Description

- The "reach out to us." link on the anonymous Access Restricted page
sat below the text baseline and had no space before it.
- `Button` is an `inline-flex` box with a fixed 24px link height,
centring its label; letting its height size to content and aligning on
the baseline puts it on the line. Set via `--button-*` tokens since
`Button` drops `className`.
- The leading space moves outside the button, where flex layout no
longer swallows it.

#### Screenshots / Screen Recordings

Visual diff (sbshot, `Pages/System/Unauthorized`, dark + light, baseline
`main`): https://claude.ai/artifact/AxR71cviVejCEE96XhbEHM
2026-11-26 09:25:37 +00:00
Vinicius Lourenço
73e6fa555a fix(infra-monitoring): restore log navigation from the entity drawer (#13742)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

Log details opened from an infra monitoring drawer works again: the
arrow keys step through the logs, and a click on another log row opens
that log. Both broke when the entity drawer moved to `@signozhq/ui`,
which blocked keys and clicks on the drawer below log details.
`0.4.1-rc.1` fixes it (SigNoz/components#532).

A new e2e test in the infra monitoring drawer spec covers both, and the
Pods story "Details Drawer Log Navigation" covers the arrow keys.

#### Screenshots

After:


https://github.com/user-attachments/assets/548292f3-41e7-4d8b-b1f5-40872a2f8fb2

#### Additional Information

`0.4.1-rc.1` is a prerelease because SigNoz/components#532 is still
open. I'll bump to the stable release once it merges.
2026-11-26 08:24:09 +00:00
Gaurav Tewari
91525d721e feat(noz): show open chats as bottom-strip tabs (#13602)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

Stacked on #13601.

- Open Noz conversations show as tabs in the bottom strip, newest beside
Ask Noz. Clicking one opens it in the Noz panel; × closes the tab
without archiving the thread.
- A tab whose reply the user hasn't seen shows a dot, and a placeholder
chime plays when a reply lands off screen. A reply on screen is read at
once.
- Tabs and unseen replies persist in localStorage, so they survive a
reload, a closed tab or a restart. Tabs are capped at 5; past that, the
oldest tab goes.
- Saved ids are pruned only after a successful thread fetch, so a failed
fetch can't wipe them. A deleted, archived or another user's thread
drops out on the next good fetch.
- `StripTab` / `StripTabs` are generic strip components (no Noz imports)
beside `StripTypography` and `StripKeyValue`.
- When the strip runs short, the tabs shrink first and their titles
truncate; Ask Noz, history and Support keep their size, and the tabs
never cover the left slot.
- Chat tabs also show on the Noz page, where a tab opens its chat in the
page.
- The Noz page's conversation list marks a chat with an unseen reply
with the same blue dot.
- The panel header gains a minimize button, which hides the panel and
keeps the chat as a tab. × now also closes the chat's tab; a reply
landing later brings it back.
- A tab also shows the dot while Noz waits on the user's approval or
answer there, and a chat that starts waiting joins the strip. Ask Noz
loses its pulsing dot: it always starts a new chat, so it can't lead to
the waiting one.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR


https://github.com/orgs/SigNoz/projects/59/views/18?pane=issue&itemId=306515634&issue=SigNoz%7Cnerve-pod%7C643

<!--If applicable, include screenshots or screen recordings that clearly
show the behavior before the change and the result after the change. -->
#### Screenshots / Screen Recordings


https://github.com/user-attachments/assets/99192505-8df2-4108-896d-3872e1926fe2



<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information

- Tab state lives with Noz, not the strip:
`useAIAssistantOpenConversationsStore` in `AIAssistant/store` and
`useAIAssistantActiveChats` (which also plays the chime) in
`AIAssistant/hooks`. `BottomStrip/NozActiveChat` only renders the tabs,
so the panel doesn't import from the strip.
- The store tracks loading per thread (`loadingThreadIds` replaces the
global `isLoadingThread`), so switching tabs while another chat loads
works, and a chat's skeleton and disabled input follow only its own
load.
- Stories: Components/Strip Tabs (Default, Crowded, Focused) and
Foundations/Bottom Strip `NozChats` / `NozChatOpen`. The global Noz
mocks gain "Open chats" and "Unseen replies" controls (default 0, so
other stories are unchanged). `NozAwaitingYou` now shows the waiting dot
on a tab.
- Bottom Strip `NozChatOpen` checks each chat opens on its end.
Pages/Noz with Open chats and Unseen replies set shows the list dot. The
Noz page mock now answers each thread as itself.
- Ports the earlier work from #13573 onto the Noz stack.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-26 07:00:30 +00:00
Gaurav Tewari
251d49efce feat(noz): open recent conversations from the bottom strip (#13601)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

Stacked on #13598.

- A history icon in the bottom strip, next to Ask Noz, opens a popover
of recent conversations with a title search. Picking one opens it in the
Noz panel.
- It stays while the panel is open, and hides when Noz is off, on the
Noz full page (whose sidebar lists the chats), or with no saved
conversation.
- It reads the list the shell already loads on every page, so it adds no
request.
- The floating panel and the Cmd/Ctrl+J popup chat lose their history
toggle. The conversation list is now full-page only, so its panel layout
is gone.
- Ask Noz always starts a new chat (reusing an empty open one) and stays
in the strip while the panel is open, so the panel and the popup chat
drop their + button.
- Opening the history closes the panel behind it, so one Noz surface
shows at a time.
- The list's open state lives in the Noz store (`isHistoryOpen`), like
the panel's, so a keyboard shortcut can open it later. It isn't
persisted.
- Both history lists open a chat through `useOpenConversation`, which
always reloads it, so a chat whose load failed can be retried.
- Like the panel, the popover moves left of the support chat while it's
open and back once it closes; Support no longer dismisses it. No new
obstacle system: `FloatingPanel`'s existing obstacle types and utils
move to `lib/obstacles` (renamed, not rewritten), and
`useAvoidObstacles` now subscribes through a shared `watchObstacles`.
The only new pieces are `getRightClearance` and `usePopoverAvoidance`,
the popover's counterpart to `useAvoidObstacles`.
- The @ picker's row style and the conversation list's relative time are
shared with the popover.
- Popover rows use the full-page list's text: vanilla-400 titles in dark
mode (`--l2-foreground` in light, since vanilla-400 doesn't follow the
theme), 20px line height and plain digits.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR


https://github.com/orgs/SigNoz/projects/59/views/18?pane=issue&itemId=306515634&issue=SigNoz%7Cnerve-pod%7C643

<!--If applicable, include screenshots or screen recordings that clearly
show the behavior before the change and the result after the change. -->
#### Screenshots / Screen Recordings

Visual diff (sbshot, both themes, vs `main`):
https://claude.ai/artifact/8xwuRCyTKntdDsfktVKjLP

- 98 pairs change: History and + leave the modal and panel headers, and
the strip gains the History icon. 2 are new (the History popover), 16
are removed (the header History stories), 62 are identical.



https://github.com/user-attachments/assets/ebf88e0b-0096-40e1-b605-b1df9bd7bc94


https://github.com/user-attachments/assets/6772ab32-44b2-48bd-812f-231525860bbb




<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information

-  We should merge this with the next follow up

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-26 06:27:11 +00:00
Vinicius Lourenço
7d92c443b3 refactor(web): move the changelog modal to the signozhq dialog (#13692)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

The changelog modal now uses the `@signozhq/ui` dialog instead of the
antd `Modal`, with the dialog's own colors and spacing. The title row,
scrollable content, footer actions and the "Scroll for more" button
stay, and the surface is one flat panel instead of boxes inside a box.
"Scroll for more" is now a primary `@signozhq/ui` button, so Tab shows
the same focus ring on it as on the footer buttons.

On main the modal's background depended on CSS load order: its own rule
and the global `.ant-modal .ant-modal-content` rule from #10742 have the
same specificity, so whichever loaded last won. The dialog drops those
antd overrides. It also no longer sits under the other `@signozhq/ui`
dialogs, and cloud workspaces, which have no upgrade actions, no longer
get an empty footer bar.

Stacked on #13689.

#### Screenshots / Screen Recordings

![Changelog
dialog](https://github.com/user-attachments/assets/02d6a5af-229c-4ff0-b5f8-b3d196bb092b)

Self-hosted workspace in the dark theme, main on the left and this
branch on the right.
2026-11-26 01:21:47 +00:00
Vinicius Lourenço
11cc323ca5 perf(web): load the AI assistant and changelog only when they render (#13689)
#### Description

The app layout imported the AI assistant panel and modal and the
changelog modal up front, so every page downloaded them before it could
render, including for users who never see the assistant. The assistant
brings the dashboard panel registry and the query builder along, and
with them uPlot, chart.js, CodeMirror, `moment-timezone` and
react-markdown. The assistant's code now loads only when it renders for
the user, and the changelog when it opens. If one of those chunks is
gone after a deploy, the page reloads once, the same way lazy pages
recover.

The entry chunk goes from 10.94 MB to 6.67 MB (2.94 MB to 1.81 MB
gzipped). On a 10 Mbps connection with a 4x slower CPU, the login form
shows in 3.7 s instead of 5.3 s.

Part of #10192

#### Screenshots / Screen Recordings

Cold load of the login page, main on the left. The stats include a build
with every bundle PR merged, for where this is heading:


https://github.com/user-attachments/assets/934ec550-4431-4d54-be51-dc952409565e

![First load
stats](https://github.com/user-attachments/assets/1f10ec42-bea4-48cc-afcb-89a8186f0733)

The changelog modal, main on the left. It now shows "Scroll for more"
when the notes overflow; on main the modal measured before its content
had laid out:

![Changelog
modal](https://github.com/user-attachments/assets/5ca17f48-24fe-4d21-be07-d8d995af6fc5)

The other app layout and bottom strip stories are pixel-identical in
both themes.
2026-11-26 00:26:26 +00:00
Vinicius Lourenço
2d5a07048a fix(widget-card): never request the previous widget query when the card is enabled (#13722)
#### Description

A panel whose widget query changed fetched once more with the previous
query before the new one.

The card kept a copy of the query in state and refreshed it in an
effect, one render late. On the service overview this is the latency
chart: it waits for the top level operations, then sends `name in []`,
which `query_range` rejects with a 400.

The card now sends the widget query directly, and list panels keep only
their paging in the request state.

The logs list stored its page size in that copy, so a query change reset
the request to the widget's page size while the picker kept showing the
user's. It now lives in the paging params and survives a query change.

> The list of logs does not appear to be used by these legacy pages, so
it is likely that this code path is not executed.

This fails `services/detail.spec.ts` TC-04 and `services/list.spec.ts`
TC-02 on #13689, whose timing hits the race on every run.
`GridCardGraph.test.tsx` covers both stale-query cases and the page
size; all three fail without the change.

#### Screenshots

Before:

<img width="894" height="157" alt="image"
src="https://github.com/user-attachments/assets/71a50d88-c49f-4ace-9510-0d40355ec7d0"
/>

After:

<img width="893" height="132" alt="image"
src="https://github.com/user-attachments/assets/2a618cfd-6796-40f9-99a5-aca2436f5fcb"
/>

> No failed requests
2026-11-25 23:52:50 +00:00
Abhi kumar
6921b40467 fix(dashboard): paint the page background in full screen (#13752)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
## Description

- In full screen the dashboard container had no background, so the
browser's black full-screen backdrop showed through in light mode,
hiding the dark section titles.
- The container now paints `--l1-background`, the same surface as the
app shell, in both themes.

Before: 


<img width="3024" height="1964" alt="Screenshot 2026-11-25 at 9 39
43 PM"
src="https://github.com/user-attachments/assets/0f1cf438-a3b7-4323-b532-335fcb0440f6"
/>

After: 

<img width="2056" height="1329" alt="image"
src="https://github.com/user-attachments/assets/9ed6e1dc-9b9f-4ebe-bbad-80494944fd1d"
/>
2026-11-25 17:25:19 +00:00
Vinicius Lourenço
d655a8998b perf(web): load Monaco on the first editor mount (#13686)
#### Description

Since #12515, `src/index.tsx` imports Monaco, so every page loads the
whole editor before it renders. Monaco and our setup (workers, themes,
`loader.config`) now load on the first editor mount. The entry chunk
goes from 10.94 MB to 7.19 MB (2.95 MB to 2.00 MB gzipped).

The hook sits on `@monaco-editor/react`'s loader, not on a wrapper
component, so every editor, including ones added later, gets the bundled
Monaco without changing its import. #12697 takes the wrapper route, and
the editors added or moved since it opened bypass it and can fall back
to the CDN.

Storybook's preview imported the setup directly, so it now imports the
loader as well.

#### Issues closed by this PR

Closes #12692

#### Screenshots / Screen Recordings

ClickHouse query editor, main on top and this branch below:

![ClickHouse query
editor](https://github.com/user-attachments/assets/16f807de-6c51-47f1-85a3-5d3cade864aa)

The 31 editor stories render the same in both themes. The differences
left are the role JSON view race that #13671 fixes and Monaco's overview
ruler drawn a moment later.
2026-11-25 15:42:47 +00:00
Vinicius Lourenço
70ab9c2321 perf(web): load each logs, traces and LLM observability tab when it opens (#13695)
#### Description

Logs, Traces and LLM Observability import all of their tabs up front, so
opening the logs explorer also downloads pipelines, and the traces
explorer downloads funnels. Each tab now loads when it opens, using the
per-tab loading state from #13691. Tab URLs and order stay as they are.

Opening each page's default tab, entry included: LLM Observability goes
from 12.45 MB to 11.80 MB, Logs from 11.63 MB to 11.50 MB and Traces
from 11.75 MB to 11.62 MB. The smaller tabs gain more: funnels drops to
10.97 MB. With the entry PRs in, the page shell alone is 2.55 MB.

Part of #10192

#### Screenshots / Screen Recordings

Switching from the traces explorer to funnels in Storybook, main on the
left, with the network slowed to 1.6 Mbps so the loading state is
visible:


https://github.com/user-attachments/assets/a910cbe8-2db8-431e-95a1-586ba6e0e50d

The 141 logs, traces and LLM observability stories render the same in
both themes; the differences left are live tail offsets, toasts and
loading spinners caught on different frames.
2026-11-25 14:20:48 +00:00
Gaurav Tewari
e085decc05 feat: add support for ai alerts (#13268)
#### Description

Frontend for `AI_TRACES_BASED_ALERT` (backend already supports it,
#12783).

- **Alert type:** "AI Trace-based Alert" card on `/alerts/new`, with its
defaults and alert-type map entries. No docs link until an AI docs page
exists.
- **Editor:** AI alerts open only the AI Query Builder tab (traces, no
trace operator), always in the new editor (classic page and its switch
hidden). Preview, condition query, "Group alerts by" and label-key
checks read the AI slot.
- **Query shape:** the editor keeps AI in its own slot
(`builder_ai_query`), like the dashboard panel editor. It converts to
the wire shape (`builder` + `builder_ai_query` envelopes) only on
preview/save, since a rule's `queryType` must be `builder | promql |
clickhouse_sql`. Saved rules are moved back into the AI slot on edit
(`toAISlotQuery`).
- **Dashboard:** Create Alerts is enabled for AI panels. The link keeps
the AI slot, and the alert page detects AI from the query's `queryType`.
- **History:** the alert popover / top contributors show "View AI
Traces" from `relatedAITracesLink`.

#### Issues closed by this PR


Closes
https://github.com/orgs/SigNoz/projects/59/views/18?pane=issue&itemId=283123867&issue=SigNoz%7Cnerve-pod%7C513


#### Screenshots / Screen Recordings



https://github.com/user-attachments/assets/6663a68a-5eea-4920-b30a-205eeba311d3



#### Additional Information

- was Stacked on #13486 (`refactor/ai-explorer-query-type`).
- Not in scope: Create alert from the AI explorer (its query is still in
the tagged shape; to discuss separately)
- SBSHOT -
https://claude.ai/artifact/X2JQRsNXJ8KCNFcmtgFLMd?sk=CHo7GMdRF6MGhUdbE0PkSg

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-25 13:06:39 +00:00
Abhi kumar
415a74938b feat(dashboard): add the distribution chart (#13536)
#### Description

- Adds the `Distribution` chart: bucket counts as bars over equal-width
bucket slots, groups stacked, side by side or as 100% shares; the
overflow bucket is hatched.
- `TooltipPlugin` / `ChartWrapper`: opt-in `pinOnClick`, so a chart can
pin its tooltip on a click instead of handling it.
- New reusable uPlot `variableWidthBars` path builder; hover focuses the
group under the cursor, as the bar panel does.
- Stacked and percent draw every group. Side by side draws as many as
fit (at most 10) and sums the rest into Other, with Pie's Other label
and colour; the legend keeps every group.
- Percentile markers computed client-side the way `histogram_quantile`
does, drawn as dashed lines with diamond badges; hovering one shows its
value on the x axis. Markers on the same spot share one badge (`p90+`).
- Tooltip in the time-series layout: bucket range and total, the hovered
group above the divider, then every group by count, named by its
group-by value. Over Other it lists the groups Other sums; clicking the
Other bar pins it, as on Pie, and a group can then be picked for
drilldown.
- `jest.config`: `modulePathIgnorePatterns` matched any path containing
`dist`, which silently skipped these tests; now only `<rootDir>/dist/`.

#### Additional Information

- Chart-only, on `main`. Stack: this PR → #13535 (spec) → #13537
(panel).
- The jest change may start running other suites under paths containing
`dist`.
2026-11-25 13:04:51 +00:00
hardik-signoz
af3fd93339 fix(authdomain): stack provider title above description and correct role mapping copy (#13747)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Stacks each provider's title above its description in the "Configure
Authentication Method" dialog. They sat inline, so the title ran into
the description, and the Configure buttons started at different x
positions. The text column now fills the row.
- Fixes the group mapping help text. A user in several mapped groups
gets every matching role, not the highest-privilege one.

Before
<img width="565" height="339" alt="image"
src="https://github.com/user-attachments/assets/46016493-ba29-44b5-8012-dd74eddc0a61"
/>

After
<img width="547" height="364" alt="image"
src="https://github.com/user-attachments/assets/59e21df8-0a20-4bc9-97f9-c8d3713173f8"
/>

Before
<img width="1000" height="578" alt="image"
src="https://github.com/user-attachments/assets/d814a2a2-a0aa-40bf-b1c8-e7f476e9e50f"
/>

After
<img width="1011" height="587" alt="image"
src="https://github.com/user-attachments/assets/2775cfca-bc63-4d20-8751-36d6b316e69e"
/>





#### Issues closed by this PR

Closes SigNoz/keystone-pod#233
2026-11-25 08:21:28 +00:00
Ashwin Bhatkal
22a65c4f74 test(frontend): replace DOM traversal in tests with Testing Library queries (#13731)
#### Description

Stacked on [#13729](https://github.com/SigNoz/signoz/pull/13729).

- The 520 DOM lookups left in 148 test files (`querySelector`,
`closest`, `parentElement` and the like) now go through Testing Library:
test IDs first, then role, label or text, scoped with `within`. App
components gain the test IDs this needs.
- A new lint rule, `signoz/no-dom-node-access`, flags these calls in
test files. A test that checks DOM structure on purpose disables it on
that line with a reason; 9 lines do.
- Some checks that could never fail now can: a multi-select filter test
that never typed, role table rows found by a class that matched nothing,
and a query section test whose async loop was never awaited.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/770

#### Additional Information

- antd `Skeleton` drops `data-*`, so a few loading states gain a wrapper
`div` that carries the test ID (AuthCard, ViewRolePage,
WidgetGraphComponent, TraceDetailsHeader). TraceDetailsHeader's skeleton
class moves to that wrapper, with `display: flex` to keep the layout.
2026-11-25 05:16:03 +00:00
Gaurav Tewari
fa1dbe25cb fix(noz): drop the reply bubble colour and add modal and panel stories (#13740)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

- Noz replies lose the grey bubble background in the modal and the side
panel. Width, padding and radius stay as they were; errors keep their
red callout.
- Approval and clarification cards use `border-box`. The modal and panel
portal outside the layout's border-box reset, so the cards ran 26px past
the reply column.
- Adds `Pages/Noz/Modal` and `Pages/Noz/Panel`: every state of the Noz
page story in the ⌘J modal and the floating panel, plus History for the
conversation list behind their headers.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

<!--If applicable, include screenshots or screen recordings that clearly
show the behavior before the change and the result after the change. -->
#### Screenshots / Screen Recordings

Visual diff (sbshot, both themes):
https://claude.ai/artifact/E1eFXkLUQ6UUvpQ7Mg5SyJ

- 182 pairs at a 0.005 threshold (the grey is below sbshot's default):
53 changed (40 modal, 13 panel), 120 pixel-identical, 9 noise.
- The Noz page and the bottom strip are unchanged.

<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-24 23:05:13 +00:00
630 changed files with 15411 additions and 4431 deletions

View File

@@ -9,7 +9,7 @@ paths:
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. `signoz/no-dom-node-access` flags the DOM calls in test files; a test that checks DOM structure on purpose disables it on that line with a reason. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check: Base UI popups sit inside an element with an inline `pointer-events: none`, and the stylesheet that turns it back on for the popup never loads in jsdom, so the check would block every click on them. Never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.

View File

@@ -10,5 +10,6 @@
- **Use convensional commit format** for commits and PR title.
- **Do not amend the commits once pushed.** Always create a new commit once changes are pushed to remote.
- **Review fixes are new commits too.** A force push hides what changed from human reviewers and makes Greptile post its findings again. Bring in `main` with a merge; only a stacked branch (`gh stack`) rebases, since the stack moves as a unit.
- **A review fix to an AI-owned file fixes its generator too.** A file with the AI-owned banner (story mocks and plays, `tests/e2e/drivers/`) is rewritten by the skill or agent that made it, so a fix made only in the file comes back on the next run. In the same PR, add the lesson to that skill or agent as a concrete case.
- **Answer every Greptile thread.** Reply with the commit that fixes it (`Fixed in 4df6f3198d: <what changed>`) or the reason it stays, then resolve. Never resolve one with neither: Greptile withdraws a finding, and remembers it, only when told why.
- **Leave human review threads to the author.** Fix the code they ask for, but never reply to or resolve a human reviewer's thread.

View File

@@ -110,8 +110,9 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
CI runs each play once, with its story's own args. Anyone can flip a control in the panel, and nothing runs the play against that value, so a play that breaks on it goes unnoticed. Write each play so it cannot.
Before writing the clicks, list what has to be on screen for the play's target to exist, and return early when the args take it away. These are the cases plays have missed:
Before writing the clicks, list what has to be on screen for the play's target to exist. Then walk every control the story exposes, the page's own as well as the shared ones, and return early for each value that takes something on that list away. These are the cases plays have missed:
- An arg the story sets. The story sets it because the play needs what that value renders, and the panel can flip it. On the `mine` view the dashboards Created-by filter opens with a tag to remove; on the other views it opens empty and there is no × to click. Check the tag is there by parsing the route the view resolves to.
- The controls every story has. `State` on loading or error renders no rows and no filter suggestions. `Access`, `Permissions` and `Revoked` remove rows, row actions and gated buttons, and the `editor` and `viewer` presets grant telemetry reads only, so a page gated on its own resource shows them nothing. `Check state` on loading disables every gated control, and on error an `AuthZButton` stays enabled while an `AuthZGuardContent` set to fail closed hides what it wraps. `License` and `Banner` decide the plan, so a cloud-only form is gone on the others. `Hold tooltips open` shows a label a second time, inside its tooltip.
- A count at 0. The page can swap its whole list for an empty state, and the header, filters and column picker go with it.
- A view, filter or invalid query that leaves no rows, even when the count is above 0.

View File

@@ -63,7 +63,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: check-semconv-generated-files
@@ -78,7 +78,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: qemu-install
@@ -114,7 +114,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-openapi
@@ -131,7 +131,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-authz
@@ -148,7 +148,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-web-settings
@@ -165,7 +165,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-transaction-groups

View File

@@ -131,6 +131,10 @@ func runGenerateAuthz(_ context.Context) error {
coretypes.NewResourceRef(coretypes.ResourceMetaResourceNotificationChannel).String(): true,
coretypes.NewResourceRef(coretypes.ResourceUser).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorPassword).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionKey).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionLimit).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceAuthDomain).String(): true,
coretypes.NewResourceRef(coretypes.ResourceOrganization).String(): true,
}
allowedTypes := map[string]bool{}

View File

@@ -296,6 +296,8 @@
// Bans msw imports in *.stories.tsx; handlers/mock data belong in the sibling .stories.mocks.tsx
"signoz/no-direct-react-router-import": "error",
// Steers call sites to the src/lib/router facade (allowlisted in overrides below)
"signoz/no-builder-ai-query-access": "error",
// Steers AI slot access to lib/query/builderSlot (allowlisted in overrides below)
"no-restricted-globals": [
"error",
{
@@ -316,6 +318,11 @@
"name": "redux",
"message": "[State mgmt] redux is deprecated. Migrate to Zustand, nuqs, or react-query."
},
{
"name": "@signozhq/design-tokens",
"importNames": ["Style"],
"message": "[bundle] Style is a large object of CSS variable strings and is not tree-shaken. Write the CSS variable directly, for example 'var(--l3-foreground)'."
},
{
"name": "react-redux",
"message": "[State mgmt] react-redux is deprecated. Migrate to Zustand, nuqs, or react-query."
@@ -338,6 +345,11 @@
"importNames": ["patchDashboardV2", "usePatchDashboardV2"],
"message": "[dashboard-v2] Don't call patchDashboardV2/usePatchDashboardV2 directly — use useOptimisticPatch().patchAsync so spec edits update the react-query cache optimistically and reconcile on settle."
},
{
"name": "antd/lib",
"allowTypeImports": true,
"message": "[bundle] antd/lib is the CommonJS root and bundles every antd component. Import from 'antd' instead."
},
{
"name": "motion/react-client",
"message": "[motion] motion/react-client is for React Server Components only. Use 'motion/react' instead — it provides the same exports and works correctly in client-side SPAs."
@@ -552,6 +564,7 @@
],
"rules": {
"import/first": "off",
"signoz/no-dom-node-access": "error",
// Should ignore due to mocks
"signoz/no-navigator-clipboard": "off",
// Tests can use navigator.clipboard directly,
@@ -559,6 +572,8 @@
"no-restricted-globals": "off",
// Tests need raw localStorage/sessionStorage to seed DOM state for isolation
"signoz/no-zustand-getstate-in-hooks": "off",
"signoz/no-builder-ai-query-access": "off",
// Fixtures build and assert on the raw AI slot
"@typescript-eslint/no-explicit-any": "off", // Tests often need any for mocks/stubs
"@typescript-eslint/explicit-module-boundary-types": "off", // Return types not required in tests
"@typescript-eslint/explicit-function-return-type": "off" // Same as above rule, don't need to care about return type
@@ -615,6 +630,20 @@
"rules": {
"signoz/no-direct-react-router-import": "off"
}
},
{
// builderSlot owns the AI slot; the rest normalise its wire shape or test whether it exists, which the helpers hide
"files": [
"src/lib/query/builderSlot.ts",
"src/hooks/queryBuilder/normalizeCompositeQuery.ts",
"src/hooks/queryBuilder/useGetCompositeQueryParam.ts",
"src/providers/QueryBuilder.tsx",
"src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/usePanelKindChange.ts",
"src/pages/DashboardPage/DashboardContainer/Panels/utils/seedBuilderForMode.ts"
],
"rules": {
"signoz/no-builder-ai-query-access": "off"
}
}
]
}

View File

@@ -15,8 +15,6 @@
content="frame-src 'self' blob: data:"
/>
<link rel="stylesheet" href="css/uPlot.min.css" />
<script>
// i18n's language detector would pick the browser locale (e.g. `en-US`), which
// /public/locales does not ship; pin it to the bundled language instead.

View File

@@ -21,7 +21,8 @@ import i18n from '../src/ReactI18';
// `src/index.tsx` does this at boot: without it `@monaco-editor/react` falls back
// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does
// not report because the requests look like static assets.
import '../src/lib/monaco/setup';
import '../src/lib/monaco/loader';
import '../src/lib/uPlotStylesheet';
import '../src/styles.scss';
@@ -176,6 +177,7 @@ const preview: Preview = {
'AI Observability',
['Overview', 'Explorer', 'Model Pricing', 'Attribute Mapping'],
'Noz',
['Overview', 'Modal', 'Panel'],
'Metering',
['Cost Meter', 'Usage Explorer'],
'Messaging Queues',
@@ -196,7 +198,9 @@ const preview: Preview = {
['Overview', 'Authz'],
'Service Accounts',
'Ingestion',
['Overview', 'Authz'],
'Single Sign-on',
['Overview', 'Authz'],
'Keyboard Shortcuts',
],
'Auth',

View File

@@ -157,7 +157,6 @@
})(document, 'script');
}
</script>
<link rel="stylesheet" href="css/uPlot.min.css" />
<script type="module" src="./src/index.tsx"></script>
</body>
</html>

View File

@@ -11,9 +11,9 @@ const config: Config.InitialOptions = {
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
collectCoverageFrom: ['src/**/*.{ts,tsx}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
modulePathIgnorePatterns: ['dist'],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
moduleNameMapper: {
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff|wav)$':
'<rootDir>/__mocks__/fileMock.ts',
// The icon glob module uses `import.meta.glob` (Vite-only); jest can't parse
// it, so redirect any import of it to a stub.

View File

@@ -57,7 +57,7 @@
"@signozhq/design-tokens": "2.8.0",
"@signozhq/icons": "0.4.0",
"@signozhq/noz-client": "1.13.0",
"@signozhq/ui": "0.4.0-rc.5",
"@signozhq/ui": "0.4.1-rc.2",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",
"@uiw/codemirror-theme-copilot": "4.23.11",

View File

@@ -0,0 +1,59 @@
import { ruleTester } from './rule-tester.mjs';
const message =
'from lib/query/builderSlot instead of accessing builder_ai_query';
await ruleTester({
rule: 'no-builder-ai-query-access',
valid: [
{
name: 'reading through the slot helper',
code: 'export const data = getActiveBuilder(query).queryData;',
},
{
name: 'reading the builder slot',
code: 'export const data = query.builder.queryData;',
},
{
name: 'building a query with the AI slot',
code: 'export const next = { ...query, builder_ai_query: builder };',
},
{
name: 'generated enum member',
code:
'export const type = Querybuildertypesv5QueryTypeDTO.builder_ai_query;',
},
{
name: 'type position',
code: "export type Slot = Query['builder_ai_query'];",
},
],
invalid: [
{
name: 'picking the slot by query type',
code:
'export const data =\n\tquery.queryType === EQueryType.AI_QUERY_BUILDER\n\t\t? query.builder_ai_query?.queryData\n\t\t: query.builder.queryData;',
errors: [{ message, line: 3 }],
},
{
name: 'optional chaining',
code: 'export const slot = query?.builder_ai_query;',
errors: [{ message, line: 1 }],
},
{
name: 'writing the slot',
code: 'query.builder_ai_query = builder;',
errors: [{ message, line: 1 }],
},
{
name: 'bracket access',
code: "export const slot = query['builder_ai_query'];",
errors: [{ message, line: 1 }],
},
{
name: 'destructuring',
code: 'export const { builder_ai_query: slot } = query;',
errors: [{ message, line: 1 }],
},
],
});

View File

@@ -0,0 +1,60 @@
import { ruleTester } from './rule-tester.mjs';
const message = (name) =>
`Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`;
await ruleTester({
rule: 'no-dom-node-access',
valid: [
{
name: 'Testing Library queries',
code: "within(screen.getByTestId('row')).getByText('Name');",
},
{
name: 'a query method that is not called',
code:
'jest.spyOn(document, "querySelector");\nconst q = Element.prototype.closest;',
},
{
name: 'computed access',
code: "const name = 'closest';\nel[name]('tr');",
},
],
invalid: [
{
name: 'querySelector on the container',
code: "container.querySelector('.row');",
errors: [{ message: message('querySelector'), line: 1, column: 11 }],
},
{
name: 'closest after a screen query',
code: "screen.getByText('Name').closest('tr');",
errors: [{ message: message('closest'), line: 1, column: 26 }],
},
{
name: 'optional call',
code: "row?.querySelectorAll('td');",
errors: [{ message: message('querySelectorAll'), line: 1, column: 6 }],
},
{
name: 'traversal property',
code: 'expect(cell.parentElement).toBeVisible();',
errors: [{ message: message('parentElement'), line: 1, column: 13 }],
},
{
name: 'children of a DOM node',
code: "expect(screen.getByTestId('list').children).toHaveLength(2);",
errors: [{ message: message('children'), line: 1, column: 35 }],
},
{
name: 'children of a data tree',
code: 'expect(tree.children).toHaveLength(2);',
errors: [{ message: message('children'), line: 1, column: 13 }],
},
{
name: 'document lookup by id',
code: "document.getElementById('root');",
errors: [{ message: message('getElementById'), line: 1, column: 10 }],
},
],
});

View File

@@ -0,0 +1,51 @@
const SLOT = 'builder_ai_query';
function isSlotKey(key, computed) {
if (key.type === 'Literal') {
return key.value === SLOT;
}
return !computed && key.type === 'Identifier' && key.name === SLOT;
}
// Generated enums like Querybuildertypesv5QueryTypeDTO.builder_ai_query are not queries
function isGeneratedEnum(object) {
return object.type === 'Identifier' && /^[A-Z]/.test(object.name);
}
export default {
meta: {
type: 'suggestion',
docs: {
description:
'Disallow direct builder_ai_query access; use the lib/query/builderSlot helpers',
category: 'Query Builder',
},
schema: [],
messages: {
useSlotHelper:
'Use getActiveBuilder, getBuilderBySlotKey or replaceBuilderBySlotKey from lib/query/builderSlot instead of accessing builder_ai_query directly.',
},
},
create(context) {
return {
MemberExpression(node) {
if (
isSlotKey(node.property, node.computed) &&
!isGeneratedEnum(node.object)
) {
context.report({ node, messageId: 'useSlotHelper' });
}
},
ObjectPattern(node) {
node.properties.forEach((property) => {
if (
property.type === 'Property' &&
isSlotKey(property.key, property.computed)
) {
context.report({ node: property, messageId: 'useSlotHelper' });
}
});
},
};
},
};

View File

@@ -0,0 +1,60 @@
/**
* Rule: no-dom-node-access
*
* Tests find elements through Testing Library (`screen`, `within`), not by
* walking the DOM. Flags calls to DOM query methods and reads of node
* traversal properties:
* container.querySelector('.row')
* screen.getByText('Name').closest('tr')
* cell.parentElement
* list.children
*
* A non-DOM `children` read (a data tree, React props) disables the rule on
* that line with a reason.
*/
const QUERY_METHODS = new Set([
'querySelector',
'querySelectorAll',
'closest',
'getElementById',
'getElementsByClassName',
'getElementsByTagName',
'getElementsByName',
]);
const TRAVERSAL_PROPERTIES = new Set([
'parentElement',
'parentNode',
'firstChild',
'lastChild',
'firstElementChild',
'lastElementChild',
'nextSibling',
'previousSibling',
'nextElementSibling',
'previousElementSibling',
'childNodes',
'children',
]);
export default {
create(context) {
return {
MemberExpression(node) {
if (node.computed || node.property.type !== 'Identifier') {
return;
}
const { name } = node.property;
const isCall =
node.parent?.type === 'CallExpression' && node.parent.callee === node;
if ((isCall && QUERY_METHODS.has(name)) || TRAVERSAL_PROPERTIES.has(name)) {
context.report({
node: node.property,
message: `Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`,
});
}
},
};
},
};

View File

@@ -19,6 +19,8 @@ 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';
import noDomNodeAccess from './rules/no-dom-node-access.mjs';
import noBuilderAiQueryAccess from './rules/no-builder-ai-query-access.mjs';
export default {
meta: {
@@ -39,5 +41,7 @@ export default {
'no-direct-react-router-import': noDirectReactRouterImport,
'no-text-css': noTextCss,
'require-disable-reason': requireDisableReason,
'no-dom-node-access': noDomNodeAccess,
'no-builder-ai-query-access': noBuilderAiQueryAccess,
},
};

View File

@@ -86,8 +86,8 @@ importers:
specifier: 1.13.0
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
'@signozhq/ui':
specifier: 0.4.0-rc.5
version: 0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
specifier: 0.4.1-rc.2
version: 0.4.1-rc.2(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@tanstack/react-table':
specifier: 8.21.3
version: 8.21.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -3258,8 +3258,8 @@ packages:
react: ^18.2.0
react-query: ^3.39.3
'@signozhq/ui@0.4.0-rc.5':
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
'@signozhq/ui@0.4.1-rc.2':
resolution: {integrity: sha512-pCMRzrJ6CmGjEgAQ2B6wRRengP2sy7Y860Npr5nkCapc9NPH5jy4VO48CDv5gnKwWSKShmLHwzbiK2E1cGndKQ==}
peerDependencies:
'@signozhq/design-tokens': '>=2.7.0'
'@signozhq/icons': 0.3.0
@@ -12389,7 +12389,7 @@ snapshots:
react: 18.2.0
react-query: 3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@signozhq/ui@0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
'@signozhq/ui@0.4.1-rc.2(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
dependencies:
'@base-ui/react': 1.8.0(@date-fns/tz@1.4.1)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@signozhq/design-tokens': 2.8.0

View File

@@ -1 +0,0 @@
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}

View File

@@ -117,6 +117,8 @@
"log_based_alert_desc": "Send a notification when a condition occurs in the logs data.",
"traces_based_alert": "Trace-based Alert",
"traces_based_alert_desc": "Send a notification when a condition occurs in the traces data.",
"ai_traces_based_alert": "AI Trace-based Alert",
"ai_traces_based_alert_desc": "Send a notification when a condition occurs in AI and LLM traces.",
"exceptions_based_alert": "Exceptions-based Alert",
"exceptions_based_alert_desc": "Send a notification when a condition occurs in the exceptions data.",
"field_unit": "Threshold unit",

View File

@@ -121,6 +121,8 @@
"log_based_alert_desc": "Send a notification when a condition occurs in the logs data.",
"traces_based_alert": "Trace-based Alert",
"traces_based_alert_desc": "Send a notification when a condition occurs in the traces data.",
"ai_traces_based_alert": "AI Trace-based Alert",
"ai_traces_based_alert_desc": "Send a notification when a condition occurs in AI and LLM traces.",
"exceptions_based_alert": "Exceptions-based Alert",
"exceptions_based_alert_desc": "Send a notification when a condition occurs in the exceptions data.",
"field_unit": "Threshold unit",

View File

@@ -175,8 +175,8 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
pathname === ROUTES.SETTINGS ||
pathname === ROUTES.BILLING ||
pathname === ROUTES.MEMBERS_SETTINGS ||
(isAdmin &&
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
pathname === ROUTES.ORG_SETTINGS ||
(isAdmin && pathname === ROUTES.MY_SETTINGS);
if (
pathname !== ROUTES.WORKSPACE_LOCKED &&

View File

@@ -808,7 +808,7 @@ describe('PrivateRoute', () => {
assertStaysOnRoute(ROUTES.BILLING);
});
it('should redirect VIEWER to workspace locked when trying to access org-settings', async () => {
it('should allow VIEWER to access org-settings when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.ORG_SETTINGS,
appContext: {
@@ -821,7 +821,7 @@ describe('PrivateRoute', () => {
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
});
it('should allow VIEWER to access members settings when workspace is blocked', () => {
@@ -1707,6 +1707,7 @@ describe('PrivateRoute', () => {
// Everything under /settings resolves to the non-exact SETTINGS route
SETTINGS: { path: ROUTES.SETTINGS, deniedRoles: DENIED_ROLES },
MY_SETTINGS: { path: ROUTES.MY_SETTINGS, deniedRoles: DENIED_ROLES },
ORG_SETTINGS: { path: ROUTES.ORG_SETTINGS, deniedRoles: DENIED_ROLES },
ROLES_SETTINGS: { path: ROUTES.ROLES_SETTINGS, deniedRoles: DENIED_ROLES },
ROLE_CREATE: { path: ROUTES.ROLE_CREATE, deniedRoles: DENIED_ROLES },
ROLE_DETAILS: {

View File

@@ -17,13 +17,11 @@ function loadGetModule(href: string): GetModule {
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
mod = require('../get');
});
base.remove();
return mod;
}
afterEach(() => {
for (const el of document.head.querySelectorAll('base')) {
el.remove();
}
localStorage.clear();
});

View File

@@ -15,13 +15,11 @@ function loadGetModule(href: string): GetModule {
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
mod = require('../get');
});
base.remove();
return mod;
}
afterEach(() => {
for (const el of document.head.querySelectorAll('base')) {
el.remove();
}
sessionStorage.clear();
});

Binary file not shown.

View File

@@ -1,4 +1,4 @@
import { act, render, screen } from '@testing-library/react';
import { act, render, screen } from 'tests/test-utils';
import LabelColumn from './LabelColumn';
@@ -92,7 +92,9 @@ describe('LabelColumn', () => {
renderWithProviders(<LabelColumn labels={labels} />);
const isHidden = (label: string): boolean =>
screen.getByTestId(`label-tag-${label}`).closest('.overflowed') !== null;
screen
.getByTestId(`label-tag-container-${label}`)
.classList.contains('overflowed');
expect(labels.filter(isHidden)).toStrictEqual(['team', 'owner', 'version']);
expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
@@ -157,8 +159,7 @@ describe('LabelColumn', () => {
it('should render empty when no labels provided', () => {
renderWithProviders(<LabelColumn labels={[]} />);
const column = screen.getByTestId('label-column');
expect(column.children).toHaveLength(0);
expect(screen.getByTestId('label-column')).toBeEmptyDOMElement();
});
it('should use primary color by default', () => {

View File

@@ -45,7 +45,7 @@ function LabelTag({
</div>
}
>
<span className={className}>
<span className={className} data-testid={`label-tag-container-${label}`}>
<Badge
textTransform="none"
color={color ?? 'secondary'}

View File

@@ -22,7 +22,10 @@ function AppLoading(): JSX.Element {
const isDarkMode = getThemeFromStorage();
return (
<div className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}>
<div
className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}
data-testid="app-loading-container"
>
<div className="perilin-bg" />
<div className="app-loading-content">
<div className="brand">
@@ -53,7 +56,7 @@ function AppLoading(): JSX.Element {
</Typography>
</div>
<div className="loader" />
<div className="loader" data-testid="app-loading-loader" />
</div>
</div>
);

View File

@@ -1,4 +1,5 @@
import { render, screen } from '@testing-library/react';
import { render } from '@testing-library/react';
import { screen } from 'tests/test-utils';
import getLocal from '../../../api/browser/localstorage/get';
import AppLoading from '../AppLoading';
@@ -15,7 +16,6 @@ describe('AppLoading', () => {
const SIGNOZ_TEXT = 'SigNoz';
const TAGLINE_TEXT =
'OpenTelemetry-Native Logs, Metrics and Traces in a single pane';
const CONTAINER_SELECTOR = '.app-loading-container';
beforeEach(() => {
jest.clearAllMocks();
@@ -33,7 +33,7 @@ describe('AppLoading', () => {
expect(screen.getByText(TAGLINE_TEXT)).toBeInTheDocument();
// Check if dark theme class is applied
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
const container = screen.getByTestId('app-loading-container');
expect(container).toHaveClass('dark');
expect(container).not.toHaveClass('lightMode');
});
@@ -58,7 +58,7 @@ describe('AppLoading', () => {
expect(tagline).toBeInTheDocument();
// Check for loader
const loader = document.querySelector('.loader');
const loader = screen.getByTestId('app-loading-loader');
expect(loader).toBeInTheDocument();
});
@@ -72,7 +72,7 @@ describe('AppLoading', () => {
// Should still render with dark theme as fallback
expect(screen.getByText(SIGNOZ_TEXT)).toBeInTheDocument();
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
const container = screen.getByTestId('app-loading-container');
expect(container).toHaveClass('dark');
});
});

View File

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

View File

@@ -0,0 +1,25 @@
.scrollHint {
position: sticky;
bottom: 0;
height: 0;
}
.scrollButton {
position: absolute;
bottom: var(--spacing-7);
left: 50%;
transform: translateX(-50%);
}
.scrollIcon {
animation: pulse 1s infinite;
}
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}

View File

@@ -1,129 +0,0 @@
.changelog-modal {
.ant-modal-content {
padding: unset;
background-color: var(--l2-background);
.ant-modal-header {
margin-bottom: unset;
}
.ant-modal-footer {
margin-top: unset;
}
}
&-title {
display: flex;
align-items: center;
gap: 8px;
background-color: var(--l2-background);
padding: 16px;
font-size: 14px;
line-height: 20px;
color: var(--l1-foreground);
border-bottom: 1px solid var(--l1-border);
}
&-footer.scroll-available {
.scroll-btn-container {
display: block;
}
}
&-footer {
position: relative;
border: 1px solid var(--l1-border);
padding: 12px;
display: flex;
align-items: center;
justify-content: space-between;
&-label {
color: var(--text-robin-400);
font-size: 14px;
line-height: 24px;
position: relative;
padding-left: 14px;
&::before {
content: '';
position: absolute;
top: 50%;
left: 0;
transform: translateY(-50%);
width: 6px;
height: 6px;
border-radius: 100%;
background-color: var(--primary-background);
}
}
&-ctas {
display: flex;
margin-left: auto;
& svg {
font-size: 14px;
}
}
.scroll-btn-container {
display: none;
position: absolute;
top: -40px;
left: 50%;
transform: translateX(-50%);
.scroll-btn {
all: unset;
padding: 4px 12px 4px 10px;
background-color: var(--l1-border);
border-radius: 20px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
transition: background-color 0.1s;
&:hover {
background-color: var(--l1-border);
}
&:active {
background-color: var(--l1-border);
}
span {
font-size: 12px;
line-height: 18px;
color: var(--l2-foreground);
}
// add animation to the chevrons down icon
svg {
animation: pulse 1s infinite;
}
}
}
}
&-content {
max-height: calc(100vh - 300px);
overflow-y: auto;
padding: 16px 16px 18px 16px;
border: 1px solid var(--l1-border);
border-top-width: 0;
border-bottom-width: 0;
}
}
// pulse for the scroll for more icon
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}

View File

@@ -1,10 +1,9 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useEffect } from 'react';
import { useMutation } from 'react-query';
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
import { Button, Modal } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button } from '@signozhq/ui/button';
import { Dialog } from '@signozhq/ui/dialog';
import updateUserPreference from 'api/v1/user/preferences/name/update';
import cx from 'classnames';
import { USER_PREFERENCES } from 'constants/userPreferences';
import dayjs from 'dayjs';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
@@ -13,8 +12,9 @@ import { ChangelogSchema } from 'types/api/changelog/getChangelogByVersion';
import { UserPreference } from 'types/api/preferences/preference';
import ChangelogRenderer from './components/ChangelogRenderer';
import { useChangelogScroll } from './useChangelogScroll';
import './ChangelogModal.styles.scss';
import styles from './ChangelogModal.module.scss';
interface Props {
changelog: ChangelogSchema;
@@ -22,8 +22,7 @@ interface Props {
}
function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
const [hasScroll, setHasScroll] = useState(false);
const changelogContentSectionRef = useRef<HTMLDivElement>(null);
const { contentRef, hasScroll, scrollForMore } = useChangelogScroll();
const { userPreferences, updateUserPreferenceInContext } = useAppContext();
const formattedReleaseDate = dayjs(changelog?.release_date).format(
@@ -57,30 +56,6 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
updateUserPreferenceInContext,
]);
const checkScroll = useCallback((): void => {
if (changelogContentSectionRef.current) {
const { scrollHeight, clientHeight, scrollTop } =
changelogContentSectionRef.current;
const isAtBottom = scrollHeight - clientHeight - scrollTop <= 8;
setHasScroll(scrollHeight > clientHeight + 24 && !isAtBottom); // 24px - buffer height to show show more
}
}, []);
useEffect(() => {
checkScroll();
const changelogContentSection = changelogContentSectionRef.current;
if (changelogContentSection) {
changelogContentSection.addEventListener('scroll', checkScroll);
}
return (): void => {
if (changelogContentSection) {
changelogContentSection.removeEventListener('scroll', checkScroll);
}
};
}, [checkScroll]);
const onClickUpdateWorkspace = (): void => {
window.open(
'https://signoz.io/upgrade-path',
@@ -89,75 +64,61 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
);
};
const onClickScrollForMore = (): void => {
if (changelogContentSectionRef.current) {
changelogContentSectionRef.current.scrollTo({
top: changelogContentSectionRef.current.scrollTop + 600, // Scroll 600px from the current position
behavior: 'smooth',
});
}
};
// 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')}
title={
<div className="changelog-modal-title">
<ScrollText size={16} />
What’s New ⎯ Changelog : {formattedReleaseDate}
</div>
}
width={820}
<Dialog
open
onCancel={onClose}
footer={
<div
className={cx('changelog-modal-footer', hasScroll && 'scroll-available')}
>
{!isCloudUser && (
<div className="changelog-modal-footer-ctas">
<Button type="default" onClick={onClose}>
<Flex align="center" gap="4px">
<X size="md" />
Skip for now
</Flex>
</Button>
<Button type="primary" onClick={onClickUpdateWorkspace}>
<Flex align="center" gap="4px">
<Check size="md" />
Update my workspace
</Flex>
</Button>
</div>
)}
{changelog && (
<div className="scroll-btn-container">
<button
data-testid="scroll-more-btn"
type="button"
className="scroll-btn"
onClick={onClickScrollForMore}
>
<ChevronsDown size={14} />
<span>Scroll for more</span>
</button>
</div>
)}
</div>
onClose={onClose}
title={`What’s New ⎯ Changelog : ${formattedReleaseDate}`}
titleIcon={<ScrollText size={16} />}
width="extra-wide"
testId="changelog-dialog"
footerSuffix={
isCloudUser ? undefined : (
<>
<Button
variant="outlined"
color="secondary"
size="md"
prefix={<X size={12} />}
onClick={onClose}
testId="changelog-skip-btn"
>
Skip for now
</Button>
<Button
variant="solid"
color="primary"
size="md"
prefix={<Check size={12} />}
onClick={onClickUpdateWorkspace}
testId="changelog-update-btn"
>
Update my workspace
</Button>
</>
)
}
>
<div
className="changelog-modal-content"
data-testid="changelog-content"
ref={changelogContentSectionRef}
>
{changelog && <ChangelogRenderer changelog={changelog} />}
<div data-testid="changelog-content" ref={contentRef}>
<ChangelogRenderer changelog={changelog} />
</div>
</Modal>
{hasScroll && (
<div className={styles.scrollHint}>
<div className={styles.scrollButton}>
<Button
variant="solid"
color="primary"
size="sm"
prefix={<ChevronsDown size={14} className={styles.scrollIcon} />}
onClick={scrollForMore}
testId="scroll-more-btn"
>
Scroll for more
</Button>
</div>
</div>
)}
</Dialog>
);
}

View File

@@ -1,12 +1,23 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { fireEvent, render, screen } from '@testing-library/react';
import { ReactNode } from 'react';
import { USER_PREFERENCES } from 'constants/userPreferences';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import { IAppContext } from 'providers/App/types';
import {
fireEvent,
getAppContextMock,
render,
screen,
userEvent,
waitFor,
} from 'tests/test-utils';
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
import {
LicensePlatform,
LicenseResModel,
} from 'types/api/licensesV3/getActive';
import { UserPreference } from 'types/api/preferences/preference';
import ChangelogModal from '../ChangelogModal';
@@ -40,71 +51,165 @@ const mockChangelog: ChangelogSchema = {
jest.mock(
'react-markdown',
() =>
function ReactMarkdown({ children }: any) {
function ReactMarkdown({ children }: { children: ReactNode }): JSX.Element {
return <div>{children}</div>;
},
);
// mock useAppContext
jest.mock('providers/App/App', () => ({
useAppContext: jest.fn(() => ({
updateUserPreferenceInContext: jest.fn(),
userPreferences: [
{
name: USER_PREFERENCES.LAST_SEEN_CHANGELOG_VERSION,
value: 'v1.0.0',
},
],
})),
}));
function renderChangelog(onClose: () => void = jest.fn()): void {
const seenChangelogVersion: UserPreference = {
name: USER_PREFERENCES.LAST_SEEN_CHANGELOG_VERSION,
description: '',
valueType: 'string',
defaultValue: '',
allowedValues: [],
allowedScopes: ['user'],
value: 'v1.0.0',
};
const selfHostedContext: Partial<IAppContext> = {
activeLicense: {
...(getAppContextMock('ADMIN').activeLicense as LicenseResModel),
platform: LicensePlatform.SELF_HOSTED,
},
};
function renderChangelog(
onClose: () => void = jest.fn(),
appContextOverrides: Partial<IAppContext> = {},
): void {
render(
<MockQueryClientProvider>
<ChangelogModal changelog={mockChangelog} onClose={onClose} />
</MockQueryClientProvider>,
<ChangelogModal changelog={mockChangelog} onClose={onClose} />,
undefined,
{
appContextOverrides: {
userPreferences: [seenChangelogVersion],
...appContextOverrides,
},
},
);
}
describe('ChangelogModal', () => {
it('renders modal with changelog data', () => {
it('renders the dialog with the changelog data', async () => {
renderChangelog();
expect(
screen.getByText('What’s New ⎯ Changelog : June 10, 2025'),
).toBeInTheDocument();
await expect(
screen.findByTestId('changelog-dialog-title'),
).resolves.toHaveTextContent('What’s New ⎯ Changelog : June 10, 2025');
expect(screen.getByText('Feature 1')).toBeInTheDocument();
expect(screen.getByText('Description for feature 1')).toBeInTheDocument();
expect(screen.getByText('Bug fix details')).toBeInTheDocument();
expect(screen.getByText('Maintenance details')).toBeInTheDocument();
});
it('calls onClose when Skip for now is clicked', () => {
it('calls onClose when the close button is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
renderChangelog(onClose);
fireEvent.click(screen.getByText('Skip for now'));
expect(onClose).toHaveBeenCalled();
await user.click(await screen.findByTestId('changelog-dialog-close'));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('opens migration docs when Update my workspace is clicked', () => {
window.open = jest.fn();
it('offers no upgrade actions to a cloud workspace', async () => {
renderChangelog();
fireEvent.click(screen.getByText('Update my workspace'));
expect(window.open).toHaveBeenCalledWith(
await screen.findByTestId('changelog-content');
expect(
screen.queryByTestId('changelog-dialog-footer'),
).not.toBeInTheDocument();
expect(screen.queryByTestId('changelog-skip-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('changelog-update-btn')).not.toBeInTheDocument();
});
it('calls onClose when Skip for now is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
renderChangelog(onClose, selfHostedContext);
await user.click(await screen.findByTestId('changelog-skip-btn'));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('opens migration docs when Update my workspace is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const open = jest.spyOn(window, 'open').mockImplementation(() => null);
renderChangelog(jest.fn(), selfHostedContext);
await user.click(await screen.findByTestId('changelog-update-btn'));
expect(open).toHaveBeenCalledWith(
'https://signoz.io/upgrade-path',
'_blank',
'noopener,noreferrer',
);
open.mockRestore();
});
it('scrolls for more when Scroll for more is clicked', () => {
renderChangelog();
const scrollBtn = screen.getByTestId('scroll-more-btn');
const contentDiv = screen.getByTestId('changelog-content');
if (contentDiv) {
contentDiv.scrollTo = jest.fn();
}
fireEvent.click(scrollBtn);
if (contentDiv) {
expect(contentDiv.scrollTo).toHaveBeenCalled();
}
describe('scroll for more', () => {
let scrollHeight: jest.SpyInstance;
let clientHeight: jest.SpyInstance;
beforeEach(() => {
scrollHeight = jest.spyOn(Element.prototype, 'scrollHeight', 'get');
clientHeight = jest.spyOn(Element.prototype, 'clientHeight', 'get');
});
afterEach(() => {
scrollHeight.mockRestore();
clientHeight.mockRestore();
});
it('is hidden while the content fits', async () => {
scrollHeight.mockReturnValue(400);
clientHeight.mockReturnValue(400);
renderChangelog();
await screen.findByTestId('changelog-content');
expect(screen.queryByTestId('scroll-more-btn')).not.toBeInTheDocument();
});
it('scrolls 600px further from the current position when clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
scrollHeight.mockReturnValue(2000);
clientHeight.mockReturnValue(400);
renderChangelog();
const content = await screen.findByTestId('changelog-dialog-body');
Object.defineProperty(content, 'scrollTop', {
value: 100,
configurable: true,
});
const scrollTo = jest.fn();
Object.defineProperty(content, 'scrollTo', { value: scrollTo });
await user.click(await screen.findByTestId('scroll-more-btn'));
expect(scrollTo).toHaveBeenCalledWith({
top: 700,
behavior: 'smooth',
});
});
it('hides once the content is scrolled to the bottom', async () => {
scrollHeight.mockReturnValue(1000);
clientHeight.mockReturnValue(400);
renderChangelog();
const content = await screen.findByTestId('changelog-dialog-body');
await screen.findByTestId('scroll-more-btn');
Object.defineProperty(content, 'scrollTop', {
value: 600,
configurable: true,
});
fireEvent.scroll(content);
await waitFor(() =>
expect(screen.queryByTestId('scroll-more-btn')).not.toBeInTheDocument(),
);
});
});
});

View File

@@ -34,7 +34,7 @@
&-line {
position: absolute;
left: 0;
left: 3px;
top: 6px;
bottom: -30px;
width: 1px;

View File

@@ -0,0 +1,52 @@
import { useCallback, useEffect, useState } from 'react';
const SCROLL_STEP_PX = 600;
const MIN_OVERFLOW_PX = 24;
const BOTTOM_TOLERANCE_PX = 8;
interface UseChangelogScrollReturn {
contentRef: (node: HTMLDivElement | null) => void;
hasScroll: boolean;
scrollForMore: () => void;
}
export function useChangelogScroll(): UseChangelogScrollReturn {
const [content, setContent] = useState<HTMLElement | null>(null);
const [hasScroll, setHasScroll] = useState(false);
const checkScroll = useCallback((): void => {
if (!content) {
return;
}
const { scrollHeight, clientHeight, scrollTop } = content;
const isAtBottom =
scrollHeight - clientHeight - scrollTop <= BOTTOM_TOLERANCE_PX;
setHasScroll(scrollHeight > clientHeight + MIN_OVERFLOW_PX && !isAtBottom);
}, [content]);
useEffect(() => {
if (!content) {
return undefined;
}
checkScroll();
content.addEventListener('scroll', checkScroll);
return (): void => {
content.removeEventListener('scroll', checkScroll);
};
}, [content, checkScroll]);
const scrollForMore = useCallback((): void => {
content?.scrollTo({
top: content.scrollTop + SCROLL_STEP_PX,
behavior: 'smooth',
});
}, [content]);
// The dialog body owns the scroll; a second scroller inside it shows two scrollbars.
const contentRef = useCallback((node: HTMLDivElement | null): void => {
setContent(node?.closest<HTMLElement>('[data-slot="dialog-body"]') ?? null);
}, []);
return { contentRef, hasScroll, scrollForMore };
}

View File

@@ -68,7 +68,7 @@ describe('CreateServiceAccountModal', () => {
});
it('submit button becomes disabled after clearing the name field', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
@@ -86,7 +86,7 @@ describe('CreateServiceAccountModal', () => {
});
it('successful submit shows toast.success and closes modal', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
@@ -112,7 +112,7 @@ describe('CreateServiceAccountModal', () => {
});
it('pressing Enter again while creating sends one request', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
let requests = 0;
server.use(
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) => {
@@ -146,7 +146,7 @@ describe('CreateServiceAccountModal', () => {
});
it('shows toast.error on API error and keeps modal open', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) =>
@@ -186,7 +186,7 @@ describe('CreateServiceAccountModal', () => {
});
it('Cancel button closes modal without submitting', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderModal();
const cancelBtn = await screen.findByTestId('create-sa-cancel-btn');
@@ -217,7 +217,7 @@ describe('CreateServiceAccountModal', () => {
});
it('keeps the footer usable when create permission is denied', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(setupAuthzDenyAll());
renderModal();
@@ -242,7 +242,7 @@ describe('CreateServiceAccountModal', () => {
});
it('shows "Name is required" after clearing the name field', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');

View File

@@ -1,5 +1,6 @@
import { useState } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { render } from '@testing-library/react';
import { fireEvent, screen, userEvent } from 'tests/test-utils';
import dayjs from 'dayjs';
import { mockAppLocation } from 'tests/router-mocks';
import * as timeUtils from 'utils/timeUtils';
@@ -157,7 +158,8 @@ describe('CustomTimePicker', () => {
expect(onValid).not.toHaveBeenCalled();
});
it('treats close after change like pressing Enter (blur + chevron)', () => {
it('treats close after change like pressing Enter (blur + chevron)', async () => {
const user = userEvent.setup();
const onValid = jest.fn();
const onError = jest.fn();
@@ -166,16 +168,13 @@ describe('CustomTimePicker', () => {
const input = screen.getByRole('textbox');
// Open and change value so "changed since open" is true
fireEvent.focus(input);
fireEvent.change(input, { target: { value: '5m' } });
fireEvent.blur(input);
await user.click(input);
await user.clear(input);
await user.type(input, '5m');
await user.tab();
// Click the chevron (which triggers handleClose)
const chevron = document.querySelector(
'.time-input-suffix-icon-badge',
) as HTMLElement;
fireEvent.click(chevron);
await user.click(screen.getByTestId('time-picker-close-chevron'));
// Should have applied the value (same as Enter)
expect(onValid).toHaveBeenCalledTimes(1);

View File

@@ -640,12 +640,14 @@ function CustomTimePicker({
size={14}
className="cursor-pointer time-input-suffix-icon-badge"
onClick={handleClose}
data-testid="time-picker-close-chevron"
/>
) : (
<ChevronDown
size={14}
className="cursor-pointer time-input-suffix-icon-badge"
onClick={handleOpen}
data-testid="time-picker-open-chevron"
/>
)}
</div>

View File

@@ -273,7 +273,7 @@ describe('EditMemberDrawer', () => {
it('enables Save after editing name and calls updateUser on confirm', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const mockMutateAsync = jest.fn().mockResolvedValue({});
(useUpdateUser as jest.Mock).mockReturnValue({
@@ -306,7 +306,7 @@ describe('EditMemberDrawer', () => {
it('does not close the drawer after a successful save', async () => {
const onClose = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer({ onClose });
@@ -331,7 +331,7 @@ describe('EditMemberDrawer', () => {
it('adding a new role creates a user role without removing existing ones', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const mockSet = jest.fn().mockResolvedValue({});
(useCreateUserRole as jest.Mock).mockReturnValue({
@@ -365,7 +365,7 @@ describe('EditMemberDrawer', () => {
it('deselecting a role deletes the user role by its assignment id', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer({ onComplete });
@@ -392,7 +392,7 @@ describe('EditMemberDrawer', () => {
it('shows delete confirm dialog and calls deleteUser for active members', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
@@ -553,7 +553,7 @@ describe('EditMemberDrawer', () => {
it('calls deleteUser after confirming revoke invite for invited members', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
@@ -583,7 +583,7 @@ describe('EditMemberDrawer', () => {
it('calls updateUser when saving name change for an invited member', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const mockMutateAsync = jest.fn().mockResolvedValue({});
(useGetUser as jest.Mock).mockReturnValue({
@@ -641,7 +641,7 @@ describe('EditMemberDrawer', () => {
});
it('shows SaveErrorItem when updateUser fails for name change', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
(useUpdateUser as jest.Mock).mockReturnValue({
mutateAsync: jest.fn().mockRejectedValue(new Error('server error')),
@@ -669,7 +669,7 @@ describe('EditMemberDrawer', () => {
});
it('shows API error message when deleteUser fails for active member', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
@@ -700,7 +700,7 @@ describe('EditMemberDrawer', () => {
});
it('shows API error message when deleteUser fails for invited member', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
@@ -740,7 +740,7 @@ describe('EditMemberDrawer', () => {
});
it('does not open delete confirm dialog when Delete is clicked while disabled (isSelf)', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer({ member: selfMember });
await user.click(screen.getByRole('button', { name: /delete member/i }));
@@ -811,7 +811,7 @@ describe('EditMemberDrawer', () => {
isLoading: false,
});
server.use(setupAuthzDeny(buildUserUpdatePermission(selfMember.id)));
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer({ member: selfMember });
const input = await screen.findByDisplayValue('Alice Smith');
@@ -875,7 +875,7 @@ describe('EditMemberDrawer', () => {
});
it('does not open delete confirm dialog when Delete is clicked while disabled (root)', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer();
await user.click(screen.getByRole('button', { name: /delete member/i }));
@@ -886,7 +886,7 @@ describe('EditMemberDrawer', () => {
});
it('does not call createResetPasswordToken when Reset Link is clicked while disabled (root)', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer();
await user.click(
@@ -903,7 +903,7 @@ describe('EditMemberDrawer', () => {
});
it('calls POST and opens the reset link dialog with the generated link and expiry', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer();
@@ -925,7 +925,7 @@ describe('EditMemberDrawer', () => {
});
it('copies the link to clipboard and shows "Copied!" on the button', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const mockToast = jest.mocked(toast);
renderDrawer();

View File

@@ -53,7 +53,7 @@ describe('ErrorModal Component', () => {
// Click the close button
const closeButton = screen.getByTestId('close-button');
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
await user.click(closeButton);
// Check if onClose was called
@@ -145,7 +145,7 @@ it('should open the modal when the trigger component is clicked', async () => {
// Click the trigger component
const triggerButton = screen.getByText('Open Error Modal');
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
await user.click(triggerButton);
// Check if the modal is displayed
@@ -165,12 +165,13 @@ it('should close the modal when the onCancel event is triggered', async () => {
// Click the trigger component
const triggerButton = screen.getByText('error');
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
await user.click(triggerButton);
await waitFor(() => {
expect(screen.getByText('An error occurred')).toBeInTheDocument();
});
const modal = screen.getByRole('dialog');
// Trigger the onCancel event
await user.click(screen.getByTestId('close-button'));
@@ -180,8 +181,6 @@ it('should close the modal when the onCancel event is triggered', async () => {
await waitFor(() => {
// check if the modal is not visible
const modal = document.getElementsByClassName('ant-modal');
const style = window.getComputedStyle(modal[0]);
expect(style.display).toBe('none');
expect(modal).toHaveStyle({ display: 'none' });
});
});

View File

@@ -1,6 +1,6 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
import { act, render, renderHook } from '@testing-library/react';
import { act, render, renderHook } from 'tests/test-utils';
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
import { useGlobalTimeStore } from 'store/globalTime/globalTimeStore';
@@ -42,13 +42,13 @@ describe('GlobalTimeStoreAdapter', () => {
globalTime: createGlobalTimeState(),
});
const { container } = render(
const { asFragment } = render(
<Provider store={store}>
<GlobalTimeStoreAdapter />
</Provider>,
);
expect(container.firstChild).toBeNull();
expect(asFragment().hasChildNodes()).toBe(false);
});
it('should sync relative time from Redux to Zustand store', () => {

View File

@@ -2,8 +2,14 @@ import { Typography } from '@signozhq/ui/typography';
function AnnouncementsModal(): JSX.Element {
return (
<div className="announcements-modal-container">
<div className="announcements-modal-container-header">
<div
className="announcements-modal-container"
data-testid="announcements-modal"
>
<div
className="announcements-modal-container-header"
data-testid="announcements-modal-header"
>
<Typography
variant="paragraph"
size="base"

View File

@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react';
import { render, screen, within } from 'tests/test-utils';
import AnnouncementsModal from '../AnnouncementsModal';
@@ -12,15 +12,14 @@ describe('AnnouncementsModal', () => {
it('should have proper structure and classes', () => {
render(<AnnouncementsModal />);
const container = screen
.getByText('Announcements')
.closest('.announcements-modal-container');
expect(container).toBeInTheDocument();
const container = screen.getByTestId('announcements-modal');
expect(container).toHaveClass('announcements-modal-container');
const headerContainer = screen
.getByText('Announcements')
.closest('.announcements-modal-container-header');
expect(headerContainer).toBeInTheDocument();
const headerContainer = within(container).getByTestId(
'announcements-modal-header',
);
expect(headerContainer).toHaveClass('announcements-modal-container-header');
expect(headerContainer).toHaveTextContent('Announcements');
});
it('should render without any errors', () => {

View File

@@ -64,7 +64,10 @@ function InviteMembers({
const hasSuccesses = successResults.length > 0;
return (
<div className={cx(styles.inviteMembers, className)}>
<div
className={cx(styles.inviteMembers, className)}
data-testid="invite-members"
>
<div className={styles.table}>
{showHeader && (
<div className={styles.header}>

View File

@@ -66,9 +66,9 @@ describe('InviteMembers - Rendering', () => {
});
it('applies custom className', () => {
const { container } = render(<InviteMembers className="custom-class" />);
render(<InviteMembers className="custom-class" />);
expect(container.querySelector('.custom-class')).toBeInTheDocument();
expect(screen.getByTestId('invite-members')).toHaveClass('custom-class');
});
it('renders footer via renderFooter prop', () => {

View File

@@ -15,7 +15,7 @@ describe('InviteMembers - Row Management', () => {
});
it('adds a row when "Add another" is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(<InviteMembers initialRowCount={2} />);
@@ -27,7 +27,7 @@ describe('InviteMembers - Row Management', () => {
});
it('removes a row when trash button is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(<InviteMembers initialRowCount={3} />);
@@ -40,7 +40,7 @@ describe('InviteMembers - Row Management', () => {
});
it('respects minRows constraint when removing rows', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(<InviteMembers initialRowCount={2} minRows={2} />);
@@ -62,7 +62,7 @@ describe('InviteMembers - Row Management', () => {
});
it('cannot remove rows below minRows=1 default', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(<InviteMembers initialRowCount={2} />);
@@ -76,7 +76,7 @@ describe('InviteMembers - Row Management', () => {
});
it('preserves data in other rows when removing one', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(<InviteMembers initialRowCount={3} />);

View File

@@ -22,7 +22,7 @@ describe('InviteMembers - Validation', () => {
describe('email validation', () => {
it('shows email validation error when email is invalid and role is selected', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -46,7 +46,7 @@ describe('InviteMembers - Validation', () => {
});
it('shows inline error for invalid email field', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -70,7 +70,7 @@ describe('InviteMembers - Validation', () => {
});
it('clears validation error when email is corrected', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -104,7 +104,7 @@ describe('InviteMembers - Validation', () => {
describe('role validation', () => {
it('shows role validation error when role is missing', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -127,7 +127,7 @@ describe('InviteMembers - Validation', () => {
});
it('clears role validation error when role is selected', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -159,7 +159,7 @@ describe('InviteMembers - Validation', () => {
describe('combined validation', () => {
it('shows combined error when both email and role are invalid', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -186,7 +186,7 @@ describe('InviteMembers - Validation', () => {
describe('touched rows', () => {
it('only validates touched rows (rows with email or role)', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers

View File

@@ -14,14 +14,14 @@ export type CreatedByProps =
creatorOptions: CreatorOption[];
createdBy: string[];
onCreatedByChange: (emails: string[]) => void;
// Clear all Created-by selections and run immediately.
onClearCreatedBy: () => void;
// Run a Created-by change made with the dropdown closed.
onCreatedByCommit: (emails: string[]) => void;
}
| {
creatorOptions?: undefined;
createdBy?: undefined;
onCreatedByChange?: undefined;
onClearCreatedBy?: undefined;
onCreatedByCommit?: undefined;
};
type Props = CreatedByProps & {
@@ -61,8 +61,8 @@ function FilterChips(props: Props): JSX.Element {
placeholder="Created by"
testId={`${testIdPrefix}-filter-created-by`}
disabled={disabled}
onClear={props.onClearCreatedBy}
onChange={props.onCreatedByChange}
onCommit={props.onCreatedByCommit}
onDropdownVisibleChange={runOnClose}
/>
)}

View File

@@ -81,7 +81,7 @@ function FilterZone({
applyDraft,
handleCreatedByChange,
handleUpdatedChange,
handleClearCreatedBy,
handleCreatedByCommit,
handleClear,
} = useFilterZoneDraft({
query,
@@ -96,7 +96,7 @@ function FilterZone({
creatorOptions,
createdBy: reflected.createdBy,
onCreatedByChange: handleCreatedByChange,
onClearCreatedBy: handleClearCreatedBy,
onCreatedByCommit: handleCreatedByCommit,
}
: {};

View File

@@ -1,3 +1,4 @@
import { useCallback, useState } from 'react';
import { ConfigProvider, Select } from 'antd';
import { Checkbox } from '@signozhq/ui/checkbox';
import cx from 'classnames';
@@ -20,7 +21,9 @@ interface Props {
placeholder: string;
testId: string;
onChange: (values: string[]) => void;
onClear?: () => void;
// A change made with the dropdown closed (a tag's ×, the clear icon) has no
// close to run on, so it is committed here instead of staged via onChange.
onCommit: (values: string[]) => void;
onDropdownVisibleChange?: (open: boolean) => void;
disabled?: boolean;
}
@@ -31,10 +34,31 @@ function MultiSelectFilter({
placeholder,
testId,
onChange,
onClear,
onCommit,
onDropdownVisibleChange,
disabled = false,
}: Props): JSX.Element {
const [isOpen, setIsOpen] = useState(false);
const handleChange = useCallback(
(next: string[]): void => {
if (!isOpen) {
onCommit(next);
return;
}
onChange(next);
},
[isOpen, onChange, onCommit],
);
const handleDropdownVisibleChange = useCallback(
(nextOpen: boolean): void => {
setIsOpen(nextOpen);
onDropdownVisibleChange?.(nextOpen);
},
[onDropdownVisibleChange],
);
return (
<ConfigProvider theme={CHECKBOX_SELECT_THEME}>
<Select
@@ -51,7 +75,6 @@ function MultiSelectFilter({
menuItemSelectedIcon={null}
data-testid={testId}
disabled={disabled}
onClear={onClear}
optionRender={(option): JSX.Element => (
<div
className={styles.checkOption}
@@ -66,8 +89,8 @@ function MultiSelectFilter({
<span className={styles.checkOptionLabel}>{option.label}</span>
</div>
)}
onChange={(next): void => onChange(next as string[])}
onDropdownVisibleChange={onDropdownVisibleChange}
onChange={(next): void => handleChange(next as string[])}
onDropdownVisibleChange={handleDropdownVisibleChange}
/>
</ConfigProvider>
);

View File

@@ -1,4 +1,5 @@
import { render, screen } from 'tests/test-utils';
import userEvent from '@testing-library/user-event';
import { render, screen, within } from 'tests/test-utils';
import type { DslGrammar } from '../../dsl/types';
import FilterZone from '../FilterZone';
@@ -47,4 +48,33 @@ describe('FilterZone', () => {
).not.toBeInTheDocument();
expect(screen.getByTestId('things-filter-updated')).toBeInTheDocument();
});
it('runs the query when a creator is removed with the dropdown closed', async () => {
const user = userEvent.setup();
const onQueryChange = jest.fn();
render(
<FilterZone
query="created_by = 'ada@example.com'"
grammar={grammar}
testIdPrefix="things"
creatorOptions={[{ email: 'ada@example.com', label: 'Ada' }]}
source={source}
onQueryChange={onQueryChange}
/>,
);
// antd renders the tag's × aria-hidden.
await user.click(
within(screen.getByTitle('Ada')).getByRole('img', {
name: 'close',
hidden: true,
}),
);
expect(
within(screen.getByTestId('things-filter-created-by')).getByRole('combobox'),
).toHaveAttribute('aria-expanded', 'false');
expect(onQueryChange).toHaveBeenCalledWith('');
});
});

View File

@@ -106,12 +106,20 @@ describe('useFilterZoneDraft', () => {
"created_by = 'a@x.io' AND name = 'x'",
);
act(() => result.current.handleClearCreatedBy());
act(() => result.current.handleCreatedByCommit([]));
expect(result.current.draft).toBe("name = 'x'");
expect(onQueryChange).toHaveBeenCalledWith("name = 'x'");
});
it('runs the remaining creators when one is removed', () => {
const { result, onQueryChange } = setup("created_by IN ['a@x.io', 'b@x.io']");
act(() => result.current.handleCreatedByCommit(['b@x.io']));
expect(onQueryChange).toHaveBeenCalledWith("created_by = 'b@x.io'");
});
it('empties the draft and runs the empty query on clear', () => {
const { result, onQueryChange, onCleared, onClearAll } = setup();

View File

@@ -31,7 +31,7 @@ interface FilterZoneDraft {
applyDraft: (next: string) => void;
handleCreatedByChange: (emails: string[]) => void;
handleUpdatedChange: (window: UpdatedWindow) => void;
handleClearCreatedBy: () => void;
handleCreatedByCommit: (emails: string[]) => void;
handleClear: () => void;
}
@@ -97,10 +97,14 @@ export function useFilterZoneDraft({
[draft, applyDraft, onFilterApplied],
);
// Clear-all on the Created-by select removes its clause and runs immediately.
const handleClearCreatedBy = useCallback((): void => {
applyDraft(spliceClause(draft, 'created_by', null));
}, [draft, applyDraft]);
// Runs a Created-by change made with its dropdown closed.
const handleCreatedByCommit = useCallback(
(emails: string[]): void => {
onFilterApplied?.('createdBy', { valueCount: emails.length });
applyDraft(spliceClause(draft, 'created_by', createdByClause(emails)));
},
[draft, applyDraft, onFilterApplied],
);
// Clear resets the draft and runs immediately (empty query).
const handleClear = useCallback((): void => {
@@ -122,7 +126,7 @@ export function useFilterZoneDraft({
applyDraft,
handleCreatedByChange,
handleUpdatedChange,
handleClearCreatedBy,
handleCreatedByCommit,
handleClear,
};
}

View File

@@ -34,7 +34,7 @@ describe('InvalidQueryState', () => {
});
it('runs the callback, then opens support', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const onContactSupport = jest.fn();
render(
<InvalidQueryState

View File

@@ -1,5 +1,5 @@
import type { ComponentProps } from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import { render, screen, userEvent, within } from 'tests/test-utils';
import type { DslGrammar } from '../../dsl/types';
import SearchBar from '../SearchBar';
@@ -40,9 +40,7 @@ function renderSearchBar(props: { dirty: boolean; disabled?: boolean }): {
}
function searchContent(): HTMLElement {
return screen
.getByTestId('list-search')
.querySelector('.cm-content') as HTMLElement;
return within(screen.getByTestId('list-search')).getByRole('textbox');
}
describe('SearchBar — run on blur', () => {

View File

@@ -24,6 +24,7 @@ interface Props {
confirmLabel: string;
/** Name the input holds each time the dialog opens. */
initialName?: string;
placeholder: string;
testIdPrefix: string;
}
@@ -35,6 +36,7 @@ function ViewNameDialog({
description,
confirmLabel,
initialName = '',
placeholder,
testIdPrefix,
}: Props): JSX.Element {
const [name, setName] = useState(initialName);
@@ -116,7 +118,7 @@ function ViewNameDialog({
id={inputId}
value={name}
maxLength={VIEW_NAME_MAX_LENGTH}
placeholder="e.g. Prod alerts"
placeholder={placeholder}
autoComplete="off"
testId={`${testIdPrefix}-name`}
onChange={(e: ChangeEvent<HTMLInputElement>): void =>

View File

@@ -39,6 +39,7 @@ interface Props {
saveTestIdPrefix?: string;
renameTestIdPrefix?: string;
customSectionLabel?: string;
viewNamePlaceholder?: string;
deleteDescription?: string;
/** Wraps the rail body, e.g. in an authz guard. */
guard?: (content: ReactElement) => ReactElement;
@@ -67,6 +68,7 @@ function ViewsRail({
saveTestIdPrefix = 'save-view',
renameTestIdPrefix = 'rename-view',
customSectionLabel = 'My views',
viewNamePlaceholder = 'e.g. Production',
deleteDescription = 'This removes the saved view.',
guard,
onViewSaved,
@@ -287,6 +289,7 @@ function ViewsRail({
title="Save as view"
description="Save the current filters as a view you can return to."
confirmLabel="Save view"
placeholder={viewNamePlaceholder}
testIdPrefix={saveTestIdPrefix}
/>
<ViewNameDialog
@@ -297,6 +300,7 @@ function ViewsRail({
description="The view keeps its filters under the new name."
confirmLabel="Rename"
initialName={renameTarget?.label}
placeholder={viewNamePlaceholder}
testIdPrefix={renameTestIdPrefix}
/>
{contextHolder}

View File

@@ -52,7 +52,7 @@ describe('ViewsRail', () => {
});
it('selects a view by id', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const props = renderRail();
await user.click(screen.getByTestId(`${PREFIX}-view-view-2`));
@@ -61,7 +61,7 @@ describe('ViewsRail', () => {
});
it('filters views by name and says when none match', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderRail();
const search = screen.getByTestId(`${PREFIX}-view-search-field`);
@@ -109,7 +109,7 @@ describe('ViewsRail', () => {
});
it('offers save, save as and reset for a modified custom view', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const onViewSaved = jest.fn();
const props = renderRail({
activeViewId: 'view-1',
@@ -138,7 +138,7 @@ describe('ViewsRail', () => {
});
it('saves the current filters as a named view from the dialog', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const onViewSaved = jest.fn();
const props = renderRail({ onViewSaved });
@@ -163,8 +163,24 @@ describe('ViewsRail', () => {
);
});
it('shows the list placeholder in the save and rename dialogs', async () => {
const user = userEvent.setup();
renderRail({ viewNamePlaceholder: 'e.g. Prod things' });
await user.click(screen.getByTestId(`${PREFIX}-view-save-trigger`));
await expect(
screen.findByTestId('save-view-name-field'),
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
await user.click(screen.getByTestId('save-view-cancel'));
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));
await expect(
screen.findByTestId('rename-view-name-field'),
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
});
it('opens the save dialog empty again after a cancel', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const props = renderRail({ isModified: true });
await user.click(screen.getByTestId(`${PREFIX}-view-save-as-new`));
@@ -183,7 +199,7 @@ describe('ViewsRail', () => {
});
it('renames a custom view from a dialog filled with its name', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const onViewRenamed = jest.fn();
const props = renderRail({ onViewRenamed });
@@ -206,7 +222,7 @@ describe('ViewsRail', () => {
});
it('refills the rename dialog with the name of the view it opens for', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const props = renderRail();
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));

View File

@@ -104,7 +104,7 @@ describe('LogDetail drawer — header', () => {
});
it('copies the log link from the ⋯ menu', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer();
@@ -115,7 +115,7 @@ describe('LogDetail drawer — header', () => {
});
it('copies the log from the ⋯ menu', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer();
@@ -128,7 +128,7 @@ describe('LogDetail drawer — header', () => {
});
it('keeps the drawer open when a ⋯ menu item is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const onClose = jest.fn();
renderDrawer({ onClose });
@@ -152,7 +152,7 @@ describe('LogDetail drawer — header', () => {
});
it('calls handleOpenInExplorer when "Open in Explorer" is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const handleOpenInExplorer = jest.fn();
renderDrawer({ handleOpenInExplorer });
@@ -163,7 +163,7 @@ describe('LogDetail drawer — header', () => {
});
it('closes from the close button and from Escape', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const onClose = jest.fn();
renderDrawer({ onClose });
@@ -176,7 +176,7 @@ describe('LogDetail drawer — header', () => {
});
it('closes on a mousedown outside the drawer and not on one inside it', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const onClose = jest.fn();
renderDrawer({ onClose });
@@ -196,7 +196,7 @@ describe('LogDetail drawer — header', () => {
});
it('keeps the drawer open on a mousedown in a data-log-detail-ignore region', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const onClose = jest.fn();
render(
@@ -258,7 +258,7 @@ describe('LogDetail drawer — header', () => {
});
it('navigates to the next / previous log with the Down / Up arrow keys', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const logs = [makeLog('log-0'), makeLog('log-1'), makeLog('log-2')];
const onNavigateLog = jest.fn();
const onScrollToLog = jest.fn();
@@ -276,7 +276,7 @@ describe('LogDetail drawer — header', () => {
});
it('does not navigate past the first log on ArrowUp', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const logs = [makeLog('log-0'), makeLog('log-1')];
const onNavigateLog = jest.fn();
@@ -287,7 +287,7 @@ describe('LogDetail drawer — header', () => {
});
it('navigates via the header up / down buttons and disables them at boundaries', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const logs = [makeLog('log-0'), makeLog('log-1')];
const onNavigateLog = jest.fn();

View File

@@ -1,46 +1,39 @@
import { render } from '@testing-library/react';
import { render, screen, within } from 'tests/test-utils';
import { FontSize } from 'container/OptionsMenu/types';
import LogStateIndicator from './LogStateIndicator';
describe('LogStateIndicator', () => {
it('renders correctly with default props', () => {
const { container } = render(
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
render(<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />);
const indicator = screen.getByTestId('log-state-indicator');
expect(indicator).toHaveClass('log-state-indicator');
expect(indicator).not.toHaveClass('isActive');
expect(within(indicator).getByTestId('log-state-indicator-line')).toHaveClass(
'severity-info-0',
);
const indicator = container.firstChild as HTMLElement;
expect(indicator.classList.contains('log-state-indicator')).toBe(true);
expect(indicator.classList.contains('isActive')).toBe(false);
expect(container.querySelector('.line')).toBeTruthy();
expect(
container.querySelector('.line')?.classList.contains('severity-info-0'),
).toBe(true);
});
it('renders correctly with different types', () => {
const { container: containerInfo } = render(
const { rerender } = render(
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
);
expect(
containerInfo.querySelector('.line')?.classList.contains('severity-info-0'),
).toBe(true);
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
'severity-info-0',
);
const { container: containerWarning } = render(
rerender(
<LogStateIndicator severityText="WARNING" fontSize={FontSize.MEDIUM} />,
);
expect(
containerWarning
.querySelector('.line')
?.classList.contains('severity-warn-0'),
).toBe(true);
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
'severity-warn-0',
);
const { container: containerError } = render(
rerender(
<LogStateIndicator severityText="ERROR" fontSize={FontSize.MEDIUM} />,
);
expect(
containerError
.querySelector('.line')
?.classList.contains('severity-error-0'),
).toBe(true);
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
'severity-error-0',
);
});
});

View File

@@ -138,8 +138,11 @@ function LogStateIndicator({
const severityClass = getSeverityClass(severityText, severityNumber);
return (
<div className="log-state-indicator">
<div className={cx('line', fontSize, severityClass)} />
<div className="log-state-indicator" data-testid="log-state-indicator">
<div
className={cx('line', fontSize, severityClass)}
data-testid="log-state-indicator-line"
/>
</div>
);
}

View File

@@ -128,7 +128,9 @@ function OptionsMenu({
>
<span className="menu-row">
{size}
{fontSizeValue === size && <Check size={14} />}
{fontSizeValue === size && (
<Check size={14} data-testid="font-size-option-check" />
)}
</span>
</Button>
))}
@@ -156,7 +158,7 @@ function OptionsMenu({
</Button>
</div>
<div className="horizontal-line" />
<div className="menu-container">
<div className="menu-container" data-testid="format-options-menu">
<div className="title">FORMAT</div>
<div className="menu-items">
@@ -170,7 +172,9 @@ function OptionsMenu({
<div className={cx('item-label')}>
{item.label}
{selectedItem === item.key && <Check size={12} />}
{selectedItem === item.key && (
<Check size={12} data-testid="format-check-icon" />
)}
</div>
</div>
))}

View File

@@ -5,6 +5,7 @@ import {
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import LogsFormatOptionsMenu from '../LogsFormatOptionsMenu';
@@ -34,13 +35,14 @@ describe('LogsFormatOptionsMenu (unit)', () => {
mockUpdateFormatting.mockClear();
});
function setup(): {
async function setup(): Promise<{
user: ReturnType<typeof userEvent.setup>;
getByTestId: ReturnType<typeof render>['getByTestId'];
findItemByLabel: (label: string) => Element | undefined;
formatOnChange: jest.Mock<any, any>;
maxLinesOnChange: jest.Mock<any, any>;
fontSizeOnChange: jest.Mock<any, any>;
} {
}> {
const user = userEvent.setup();
const items = [
{ key: 'raw', label: 'Raw', data: { title: 'max lines per row' } },
{ key: 'list', label: 'Default' },
@@ -76,16 +78,11 @@ describe('LogsFormatOptionsMenu (unit)', () => {
// Open the popover menu by default for each test
const formatButton = getByTestId('periscope-btn-format-options');
fireEvent.click(formatButton);
const getMenuItems = (): Element[] =>
Array.from(document.querySelectorAll('.menu-items .item'));
const findItemByLabel = (label: string): Element | undefined =>
getMenuItems().find((el) => (el.textContent || '').includes(label));
await user.click(formatButton);
return {
user,
getByTestId,
findItemByLabel,
formatOnChange,
maxLinesOnChange,
fontSizeOnChange,
@@ -94,31 +91,36 @@ describe('LogsFormatOptionsMenu (unit)', () => {
// Covers: opens menu, changes format selection, updates max-lines, changes font size
it('opens and toggles format selection', async () => {
const { findItemByLabel, formatOnChange } = setup();
const { user, formatOnChange } = await setup();
// Assert initial selection
const columnItem = findItemByLabel('Column') as Element;
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
expect(columnItem.querySelector('svg')).toBeInTheDocument();
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
expect(
within(screen.getByTestId('format-option-table')).getByTestId(
'format-check-icon',
),
).toBeInTheDocument();
// Change selection to 'Raw'
const rawItem = findItemByLabel('Raw') as Element;
fireEvent.click(rawItem as HTMLElement);
await user.click(screen.getByTestId('format-option-raw'));
await waitFor(() => {
const rawEl = findItemByLabel('Raw') as Element;
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
expect(rawEl.querySelector('svg')).toBeInTheDocument();
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
expect(
within(screen.getByTestId('format-option-raw')).getByTestId(
'format-check-icon',
),
).toBeInTheDocument();
});
expect(formatOnChange).toHaveBeenCalledWith('raw');
});
it('increments max-lines and calls onChange', async () => {
const { maxLinesOnChange, getByTestId } = setup();
const { user, maxLinesOnChange, getByTestId } = await setup();
// Increment max lines
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
const initial = Number(input.value);
fireEvent.click(screen.getByRole('button', { name: 'More lines per row' }));
await user.click(screen.getByRole('button', { name: 'More lines per row' }));
await waitFor(() => {
expect(Number(input.value)).toBe(initial + 1);
@@ -129,9 +131,8 @@ describe('LogsFormatOptionsMenu (unit)', () => {
});
it('clamps a typed max-lines value to 10', async () => {
const { maxLinesOnChange, getByTestId } = setup();
const { user, maxLinesOnChange, getByTestId } = await setup();
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
const user = userEvent.setup();
await user.clear(input);
await user.type(input, '15');
@@ -142,10 +143,9 @@ describe('LogsFormatOptionsMenu (unit)', () => {
});
it('stops max-lines at 10', async () => {
const { getByTestId } = setup();
const { user, getByTestId } = await setup();
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
const increment = screen.getByRole('button', { name: 'More lines per row' });
const user = userEvent.setup();
for (let i = 0; i < 12; i++) {
await user.click(increment);
@@ -155,19 +155,23 @@ describe('LogsFormatOptionsMenu (unit)', () => {
});
it('changes font size to MEDIUM and calls onChange', async () => {
const { fontSizeOnChange, getByTestId } = setup();
const { user, fontSizeOnChange, getByTestId } = await setup();
// Open font dropdown
fireEvent.click(getByTestId('font-size-select'));
await user.click(getByTestId('font-size-select'));
// Choose MEDIUM
fireEvent.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
await user.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
await waitFor(() => {
expect(
getByTestId(`font-size-option-${FontSize.MEDIUM}`).querySelector('svg'),
within(getByTestId(`font-size-option-${FontSize.MEDIUM}`)).getByTestId(
'font-size-option-check',
),
).toBeInTheDocument();
expect(
getByTestId(`font-size-option-${FontSize.SMALL}`).querySelector('svg'),
within(getByTestId(`font-size-option-${FontSize.SMALL}`)).queryByTestId(
'font-size-option-check',
),
).not.toBeInTheDocument();
});
await waitFor(() => {
@@ -212,16 +216,16 @@ describe('LogsFormatOptionsMenu (unit)', () => {
renderWithOnOpen(undefined, 'table');
expect(
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
).toBeNull();
screen.queryByTestId('periscope-btn-edit-columns'),
).not.toBeInTheDocument();
});
it('does not render "Edit columns" row when format is not table', () => {
renderWithOnOpen(jest.fn(), 'raw');
expect(
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
).toBeNull();
screen.queryByTestId('periscope-btn-edit-columns'),
).not.toBeInTheDocument();
});
it('fires onOpenColumns and closes the popover when "Edit columns" is clicked', async () => {
@@ -233,7 +237,7 @@ describe('LogsFormatOptionsMenu (unit)', () => {
expect(onOpenColumns).toHaveBeenCalledTimes(1);
await waitFor(() => {
// Popover content unmounts on close.
expect(document.querySelector('.menu-container')).toBeNull();
expect(screen.queryByTestId('format-option-table')).not.toBeInTheDocument();
});
});
});

View File

@@ -74,8 +74,7 @@ function Harness({
}
const getView = (): EditorView => {
const dom = document.querySelector('.cm-editor');
const view = dom ? EditorView.findFromDOM(dom as HTMLElement) : null;
const view = EditorView.findFromDOM(screen.getByTestId('markdown-editor'));
if (!view) {
throw new Error('editor view not mounted');
}
@@ -151,11 +150,9 @@ describe('MarkdownEditor', () => {
render(<Harness initialValue={'## Runbook\nowner {{team}}'} />);
await waitFor(() => {
expect(document.querySelector('.cm-md-heading')).toBeInTheDocument();
expect(screen.getByText('## Runbook')).toHaveClass('cm-md-heading');
});
expect(document.querySelector('.cm-md-variable')).toHaveTextContent(
'{{team}}',
);
expect(screen.getByText('{{team}}')).toHaveClass('cm-md-variable');
});
describe('uncontrolled document', () => {

View File

@@ -189,7 +189,13 @@ function MembersTable({
<span className="members-pagination-range">
{range[0]} &#8212; {range[1]}
</span>
<span className="members-pagination-total"> of {_total}</span>
<span
className="members-pagination-total"
data-testid="members-pagination-total"
>
{' '}
of {_total}
</span>
</>
);

View File

@@ -68,7 +68,7 @@ describe('MembersTable', () => {
const onRowClick = jest.fn() as jest.MockedFunction<
(member: MemberRow) => void
>;
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<MembersTable
@@ -88,7 +88,7 @@ describe('MembersTable', () => {
it('renders DELETED badge and calls onRowClick when a deleted member row is clicked', async () => {
const onRowClick = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const deletedMember: MemberRow = {
id: 'user-del',
name: 'Dave Deleted',
@@ -129,7 +129,7 @@ describe('MembersTable', () => {
});
it('hides pagination when total does not exceed pageSize', () => {
const { container } = render(
render(
<MembersTable
{...defaultProps}
data={mockActiveMembers}
@@ -139,12 +139,12 @@ describe('MembersTable', () => {
);
expect(
container.querySelector('.members-table-pagination'),
screen.queryByTestId('members-pagination-total'),
).not.toBeInTheDocument();
});
it('shows pagination when total exceeds pageSize', () => {
const { container } = render(
render(
<MembersTable
{...defaultProps}
data={mockActiveMembers}
@@ -153,11 +153,8 @@ describe('MembersTable', () => {
/>,
);
expect(
container.querySelector('.members-table-pagination'),
).toBeInTheDocument();
expect(
container.querySelector('.members-pagination-total'),
).toBeInTheDocument();
expect(screen.getByTestId('members-pagination-total')).toHaveTextContent(
'of 25',
);
});
});

View File

@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react';
import { render, screen } from 'tests/test-utils';
import MessageTip from './index';
@@ -35,13 +35,13 @@ describe('MessageTip', () => {
// taken from antd docs
// https://github.com/ant-design/ant-design/blob/master/components/alert/__tests__/index.test.tsx
it('custom action', () => {
const { container } = render(
const { asFragment } = render(
<MessageTip
show
message="Success Tips"
action={<button type="button">Close</button>}
/>,
);
expect(container.firstChild).toMatchSnapshot();
expect(asFragment()).toMatchSnapshot();
});
});

View File

@@ -1,7 +1,8 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`MessageTip custom action 1`] = `
.c0 {
<DocumentFragment>
.c0 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
@@ -9,46 +10,47 @@ exports[`MessageTip custom action 1`] = `
}
<div
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
data-show="true"
role="alert"
>
<span
aria-label="info-circle"
class="anticon anticon-info-circle ant-alert-icon"
role="img"
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
data-show="true"
role="alert"
>
<svg
aria-hidden="true"
data-icon="info-circle"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
<span
aria-label="info-circle"
class="anticon anticon-info-circle ant-alert-icon"
role="img"
>
<path
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
/>
</svg>
</span>
<div
class="ant-alert-content"
>
<svg
aria-hidden="true"
data-icon="info-circle"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
/>
</svg>
</span>
<div
class="ant-alert-description"
class="ant-alert-content"
>
Success Tips
<div
class="ant-alert-description"
>
Success Tips
</div>
</div>
<div
class="ant-alert-action"
>
<button
type="button"
>
Close
</button>
</div>
</div>
<div
class="ant-alert-action"
>
<button
type="button"
>
Close
</button>
</div>
</div>
</DocumentFragment>
`;

View File

@@ -632,7 +632,11 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
const uniqueKey = `${text.substring(0, 3)}-${part.substring(0, 3)}-${i}`;
return part.toLowerCase() === searchQuery.toLowerCase() ? (
<span key={uniqueKey} className="highlight-text">
<span
key={uniqueKey}
className="highlight-text"
data-testid="highlight-text"
>
{part}
</span>
) : (
@@ -746,6 +750,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
selected: isSelected,
active: isActive,
})}
data-testid={`option-item-${option.value}`}
onKeyDown={(e): void => {
if ((e.key === 'Enter' || e.key === SPACEKEY) && isActive) {
e.stopPropagation();
@@ -777,7 +782,9 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
{highlightMatchedText(String(option.label || ''), searchText)}
</span>
{(option.type === 'custom' || option.type === 'regex') && (
<div className="option-badge">{capitalize(option.type)}</div>
<div className="option-badge" data-testid="option-badge">
{capitalize(option.type)}
</div>
)}
{option.value && ensureValidOption(option.value) && (
<Button
@@ -1562,6 +1569,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
<div
ref={dropdownRef}
className="custom-multiselect-dropdown"
data-testid="custom-multiselect-dropdown"
onMouseDown={handleDropdownMouseDown}
onClick={handleDropdownClick}
onKeyDown={handleKeyDown}
@@ -1583,6 +1591,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
active: activeIndex === 0,
})}
key={`all-option-${allOptionsSelected}`}
data-testid="all-option"
id="option-0"
onMouseEnter={(): void => {
setActiveIndex(0);
@@ -1641,7 +1650,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
</div>
</div>
</div>
<div className="divider" />
<div className="divider" data-testid="all-option-divider" />
</>
)}
@@ -1711,7 +1720,11 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
)}
{/* Navigation help footer */}
<div className="navigation-footer" role="note">
<div
className="navigation-footer"
role="note"
data-testid="navigation-footer"
>
{!loading &&
!errorMessage &&
!noDataMessage &&
@@ -1726,7 +1739,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
</section>
)}
{loading && (
<div className="navigation-loading">
<div className="navigation-loading" data-testid="navigation-loading">
<div className="navigation-icons">
<Loader size="md" className="animate-spin" />
</div>
@@ -1734,7 +1747,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
</div>
)}
{!loading && waitingMessage && (
<div className="navigation-loading">
<div className="navigation-loading" data-testid="navigation-loading">
<div className="navigation-icons">
<Loader size="md" className="animate-spin" />
</div>
@@ -1744,7 +1757,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
</div>
)}
{errorMessage && !loading && !waitingMessage && (
<div className="navigation-error">
<div className="navigation-error" data-testid="navigation-error">
<div className="navigation-text">
{errorMessage || SOMETHING_WENT_WRONG}
</div>
@@ -1959,6 +1972,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
'ant-select-selection-item-active': isActive,
'ant-select-selection-item-selected': isSelected,
})}
data-testid={`selected-tag-${value}`}
style={
isActive || isSelected
? {

View File

@@ -170,7 +170,11 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
const uniqueKey = `${text.substring(0, 3)}-${part.substring(0, 3)}-${i}`;
return part.toLowerCase() === searchQuery.toLowerCase() ? (
<span key={uniqueKey} className="highlight-text">
<span
key={uniqueKey}
className="highlight-text"
data-testid="highlight-text"
>
{part}
</span>
) : (
@@ -220,6 +224,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
selected: isSelected,
active: isActive,
})}
data-testid={`option-item-${option.value}`}
onClick={(e): void => {
e.stopPropagation();
handleSelection();
@@ -241,7 +246,9 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
{highlightMatchedText(String(option.label || ''), searchText)}
</span>
{option.type === 'custom' && (
<div className="option-badge">{capitalize(option.type)}</div>
<div className="option-badge" data-testid="option-badge">
{capitalize(option.type)}
</div>
)}
</div>
</div>
@@ -268,6 +275,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
() => (
<X
size="md"
data-testid="custom-select-clear"
onClick={(e): void => {
e.stopPropagation();
if (onChange) {
@@ -528,6 +536,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
<div
ref={dropdownRef}
className="custom-select-dropdown"
data-testid="custom-select-dropdown"
onClick={handleDropdownClick}
onKeyDown={handleKeyDown}
onScroll={handleDropdownScroll}
@@ -587,7 +596,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
</section>
)}
{loading && (
<div className="navigation-loading">
<div className="navigation-loading" data-testid="navigation-loading">
<div className="navigation-icons">
<Loader size="md" className="animate-spin" />
</div>
@@ -595,7 +604,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
</div>
)}
{!loading && waitingMessage && (
<div className="navigation-loading">
<div className="navigation-loading" data-testid="navigation-loading">
<div className="navigation-icons">
<Loader size="md" className="animate-spin" />
</div>
@@ -605,7 +614,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
</div>
)}
{errorMessage && !loading && (
<div className="navigation-error">
<div className="navigation-error" data-testid="navigation-error">
<div className="navigation-text">
{errorMessage || SOMETHING_WENT_WRONG}
</div>

View File

@@ -1,8 +1,9 @@
import { useState } from 'react';
import { VirtuosoMockContext } from 'react-virtuoso';
import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import CustomMultiSelect from '../CustomMultiSelect';
import type { CustomMultiSelectProps } from '../types';
// Mock scrollIntoView which isn't available in JSDOM
window.HTMLElement.prototype.scrollIntoView = jest.fn();
@@ -49,6 +50,26 @@ const mockGroupedOptions = [
},
];
function StatefulMultiSelect({
initialValue,
onChange,
}: {
initialValue: string[];
onChange: CustomMultiSelectProps['onChange'];
}): JSX.Element {
const [value, setValue] = useState<string[] | string>(initialValue);
return (
<CustomMultiSelect
options={mockOptions}
value={value}
onChange={(next, option): void => {
onChange?.(next, option);
setValue(next);
}}
/>
);
}
describe('CustomMultiSelect - Comprehensive Tests', () => {
let user: ReturnType<typeof userEvent.setup>;
let mockOnChange: jest.Mock;
@@ -114,16 +135,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
{ timeout: 5000 },
);
// Find input by class name
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
// Type partial match that doesn't exist exactly
if (searchInput) {
await user.type(searchInput, 'fro');
}
await user.type(combobox, 'fro');
// Verify the component renders without crashing
expect(combobox).toBeInTheDocument();
@@ -141,30 +154,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'frontend');
}
await user.type(combobox, 'frontend');
// Should show the Frontend option in dropdown for exact match
await waitFor(() => {
// Check for highlighted "frontend" text
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('Frontend');
// Frontend option should be visible in dropdown - use a simpler approach
const optionLabels = document.querySelectorAll('.option-label-text');
const hasFrontendOption = Array.from(optionLabels).some((label) =>
label.textContent?.includes('Frontend'),
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
);
expect(hasFrontendOption).toBe(true);
});
// Press Enter to select the exact match
@@ -188,49 +191,31 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'end');
}
await user.type(combobox, 'end');
// Should filter to show only Frontend and Backend with highlighted "end"
await waitFor(() => {
// Check for highlighted "end" text in the options
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('end');
// Check that Frontend and Backend options are present with highlighted text
const optionLabels = document.querySelectorAll('.option-label-text');
const hasFrontendOption = Array.from(optionLabels).some(
(label) =>
label.textContent?.includes('Front') &&
label.textContent?.includes('end'),
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
);
const hasBackendOption = Array.from(optionLabels).some(
(label) =>
label.textContent?.includes('Back') && label.textContent?.includes('end'),
expect(screen.getByTestId('option-item-backend')).toHaveTextContent(
'Backend',
);
expect(hasFrontendOption).toBe(true);
expect(hasBackendOption).toBe(true);
// Other options should be filtered out
const hasDatabaseOption = Array.from(optionLabels).some((label) =>
label.textContent?.includes('Database'),
);
const hasApiGatewayOption = Array.from(optionLabels).some((label) =>
label.textContent?.includes('API Gateway'),
);
expect(hasDatabaseOption).toBe(false);
expect(hasApiGatewayOption).toBe(false);
expect(
screen.queryByTestId('option-item-database'),
).not.toBeInTheDocument();
expect(
screen.queryByTestId('option-item-api-gateway'),
).not.toBeInTheDocument();
});
});
@@ -246,15 +231,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
// Type comma-separated values
await user.type(searchInput, 'test1, test2, test3');
}
// Type comma-separated values
await user.type(combobox, 'test1, test2, test3');
// Press Enter to create the comma-separated chips
await user.keyboard('{Enter}');
@@ -294,14 +272,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
const dropdown = document.querySelector('.custom-multiselect-dropdown');
expect(dropdown).toBeInTheDocument();
const options = dropdown?.querySelectorAll('.option-label-text') || [];
const optionTexts = Array.from(options).map((el) => el.textContent);
expect(
screen.getByTestId('custom-multiselect-dropdown'),
).toBeInTheDocument();
// Database should be at the top (after ALL option if present)
expect(optionTexts[0]).toBe('Database');
const [firstOption] = screen.getAllByTestId(/^option-item-/);
expect(firstOption).toBe(screen.getByTestId('option-item-database'));
});
});
@@ -319,30 +296,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
});
// Find and type in search input
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'front');
}
await user.type(combobox, 'front');
// Should filter to show only options containing 'front' and highlight search term
await waitFor(() => {
// Check for highlighted text within the Frontend option
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('Front');
// Should show Frontend option (highlighted) - use a simpler approach
const optionLabels = document.querySelectorAll('.option-label-text');
const hasFrontendOption = Array.from(optionLabels).some((label) =>
label.textContent?.includes('Frontend'),
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
);
expect(hasFrontendOption).toBe(true);
// Backend and Database should not be visible
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
@@ -362,21 +329,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'end');
}
await user.type(combobox, 'end');
// Should highlight matching text in options
await waitFor(() => {
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('end');
});
});
@@ -393,14 +352,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'nonexistent');
}
await user.type(combobox, 'nonexistent');
// Should show custom value option when no matches found
await waitFor(() => {
@@ -411,13 +363,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
// Should show custom value option
const customOptions = screen.getAllByText('nonexistent');
const customOption = customOptions.find((option) => {
const optionItem = option.closest('.option-item');
const badge = optionItem?.querySelector('.option-badge');
return badge?.textContent === 'Custom';
});
expect(customOption).toBeInTheDocument();
const customOption = screen.getByTestId('option-item-nonexistent');
expect(customOption).toHaveTextContent('nonexistent');
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
});
});
});
@@ -445,23 +395,19 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// First option should be active
await waitFor(() => {
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
const activeOption = screen.getByTestId('option-item-frontend');
expect(activeOption).toHaveClass('active');
expect(activeOption).toHaveAttribute('role', 'option');
// The active option should be an option in the dropdown
expect(activeOption?.textContent).toBeTruthy();
});
// Arrow up should go to previous option (goes back to ALL)
await user.keyboard('{ArrowUp}');
await waitFor(() => {
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
const activeOption = screen.getByTestId('all-option');
expect(activeOption).toHaveClass('active');
expect(activeOption).toHaveAttribute('role', 'option');
expect(activeOption?.textContent).toContain('ALL');
expect(activeOption).toHaveTextContent('ALL');
});
});
@@ -499,19 +445,14 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Should navigate to first option in dropdown
await waitFor(() => {
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
expect(activeOption).toHaveClass('active');
expect(activeOption?.textContent).toBeTruthy();
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
});
// Tab again to move to next option
await user.tab();
await waitFor(() => {
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
expect(activeOption?.textContent).toContain('Backend');
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
});
});
@@ -558,10 +499,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Should have an active chip
await waitFor(() => {
const activeChip = document.querySelector(
'.ant-select-selection-item-active',
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
'ant-select-selection-item-active',
);
expect(activeChip).toBeInTheDocument();
});
// Delete the active chip
@@ -575,11 +515,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Verify that the active chip (backend) is highlighted for deletion
await waitFor(() => {
const activeChip = document.querySelector(
'.ant-select-selection-item-active',
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
'ant-select-selection-item-active',
);
expect(activeChip).toBeInTheDocument();
expect(activeChip).toHaveTextContent('backend');
});
});
});
@@ -688,9 +626,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
);
await user.click(screen.getByRole('combobox'));
const backendRow = (await screen.findByText('Backend')).closest(
'[role="option"]',
) as HTMLElement;
const backendRow = await screen.findByTestId('option-item-backend');
mockOnChange.mockClear();
await user.click(within(backendRow).getByRole('checkbox'));
@@ -726,9 +662,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
);
await user.click(screen.getByRole('combobox'));
const backendRow = (await screen.findByText('Backend')).closest(
'[role="option"]',
) as HTMLElement;
const backendRow = await screen.findByTestId('option-item-backend');
mockOnChange.mockClear();
await user.click(within(backendRow).getByText('Toggle'));
@@ -751,8 +685,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('Database')).toBeInTheDocument();
expect(screen.getByText('API Gateway')).toBeInTheDocument();
const loadingFooter = document.querySelector('.navigation-loading');
expect(loadingFooter).toBeInTheDocument();
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
expect(screen.getByText('Refreshing values...')).toBeInTheDocument();
});
});
@@ -770,8 +703,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
const errorFooter = document.querySelector('.navigation-error');
expect(errorFooter).toBeInTheDocument();
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});
});
@@ -813,21 +745,17 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await waitFor(() => {
// All chips should be selected (have selected class)
const selectedChips = document.querySelectorAll(
'.ant-select-selection-item-selected',
);
const selectedChips = screen
.getAllByTestId(/^selected-tag-/)
.filter((chip) =>
chip.classList.contains('ant-select-selection-item-selected'),
);
expect(selectedChips.length).toBeGreaterThan(0);
// Verify that all expected chips are present AND selected
const frontendChip = screen
.getByText('frontend')
.closest('.ant-select-selection-item');
const backendChip = screen
.getByText('backend')
.closest('.ant-select-selection-item');
const databaseChip = screen
.getByText('database')
.closest('.ant-select-selection-item');
const frontendChip = screen.getByTestId('selected-tag-frontend');
const backendChip = screen.getByTestId('selected-tag-backend');
const databaseChip = screen.getByTestId('selected-tag-database');
expect(frontendChip).toHaveClass('ant-select-selection-item-selected');
expect(backendChip).toHaveClass('ant-select-selection-item-selected');
@@ -850,11 +778,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
/>,
);
const clearButton = document.querySelector('.ant-select-clear');
if (clearButton) {
await user.click(clearButton as Element);
expect(mockOnChange).toHaveBeenCalledWith([], []);
}
await user.click(screen.getByLabelText('close-circle'));
expect(mockOnChange).toHaveBeenCalledWith([], []);
});
it('CA-03: Individual chip removal', async () => {
@@ -867,12 +792,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
);
// Find and click the close button on a chip
const removeButtons = document.querySelectorAll(
'.ant-select-selection-item-remove',
);
const removeButtons = screen.getAllByLabelText(/^Remove tag /);
expect(removeButtons).toHaveLength(2);
await user.click(removeButtons[1] as Element);
await user.click(removeButtons[1]);
// Should call onChange with one item removed
expect(mockOnChange).toHaveBeenCalledWith(
@@ -911,9 +834,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await waitFor(() => {
// Dropdown should be hidden (not completely removed from DOM)
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
expect(dropdown).toHaveStyle('pointer-events: none');
expect(
screen.getByTestId('custom-multiselect-dropdown'),
).toBeInTheDocument();
expect(combobox).toHaveAttribute('aria-expanded', 'false');
});
});
@@ -951,14 +875,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'custom-input');
}
await user.type(combobox, 'custom-input');
// Press Enter in input field
await user.keyboard('{Enter}');
@@ -984,18 +901,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'search-text');
}
await user.type(combobox, 'search-text');
// Verify search text is in input
await waitFor(() => {
expect(searchInput).toHaveValue('search-text');
expect(combobox).toHaveValue('search-text');
});
// Press Escape to close dropdown
@@ -1003,9 +913,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Dropdown should close and search text should be cleared
await waitFor(() => {
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
expect(searchInput).toHaveValue('');
expect(combobox).toHaveAttribute('aria-expanded', 'false');
expect(combobox).toHaveValue('');
});
});
});
@@ -1029,8 +938,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(allOption).toBeInTheDocument();
// Check for divider after ALL option
const divider = document.querySelector('.divider');
expect(divider).toBeInTheDocument();
expect(screen.getByTestId('all-option-divider')).toBeInTheDocument();
});
});
@@ -1086,8 +994,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await waitFor(() => {
// Should show navigation footer
const footer = document.querySelector('.navigation-footer');
expect(footer).toBeInTheDocument();
expect(screen.getByTestId('navigation-footer')).toBeInTheDocument();
// Should show navigation hint
expect(screen.getByText('to navigate')).toBeInTheDocument();
@@ -1161,10 +1068,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
describe('Advanced Keyboard Navigation (AKN)', () => {
it('AKN-01: Shift + Arrow + Del chip deletion', async () => {
renderWithVirtuoso(
<CustomMultiSelect
options={mockOptions}
<StatefulMultiSelect
initialValue={['frontend', 'backend', 'database']}
onChange={mockOnChange}
value={['frontend', 'backend', 'database']}
/>,
);
@@ -1176,12 +1082,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Should have an active chip - verify initial chip
await waitFor(() => {
const activeChip = document.querySelector(
'.ant-select-selection-item-active',
);
expect(activeChip).toBeInTheDocument();
// Verify we're on the last chip (database)
expect(activeChip?.textContent).toContain('database');
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
'ant-select-selection-item-active',
);
});
// Use Shift + Arrow to navigate to previous chip
@@ -1189,12 +1093,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Verify we're on a different chip (backend)
await waitFor(() => {
const activeChip = document.querySelector(
'.ant-select-selection-item-active',
);
expect(activeChip).toBeInTheDocument();
// Verify we moved to the previous chip (backend)
expect(activeChip?.textContent).toContain('backend');
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
'ant-select-selection-item-active',
);
});
// Use Del to delete the active chip
@@ -1203,8 +1105,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Verify the chip was deleted
await waitFor(() => {
// Check that the backend chip is no longer present
const backendChip = document.querySelector('.ant-select-selection-item');
expect(backendChip?.textContent).not.toContain('backend');
expect(
screen.queryByTestId('selected-tag-backend'),
).not.toBeInTheDocument();
// Verify onChange was called with the updated value (without backend)
expect(mockOnChange).toHaveBeenCalledWith(
@@ -1235,9 +1138,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Dropdown should close - check for hidden state
await waitFor(() => {
const dropdown = document.querySelector('.ant-select-dropdown');
// The dropdown should be hidden with the hidden class
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
expect(combobox).toHaveAttribute('aria-expanded', 'false');
});
});
});
@@ -1256,32 +1158,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'front');
}
await user.type(combobox, 'front');
// Should show highlighted options with correct order
await waitFor(() => {
// Check for highlighted text
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('front');
// Get all option items to check the order
const optionItems = document.querySelectorAll('.option-item');
const optionTexts = Array.from(optionItems)
.map((item) => {
const labelElement = item.querySelector('.option-label-text');
return labelElement?.textContent?.trim();
})
.filter(Boolean);
const optionTexts = screen
.getAllByTestId(/^option-item-/)
.map((item) => item.textContent?.trim());
// Custom value "front" should appear first (above Frontend)
// The text should contain "front"
@@ -1325,12 +1215,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
});
// Now type something and press Enter to save
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
if (searchInput) {
await user.type(searchInput, 'custom-value');
}
await user.type(combobox, 'custom-value');
// Press Enter to save (should create custom value)
await user.keyboard('{Enter}');
@@ -1364,11 +1249,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
/>,
);
const clearButton = document.querySelector('.ant-select-clear');
expect(clearButton).toBeInTheDocument();
// Click clear button
await user.click(clearButton as Element);
await user.click(screen.getByLabelText('close-circle'));
// Should call onChange immediately (no loading state in this component)
expect(mockOnChangeWithDelay).toHaveBeenCalledWith([], []);
@@ -1426,19 +1308,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
const combobox = screen.getByRole('combobox');
await user.click(combobox);
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
// Type a long search value
if (searchInput) {
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
await user.type(searchInput, longSearchValue);
}
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
await user.type(combobox, longSearchValue);
// Should not overflow or break layout
await waitFor(() => {
// oxlint-disable-next-line signoz/no-dom-node-access -- antd's search wrapper has no test hook; the test reads its computed overflow
const searchContainer = document.querySelector(
'.ant-select-selection-search',
);
@@ -1469,25 +1345,16 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
// Test regex pattern
await user.type(searchInput, '.*test.*');
}
// Test regex pattern
await user.type(combobox, '.*test.*');
// Should create custom value for regex pattern
await waitFor(() => {
const regexOptions = screen.getAllByText('.*test.*');
const regexOption = regexOptions.find((option) => {
const optionItem = option.closest('.option-item');
const badge = optionItem?.querySelector('.option-badge');
return badge?.textContent === 'Custom';
});
expect(regexOption).toBeInTheDocument();
const regexOption = screen.getByTestId('option-item-.*test.*');
expect(regexOption).toHaveTextContent('.*test.*');
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
});
// Press Enter to create the regex value
@@ -1570,8 +1437,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await user.keyboard('{Escape}');
await waitFor(() => {
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
expect(combobox).toHaveAttribute('aria-expanded', 'false');
});
});
});

View File

@@ -4,8 +4,9 @@ import {
render,
RenderResult,
screen,
userEvent,
waitFor,
} from '@testing-library/react';
} from 'tests/test-utils';
import CustomMultiSelect from '../CustomMultiSelect';
@@ -29,9 +30,6 @@ const mockOptions = [
{ label: 'Option 3', value: 'option3' },
];
// CSS selector for retry button
const RETRY_BUTTON_SELECTOR = '[data-testid="retry-button"]';
describe('CustomMultiSelect - Retry Functionality', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -61,8 +59,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
});
// Check that retry button (ReloadOutlined icon) is present
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).toBeInTheDocument();
expect(screen.getByTestId('retry-button')).toBeInTheDocument();
});
it('should show retry button when 4xx error occurs and error message is displayed (current behavior)', async () => {
@@ -88,11 +85,11 @@ describe('CustomMultiSelect - Retry Functionality', () => {
expect(screen.getByText(errorMessage)).toBeInTheDocument();
});
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).not.toBeInTheDocument();
expect(screen.queryByTestId('retry-button')).not.toBeInTheDocument();
});
it('should call onRetry function when retry button is clicked', async () => {
const user = userEvent.setup();
const mockOnRetry = jest.fn();
const errorMessage = 'Internal Server Error (500)';
@@ -108,7 +105,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
// Open dropdown
const selectElement = screen.getByRole('combobox');
fireEvent.mouseDown(selectElement);
await user.click(selectElement);
// Wait for dropdown to appear
await waitFor(() => {
@@ -116,10 +113,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
});
// Find and click the retry button
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).toBeInTheDocument();
fireEvent.click(retryButton as Element);
await user.click(screen.getByTestId('retry-button'));
// Verify onRetry was called
expect(mockOnRetry).toHaveBeenCalledTimes(1);

View File

@@ -4,9 +4,10 @@ import {
render,
RenderResult,
screen,
userEvent,
waitFor,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
within,
} from 'tests/test-utils';
import CustomMultiSelect from '../CustomMultiSelect';
@@ -156,6 +157,7 @@ describe('CustomMultiSelect Component', () => {
});
it('removes a tag when clicked', async () => {
const user = userEvent.setup();
const handleChange = jest.fn();
renderWithVirtuoso(
<CustomMultiSelect
@@ -166,10 +168,7 @@ describe('CustomMultiSelect Component', () => {
);
// Find close button on Option 1 tag and click it
const closeButtons = document.querySelectorAll(
'.ant-select-selection-item-remove',
);
fireEvent.click(closeButtons[0]);
await user.click(screen.getByLabelText('Remove tag option1'));
// Verify onChange was called with remaining option
expect(handleChange).toHaveBeenCalledWith(
@@ -179,39 +178,24 @@ describe('CustomMultiSelect Component', () => {
});
it('filters options when searching', async () => {
const user = userEvent.setup();
renderWithVirtuoso(<CustomMultiSelect options={mockOptions} />);
// Open dropdown
const selectElement = screen.getByRole('combobox');
fireEvent.mouseDown(selectElement);
await user.click(selectElement);
// Type into search box - get input directly
const inputElement = selectElement.querySelector('input');
if (inputElement) {
fireEvent.change(inputElement, { target: { value: '2' } });
}
// Type into search box - the combobox is the search input
await user.type(selectElement, '2');
// Wait for the dropdown filtering to happen
await waitFor(() => {
// Check that the dropdown is present
const dropdownElement = document.querySelector(
'.custom-multiselect-dropdown',
);
expect(dropdownElement).toBeInTheDocument();
// Verify Option 2 is visible in the dropdown
const options = document.querySelectorAll('.option-label-text');
let foundOption2 = false;
options.forEach((option) => {
const text = option.textContent || '';
if (text.includes('Option 2')) {
foundOption2 = true;
}
});
expect(foundOption2).toBe(true);
});
await waitFor(() =>
expect(screen.queryByTestId('option-item-option1')).not.toBeInTheDocument(),
);
expect(
within(screen.getByTestId('custom-multiselect-dropdown'))
.getAllByTestId(/^option-item-/)
.map((option) => option.dataset.testid),
).toStrictEqual(['option-item-2', 'option-item-option2']);
});
it('renders grouped options correctly', async () => {

View File

@@ -1,5 +1,4 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import CustomSelect from '../CustomSelect';
@@ -67,34 +66,19 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
// Find input by class name
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
// Type partial match that doesn't exist exactly
if (searchInput) {
await user.type(searchInput, 'fro');
}
await user.type(combobox, 'fro');
// Check that custom value appears in dropdown with custom tag
await waitFor(() => {
// Find the custom option with "fro" text and "Custom" badge
const customOptions = screen.getAllByText('fro');
const customOption = customOptions.find((option) => {
const optionItem = option.closest('.option-item');
const badge = optionItem?.querySelector('.option-badge');
return badge?.textContent === 'Custom';
});
expect(customOption).toBeInTheDocument();
const customOption = screen.getByTestId('option-item-fro');
expect(customOption).toHaveTextContent('fro');
// Verify it has the custom badge
const optionItem = customOption?.closest('.option-item');
const badge = optionItem?.querySelector('.option-badge');
expect(badge).toBeInTheDocument();
expect(badge?.textContent).toBe('Custom');
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
});
// Press Enter to create the custom value
@@ -120,30 +104,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'frontend');
}
await user.type(combobox, 'frontend');
// Should show the Frontend option in dropdown for exact match
await waitFor(() => {
// Check for highlighted "frontend" text
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('Frontend');
// Frontend option should be visible in dropdown - use a simpler approach
const optionContents = document.querySelectorAll('.option-content');
const hasFrontendOption = Array.from(optionContents).some((content) =>
content.textContent?.includes('Frontend'),
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
);
expect(hasFrontendOption).toBe(true);
});
// Press Enter to select the exact match
@@ -174,14 +148,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
const dropdown = document.querySelector('.custom-select-dropdown');
expect(dropdown).toBeInTheDocument();
const options = dropdown?.querySelectorAll('.option-content') || [];
const optionTexts = Array.from(options).map((el) => el.textContent);
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
// Database should be at the top
expect(optionTexts[0]).toContain('Database');
const [firstOption] = screen.getAllByTestId(/^option-item-/);
expect(firstOption).toHaveTextContent('Database');
});
});
@@ -197,30 +168,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
});
// Find and type in search input
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'front');
}
await user.type(combobox, 'front');
// Should filter to show only options containing 'front'
await waitFor(() => {
// Check for highlighted text within the Frontend option
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('Front');
// Should show Frontend option (highlighted) - use a simpler approach
const optionContents = document.querySelectorAll('.option-content');
const hasFrontendOption = Array.from(optionContents).some((content) =>
content.textContent?.includes('Frontend'),
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
);
expect(hasFrontendOption).toBe(true);
// Backend and Database should not be visible
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
@@ -238,21 +199,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'end');
}
await user.type(combobox, 'end');
// Should highlight matching text in options
await waitFor(() => {
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('end');
});
});
@@ -267,14 +220,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'nonexistent');
}
await user.type(combobox, 'nonexistent');
// Should show custom value option when no matches found
await waitFor(() => {
@@ -285,13 +231,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
// Should show custom value option
const customOptions = screen.getAllByText('nonexistent');
const customOption = customOptions.find((option) => {
const optionItem = option.closest('.option-item');
const badge = optionItem?.querySelector('.option-badge');
return badge?.textContent === 'Custom';
});
expect(customOption).toBeInTheDocument();
const customOption = screen.getByTestId('option-item-nonexistent');
expect(customOption).toHaveTextContent('nonexistent');
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
});
});
});
@@ -313,19 +257,15 @@ describe('CustomSelect - Comprehensive Tests', () => {
// First option should be active
await waitFor(() => {
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
// Verify it's the first option (Frontend)
expect(activeOption?.textContent).toContain('Backend');
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
});
// Arrow up should go to previous option
await user.keyboard('{ArrowUp}');
await waitFor(() => {
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
expect(activeOption?.textContent).toContain('Frontend');
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
});
});
@@ -410,8 +350,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
await user.keyboard('{Tab}');
// Should still be within dropdown context
const dropdown = document.querySelector('.custom-select-dropdown');
expect(dropdown).toBeInTheDocument();
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
});
});
@@ -453,8 +392,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
const loadingFooter = document.querySelector('.navigation-loading');
expect(loadingFooter).toBeInTheDocument();
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
});
});
@@ -471,8 +409,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
const errorFooter = document.querySelector('.navigation-error');
expect(errorFooter).toBeInTheDocument();
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});
});
@@ -605,8 +542,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(combobox).toHaveFocus();
await waitFor(() => {
const dropdown = document.querySelector('.custom-select-dropdown');
expect(dropdown).toBeInTheDocument();
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
});
// Focus should remain manageable
@@ -679,8 +615,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
// Dropdown should close
await waitFor(() => {
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
expect(combobox).toHaveAttribute('aria-expanded', 'false');
});
});
@@ -714,8 +649,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
// Should navigate to first option in dropdown
await waitFor(() => {
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
});
});
});
@@ -732,32 +666,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'front');
}
await user.type(combobox, 'front');
// Should show highlighted options with correct order
await waitFor(() => {
// Check for highlighted text
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
expect(highlightTexts).toContain('front');
// Get all option items to check the order
const optionItems = document.querySelectorAll('.option-item');
const optionTexts = Array.from(optionItems)
.map((item) => {
const contentElement = item.querySelector('.option-content');
return contentElement?.textContent?.trim();
})
.filter(Boolean);
const optionTexts = screen
.getAllByTestId(/^option-item-/)
.map((item) => item.textContent?.trim());
// Custom value "front" should appear first (above Frontend)
// The text includes "Custom" badge, so check for "front" in the text
@@ -807,12 +729,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
});
// Now type something and press Enter to save
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
if (searchInput) {
await user.type(searchInput, 'custom-value');
}
await user.type(combobox, 'custom-value');
// Press Enter to save (should close dropdown)
await user.keyboard('{Enter}');
@@ -847,11 +764,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
/>,
);
const clearButton = document.querySelector('.ant-select-clear');
expect(clearButton).toBeInTheDocument();
// Click clear button
await user.click(clearButton as Element);
await user.click(screen.getByTestId('custom-select-clear'));
// Should call onChange immediately (no loading state in this component)
expect(mockOnChangeWithDelay).toHaveBeenCalledWith(undefined, undefined);
@@ -870,11 +784,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
/>,
);
const clearButton = document.querySelector('.ant-select-clear');
expect(clearButton).toBeInTheDocument();
// Click clear button
await user.click(clearButton as Element);
await user.click(screen.getByTestId('custom-select-clear'));
// Should clear the single selection
expect(mockOnChange).toHaveBeenCalledWith(undefined, undefined);
@@ -927,19 +838,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
const combobox = screen.getByRole('combobox');
await user.click(combobox);
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
// Type a long search value
if (searchInput) {
const longSearchValue = 'a'.repeat(100);
await user.type(searchInput, longSearchValue);
}
const longSearchValue = 'a'.repeat(100);
await user.type(combobox, longSearchValue);
// Should not overflow or break layout
await waitFor(() => {
// oxlint-disable-next-line signoz/no-dom-node-access -- antd's search wrapper has no test hook; the test reads its computed overflow
const searchContainer = document.querySelector(
'.ant-select-selection-search',
);
@@ -962,12 +867,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(combobox).toHaveFocus();
// Should be able to type even with loading state
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
if (searchInput) {
await user.type(searchInput, 'test');
}
await user.type(combobox, 'test');
// Should not be blocked by loading spinner
expect(combobox).not.toBeDisabled();
@@ -986,25 +886,16 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
// Test regex pattern
await user.type(searchInput, '.*test.*');
}
// Test regex pattern
await user.type(combobox, '.*test.*');
// Should create custom value for regex pattern
await waitFor(() => {
const regexOptions = screen.getAllByText('.*test.*');
const regexOption = regexOptions.find((option) => {
const optionItem = option.closest('.option-item');
const badge = optionItem?.querySelector('.option-badge');
return badge?.textContent === 'Custom';
});
expect(regexOption).toBeInTheDocument();
const regexOption = screen.getByTestId('option-item-.*test.*');
expect(regexOption).toHaveTextContent('.*test.*');
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
});
// Press Enter to create the regex value
@@ -1076,8 +967,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
// Dropdown should close after selection in single select
await waitFor(() => {
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
expect(combobox).toHaveAttribute('aria-expanded', 'false');
});
});
});

View File

@@ -1,5 +1,11 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import CustomSelect from '../CustomSelect';
@@ -93,11 +99,12 @@ describe('CustomSelect Component', () => {
// Dropdown should only show Option 2
await waitFor(() => {
// Check that the dropdown is present
const dropdownElement = document.querySelector('.custom-select-dropdown');
const dropdownElement = screen.getByTestId('custom-select-dropdown');
expect(dropdownElement).toBeInTheDocument();
// Use a simple approach to verify filtering
const allOptionsInDropdown = document.querySelectorAll('.option-item');
const allOptionsInDropdown =
within(dropdownElement).queryAllByTestId(/^option-item-/);
let foundOption2 = false;
allOptionsInDropdown.forEach((option) => {

View File

@@ -40,7 +40,7 @@ function ListViewOrderBy({
const [searchInput, setSearchInput] = useState('');
const [debouncedInput, setDebouncedInput] = useState('');
const [selectOptions, setSelectOptions] = useState<
{ label: string; value: string }[]
{ label: string; value: string; 'data-testid': string }[]
>([]);
const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -75,8 +75,16 @@ function ListViewOrderBy({
setSelectOptions(
uniqueKeys.flatMap((key) => [
{ label: `${key} (desc)`, value: `${key}:desc` },
{ label: `${key} (asc)`, value: `${key}:asc` },
{
label: `${key} (desc)`,
value: `${key}:desc`,
'data-testid': 'list-view-order-by-option',
},
{
label: `${key} (asc)`,
value: `${key}:asc`,
'data-testid': 'list-view-order-by-option',
},
]),
);
}, [data, searchInput, extraKeysSignature]);

View File

@@ -59,9 +59,9 @@ const openDropdown = (): void => {
};
const getOptionLabels = (): string[] =>
Array.from(document.querySelectorAll('.ant-select-item-option-content')).map(
(node) => node.textContent ?? '',
);
screen
.queryAllByTestId('list-view-order-by-option')
.map((node) => node.textContent ?? '');
describe('ListViewOrderBy', () => {
beforeEach(() => {

View File

@@ -1,8 +1,7 @@
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { act, render, screen, userEvent, within } from 'tests/test-utils';
import OverflowInputToolTip from './OverflowInputToolTip';
const TOOLTIP_INNER_SELECTOR = '.ant-tooltip-inner';
// Utility to mock overflow behaviour on inputs / elements.
// Stubs HTMLElement.prototype.clientWidth, scrollWidth and offsetWidth used by component.
function mockOverflow(clientWidth: number, scrollWidth: number): void {
@@ -22,21 +21,17 @@ function mockOverflow(clientWidth: number, scrollWidth: number): void {
});
}
function queryTooltipInner(): HTMLElement | null {
// find element that has role="tooltip" (could be the inner itself)
const tooltip = document.querySelector<HTMLElement>('[role="tooltip"]');
if (!tooltip) {
return document.querySelector(TOOLTIP_INNER_SELECTOR);
}
const ANTD_TOOLTIP_OPEN_DELAY_MS = 100;
// if the role element is already the inner, return it; otherwise return its descendant
if (tooltip.classList.contains('ant-tooltip-inner')) {
return tooltip;
}
return (
(tooltip.querySelector(TOOLTIP_INNER_SELECTOR) as HTMLElement) ??
document.querySelector(TOOLTIP_INNER_SELECTOR)
);
async function hoverPastOpenDelay(element: HTMLElement): Promise<void> {
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
await user.hover(element);
act(() => {
jest.advanceTimersByTime(ANTD_TOOLTIP_OPEN_DELAY_MS * 2);
});
}
describe('OverflowInputToolTip', () => {
@@ -44,6 +39,10 @@ describe('OverflowInputToolTip', () => {
jest.restoreAllMocks();
});
afterEach(() => {
jest.useRealTimers();
});
it('shows tooltip when content overflows and input is clamped at maxAutoWidth', async () => {
mockOverflow(150, 250); // clientWidth >= maxAutoWidth (150), scrollWidth > clientWidth
@@ -51,16 +50,9 @@ describe('OverflowInputToolTip', () => {
await userEvent.hover(screen.getByRole('textbox'));
await waitFor(() => {
expect(queryTooltipInner()).not.toBeNull();
});
const tooltipInner = queryTooltipInner();
if (!tooltipInner) {
throw new Error('Tooltip inner not found');
}
const tooltip = await screen.findByRole('tooltip');
expect(
within(tooltipInner).getByText('Very long overflowing text'),
within(tooltip).getByText('Very long overflowing text'),
).toBeInTheDocument();
});
@@ -69,11 +61,9 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Short text" />);
await userEvent.hover(screen.getByRole('textbox'));
await hoverPastOpenDelay(screen.getByRole('textbox'));
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
});
it('does NOT show tooltip when content overflows but input is NOT at maxAutoWidth', async () => {
@@ -81,11 +71,9 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Long but input not clamped" />);
await userEvent.hover(screen.getByRole('textbox'));
await hoverPastOpenDelay(screen.getByRole('textbox'));
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
});
it('uncontrolled input allows typing', async () => {
@@ -102,24 +90,20 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Overflowing!" disabled />);
await userEvent.hover(screen.getByRole('textbox'));
await hoverPastOpenDelay(screen.getByRole('textbox'));
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
});
it('renders mirror span and input correctly (structural assertions instead of snapshot)', () => {
const { container } = render(<OverflowInputToolTip value="Snapshot" />);
const mirror = container.querySelector('.overflow-input-mirror');
const input = container.querySelector('input') as HTMLInputElement | null;
render(<OverflowInputToolTip value="Snapshot" />);
const mirror = screen.getByTestId('overflow-input-mirror');
const input = screen.getByRole('textbox');
expect(mirror).toBeTruthy();
expect(mirror?.textContent).toBe('Snapshot');
expect(input).toBeTruthy();
expect(input?.value).toBe('Snapshot');
expect(mirror.textContent).toBe('Snapshot');
expect(input).toHaveValue('Snapshot');
// width should be set inline (component calculates width on mount)
expect(input?.getAttribute('style')).toContain('width:');
expect(input.getAttribute('style')).toContain('width:');
});
});

View File

@@ -49,7 +49,12 @@ function OverflowInputToolTip({
return (
<>
<span ref={mirrorRef} aria-hidden className="overflow-input-mirror" />
<span
ref={mirrorRef}
aria-hidden
className="overflow-input-mirror"
data-testid="overflow-input-mirror"
/>
<Tooltip title={tooltipTitle} placement={tooltipPlacement}>
<Input
{...rest}

View File

@@ -105,6 +105,8 @@ const stopEventsExtension = EditorView.domEventHandlers({
},
});
const EDITOR_BASIC_SETUP = { lineNumbers: false };
interface QuerySearchProps {
placeholder?: string;
onChange: (value: string) => void;
@@ -317,23 +319,20 @@ function QuerySearch({
500,
);
const toggleSuggestions = useCallback(
(timeout?: number) => {
const timeoutId = setTimeout(() => {
if (!editorRef.current) {
return;
}
if (isFocused) {
startCompletion(editorRef.current);
} else {
closeCompletion(editorRef.current);
}
}, timeout);
const toggleSuggestions = useCallback((timeout?: number) => {
const timeoutId = setTimeout(() => {
if (!editorRef.current) {
return;
}
if (editorRef.current.hasFocus) {
startCompletion(editorRef.current);
} else {
closeCompletion(editorRef.current);
}
}, timeout);
return (): void => clearTimeout(timeoutId);
},
[isFocused],
);
return (): void => clearTimeout(timeoutId);
}, []);
const fetchKeySuggestions = useCallback(
async (searchText?: string): Promise<void> => {
@@ -716,14 +715,17 @@ function QuerySearch({
}
}, []);
const handleChange = (value: string): void => {
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const handleChange = useCallback((value: string): void => {
if (isProgrammaticChangeRef.current) {
isProgrammaticChangeRef.current = false;
return;
}
onChange(value);
};
onChangeRef.current(value);
}, []);
const handleBlur = (): void => {
const currentExpression = getCurrentExpression();
@@ -1477,6 +1479,65 @@ function QuerySearch({
};
}
const completionSourceRef = useRef(combinedSuggestions);
completionSourceRef.current = combinedSuggestions;
const handleRunRef = useRef(handleRun);
handleRunRef.current = handleRun;
// Built once: new extensions reconfigure CodeMirror, which closes the open suggestions.
const editorExtensions = useMemo(
() => [
autocompletion({
override: [
(context: CompletionContext): CompletionResult | null =>
completionSourceRef.current(context),
],
defaultKeymap: true,
closeOnBlur: true,
activateOnTyping: true,
maxRenderedOptions: 50,
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
}),
javascript({ jsx: false, typescript: false }),
EditorView.lineWrapping,
stopEventsExtension,
Prec.highest(
keymap.of([
...completionKeymap,
{
key: 'Escape',
run: closeCompletion,
},
{
key: 'Enter',
preventDefault: true,
// Prevent default behavior of Enter to add new line
// and instead run a custom action
run: (): boolean => true,
},
{
key: 'Mod-Enter',
preventDefault: true,
// Prevent default behavior of Mod-Enter to add new line
// and instead run a custom action
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
run: (): boolean => {
handleRunRef.current();
return true;
},
},
{
key: 'Shift-Enter',
preventDefault: true,
// Prevent default behavior of Shift-Enter to add new line
run: (): boolean => true,
},
]),
),
],
[],
);
// Effect to handle focus state and trigger suggestions
useEffect(() => {
const clearTimeout = toggleSuggestions(10);
@@ -1597,7 +1658,10 @@ function QuerySearch({
{showScopeChip && <ScopeChip expression={initialExpression ?? ''} />}
{isScopedFilter && !showScopeChip ? (
<Tooltip title={initialExpression || ''} placement="left">
<div className="query-search-initial-scope-label">
<div
className="query-search-initial-scope-label"
data-testid="query-search-initial-scope-label"
>
<Filter
size={14}
style={{
@@ -1650,56 +1714,9 @@ function QuerySearch({
hasErrors: validation.errors.length > 0,
hasInitialExpression: isScopedFilter && !showScopeChip,
})}
extensions={[
autocompletion({
override: [combinedSuggestions],
defaultKeymap: true,
closeOnBlur: true,
activateOnTyping: true,
maxRenderedOptions: 50,
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
}),
javascript({ jsx: false, typescript: false }),
EditorView.lineWrapping,
stopEventsExtension,
Prec.highest(
keymap.of([
...completionKeymap,
{
key: 'Escape',
run: closeCompletion,
},
{
key: 'Enter',
preventDefault: true,
// Prevent default behavior of Enter to add new line
// and instead run a custom action
run: (): boolean => true,
},
{
key: 'Mod-Enter',
preventDefault: true,
// Prevent default behavior of Mod-Enter to add new line
// and instead run a custom action
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
run: (): boolean => {
handleRun();
return true;
},
},
{
key: 'Shift-Enter',
preventDefault: true,
// Prevent default behavior of Shift-Enter to add new line
run: (): boolean => true,
},
]),
),
]}
extensions={editorExtensions}
placeholder={placeholder}
basicSetup={{
lineNumbers: false,
}}
basicSetup={EDITOR_BASIC_SETUP}
onFocus={(): void => {
setIsFocused(true);
}}

View File

@@ -168,6 +168,7 @@ export function renderRecentDeleteButton(
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'cm-recent-delete';
btn.dataset.testid = 'query-search-recent-delete';
btn.setAttribute('aria-label', 'Remove from recent searches');
btn.title = 'Remove from recent searches';
btn.textContent = '×';

View File

@@ -9,7 +9,7 @@ import {
import { ENVIRONMENT } from 'constants/env';
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { render, screen, userEvent, within } from 'tests/test-utils';
import type {
IBuilderQuery,
Query,
@@ -19,6 +19,7 @@ import { EQueryType } from 'types/common/dashboard';
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
import QueryAggregationSelect from '../QueryAggregation/QueryAggregationSelect';
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
import { findCompletionOption } from './findCompletionOption';
const EDITOR_TEST_ID = 'query-aggregation-editor';
// CodeMirror's suggestion popup is slow to open under a parallel jest run.
@@ -116,7 +117,7 @@ async function enterAggregation(
queryData: IBuilderQuery = aiQuery,
currentQuery?: Query,
): Promise<void> {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<QueryBuilderV2Provider>
<QueryAggregationSelect queryData={queryData} />
@@ -125,12 +126,9 @@ async function enterAggregation(
{ queryBuilderOverrides: currentQuery && { currentQuery } },
);
const content = (
await screen.findByTestId(EDITOR_TEST_ID)
).querySelector<HTMLElement>('.cm-content');
if (!content) {
throw new Error('CodeMirror content element not rendered');
}
const content = within(await screen.findByTestId(EDITOR_TEST_ID)).getByRole(
'textbox',
);
await user.click(content);
// Typed keys drop under load: a re-render's dispatch discards DOM input CodeMirror hasn't read yet.
await user.paste(text);
@@ -138,10 +136,10 @@ async function enterAggregation(
}
function suggestionLabels(): string[] {
return Array.from(
screen.getByTestId(EDITOR_TEST_ID).querySelectorAll('.cm-completionLabel'),
(label) => label.textContent ?? '',
).sort();
return within(screen.getByTestId(EDITOR_TEST_ID))
.queryAllByRole('option')
.map((option) => option.textContent ?? '')
.sort();
}
describe('QueryAggregationSelect field suggestions for an AI query', () => {
@@ -161,9 +159,10 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
async ({ aggregation, fieldDataType, labels }) => {
await enterAggregation(aggregation);
await waitFor(() => expect(suggestionLabels()).toStrictEqual(labels), {
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
timeout: SUGGESTIONS_TIMEOUT_MS,
});
expect(suggestionLabels()).toStrictEqual(labels);
expect(keysRequests).toHaveLength(0);
expect(
aiKeysRequests.map((params) => ({
@@ -185,14 +184,13 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
);
await waitFor(
() =>
expect(suggestionLabels()).toStrictEqual([
'duration_nano',
'trace.total_tokens',
]),
{ timeout: SUGGESTIONS_TIMEOUT_MS },
);
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
timeout: SUGGESTIONS_TIMEOUT_MS,
});
expect(suggestionLabels()).toStrictEqual([
'duration_nano',
'trace.total_tokens',
]);
expect(keysRequests).toHaveLength(0);
},
TEST_TIMEOUT_MS,

View File

@@ -1,13 +1,14 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { render, userEvent, waitFor } from 'tests/test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
import QuerySearch from '../QuerySearch/QuerySearch';
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
import { findCompletionOption } from './findCompletionOption';
import { findQueryEditorTextbox } from './queryEditorTextbox';
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
const CM_OPTION_SELECTOR = '.cm-tooltip-autocomplete .cm-completionLabel';
const EDITOR_TEST_ID = 'query-where-clause-editor';
beforeAll(() => {
mockCodeMirrorDomApis();
@@ -110,11 +111,7 @@ async function renderAndType(text: string): Promise<HTMLElement> {
/>,
);
await waitFor(() => {
expect(document.querySelector(CM_EDITOR_SELECTOR)).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
const editor = await findQueryEditorTextbox();
await userEvent.click(editor);
await userEvent.type(editor, text);
return editor;
@@ -128,32 +125,26 @@ async function typeKeyThenEnterOperatorContext(
): Promise<void> {
const editor = await renderAndType(key);
await waitFor(() => {
expect(visibleOptionLabels()).toContain(expectedKeyLabel);
});
await findCompletionOption(EDITOR_TEST_ID, expectedKeyLabel);
// skipClick: a click would reset the caret to position 0 under the mocked
// DOM rects; we need the space appended at the end of the typed key.
await userEvent.type(editor, ' ', { skipClick: true });
await waitFor(() => {
expect(visibleOptionLabels()).toContain('=');
});
await findCompletionOption(EDITOR_TEST_ID, '=');
}
function visibleOptionLabels(): string[] {
return Array.from(document.querySelectorAll(CM_OPTION_SELECTOR)).map(
(el) => el.textContent ?? '',
);
return within(screen.getByTestId(EDITOR_TEST_ID))
.queryAllByRole('option')
.map((el) => el.textContent ?? '');
}
describe('QuerySearch context-prefixed key suggestions', () => {
it('shows one deduped suggestion per key name in normal mode', async () => {
await renderAndType('statu');
await waitFor(() => {
expect(visibleOptionLabels()).toContain('status.code');
});
await findCompletionOption(EDITOR_TEST_ID, 'status.code');
const statusOptions = visibleOptionLabels().filter(
(label) => label === 'status.code',
@@ -164,9 +155,7 @@ describe('QuerySearch context-prefixed key suggestions', () => {
it('shows context-scoped suggestions for a complete context prefix', async () => {
await renderAndType('attribute.');
await waitFor(() => {
expect(visibleOptionLabels()).toContain('attribute.status.code');
});
await findCompletionOption(EDITOR_TEST_ID, 'attribute.status.code');
const labels = visibleOptionLabels();
// Literal key name match ranks first

View File

@@ -2,7 +2,9 @@ import { EditorView } from '@uiw/react-codemirror';
import { getFieldKeySuggestions } from 'api/querySuggestions/getFieldKeySuggestions';
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
import { initialQueriesMap } from 'constants/queryBuilder';
import { holdResponse } from 'tests/holdResponse';
import {
act,
fireEvent,
render,
screen,
@@ -14,8 +16,9 @@ import { DataSource } from 'types/common/queryBuilder';
import QuerySearch from '../QuerySearch/QuerySearch';
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
import { findQueryEditorTextbox } from './queryEditorTextbox';
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
const EDITOR_TEST_ID = 'query-where-clause-editor';
// Mock DOM APIs that CodeMirror needs
beforeAll(() => {
@@ -75,8 +78,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// CodeMirror renders a contenteditable div, so we check for the container
const editorContainer = document.querySelector('.query-where-clause-editor');
expect(editorContainer).toBeInTheDocument();
expect(screen.getByTestId(EDITOR_TEST_ID)).toBeInTheDocument();
});
it('fetches key suggestions when typing a key (debounced)', async () => {
@@ -94,14 +96,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
// Wait for CodeMirror to initialize
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
// Find the CodeMirror editor contenteditable element
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
const editor = await findQueryEditorTextbox();
// Focus and type into the editor
await userEvent.click(editor);
@@ -141,12 +137,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
const editor = await findQueryEditorTextbox();
await userEvent.click(editor);
await userEvent.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
@@ -162,6 +153,51 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
await expect(screen.findByText('200')).resolves.toBeInTheDocument();
});
it('keeps the value suggestions open when the key suggestions load', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { held, release } = holdResponse();
const mockedGetKeys = jest.mocked(getFieldKeySuggestions);
mockedGetKeys.mockClear();
mockedGetKeys.mockImplementationOnce(async () => {
await held;
return { status: 'success', data: { complete: true, keys: {} } };
});
jest.mocked(getFieldValueSuggestions).mockResolvedValueOnce({
status: 'success',
data: {
complete: true,
values: {
stringValues: ['payment-service'],
numberValues: [],
boolValues: [],
relatedValues: [],
},
},
});
render(
<QuerySearch
onChange={jest.fn()}
queryData={initialQueriesMap.logs.builder.queryData[0]}
dataSource={DataSource.LOGS}
/>,
);
const editor = await findQueryEditorTextbox();
await user.click(editor);
await user.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
await screen.findByText('payment-service');
await waitFor(() => expect(mockedGetKeys).toHaveBeenCalled());
release();
// Outlasts the 10 ms timer QuerySearch uses to reopen suggestions.
await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
// Outlasts the 100 ms CodeMirror waits before it queries suggestions again.
await new Promise((resolve) => setTimeout(resolve, 150));
expect(screen.getByText('payment-service')).toBeInTheDocument();
});
it('fetches key suggestions on mount for LOGS', async () => {
// Use real timers for CodeMirror integration tests
const mockedGetKeysOnMount = getFieldKeySuggestions as jest.MockedFunction<
@@ -203,12 +239,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
const editor = await findQueryEditorTextbox();
await userEvent.click(editor);
await userEvent.type(editor, SAMPLE_STATUS_QUERY);
@@ -255,11 +286,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
await waitFor(() =>
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
SAMPLE_STATUS_QUERY,
),
);
const editor = await findQueryEditorTextbox();
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
await userEvent.click(screen.getByTestId('query-search-run-button'));
@@ -268,7 +296,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
it('shows the locked scope as a chip in place of the scope icon', () => {
const scope = "kind_string = 'Client' AND http_host = 'api.example.com'";
const { container } = render(
render(
<QuerySearch
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
queryData={initialQueriesMap.traces.builder.queryData[0]}
@@ -283,12 +311,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
expect(chip).toHaveTextContent('+1');
expect(chip).not.toHaveTextContent('kind_string');
expect(
container.querySelector('.query-search-initial-scope-label'),
screen.queryByTestId('query-search-initial-scope-label'),
).not.toBeInTheDocument();
});
it('keeps the scope icon unless the chip is asked for', () => {
const { container } = render(
render(
<QuerySearch
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
queryData={initialQueriesMap.traces.builder.queryData[0]}
@@ -301,7 +329,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
screen.queryByTestId('query-search-scope-chip'),
).not.toBeInTheDocument();
expect(
container.querySelector('.query-search-initial-scope-label'),
screen.getByTestId('query-search-initial-scope-label'),
).toBeInTheDocument();
});
@@ -341,11 +369,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
await waitFor(() =>
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
SAMPLE_STATUS_QUERY,
),
);
const editor = await findQueryEditorTextbox();
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
await userEvent.click(screen.getByTestId('query-search-run-button'));
@@ -371,13 +396,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize and the expression to be set
const editorContent = await findQueryEditorTextbox();
await waitFor(
() => {
// CodeMirror stores content in .cm-content, check the text content
const editorContent = document.querySelector(
CM_EDITOR_SELECTOR,
) as HTMLElement;
expect(editorContent).toBeInTheDocument();
// CodeMirror may render the text in multiple ways, check if it contains our expression
const textContent = editorContent.textContent || '';
expect(textContent).toContain('http.status_code');
@@ -412,12 +433,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize with the initial expression
const editorContent = await findQueryEditorTextbox();
await waitFor(
() => {
const editorContent = document.querySelector(
CM_EDITOR_SELECTOR,
) as HTMLElement;
expect(editorContent).toBeInTheDocument();
const textContent = editorContent.textContent || '';
expect(textContent).toBe(initialExpression);
},
@@ -477,11 +495,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
const editorContent = await findQueryEditorTextbox();
await waitFor(
() => {
const editorContent = document.querySelector(
CM_EDITOR_SELECTOR,
) as HTMLElement;
expect(editorContent.textContent || '').toBe(initialExpression);
},
{ timeout: 3000 },

View File

@@ -6,18 +6,22 @@ import {
import { EditorView } from '@uiw/react-codemirror';
import { initialQueriesMap } from 'constants/queryBuilder';
import * as recentQueriesStore from 'lib/recentQueries/recentQueriesStore';
import { fireEvent, render, userEvent, waitFor } from 'tests/test-utils';
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
import { RECENTS_DISPLAY_CAP, RECENTS_SECTION } from '../QuerySearch/constants';
import QuerySearch from '../QuerySearch/QuerySearch';
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
import { findQueryEditorTextbox } from './queryEditorTextbox';
const CM_ROOT_SELECTOR = '.cm-editor';
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
const TOOLTIP_SELECTOR = '.cm-tooltip-autocomplete';
const COMPLETION_LABEL_SELECTOR = '.cm-completionLabel';
const DELETE_BUTTON_SELECTOR = '.cm-recent-delete';
const EDITOR_TEST_ID = 'query-where-clause-editor';
const FRONTEND_FILTER = "service.name = 'frontend'";
const STATUS_CODE_FILTER = "http.status_code = '500'";
@@ -68,7 +72,7 @@ function saveLogsRecent(expression: string): void {
}
function getEditorView(): EditorView | null {
const root = document.querySelector<HTMLElement>(CM_ROOT_SELECTOR);
const root = screen.queryByTestId(EDITOR_TEST_ID);
return root ? EditorView.findFromDOM(root) : null;
}
@@ -98,14 +102,7 @@ async function renderAndFocus(
): Promise<HTMLElement> {
renderLogsSearch(onChange);
const editor = await waitFor(
() => {
const element = document.querySelector(CM_EDITOR_SELECTOR);
expect(element).toBeInTheDocument();
return element as HTMLElement;
},
{ timeout: 2000 },
);
const editor = await findQueryEditorTextbox();
await userEvent.click(editor);
return editor;
@@ -235,9 +232,7 @@ describe('QuerySearch recent searches', () => {
await openRecents();
const option = await waitForPopupElement(() =>
Array.from(
document.querySelectorAll<HTMLElement>(COMPLETION_LABEL_SELECTOR),
).find((element) => element.textContent === FRONTEND_FILTER),
screen.queryByText(FRONTEND_FILTER),
);
// fireEvent: userEvent's pointerdown blurs the editor, closing the popup before CM's mousedown apply.
fireEvent.mouseDown(option);
@@ -253,7 +248,9 @@ describe('QuerySearch recent searches', () => {
await waitFor(
() => {
expect(document.querySelector(TOOLTIP_SELECTOR)).not.toBeInTheDocument();
expect(
within(screen.getByTestId(EDITOR_TEST_ID)).queryByLabelText('Completions'),
).not.toBeInTheDocument();
},
{ timeout: 2000 },
);
@@ -266,7 +263,7 @@ describe('QuerySearch recent searches', () => {
await openRecents();
const deleteButton = await waitForPopupElement(() =>
document.querySelector<HTMLElement>(DELETE_BUTTON_SELECTOR),
screen.queryByTestId('query-search-recent-delete'),
);
// fireEvent: the button preventDefaults pointerdown, which makes userEvent.click drop the mouse chain.

View File

@@ -0,0 +1,14 @@
import { screen, within, type waitForOptions } from 'tests/test-utils';
export function findCompletionOption(
editorTestId: string,
label: string,
options?: waitForOptions,
): Promise<HTMLElement> {
return within(screen.getByTestId(editorTestId)).findByText(
(_, element) =>
element?.getAttribute('role') === 'option' && element.textContent === label,
undefined,
options,
);
}

View File

@@ -0,0 +1,7 @@
import { screen, within } from 'tests/test-utils';
export async function findQueryEditorTextbox(): Promise<HTMLElement> {
return within(
await screen.findByTestId('query-where-clause-editor'),
).getByRole('textbox');
}

View File

@@ -361,7 +361,7 @@ describe('QueryAddOns', () => {
});
it('calls handleSetQueryData when reduce-to value changes', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const query = baseQuery({
reduceTo: ReduceOperators.AVG,
aggregations: [

View File

@@ -1,7 +1,7 @@
import { jest } from '@jest/globals';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { render, screen, userEvent } from 'tests/test-utils';
import { render, screen, userEvent, within } from 'tests/test-utils';
import {
Having,
IBuilderQuery,
@@ -146,7 +146,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
});
it('savePreviousQuery=true: metrics → meter saves previous query in session storage with appropriate key and query', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<QueryBuilderV2
panelType={PANEL_TYPES.TABLE}
@@ -155,9 +155,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
savePreviousQuery
/>,
);
const trigger = document.querySelector(
'.metrics-container .source-selector .ant-select-selector',
) as HTMLElement;
const trigger = within(
screen.getByTestId('metrics-source-selector-0'),
).getByRole('combobox');
await user.click(trigger);
@@ -182,7 +182,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
});
it('savePreviousQuery=false: metrics → meter does not write to sessionStorage and applies defaults', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
// render WITHOUT savePreviousQuery enabled
render(
<QueryBuilderV2
@@ -193,9 +193,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
);
// open Source and choose Meter
const trigger = document.querySelector(
'.metrics-container .source-selector .ant-select-selector',
) as HTMLElement;
const trigger = within(
screen.getByTestId('metrics-source-selector-0'),
).getByRole('combobox');
await user.click(trigger);
const meterOption = await screen.findByText('Meter');
await user.click(meterOption);
@@ -302,7 +302,7 @@ describe('DataSource change - Logs to Traces', () => {
});
it('updates query dataSource to TRACES saves previous query in session storage', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<QueryBuilderV2
@@ -313,19 +313,12 @@ describe('DataSource change - Logs to Traces', () => {
/>,
);
const logsTrigger = document.querySelector(
'.query-data-source .ant-select-selector',
) as HTMLElement;
const logsTrigger = within(
screen.getByTestId('query-data-source-selector-0'),
).getByRole('combobox');
await user.click(logsTrigger);
const tracesContent = screen.getByText('Traces', {
selector: '.ant-select-item-option-content',
});
// click the option (prefer the option element; fallback to content)
await user.click(
(tracesContent.closest('[role="option"]') as HTMLElement) || tracesContent,
);
await user.click(screen.getByTitle('Traces'));
// verify previousQuery store saved the current LOGS snapshot before switch
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);
@@ -337,7 +330,7 @@ describe('DataSource change - Logs to Traces', () => {
);
});
it('updates query dataSource to TRACES does not saves previous query in session storage', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<QueryBuilderV2
@@ -347,19 +340,12 @@ describe('DataSource change - Logs to Traces', () => {
/>,
);
const logsTrigger = document.querySelector(
'.query-data-source .ant-select-selector',
) as HTMLElement;
const logsTrigger = within(
screen.getByTestId('query-data-source-selector-0'),
).getByRole('combobox');
await user.click(logsTrigger);
const tracesContent = screen.getByText('Traces', {
selector: '.ant-select-item-option-content',
});
// click the option (prefer the option element; fallback to content)
await user.click(
(tracesContent.closest('[role="option"]') as HTMLElement) || tracesContent,
);
await user.click(screen.getByTitle('Traces'));
// Assert that no snapshot was written
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);

View File

@@ -197,7 +197,7 @@ export default function CheckboxFilterV2(
onClear={onClear}
/>
{isOpen && isLoading && !hasLoadedOnce.current && (
<section>
<section data-testid="checkbox-filter-skeleton">
<Skeleton paragraph={{ rows: 4 }} />
</section>
)}

View File

@@ -1,5 +1,3 @@
import { useState } from 'react';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import { ChevronDown, ChevronRight, Undo2 } from '@signozhq/icons';
@@ -22,31 +20,6 @@ export function CheckboxFilterV2Header({
onToggleOpen,
onClear,
}: CheckboxFilterHeaderProps): JSX.Element {
const [isTitleTruncated, setIsTitleTruncated] = useState(false);
const measureTitle = (el: HTMLElement | null): void => {
if (el) {
setIsTitleTruncated(el.scrollWidth > el.clientWidth);
}
};
const titleText = (
<Typography
ref={measureTitle}
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
display="inline-block"
minWidth={0}
textOverflow="ellipsis"
textTransform="capitalize"
>
{title}
</Typography>
);
return (
<section
role="button"
@@ -67,7 +40,19 @@ export function CheckboxFilterV2Header({
) : (
<ChevronRight size={13} cursor="pointer" />
)}
<Tooltip title={isTitleTruncated ? title : undefined}>{titleText}</Tooltip>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
display="inline-block"
minWidth={0}
textOverflow="ellipsis"
textTransform="capitalize"
>
{title}
</Typography>
</section>
{isOpen && canReset && (
<section className={styles.rightAction}>

View File

@@ -69,6 +69,7 @@ export function CheckboxFilterV2ValueRow({
<div
role="button"
data-testid={`checkbox-value-button-${value}`}
tabIndex={disabled ? -1 : 0}
className={cx(styles.valueButton, disabled && styles.isDisabled)}
onClick={(): void => {

View File

@@ -1,7 +1,5 @@
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { server, rest } from 'mocks-server/server';
import { render } from 'tests/test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { QuickFiltersSource } from '../../../../types';
@@ -31,11 +29,9 @@ describe('CheckboxFilterV2 - states', () => {
);
expect(screen.getByTestId('checkbox-filter-v2')).toBeInTheDocument();
await waitFor(() => {
expect(
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
).toBeInTheDocument();
});
await expect(
screen.findByTestId('checkbox-filter-skeleton'),
).resolves.toBeInTheDocument();
});
it('shows skeleton when initially closed filter is opened for the first time', async () => {
@@ -54,7 +50,7 @@ describe('CheckboxFilterV2 - states', () => {
// Filter starts closed - no skeleton, no content
expect(
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
screen.queryByTestId('checkbox-filter-skeleton'),
).not.toBeInTheDocument();
expect(
screen.queryByTestId('checkbox-filter-empty'),
@@ -65,11 +61,9 @@ describe('CheckboxFilterV2 - states', () => {
await user.click(header);
// Should show skeleton while loading, NOT "No values found"
await waitFor(() => {
expect(
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
).toBeInTheDocument();
});
await expect(
screen.findByTestId('checkbox-filter-skeleton'),
).resolves.toBeInTheDocument();
expect(
screen.queryByTestId('checkbox-filter-empty'),
).not.toBeInTheDocument();

View File

@@ -120,43 +120,4 @@ describe('CheckboxFilterV2Header', () => {
expect(onToggleOpen).not.toHaveBeenCalled();
});
});
describe('title tooltip', () => {
// jsdom has no layout, so truncation is simulated at the prototype level
// before mount (the component measures in a layout effect).
function mockTitleWidths(scrollWidth: number, clientWidth: number): void {
jest
.spyOn(HTMLElement.prototype, 'scrollWidth', 'get')
.mockReturnValue(scrollWidth);
jest
.spyOn(HTMLElement.prototype, 'clientWidth', 'get')
.mockReturnValue(clientWidth);
}
afterEach(() => {
jest.restoreAllMocks();
});
it('shows the full name on hover when the title is truncated', async () => {
mockTitleWidths(200, 100);
const user = userEvent.setup();
render(<CheckboxFilterV2Header {...defaultProps} />);
await user.hover(screen.getByText(defaultProps.title));
await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
defaultProps.title,
);
});
it('shows no tooltip when the title fits', async () => {
mockTitleWidths(100, 100);
const user = userEvent.setup();
render(<CheckboxFilterV2Header {...defaultProps} />);
await user.hover(screen.getByText(defaultProps.title));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
});
});
});

View File

@@ -1,10 +1,14 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ComponentProps } from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import { BadgeConfig } from '../itemRules';
import { CheckedState } from '../../../../types';
import { CheckboxFilterV2ValueRow } from '../CheckboxFilterV2ValueRow';
type OnOnlyOrAllClick = ComponentProps<
typeof CheckboxFilterV2ValueRow
>['onOnlyOrAllClick'];
describe('CheckboxFilterV2ValueRow', () => {
const defaultProps = {
value: 'production',
@@ -111,7 +115,7 @@ describe('CheckboxFilterV2ValueRow', () => {
it('does not call onOnlyOrAllClick when disabled + clicked', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -127,7 +131,7 @@ describe('CheckboxFilterV2ValueRow', () => {
it('does not call onOnlyOrAllClick on keydown when disabled', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -181,7 +185,7 @@ describe('CheckboxFilterV2ValueRow', () => {
it('calls onOnlyOrAllClick on value text click', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -196,7 +200,7 @@ describe('CheckboxFilterV2ValueRow', () => {
it('calls onOnlyOrAllClick on Enter key', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -204,21 +208,17 @@ describe('CheckboxFilterV2ValueRow', () => {
/>,
);
const valueButton = screen
.getByText('production')
.closest('[role="button"]');
await user.tab();
await user.tab();
if (valueButton && document.activeElement === valueButton) {
await user.keyboard('{Enter}');
}
expect(screen.getByTestId('checkbox-value-button-production')).toHaveFocus();
await user.keyboard('{Enter}');
expect(onOnlyOrAllClick).toHaveBeenCalled();
expect(onOnlyOrAllClick).toHaveBeenCalledTimes(1);
});
it('calls onOnlyOrAllClick on Space key', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -226,16 +226,12 @@ describe('CheckboxFilterV2ValueRow', () => {
/>,
);
const valueButton = screen
.getByText('production')
.closest('[role="button"]');
await user.tab();
await user.tab();
if (valueButton && document.activeElement === valueButton) {
await user.keyboard(' ');
}
expect(screen.getByTestId('checkbox-value-button-production')).toHaveFocus();
await user.keyboard(' ');
expect(onOnlyOrAllClick).toHaveBeenCalled();
expect(onOnlyOrAllClick).toHaveBeenCalledTimes(1);
});
it('shows Toggle button', () => {

View File

@@ -377,7 +377,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
);
const filtersSkeleton = (
<div className="quick-filters-skeleton">
<div className="quick-filters-skeleton" data-testid="quick-filters-skeleton">
{Array.from({ length: 5 }).map((_, index) => (
// eslint-disable-next-line react/no-array-index-key
<Skeleton.Input active size="small" key={index} />

View File

@@ -114,6 +114,19 @@ export const loadingFiltersHandlers = [
),
];
export const longTitleConfig = [
{
attributeKey: {
dataType: DataTypes.Int64,
key: 'http.request.content_length_uncompressed',
type: 'tag',
},
defaultOpen: false,
title: 'Http Request Content Length Uncompressed',
type: FiltersType.CHECKBOX,
},
];
export const LONG_FILTER_VALUES = [
'checkout-service.production-eu-central-1.svc.cluster.local',
'payments-authorisation-worker.production-us-east-2.svc.cluster.local',

View File

@@ -8,6 +8,7 @@ import type { GlobalMockArgs } from '@/storybook/globals';
import QuickFilters from '../QuickFilters';
import {
dirtySettings,
hoverTruncatedTitle,
openQueryPicker,
openSettings,
} from './__story_mockdata__/quickFilters.play';
@@ -18,6 +19,7 @@ import {
handlers,
LONG_FILTER_VALUES,
loadingFiltersHandlers,
longTitleConfig,
MANY_FILTER_VALUES,
queryBuilder,
selectedServiceQueryBuilder,
@@ -159,6 +161,15 @@ export const Tooltips: GlobalArgsStory = {
},
};
/** A section title too long for the rail: hovering it shows the full title once. */
export const TruncatedTitle: GlobalArgsStory = {
args: { config: longTitleConfig },
parameters: {
msw: { handlers: [noSavedFiltersHandler, ...handlers] },
},
play: hoverTruncatedTitle,
};
const [firstQuery] = queryBuilder.currentQuery.builder.queryData;
/** Interaction: the query picker lists every query the filters can follow. */

View File

@@ -8,9 +8,12 @@ import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissio
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import { hoverTruncatableText } from '@/storybook/play/truncatedText';
import type { GlobalMockArgs } from '@/storybook/globals';
import type QuickFilters from '../../QuickFilters';
import { longTitleConfig } from '../QuickFilters.stories.mocks';
import { FiltersType } from '../../types';
interface PlayContext {
canvasElement: HTMLElement;
@@ -61,6 +64,26 @@ export const dirtySettings = async (context: PlayContext): Promise<void> => {
await screen.findByRole('button', { name: 'Save changes' });
};
export const hoverTruncatedTitle = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
const [filter] = args.config ?? [];
// Duration and slider sections render no title of their own.
if (filter?.type !== FiltersType.CHECKBOX || !filter.title) {
return;
}
const [label] = await within(canvasElement).findAllByText(
filter.title,
{},
UNTIL_LOADED,
);
await hoverTruncatableText(label, filter.title, {
cut: filter.title === longTitleConfig[0].title || undefined,
});
};
export const openQueryPicker = async ({
canvasElement,
}: PlayContext): Promise<void> => {

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