feat(v2): headings anchors (#1385)

* feat(v2): headings anchors

* misc: make hash link appear on hover

* misc: convert to rem
This commit is contained in:
Radosław Miernik 2019-04-24 06:41:51 +02:00 committed by Yangshun Tay
parent 82ded54b1a
commit 93894e7bdc
4 changed files with 93 additions and 1 deletions

View file

@ -9,10 +9,11 @@ const mdx = require('@mdx-js/mdx');
const rehypePrism = require('@mapbox/rehype-prism');
const emoji = require('remark-emoji');
const slug = require('rehype-slug');
const linkHeadings = require('./linkHeadings');
const rightToc = require('./rightToc');
const DEFAULT_OPTIONS = {
rehypePlugins: [[rehypePrism, {ignoreMissing: true}], slug],
rehypePlugins: [[rehypePrism, {ignoreMissing: true}], slug, linkHeadings],
remarkPlugins: [emoji, rightToc],
prismTheme: 'prism-themes/themes/prism-atom-dark.css',
};

View file

@ -0,0 +1,56 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const visit = require('unist-util-visit');
const createAnchor = id => ({
type: 'element',
tagName: 'a',
properties: {
ariaHidden: true,
className: 'anchor',
id,
},
});
const createLink = id => ({
type: 'element',
tagName: 'a',
properties: {
ariaHidden: true,
className: 'hash-link',
href: `#${id}`,
},
children: [
{
type: 'text',
value: '#',
},
],
});
const headings = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
const visitor = node => {
const {properties} = node;
if (!properties || !properties.id || !headings.includes(node.tagName)) {
return;
}
node.children.unshift(createLink(properties.id));
node.children.unshift(createAnchor(properties.id));
delete properties.id;
};
const transformer = node => {
visit(node, 'element', visitor);
};
const plugin = () => transformer;
module.exports = plugin;