• Stars
    star
    206
  • Rank 190,504 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

plugin to add links to headings in HTML

rehype-autolink-headings

Build Coverage Downloads Size Sponsors Backers Chat

rehype plugin to add links to headings with ids back to themselves.

Contents

What is this?

This package is a unified (rehype) plugin to add links from headings back to themselves. It looks for headings (so <h1> through <h6>), that have id attributes, and injects a link to themselves. Similar functionality is applied by many places that render markdown. For example, when browsing this readme on GitHub or npm, an anchor is added to headings, which you can share to point people to a particular place in a document.

unified is a project that transforms content with abstract syntax trees (ASTs). rehype adds support for HTML to unified. hast is the HTML AST that rehype uses. This is a rehype plugin that adds links to headings in the AST.

When should I use this?

This plugin is useful when you have relatively long documents, where you want users to be able to link to particular sections, and you already have id attributes set on all (or certain?) headings.

A different plugin, rehype-slug, adds ids to headings. When a heading doesn’t already have an id attribute, it creates a slug from it, and adds that as the id attribute. When using both plugins together, all headings (whether explicitly with a certain id or automatically with a generate one) will get a link back to themselves.

Install

This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:

npm install rehype-autolink-headings

In Deno with esm.sh:

import rehypeAutolinkHeadings from 'https://esm.sh/rehype-autolink-headings@6'

In browsers with esm.sh:

<script type="module">
  import rehypeAutolinkHeadings from 'https://esm.sh/rehype-autolink-headings@6?bundle'
</script>

Use

Say we have the following file example.html:

<h1 id=some-id>Lorem ipsum</h1>
<h2>Dolor sit amet πŸ˜ͺ</h2>
<h3>consectetur &amp; adipisicing</h3>
<h4>elit</h4>
<h5>elit</h5>

And our module example.js looks as follows:

import {read} from 'to-vfile'
import {rehype} from 'rehype'
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'

main()

async function main() {
  const file = await rehype()
    .data('settings', {fragment: true})
    .use(rehypeSlug)
    .use(rehypeAutolinkHeadings)
    .process(await read('example.html'))

  console.log(String(file))
}

Now, running node example.js yields:

<h1 id="some-id"><a aria-hidden="true" tabindex="-1" href="#some-id"><span class="icon icon-link"></span></a>Lorem ipsum</h1>
<h2 id="dolor-sit-amet-"><a aria-hidden="true" tabindex="-1" href="#dolor-sit-amet-"><span class="icon icon-link"></span></a>Dolor sit amet πŸ˜ͺ</h2>
<h3 id="consectetur--adipisicing"><a aria-hidden="true" tabindex="-1" href="#consectetur--adipisicing"><span class="icon icon-link"></span></a>consectetur &#x26; adipisicing</h3>
<h4 id="elit"><a aria-hidden="true" tabindex="-1" href="#elit"><span class="icon icon-link"></span></a>elit</h4>
<h5 id="elit-1"><a aria-hidden="true" tabindex="-1" href="#elit-1"><span class="icon icon-link"></span></a>elit</h5>

πŸ‘‰ Note: observe that from the <h2> on, automatic ids are generated. This is done by rehype-slug. Without rehype-slug, those headings would not be linked.

API

This package exports no identifiers. The default export is rehypeAutolinkHeadings.

unified().use(rehypeAutolinkHeadings[, options])

Add links to headings with ids back to themselves.

πŸ‘‰ Note: this plugin operates on headings that have id attributes. You can use rehype-slug to automatically generate ids for headings.

options

Configuration (optional).

options.behavior

How to create links (string, default: 'prepend').

  • 'prepend' β€” inject link before the heading text
  • 'append' β€” inject link after the heading text
  • 'wrap' β€” wrap the whole heading text with the link
  • 'before' β€” insert link before the heading
  • 'after' β€” insert link after the heading

πŸ‘‰ Note: options.content is ignored when the behavior is wrap, options.group is ignored when the behavior is prepend, append, or wrap.

options.properties

Attributes to set on the link (Properties, optional). Defaults to {ariaHidden: true, tabIndex: -1} when in 'prepend' or 'append' mode, and {} otherwise.

options.content

hast nodes to insert in the link (Function|Node|Children). By default, a <span class="icon icon-link"></span> is used.

When a function is given, it’s called with the current heading (Element) and should return one or more nodes.

πŸ‘‰ Note: this option is ignored when the behavior is wrap.

options.group

hast node to wrap the heading and link with (Function|Node, optional). There is no default.

When a function is given, it’s called with the current heading (Element) and should return a hast node.

πŸ‘‰ Note: this option is ignored when the behavior is prepend, append, or wrap

options.test

Test to define which heading elements are linked. Any test that can be given to hast-util-is-element is supported. The default (no test) is to link all headings with an id attribute.

Can be used to link only <h1> through <h3> (with ['h1', 'h2', 'h3']), or for example all except <h1> (with ['h2', 'h3', 'h4', 'h5', 'h6']). A function can be given to do more complex things.

Examples

Example: different behaviors

This example shows what each behavior generates by default.

import {rehype} from 'rehype'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'

main()

async function main() {
  const behaviors = ['prepend', 'append', 'wrap', 'before', 'after']
  let index = -1
  while (++index < behaviors.length) {
    const behavior = behaviors[index]
    console.log(
      String(
        await rehype()
          .data('settings', {fragment: true})
          .use(rehypeAutolinkHeadings, {behavior})
          .process('<h1 id="' + behavior + '">' + behavior + '</h1>')
      )
    )
  }
}

Yields:

<h1 id="prepend"><a aria-hidden="true" tabindex="-1" href="#prepend"><span class="icon icon-link"></span></a>prepend</h1>
<h1 id="append">append<a aria-hidden="true" tabindex="-1" href="#append"><span class="icon icon-link"></span></a></h1>
<h1 id="wrap"><a href="#wrap">wrap</a></h1>
<a href="#before"><span class="icon icon-link"></span></a><h1 id="before">before</h1>
<h1 id="after">after</h1><a href="#after"><span class="icon icon-link"></span></a>

Example: content from h builder

The following example passes content as a function, to generate an accessible description of each link.

import {rehype} from 'rehype'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import {toString} from 'hast-util-to-string'
import {h} from 'hastscript'

main()

async function main() {
  const file = await rehype()
    .data('settings', {fragment: true})
    .use(rehypeAutolinkHeadings, {
      content(node) {
        return [
          h('span.visually-hidden', 'Read the β€œ', toString(node), '” section'),
          h('span.icon.icon-link', {ariaHidden: 'true'})
        ]
      }
    })
    .process('<h1 id="xxx">xxx</h1>')

  console.log(String(file))
}

Yields:

<h1 id="xxx"><a aria-hidden="true" tabindex="-1" href="#xxx"><span class="visually-hidden">Read the β€œxxx” section</span><span class="icon icon-link" aria-hidden="true"></span></a>xxx</h1>

Example: content from fromHtml builder

The following example passes content as a function, to generate an accessible description of each link.

import {rehype} from 'rehype'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import {fromHtmlIsomorphic} from 'hast-util-from-html-isomorphic'

main()

async function main() {
  const file = await rehype()
    .data('settings', {fragment: true})
    .use(rehypeAutolinkHeadings, {
      content: fromHtmlIsomorphic(
        '<svg height="10" width="10"><circle cx="5" cy="5" r="5" fill="black" /></svg>',
        {fragment: true}
      ).children
    })
    .process('<h1 id="xxx">xxx</h1>')

  console.log(String(file))
}

Yields:

<h1 id="xxx"><a aria-hidden="true" tabindex="-1" href="#xxx"><span class="icon icon-link" aria-hidden="true"><svg height="10" width="10"><circle cx="5" cy="5" r="5" fill="black"></circle></svg></span></a>xxx</h1>

Example: group

The following example passes group as a function, to dynamically generate a differing element that wraps the heading.

import {rehype} from 'rehype'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import {h} from 'hastscript'

main()

async function main() {
  const file = await rehype()
    .data('settings', {fragment: true})
    .use(rehypeAutolinkHeadings, {
      behavior: 'before',
      group(node) {
        return h('.heading-' + node.tagName.charAt(1) + '-group')
      }
    })
    .process('<h1 id="xxx">xxx</h1>')

  console.log(String(file))
}

Yields:

<div class="heading-1-group"><a href="#xxx"><span class="icon icon-link"></span></a><h1 id="xxx">xxx</h1></div>

Types

This package is fully typed with TypeScript. It exports an Options type, which specifies the interface of the accepted options.

Compatibility

Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.

This plugin works with rehype-parse version 1+, rehype-stringify version 1+, rehype version 1+, and unified version 4+.

Security

Use of rehype-autolink-headings can open you up to a cross-site scripting (XSS) attack if you pass user provided content in properties or content.

Always be wary of user input and use rehype-sanitize.

Related

Contribute

See contributing.md in rehypejs/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT Β© Titus Wormer

More Repositories

1

rehype

HTML processor powered by plugins part of the @unifiedjs collective
JavaScript
1,732
star
2

rehype-react

plugin to transform to preact, react, vue, etc
JavaScript
390
star
3

rehype-highlight

plugin to highlight code blocks
JavaScript
253
star
4

rehype-slug

plugin to add `id` attributes to headings
JavaScript
191
star
5

awesome-rehype

Curated list of awesome rehype resources
171
star
6

rehype-sanitize

plugin to sanitize HTML
JavaScript
138
star
7

rehype-raw

plugin to parse the tree again
JavaScript
130
star
8

rehype-minify

plugins to minify HTML
JavaScript
89
star
9

rehype-external-links

rehype plugin to add rel (and target) to external links
JavaScript
85
star
10

rehype-remark

plugin to transform from HTML (rehype) to Markdown (remark)
JavaScript
78
star
11

rehype-meta

plugin to add metadata to the head of a document
JavaScript
31
star
12

rehype-document

plugin to wrap a fragment in a document
JavaScript
31
star
13

rehype-format

plugin to format HTML
JavaScript
28
star
14

rehype-dom

HTML processor to parse and compile with browser APIs, powered by plugins
JavaScript
25
star
15

rehype-retext

plugin to transform from HTML (rehype) to prose (retext)
JavaScript
17
star
16

rehype-twoslash

plugin to process JavaScript and TypeScript code with `twoslash` and highlight it with `starry-night`
JavaScript
14
star
17

rehype-github

rehype plugins that match how GitHub transforms markdown on their site
HTML
14
star
18

rehype-picture

plugin to wrap images in pictures
JavaScript
12
star
19

rehype-infer-reading-time-meta

rehype plugin to infer reading time as file metadata from the document
JavaScript
10
star
20

rehype-infer-description-meta

rehype plugin to infer file metadata from the contents of the document
JavaScript
9
star
21

camomile

Node.js HTTP image proxy to route images through SSL
JavaScript
8
star
22

ideas

Share ideas for new utilities and tools built with @rehypejs
6
star
23

rehype-starry-night

plugin to apply syntax highlighting to code with `starry-night`
JavaScript
5
star
24

rehype-infer-title-meta

plugin to infer file metadata from the main title of a document
JavaScript
5
star
25

.github

Community health files for rehype
TypeScript
2
star
26

rehype-shift-heading

plugin to change the rank (depth, level) of headings
JavaScript
2
star