Add memorized hook for table of contents (#2242)

* Create hook for converter function

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>

* Add tests

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2022-07-31 01:04:58 +02:00 committed by GitHub
parent 4be2e43914
commit 2e5fd5cc5c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 154 additions and 23 deletions

View file

@ -0,0 +1,69 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Table of contents renders correctly 1`] = `
<div>
<div
class="markdown-toc customClassName"
>
<ul>
<li>
<a
href="https://example.org/#level-1"
title="Level 1"
>
Level 1
</a>
<ul>
<li>
<a
href="https://example.org/#level-2"
title="Level 2"
>
Level 2
</a>
<ul>
<li>
<a
href="https://example.org/#level-3"
title="Level 3"
>
Level 3
</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
`;
exports[`Table of contents renders only in requested max depth 1`] = `
<div>
<div
class="markdown-toc customClassName"
>
<ul>
<li>
<a
href="https://example.org/#level-1"
title="Level 1"
>
Level 1
</a>
<ul>
<li>
<a
href="https://example.org/#level-2"
title="Level 2"
>
Level 2
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
`;

View file

@ -0,0 +1,56 @@
/*
* SPDX-FileCopyrightText: 2022 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { mockI18n } from '../../markdown-renderer/test-utils/mock-i18n'
import { render } from '@testing-library/react'
import { TableOfContents } from './table-of-contents'
import type { TocAst } from 'markdown-it-toc-done-right'
describe('Table of contents', () => {
beforeAll(async () => {
await mockI18n()
})
const level4Ast: TocAst = {
n: 'Level 4',
l: 4,
c: []
}
const level3Ast: TocAst = {
n: 'Level 3',
l: 3,
c: [level4Ast]
}
const level2Ast: TocAst = {
n: 'Level 2',
l: 2,
c: [level3Ast]
}
const level1Ast: TocAst = {
n: 'Level 1',
l: 1,
c: [level2Ast]
}
const level0Ast: TocAst = {
n: '',
l: 0,
c: [level1Ast]
}
it('renders correctly', () => {
const view = render(
<TableOfContents ast={level0Ast} className={'customClassName'} baseUrl={'https://example.org'} />
)
expect(view.container).toMatchSnapshot()
})
it('renders only in requested max depth', () => {
const view = render(
<TableOfContents ast={level0Ast} maxDepth={2} className={'customClassName'} baseUrl={'https://example.org'} />
)
expect(view.container).toMatchSnapshot()
})
})

View file

@ -5,17 +5,17 @@
*/
import type { TocAst } from 'markdown-it-toc-done-right'
import React, { useMemo } from 'react'
import React from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { ShowIf } from '../../common/show-if/show-if'
import { buildReactDomFromTocAst } from './build-react-dom-from-toc-ast'
import styles from './table-of-contents.module.scss'
import { useBuildReactDomFromTocAst } from './use-build-react-dom-from-toc-ast'
export interface TableOfContentsProps {
ast: TocAst
maxDepth?: number
className?: string
baseUrl?: string
baseUrl: string
}
/**
@ -28,10 +28,7 @@ export interface TableOfContentsProps {
*/
export const TableOfContents: React.FC<TableOfContentsProps> = ({ ast, maxDepth = 3, className, baseUrl }) => {
useTranslation()
const tocTree = useMemo(
() => buildReactDomFromTocAst(ast, maxDepth, new Map<string, number>(), false, baseUrl),
[ast, maxDepth, baseUrl]
)
const tocTree = useBuildReactDomFromTocAst(ast, maxDepth, baseUrl)
return (
<div className={`${styles['markdown-toc']} ${className ?? ''}`}>

View file

@ -6,7 +6,7 @@
import type { TocAst } from 'markdown-it-toc-done-right'
import type { ReactElement } from 'react'
import React, { Fragment } from 'react'
import React, { Fragment, useMemo } from 'react'
import { ShowIf } from '../../common/show-if/show-if'
import { tocSlugify } from './toc-slugify'
import { JumpAnchor } from '../../markdown-renderer/markdown-extension/link-replacer/jump-anchor'
@ -17,15 +17,13 @@ import { JumpAnchor } from '../../markdown-renderer/markdown-extension/link-repl
* @param toc The abstract syntax tree of the document for TOC generation
* @param levelsToShowUnderThis The amount of levels which should be shown below this TOC item
* @param headerCounts Map that contains the number of occurrences of single header names to allow suffixing them with a number to make them distinguishable
* @param wrapInListItem Whether to wrap the TOC content in a list item
* @param baseUrl The base URL used for generating absolute links to the note with the correct slug anchor
*/
export const buildReactDomFromTocAst = (
const buildReactDomFromTocAst = (
toc: TocAst,
levelsToShowUnderThis: number,
headerCounts: Map<string, number>,
wrapInListItem: boolean,
baseUrl?: string
baseUrl: string
): ReactElement | null => {
if (levelsToShowUnderThis < 0) {
return null
@ -38,24 +36,35 @@ export const buildReactDomFromTocAst = (
headerCounts.set(rawName, nameCount)
const content = (
const children = toc.c
.map((child) => buildReactDomFromTocAst(child, levelsToShowUnderThis - 1, headerCounts, baseUrl))
.filter((value) => !!value)
.map((child, index) => <li key={index}>{child}</li>)
return (
<Fragment>
<ShowIf condition={toc.l > 0}>
<JumpAnchor href={headlineUrl} title={rawName} jumpTargetId={slug.slice(1)}>
{rawName}
</JumpAnchor>
</ShowIf>
<ShowIf condition={toc.c.length > 0}>
<ul>
{toc.c.map((child) => buildReactDomFromTocAst(child, levelsToShowUnderThis - 1, headerCounts, true, baseUrl))}
</ul>
<ShowIf condition={children.length > 0}>
<ul>{children}</ul>
</ShowIf>
</Fragment>
)
if (wrapInListItem) {
return <li key={headlineUrl}>{content}</li>
} else {
return content
}
}
/**
* Generates a React DOM part for the table of contents from the given AST of the document.
*
* @param toc The abstract syntax tree of the document for TOC generation
* @param maxDepth The maximum depth of levels which should be shown in the TOC
* @param baseUrl The base URL used for generating absolute links to the note with the correct slug anchor
*/
export const useBuildReactDomFromTocAst = (toc: TocAst, maxDepth: number, baseUrl: string) => {
return useMemo(
() => buildReactDomFromTocAst(toc, maxDepth, new Map<string, number>(), baseUrl),
[toc, maxDepth, baseUrl]
)
}