Redesign Learn, and give it five real videos in Karti's voice
CI / verify (push) Successful in 3m32s
CI / publish (push) Has been skipped

THE PAGE. The anonymous route rendered outside Shell, so it sat flush against
the viewport edge and read as a form rather than a product — which is the first
thing anyone at Prime Intellect sees when the link is shared. It now brings its
own chrome and leads with a hero; the platform track is a numbered course, the
concept tracks are a poster grid, and admin add/archive moved behind one Manage
toggle so they stop competing with the content. Verified in Chrome at 1440 and
393, light and dark: horizontal overflow is 0 in all three access states.

THE VIDEOS. Five ~30s walkthroughs, narrated in Karti's cloned voice through
Chatterbox and cut against real screen capture of the seeded demo book. The
audio is rendered FIRST and its measured duration drives the capture, because a
shot list that runs short leaves the narrator talking over a frozen frame and
one that runs long gets cut mid-sentence. Levels are loudness-normalised so
clips do not jump between videos.

Cap cannot take a programmatic upload — video.karti.ai needs an interactive
login — so PIG serves these itself. A native <video> on this origin needs no
iframe and therefore no CSP frame-src at all; Karti's own Cap recordings still
render through the existing iframe path, which is why the resolver is now a
discriminated union.

THREE THINGS THE VERIFIERS CAUGHT, all of which shipped green:

  - createMediaRoutes was never mounted. Every layer landed — migration, seed,
    both feeds, the bind mount, the docs — except the one that serves the bytes,
    so /media/learn/* fell through to the SPA fallback and answered HTTP 200
    text/html. The player showed a black box with working controls and no error.
    The tests certified the route factory in isolation, which proves the handler
    and says nothing about whether it is wired in. There is now an assertion
    against the ASSEMBLED app, and it fails loudly on content-type — the failure
    mode is a 200, not a 404.
  - A symlink in the media directory escaped the root. resolve() is lexical and
    stat() follows links, so the containment check this file's own header
    promised did not hold. realpath before the check closes it.
  - Vite proxied only /api, so self-hosted playback broke for anyone running the
    app the documented way — in the same invisible 200-text/html manner.

Also: a duplicate media slug used to throw from the middle of seedDemo() and
take out every later section; it now reports and skips that one entry. And the
player has an onError state, because content-addressed filenames mean a
re-render deliberately leaves the old row pointing at a file that is gone.

The three DEMO platform rows are dropped — five real recordings supersede them,
and placeholders sitting under real ones made the page read as half-finished to
the audience it is meant to convince. The supply and demand concept rows stay:
there are no real recordings for those tracks yet, and an empty track hides the
shape of the page.

Tests 275, typecheck clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-13 17:30:08 -07:00
parent a21ecf9e53
commit 45b70b17f0
24 changed files with 2728 additions and 654 deletions
@@ -0,0 +1,214 @@
/**
* The admin add form.
*
* Track and visibility are plain selects rather than a clever control because
* the pairing rule between them is enforced by the API and the database, not
* here — so the UI's job is to be legible, and disabling the option would only
* hide a refusal the server is going to make anyway with a better message.
*/
import { useState, type ReactNode } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import {
LEARN_TRACKS,
LEARN_TRACK_LABELS,
LEARN_VISIBILITIES,
type LearnTrack,
type LearnVisibility,
} from '@pig/core';
import { api } from '@/lib/api';
import { Button, Input } from '@/components/ui';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import type { LearnResourceView } from './model';
export function AddResourceDialog({
open,
onOpenChange,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const queryClient = useQueryClient();
const [track, setTrack] = useState<LearnTrack>('platform');
const [visibility, setVisibility] = useState<LearnVisibility>('code');
const [title, setTitle] = useState('');
const [summary, setSummary] = useState('');
const [url, setUrl] = useState('');
const [minutes, setMinutes] = useState('');
const create = useMutation({
mutationFn: () => {
const parsedMinutes = Number(minutes);
return api<LearnResourceView>('/api/learn/resources', {
method: 'POST',
body: JSON.stringify({
track,
visibility,
title: title.trim(),
summary: summary.trim() || undefined,
url: url.trim(),
durationSeconds:
minutes.trim() && Number.isFinite(parsedMinutes) && parsedMinutes > 0
? Math.round(parsedMinutes * 60)
: undefined,
}),
});
},
onSuccess: async (created) => {
await queryClient.invalidateQueries({ queryKey: ['learn'] });
onOpenChange(false);
setTitle('');
setSummary('');
setUrl('');
setMinutes('');
toast.success(`Added “${created.title}”.`);
},
onError: (error: unknown) => {
toast.error(error instanceof Error ? error.message : 'Could not add that video.');
},
});
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90dvh] w-[calc(100vw-1.5rem)] max-w-lg overflow-y-auto">
<DialogHeader>
<DialogTitle>Add a video</DialogTitle>
<DialogDescription>
Paste a share link from video.karti.ai. Other hosts are rejected until they are added
to the allowlist.
</DialogDescription>
</DialogHeader>
<form
className="flex min-w-0 flex-col gap-3"
onSubmit={(event) => {
event.preventDefault();
create.mutate();
}}
>
<Field label="Share link" htmlFor="learn-url">
<Input
id="learn-url"
value={url}
onChange={(event) => setUrl(event.target.value)}
placeholder="https://video.karti.ai/s/…"
autoComplete="off"
spellCheck={false}
/>
</Field>
<Field label="Title" htmlFor="learn-title">
<Input
id="learn-title"
value={title}
onChange={(event) => setTitle(event.target.value)}
/>
</Field>
<Field label="Summary" htmlFor="learn-summary">
<Input
id="learn-summary"
value={summary}
onChange={(event) => setSummary(event.target.value)}
placeholder="What someone learns from it"
/>
</Field>
<div className="grid min-w-0 gap-3 sm:grid-cols-2">
<Field label="Track" htmlFor="learn-track">
<NativeSelect
id="learn-track"
value={track}
onChange={(value) => setTrack(value as LearnTrack)}
options={LEARN_TRACKS.map((value) => ({
value,
label: LEARN_TRACK_LABELS[value],
}))}
/>
</Field>
<Field label="Visibility" htmlFor="learn-visibility">
<NativeSelect
id="learn-visibility"
value={visibility}
onChange={(value) => setVisibility(value as LearnVisibility)}
options={LEARN_VISIBILITIES.map((value) => ({
value,
label: value === 'code' ? 'Anyone with the code' : 'Members only',
}))}
/>
</Field>
</div>
<Field label="Length in minutes" htmlFor="learn-minutes">
<Input
id="learn-minutes"
value={minutes}
onChange={(event) => setMinutes(event.target.value)}
inputMode="decimal"
placeholder="Optional"
/>
</Field>
<div className="flex min-w-0 flex-col gap-2 pt-1 sm:flex-row sm:justify-end">
<Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button
type="submit"
variant="primary"
disabled={create.isPending || !url.trim() || !title.trim()}
>
{create.isPending ? 'Adding…' : 'Add video'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
function Field({
label,
htmlFor,
children,
}: {
label: string;
htmlFor: string;
children: ReactNode;
}) {
return (
<div className="flex min-w-0 flex-col gap-1.5">
<label htmlFor={htmlFor} className="text-sm font-medium">
{label}
</label>
{children}
</div>
);
}
function NativeSelect({
id,
value,
onChange,
options,
}: {
id: string;
value: string;
onChange: (value: string) => void;
options: { value: string; label: string }[];
}) {
return (
<select
id={id}
value={value}
onChange={(event) => onChange(event.target.value)}
className="h-11 w-full min-w-0 rounded-lg border border-border bg-surface px-3 text-base text-fg focus-visible:border-accent"
>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
);
}
@@ -0,0 +1,69 @@
/**
* Archive, as an overlay rather than a footer.
*
* It used to sit in the card's footer, which is where a reader's eye lands
* after the title — so the most destructive control on the page was competing
* with the content for attention, for the majority of viewers who cannot even
* use it. It is now a sibling of the play button (never a descendant: a button
* inside a button is invalid and Firefox drops the inner one) and only appears
* once an admin has asked to manage.
*/
import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { cn } from '@/components/ui';
export function ArchiveControl({
id,
title,
className,
}: {
id: string;
title: string;
className?: string;
}) {
const queryClient = useQueryClient();
const [confirming, setConfirming] = useState(false);
const archive = useMutation({
mutationFn: () => api<unknown>(`/api/learn/resources/${id}`, { method: 'DELETE' }),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['learn'] });
toast.success(`Archived “${title}”.`);
},
onError: (error: unknown) => {
setConfirming(false);
toast.error(error instanceof Error ? error.message : 'Could not archive that video.');
},
});
return (
<button
type="button"
onClick={() => {
// Two taps, no dialog. A modal for an archive that a colleague can
// restore is ceremony; one silent tap is a video gone from a shared
// library because a thumb brushed the corner of a card.
if (!confirming) {
setConfirming(true);
return;
}
archive.mutate();
}}
onBlur={() => setConfirming(false)}
disabled={archive.isPending}
aria-label={confirming ? `Confirm archiving ${title}` : `Archive ${title}`}
className={cn(
'tap inline-flex items-center gap-1.5 rounded-lg border border-border px-2.5 text-xs font-medium',
'bg-surface/90 backdrop-blur-sm transition-colors disabled:opacity-50',
confirming ? 'text-danger hover:bg-danger/10' : 'text-muted hover:bg-surface-2 hover:text-fg',
className,
)}
>
<Trash2 className="size-4 shrink-0" aria-hidden />
{confirming ? 'Confirm' : 'Archive'}
</button>
);
}
@@ -0,0 +1,153 @@
/**
* The first thing a stranger sees.
*
* This route is what gets pasted into a message to someone at Prime Intellect,
* and until they type the code it is the entire product as far as they are
* concerned. It was a bare label, an input and a button — a form, with no
* indication of what it opened. So the gate is now the hero: it says whose
* page this is, what is behind the code, and how long the access lasts, and
* the input is the largest thing on the screen.
*
* The right-hand panel is ornament and is marked as such. It is a locked
* poster, not a fake video: inventing a plausible-looking thumbnail with a
* made-up title would be a promise about content that may not exist.
*/
import { useState, type FormEvent } from 'react';
import { useMutation } from '@tanstack/react-query';
import { ArrowRight, Lock, PlayCircle } from 'lucide-react';
import { toast } from 'sonner';
import { ApiError } from '@/lib/api';
import { Button, Input } from '@/components/ui';
/** Uneven on purpose — three identical bars read as a loading state. */
const BAR_WIDTHS = [{ width: '78%' }, { width: '58%' }, { width: '68%' }];
export function LearnAccessHero({ onUnlocked }: { onUnlocked: (token: string) => void }) {
const [code, setCode] = useState('');
const unlock = useMutation({
mutationFn: async (value: string) => {
const response = await fetch('/api/learn/access', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ code: value }),
});
const body = (await response.json().catch(() => ({}))) as {
token?: string;
error?: string;
code?: string;
};
if (!response.ok || !body.token) {
throw new ApiError(body.error ?? 'That code is not valid.', response.status, body.code);
}
return body.token;
},
onSuccess: (minted) => {
onUnlocked(minted);
toast.success('Unlocked. Here are the product walkthroughs.');
},
onError: (error: unknown) => {
toast.error(error instanceof Error ? error.message : 'That code is not valid.');
},
});
function submit(event: FormEvent) {
event.preventDefault();
const trimmed = code.trim();
if (!trimmed) return;
unlock.mutate(trimmed);
}
return (
<section className="relative min-w-0 overflow-hidden rounded-3xl border border-border bg-surface">
<div
className="absolute inset-0 bg-[radial-gradient(circle_at_82%_-10%,hsl(var(--accent-subtle)),transparent_58%),radial-gradient(circle_at_-5%_110%,hsl(var(--surface-2)),transparent_55%)]"
aria-hidden
/>
<div className="relative grid min-w-0 gap-10 p-6 sm:p-10 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)] lg:items-center lg:gap-12 lg:p-14">
<div className="flex min-w-0 flex-col gap-5">
<span className="inline-flex w-fit min-w-0 items-center gap-2 rounded-full border border-border bg-surface px-3 py-1 text-xs font-medium text-muted">
<PlayCircle className="size-3.5 shrink-0 text-accent-fg" aria-hidden />
<span className="min-w-0">Shared preview · Prime Intellect Growth</span>
</span>
<h1 className="min-w-0 text-3xl font-semibold leading-[1.1] tracking-tight sm:text-4xl lg:text-[2.75rem]">
See how PIG runs both sides of the book.
</h1>
<p className="min-w-0 max-w-xl text-base leading-7 text-muted">
Short product walkthroughs: what the platform does with contracted capacity, how it
joins what we bought to what we sold, and what the numbers on the margin report
actually mean. Enter the code you were given to watch them.
</p>
<form onSubmit={submit} className="flex min-w-0 flex-col gap-2 pt-1 sm:flex-row">
<div className="min-w-0 flex-1">
<label htmlFor="learn-code" className="sr-only">
Access code
</label>
<Input
id="learn-code"
value={code}
onChange={(event) => setCode(event.target.value)}
autoComplete="off"
autoCapitalize="none"
spellCheck={false}
placeholder="Enter your access code"
className="h-12 w-full min-w-0 bg-surface text-base"
/>
</div>
<Button
type="submit"
variant="primary"
size="lg"
className="shrink-0"
disabled={unlock.isPending || !code.trim()}
>
{unlock.isPending ? 'Checking…' : 'Unlock'}
{unlock.isPending ? null : <ArrowRight className="size-4" aria-hidden />}
</Button>
</form>
<p className="min-w-0 text-sm text-muted">
Whoever shared this page has the code. Access lasts twelve hours and covers the
platform walkthroughs only.{' '}
<a href="/" className="font-medium text-accent-fg underline underline-offset-4">
Have a PIG account? Sign in
</a>
.
</p>
</div>
{/*
Decorative, and hidden from assistive technology: it carries no
information the copy has not already given. Redacted bars rather than
invented titles — a plausible-looking fake thumbnail is a promise
about content that may not exist.
*/}
<div className="hidden min-w-0 lg:block" aria-hidden>
<div className="relative flex min-w-0 flex-col gap-3 rounded-2xl border border-border bg-surface/70 p-4 shadow-sm backdrop-blur-sm">
{[0, 1, 2].map((row) => (
<div key={row} className="flex min-w-0 items-center gap-3">
<div className="relative aspect-video w-24 shrink-0 overflow-hidden rounded-lg border border-border bg-gradient-to-br from-accent-subtle via-surface-2 to-surface">
<span className="absolute inset-0 flex items-center justify-center text-muted">
<Lock className="size-4" strokeWidth={1.75} />
</span>
</div>
<div className="flex min-w-0 flex-1 flex-col gap-2">
<span className="block h-2.5 rounded-full bg-fg/[0.09]" style={BAR_WIDTHS[row]} />
<span className="block h-2 w-full rounded-full bg-fg/[0.05]" />
<span className="block h-2 w-2/3 rounded-full bg-fg/[0.05]" />
</div>
</div>
))}
<p className="border-t border-border pt-3 text-center text-sm font-medium text-muted">
Product walkthroughs, waiting on a code.
</p>
</div>
</div>
</div>
</section>
);
}
@@ -0,0 +1,133 @@
/**
* The player.
*
* Two kinds of source, one frame. A Cap resource is a third-party document and
* has to be an iframe with a sandbox; a PIG-hosted resource is bytes from this
* origin and has to be a native `<video>`, because framing our own origin
* would hand a media file a document context it has no business having. The
* branch is on the resolved `kind`, never on the url — see `model.ts`.
*
* Nothing here builds a source. Every src arrives from the API already
* resolved through the host allowlist in `@pig/core`; a resource the server
* could not resolve is not in the response at all. Concatenating a URL in this
* file would reintroduce exactly the hole the allowlist closes.
*
* The media box is a fixed `aspect-video` with an absolutely positioned child,
* so the dialog is the same height before and after the embed loads. Sizing it
* from the loaded content instead is what makes a player jump under the
* pointer a beat after it opens.
*/
import { useEffect, useState } from 'react';
import { ExternalLink } from 'lucide-react';
import { formatLearnDuration, LEARN_TRACK_LABELS } from '@pig/core';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui';
import { learnPlayback, watchHost, type LearnResourceView } from './model';
export function LearnPlayerDialog({
resource,
onClose,
}: {
resource: LearnResourceView | null;
onClose: () => void;
}) {
// Reset per resource, or a failure on one video would persist as the error
// state of the next one opened.
const [failed, setFailed] = useState(false);
useEffect(() => setFailed(false), [resource?.id]);
const playback = resource ? learnPlayback(resource) : null;
const duration = formatLearnDuration(resource?.durationSeconds);
const host = watchHost(resource?.watchUrl);
return (
<Dialog open={resource !== null} onOpenChange={(next) => !next && onClose()}>
{/* Esc and the overlay both close it — Radix's behaviour, kept. */}
<DialogContent className="max-h-[92dvh] w-[calc(100vw-1.5rem)] max-w-4xl gap-0 overflow-y-auto p-0">
{resource ? (
<>
<DialogHeader className="min-w-0 gap-1 p-4 pr-14 text-left sm:p-5 sm:pr-16">
<DialogTitle className="min-w-0 break-words text-base leading-snug sm:text-lg">
{resource.title}
</DialogTitle>
<DialogDescription className="min-w-0 break-words">
{resource.summary ?? `${LEARN_TRACK_LABELS[resource.track]} track.`}
</DialogDescription>
</DialogHeader>
<div className="relative aspect-video w-full min-w-0 border-y border-border bg-surface-2">
{playback?.kind === 'video' ? (
<video
key={resource.id}
src={playback.src}
poster={playback.poster}
controls
playsInline
preload="metadata"
className="absolute inset-0 size-full"
/*
* A resolved source that will not load is an ORDINARY state
* here, not an edge case: media filenames are content-
* addressed, so re-rendering a video leaves the old row
* pointing at a file that no longer exists, and the seed
* deliberately reports that rather than resolving it. Without
* this the viewer gets a black rectangle with a scrubber that
* does nothing and no explanation.
*/
onError={() => setFailed(true)}
/>
) : null}
{playback?.kind === 'iframe' ? (
/*
* The sandbox keeps the frame from navigating the top window or
* opening downloads; `allow-same-origin` is safe and necessary
* here because the frame is cross-origin, so "same origin"
* means the video host's own, not PIG's.
*/
<iframe
key={resource.id}
src={playback.src}
title={resource.title}
className="absolute inset-0 size-full border-0"
allow="autoplay; fullscreen; picture-in-picture; clipboard-write"
allowFullScreen
referrerPolicy="strict-origin-when-cross-origin"
sandbox="allow-scripts allow-same-origin allow-presentation"
/>
) : null}
{!playback || failed ? (
<p className="absolute inset-0 flex items-center justify-center bg-surface-2 p-6 text-center text-sm text-muted">
{failed
? 'This video could not be loaded. The recording may have been replaced — ask an admin to refresh it.'
: 'This video has no playable source.'}
</p>
) : null}
</div>
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 p-4 sm:p-5">
<Badge tone="neutral">{LEARN_TRACK_LABELS[resource.track]}</Badge>
{duration ? <Badge tone="neutral" className="nums">{duration}</Badge> : null}
{playback?.kind === 'iframe' && resource.watchUrl ? (
<a
href={resource.watchUrl}
target="_blank"
rel="noreferrer noopener"
className="tap ml-auto inline-flex min-w-0 items-center gap-1.5 text-sm font-medium text-accent-fg underline-offset-4 hover:underline"
>
<ExternalLink className="size-4 shrink-0" aria-hidden />
<span className="min-w-0 break-words">Open on {host ?? 'the video host'}</span>
</a>
) : null}
</div>
</>
) : null}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,118 @@
/**
* The 16:9 area a video card leads with.
*
* There are no thumbnail images — nothing renders a frame of a Cap embed
* without loading the embed, and loading nine of them to decorate a grid is
* how a page becomes unusable on a phone. So the poster is generated: a
* gradient picked deterministically from the resource id, a watermark glyph
* for the track, and the two things a reader actually needs on it — an
* unmistakable play affordance and the duration.
*
* Deterministic, not random, because a card that re-tints on every render
* reads as a bug and destroys the sense that these are distinct objects.
*/
import { BookOpen, LineChart, MonitorPlay, Play } from 'lucide-react';
import type { LearnTrack } from '@pig/core';
import { cn } from '@/components/ui';
/**
* Every tint is a pair of semantic tokens, so the whole set re-tints with the
* user's accent and inverts correctly in dark mode without a second palette.
*/
const TINTS = [
'from-accent-subtle via-surface-2 to-surface',
'from-surface-2 via-accent-subtle to-surface',
'from-surface via-surface-2 to-accent-subtle',
'from-accent-subtle via-surface to-surface-2',
] as const;
const TRACK_GLYPHS: Record<LearnTrack, typeof Play> = {
supply: LineChart,
demand: BookOpen,
platform: MonitorPlay,
};
function tintFor(seed: string): string {
let hash = 0;
for (let index = 0; index < seed.length; index += 1) {
hash = (hash * 31 + seed.charCodeAt(index)) % 100_000;
}
return TINTS[hash % TINTS.length] as string;
}
export function LearnPoster({
seed,
track,
duration,
size = 'card',
className,
}: {
seed: string;
track: LearnTrack;
duration: string | null;
/** `row` drops the ornament and shrinks the play button for a list thumbnail. */
size?: 'card' | 'row';
className?: string;
}) {
const Glyph = TRACK_GLYPHS[track];
const compact = size === 'row';
return (
<div
className={cn(
'relative aspect-video w-full min-w-0 overflow-hidden bg-gradient-to-br',
tintFor(seed),
className,
)}
>
{/*
Texture, so a generated poster reads as an image rather than as a card
that failed to load. All three layers are the palette's own tokens at
low alpha, which is what keeps them legible in both themes without a
second set of values for dark.
*/}
<div
className="absolute inset-0 bg-[repeating-linear-gradient(135deg,hsl(var(--fg)/0.04)_0px,hsl(var(--fg)/0.04)_1px,transparent_1px,transparent_10px)]"
aria-hidden
/>
<div
className="absolute inset-0 bg-[radial-gradient(circle_at_28%_18%,hsl(var(--surface)/0.8),transparent_62%)]"
aria-hidden
/>
{/* The track's glyph, at card size only — at thumbnail size it collides
with the play button and reads as a second, broken control. */}
{compact ? null : (
<Glyph
className="absolute -bottom-6 -right-4 size-32 text-fg/[0.06]"
strokeWidth={1.25}
aria-hidden
/>
)}
<div className="absolute inset-0 flex items-center justify-center">
<span
className={cn(
'inline-flex items-center justify-center rounded-full border border-border',
'bg-surface/85 text-fg shadow-sm backdrop-blur-sm',
'transition-transform duration-200 group-hover:scale-105 group-focus-visible:scale-105',
compact ? 'size-9' : 'size-14',
)}
aria-hidden
>
<Play className={compact ? 'size-4' : 'size-6'} fill="currentColor" strokeWidth={0} />
</span>
</div>
{duration ? (
<span
className={cn(
'nums absolute rounded-md bg-fg/85 px-1.5 py-0.5 text-xs font-medium text-bg',
compact ? 'bottom-1 right-1' : 'bottom-2 right-2',
)}
>
{duration}
</span>
) : null}
</div>
);
}
@@ -0,0 +1,94 @@
/**
* What is behind the door, shown to someone standing outside it.
*
* The locked concept panel is deliberate, not an oversight: a code-holder is
* shown that supply and demand material exists and is behind sign-in, because
* the point of this page for an outsider is partly to advertise the rest of
* it. That argument only pays off if the panel *sells* — a grey "members only"
* box tells a visitor they are unwelcome and nothing else — so each track is
* named, described and given its own tile.
*
* The server never sends a single row of the locked tracks. This panel is a
* signpost, not a redaction.
*/
import { KeyRound, LineChart, Lock, MonitorPlay, Users } from 'lucide-react';
import { LEARN_TRACK_DESCRIPTIONS, LEARN_TRACK_LABELS, type LearnTrack } from '@pig/core';
import { Button, Card } from '@/components/ui';
const TRACK_ICONS: Record<LearnTrack, typeof Lock> = {
supply: LineChart,
demand: Users,
platform: MonitorPlay,
};
export interface LearnTrackTeaser {
track: LearnTrack;
/** `code` reads as an invitation; `members` reads as a locked door. */
access: 'code' | 'members';
}
export function LearnTrackPanel({
heading,
description,
teasers,
showSignIn = true,
}: {
heading: string;
description: string;
teasers: readonly LearnTrackTeaser[];
showSignIn?: boolean;
}) {
return (
<Card className="flex min-w-0 flex-col gap-5 p-5 sm:p-6">
<div className="flex min-w-0 flex-col gap-1">
<h2 className="text-lg font-semibold tracking-tight">{heading}</h2>
<p className="min-w-0 max-w-2xl text-sm leading-6 text-muted">{description}</p>
</div>
<ul className="grid min-w-0 list-none gap-3 sm:grid-cols-2 lg:grid-cols-3">
{teasers.map(({ track, access }) => {
const Icon = TRACK_ICONS[track];
return (
<li
key={track}
className="flex min-w-0 flex-col gap-2 rounded-xl border border-border bg-surface-2/60 p-4"
>
<span className="inline-flex size-9 shrink-0 items-center justify-center rounded-lg bg-accent-subtle text-accent-fg">
<Icon className="size-4" aria-hidden />
</span>
<p className="min-w-0 font-semibold leading-snug">{LEARN_TRACK_LABELS[track]}</p>
<p className="min-w-0 break-words text-sm leading-6 text-muted">
{LEARN_TRACK_DESCRIPTIONS[track]}
</p>
<p className="mt-auto inline-flex min-w-0 items-center gap-1.5 pt-2 text-xs font-medium text-muted">
{access === 'code' ? (
<>
<KeyRound className="size-3.5 shrink-0 text-accent-fg" aria-hidden />
<span className="min-w-0 text-accent-fg">Opens with your code</span>
</>
) : (
<>
<Lock className="size-3.5 shrink-0" aria-hidden />
<span className="min-w-0">Members only</span>
</>
)}
</p>
</li>
);
})}
</ul>
{showSignIn ? (
<div className="flex min-w-0 flex-col gap-2 border-t border-border pt-4 sm:flex-row sm:items-center sm:justify-between">
<p className="min-w-0 text-sm text-muted">
Concept training is for the go-to-market team. Sign in with your PIG account to watch
it.
</p>
<Button variant="primary" className="shrink-0" asChild>
<a href="/">Sign in</a>
</Button>
</div>
) : null}
</Card>
);
}
@@ -0,0 +1,68 @@
/**
* A concept video, as a browsable card.
*
* Concepts are market education — someone scans the shelf and picks what they
* need — so this is a poster-led grid tile. The platform track is a course you
* work through in order and is rendered as a list instead; see
* `LearnWalkthroughList`.
*/
import { formatLearnDuration } from '@pig/core';
import { Badge, Card } from '@/components/ui';
import { ArchiveControl } from './ArchiveControl';
import { LearnPoster } from './LearnPoster';
import type { LearnResourceView } from './model';
export function LearnVideoCard({
resource,
managing,
onPlay,
}: {
resource: LearnResourceView;
managing: boolean;
onPlay: (resource: LearnResourceView) => void;
}) {
return (
<Card className="group relative flex min-w-0 flex-col overflow-hidden transition-shadow hover:shadow-md">
<button
type="button"
onClick={() => onPlay(resource)}
// The ring is inset because the card clips its overflow, and an offset
// ring on a clipped child is a focus indicator nobody can see.
className="flex min-w-0 flex-1 flex-col text-left focus-visible:ring-inset focus-visible:ring-offset-0"
>
<LearnPoster
seed={resource.id}
track={resource.track}
duration={formatLearnDuration(resource.durationSeconds)}
/>
<div className="flex min-w-0 flex-1 flex-col gap-1.5 p-4">
{/* break-words, not truncate: a title is the only way to tell two
walkthroughs apart, and an unbroken word at 393px is what drags
the whole page sideways. */}
<h3 className="min-w-0 break-words font-semibold leading-snug">{resource.title}</h3>
{resource.summary ? (
<p className="line-clamp-2 min-w-0 break-words text-sm leading-6 text-muted">
{resource.summary}
</p>
) : null}
</div>
</button>
{managing ? (
<div className="pointer-events-none absolute inset-x-0 top-0 flex min-w-0 items-start justify-between gap-2 p-2">
<Badge
tone={resource.visibility === 'code' ? 'accent' : 'neutral'}
className="pointer-events-auto bg-surface/90 backdrop-blur-sm"
>
{resource.visibility === 'code' ? 'Shared by code' : 'Members only'}
</Badge>
<ArchiveControl
id={resource.id}
title={resource.title}
className="pointer-events-auto"
/>
</div>
) : null}
</Card>
);
}
@@ -0,0 +1,84 @@
/**
* The platform track, as an ordered course.
*
* Product how-to has a running order — `sortOrder` is the curriculum, and
* "your first hour in PIG" is not interchangeable with the margin report. A
* grid of equal tiles says "pick one"; a numbered list says "start here", so
* the two tracks are rendered as different objects rather than one
* undifferentiated grid.
*/
import { ChevronRight } from 'lucide-react';
import { formatLearnDuration } from '@pig/core';
import { Badge, Card } from '@/components/ui';
import { ArchiveControl } from './ArchiveControl';
import { LearnPoster } from './LearnPoster';
import { bySortOrder, type LearnResourceView } from './model';
export function LearnWalkthroughList({
resources,
managing,
onPlay,
}: {
resources: readonly LearnResourceView[];
managing: boolean;
onPlay: (resource: LearnResourceView) => void;
}) {
const ordered = bySortOrder(resources);
return (
/* Width is the caller's business — this list sits in a 1024px page column
for a code-holder and in a capped column inside the shell for a member,
and a cap here would fight one of them. */
<ol className="flex min-w-0 list-none flex-col gap-3">
{ordered.map((resource, index) => (
<li key={resource.id} className="min-w-0">
<Card className="group relative flex min-w-0 flex-col overflow-hidden transition-shadow hover:shadow-md sm:flex-row">
<button
type="button"
onClick={() => onPlay(resource)}
className="flex min-w-0 flex-1 items-center gap-3 p-3 text-left focus-visible:ring-inset focus-visible:ring-offset-0 sm:gap-4 sm:p-4"
>
<div className="w-28 shrink-0 overflow-hidden rounded-lg border border-border sm:w-44">
<LearnPoster
seed={resource.id}
track={resource.track}
duration={formatLearnDuration(resource.durationSeconds)}
size="row"
/>
</div>
<div className="flex min-w-0 flex-1 flex-col gap-1">
<p className="nums text-[0.6875rem] font-semibold uppercase tracking-[0.14em] text-accent-fg">
Step {index + 1}
</p>
<h3 className="min-w-0 break-words font-semibold leading-snug">
{resource.title}
</h3>
{resource.summary ? (
<p className="line-clamp-2 min-w-0 break-words text-sm leading-6 text-muted">
{resource.summary}
</p>
) : null}
</div>
<ChevronRight
className="hidden size-5 shrink-0 text-muted transition-transform group-hover:translate-x-0.5 sm:block"
aria-hidden
/>
</button>
{managing ? (
/* A right-hand rail on a desktop row, a strip underneath on a
phone — squeezed into 393px beside the text it left the title
wrapping one word to a line. */
<div className="flex min-w-0 shrink-0 flex-row items-center justify-between gap-2 border-t border-border p-2 sm:flex-col sm:items-end sm:justify-center sm:border-l sm:border-t-0">
<Badge tone={resource.visibility === 'code' ? 'accent' : 'neutral'}>
{resource.visibility === 'code' ? 'By code' : 'Members'}
</Badge>
<ArchiveControl id={resource.id} title={resource.title} />
</div>
) : null}
</Card>
</li>
))}
</ol>
);
}
+111
View File
@@ -0,0 +1,111 @@
/**
* The shapes the Learn page reads off the wire, and the one decision every
* player has to make: iframe or `<video>`.
*
* The API is mid-migration. It serialises `embedUrl` today, and a self-hosted
* provider is landing that resolves to `LearnEmbed` — a discriminated union
* carrying `kind`. Rather than wait for the shape to settle, this reads
* whichever of the three forms is present, in order of how much the server has
* actually told us: an explicit `embed` object, then a `kind` beside the url,
* then an inference from the url itself. The inference is the only branch that
* guesses, and it guesses in the safe direction — a relative path is bytes
* this origin serves, so it becomes a `<video>` and never an iframe pointed at
* our own origin.
*/
import { LEARN_MEDIA_PATH_PREFIX, type LearnTrack, type LearnVisibility } from '@pig/core';
/**
* Structural rather than an import of `LearnEmbed`, deliberately. This file
* describes *untrusted JSON*, not the server's type: a field the server has
* not sent yet must be optional here or the compiler will assert a guarantee
* the response does not carry.
*/
export interface LearnEmbedPayload {
kind?: string;
src?: string;
poster?: string;
}
export interface LearnResourceView {
id: string;
track: LearnTrack;
title: string;
summary: string | null;
provider: string;
visibility: LearnVisibility;
durationSeconds: number | null;
sortOrder: number;
publishedAt: string;
/** The settled shape. Present once the self-hosted provider lands. */
embed?: LearnEmbedPayload | null;
/** The discriminator on its own, if it arrives beside the url instead. */
embedKind?: string | null;
/** Today's shape: a resolved url with no discriminator. */
embedUrl?: string | null;
watchUrl?: string | null;
}
export interface MemberFeed {
tracks: Record<LearnTrack, LearnResourceView[]>;
canManage: boolean;
}
export interface PublicFeed {
track: LearnTrack;
expiresAt: string;
resources: LearnResourceView[];
lockedTracks: LearnTrack[];
}
export type LearnPlayback =
| { kind: 'iframe'; src: string }
| { kind: 'video'; src: string; poster?: string };
/**
* A source with no host is a source on this origin, and this origin serves
* media files, not embeddable documents. Protocol-relative (`//host/…`) is
* excluded because it is another origin wearing a relative path's clothes.
*/
function isSelfHostedSource(src: string): boolean {
if (src.startsWith(LEARN_MEDIA_PATH_PREFIX)) return true;
return src.startsWith('/') && !src.startsWith('//');
}
export function learnPlayback(resource: LearnResourceView): LearnPlayback | null {
const embed = resource.embed;
if (embed?.src) {
if (embed.kind === 'video') return { kind: 'video', src: embed.src, poster: embed.poster };
if (embed.kind === 'iframe') return { kind: 'iframe', src: embed.src };
}
const src = embed?.src ?? resource.embedUrl;
if (!src) return null;
if (resource.embedKind === 'video') return { kind: 'video', src };
if (resource.embedKind === 'iframe') return { kind: 'iframe', src };
const selfHosted = resource.provider === 'pig' || isSelfHostedSource(src);
return selfHosted ? { kind: 'video', src } : { kind: 'iframe', src };
}
/**
* `sortOrder` is the curriculum's running order and the reason these are a
* course rather than a pile. Sorted here as well as in the API because the
* page renders two different feeds and only one of them is guaranteed to have
* come through the member query's ordering.
*/
export function bySortOrder(resources: readonly LearnResourceView[]): LearnResourceView[] {
return [...resources].sort(
(a, b) => a.sortOrder - b.sortOrder || a.publishedAt.localeCompare(b.publishedAt),
);
}
/** The host of a share link, for a label. Never used to build a src. */
export function watchHost(watchUrl: string | null | undefined): string | null {
if (!watchUrl) return null;
try {
return new URL(watchUrl).hostname;
} catch {
return null;
}
}
File diff suppressed because it is too large Load Diff
+11 -1
View File
@@ -12,7 +12,17 @@ export default defineConfig({
// Proxy in development so the browser sees one origin, matching how
// production serves the API and the app together. Auth sessions are
// per-origin, so a split origin in dev but not prod hides real bugs.
proxy: { '/api': { target: 'http://localhost:8920', changeOrigin: true } },
/*
* `/media` is proxied as well as `/api`, because Learn videos PIG hosts
* itself are served from the API on a non-/api path. Without this entry
* Vite answers the <video> request with index.html and the player shows a
* black box with working controls and no error — the same silent
* 200-text/html failure the API guards against for its own routes.
*/
proxy: {
'/api': { target: 'http://localhost:8920', changeOrigin: true },
'/media': { target: 'http://localhost:8920', changeOrigin: true },
},
},
build: {
outDir: 'dist',