如何在 Angular 中使用 Markdown
有很多的第三方库来处理 markdown 文档,其中 marked.js , showdown.js 和 markdown-it 是其中比较流行的,所以这里我们不再打算重复造轮子。
但是,所有的这些库都是生成HTML的输出,所以,你可以在 Angular 中对它们做很多事情,而不是将输出传递给应用程序中元素的 innerHTML 属性,而几乎无法控制结果。
我们尝试使用标准的 Angular 指令来执行渲染怎么样?
选择合适的类库
为了获得对渲染输出的完全控制,我们需要一个库以某种抽象数据格式解析 markdown 文本,然后将其输入到组件的视图中。
在深入研究了许多库文档和源代码之后,我决定使用 remarkjs,它是 unifiedjs 生态系统的一部分。
根据项目主页:“项目解析和编译 Markdown,让程序处理 Markdown 而无需编译为 HTML”;听起来和我们正在寻找的完全一样。
mdAST
当使用 remark 解析 Markdown 文档时,库输出他们所谓的“Markdown 抽象语法树”,简称为 mdAST。
详细的文档看这里。
数据树有一个根节点(文档)、由块节点(标题、段落、块引用、列表……)组成的分支和由短语节点(文本、链接、内联代码、图像……)组成的叶子。
我们将遵循同样的数据模型来塑造我们的组件,用一个用于文档的 MarkdownRoot 组件、一个用于分支的 MarkdownBlock 组件和一个用于叶子的 MarkdownInline 组件来构建我们的树视图。
渲染数据 Tree
一旦输入文本被解析为 mdAST,根组件在根节点子节点上循环以呈现其内容。每个数据节点都包含一个我们将在 ngSwitch 指令中使用的类型值:
markdown-block.component.html
<ng-container *ngFor="let child of node?.children">
<ng-container [ngSwitch]="child.type">
<!-- Headings -->
<ng-container *ngSwitchCase="'heading'">
<h1 *ngIf="child.depth === 1" [id]="toc(child)" [attr.data-line]="pos(child)" [wm-inline]="child"></h1>
<h2 *ngIf="child.depth === 2" [id]="toc(child)" [attr.data-line]="pos(child)" [wm-inline]="child"></h2>
<h3 *ngIf="child.depth === 3" [id]="toc(child)" [attr.data-line]="pos(child)" [wm-inline]="child"></h3>
<h4 *ngIf="child.depth === 4" [id]="toc(child)" [attr.data-line]="pos(child)" [wm-inline]="child"></h4>
<h5 *ngIf="child.depth === 5" [id]="toc(child)" [attr.data-line]="pos(child)" [wm-inline]="child"></h5>
<h6 *ngIf="child.depth === 6" [id]="toc(child)" [attr.data-line]="pos(child)" [wm-inline]="child"></h6>
</ng-container>
<!-- Paragraph -->
<p *ngSwitchCase="'paragraph'" [attr.data-line]="pos(child)" [wm-inline]="child"></p>
<!-- Lists -->
<ng-container *ngSwitchCase="'list'">
<ol *ngIf="child.ordered" [start]="child.start">
<li *ngFor="let item of child.children" [wm-block]="item"></li>
</ol>
<ul *ngIf="!child.ordered">
<li *ngFor="let item of child.children" [wm-block]="item"></li>
</ul>
</ng-container>
<!-- Tables -->
<table *ngSwitchCase="'table'" [attr.data-line]="pos(child)">
<tbody>
<tr *ngFor="let row of child.children">
<td *ngFor="let cell of row.children; index as i" [attr.align]="child.align[i]||''" [wm-inline]="cell"></td>
</tr>
</tbody>
</table>
<!-- Code -->
<pre *ngSwitchCase="'code'" [attr.data-line]="pos(child)">
<code>{{ child.value }}</code>
</pre>
<!-- Thematic Break -->
<hr *ngSwitchCase="'thematicBreak'" [attr.data-line]="pos(child)"/>
<!-- Blockquotes -->
<blockquote *ngSwitchCase="'blockquote'" [wm-block]="child"></blockquote>
<!-- Left aligned block - Align plugin -->
<span *ngSwitchCase="'leftAligned'" align="left" [wm-block]="child"></span>
<!-- Center aligned block - Align plugin -->
<span *ngSwitchCase="'centerAligned'" align="center" [wm-block]="child"></span>
<!-- Right aligned block - Align plugin -->
<span *ngSwitchCase="'rightAligned'" align="right" [wm-block]="child"></span>
</ng-container>
</ng-container>在 root 级别,MarkdownRoot 组件根据节点类型呈现实例化 wm-block 或 wm-inline 指令的顶级块:
blockquote,listItem,leftAligned,centerAlignedandrightAligned类型被渲染成 blocks.heading,paragraphandtableCell类型被渲染成 inlines.
渲染 Blocks
MarkdownBlock 组件模仿了与 MarkdownRoot 完全相同的行为。事实上,两个组件共享相同的模板,因为它们以完全相同的方式呈现它们的视图:
markdown-block.component.ts
@Component({
selector: '[wm-block]',
templateUrl: './block.component.html',
styleUrls: ['./block.component.scss'],
encapsulation: ViewEncapsulation.None
})
/** Renders a markdown text into an angular view */
export class MarkdownBlock {
constructor(readonly tree: MarkdownTree) {}
@Input('wm-block') node: mdContent;
// Table of content anchor helper
public toc(heading: mdHeading): string {
return this.tree.text(heading)
// Removes any non alphanumerical characters (keeps spaces)
.replace(/[^a-zA-Z0-9 ]/g, '')
// Replaces spaces with '-'
.replace(/\s+/g,'-')
// Lowers the case
.toLowerCase();
}
public pos(node: mdContent): string {
return '' + (!!node && !!node.position && node.position.start.line);
}
}markdown-root.component.ts
@Component({
selector: '[wm-markdown]',
templateUrl: './block/block.component.html',
styleUrls: ['./block/block.component.scss'],
providers: [ MarkdownTree ],
encapsulation: ViewEncapsulation.None,
host: { 'class': 'wm-markdown' }
})
/** Renders a markdown text into an angular view */
export class MarkdownRoot extends MarkdownBlock {
constructor(tree: MarkdownTree) { super(tree); }
/** Returns the array of parsed footnotes */
public get notes(): mdFootnoteDefinition[] { return this.tree.notes || []; }
@Input('wm-markdown') set parse(source: string|mdContent) {
// Parses the source md file into an mdAST syntax tree
this.node = typeof source === 'string' ? this.tree.parse(source) : source;
}
/** Navigation event emitted when a link is clicked on */
@Output('navigate') navigate = new EventEmitter<string>();
}组件主体做的很少,因为大部分魔法都是由 Angular 渲染视图完成的。只实现了两个辅助方法:
toc()返回一个字符串来分配标题 id(s) 以支持目录。pos()为每个渲染块计算源文本中的行位置。
MarkdownRoot 是 MarkdownBlock 组件的超集,通过扩展其类并添加:
parse()将输入源文本实际解析到 mdAST 数据树中。- 返回脚注数组以单独呈现。
MarkdownRoot 还实现了在用户单击链接时发出 url 字符串的导航输出,以便组件容器根据应用程序逻辑对其进行操作。
渲染 Inlines
正如您在下面看到的,内联元素也以递归方式呈现:
markdown-inline.component.html
<ng-container *ngFor="let child of node?.children">
<ng-container [ngSwitch]="child.type">
<!-- Emphasis -->
<em *ngSwitchCase="'emphasis'" [wm-inline]="child"></em>
<!-- Strong -->
<strong *ngSwitchCase="'strong'" [wm-inline]="child"></strong>
<!-- Delete -->
<del *ngSwitchCase="'delete'"[wm-inline]="child"></del>
<!-- Inlide Code -->
<code *ngSwitchCase="'inlineCode'">{{ _T(child.value) }}</code>
<!-- Sub-script Super-script plugin -->
<sub *ngSwitchCase="'sub'" [wm-inline]="child"></sub>
<!-- Super-script Super-script plugin -->
<sup *ngSwitchCase="'sup'" [wm-inline]="child"></sup>
<!-- Footnote Reference -->
<ng-container *ngSwitchCase="'footnoteReference'">
<sup *ngIf="tree.footnoteIndex(child) as index">[{{ index }}]</sup>
</ng-container>
<!-- Plain text -->
<ng-container *ngSwitchCase="'text'">{{ _T(child.value) }}</ng-container>
<!-- Line Break -->
<br *ngSwitchCase="'break'" />
<!-- Link -->
<a *ngSwitchCase="'link'" [href]="child.url" (click)="navigate(child.url)" [wm-inline]="child"></a>
<!-- Link Reference -->
<ng-container *ngSwitchCase="'linkReference'">
<a *ngIf="tree.definition(child) as def" [href]="def.url" (click)="navigate(def.url)" [wm-inline]="child"></a>
</ng-container>
<!-- Image -->
<img *ngSwitchCase="'image'" [src]="child.url" [title]="_T(child.title)" [alt]="_T(child.alt)" />
<!-- Image Reference -->
<ng-container *ngSwitchCase="'imageReference'">
<img *ngIf="tree.definition(child) as def" [src]="def.url" [title]="_T(def.title)" [alt]="_T(def.alt)" />
</ng-container>
</ng-container>
</ng-container>事实上,只有 text、inlineCode 和 image 类型的节点呈现它们的值(或 url),而所有其他类型(emphasis、strong、link 等)都实例化一个子 wm-inline 组件,而不是沿着树向下。
图像大小
获得对渲染的控制让我们也可以调整图像大小,这是我一直希望在 Markdown 中实现的。
不过,有许多既定的做法,对于这个实现,我决定在特殊的 url 参数上使用 CSS 选择器:
markdown-inline.component.scss
.wm-markdown {
img {
// Limits image size to 100%
max-width: 100%;
box-sizing: border-box;
// % resizing shortcuts
&[src*="#25"] { max-width: 25%; }
&[src*="#33"] { max-width: 33%; }
&[src*="#50"] { max-width: 50%; }
&[src*="#66"] { max-width: 66%; }
&[src*="#75"] { max-width: 75%; }
// px resizing shortcuts
&[src*="#regular"] { max-width: 1024px; }
&[src*="#small"] { max-width: 400px; }
&[src*="#thumb"] { max-width: 150px; }
&[src*="#icon"] { max-width: 48px; }
}
}因此,基本上,在我们的渲染器中,所有图像默认为 100% 宽度,而通过将片段附加到 url 来应用相关样式:
- 附加
#25,#33,#50,#66或者#75将图像的大小分别从 25% 调整到 75%。 - 附加
#icon,#thumb,#small或者#regular将图像分别调整为 48px、150px、400px 或 1024px 固定大小。
处理导航
在呈现链接时,组件模板将节点 url 分配给锚元素的 href 属性,但是,标准行为被 click 调用的 navigate() 方法阻止:
markdown-inline.component.ts
@Component({
selector: '[wm-inline]',
templateUrl: './inline.component.html',
styleUrls: ['./inline.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class MarkdownInline {
constructor(readonly tree: MarkdownTree, private root: MarkdownRoot) {}
@Input('wm-inline') node: mdPhrasingContent;
// Text rendering helper
public _T(value: string) { return value || ''; }
// Navigation helper functions
public navigate(url: string): boolean {
// Relies on the root parent navigation mechanism
this.root.navigate.emit(url);
// Prevents default navigation towards href
return false;
}
}navigate() 方法只是在返回 false 停止默认事件链之前恢复到根父 EventEmitter。
解析源文本
markdown-tree.service.ts
@Injectable()
/** Parses a markdown text into an 'mdContent' syntax tree using Remark @see {https://github.com/remarkjs/remark} */
export class MarkdownTree {
public root: mdRoot;
public defs: mdDefinition[];
public notes: mdFootnoteDefinition[];
/** Top level nodes (root's children) */
public get tops(): mdTopLevelContent[] { return !!this.root && this.root.children || [];}
/** Parses the markdown source into an mdContent tree */
public parse(source: string): mdRoot {
// Parses the source into the mdContent tree
this.root = !!source ? reparse.parse(source) : [];
// Extracts the definitions (links and images)
this.defs = this.tops.filter(node => node.type === 'definition') as mdDefinition[];
// Extracts the footnote definitions
this.notes = this.tops.filter(node => node.type === 'footnoteDefinition') as mdFootnoteDefinition[];
// Returns the root node
return this.root;
}
/** Seeks for the definition's node of the matching reference */
public definition(ref: mdReference): mdDefinition {
// Seeks the referred definition node
return this.defs.find(def => def.identifier === ref.identifier);
}
/** Seeks for the footnode definition's node of the matching reference */
public footnote(ref: mdFootnoteReference): mdFootnoteDefinition {
// Seeks the referred definition node
return this.notes.find(def => def.identifier === ref.identifier);
}
/** Seeks for the footnote definition index of the matching reference */
public footnoteIndex(ref: mdFootnoteDefinition): number {
return 1 + this.notes.findIndex(def => def.identifier === ref.identifier);
}
/** Parses the tree branch returning a plain concatenated text */
public text(node: mdContent): string {
return ("children" in node) ? (node as mdParent).children.reduce((txt: string, child: mdContent) => {
return txt + (child.type === 'text' ? child.value : '') + this.text(child);
}, '') : '';
}
}parse() 方法依赖于 remark 将输入 markdown 解析为 mdAST 树,该树完全由“tree-types.ts”中的一组 Typescript 接口定义。
此外,该服务会在树中扫描顶部节点中的 definitions 和 footnotes ,以供以后使用:
definition(), 在数据树中寻找definitions类型的节点。definitions节点是由imageReference或linkReference类型的节点在别处引用的资源(又名 url)。footnote(), 寻找要由footnoteReference类型的节点在别处引用的footnoteDefinition类型的节点。footnoteIndex(), 返回所请求footnoteReference引用的数字索引(从 1 开始)。
text() 辅助方法完成了服务,该服务返回通过展平树枝产生的纯文本。
引入 Remark
我决定将所需的内容包装到单独的 reparse.js 模块中,而不是在服务模块中导入我们选择的库 remarkjs:
reparse.js
(function(global){
'use strict';
// Implements a basic process shim to support vfile/path modules to work in a browser
if(!!global && !global.process) {
global.process = {
cwd: function() { return '/'; },
platform: ''
};
}
// Imports the UNIFIED and REMARK modules
const unified = require('unified');
const parse = require('remark-parse');
const subsup = require('remark-sub-super');
const align = require('remark-align');
// Defines the parsing options
const options = {
commonmark : true,
pedantic : true,
footnotes : true
};
// Exports the markdown parser including align and subsup plugins
module.exports = unified()
.use(parse, options)
.use(subsup)
.use(align)
.freeze();
}(window));这样,我们实际上只需要添加我们选择的插件的解析器模块来支持上标/下标和块对齐。
请注意,remarkjs 旨在与依赖于工具链的 shim 的 Node.js 一起在浏览器中工作。从版本 6 开始,Angular 删除了所有节点 shim,因此,我们的重解析模块在需要时应用了最小的进程 shim。
支持多个文档
您可能已经注意到,MarkdownTree 服务是在 MarkdownRoot 组件范围内提供的,允许在同一个应用程序中拥有该服务的多个实例。这是我们支持多个文档的方式,因为每个 MarkdownRoot 实例都将拥有自己的 MarkdownTree 服务实例,并与其自己的 MarkdownBlock 和 MarkdownInline 子级共享。
The MarkdownModule is part of wizdm.io, an open source project hosted on github.
