Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

Heading.js

37 lines1.0 KB

1import * as React from 'react';
2​
3const collectText = (el, acc = []) => {
4 if (el) {
5 if (typeof el === 'string') acc.push(el);
6 if (Array.isArray(el)) el.map(item => collectText(item, acc));
7 if (typeof el === 'object') collectText(el.props && el.props.children, acc);
8 }
9​
10 return acc.join('').trim();
11}; // Structure is in Heading
12​
13​
14export const getTocDataFromHeading = el => {
15 return {
16 text: el.parentElement?.getAttribute('[data-text]'),
17 url: el.parentElement?.getAttribute('href')
18 };
19};
20export const NOTION_ANCHOR_CLASSNAME = 'notion-anchor';
21export default (({
22 children: component,
23 id
24}) => {
25 const children = component.props.children || '';
26 let text = children;
27​
28 if (null == id) {
29 id = collectText(text).toLowerCase().replace(/\s/g, '-').replace(/[?!:]/g, '');
30 }
31​
32 return <a href={`#${id}`} id={id} className={NOTION_ANCHOR_CLASSNAME} style={{
33 color: 'inherit'
34 }} data-heading-text={collectText(text)} data-heading-depth={component.type.replace('h', '')}>
35 {component}
36 </a>;
37});