Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { splitMarkdown, type SplitMarkdown } from "@t3tools/shared/markdownChunks";
3import * as Effect from "effect/Effect";
4import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
5import * as Stream from "effect/Stream";
6import { AsyncResult, Atom } from "effect/reactivity";
7
8import { connectionAtomRuntime } from "~/connection/runtime";
9
10import { FULL_TEXT_MAX_BYTES, RENDERED_MAX_LINES } from "./largeTextProtocol";
11
12// A slow download swaps in what has arrived this often, so the reader is not left at 1 MB.
13const SWAP_INTERVAL = "1 second";
14// Switching back to a recently closed file reuses its text instead of downloading it again.
15const RECENT_FILE_TTL_MS = 60_000;
16
17interface Downloaded {
18 readonly text: string;
19 readonly lines: number;
20}
21
22function countNewlines(text: string): number {
23 let lines = 0;
24 for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) {
25 lines += 1;
26 }
27 return lines;
28}
29
30// Past either cap the main thread cannot hold or lay the text out.
31const tooLarge = (file: Downloaded) =>
32 file.lines > RENDERED_MAX_LINES || file.text.length > FULL_TEXT_MAX_BYTES;
33
34/** A file's text so far, at most once per interval, ending at its whole text or past a cap. */
35export const downloadText = (src: string) =>
36 HttpClient.get(src).pipe(
37 Effect.flatMap(HttpClientResponse.filterStatusOk),
38 Effect.map((response) => response.stream),
39 Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
40 Stream.unwrap,
41 // Drops a leading BOM, as the 1 MB preview read does.
42 Stream.decodeText,
43 Stream.scan(
44 (): Downloaded => ({ text: "", lines: 1 }),
45 (file, chunk) => ({ text: file.text + chunk, lines: file.lines + countNewlines(chunk) }),
46 ),
47 Stream.takeUntil(tooLarge),
48 Stream.groupedWithin(Number.MAX_SAFE_INTEGER, SWAP_INTERVAL),
49 Stream.map((swaps) => swaps[swaps.length - 1]!),
50 );
51
52/** `src` is the asset URL with its revision, so a changed file downloads again. */
53const fullFileTextAtom = Atom.family((src: string) =>
54 connectionAtomRuntime
55 .atom(downloadText(src))
56 .pipe(Atom.setIdleTTL(RECENT_FILE_TTL_MS), Atom.withLabel(`full-file-text:${src}`)),
57);
58
59export type FullFileText =
60 | { readonly text: string; readonly done: boolean }
61 | "too-large"
62 | "failed";
63
64/** A file past the 1 MB read: the preview at once, then the full file as it downloads. */
65export function useFullFileText(src: string, preview: string): FullFileText {
66 const result = useAtomValue(fullFileTextAtom(src));
67 if (AsyncResult.isFailure(result)) return "failed";
68 if (!AsyncResult.isSuccess(result)) return { text: preview, done: false };
69 if (tooLarge(result.value)) return "too-large";
70 if (!result.waiting) return { text: result.value.text, done: true };
71 // Whole lines only, so the last row does not flicker as it fills in; the first swap can still
72 // hold less than the preview already shows.
73 const text = result.value.text.slice(0, result.value.text.lastIndexOf("\n") + 1);
74 return { text: text.length >= preview.length ? text : preview, done: false };
75}
76
77/** The finished text's Markdown pieces, kept as long as its text; splitting 12 MB takes 0.5 s. */
78const fullFileMarkdownAtom = Atom.family((src: string) =>
79 Atom.make((get) => {
80 const result = get(fullFileTextAtom(src));
81 return AsyncResult.isSuccess(result) && !result.waiting && !tooLarge(result.value)
82 ? splitMarkdown(result.value.text)
83 : null;
84 }).pipe(Atom.setIdleTTL(RECENT_FILE_TTL_MS), Atom.withLabel(`full-file-markdown:${src}`)),
85);
86
87/** Markdown pieces of the text so far; a finished file's are split once and kept. */
88export function useFullFileMarkdown(src: string, text: string): SplitMarkdown {
89 return useAtomValue(fullFileMarkdownAtom(src)) ?? splitMarkdown(text);
90}