Compare commits

...

3 Commits

Author SHA1 Message Date
Vinícius Lourenço
2c3cafdaf7 chore(claude): replace cursor rules and add lessons from greptile reviews 2026-10-30 15:22:59 -03:00
Vinícius Lourenço
ef0f732d3b fix(tests): render children in the test harness wrapper 2026-10-30 15:22:50 -03:00
Vinicius Lourenço
b37231f31a fix(saved-views): remove loading effect from authz checks (#13287)
Some checks failed
build-staging / prepare (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (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
<!--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

This basically does two fixes:
- Remove loading effect
- The effect was not looking good, this was implemented during the
migration of components.
- Remove read checks for each item
- We should not have loading for each item in the list, against our
guidelines for authz
- The list already returns the info needed in read, redundant to have
both checks
- Replace the button with a link
  - To improve UX of this views, they were suppose to act as links.

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

Closes https://github.com/SigNoz/uforge-pod/issues/6394

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

Normal view:
<img width="1680" height="1224"
alt="dark--components-saved-views-authz--no-read-open-view--blink (1)"
src="https://github.com/user-attachments/assets/68772cda-11f1-4798-8012-79bfe685cbcd"
/>

No read only:
<img width="1680" height="1224"
alt="dark--components-saved-views-overview--unsaved-changes--blink (1)"
src="https://github.com/user-attachments/assets/898ab59a-f870-4d7c-8c2a-e20843f98444"
/>

Long names:
<img width="1680" height="1224"
alt="dark--components-saved-views-overview--long-names--blink (1)"
src="https://github.com/user-attachments/assets/48a4bd61-8335-4047-8c2a-eca42c43653e"
/>

No read only 2:
<img width="1680" height="1224"
alt="dark--components-saved-views-authz--no-read--blink (1)"
src="https://github.com/user-attachments/assets/af04bb90-1ce7-4c36-818b-49e26933ea0b"
/>


Full diff:
https://claude.ai/artifact/S43YyxbMmCdtZLmEXVNsgm?sk=LXctCOiBiN5kGigap2M_JA
2026-10-30 16:53:33 +00:00
54 changed files with 1086 additions and 586 deletions

View File

@@ -4,9 +4,9 @@ Applies to everything in the repo — code, config, workflows.
- **No unnecessary comments.** Do not comment where the code is self-explanatory; never restate what the code already says.
- **Document only** non-obvious behavior, constraints, formats, and edge cases.
- **Rationale goes in prose, not source.** Why a version is pinned, why a job exists, how a subsystem fits together — that belongs in the README or the PR.
- **Never remove pre-existing comments** when editing code. The bar above applies to comments you write, not comments already there.
- **Never talk to the reviewer.** No comments about where a change came from, what was changed, or why the change is correct — that belongs in the PR description and is noise the moment it merges.
- **Rationale goes in prose, not source.** Why a job exists, how a subsystem fits together: that belongs in the README or the PR. Exception: a config entry that would look like a mistake without its reason (a pinned version, a trust or lint exclusion) keeps a short reason next to it.
- **Never remove pre-existing comments** when editing code. The bar above applies to comments you write, not comments already there. When the code a comment describes changes, update the comment; when that code is deleted, delete the comment with it.
- **Never talk to the reviewer.** No comments about where a change came from, what was changed, or why the change is correct — that belongs in the PR description and is noise the moment it merges. A banner a skill requires (the AI-owned banner on story mocks and `tests/e2e/drivers/`) tells maintainers how the file is made; keep it.
- **Less is more.** When writing something intended for human consumption, (comment, commit message, reply to prompt) use as few words as possible. Pick every word meticulously to reduce the volume to a strict minimum. Be down to the point. Less is more.
Language rules build on this one: [`go-comments`](go-comments.md), [`py-comments`](py-comments.md).

View File

@@ -0,0 +1,40 @@
---
paths:
- "frontend/src/**/*.ts"
- "frontend/src/**/*.tsx"
---
# Frontend state
Pick the store by what the state is. Never add Redux or React Context for shared state; to move existing Redux or Context state, use the `migrate-state-management` skill ([`frontend/.claude/skills/migrate-state-management/SKILL.md`](../../frontend/.claude/skills/migrate-state-management/SKILL.md)).
| State | Use | Never |
|---|---|---|
| Server / API data | React Query, generated hooks from `src/api/generated` | a copy in Redux, Context or Zustand |
| Shareable: filters, time range, selection, page | nuqs (`useQueryState` with a parser) | Redux, Context, hand-parsed `useSearchParams` |
| Global client state | a small Zustand store per domain | Redux, Context |
| One component's UI state | `useState` / `useReducer` | any store |
## Server state
- Expose a query through a hook that returns its result plus memoized derived values. Never dispatch a response into another store.
- **The query key holds every value the request reads.** A field change that alters the request (name, context, data type) must change the key; a lossy signature serves stale rows.
## URL state
- Keep the URL small (Chrome trims near 2k characters). No large datasets, no sensitive data.
- **A rewrite touches only the params it owns.** Repairing or normalising one param keeps the rest (`activeLogId`, pagination) as they were.
- **Links carry the current time range.** A row link, "open in new tab" and "copy link" land on the same period as an in-app click.
- **A preset read from the URL applies once.** A later user change or reset must not re-apply it.
## Zustand
- One `create()` per module; split a large store into slice factories combined in that one `create()`.
- Always read through a selector: `useDashboardStore((s) => s.isDashboardLocked)`, never `useDashboardStore()`.
- Update only through `set`; never mutate state. State fields before actions in the store object.
- Hooks never call `useStore.getState()` (`signoz/no-zustand-getstate-in-hooks`); export standalone actions instead.
## Local and form state
- **Editable state starts from saved data once.** Initialise the form from the saved value, then let the user own it; never re-derive it from saved data on each render.
- **A mode switch owns its in-flight work.** While a request from one mode runs, disable the switch or drop the result when the mode changes, so it can't close or overwrite the new mode.

View File

@@ -0,0 +1,20 @@
---
paths:
- "frontend/src/**/*.test.ts"
- "frontend/src/**/*.test.tsx"
---
# Frontend tests
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.
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `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__`.
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.

View File

@@ -9,3 +9,5 @@
- **Keep the commit body short and human readable** focused on decision made if any. Commit body must not re-iterate the changes done, skip if title is sufficient in conveying the change.
- **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.
- **Answer every review thread.** Reply with the commit that fixes it (`Fixed in 4df6f3198d: <what changed>`) or the reason it stays, then resolve. Never resolve a thread with neither: Greptile withdraws a finding, and remembers it, only when told why.

View File

@@ -10,6 +10,9 @@ Page stories are written with the `signoz-page-story` skill ([`.claude/skills/si
- **A UI change lands with its story.** Any change that alters what a page renders — a new page, a new state, a new branch, a changed layout — updates the story of every page that renders it, or creates one where the page has none. Go through the `signoz-page-story` skill; never hand-write a page story outside it.
- **New page, new story. New state, new control or variant.** The skill decides which: a control on a response, a variant worth linking to, or a `play` story for a state only a click reaches.
- **A shared component is covered through its pages.** A change under `components/` or `container/` with no story of its own updates the stories of the pages that render it.
- **Plays live with the mocks.** A `play` is a named function exported from `stories/__story_mockdata__/<page>.play.ts`, which is collapsed for review like the rest of the AI-owned mocks. The story file only names it: `play: openEditDrawer`. A story file that still holds play bodies moves them there the first time you edit it.
- **A play passes for every control value.** Branch each check on the args it depends on (panel kind, data state, row count, hidden header). A value the page supports must never fail the play.
- **Mocks answer every request a reachable state makes.** Selecting a row, opening a view or switching a tab that fetches more hits a handler, never the 501 catch-all.
- **Already covered, say so.** When the existing story and its controls already reach the changed state, no story edit is needed; state that in the PR description.
- **Opt out only when there is no visual diff.** Skip stories only when the change renders nothing differently: types, api clients, hooks with no UI branch, tests. Deleting a page deletes its stories.
- **Prove it with a visual diff when asked.** Before/after screenshots and "did this touch other screens" go through `sbshot-visual-diff`, which can only show what a story renders.

View File

@@ -115,8 +115,8 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
- **A variant earns a story only when it is worth linking to**: an empty workspace, a viewer, a page mid-load. Everything else stays a control.
- **Endpoints the page owns go through `response.json`**, so the Data control covers loaded, loading and failed in one declaration. Endpoints the page cannot render without (ingestion detection, preferences, feature payloads) take a plain resolver so the shell survives the loading and error states.
- **Query-param state starts from `route`** (`/logs?tab=explorer`). In-page param navigation works inside a story; a different pathname is blocked and reported by the overlay. A control for a param is worth it only when the param is a page mode someone would want to flip.
- **File layout**: every story file for a page lives under `src/pages/<Page>/stories/`: `<Page>.stories.tsx`, `<Page>.stories.mocks.tsx`, payload builders in `stories/__story_mockdata__/<page>.ts`. Nothing page-specific in `src/storybook/controls/`. A page that is a tab strip over several routes gets one story file per tab, in its own folder under the module page (`LogsModulePage/Pipelines/stories/Pipelines.stories.tsx`), each with its own mocks and `__story_mockdata__/`; the builders more than one tab needs stay in the module page's own `stories/__story_mockdata__/` (`AlertList/stories/__story_mockdata__/alerts.ts`), which a tab reaches as `../../stories/__story_mockdata__/alerts`. Every one of them renders the module page, so the tab strip is there, and the `route` its mocks return decides which tab is open. A page's permission stories go one level further down, in `stories/authz/<Page>.authz.stories.tsx`, on the page's own mocks: see **Permission stories**.
- **A state only a click reaches is a story with a `play` function**, not a control: a drawer, a modal, an edit mode the page holds in component state. Drive it with `userEvent` and the queries from `storybook/test`, take the first of a repeated row action, and wait on the state's own text. The page fetches before it renders a row, so the finder needs a timeout past the 1s default. A state the app drops again on its own, such as one keyed on an array identity that a refetch replaces, does not get a story: it would not survive being looked at. A _sequence_ of such states, a wizard's steps or a questionnaire's pages, is still a control: declare the steps in the mocks module and walk them from a `play` on the meta that destructures `mount`, which is what makes Storybook replay it on an arg change. See [references/controls.md](references/controls.md).
- **File layout**: every story file for a page lives under `src/pages/<Page>/stories/`: `<Page>.stories.tsx`, `<Page>.stories.mocks.tsx`, payload builders in `stories/__story_mockdata__/<page>.ts`, play functions in `stories/__story_mockdata__/<page>.play.ts`. Nothing page-specific in `src/storybook/controls/`. A page that is a tab strip over several routes gets one story file per tab, in its own folder under the module page (`LogsModulePage/Pipelines/stories/Pipelines.stories.tsx`), each with its own mocks and `__story_mockdata__/`; the builders more than one tab needs stay in the module page's own `stories/__story_mockdata__/` (`AlertList/stories/__story_mockdata__/alerts.ts`), which a tab reaches as `../../stories/__story_mockdata__/alerts`. Every one of them renders the module page, so the tab strip is there, and the `route` its mocks return decides which tab is open. A page's permission stories go one level further down, in `stories/authz/<Page>.authz.stories.tsx`, on the page's own mocks: see **Permission stories**.
- **A state only a click reaches is a story with a `play` function**, not a control: a drawer, a modal, an edit mode the page holds in component state. Drive it with `userEvent` and the queries from `storybook/test`, take the first of a repeated row action, and wait on the state's own text. The page fetches before it renders a row, so the finder needs a timeout past the 1s default. The play is a named function exported from `__story_mockdata__/<page>.play.ts` and the story file only names it (`play: openEditDrawer`), so the reviewer reads states, not clicks; a story file that still holds play bodies moves them there the first time you edit it. It branches every check on the args it depends on: a control value the page supports never fails it. A state the app drops again on its own, such as one keyed on an array identity that a refetch replaces, does not get a story: it would not survive being looked at. A _sequence_ of such states, a wizard's steps or a questionnaire's pages, is still a control: declare the steps in the mocks module and walk them from a `play` on the meta that destructures `mount`, which is what makes Storybook replay it on an arg change. See [references/controls.md](references/controls.md).
- **The mocks are AI-owned and say so.** `<Page>.stories.mocks.tsx` and every file under a `__story_mockdata__/` open with this banner, above the imports:
```ts
@@ -143,6 +143,8 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
- [ ] a page tagged `authz` has its `Authz` folder: one story per permission it reads, each reached by `revoked`, none of them a role preset, and each one checked by the `disabled` state of what the permission gates
- [ ] the mocks module and every `__story_mockdata__` file carry the AI-owned banner
- [ ] every control flipped once, its effect seen on screen
- [ ] every play passes with each control value its story exposes, and the story file holds no play body
- [ ] every request a reachable state makes (a selected row, an opened view, a switched tab) has a handler
- [ ] console clean: no `[storybook] no msw handler`, no 501, no msw unhandled request, no React warning
- [ ] no navigation overlay on mount
- [ ] `pnpm tsgo --noEmit`, `pnpm exec oxlint <files>`, `pnpm exec oxfmt --check <files>` all clean. The repo has no prettier: `pnpm exec prettier` prints a pass while exiting 254

View File

@@ -146,5 +146,5 @@ Do not use Zustand, Redux, or Context for purely local UI state.
## Additional resources
- Project rule: [.cursor/rules/state-management.mdc](../../rules/state-management.mdc)
- Project rule: [.claude/rules/frontend-state.md](../../../../.claude/rules/frontend-state.md)
- Detailed patterns and rationale: [reference.md](reference.md)

View File

@@ -1,97 +0,0 @@
---
globs: **/*.store.ts
alwaysApply: false
---
# State Management: React Query, nuqs, Zustand
Use the following stack. Do **not** introduce or recommend Redux or React Context for shared/global state.
## Server state → React Query
- **Use for:** API responses, time-series data, caching, background refetch, retries, stale/refresh.
- **Do not use Redux/Context** to store or mirror data that comes from React Query (e.g. do not dispatch API results into Redux).
- Prefer generated React Query hooks from `frontend/src/api/generated` when available.
- Keep server state in React Query; expose it via hooks that return the query result (and optionally memoized derived values). Do not duplicate it in Redux or Context.
```tsx
// ✅ GOOD: single source of truth from React Query
export function useAppStateHook() {
const { data, isError } = useQuery(...)
const memoizedConfigs = useMemo(() => ({ ... }), [data?.configs])
return { configs: memoizedConfigs, isError, ... }
}
// ❌ BAD: copying React Query result into Redux
dispatch({ type: UPDATE_LATEST_VERSION, payload: queryResponse.data })
```
## URL state → nuqs
- **Use for:** shareable state, filters, time range, selected values, pagination, view state that belongs in the URL.
- **Do not use Redux/Context** for state that should be shareable or reflected in the URL.
- Use [nuqs](https://nuqs.dev/docs/basic-usage) for typed, type-safe URL search params. Avoid ad-hoc `useSearchParams` encoding/decoding.
- Keep URL payload small; respect browser URL length limits (e.g. Chrome ~2k chars). Do not put large datasets or sensitive data in query params.
```tsx
// ✅ GOOD: nuqs for filters / time range / selection
const [timeRange, setTimeRange] = useQueryState('timeRange', parseAsString.withDefault('1h'))
const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1))
// ❌ BAD: Redux/Context for shareable or URL-synced state
const { timeRange } = useContext(SomeContext)
```
## Client state → Zustand
- **Use for:** global/client state, cross-component state, feature flags, complex or large client objects (e.g. dashboard state, query builder state).
- **Do not use Redux or React Context** for global or feature-level client state.
- Prefer small, domain-scoped stores (e.g. DashboardStore, QueryBuilderStore).
### Zustand best practices (align with eslint-plugin-zustand-rules)
- **One store per module.** Do not define multiple `create()` calls in the same file; use one store per module (or compose slices into one store).
- **Always use selectors.** Call the store hook with a selector so only the used slice triggers re-renders. Never use `useStore()` with no selector.
```tsx
// ✅ GOOD: selector — re-renders only when isDashboardLocked changes
const isLocked = useDashboardStore(state => state.isDashboardLocked)
// ❌ BAD: no selector — re-renders on any store change
const state = useDashboardStore()
```
- **Never mutate state directly.** Update only via `set` or `setState` (or `getState()` + `set` for reads). No `state.foo = x` or `state.bears += 1` inside actions.
```tsx
// ✅ GOOD: use set
increment: () => set(state => ({ bears: state.bears + 1 }))
// ❌ BAD: direct mutation
increment: () => { state.bears += 1 }
```
- **State properties before actions.** In the store object, list all state fields first, then action functions.
- **Split into slices when state is large.** If a store has many top-level properties (e.g. more than 5–10), split into slice factories and combine with one `create()`.
```tsx
// ✅ GOOD: slices for large state
const createBearSlice = set => ({ bears: 0, addBear: () => set(s => ({ bears: s.bears + 1 })) })
const createFishSlice = set => ({ fish: 0, addFish: () => set(s => ({ fish: s.fish + 1 })) })
const useStore = create(set => ({ ...createBearSlice(set), ...createFishSlice(set) }))
```
- **In projects using Zustand:** add `eslint-plugin-zustand-rules` and extend `plugin:zustand-rules/recommended` to enforce these rules automatically.
## Local state → React state only
- **Use useState/useReducer** for: component-local UI state, form inputs, toggles, hover state, data that never leaves the component.
- Do not use Zustand, Redux, or Context for state that is purely local to one component or a small subtree.
## Summary
| State type | Use | Avoid |
|-------------------|------------------|--------------------|
| Server / API | React Query | Redux, Context |
| URL / shareable | nuqs | Redux, Context |
| Global client | Zustand | Redux, Context |
| Local UI | useState/useReducer | Zustand, Redux, Context |

View File

@@ -1,74 +0,0 @@
---
description: Core testing conventions - imports, rendering, MSW, interactions, queries
globs: **/*.test.{ts,tsx}
alwaysApply: false
---
# Testing Conventions
## Imports
Always import from the test harness, never directly from `@testing-library/react`:
```ts
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { server, rest } from 'mocks-server/server';
```
## Router
Use the built-in router in `render`:
```ts
render(<Page />, undefined, { initialRoute: '/traces-explorer' });
```
Only mock `useLocation` / `useParams` if the test depends on their values.
## MSW
Global MSW server runs automatically. Override per-test:
```ts
server.use(
rest.get('*/api/v1/foo', (_req, res, ctx) =>
res(ctx.status(200), ctx.json({ ok: true })))
);
```
Keep large response fixtures in `mocks-server/__mockdata_`.
## Interactions
- Prefer `userEvent` for real user interactions (click, type, select, tab).
- Use `fireEvent` only for low-level events not covered by `userEvent` (e.g., scroll, resize). Wrap in `act(...)` if needed.
- Always `await` interactions:
```ts
const user = userEvent.setup({ pointerEventsCheck: 0 });
await user.click(screen.getByRole('button', { name: /save/i }));
```
## Timers
No global fake timers. Per-test only, for debounce/throttle:
```ts
jest.useFakeTimers();
const user = userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) });
await user.type(screen.getByRole('textbox'), 'query');
jest.advanceTimersByTime(400);
jest.useRealTimers();
```
## Queries
Prefer accessible queries: `getByRole` > `findByRole` > `getByLabelText` > visible text > `data-testid` (last resort).
## Anti-patterns
- Never import from `@testing-library/react` directly
- Never use global fake timers
- Never wrap `render` in `act(...)`
- Never mock infra dependencies locally (router, react-query)
- Limit to 3-5 focused tests per file

View File

@@ -1,54 +0,0 @@
---
description: When to use global vs local mocks in tests
globs: **/*.test.{ts,tsx}
alwaysApply: false
---
# Mock Strategy
## Use Global Mocks For
High-frequency dependencies (20+ test files):
- Core infrastructure: react-router-dom, react-query, antd
- Browser APIs: ResizeObserver, matchMedia, localStorage
- Utility libraries: date-fns, lodash
Available global mock files (from jest.config.ts):
- `uplot` -> `__mocks__/uplotMock.ts`
## Use Local Mocks For
- Business logic dependencies (API endpoints, custom hooks, domain components)
- Test-specific behavior (different data per test, error scenarios, loading states)
## Decision Tree
```
Used in 20+ test files?
YES -> Global mock
NO -> Business logic or test-specific?
YES -> Local mock
NO -> Consider global if usage grows
```
## Correct Usage
```ts
// Global mocks are already available - just import
import { useLocation } from 'react-router-dom';
// Local mocks for business logic
jest.mock('../api/tracesService', () => ({
getTraces: jest.fn(() => mockTracesData),
}));
```
## Anti-patterns
```ts
// Never re-mock globally mocked dependencies locally
jest.mock('react-router-dom', () => ({ ... }));
// Never put test-specific data in global mocks
jest.mock('../api/tracesService', () => ({ getTraces: jest.fn(() => specificTestData) }));
```

View File

@@ -1,54 +0,0 @@
---
description: TypeScript type safety requirements for Jest tests
globs: **/*.test.{ts,tsx}
alwaysApply: false
---
# TypeScript Type Safety in Tests
All Jest tests must be fully type-safe. Never use `any`.
## Mock Function Typing
```ts
// Use jest.mocked for module mocks
import useFoo from 'hooks/useFoo';
jest.mock('hooks/useFoo');
const mockUseFoo = jest.mocked(useFoo);
// Use jest.MockedFunction for standalone mocks
const mockFetch = jest.fn() as jest.MockedFunction<(id: number) => Promise<User>>;
```
## Mock Data
Define interfaces for all mock data:
```ts
const mockUser: User = { id: 1, name: 'John', email: 'john@example.com' };
const mockProps: ComponentProps = {
title: 'Test',
data: [mockUser],
onSelect: jest.fn() as jest.MockedFunction<(user: User) => void>,
};
```
## Hook Mocking Pattern
```ts
import useFoo from 'hooks/useFoo';
jest.mock('hooks/useFoo');
const mockUseFoo = jest.mocked(useFoo);
mockUseFoo.mockReturnValue(/* minimal shape */);
```
Prefer helpers (`rqSuccess`, `rqLoading`, `rqError`) for React Query results.
## Checklist
- All mock functions use `jest.MockedFunction<T>` or `jest.mocked()`
- All mock data has proper interfaces
- No `any` types in test files
- Component props are typed
- API response types are defined

View File

@@ -1,19 +0,0 @@
---
description: Prefer SigNoz UI and icons across frontend code
globs: **/*.{ts,tsx,js,jsx}
alwaysApply: true
---
# UI Components and Icons Source of Truth
For all frontend implementation work in this repository:
- Always use UI primitives/components from `@signozhq/ui`.
- Always use icons from `@signozhq/icons`.
- Do not introduce new usage of icon libraries directly (for example `lucide-react`) in app code.
- Do not mix multiple component systems for the same UI surface when an equivalent exists in `@signozhq/ui`.
## Migration guidance
- If touching a file that already uses non-`@signozhq/icons` icons, prefer migrating that file to `@signozhq/icons` as part of the same change when practical.
- If a required component or icon is missing from SigNoz packages, call this out explicitly in the PR/summary before introducing alternatives.

View File

@@ -25,8 +25,14 @@ You are operating within a constrained context window and strict system prompts.
- Never create barrel files.
- When writing new css, prefer CSS Modules
- Use ./docs/css-modules-guide.md as reference on how to write good CSS Modules.
- UI primitives come from `@signozhq/ui` (subpath imports) and icons from `@signozhq/icons`. No new `antd` component or direct icon library (`lucide-react`) where `@signozhq/ui` has an equivalent; `signoz/no-antd-components` enforces part of this list.
- Exception: a control added beside `antd` siblings of the same kind (a tab in an `antd` tab strip) matches them until that surface migrates. Say so in the PR.
- When `@signozhq/ui` or `@signozhq/icons` lacks what you need, say so in the PR before reaching for another library.
- Before styling a `@signozhq/ui` component, check its props in `node_modules/@signozhq/ui/dist/<component>/*.d.ts` for `className`/`style` support; some omit them. Avoid overriding the component's CSS vars unless explicitly needed.
- When writing code that could need authorization checks, read ./src/lib/authz/README.md
- A flow that gains a request also gates on that request's permission: a rename that now reads the view first needs `read` as well as `update`.
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. You are FORBIDDEN from reporting a task as complete until you have:
- Run `pnpm tsgo --noEmit`
@@ -34,6 +40,8 @@ You are operating within a constrained context window and strict system prompts.
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
- Run `pnpm build`
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run.
- For every test you added or changed, revert the change it covers and confirm the test fails
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
- Fixed ALL resulting errors
4. BEHAVIOR CHANGE DETECTION: When modifying existing behavior:
@@ -41,6 +49,14 @@ You are operating within a constrained context window and strict system prompts.
- Update test assertions to match new behavior
- If no tests exist, add them BEFORE changing behavior
## Repo Rules
Claude Code loads `../.claude/rules/` on its own. Other agents read the matching file before editing:
- Every file: [comments](../.claude/rules/comments.md), [pull requests](../.claude/rules/pull-requests.md)
- `src/**/*.ts(x)` that holds state, a query, URL params or a form: [frontend state](../.claude/rules/frontend-state.md)
- `*.test.ts(x)`: [frontend tests](../.claude/rules/frontend-tests.md)
- `*.tsx` that changes what a page renders: [storybook](../.claude/rules/storybook.md)
## Context Management
1. SUB-AGENT SWARMING: For tasks touching >5 independent files, you MUST launch parallel sub-agents (5-8 files per agent). Each agent gets its own context window. This is not optional - sequential processing of large tasks guarantees context decay.

View File

@@ -1,6 +1,6 @@
import { useCallback, useState } from 'react';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Dot } from '@signozhq/icons';
import { Dot, Globe, Inbox, SquarePen } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import Noz from 'components/Noz/Noz';
@@ -16,7 +16,6 @@ import {
import { selectPendingUserInputStreamCount } from 'container/AIAssistant/store/pendingInputSelectors';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { Globe, Inbox, SquarePen } from '@signozhq/icons';
import AnnouncementsModal from './AnnouncementsModal';
import FeedbackModal from './FeedbackModal';

View File

@@ -18,11 +18,9 @@ import {
import ROUTES from 'constants/routes';
import { navigate } from 'lib/router/navigation';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { DataSource } from 'types/common/queryBuilder';
import {
buildExplorerNavigationUrl,
findSavedViewInLists,
openSavedView,
openSavedViewByKey,
@@ -232,23 +230,6 @@ describe('findSavedViewInLists', () => {
});
});
describe('buildExplorerNavigationUrl', () => {
it('encodes composite query and view selectors', () => {
const url = buildExplorerNavigationUrl(
ROUTES.LOGS_EXPLORER,
{ queryType: 'builder' } as never,
{
[QueryParams.panelTypes]: PANEL_TYPES.LIST,
[QueryParams.viewKey]: 'view-1',
},
);
expect(url).toContain(ROUTES.LOGS_EXPLORER);
expect(url).toContain(`${QueryParams.compositeQuery}=`);
expect(url).toContain(`${QueryParams.viewKey}=`);
});
});
describe('openSavedView', () => {
beforeEach(() => {
mockedNavigate.mockClear();

View File

@@ -12,7 +12,7 @@ import { toSavedViewSource } from 'container/SavedViews/utils/toSavedViewSource'
import { SOURCEPAGE_VS_ROUTES } from 'container/SavedViews/constants';
import { navigate } from 'lib/router/navigation';
import { DataSource } from 'types/common/queryBuilder';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { buildExplorerNavigationUrl } from 'utils/buildExplorerNavigationUrl';
type SavedViewSourceHint = SavedViewSourcePage;
@@ -72,26 +72,6 @@ export function explorerRouteForSourcePage(
return SOURCEPAGE_VS_ROUTES[sourcePage] ?? null;
}
/**
* Builds an explorer URL the same way `redirectWithQueryBuilderData` does —
* without inheriting stale query params from the current page's `urlQuery`.
*/
export function buildExplorerNavigationUrl(
route: string,
query: Query,
searchParams: Record<string, unknown>,
): string {
const params = new URLSearchParams();
params.set(
QueryParams.compositeQuery,
encodeURIComponent(JSON.stringify(query)),
);
Object.entries(searchParams).forEach(([key, value]) => {
params.set(key, JSON.stringify(value));
});
return `${route}?${params.toString()}`;
}
export function openSavedView(view: SavedviewtypesSavedViewDTO): void {
const route = view.source ? explorerRouteForSourcePage(view.source) : null;
if (!route) {

View File

@@ -38,8 +38,7 @@ import { useAppContext } from 'providers/App/App';
import { UserPreference } from 'types/api/preferences/preference';
import { DataSource } from 'types/common/queryBuilder';
import { USER_ROLES } from 'types/roles';
import { isIngestionActive } from 'utils/app';
import { isModifierKeyPressed } from 'utils/app';
import { isIngestionActive, isModifierKeyPressed } from 'utils/app';
import { popupContainer } from 'utils/selectPopupContainer';
import crackerUrl from '@/assets/Icons/cracker.svg';

View File

@@ -77,6 +77,11 @@
word-break: break-all;
}
.error {
color: var(--l2-foreground);
font-size: var(--periscope-font-size-base);
}
.noFilters {
color: var(--l3-foreground);
font-size: var(--periscope-font-size-base);

View File

@@ -1,13 +1,8 @@
import { CalendarClock } from '@signozhq/icons';
import { Popover, PopoverAnchor, PopoverContent } from '@signozhq/ui/popover';
import { useMemo } from 'react';
import { Typography } from '@signozhq/ui/typography';
import CopyButton from 'periscope/components/CopyButton/CopyButton';
import { useTimezone } from 'providers/Timezone';
import { SavedViewReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { SAVED_VIEW_UPDATED_AT_FORMAT } from './constants';
import SavedViewHighlightedExpression from './SavedViewHighlightedExpression';
import { getSavedViewQuerySummaries } from './utils/getSavedViewQuerySummaries';
import SavedViewHoverCardDetails from './SavedViewHoverCardDetails';
import { SavedViewHoverCardProps } from './types';
import styles from './SavedViewHoverCard.module.scss';
@@ -18,23 +13,11 @@ function SavedViewHoverCard({
onCardLeave,
onClose,
}: SavedViewHoverCardProps): JSX.Element {
const { formatTimezoneAdjustedTimestamp } = useTimezone();
const view = target?.view;
const querySummaries = useMemo(
() => (view ? getSavedViewQuerySummaries(view) : []),
[view],
);
const hasQueryNames = querySummaries.length > 1;
const copyValue = querySummaries
.filter(({ expression }) => expression.length > 0)
.map(({ queryName, expression }) =>
hasQueryNames ? `${queryName}: ${expression}` : expression,
)
.join('\n');
const { allowed: canReadAll } = useAuthZ([SavedViewReadPermission]);
return (
<Popover
open={!!view}
open={!!target}
onOpenChange={(isOpen): void => {
if (!isOpen) {
onClose();
@@ -55,71 +38,17 @@ function SavedViewHoverCard({
onOpenAutoFocus={(event): void => event.preventDefault()}
onCloseAutoFocus={(event): void => event.preventDefault()}
>
{view && (
{target && (
<div
className={styles.content}
onMouseEnter={onCardEnter}
onMouseLeave={onCardLeave}
data-testid="saved-view-hover-card"
>
<div className={styles.header}>
<Typography.Text className={styles.name}>
{view.spec.displayName}
</Typography.Text>
{copyValue && (
<CopyButton
value={copyValue}
ariaLabel="Copy query"
testId="saved-view-hover-card-copy"
/>
)}
</div>
<div className={styles.query} data-testid="saved-view-hover-card-query">
{querySummaries.length === 0 ? (
<Typography.Text className={styles.noFilters}>
No filters
</Typography.Text>
) : (
querySummaries.map(({ queryName, expression, metric }) => (
<div key={queryName} className={styles.queryItem}>
{hasQueryNames && (
<Typography.Text className={styles.queryName}>
{queryName}
</Typography.Text>
)}
{metric && (
<Typography.Text className={styles.metric}>{metric}</Typography.Text>
)}
{expression && (
<Typography.Text className={styles.expression}>
<SavedViewHighlightedExpression expression={expression} />
</Typography.Text>
)}
</div>
))
)}
</div>
<div className={styles.updated}>
<Typography.Text className={styles.sectionTitle}>
Last updated
</Typography.Text>
{view.updatedBy && (
<Typography.Text className={styles.metaText}>
{view.updatedBy}
</Typography.Text>
)}
{view.updatedAt && (
<div className={styles.meta}>
<CalendarClock size={14} />
<Typography.Text className={styles.metaText}>
{formatTimezoneAdjustedTimestamp(
view.updatedAt,
SAVED_VIEW_UPDATED_AT_FORMAT,
)}
</Typography.Text>
</div>
)}
</div>
<SavedViewHoverCardDetails
viewId={target.viewId}
canReadAll={canReadAll}
/>
</div>
)}
</PopoverContent>

View File

@@ -0,0 +1,121 @@
import { useMemo } from 'react';
import { CalendarClock } from '@signozhq/icons';
import { Typography } from '@signozhq/ui/typography';
import { useGetSavedView } from 'api/generated/services/saved-view';
import { withAuthZContent } from 'lib/authz/components/withAuthZ/withAuthZContent';
import { buildSavedViewReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import CopyButton from 'periscope/components/CopyButton/CopyButton';
import { useTimezone } from 'providers/Timezone';
import {
SAVED_VIEW_LOAD_FAILED_NAME,
SAVED_VIEW_UPDATED_AT_FORMAT,
} from './constants';
import SavedViewHighlightedExpression from './SavedViewHighlightedExpression';
import SavedViewHoverCardSkeleton from './SavedViewHoverCardSkeleton';
import { SavedViewHoverCardDetailsProps } from './types';
import { getSavedViewQuerySummaries } from './utils/getSavedViewQuerySummaries';
import styles from './SavedViewHoverCard.module.scss';
function SavedViewHoverCardDetails({
viewId,
}: SavedViewHoverCardDetailsProps): JSX.Element {
const { formatTimezoneAdjustedTimestamp } = useTimezone();
const { data, isLoading, isError } = useGetSavedView({ id: viewId });
const view = data?.data;
const querySummaries = useMemo(
() => (view ? getSavedViewQuerySummaries(view) : []),
[view],
);
if (isLoading) {
return <SavedViewHoverCardSkeleton />;
}
if (isError || !view) {
return (
<Typography.Text
className={styles.error}
data-testid="saved-view-hover-card-error"
>
{SAVED_VIEW_LOAD_FAILED_NAME}
</Typography.Text>
);
}
const hasQueryNames = querySummaries.length > 1;
const copyValue = querySummaries
.filter(({ expression }) => expression.length > 0)
.map(({ queryName, expression }) =>
hasQueryNames ? `${queryName}: ${expression}` : expression,
)
.join('\n');
return (
<>
<div className={styles.header}>
<Typography.Text className={styles.name}>
{view.spec.displayName}
</Typography.Text>
{copyValue && (
<CopyButton
value={copyValue}
ariaLabel="Copy query"
testId="saved-view-hover-card-copy"
/>
)}
</div>
<div className={styles.query} data-testid="saved-view-hover-card-query">
{querySummaries.length === 0 ? (
<Typography.Text className={styles.noFilters}>No filters</Typography.Text>
) : (
querySummaries.map(({ queryName, expression, metric }) => (
<div key={queryName} className={styles.queryItem}>
{hasQueryNames && (
<Typography.Text className={styles.queryName}>
{queryName}
</Typography.Text>
)}
{metric && (
<Typography.Text className={styles.metric}>{metric}</Typography.Text>
)}
{expression && (
<Typography.Text className={styles.expression}>
<SavedViewHighlightedExpression expression={expression} />
</Typography.Text>
)}
</div>
))
)}
</div>
<div className={styles.updated}>
<Typography.Text className={styles.sectionTitle}>
Last updated
</Typography.Text>
{view.updatedBy && (
<Typography.Text className={styles.metaText}>
{view.updatedBy}
</Typography.Text>
)}
{view.updatedAt && (
<div className={styles.meta}>
<CalendarClock size={14} />
<Typography.Text className={styles.metaText}>
{formatTimezoneAdjustedTimestamp(
view.updatedAt,
SAVED_VIEW_UPDATED_AT_FORMAT,
)}
</Typography.Text>
</div>
)}
</div>
</>
);
}
export default withAuthZContent(SavedViewHoverCardDetails, {
checks: ({ viewId, canReadAll }) =>
canReadAll ? [] : [buildSavedViewReadPermission(viewId)],
fallbackOnLoading: <SavedViewHoverCardSkeleton />,
});

View File

@@ -0,0 +1,13 @@
import { Skeleton } from '@signozhq/ui/skeleton';
function SavedViewHoverCardSkeleton(): JSX.Element {
return (
<Skeleton
active
paragraph={{ rows: 3, width: ['100%', '80%', '60%'] }}
testId="saved-view-hover-card-loading"
/>
);
}
export default SavedViewHoverCardSkeleton;

View File

@@ -54,9 +54,8 @@
&.isActive {
background-color: var(--l3-background);
.rowName {
--button-variant-ghost-color: var(--l1-foreground);
--button-variant-ghost-hover-color: var(--l1-foreground);
.rowLink {
color: var(--l1-foreground);
}
}
}
@@ -76,18 +75,32 @@
opacity: 1;
}
.rowName {
--button-height: 100%;
--button-padding: 0 var(--spacing-6);
--button-justify-content: flex-start;
--button-font-size: var(--periscope-font-size-base);
--button-variant-ghost-color: var(--l2-foreground);
--button-variant-ghost-hover-color: var(--l2-foreground);
--button-variant-ghost-hover-background-color: transparent;
.rowLink {
display: flex;
flex: 1;
align-items: center;
min-width: 0;
height: 100%;
padding: 0 var(--spacing-6);
border-radius: var(--radius-1);
color: var(--l2-foreground);
text-decoration: none;
&:focus-visible {
outline: 1px solid var(--button-focus-ring);
outline-offset: -1px;
}
&:hover {
color: var(--l2-foreground-hover);
}
}
// nowrap fills the row before the ellipsis; line clamping alone stops at the last whole word.
.rowLinkLabel {
min-width: 0;
letter-spacing: -0.005em;
white-space: nowrap;
}
.loading {

View File

@@ -65,11 +65,11 @@ function SavedViewsList({
const rowHover = useMemo<SavedViewsListRowHoverProps>(
() => ({
onRowEnter: (view, row): void => {
onRowEnter: (viewId, row): void => {
const listTop = listRef.current?.getBoundingClientRect().top ?? 0;
const rowRect = row.getBoundingClientRect();
onHoverCardRowEnter({
view,
viewId,
anchorTop: rowRect.top - listTop,
anchorHeight: rowRect.height,
});

View File

@@ -1,10 +1,8 @@
import cx from 'classnames';
import { Undo2 } from '@signozhq/icons';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { buildSavedViewReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import SavedViewsRowButton from './SavedViewsRowButton';
import SavedViewsRowLink from './SavedViewsRowLink';
import SavedViewsRowMenu from './SavedViewsRowMenu';
import { SavedViewsListRowProps } from './types';
@@ -18,42 +16,17 @@ function SavedViewsListRow({
onAction,
hover,
}: SavedViewsListRowProps): JSX.Element {
const name = view.spec.displayName;
const readPermission = buildSavedViewReadPermission(view.id);
// Same cached check as the button; gates the hover card.
const { isLoading, deniedPermissions } = useAuthZ([readPermission]);
const canRead = !isLoading && deniedPermissions.length === 0;
return (
<div
className={cx(styles.row, { [styles.isActive]: isActive })}
data-testid="saved-views-row"
data-view-id={view.id}
onMouseEnter={(event): void => {
if (canRead) {
hover.onRowEnter(view, event.currentTarget);
}
}}
onMouseEnter={(event): void =>
hover.onRowEnter(view.id, event.currentTarget)
}
onMouseLeave={hover.onRowLeave}
>
<div className={styles.rowName}>
<AuthZButton
checks={[readPermission]}
size="md"
variant="ghost"
color="secondary"
width="100%"
textOverflow="ellipsis"
onClick={(): void => {
if (!isActive) {
onSelect(view);
}
}}
testId="saved-views-row-name"
>
{name}
</AuthZButton>
</div>
<SavedViewsRowLink view={view} isActive={isActive} onSelect={onSelect} />
{isActive && (
<SavedViewsRowButton
icon={<Undo2 size={14} />}

View File

@@ -5,7 +5,11 @@ import { Typography } from '@signozhq/ui/typography';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import { SavedViewListPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import {
SavedViewListPermission,
SavedViewReadPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import SavedViewsIconButton from './SavedViewsIconButton';
import SavedViewsList from './SavedViewsList';
@@ -21,6 +25,8 @@ function SavedViewsPanel({
onClose?: () => void;
}): JSX.Element {
const [search, setSearch] = useState('');
// Batched with the list check, so the hover card reads it from cache.
useAuthZ([SavedViewReadPermission]);
return (
<div

View File

@@ -0,0 +1,57 @@
import { MouseEvent, useMemo } from 'react';
import { Typography } from '@signozhq/ui/typography';
import { AppLink } from 'lib/router/AppLink';
import { useAppLocation } from 'lib/router/useAppLocation';
import { isModifierKeyPressed } from 'utils/app';
import { useTimeSearchParams } from 'hooks/useTimeSearchParams';
import { SavedViewsRowLinkProps } from './types';
import { getSavedViewPath } from './utils/getSavedViewPath';
import styles from './SavedViewsList.module.scss';
function SavedViewsRowLink({
view,
isActive,
onSelect,
}: SavedViewsRowLinkProps): JSX.Element {
const { pathname } = useAppLocation();
const timeSearch = useTimeSearchParams();
const path = useMemo(
() => getSavedViewPath(pathname, view, timeSearch),
[pathname, view, timeSearch],
);
// Opening in a new tab or window is left to the browser.
const handleClick = (event: MouseEvent<HTMLAnchorElement>): void => {
if (isModifierKeyPressed(event) || event.shiftKey) {
return;
}
event.preventDefault();
if (!isActive) {
onSelect(view);
}
};
return (
<AppLink
to={path}
className={styles.rowLink}
aria-current={isActive ? 'page' : undefined}
onClick={handleClick}
data-testid="saved-views-row-name"
>
<Typography.Text
as="span"
size="base"
weight="normal"
truncate={1}
className={styles.rowLinkLabel}
>
{view.spec.displayName}
</Typography.Text>
</AppLink>
);
}
export default SavedViewsRowLink;

View File

@@ -8,6 +8,8 @@ import {
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
@@ -16,7 +18,7 @@ import {
SAVED_VIEW_HOVER_CARD_OPEN_DELAY_MS,
} from '../constants';
import SavedViewsPanel from '../SavedViewsPanel';
import { mockSavedViewsApi } from './savedViewsApiMock';
import { API, mockSavedViewsApi } from './savedViewsApiMock';
import {
expectUsable,
explorerUrl,
@@ -139,9 +141,11 @@ function advance(ms: number): void {
});
}
function openCard(name: string): void {
// Resolves once the card has fetched its view.
async function openCard(name: string): Promise<HTMLElement> {
fireEvent.mouseEnter(row(name));
advance(SAVED_VIEW_HOVER_CARD_OPEN_DELAY_MS);
return screen.findByTestId('saved-view-hover-card-query');
}
describe('SavedViewHoverCard', () => {
@@ -168,7 +172,8 @@ describe('SavedViewHoverCard', () => {
expect(card()).toBeNull();
advance(1);
expect(card()).toHaveTextContent('Errors');
expect(card()).toBeInTheDocument();
await waitFor(() => expect(card()).toHaveTextContent('Errors'));
});
it('does not open when the pointer leaves before the delay', async () => {
@@ -184,7 +189,7 @@ describe('SavedViewHoverCard', () => {
it('stays open while the pointer moves into the card', async () => {
await renderPanel();
openCard('Errors');
await openCard('Errors');
fireEvent.mouseLeave(row('Errors'));
fireEvent.mouseEnter(card() as HTMLElement);
@@ -198,7 +203,7 @@ describe('SavedViewHoverCard', () => {
it('closes on leaving the row and reopens for the next row after the delay', async () => {
await renderPanel();
openCard('Errors');
await openCard('Errors');
fireEvent.mouseLeave(row('Errors'));
fireEvent.mouseEnter(row('Slow spans'));
@@ -206,12 +211,12 @@ describe('SavedViewHoverCard', () => {
expect(card()).toBeNull();
advance(SAVED_VIEW_HOVER_CARD_OPEN_DELAY_MS);
expect(card()).toHaveTextContent('Slow spans');
await waitFor(() => expect(card()).toHaveTextContent('Slow spans'));
});
it('closes when the row menu is pressed', async () => {
await renderPanel();
openCard('Errors');
await openCard('Errors');
fireEvent.click(within(row('Errors')).getByTestId('saved-views-row-menu'));
@@ -222,19 +227,17 @@ describe('SavedViewHoverCard', () => {
describe('content', () => {
it('shows the filter, the updater and the update time', async () => {
await renderPanel();
openCard('Errors');
const query = await openCard('Errors');
const content = card() as HTMLElement;
expect(
within(content).getByTestId('saved-view-hover-card-query'),
).toHaveTextContent('has_error = true');
expect(query).toHaveTextContent('has_error = true');
expect(content).toHaveTextContent('editor@signoz.io');
expect(content).toHaveTextContent('Sep 28, 2026');
});
it('copies the filter expression', async () => {
await renderPanel();
openCard('Errors');
await openCard('Errors');
fireEvent.click(screen.getByTestId('saved-view-hover-card-copy'));
@@ -243,9 +246,8 @@ describe('SavedViewHoverCard', () => {
it('names each query when there are several, and copies them per line', async () => {
await renderPanel();
openCard('Errors and slow');
const query = await openCard('Errors and slow');
const query = screen.getByTestId('saved-view-hover-card-query');
expect(query).toHaveTextContent('A');
expect(query).toHaveTextContent('B');
fireEvent.click(screen.getByTestId('saved-view-hover-card-copy'));
@@ -257,21 +259,74 @@ describe('SavedViewHoverCard', () => {
it('says there are no filters, with nothing to copy', async () => {
await renderPanel();
openCard('Everything');
const query = await openCard('Everything');
expect(screen.getByTestId('saved-view-hover-card-query')).toHaveTextContent(
'No filters',
);
expect(query).toHaveTextContent('No filters');
expect(screen.queryByTestId('saved-view-hover-card-copy')).toBeNull();
});
it('shows the metric of a metrics query', async () => {
await renderPanel(SavedviewtypesSourceDTO.metrics, DataSource.METRICS);
openCard('Request rate');
const query = await openCard('Request rate');
const query = screen.getByTestId('saved-view-hover-card-query');
expect(query).toHaveTextContent('app.requests · rate · sum');
expect(query).not.toHaveTextContent('No filters');
});
});
describe('fetching', () => {
it('shows the query from the view fetch, not from the list', async () => {
server.use(
rest.get(API, (_req, res, ctx) =>
res(
ctx.json({
status: 'success',
data: [{ ...errors, spec: { ...errors.spec, queries: [] } }],
}),
),
),
);
await renderPanel();
const query = await openCard('Errors');
expect(query).toHaveTextContent('has_error = true');
});
it('fetches the view again on every open', async () => {
let fetches = 0;
server.use(
rest.get(`${API}/:id`, (_req, res, ctx) => {
fetches += 1;
return res(ctx.json({ status: 'success', data: errors }));
}),
);
await renderPanel();
await openCard('Errors');
fireEvent.mouseLeave(row('Errors'));
advance(SAVED_VIEW_HOVER_CARD_CLOSE_DELAY_MS);
expect(card()).toBeNull();
await openCard('Errors');
await waitFor(() => expect(fetches).toBe(2));
});
it('says the view failed to load when its fetch fails', async () => {
server.use(
rest.get(`${API}/:id`, (_req, res, ctx) =>
res(ctx.status(500), ctx.json({ status: 'error' })),
),
);
await renderPanel();
fireEvent.mouseEnter(row('Errors'));
advance(SAVED_VIEW_HOVER_CARD_OPEN_DELAY_MS);
await expect(
screen.findByTestId('saved-view-hover-card-error'),
).resolves.toHaveTextContent('View failed to load');
expect(screen.queryByTestId('saved-view-hover-card-copy')).toBeNull();
});
});
});

View File

@@ -1,6 +1,10 @@
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import {
AuthtypesTransactionDTO,
SavedviewtypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import {
@@ -9,34 +13,42 @@ import {
buildSavedViewUpdatePermission,
SavedViewCreatePermission,
SavedViewListPermission,
SavedViewReadPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import {
AUTHZ_CHECK_URL,
authzMockResponse,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { DataSource } from 'types/common/queryBuilder';
import { SAVED_VIEW_HOVER_CARD_OPEN_DELAY_MS } from '../constants';
import SavedViewsHeader from '../SavedViewsHeader';
import SavedViewsPanel from '../SavedViewsPanel';
import { API, mockSavedViewsApi } from './savedViewsApiMock';
import {
expectUsable,
explorerUrl,
makeView,
MENU_CHECK_TIMEOUT,
queryWith,
renderWithExplorerProviders,
urlParam,
viewUrl,
} from './savedViewsTestUtils';
const PATH = ROUTES.TRACES_EXPLORER;
const HOVER_CARD_TIMEOUT = { timeout: SAVED_VIEW_HOVER_CARD_OPEN_DELAY_MS * 3 };
const errors = makeView({ id: 'view-1', displayName: 'Errors' });
const slow = makeView({ id: 'view-2', displayName: 'Slow spans' });
function renderPanel(url = explorerUrl(PATH, {})): void {
renderWithExplorerProviders(
function renderPanel(
url = explorerUrl(PATH, {}),
): ReturnType<typeof renderWithExplorerProviders> {
return renderWithExplorerProviders(
<SavedViewsPanel
source={SavedviewtypesSourceDTO.traces}
onClose={jest.fn()}
@@ -68,6 +80,37 @@ async function openRowMenu(name: string): Promise<void> {
fireEvent.click(within(rowNamed(name)).getByTestId('saved-views-row-menu'));
}
// Records every check, answered by `isGranted`.
function recordChecks(
isGranted: (transaction: AuthtypesTransactionDTO) => boolean = (): boolean =>
true,
): AuthtypesTransactionDTO[] {
const checks: AuthtypesTransactionDTO[] = [];
server.use(
rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
const payload = (await req.json()) as AuthtypesTransactionDTO[];
checks.push(...payload);
return res(ctx.json(authzMockResponse(payload, payload.map(isGranted))));
}),
);
return checks;
}
const readSelectors = (checks: AuthtypesTransactionDTO[]): string[] =>
checks
.filter((transaction) => transaction.relation === 'read')
.map((transaction) => transaction.object.selector);
async function hoverRow(name: string): Promise<HTMLElement> {
await screen.findAllByTestId('saved-views-row');
fireEvent.mouseEnter(rowNamed(name));
return screen.findByTestId(
'saved-view-hover-card',
undefined,
HOVER_CARD_TIMEOUT,
);
}
// Resolves once the row's check is back, so its state is final.
async function settledRow(testId: string): Promise<HTMLElement> {
await waitFor(
@@ -98,21 +141,51 @@ describe('SavedViews - AuthZ', () => {
expect(screen.queryByTestId('saved-views-search')).toBeNull();
});
it('disables only the views it cannot read', async () => {
it('runs no read check per row', async () => {
mockSavedViewsApi([errors, slow]);
server.use(setupAuthzDeny(buildSavedViewReadPermission(errors.id)));
const checks = recordChecks();
renderPanel();
// The menu checks go out after any check the rows made on mount.
await openRowMenu('Errors');
await settledRow('saved-views-row-menu-item-delete');
expect(checks.map((transaction) => transaction.relation)).toContain('delete');
expect(readSelectors(checks)).toStrictEqual(['*']);
});
it('opens a view it cannot read, then the header says no access', async () => {
mockSavedViewsApi([errors]);
server.use(setupAuthzDeny(buildSavedViewReadPermission(errors.id)));
const { history } = renderWithExplorerProviders(
<>
<SavedViewsHeader
source={SavedviewtypesSourceDTO.traces}
onOpenViews={jest.fn()}
onToggleViews={jest.fn()}
/>
<SavedViewsPanel
source={SavedviewtypesSourceDTO.traces}
onClose={jest.fn()}
/>
</>,
explorerUrl(PATH, {}),
);
await screen.findAllByTestId('saved-views-row');
const nameOf = (view: string): HTMLElement =>
within(rowNamed(view)).getByTestId('saved-views-row-name');
const name = within(rowNamed('Errors')).getByTestId('saved-views-row-name');
expectUsable(name);
await userEvent.click(name);
await waitFor(() =>
expect(nameOf('Errors')).toHaveAttribute('aria-disabled', 'true'),
expect(urlParam(history, QueryParams.viewKey)).toBe(
JSON.stringify(errors.id),
),
);
await waitFor(() =>
expect(nameOf('Slow spans')).not.toHaveAttribute('aria-busy'),
expect(screen.getByTestId('saved-views-name')).toHaveTextContent(
'No view access',
),
);
expect(nameOf('Slow spans')).not.toHaveAttribute('aria-disabled', 'true');
});
it('keeps the row menu on a view it cannot read', async () => {
@@ -133,6 +206,58 @@ describe('SavedViews - AuthZ', () => {
).resolves.not.toHaveAttribute('data-disabled');
});
it('shows the denied callout in the hover card of a view it cannot read, without fetching it', async () => {
let fetches = 0;
mockSavedViewsApi([errors]);
server.use(
setupAuthzDeny(
SavedViewReadPermission,
buildSavedViewReadPermission(errors.id),
),
rest.get(`${API}/:id`, (_req, res, ctx) => {
fetches += 1;
return res(ctx.json({ status: 'success', data: errors }));
}),
);
renderPanel();
const card = await hoverRow('Errors');
await expect(
within(card).findByText(/not authorized/i),
).resolves.toBeInTheDocument();
expect(within(card).queryByTestId('saved-view-hover-card-query')).toBeNull();
expect(fetches).toBe(0);
});
it('skips the read check of the hovered view with read on every view', async () => {
mockSavedViewsApi([errors]);
const checks = recordChecks();
renderPanel();
const card = await hoverRow('Errors');
await expect(
within(card).findByTestId('saved-view-hover-card-query'),
).resolves.toHaveTextContent('has_error = true');
expect(readSelectors(checks)).toStrictEqual(['*']);
});
it('checks read on the hovered view without read on every view', async () => {
mockSavedViewsApi([errors]);
const checks = recordChecks(
(transaction) =>
transaction.relation !== 'read' || transaction.object.selector !== '*',
);
renderPanel();
const card = await hoverRow('Errors');
await expect(
within(card).findByTestId('saved-view-hover-card-query'),
).resolves.toHaveTextContent('has_error = true');
expect(readSelectors(checks)).toStrictEqual(['*', errors.id]);
});
it('disables creating without create', async () => {
mockSavedViewsApi([]);
server.use(setupAuthzDeny(SavedViewCreatePermission));

View File

@@ -1,9 +1,14 @@
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { toast } from '@signozhq/ui/sonner';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import {
fireEvent,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import SavedViewsPanel from '../SavedViewsPanel';
import { mockSavedViewsApi } from './savedViewsApiMock';
@@ -14,6 +19,7 @@ import {
renderWithExplorerProviders,
urlParam,
viewUrl,
withGlobalTime,
} from './savedViewsTestUtils';
jest.mock('@signozhq/ui/sonner', () => ({
@@ -53,6 +59,9 @@ const row = (name: string): HTMLElement =>
.getAllByTestId('saved-views-row')
.find((element) => element.textContent?.includes(name)) as HTMLElement;
const rowName = (name: string): HTMLElement =>
within(row(name)).getByTestId('saved-views-row-name');
describe('SavedViewsPanel list', () => {
beforeEach(() => {
localStorage.clear();
@@ -85,9 +94,8 @@ describe('SavedViewsPanel list', () => {
const { history } = renderPanel();
await screen.findByTestId('saved-views-list');
const name = within(row('Slow spans')).getByTestId('saved-views-row-name');
await waitFor(() => expectUsable(name));
await userEvent.click(name);
await waitFor(() => expectUsable(rowName('Slow spans')));
await userEvent.click(rowName('Slow spans'));
await waitFor(() =>
expect(urlParam(history, QueryParams.viewKey)).toBe(
@@ -96,6 +104,60 @@ describe('SavedViewsPanel list', () => {
);
});
it('links each row to its view in the current time range', async () => {
mockSavedViewsApi([mine, alsoMine]);
renderWithExplorerProviders(
withGlobalTime(
<SavedViewsPanel
source={SavedviewtypesSourceDTO.traces}
onClose={jest.fn()}
/>,
{ selectedTime: '1h' },
),
explorerUrl(PATH, {}),
);
await screen.findByTestId('saved-views-list');
const url = new URL(
rowName('Slow spans').getAttribute('href') as string,
window.location.origin,
);
expect(url.pathname).toBe(PATH);
expect(url.searchParams.get(QueryParams.viewKey)).toBe(
JSON.stringify(alsoMine.id),
);
expect(url.searchParams.get(QueryParams.panelTypes)).toBe(
JSON.stringify(alsoMine.spec.panelType),
);
expect(url.searchParams.has(QueryParams.compositeQuery)).toBe(true);
expect(url.searchParams.get(QueryParams.relativeTime)).toBe('1h');
});
it.each([
['Ctrl', { ctrlKey: true }],
['Cmd', { metaKey: true }],
['Shift', { shiftKey: true }],
])('leaves a %s click on a row to the browser', async (_key, modifiers) => {
mockSavedViewsApi([mine, alsoMine]);
const { history } = renderPanel();
await screen.findByTestId('saved-views-list');
const before = history.location.search;
let defaultPrevented: boolean | undefined;
const recordClick = (event: MouseEvent): void => {
defaultPrevented = event.defaultPrevented;
// jsdom cannot open a new tab.
event.preventDefault();
};
document.addEventListener('click', recordClick);
fireEvent.click(rowName('Slow spans'), modifiers);
document.removeEventListener('click', recordClick);
expect(defaultPrevented).toBe(false);
expect(history.location.search).toBe(before);
});
it('marks the open view and clears it from its row', async () => {
mockSavedViewsApi([mine, alsoMine]);
const { history } = renderPanel(viewUrl(PATH, mine));
@@ -120,9 +182,8 @@ describe('SavedViewsPanel list', () => {
await screen.findByTestId('saved-views-list');
const before = history.location.search;
await userEvent.click(
within(row('Errors')).getByTestId('saved-views-row-name'),
);
expect(rowName('Errors')).toHaveAttribute('aria-current', 'page');
await userEvent.click(rowName('Errors'));
expect(history.location.search).toBe(before);
});

View File

@@ -4,6 +4,7 @@ import { toast } from '@signozhq/ui/sonner';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { NANO_SECOND_MULTIPLIER } from 'store/globalTime';
import SavedViewsHeader from '../SavedViewsHeader';
import SavedViewsPanel from '../SavedViewsPanel';
@@ -16,6 +17,7 @@ import {
renderWithExplorerProviders,
urlParam,
viewUrl,
withGlobalTime,
} from './savedViewsTestUtils';
const mockCopy = jest.fn();
@@ -32,6 +34,8 @@ jest.mock('@signozhq/ui/sonner', () => ({
}));
const PATH = ROUTES.TRACES_EXPLORER;
const START_MS = 1700000000000;
const END_MS = 1700003600000;
const errors = makeView({ id: 'view-1', displayName: 'Errors' });
const slow = makeView({
@@ -119,9 +123,22 @@ describe('SavedViewsPanel row menu', () => {
);
});
it('copies a link that opens the view with its query and tab', async () => {
it('copies a link that opens the view with its query, tab and time range', async () => {
mockSavedViewsApi([errors, slow]);
renderPanelWithHeader();
renderWithExplorerProviders(
withGlobalTime(
<SavedViewsPanel
source={SavedviewtypesSourceDTO.traces}
onClose={jest.fn()}
/>,
{
selectedTime: 'custom',
minTime: START_MS * NANO_SECOND_MULTIPLIER,
maxTime: END_MS * NANO_SECOND_MULTIPLIER,
},
),
explorerUrl(PATH, {}),
);
await chooseFromRowMenu('Slow spans', 'Copy link');
@@ -137,6 +154,9 @@ describe('SavedViewsPanel row menu', () => {
expect(
decodeURIComponent(link.searchParams.get(QueryParams.compositeQuery) ?? ''),
).toContain('duration_nano > 1000');
expect(link.searchParams.get(QueryParams.startTime)).toBe(String(START_MS));
expect(link.searchParams.get(QueryParams.endTime)).toBe(String(END_MS));
expect(link.searchParams.has(QueryParams.relativeTime)).toBe(false);
expect(toast.success).toHaveBeenCalledWith('Link copied', expect.anything());
});

View File

@@ -28,6 +28,7 @@ import { TestRouter } from 'tests/router';
import { getAppContextMock } from 'tests/test-utils';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import { __setSearchParamsGetterForTest } from 'utils/getUnstableCurrentSearchParams';
import { getSavedViewQuery } from '../utils/getSavedViewQuery';
@@ -160,6 +161,23 @@ export function viewUrl(
const mockStore = configureStore([thunk]);
export function withGlobalTime(
ui: ReactElement,
globalTime: Partial<GlobalReducer>,
): ReactElement {
const state = store.getState();
return (
<Provider
store={mockStore({
...state,
globalTime: { ...state.globalTime, ...globalTime },
})}
>
{ui}
</Provider>
);
}
// What the explorer page does around the header: writes its default query to a
// bare url, and sets the provider's tab from the url (the provider alone seeds
// it from the raw, still JSON-quoted param).

View File

@@ -12,11 +12,10 @@ import {
SavedviewtypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import { ErrorType } from 'api/generatedAPIInstance';
import { QueryParams } from 'constants/query';
import { buildExplorerNavigationUrl } from 'container/AIAssistant/components/ActionsSection/utils/openSavedView';
import { useAppLocation } from 'lib/router/useAppLocation';
import { getAbsoluteUrl } from 'utils/basePath';
import { toAPIError } from 'utils/errorUtils';
import { useTimeSearchParams } from 'hooks/useTimeSearchParams';
import {
SAVED_VIEW_SCHEMA_VERSION,
@@ -24,7 +23,7 @@ import {
} from '../constants';
import { SavedViewEventKeys, SavedViewEvents } from '../events';
import { UseSavedViewRowActionsResult } from '../types';
import { getSavedViewQuery } from '../utils/getSavedViewQuery';
import { getSavedViewPath } from '../utils/getSavedViewPath';
import { invalidateSavedViews } from '../utils/invalidateSavedViews';
import { useSavedViewLogEvent } from './useSavedViewLogEvent';
@@ -43,6 +42,7 @@ export function useSavedViewRowActions(
): UseSavedViewRowActionsResult {
const queryClient = useQueryClient();
const { pathname } = useAppLocation();
const timeSearch = useTimeSearchParams();
const [, copyToClipboard] = useCopyToClipboard();
const logSavedViewEvent = useSavedViewLogEvent(source);
const { mutateAsync: updateSavedView, isLoading: isRenaming } =
@@ -52,17 +52,15 @@ export function useSavedViewRowActions(
const copyViewLink = useCallback(
(view: SavedviewtypesSavedViewDTO): void => {
const path = buildExplorerNavigationUrl(pathname, getSavedViewQuery(view), {
[QueryParams.panelTypes]: view.spec.panelType,
[QueryParams.viewKey]: view.id,
});
copyToClipboard(getAbsoluteUrl(path));
copyToClipboard(
getAbsoluteUrl(getSavedViewPath(pathname, view, timeSearch)),
);
toast.success('Link copied', { position: SAVED_VIEW_TOAST_POSITION });
logSavedViewEvent(SavedViewEvents.LinkCopied, {
[SavedViewEventKeys.ViewId]: view.id,
});
},
[pathname, copyToClipboard, logSavedViewEvent],
[pathname, timeSearch, copyToClipboard, logSavedViewEvent],
);
const copyViewId = useCallback(

View File

@@ -45,6 +45,7 @@ import {
savedViewsListResponse,
type SavedViewSource,
unreadableViewId,
withLongName,
} from './__story_mockdata__/savedViews';
import SavedViewsHeader from '../SavedViewsHeader';
@@ -73,7 +74,13 @@ const controls = {
unreadableView: toggleControl('Unreadable view', {
group: VIEW,
description:
'Denies `read` on the first view created by others alone, on top of the Access controls: its row greys out, and with Open view on `created-by-others` the header shows No view access.',
'Denies `read` on the first view created by others, and so on `saved-view:*`, on top of the Access controls: its row still opens it, and the header then shows No view access, as with Open view on `created-by-others`. Its hover card shows the permission callout in place of the query.',
value: false,
}),
viewPending: toggleControl('View fetch pending', {
group: VIEW,
description:
'Holds every `GET /saved_views/:id` open, so a hover card stays on its loading skeleton.',
value: false,
}),
createdByMe: countControl('Created by me', {
@@ -87,6 +94,12 @@ const controls = {
value: 4,
max: SAVED_VIEWS_MAX,
}),
longNames: toggleControl('Long names', {
group: LIST,
description:
'Lengthens every view name past the sidebar width, so rows and the open view name truncate.',
value: false,
}),
};
type SavedViewsValues = MockControlValues<typeof controls>;
@@ -99,7 +112,7 @@ const viewDenied = (
): boolean =>
transaction.relation === 'read' &&
transaction.object.resource.kind === 'saved-view' &&
transaction.object.selector === deniedId;
[deniedId, '*'].includes(transaction.object.selector);
const definition = defineStoryMocks({
controls,
@@ -107,7 +120,14 @@ const definition = defineStoryMocks({
values: SavedViewsValues & AuthzArgs,
response,
): RequestHandler[] => {
const { source, openView, createdByMe, createdByOthers } = values;
const {
source,
openView,
viewPending,
createdByMe,
createdByOthers,
longNames,
} = values;
// What the panel writes stays in this handler set until a control changes.
const created: SavedviewtypesSavedViewDTO[] = [];
@@ -118,8 +138,14 @@ const definition = defineStoryMocks({
view: SavedviewtypesSavedViewDTO,
): SavedviewtypesSavedViewDTO => ({ ...view, ...updated.get(view.id) });
const named = (
view: SavedviewtypesSavedViewDTO,
): SavedviewtypesSavedViewDTO => (longNames ? withLongName(view) : view);
const findView = (id: string): SavedviewtypesSavedViewDTO | undefined => {
const view = created.find((item) => item.id === id) ?? savedViewById(id);
const stored = savedViewById(id);
const view =
created.find((item) => item.id === id) ?? (stored && named(stored));
return view && !deleted.has(id) ? current(view) : undefined;
};
@@ -143,7 +169,7 @@ const definition = defineStoryMocks({
return {
...list,
data: [...(list.data ?? []), ...created]
data: [...(list.data ?? []).map(named), ...created]
.filter((view) => !deleted.has(view.id))
.map(current),
};
@@ -151,6 +177,10 @@ const definition = defineStoryMocks({
),
rest.get(`${API}/:id`, (req, res, ctx) => {
if (viewPending) {
return res(ctx.delay('infinite'));
}
if (openError) {
return res(ctx.status(openError.status), ctx.json(openError.body));
}
@@ -274,7 +304,9 @@ const isPending = (element: HTMLElement): boolean =>
element.hasAttribute('data-loading');
const isDisabled = (element: HTMLElement): boolean =>
element.hasAttribute('disabled') || element.hasAttribute('data-disabled');
element.hasAttribute('disabled') ||
element.hasAttribute('data-disabled') ||
element.getAttribute('aria-disabled') === 'true';
export const expectDisabled = (
find: FindElement,
@@ -302,6 +334,30 @@ export const rowName =
(): HTMLElement =>
within(row).getByTestId('saved-views-row-name');
const hoverRow = async (row: HTMLElement): Promise<HTMLElement> => {
await userEvent.hover(row);
return screen.findByTestId('saved-view-hover-card', undefined, UNTIL_LOADED);
};
const searchViews = async (
canvasElement: HTMLElement,
text: string,
): Promise<void> => {
const search = await within(canvasElement).findByTestId(
'saved-views-search',
undefined,
UNTIL_LOADED,
);
await userEvent.type(search, text);
};
const clickWhenEnabled = async (find: FindElement): Promise<void> => {
await expectDisabled(find, false);
await userEvent.click(find());
};
export const openRowMenu = async (row: HTMLElement): Promise<void> => {
await userEvent.click(within(row).getByTestId('saved-views-row-menu'));
await screen.findByRole('menu', undefined, UNTIL_LOADED);
@@ -327,3 +383,115 @@ export const openSaveChangesMenu = async (
export const saveChangesItem = (key: 'save-as-new' | 'update'): FindElement =>
byTestId(`saved-views-save-changes-item-${key}`);
type PlayContext = {
canvasElement: HTMLElement;
args: { source: SavedViewSource };
};
export const hoverFirstRow = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const [row] = await findRows(canvasElement);
const card = await hoverRow(row);
await within(card).findByTestId(
'saved-view-hover-card-query',
undefined,
UNTIL_LOADED,
);
};
export const hoverFirstRowLoading = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const [row] = await findRows(canvasElement);
const card = await hoverRow(row);
await within(card).findByTestId(
'saved-view-hover-card-loading',
undefined,
UNTIL_LOADED,
);
};
export const searchWithNoResults = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await searchViews(canvasElement, 'nothing like this');
await screen.findByTestId('saved-views-list-no-results');
};
export const openCreateModal = async (): Promise<void> => {
await clickWhenEnabled(byTestId('saved-views-create'));
await screen.findByTestId('save-view-modal');
};
export const openEditDetailsModal = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const [row] = await findRows(canvasElement);
await openRowMenu(row);
await clickWhenEnabled(rowMenuItem('editDetails'));
await screen.findByTestId('save-view-modal');
};
export const openSaveAsNewModal = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openSaveChangesMenu(canvasElement);
await clickWhenEnabled(saveChangesItem('save-as-new'));
await screen.findByTestId('save-view-modal');
};
export const openDeleteDialog = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const [row] = await findRows(canvasElement);
await openRowMenu(row);
await clickWhenEnabled(rowMenuItem('delete'));
await screen.findByTestId('delete-saved-view-confirm');
};
const findUnreadableRow = async ({
canvasElement,
args,
}: PlayContext): Promise<HTMLElement> => {
const rows = await findRows(canvasElement);
const deniedId = unreadableViewId(args.source);
return rows.find(
(row) => row.getAttribute('data-view-id') === deniedId,
) as HTMLElement;
};
export const hoverUnreadableRow = async (
context: PlayContext,
): Promise<void> => {
const card = await hoverRow(await findUnreadableRow(context));
await expect(
await within(card).findByText(/not authorized/i, undefined, UNTIL_LOADED),
).toBeVisible();
await expect(
within(card).queryByTestId('saved-view-hover-card-query'),
).toBeNull();
};
export const openUnreadableView = async (
context: PlayContext,
): Promise<void> => {
const { canvasElement } = context;
const denied = await findUnreadableRow(context);
await userEvent.click(rowName(denied)());
await expect(
await within(canvasElement).findByText(
'No view access',
undefined,
UNTIL_LOADED,
),
).toBeVisible();
};

View File

@@ -6,10 +6,17 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import SavedViewsPanel from '../SavedViewsPanel';
import {
findRows,
hoverFirstRow,
hoverFirstRowLoading,
openCreateModal,
openDeleteDialog,
openEditDetailsModal,
openRowMenu,
openSaveAsNewModal,
openSaveChangesMenu,
SavedViewsSidebar,
savedViewsMocks,
searchWithNoResults,
sidebarCanvas,
} from './SavedViews.stories.mocks';
@@ -78,3 +85,48 @@ export const SaveChangesMenu: Story = {
await openSaveChangesMenu(canvasElement);
},
};
/**
* Views whose names run past the sidebar, with one of them open: each row and
* the open view name truncate.
*/
export const LongNames: Story = {
args: { longNames: true, openView: 'created-by-me' },
};
/** The hover card of the first row: its query, who updated it and when. */
export const HoverCard: Story = {
play: hoverFirstRow,
};
/** The hover card while its view is still loading: a skeleton in place of the query. */
export const HoverCardLoading: Story = {
args: { viewPending: true },
play: hoverFirstRowLoading,
};
/** A search that matches no view: the list says so in place of the rows. */
export const SearchNoResults: Story = {
play: searchWithNoResults,
};
/** The + in the header opens Save view for the current query. */
export const CreateModal: Story = {
play: openCreateModal,
};
/** Edit details from a row's menu: the modal starts on the view's name. */
export const EditDetailsModal: Story = {
play: openEditDetailsModal,
};
/** Save as new view from the ✓ menu on unsaved changes. */
export const SaveAsNewModal: Story = {
args: { openView: 'unsaved-changes' },
play: openSaveAsNewModal,
};
/** Delete from a row's menu asks to confirm before the view goes. */
export const DeleteDialog: Story = {
play: openDeleteDialog,
};

View File

@@ -209,6 +209,18 @@ export const createdSavedView = (
spec,
});
const LONG_NAME_SUFFIX = ', every environment and region, last 30 days';
export const withLongName = (
view: SavedviewtypesSavedViewDTO,
): SavedviewtypesSavedViewDTO => ({
...view,
spec: {
...view.spec,
displayName: `${view.spec.displayName}${LONG_NAME_SUFFIX}`,
},
});
export const savedViewResponse = (
view: SavedviewtypesSavedViewDTO,
): GetSavedView200 => ({ status: 'success', data: view });

View File

@@ -4,14 +4,15 @@ import { expect, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { unreadableViewId } from '../__story_mockdata__/savedViews';
import {
byTestId,
expectDisabled,
expectPending,
findRows,
hoverUnreadableRow,
openRowMenu,
openSaveChangesMenu,
openUnreadableView,
rowMenuItem,
rowName,
saveChangesItem,
@@ -99,21 +100,18 @@ export const NoCreateSaveMenu: Story = {
};
/**
* `read` denied on one view made by someone else: its name is disabled and its
* hover card never opens, while every other view still opens.
* `read` denied on one view made by someone else: the list checks no `read`, so
* its row opens it like any other, and the header then says No view access.
*/
export const NoRead: Story = {
args: { unreadableView: true },
play: async ({ canvasElement, args }) => {
const rows = await findRows(canvasElement);
const deniedId = unreadableViewId(args.source);
play: openUnreadableView,
};
await Promise.all(
rows.map((row) =>
expectDisabled(rowName(row), row.getAttribute('data-view-id') === deniedId),
),
);
},
/** The hover card of the unreadable view: the permission callout in place of its query. */
export const NoReadHoverCard: Story = {
args: { unreadableView: true },
play: hoverUnreadableRow,
};
/** The unreadable view open from its link: the header names it No view access. */

View File

@@ -128,6 +128,11 @@ export interface SavedViewsListRowProps {
hover: SavedViewsListRowHoverProps;
}
export type SavedViewsRowLinkProps = Pick<
SavedViewsListRowProps,
'view' | 'isActive' | 'onSelect'
>;
export type SavedViewRowActionKey =
| 'copyLink'
| 'copyId'
@@ -181,7 +186,7 @@ export interface UseSavedViewRowActionsResult {
}
export interface SavedViewHoverCardTarget {
view: SavedviewtypesSavedViewDTO;
viewId: string;
anchorTop: number;
anchorHeight: number;
}
@@ -202,8 +207,14 @@ export interface SavedViewHoverCardProps {
onClose: () => void;
}
export interface SavedViewHoverCardDetailsProps {
viewId: string;
/** `read` is granted on every view, so the view needs no check of its own. */
canReadAll: boolean;
}
export interface SavedViewsListRowHoverProps {
onRowEnter: (view: SavedviewtypesSavedViewDTO, row: HTMLElement) => void;
onRowEnter: (viewId: string, row: HTMLElement) => void;
onRowLeave: () => void;
onMenuOpen: () => void;
}

View File

@@ -0,0 +1,34 @@
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { makeView } from '../../__tests__/savedViewsTestUtils';
import { getSavedViewPath } from '../getSavedViewPath';
const view = makeView({ id: 'view-1', displayName: 'Errors' });
function paramsOf(path: string): URLSearchParams {
return new URL(path, window.location.origin).searchParams;
}
describe('getSavedViewPath', () => {
it('opens the view on the given explorer in the given time range', () => {
const path = getSavedViewPath(
ROUTES.TRACES_EXPLORER,
view,
'startTime=1700000000000&endTime=1700003600000',
);
const params = paramsOf(path);
expect(path.startsWith(`${ROUTES.TRACES_EXPLORER}?`)).toBe(true);
expect(params.get(QueryParams.viewKey)).toBe(JSON.stringify(view.id));
expect(params.get(QueryParams.startTime)).toBe('1700000000000');
expect(params.get(QueryParams.endTime)).toBe('1700003600000');
});
it('adds no time range when there is none', () => {
const path = getSavedViewPath(ROUTES.TRACES_EXPLORER, view, '');
expect(path.endsWith('&')).toBe(false);
expect(paramsOf(path).has(QueryParams.relativeTime)).toBe(false);
});
});

View File

@@ -0,0 +1,17 @@
import { SavedviewtypesSavedViewDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { buildExplorerNavigationUrl } from 'utils/buildExplorerNavigationUrl';
import { getSavedViewQuery } from './getSavedViewQuery';
export function getSavedViewPath(
pathname: string,
view: SavedviewtypesSavedViewDTO,
timeSearch: string,
): string {
const path = buildExplorerNavigationUrl(pathname, getSavedViewQuery(view), {
[QueryParams.panelTypes]: view.spec.panelType,
[QueryParams.viewKey]: view.id,
});
return timeSearch ? `${path}&${timeSearch}` : path;
}

View File

@@ -1,7 +1,7 @@
import { renderHook } from '@testing-library/react';
import { NANO_SECOND_MULTIPLIER } from 'store/globalTime';
import { useTimeSearchParams } from '../useTimeSearchParams';
import { useTimeSearchParams } from 'hooks/useTimeSearchParams';
let mockGlobalTime = {
selectedTime: '30m',

View File

@@ -12,12 +12,13 @@ import {
IOption,
IResourceAttribute,
IResourceAttributeProps,
OperatorValues,
Tags,
} from 'hooks/useResourceAttribute/types';
import { decode } from 'js-base64';
import { getCurrentLocation } from 'lib/router/navigation';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
import { OperatorValues, Tags } from 'hooks/useResourceAttribute/types';
import { v4 as uuid } from 'uuid';
import { whilelistedKeys } from './config';

View File

@@ -4,7 +4,7 @@ import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
import type { GlobalReducer } from 'types/reducer/globalTime';
import { timeParamsFromGlobalTime } from '../utils/timeUrlParams';
import { timeParamsFromGlobalTime } from 'utils/timeUrlParams';
/** Active time window as a query string (no leading `?`), or `''` when unset. */
export function useTimeSearchParams(): string {

View File

@@ -262,17 +262,21 @@ describe('withAuthZ router context stability', () => {
server.use(setupAuthzGrantByPrefix('read||__||role'));
});
it('does not re-render when useParams returns new object with same values', async () => {
it('keeps the router context when useParams returns new object with same values', async () => {
mockAppParams({ roleId: 'r-1' });
mockAppLocation({ pathname: '/', search: '' });
const seen: RouterContext[] = [];
const Guarded = withAuthZ(RenderCounter, {
checks: (_props, router: RouterContext) => [
buildPermission(
'read',
buildObjectString<'read'>('role', router.params.roleId ?? '*'),
),
],
checks: (_props, router: RouterContext) => {
seen.push(router);
return [
buildPermission(
'read',
buildObjectString<'read'>('role', router.params.roleId ?? '*'),
),
];
},
});
const { rerender } = render(<Guarded />);
@@ -281,24 +285,24 @@ describe('withAuthZ router context stability', () => {
expect(screen.getByTestId('render-count')).toBeInTheDocument();
});
const initialCount = renderCount;
const checksBefore = seen.length;
// Return NEW object with SAME values — should not cause re-render
// Return NEW object with SAME values: the router context stays the same
mockAppParams({ roleId: 'r-1' });
rerender(<Guarded />);
// Allow any pending effects to flush
await waitFor(() => {
expect(renderCount).toBe(initialCount);
});
expect(seen.length).toBeGreaterThan(checksBefore);
expect(seen[seen.length - 1]).toBe(seen[0]);
});
it('does not re-render when useLocation returns new object with same pathname', async () => {
it('keeps the router context when useLocation returns new object with same pathname', async () => {
mockAppParams({});
mockAppLocation({ pathname: '/roles', search: '' });
const seen: RouterContext[] = [];
const Guarded = withAuthZ(RenderCounter, {
checks: (_props, router: RouterContext) => {
seen.push(router);
const match = router.matchPath<{ id: string }>('/roles/:id');
return match
? [buildPermission('read', buildObjectString<'read'>('role', match.id))]
@@ -312,23 +316,24 @@ describe('withAuthZ router context stability', () => {
expect(screen.getByTestId('render-count')).toBeInTheDocument();
});
const initialCount = renderCount;
const checksBefore = seen.length;
// Return NEW object with SAME pathname — should not cause re-render
// Return NEW object with SAME pathname: the router context stays the same
mockAppLocation({ pathname: '/roles', search: '' });
rerender(<Guarded />);
await waitFor(() => {
expect(renderCount).toBe(initialCount);
});
expect(seen.length).toBeGreaterThan(checksBefore);
expect(seen[seen.length - 1]).toBe(seen[0]);
});
it('does not re-render when useLocation returns new object with same search params', async () => {
it('keeps the router context when useLocation returns new object with same search params', async () => {
mockAppParams({});
mockAppLocation({ pathname: '/', search: '?tab=keys' });
const seen: RouterContext[] = [];
const Guarded = withAuthZ(RenderCounter, {
checks: (_props, router: RouterContext) => {
seen.push(router);
// Access searchParams to ensure it's part of the dependency chain
void router.searchParams.get('tab');
return [readPerm];
@@ -341,15 +346,14 @@ describe('withAuthZ router context stability', () => {
expect(screen.getByTestId('render-count')).toBeInTheDocument();
});
const initialCount = renderCount;
const checksBefore = seen.length;
// Return NEW object with SAME search — should not cause re-render
// Return NEW object with SAME search: the router context stays the same
mockAppLocation({ pathname: '/', search: '?tab=keys' });
rerender(<Guarded />);
await waitFor(() => {
expect(renderCount).toBe(initialCount);
});
expect(seen.length).toBeGreaterThan(checksBefore);
expect(seen[seen.length - 1]).toBe(seen[0]);
});
it('re-renders when params values actually change', async () => {

View File

@@ -6,6 +6,7 @@ export const SavedViewCreatePermission = buildPermission(
'create',
'saved-view:*',
);
export const SavedViewReadPermission = buildPermission('read', 'saved-view:*');
export const buildSavedViewReadPermission = (id: string): BrandedPermission =>
buildPermission('read', `saved-view:${id}`);

View File

@@ -9,7 +9,7 @@ import { useSafeNavigate } from 'hooks/useSafeNavigate';
import type { PanelEditorHandoffState } from '../PanelEditor/panelEditorHandoff';
import { getPanelBuilderQuery } from '../Panels/utils/getPanelBuilderQuery';
import { useDashboardStore } from '../store/useDashboardStore';
import { useTimeSearchParams } from './useTimeSearchParams';
import { useTimeSearchParams } from 'hooks/useTimeSearchParams';
import logEvent from '@/api/common/logEvent';
import { DashboardDetailEvents } from '../../constants/events';

View File

@@ -24,7 +24,7 @@ import {
parseNewPanelTarget,
} from '../DashboardContainer/PanelEditor/newPanelRoute';
import { useSyncVariablesForSuggestions } from '../DashboardContainer/hooks/useSyncVariablesForSuggestions';
import { useTimeSearchParams } from '../DashboardContainer/hooks/useTimeSearchParams';
import { useTimeSearchParams } from 'hooks/useTimeSearchParams';
import { createDefaultPanel } from '../DashboardContainer/patchOps';
import { useDashboardStore } from '../DashboardContainer/store/useDashboardStore';
import { useSeedVariableSelection } from '../DashboardContainer/VariablesBar/hooks/useSeedVariableSelection';

View File

@@ -509,16 +509,34 @@ component state, is a story with a `play` function rather than a control. Use
row action, and wait on the state's own text. The page fetches before it renders
a row, so the finder needs a timeout past the 1s default.
The play is a named function in `stories/__story_mockdata__/<page>.play.ts`,
collapsed for review with the other AI-owned files, and the story file only names
it. Branch each check on the args it reads, so every control value the page
supports passes. A story file that still holds play bodies moves them there the
first time it is edited.
A *sequence* of those states, such as the steps of a wizard or the pages of a
questionnaire, is still a control. Declare the steps in the page's mocks and walk
them from a `play` on the meta, so every story of the page inherits the walk and
only sets `args`:
```tsx
play: async ({ mount, args, canvasElement }): Promise<void> => {
// stories/__story_mockdata__/<page>.play.ts
export async function walkToStep({
mount,
args,
canvasElement,
}: {
mount: () => Promise<unknown>;
args: { step: WizardStep };
canvasElement: HTMLElement;
}): Promise<void> {
await mount();
await advanceToStep(canvasElement, args.step);
},
}
// <Page>.stories.tsx, on the meta
play: walkToStep,
```
Destructuring `mount` is what makes the panel row work. Storybook replays a play

View File

@@ -10,7 +10,7 @@
#### Unit Testing: What, Why, How
- What: Small, isolated tests for components, hooks, and utilities to verify behavior and edge cases.
- Why: Confidence to refactor, faster feedback than E2E, catches regressions early, documents intended behavior.
- How: Use our test harness with providers, mock external boundaries (APIs, router), assert on visible behavior and accessible roles, not implementation details.
- How: Use our test harness with providers, mock external boundaries (APIs), find elements by test ID, and assert on visible behavior, not implementation details.
#### Basic Template
```ts
@@ -29,18 +29,20 @@ describe('MyComponent', () => {
render(<MyComponent />, undefined, { initialRoute: '/foo' });
expect(await screen.findByText(/value: 42/i)).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /refresh/i }));
await user.click(screen.getByTestId('refresh-button'));
await waitFor(() => expect(screen.getByText(/loading/i)).toBeInTheDocument());
});
});
```
#### .cursorrules (Highlights)
#### Rules (highlights)
The full list is [`.claude/rules/frontend-tests.md`](../../../.claude/rules/frontend-tests.md).
- Import from `tests/test-utils` only.
- Prefer `userEvent` for real interactions; use `fireEvent` only for low-level events (scroll/resize/setting `scrollTop`).
- Use MSW to mock network calls; large JSON goes in `mocks-server/__mockdata__`.
- Keep tests type-safe (`jest.MockedFunction<T>`, avoid `any`).
- Prefer accessible queries (`getByRole`, `findByRole`) before text and `data-testid`.
- Find elements by test ID (`getByTestId`, `findByTestId`); role or text only for markup the app doesn't own.
- Pin time only when asserting relative dates; avoid global fake timers otherwise.
Repo-specific reasons:
@@ -69,10 +71,10 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
}));
```
Interact via accessible roles:
Interact via test IDs:
```ts
const user = userEvent.setup({ pointerEventsCheck: 0 });
await user.click(screen.getByRole('button', { name: /save changes/i }));
await user.click(screen.getByTestId('save-changes'));
expect(screen.getByText(/ADDED FILTERS/i)).toBeInTheDocument();
```

View File

@@ -190,7 +190,7 @@ const customRender = (
} = providerProps;
return render(ui, {
wrapper: () => (
wrapper: ({ children }) => (
<AllTheProviders
role={role}
appContextOverrides={appContextOverrides}
@@ -198,7 +198,7 @@ const customRender = (
initialRoute={initialRoute}
routePath={routePath}
>
{ui}
{children}
</AllTheProviders>
),
...options,

View File

@@ -0,0 +1,22 @@
import ROUTES from 'constants/routes';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { buildExplorerNavigationUrl } from '../buildExplorerNavigationUrl';
describe('buildExplorerNavigationUrl', () => {
it('encodes composite query and view selectors', () => {
const url = buildExplorerNavigationUrl(
ROUTES.LOGS_EXPLORER,
{ queryType: 'builder' } as never,
{
[QueryParams.panelTypes]: PANEL_TYPES.LIST,
[QueryParams.viewKey]: 'view-1',
},
);
expect(url).toContain(ROUTES.LOGS_EXPLORER);
expect(url).toContain(`${QueryParams.compositeQuery}=`);
expect(url).toContain(`${QueryParams.viewKey}=`);
});
});

View File

@@ -1,6 +1,6 @@
import { NANO_SECOND_MULTIPLIER } from 'store/globalTime';
import { timeParamsFromGlobalTime } from '../timeUrlParams';
import { timeParamsFromGlobalTime } from 'utils/timeUrlParams';
describe('timeParamsFromGlobalTime', () => {
it('emits relativeTime for a relative selection', () => {

View File

@@ -0,0 +1,22 @@
import { QueryParams } from 'constants/query';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
/**
* Builds an explorer URL the same way `redirectWithQueryBuilderData` does —
* without inheriting stale query params from the current page's `urlQuery`.
*/
export function buildExplorerNavigationUrl(
route: string,
query: Query,
searchParams: Record<string, unknown>,
): string {
const params = new URLSearchParams();
params.set(
QueryParams.compositeQuery,
encodeURIComponent(JSON.stringify(query)),
);
Object.entries(searchParams).forEach(([key, value]) => {
params.set(key, JSON.stringify(value));
});
return `${route}?${params.toString()}`;
}