-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtoctree.tsx
98 lines (89 loc) · 2.45 KB
/
toctree.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import * as React from 'react';
import { TableOfContentsItem } from './tocitem';
import { TableOfContents } from './tokens';
/**
* Interface describing component properties.
*/
export interface ITableOfContentsTreeProps {
/**
* Currently active heading.
*/
activeHeading: TableOfContents.IHeading | null;
/**
* Type of document supported by the model.
*/
documentType: string;
/**
* List of headings to render.
*/
headings: TableOfContents.IHeading[];
/**
* Set active heading.
*/
setActiveHeading: (heading: TableOfContents.IHeading) => void;
/**
* Collapse heading callback.
*/
onCollapseChange: (heading: TableOfContents.IHeading) => void;
}
/**
* React component for a table of contents tree.
*/
export class TableOfContentsTree extends React.PureComponent<ITableOfContentsTreeProps> {
/**
* Renders a table of contents tree.
*/
render(): JSX.Element {
const { documentType } = this.props;
return (
<ol
className="jp-TableOfContents-content"
{...{ 'data-document-type': documentType }}
>
{this.buildTree()}
</ol>
);
}
/**
* Convert the flat headings list to a nested tree list
*/
protected buildTree(): JSX.Element[] {
if (this.props.headings.length === 0) {
return [];
}
let globalIndex = 0;
const getChildren = (
items: TableOfContents.IHeading[],
level: number
): JSX.Element[] => {
const nested = new Array<JSX.Element>();
while (globalIndex < items.length) {
const current = items[globalIndex];
if (current.level >= level) {
globalIndex += 1;
const next = items[globalIndex];
nested.push(
<TableOfContentsItem
key={`${current.level}-${current.text}`}
isActive={
!!this.props.activeHeading &&
current === this.props.activeHeading
}
heading={current}
onMouseDown={this.props.setActiveHeading}
onCollapse={this.props.onCollapseChange}
>
{next && next.level > level && getChildren(items, level + 1)}
</TableOfContentsItem>
);
} else {
break;
}
}
return nested;
};
return getChildren(this.props.headings, this.props.headings[0].level);
}
}