pantsdown 2.2.3 → 2.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/renderer.ts CHANGED
@@ -1,258 +1,250 @@
1
1
  import GithubSlugger from "github-slugger";
2
2
  import hljs from "highlight.js";
3
- import katex from "katex";
3
+ import { renderToString } from "katex";
4
4
  import { type Pantsdown } from "./pantsdown.ts";
5
5
  import { inline } from "./rules/inline.ts";
6
6
  import { type HTMLAttrs, type SourceMap, type Tokens } from "./types.ts";
7
7
  import {
8
- cleanUrl,
9
- escape,
10
- fixHtmlLocalImageHref,
11
- fixLocalImageHref,
12
- getHtmlElementText,
13
- injectHtmlAttributes,
8
+ addGithubImageStyles,
9
+ cleanUrl,
10
+ escape,
11
+ fixHtmlLocalImageHref,
12
+ fixLocalImageHref,
13
+ getHtmlElementText,
14
+ injectHtmlAttributes,
14
15
  } from "./utils.ts";
15
16
 
16
17
  /**
17
18
  * An object containing functions to render tokens to HTML.
18
19
  */
19
20
  export class Renderer {
20
- private pantsdown: Pantsdown;
21
- slugger = new GithubSlugger();
22
-
23
- constructor(pantsdown: Pantsdown) {
24
- this.pantsdown = pantsdown;
25
- }
26
-
27
- code(code: string, infostring: string | undefined, sourceMap: SourceMap): string {
28
- const lang = /^\S*/.exec(infostring ?? "")?.[0];
29
- code = code.replace(/\n$/, "");
30
-
31
- const attrs: HTMLAttrs = [];
32
-
33
- if (lang === "mermaid") {
34
- attrs.push(["class", "mermaid-container mermaid"]);
35
- const result = `<pre style="position: relative;">` + code + "\n" + `</pre>`;
36
- return injectHtmlAttributes(result, attrs, sourceMap);
37
- }
38
-
39
- if (lang === "math") {
40
- return this.latexBlock(code, sourceMap);
41
- }
42
-
43
- const language = lang && hljs.getLanguage(lang) ? lang : "plaintext";
44
- code = hljs.highlight(code + "\n", { language }).value;
45
- code = `<code class="hljs language-${escape(language)}">${code}</code>`;
46
-
47
- const result = `<pre style="position: relative;">` + code + `</pre>`;
48
- return injectHtmlAttributes(result, attrs, sourceMap);
49
- }
50
-
51
- alert(body: string, token: Tokens["Alert"]): string {
52
- const result = `<div><span>${token.icon + token.variant}</span>${body}</div>\n`;
53
- return injectHtmlAttributes(result, [
54
- ["class", `markdown-alert markdown-alert-${token.variant.toLowerCase()}`],
55
- ]);
56
- }
57
-
58
- blockquote(quote: string): string {
59
- return `<blockquote>\n${quote}</blockquote>\n`;
60
- }
61
-
62
- html(html: string, _block: boolean, sourceMap?: SourceMap): string {
63
- const result = fixHtmlLocalImageHref(
64
- html,
65
- this.pantsdown.config.renderer.relativeImageUrlPrefix,
66
- );
67
-
68
- const attrs: HTMLAttrs = [];
69
-
70
- if (this.pantsdown.config.renderer.detailsTagDefaultOpen) {
71
- const tag = inline.tag.exec(html);
72
- if (tag?.[0] === "<details>") {
73
- attrs.push(["open", ""]);
74
- }
75
- }
76
-
77
- return injectHtmlAttributes(result, attrs, sourceMap);
78
- }
79
-
80
- heading(text: string, level: number, sourceMap: SourceMap): string {
81
- const elementText = getHtmlElementText(text);
82
- const slug = this.slugger.slug(elementText);
83
- let result = `<h${level}>`;
84
- // span with negative top to add some offset when scrolling to #slug
85
- result += `<span style="position: absolute; top: -50px;" id="${slug}"></span>`;
86
- result += `${text}<a class="anchor octicon-link" href="#${slug}"></a>`;
87
- result += `</h${level}>\n`;
88
- return injectHtmlAttributes(result, [["style", "position: relative;"]], sourceMap);
89
- }
90
-
91
- hr(sourceMap: SourceMap): string {
92
- return injectHtmlAttributes(`<hr>\n`, [], sourceMap);
93
- }
94
-
95
- list(body: string, ordered: boolean, start: number | "", classes: string[] = []): string {
96
- const type = ordered ? "ol" : "ul";
97
- const attrs: HTMLAttrs = [["class", classes.join(" ")]];
98
- if (ordered && start && start !== 1) {
99
- attrs.push(["start", String(start)]);
100
- }
101
- const result = `<${type}>\n${body}</${type}>\n`;
102
- return injectHtmlAttributes(result, attrs);
103
- }
104
-
105
- listitem(text: string, task: boolean, _checked: boolean, sourceMap: SourceMap): string {
106
- const attrs: [string, string][] = [];
107
- if (task) attrs.push(["class", "task-list-item"]);
108
- const result = `<li>${text}</li>\n`;
109
- return injectHtmlAttributes(result, attrs, sourceMap);
110
- }
111
-
112
- checkbox(checked: boolean, classes: string[] = []): string {
113
- const result = "<input>";
114
- const attrs: HTMLAttrs = [
115
- ["disabled", ""],
116
- ["type", "checkbox"],
117
- ["class", classes.join(" ")],
118
- ];
119
- if (checked) attrs.push(["checked", ""]);
120
- return injectHtmlAttributes(result, attrs);
121
- }
122
-
123
- paragraph(text: string, sourceMap: SourceMap): string {
124
- const result = `<p>${text}</p>\n`;
125
- return injectHtmlAttributes(result, [], sourceMap);
126
- }
127
-
128
- table(header: string, body: string): string {
129
- if (body) body = `<tbody>${body}</tbody>`;
130
- return "<table>\n" + "<thead>\n" + header + "</thead>\n" + body + "</table>\n";
131
- }
132
-
133
- tablerow(content: string, sourceMapStart: number | undefined): string {
134
- const sourceMap: SourceMap = sourceMapStart ? [sourceMapStart, sourceMapStart] : undefined;
135
- return injectHtmlAttributes(`<tr>\n${content}</tr>\n`, [], sourceMap);
136
- }
137
-
138
- tablecell(
139
- content: string,
140
- flags: {
141
- header: boolean;
142
- align: "center" | "left" | "right" | null;
143
- },
144
- ): string {
145
- const type = flags.header ? "th" : "td";
146
- const attrs: HTMLAttrs = [];
147
- if (flags.align) attrs.push(["align", flags.align]);
148
- const result = `<${type}>` + content + `</${type}>\n`;
149
- return injectHtmlAttributes(result, attrs);
150
- }
151
-
152
- /**
153
- * span level renderer
154
- */
155
- strong(text: string): string {
156
- return `<strong>${text}</strong>`;
157
- }
158
-
159
- em(text: string): string {
160
- return `<em>${text}</em>`;
161
- }
162
-
163
- codespan(text: string): string {
164
- return `<code>${text}</code>`;
165
- }
166
-
167
- br(): string {
168
- return "<br>";
169
- }
170
-
171
- del(text: string): string {
172
- return `<del>${text}</del>`;
173
- }
174
-
175
- link(href: string, title: string | null | undefined, text: string): string {
176
- const cleanHref = cleanUrl(href);
177
- if (cleanHref === null) {
178
- return text;
179
- }
180
- const attrs: HTMLAttrs = [["href", cleanHref]];
181
- if (title) attrs.push(["title", title]);
182
- return injectHtmlAttributes(`<a>${text}</a>`, attrs);
183
- }
184
-
185
- image(href: string, title: string | null, text: string): string {
186
- const cleanHref = cleanUrl(href);
187
- if (cleanHref === null) {
188
- return text;
189
- }
190
- const attrs: HTMLAttrs = [
191
- [
192
- "src",
193
- fixLocalImageHref(cleanHref, this.pantsdown.config.renderer.relativeImageUrlPrefix),
194
- ],
195
- ["alt", text],
196
- ];
197
- if (title) attrs.push(["title", title]);
198
- return injectHtmlAttributes("<img>", attrs);
199
- }
200
-
201
- footnoteRef(token: Tokens["FootnoteRef"]) {
202
- const encodedLabel = encodeURIComponent(token.label);
203
-
204
- return `<sup><a id="footnote-ref-${encodedLabel}" href="#${
205
- "footnote-" + encodedLabel
206
- }" data-footnote-ref aria-describedby="footnote-label">${token.label}</a></sup>`;
207
- }
208
-
209
- footnotes(token: Tokens["Footnotes"], body: string) {
210
- if (!token.items.length) return "";
211
-
212
- let footnotesHTML = '<section class="footnotes" data-footnotes>\n';
213
- footnotesHTML += `<ol>\n${body}\n</ol>\n`;
214
- footnotesHTML += "</section>\n";
215
-
216
- return footnotesHTML;
217
- }
218
-
219
- text(text: string): string {
220
- return text;
221
- }
222
-
223
- latexBlock(latex: string, sourceMap: SourceMap): string {
224
- try {
225
- const rendered = katex.renderToString(latex, {
226
- displayMode: true,
227
- throwOnError: false,
228
- output: "html",
229
- trust: false,
230
- });
231
- return injectHtmlAttributes(
232
- `<div class="katex-block">${rendered}</div>\n`,
233
- [],
234
- sourceMap,
235
- );
236
- } catch {
237
- return injectHtmlAttributes(
238
- `<div class="katex-block katex-error"><code>${escape(latex)}</code></div>\n`,
239
- [],
240
- sourceMap,
241
- );
242
- }
243
- }
244
-
245
- latexInline(latex: string): string {
246
- try {
247
- const rendered = katex.renderToString(latex, {
248
- displayMode: false,
249
- throwOnError: false,
250
- output: "html",
251
- trust: false,
252
- });
253
- return `<span class="katex-inline">${rendered}</span>`;
254
- } catch {
255
- return `<span class="katex-inline katex-error"><code>${escape(latex)}</code></span>`;
256
- }
257
- }
21
+ private pantsdown: Pantsdown;
22
+ slugger = new GithubSlugger();
23
+
24
+ constructor(pantsdown: Pantsdown) {
25
+ this.pantsdown = pantsdown;
26
+ }
27
+
28
+ code(code: string, infostring: string | undefined, sourceMap: SourceMap): string {
29
+ const lang = /^\S*/.exec(infostring ?? "")?.[0];
30
+ code = code.replace(/\n$/, "");
31
+
32
+ const attrs: HTMLAttrs = [];
33
+
34
+ if (lang === "mermaid") {
35
+ attrs.push(["class", "mermaid-container mermaid"]);
36
+ const result = `<pre style="position: relative;">` + code + "\n" + `</pre>`;
37
+ return injectHtmlAttributes(result, attrs, sourceMap);
38
+ }
39
+
40
+ if (lang === "math") {
41
+ return this.latexBlock(code, sourceMap);
42
+ }
43
+
44
+ const language = lang && hljs.getLanguage(lang) ? lang : "plaintext";
45
+ code = hljs.highlight(code + "\n", { language }).value;
46
+ code = `<code class="hljs language-${escape(language)}">${code}</code>`;
47
+
48
+ const result = `<pre style="position: relative;">` + code + `</pre>`;
49
+ return injectHtmlAttributes(result, attrs, sourceMap);
50
+ }
51
+
52
+ alert(body: string, token: Tokens["Alert"]): string {
53
+ const result = `<div><span>${token.icon + token.variant}</span>${body}</div>\n`;
54
+ return injectHtmlAttributes(result, [
55
+ ["class", `markdown-alert markdown-alert-${token.variant.toLowerCase()}`],
56
+ ]);
57
+ }
58
+
59
+ blockquote(quote: string): string {
60
+ return `<blockquote>\n${quote}</blockquote>\n`;
61
+ }
62
+
63
+ html(html: string, _block: boolean, sourceMap?: SourceMap): string {
64
+ let result = fixHtmlLocalImageHref(html, this.pantsdown.config);
65
+ result = addGithubImageStyles(result);
66
+
67
+ const attrs: HTMLAttrs = [];
68
+
69
+ if (this.pantsdown.config.renderer.detailsTagDefaultOpen) {
70
+ const tag = inline.tag.exec(html);
71
+ if (tag?.[0] === "<details>") {
72
+ attrs.push(["open", ""]);
73
+ }
74
+ }
75
+
76
+ return injectHtmlAttributes(result, attrs, sourceMap);
77
+ }
78
+
79
+ heading(text: string, level: number, sourceMap: SourceMap): string {
80
+ const elementText = getHtmlElementText(text);
81
+ const slug = this.slugger.slug(elementText);
82
+ let result = `<h${level}>`;
83
+ // span with negative top to add some offset when scrolling to #slug
84
+ result += `<span style="position: absolute; top: -50px;" id="${slug}"></span>`;
85
+ result += `${text}<a class="anchor octicon-link" href="#${slug}"></a>`;
86
+ result += `</h${level}>\n`;
87
+ return injectHtmlAttributes(result, [["style", "position: relative;"]], sourceMap);
88
+ }
89
+
90
+ hr(sourceMap: SourceMap): string {
91
+ return injectHtmlAttributes(`<hr>\n`, [], sourceMap);
92
+ }
93
+
94
+ list(body: string, ordered: boolean, start: number | "", classes: string[] = []): string {
95
+ const type = ordered ? "ol" : "ul";
96
+ const attrs: HTMLAttrs = [["class", classes.join(" ")]];
97
+ if (ordered && start && start !== 1) {
98
+ attrs.push(["start", String(start)]);
99
+ }
100
+ const result = `<${type}>\n${body}</${type}>\n`;
101
+ return injectHtmlAttributes(result, attrs);
102
+ }
103
+
104
+ listitem(text: string, task: boolean, _checked: boolean, sourceMap: SourceMap): string {
105
+ const attrs: [string, string][] = [];
106
+ if (task) attrs.push(["class", "task-list-item"]);
107
+ const result = `<li>${text}</li>\n`;
108
+ return injectHtmlAttributes(result, attrs, sourceMap);
109
+ }
110
+
111
+ checkbox(checked: boolean, classes: string[] = []): string {
112
+ const result = "<input>";
113
+ const attrs: HTMLAttrs = [
114
+ ["disabled", ""],
115
+ ["type", "checkbox"],
116
+ ["class", classes.join(" ")],
117
+ ];
118
+ if (checked) attrs.push(["checked", ""]);
119
+ return injectHtmlAttributes(result, attrs);
120
+ }
121
+
122
+ paragraph(text: string, sourceMap: SourceMap): string {
123
+ const result = `<p>${text}</p>\n`;
124
+ return injectHtmlAttributes(result, [], sourceMap);
125
+ }
126
+
127
+ table(header: string, body: string): string {
128
+ if (body) body = `<tbody>${body}</tbody>`;
129
+ return "<table>\n" + "<thead>\n" + header + "</thead>\n" + body + "</table>\n";
130
+ }
131
+
132
+ tablerow(content: string, sourceMapStart: number | undefined): string {
133
+ const sourceMap: SourceMap = sourceMapStart ? [sourceMapStart, sourceMapStart] : undefined;
134
+ return injectHtmlAttributes(`<tr>\n${content}</tr>\n`, [], sourceMap);
135
+ }
136
+
137
+ tablecell(
138
+ content: string,
139
+ flags: {
140
+ header: boolean;
141
+ align: "center" | "left" | "right" | null;
142
+ },
143
+ ): string {
144
+ const type = flags.header ? "th" : "td";
145
+ const attrs: HTMLAttrs = [];
146
+ if (flags.align) attrs.push(["align", flags.align]);
147
+ const result = `<${type}>` + content + `</${type}>\n`;
148
+ return injectHtmlAttributes(result, attrs);
149
+ }
150
+
151
+ /**
152
+ * span level renderer
153
+ */
154
+ strong(text: string): string {
155
+ return `<strong>${text}</strong>`;
156
+ }
157
+
158
+ em(text: string): string {
159
+ return `<em>${text}</em>`;
160
+ }
161
+
162
+ codespan(text: string): string {
163
+ return `<code>${text}</code>`;
164
+ }
165
+
166
+ br(): string {
167
+ return "<br>";
168
+ }
169
+
170
+ del(text: string): string {
171
+ return `<del>${text}</del>`;
172
+ }
173
+
174
+ link(href: string, title: string | null | undefined, text: string): string {
175
+ const cleanHref = cleanUrl(href);
176
+ if (cleanHref === null) {
177
+ return text;
178
+ }
179
+ const attrs: HTMLAttrs = [["href", cleanHref]];
180
+ if (title) attrs.push(["title", title]);
181
+ return injectHtmlAttributes(`<a>${text}</a>`, attrs);
182
+ }
183
+
184
+ image(href: string, title: string | null, text: string): string {
185
+ const cleanHref = cleanUrl(href);
186
+ if (cleanHref === null) {
187
+ return text;
188
+ }
189
+ const attrs: HTMLAttrs = [
190
+ ["src", fixLocalImageHref(cleanHref, this.pantsdown.config)],
191
+ ["alt", text],
192
+ ];
193
+ if (title) attrs.push(["title", title]);
194
+ return injectHtmlAttributes("<img>", attrs);
195
+ }
196
+
197
+ footnoteRef(token: Tokens["FootnoteRef"]) {
198
+ const encodedLabel = encodeURIComponent(token.label);
199
+
200
+ return `<sup><a id="footnote-ref-${encodedLabel}" href="#${
201
+ "footnote-" + encodedLabel
202
+ }" data-footnote-ref aria-describedby="footnote-label">${token.label}</a></sup>`;
203
+ }
204
+
205
+ footnotes(token: Tokens["Footnotes"], body: string) {
206
+ if (!token.items.length) return "";
207
+
208
+ let footnotesHTML = '<section class="footnotes" data-footnotes>\n';
209
+ footnotesHTML += `<ol>\n${body}\n</ol>\n`;
210
+ footnotesHTML += "</section>\n";
211
+
212
+ return footnotesHTML;
213
+ }
214
+
215
+ text(text: string): string {
216
+ return text;
217
+ }
218
+
219
+ latexBlock(latex: string, sourceMap: SourceMap): string {
220
+ try {
221
+ const rendered = renderToString(latex, {
222
+ displayMode: true,
223
+ throwOnError: false,
224
+ output: "html",
225
+ trust: false,
226
+ });
227
+ return injectHtmlAttributes(`<div class="katex-block">${rendered}</div>\n`, [], sourceMap);
228
+ } catch {
229
+ return injectHtmlAttributes(
230
+ `<div class="katex-block katex-error"><code>${escape(latex)}</code></div>\n`,
231
+ [],
232
+ sourceMap,
233
+ );
234
+ }
235
+ }
236
+
237
+ latexInline(latex: string): string {
238
+ try {
239
+ const rendered = renderToString(latex, {
240
+ displayMode: false,
241
+ throwOnError: false,
242
+ output: "html",
243
+ trust: false,
244
+ });
245
+ return `<span class="katex-inline">${rendered}</span>`;
246
+ } catch {
247
+ return `<span class="katex-inline katex-error"><code>${escape(latex)}</code></span>`;
248
+ }
249
+ }
258
250
  }