forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

rag-output-drawer.tsx281 lines, 11.8 KiBHistoryRawDownload
1import { For, Show, createSignal, onCleanup } from "solid-js";
2import type { RagOutput } from "@/api/client";
3import { Alert } from "@/components/ui/alert";
4import { Button } from "@/components/ui/button";
5import { SidePanel } from "@/components/ui/side-panel";
6import { IconCopy, IconDownload, IconFileText } from "@/components/ui/icons";
7import {
8 buildRagOutputMarkdown,
9 fieldValueText,
10 ragOutputFileName,
11 readRagOutputDocument,
12 type RagOutputDocument,
13 type RagOutputPassage,
14} from "@/components/notes/rag-output-document";
15import {
16 ragOutputMessage,
17 ragOutputPassagePages,
18 type RagOutputMessageKey,
19} from "@/components/notes/rag-output-messages";
20import { formatDateTime } from "@/lib/format";
21import { usePreferences } from "@/stores/preferences-context";
22
23/**
24 * Print isolation: the SidePanel portals into the app's document, so a bare
25 * `window.print()` would capture the whole page. These rules hide every
26 * element except the document body, flatten the panel out of its fixed,
27 * scroll-clipped layout, and pull the document to the page origin. The action
28 * row and the technical disclosure opt out with `print:hidden`.
29 */
30const PRINT_STYLES = `
31@media print {
32 body * { visibility: hidden; }
33 .rag-output-print, .rag-output-print * { overflow: visible !important; }
34 .rag-output-print { position: static !important; max-width: none !important; height: auto !important; box-shadow: none !important; }
35 .rag-output-print [data-rag-print-doc], .rag-output-print [data-rag-print-doc] * { visibility: visible; }
36 .rag-output-print [data-rag-print-doc] { position: absolute; left: 0; top: 0; width: 100%; color: #000; }
37}
38`;
39
40/** Payload keys with a Turkish label; anything else is labelled by its key. */
41const FIELD_LABELS: Partial<Record<string, RagOutputMessageKey>> = {
42 chunks: "chunks",
43};
44
45/**
46 * One stored AI output, readable and exportable: the note it belongs to, the
47 * attachments by name, the produced prose, the lesser payload fields, and the
48 * raw record behind a disclosure. Copy / download / print all build their
49 * output from this same document.
50 */
51export function RagOutputDrawer(props: {
52 output: RagOutput | null;
53 /** The note the output belongs to — shown by title, never by id. */
54 noteTitle?: string;
55 onOpenChange: (open: boolean) => void;
56}) {
57 const { locale } = usePreferences();
58 const rt = (key: RagOutputMessageKey, vars?: Record<string, string | number>) =>
59 ragOutputMessage(locale(), key, vars);
60 const [copied, setCopied] = createSignal(false);
61 const [copyError, setCopyError] = createSignal("");
62 let copiedTimer: ReturnType<typeof setTimeout> | undefined;
63 onCleanup(() => copiedTimer && clearTimeout(copiedTimer));
64
65 const doc = () => (props.output ? readRagOutputDocument(props.output) : null);
66 const noteTitle = () => props.noteTitle?.trim() ?? "";
67 /** One passage's heading: the source file by name, its page range if any. */
68 const passageHeader = (passage: RagOutputPassage) => {
69 const source = passage.sourceName
70 ?? (passage.fromNote ? noteTitle() || rt("noteText") : rt("unnamedSource"));
71 const pages = ragOutputPassagePages(locale(), passage.pageStart, passage.pageEnd);
72 return pages ? `${source} · ${pages}` : source;
73 };
74 /** The honest note when the service's cap means more passages exist. */
75 const passagesNote = (read: RagOutputDocument) => {
76 if (!read.passagesTruncated) return "";
77 return read.chunksTotal != null
78 ? rt("passagesTruncated", { shown: read.passages.length, total: read.chunksTotal })
79 : rt("passagesTruncatedNoTotal", { shown: read.passages.length });
80 };
81 const markdown = () => {
82 const output = props.output;
83 const read = doc();
84 if (!output || !read) return "";
85 return buildRagOutputMarkdown({
86 title: noteTitle() || rt("drawerTitle"),
87 date: formatDateTime(output.generated_at, locale()),
88 noteTitle: noteTitle(),
89 document: read,
90 labels: {
91 date: rt("date"),
92 note: rt("note"),
93 sources: rt("sources"),
94 failed: rt("failedTitle"),
95 otherFields: rt("otherFields"),
96 passages: rt("passages"),
97 passageHeader,
98 passagesTruncated: passagesNote(read),
99 },
100 });
101 };
102
103 const copy = async () => {
104 setCopyError("");
105 if (!navigator.clipboard?.writeText) {
106 setCopyError(rt("copyFailed"));
107 return;
108 }
109 try {
110 await navigator.clipboard.writeText(markdown());
111 setCopied(true);
112 copiedTimer = setTimeout(() => setCopied(false), 2500);
113 } catch {
114 setCopied(false);
115 setCopyError(rt("copyFailed"));
116 }
117 };
118
119 const download = () => {
120 const output = props.output;
121 if (!output) return;
122 const blob = new Blob([markdown()], { type: "text/markdown;charset=utf-8" });
123 const url = URL.createObjectURL(blob);
124 const link = document.createElement("a");
125 link.href = url;
126 link.download = ragOutputFileName(output.generated_at);
127 document.body.appendChild(link);
128 link.click();
129 link.remove();
130 URL.revokeObjectURL(url);
131 };
132
133 return (
134 <SidePanel
135 open={props.output != null}
136 onOpenChange={props.onOpenChange}
137 title={rt("drawerTitle")}
138 description={noteTitle()}
139 size="wide"
140 class="rag-output-print"
141 >
142 <style>{PRINT_STYLES}</style>
143 <Show when={props.output}>
144 {(output) => (
145 <Show when={doc()}>
146 {(read) => (
147 <article data-rag-print-doc class="space-y-4">
148 <header class="space-y-0.5 border-b border-border/60 pb-3">
149 <p class="text-xs uppercase tracking-wide text-muted-foreground">{rt("drawerTitle")}</p>
150 <h2 class="text-base font-semibold">{noteTitle() || rt("drawerTitle")}</h2>
151 <p class="text-xs text-muted-foreground">{formatDateTime(output().generated_at, locale())}</p>
152 </header>
153
154 <div class="flex flex-wrap items-center gap-2 print:hidden">
155 <Button type="button" size="sm" variant="outline" onClick={() => void copy()}>
156 <IconCopy class="h-4 w-4" />
157 {rt("copy")}
158 </Button>
159 <Button type="button" size="sm" variant="outline" onClick={download}>
160 <IconDownload class="h-4 w-4" />
161 {rt("download")}
162 </Button>
163 <Button type="button" size="sm" variant="outline" onClick={() => window.print()}>
164 <IconFileText class="h-4 w-4" />
165 {rt("print")}
166 </Button>
167 </div>
168 <Show when={copied()}>
169 <Alert variant="success">{rt("copied")}</Alert>
170 </Show>
171 <Show when={copyError()}>
172 <Alert variant="destructive">{copyError()}</Alert>
173 </Show>
174
175 <dl class="grid gap-1 text-sm sm:grid-cols-[auto_1fr] sm:gap-x-3">
176 <dt class="text-muted-foreground">{rt("date")}</dt>
177 <dd class="text-xs sm:pt-0.5">{formatDateTime(output().generated_at, locale())}</dd>
178 <Show when={noteTitle()}>
179 <dt class="text-muted-foreground">{rt("note")}</dt>
180 <dd>{noteTitle()}</dd>
181 </Show>
182 </dl>
183
184 <div class="space-y-1">
185 <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{rt("sources")}</p>
186 <Show
187 when={read().sourceNames.length > 0 || read().unnamedSources > 0}
188 fallback={<p class="text-sm text-muted-foreground">{rt("noSources")}</p>}
189 >
190 <ul class="list-disc space-y-0.5 pl-5 text-sm">
191 <For each={read().sourceNames}>{(name) => <li>{name}</li>}</For>
192 <Show when={read().unnamedSources > 0}>
193 <li>
194 {rt("unnamedSource")}
195 {read().unnamedSources > 1 ? ` × ${read().unnamedSources}` : ""}
196 </li>
197 </Show>
198 </ul>
199 </Show>
200 </div>
201
202 <Show when={read().failed.length > 0}>
203 <Alert variant="warning">
204 {/* One flex item: Alert lays its children out in a row. */}
205 <div class="space-y-0.5">
206 <p class="font-medium">{rt("failedTitle")}</p>
207 <p>{rt("failedLine", { names: read().failed.join(", ") })}</p>
208 </div>
209 </Alert>
210 </Show>
211
212 <Show
213 when={read().summary || read().points.length > 0}
214 fallback={<Alert variant="warning">{rt("emptyText")}</Alert>}
215 >
216 <Show when={read().summary}>
217 <p class="whitespace-pre-wrap text-sm leading-6">{read().summary}</p>
218 </Show>
219 <Show when={read().points.length > 0}>
220 <ul class="list-disc space-y-1 pl-5 text-sm text-foreground/85">
221 <For each={read().points}>{(point) => <li>{point}</li>}</For>
222 </ul>
223 </Show>
224 </Show>
225
226 <Show when={read().passages.length > 0}>
227 <div class="space-y-2">
228 <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{rt("passages")}</p>
229 <ul class="space-y-3">
230 <For each={read().passages}>
231 {(passage) => (
232 <li class="rounded-lg border border-border/60 p-3">
233 <p class="text-xs text-muted-foreground">{passageHeader(passage)}</p>
234 {/* Scrolls past its cap on screen; print flows it out in full. */}
235 <div class="mt-1.5 max-h-60 overflow-y-auto print:max-h-none">
236 <p class="whitespace-pre-wrap break-words text-sm leading-6">{passage.text}</p>
237 </div>
238 </li>
239 )}
240 </For>
241 </ul>
242 <Show when={passagesNote(read())}>
243 <p class="text-xs text-muted-foreground">{passagesNote(read())}</p>
244 </Show>
245 </div>
246 </Show>
247
248 <Show when={read().fields.length > 0}>
249 <div class="space-y-1.5">
250 <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
251 {rt("otherFields")}
252 </p>
253 <dl class="space-y-1.5 text-sm">
254 <For each={read().fields}>
255 {(field) => (
256 <div class="flex flex-wrap gap-x-2">
257 <dt class="shrink-0 text-muted-foreground">
258 {FIELD_LABELS[field.key] ? rt(FIELD_LABELS[field.key]!) : field.key}
259 </dt>
260 <dd class="min-w-0 break-words whitespace-pre-wrap">{fieldValueText(field.value)}</dd>
261 </div>
262 )}
263 </For>
264 </dl>
265 </div>
266 </Show>
267
268 <details class="rounded-lg border border-border/60 p-3 print:hidden">
269 <summary class="cursor-pointer text-xs font-medium text-muted-foreground">{rt("technical")}</summary>
270 <pre class="mt-2 overflow-x-auto whitespace-pre-wrap text-xs leading-5">
271 {JSON.stringify(read().raw, null, 2)}
272 </pre>
273 </details>
274 </article>
275 )}
276 </Show>
277 )}
278 </Show>
279 </SidePanel>
280 );
281}