Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

sourceHighlightingState.ts

42 lines1.4 KB

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