Open History to see the last commit
1import * as Data from "effect/Data";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { Atom } from "effect/reactivity";
5
6import { resolveHighlightLanguage } from "../../lib/highlightLanguage";
7import { highlightCode, type HighlightedLines, type HighlightScheme } from "../../lib/highlights";
8
9const SOURCE_HIGHLIGHT_IDLE_TTL_MS = 5 * 60_000;
10
11export interface SourceHighlightInput {
12 readonly path: string;
13 readonly contents: string;
14 readonly theme: HighlightScheme;
15}
16
17class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
18
19class SourceHighlightError extends Schema.TaggedError<SourceHighlightError>()(
20 "SourceHighlightError",
21 { cause: Schema.Defect() },
22) {}
23
24// Highlighting is synchronous, so a cold atom resolves on its first read. The
25// family keeps results for files the user moves between.
26const sourceHighlightFamily = Atom.family((request: SourceHighlightCacheKey) =>
27 Atom.make(
28 Effect.try({
29 try: (): HighlightedLines =>
30 highlightCode(
31 request.contents,
32 resolveHighlightLanguage({ path: request.path }),
33 request.theme,
34 ),
35 catch: (cause) => new SourceHighlightError({ cause }),
36 }),
37 ).pipe(
38 Atom.setIdleTTL(SOURCE_HIGHLIGHT_IDLE_TTL_MS),
39 Atom.withLabel(`mobile:source-highlight:${request.theme}:${request.path}`),
40 ),
41);
42
43export const sourceHighlightAtom = (input: SourceHighlightInput) =>
44 sourceHighlightFamily(new SourceHighlightCacheKey(input));