Redesign Learn, and give it five real videos in Karti's voice
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:
@@ -46,6 +46,7 @@ import {
|
||||
type AuthProvider,
|
||||
} from './lib/auth-provider';
|
||||
import { apiError } from './lib/mutation';
|
||||
import { createMediaRoutes } from './lib/media';
|
||||
import { CapacityService } from './services/capacity';
|
||||
import { createSignupRoute } from './routes/signup';
|
||||
import { createRegisterRoute } from './routes/register';
|
||||
@@ -132,6 +133,18 @@ export function createApp(
|
||||
}),
|
||||
);
|
||||
|
||||
/*
|
||||
* Learn videos PIG serves itself. Mounted here — before the authenticator,
|
||||
* and before server.ts's SPA fallback — because a <video> re-requests byte
|
||||
* ranges on every seek and carries no bearer token while doing it.
|
||||
*
|
||||
* The FILES are unauthenticated; the LISTING behind /api/learn is not. See
|
||||
* lib/media.ts for that trade and what it costs. Position IS the access
|
||||
* decision here: the /api/* allowlist below can never match /media/learn/*,
|
||||
* so adding an entry there would be dead code.
|
||||
*/
|
||||
app.route('/', createMediaRoutes());
|
||||
|
||||
// Everything below requires a principal.
|
||||
app.use('/api/*', async (c, next) => {
|
||||
const path = new URL(c.req.url).pathname;
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* Serving the Learn videos PIG hosts itself.
|
||||
*
|
||||
* ## The trade, stated plainly
|
||||
*
|
||||
* **The files are unauthenticated. The listing is not.** `/api/learn` and
|
||||
* `/api/learn/public` decide who learns that a video exists, what it is called
|
||||
* and which track it belongs to; this route hands the bytes to anyone who can
|
||||
* name the file. That is the same shape every video platform has — a gated
|
||||
* manifest in front of segments on a public CDN — and it is the shape a
|
||||
* `<video>` element actually wants, because a media element re-requests ranges
|
||||
* on every seek and does not carry a bearer token while doing it.
|
||||
*
|
||||
* What it costs: **a URL, once shared, is a permanent public link to that
|
||||
* video**. Someone who has been given the share code can copy the `src` out of
|
||||
* the page and post it, and revoking the Learn access code will not close it.
|
||||
* The only remedies are renaming the file (a new hash) or deleting it. We are
|
||||
* taking that deliberately, because these are product demos meant to be
|
||||
* shareable with the code — the material that must never leak is the concept
|
||||
* tracks, and those are gated by the listing, which is where the boundary
|
||||
* genuinely is.
|
||||
*
|
||||
* The mitigation is the filename. Names are **content-addressed** — a hash in
|
||||
* the middle — so a URL is unguessable and enumerating the directory over HTTP
|
||||
* is not possible: there is no index, and a wrong guess is a flat 404. That
|
||||
* makes the exposure "whoever was given the link" rather than "the internet",
|
||||
* which is exactly what an unlisted video is.
|
||||
*
|
||||
* ## Ranges are not optional
|
||||
*
|
||||
* A `<video>` that cannot be range-requested cannot be scrubbed: the browser
|
||||
* asks for `bytes=…` when the user drags the scrubber, and a server that
|
||||
* answers 200 with the whole file makes seeking either impossible or a
|
||||
* re-download. So `Accept-Ranges: bytes` is advertised and a single range is
|
||||
* honoured with a 206. This is also why the route streams from a file
|
||||
* descriptor rather than reading the file into memory: these are hundreds of
|
||||
* megabytes and several viewers may be seeking at once.
|
||||
*
|
||||
* ## Why the path cannot escape the directory
|
||||
*
|
||||
* The filename is validated by the same allowlist that decides whether a row
|
||||
* may exist at all (`isLearnMediaFilename` in `@pig/core`), so the pattern
|
||||
* that admits a video source and the pattern that admits a file read are one
|
||||
* pattern rather than two that drift. It permits no slash and no `..`. The
|
||||
* resolved path is then checked to be inside the root anyway, because a
|
||||
* defence that rests on a single regular expression rests on nobody ever
|
||||
* editing that regular expression.
|
||||
*/
|
||||
import { Hono } from 'hono';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { realpath, stat } from 'node:fs/promises';
|
||||
import { join, resolve, sep } from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { isLearnMediaFilename, learnMediaContentType, LEARN_MEDIA_PATH_PREFIX } from '@pig/core';
|
||||
|
||||
/**
|
||||
* Where the files live.
|
||||
*
|
||||
* Read from the environment here rather than through `loadConfig` because the
|
||||
* media root is an operational detail of one route, and a missing value is not
|
||||
* a reason to refuse to boot — an install with no videos should serve 404s and
|
||||
* work in every other respect.
|
||||
*
|
||||
* The default is relative to the working directory, which is the repository
|
||||
* root in development. The container sets it explicitly to `/app/media`, which
|
||||
* is where docker-compose bind-mounts the host directory read-only.
|
||||
*/
|
||||
export const LEARN_MEDIA_DIR_ENV = 'PIG_MEDIA_DIR';
|
||||
const DEFAULT_MEDIA_DIR = './media';
|
||||
|
||||
export function learnMediaRoot(env: NodeJS.ProcessEnv = process.env): string {
|
||||
const configured = env[LEARN_MEDIA_DIR_ENV]?.trim();
|
||||
return resolve(configured && configured.length > 0 ? configured : DEFAULT_MEDIA_DIR);
|
||||
}
|
||||
|
||||
/** The mount path, exported so `app.ts` and the resolver cannot disagree. */
|
||||
export const LEARN_MEDIA_ROUTE = `${LEARN_MEDIA_PATH_PREFIX}:filename`;
|
||||
|
||||
interface ParsedRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a single byte range against a known size, or say what to do instead.
|
||||
*
|
||||
* `null` means "serve the whole thing with 200" — the correct answer for no
|
||||
* header, a syntactically odd one, or a multi-range request, all of which a
|
||||
* server is permitted to ignore. `'unsatisfiable'` is the one case that must
|
||||
* NOT become a 200: a range starting past the end is a client with a stale
|
||||
* idea of the file, and answering it with the whole file would splice the
|
||||
* beginning of the video into the middle of its buffer.
|
||||
*/
|
||||
export function parseByteRange(header: string | undefined, size: number): ParsedRange | null | 'unsatisfiable' {
|
||||
if (!header) return null;
|
||||
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
||||
if (!match) return null;
|
||||
const [, rawStart, rawEnd] = match;
|
||||
if (rawStart === '' && rawEnd === '') return null;
|
||||
|
||||
// A suffix range — `bytes=-500`, the last 500 bytes. Browsers use it to read
|
||||
// the MP4 moov atom when it sits at the end of the file, so a player that
|
||||
// cannot start at all is often this branch missing.
|
||||
if (rawStart === '') {
|
||||
const suffix = Number(rawEnd);
|
||||
if (!Number.isSafeInteger(suffix) || suffix <= 0) return 'unsatisfiable';
|
||||
if (size === 0) return 'unsatisfiable';
|
||||
return { start: Math.max(0, size - suffix), end: size - 1 };
|
||||
}
|
||||
|
||||
const start = Number(rawStart);
|
||||
if (!Number.isSafeInteger(start) || start < 0) return 'unsatisfiable';
|
||||
if (start >= size) return 'unsatisfiable';
|
||||
const end = rawEnd === '' ? size - 1 : Math.min(Number(rawEnd), size - 1);
|
||||
if (!Number.isSafeInteger(end) || end < start) return 'unsatisfiable';
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
export function createMediaRoutes(options: { root?: string } = {}) {
|
||||
const app = new Hono();
|
||||
const root = options.root ? resolve(options.root) : learnMediaRoot();
|
||||
|
||||
// GET and HEAD both, because a player probes with HEAD before it commits to
|
||||
// downloading, and an unrouted HEAD would 404 a file that is plainly there.
|
||||
app.on(['GET', 'HEAD'], LEARN_MEDIA_ROUTE, async (c) => {
|
||||
const filename = c.req.param('filename');
|
||||
if (!filename || !isLearnMediaFilename(filename)) return c.notFound();
|
||||
|
||||
const contentType = learnMediaContentType(filename);
|
||||
if (!contentType) return c.notFound();
|
||||
|
||||
const path = join(root, filename);
|
||||
// Belt and braces over the pattern: if this ever fails, the pattern has
|
||||
// been loosened and the loosening is a traversal.
|
||||
if (path !== resolve(path) || !path.startsWith(root + sep)) return c.notFound();
|
||||
|
||||
let size: number;
|
||||
let modified: Date;
|
||||
try {
|
||||
/*
|
||||
* realpath BEFORE the containment check, not just resolve().
|
||||
*
|
||||
* resolve() is lexical: it collapses `..` in the string but cannot see
|
||||
* through a symlink, and stat() follows one. So a link planted in the
|
||||
* media directory pointing at /etc/passwd passed the check above and was
|
||||
* served in full, while this file's own header claimed containment. The
|
||||
* directory is operator-populated and mounted read-only, so this was
|
||||
* hardening rather than a live hole — but it becomes real the moment the
|
||||
* directory is filled by an rsync or a tarball unpack.
|
||||
*/
|
||||
const real = await realpath(path);
|
||||
if (real !== path && !real.startsWith(root + sep)) return c.notFound();
|
||||
const info = await stat(real);
|
||||
if (!info.isFile()) return c.notFound();
|
||||
size = info.size;
|
||||
modified = info.mtime;
|
||||
} catch {
|
||||
// Missing, unreadable, a dangling symlink — all one answer. Telling the
|
||||
// difference tells a prober which names exist, and unguessable names are
|
||||
// the only thing standing between these files and enumeration.
|
||||
return c.notFound();
|
||||
}
|
||||
|
||||
const headers = new Headers({
|
||||
'content-type': contentType,
|
||||
'accept-ranges': 'bytes',
|
||||
// Content-addressed: the bytes behind a name never change, so a year is
|
||||
// safe and `immutable` stops the revalidation round trip on every seek.
|
||||
'cache-control': 'public, max-age=31536000, immutable',
|
||||
'last-modified': modified.toUTCString(),
|
||||
etag: `"${size.toString(16)}-${modified.getTime().toString(16)}"`,
|
||||
// These are downloads to a media element, never documents. Without it a
|
||||
// browser that sniffs its way to text/html on a truncated file would
|
||||
// treat same-origin bytes as a page.
|
||||
'x-content-type-options': 'nosniff',
|
||||
});
|
||||
|
||||
const range = parseByteRange(c.req.header('range'), size);
|
||||
if (range === 'unsatisfiable') {
|
||||
headers.set('content-range', `bytes */${size}`);
|
||||
// Explicit zero rather than an absent header: without it Node falls back
|
||||
// to chunked encoding for a body that does not exist.
|
||||
headers.set('content-length', '0');
|
||||
return new Response(null, { status: 416, headers });
|
||||
}
|
||||
|
||||
const start = range ? range.start : 0;
|
||||
const end = range ? range.end : Math.max(0, size - 1);
|
||||
const length = size === 0 ? 0 : end - start + 1;
|
||||
headers.set('content-length', String(length));
|
||||
if (range) headers.set('content-range', `bytes ${start}-${end}/${size}`);
|
||||
|
||||
// A HEAD answers with the headers and no body — including the 206 status
|
||||
// and Content-Range, so the player learns the file is seekable without
|
||||
// fetching a byte of it.
|
||||
if (c.req.method === 'HEAD') {
|
||||
return new Response(null, { status: range ? 206 : 200, headers });
|
||||
}
|
||||
|
||||
const stream = createReadStream(path, size === 0 ? undefined : { start, end });
|
||||
return new Response(Readable.toWeb(stream) as ReadableStream, {
|
||||
status: range ? 206 : 200,
|
||||
headers,
|
||||
});
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -47,7 +47,7 @@ import {
|
||||
LEARN_EMBED_REJECTION_MESSAGES,
|
||||
LEARN_TRACKS,
|
||||
LEARN_VISIBILITIES,
|
||||
learnEmbedUrl,
|
||||
learnEmbed,
|
||||
learnVisibilityPermitted,
|
||||
learnWatchUrl,
|
||||
resolveLearnEmbed,
|
||||
@@ -326,9 +326,9 @@ interface LearnRowForView {
|
||||
* available, not that it is broken.
|
||||
*/
|
||||
export function learnResourceView(row: LearnRowForView) {
|
||||
const embedUrl = learnEmbedUrl(row.provider, row.externalId);
|
||||
const embed = learnEmbed(row.provider, row.externalId);
|
||||
const watchUrl = learnWatchUrl(row.provider, row.externalId);
|
||||
if (!embedUrl || !watchUrl) return null;
|
||||
if (!embed || !watchUrl) return null;
|
||||
return {
|
||||
id: row.id,
|
||||
track: row.track,
|
||||
@@ -339,7 +339,14 @@ export function learnResourceView(row: LearnRowForView) {
|
||||
durationSeconds: row.durationSeconds,
|
||||
sortOrder: row.sortOrder,
|
||||
publishedAt: row.publishedAt,
|
||||
embedUrl,
|
||||
/**
|
||||
* The discriminated union — `kind: 'iframe' | 'video'` — is what the
|
||||
* client branches on. Sent alongside the flat `embedUrl` rather than
|
||||
* instead of it so a client mid-deploy keeps rendering; the flat field is
|
||||
* the same string and will go once nothing reads it.
|
||||
*/
|
||||
embed,
|
||||
embedUrl: embed.src,
|
||||
watchUrl,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -20,11 +20,17 @@ import {
|
||||
LEARN_CODE_TRACK,
|
||||
LEARN_FRAME_SRC_HOSTS,
|
||||
formatLearnDuration,
|
||||
learnEmbed,
|
||||
learnEmbedUrl,
|
||||
learnVisibilityPermitted,
|
||||
resolveLearnEmbed,
|
||||
} from '@pig/core';
|
||||
import type { Database } from '@pig/db';
|
||||
import { learnResources, platformSettings } from '@pig/db';
|
||||
import { createMediaRoutes, LEARN_MEDIA_DIR_ENV, parseByteRange } from '../src/lib/media';
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createApp } from '../src/app';
|
||||
import { loadConfig } from '../src/lib/config';
|
||||
import {
|
||||
@@ -95,10 +101,89 @@ describe('embed allowlist', () => {
|
||||
});
|
||||
|
||||
it('names every enabled host, so the CSP handoff cannot drift', () => {
|
||||
// The self-hosted provider is enabled and contributes NOTHING here. A
|
||||
// native <video> on this origin is covered by `default-src 'self'`, and
|
||||
// widening frame-src for it would hand out framing rights nothing needs.
|
||||
assert.deepEqual(LEARN_FRAME_SRC_HOSTS, ['https://video.karti.ai']);
|
||||
});
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------- self-hosted
|
||||
|
||||
describe('self-hosted media', () => {
|
||||
it('resolves a /media/learn path to a native video, not an iframe', () => {
|
||||
const resolved = resolveLearnEmbed('/media/learn/pig-tour.7f3a91c2.mp4');
|
||||
assert.equal(resolved.ok, true);
|
||||
assert.equal(resolved.ok && resolved.provider, 'pig');
|
||||
assert.equal(resolved.ok && resolved.externalId, 'pig-tour.7f3a91c2.mp4');
|
||||
assert.deepEqual(resolved.ok && resolved.embed, {
|
||||
kind: 'video',
|
||||
src: '/media/learn/pig-tour.7f3a91c2.mp4',
|
||||
});
|
||||
// The flat field stays in step for callers written before the union.
|
||||
assert.equal(resolved.ok && resolved.embedUrl, '/media/learn/pig-tour.7f3a91c2.mp4');
|
||||
});
|
||||
|
||||
it('still resolves a remote provider to an iframe', () => {
|
||||
const resolved = resolveLearnEmbed('https://video.karti.ai/s/0n6n9p83efnxbs2');
|
||||
assert.deepEqual(resolved.ok && resolved.embed, {
|
||||
kind: 'iframe',
|
||||
src: 'https://video.karti.ai/embed/0n6n9p83efnxbs2',
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses every path that would read a file we did not mean to serve', () => {
|
||||
// Traversal in each encoding that has ever worked somewhere, a scheme, a
|
||||
// host, a protocol-relative URL that a naive `startsWith('/')` would treat
|
||||
// as a path, an extension we do not serve, and a bare dotfile.
|
||||
const hostile = [
|
||||
'/media/learn/../../etc/passwd',
|
||||
'/media/learn/..%2f..%2fetc%2fpasswd',
|
||||
'/media/learn/../secrets.mp4',
|
||||
'/media/learn/..',
|
||||
'/media/learn/sub/dir/video.mp4',
|
||||
'/media/learn/',
|
||||
'/etc/passwd',
|
||||
'/media/other/video.mp4',
|
||||
'//evil.example/media/learn/video.mp4',
|
||||
'file:///media/learn/video.mp4',
|
||||
'https://primeintellectgrowth.com/media/learn/pig-tour.7f3a91c2.mp4',
|
||||
'/media/learn/.env',
|
||||
'/media/learn/video.mp4.sh',
|
||||
'/media/learn/video mp4.mp4',
|
||||
'/media/learn/video.mp4?v=2',
|
||||
'/media/learn/video.mp4#t=10',
|
||||
'/media/learn/-leading-dash.mp4',
|
||||
`/media/learn/${'a'.repeat(130)}.mp4`,
|
||||
];
|
||||
for (const candidate of hostile) {
|
||||
assert.equal(resolveLearnEmbed(candidate).ok, false, `should reject: ${candidate}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('re-validates a stored filename rather than trusting the database', () => {
|
||||
// Same argument as the Cap case: persistence is not validation. A row
|
||||
// written by a future path that skipped the resolver must not become a
|
||||
// file read.
|
||||
assert.equal(learnEmbed('pig', '../../etc/passwd'), null);
|
||||
assert.equal(learnEmbed('pig', 'pig-tour.mp4.sh'), null);
|
||||
assert.deepEqual(learnEmbed('pig', 'pig-tour.7f3a91c2.mp4'), {
|
||||
kind: 'video',
|
||||
src: '/media/learn/pig-tour.7f3a91c2.mp4',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts a self-hosted path at the create schema, on the platform track', () => {
|
||||
const parsed = learnResourceCreateSchema.safeParse({
|
||||
track: LEARN_CODE_TRACK,
|
||||
title: 'A tour of PIG in five minutes',
|
||||
url: '/media/learn/pig-tour.7f3a91c2.mp4',
|
||||
visibility: 'code',
|
||||
});
|
||||
assert.equal(parsed.success, true);
|
||||
});
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------- the two rules
|
||||
|
||||
describe('code visibility', () => {
|
||||
@@ -269,6 +354,232 @@ describe('attempt limiter', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ------------------------------------------------- the public round trip
|
||||
|
||||
/**
|
||||
* A self-hosted row must survive the whole read path as a `video`.
|
||||
*
|
||||
* Asserted through `app.request` on the real public route rather than on the
|
||||
* serialiser, because the failure this guards against is composition: the
|
||||
* route enumerates its columns, drops rows it cannot rebuild an embed for, and
|
||||
* is the one read a code-holder performs. A row that resolves fine in
|
||||
* isolation and is silently dropped by `renderable()` would leave the Learn
|
||||
* page empty with nothing in the log.
|
||||
*/
|
||||
describe('a self-hosted row through /api/learn/public', () => {
|
||||
const config = loadConfig({
|
||||
NODE_ENV: 'production',
|
||||
DATABASE_URL: 'postgres://unused:unused@127.0.0.1:1/unused',
|
||||
PIG_PUBLIC_URL: 'https://pig-learn-test.invalid',
|
||||
SUPABASE_URL: 'https://identity-learn-test.invalid',
|
||||
SUPABASE_ANON_KEY: 'learn-test-anon-key',
|
||||
SUPABASE_SERVICE_KEY: '',
|
||||
PIG_ADMIN_EMAILS: '',
|
||||
PIGGY_ENABLED: 'false',
|
||||
});
|
||||
|
||||
const rows = [
|
||||
{
|
||||
id: '00000000-0000-4000-8000-000000000001',
|
||||
track: 'platform' as const,
|
||||
title: 'A tour of PIG in five minutes',
|
||||
summary: 'What the product is for.',
|
||||
provider: 'pig' as const,
|
||||
externalId: 'pig-tour.7f3a91c2.mp4',
|
||||
visibility: 'code' as const,
|
||||
durationSeconds: 300,
|
||||
sortOrder: 1,
|
||||
publishedAt: new Date('2026-08-01T00:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: '00000000-0000-4000-8000-000000000002',
|
||||
track: 'platform' as const,
|
||||
title: 'The Cap-hosted one, still an iframe',
|
||||
summary: null,
|
||||
provider: 'cap' as const,
|
||||
externalId: '0n6n9p83efnxbs2',
|
||||
visibility: 'code' as const,
|
||||
durationSeconds: 520,
|
||||
sortOrder: 2,
|
||||
publishedAt: new Date('2026-08-02T00:00:00.000Z'),
|
||||
},
|
||||
];
|
||||
|
||||
/** Answers the settings lookup and the resource read, and nothing else. */
|
||||
const db = {
|
||||
select: () => ({
|
||||
from: (table: unknown) => ({
|
||||
where: () => ({
|
||||
limit: async () =>
|
||||
table === platformSettings ? [{ code: ACCESS_CODE }] : [],
|
||||
orderBy: async () => (table === learnResources ? rows : []),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
} as unknown as Database;
|
||||
|
||||
const authProvider = {
|
||||
name: 'learn-test-stub',
|
||||
async verifyAccessToken(): Promise<{ subject: string; email: string }> {
|
||||
throw new Error('Not a valid identity token.');
|
||||
},
|
||||
};
|
||||
|
||||
it('returns kind:"video" for the self-hosted row and kind:"iframe" for the remote one', async () => {
|
||||
const app = createApp(config, db, authProvider);
|
||||
const token = mintLearnToken(ACCESS_CODE, Date.now() + LEARN_TOKEN_TTL_MS);
|
||||
const response = await app.request('https://pig-learn-test.invalid/api/learn/public', {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
|
||||
const body = (await response.json()) as {
|
||||
resources: { title: string; embed: { kind: string; src: string }; embedUrl: string }[];
|
||||
};
|
||||
assert.equal(body.resources.length, 2, 'neither row may be dropped');
|
||||
|
||||
const [hosted, remote] = body.resources;
|
||||
assert.deepEqual(hosted?.embed, {
|
||||
kind: 'video',
|
||||
src: '/media/learn/pig-tour.7f3a91c2.mp4',
|
||||
});
|
||||
// Same-origin and relative, so the page needs no CSP host for it at all.
|
||||
assert.equal(hosted?.embedUrl, '/media/learn/pig-tour.7f3a91c2.mp4');
|
||||
assert.equal(remote?.embed.kind, 'iframe');
|
||||
assert.equal(remote?.embed.src, 'https://video.karti.ai/embed/0n6n9p83efnxbs2');
|
||||
});
|
||||
|
||||
it('serves that src from the ASSEMBLED app, not just from the route factory', async () => {
|
||||
/*
|
||||
* The assertion that would have caught the media route shipping unmounted.
|
||||
*
|
||||
* `describe('the media route')` below exercises createMediaRoutes() as a
|
||||
* standalone Hono app, which verifies the handler and proves nothing about
|
||||
* whether createApp wires it in. It did not: every layer landed — the
|
||||
* migration, the seed, both feeds, the bind mount, the docs — except the
|
||||
* one that serves the bytes, and the whole suite stayed green. Requests to
|
||||
* /media/learn/* fell through to server.ts's SPA fallback and returned
|
||||
* HTTP 200 text/html, so the player showed a black box with working
|
||||
* controls and no error.
|
||||
*
|
||||
* Assert against the composed application, and specifically on the
|
||||
* content-type: the failure mode is a 200, not a 404.
|
||||
*/
|
||||
// The route reads its root from the environment at request time, so point
|
||||
// it at a directory that really holds the file the feed advertises.
|
||||
const root = mkdtempSync(join(tmpdir(), 'pig-media-mounted-'));
|
||||
writeFileSync(join(root, 'pig-tour.7f3a91c2.mp4'), Buffer.alloc(2048, 7));
|
||||
const previous = process.env[LEARN_MEDIA_DIR_ENV];
|
||||
process.env[LEARN_MEDIA_DIR_ENV] = root;
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
const app = createApp(config, db, authProvider);
|
||||
response = await app.request(
|
||||
'https://pig-learn-test.invalid/media/learn/pig-tour.7f3a91c2.mp4',
|
||||
);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env[LEARN_MEDIA_DIR_ENV];
|
||||
else process.env[LEARN_MEDIA_DIR_ENV] = previous;
|
||||
}
|
||||
|
||||
assert.notEqual(response.status, 404, 'the media route is not mounted in createApp');
|
||||
assert.equal(
|
||||
response.headers.get('content-type'),
|
||||
'video/mp4',
|
||||
'the SPA fallback answered instead of the media route',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------- serving the file
|
||||
|
||||
describe('the media route', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'pig-media-'));
|
||||
// 1 KiB of distinguishable bytes: an assertion on a range is only meaningful
|
||||
// if the wrong offset produces different content.
|
||||
const body = Buffer.from(Array.from({ length: 1024 }, (_, i) => i % 251));
|
||||
writeFileSync(join(root, 'pig-tour.7f3a91c2.mp4'), body);
|
||||
const app = createMediaRoutes({ root });
|
||||
const url = (path: string) => `https://pig.invalid${path}`;
|
||||
|
||||
it('serves the whole file with a seekable header set', async () => {
|
||||
const response = await app.request(url('/media/learn/pig-tour.7f3a91c2.mp4'));
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(response.headers.get('content-type'), 'video/mp4');
|
||||
// Without this a browser will not attempt a range request at all, and the
|
||||
// scrubber becomes decorative.
|
||||
assert.equal(response.headers.get('accept-ranges'), 'bytes');
|
||||
assert.equal(response.headers.get('content-length'), '1024');
|
||||
assert.deepEqual(Buffer.from(await response.arrayBuffer()), body);
|
||||
});
|
||||
|
||||
it('answers a range with 206 and exactly those bytes', async () => {
|
||||
const response = await app.request(url('/media/learn/pig-tour.7f3a91c2.mp4'), {
|
||||
headers: { range: 'bytes=100-199' },
|
||||
});
|
||||
assert.equal(response.status, 206);
|
||||
assert.equal(response.headers.get('content-range'), 'bytes 100-199/1024');
|
||||
assert.equal(response.headers.get('content-length'), '100');
|
||||
assert.deepEqual(Buffer.from(await response.arrayBuffer()), body.subarray(100, 200));
|
||||
});
|
||||
|
||||
it('answers an open-ended and a suffix range', async () => {
|
||||
const open = await app.request(url('/media/learn/pig-tour.7f3a91c2.mp4'), {
|
||||
headers: { range: 'bytes=1000-' },
|
||||
});
|
||||
assert.equal(open.headers.get('content-range'), 'bytes 1000-1023/1024');
|
||||
|
||||
// How a player finds an MP4 moov atom at the end of the file. Getting this
|
||||
// branch wrong is why some videos never start rather than never seek.
|
||||
const suffix = await app.request(url('/media/learn/pig-tour.7f3a91c2.mp4'), {
|
||||
headers: { range: 'bytes=-24' },
|
||||
});
|
||||
assert.equal(suffix.headers.get('content-range'), 'bytes 1000-1023/1024');
|
||||
assert.deepEqual(Buffer.from(await suffix.arrayBuffer()), body.subarray(1000));
|
||||
});
|
||||
|
||||
it('refuses a range past the end rather than restarting the file', () => {
|
||||
// 200-with-the-whole-file here splices byte 0 into the middle of the
|
||||
// player's buffer, which corrupts playback instead of failing it.
|
||||
assert.equal(parseByteRange('bytes=2000-', 1024), 'unsatisfiable');
|
||||
assert.equal(parseByteRange('bytes=500-400', 1024), 'unsatisfiable');
|
||||
// A multi-range request is ignored, which the spec permits.
|
||||
assert.equal(parseByteRange('bytes=0-10,20-30', 1024), null);
|
||||
assert.equal(parseByteRange(undefined, 1024), null);
|
||||
});
|
||||
|
||||
it('answers 416 with the real size so a client can recover', async () => {
|
||||
const response = await app.request(url('/media/learn/pig-tour.7f3a91c2.mp4'), {
|
||||
headers: { range: 'bytes=5000-' },
|
||||
});
|
||||
assert.equal(response.status, 416);
|
||||
assert.equal(response.headers.get('content-range'), 'bytes */1024');
|
||||
});
|
||||
|
||||
it('answers HEAD without a body, so a player can probe cheaply', async () => {
|
||||
const response = await app.request(url('/media/learn/pig-tour.7f3a91c2.mp4'), {
|
||||
method: 'HEAD',
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(response.headers.get('content-length'), '1024');
|
||||
assert.equal((await response.text()).length, 0);
|
||||
});
|
||||
|
||||
it('reads nothing outside the media directory', async () => {
|
||||
// The route sees these as filenames; each must 404 rather than resolve.
|
||||
for (const path of [
|
||||
'/media/learn/..%2f..%2fpackage.json',
|
||||
'/media/learn/%2e%2e%2fpackage.json',
|
||||
'/media/learn/pig-tour.7f3a91c2.mp4.sh',
|
||||
'/media/learn/absent.7f3a91c2.mp4',
|
||||
]) {
|
||||
const response = await app.request(url(path));
|
||||
assert.equal(response.status, 404, `should not serve: ${path}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('duration formatting', () => {
|
||||
it('crosses the hour without renaming the minutes', () => {
|
||||
assert.equal(formatLearnDuration(272), '4:32');
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+297
-606
File diff suppressed because it is too large
Load Diff
+11
-1
@@ -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',
|
||||
|
||||
Reference in New Issue
Block a user