diff --git a/apps/dashboard/src/App.tsx b/apps/dashboard/src/App.tsx index 0b0521d..f0a0c2f 100644 --- a/apps/dashboard/src/App.tsx +++ b/apps/dashboard/src/App.tsx @@ -5,7 +5,7 @@ import { CallbackPage } from './auth/CallbackPage'; import { Layout } from './components/Layout'; import { ApiKeysPage } from './pages/ApiKeysPage'; import { AuditPage } from './pages/AuditPage'; -import { LoginPage } from './pages/LoginPage'; +import { GuestHomePage } from './pages/GuestHomePage'; import { MembersPage } from './pages/MembersPage'; import { SegmentsPage } from './pages/SegmentsPage'; import { ToolDetailPage } from './pages/ToolDetailPage'; @@ -24,7 +24,9 @@ export function App() { loading ? (
Loading…
) : !user ? ( - + // Guests land on the public home page whatever path they asked for; + // its sign-in carries that path so the deep link survives login. + ) : ( diff --git a/apps/dashboard/src/auth/AuthContext.tsx b/apps/dashboard/src/auth/AuthContext.tsx index b87ec1d..3b5137b 100644 --- a/apps/dashboard/src/auth/AuthContext.tsx +++ b/apps/dashboard/src/auth/AuthContext.tsx @@ -2,12 +2,14 @@ import type { User } from 'oidc-client-ts'; import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; import { signupRedirect, userManager } from './oidc'; +import { safeReturnTo } from './return-to'; interface AuthState { user: User | null; loading: boolean; - login: () => Promise; - signup: () => Promise; + /** `returnTo` is the in-app path to land on after the Keycloak round trip. */ + login: (returnTo?: string) => Promise; + signup: (returnTo?: string) => Promise; logout: () => Promise; } @@ -40,8 +42,9 @@ export function AuthProvider({ children }: { children: ReactNode }) { value={{ user, loading, - login: () => userManager.signinRedirect(), - signup: signupRedirect, + login: (returnTo) => + userManager.signinRedirect({ state: { returnTo: safeReturnTo(returnTo) } }), + signup: (returnTo) => signupRedirect(safeReturnTo(returnTo)), logout: () => userManager.signoutRedirect(), }} > diff --git a/apps/dashboard/src/auth/CallbackPage.tsx b/apps/dashboard/src/auth/CallbackPage.tsx index 6396e7f..d9898c0 100644 --- a/apps/dashboard/src/auth/CallbackPage.tsx +++ b/apps/dashboard/src/auth/CallbackPage.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { userManager } from './oidc'; +import { returnToFromState } from './return-to'; export function CallbackPage() { const navigate = useNavigate(); @@ -14,7 +15,7 @@ export function CallbackPage() { ran.current = true; userManager .signinRedirectCallback() - .then(() => navigate('/', { replace: true })) + .then((loaded) => navigate(returnToFromState(loaded.state), { replace: true })) .catch((err: unknown) => setError(err instanceof Error ? err.message : String(err))); }, [navigate]); diff --git a/apps/dashboard/src/auth/oidc.ts b/apps/dashboard/src/auth/oidc.ts index f45519e..797f3e9 100644 --- a/apps/dashboard/src/auth/oidc.ts +++ b/apps/dashboard/src/auth/oidc.ts @@ -42,4 +42,5 @@ const signupUserManager = new UserManager({ }); /** Keycloak registration page with a full code-flow round trip back to the app. */ -export const signupRedirect = (): Promise => signupUserManager.signinRedirect(); +export const signupRedirect = (returnTo?: string): Promise => + signupUserManager.signinRedirect({ state: { returnTo } }); diff --git a/apps/dashboard/src/auth/return-to.ts b/apps/dashboard/src/auth/return-to.ts new file mode 100644 index 0000000..fbbe06b --- /dev/null +++ b/apps/dashboard/src/auth/return-to.ts @@ -0,0 +1,22 @@ +/** + * Where to land after a Keycloak round trip. The guest home sends the path the + * visitor was trying to reach through the OIDC `state`, so a deep link survives + * signing in. Anything that isn't an in-app path falls back to `/`. + */ +export function safeReturnTo(value: unknown): string { + if (typeof value !== 'string' || !value.startsWith('/')) return '/'; + // `//host` and `/\host` are protocol-relative — they leave the app. + if (/^\/[/\\]/.test(value)) return '/'; + // Returning to the callback would re-run a spent auth code. + if (value.startsWith('/auth/')) return '/'; + return value; +} + +/** Read the return path out of the `state` oidc-client-ts hands back on callback. */ +export function returnToFromState(state: unknown): string { + const raw = + typeof state === 'object' && state !== null + ? (state as { returnTo?: unknown }).returnTo + : state; + return safeReturnTo(raw); +} diff --git a/apps/dashboard/src/components/GuestNav.tsx b/apps/dashboard/src/components/GuestNav.tsx new file mode 100644 index 0000000..8d99e05 --- /dev/null +++ b/apps/dashboard/src/components/GuestNav.tsx @@ -0,0 +1,245 @@ +import { useEffect, useRef, useState } from 'react'; + +import { useAuth } from '../auth/AuthContext'; +import { cn } from '../ui/cn'; +import { MenuIcon, XIcon } from '../ui/icons'; +import { ThemeToggle } from '../ui/theme-toggle'; + +/** + * Floating "island" nav for the public landing page — a fixed, centred bar that + * gains weight past 40px of scroll but never changes size, so nothing under it + * shifts. Below `sm` the section links collapse into a disclosure panel, while + * Sign in stays in the island at every width: there is no /login screen, so this + * is the app's only entry point (see GuestHomePage). + * + * Geometry mirrors velobits-website's Navbar so the VeloBits properties share a + * visual language; the palette is ToggleFlow's own tokens (that site is + * dark-only lime, this must work in light and dark on the product accent). + */ + +const NAV_LINKS: { href: string; label: string }[] = [ + { href: '#features', label: 'Features' }, + { href: '#how', label: 'How it works' }, + { href: '#why', label: 'Why ToggleFlow' }, +]; + +/** + * At rest. In light mode --panel (#fff) ≈ --bg (#f8f8f8), so the fill reads as + * almost nothing on purpose: the hairline border and an ambient shadow do the + * separating. Dark mode's --panel is lighter than its --bg, so translucency is + * genuinely visible there and the border can step back. + */ +const SURFACE_TOP = + 'border-border/80 bg-panel/80 shadow-[0_1px_2px_rgba(0,0,0,0.03),0_6px_20px_rgba(0,0,0,0.05)] dark:border-border/60 dark:bg-panel/55 dark:shadow-[0_1px_2px_rgba(0,0,0,0.25),0_6px_20px_rgba(0,0,0,0.28)]'; + +/** Scrolled: content is passing underneath, so the pill goes near-opaque and lifts. */ +const SURFACE_SCROLLED = + 'border-border bg-panel/95 shadow-[0_1px_2px_rgba(0,0,0,0.05),0_10px_30px_rgba(0,0,0,0.10)] dark:border-border-strong dark:bg-panel/85 dark:shadow-[0_1px_2px_rgba(0,0,0,0.40),0_12px_34px_rgba(0,0,0,0.45)]'; + +const FOCUS = 'focus-visible:ring-accent focus-visible:ring-2 focus-visible:outline-none'; + +/** Section anchor as a pill hover-chip. Muted, so the accent stays with the CTA. */ +const LINK = `text-muted hover:bg-highlight hover:text-text rounded-pill px-[0.85rem] py-[0.42rem] text-[13px] font-medium whitespace-nowrap transition-colors duration-150 motion-reduce:transition-none ${FOCUS}`; + +/** Quiet button — chip treatment, with the legacy `button` box explicitly undone. */ +const QUIET = `text-muted hover:bg-highlight hover:text-text shrink-0 rounded-pill border-0 bg-transparent px-3 py-1.5 text-[13px] font-medium whitespace-nowrap transition-colors duration-150 motion-reduce:transition-none ${FOCUS}`; + +/** The one accent action. Ring offset keeps the focus ring visible on accent fill. */ +const CTA = `border-accent bg-accent hover:border-accent-hover hover:bg-accent-hover focus-visible:ring-offset-panel shrink-0 rounded-pill border px-4 py-1.5 text-[13px] font-semibold whitespace-nowrap text-white transition-colors duration-150 focus-visible:ring-offset-2 motion-reduce:transition-none ${FOCUS}`; + +export function GuestNav({ returnTo }: { returnTo: string }) { + const { login, signup } = useAuth(); + const [scrolled, setScrolled] = useState(false); + const [menuOpen, setMenuOpen] = useState(false); + const [activeHash, setActiveHash] = useState(() => window.location.hash); + const menuRef = useRef(null); + const toggleRef = useRef(null); + + useEffect(() => { + const onScroll = () => setScrolled(window.scrollY > 40); + onScroll(); // browsers restore scroll position on reload + window.addEventListener('scroll', onScroll, { passive: true }); + return () => window.removeEventListener('scroll', onScroll); + }, []); + + // aria-current follows the fragment so back/forward and deep links stay right; + // the click handlers below also set it, since hashchange fires asynchronously. + useEffect(() => { + const onHashChange = () => setActiveHash(window.location.hash); + window.addEventListener('hashchange', onHashChange); + return () => window.removeEventListener('hashchange', onHashChange); + }, []); + + useEffect(() => { + if (!menuOpen) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return; + setMenuOpen(false); + toggleRef.current?.focus(); + }; + const onMouseDown = (event: MouseEvent) => { + const target = event.target as Node; + if (menuRef.current?.contains(target) || toggleRef.current?.contains(target)) return; + setMenuOpen(false); + }; + document.addEventListener('keydown', onKeyDown); + document.addEventListener('mousedown', onMouseDown); + return () => { + document.removeEventListener('keydown', onKeyDown); + document.removeEventListener('mousedown', onMouseDown); + }; + }, [menuOpen]); + + const linkProps = (href: string) => ({ + href, + 'aria-current': activeHash === href ? ('location' as const) : undefined, + onClick: () => setActiveHash(href), + }); + + return ( + <> +
+ + + {menuOpen && ( + // `top-full` lands the panel exactly the header's pb-4 below the island + // at any nav height — no magic offset to retune. +
+ + + + +
+ )} +
+ + {menuOpen && ( +
setMenuOpen(false)} + /> + )} + + ); +} diff --git a/apps/dashboard/src/components/Layout.tsx b/apps/dashboard/src/components/Layout.tsx index 7bdd642..7aecfde 100644 --- a/apps/dashboard/src/components/Layout.tsx +++ b/apps/dashboard/src/components/Layout.tsx @@ -3,25 +3,10 @@ import { NavLink } from 'react-router-dom'; import { useAuth } from '../auth/AuthContext'; import { useWorkspace } from '../state/WorkspaceContext'; -import { isDark, toggleTheme } from '../ui/theme'; +import { ThemeToggle } from '../ui/theme-toggle'; import { useToast } from '../ui/toast'; import { ErrorNote, Modal } from './ui'; -function ThemeToggle() { - const [dark, setDark] = useState(isDark); - return ( - - ); -} - function Switchers() { const ws = useWorkspace(); const toast = useToast(); diff --git a/apps/dashboard/src/main.tsx b/apps/dashboard/src/main.tsx index df6f805..435ab94 100644 --- a/apps/dashboard/src/main.tsx +++ b/apps/dashboard/src/main.tsx @@ -6,7 +6,6 @@ import { BrowserRouter } from 'react-router-dom'; import { App } from './App'; import { AuthProvider } from './auth/AuthContext'; import './theme.css'; -import './styles.css'; import { ToastProvider } from './ui/toast'; import { initTheme } from './ui/theme'; diff --git a/apps/dashboard/src/pages/GuestHomePage.tsx b/apps/dashboard/src/pages/GuestHomePage.tsx new file mode 100644 index 0000000..276de9d --- /dev/null +++ b/apps/dashboard/src/pages/GuestHomePage.tsx @@ -0,0 +1,303 @@ +import type { ReactNode } from 'react'; +import { useLocation } from 'react-router-dom'; + +import { useAuth } from '../auth/AuthContext'; +import { GuestNav } from '../components/GuestNav'; + +/** + * Public landing page — the default screen for anyone who isn't signed in. + * Sign-in lives in the topbar (right side) rather than on a dedicated login + * screen; both auth entry points carry the path the visitor asked for so a deep + * link survives the Keycloak round trip. + */ + +const FEATURES: { title: string; body: string; glyph: string }[] = [ + { + glyph: '⏻', + title: 'Kill switch', + body: 'Turn any tool off in production instantly — no redeploy. Define the fallback users see: hide it, show a notice, or run an alternate path.', + }, + { + glyph: '◐', + title: 'Gradual rollouts', + body: 'Ship to 5%, then 25%, then everyone. Bucketing is deterministic per user, so nobody flickers between versions.', + }, + { + glyph: '◱', + title: 'Targeting & segments', + body: 'Reusable segments by plan, region, or any trait you send. The same rule model everywhere — no invented jargon.', + }, + { + glyph: '⚙', + title: 'Remote config & prompts', + body: 'Limits, endpoints, model params, and prompts edited live. Every change is versioned with a diff and one-click rollback.', + }, + { + glyph: '⚡', + title: 'Edge delivery', + body: 'Reads are served from the edge and keep serving the last published ruleset even if the control plane is down.', + }, + { + glyph: '≡', + title: 'Audit trail', + body: 'Who flipped what, when, and why — per flag and org-wide, with scoped per-environment API keys and roles.', + }, +]; + +const STEPS: { step: string; title: string; body: string }[] = [ + { + step: '1', + title: 'Register your tools', + body: 'Create a project and get dev, staging, and production environments with their own keys.', + }, + { + step: '2', + title: 'Guard them in code', + body: 'The backend SDK evaluates locally from an in-memory ruleset, so a flag check costs ~0ms and survives outages.', + }, + { + step: '3', + title: 'Control from the dashboard', + body: 'Flip a switch or edit config; connected SDKs pick the change up within seconds.', + }, +]; + +// Real `@toggleflow/sdk` API (server client) — keep in step with packages/sdk-js. +const SNIPPET = `import { createServerClient } from '@toggleflow/sdk'; + +const flags = createServerClient({ + edgeUrl: 'https://edge.toggleflow.dev', + environmentId: process.env.TF_ENV_ID, + serverKey: process.env.TF_SERVER_KEY, +}); + +app.post('/summarize', (req, res) => { + const flag = 'tool.summarize'; + if (!flags.isEnabled(flag, req.user)) { + return res.status(503).json(flags.getFallback(flag)); + } + const { model } = flags.getConfig(flag) ?? {}; + // …run the tool +});`; + +function MockRow({ + flagKey, + name, + state, +}: { + flagKey: string; + name: string; + state: 'on' | 'off' | 'rollout'; +}) { + const chip = + state === 'on' ? ( + ON + ) : state === 'off' ? ( + OFF + ) : ( + 25% + ); + const glyph = state === 'on' ? '●' : state === 'off' ? '○' : '◐'; + const tone = state === 'on' ? 'text-on' : state === 'off' ? 'text-off' : 'text-rollout'; + return ( +
+ + {glyph} + + + {flagKey} + {name} + + {chip} +
+ ); +} + +function Section({ + id, + eyebrow, + title, + children, +}: { + id: string; + eyebrow: string; + title: string; + children: ReactNode; +}) { + return ( +
+
+

+ {eyebrow} +

+

{title}

+ {children} +
+
+ ); +} + +export function GuestHomePage() { + const { login, signup } = useAuth(); + const location = useLocation(); + // A visitor who landed on /tools/abc gets sent back there after signing in. + const returnTo = `${location.pathname}${location.search}`; + + return ( +
+ + Skip to content + + + + {/* The nav is fixed, so the hero owns the clearance under it. */} +
+
+
+
+

+ VeloBits Control Plane +

+

+ A remote control plane for every tool in your app +

+

+ Kill switches, gradual rollouts, targeting, and live configuration — changed from a + dashboard and delivered in seconds. No redeploy, no waiting on a release. +

+
+ + +
+

+ Free tier · Set up in about 15 minutes · Flat, predictable pricing +

+
+ +
+
+ + ● + + fixmytext · production + + ruleset v418 +
+ + + + +
+ 254 flags · 246 on · 5 off · 3 rolling out +
+
+
+
+ +
+
    + {FEATURES.map((feature) => ( +
  • + + {feature.glyph} + +

    {feature.title}

    +

    {feature.body}

    +
  • + ))} +
+
+ +
+
+
    + {STEPS.map((item) => ( +
  1. + + {item.step} + + +

    {item.title}

    +

    {item.body}

    +
    +
  2. + ))} +
+
+              {SNIPPET}
+            
+
+
+ +
+
+
+

Flags that know what they control

+

+ A flag can carry its tool's route, owner, and model parameters — not just a + bare boolean. +

+
+
+

Config and prompts, versioned

+

+ Prompts and model params are configuration: edit, diff, and roll back without a + deploy. +

+
+
+

The read path is the promise

+

+ Evaluation runs at the edge or in your process, so your app keeps working even when + ours doesn't. +

+
+
+
+ +
+

Take back control of production

+

+ Create an organization, add your first application, and flip a real flag in minutes. +

+
+ + +
+
+
+ +
+
+ ToggleFlow — a VeloBits product + + +
+
+
+ ); +} diff --git a/apps/dashboard/src/pages/LoginPage.tsx b/apps/dashboard/src/pages/LoginPage.tsx deleted file mode 100644 index 4e33df3..0000000 --- a/apps/dashboard/src/pages/LoginPage.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { useAuth } from '../auth/AuthContext'; - -export function LoginPage() { - const { login, signup } = useAuth(); - return ( -
-
-

ToggleFlow

-

- Kill switches, gradual rollouts, and live configuration for every tool in your app. -

-
- - -
-
-
- ); -} diff --git a/apps/dashboard/src/styles.css b/apps/dashboard/src/styles.css index 3857b66..6592261 100644 --- a/apps/dashboard/src/styles.css +++ b/apps/dashboard/src/styles.css @@ -363,20 +363,3 @@ tr.clickable { height: 100vh; gap: 12px; } -.login-card { - background: var(--panel); - border: 1px solid var(--border); - border-radius: 12px; - padding: 40px; - text-align: center; - width: 360px; -} -.login-card h1 { - color: var(--accent); -} -.login-card .actions { - display: flex; - flex-direction: column; - gap: 8px; - margin-top: 20px; -} diff --git a/apps/dashboard/src/theme.css b/apps/dashboard/src/theme.css index af2323a..a0b77dd 100644 --- a/apps/dashboard/src/theme.css +++ b/apps/dashboard/src/theme.css @@ -1,5 +1,14 @@ @import 'tailwindcss'; +/* + * The hand-written component CSS goes into Tailwind's `components` layer, so + * utilities (a later layer) override it without `!important` while it still + * beats Preflight. Unlayered, `button { border-radius; padding }` and + * `a { color }` would win over every utility. Imported here rather than in + * main.tsx — a second unlayered import would defeat this. + */ +@import './styles.css' layer(components); + /* * VeloBits theme bridge — VSCode Dark+/Light inspired, same palette as * fixmytext's design system (frontend/packages/design-system/theme.css + diff --git a/apps/dashboard/src/ui/icons.tsx b/apps/dashboard/src/ui/icons.tsx new file mode 100644 index 0000000..8f01a0f --- /dev/null +++ b/apps/dashboard/src/ui/icons.tsx @@ -0,0 +1,71 @@ +import type { ReactNode, SVGProps } from 'react'; + +export interface IconProps extends SVGProps { + /** Width and height in px — icons are square. */ + size?: number | string; +} + +/** + * Stroke-based icon set (Feather/Lucide-style, 24×24 grid, currentColor) — the + * same convention as fixmytext's `@velobits/design-system` icons, copied rather + * than imported because that package is private and in a different workspace. + * Icons are decorative by default (aria-hidden); pass `aria-hidden={undefined}` + * plus an `aria-label` for semantic use. + */ +function createIcon(displayName: string, children: ReactNode) { + function Icon({ size = 16, ...props }: IconProps) { + return ( + + ); + } + Icon.displayName = displayName; + return Icon; +} + +export const MenuIcon = createIcon( + 'MenuIcon', + <> + + + + , +); + +export const MoonIcon = createIcon('MoonIcon', ); + +export const SunIcon = createIcon( + 'SunIcon', + <> + + + + + + + + + + , +); + +export const XIcon = createIcon( + 'XIcon', + <> + + + , +); diff --git a/apps/dashboard/src/ui/theme-toggle.tsx b/apps/dashboard/src/ui/theme-toggle.tsx new file mode 100644 index 0000000..a1818a2 --- /dev/null +++ b/apps/dashboard/src/ui/theme-toggle.tsx @@ -0,0 +1,21 @@ +import { useState } from 'react'; + +import { cn } from './cn'; +import { MoonIcon, SunIcon } from './icons'; +import { isDark, toggleTheme } from './theme'; + +/** Light/dark switch — shared by the app shell topbar and the public guest home. */ +export function ThemeToggle({ className }: { className?: string }) { + const [dark, setDark] = useState(isDark); + return ( + + ); +} diff --git a/apps/dashboard/test/auth.test.tsx b/apps/dashboard/test/auth.test.tsx index 1e250f4..a658f72 100644 --- a/apps/dashboard/test/auth.test.tsx +++ b/apps/dashboard/test/auth.test.tsx @@ -11,7 +11,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { AuthProvider, getAccessToken, useAuth } from '../src/auth/AuthContext'; import { CallbackPage } from '../src/auth/CallbackPage'; import { userManager } from '../src/auth/oidc'; -import { LoginPage } from '../src/pages/LoginPage'; import { stubAuth, testUser } from './harness'; afterEach(() => { @@ -113,8 +112,14 @@ describe('AuthProvider', () => { renderProbe(); await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('dev@velobits.test')); + // No argument means "land back on /" once Keycloak returns. fireEvent.click(screen.getByText('login')); - expect(auth.signinRedirect).toHaveBeenCalled(); + expect(auth.signinRedirect).toHaveBeenCalledWith({ state: { returnTo: '/' } }); + + // signupRedirect drives a second UserManager (Keycloak's /registrations) + // that this module never exports, so it is only observable as "did not + // throw" here. + expect(() => fireEvent.click(screen.getByText('signup'))).not.toThrow(); fireEvent.click(screen.getByText('logout')); expect(auth.signoutRedirect).toHaveBeenCalled(); @@ -138,23 +143,9 @@ describe('getAccessToken', () => { }); }); -describe('LoginPage', () => { - it('starts the sign-in and sign-up redirects', async () => { - const auth = stubAuth({ user: null }); - render( - - - , - ); - - fireEvent.click(screen.getByText('Sign in')); - expect(auth.signinRedirect).toHaveBeenCalled(); - - // signupRedirect drives a second UserManager (Keycloak's /registrations), - // so it is only observable as "did not throw" here. - expect(() => fireEvent.click(screen.getByText('Create account'))).not.toThrow(); - }); -}); +// The sign-in/sign-up entry points moved to GuestHomePage when the dedicated +// login screen was dropped; units.test.tsx covers them, including the returnTo +// deep link that the old LoginPage had no notion of. describe('CallbackPage', () => { const renderCallback = () => diff --git a/apps/dashboard/test/units.test.tsx b/apps/dashboard/test/units.test.tsx index 5ed93b2..e3b095b 100644 --- a/apps/dashboard/test/units.test.tsx +++ b/apps/dashboard/test/units.test.tsx @@ -1,12 +1,22 @@ // @vitest-environment happy-dom import { cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { MemoryRouter } from 'react-router-dom'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; afterEach(cleanup); +// The guest home only needs the auth actions; stubbing the context keeps the +// test off the real UserManager (network + storage). +const auth = vi.hoisted(() => ({ login: vi.fn(), signup: vi.fn() })); +vi.mock('../src/auth/AuthContext', () => ({ + useAuth: () => ({ user: null, loading: false, logout: vi.fn(), ...auth }), +})); + import type { FlagRow } from '../src/api/client'; +import { returnToFromState, safeReturnTo } from '../src/auth/return-to'; import { diffLines } from '../src/components/diff'; import { ConfirmButton, StatusChip } from '../src/components/ui'; +import { GuestHomePage } from '../src/pages/GuestHomePage'; import { EMPTY_FILTER, filterRows } from '../src/pages/tools-filter'; describe('diffLines', () => { @@ -101,3 +111,124 @@ describe('ConfirmButton', () => { expect(onConfirm).toHaveBeenCalledOnce(); }); }); + +describe('safeReturnTo', () => { + it('keeps in-app paths', () => { + expect(safeReturnTo('/tools/abc')).toBe('/tools/abc'); + expect(safeReturnTo('/audit?actor=ns')).toBe('/audit?actor=ns'); + }); + + it('rejects external, non-path, and callback targets', () => { + expect(safeReturnTo('//evil.example.com')).toBe('/'); + expect(safeReturnTo('/\\evil.example.com')).toBe('/'); + expect(safeReturnTo('https://evil.example.com')).toBe('/'); + expect(safeReturnTo('tools/abc')).toBe('/'); + expect(safeReturnTo(undefined)).toBe('/'); + expect(safeReturnTo('/auth/callback')).toBe('/'); + }); + + it('reads the path out of the oidc state', () => { + expect(returnToFromState({ returnTo: '/segments' })).toBe('/segments'); + expect(returnToFromState({})).toBe('/'); + expect(returnToFromState(null)).toBe('/'); + }); +}); + +describe('GuestHomePage', () => { + beforeEach(() => { + auth.login.mockClear(); + auth.signup.mockClear(); + // happy-dom keeps one document per file, so scroll offset and the fragment + // would leak between cases. + window.scroll({ top: 0 }); + window.history.replaceState(null, '', '/'); + }); + + const renderAt = (path: string) => + render( + + + , + ); + + it('is the landing page and offers sign-in without a login screen', () => { + renderAt('/'); + expect(screen.getByRole('heading', { level: 1 }).textContent).toContain('control plane'); + fireEvent.click(screen.getAllByText('Sign in')[0]!); + expect(auth.login).toHaveBeenCalledWith('/'); + fireEvent.click(screen.getAllByText('Get started free')[0]!); + expect(auth.signup).toHaveBeenCalledWith('/'); + }); + + it('carries the requested path into sign-in so deep links survive', () => { + renderAt('/tools/abc?env=prod'); + fireEvent.click(screen.getAllByText('Sign in')[0]!); + expect(auth.login).toHaveBeenCalledWith('/tools/abc?env=prod'); + }); + + it('weights the nav island past 40px of scroll', () => { + renderAt('/'); + const island = document.getElementById('site-nav')!; + expect(island.getAttribute('data-scrolled')).toBe('false'); + window.scroll({ top: 120 }); + fireEvent.scroll(window); + expect(island.getAttribute('data-scrolled')).toBe('true'); + window.scroll({ top: 10 }); + fireEvent.scroll(window); + expect(island.getAttribute('data-scrolled')).toBe('false'); + }); + + it('opens the mobile menu, then closes it on Escape and restores focus', () => { + renderAt('/'); + const toggle = screen.getByRole('button', { name: 'Open navigation menu' }); + expect(toggle.getAttribute('aria-expanded')).toBe('false'); + expect(toggle.getAttribute('aria-controls')).toBe('mobile-menu'); + expect(document.getElementById('mobile-menu')).toBeNull(); + + fireEvent.click(toggle); + const menu = document.getElementById('mobile-menu')!; + expect(toggle.getAttribute('aria-expanded')).toBe('true'); + expect(toggle.getAttribute('aria-label')).toBe('Close navigation menu'); + expect([...menu.querySelectorAll('a')].map((link) => link.getAttribute('href'))).toEqual([ + '#features', + '#how', + '#why', + ]); + + fireEvent.keyDown(document, { key: 'Escape' }); + expect(document.getElementById('mobile-menu')).toBeNull(); + expect(document.activeElement).toBe(toggle); + }); + + it('closes the mobile menu on an outside mousedown but not an inside one', () => { + renderAt('/'); + fireEvent.click(screen.getByRole('button', { name: 'Open navigation menu' })); + fireEvent.mouseDown(document.getElementById('mobile-menu')!); + expect(document.getElementById('mobile-menu')).toBeTruthy(); + fireEvent.mouseDown(document.body); + expect(document.getElementById('mobile-menu')).toBeNull(); + }); + + it('carries the requested path from inside the mobile menu', () => { + renderAt('/tools/abc?env=prod'); + fireEvent.click(screen.getByRole('button', { name: 'Open navigation menu' })); + const menu = document.getElementById('mobile-menu')!; + const getStarted = [...menu.querySelectorAll('button')].find( + (button) => button.textContent === 'Get started free', + )!; + fireEvent.click(getStarted); + expect(auth.signup).toHaveBeenCalledWith('/tools/abc?env=prod'); + expect(document.getElementById('mobile-menu')).toBeNull(); + }); + + it('marks the section the visitor jumped to with aria-current', () => { + renderAt('/'); + const island = document.getElementById('site-nav')!; + const features = island.querySelector('a[href="#features"]')!; + const how = island.querySelector('a[href="#how"]')!; + expect(features.getAttribute('aria-current')).toBeNull(); + fireEvent.click(features); + expect(features.getAttribute('aria-current')).toBe('location'); + expect(how.getAttribute('aria-current')).toBeNull(); + }); +});