Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(frontend): add the shared pieces for the UX laws work

spacesdrive2d03aa6db04f
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index feac71b..b9cbdcb 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -74,7 +74,7 @@ export default function App() {
<Suspense fallback={null}>
<RouterProvider router={router} />
</Suspense>
- <Toaster position="bottom-right" richColors />
+ <Toaster position="bottom-right" richColors closeButton duration={6000} />
</AuthProvider>
</TooltipProvider>
</ThemeProvider>
diff --git a/frontend/src/components/DetailPanel.tsx b/frontend/src/components/DetailPanel.tsx
index 58be805..478a33b 100644
--- a/frontend/src/components/DetailPanel.tsx
+++ b/frontend/src/components/DetailPanel.tsx
@@ -1,4 +1,5 @@
import React from 'react';
+import { AlertCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
// sticky on wide screens, stacked below the main area on narrow ones
@@ -30,23 +31,74 @@ export default function DetailPanel({ title, description, children, footer, clas
);
}
-// Label, hint and control in one settings-style row.
+export function fieldHintId(htmlFor: string): string {
+ return `${htmlFor}-hint`;
+}
+
+export function fieldErrorId(htmlFor: string): string {
+ return `${htmlFor}-error`;
+}
+
+// Label, hint, error and control in one settings-style row. With htmlFor, the hint and error are wired to a single
+// child control through aria-describedby and aria-invalid; group renders a fieldset for several controls.
export interface FieldRowProps {
label: React.ReactNode;
hint?: React.ReactNode;
+ error?: React.ReactNode;
+ optional?: boolean;
htmlFor?: string;
+ group?: boolean;
children?: React.ReactNode;
className?: string;
}
-export function FieldRow({ label, hint, htmlFor, children, className }: FieldRowProps) {
+interface DescribableProps {
+ 'aria-describedby'?: string;
+ 'aria-invalid'?: boolean;
+}
+
+export function FieldRow({ label, hint, error, optional = false, htmlFor, group = false, children, className }: FieldRowProps) {
+ const hintId = htmlFor && hint ? fieldHintId(htmlFor) : undefined;
+ const errorId = htmlFor && error ? fieldErrorId(htmlFor) : undefined;
+ const describedBy = [hintId, errorId].filter(Boolean).join(' ') || undefined;
+ const control = !group && describedBy && React.isValidElement<DescribableProps>(children)
+ ? React.cloneElement(children, {
+ 'aria-describedby': [children.props['aria-describedby'], describedBy].filter(Boolean).join(' '),
+ 'aria-invalid': error ? true : children.props['aria-invalid'],
+ })
+ : children;
+ const labelText = (
+ <>
+ {label}
+ {optional && <span className="font-normal text-ink-faint"> (optional)</span>}
+ </>
+ );
+ const hintText = hint && <p id={hintId} className="max-w-prose text-sm text-ink-muted">{hint}</p>;
+ const errorText = error && (
+ <p id={errorId} className="flex items-start gap-1.5 text-sm text-danger">
+ <AlertCircle className="mt-0.5 size-4 shrink-0 stroke-[1.75]" aria-hidden="true" />
+ <span><span className="sr-only">Error: </span>{error}</span>
+ </p>
+ );
+ if (group) {
+ // a legend only names its fieldset when it is the first child
+ return (
+ <fieldset className={cn('flex min-w-0 flex-col gap-2', className)} aria-describedby={describedBy}>
+ <legend className="text-sm font-medium text-ink">{labelText}</legend>
+ {hintText}
+ {control}
+ {errorText}
+ </fieldset>
+ );
+ }
return (
<div className={cn('flex flex-col gap-2', className)}>
<div className="flex flex-col gap-0.5">
- <label htmlFor={htmlFor} className="text-sm font-medium text-ink">{label}</label>
- {hint && <p className="text-caption text-ink-faint">{hint}</p>}
+ <label htmlFor={htmlFor} className="text-sm font-medium text-ink">{labelText}</label>
+ {hintText}
</div>
- {children}
+ {control}
+ {errorText}
</div>
);
}
diff --git a/frontend/src/components/LiveStatus.tsx b/frontend/src/components/LiveStatus.tsx
new file mode 100644
index 0000000..d67d861
--- /dev/null
+++ b/frontend/src/components/LiveStatus.tsx
@@ -0,0 +1,16 @@
+import { cn } from '@/lib/utils';
+
+export interface LiveStatusProps {
+ message: string;
+ visible?: boolean;
+ className?: string;
+}
+
+// stays mounted with changing text, because screen readers only announce changes to a region they already know
+export default function LiveStatus({ message, visible = false, className }: LiveStatusProps) {
+ return (
+ <p role="status" aria-live="polite" aria-atomic="true" className={cn(!visible && 'sr-only', className)}>
+ {message}
+ </p>
+ );
+}
diff --git a/frontend/src/components/Num.tsx b/frontend/src/components/Num.tsx
new file mode 100644
index 0000000..3685aa7
--- /dev/null
+++ b/frontend/src/components/Num.tsx
@@ -0,0 +1,24 @@
+import { fmtNum, fmtNumFull } from '@/utils/formatters';
+import type { NumberLike } from '@/utils/formatters';
+import { cn } from '@/lib/utils';
+
+export interface NumProps {
+ value: NumberLike;
+ suffix?: string;
+ className?: string;
+}
+
+// a rounded figure that still offers the exact one: on hover for the mouse, and read aloud in full
+export default function Num({ value, suffix = '', className }: NumProps) {
+ const short = fmtNum(value);
+ const full = fmtNumFull(value);
+ if (short === full) {
+ return <span className={cn('tabular-nums', className)}>{short}{suffix}</span>;
+ }
+ return (
+ <data value={String(Number(value ?? 0))} title={`${full}${suffix}`} className={cn('tabular-nums', className)}>
+ <span aria-hidden="true">{short}{suffix}</span>
+ <span className="sr-only">{full}{suffix}</span>
+ </data>
+ );
+}
diff --git a/frontend/src/components/RelativeTime.tsx b/frontend/src/components/RelativeTime.tsx
new file mode 100644
index 0000000..1e43d65
--- /dev/null
+++ b/frontend/src/components/RelativeTime.tsx
@@ -0,0 +1,20 @@
+import { fmtDateTime, timeAgo } from '@/utils/formatters';
+import type { DateLike } from '@/utils/formatters';
+
+export interface RelativeTimeProps {
+ date: DateLike;
+ prefix?: string;
+ className?: string;
+}
+
+// a recent age reads faster as "2h ago"; the exact date and time stay on hover and are read aloud
+export default function RelativeTime({ date, prefix = '', className }: RelativeTimeProps) {
+ if (!date) return <span className={className}>{prefix}{timeAgo(date)}</span>;
+ const exact = fmtDateTime(date);
+ return (
+ <time dateTime={new Date(date).toISOString()} title={exact} className={className}>
+ <span aria-hidden="true">{prefix}{timeAgo(date)}</span>
+ <span className="sr-only">{prefix}{exact}</span>
+ </time>
+ );
+}
diff --git a/frontend/src/components/SurfaceBox.tsx b/frontend/src/components/SurfaceBox.tsx
index 7d3f22f..fae49e7 100644
--- a/frontend/src/components/SurfaceBox.tsx
+++ b/frontend/src/components/SurfaceBox.tsx
@@ -1,5 +1,6 @@
-import React from 'react';
+import React, { useId } from 'react';
import { cn } from '@/lib/utils';
+import { SurfaceTitleContext } from './surfaceTitle';
export interface SurfaceBoxProps extends Omit<React.ComponentProps<'section'>, 'title' | 'content'> {
children?: React.ReactNode;
@@ -10,6 +11,7 @@ export interface SurfaceBoxProps extends Omit<React.ComponentProps<'section'>, '
contentClassName?: string;
className?: string;
noPadding?: boolean;
+ headingLevel?: 'h2' | 'h3';
}
// the one container for grouped content; without a title it is a plain panel
@@ -22,27 +24,31 @@ export default function SurfaceBox({
contentClassName = '',
className = '',
noPadding = false,
+ headingLevel: Heading = 'h2',
...props
}: SurfaceBoxProps) {
+ const titleId = useId();
return (
- <section
- className={cn('flex flex-col rounded-card border border-line bg-surface-raised text-ink', className)}
- {...props}
- >
- {title && (
- <header className="flex items-start justify-between gap-4 border-b border-divider px-5 py-4">
- <div className="min-w-0">
- <h3 className="font-heading text-section font-semibold">{title}</h3>
- {subheader && <p className="mt-0.5 text-small text-ink-muted">{subheader}</p>}
- </div>
- {secondary && <div className="shrink-0">{secondary}</div>}
- </header>
- )}
- {content ? (
- <div className={cn('px-5 py-4', noPadding && 'p-0', contentClassName)}>{children}</div>
- ) : (
- children
- )}
- </section>
+ <SurfaceTitleContext.Provider value={title ? titleId : undefined}>
+ <section
+ className={cn('flex flex-col rounded-card border border-line bg-surface-raised text-ink', className)}
+ {...props}
+ >
+ {title && (
+ <header className="flex items-start justify-between gap-4 border-b border-divider px-5 py-4">
+ <div className="min-w-0">
+ <Heading id={titleId} className="font-heading text-section font-semibold">{title}</Heading>
+ {subheader && <div className="mt-0.5 max-w-prose text-small text-ink-muted">{subheader}</div>}
+ </div>
+ {secondary && <div className="shrink-0">{secondary}</div>}
+ </header>
+ )}
+ {content ? (
+ <div className={cn('px-5 py-4', noPadding && 'p-0', contentClassName)}>{children}</div>
+ ) : (
+ children
+ )}
+ </section>
+ </SurfaceTitleContext.Provider>
);
}
diff --git a/frontend/src/components/surfaceTitle.ts b/frontend/src/components/surfaceTitle.ts
new file mode 100644
index 0000000..d227aa7
--- /dev/null
+++ b/frontend/src/components/surfaceTitle.ts
@@ -0,0 +1,8 @@
+import { createContext, useContext } from 'react';
+
+// the id of the nearest SurfaceBox title, so a table inside can take its accessible name from it
+export const SurfaceTitleContext = createContext<string | undefined>(undefined);
+
+export function useSurfaceTitleId(): string | undefined {
+ return useContext(SurfaceTitleContext);
+}
diff --git a/frontend/src/components/ui/alert.tsx b/frontend/src/components/ui/alert.tsx
index 91a68f3..5a17394 100644
--- a/frontend/src/components/ui/alert.tsx
+++ b/frontend/src/components/ui/alert.tsx
@@ -21,6 +21,7 @@ const alertVariants = cva(
}
)
+// static notes stay silent; pass role="alert" only for a message that appears in response to something
function Alert({
className,
variant,
@@ -29,7 +30,6 @@ function Alert({
return (
<div
data-slot="alert"
- role="alert"
className={cn(alertVariants({ variant }), className)}
{...props} />
);
@@ -43,7 +43,7 @@ function AlertTitle({
<div
data-slot="alert-title"
className={cn(
- "font-medium group-has-[>svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground",
+ "font-medium group-has-[>svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-ink",
className
)}
{...props} />
@@ -58,7 +58,7 @@ function AlertDescription({
<div
data-slot="alert-description"
className={cn(
- "text-sm text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
+ "text-sm text-balance text-ink-muted md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-ink [&_p:not(:last-child)]:mb-4",
className
)}
{...props} />
diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsx
index 033abc7..f64eddc 100644
--- a/frontend/src/components/ui/input.tsx
+++ b/frontend/src/components/ui/input.tsx
@@ -13,7 +13,7 @@ function Input({
type={type}
data-slot="input"
className={cn(
- "h-(--control-h) w-full min-w-0 rounded-field border border-input bg-surface-raised px-3 py-1 text-base text-ink transition-colors duration-(--duration-fast) outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-ink placeholder:text-ink-faint hover:border-ink-muted focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-surface-sunken disabled:opacity-60 aria-invalid:border-danger md:text-sm",
+ "h-(--control-h) w-full min-w-0 rounded-field border border-input bg-surface-raised px-3 py-1 text-base text-ink transition-colors duration-(--duration-fast) outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-ink placeholder:text-ink-faint hover:border-ink-muted focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-surface-sunken disabled:opacity-60 aria-invalid:border-danger",
className
)}
{...props} />
diff --git a/frontend/src/components/ui/spinner.tsx b/frontend/src/components/ui/spinner.tsx
index a96a654..4feb256 100644
--- a/frontend/src/components/ui/spinner.tsx
+++ b/frontend/src/components/ui/spinner.tsx
@@ -2,16 +2,17 @@ import type * as React from "react"
import { cn } from "@/lib/utils"
import { Loader2Icon } from "lucide-react"
+// decorative: the busy button label or the surrounding status region says what is happening
function Spinner({
className,
...props
}: React.ComponentProps<"svg">) {
return (
- <Loader2Icon
- role="status"
- aria-label="Loading"
- className={cn("size-4 animate-spin", className)}
- {...props} />
+ <span data-slot="spinner" className="delayed-appear inline-flex shrink-0" aria-hidden="true">
+ <Loader2Icon
+ className={cn("size-4 animate-spin", className)}
+ {...props} />
+ </span>
);
}
diff --git a/frontend/src/components/ui/table.tsx b/frontend/src/components/ui/table.tsx
index f5ad0ed..2cc0a21 100644
--- a/frontend/src/components/ui/table.tsx
+++ b/frontend/src/components/ui/table.tsx
@@ -1,16 +1,46 @@
import * as React from "react"
import { cn } from "@/lib/utils"
+import { useSurfaceTitleId } from "@/components/surfaceTitle"
+
+// a table wider than its box scrolls inside it, and the scroll box must then be reachable by keyboard
+function useOverflows(ref: React.RefObject<HTMLDivElement | null>): boolean {
+ const [overflows, setOverflows] = React.useState(false)
+ React.useEffect(() => {
+ const node = ref.current
+ if (!node) return
+ const measure = () => setOverflows(node.scrollWidth > node.clientWidth + 1)
+ measure()
+ const observer = new ResizeObserver(measure)
+ observer.observe(node)
+ if (node.firstElementChild) observer.observe(node.firstElementChild)
+ return () => observer.disconnect()
+ }, [ref])
+ return overflows
+}
function Table({
className,
+ containerClassName,
...props
-}: React.ComponentProps<"table">) {
+}: React.ComponentProps<"table"> & { containerClassName?: string }) {
+ const containerRef = React.useRef<HTMLDivElement>(null)
+ const overflows = useOverflows(containerRef)
+ const surfaceTitleId = useSurfaceTitleId()
+ const labelledBy = props["aria-label"] ? undefined : (props["aria-labelledby"] ?? surfaceTitleId)
return (
- <div data-slot="table-container" className="relative w-full overflow-x-auto">
+ <div
+ ref={containerRef}
+ data-slot="table-container"
+ className={cn("relative w-full overflow-x-auto", containerClassName)}
+ {...(overflows
+ ? { tabIndex: 0, role: "region", "aria-labelledby": labelledBy, "aria-label": props["aria-label"] }
+ : {})}
+ >
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
+ aria-labelledby={labelledBy}
{...props} />
</div>
);
@@ -69,11 +99,13 @@ function TableRow({
function TableHead({
className,
+ scope = "col",
...props
}: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
+ scope={scope}
className={cn(
"h-10 px-3 text-left align-middle text-caption font-medium whitespace-nowrap text-ink-muted [&:has([role=checkbox])]:pr-0",
className
@@ -104,7 +136,7 @@ function TableCaption({
return (
<caption
data-slot="table-caption"
- className={cn("mt-4 text-sm text-muted-foreground", className)}
+ className={cn("mt-4 text-sm text-ink-muted", className)}
{...props} />
);
}
diff --git a/frontend/src/components/ui/textarea.tsx b/frontend/src/components/ui/textarea.tsx
index 9a06db3..392d840 100644
--- a/frontend/src/components/ui/textarea.tsx
+++ b/frontend/src/components/ui/textarea.tsx
@@ -10,7 +10,7 @@ function Textarea({
<textarea
data-slot="textarea"
className={cn(
- "flex field-sizing-content min-h-16 w-full rounded-field border border-input bg-surface-raised px-3 py-2 text-base text-ink transition-colors duration-(--duration-fast) outline-none placeholder:text-ink-faint hover:border-ink-muted focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:bg-surface-sunken disabled:opacity-60 aria-invalid:border-danger md:text-sm",
+ "flex field-sizing-content min-h-16 w-full rounded-field border border-input bg-surface-raised px-3 py-2 text-base text-ink transition-colors duration-(--duration-fast) outline-none placeholder:text-ink-faint hover:border-ink-muted focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:bg-surface-sunken disabled:opacity-60 aria-invalid:border-danger",
className
)}
{...props} />
diff --git a/frontend/src/context/AppContext.tsx b/frontend/src/context/AppContext.tsx
index f00da56..68f1846 100644
--- a/frontend/src/context/AppContext.tsx
+++ b/frontend/src/context/AppContext.tsx
@@ -23,7 +23,8 @@ export function AppProvider({ children }: { children: ReactNode }) {
const [loading, setLoading] = useState(false);
const showToast = useCallback((message: string, severity: ToastSeverity = 'success') => {
- if (severity === 'error') toast.error(message);
+ // an error stays until it is closed, because reading it and acting on it takes longer than a confirmation
+ if (severity === 'error') toast.error(message, { duration: Infinity });
else if (severity === 'warning') toast.warning(message);
else if (severity === 'info') toast.info(message);
else toast.success(message);
diff --git a/frontend/src/hooks/use-url-state.ts b/frontend/src/hooks/use-url-state.ts
new file mode 100644
index 0000000..4fbe146
--- /dev/null
+++ b/frontend/src/hooks/use-url-state.ts
@@ -0,0 +1,38 @@
+import { useCallback } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import { readChoice, readParam, readPositiveInt, withParam } from '@/lib/urlState';
+
+export interface UrlStateOptions {
+ // typing replaces the history entry; a tab or page change adds one so Back returns to it
+ history?: 'push' | 'replace';
+}
+
+export function useUrlState(key: string, fallback = '', { history = 'replace' }: UrlStateOptions = {}) {
+ const [params, setParams] = useSearchParams();
+ const value = readParam(params, key, fallback);
+ const setValue = useCallback(
+ (next: string) => setParams(current => withParam(current, key, next, fallback), { replace: history === 'replace' }),
+ [setParams, key, fallback, history],
+ );
+ return [value, setValue] as const;
+}
+
+export function useUrlChoice<T extends string>(key: string, choices: readonly T[], fallback: T, { history = 'push' }: UrlStateOptions = {}) {
+ const [params, setParams] = useSearchParams();
+ const value = readChoice(params, key, choices, fallback);
+ const setValue = useCallback(
+ (next: T) => setParams(current => withParam(current, key, next, fallback), { replace: history === 'replace' }),
+ [setParams, key, fallback, history],
+ );
+ return [value, setValue] as const;
+}
+
+export function useUrlPage(key = 'page', { history = 'push' }: UrlStateOptions = {}) {
+ const [params, setParams] = useSearchParams();
+ const value = readPositiveInt(params, key, 1);
+ const setValue = useCallback(
+ (next: number) => setParams(current => withParam(current, key, String(next), '1'), { replace: history === 'replace' }),
+ [setParams, key, history],
+ );
+ return [value, setValue] as const;
+}
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 5e7bd2d..babb36b 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -100,6 +100,8 @@
--control-h-sm: 2rem;
--control-h-lg: 2.5rem;
--nav-row-h: 2rem;
+ /* room kept above a focused element so the sticky top bar never covers it */
+ --focus-clearance: calc(var(--topbar-h) + 1rem);
/* Motion */
--duration-fast: 75ms;
@@ -198,12 +200,15 @@
--text-section: 1rem;
--text-section--line-height: 1.5rem;
--text-section--letter-spacing: -0.01em;
- --text-body: 0.875rem;
- --text-body--line-height: 1.25rem;
+ --text-body: 1rem;
+ --text-body--line-height: 1.5rem;
--text-small: 0.8125rem;
--text-small--line-height: 1.21875rem;
--text-caption: 0.75rem;
--text-caption--line-height: 1rem;
+ --text-metric: 1.75rem;
+ --text-metric--line-height: 2.25rem;
+ --text-metric--letter-spacing: -0.02em;
--color-background: var(--background);
--color-foreground: var(--foreground);
@@ -293,6 +298,12 @@
--animate-fold-in: fold-in var(--duration-fold) var(--ease-fold) both;
}
+/* spinners wait before showing, so a fast answer does not flash one */
+@keyframes delayed-appear {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+
@keyframes fold-in {
from { opacity: 0; transform: translate(-4px, 7px); }
to { opacity: 1; transform: none; }
@@ -311,6 +322,7 @@
}
html {
@apply font-sans;
+ scroll-padding-top: var(--focus-clearance);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
@@ -325,6 +337,15 @@
font-family: var(--font-heading);
font-weight: 600;
}
+ /* a finger needs a bigger target than a pointer, so touch screens get 44 px controls */
+ @media (pointer: coarse) {
+ :root {
+ --control-h: 2.75rem;
+ --control-h-sm: 2.5rem;
+ --control-h-lg: 2.75rem;
+ --nav-row-h: 2.75rem;
+ }
+ }
:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
@@ -351,6 +372,9 @@
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
+ .delayed-appear {
+ animation: delayed-appear 1ms var(--spinner-delay, 300ms) both;
+ }
.tabular {
font-variant-numeric: tabular-nums;
}
diff --git a/frontend/src/lib/deferredActions.ts b/frontend/src/lib/deferredActions.ts
new file mode 100644
index 0000000..ed34f64
--- /dev/null
+++ b/frontend/src/lib/deferredActions.ts
@@ -0,0 +1,46 @@
+// a delete that waits a few seconds before it reaches the server, so Undo can cancel it without a restore call
+
+export interface DeferredActions {
+ schedule: (id: string, delayMs: number, commit: () => Promise<void> | void) => void;
+ cancel: (id: string) => boolean;
+ flush: () => Promise<void>;
+ pending: () => number;
+}
+
+interface DeferredAction {
+ commit: () => Promise<void> | void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+export function createDeferredActions(): DeferredActions {
+ const actions = new Map<string, DeferredAction>();
+
+ const run = async (id: string) => {
+ const action = actions.get(id);
+ if (!action) return;
+ actions.delete(id);
+ clearTimeout(action.timer);
+ await action.commit();
+ };
+
+ return {
+ schedule(id, delayMs, commit) {
+ const existing = actions.get(id);
+ if (existing) clearTimeout(existing.timer);
+ actions.set(id, { commit, timer: setTimeout(() => { void run(id); }, delayMs) });
+ },
+ cancel(id) {
+ const action = actions.get(id);
+ if (!action) return false;
+ clearTimeout(action.timer);
+ actions.delete(id);
+ return true;
+ },
+ async flush() {
+ await Promise.all([...actions.keys()].map(run));
+ },
+ pending() {
+ return actions.size;
+ },
+ };
+}
diff --git a/frontend/src/lib/undoToast.ts b/frontend/src/lib/undoToast.ts
new file mode 100644
index 0000000..eee1b36
--- /dev/null
+++ b/frontend/src/lib/undoToast.ts
@@ -0,0 +1,40 @@
+import { toast } from 'sonner';
+import { createDeferredActions } from './deferredActions';
+
+// long enough to notice the toast and reach Undo, short enough that the list does not show a stale state for long
+export const UNDO_WINDOW_MS = 8000;
+
+const deferred = createDeferredActions();
+
+// leaving the page sends any delete still waiting, so what the person saw removed stays removed
+if (typeof window !== 'undefined') {
+ window.addEventListener('pagehide', () => { void deferred.flush(); });
+}
+
+export interface UndoableDelete {
+ id: string;
+ message: string;
+ commit: () => Promise<void>;
+ onUndo: () => void;
+ onFailure: (error: Error) => void;
+}
+
+// the caller removes the item from view first; the server delete runs only if Undo is not pressed in time
+export function deleteWithUndo({ id, message, commit, onUndo, onFailure }: UndoableDelete): void {
+ deferred.schedule(id, UNDO_WINDOW_MS, async () => {
+ try {
+ await commit();
+ } catch (err) {
+ onFailure(err as Error);
+ }
+ });
+ toast.success(message, {
+ duration: UNDO_WINDOW_MS,
+ action: {
+ label: 'Undo',
+ onClick: () => {
+ if (deferred.cancel(id)) onUndo();
+ },
+ },
+ });
+}
diff --git a/frontend/src/lib/urlState.ts b/frontend/src/lib/urlState.ts
new file mode 100644
index 0000000..b475683
--- /dev/null
+++ b/frontend/src/lib/urlState.ts
@@ -0,0 +1,24 @@
+// view state kept in the address, so Back, refresh and a shared link show the same view
+
+export function readParam(params: URLSearchParams, key: string, fallback: string): string {
+ return params.get(key) ?? fallback;
+}
+
+// the default value is left out, so a page with nothing changed keeps a clean address
+export function withParam(params: URLSearchParams, key: string, value: string, fallback: string): URLSearchParams {
+ const next = new URLSearchParams(params);
+ if (value === fallback || value === '') next.delete(key);
+ else next.set(key, value);
+ return next;
+}
+
+export function readPositiveInt(params: URLSearchParams, key: string, fallback: number): number {
+ const parsed = Number.parseInt(params.get(key) ?? '', 10);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
+}
+
+// an address can carry any text, so a value outside the allowed set falls back to the default
+export function readChoice<T extends string>(params: URLSearchParams, key: string, choices: readonly T[], fallback: T): T {
+ const value = params.get(key);
+ return choices.find(choice => choice === value) ?? fallback;
+}
diff --git a/frontend/src/utils/formatters.ts b/frontend/src/utils/formatters.ts
index 7cdf435..6d6c689 100644
--- a/frontend/src/utils/formatters.ts
+++ b/frontend/src/utils/formatters.ts
@@ -3,13 +3,20 @@ import type { SafeAccount } from '../../../shared/types/domain.ts';
export type NumberLike = number | string | null | undefined;
export type DateLike = string | number | Date | null | undefined;
+const COMPACT_UNITS: ReadonlyArray<readonly [number, string]> = [[1e9, 'B'], [1e6, 'M'], [1e3, 'K']];
+
+// one decimal, without a trailing .0, and a value that would round up to 1000 of a unit moves to the next unit
export function fmtNum(n: NumberLike): string {
if (n == null) return '0';
- n = Number(n);
- if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B';
- if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
- if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
- return n.toLocaleString();
+ const value = Number(n);
+ const size = Math.abs(value);
+ for (let index = 0; index < COMPACT_UNITS.length; index++) {
+ const [unit, suffix] = COMPACT_UNITS[index];
+ const smaller = COMPACT_UNITS[index + 1];
+ const roundsUp = smaller !== undefined && Math.round((size / smaller[0]) * 10) / 10 >= 1000;
+ if (size >= unit || roundsUp) return String(Number((value / unit).toFixed(1))) + suffix;
+ }
+ return value.toLocaleString('en-US');
}
// For counts a platform can hide (YouTube likes, disabled comments): null means hidden, not zero.
@@ -19,7 +26,7 @@ export function fmtCount(n: NumberLike): string {
export function fmtNumFull(n: NumberLike): string {
if (n == null) return '0';
- return Number(n).toLocaleString();
+ return Number(n).toLocaleString('en-US');
}
export function fmtDate(d: DateLike): string {
@@ -27,6 +34,13 @@ export function fmtDate(d: DateLike): string {
return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}
+export function fmtDateTime(d: DateLike): string {
+ if (!d) return '';
+ return new Date(d).toLocaleString('en-US', {
+ year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
+ });
+}
+
export function fmtDateShort(d: DateLike): string {
if (!d) return '';
return new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
@@ -56,8 +70,8 @@ export function timeAgo(date: DateLike): string {
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
if (days < 30) return `${days}d ago`;
- const months = Math.floor(days / 30);
- return `${months}mo ago`;
+ // past a month a relative age is harder to place than the date itself
+ return fmtDate(date);
}
export const CATEGORY_MAP: Record<string, string> = {
diff --git a/frontend/tests/lib/deferredActions.test.ts b/frontend/tests/lib/deferredActions.test.ts
new file mode 100644
index 0000000..359fdbf
--- /dev/null
+++ b/frontend/tests/lib/deferredActions.test.ts
@@ -0,0 +1,38 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createDeferredActions } from '../../src/lib/deferredActions.ts';
+
+test('a scheduled action runs once its delay has passed', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const actions = createDeferredActions();
+ let ran = 0;
+ actions.schedule('rule-1', 8000, () => { ran++; });
+ t.mock.timers.tick(7999);
+ assert.equal(ran, 0);
+ t.mock.timers.tick(1);
+ await Promise.resolve();
+ assert.equal(ran, 1);
+ assert.equal(actions.pending(), 0);
+});
+
+test('cancelling before the delay means the action never runs', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const actions = createDeferredActions();
+ let ran = 0;
+ actions.schedule('rule-1', 8000, () => { ran++; });
+ assert.equal(actions.cancel('rule-1'), true);
+ t.mock.timers.tick(8000);
+ await Promise.resolve();
+ assert.equal(ran, 0);
+ assert.equal(actions.cancel('rule-1'), false);
+});
+
+test('flushing runs every waiting action at once', async () => {
+ const actions = createDeferredActions();
+ const ran: string[] = [];
+ actions.schedule('a', 60_000, () => { ran.push('a'); });
+ actions.schedule('b', 60_000, () => { ran.push('b'); });
+ await actions.flush();
+ assert.deepEqual(ran.sort(), ['a', 'b']);
+ assert.equal(actions.pending(), 0);
+});
diff --git a/frontend/tests/lib/urlState.test.ts b/frontend/tests/lib/urlState.test.ts
new file mode 100644
index 0000000..6cef707
--- /dev/null
+++ b/frontend/tests/lib/urlState.test.ts
@@ -0,0 +1,33 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readChoice, readParam, readPositiveInt, withParam } from '../../src/lib/urlState.ts';
+
+test('a missing parameter reads as its default', () => {
+ assert.equal(readParam(new URLSearchParams(''), 'q', ''), '');
+ assert.equal(readParam(new URLSearchParams('q=cats'), 'q', ''), 'cats');
+});
+
+test('setting a parameter to its default removes it from the address', () => {
+ const params = withParam(new URLSearchParams('q=cats&tab=views'), 'tab', 'overview', 'overview');
+ assert.equal(params.toString(), 'q=cats');
+ assert.equal(withParam(params, 'q', '', '').toString(), '');
+});
+
+test('setting a parameter keeps the others and leaves the original unchanged', () => {
+ const original = new URLSearchParams('q=cats');
+ const next = withParam(original, 'page', '3', '1');
+ assert.equal(next.toString(), 'q=cats&page=3');
+ assert.equal(original.toString(), 'q=cats');
+});
+
+test('a page number that is not a positive whole number falls back to the default', () => {
+ assert.equal(readPositiveInt(new URLSearchParams('page=4'), 'page', 1), 4);
+ assert.equal(readPositiveInt(new URLSearchParams('page=0'), 'page', 1), 1);
+ assert.equal(readPositiveInt(new URLSearchParams('page=abc'), 'page', 1), 1);
+});
+
+test('a choice outside the allowed set falls back to the default', () => {
+ const tabs = ['overview', 'views'] as const;
+ assert.equal(readChoice(new URLSearchParams('tab=views'), 'tab', tabs, 'overview'), 'views');
+ assert.equal(readChoice(new URLSearchParams('tab=unknown'), 'tab', tabs, 'overview'), 'overview');
+});
diff --git a/frontend/tests/utils/formatters.test.ts b/frontend/tests/utils/formatters.test.ts
new file mode 100644
index 0000000..9c02f20
--- /dev/null
+++ b/frontend/tests/utils/formatters.test.ts
@@ -0,0 +1,25 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { fmtDate, fmtNum, timeAgo } from '../../src/utils/formatters.ts';
+
+test('compact numbers drop a trailing .0', () => {
+ assert.equal(fmtNum(1000), '1K');
+ assert.equal(fmtNum(12_400), '12.4K');
+ assert.equal(fmtNum(2_000_000), '2M');
+});
+
+test('a value that would round to 1000 of a unit moves to the next unit', () => {
+ assert.equal(fmtNum(999_950), '1M');
+ assert.equal(fmtNum(999_949), '999.9K');
+});
+
+test('small and missing numbers are shown in full', () => {
+ assert.equal(fmtNum(999), '999');
+ assert.equal(fmtNum(null), '0');
+});
+
+test('a date older than a month shows as a date rather than an age', () => {
+ const old = new Date(Date.now() - 45 * 24 * 60 * 60 * 1000);
+ assert.equal(timeAgo(old), fmtDate(old));
+ assert.equal(timeAgo(new Date(Date.now() - 2 * 60 * 60 * 1000)), '2h ago');
+});