版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 1 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. # markdown-it-anchor [![npm version](http://img.shields.io/npm/v/markdown-it-anchor.svg?style=flat-square)](https://www.npmjs.org/package/markdown-it-anchor)
  2. > A markdown-it plugin that adds an `id` attribute to headings and
  3. > optionally permalinks.
  4. [markdown-it]: https://github.com/markdown-it/markdown-it
  5. English | [中文 (v7.0.1)](./README-zh_CN.md)
  6. ## Overview
  7. This plugin adds an `id` attribute to headings, e.g. `## Foo` becomes
  8. `<h2 id="foo">Foo</h2>`.
  9. Optionally it can also include [permalinks](#permalinks), e.g.
  10. `<h2 id="foo"><a class="header-anchor" href="#foo">Foo</a></h2>`
  11. and a bunch of other variants!
  12. * [**Usage**](#usage)
  13. * [User-friendly URLs](#user-friendly-urls)
  14. * [Manually setting the `id` attribute](#manually-setting-the-id-attribute)
  15. * [Compatible table of contents plugin](#compatible-table-of-contents-plugin)
  16. * [Parsing headings from HTML blocks](#parsing-headings-from-html-blocks)
  17. * [Browser example](#browser-example)
  18. * [**Permalinks**](#permalinks)
  19. * [Header link](#header-link)
  20. * [Link after header](#link-after-header)
  21. * [Link inside header](#link-inside-header)
  22. * [ARIA hidden](#aria-hidden)
  23. * [Custom permalink](#custom-permalink)
  24. * [Debugging](#debugging)
  25. * [Development](#development)
  26. ## Usage
  27. ```js
  28. const md = require('markdown-it')()
  29. .use(require('markdown-it-anchor'), opts)
  30. ```
  31. See a [demo as JSFiddle](https://jsfiddle.net/9ukc8dy6/).
  32. The `opts` object can contain:
  33. | Name | Description | Default |
  34. |------------------------|---------------------------------------------------------------------------|-----------------------------------------|
  35. | `level` | Minimum level to apply anchors, or array of selected levels. | 1 |
  36. | `permalink` | A function to render permalinks, see [permalinks] below. | `undefined` |
  37. | `slugify` | A custom slugification function. | See [`index.js`][index-slugify] |
  38. | `callback` | Called with token and info after rendering. | `undefined` |
  39. | `getTokensText` | A custom function to get the text contents of the title from its tokens. | See [`index.js`][index-get-tokens-text] |
  40. | `tabIndex` | Value of the `tabindex` attribute on headings, set to `false` to disable. | `-1` |
  41. | `uniqueSlugStartIndex` | Index to start with when making duplicate slugs unique. | 1 |
  42. [index-slugify]: https://github.com/valeriangalliat/markdown-it-anchor/blob/master/index.js#L3
  43. [index-get-tokens-text]: https://github.com/valeriangalliat/markdown-it-anchor/blob/master/index.js#L5
  44. [permalinks]: #permalinks
  45. All headers greater than the minimum `level` will have an `id` attribute
  46. with a slug of their content. For example, you can set `level` to 2 to
  47. add anchors to all headers but `h1`. You can also pass an array of
  48. header levels to apply the anchor, like `[2, 3]` to have an anchor on
  49. only level 2 and 3 headers.
  50. If a `permalink` renderer is given, it will be called for each matching header
  51. to add a permalink. See [permalinks] below.
  52. If a `slugify` function is given, you can decide how to transform a
  53. heading text to a URL slug. See [user-friendly URLs](#user-friendly-urls).
  54. The `callback` option is a function that will be called at the end of
  55. rendering with the `token` and an `info` object. The `info` object has
  56. `title` and `slug` properties with the token content and the slug used
  57. for the identifier.
  58. We set by default [`tabindex="-1"`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex)
  59. on headers. This marks the headers as focusable elements that are not
  60. reachable by keyboard navigation. The effect is that screen readers will
  61. read the title content when it's being jumped to. Outside of screen
  62. readers, the experience is the same as not setting that attribute. You
  63. can override this behavior with the `tabIndex` option. Set it to `false`
  64. to remove the attribute altogether, otherwise the value will be used as
  65. attribute value.
  66. Finally, you can customize how the title text is extracted from the
  67. markdown-it tokens (to later generate the slug). See [user-friendly URLs](#user-friendly-urls).
  68. ## User-friendly URLs
  69. Starting from v5.0.0, markdown-it-anchor dropped the [`string`](https://github.com/jprichardson/string.js)
  70. package to retain our core value of being an impartial and secure
  71. library. Nevertheless, users looking for backward compatibility may want
  72. the old `slugify` function:
  73. ```sh
  74. npm install string
  75. ```
  76. ```js
  77. const string = require('string')
  78. const slugify = s => string(s).slugify().toString()
  79. const md = require('markdown-it')()
  80. .use(require('markdown-it-anchor'), { slugify })
  81. ```
  82. Another popular library for this is [`@sindresorhus/slugify`](https://github.com/sindresorhus/slugify),
  83. which have better Unicode support and other cool features:
  84. ```sh
  85. npm install @sindresorhus/slugify
  86. ```
  87. ```js
  88. const slugify = require('@sindresorhus/slugify')
  89. const md = require('markdown-it')()
  90. .use(require('markdown-it-anchor'), { slugify: s => slugify(s) })
  91. ```
  92. Additionally, if you want to further customize the title that gets
  93. passed to the `slugify` function, you can do so by customizing the
  94. `getTokensText` function, that gets the plain text from a list of
  95. markdown-it inline tokens:
  96. ```js
  97. function getTokensText (tokens) {
  98. return tokens
  99. .filter(token => !['html_inline', 'image'].includes(token.type))
  100. .map(t => t.content)
  101. .join('')
  102. }
  103. const md = require('markdown-it')()
  104. .use(require('markdown-it-anchor'), { getTokensText })
  105. ```
  106. By default we include only `text` and `code_inline` tokens, which
  107. appeared to be a sensible approach for the vast majority of use cases.
  108. An alternative approach is to include every token's content except for
  109. `html_inline` and `image` tokens, which yields the exact same results as
  110. the previous approach with a stock markdown-it, but would also include
  111. custom tokens added by any of your markdown-it plugins, which might or
  112. might not be desirable for you. Now you have the option!
  113. ## Manually setting the `id` attribute
  114. You might want to explicitly set the `id` attribute of your headings
  115. from the Markdown document, for example to keep them consistent across
  116. translations.
  117. markdown-it-anchor is designed to reuse any existing `id`, making [markdown-it-attrs](https://www.npmjs.com/package/markdown-it-attrs)
  118. a perfect fit for this use case. Make sure to load it before markdown-it-anchor!
  119. Then you can do something like this:
  120. ```markdown
  121. # Your title {#your-custom-id}
  122. ```
  123. The anchor link will reuse the `id` that you explicitly defined.
  124. ## Compatible table of contents plugin
  125. Looking for an automatic table of contents (TOC) generator? Take a look at
  126. [markdown-it-toc-done-right](https://www.npmjs.com/package/markdown-it-toc-done-right)
  127. it's made from the ground to be a great companion of this plugin.
  128. ## Parsing headings from HTML blocks
  129. markdown-it-anchor doesn't parse HTML blocks, so headings defined in
  130. HTML blocks will be ignored. If you need to add anchors to both HTML
  131. headings and Markdown headings, the easiest way would be to do it on the
  132. final HTML rather than during the Markdown parsing phase:
  133. ```js
  134. const { parse } = require('node-html-parser')
  135. const root = parse(html)
  136. for (const h of root.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
  137. const slug = h.getAttribute('id') || slugify(h.textContent)
  138. h.setAttribute('id', slug)
  139. h.innerHTML = `<a href="#${slug}>${h.innerHTML}</a>`
  140. }
  141. console.log(root.toString())
  142. ```
  143. Or with a (not accessible) GitHub-style anchor, replace the
  144. `h.innerHTML` part with:
  145. ```js
  146. h.insertAdjacentHTML('afterbegin', `<a class="anchor" aria-hidden="true" href="#${slug}">🔗</a> `)
  147. ```
  148. While this still needs extra work like handling duplicated slugs and
  149. IDs, this should give you a solid base.
  150. That said if you really want to use markdown-it-anchor for this even
  151. though it's not designed to, you can do like npm does with their
  152. [marky-markdown](https://github.com/npm/marky-markdown) parser, and
  153. [transform the `html_block` tokens](https://github.com/npm/marky-markdown/blob/master/lib/plugin/html-heading.js)
  154. into a sequence of `heading_open`, `inline`, and `heading_close` tokens
  155. that can be handled by markdown-it-anchor:
  156. ```js
  157. const md = require('markdown-it')()
  158. .use(require('@npmcorp/marky-markdown/lib/plugin/html-heading'))
  159. .use(require('markdown-it-anchor'), opts)
  160. ```
  161. While they use regexes to parse the HTML and it won't gracefully handle
  162. any arbitrary HTML, it should work okay for the happy path, which might
  163. be good enough for you.
  164. You might also want to check [this implementation](https://github.com/valeriangalliat/markdown-it-anchor/issues/105#issuecomment-907323858)
  165. which uses [Cheerio](https://www.npmjs.com/package/cheerio) for a more
  166. solid parsing, including support for HTML attributes.
  167. The only edge cases I see it failing with are multiple headings defined
  168. in the same HTML block with arbitrary content between them, or headings
  169. where the opening and closing tag are defined in separate `html_block`
  170. tokens, both which should very rarely happen.
  171. If you need a bulletproof implementation, I would recommend the first
  172. HTML parser approach I documented instead.
  173. ## Browser example
  174. See [`example.html`](example.html).
  175. ## Permalinks
  176. Version 8.0.0 completely reworked the way permalinks work in order to
  177. offer more accessible options out of the box. You can also [make your own permalink](#custom-permalink).
  178. Instead of a single default way of rendering permalinks (which used to
  179. have a poor UX on screen readers), we now have multiple styles of
  180. permalinks for you to chose from.
  181. ```js
  182. const anchor = require('markdown-it-anchor')
  183. const md = require('markdown-it')()
  184. md.use(anchor, {
  185. permalink: anchor.permalink[styleOfPermalink](permalinkOpts)
  186. })
  187. ```
  188. Here, `styleOfPermalink` is one of the available styles documented
  189. below, and `permalinkOpts` is an options object.
  190. <div id="common-options"></div>
  191. All renderers share a common set of options:
  192. | Name | Description | Default |
  193. |---------------|---------------------------------------------------|------------------------------------|
  194. | `class` | The class of the permalink anchor. | `header-anchor` |
  195. | `symbol` | The symbol in the permalink anchor. | `#` |
  196. | `renderHref` | A custom permalink `href` rendering function. | See [`permalink.js`](permalink.js) |
  197. | `renderAttrs` | A custom permalink attributes rendering function. | See [`permalink.js`](permalink.js) |
  198. For the `symbol`, you may want to use the [link symbol](http://graphemica.com/🔗),
  199. or a symbol from your favorite web font.
  200. ### Header link
  201. This style wraps the header itself in an anchor link. It doesn't use the
  202. `symbol` option as there's no symbol needed in the markup (though you
  203. could add it with CSS using `::before` if you like).
  204. It's so simple it doesn't have any behaviour to custom, and it's also
  205. accessible out of the box without any further configuration, hence it
  206. doesn't have other options than the common ones described above.
  207. You can find this style on the [MDN] as well as [HTTP Archive] and their
  208. [Web Almanac], which to me is a good sign that this is a thoughtful way of
  209. implementing permalinks. This is also the style that I chose for my own
  210. [blog].
  211. [MDN]: https://developer.mozilla.org/en-US/docs/Web
  212. [HTTP Archive]: https://httparchive.org/reports/state-of-the-web
  213. [Web Almanac]: https://almanac.httparchive.org/en/2020/table-of-contents
  214. [blog]: https://www.codejam.info/
  215. | Name | Description | Default |
  216. |-------------------|-----------------------------------------------------------------------|---------------------------------------|
  217. | `safariReaderFix` | Add a `span` inside the link so Safari shows headings in reader view. | `false` (for backwards compatibility) |
  218. | | See [common options](#common-options). | |
  219. ```js
  220. const anchor = require('markdown-it-anchor')
  221. const md = require('markdown-it')()
  222. md.use(anchor, {
  223. permalink: anchor.permalink.headerLink()
  224. })
  225. ```
  226. ```html
  227. <h2 id="title"><a class="header-anchor" href="#title">Title</a></h2>
  228. ```
  229. The main caveat of this approach is that you can't include links inside
  230. headers. If you do, consider the other styles.
  231. Also note that this pattern [breaks reader mode in Safari](https://www.leereamsnyder.com/blog/making-headings-with-links-show-up-in-safari-reader),
  232. an issue you can also notice on the referenced websites above. This was
  233. already [reported to Apple](https://bugs.webkit.org/show_bug.cgi?id=225609#c2)
  234. but their bug tracker is not public. In the meantime, a fix mentioned in
  235. the article above is to insert a `span` inside the link. You can use the
  236. `safariReaderFix` option to enable it.
  237. ```js
  238. const anchor = require('markdown-it-anchor')
  239. const md = require('markdown-it')()
  240. md.use(anchor, {
  241. permalink: anchor.permalink.headerLink({ safariReaderFix: true })
  242. })
  243. ```
  244. ```html
  245. <h2 id="title"><a class="header-anchor" href="#title"><span>Title</span></a></h2>
  246. ```
  247. ### Link after header
  248. If you want to customize further the screen reader experience of your
  249. permalinks, this style gives you much more freedom than the [header link](#header-link).
  250. It works by leaving the header itself alone, and adding the permalink
  251. *after* it, giving you different methods of customizing the assistive
  252. text. It makes the permalink symbol `aria-hidden` to not pollute the
  253. experience, and leverages a `visuallyHiddenClass` to hide the assistive
  254. text from the visual experience.
  255. | Name | Description | Default |
  256. |-----------------------|-----------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------|
  257. | `style` | The (sub) style of link, one of `visually-hidden`, `aria-label`, `aria-describedby` or `aria-labelledby`. | `visually-hidden` |
  258. | `assistiveText` | A function that takes the title and returns the assistive text. | `undefined`, required for `visually-hidden` and `aria-label` styles |
  259. | `visuallyHiddenClass` | The class you use to make an element visually hidden. | `undefined`, required for `visually-hidden` style |
  260. | `space` | Add a space between the assistive text and the permalink symbol. | `true` |
  261. | `placement` | Placement of the permalink symbol relative to the assistive text, can be `before` or `after` the header. | `after` |
  262. | `wrapper` | Opening and closing wrapper string, e.g. `['<div class="wrapper">', '</div>']`. | `null` |
  263. | | See [common options](#common-options). | |
  264. ```js
  265. const anchor = require('markdown-it-anchor')
  266. const md = require('markdown-it')()
  267. md.use(anchor, {
  268. permalink: anchor.permalink.linkAfterHeader({
  269. style: 'visually-hidden',
  270. assistiveText: title => `Permalink to “${title}”`,
  271. visuallyHiddenClass: 'visually-hidden',
  272. wrapper: ['<div class="wrapper">', '</div>']
  273. })
  274. })
  275. ```
  276. ```html
  277. <div class="wrapper">
  278. <h2 id="title">Title</h2>
  279. <a class="header-anchor" href="#title">
  280. <span class="visually-hidden">Permalink to “Title”</span>
  281. <span aria-hidden="true">#</span>
  282. </a>
  283. </div>
  284. ```
  285. By using a visually hidden element for the assistive text, we make sure
  286. that the assistive text can be picked up by translation services, as
  287. most of the popular translation services (including Google Translate)
  288. currently ignore `aria-label`.
  289. If you prefer an alternative method for the assistive text, see other
  290. styles:
  291. <details>
  292. <summary><code>aria-label</code> variant</summary>
  293. This removes the need from a visually hidden `span`, but will likely
  294. hurt the permalink experience when using a screen reader through a
  295. translation service.
  296. ```js
  297. const anchor = require('markdown-it-anchor')
  298. const md = require('markdown-it')()
  299. md.use(anchor, {
  300. permalink: anchor.permalink.linkAfterHeader({
  301. style: 'aria-label'
  302. assistiveText: title => `Permalink to “${title}”`
  303. })
  304. })
  305. ```
  306. ```html
  307. <h2 id="title">Title</h2>
  308. <a class="header-anchor" href="#title" aria-label="Permalink to “Title”">#</a>
  309. ```
  310. </details>
  311. <details>
  312. <summary><code>aria-describedby</code> and <code>aria-labelledby</code> variants</summary>
  313. This removes the need to customize the assistive text to your locale and
  314. doesn't need a visually hidden `span` either, but since the anchor will
  315. be described by just the text of the title without any context, it might
  316. be confusing.
  317. ```js
  318. const anchor = require('markdown-it-anchor')
  319. const md = require('markdown-it')()
  320. md.use(anchor, {
  321. permalink: anchor.permalink.linkAfterHeader({
  322. style: 'aria-describedby' // Or `aria-labelledby`
  323. })
  324. })
  325. ```
  326. ```html
  327. <h2 id="title">Title</h2>
  328. <a class="header-anchor" href="#title" aria-describedby="title">#</a>
  329. ```
  330. </details>
  331. ### Link inside header
  332. This is the equivalent of the default permalink in previous versions.
  333. The reason it's not the first one in the list is because this method has
  334. accessibility issues.
  335. If you use a symbol like just `#` without adding any markup around,
  336. screen readers will read it as part of every heading (in the case of
  337. `#`, it could be read "pound", "number" or "number sign") meaning that
  338. if you title is "my beautiful title", it will read "number sign my
  339. beautiful title" for example. For other common symbols, `🔗` is usually
  340. read as "link symbol" and `¶` as "pilcrow".
  341. Additionally, screen readers users commonly request the list of all
  342. links in the page, so they'll be flooded with "number sign, number sign,
  343. number sign" for each of your headings.
  344. I would highly recommend using one of the markups above which have a
  345. better experience, but if you really want to use this markup, make sure
  346. to pass accessible HTML as `symbol` to make things usable, like in the
  347. example below, but even that has some flaws.
  348. With that said, this permalink allows the following options:
  349. | Name | Description | Default |
  350. |--------------|--------------------------------------------------------------------------------------------------------------------------|---------|
  351. | `space` | Add a space between the header text and the permalink symbol. Set it to a string to customize the space (e.g. `&nbsp;`). | `true` |
  352. | `placement` | Placement of the permalink, can be `before` or `after` the header. This option used to be called `permalinkBefore`. | `after` |
  353. | `ariaHidden` | Whether to add `aria-hidden="true"`, see [ARIA hidden](#aria-hidden). | `false` |
  354. | | See [common options](#common-options). | |
  355. ```js
  356. const anchor = require('markdown-it-anchor')
  357. const md = require('markdown-it')()
  358. md.use(anchor, {
  359. permalink: anchor.permalink.linkInsideHeader({
  360. symbol: `
  361. <span class="visually-hidden">Jump to heading</span>
  362. <span aria-hidden="true">#</span>
  363. `,
  364. placement: 'before'
  365. })
  366. })
  367. ```
  368. ```html
  369. <h2 id="title">
  370. <a class="header-anchor" href="#title">
  371. <span class="visually-hidden">Jump to heading</span>
  372. <span aria-hidden="true">#</span>
  373. </a>
  374. Title
  375. </h2>
  376. ```
  377. While this example allows more accessible anchors with the same markup
  378. as previous versions of markdown-it-anchor, it's still not ideal. The
  379. assistive text for permalinks will be read as part of the heading when
  380. listing all the titles of the page, e.g. "jump to heading title 1, jump
  381. to heading title 2" and so on. Also that assistive text is not very
  382. useful when listing the links in the page (which will read "jump to
  383. heading, jump to heading, jump to heading" for each of your permalinks).
  384. ### ARIA hidden
  385. This is just an alias for [`linkInsideHeader`](#link-inside-header) with
  386. `ariaHidden: true` by default, to mimic GitHub's way of rendering
  387. permalinks.
  388. Setting `aria-hidden="true"` makes the permalink explicitly inaccessible
  389. instead of having the permalink and its symbol being read by screen
  390. readers as part of every single headings (which was a pretty terrible
  391. experience).
  392. ```js
  393. const anchor = require('markdown-it-anchor')
  394. const md = require('markdown-it')()
  395. md.use(anchor, {
  396. permalink: anchor.permalink.ariaHidden({
  397. placement: 'before'
  398. })
  399. })
  400. ```
  401. ```html
  402. <h2 id="title"><a class="header-anchor" href="#title" aria-hidden="true">#</a> Title</h2>
  403. ```
  404. While no experience might be arguably better than a bad experience, I
  405. would instead recommend using one of the above renderers to provide an
  406. accessible experience. My favorite one is the [header link](#header-link),
  407. which is also the simplest one.
  408. ### Custom permalink
  409. If none of those options suit you, you can always make your own
  410. renderer! Take inspiration from [the code behind all permalinks](permalink.js).
  411. The signature of the function you pass in the `permalink` option is the
  412. following:
  413. ```js
  414. function renderPermalink (slug, opts, state, idx) {}
  415. ```
  416. Where `opts` are the markdown-it-anchor options, `state` is a
  417. markdown-it [`StateCore`](https://github.com/markdown-it/markdown-it)
  418. instance, and `idx` is the index of the `heading_open` token in the
  419. `state.tokens` array. That array contains [`Token`](https://markdown-it.github.io/markdown-it/#Token)
  420. objects.
  421. To make sense of the "token stream" and the way token objects are
  422. organized, you will probably want to read the [markdown-it design principles](https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md)
  423. page.
  424. This function can freely modify the token stream (`state.tokens`),
  425. usually around the given `idx`, to construct the anchor.
  426. Because of the way the token stream works, a `heading_open` token is
  427. usually followed by a `inline` token that contains the actual text (and
  428. inline markup) of the heading, and finally a `heading_close` token. This
  429. is why you'll see most built-in permalink renderers touch
  430. `state.tokens[idx + 1]`, because they update the contents of the
  431. `inline` token that follows a `heading_open`.
  432. ## Debugging
  433. If you want to debug this library more easily, we support source maps.
  434. Use the [source-map-support](https://www.npmjs.com/package/source-map-support)
  435. module to enable it with Node.js.
  436. ```sh
  437. node -r source-map-support/register your-script.js
  438. ```
  439. ## Development
  440. ```sh
  441. # Build the library in the `dist/` directory.
  442. npm run build
  443. # Watch file changes to update `dist/`.
  444. npm run dev
  445. # Run tests, will use the build version so make sure to build after
  446. # making changes.
  447. npm test
  448. ```