loopable / web /src /intelligence /FileView.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
c72f0a1 verified
Raw History Blame
12.9 kB
import { Fragment, createElement, useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import type { FormEvent, ReactNode } from "react";
// @ts-expect-error TS7016: Frozen marked 4.3.0 has no declarations; its consumed API is typed below.
import { marked as untypedMarked } from "marked";
import { fileDate, IntelligenceApiError, intelligenceProblem } from "./intelligenceApi";
import type { IntelligenceApi, IntelligenceFile, IntelligenceProposal } from "./intelligenceApi";
import PromptView from "./PromptView";
import Proposals from "./Proposals";
import History from "./History";
interface MarkdownToken {
type: string; text?: string; raw?: string; tokens?: MarkdownToken[]; depth?: number;
href?: string; ordered?: boolean; start?: number; items?: MarkdownToken[];
header?: MarkdownToken[]; rows?: MarkdownToken[][]; task?: boolean; checked?: boolean;
}
const markdownParser: { lexer(source: string): MarkdownToken[] } = untypedMarked;
function safeLink(href = ""): string | undefined {
if (/^#\//.test(href)) return href;
try {
const url = new URL(href);
if (["https:", "http:", "mailto:"].includes(url.protocol) && !url.username && !url.password) return href;
} catch { /* A relative file path has no navigation contract. */ }
return undefined;
}
/** Use the installed Markdown parser, with React nodes instead of an HTML injection sink. */
function markdownNodes(tokens: MarkdownToken[]): ReactNode {
return tokens.map((token, index) => {
const children = token.tokens ? markdownNodes(token.tokens) : token.text || "";
let node: ReactNode;
switch (token.type) {
case "space": return null;
case "heading": node = createElement(`h${Math.min(6, Math.max(2, token.depth || 2))}`, null, children); break;
case "paragraph": node = <p>{children}</p>; break;
case "strong": node = <strong>{children}</strong>; break;
case "em": node = <em>{children}</em>; break;
case "del": node = <del>{children}</del>; break;
case "codespan": node = <code>{token.text}</code>; break;
case "code": node = <pre tabIndex={0}><code>{token.text}</code></pre>; break;
case "blockquote": node = <blockquote>{children}</blockquote>; break;
case "br": node = <br />; break;
case "hr": node = <hr />; break;
case "link": node = safeLink(token.href) ? <a href={safeLink(token.href)} rel="noopener noreferrer">{children}</a> : children; break;
case "image": node = token.text || ""; break;
case "list": node = createElement(token.ordered ? "ol" : "ul", token.ordered ? { start: token.start } : {},
token.items?.map((item, itemIndex) => <li key={itemIndex}>
{item.task ? <input type="checkbox" checked={!!item.checked} disabled aria-label="Task" /> : null}
{markdownNodes(item.tokens || [])}</li>)); break;
case "table": node = <div className="intelligence-markdown-table" tabIndex={0} role="region" aria-label="File table"><table>
<thead><tr>{token.header?.map((cell, cellIndex) => <th key={cellIndex} scope="col">{markdownNodes(cell.tokens || [])}</th>)}</tr></thead>
<tbody>{token.rows?.map((row, rowIndex) => <tr key={rowIndex}>{row.map((cell, cellIndex) =>
<td key={cellIndex}>{markdownNodes(cell.tokens || [])}</td>)}</tr>)}</tbody>
</table></div>; break;
// Raw HTML remains text. Images cannot make third-party requests from a private file.
default: node = children;
}
return <Fragment key={index}>{node}</Fragment>;
});
}
export function FileMarkdown({ body, preserveFrontmatter = false }: { body: string; preserveFrontmatter?: boolean }) {
const content = preserveFrontmatter ? body : body.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, "");
const nodes = useMemo(() => markdownNodes(markdownParser.lexer(content)), [content]);
return <div className="intelligence-markdown" data-testid="intelligence-markdown">{nodes}</div>;
}
export default function FileView({ path, api, onClose, initialHistory = false, onChanged }: {
path: string; api: IntelligenceApi; onClose: () => void; initialHistory?: boolean; onChanged?: () => void;
}) {
const backRef = useRef<HTMLButtonElement>(null);
const titleId = useId();
const [file, setFile] = useState<IntelligenceFile | null>(null);
const [problem, setProblem] = useState("");
const [missingFile, setMissingFile] = useState(false);
const [loading, setLoading] = useState(true);
const [retry, setRetry] = useState(0);
const [showHistory, setShowHistory] = useState(initialHistory);
const [restoreBusy, setRestoreBusy] = useState(false);
const restoring = useRef(false);
const readRequest = useRef<AbortController | null>(null);
const noteEditorRef = useRef<HTMLTextAreaElement>(null);
const saveRequest = useRef<AbortController | null>(null);
const [draft, setDraft] = useState<{ body: string; version: number } | null>(null);
const [saveBusy, setSaveBusy] = useState(false);
const [saveProblem, setSaveProblem] = useState("");
const [saveConflict, setSaveConflict] = useState(false);
const [saved, setSaved] = useState(false);
const [admission, setAdmission] = useState<{
api: IntelligenceApi; path: string; retry: number; proposal: IntelligenceProposal | null;
} | null>(null);
const onProposalsLoaded = useCallback((rows: IntelligenceProposal[] | null) => {
setAdmission({ api, path, retry, proposal: rows?.find((row) => row.path === path
&& row.baseVersion === 0 && row.status !== "approved") || null });
}, [api, path, retry]);
const newProposal = admission?.api === api && admission.path === path && admission.retry === retry
? admission.proposal : null;
const databaseNote = path.startsWith("database-notes/") || file?.section === "database-notes";
const editing = draft !== null;
const viewingHistory = showHistory && !databaseNote;
// A file is a page: focus lands on Back, the control that returns to the folder.
useEffect(() => { backRef.current?.focus({ preventScroll: true }); }, []);
useEffect(() => {
const abort = new AbortController();
readRequest.current = abort;
setLoading(true); setProblem(""); setMissingFile(false); setFile(null);
setDraft(null); setSaveBusy(false); setSaveProblem(""); setSaveConflict(false); setSaved(false);
void api.readFile(path, abort.signal).then((value) => {
if (!abort.signal.aborted) setFile(value);
}).catch((error: unknown) => {
if (!abort.signal.aborted) {
setMissingFile(error instanceof IntelligenceApiError && error.status === 404 && error.code === "no_file");
setProblem(intelligenceProblem(error, "This file could not be read. Try again."));
}
}).finally(() => { if (!abort.signal.aborted) setLoading(false); });
return () => { abort.abort(); saveRequest.current?.abort(); saveRequest.current = null; };
}, [api, path, retry]);
useEffect(() => { if (editing) noteEditorRef.current?.focus(); }, [editing]);
function acceptFile(value: IntelligenceFile) {
readRequest.current?.abort();
setFile(value); setProblem(""); setMissingFile(false); setLoading(false); onChanged?.();
}
async function saveNote(event: FormEvent) {
event.preventDefault();
if (!draft || !file || !databaseNote || file.canEdit !== true || !api.saveFile || saveRequest.current || saveConflict
|| draft.body === file.body) return;
const abort = new AbortController();
saveRequest.current = abort;
setSaveBusy(true); setSaveProblem(""); setSaved(false);
try {
const value = await api.saveFile(path, draft.body, draft.version, abort.signal);
if (abort.signal.aborted || saveRequest.current !== abort) return;
acceptFile(value); setDraft(null); setSaved(true);
} catch (error) {
if (abort.signal.aborted || saveRequest.current !== abort) return;
const conflict = error instanceof IntelligenceApiError && error.code === "version_conflict";
setSaveConflict(conflict);
setSaveProblem(conflict ? "The note changed. Reload before editing." : intelligenceProblem(error, "The note could not be saved. Try again."));
} finally {
if (!abort.signal.aborted && saveRequest.current === abort) { saveRequest.current = null; setSaveBusy(false); }
}
}
function cancelEdit() {
setDraft(null); setSaveProblem(""); setSaved(false);
if (saveConflict) setRetry((value) => value + 1);
setSaveConflict(false);
}
return <section className="intelligence-file-page" aria-labelledby={titleId}
data-testid="intelligence-file" aria-busy={loading || saveBusy}>
<header className="home-section-head intelligence-file-head">
<button ref={backRef} type="button" className="cg-btn" data-file-close aria-label="Back" title="Back"
disabled={restoreBusy || saveBusy} onClick={onClose}>
<svg viewBox="0 0 16 16" aria-hidden="true" className="home-layout-icon" fill="none" stroke="currentColor">
<path d="M10 3 5 8l5 5" />
</svg>
</button>
<h1 id={titleId} className="home-title">{file?.title || newProposal?.title || "File"}</h1>
</header>
{loading ? <div className="intelligence-skeleton" role="status" aria-label="Loading file"><span /><span /><span /></div> : null}
{problem && !(missingFile && newProposal) ? <div className="intelligence-feedback" role="alert"><span>{problem}</span>
<button type="button" className="intelligence-button" onClick={() => setRetry((value) => value + 1)}>Retry</button></div> : null}
{!databaseNote ? <div className="intelligence-view-switch" role="group" aria-label="File view">
<button type="button" className="intelligence-button" disabled={restoreBusy} aria-pressed={!showHistory} onClick={() => setShowHistory(false)}>File</button>
<button type="button" className="intelligence-button" disabled={restoreBusy} aria-pressed={showHistory} onClick={() => setShowHistory(true)}>History</button>
</div> : null}
{viewingHistory ? <History path={path} api={api} revision={file?.version || 0}
onBusy={(busy) => { restoring.current = busy; setRestoreBusy(busy); }}
onRestored={acceptFile} /> : <>
<Proposals key={path} path={path} api={api} onApproved={acceptFile} onLoaded={onProposalsLoaded} />
{file ? <>
{databaseNote ? <div className="intelligence-view-switch" role="group" aria-label="Database note">
{file.databaseKey ? <a className="intelligence-button" href={`#/data?database=${encodeURIComponent(file.databaseKey)}`}>Open database</a> : null}
{file.canEdit === true && api.saveFile && !editing ? <button type="button" className="intelligence-button"
onClick={() => { setDraft({ body: file.body, version: file.version }); setSaveProblem(""); setSaved(false); }}>Edit</button> : null}
</div> : null}
{databaseNote && draft ? <form className="intelligence-create" aria-busy={saveBusy} onSubmit={(event) => void saveNote(event)}>
<label>Note<textarea ref={noteEditorRef} value={draft.body} disabled={saveBusy} rows={12}
onChange={(event) => { const body = event.target.value; setDraft((current) => current ? { ...current, body } : null); }} /></label>
{saveProblem ? <div className="intelligence-feedback" role="alert"><span>{saveProblem}</span>
<button className="intelligence-button" type="button" disabled={saveBusy} onClick={() => setRetry((value) => value + 1)}>Reload</button></div> : null}
<div className="intelligence-create-actions">
<button className="intelligence-button" type="button" disabled={saveBusy} onClick={cancelEdit}>Cancel</button>
<button className="intelligence-button intelligence-primary" type="submit"
disabled={saveBusy || saveConflict || file.canEdit !== true || !api.saveFile || draft.body === file.body}>{saveBusy ? "Saving…" : "Save"}</button>
</div>
</form> : file.section === "agent-prompts"
? <PromptView tools={file.resolvedTools || []}><FileMarkdown body={file.body} /></PromptView>
: <FileMarkdown body={file.body} preserveFrontmatter={databaseNote} />}
{saved ? <p className="intelligence-meta" role="status">Saved.</p> : null}
<footer className="intelligence-file-by" data-testid="intelligence-version">
{databaseNote ? <div>History is in Notes</div> : null}
<div>Version {file.version} · Last changed by {file.author}{file.onBehalfOf ? ` for ${file.onBehalfOf}` : ""}</div>
{file.approvedBy?.length ? <div>Approved by {file.approvedBy.join(", ")}</div> : null}
{file.restoredFrom ? <div>Restored from version {file.restoredFrom}</div> : null}
<time dateTime={file.updated}>{fileDate(file.updated)}</time>
</footer>
</> : null}</>}
</section>;
}