feat: Send token objects to renderers (#3291)

BREAKING CHANGE: extensions that change marked renderers will need to be updated and use new option `useNewRenderer`
This commit is contained in:
Tony Brix
2024-06-12 00:00:22 -06:00
committed by GitHub
parent 7ab818502e
commit 1ce59ea827
13 changed files with 820 additions and 537 deletions
+53 -56
View File
@@ -68,16 +68,16 @@ import { marked } from 'marked';
// Override function
const renderer = {
heading(text, level) {
heading({ text, depth }) {
const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
return `
<h${level}>
<h${depth}>
<a name="${escapedText}" class="anchor" href="#${escapedText}">
<span class="header-link"></span>
</a>
${text}
</h${level}>`;
</h${depth}>`;
}
};
@@ -97,7 +97,7 @@ console.log(marked.parse('# heading+'));
heading+
</h1>
```
**Note:** Calling `marked.use()` in the following way will avoid overriding the `heading` token output but create a new renderer in the process.
**Note:** Calling `marked.use()` in the following way will avoid overriding the `heading` token output but create a new `heading` renderer in the process.
```js
marked.use({
@@ -112,38 +112,32 @@ marked.use({
### Block-level renderer methods
- <code>**code**(*string* code, *string* infostring, *boolean* escaped)</code>
- <code>**blockquote**(*string* quote)</code>
- <code>**html**(*string* html, *boolean* block)</code>
- <code>**heading**(*string* text, *number* level, *string* raw)</code>
- <code>**hr**()</code>
- <code>**list**(*string* body, *boolean* ordered, *number* start)</code>
- <code>**listitem**(*string* text, *boolean* task, *boolean* checked)</code>
- <code>**checkbox**(*boolean* checked)</code>
- <code>**paragraph**(*string* text)</code>
- <code>**table**(*string* header, *string* body)</code>
- <code>**tablerow**(*string* content)</code>
- <code>**tablecell**(*string* content, *object* flags)</code>
- <code>**space**(token: *Tokens.Space*): *string*</code>
- <code>**code**(token: *Tokens.Code*): *string*</code>
- <code>**blockquote**(token: *Tokens.Blockquote*): *string*</code>
- <code>**html**(token: *Tokens.HTML | Tokens.Tag*): *string*</code>
- <code>**heading**(token: *Tokens.Heading*): *string*</code>
- <code>**hr**(token: *Tokens.Hr*): *string*</code>
- <code>**list**(token: *Tokens.List*): *string*</code>
- <code>**listitem**(token: *Tokens.ListItem*): *string*</code>
- <code>**checkbox**(token: *Tokens.Checkbox*): *string*</code>
- <code>**paragraph**(token: *Tokens.Paragraph*): *string*</code>
- <code>**table**(token: *Tokens.Table*): *string*</code>
- <code>**tablerow**(token: *Tokens.TableRow*): *string*</code>
- <code>**tablecell**(token: *Tokens.TableCell*): *string*</code>
### Inline-level renderer methods
- <code>**strong**(*string* text)</code>
- <code>**em**(*string* text)</code>
- <code>**codespan**(*string* code)</code>
- <code>**br**()</code>
- <code>**del**(*string* text)</code>
- <code>**link**(*string* href, *string* title, *string* text)</code>
- <code>**image**(*string* href, *string* title, *string* text)</code>
- <code>**text**(*string* text)</code>
- <code>**strong**(token: *Tokens.Strong*): *string*</code>
- <code>**em**(token: *Tokens.Em*): *string*</code>
- <code>**codespan**(token: *Tokens.Codespan*): *string*</code>
- <code>**br**(token: *Tokens.Br*): *string*</code>
- <code>**del**(token: *Tokens.Del*): *string*</code>
- <code>**link**(token: *Tokens.Link*): *string*</code>
- <code>**image**(token: *Tokens.Image*): *string*</code>
- <code>**text**(token: *Tokens.Text | Tokens.Escape | Tokens.Tag*): *string*</code>
`flags` has the following properties:
```js
{
header: true || false,
align: 'center' || 'left' || 'right'
}
```
The Tokens.* properties can be found [here](https://github.com/markedjs/marked/blob/master/src/Tokens.ts).
***
@@ -192,33 +186,35 @@ console.log(marked.parse('$ latex code $\n\n` other code `'));
### Block level tokenizer methods
- <code>**space**(*string* src)</code>
- <code>**code**(*string* src)</code>
- <code>**fences**(*string* src)</code>
- <code>**heading**(*string* src)</code>
- <code>**hr**(*string* src)</code>
- <code>**blockquote**(*string* src)</code>
- <code>**list**(*string* src)</code>
- <code>**html**(*string* src)</code>
- <code>**def**(*string* src)</code>
- <code>**table**(*string* src)</code>
- <code>**lheading**(*string* src)</code>
- <code>**paragraph**(*string* src)</code>
- <code>**text**(*string* src)</code>
- <code>**space**(src: *string*): *Tokens.Space*</code>
- <code>**code**(src: *string*): *Tokens.Code*</code>
- <code>**fences**(src: *string*): *Tokens.Code*</code>
- <code>**heading**(src: *string*): *Tokens.Heading*</code>
- <code>**hr**(src: *string*): *Tokens.Hr*</code>
- <code>**blockquote**(src: *string*): *Tokens.Blockquote*</code>
- <code>**list**(src: *string*): *Tokens.List*</code>
- <code>**html**(src: *string*): *Tokens.HTML*</code>
- <code>**def**(src: *string*): *Tokens.Def*</code>
- <code>**table**(src: *string*): *Tokens.Table*</code>
- <code>**lheading**(src: *string*): *Tokens.Heading*</code>
- <code>**paragraph**(src: *string*): *Tokens.Paragraph*</code>
- <code>**text**(src: *string*): *Tokens.Text*</code>
### Inline level tokenizer methods
- <code>**escape**(*string* src)</code>
- <code>**tag**(*string* src)</code>
- <code>**link**(*string* src)</code>
- <code>**reflink**(*string* src, *object* links)</code>
- <code>**emStrong**(*string* src, *string* maskedSrc, *string* prevChar)</code>
- <code>**codespan**(*string* src)</code>
- <code>**br**(*string* src)</code>
- <code>**del**(*string* src)</code>
- <code>**autolink**(*string* src)</code>
- <code>**url**(*string* src)</code>
- <code>**inlineText**(*string* src)</code>
- <code>**escape**(src: *string*): *Tokens.Escape*</code>
- <code>**tag**(src: *string*): *Tokens.Tag*</code>
- <code>**link**(src: *string*): *Tokens.Link | Tokens.Image*</code>
- <code>**reflink**(src: *string*, links: *object*): *Tokens.Link | Tokens.Image | Tokens.Text*</code>
- <code>**emStrong**(src: *string*, maskedSrc: *string*, prevChar: *string*): *Tokens.Em | Tokens.Strong*</code>
- <code>**codespan**(src: *string*): *Tokens.Codespan*</code>
- <code>**br**(src: *string*): *Tokens.Br*</code>
- <code>**del**(src: *string*): *Tokens.Del*</code>
- <code>**autolink**(src: *string*): *Tokens.Link*</code>
- <code>**url**(src: *string*): *Tokens.Link*</code>
- <code>**inlineText**(src: *string*): *Tokens.Text*</code>
The Tokens.* properties can be found [here](https://github.com/markedjs/marked/blob/master/src/Tokens.ts).
***
@@ -263,6 +259,7 @@ Hooks are methods that hook into some part of marked. The following hooks are av
|-----------|-------------|
| `preprocess(markdown: string): string` | Process markdown before sending it to marked. |
| `postprocess(html: string): string` | Process html after marked has finished parsing. |
| `processAllTokens(tokens: Token[]): Token[]` | Process all tokens before walk tokens. |
`marked.use()` can be called multiple times with different `hooks` functions. Each function will be called in order, starting with the function that was assigned *last*.
+214 -245
View File
File diff suppressed because it is too large Load Diff
+253 -4
View File
@@ -6,7 +6,8 @@ import { _Renderer } from './Renderer.ts';
import { _Tokenizer } from './Tokenizer.ts';
import { _TextRenderer } from './TextRenderer.ts';
import {
escape
escape,
unescape
} from './helpers.ts';
import type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';
import type { Token, Tokens, TokensList } from './Tokens.ts';
@@ -146,15 +147,19 @@ export class Marked {
if (!(prop in renderer)) {
throw new Error(`renderer '${prop}' does not exist`);
}
if (prop === 'options') {
if (['options', 'parser'].includes(prop)) {
// ignore options property
continue;
}
const rendererProp = prop as Exclude<keyof _Renderer, 'options'>;
const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;
const rendererProp = prop as Exclude<keyof _Renderer, 'options' | 'parser'>;
let rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;
const prevRenderer = renderer[rendererProp] as GenericRendererFunction;
// Replace renderer with func to run extension, but fall back if false
renderer[rendererProp] = (...args: unknown[]) => {
if (!pack.useNewRenderer) {
// TODO: Remove this in next major version
rendererFunc = this.#convertRendererFunction(rendererFunc, rendererProp, renderer) as GenericRendererFunction;
}
let ret = rendererFunc.apply(renderer, args);
if (ret === false) {
ret = prevRenderer.apply(renderer, args);
@@ -250,6 +255,250 @@ export class Marked {
return this;
}
// TODO: Remove this in next major release
#convertRendererFunction(func: GenericRendererFunction, prop: string, renderer: _Renderer) {
switch (prop) {
case 'heading':
return function(token: Tokens.Heading) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(
renderer.parser.parseInline(token.tokens),
token.depth,
unescape(renderer.parser.parseInline(token.tokens, renderer.parser.textRenderer))
);
};
case 'code':
return function(token: Tokens.Code) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(
token.text,
token.lang,
!!token.escaped
);
};
case 'table':
return function(this: _Renderer, token: Tokens.Table) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
let header = '';
// header
let cell = '';
for (let j = 0; j < token.header.length; j++) {
cell += this.tablecell(
{
text: token.header[j].text,
tokens: token.header[j].tokens,
header: true,
align: token.align[j]
}
);
}
header += this.tablerow({ text: cell });
let body = '';
for (let j = 0; j < token.rows.length; j++) {
const row = token.rows[j];
cell = '';
for (let k = 0; k < row.length; k++) {
cell += this.tablecell(
{
text: row[k].text,
tokens: row[k].tokens,
header: false,
align: token.align[k]
}
);
}
body += this.tablerow({ text: cell });
}
return func(header, body);
};
case 'blockquote':
return function(this: _Renderer, token: Tokens.Blockquote) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
const body = this.parser.parse(token.tokens);
return func(body);
};
case 'list':
return function(this: _Renderer, token: Tokens.List) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
const ordered = token.ordered;
const start = token.start;
const loose = token.loose;
let body = '';
for (let j = 0; j < token.items.length; j++) {
const item = token.items[j];
const checked = item.checked;
const task = item.task;
let itemBody = '';
if (item.task) {
const checkbox = this.checkbox({ checked: !!checked });
if (loose) {
if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
}
} else {
item.tokens.unshift({
type: 'text',
text: checkbox + ' '
} as Tokens.Text);
}
} else {
itemBody += checkbox + ' ';
}
}
itemBody += this.parser.parse(item.tokens, loose);
body += this.listitem({
type: 'list_item',
raw: itemBody,
text: itemBody,
task,
checked: !!checked,
loose,
tokens: item.tokens
});
}
return func(body, ordered, start);
};
case 'html':
return function(token: Tokens.HTML) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(token.text, token.block);
};
case 'paragraph':
return function(this: _Renderer, token: Tokens.Paragraph) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(this.parser.parseInline(token.tokens));
};
case 'escape':
return function(token: Tokens.Escape) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(token.text);
};
case 'link':
return function(this: _Renderer, token: Tokens.Link) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(token.href, token.title, this.parser.parseInline(token.tokens));
};
case 'image':
return function(token: Tokens.Image) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(token.href, token.title, token.text);
};
case 'strong':
return function(this: _Renderer, token: Tokens.Strong) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(this.parser.parseInline(token.tokens));
};
case 'em':
return function(this: _Renderer, token: Tokens.Em) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(this.parser.parseInline(token.tokens));
};
case 'codespan':
return function(token: Tokens.Codespan) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(token.text);
};
case 'del':
return function(this: _Renderer, token: Tokens.Del) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(this.parser.parseInline(token.tokens));
};
case 'text':
return function(token: Tokens.Text) {
if (!token.type || token.type !== prop) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
return func.apply(this, arguments);
}
return func(token.text);
};
default:
// do nothing
}
return func;
}
setOptions(opt: MarkedOptions) {
this.defaults = { ...this.defaults, ...opt };
return this;
+8 -2
View File
@@ -39,7 +39,7 @@ type HooksObject = {
[K in keyof HooksApi]?: (...args: Parameters<HooksApi[K]>) => ReturnType<HooksApi[K]> | Promise<ReturnType<HooksApi[K]>>
};
type RendererApi = Omit<_Renderer, 'constructor' | 'options'>;
type RendererApi = Omit<_Renderer, 'constructor' | 'options' | 'parser'>;
type RendererObject = {
[K in keyof RendererApi]?: (...args: Parameters<RendererApi[K]>) => ReturnType<RendererApi[K]> | false
};
@@ -109,9 +109,15 @@ export interface MarkedExtension {
* The return value of the function is ignored.
*/
walkTokens?: ((token: Token) => void | Promise<void>) | undefined | null;
/**
* Use the new renderer that accepts an object instead of individual parameters.
* This option will be removed and default to true in the next major version.
*/
useNewRenderer?: boolean | undefined;
}
export interface MarkedOptions extends Omit<MarkedExtension, 'hooks' | 'renderer' | 'tokenizer' | 'extensions' | 'walkTokens'> {
export interface MarkedOptions extends Omit<MarkedExtension, 'useNewRenderer' | 'hooks' | 'renderer' | 'tokenizer' | 'extensions' | 'walkTokens'> {
/**
* Hooks are methods that hook into some part of marked.
*/
+46 -116
View File
@@ -1,10 +1,7 @@
import { _Renderer } from './Renderer.ts';
import { _TextRenderer } from './TextRenderer.ts';
import { _defaults } from './defaults.ts';
import {
unescape
} from './helpers.ts';
import type { Token, Tokens } from './Tokens.ts';
import type { MarkedToken, Token, Tokens } from './Tokens.ts';
import type { MarkedOptions } from './MarkedOptions.ts';
/**
@@ -19,6 +16,7 @@ export class _Parser {
this.options.renderer = this.options.renderer || new _Renderer();
this.renderer = this.options.renderer;
this.renderer.options = this.options;
this.renderer.parser = this;
this.textRenderer = new _TextRenderer();
}
@@ -45,11 +43,11 @@ export class _Parser {
let out = '';
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
const anyToken = tokens[i];
// Run any renderer extensions
if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
const genericToken = token as Tokens.Generic;
if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
const genericToken = anyToken as Tokens.Generic;
const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) {
out += ret || '';
@@ -57,123 +55,62 @@ export class _Parser {
}
}
const token = anyToken as MarkedToken;
switch (token.type) {
case 'space': {
out += this.renderer.space(token);
continue;
}
case 'hr': {
out += this.renderer.hr();
out += this.renderer.hr(token);
continue;
}
case 'heading': {
const headingToken = token as Tokens.Heading;
out += this.renderer.heading(
this.parseInline(headingToken.tokens),
headingToken.depth,
unescape(this.parseInline(headingToken.tokens, this.textRenderer)));
out += this.renderer.heading(token);
continue;
}
case 'code': {
const codeToken = token as Tokens.Code;
out += this.renderer.code(codeToken.text,
codeToken.lang,
!!codeToken.escaped);
out += this.renderer.code(token);
continue;
}
case 'table': {
const tableToken = token as Tokens.Table;
let header = '';
// header
let cell = '';
for (let j = 0; j < tableToken.header.length; j++) {
cell += this.renderer.tablecell(
this.parseInline(tableToken.header[j].tokens),
{ header: true, align: tableToken.align[j] }
);
}
header += this.renderer.tablerow(cell);
let body = '';
for (let j = 0; j < tableToken.rows.length; j++) {
const row = tableToken.rows[j];
cell = '';
for (let k = 0; k < row.length; k++) {
cell += this.renderer.tablecell(
this.parseInline(row[k].tokens),
{ header: false, align: tableToken.align[k] }
);
}
body += this.renderer.tablerow(cell);
}
out += this.renderer.table(header, body);
out += this.renderer.table(token);
continue;
}
case 'blockquote': {
const blockquoteToken = token as Tokens.Blockquote;
const body = this.parse(blockquoteToken.tokens);
out += this.renderer.blockquote(body);
out += this.renderer.blockquote(token);
continue;
}
case 'list': {
const listToken = token as Tokens.List;
const ordered = listToken.ordered;
const start = listToken.start;
const loose = listToken.loose;
let body = '';
for (let j = 0; j < listToken.items.length; j++) {
const item = listToken.items[j];
const checked = item.checked;
const task = item.task;
let itemBody = '';
if (item.task) {
const checkbox = this.renderer.checkbox(!!checked);
if (loose) {
if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
}
} else {
item.tokens.unshift({
type: 'text',
text: checkbox + ' '
} as Tokens.Text);
}
} else {
itemBody += checkbox + ' ';
}
}
itemBody += this.parse(item.tokens, loose);
body += this.renderer.listitem(itemBody, task, !!checked);
}
out += this.renderer.list(body, ordered, start);
out += this.renderer.list(token);
continue;
}
case 'html': {
const htmlToken = token as Tokens.HTML;
out += this.renderer.html(htmlToken.text, htmlToken.block);
out += this.renderer.html(token);
continue;
}
case 'paragraph': {
const paragraphToken = token as Tokens.Paragraph;
out += this.renderer.paragraph(this.parseInline(paragraphToken.tokens));
out += this.renderer.paragraph(token);
continue;
}
case 'text': {
let textToken = token as Tokens.Text;
let body = textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text;
let textToken = token;
let body = this.renderer.text(textToken);
while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {
textToken = tokens[++i] as Tokens.Text;
body += '\n' + (textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text);
textToken = tokens[++i] as Tokens.Text | Tokens.Tag;
body += '\n' + this.renderer.text(textToken);
}
if (top) {
out += this.renderer.paragraph({
type: 'paragraph',
raw: body,
text: body,
tokens: [{ type: 'text', raw: body, text: body }]
});
} else {
out += body;
}
out += top ? this.renderer.paragraph(body) : body;
continue;
}
@@ -200,65 +137,58 @@ export class _Parser {
let out = '';
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
const anyToken = tokens[i];
// Run any renderer extensions
if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
const ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) {
if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {
out += ret || '';
continue;
}
}
const token = anyToken as MarkedToken;
switch (token.type) {
case 'escape': {
const escapeToken = token as Tokens.Escape;
out += renderer.text(escapeToken.text);
out += renderer.text(token);
break;
}
case 'html': {
const tagToken = token as Tokens.Tag;
out += renderer.html(tagToken.text);
out += renderer.html(token);
break;
}
case 'link': {
const linkToken = token as Tokens.Link;
out += renderer.link(linkToken.href, linkToken.title, this.parseInline(linkToken.tokens, renderer));
out += renderer.link(token);
break;
}
case 'image': {
const imageToken = token as Tokens.Image;
out += renderer.image(imageToken.href, imageToken.title, imageToken.text);
out += renderer.image(token);
break;
}
case 'strong': {
const strongToken = token as Tokens.Strong;
out += renderer.strong(this.parseInline(strongToken.tokens, renderer));
out += renderer.strong(token);
break;
}
case 'em': {
const emToken = token as Tokens.Em;
out += renderer.em(this.parseInline(emToken.tokens, renderer));
out += renderer.em(token);
break;
}
case 'codespan': {
const codespanToken = token as Tokens.Codespan;
out += renderer.codespan(codespanToken.text);
out += renderer.codespan(token);
break;
}
case 'br': {
out += renderer.br();
out += renderer.br(token);
break;
}
case 'del': {
const delToken = token as Tokens.Del;
out += renderer.del(this.parseInline(delToken.tokens, renderer));
out += renderer.del(token);
break;
}
case 'text': {
const textToken = token as Tokens.Text;
out += renderer.text(textToken.text);
out += renderer.text(token);
break;
}
default: {
+101 -43
View File
@@ -4,72 +4,131 @@ import {
escape
} from './helpers.ts';
import type { MarkedOptions } from './MarkedOptions.ts';
import type { Tokens } from './Tokens.ts';
import type { _Parser } from './Parser.ts';
/**
* Renderer
*/
export class _Renderer {
options: MarkedOptions;
parser!: _Parser; // set by the parser
constructor(options?: MarkedOptions) {
this.options = options || _defaults;
}
code(code: string, infostring: string | undefined, escaped: boolean): string {
const lang = (infostring || '').match(/^\S*/)?.[0];
space(token: Tokens.Space): string {
return '';
}
code = code.replace(/\n$/, '') + '\n';
code({ text, lang, escaped }: Tokens.Code): string {
const langString = (lang || '').match(/^\S*/)?.[0];
if (!lang) {
const code = text.replace(/\n$/, '') + '\n';
if (!langString) {
return '<pre><code>'
+ (escaped ? code : escape(code, true))
+ '</code></pre>\n';
}
return '<pre><code class="language-'
+ escape(lang)
+ escape(langString)
+ '">'
+ (escaped ? code : escape(code, true))
+ '</code></pre>\n';
}
blockquote(quote: string): string {
return `<blockquote>\n${quote}</blockquote>\n`;
blockquote({ tokens }: Tokens.Blockquote): string {
const body = this.parser.parse(tokens);
return `<blockquote>\n${body}</blockquote>\n`;
}
html(html: string, block?: boolean) : string {
return html;
html({ text }: Tokens.HTML | Tokens.Tag) : string {
return text;
}
heading(text: string, level: number, raw: string): string {
// ignore IDs
return `<h${level}>${text}</h${level}>\n`;
heading({ tokens, depth }: Tokens.Heading): string {
return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\n`;
}
hr(): string {
hr(token: Tokens.Hr): string {
return '<hr>\n';
}
list(body: string, ordered: boolean, start: number | ''): string {
list(token: Tokens.List): string {
const ordered = token.ordered;
const start = token.start;
let body = '';
for (let j = 0; j < token.items.length; j++) {
const item = token.items[j];
body += this.listitem(item);
}
const type = ordered ? 'ol' : 'ul';
const startatt = (ordered && start !== 1) ? (' start="' + start + '"') : '';
return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : '';
return '<' + type + startAttr + '>\n' + body + '</' + type + '>\n';
}
listitem(text: string, task: boolean, checked: boolean): string {
return `<li>${text}</li>\n`;
listitem(item: Tokens.ListItem): string {
let itemBody = '';
if (item.task) {
const checkbox = this.checkbox({ checked: !!item.checked });
if (item.loose) {
if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
}
} else {
item.tokens.unshift({
type: 'text',
raw: checkbox + ' ',
text: checkbox + ' '
});
}
} else {
itemBody += checkbox + ' ';
}
}
itemBody += this.parser.parse(item.tokens, !!item.loose);
return `<li>${itemBody}</li>\n`;
}
checkbox(checked: boolean): string {
checkbox({ checked }: Tokens.Checkbox): string {
return '<input '
+ (checked ? 'checked="" ' : '')
+ 'disabled="" type="checkbox">';
}
paragraph(text: string): string {
return `<p>${text}</p>\n`;
paragraph({ tokens }: Tokens.Paragraph): string {
return `<p>${this.parser.parseInline(tokens)}</p>\n`;
}
table(header: string, body: string): string {
table(token: Tokens.Table): string {
let header = '';
// header
let cell = '';
for (let j = 0; j < token.header.length; j++) {
cell += this.tablecell(token.header[j]);
}
header += this.tablerow({ text: cell });
let body = '';
for (let j = 0; j < token.rows.length; j++) {
const row = token.rows[j];
cell = '';
for (let k = 0; k < row.length; k++) {
cell += this.tablecell(row[k]);
}
body += this.tablerow({ text: cell });
}
if (body) body = `<tbody>${body}</tbody>`;
return '<table>\n'
@@ -80,17 +139,15 @@ export class _Renderer {
+ '</table>\n';
}
tablerow(content: string): string {
return `<tr>\n${content}</tr>\n`;
tablerow({ text }: Tokens.TableRow): string {
return `<tr>\n${text}</tr>\n`;
}
tablecell(content: string, flags: {
header: boolean;
align: 'center' | 'left' | 'right' | null;
}): string {
const type = flags.header ? 'th' : 'td';
const tag = flags.align
? `<${type} align="${flags.align}">`
tablecell(token: Tokens.TableCell): string {
const content = this.parser.parseInline(token.tokens);
const type = token.header ? 'th' : 'td';
const tag = token.align
? `<${type} align="${token.align}">`
: `<${type}>`;
return tag + content + `</${type}>\n`;
}
@@ -98,27 +155,28 @@ export class _Renderer {
/**
* span level renderer
*/
strong(text: string): string {
return `<strong>${text}</strong>`;
strong({ tokens }: Tokens.Strong): string {
return `<strong>${this.parser.parseInline(tokens)}</strong>`;
}
em(text: string): string {
return `<em>${text}</em>`;
em({ tokens }: Tokens.Em): string {
return `<em>${this.parser.parseInline(tokens)}</em>`;
}
codespan(text: string): string {
codespan({ text }: Tokens.Codespan): string {
return `<code>${text}</code>`;
}
br(): string {
br(token: Tokens.Br): string {
return '<br>';
}
del(text: string): string {
return `<del>${text}</del>`;
del({ tokens }: Tokens.Del): string {
return `<del>${this.parser.parseInline(tokens)}</del>`;
}
link(href: string, title: string | null | undefined, text: string): string {
link({ href, title, tokens }: Tokens.Link): string {
const text = this.parser.parseInline(tokens);
const cleanHref = cleanUrl(href);
if (cleanHref === null) {
return text;
@@ -132,7 +190,7 @@ export class _Renderer {
return out;
}
image(href: string, title: string | null, text: string): string {
image({ href, title, text }: Tokens.Image): string {
const cleanHref = cleanUrl(href);
if (cleanHref === null) {
return text;
@@ -147,7 +205,7 @@ export class _Renderer {
return out;
}
text(text: string) : string {
return text;
text(token: Tokens.Text | Tokens.Escape | Tokens.Tag) : string {
return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;
}
}
+10 -8
View File
@@ -1,38 +1,40 @@
import type { Tokens } from './Tokens.ts';
/**
* TextRenderer
* returns only the textual part of the token
*/
export class _TextRenderer {
// no need for block level renderers
strong(text: string) {
strong({ text }: Tokens.Strong) {
return text;
}
em(text: string) {
em({ text }: Tokens.Em) {
return text;
}
codespan(text: string) {
codespan({ text }: Tokens.Codespan) {
return text;
}
del(text: string) {
del({ text }: Tokens.Del) {
return text;
}
html(text: string) {
html({ text }: Tokens.HTML | Tokens.Tag) {
return text;
}
text(text: string) {
text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag) {
return text;
}
link(href: string, title: string | null | undefined, text: string) {
link({ text }: Tokens.Link) {
return '' + text;
}
image(href: string, title: string | null, text: string) {
image({ text }: Tokens.Image) {
return '' + text;
}
+9 -5
View File
@@ -503,18 +503,22 @@ export class _Tokenizer {
}
}
for (const header of headers) {
for (let i = 0; i < headers.length; i++) {
item.header.push({
text: header,
tokens: this.lexer.inline(header)
text: headers[i],
tokens: this.lexer.inline(headers[i]),
header: true,
align: item.align[i]
});
}
for (const row of rows) {
item.rows.push(splitCells(row, item.header.length).map(cell => {
item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
return {
text: cell,
tokens: this.lexer.inline(cell)
tokens: this.lexer.inline(cell),
header: false,
align: item.align[i]
};
}));
}
+16 -2
View File
@@ -1,5 +1,6 @@
/* eslint-disable no-use-before-define */
export type Token = (
export type MarkedToken = (
Tokens.Space
| Tokens.Code
| Tokens.Heading
@@ -20,7 +21,10 @@ export type Token = (
| Tokens.Em
| Tokens.Codespan
| Tokens.Br
| Tokens.Del
| Tokens.Del);
export type Token = (
MarkedToken
| Tokens.Generic);
export namespace Tokens {
@@ -54,9 +58,15 @@ export namespace Tokens {
rows: TableCell[][];
}
export interface TableRow {
text: string;
}
export interface TableCell {
text: string;
tokens: Token[];
header: boolean;
align: 'center' | 'left' | 'right' | null;
}
export interface Hr {
@@ -90,6 +100,10 @@ export namespace Tokens {
tokens: Token[];
}
export interface Checkbox {
checked: boolean;
}
export interface Paragraph {
type: 'paragraph';
raw: string;
+26 -25
View File
@@ -64,6 +64,7 @@ console.log(marked.parseInline('9) I am using __markdown__.'));
console.log(marked.parseInline('10) I am using __markdown__.', options));
const text = 'Something';
const raw = 'Raw';
const tokens: TokensList = marked.lexer(text, options);
console.log(marked.parser(tokens));
@@ -79,8 +80,8 @@ const re: Record<string, Record<string, Record<string, RegExp>>> = marked.Lexer.
const lexerOptions: MarkedOptions = lexer.options;
const renderer = new marked.Renderer();
renderer.heading = (text, level, raw) => {
return text + level.toString();
renderer.heading = ({ text, depth }) => {
return text + depth.toString();
};
renderer.hr = () => {
return `<hr>\n`;
@@ -90,31 +91,31 @@ renderer.checkbox = checked => {
};
class ExtendedRenderer extends marked.Renderer {
code = (code: string, language: string | undefined, isEscaped: boolean): string => super.code(code, language, isEscaped);
blockquote = (quote: string): string => super.blockquote(quote);
html = (html: string): string => super.html(html);
heading = (text: string, level: 1 | 2 | 3 | 4 | 5 | 6, raw: string): string => super.heading(text, level, raw);
hr = (): string => super.hr();
list = (body: string, ordered: boolean, start: number): string => super.list(body, ordered, start);
listitem = (text: string, task: boolean, checked: boolean): string => super.listitem(text, task, checked);
checkbox = (checked: boolean): string => super.checkbox(checked);
paragraph = (text: string): string => super.paragraph(text);
table = (header: string, body: string): string => super.table(header, body);
tablerow = (content: string): string => super.tablerow(content);
tablecell = (content: string, flags: { header: boolean; align: 'center' | 'left' | 'right' | null }): string => super.tablecell(content, flags);
strong = (text: string): string => super.strong(text);
em = (text: string): string => super.em(text);
codespan = (code: string): string => super.codespan(code);
br = (): string => super.br();
del = (text: string): string => super.del(text);
link = (href: string, title: string, text: string): string => super.link(href, title, text);
image = (href: string, title: string, text: string): string => super.image(href, title, text);
code = ({ type, raw, text, codeBlockStyle, lang, escaped }: Tokens.Code): string => super.code({ type, raw, text, codeBlockStyle, lang, escaped });
blockquote = ({ type, raw, text, tokens }: Tokens.Blockquote): string => super.blockquote({ type, raw, text, tokens });
html = ({ type, raw, text, pre, block }: Tokens.HTML): string => super.html({ type, raw, text, pre, block });
heading = ({ type, raw, text, depth, tokens }: Tokens.Heading): string => super.heading({ type, raw, text, depth, tokens });
hr = ({ type, raw }: Tokens.Hr): string => super.hr({ type, raw });
list = ({ type, raw, ordered, start, loose, items }: Tokens.List): string => super.list({ type, raw, ordered, start, loose, items});
listitem = ({ type, raw, task, checked, loose, text, tokens }: Tokens.ListItem): string => super.listitem({ type, raw, task, checked, loose, text, tokens });
checkbox = ({ checked }: Tokens.Checkbox): string => super.checkbox({ checked });
paragraph = ({ type, raw, pre, text, tokens }: Tokens.Paragraph): string => super.paragraph({ type, raw, pre, text, tokens });
table = ({ type, raw, align, header, rows }: Tokens.Table): string => super.table({ type, raw, align, header, rows });
tablerow = ({ text }: Tokens.TableRow): string => super.tablerow({ text });
tablecell = ({ text, tokens, header, align }: Tokens.TableCell): string => super.tablecell({ text, tokens, header, align });
strong = ({ type, raw, text, tokens }: Tokens.Strong): string => super.strong({ type, raw, text, tokens });
em = ({ type, raw, text, tokens }: Tokens.Em): string => super.em({ type, raw, text, tokens });
codespan = ({ type, raw, text }: Tokens.Codespan): string => super.codespan({ type, raw, text });
br = ({ type, raw }: Tokens.Br): string => super.br({ type, raw });
del = ({ type, raw, text, tokens }: Tokens.Del): string => super.del({ type, raw, text, tokens });
link = ({ type, raw, href, title, text, tokens }: Tokens.Link): string => super.link({ type, raw, href, title, text, tokens });
image = ({ type, raw, href, title, text }: Tokens.Image): string => super.image({ type, raw, href, title, text });
}
const rendererOptions: MarkedOptions = renderer.options;
const textRenderer = new marked.TextRenderer();
console.log(textRenderer.strong(text));
console.log(textRenderer.strong({ type : 'strong', raw, text, tokens }));
const parseTestText = '- list1\n - list1.1\n\n listend';
const parseTestTokens: TokensList = marked.lexer(parseTestText, options);
@@ -135,14 +136,14 @@ marked.use({ renderer }, { tokenizer });
marked.use({
renderer: {
heading(text, level) {
if (level > 3) {
heading({ text, depth }) {
if (depth > 3) {
return `<p>${text}</p>`;
}
return false;
},
listitem(text, task, checked) {
listitem({ text, task, checked }) {
if (task) return `<li class="task-list-item ${checked ? 'checked' : ''}">${text}</li>\n`;
else return `<li>${text}</li>\n`;
}
+54 -18
View File
@@ -196,22 +196,30 @@ lheading 2
header: [
{
text: 'a',
tokens: [{ type: 'text', raw: 'a', text: 'a' }]
tokens: [{ type: 'text', raw: 'a', text: 'a' }],
header: true,
align: null
},
{
text: 'b',
tokens: [{ type: 'text', raw: 'b', text: 'b' }]
tokens: [{ type: 'text', raw: 'b', text: 'b' }],
header: true,
align: null
}
],
rows: [
[
{
text: '1',
tokens: [{ type: 'text', raw: '1', text: '1' }]
tokens: [{ type: 'text', raw: '1', text: '1' }],
header: false,
align: null
},
{
text: '2',
tokens: [{ type: 'text', raw: '2', text: '2' }]
tokens: [{ type: 'text', raw: '2', text: '2' }],
header: false,
align: null
}
]
]
@@ -243,22 +251,30 @@ paragraph 1
header: [
{
text: 'a',
tokens: [{ type: 'text', raw: 'a', text: 'a' }]
tokens: [{ type: 'text', raw: 'a', text: 'a' }],
header: true,
align: null
},
{
text: 'b',
tokens: [{ type: 'text', raw: 'b', text: 'b' }]
tokens: [{ type: 'text', raw: 'b', text: 'b' }],
header: true,
align: null
}
],
rows: [
[
{
text: '1',
tokens: [{ type: 'text', raw: '1', text: '1' }]
tokens: [{ type: 'text', raw: '1', text: '1' }],
header: false,
align: null
},
{
text: '2',
tokens: [{ type: 'text', raw: '2', text: '2' }]
tokens: [{ type: 'text', raw: '2', text: '2' }],
header: false,
align: null
}
]
]
@@ -284,30 +300,42 @@ paragraph 1
header: [
{
text: 'a',
tokens: [{ type: 'text', raw: 'a', text: 'a' }]
tokens: [{ type: 'text', raw: 'a', text: 'a' }],
header: true,
align: 'left'
},
{
text: 'b',
tokens: [{ type: 'text', raw: 'b', text: 'b' }]
tokens: [{ type: 'text', raw: 'b', text: 'b' }],
header: true,
align: 'center'
},
{
text: 'c',
tokens: [{ type: 'text', raw: 'c', text: 'c' }]
tokens: [{ type: 'text', raw: 'c', text: 'c' }],
header: true,
align: 'right'
}
],
rows: [
[
{
text: '1',
tokens: [{ type: 'text', raw: '1', text: '1' }]
tokens: [{ type: 'text', raw: '1', text: '1' }],
header: false,
align: 'left'
},
{
text: '2',
tokens: [{ type: 'text', raw: '2', text: '2' }]
tokens: [{ type: 'text', raw: '2', text: '2' }],
header: false,
align: 'center'
},
{
text: '3',
tokens: [{ type: 'text', raw: '3', text: '3' }]
tokens: [{ type: 'text', raw: '3', text: '3' }],
header: false,
align: 'right'
}
]
]
@@ -333,22 +361,30 @@ a | b
header: [
{
text: 'a',
tokens: [{ type: 'text', raw: 'a', text: 'a' }]
tokens: [{ type: 'text', raw: 'a', text: 'a' }],
header: true,
align: null
},
{
text: 'b',
tokens: [{ type: 'text', raw: 'b', text: 'b' }]
tokens: [{ type: 'text', raw: 'b', text: 'b' }],
header: true,
align: null
}
],
rows: [
[
{
text: '1',
tokens: [{ type: 'text', raw: '1', text: '1' }]
tokens: [{ type: 'text', raw: '1', text: '1' }],
header: false,
align: null
},
{
text: '2',
tokens: [{ type: 'text', raw: '2', text: '2' }]
tokens: [{ type: 'text', raw: '2', text: '2' }],
header: false,
align: null
}
]
]
+14 -4
View File
@@ -77,22 +77,30 @@ describe('Parser', () => {
header: [
{
text: 'a',
tokens: [{ type: 'text', raw: 'a', text: 'a' }]
tokens: [{ type: 'text', raw: 'a', text: 'a' }],
header: true,
align: 'left'
},
{
text: 'b',
tokens: [{ type: 'text', raw: 'b', text: 'b' }]
tokens: [{ type: 'text', raw: 'b', text: 'b' }],
header: true,
align: 'right'
}
],
rows: [
[
{
text: '1',
tokens: [{ type: 'text', raw: '1', text: '1' }]
tokens: [{ type: 'text', raw: '1', text: '1' }],
header: false,
align: 'left'
},
{
text: '2',
tokens: [{ type: 'text', raw: '2', text: '2' }]
tokens: [{ type: 'text', raw: '2', text: '2' }],
header: false,
align: 'right'
}
]
]
@@ -273,6 +281,7 @@ describe('Parser', () => {
{
task: false,
checked: undefined,
loose: true,
tokens: [
{
type: 'text',
@@ -284,6 +293,7 @@ describe('Parser', () => {
{
task: false,
checked: undefined,
loose: true,
tokens: [
{
type: 'text',
+16 -9
View File
@@ -38,7 +38,7 @@ describe('marked unit', () => {
const md = 'HTML Image: <img alt="MY IMAGE" src="example.png" />';
marked.parse(md, { renderer });
assert.strictEqual(renderer.html.mock.calls[0].arguments[0], '<img alt="MY IMAGE" src="example.png" />');
assert.strictEqual(renderer.html.mock.calls[0].arguments[0].raw, '<img alt="MY IMAGE" src="example.png" />');
});
});
@@ -489,8 +489,9 @@ describe('marked unit', () => {
return false;
}
},
useNewRenderer: true,
renderer: {
heading(text, depth, raw) {
heading({ text, depth }) {
if (text === name) {
return `<h${depth}>${text}</h${depth}>\n`;
}
@@ -691,8 +692,9 @@ used extension2 walked</p>
it('should use renderer', () => {
const extension = {
useNewRenderer: true,
renderer: {
paragraph(text) {
paragraph() {
return 'extension';
}
}
@@ -700,7 +702,7 @@ used extension2 walked</p>
mock.method(extension.renderer, 'paragraph');
marked.use(extension);
const html = marked.parse('text');
assert.strictEqual(extension.renderer.paragraph.mock.calls[0].arguments[0], 'text');
assert.strictEqual(extension.renderer.paragraph.mock.calls[0].arguments[0].raw, 'text');
assert.strictEqual(html, 'extension');
});
@@ -772,18 +774,20 @@ used extension2 walked</p>
it('should use last extension function and not override others', () => {
const extension1 = {
useNewRenderer: true,
renderer: {
paragraph(text) {
paragraph() {
return 'extension1 paragraph\n';
},
html(html) {
html() {
return 'extension1 html\n';
}
}
};
const extension2 = {
useNewRenderer: true,
renderer: {
paragraph(text) {
paragraph() {
return 'extension2 paragraph\n';
}
}
@@ -802,8 +806,9 @@ paragraph
it('should use previous extension when returning false', () => {
const extension1 = {
useNewRenderer: true,
renderer: {
paragraph(text) {
paragraph({ text }) {
if (text !== 'original') {
return 'extension1 paragraph\n';
}
@@ -812,8 +817,9 @@ paragraph
}
};
const extension2 = {
useNewRenderer: true,
renderer: {
paragraph(text) {
paragraph({ text }) {
if (text !== 'extension1' && text !== 'original') {
return 'extension2 paragraph\n';
}
@@ -835,6 +841,7 @@ original
it('should get options with this.options', () => {
const extension = {
useNewRenderer: true,
renderer: {
heading: () => {
return this && this.options ? 'arrow options\n' : 'arrow no options\n';