Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
/**
* Pipeline — Prose Series Export (#2181).
*
* The shipping step for a prose series: configure per-series export settings
* (trim size, interior font, title-page fields) and download the compiled
* manuscript (Markdown), an ePub, or a print-interior PDF. Settings persist on
* the series record via PATCH; the three downloads are plain <a href> links to
* server routes that stream the artifact (they read the SAVED settings, so the
* download buttons gate on the form being clean — a dirty form must be saved
* first, mirroring the "Run Now gates on saved state" rule).
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router';
import { Loader2, ArrowLeft, Download, Save, BookText, FileText, FileType } from 'lucide-react';
import toast from '../components/ui/Toast';
import PageSkeleton from '../components/ui/PageSkeleton';
import {
getPipelineSeries,
updatePipelineSeries,
proseExportManuscriptUrl,
proseExportEpubUrl,
proseExportPdfUrl,
listMediaCollections,
getGalleryImages,
listVideoHistory,
} from '../services/api';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { normalizeImage, normalizeVideo } from '../components/media/normalize';
import AttributionList from '../components/media/AttributionList';
import ListLoadError from '../components/ui/ListLoadError';
import useListResource from '../hooks/useListResource';
import { TRIM_SIZES, DEFAULT_TRIM_SIZE, INTERIOR_FONTS, DEFAULT_INTERIOR_FONT } from '../lib/proseExportSettings.js';
// Client labels for the server TRIM_SIZES and INTERIOR_FONTS (via
// lib/proseExportSettings.js); a test asserts every server value has a label.
export const TRIM_SIZE_LABELS = {
'us-trade': 'US Trade (6" × 9")',
'digest': 'Digest (5.5" × 8.5")',
'mass-market': 'Mass Market (4.25" × 6.75")',
'us-letter': 'US Letter (8.5" × 11")',
'a5': 'A5',
};
export const FONT_LABELS = {
'times': 'Times (serif)',
'helvetica': 'Helvetica (sans)',
'courier': 'Courier (mono)',
};
// Build select options from server enums with client labels
const TRIM_SIZE_OPTIONS = Object.entries(TRIM_SIZES).map(([value]) => ({
value,
label: TRIM_SIZE_LABELS[value],
}));
const FONT_OPTIONS = INTERIOR_FONTS.map((value) => ({
value,
label: FONT_LABELS[value],
}));
const emptyForm = {
trimSize: DEFAULT_TRIM_SIZE,
interiorFont: DEFAULT_INTERIOR_FONT,
titlePageTitle: '',
titlePageSubtitle: '',
titlePageAuthor: '',
copyright: '',
dedication: '',
};
// Shape the stored (possibly-null) exportSettings into a fully-populated form,
// filling blank title-page fields from the series so the inputs show the same
// values the export would use.
const formFromSeries = (series) => {
const es = series?.exportSettings || {};
return {
trimSize: es.trimSize || DEFAULT_TRIM_SIZE,
interiorFont: es.interiorFont || DEFAULT_INTERIOR_FONT,
titlePageTitle: es.titlePageTitle || series?.name || '',
titlePageSubtitle: es.titlePageSubtitle || series?.logline || '',
titlePageAuthor: es.titlePageAuthor || series?.author || '',
copyright: es.copyright || '',
dedication: es.dedication || '',
};
};
export default function PipelineExport() {
const { seriesId } = useParams();
const navigate = useNavigate();
const [series, setSeries] = useState(null);
const [loading, setLoading] = useState(true);
const [form, setForm] = useState(emptyForm);
const [savedForm, setSavedForm] = useState(emptyForm);
// Roll up licenses from the series media collection so a user about to
// publish can see the terms that applied when the pixels were made (#5638).
const fetchSeriesAssets = useCallback(async () => {
const [collections, videos] = await Promise.all([
listMediaCollections({ silent: true }),
// Full (non-compact) read: compact rows drop the stamped `provenance` the rollup needs.
listVideoHistory({ silent: true }),
]);
const list = Array.isArray(collections) ? collections : [];
const collection = list.find((c) => c.seriesId === seriesId || c.id === `sc-${seriesId}`);
if (!collection) return [];
const images = await getGalleryImages((collection.items || []).filter(item => item.kind === 'image').map(item => item.ref), { silent: true });
const imagesByName = new Map((images || []).map((i) => [i.filename, i]));
const videosById = new Map((videos || []).map((v) => [v.id, v]));
const out = [];
for (const it of collection.items || []) {
if (it.kind === 'image' && imagesByName.has(it.ref)) {
out.push(normalizeImage(imagesByName.get(it.ref)));
} else if (it.kind === 'video' && videosById.has(it.ref)) {
out.push(normalizeVideo(videosById.get(it.ref)));
}
}
return out;
}, [seriesId]);
const { items: seriesAssets, state: assetsState, error: assetsError, retry: retryAssets } = useListResource(fetchSeriesAssets);
useEffect(() => {
let canceled = false;
setLoading(true);
getPipelineSeries(seriesId, { silent: true })
.then((s) => {
if (canceled) return;
setSeries(s);
const f = formFromSeries(s);
setForm(f);
setSavedForm(f);
})
.catch((err) => {
if (canceled) return;
toast.error(err.message || 'Failed to load series');
navigate('/pipeline');
})
.finally(() => { if (!canceled) setLoading(false); });
return () => { canceled = true; };
}, [seriesId, navigate]);
const dirty = useMemo(
() => JSON.stringify(form) !== JSON.stringify(savedForm),
[form, savedForm],
);
const [saveSettings, saving] = useAsyncAction(async () => {
const updated = await updatePipelineSeries(seriesId, { exportSettings: form }, { silent: true });
setSeries(updated);
setSavedForm(form);
toast.success('Export settings saved');
}, { errorMessage: 'Failed to save export settings' });
const setField = (key) => (e) => setForm((prev) => ({ ...prev, [key]: e.target.value }));
if (loading) {
return (
<PageSkeleton
label="Loading export options"
fullHeight
padded
headerRowClass="flex flex-wrap items-center gap-2"
titleWidthClass="w-56"
showAction={false}
layout="grid"
gridColsClass="lg:grid-cols-2"
cards={2}
/>
);
}
const downloads = [
{ key: 'md', label: 'Manuscript (.md)', desc: 'Compiled Markdown — front matter, volume breaks, chapter headings.', url: proseExportManuscriptUrl(seriesId), Icon: FileText },
{ key: 'epub', label: 'ePub (.epub)', desc: 'Reflowable e-book — chapters, table of contents, cover.', url: proseExportEpubUrl(seriesId), Icon: BookText },
{ key: 'pdf', label: 'Print Interior (.pdf)', desc: 'Trade-format interior — trim size, running heads, chapter openers.', url: proseExportPdfUrl(seriesId), Icon: FileType },
];
return (
<div className="h-full overflow-y-auto p-4 md:p-6">
<header className="flex flex-wrap items-center gap-2 mb-6">
<Link
to={`/pipeline/series/${seriesId}`}
className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
title="Back to series"
>
<ArrowLeft size={12} /> Series
</Link>
<h1 className="text-lg font-semibold text-white flex items-center gap-2">
<Download size={18} className="text-port-accent" /> Export
</h1>
{series?.name ? <span className="text-sm text-gray-400 truncate">— {series.name}</span> : null}
</header>
<div className="grid gap-6 lg:grid-cols-2 max-w-5xl">
{/* Settings */}
<section className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col gap-4">
<h2 className="text-sm font-semibold text-white">Export settings</h2>
<div className="grid grid-cols-2 gap-3">
<div>
<label htmlFor="export-trim" className="block text-xs text-gray-400 mb-1">Trim size</label>
<select
id="export-trim"
value={form.trimSize}
onChange={setField('trimSize')}
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
>
{TRIM_SIZE_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
</div>
<div>
<label htmlFor="export-font" className="block text-xs text-gray-400 mb-1">Interior font</label>
<select
id="export-font"
value={form.interiorFont}
onChange={setField('interiorFont')}
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
>
{FONT_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
</div>
</div>
<div>
<label htmlFor="export-title" className="block text-xs text-gray-400 mb-1">Title-page title</label>
<input
id="export-title"
type="text"
value={form.titlePageTitle}
onChange={setField('titlePageTitle')}
placeholder={series?.name || 'Title'}
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
/>
</div>
<div>
<label htmlFor="export-subtitle" className="block text-xs text-gray-400 mb-1">Subtitle</label>
<input
id="export-subtitle"
type="text"
value={form.titlePageSubtitle}
onChange={setField('titlePageSubtitle')}
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
/>
</div>
<div>
<label htmlFor="export-author" className="block text-xs text-gray-400 mb-1">Author</label>
<input
id="export-author"
type="text"
value={form.titlePageAuthor}
onChange={setField('titlePageAuthor')}
placeholder={series?.author || 'Author'}
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
/>
</div>
<div>
<label htmlFor="export-copyright" className="block text-xs text-gray-400 mb-1">Copyright line</label>
<input
id="export-copyright"
type="text"
value={form.copyright}
onChange={setField('copyright')}
placeholder="© 2026 …"
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
/>
</div>
<div>
<label htmlFor="export-dedication" className="block text-xs text-gray-400 mb-1">Dedication</label>
<textarea
id="export-dedication"
value={form.dedication}
onChange={setField('dedication')}
rows={2}
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white resize-y"
/>
</div>
<div className="flex items-center gap-3">
<button
type="button"
onClick={saveSettings}
disabled={!dirty || saving}
className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
>
{saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
{saving ? 'Saving…' : 'Save settings'}
</button>
{dirty ? <span className="text-xs text-port-warning">Unsaved changes — save before downloading.</span> : null}
</div>
</section>
{/* Downloads */}
<section className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col gap-3">
<h2 className="text-sm font-semibold text-white">Download</h2>
<p className="text-xs text-gray-500">
Each export stitches the drafted issue prose in arc order (volume breaks + chapter headings).
Requires at least one issue with drafted prose.
</p>
{downloads.map(({ key, label, desc, url, Icon }) => (
<a
key={key}
href={dirty ? undefined : url}
download
aria-disabled={dirty}
onClick={(e) => { if (dirty) { e.preventDefault(); toast.warning('Save your export settings first'); } }}
className={`flex items-start gap-3 p-3 rounded-lg border border-port-border bg-port-bg transition ${dirty ? 'opacity-50 cursor-not-allowed' : 'hover:border-port-accent'}`}
>
<Icon size={18} className="text-port-accent mt-0.5 shrink-0" />
<span className="flex flex-col">
<span className="text-sm text-white font-medium">{label}</span>
<span className="text-xs text-gray-500">{desc}</span>
</span>
</a>
))}
</section>
</div>
{assetsState === 'error' && (
<ListLoadError what="attribution and licenses" error={assetsError} onRetry={retryAssets} className="mt-6 max-w-5xl" />
)}
<AttributionList
records={seriesAssets}
className="mt-6 max-w-5xl bg-port-card border border-port-border rounded-lg px-3 py-2"
/>
</div>
);
}