Skip to content
302 linesCodeBlameRaw
1/**
2 * sudo's building blocks, after apps/web/app/components/ui. None of them
3 * sets a `style` attribute: the content security policy allows no inline
4 * styles, so sizes and colours that vary are drawn as SVG attributes.
5 */
6import { AlertTriangle, CheckCircle2, ChevronDown, Info } from "lucide-react";
7import type { ComponentProps, ReactNode } from "react";
8import { Link, type LinkProps, useRouteLoaderData } from "react-router";
9
10import type { Limit, Terms, Trust } from "@g1t/contracts";
11
12import { usd } from "~/lib/money";
13import { fullDiscount, termsLabel } from "~/lib/terms";
14import { when } from "~/lib/time";
15
16export function Field({
17 label,
18 hint,
19 children,
20 className = "",
21}: {
22 label: string;
23 hint?: ReactNode;
24 children: ReactNode;
25 className?: string;
26}) {
27 return (
28 <label className={`block ${className}`}>
29 <span className="mb-1.5 block text-sm font-medium text-muted">{label}</span>
30 {children}
31 {hint && <span className="mt-1.5 block text-xs text-faint">{hint}</span>}
32 </label>
33 );
34}
35
36const CONTROL =
37 "w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none transition-colors placeholder:text-faint hover:border-line-strong focus:border-accent/60";
38
39/** Tells password managers that a field is not a login. */
40const NOT_A_CREDENTIAL = {
41 autoComplete: "off",
42 "data-1p-ignore": true,
43 "data-lpignore": "true",
44 "data-bwignore": true,
45 "data-form-type": "other",
46};
47
48export function Input({ className = "", ...props }: ComponentProps<"input">) {
49 return <input {...NOT_A_CREDENTIAL} {...props} className={`${CONTROL} ${className}`} />;
50}
51
52export function Textarea({ className = "", ...props }: ComponentProps<"textarea">) {
53 return <textarea {...NOT_A_CREDENTIAL} {...props} className={`${CONTROL} ${className}`} />;
54}
55
56/** Classes that size or place the control, which belong on its wrapper. */
57const LAYOUT = /^(?:[a-z0-9]+:)*(?:w-|min-w-|max-w-|flex-|shrink|grow|basis-|self-|col-|row-|order-|m[trblxy]?-)/;
58
59/**
60 * A native select drawn as shadcn's NativeSelect: the browser's own arrow
61 * hidden, a chevron of ours in its place. Native because sudo ships no
62 * JavaScript, so it still opens, types to search and works on phones.
63 */
64export function Select({ className = "", ...props }: ComponentProps<"select">) {
65 const classes = className.split(/\s+/).filter(Boolean);
66 const outer = classes.filter((name) => LAYOUT.test(name)).join(" ");
67 const inner = classes.filter((name) => !LAYOUT.test(name)).join(" ");
68 return (
69 <span className={`relative block w-full ${outer}`}>
70 <select {...props} className={`${CONTROL} cursor-pointer appearance-none pr-9 ${inner}`} />
71 <ChevronDown aria-hidden className="pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted" />
72 </span>
73 );
74}
75
76type Variant = "primary" | "quiet" | "danger" | "lavender";
77
78const BUTTON_BASE =
79 "inline-flex items-center justify-center gap-2 rounded-md px-3.5 py-2 text-sm font-medium whitespace-nowrap transition-colors disabled:opacity-50";
80
81const BUTTON_VARIANTS: Record<Variant, string> = {
82 primary: "bg-fg text-bg hover:bg-white",
83 lavender: "bg-accent text-bg hover:bg-accent-hover",
84 quiet: "border border-line text-fg/80 hover:border-line-strong hover:bg-surface hover:text-fg",
85 danger: "border border-danger/40 text-danger hover:border-danger/70 hover:bg-danger/10",
86};
87
88export function Button({ variant = "primary", className = "", ...props }: ComponentProps<"button"> & { variant?: Variant }) {
89 return <button {...props} className={`${BUTTON_BASE} ${BUTTON_VARIANTS[variant]} ${className}`} />;
90}
91
92export function ButtonLink({ variant = "primary", className = "", ...props }: LinkProps & { variant?: Variant }) {
93 return <Link {...props} className={`${BUTTON_BASE} ${BUTTON_VARIANTS[variant]} ${className}`} />;
94}
95
96/** A bordered panel with a heading. */
97export function Section({
98 id,
99 title,
100 description,
101 actions,
102 children,
103 className = "",
104}: {
105 id?: string;
106 title: string;
107 description?: ReactNode;
108 actions?: ReactNode;
109 children: ReactNode;
110 className?: string;
111}) {
112 return (
113 <section id={id} className={`scroll-mt-20 rounded-lg border border-line bg-surface ${className}`}>
114 <header className="flex flex-wrap items-start justify-between gap-3 border-b border-line px-4 py-3 sm:px-5">
115 <div>
116 <h2 className="text-[0.9375rem] font-semibold tracking-tight">{title}</h2>
117 {description && <p className="mt-0.5 text-sm text-muted">{description}</p>}
118 </div>
119 {actions}
120 </header>
121 <div className="p-4 sm:p-5">{children}</div>
122 </section>
123 );
124}
125
126export function EmptyState({ title, children }: { title: string; children?: ReactNode }) {
127 return (
128 <div className="rounded-lg border border-dashed border-line px-6 py-10 text-center">
129 <p className="font-medium">{title}</p>
130 {children && <div className="mt-1.5 text-sm text-muted">{children}</div>}
131 </div>
132 );
133}
134
135const NOTICE = {
136 ok: { icon: CheckCircle2, className: "border-success/30 bg-success/8 text-success" },
137 error: { icon: AlertTriangle, className: "border-danger/30 bg-danger/8 text-danger" },
138 warn: { icon: AlertTriangle, className: "border-warn/30 bg-warn/8 text-warn" },
139 info: { icon: Info, className: "border-accent/30 bg-accent/8 text-accent" },
140} as const;
141
142export function Notice({ tone, children }: { tone: keyof typeof NOTICE; children: ReactNode }) {
143 const { icon: Icon, className } = NOTICE[tone];
144 return (
145 <div role={tone === "error" ? "alert" : "status"} className={`flex gap-2.5 rounded-md border px-3.5 py-2.5 text-sm ${className}`}>
146 <Icon size={16} className="mt-0.5 shrink-0" />
147 <div className="min-w-0 text-fg-soft">{children}</div>
148 </div>
149 );
150}
151
152/** A small label; `tone` colours it. */
153export function Badge({ tone = "plain", children }: { tone?: "plain" | "lavender" | "mint" | "warn" | "danger" | "info"; children: ReactNode }) {
154 const tones = {
155 plain: "border-line text-muted",
156 lavender: "border-accent/35 bg-accent/10 text-accent",
157 mint: "border-success/30 bg-success/8 text-success",
158 warn: "border-warn/35 bg-warn/10 text-warn",
159 danger: "border-danger/35 bg-danger/10 text-danger",
160 info: "border-info/35 bg-info/10 text-info",
161 };
162 return (
163 <span className={`inline-flex items-center rounded-full border px-2 py-px text-xs font-medium whitespace-nowrap ${tones[tone]}`}>
164 {children}
165 </span>
166 );
167}
168
169export function TermsBadge({ terms }: { terms: Terms }) {
170 if (fullDiscount(terms)) return <Badge tone="mint">100% discount</Badge>;
171 if (terms.kind === "standard") return <Badge>Standard</Badge>;
172 return <Badge tone="info">{termsLabel(terms)}</Badge>;
173}
174
175const TRUST: Record<Trust, { label: string; tone: "plain" | "lavender" | "mint" | "info"; about: string }> = {
176 new: { label: "New", tone: "plain", about: "New: has not paid g1t yet, so the limit is small." },
177 paid: { label: "Paid", tone: "info", about: "Paid: has paid g1t, and the limit grows with what it has paid." },
178 established: {
179 label: "Established",
180 tone: "mint",
181 about: "Established: the limit follows their monthly spend, up to $10,000.",
182 },
183 reviewed: { label: "Reviewed", tone: "mint", about: "Reviewed: g1t set the limit by hand, after talking to them." },
184 // A 100% discount: nothing is charged, so no limit on unpaid usage.
185 internal: { label: "100% discount", tone: "lavender", about: "A 100% discount: nothing is charged, so there is no limit on unpaid usage." },
186};
187
188export function TrustBadge({ trust }: { trust: Trust }) {
189 const { label, tone, about } = TRUST[trust] ?? { label: trust, tone: "plain", about: "" };
190 return (
191 <span title={about || undefined}>
192 <Badge tone={tone}>{label}</Badge>
193 </span>
194 );
195}
196
197/** What a trust level means for the limit, in a sentence. */
198export function trustAbout(trust: Trust): string {
199 return TRUST[trust]?.about ?? "";
200}
201
202/** A page's title, a line about it, and anything to its right. */
203export function PageHeader({ title, description, actions }: { title: ReactNode; description?: ReactNode; actions?: ReactNode }) {
204 return (
205 <div className="flex flex-wrap items-start justify-between gap-4">
206 <div className="min-w-0">
207 <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
208 {description && <p className="mt-1 text-sm text-muted">{description}</p>}
209 </div>
210 {actions}
211 </div>
212 );
213}
214
215const STATE = {
216 ok: { label: "OK", fill: "var(--g1t-success)", text: "text-success" },
217 warning: { label: "Warning", fill: "var(--g1t-warn)", text: "text-warn" },
218 stopped: { label: "Stopped", fill: "var(--g1t-danger)", text: "text-danger" },
219} as const;
220
221export function StateBadge({ state }: { state: Limit["state"] }) {
222 const tone = state === "stopped" ? "danger" : state === "warning" ? "warn" : "mint";
223 return <Badge tone={tone}>{STATE[state].label}</Badge>;
224}
225
226/**
227 * Usage this month that is not paid for yet, against the limit, as a bar
228 * coloured by where it stands. With no limit (comped) it shows the figure.
229 */
230export function ExposureBar({ limit, wide = false }: { limit: Limit; wide?: boolean }) {
231 const { exposureMicros, ceilingMicros, state } = limit;
232 const share = ceilingMicros && ceilingMicros > 0 ? Math.min(1, Math.max(0, exposureMicros / ceilingMicros)) : 0;
233 const percent = ceilingMicros && ceilingMicros > 0 ? Math.round((exposureMicros / ceilingMicros) * 100) : null;
234 return (
235 <div className={wide ? "w-full" : "w-40 max-w-full"}>
236 <div className="flex items-baseline justify-between gap-2 text-xs">
237 <span className="tabular font-medium text-fg-soft">
238 {usd(exposureMicros)}
239 <span className="font-normal text-faint"> / {ceilingMicros == null ? "no limit" : usd(ceilingMicros)}</span>
240 </span>
241 {percent != null && <span className={`tabular ${STATE[state].text}`}>{percent}%</span>}
242 </div>
243 <svg viewBox="0 0 100 4" preserveAspectRatio="none" className="mt-1.5 block h-1.5 w-full" role="img" aria-label={`${STATE[state].label}: ${percent ?? 0}% of the limit`}>
244 <rect x="0" y="0" width="100" height="4" rx="2" fill="var(--g1t-raised)" />
245 {ceilingMicros != null && share > 0 && (
246 <rect x="0" y="0" width={Math.max(2, share * 100)} height="4" rx="2" fill={STATE[state].fill} />
247 )}
248 </svg>
249 </div>
250 );
251}
252
253/** A label and a figure, for the strip of totals over a page. */
254export function Stat({ label, value, hint, tone }: { label: string; value: ReactNode; hint?: ReactNode; tone?: "danger" | "warn" | "mint" }) {
255 const color = tone === "danger" ? "text-danger" : tone === "warn" ? "text-warn" : tone === "mint" ? "text-success" : "text-fg";
256 return (
257 <div className="rounded-lg border border-line bg-surface px-4 py-3">
258 <p className="text-xs text-muted">{label}</p>
259 <p className={`tabular mt-1 text-lg font-semibold tracking-tight ${color}`}>{value}</p>
260 {hint && <p className="mt-0.5 text-xs text-faint">{hint}</p>}
261 </div>
262 );
263}
264
265/** The zone the pages say times in, from the root loader (lib/time.ts); UTC without one. */
266export function useZone(): string {
267 return useRouteLoaderData<{ zone?: string }>("root")?.zone ?? "UTC";
268}
269
270/**
271 * A timestamp in the staff member's zone, with the zone's abbreviation;
272 * the UTC instant in `datetime` and on hover, for comparing notes.
273 */
274export function When({ at, time = false }: { at: string | null | undefined; time?: boolean }) {
275 const zone = useZone();
276 if (!at) return <span className="text-faint">—</span>;
277 const date = new Date(at);
278 if (Number.isNaN(date.getTime())) return <span>{at}</span>;
279 const shown = when(date, zone, time);
280 return (
281 <time dateTime={date.toISOString()} title={shown.utc}>
282 {shown.text}
283 {shown.zone && <span className="text-faint"> {shown.zone}</span>}
284 </time>
285 );
286}
287
288/** A letter avatar, drawn as SVG so its colour needs no inline style. */
289export function Avatar({ name, size = 20, square = true }: { name: string; size?: number; square?: boolean }) {
290 const hues = [82, 200, 262, 28, 330, 160];
291 let hash = 0;
292 for (const char of name) hash = (hash * 31 + char.charCodeAt(0)) | 0;
293 const hue = hues[Math.abs(hash) % hues.length];
294 return (
295 <svg width={size} height={size} viewBox="0 0 20 20" aria-hidden="true" className="shrink-0">
296 <rect width="20" height="20" rx={square ? 5 : 10} fill={`oklch(0.4 0.09 ${hue})`} />
297 <text x="10" y="14.2" textAnchor="middle" fontSize="11" fontWeight="600" fontFamily="var(--g1t-font-mono)" fill={`oklch(0.93 0.08 ${hue})`}>
298 {(name[0] ?? "?").toUpperCase()}
299 </text>
300 </svg>
301 );
302}