-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcell.ts
58 lines (55 loc) · 2.03 KB
/
cell.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import type { CellType, TagType } from './interfaces/ehtag.js';
import { parse, render, type Context } from './markdown/index.js';
import type { Tree } from './interfaces/ehtag.ast.js';
export class Cell {
constructor(raw: string) {
raw = raw.trim();
this.input = raw;
}
readonly input: string;
private cache!: Partial<CellType<'full'>>;
private revision?: number;
private getCache<T extends TagType>(target: T, revision: number): CellType<T> | undefined {
if (revision !== this.revision) {
this.cache = {};
this.revision = revision;
return undefined;
}
const cache = this.cache;
if (target === 'full') {
if (cache.ast && cache.html && cache.raw && cache.text) {
return cache as CellType<T>;
} else {
return undefined;
}
} else {
return cache[target as TagType as Exclude<TagType, 'full'>] as CellType<T> | undefined;
}
}
private setCache<T extends TagType>(target: T, revision: number, rendered: CellType<T>): void {
if (this.revision !== revision) {
this.cache = {};
}
if (target === 'full') {
const i = rendered as CellType<'full'>;
this.cache.raw = i.raw;
this.cache.text = i.text;
this.cache.html = i.html;
this.cache.ast = i.ast;
} else {
this.cache[target as TagType as Exclude<TagType, 'full'>] = rendered as string & Tree;
}
this.revision = revision;
}
render<T extends TagType>(target: T, context: Context | undefined): CellType<T> {
const revision = context?.database.revision;
if (revision) {
const cache = this.getCache(target, revision);
if (cache) return cache;
}
const tokens = parse(this.input, context);
const result = render(tokens, target);
if (revision) this.setCache(target, revision, result);
return result;
}
}