Compare commits

...

3 Commits

Author SHA1 Message Date
Alan Buscaglia
cca5c52a15 docs(skills): add guardrails for review-driven UI patterns
- Add batch/instant API contract and derived-state guardrails to prowler-ui

- Add coupled optional props rule to TypeScript skill

- Add pre-re-review thread hygiene checklist to prowler-pr
2026-03-20 12:53:42 +01:00
Alan Buscaglia
8604215b99 fix(ui): finalize reviewer feedback for findings batch filters
- Enforce batch/instant props with discriminated unions in filter components

- Add strict FilterParam typing for findings filter labels

- Simplify apply button label logic and clarify batch hook comments
2026-03-20 12:53:33 +01:00
Alan Buscaglia
1116228fc2 fix(ui): polish findings filter chips and pending count
- Hide default muted=false from summary chips

- Exclude muted=false from pending clear-filters count

- Keep inserted_at chip value as ISO date string
2026-03-20 12:08:20 +01:00
11 changed files with 293 additions and 55 deletions

View File

@@ -132,6 +132,18 @@ Follow conventional commits:
4. ✅ Branch is up to date with main
5. ✅ Commits are clean and descriptive
## Before Re-Requesting Review (REQUIRED)
Resolve or respond to **every** open inline review thread before re-requesting review:
1. **Agreed + fixed**: Commit the change. Reply with the commit hash so the reviewer can verify quickly:
> Fixed in `abc1234`.
2. **Agreed but deferred**: Explain why it's out of scope for this PR and where it's tracked.
3. **Disagreed**: Reply with clear technical reasoning. Do not leave threads silently open.
4. **Re-request review** only after all threads are in a clean state — either resolved or explicitly responded to.
> **Rule of thumb**: A reviewer should never have to wonder "did they see my comment?" when they re-open the PR.
## Resources
- **Documentation**: See [references/](references/) for links to local developer guide

View File

@@ -186,6 +186,109 @@ cd ui && pnpm run build
cd ui && pnpm start
```
## Batch vs Instant Component API (REQUIRED)
When a component supports both **batch** (deferred, submit-based) and **instant** (immediate callback) behavior, model the coupling with a discriminated union — never as independent optionals. Coupled props must be all-or-nothing.
```typescript
// ❌ NEVER: Independent optionals — allows invalid half-states
interface FilterProps {
onBatchApply?: (values: string[]) => void;
onInstantChange?: (value: string) => void;
isBatchMode?: boolean;
}
// ✅ ALWAYS: Discriminated union — one valid shape per mode
type BatchProps = {
mode: "batch";
onApply: (values: string[]) => void;
onCancel: () => void;
};
type InstantProps = {
mode: "instant";
onChange: (value: string) => void;
// onApply/onCancel are forbidden here via structural exclusion
onApply?: never;
onCancel?: never;
};
type FilterProps = BatchProps | InstantProps;
```
This makes invalid prop combinations a compile error, not a runtime surprise.
## Reuse Shared Display Utilities First (REQUIRED)
Before adding **local** display maps (labels, provider names, status strings, category formatters), search `ui/types/*` and `ui/lib/*` for existing helpers.
```typescript
// ✅ CHECK THESE FIRST before creating a new map:
// ui/lib/utils.ts → general formatters
// ui/types/providers.ts → provider display names, icons
// ui/types/findings.ts → severity/status display maps
// ui/types/compliance.ts → category/group formatters
// ❌ NEVER add a local map that already exists:
const SEVERITY_LABELS: Record<string, string> = {
critical: "Critical",
high: "High",
// ...duplicating an existing shared map
};
// ✅ Import and reuse instead:
import { severityLabel } from "@/types/findings";
```
If a helper doesn't exist and will be used in 2+ places, add it to `ui/lib/` or `ui/types/` and reuse it. Keep local only if used in exactly one place.
## Derived State Rule (REQUIRED)
Avoid `useState` + `useEffect` patterns that mirror props or searchParams — they create sync bugs and unnecessary re-renders. Derive values directly from the source of truth.
```typescript
// ❌ NEVER: Mirror props into state via effect
const [localFilter, setLocalFilter] = useState(filter);
useEffect(() => { setLocalFilter(filter); }, [filter]);
// ✅ ALWAYS: Derive directly
const localFilter = filter; // or compute inline
```
If local state is genuinely needed (e.g., optimistic UI, pending edits before submit), add a short comment:
```typescript
// Local state needed: user edits are buffered until "Apply" is clicked
const [pending, setPending] = useState(initialValues);
```
## Strict Key Typing for Label Maps (REQUIRED)
Avoid `Record<string, string>` when the key set is known. Use an explicit union type or a const-key object so typos are caught at compile time.
```typescript
// ❌ Loose — typos compile silently
const STATUS_LABELS: Record<string, string> = {
actve: "Active", // typo, no error
};
// ✅ Tight — union key
type Status = "active" | "inactive" | "pending";
const STATUS_LABELS: Record<Status, string> = {
active: "Active",
inactive: "Inactive",
pending: "Pending",
// actve: "Active" ← compile error
};
// ✅ Also fine — const satisfies
const STATUS_LABELS = {
active: "Active",
inactive: "Inactive",
pending: "Pending",
} as const satisfies Record<Status, string>;
```
## QA Checklist Before Commit
- [ ] `pnpm run typecheck` passes
@@ -199,6 +302,15 @@ cd ui && pnpm start
- [ ] Accessibility: keyboard navigation, ARIA labels
- [ ] Mobile responsive (if applicable)
## Pre-Re-Review Checklist (Review Thread Hygiene)
Before requesting re-review from a reviewer:
- [ ] Every unresolved inline thread has been either fixed or explicitly answered with a rationale
- [ ] If you agreed with a comment: the change is committed and the commit hash is mentioned in the reply
- [ ] If you disagreed: the reply explains why with clear reasoning — do not leave threads silently open
- [ ] Re-request review only after all threads are in a clean state
## Migrations Reference
| From | To | Key Changes |

View File

@@ -102,6 +102,38 @@ function isUser(value: unknown): value is User {
}
```
## Coupled Optional Props (REQUIRED)
Do not model semantically coupled props as independent optionals — this allows invalid half-states that compile but break at runtime. Use discriminated unions with `never` to make invalid combinations impossible.
```typescript
// ❌ BEFORE: Independent optionals — half-states allowed
interface PaginationProps {
onPageChange?: (page: number) => void;
pageSize?: number;
currentPage?: number;
}
// ✅ AFTER: Discriminated union — shape is all-or-nothing
type ControlledPagination = {
controlled: true;
currentPage: number;
pageSize: number;
onPageChange: (page: number) => void;
};
type UncontrolledPagination = {
controlled: false;
currentPage?: never;
pageSize?: never;
onPageChange?: never;
};
type PaginationProps = ControlledPagination | UncontrolledPagination;
```
**Key rule:** If two or more props are only meaningful together, they belong to the same discriminated union branch. Mixing them as independent optionals shifts correctness responsibility from the type system to runtime guards.
## Import Types
```typescript

View File

@@ -50,23 +50,9 @@ const PROVIDER_ICON: Record<ProviderType, ReactNode> = {
openstack: <OpenStackProviderBadge width={18} height={18} />,
};
interface AccountsSelectorProps {
/** Common props shared by both batch and instant modes. */
interface AccountsSelectorBaseProps {
providers: ProviderProps[];
/**
* When provided, called instead of navigating immediately.
* Use this on pages that batch filter changes (e.g. Findings).
* The Overview page omits this prop to keep instant-apply behavior.
*
* @param filterKey - The raw filter key without "filter[]" wrapper, e.g. "provider_id__in"
* @param values - The selected values array
*/
onBatchChange?: (filterKey: string, values: string[]) => void;
/**
* When in batch mode, pass the pending selected values from the parent.
* This allows the component to reflect pending state before Apply is clicked.
* Ignored when `onBatchChange` is not provided (URL-driven mode).
*/
selectedValues?: string[];
/**
* Currently selected provider types (from the pending ProviderTypeSelector state).
* Used only for contextual description/empty-state messaging — does NOT narrow
@@ -75,6 +61,33 @@ interface AccountsSelectorProps {
selectedProviderTypes?: string[];
}
/** Batch mode: caller controls both pending state and notification callback (all-or-nothing). */
interface AccountsSelectorBatchProps extends AccountsSelectorBaseProps {
/**
* Called instead of navigating immediately.
* Use this on pages that batch filter changes (e.g. Findings).
*
* @param filterKey - The raw filter key without "filter[]" wrapper, e.g. "provider_id__in"
* @param values - The selected values array
*/
onBatchChange: (filterKey: string, values: string[]) => void;
/**
* Pending selected values controlled by the parent.
* Reflects pending state before Apply is clicked.
*/
selectedValues: string[];
}
/** Instant mode: URL-driven — neither callback nor controlled value. */
interface AccountsSelectorInstantProps extends AccountsSelectorBaseProps {
onBatchChange?: never;
selectedValues?: never;
}
type AccountsSelectorProps =
| AccountsSelectorBatchProps
| AccountsSelectorInstantProps;
export function AccountsSelector({
providers,
onBatchChange,
@@ -89,7 +102,7 @@ export function AccountsSelector({
const urlSelectedIds = current ? current.split(",").filter(Boolean) : [];
// In batch mode, use the parent-controlled pending values; otherwise, use URL state.
const selectedIds = onBatchChange ? (selectedValues ?? []) : urlSelectedIds;
const selectedIds = onBatchChange ? selectedValues : urlSelectedIds;
const visibleProviders = providers;
// .filter((p) => p.attributes.connection?.connected)

View File

@@ -152,24 +152,38 @@ const PROVIDER_DATA: Record<
},
};
type ProviderTypeSelectorProps = {
/** Common props shared by both batch and instant modes. */
interface ProviderTypeSelectorBaseProps {
providers: ProviderProps[];
}
/** Batch mode: caller controls both pending state and notification callback (all-or-nothing). */
interface ProviderTypeSelectorBatchProps extends ProviderTypeSelectorBaseProps {
/**
* When provided, called instead of navigating immediately.
* Called instead of navigating immediately.
* Use this on pages that batch filter changes (e.g. Findings).
* The Overview page omits this prop to keep instant-apply behavior.
*
* @param filterKey - The raw filter key without "filter[]" wrapper, e.g. "provider_type__in"
* @param values - The selected values array
*/
onBatchChange?: (filterKey: string, values: string[]) => void;
onBatchChange: (filterKey: string, values: string[]) => void;
/**
* When in batch mode, pass the pending selected values from the parent.
* This allows the component to reflect pending state before Apply is clicked.
* Ignored when `onBatchChange` is not provided (URL-driven mode).
* Pending selected values controlled by the parent.
* Reflects pending state before Apply is clicked.
*/
selectedValues?: string[];
};
selectedValues: string[];
}
/** Instant mode: URL-driven — neither callback nor controlled value. */
interface ProviderTypeSelectorInstantProps
extends ProviderTypeSelectorBaseProps {
onBatchChange?: never;
selectedValues?: never;
}
type ProviderTypeSelectorProps =
| ProviderTypeSelectorBatchProps
| ProviderTypeSelectorInstantProps;
export const ProviderTypeSelector = ({
providers,
@@ -185,9 +199,7 @@ export const ProviderTypeSelector = ({
: [];
// In batch mode, use the parent-controlled pending values; otherwise, use URL state.
const selectedTypes = onBatchChange
? (selectedValues ?? [])
: urlSelectedTypes;
const selectedTypes = onBatchChange ? selectedValues : urlSelectedTypes;
const handleMultiValueChange = (values: string[]) => {
if (onBatchChange) {

View File

@@ -33,11 +33,8 @@ export const ApplyFiltersButton = ({
onDiscard,
className,
}: ApplyFiltersButtonProps) => {
const label = hasChanges
? changeCount > 0
? `Apply Filters (${changeCount})`
: "Apply Filters"
: "Apply Filters";
const label =
changeCount > 0 ? `Apply Filters (${changeCount})` : "Apply Filters";
return (
<div className={cn("flex items-center gap-1", className)}>

View File

@@ -11,21 +11,31 @@ const MUTED_FILTER_VALUES = {
INCLUDE: "include",
} as const;
interface CustomCheckboxMutedFindingsProps {
/** Batch mode: caller controls both the checked state and the notification callback (all-or-nothing). */
interface CustomCheckboxMutedFindingsBatchProps {
/**
* Called in batch mode instead of navigating directly.
* Called instead of navigating directly.
* Receives the filter key ("muted") and the string value ("include" or "false").
* When provided, the component does NOT call `navigateWithParams`.
*/
onBatchChange?: (filterKey: string, value: string) => void;
onBatchChange: (filterKey: string, value: string) => void;
/**
* Controlled checked state override for batch mode.
* When provided, this value is used as the checkbox state instead of reading from URL params.
* Controlled checked state from the parent (pending state).
* `true` = include muted, `false` = exclude muted.
* `undefined` defers to URL state while pending state is not yet set.
*/
checked?: boolean;
checked: boolean | undefined;
}
/** Instant mode: URL-driven — neither callback nor controlled value. */
interface CustomCheckboxMutedFindingsInstantProps {
onBatchChange?: never;
checked?: never;
}
type CustomCheckboxMutedFindingsProps =
| CustomCheckboxMutedFindingsBatchProps
| CustomCheckboxMutedFindingsInstantProps;
export const CustomCheckboxMutedFindings = ({
onBatchChange,
checked: checkedProp,

View File

@@ -14,21 +14,30 @@ import {
import { useUrlFilters } from "@/hooks/use-url-filters";
import { cn } from "@/lib/utils";
interface CustomDatePickerProps {
/** Batch mode: caller controls both the pending date value and the notification callback (all-or-nothing). */
interface CustomDatePickerBatchProps {
/**
* Called in batch mode instead of updating the URL directly.
* Receives the filter key and the formatted date string (YYYY-MM-DD).
* When provided, the component does NOT call `updateFilter`.
* Called instead of updating the URL directly.
* Receives the filter key ("inserted_at") and the formatted date string (YYYY-MM-DD).
*/
onBatchChange?: (filterKey: string, value: string) => void;
onBatchChange: (filterKey: string, value: string) => void;
/**
* Controlled value override for batch mode.
* When provided, this value is used as the displayed date instead of reading from URL params.
* Controlled date value from the parent (pending state).
* Expected format: YYYY-MM-DD (or any value parseable by `new Date()`).
*/
value?: string;
value: string | undefined;
}
/** Instant mode: URL-driven — neither callback nor controlled value. */
interface CustomDatePickerInstantProps {
onBatchChange?: never;
value?: never;
}
type CustomDatePickerProps =
| CustomDatePickerBatchProps
| CustomDatePickerInstantProps;
const parseDate = (raw: string | null | undefined): Date | undefined => {
if (!raw) return undefined;
try {

View File

@@ -20,7 +20,7 @@ import { DataTableFilterCustom } from "@/components/ui/table";
import { useFilterBatch } from "@/hooks/use-filter-batch";
import { formatLabel, getCategoryLabel, getGroupLabel } from "@/lib/categories";
import { FilterType, FINDING_STATUS_DISPLAY_NAMES, ScanEntity } from "@/types";
import { DATA_TABLE_FILTER_MODE } from "@/types/filters";
import { DATA_TABLE_FILTER_MODE, FilterParam } from "@/types/filters";
import { getProviderDisplayName, ProviderProps } from "@/types/providers";
import { SEVERITY_DISPLAY_NAMES } from "@/types/severities";
@@ -39,8 +39,10 @@ interface FindingsFiltersProps {
/**
* Maps raw filter param keys (e.g. "filter[severity__in]") to human-readable labels.
* Used to render chips in the FilterSummaryStrip.
* Typed as Record<FilterParam, string> so TypeScript enforces exhaustiveness — any
* addition to FilterParam will cause a compile error here if the label is missing.
*/
const FILTER_KEY_LABELS: Record<string, string> = {
const FILTER_KEY_LABELS: Record<FilterParam, string> = {
"filter[provider_type__in]": "Provider",
"filter[provider_id__in]": "Account",
"filter[severity__in]": "Severity",
@@ -63,6 +65,7 @@ const FILTER_KEY_LABELS: Record<string, string> = {
* - Status: uses shared FINDING_STATUS_DISPLAY_NAMES (e.g. "FAIL" → "Fail")
* - Categories: uses getCategoryLabel (handles IAM, EC2, IMDSv1, etc.)
* - Resource groups: uses getGroupLabel (underscore-delimited)
* - Date (filter[inserted_at]): returns the ISO date string as-is (YYYY-MM-DD)
* - Other values: uses formatLabel as a generic fallback (avoids naive capitalisation)
*/
const formatFilterValue = (filterKey: string, value: string): string => {
@@ -90,6 +93,10 @@ const formatFilterValue = (filterKey: string, value: string): string => {
if (filterKey === "filter[resource_groups__in]") {
return getGroupLabel(value);
}
// Date filter: preserve ISO date string (YYYY-MM-DD) — do not run through formatLabel
if (filterKey === "filter[inserted_at]") {
return value;
}
// Generic fallback: handles hyphen/underscore-delimited IDs with smart capitalisation
return formatLabel(value);
};
@@ -165,12 +172,15 @@ export const FindingsFilters = ({
const hasCustomFilters = customFilters.length > 0;
// Build FilterChip[] from pendingFilters — one chip per individual value, not per key
// Build FilterChip[] from pendingFilters — one chip per individual value, not per key.
// Skip filter[muted]="false" — it is the silent default and should not appear as a chip.
const filterChips: FilterChip[] = [];
Object.entries(pendingFilters).forEach(([key, values]) => {
if (!values || values.length === 0) return;
const label = FILTER_KEY_LABELS[key] ?? key;
const label = FILTER_KEY_LABELS[key as FilterParam] ?? key;
values.forEach((value) => {
// Do not show a chip for the default muted=false state
if (key === "filter[muted]" && value === "false") return;
filterChips.push({
key,
label,
@@ -244,7 +254,17 @@ export const FindingsFilters = ({
showCount
onClear={clearAll}
pendingCount={
Object.values(pendingFilters).filter((v) => v.length > 0).length
Object.entries(pendingFilters).filter(([key, values]) => {
if (!values || values.length === 0) return false;
// filter[muted]=false is the silent default — don't count it as active
if (
key === "filter[muted]" &&
values.length === 1 &&
values[0] === "false"
)
return false;
return true;
}).length
}
/>
<ApplyFiltersButton

View File

@@ -165,7 +165,8 @@ export const useFilterBatch = (
};
const applyAll = () => {
// Start from the current URL params to preserve non-batch params (e.g. filter[search])
// Start from the current URL params to preserve non-batch params.
// Only filter[search] is excluded from batch management and preserved from the URL as-is.
const params = new URLSearchParams(searchParams.toString());
// Remove all existing batch-managed filter params

View File

@@ -55,3 +55,23 @@ export const DATA_TABLE_FILTER_MODE = {
export type DataTableFilterMode =
(typeof DATA_TABLE_FILTER_MODE)[keyof typeof DATA_TABLE_FILTER_MODE];
/**
* Exhaustive union of all URL filter param keys used in Findings filters.
* Use this instead of `string` to ensure FILTER_KEY_LABELS and other
* param-keyed records stay in sync with the actual filter surface.
*/
export type FilterParam =
| "filter[provider_type__in]"
| "filter[provider_id__in]"
| "filter[severity__in]"
| "filter[status__in]"
| "filter[delta__in]"
| "filter[region__in]"
| "filter[service__in]"
| "filter[resource_type__in]"
| "filter[category__in]"
| "filter[resource_groups__in]"
| "filter[scan__in]"
| "filter[inserted_at]"
| "filter[muted]";