mirror of
https://github.com/facebook/docusaurus.git
synced 2025-06-26 06:27:59 +02:00
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:
parent
82ded54b1a
commit
93894e7bdc
4 changed files with 93 additions and 1 deletions
|
@ -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',
|
||||
};
|
||||
|
|
56
packages/docusaurus-mdx-loader/src/linkHeadings.js
Normal file
56
packages/docusaurus-mdx-loader/src/linkHeadings.js
Normal 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;
|
Loading…
Add table
Add a link
Reference in a new issue