-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrehype-typst.js
More file actions
228 lines (188 loc) · 8 KB
/
rehype-typst.js
File metadata and controls
228 lines (188 loc) · 8 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { visit } from 'unist-util-visit';
import { NodeCompiler } from '@myriaddreamin/typst-ts-node-compiler';
import { fromHtmlIsomorphic } from 'hast-util-from-html-isomorphic';
let compilerInstance;
async function renderTypstToSVG(code, displayMode = false, isCodeBlock = false, importsString = '') {
const compiler = compilerInstance || (compilerInstance = NodeCompiler.create());
let template;
// Only add imports to code blocks, not to math expressions (inline/display)
const imports = (isCodeBlock && importsString) ? `${importsString}\n` : '';
if (isCodeBlock) {
// For code blocks, user provides complete Typst code
template = `${imports}#set page(height: auto, width: auto, margin: 0pt)\n${code}`;
} else if (displayMode) {
template = `#set page(height: auto, width: auto, margin: 0pt)\n$ ${code} $`;
} else {
template = `#set page(height: auto, width: auto, margin: 0pt)\n$${code}$`;
}
const docRes = compiler.compile({ mainFileContent: template });
if (!docRes.result) {
const diags = compiler.fetchDiagnostics(docRes.takeDiagnostics());
throw new Error(`Typst compilation failed: ${JSON.stringify(diags)}`);
}
const svg = compiler.svg(docRes.result);
compiler.evictCache(10);
return svg;
}
export default function rehypeTypstCustom() {
return async (tree, file) => {
const promises = [];
// Get Typst imports from frontmatter
const typstImports = file.data?.astro?.frontmatter?.typstImports || [];
const importsString = Array.isArray(typstImports) ? typstImports.join('\n') : typstImports;
visit(tree, 'element', (node, index, parent) => {
// Look for custom typst block divs
if (node.tagName === 'div' && node.properties?.dataTypstBlock !== undefined && parent) {
const processNode = async () => {
// Get the text content from all text children
let code = '';
const collectText = (n) => {
if (n.type === 'text') {
code += n.value;
} else if (n.children) {
n.children.forEach(collectText);
}
};
node.children.forEach(collectText);
code = code.trim();
console.log('Typst block code:', code);
if (!code) {
return;
}
try {
const svg = await renderTypstToSVG(code, false, true, importsString);
const root = fromHtmlIsomorphic(svg, { fragment: true });
const svgNode = root.children[0];
if (svgNode) {
const height = parseFloat(svgNode.properties['dataHeight'] || '11');
const width = parseFloat(svgNode.properties['dataWidth'] || '11');
const defaultEm = 11;
svgNode.properties.height = `${height / defaultEm}em`;
svgNode.properties.width = `${width / defaultEm}em`;
// Replace the div with a typst-display div containing the SVG
parent.children[index] = {
type: 'element',
tagName: 'div',
properties: { className: ['typst-display'] },
children: [svgNode]
};
}
} catch (error) {
console.error('Typst rendering error:', error);
node.children = [{
type: 'text',
value: `[Typst Error: ${error.message}]`
}];
}
};
promises.push(processNode());
return;
}
// Look for code blocks with language-typst class (inside pre tags)
if (node.tagName === 'pre' && parent) {
const codeNode = node.children?.find(child => child.type === 'element' && child.tagName === 'code');
if (codeNode) {
const classes = codeNode.properties?.className || [];
if (classes.includes('language-typst')) {
// Check if eval is disabled
if (classes.includes('typst-no-eval')) {
return; // Skip processing, just show the code
}
// Process the typst code block
const processNode = async () => {
let code = codeNode.children[0]?.value || '';
if (!code || code.trim() === '') {
return;
}
// Unescape HTML entities
code = code
.replace(/{/g, '{')
.replace(/}/g, '}');
// Convert smart quotes to straight quotes
code = code.replace(/[\u201C\u201D]/g, '"');
code = code.replace(/[\u2018\u2019]/g, "'");
try {
const svg = await renderTypstToSVG(code, false, true, importsString);
const root = fromHtmlIsomorphic(svg, { fragment: true });
const svgNode = root.children[0];
if (svgNode) {
const height = parseFloat(svgNode.properties['dataHeight'] || '11');
const width = parseFloat(svgNode.properties['dataWidth'] || '11');
const defaultEm = 11;
svgNode.properties.height = `${height / defaultEm}em`;
svgNode.properties.width = `${width / defaultEm}em`;
// Replace the pre node with a div containing the SVG
parent.children[index] = {
type: 'element',
tagName: 'div',
properties: { className: ['typst-display'] },
children: [svgNode]
};
}
} catch (error) {
console.error('Typst rendering error:', error);
codeNode.children = [{
type: 'text',
value: `[Typst Error: ${error.message}]`
}];
}
};
promises.push(processNode());
return;
}
}
}
// Look for inline code with our class markers
if (node.tagName === 'code') {
const classes = node.properties?.className || [];
const isMathInline = classes.includes('typst-math-inline');
const isMathDisplay = classes.includes('typst-math-display');
if (isMathInline || isMathDisplay) {
const processNode = async () => {
let code = node.children[0]?.value || '';
if (!code || code.trim() === '') {
return;
}
// Unescape HTML entities
code = code
.replace(/{/g, '{')
.replace(/}/g, '}');
// Convert smart quotes to straight quotes
code = code.replace(/[\u201C\u201D]/g, '"');
code = code.replace(/[\u2018\u2019]/g, "'");
const isDisplayMode = isMathDisplay;
try {
const svg = await renderTypstToSVG(code, isDisplayMode, false, importsString);
const root = fromHtmlIsomorphic(svg, { fragment: true });
const svgNode = root.children[0];
if (svgNode) {
const height = parseFloat(svgNode.properties['dataHeight'] || '11');
const width = parseFloat(svgNode.properties['dataWidth'] || '11');
const defaultEm = 11;
svgNode.properties.height = `${height / defaultEm}em`;
svgNode.properties.width = `${width / defaultEm}em`;
if (isDisplayMode) {
node.tagName = 'div';
node.properties = { className: ['typst-display'] };
node.children = [svgNode];
} else {
node.tagName = 'span';
node.properties = { className: ['typst-inline'] };
node.children = [svgNode];
}
}
} catch (error) {
console.error('Typst rendering error:', error);
node.children = [{
type: 'text',
value: `[Typst Error: ${error.message}]`
}];
}
};
promises.push(processNode());
}
}
});
await Promise.all(promises);
};
}