From db8b87f95c49a35899fbde83c35030dc787172a1 Mon Sep 17 00:00:00 2001 From: Mark Hazleton Date: Sat, 21 Nov 2026 20:47:09 -0600 Subject: [PATCH 1/4] feat(dashboard): unified operator experience with one scope Self-hosted dashboard: - Scope selector (client, source, repository, domain filters) held in the URL, changed without a reload, followed by every section including Security; old ?user= links still work. - Alert counts in Health, the drawer, the fix-score prompt and exports come from the stored Dependabot alerts; missing readings show why. - Security rows open the repository drawer, which gains a Security panel. - Shared page header, filter bar, data table and coverage state; Security exports through ExportButton (CSV now neutralises formulas everywhere). - Sections from one list (Admin replaces Sources, #sources still works); mobile tab bar puts overflow behind More. - "Reload data" and "Collect now" name the two refresh actions. - Unused layout and mobile components removed. The public Pages dashboard renders Overview, Insights and Health unchanged. Co-Authored-By: Claude Opus 5.5 --- .../002-work-ps-022-unified-operator/work.md | 100 +++ .documentation/guides/DOCKER_DEPLOYMENT.md | 24 +- frontend/src/App.jsx | 580 ++++++++---------- frontend/src/components/Admin/SourcesView.jsx | 22 +- .../components/Attention/AttentionView.jsx | 20 +- .../src/components/Common/CoverageState.jsx | 92 +++ frontend/src/components/Common/DataTable.jsx | 76 +++ .../components/Common/DataViews.module.css | 106 ++++ .../src/components/Common/ExportButton.jsx | 224 +++---- frontend/src/components/Common/FilterBar.jsx | 63 ++ frontend/src/components/Common/PageHeader.jsx | 59 ++ .../src/components/Common/ScopeSelector.jsx | 133 ++++ .../Common/ScopeSelector.module.css | 26 + frontend/src/components/Common/Tooltip.jsx | 93 --- .../src/components/Common/Tooltip.module.css | 107 ---- frontend/src/components/Common/UserPicker.jsx | 97 --- .../components/Common/UserPicker.module.css | 25 - .../components/DrillDown/RepositoryDetail.jsx | 10 + .../hooks/useSectionToggles.js | 1 + .../sections/SecuritySection.jsx | 61 ++ .../components/Layout/Container/Container.css | 51 -- .../components/Layout/Container/Container.jsx | 44 -- .../components/Layout/SafeArea/SafeArea.css | 8 - .../components/Layout/SafeArea/SafeArea.jsx | 33 - .../components/Layout/SkipLink/SkipLink.css | 39 -- .../components/Layout/SkipLink/SkipLink.jsx | 18 - .../src/components/Layout/Stack/Stack.css | 57 -- .../src/components/Layout/Stack/Stack.jsx | 60 -- .../Mobile/BottomSheet/BottomSheet.css | 146 ----- .../Mobile/BottomSheet/BottomSheet.jsx | 141 ----- .../Mobile/GestureHandler/GestureHandler.css | 149 ----- .../Mobile/GestureHandler/GestureHandler.jsx | 158 ----- .../Mobile/LoadingState/LoadingState.css | 110 ---- .../Mobile/LoadingState/LoadingState.jsx | 87 --- .../src/components/Mobile/TabBar/TabBar.css | 41 ++ .../src/components/Mobile/TabBar/TabBar.jsx | 143 +++-- .../Mobile/TouchTarget/TouchTarget.css | 11 - .../Mobile/TouchTarget/TouchTarget.jsx | 76 --- .../src/components/Security/SecurityView.jsx | 292 +++------ .../Security/SecurityView.module.css | 100 +-- .../src/components/Security/alertColumns.jsx | 115 ++++ frontend/src/components/Shell/AppFooter.jsx | 78 +++ frontend/src/components/Shell/AppHeader.jsx | 100 +++ frontend/src/config/sections.js | 118 ++++ frontend/src/hooks/useBottomSheet.js | 132 ---- frontend/src/hooks/useDashboardShell.js | 41 +- frontend/src/hooks/usePortfolio.js | 106 ++++ frontend/src/hooks/useRepositoryData.js | 112 ++-- frontend/src/hooks/useScope.js | 39 ++ frontend/src/hooks/useUserOptions.js | 94 --- frontend/src/utils/dependabot.js | 6 + frontend/src/utils/scope.js | 181 ++++++ frontend/src/utils/scopedData.js | 61 ++ frontend/src/utils/storedAlerts.js | 106 ++++ frontend/tests/App.test.jsx | 270 +++++++- frontend/tests/AttentionView.test.jsx | 22 +- frontend/tests/RepositoryDetail.test.jsx | 75 +++ frontend/tests/Scope.test.jsx | 401 ++++++++++++ frontend/tests/SecurityView.test.jsx | 46 +- frontend/tests/SharedComponents.test.jsx | 256 ++++++++ frontend/tests/SourcesView.test.jsx | 4 +- frontend/tests/UserPicker.test.jsx | 196 ------ 62 files changed, 3439 insertions(+), 2803 deletions(-) create mode 100644 .devspark.work/specs/002-work-ps-022-unified-operator/work.md create mode 100644 frontend/src/components/Common/CoverageState.jsx create mode 100644 frontend/src/components/Common/DataTable.jsx create mode 100644 frontend/src/components/Common/DataViews.module.css create mode 100644 frontend/src/components/Common/FilterBar.jsx create mode 100644 frontend/src/components/Common/PageHeader.jsx create mode 100644 frontend/src/components/Common/ScopeSelector.jsx create mode 100644 frontend/src/components/Common/ScopeSelector.module.css delete mode 100644 frontend/src/components/Common/Tooltip.jsx delete mode 100644 frontend/src/components/Common/Tooltip.module.css delete mode 100644 frontend/src/components/Common/UserPicker.jsx delete mode 100644 frontend/src/components/Common/UserPicker.module.css create mode 100644 frontend/src/components/DrillDown/RepositoryDetail/sections/SecuritySection.jsx delete mode 100644 frontend/src/components/Layout/Container/Container.css delete mode 100644 frontend/src/components/Layout/Container/Container.jsx delete mode 100644 frontend/src/components/Layout/SafeArea/SafeArea.css delete mode 100644 frontend/src/components/Layout/SafeArea/SafeArea.jsx delete mode 100644 frontend/src/components/Layout/SkipLink/SkipLink.css delete mode 100644 frontend/src/components/Layout/SkipLink/SkipLink.jsx delete mode 100644 frontend/src/components/Layout/Stack/Stack.css delete mode 100644 frontend/src/components/Layout/Stack/Stack.jsx delete mode 100644 frontend/src/components/Mobile/BottomSheet/BottomSheet.css delete mode 100644 frontend/src/components/Mobile/BottomSheet/BottomSheet.jsx delete mode 100644 frontend/src/components/Mobile/GestureHandler/GestureHandler.css delete mode 100644 frontend/src/components/Mobile/GestureHandler/GestureHandler.jsx delete mode 100644 frontend/src/components/Mobile/LoadingState/LoadingState.css delete mode 100644 frontend/src/components/Mobile/LoadingState/LoadingState.jsx delete mode 100644 frontend/src/components/Mobile/TouchTarget/TouchTarget.css delete mode 100644 frontend/src/components/Mobile/TouchTarget/TouchTarget.jsx create mode 100644 frontend/src/components/Security/alertColumns.jsx create mode 100644 frontend/src/components/Shell/AppFooter.jsx create mode 100644 frontend/src/components/Shell/AppHeader.jsx create mode 100644 frontend/src/config/sections.js delete mode 100644 frontend/src/hooks/useBottomSheet.js create mode 100644 frontend/src/hooks/usePortfolio.js create mode 100644 frontend/src/hooks/useScope.js delete mode 100644 frontend/src/hooks/useUserOptions.js create mode 100644 frontend/src/utils/scope.js create mode 100644 frontend/src/utils/scopedData.js create mode 100644 frontend/src/utils/storedAlerts.js create mode 100644 frontend/tests/Scope.test.jsx create mode 100644 frontend/tests/SharedComponents.test.jsx delete mode 100644 frontend/tests/UserPicker.test.jsx diff --git a/.devspark.work/specs/002-work-ps-022-unified-operator/work.md b/.devspark.work/specs/002-work-ps-022-unified-operator/work.md new file mode 100644 index 00000000..1b281ac9 --- /dev/null +++ b/.devspark.work/specs/002-work-ps-022-unified-operator/work.md @@ -0,0 +1,100 @@ +# Work: ps-022 Unified operator experience + +**Status**: Complete (implemented and validated locally 2026-11-22, not yet committed) +**Branch**: 002-work-ps-022-unified-operator (from main 54a09ef) +**Source**: roadmap item ps-022 (`.devspark.work/roadmap/specs/ps-022-unified-operator-experience.md`) + +## Intended outcome + +One consistent self-hosted app: a single scope selector (portfolio → client → source → repository, plus +domain filters) that every view honours, fixed sections, shared page building blocks, one source per +number, and views that link to each other. The public GitHub Pages dashboard is unchanged. The whole +item ships in one PR (developer decision, 2026-11-22, chose this over splitting). + +## Acceptance evidence + +- Choosing a client, source, or repository changes every view, Security included, with no page reload, + and the URL restores it. The old `?user=` links and the existing hashes keep working. +- Health, the drawer, and the fix-score prompt show the same open-alert count as Security for a + repository with more than 100 alerts. All three read the ps-006 store in self-hosted mode. +- A Security row opens the repository drawer, and the drawer has a Security panel with that repository's + alerts. +- Every table exports through `ExportButton`. Security drops its own CSV code. +- One shared coverage/state component shows zero, unavailable, unauthorized, unsupported, and stale + distinctly, and every view uses it. +- There is one shared page header, filter bar (including domain filters), and data table. +- Sections: Overview, Health, Security, Sites, Delivery, Presence, Admin. A section appears only when it + has data. The mobile tab bar holds the primary sections and puts the rest behind an overflow. +- No unused component remains. `EmptyState`, `GestureHandler`, `TouchTarget`, `SafeArea`, and the mobile + `LoadingState` are each either adopted or removed, and the two `LoadingState`s become one. +- The refresh actions are labelled "Reload data" (browser cache) and "Collect now" (worker). +- The public Pages build renders Overview, Insights, Health, and the drawer unchanged. +- vitest covers scope switching, cross-links, the shared components, and accessibility. Existing tests + pass, and `./run-validation.ps1` exits 0. + +## Material exclusions + +- No content for undelivered sections: Sites, Delivery, and Presence stay hidden. +- No rebranding. +- No per-client access control. +- No change to the attention-score model beyond its data source. + +## Operating assumptions + +- Self-hosted mode is detected by the existing data files. `portfolio.json` and + `security/dependabot.json` are present only on the self-hosted server. The admin API is optional. +- The decision owner is the developer, a single administrator. + +## Facts verified at start (main 54a09ef) + +- `useDependabot.js` always loads the portfolio-wide `data/security/dependabot.json`. Security ignores + `?user=`. +- `dataService.js` loads `data/users//repositories.json` for the `?user=` source. Choosing a source + calls `window.location.reload()`. +- `FixScorePromptSection.jsx` reads `security.dependabot.total_open`, the fetcher's first-page summary. +- The per-source `repositories.json` is written by `worker/loop.py` without reading the registry, so it + has no classifications. Client, project, application, and domain values exist only in `portfolio.json`. +- The unused mobile/layout components listed in the spec exist under `components/Mobile` and + `components/Layout`. + +## Open design point (decide during implementation, from evidence) + +- **Portfolio and client scope span several sources**, but repository data is stored per source. + - Option A: the frontend loads the needed per-source files and de-duplicates them by `full_name`. + - Option B: the worker writes one portfolio-wide repositories file. + - Prefer A unless loading many sources is measurably slow. + - Classifications are joined from `portfolio.json` by `full_name`, which fills the per-source gap + recorded at ps-023 closeout. + +## Invariants + +- Domain invariant: a repository is identified by its case-insensitive `full_name` in every scope and + view, so the same repository shows the same counts everywhere. +- Architectural constraint: public mode never requests the admin API or self-hosted-only files in a way + that breaks or changes the Pages build. + +## Verification expectations + +- Public Pages build: `verify:snapshot-neutral`. The Overview, Insights, Health, and drawer output must be + unchanged in public mode. +- If the worker export changes (Option B, or added fields): `verify:end-to-end` against a real worker + run. Checking it on the server after deploy is a `stage: post-deploy` item, not pre-merge proof. + +## Material decisions (implementation) + +- Open design point resolved as Option A. The browser loads the per-source files the scope needs and + joins classifications from `portfolio.json`; no worker change. +- Insights is kept as a section (the public view requires it), alongside the listed sections. +- Stored alert counts replace the collected counts everywhere they are shown. The attention score is + still computed at collection time; recomputing it would change the score model, which is out of scope. + +## Known differences (not defects of this change) + +- On server data (2026-11-22), the per-source files hold 38 repositories while the portfolio and + Security list 45. The collector writes fewer records than discovery finds, so Overview and Security + can list different repository sets. + +## Next action + +Commit, then `/devspark-create-pr`. After deploy: pick a client and a domain filter on the server, +and confirm that Security and Health follow the choice and show the same alert counts. diff --git a/.documentation/guides/DOCKER_DEPLOYMENT.md b/.documentation/guides/DOCKER_DEPLOYMENT.md index 8b21bd8a..58193ac2 100644 --- a/.documentation/guides/DOCKER_DEPLOYMENT.md +++ b/.documentation/guides/DOCKER_DEPLOYMENT.md @@ -58,7 +58,7 @@ keeps private data out of this release). Prefer a secret file over `GITHUB_TOKEN 2. Stack variables: `SPARK_USER`, `GITHUB_TOKEN` (or the secret-file approach), `BIND_ADDRESS=192.168.1.197`, `WEB_PORT=8086`. 3. Deploy. Both containers become healthy; the worker collects on start and then every interval. -4. Refresh now: restart the `worker` container in Portainer. +4. To collect immediately, use **Collect now** in Admin, or restart the `worker` container in Portainer. 5. Browse to `http://192.168.1.197:8086` from the LAN. The default bind is `127.0.0.1`; the app has no authentication yet, so keep it on the trusted LAN and do @@ -134,7 +134,25 @@ dashboard shows a **Sources** page only when the API answers; on GitHub Pages it encrypted at rest. A token's expiry is tracked: the page warns when one is within 14 days, and a source whose token has expired reports `connection_unusable` instead of silently using another. Sources without a token use the stack's `GITHUB_TOKEN`. -- **Refresh now:** asks the worker to collect; it starts within seconds. +- **Collect now:** asks the worker to collect; it starts within seconds. + +**Scope and sections** +- **Scope:** the bar under the header chooses what every section shows: the whole portfolio, a + client (repositories with no client are **Internal**), a source, or one repository, filtered by + any domain value. Each list offers only choices within the levels above it. The scope is part of + the URL (`?client=Acme&source=acme&repo=Acme/web&d.tier=core`), so a link or reload restores it; + older `?user=` links still work. Overview, Insights, Health and Security all follow it. +- **Sections:** Overview, Insights, Health, Security and Admin. Sites, Delivery and Presence appear + only once those capabilities collect data. Old `#sources` links open Admin. On a phone, sections + that do not fit in the bottom bar are under **More**. +- **One number per fact:** wherever an open Dependabot alert count appears (Health, the repository + drawer, the fix-score prompt, exports), it comes from the stored alerts behind Security, not the + first-page summary taken during collection. The attention score itself is still computed at + collection time. A repository whose alerts could not be read shows why, never zero. +- **Links:** a repository name in Security opens that repository's details; the details drawer has a + Security panel listing its open alerts. +- **Reload data** (footer) re-reads the published files in the browser. **Collect now** (Admin) asks + the worker to collect from GitHub. **Security notes** - Passwords are stored as Argon2id hashes; session cookies are `HttpOnly`, `SameSite=Strict`, and only @@ -163,7 +181,7 @@ After the first collection, and then every `SPARK_SECURITY_INTERVAL` (default `6 `off` disables it), the worker reads every Dependabot alert (open, dismissed and fixed, all pages) for each **public** repository an enabled source reaches. Alerts are kept in the database, one observation of the counts is added per read, and `/data/security/dependabot.json` is rewritten for the **Security** -view. "Refresh now" also triggers it. The result appears in `/data/status.json` under `security`. +view. "Collect now" also triggers it. The result appears in `/data/status.json` under `security`. The token needs read access to Dependabot alerts: for a fine-grained token, the **Dependabot alerts** repository permission set to read. A repository that cannot be read is listed in the view's Coverage diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index ba1e2193..6ca03e1b 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,27 +1,43 @@ -import React, { Suspense, lazy } from "react"; +import React, { Suspense, lazy, useCallback, useMemo } from "react"; import { ViewportProvider } from "@/contexts/ViewportContext"; import { ThemeProvider } from "@/contexts/ThemeContext"; import useRepositoryData from "@/hooks/useRepositoryData"; import { useDashboardShell } from "@/hooks/useDashboardShell"; +import usePortfolio from "@/hooks/usePortfolio"; +import useScope from "@/hooks/useScope"; +import useAdminAvailable from "@/hooks/useAdminAvailable"; +import useDependabot from "@/hooks/useDependabot"; import LoadingState from "@/components/Common/LoadingState"; import FilterControls from "@/components/Common/FilterControls"; +import PageHeader from "@/components/Common/PageHeader"; import ContributionHeatmap from "@/components/Visualizations/ContributionHeatmap"; import ProfileHero from "@/components/ProfileHero/ProfileHero"; -import { Eyebrow, Card, Button } from "@/components/Brand"; -import { RefreshCw } from "lucide-react"; +import { Card, Button } from "@/components/Brand"; import RepositoryGrid from "@/components/RepositoryGrid/RepositoryGrid"; import TabBar from "@/components/Mobile/TabBar/TabBar"; -import { OfflineIndicator } from "@/components/Mobile/OfflineIndicator/OfflineIndicator"; -import CollectionStatus from "@/components/Common/CollectionStatus"; -import UserPicker from "@/components/Common/UserPicker"; -import useUserOptions from "@/hooks/useUserOptions"; -import useAdminAvailable from "@/hooks/useAdminAvailable"; -import useDependabot from "@/hooks/useDependabot"; +import EmptyState from "@/components/Mobile/EmptyState/EmptyState"; +import AppHeader from "@/components/Shell/AppHeader"; +import AppFooter from "@/components/Shell/AppFooter"; import { ToastContainer } from "@/components/Mobile/Toast/Toast"; +import { visibleSections } from "@/config/sections"; +import { + EMPTY_SCOPE, + fullNameOf, + isWholePortfolio, + repoKey, + scopeLabel, + scopedRepoKeys, +} from "@/utils/scope"; +import { + alertsForRepository, + scopeAlertFile, + storedCoverage, + withStoredAlerts, +} from "@/utils/storedAlerts"; -// SIZE JUSTIFICATION (Constitution I): App composes routing/layout for the -// three primary views and delegates all cross-cutting state (toasts, view -// routing, active result list, refresh) to useDashboardShell. +// Composes the shell (header, sections, footer, drawer, toasts). Data +// loading lives in the hooks and utils above; cross-cutting view state in +// useDashboardShell, so this file stays compositional. const DashboardView = lazy( () => import("@/components/Visualizations/DashboardView"), @@ -38,23 +54,53 @@ const RepositoryDetail = lazy( /** * GitHub Stats Spark Dashboard - Root App Component * - * Composes the dashboard shell (header/nav, main content, footer, drawer, - * toasts) around the three primary views. All cross-cutting state lives in - * useDashboardShell so this component stays presentational. + * Public (GitHub Pages): one profile, Overview, Insights and Health. + * Self-hosted (a portfolio.json exists): a scope selector that every + * section follows, alert counts from the stored Dependabot alerts, and the + * Security and Admin sections when their data is available. * * @component */ function App() { + const { loading: portfolioLoading, portfolio } = usePortfolio(); + const [scope, setScope] = useScope(); + const selfHosted = Boolean(portfolio); const { - data, + data: collected, loading: dataLoading, error: dataError, refetch, - } = useRepositoryData(); + } = useRepositoryData({ + portfolio, + portfolioLoading, + scope: selfHosted ? scope : null, + }); const adminAvailable = useAdminAvailable(); - const dependabot = useDependabot(); - const userOptions = useUserOptions(); - const showUserPicker = userOptions.length >= 2; + const alertFile = useDependabot(); + + // One source per number: stored alerts replace the collected summary. + const data = useMemo(() => { + if (!collected || !alertFile) return collected; + const coverage = storedCoverage(alertFile); + return { + ...collected, + repositories: collected.repositories.map((repo) => + withStoredAlerts(repo, coverage), + ), + }; + }, [collected, alertFile]); + + const scopeKeys = useMemo( + () => + selfHosted && !isWholePortfolio(scope) + ? scopedRepoKeys(portfolio, scope) + : null, + [selfHosted, portfolio, scope], + ); + const scopedAlerts = useMemo( + () => scopeAlertFile(alertFile, scopeKeys), + [alertFile, scopeKeys], + ); const { toasts, @@ -77,119 +123,72 @@ function App() { handleForceRefresh, } = useDashboardShell({ data, refetch }); - // Admin pages do not depend on dashboard data, so a data failure must not hide them. - const onAdminView = adminAvailable && currentView === "sources"; + const sections = visibleSections({ + security: Boolean(alertFile), + admin: adminAvailable, + }); + const header = selfHosted + ? { + scope: scopeLabel(scope, portfolio), + freshness: [ + { label: "Repository data", at: data?.metadata?.generated_at }, + ...(alertFile + ? [{ label: "Security", at: alertFile.generated_at }] + : []), + ], + } + : {}; + + const openRepository = useCallback( + (fullName) => { + const key = repoKey(fullName); + const list = data?.repositories || []; + const found = list.find((repo) => repoKey(fullNameOf(repo)) === key); + if (found) { + handleRepoClick(found, list); + return; + } + const entry = alertFile?.repositories.find( + (repo) => repoKey(repo.full_name) === key, + ); + handleRepoClick( + { + name: fullName.split("/").pop(), + full_name: fullName, + url: entry?.html_url, + }, + [], + ); + }, + [data, alertFile, handleRepoClick], + ); + + // Admin and Security do not depend on dashboard data, so a data failure must not hide them. + const onAdminView = adminAvailable && currentView === "admin"; const onSecurityView = currentView === "security"; const standaloneView = onAdminView || onSecurityView; - const loading = dataLoading && !standaloneView; + const loading = (dataLoading || portfolioLoading) && !standaloneView; const error = standaloneView ? null : dataError; + const emptyScope = + selfHosted && data && (data.repositories || []).length === 0; return (
- {/* Header */} -
-
-
-
- - -
- GitHubSpark - {!showUserPicker && ( - - {data?.profile?.username || "MakeBoldSolutions"} - - )} -
-
- {/* Outside the link: a control inside an anchor is invalid and would navigate home. */} - -
- - {/* Navigation Menu */} - -
-
- refetch({ cacheBust: false })} /> - -
+ refetch({ cacheBust: false })} + /> - {/* Main Content */}
-
- Security -

Dependabot alerts

-
- {dependabot ? ( + + {scopedAlerts ? ( } > - + ) : (

@@ -228,15 +233,13 @@ function App() { )} - {/* Loading State */} - {loading && ( + {loading && !standaloneView && ( )} - {/* Error State */} {error && !loading && (

Error loading data

@@ -257,205 +260,161 @@ function App() { )} - {/* Data Loaded - Render Current View */} - {!loading && !error && data && ( - <> - {currentView === "table" && ( -
- {/* Profile Hero */} - + {!loading && + !error && + data && + !standaloneView && + emptyScope && ( + setScope(EMPTY_SCOPE)} + /> + )} - {/* Contribution heatmap for trailing 365-day activity */} - {data?.profile?.activity_calendar && ( -
- + {currentView === "table" && ( +
+ {selfHosted && !data.profile && ( + -
- )} - - {/* Repository Grid */} - -
- )} + )} + - {currentView === "visualizations" && ( -
-
- Insights -

- Repository insights -

-

- Showing {processedRepositories.length} repositories - {filterLanguage && ` filtered by ${filterLanguage}`} -

-
+ {data?.profile?.activity_calendar && ( +
+ +
+ )} - {availableLanguages.length > 0 && ( - - )} +
+ )} - - } + {currentView === "visualizations" && ( +
- - handleRepoClick(repo, processedRepositories) + + Showing {processedRepositories.length}{" "} + repositories + {filterLanguage && + ` filtered by ${filterLanguage}`} + } + {...header} /> - -
- )} - {currentView === "attention" && ( -
-
- Health -

- Repositories needing attention -

-

- Ranked by pull request pressure, security findings, - staleness, and dependency health -

-
+ {availableLanguages.length > 0 && ( + + )} - {availableLanguages.length > 0 && ( - - )} + + } + > + + handleRepoClick(repo, processedRepositories) + } + /> + +
+ )} - - } + {currentView === "attention" && ( +
- - -
- )} - - )} + + {availableLanguages.length > 0 && ( + + )} + + + } + > + + + + )} + + )}
- {/* Mobile TabBar Navigation */} - {/* Footer */} - + - {/* Detail Drawer (drill-down) */} {selectedRepo && ( }> r.name === selectedRepo.name, )} resultTotal={activeResultList.length} + security={alertsForRepository( + alertFile, + fullNameOf(selectedRepo), + )} /> )} - {/* Toast Notifications */}
diff --git a/frontend/src/components/Admin/SourcesView.jsx b/frontend/src/components/Admin/SourcesView.jsx index e1299dc4..1d280ca0 100644 --- a/frontend/src/components/Admin/SourcesView.jsx +++ b/frontend/src/components/Admin/SourcesView.jsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useState } from "react"; import PropTypes from "prop-types"; -import { Button, Eyebrow } from "@/components/Brand"; +import { Button } from "@/components/Brand"; +import PageHeader from "@/components/Common/PageHeader"; import { adminApi } from "@/services/adminApi"; import LoginForm from "./LoginForm"; import SourcesPanel from "./SourcesPanel"; @@ -44,13 +45,13 @@ export default function SourcesView({ onToast }) { const changed = useCallback(() => setChangeCount((count) => count + 1), []); const openLists = useCallback(() => setTab("lists"), []); - const refreshNow = async () => { + const collectNow = async () => { try { await adminApi.refresh(); setRefreshNote( - "Refresh requested. The worker starts within seconds; watch the status line in the header.", + "Collection requested. The worker starts within seconds; watch the status line in the header.", ); - onToast?.("Refresh requested", "info"); + onToast?.("Collection requested", "info"); } catch (error) { if (error.status === 401) signedOut(); setRefreshNote(error.message); @@ -68,10 +69,11 @@ export default function SourcesView({ onToast }) { aria-labelledby="admin-heading" data-testid="admin-view" > -
- Admin -

Manage sources

-
+ {auth.state === "checking" &&

Checking sign-in…

} @@ -86,8 +88,8 @@ export default function SourcesView({ onToast }) { Signed in as {auth.info.username}
-
{openPrs ?? "n/a"} - {getSecurityAlerts(repo)} + + {getSecurityAvailability(repo) === "available" ? ( + getSecurityAlerts(repo) + ) : ( + + )} + {repo.days_since_last_push ?? "n/a"} `${n} open`, tone: "caution" }, + zero: { label: () => "None open", tone: "positive" }, + partial: { label: () => "Only partly read", tone: "caution" }, + stale: { label: () => "Out of date", tone: "caution" }, + unavailable: { label: () => "Not available", tone: "caution" }, + unauthorized: { label: () => "No access", tone: "critical" }, + unsupported: { label: () => "Not enabled", tone: "neutral" }, + not_checked: { label: () => "Not checked yet", tone: "neutral" }, +}; + +/** Collector status values, mapped to a coverage state. */ +const STATUS_STATE = { + available: "count", + partial: "partial", + unavailable: "unavailable", + unauthorized: "unauthorized", + disabled: "unsupported", + unsupported: "unsupported", + not_checked: "not_checked", +}; + +/** + * Pure: which state to show for a reading. A successful reading older than + * `staleAfterSeconds` (when given) is stale. + */ +export function coverageStateOf({ + status, + count, + checkedAt, + staleAfterSeconds, + now = Date.now(), +}) { + const state = STATUS_STATE[status] || "unavailable"; + if (state === "count" || state === "partial") { + const checked = checkedAt ? Date.parse(checkedAt) : NaN; + if ( + staleAfterSeconds && + Number.isFinite(checked) && + now - checked > staleAfterSeconds * 1000 + ) { + return "stale"; + } + } + if (state === "count") return count ? "count" : "zero"; + return state; +} + +/** + * Shows a collector reading so that zero, unavailable, unauthorized, + * unsupported and stale all look different. `reason` is the plain-language + * explanation shown beside a missing reading. + */ +export default function CoverageState({ + status, + count = 0, + checkedAt = null, + staleAfterSeconds = null, + reason = "", +}) { + const state = coverageStateOf({ + status, + count, + checkedAt, + staleAfterSeconds, + }); + const { label, tone } = COVERAGE_STATES[state]; + const showReason = reason && state !== "count" && state !== "zero"; + return ( + + {label(count)} + {showReason && {reason}} + + ); +} + +CoverageState.propTypes = { + status: PropTypes.string.isRequired, + count: PropTypes.number, + checkedAt: PropTypes.string, + staleAfterSeconds: PropTypes.number, + reason: PropTypes.string, +}; diff --git a/frontend/src/components/Common/DataTable.jsx b/frontend/src/components/Common/DataTable.jsx new file mode 100644 index 00000000..69219e05 --- /dev/null +++ b/frontend/src/components/Common/DataTable.jsx @@ -0,0 +1,76 @@ +import PropTypes from "prop-types"; +import shared from "./DataViews.module.css"; + +/** + * A captioned table with scoped column headers. Columns render a field by + * key, or anything through `render(row)`. The caption is a polite live + * region so a filtered row count is announced. + */ +export default function DataTable({ + columns, + rows, + rowKey, + caption, + emptyMessage = "Nothing to show.", + labelledBy, + minWidth, +}) { + return ( +
+ + + + + {columns.map((column) => ( + + ))} + + + + {rows.length === 0 && ( + + + + )} + {rows.map((row) => ( + + {columns.map((column) => ( + + ))} + + ))} + +
+ {caption} +
+ {column.header} +
+ {emptyMessage} +
+ {column.render + ? column.render(row) + : (row[column.key] ?? "—")} +
+
+ ); +} + +DataTable.propTypes = { + columns: PropTypes.arrayOf( + PropTypes.shape({ + key: PropTypes.string.isRequired, + header: PropTypes.node.isRequired, + render: PropTypes.func, + }), + ).isRequired, + rows: PropTypes.array.isRequired, + rowKey: PropTypes.func.isRequired, + caption: PropTypes.node.isRequired, + emptyMessage: PropTypes.node, + labelledBy: PropTypes.string, + minWidth: PropTypes.number, +}; diff --git a/frontend/src/components/Common/DataViews.module.css b/frontend/src/components/Common/DataViews.module.css new file mode 100644 index 00000000..8d135930 --- /dev/null +++ b/frontend/src/components/Common/DataViews.module.css @@ -0,0 +1,106 @@ +/* Shared styles for the page header, filter bar, data table and coverage + state used across the self-hosted views. */ + +.headerMeta { + display: flex; + flex-wrap: wrap; + gap: 4px 16px; + margin: 4px 0 0; + font-size: 13px; + color: var(--text-muted); +} + +.filters { + display: flex; + flex-wrap: wrap; + gap: 16px; + align-items: flex-end; + padding: 16px 24px; +} + +.field { + display: flex; + flex-direction: column; + gap: 4px; + font-size: 12px; + color: var(--text-muted); +} + +.field select { + min-height: 40px; + max-width: 260px; + padding: 6px 10px; + font: inherit; + color: var(--text-strong); + background: var(--surface); + border: 1px solid var(--border-default); + border-radius: 6px; +} + +.field select:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.tableWrapper { + overflow-x: auto; +} + +.table { + width: 100%; + border-collapse: collapse; +} + +.table caption { + text-align: left; + padding: 0 24px 12px; + font-size: 13px; + color: var(--text-muted); +} + +.table th, +.table td { + padding: 10px 16px; + text-align: left; + border-bottom: 1px solid var(--border-subtle); + vertical-align: top; + font-size: 14px; +} + +.table th { + background: var(--surface-sunken); + color: var(--text-muted); + font-size: 11px; + font-weight: var(--fw-semibold); + text-transform: uppercase; + letter-spacing: 0.14em; + white-space: nowrap; +} + +.muted { + color: var(--text-muted); +} + +.coverage { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.coverageReason { + font-size: 13px; + color: var(--text-muted); +} + +@media (max-width: 767px) { + .filters { + padding: 12px 16px; + } + + .field, + .field select { + width: 100%; + max-width: none; + } +} diff --git a/frontend/src/components/Common/ExportButton.jsx b/frontend/src/components/Common/ExportButton.jsx index 063e2bed..01da437d 100644 --- a/frontend/src/components/Common/ExportButton.jsx +++ b/frontend/src/components/Common/ExportButton.jsx @@ -3,12 +3,113 @@ import PropTypes from "prop-types"; import { Download } from "lucide-react"; import styles from "./ExportButton.module.css"; +const REPOSITORY_COLUMNS = [ + { key: "name", label: "Repository Name" }, + { key: "language", label: "Language" }, + { key: "stars", label: "Stars" }, + { key: "forks", label: "Forks" }, + { key: "watchers", label: "Watchers" }, + { key: "open_issues", label: "Open Issues" }, + { key: "created_at", label: "Created At" }, + { key: "updated_at", label: "Last Updated" }, + { key: "commit_history.total_commits", label: "Total Commits" }, + { key: "commit_history.recent_90d", label: "Commits (90d)" }, + { key: "commit_history.recent_180d", label: "Commits (180d)" }, + { key: "commit_history.recent_365d", label: "Commits (365d)" }, + { key: "commit_history.first_commit_date", label: "First Commit" }, + { key: "commit_history.last_commit_date", label: "Last Commit" }, + { key: "commit_metrics.avg_size", label: "Avg Commit Size" }, + { key: "commit_metrics.largest_commit.size", label: "Largest Commit" }, + { key: "commit_metrics.smallest_commit.size", label: "Smallest Commit" }, + { key: "commit_velocity", label: "Commit Velocity" }, + { key: "age_days", label: "Age (days)" }, + { key: "days_since_last_push", label: "Days Since Push" }, + { key: "has_readme", label: "Has README" }, + { key: "has_license", label: "Has License" }, + { key: "has_ci_cd", label: "Has CI/CD" }, + { key: "has_tests", label: "Has Tests" }, + { + key: "pull_request_summary.availability", + label: "PR Data Availability", + }, + { key: "pull_request_summary.total_open", label: "Open Pull Requests" }, + { key: "pull_request_summary.draft_count", label: "Draft Pull Requests" }, + { + key: "pull_request_summary.review_requested_count", + label: "PRs Awaiting Review", + }, + { + key: "security_summary.availability", + label: "Security Data Availability", + }, + { + key: "security_summary.overall_state", + label: "Security Overall State", + }, + { + key: "security_summary.active_alert_counts.total_open", + label: "Open Security Alerts", + }, + { + key: "security_summary.active_alert_counts.critical", + label: "Critical Alerts", + }, + { + key: "security_summary.active_alert_counts.high", + label: "High Alerts", + }, + { + key: "diagnostics_summary.availability", + label: "Diagnostics Availability", + }, + { + key: "diagnostics_summary.issues.total_open", + label: "Open Issues (Diagnostics)", + }, + { + key: "diagnostics_summary.security.dependabot.total_open", + label: "Dependabot Open Alerts", + }, + { + key: "diagnostics_summary.actions.failure_count", + label: "Workflow Failures", + }, + { key: "screenshot_audit.status", label: "Screenshot Audit Status" }, + { key: "screenshot_audit.flags", label: "Screenshot Audit Flags" }, +]; + +const getNestedValue = (obj, path) => + path.split(".").reduce((acc, part) => acc?.[part], obj); + +const csvCell = (value) => { + if (value === null || value === undefined) return '""'; + if (typeof value === "boolean") return value ? "Yes" : "No"; + if (typeof value === "number") return value; + if (Array.isArray(value)) return csvCell(value.join("; ")); + const text = String(value); + // Prefix formula starters so a spreadsheet never evaluates cell text. + const safe = /^[=+\-@\t\r]/.test(text) ? `'${text}` : text; + return `"${safe.replace(/"/g, '""')}"`; +}; + +/** CSV for `rows` with the given `{key, label}` columns (keys may be dotted). */ +export function toCsv(rows, columns) { + if (!Array.isArray(rows) || rows.length === 0) return ""; + const header = columns.map((col) => `"${col.label}"`).join(","); + const body = rows.map((row) => + columns.map((col) => csvCell(getNestedValue(row, col.key))).join(","), + ); + return [header, ...body].join("\n"); +} + /** * ExportButton Component * - * Accessible, dismissible export menu for the current Overview filtered - * list or Health ranked list. Exports CSV or JSON client-side and reports - * outcomes through the supplied toast callback instead of alert(). + * Accessible, dismissible export menu used by every data table: the + * Overview list, the Health ranking and the Security alerts. Exports CSV or + * JSON client-side and reports outcomes through the supplied toast + * callback instead of alert(). `columns` picks the CSV columns (repository + * columns by default); `noun` names the rows in messages. * * @component * @param {Object} props @@ -17,6 +118,9 @@ import styles from "./ExportButton.module.css"; * @param {string} [props.label='Export'] - Button label * @param {boolean} [props.disabled=false] - Whether button is disabled * @param {Function} [props.onToast] - (message, variant) => void, for export outcomes + * @param {Array} [props.columns] - CSV columns as {key, label}; dotted keys reach nested fields + * @param {string} [props.noun='repositories'] - What the rows are, for messages + * @param {string} [props.jsonDescription] - Menu description of the JSON export */ function ExportButton({ data, @@ -24,6 +128,9 @@ function ExportButton({ label = "Export", disabled = false, onToast, + columns = null, + noun = "repositories", + jsonDescription = "Full repository records", }) { const [showMenu, setShowMenu] = useState(false); const rootRef = useRef(null); @@ -50,103 +157,7 @@ function ExportButton({ if (onToast) onToast(message, variant); }; - const convertToCSV = (repositories) => { - if (!Array.isArray(repositories) || repositories.length === 0) return ""; - - const columns = [ - { key: "name", label: "Repository Name" }, - { key: "language", label: "Language" }, - { key: "stars", label: "Stars" }, - { key: "forks", label: "Forks" }, - { key: "watchers", label: "Watchers" }, - { key: "open_issues", label: "Open Issues" }, - { key: "created_at", label: "Created At" }, - { key: "updated_at", label: "Last Updated" }, - { key: "commit_history.total_commits", label: "Total Commits" }, - { key: "commit_history.recent_90d", label: "Commits (90d)" }, - { key: "commit_history.recent_180d", label: "Commits (180d)" }, - { key: "commit_history.recent_365d", label: "Commits (365d)" }, - { key: "commit_history.first_commit_date", label: "First Commit" }, - { key: "commit_history.last_commit_date", label: "Last Commit" }, - { key: "commit_metrics.avg_size", label: "Avg Commit Size" }, - { key: "commit_metrics.largest_commit.size", label: "Largest Commit" }, - { key: "commit_metrics.smallest_commit.size", label: "Smallest Commit" }, - { key: "commit_velocity", label: "Commit Velocity" }, - { key: "age_days", label: "Age (days)" }, - { key: "days_since_last_push", label: "Days Since Push" }, - { key: "has_readme", label: "Has README" }, - { key: "has_license", label: "Has License" }, - { key: "has_ci_cd", label: "Has CI/CD" }, - { key: "has_tests", label: "Has Tests" }, - { - key: "pull_request_summary.availability", - label: "PR Data Availability", - }, - { key: "pull_request_summary.total_open", label: "Open Pull Requests" }, - { key: "pull_request_summary.draft_count", label: "Draft Pull Requests" }, - { - key: "pull_request_summary.review_requested_count", - label: "PRs Awaiting Review", - }, - { - key: "security_summary.availability", - label: "Security Data Availability", - }, - { - key: "security_summary.overall_state", - label: "Security Overall State", - }, - { - key: "security_summary.active_alert_counts.total_open", - label: "Open Security Alerts", - }, - { - key: "security_summary.active_alert_counts.critical", - label: "Critical Alerts", - }, - { - key: "security_summary.active_alert_counts.high", - label: "High Alerts", - }, - { - key: "diagnostics_summary.availability", - label: "Diagnostics Availability", - }, - { - key: "diagnostics_summary.issues.total_open", - label: "Open Issues (Diagnostics)", - }, - { - key: "diagnostics_summary.security.dependabot.open_alerts", - label: "Dependabot Open Alerts", - }, - { - key: "diagnostics_summary.actions.failure_count", - label: "Workflow Failures", - }, - { key: "screenshot_audit.status", label: "Screenshot Audit Status" }, - { key: "screenshot_audit.flags", label: "Screenshot Audit Flags" }, - ]; - - const getNestedValue = (obj, path) => - path.split(".").reduce((acc, part) => acc?.[part], obj); - - const header = columns.map((col) => `"${col.label}"`).join(","); - - const rows = repositories.map((repo) => - columns - .map((col) => { - const value = getNestedValue(repo, col.key); - if (value === null || value === undefined) return '""'; - if (typeof value === "boolean") return value ? "Yes" : "No"; - if (typeof value === "number") return value; - return `"${String(value).replace(/"/g, '""')}"`; - }) - .join(","), - ); - - return [header, ...rows].join("\n"); - }; + const convertToCSV = (rows) => toCsv(rows, columns || REPOSITORY_COLUMNS); const downloadFile = (content, downloadFilename, mimeType) => { const blob = new Blob([content], { type: mimeType }); @@ -174,7 +185,7 @@ function ExportButton({ `${filename}-${timestamp}.csv`, "text/csv;charset=utf-8;", ); - notify(`Exported ${data.length} repositories as CSV`, "success"); + notify(`Exported ${data.length} ${noun} as CSV`, "success"); } catch (error) { console.error("CSV export failed:", error); notify("Export failed. Check the console for details.", "error"); @@ -195,7 +206,7 @@ function ExportButton({ `${filename}-${timestamp}.json`, "application/json;charset=utf-8;", ); - notify(`Exported ${data.length} repositories as JSON`, "success"); + notify(`Exported ${data.length} ${noun} as JSON`, "success"); } catch (error) { console.error("JSON export failed:", error); notify("Export failed. Check the console for details.", "error"); @@ -222,7 +233,7 @@ function ExportButton({ {showMenu && (

- {count} repositories in current view + {count} {noun} in current view

)} @@ -256,6 +267,11 @@ ExportButton.propTypes = { label: PropTypes.string, disabled: PropTypes.bool, onToast: PropTypes.func, + columns: PropTypes.arrayOf( + PropTypes.shape({ key: PropTypes.string, label: PropTypes.string }), + ), + noun: PropTypes.string, + jsonDescription: PropTypes.string, }; export default ExportButton; diff --git a/frontend/src/components/Common/FilterBar.jsx b/frontend/src/components/Common/FilterBar.jsx new file mode 100644 index 00000000..aef77fe1 --- /dev/null +++ b/frontend/src/components/Common/FilterBar.jsx @@ -0,0 +1,63 @@ +import PropTypes from "prop-types"; +import styles from "./DataViews.module.css"; + +/** + * A row of labelled select filters. Each field offers "all" (empty value) + * first unless `allLabel` is null. Extra controls (an export menu, a reset + * button) go in `children`, after the fields. + */ +export default function FilterBar({ label, fields, children }) { + return ( +
event.preventDefault()} + > + {fields.map((field) => ( + + ))} + {children} +
+ ); +} + +FilterBar.propTypes = { + label: PropTypes.string.isRequired, + fields: PropTypes.arrayOf( + PropTypes.shape({ + id: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + value: PropTypes.string.isRequired, + onChange: PropTypes.func.isRequired, + options: PropTypes.arrayOf( + PropTypes.shape({ + value: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + disabled: PropTypes.bool, + }), + ).isRequired, + allLabel: PropTypes.string, + }), + ).isRequired, + children: PropTypes.node, +}; diff --git a/frontend/src/components/Common/PageHeader.jsx b/frontend/src/components/Common/PageHeader.jsx new file mode 100644 index 00000000..bcae61f7 --- /dev/null +++ b/frontend/src/components/Common/PageHeader.jsx @@ -0,0 +1,59 @@ +import PropTypes from "prop-types"; +import { Eyebrow } from "@/components/Brand"; +import styles from "./DataViews.module.css"; + +const formatTime = (value) => { + const parsed = value ? new Date(value) : null; + return parsed && !Number.isNaN(parsed.getTime()) + ? parsed.toLocaleString() + : "not yet"; +}; + +/** + * The heading every section starts with: eyebrow, title and an optional + * status line. In the self-hosted deployment it also names the scope being + * shown and how fresh each kind of data is. Without `scope` or `freshness` + * it renders exactly the original markup, so the public dashboard is + * unchanged. + */ +export default function PageHeader({ + eyebrow, + title, + titleId, + description = null, + scope = null, + freshness = [], +}) { + return ( +
+ {eyebrow} +

{title}

+ {description && ( +

+ {description} +

+ )} + {(scope || freshness.length > 0) && ( +

+ {scope && Showing: {scope}} + {freshness.map((item) => ( + + {item.label} updated {formatTime(item.at)} + + ))} +

+ )} +
+ ); +} + +PageHeader.propTypes = { + eyebrow: PropTypes.string.isRequired, + title: PropTypes.string.isRequired, + titleId: PropTypes.string.isRequired, + description: PropTypes.node, + scope: PropTypes.string, + freshness: PropTypes.arrayOf( + PropTypes.shape({ label: PropTypes.string, at: PropTypes.string }), + ), +}; diff --git a/frontend/src/components/Common/ScopeSelector.jsx b/frontend/src/components/Common/ScopeSelector.jsx new file mode 100644 index 00000000..122a4b87 --- /dev/null +++ b/frontend/src/components/Common/ScopeSelector.jsx @@ -0,0 +1,133 @@ +import { useMemo } from "react"; +import PropTypes from "prop-types"; +import FilterBar from "./FilterBar"; +import { + clientChoices, + isWholePortfolio, + scopedRepoKeys, + repoKey, + EMPTY_SCOPE, +} from "@/utils/scope"; +import styles from "./ScopeSelector.module.css"; + +const SOURCE_GROUP = { user: "user", org: "organization", repo: "repository" }; + +/** + * Chooses what every view shows: the whole portfolio, a client, a source + * or one repository, optionally filtered by classification values. Each + * list offers only choices that exist within the levels above it. + * Choosing a level clears the levels below it. + */ +export default function ScopeSelector({ portfolio, scope, onChange }) { + const fields = useMemo(() => { + const clients = clientChoices(portfolio); + const withinClient = scopedRepoKeys(portfolio, { + ...EMPTY_SCOPE, + client: scope.client, + }); + const reaching = new Set( + portfolio.repositories + .filter((r) => withinClient.has(repoKey(r.full_name))) + .flatMap((r) => (r.sources || []).map((s) => s.toLowerCase())), + ); + const sources = portfolio.sources + .filter((s) => reaching.has(`${s.type}:${s.identifier}`.toLowerCase())) + .map((s) => ({ + value: s.slug, + label: `${s.identifier} (${SOURCE_GROUP[s.type] || s.type})${ + s.ready ? "" : " - not collected yet" + }`, + disabled: !s.ready && s.slug !== scope.source, + })); + const withinSource = scopedRepoKeys(portfolio, { + ...EMPTY_SCOPE, + client: scope.client, + source: scope.source, + }); + const repositories = portfolio.repositories + .filter((r) => withinSource.has(repoKey(r.full_name))) + .map((r) => ({ value: r.full_name, label: r.full_name })) + .sort((a, b) => a.label.localeCompare(b.label)); + + const list = []; + if (clients.length > 0) { + list.push({ + id: "scope-client", + label: "Client", + value: scope.client, + allLabel: "All clients", + options: clients, + onChange: (client) => + onChange({ ...scope, client, source: "", repo: "" }), + }); + } + list.push( + { + id: "scope-source", + label: "Source", + value: scope.source, + allLabel: "All sources", + options: sources, + onChange: (source) => onChange({ ...scope, source, repo: "" }), + }, + { + id: "scope-repo", + label: "Repository", + value: scope.repo, + allLabel: "All repositories", + options: repositories, + onChange: (repo) => onChange({ ...scope, repo }), + }, + ); + for (const domain of portfolio.domains) { + list.push({ + id: `scope-domain-${domain.key}`, + label: domain.label, + value: scope.filters[domain.key] || "", + allLabel: `Any ${domain.label.toLowerCase()}`, + options: domain.values + .filter((v) => !v.retired || v.key === scope.filters[domain.key]) + .map((v) => ({ value: v.key, label: v.label })), + onChange: (value) => { + const filters = { ...scope.filters, [domain.key]: value }; + if (!value) delete filters[domain.key]; + onChange({ ...scope, filters }); + }, + }); + } + return list; + }, [portfolio, scope, onChange]); + + return ( +
+
+ + {!isWholePortfolio(scope) && ( + + )} + +
+
+ ); +} + +ScopeSelector.propTypes = { + portfolio: PropTypes.shape({ + repositories: PropTypes.array.isRequired, + sources: PropTypes.array.isRequired, + domains: PropTypes.array.isRequired, + }).isRequired, + scope: PropTypes.shape({ + client: PropTypes.string, + source: PropTypes.string, + repo: PropTypes.string, + filters: PropTypes.object, + }).isRequired, + onChange: PropTypes.func.isRequired, +}; diff --git a/frontend/src/components/Common/ScopeSelector.module.css b/frontend/src/components/Common/ScopeSelector.module.css new file mode 100644 index 00000000..c503bbc3 --- /dev/null +++ b/frontend/src/components/Common/ScopeSelector.module.css @@ -0,0 +1,26 @@ +.bar { + background: var(--surface-sunken); + border-bottom: 1px solid var(--border-subtle); +} + +.bar form { + padding-left: 0; + padding-right: 0; +} + +.reset { + min-height: 40px; + padding: 6px 14px; + font: inherit; + font-size: 14px; + color: var(--text-strong); + background: transparent; + border: 1px solid var(--border-default); + border-radius: 6px; + cursor: pointer; +} + +.reset:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} diff --git a/frontend/src/components/Common/Tooltip.jsx b/frontend/src/components/Common/Tooltip.jsx deleted file mode 100644 index 3c4c3f24..00000000 --- a/frontend/src/components/Common/Tooltip.jsx +++ /dev/null @@ -1,93 +0,0 @@ -import React, { useState, useRef, useEffect } from "react"; -import styles from "./Tooltip.module.css"; - -/** - * Tooltip Component - * - * Displays contextual information on hover with smooth animations. - * Automatically positions itself to avoid viewport edges. - * - * @component - * @param {Object} props - Component props - * @param {React.ReactNode} props.children - Trigger element that shows tooltip on hover - * @param {string} props.content - Tooltip text content - * @param {string} [props.position='top'] - Preferred tooltip position ('top', 'bottom', 'left', 'right') - * @param {number} [props.delay=300] - Show delay in milliseconds - * - * @example - * - * 1,234 commits - * - */ -export default function Tooltip({ - children, - content, - position = "top", - delay = 300, -}) { - const [isVisible, setIsVisible] = useState(false); - const [showTimeout, setShowTimeout] = useState(null); - const tooltipRef = useRef(null); - const triggerRef = useRef(null); - - /** - * Show tooltip after delay - */ - const handleMouseEnter = () => { - const timeout = setTimeout(() => { - setIsVisible(true); - }, delay); - setShowTimeout(timeout); - }; - - /** - * Hide tooltip and clear delay timeout - */ - const handleMouseLeave = () => { - if (showTimeout) { - clearTimeout(showTimeout); - setShowTimeout(null); - } - setIsVisible(false); - }; - - /** - * Cleanup timeout on unmount - */ - useEffect(() => { - return () => { - if (showTimeout) { - clearTimeout(showTimeout); - } - }; - }, [showTimeout]); - - // Don't render if no content - if (!content) { - return <>{children}; - } - - return ( -
- {children} - {isVisible && ( -
-
{content}
-
-
- )} -
- ); -} diff --git a/frontend/src/components/Common/Tooltip.module.css b/frontend/src/components/Common/Tooltip.module.css deleted file mode 100644 index 20165c52..00000000 --- a/frontend/src/components/Common/Tooltip.module.css +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Tooltip Component Styles - * - * CSS Module for the Tooltip component with positioning and animations. - */ - -.tooltipWrapper { - position: relative; - display: inline-block; -} - -.tooltip { - position: absolute; - z-index: var(--z-index-tooltip); - padding: var(--spacing-sm) var(--spacing-md); - background-color: var(--color-text); - color: var(--color-background); - font-size: var(--font-size-sm); - line-height: var(--line-height-normal); - border-radius: var(--radius-md); - box-shadow: var(--shadow-lg); - white-space: nowrap; - pointer-events: none; - animation: tooltipFadeIn 0.2s ease-in-out; - max-width: 300px; -} - -.tooltipContent { - position: relative; - z-index: 1; -} - -.tooltipArrow { - position: absolute; - width: 8px; - height: 8px; - background-color: var(--color-text); - transform: rotate(45deg); -} - -/* Position variants */ -.tooltip--top { - bottom: calc(100% + 8px); - left: 50%; - transform: translateX(-50%); -} - -.tooltip--top .tooltipArrow { - bottom: -4px; - left: 50%; - transform: translateX(-50%) rotate(45deg); -} - -.tooltip--bottom { - top: calc(100% + 8px); - left: 50%; - transform: translateX(-50%); -} - -.tooltip--bottom .tooltipArrow { - top: -4px; - left: 50%; - transform: translateX(-50%) rotate(45deg); -} - -.tooltip--left { - right: calc(100% + 8px); - top: 50%; - transform: translateY(-50%); -} - -.tooltip--left .tooltipArrow { - right: -4px; - top: 50%; - transform: translateY(-50%) rotate(45deg); -} - -.tooltip--right { - left: calc(100% + 8px); - top: 50%; - transform: translateY(-50%); -} - -.tooltip--right .tooltipArrow { - left: -4px; - top: 50%; - transform: translateY(-50%) rotate(45deg); -} - -/* Animations */ -@keyframes tooltipFadeIn { - from { - opacity: 0; - transform: translateX(-50%) translateY(-4px); - } - to { - opacity: 1; - transform: translateX(-50%) translateY(0); - } -} - -/* Responsive: Hide tooltips on touch devices to avoid UX issues */ -@media (hover: none) and (pointer: coarse) { - .tooltip { - display: none; - } -} diff --git a/frontend/src/components/Common/UserPicker.jsx b/frontend/src/components/Common/UserPicker.jsx deleted file mode 100644 index 4bd8decb..00000000 --- a/frontend/src/components/Common/UserPicker.jsx +++ /dev/null @@ -1,97 +0,0 @@ -import PropTypes from "prop-types"; -import { getSelectedUser } from "@/services/dataService"; -import styles from "./UserPicker.module.css"; - -/** Reload the dashboard for another user (the data service reads ?user=). */ -export function navigateToUser(slug) { - const url = new URL(window.location.href); - url.searchParams.set("user", slug); - window.location.assign(url.toString()); -} - -const GROUPS = [ - ["user", "Users"], - ["org", "Organizations"], - ["repo", "Repositories"], -]; - -const sourceShape = PropTypes.shape({ - login: PropTypes.string.isRequired, - slug: PropTypes.string.isRequired, - type: PropTypes.string, - ready: PropTypes.bool, -}); - -/** - * Presentational picker. Sources whose data has not been collected yet are - * listed but disabled, with the reason in the label. Grouped by type once - * more than one type is registered. - */ -export function UserPickerView({ users, selected, onSelect }) { - const option = (user) => ( - - ); - const types = new Set(users.map((user) => user.type || "user")); - - return ( - - ); -} - -UserPickerView.propTypes = { - users: PropTypes.arrayOf(sourceShape).isRequired, - selected: PropTypes.string.isRequired, - onSelect: PropTypes.func.isRequired, -}; - -/** - * Renders nothing unless at least two sources are registered, so single-user - * and static (GitHub Pages) deployments look exactly as before. `users` - * comes from useUserOptions (the caller also needs the count). - */ -export default function UserPicker({ users }) { - const selected = getSelectedUser(); - if (users.length < 2) return null; - - // Keep the current user selectable even if it is not in the registry. - const known = users.some((user) => user.slug === selected); - const list = known - ? users - : [{ login: selected, slug: selected, ready: true }, ...users]; - - return ( - slug !== selected && navigateToUser(slug)} - /> - ); -} - -UserPicker.propTypes = { - users: PropTypes.arrayOf(sourceShape).isRequired, -}; diff --git a/frontend/src/components/Common/UserPicker.module.css b/frontend/src/components/Common/UserPicker.module.css deleted file mode 100644 index 3d0fc793..00000000 --- a/frontend/src/components/Common/UserPicker.module.css +++ /dev/null @@ -1,25 +0,0 @@ -.picker { - max-width: 180px; - min-height: 24px; - padding: 0 4px; - border: 1px solid var(--color-border); - border-radius: 4px; - background: var(--color-surface); - color: var(--color-text-secondary); - font: inherit; - font-size: 0.75rem; - cursor: pointer; -} - -.picker:focus-visible { - outline: 2px solid var(--color-primary); - outline-offset: 2px; -} - -@media (max-width: 767px) { - /* The header's text subtitle is hidden on small screens; the picker stays. */ - .picker { - min-height: 44px; - max-width: 140px; - } -} diff --git a/frontend/src/components/DrillDown/RepositoryDetail.jsx b/frontend/src/components/DrillDown/RepositoryDetail.jsx index 249eaeb8..80abd154 100644 --- a/frontend/src/components/DrillDown/RepositoryDetail.jsx +++ b/frontend/src/components/DrillDown/RepositoryDetail.jsx @@ -29,6 +29,7 @@ import ActivityMetricsSection from "./RepositoryDetail/sections/ActivityMetricsS import RankingSection from "./RepositoryDetail/sections/RankingSection"; import TechStackSection from "./RepositoryDetail/sections/TechStackSection"; import FixScorePromptSection from "./RepositoryDetail/sections/FixScorePromptSection"; +import SecuritySection from "./RepositoryDetail/sections/SecuritySection"; /** * RepositoryDetail Component @@ -50,6 +51,8 @@ import FixScorePromptSection from "./RepositoryDetail/sections/FixScorePromptSec * @param {Function} props.onClose - Callback to close the modal * @param {Function} [props.onNext] - Callback to navigate to next repository * @param {Function} [props.onPrevious] - Callback to navigate to previous repository + * @param {Object} [props.security] - Stored alerts and coverage for this + * repository (self-hosted only); adds the Security panel */ const STAT_TILES = [ { key: "stars", label: "Stars" }, @@ -99,6 +102,7 @@ function RepositoryDetail({ onPrevious, resultIndex, resultTotal, + security = null, }) { const { expandedSections, toggleSection } = useSectionToggles(); const bind = useRepositoryDetailInteractions({ onClose, onNext, onPrevious }); @@ -184,6 +188,12 @@ function RepositoryDetail({ components={repository.attention_metrics?.components} /> + + +
+

+ Dependabot:{" "} + +

+ {open.length > 0 && ( + + )} +
+ + ); +} + +SecuritySection.propTypes = { + security: PropTypes.shape({ + coverage: PropTypes.object.isRequired, + alerts: PropTypes.array.isRequired, + }), + expanded: PropTypes.bool, + onToggle: PropTypes.func.isRequired, +}; + +export default SecuritySection; diff --git a/frontend/src/components/Layout/Container/Container.css b/frontend/src/components/Layout/Container/Container.css deleted file mode 100644 index 3242f45d..00000000 --- a/frontend/src/components/Layout/Container/Container.css +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Container Component Styles - * Mobile-first responsive container - */ - -.container { - width: 100%; - margin-left: auto; - margin-right: auto; -} - -/* Padding variants */ -.container-padding { - padding-left: 1rem; - padding-right: 1rem; -} - -@media (min-width: 768px) { - .container-padding { - padding-left: 2rem; - padding-right: 2rem; - } -} - -/* Centered content */ -.container-centered { - display: flex; - flex-direction: column; - align-items: center; -} - -/* Max-width variants */ -.container-sm { - max-width: 640px; -} - -.container-md { - max-width: 768px; -} - -.container-lg { - max-width: 1024px; -} - -.container-xl { - max-width: 1280px; -} - -.container-full { - max-width: 100%; -} diff --git a/frontend/src/components/Layout/Container/Container.jsx b/frontend/src/components/Layout/Container/Container.jsx deleted file mode 100644 index d82e0d61..00000000 --- a/frontend/src/components/Layout/Container/Container.jsx +++ /dev/null @@ -1,44 +0,0 @@ -import React from "react"; -import PropTypes from "prop-types"; -import "./Container.css"; - -/** - * Container Component - * Mobile-first responsive container with proper padding and max-width - * - * @param {Object} props - * @param {React.ReactNode} props.children - Content to wrap - * @param {string} props.maxWidth - Maximum width breakpoint ('sm'|'md'|'lg'|'xl'|'full') - * @param {boolean} props.centered - Center content horizontally - * @param {boolean} props.padding - Apply responsive padding - * @param {string} props.className - Additional CSS classes - */ -export function Container({ - children, - maxWidth = "lg", - centered = false, - padding = true, - className = "", -}) { - const classes = [ - "container", - `container-${maxWidth}`, - centered && "container-centered", - padding && "container-padding", - className, - ] - .filter(Boolean) - .join(" "); - - return
{children}
; -} - -Container.propTypes = { - children: PropTypes.node.isRequired, - maxWidth: PropTypes.oneOf(["sm", "md", "lg", "xl", "full"]), - centered: PropTypes.bool, - padding: PropTypes.bool, - className: PropTypes.string, -}; - -export default Container; diff --git a/frontend/src/components/Layout/SafeArea/SafeArea.css b/frontend/src/components/Layout/SafeArea/SafeArea.css deleted file mode 100644 index f502a3d1..00000000 --- a/frontend/src/components/Layout/SafeArea/SafeArea.css +++ /dev/null @@ -1,8 +0,0 @@ -/** - * SafeArea Component Styles - * Uses CSS safe-area-inset-* from safe-area.css - */ - -.safe-area { - /* Styles imported from mobile/safe-area.css */ -} diff --git a/frontend/src/components/Layout/SafeArea/SafeArea.jsx b/frontend/src/components/Layout/SafeArea/SafeArea.jsx deleted file mode 100644 index 1a75fd2d..00000000 --- a/frontend/src/components/Layout/SafeArea/SafeArea.jsx +++ /dev/null @@ -1,33 +0,0 @@ -import PropTypes from "prop-types"; -import "./SafeArea.css"; - -/** - * SafeArea Component - * Applies safe area insets for notched devices (iOS, Android) - * - * @param {Object} props - * @param {React.ReactNode} props.children - Content to wrap - * @param {string[]} props.edges - Which edges to apply insets (['top', 'right', 'bottom', 'left']) - * @param {string} props.className - Additional CSS classes - */ -export function SafeArea({ children, edges = ["all"], className = "" }) { - const edgeClasses = edges.includes("all") - ? "safe-all" - : edges.map((edge) => `safe-${edge}`).join(" "); - - const classes = ["safe-area", edgeClasses, className] - .filter(Boolean) - .join(" "); - - return
{children}
; -} - -SafeArea.propTypes = { - children: PropTypes.node.isRequired, - edges: PropTypes.arrayOf( - PropTypes.oneOf(["top", "right", "bottom", "left", "all"]), - ), - className: PropTypes.string, -}; - -export default SafeArea; diff --git a/frontend/src/components/Layout/SkipLink/SkipLink.css b/frontend/src/components/Layout/SkipLink/SkipLink.css deleted file mode 100644 index fcb403b0..00000000 --- a/frontend/src/components/Layout/SkipLink/SkipLink.css +++ /dev/null @@ -1,39 +0,0 @@ -/** - * SkipLink Styles - * Hidden by default, visible on keyboard focus - */ - -.skip-link { - position: absolute; - top: -9999px; - left: 0; - z-index: 9999; - padding: var(--spacing-md) var(--spacing-lg); - background-color: var(--color-primary); - color: white; - text-decoration: none; - font-weight: 600; - border-radius: 0 0 var(--border-radius-sm) 0; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); - transition: top 0.2s; -} - -.skip-link:focus { - top: 0; - outline: 3px solid var(--color-focus); - outline-offset: 2px; -} - -/* Ensure skip link is always readable */ -[data-theme="dark"] { - .skip-link { - background-color: var(--color-primary-dark, #0056b3); - } -} - -/* Reduced motion */ -@media (prefers-reduced-motion: reduce) { - .skip-link { - transition: none; - } -} diff --git a/frontend/src/components/Layout/SkipLink/SkipLink.jsx b/frontend/src/components/Layout/SkipLink/SkipLink.jsx deleted file mode 100644 index a69d0123..00000000 --- a/frontend/src/components/Layout/SkipLink/SkipLink.jsx +++ /dev/null @@ -1,18 +0,0 @@ -/** - * SkipLink Component - * Provides keyboard navigation shortcuts to bypass repetitive navigation - * WCAG 2.1 Level A requirement - */ - -import React from "react"; -import "./SkipLink.css"; - -export function SkipLink({ href, children }) { - return ( - - {children} - - ); -} - -export default SkipLink; diff --git a/frontend/src/components/Layout/Stack/Stack.css b/frontend/src/components/Layout/Stack/Stack.css deleted file mode 100644 index c6fc020e..00000000 --- a/frontend/src/components/Layout/Stack/Stack.css +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Stack Component Styles - * Flexible layout with gap-based spacing - */ - -.stack { - display: flex; - gap: var(--stack-spacing, 16px); -} - -/* Direction */ -.stack-vertical { - flex-direction: column; -} - -.stack-horizontal { - flex-direction: row; - flex-wrap: wrap; -} - -/* Alignment */ -.stack-align-start { - align-items: flex-start; -} - -.stack-align-center { - align-items: center; -} - -.stack-align-end { - align-items: flex-end; -} - -.stack-align-stretch { - align-items: stretch; -} - -/* Justification */ -.stack-justify-start { - justify-content: flex-start; -} - -.stack-justify-center { - justify-content: center; -} - -.stack-justify-end { - justify-content: flex-end; -} - -.stack-justify-space-between { - justify-content: space-between; -} - -.stack-justify-space-around { - justify-content: space-around; -} diff --git a/frontend/src/components/Layout/Stack/Stack.jsx b/frontend/src/components/Layout/Stack/Stack.jsx deleted file mode 100644 index eab33a99..00000000 --- a/frontend/src/components/Layout/Stack/Stack.jsx +++ /dev/null @@ -1,60 +0,0 @@ -import PropTypes from "prop-types"; -import "./Stack.css"; - -/** - * Stack Component - * Flexible layout for vertical/horizontal spacing with mobile-friendly gaps - * - * @param {Object} props - * @param {React.ReactNode} props.children - Content to stack - * @param {string} props.direction - Stack direction ('vertical'|'horizontal') - * @param {number} props.spacing - Gap between items in pixels - * @param {string} props.align - Alignment ('start'|'center'|'end'|'stretch') - * @param {string} props.justify - Justification ('start'|'center'|'end'|'space-between'|'space-around') - * @param {string} props.className - Additional CSS classes - */ -export function Stack({ - children, - direction = "vertical", - spacing = 16, - align = "stretch", - justify = "start", - className = "", -}) { - const style = { - "--stack-spacing": `${spacing}px`, - }; - - const classes = [ - "stack", - `stack-${direction}`, - `stack-align-${align}`, - `stack-justify-${justify}`, - className, - ] - .filter(Boolean) - .join(" "); - - return ( -
- {children} -
- ); -} - -Stack.propTypes = { - children: PropTypes.node.isRequired, - direction: PropTypes.oneOf(["vertical", "horizontal"]), - spacing: PropTypes.number, - align: PropTypes.oneOf(["start", "center", "end", "stretch"]), - justify: PropTypes.oneOf([ - "start", - "center", - "end", - "space-between", - "space-around", - ]), - className: PropTypes.string, -}; - -export default Stack; diff --git a/frontend/src/components/Mobile/BottomSheet/BottomSheet.css b/frontend/src/components/Mobile/BottomSheet/BottomSheet.css deleted file mode 100644 index 1c098661..00000000 --- a/frontend/src/components/Mobile/BottomSheet/BottomSheet.css +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Bottom Sheet Styles - * - * Mobile-native bottom sheet styling with iOS/Android-like appearance - * Includes smooth animations, safe area handling, and accessibility features - */ - -/* Sheet container */ -.react-modal-sheet-container { - background-color: var(--color-background, #ffffff) !important; - border-top-left-radius: 16px !important; - border-top-right-radius: 16px !important; - box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1) !important; - /* Respect safe area insets for devices with notches/home indicators */ - padding-bottom: env(safe-area-inset-bottom, 0px) !important; -} - -/* Dark theme support */ -[data-theme="dark"] { - .react-modal-sheet-container { - background-color: var(--color-background, #1a1a1a) !important; - box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.3) !important; - } -} - -/* Header section */ -.bottom-sheet-header { - display: flex; - flex-direction: column; - align-items: center; - padding: 12px 16px 8px; - gap: 8px; -} - -/* Drag indicator (visual affordance for swipe-to-dismiss) */ -.bottom-sheet-drag-indicator { - width: 36px; - height: 4px; - background-color: var(--color-border, #d1d5db); - border-radius: 2px; - flex-shrink: 0; - transition: background-color 0.2s ease; -} - -[data-theme="dark"] { - .bottom-sheet-drag-indicator { - background-color: var(--color-border, #4b5563); - } -} - -/* Title */ -.bottom-sheet-title { - font-size: 1.125rem; - font-weight: 600; - color: var(--color-text, #1f2937); - margin: 0; - width: 100%; - text-align: center; -} - -[data-theme="dark"] { - .bottom-sheet-title { - color: var(--color-text, #f9fafb); - } -} - -/* Body content */ -.bottom-sheet-body { - padding: 16px; - /* Allow scrolling within the sheet */ - overflow-y: auto; - /* Smooth scrolling */ - -webkit-overflow-scrolling: touch; - /* Maximum height to prevent content from being too tall */ - max-height: calc(100vh - 120px); -} - -/* Backdrop (dimmed overlay) */ -.react-modal-sheet-backdrop { - background-color: rgba(0, 0, 0, 0.4) !important; - /* Smooth fade in/out */ - transition: opacity 0.2s ease !important; -} - -[data-theme="dark"] { - .react-modal-sheet-backdrop { - background-color: rgba(0, 0, 0, 0.6) !important; - } -} - -/* Content scrolling behavior */ -.react-modal-sheet-content { - /* Allow content to scroll independently */ - overflow-y: auto; - -webkit-overflow-scrolling: touch; -} - -/* Prevent body scroll when sheet is open */ -body.react-modal-sheet-open { - overflow: hidden !important; -} - -/* Animation states */ -.react-modal-sheet-container[data-rsbs-is-dismissable="true"] { - cursor: grab; -} - -.react-modal-sheet-container[data-rsbs-is-dismissable="true"]:active { - cursor: grabbing; -} - -/* Focus styles for accessibility */ -.bottom-sheet button:focus-visible, -.bottom-sheet input:focus-visible, -.bottom-sheet select:focus-visible, -.bottom-sheet textarea:focus-visible, -.bottom-sheet [tabindex]:focus-visible { - outline: 2px solid var(--color-primary, #3b82f6); - outline-offset: 2px; - border-radius: 4px; -} - -/* Reduced motion support */ -@media (prefers-reduced-motion: reduce) { - .react-modal-sheet-container, - .react-modal-sheet-backdrop, - .bottom-sheet-drag-indicator { - transition: none !important; - animation: none !important; - } -} - -/* Desktop: limit width and center */ -@media (min-width: 768px) { - .react-modal-sheet-container { - max-width: 600px; - margin: 0 auto; - } -} - -/* Touch target optimization for interactive elements */ -.bottom-sheet button, -.bottom-sheet [role="button"] { - min-height: 44px; - min-width: 44px; -} diff --git a/frontend/src/components/Mobile/BottomSheet/BottomSheet.jsx b/frontend/src/components/Mobile/BottomSheet/BottomSheet.jsx deleted file mode 100644 index 34acb958..00000000 --- a/frontend/src/components/Mobile/BottomSheet/BottomSheet.jsx +++ /dev/null @@ -1,141 +0,0 @@ -/** - * BottomSheet Component - * - * A mobile-native bottom sheet component using react-modal-sheet for iOS/Android-like behavior. - * Supports multiple snap points, swipe-to-dismiss, backdrop interaction, and accessibility features. - * - * Features: - * - Configurable snap points (default: [0.4, 0.9] for partial/full height) - * - Swipe-down gesture to dismiss - * - Tap backdrop to close - * - Smooth spring animations - * - Focus trap for keyboard accessibility - * - Prevents browser pull-to-refresh when active - * - Header with visual drag indicator - * - * @example - * - * - * - */ - -import React, { useEffect, useRef } from "react"; -import { Sheet } from "react-modal-sheet"; -import "./BottomSheet.css"; - -export function BottomSheet({ - isOpen, - onClose, - children, - title, - snapPoints = [0.4, 0.9], - initialSnap = 0, - disableDrag = false, - closeOnBackdrop = true, - showHeader = true, - className = "", -}) { - const sheetRef = useRef(null); - const contentRef = useRef(null); - - /** - * Prevent browser pull-to-refresh when bottom sheet is active - * This prevents conflicts between swipe-down-to-dismiss and browser's native pull-to-refresh - */ - useEffect(() => { - if (!isOpen) return; - - const preventRefresh = (e) => { - // Only prevent if the sheet is at the top of its scroll (scrollTop === 0) - // This allows scrolling within the sheet content - if (contentRef.current?.scrollTop === 0) { - e.preventDefault(); - } - }; - - const contentElement = contentRef.current; - if (contentElement?.addEventListener) { - contentElement.addEventListener("touchmove", preventRefresh, { - passive: false, - }); - } - - return () => { - if (contentElement?.removeEventListener) { - contentElement.removeEventListener("touchmove", preventRefresh); - } - }; - }, [isOpen]); - - /** - * Focus trap: Focus the sheet when it opens for keyboard accessibility - */ - useEffect(() => { - if (isOpen) { - const focusRoot = contentRef.current ?? sheetRef.current; - const focusableElements = focusRoot?.querySelectorAll?.( - 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', - ); - - if (focusableElements?.length > 0) { - // Focus the first focusable element - focusableElements[0]?.focus(); - } - } - }, [isOpen]); - - /** - * Keyboard handler for ESC key to close - */ - useEffect(() => { - if (!isOpen) return; - - const handleKeyDown = (e) => { - if (e.key === "Escape") { - onClose(); - } - }; - - document.addEventListener("keydown", handleKeyDown); - return () => document.removeEventListener("keydown", handleKeyDown); - }, [isOpen, onClose]); - - return ( - - - - {showHeader && ( -
- - )} - - - -
{children}
-
- - - - - ); -} - -export default BottomSheet; diff --git a/frontend/src/components/Mobile/GestureHandler/GestureHandler.css b/frontend/src/components/Mobile/GestureHandler/GestureHandler.css deleted file mode 100644 index 508b791f..00000000 --- a/frontend/src/components/Mobile/GestureHandler/GestureHandler.css +++ /dev/null @@ -1,149 +0,0 @@ -/** - * GestureHandler Styles - * - * Visual feedback for touch gestures - */ - -.gesture-handler { - position: relative; - touch-action: pan-y; /* Allow vertical scrolling but enable gesture detection */ - user-select: none; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; -} - -/* Dragging state */ -.gesture-handler[data-gesture-active="true"] { - cursor: grabbing; -} - -/* Gesture feedback animations */ -.gesture-feedback-left { - animation: swipe-left-feedback 300ms ease-out; -} - -.gesture-feedback-right { - animation: swipe-right-feedback 300ms ease-out; -} - -.gesture-feedback-up { - animation: swipe-up-feedback 300ms ease-out; -} - -.gesture-feedback-down { - animation: swipe-down-feedback 300ms ease-out; -} - -/* Swipe animations */ -@keyframes swipe-left-feedback { - 0% { - transform: translateX(0); - } - 50% { - transform: translateX(-10px); - } - 100% { - transform: translateX(0); - } -} - -@keyframes swipe-right-feedback { - 0% { - transform: translateX(0); - } - 50% { - transform: translateX(10px); - } - 100% { - transform: translateX(0); - } -} - -@keyframes swipe-up-feedback { - 0% { - transform: translateY(0); - } - 50% { - transform: translateY(-10px); - } - 100% { - transform: translateY(0); - } -} - -@keyframes swipe-down-feedback { - 0% { - transform: translateY(0); - } - 50% { - transform: translateY(10px); - } - 100% { - transform: translateY(0); - } -} - -/* Gesture indicator */ -.gesture-indicator { - position: absolute; - top: 50%; - transform: translateY(-50%); - background-color: rgba(0, 0, 0, 0.7); - color: white; - padding: 0.5rem 1rem; - border-radius: 9999px; - font-size: 1.5rem; - font-weight: bold; - pointer-events: none; - z-index: 100; - animation: fade-in-out 300ms ease-out; -} - -.gesture-indicator-left { - left: 1rem; -} - -.gesture-indicator-right { - right: 1rem; -} - -.gesture-indicator-up, -.gesture-indicator-down { - left: 50%; - transform: translate(-50%, -50%); -} - -@keyframes fade-in-out { - 0% { - opacity: 0; - scale: 0.8; - } - 50% { - opacity: 1; - scale: 1; - } - 100% { - opacity: 0; - scale: 0.8; - } -} - -/* Reduced motion support */ -@media (prefers-reduced-motion: reduce) { - .gesture-handler { - animation: none !important; - } - - .gesture-feedback-left, - .gesture-feedback-right, - .gesture-feedback-up, - .gesture-feedback-down { - animation: none; - } - - .gesture-indicator { - animation: none; - opacity: 1; - } -} diff --git a/frontend/src/components/Mobile/GestureHandler/GestureHandler.jsx b/frontend/src/components/Mobile/GestureHandler/GestureHandler.jsx deleted file mode 100644 index 5f9a1b19..00000000 --- a/frontend/src/components/Mobile/GestureHandler/GestureHandler.jsx +++ /dev/null @@ -1,158 +0,0 @@ -/** - * GestureHandler Component - * - * Wraps child elements with swipe gesture detection and visual feedback. - * Provides haptic feedback and animation for touch interactions. - * - * @component - * @example - * console.log('Swiped left')} - * onSwipeRight={() => console.log('Swiped right')} - * > - *
Swipeable content
- *
- */ - -import React, { useState } from "react"; -import { useGesture } from "@/hooks/useGesture"; -import "./GestureHandler.css"; - -export const GestureHandler = ({ - children, - onSwipeLeft, - onSwipeRight, - onSwipeUp, - onSwipeDown, - onTap, - onLongPress, - swipeThreshold = 50, - velocityThreshold = 0.5, - enableHaptics = true, - showFeedback = true, - className = "", - ...props -}) => { - const [gestureState, setGestureState] = useState({ - isDragging: false, - direction: null, - distance: 0, - }); - - const bind = useGesture( - { - onSwipeLeft: (data) => { - if (showFeedback) { - setGestureState({ - isDragging: false, - direction: "left", - distance: data.distance, - }); - setTimeout( - () => - setGestureState({ - isDragging: false, - direction: null, - distance: 0, - }), - 300, - ); - } - onSwipeLeft?.(data); - }, - onSwipeRight: (data) => { - if (showFeedback) { - setGestureState({ - isDragging: false, - direction: "right", - distance: data.distance, - }); - setTimeout( - () => - setGestureState({ - isDragging: false, - direction: null, - distance: 0, - }), - 300, - ); - } - onSwipeRight?.(data); - }, - onSwipeUp: (data) => { - if (showFeedback) { - setGestureState({ - isDragging: false, - direction: "up", - distance: data.distance, - }); - setTimeout( - () => - setGestureState({ - isDragging: false, - direction: null, - distance: 0, - }), - 300, - ); - } - onSwipeUp?.(data); - }, - onSwipeDown: (data) => { - if (showFeedback) { - setGestureState({ - isDragging: false, - direction: "down", - distance: data.distance, - }); - setTimeout( - () => - setGestureState({ - isDragging: false, - direction: null, - distance: 0, - }), - 300, - ); - } - onSwipeDown?.(data); - }, - onTap: (event) => { - onTap?.(event); - }, - onLongPress: (event) => { - onLongPress?.(event); - }, - }, - { - swipeThreshold, - velocityThreshold, - enableHaptics, - }, - ); - - return ( -
- {children} - - {/* Visual feedback indicator */} - {showFeedback && gestureState.direction && ( -
- {gestureState.direction === "left" && ←} - {gestureState.direction === "right" && →} - {gestureState.direction === "up" && ↑} - {gestureState.direction === "down" && ↓} -
- )} -
- ); -}; - -export default GestureHandler; diff --git a/frontend/src/components/Mobile/LoadingState/LoadingState.css b/frontend/src/components/Mobile/LoadingState/LoadingState.css deleted file mode 100644 index ae83f892..00000000 --- a/frontend/src/components/Mobile/LoadingState/LoadingState.css +++ /dev/null @@ -1,110 +0,0 @@ -/** - * LoadingState Component Styles - * Skeleton screens with shimmer animation - */ - -.loading-state-container { - width: 100%; -} - -.loading-state { - padding: 1rem; - margin-bottom: 1rem; - background: #fff; - border-radius: 8px; -} - -/* Skeleton elements */ -.skeleton-title, -.skeleton-badge, -.skeleton-meta, -.skeleton-line, -.skeleton-chart { - background: linear-gradient( - 90deg, - #f0f0f0 0%, - #e0e0e0 20%, - #f0f0f0 40%, - #f0f0f0 100% - ); - background-size: 200% 100%; - animation: shimmer 1.5s ease-in-out infinite; - border-radius: 4px; -} - -@keyframes shimmer { - 0% { - background-position: -200% 0; - } - 100% { - background-position: 200% 0; - } -} - -/* Card skeleton */ -.loading-card .skeleton-title { - width: 60%; - height: 20px; - margin-bottom: 8px; -} - -.loading-card .skeleton-badge { - width: 80px; - height: 24px; - margin-bottom: 8px; -} - -.loading-card .skeleton-meta { - width: 40%; - height: 16px; -} - -/* List skeleton */ -.loading-list .skeleton-line { - height: 16px; - margin-bottom: 8px; -} - -.skeleton-line-full { - width: 100%; -} - -.skeleton-line-long { - width: 80%; -} - -.skeleton-line-medium { - width: 60%; -} - -/* Chart skeleton */ -.loading-chart .skeleton-chart { - width: 100%; - height: 200px; -} - -/* Spinner */ -.loading-spinner-container { - display: flex; - justify-content: center; - align-items: center; - padding: 2rem; -} - -.loading-spinner { - width: 40px; - height: 40px; - border: 4px solid #f3f3f3; - border-top: 4px solid #0066cc; - border-radius: 50%; - animation: spin 1s linear infinite; -} - -@keyframes spin { - 0% { - transform: rotate(0deg); - } - 100% { - transform: rotate(360deg); - } -} diff --git a/frontend/src/components/Mobile/LoadingState/LoadingState.jsx b/frontend/src/components/Mobile/LoadingState/LoadingState.jsx deleted file mode 100644 index 335c9a86..00000000 --- a/frontend/src/components/Mobile/LoadingState/LoadingState.jsx +++ /dev/null @@ -1,87 +0,0 @@ -import PropTypes from "prop-types"; -import "./LoadingState.css"; - -/** - * LoadingState Component - * Skeleton screens for progressive loading - * - * @param {Object} props - * @param {string} props.type - Type of loading indicator ('card'|'list'|'chart'|'text') - * @param {string} props.variant - Visual style ('skeleton'|'spinner') - * @param {number} props.count - Number of skeleton items - * @param {string} props.className - Additional CSS classes - */ -export function LoadingState({ - type = "card", - variant = "skeleton", - count = 1, - className = "", -}) { - const classes = [ - "loading-state", - `loading-${type}`, - `loading-${variant}`, - className, - ] - .filter(Boolean) - .join(" "); - - if (variant === "spinner") { - return ( -
-
-
- ); - } - - const items = Array.from({ length: count }, (_, i) => ( -
- {type === "card" && ( - <> -
-
-
- - )} - {type === "list" && ( - <> -
-
- - )} - {type === "chart" &&
} - {type === "text" && ( - <> -
-
-
- - )} -
- )); - - return ( -
- {items} -
- ); -} - -LoadingState.propTypes = { - type: PropTypes.oneOf(["card", "list", "chart", "text"]), - variant: PropTypes.oneOf(["skeleton", "spinner"]), - count: PropTypes.number, - className: PropTypes.string, -}; - -export default LoadingState; diff --git a/frontend/src/components/Mobile/TabBar/TabBar.css b/frontend/src/components/Mobile/TabBar/TabBar.css index 9dd8e09f..51a8f1c1 100644 --- a/frontend/src/components/Mobile/TabBar/TabBar.css +++ b/frontend/src/components/Mobile/TabBar/TabBar.css @@ -182,3 +182,44 @@ box-shadow: 0 0 0 2px var(--background-primary, #0d1117); } } + +/* "More" menu: the sections that do not fit in the bar. */ +.tab-bar__menu { + position: absolute; + right: 8px; + bottom: calc(64px + env(safe-area-inset-bottom) + 8px); + min-width: 200px; + margin: 0; + padding: 6px; + list-style: none; + background-color: var(--color-background, #ffffff); + border: 1px solid var(--color-border, #e1e4e8); + border-radius: 8px; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12); +} + +.tab-bar__menu-item { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + min-height: 44px; + padding: 8px 12px; + font: inherit; + color: var(--color-text-secondary, #586069); + text-align: left; + background: none; + border: none; + border-radius: 6px; + cursor: pointer; +} + +.tab-bar__menu-item[aria-current="page"] { + color: var(--color-primary, #0366d6); + font-weight: 600; +} + +.tab-bar__menu-item:focus-visible { + outline: 2px solid var(--color-primary, #0366d6); + outline-offset: -2px; +} diff --git a/frontend/src/components/Mobile/TabBar/TabBar.jsx b/frontend/src/components/Mobile/TabBar/TabBar.jsx index a6f3074a..3c1e7007 100644 --- a/frontend/src/components/Mobile/TabBar/TabBar.jsx +++ b/frontend/src/components/Mobile/TabBar/TabBar.jsx @@ -1,64 +1,129 @@ -import { - LayoutGrid, - BarChart3, - AlertTriangle, - Settings, - ShieldAlert, -} from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import PropTypes from "prop-types"; +import { MoreHorizontal } from "lucide-react"; +import { visibleSections } from "@/config/sections"; import "./TabBar.css"; +/** Tabs the bar holds before the rest move behind "More". */ +const MAX_TABS = 4; + /** * TabBar - Fixed bottom navigation for mobile devices (<768px) * - * Three tabs: Overview, Insights, Health. Fixed at bottom with safe-area - * insets, 44x44px minimum touch targets, and active-tab highlighting. + * Shows the visible sections ranked for mobile. Up to four fit; with more, + * the top three stay and the rest open from a "More" menu. Fixed at bottom + * with safe-area insets, 44x44px minimum touch targets, and active-tab + * highlighting. */ -const TABS = [ - { id: "table", label: "Overview", Icon: LayoutGrid }, - { id: "visualizations", label: "Insights", Icon: BarChart3 }, - { id: "attention", label: "Health", Icon: AlertTriangle }, -]; - -const SECURITY_TAB = { id: "security", label: "Security", Icon: ShieldAlert }; -const ADMIN_TAB = { id: "sources", label: "Sources", Icon: Settings }; - const TabBar = ({ activeTab = "table", onTabChange, - showAdmin = false, - showSecurity = false, + sections = visibleSections(), }) => { - const tabs = [ - ...TABS, - ...(showSecurity ? [SECURITY_TAB] : []), - ...(showAdmin ? [ADMIN_TAB] : []), - ]; - const handleTabClick = (tabId) => { - if (onTabChange && tabId !== activeTab) { - onTabChange(tabId); - } + const [menuOpen, setMenuOpen] = useState(false); + const rootRef = useRef(null); + // When everything fits, keep the header's order; otherwise rank for mobile. + const overflow = sections.length > MAX_TABS; + const ranked = overflow + ? [...sections].sort((a, b) => a.mobileRank - b.mobileRank) + : sections; + const shown = overflow ? ranked.slice(0, MAX_TABS - 1) : ranked; + const more = overflow ? ranked.slice(MAX_TABS - 1) : []; + const moreActive = more.some((section) => section.id === activeTab); + + useEffect(() => { + if (!menuOpen) return undefined; + const close = (event) => { + if (event.type === "keydown" && event.key !== "Escape") return; + if (event.type === "mousedown" && rootRef.current?.contains(event.target)) + return; + setMenuOpen(false); + }; + document.addEventListener("mousedown", close); + document.addEventListener("keydown", close); + return () => { + document.removeEventListener("mousedown", close); + document.removeEventListener("keydown", close); + }; + }, [menuOpen]); + + const choose = (id) => { + setMenuOpen(false); + if (onTabChange && id !== activeTab) onTabChange(id); }; + const tab = ({ id, label, Icon }) => ( + + ); + return ( -