@vuepress/markdown 2.0.0-beta.4 → 2.0.0-beta.42

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.
Files changed (54) hide show
  1. package/lib/index.js +5 -1
  2. package/lib/markdown.d.ts +1 -1
  3. package/lib/markdown.js +18 -7
  4. package/lib/plugins/anchorPlugin.d.ts +3 -62
  5. package/lib/plugins/anchorPlugin.js +2 -2
  6. package/lib/plugins/{assetsPlugin.d.ts → assetsPlugin/assetsPlugin.d.ts} +0 -0
  7. package/lib/plugins/assetsPlugin/assetsPlugin.js +32 -0
  8. package/lib/plugins/assetsPlugin/index.d.ts +2 -0
  9. package/lib/plugins/assetsPlugin/index.js +18 -0
  10. package/lib/plugins/assetsPlugin/resolveLink.d.ts +2 -0
  11. package/lib/plugins/assetsPlugin/resolveLink.js +16 -0
  12. package/lib/plugins/codePlugin/codePlugin.d.ts +4 -1
  13. package/lib/plugins/codePlugin/codePlugin.js +24 -20
  14. package/lib/plugins/codePlugin/index.js +5 -1
  15. package/lib/plugins/codePlugin/resolveLanguage.js +2 -3
  16. package/lib/plugins/customComponentPlugin/index.d.ts +2 -0
  17. package/lib/plugins/customComponentPlugin/index.js +7 -1
  18. package/lib/plugins/customComponentPlugin/vueReservedTags.d.ts +1 -1
  19. package/lib/plugins/customComponentPlugin/vueReservedTags.js +1 -1
  20. package/lib/plugins/extractHeadersPlugin.js +3 -2
  21. package/lib/plugins/extractTitlePlugin.d.ts +5 -0
  22. package/lib/plugins/extractTitlePlugin.js +33 -0
  23. package/lib/plugins/hoistTagsPlugin.js +3 -2
  24. package/lib/plugins/importCodePlugin/createImportCodeBlockRule.d.ts +3 -0
  25. package/lib/plugins/importCodePlugin/createImportCodeBlockRule.js +52 -0
  26. package/lib/plugins/importCodePlugin/importCodePlugin.d.ts +8 -0
  27. package/lib/plugins/importCodePlugin/importCodePlugin.js +26 -0
  28. package/lib/plugins/importCodePlugin/index.d.ts +4 -0
  29. package/lib/plugins/importCodePlugin/index.js +20 -0
  30. package/lib/plugins/importCodePlugin/resolveImportCode.d.ts +6 -0
  31. package/lib/plugins/importCodePlugin/resolveImportCode.js +37 -0
  32. package/lib/plugins/importCodePlugin/types.d.ts +5 -0
  33. package/lib/plugins/importCodePlugin/types.js +2 -0
  34. package/lib/plugins/index.d.ts +2 -0
  35. package/lib/plugins/index.js +7 -1
  36. package/lib/plugins/linksPlugin/index.js +5 -1
  37. package/lib/plugins/linksPlugin/linksPlugin.d.ts +18 -1
  38. package/lib/plugins/linksPlugin/linksPlugin.js +44 -50
  39. package/lib/plugins/linksPlugin/resolvePaths.js +3 -1
  40. package/lib/plugins/tocPlugin/createRenderHeaders.js +5 -5
  41. package/lib/plugins/tocPlugin/index.js +5 -1
  42. package/lib/plugins/tocPlugin/tocPlugin.js +5 -3
  43. package/lib/types.d.ts +21 -3
  44. package/lib/utils/index.d.ts +1 -1
  45. package/lib/utils/index.js +6 -2
  46. package/lib/utils/resolveHeadersFromTokens.d.ts +4 -3
  47. package/lib/utils/resolveHeadersFromTokens.js +10 -28
  48. package/lib/utils/resolveTitleFromToken.d.ts +10 -0
  49. package/lib/utils/resolveTitleFromToken.js +37 -0
  50. package/package.json +14 -14
  51. package/CHANGELOG.md +0 -201
  52. package/lib/plugins/assetsPlugin.js +0 -24
  53. package/lib/utils/parseEmoji.d.ts +0 -1
  54. package/lib/utils/parseEmoji.js +0 -6
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveImportCode = void 0;
4
+ const utils_1 = require("@vuepress/utils");
5
+ const resolveImportCode = ({ importPath, lineStart, lineEnd }, { filePath }) => {
6
+ let importFilePath = importPath;
7
+ if (!utils_1.path.isAbsolute(importPath)) {
8
+ // if the importPath is relative path, we need to resolve it
9
+ // according to the markdown filePath
10
+ if (!filePath) {
11
+ return {
12
+ importFilePath: null,
13
+ importCode: 'Error when resolving path',
14
+ };
15
+ }
16
+ importFilePath = utils_1.path.resolve(filePath, '..', importPath);
17
+ }
18
+ // check file existence
19
+ if (!utils_1.fs.existsSync(importFilePath)) {
20
+ return {
21
+ importFilePath,
22
+ importCode: 'File not found',
23
+ };
24
+ }
25
+ // read file content
26
+ const fileContent = utils_1.fs.readFileSync(importFilePath).toString();
27
+ // resolve partial import
28
+ return {
29
+ importFilePath,
30
+ importCode: fileContent
31
+ .split('\n')
32
+ .slice(lineStart ? lineStart - 1 : lineStart, lineEnd)
33
+ .join('\n')
34
+ .replace(/\n?$/, '\n'),
35
+ };
36
+ };
37
+ exports.resolveImportCode = resolveImportCode;
@@ -0,0 +1,5 @@
1
+ export interface ImportCodeTokenMeta {
2
+ importPath: string;
3
+ lineStart: number;
4
+ lineEnd?: number;
5
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -4,6 +4,8 @@ export * from './codePlugin';
4
4
  export * from './customComponentPlugin';
5
5
  export * from './emojiPlugin';
6
6
  export * from './extractHeadersPlugin';
7
+ export * from './extractTitlePlugin';
7
8
  export * from './hoistTagsPlugin';
9
+ export * from './importCodePlugin';
8
10
  export * from './linksPlugin';
9
11
  export * from './tocPlugin';
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -16,6 +20,8 @@ __exportStar(require("./codePlugin"), exports);
16
20
  __exportStar(require("./customComponentPlugin"), exports);
17
21
  __exportStar(require("./emojiPlugin"), exports);
18
22
  __exportStar(require("./extractHeadersPlugin"), exports);
23
+ __exportStar(require("./extractTitlePlugin"), exports);
19
24
  __exportStar(require("./hoistTagsPlugin"), exports);
25
+ __exportStar(require("./importCodePlugin"), exports);
20
26
  __exportStar(require("./linksPlugin"), exports);
21
27
  __exportStar(require("./tocPlugin"), exports);
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -1,11 +1,28 @@
1
1
  import type { PluginWithOptions } from 'markdown-it';
2
2
  export interface LinksPluginOptions {
3
+ /**
4
+ * Tag for internal links
5
+ *
6
+ * @default 'RouterLink'
7
+ */
8
+ internalTag?: 'a' | 'RouterLink';
9
+ /**
10
+ * Additional attributes for external links
11
+ *
12
+ * @default
13
+ * ```js
14
+ * ({
15
+ * target: '_blank',
16
+ * rel: 'noopener noreferrer',
17
+ * })
18
+ * ```
19
+ */
3
20
  externalAttrs?: Record<string, string>;
4
21
  }
5
22
  /**
6
23
  * Process links in markdown file
7
24
  *
8
25
  * - internal links: convert them into `<RouterLink>`
9
- * - external links: add extra attrs and add `<OutboundLink/>` before their ending tag
26
+ * - external links: add extra attrs and external icon
10
27
  */
11
28
  export declare const linksPlugin: PluginWithOptions<LinksPluginOptions>;
@@ -7,17 +7,18 @@ const resolvePaths_1 = require("./resolvePaths");
7
7
  * Process links in markdown file
8
8
  *
9
9
  * - internal links: convert them into `<RouterLink>`
10
- * - external links: add extra attrs and add `<OutboundLink/>` before their ending tag
10
+ * - external links: add extra attrs and external icon
11
11
  */
12
12
  const linksPlugin = (md, options = {}) => {
13
+ // tag of internal links
14
+ const internalTag = options.internalTag || 'RouterLink';
13
15
  // attrs that going to be added to external links
14
16
  const externalAttrs = {
15
17
  target: '_blank',
16
18
  rel: 'noopener noreferrer',
17
19
  ...options.externalAttrs,
18
20
  };
19
- let hasOpenRouterLink = false;
20
- let hasOpenExternalLink = false;
21
+ let hasOpenInternalLink = false;
21
22
  const handleLinkOpen = (tokens, idx, env) => {
22
23
  // get current token
23
24
  const token = tokens[idx];
@@ -34,69 +35,62 @@ const linksPlugin = (md, options = {}) => {
34
35
  // get `base` and `filePathRelative` from `env`
35
36
  const { base = '/', filePathRelative = null } = env;
36
37
  // check if a link is an external link
37
- if (shared_1.isLinkExternal(hrefLink, base)) {
38
+ if ((0, shared_1.isLinkExternal)(hrefLink, base)) {
38
39
  // set `externalAttrs` to current token
39
40
  Object.entries(externalAttrs).forEach(([key, val]) => token.attrSet(key, val));
40
- // only when an external link has `target="_blank"`
41
- // should we add `<OutboundLink/>` before ending tag
42
- if (/\b_blank\b/i.test(externalAttrs.target)) {
43
- hasOpenExternalLink = true;
44
- }
45
41
  return;
46
42
  }
47
43
  // check if a link is an internal link
48
44
  const internalLinkMatch = hrefLink.match(/^((?:.*)(?:\/|\.md|\.html))(#.*)?$/);
49
- if (internalLinkMatch) {
50
- hasOpenRouterLink = true;
51
- // convert
52
- // <a href="hrefLink">
53
- // to
54
- // <RouterLink to="toProp">
55
- // notice that the path and hash are encoded by markdown-it
56
- const rawPath = internalLinkMatch[1];
57
- const rawHash = internalLinkMatch[2] || '';
58
- // resolve relative and absolute path
59
- const { relativePath, absolutePath } = resolvePaths_1.resolvePaths(rawPath, base, filePathRelative);
60
- // normalize markdown file path to route path
61
- //
62
- // we are removing the `base` from absolute path because it should not be
63
- // passed to `<RouterLink>`
64
- //
65
- // '/foo/index.md' => '/foo/'
66
- // '/foo/bar.md' => '/foo/bar.html'
67
- const normalizedPath = absolutePath
68
- .replace(new RegExp(`^${base}`), '/')
69
- .replace(/(^|\/)(README|index).md$/i, '$1')
70
- .replace(/\.md$/, '.html');
45
+ if (!internalLinkMatch) {
46
+ return;
47
+ }
48
+ // convert
49
+ // <a href="hrefLink">
50
+ // to
51
+ // <RouterLink to="toProp">
52
+ // notice that the path and hash are encoded by markdown-it
53
+ const rawPath = internalLinkMatch[1];
54
+ const rawHash = internalLinkMatch[2] || '';
55
+ // resolve relative and absolute path
56
+ const { relativePath, absolutePath } = (0, resolvePaths_1.resolvePaths)(rawPath, base, filePathRelative);
57
+ // normalize markdown file path to route path
58
+ //
59
+ // we are removing the `base` from absolute path because it should not be
60
+ // passed to `<RouterLink>`
61
+ //
62
+ // '/foo/index.md' => '/foo/'
63
+ // '/foo/bar.md' => '/foo/bar.html'
64
+ const normalizedPath = absolutePath
65
+ .replace(new RegExp(`^${base}`), '/')
66
+ .replace(/(^|\/)(README|index).md$/i, '$1')
67
+ .replace(/\.md$/, '.html');
68
+ if (internalTag === 'RouterLink') {
71
69
  // convert starting tag of internal link to `<RouterLink>`
72
- token.tag = 'RouterLink';
70
+ token.tag = internalTag;
73
71
  // replace the original `href` attr with `to` attr
74
72
  hrefAttr[0] = 'to';
75
- hrefAttr[1] = `${normalizedPath}${rawHash}`;
76
- // extract internal links for file / page existence check
77
- const links = env.links || (env.links = []);
78
- links.push({
79
- raw: hrefLink,
80
- relative: relativePath,
81
- absolute: absolutePath,
82
- });
73
+ // set `hasOpenInternalLink` to modify the ending tag
74
+ hasOpenInternalLink = true;
83
75
  }
76
+ hrefAttr[1] = `${normalizedPath}${rawHash}`;
77
+ // extract internal links for file / page existence check
78
+ const links = env.links || (env.links = []);
79
+ links.push({
80
+ raw: hrefLink,
81
+ relative: relativePath,
82
+ absolute: absolutePath,
83
+ });
84
84
  };
85
85
  md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
86
86
  handleLinkOpen(tokens, idx, env);
87
87
  return self.renderToken(tokens, idx, options);
88
88
  };
89
89
  md.renderer.rules.link_close = (tokens, idx, options, env, self) => {
90
- const token = tokens[idx];
91
- // add `<OutboundLink/>` before ending tag of external link
92
- if (hasOpenExternalLink) {
93
- hasOpenExternalLink = false;
94
- return '<OutboundLink/>' + self.renderToken(tokens, idx, options);
95
- }
96
- // convert ending tag of internal link to `</RouterLink>`
97
- if (hasOpenRouterLink) {
98
- hasOpenRouterLink = false;
99
- token.tag = 'RouterLink';
90
+ // convert ending tag of internal link
91
+ if (hasOpenInternalLink) {
92
+ hasOpenInternalLink = false;
93
+ tokens[idx].tag = internalTag;
100
94
  }
101
95
  return self.renderToken(tokens, idx, options);
102
96
  };
@@ -18,7 +18,9 @@ const resolvePaths = (rawPath, base, filePathRelative) => {
18
18
  if (filePathRelative) {
19
19
  // if `filePathRelative` is available
20
20
  // resolve relative path according to `filePathRelative`
21
- relativePath = utils_1.path.join(utils_1.path.dirname(filePathRelative), rawPath);
21
+ relativePath = utils_1.path.join(
22
+ // file path may contain non-ASCII characters
23
+ utils_1.path.dirname(encodeURI(filePathRelative)), rawPath);
22
24
  // resolve absolute path according to `base`
23
25
  absolutePath = utils_1.path.join(base, relativePath);
24
26
  }
@@ -3,12 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createRenderHeaders = void 0;
4
4
  const shared_1 = require("@vuepress/shared");
5
5
  const createRenderHeaders = ({ listTag, listClass, itemClass, linkTag, linkClass, }) => {
6
- const listTagString = shared_1.htmlEscape(listTag);
7
- const listClassString = listClass ? ` class="${shared_1.htmlEscape(listClass)}"` : '';
6
+ const listTagString = (0, shared_1.htmlEscape)(listTag);
7
+ const listClassString = listClass ? ` class="${(0, shared_1.htmlEscape)(listClass)}"` : '';
8
8
  const itemTagString = 'li';
9
- const itemClassString = itemClass ? ` class="${shared_1.htmlEscape(itemClass)}"` : '';
10
- const linkTagString = shared_1.htmlEscape(linkTag);
11
- const linkClassString = linkClass ? ` class="${shared_1.htmlEscape(linkClass)}` : '';
9
+ const itemClassString = itemClass ? ` class="${(0, shared_1.htmlEscape)(itemClass)}"` : '';
10
+ const linkTagString = (0, shared_1.htmlEscape)(linkTag);
11
+ const linkClassString = linkClass ? ` class="${(0, shared_1.htmlEscape)(linkClass)}` : '';
12
12
  const linkTo = (slug) => linkTag === 'RouterLink' ? ` to="#${slug}"` : ` href="#${slug}"`;
13
13
  const renderHeaders = (headers) => `\
14
14
  <${listTagString}${listClassString}>\
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -20,23 +20,24 @@ const tocPlugin = (md, { pattern = /^\[\[toc\]\]$/i, slugify = utils_1.slugify,
20
20
  // push the rule to the end of the chain
21
21
  // resolve headers from the parsed tokens
22
22
  md.core.ruler.push('resolveTocHeaders', (state) => {
23
- headers = utils_1.resolveHeadersFromTokens(state.tokens, {
23
+ headers = (0, utils_1.resolveHeadersFromTokens)(state.tokens, {
24
24
  level,
25
25
  allowHtml: true,
26
+ escapeText: true,
26
27
  slugify,
27
28
  format,
28
29
  });
29
30
  return true;
30
31
  });
31
32
  // add toc syntax as a block rule
32
- md.block.ruler.before('heading', 'toc', createTocBlockRule_1.createTocBlockRule({
33
+ md.block.ruler.before('heading', 'toc', (0, createTocBlockRule_1.createTocBlockRule)({
33
34
  pattern,
34
35
  containerTag,
35
36
  containerClass,
36
37
  }), {
37
38
  alt: ['paragraph', 'reference', 'blockquote'],
38
39
  });
39
- const renderHeaders = createRenderHeaders_1.createRenderHeaders({
40
+ const renderHeaders = (0, createRenderHeaders_1.createRenderHeaders)({
40
41
  listTag,
41
42
  listClass,
42
43
  itemClass,
@@ -45,6 +46,7 @@ const tocPlugin = (md, { pattern = /^\[\[toc\]\]$/i, slugify = utils_1.slugify,
45
46
  });
46
47
  // custom toc_body render rule
47
48
  md.renderer.rules.toc_body = () => {
49
+ /* istanbul ignore if */
48
50
  if (!headers) {
49
51
  return '';
50
52
  }
package/lib/types.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import * as MarkdownIt from 'markdown-it';
2
- import type { PageHeader } from '@vuepress/shared';
3
- import type { AnchorPluginOptions, AssetsPluginOptions, CodePluginOptions, EmojiPluginOptions, ExtractHeadersPluginOptions, HoistTagsPluginOptions, LinksPluginOptions, TocPluginOptions } from './plugins';
1
+ import type { PageFrontmatter, PageHeader } from '@vuepress/shared';
2
+ import type * as MarkdownIt from 'markdown-it';
3
+ import type { AnchorPluginOptions, AssetsPluginOptions, CodePluginOptions, EmojiPluginOptions, ExtractHeadersPluginOptions, HoistTagsPluginOptions, ImportCodePluginOptions, LinksPluginOptions, TocPluginOptions } from './plugins';
4
4
  export declare type Markdown = MarkdownIt;
5
5
  export interface MarkdownOptions extends MarkdownIt.Options {
6
6
  anchor?: false | AnchorPluginOptions;
@@ -9,7 +9,9 @@ export interface MarkdownOptions extends MarkdownIt.Options {
9
9
  customComponent?: false;
10
10
  emoji?: false | EmojiPluginOptions;
11
11
  extractHeaders?: false | ExtractHeadersPluginOptions;
12
+ extractTitle?: false;
12
13
  hoistTags?: false | HoistTagsPluginOptions;
14
+ importCode?: false | ImportCodePluginOptions;
13
15
  links?: false | LinksPluginOptions;
14
16
  toc?: false | TocPluginOptions;
15
17
  }
@@ -39,10 +41,18 @@ export interface MarkdownEnv {
39
41
  * Base / publicPath of current site
40
42
  */
41
43
  base?: string;
44
+ /**
45
+ * Absolute file path of the markdown file
46
+ */
47
+ filePath?: string | null;
42
48
  /**
43
49
  * Relative file path of the markdown file
44
50
  */
45
51
  filePathRelative?: string | null;
52
+ /**
53
+ * Frontmatter of the markdown file
54
+ */
55
+ frontmatter?: PageFrontmatter;
46
56
  /**
47
57
  * Headers that extracted by extractHeadersPlugin
48
58
  */
@@ -51,8 +61,16 @@ export interface MarkdownEnv {
51
61
  * Hoisted tags that extracted by hoistTagsPlugin
52
62
  */
53
63
  hoistedTags?: string[];
64
+ /**
65
+ * Imported file that extracted by importCodePlugin
66
+ */
67
+ importedFiles?: string[];
54
68
  /**
55
69
  * Links that extracted by linksPlugin
56
70
  */
57
71
  links?: MarkdownLink[];
72
+ /**
73
+ * Title that extracted by extractTitlePlugin
74
+ */
75
+ title?: string;
58
76
  }
@@ -1,3 +1,3 @@
1
- export * from './parseEmoji';
2
1
  export * from './resolveHeadersFromTokens';
2
+ export * from './resolveTitleFromToken';
3
3
  export * from './slugify';
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -10,6 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
15
  };
12
16
  Object.defineProperty(exports, "__esModule", { value: true });
13
- __exportStar(require("./parseEmoji"), exports);
14
17
  __exportStar(require("./resolveHeadersFromTokens"), exports);
18
+ __exportStar(require("./resolveTitleFromToken"), exports);
15
19
  __exportStar(require("./slugify"), exports);
@@ -1,11 +1,12 @@
1
- import * as Token from 'markdown-it/lib/token';
2
- import { MarkdownHeader } from '../types';
1
+ import type * as Token from 'markdown-it/lib/token';
2
+ import type { MarkdownHeader } from '../types';
3
3
  /**
4
4
  * Resolve headers from markdown-it tokens
5
5
  */
6
- export declare const resolveHeadersFromTokens: (tokens: Token[], { level, allowHtml, slugify, format, }: {
6
+ export declare const resolveHeadersFromTokens: (tokens: Token[], { level, allowHtml, escapeText, slugify, format, }: {
7
7
  level: number[];
8
8
  allowHtml: boolean;
9
+ escapeText: boolean;
9
10
  slugify: (str: string) => string;
10
11
  format?: ((str: string) => string) | undefined;
11
12
  }) => MarkdownHeader[];
@@ -2,10 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveHeadersFromTokens = void 0;
4
4
  const shared_1 = require("@vuepress/shared");
5
+ const resolveTitleFromToken_1 = require("./resolveTitleFromToken");
5
6
  /**
6
7
  * Resolve headers from markdown-it tokens
7
8
  */
8
- const resolveHeadersFromTokens = (tokens, { level, allowHtml, slugify, format, }) => {
9
+ const resolveHeadersFromTokens = (tokens, { level, allowHtml, escapeText, slugify, format, }) => {
9
10
  // store the result of headers
10
11
  const headers = [];
11
12
  // a temp headers stack for generating the headers tree
@@ -25,10 +26,9 @@ const resolveHeadersFromTokens = (tokens, { level, allowHtml, slugify, format, }
25
26
  }
26
27
  };
27
28
  tokens.forEach((_, idx) => {
28
- var _a, _b;
29
29
  const token = tokens[idx];
30
- // if the token type is not matched, skip
31
- if ((token === null || token === void 0 ? void 0 : token.type) !== 'heading_open') {
30
+ // if the token type does not match, skip
31
+ if (token?.type !== 'heading_open') {
32
32
  return;
33
33
  }
34
34
  // get the level from the tag, h1 -> 1
@@ -43,35 +43,17 @@ const resolveHeadersFromTokens = (tokens, { level, allowHtml, slugify, format, }
43
43
  if (!nextToken) {
44
44
  return;
45
45
  }
46
- // children of the next token contains the parsed result of the heading title
47
- const nextTokenChildren = (_a = nextToken.children) !== null && _a !== void 0 ? _a : [];
48
- // filter tokens for generating heading title
49
- // 'text' and 'code_inline' should be escaped to avoid being treated as html
50
- // 'emoji' and 'html_inline' should be used directly
51
- const titleTokenTypes = ['text', 'emoji', 'code_inline'];
52
- // include 'html_inline' or not
53
- if (allowHtml) {
54
- titleTokenTypes.push('html_inline');
55
- }
56
- const titleTokens = nextTokenChildren.filter((item) => titleTokenTypes.includes(item.type));
57
- // get title from tokens
58
- const title = titleTokens
59
- .reduce((result, item) => {
60
- // escape content of 'code_inline' and 'text'
61
- if (item.type === 'code_inline' || item.type === 'text') {
62
- return `${result}${shared_1.htmlEscape(item.content)}`;
63
- }
64
- // keep the content of 'emoji' and 'html_inline'
65
- return `${result}${item.content}`;
66
- }, '')
67
- .trim();
46
+ const title = (0, resolveTitleFromToken_1.resolveTitleFromToken)(nextToken, {
47
+ allowHtml,
48
+ escapeText,
49
+ });
68
50
  // the id of the heading anchor is the slugify result of markdown-it-anchor
69
51
  // if the id does not exist, slugify the title ourselves
70
- const slug = (_b = token.attrGet('id')) !== null && _b !== void 0 ? _b : slugify(title);
52
+ const slug = token.attrGet('id') ?? slugify(title);
71
53
  // push the header to tree
72
54
  push({
73
55
  level: headerLevel,
74
- title: shared_1.isFunction(format) ? format(title) : title,
56
+ title: (0, shared_1.isFunction)(format) ? format(title) : title,
75
57
  slug,
76
58
  children: [],
77
59
  });
@@ -0,0 +1,10 @@
1
+ import type * as Token from 'markdown-it/lib/token';
2
+ /**
3
+ * Resolve header title from markdown-it token
4
+ *
5
+ * Typically using the next token of `heading_open` token
6
+ */
7
+ export declare const resolveTitleFromToken: (token: Token, { allowHtml, escapeText, }: {
8
+ allowHtml: boolean;
9
+ escapeText: boolean;
10
+ }) => string;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveTitleFromToken = void 0;
4
+ const shared_1 = require("@vuepress/shared");
5
+ /**
6
+ * Resolve header title from markdown-it token
7
+ *
8
+ * Typically using the next token of `heading_open` token
9
+ */
10
+ const resolveTitleFromToken = (token, { allowHtml, escapeText, }) => {
11
+ // children of the token contains the parsed result of the heading title
12
+ const children = token.children ?? [];
13
+ // type of tokens to be included in the heading title
14
+ const titleTokenTypes = ['text', 'emoji', 'code_inline'];
15
+ // include 'html_inline' or not
16
+ if (allowHtml) {
17
+ titleTokenTypes.push('html_inline');
18
+ }
19
+ // filter the token type to be included in the title
20
+ const titleTokens = children.filter((item) => titleTokenTypes.includes(item.type) &&
21
+ // filter permalink symbol that generated by markdown-it-anchor
22
+ !item.meta?.isPermalinkSymbol);
23
+ // get title from tokens
24
+ return titleTokens
25
+ .reduce((result, item) => {
26
+ if (escapeText) {
27
+ // escape the content of 'code_inline' and 'text'
28
+ if (item.type === 'code_inline' || item.type === 'text') {
29
+ return `${result}${(0, shared_1.htmlEscape)(item.content)}`;
30
+ }
31
+ }
32
+ // keep the content of 'emoji' and 'html_inline'
33
+ return `${result}${item.content}`;
34
+ }, '')
35
+ .trim();
36
+ };
37
+ exports.resolveTitleFromToken = resolveTitleFromToken;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vuepress/markdown",
3
- "version": "2.0.0-beta.4",
3
+ "version": "2.0.0-beta.42",
4
4
  "description": "Markdown package of VuePress",
5
5
  "keywords": [
6
6
  "vuepress",
@@ -15,26 +15,26 @@
15
15
  "url": "git+https://github.com/vuepress/vuepress-next.git"
16
16
  },
17
17
  "license": "MIT",
18
- "author": "Evan You",
18
+ "author": "meteorlxy",
19
19
  "main": "lib/index.js",
20
20
  "types": "lib/index.d.ts",
21
21
  "files": [
22
22
  "lib"
23
23
  ],
24
- "scripts": {
25
- "build": "tsc -b tsconfig.build.json",
26
- "clean": "rimraf lib *.tsbuildinfo"
27
- },
28
24
  "dependencies": {
29
- "@types/markdown-it": "^12.0.1",
30
- "@vuepress/shared": "2.0.0-beta.4",
31
- "@vuepress/utils": "2.0.0-beta.4",
32
- "markdown-it": "^12.0.4",
33
- "markdown-it-anchor": "^7.0.2",
34
- "markdown-it-emoji": "^2.0.0"
25
+ "@types/markdown-it": "^12.2.3",
26
+ "@vuepress/shared": "2.0.0-beta.42",
27
+ "@vuepress/utils": "2.0.0-beta.42",
28
+ "markdown-it": "^13.0.0",
29
+ "markdown-it-anchor": "^8.4.1",
30
+ "markdown-it-emoji": "^2.0.0",
31
+ "mdurl": "^1.0.1"
35
32
  },
36
33
  "publishConfig": {
37
34
  "access": "public"
38
35
  },
39
- "gitHead": "d42716e1b5b682ffb5d7cf124d0a24344493c467"
40
- }
36
+ "scripts": {
37
+ "build": "tsc -b tsconfig.build.json",
38
+ "clean": "rimraf lib *.tsbuildinfo"
39
+ }
40
+ }