forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAppTableOfContents.js
239 lines (212 loc) · 6.59 KB
/
AppTableOfContents.js
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import throttle from 'lodash/throttle';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import NoSsr from '@mui/material/NoSsr';
import Link from 'docs/src/modules/components/Link';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import TableOfContentsBanner from 'docs/src/components/banner/TableOfContentsBanner';
const Nav = styled('nav')(({ theme }) => ({
top: 'var(--MuiDocs-header-height)',
order: 1,
width: 240,
flexShrink: 0,
position: 'sticky',
height: 'calc(100vh - var(--MuiDocs-header-height))',
overflowY: 'auto',
padding: theme.spacing(2, 4, 2, 0),
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
},
}));
const NavLabel = styled(Typography)(({ theme }) => ({
marginTop: theme.spacing(2),
marginBottom: theme.spacing(1),
paddingLeft: theme.spacing(1.4),
fontSize: theme.typography.pxToRem(11),
fontWeight: theme.typography.fontWeightBold,
textTransform: 'uppercase',
letterSpacing: '.08rem',
color: theme.palette.grey[600],
}));
const NavList = styled(Typography)({
padding: 0,
margin: 0,
listStyle: 'none',
});
const NavItem = styled(Link, {
shouldForwardProp: (prop) => prop !== 'active' && prop !== 'secondary',
})(({ active, secondary, theme }) => {
const activeStyles = {
borderLeftColor:
theme.palette.mode === 'light' ? theme.palette.primary[200] : theme.palette.primary[600],
color: theme.palette.mode === 'dark' ? theme.palette.primary[300] : theme.palette.primary[600],
'&:hover': {
borderLeftColor:
theme.palette.mode === 'light' ? theme.palette.primary[600] : theme.palette.primary[400],
color:
theme.palette.mode === 'light' ? theme.palette.primary[600] : theme.palette.primary[400],
},
};
return {
fontSize: theme.typography.pxToRem(13),
padding: theme.spacing(0, 1, 0, secondary ? 2.5 : '10px'),
margin: theme.spacing(0.5, 0, 1, 0),
borderLeft: `1px solid transparent`,
boxSizing: 'border-box',
fontWeight: 500,
'&:hover': {
borderLeftColor:
theme.palette.mode === 'light' ? theme.palette.grey[400] : theme.palette.grey[600],
color: theme.palette.mode === 'light' ? theme.palette.grey[600] : theme.palette.grey[200],
},
...(!active && {
color: theme.palette.mode === 'dark' ? theme.palette.grey[500] : theme.palette.text.primary,
}),
// TODO: We probably want `aria-current="location"` instead.
...(active && activeStyles),
'&:active': activeStyles,
};
});
const noop = () => {};
function useThrottledOnScroll(callback, delay) {
const throttledCallback = React.useMemo(
() => (callback ? throttle(callback, delay) : noop),
[callback, delay],
);
React.useEffect(() => {
if (throttledCallback === noop) {
return undefined;
}
window.addEventListener('scroll', throttledCallback);
return () => {
window.removeEventListener('scroll', throttledCallback);
throttledCallback.cancel();
};
}, [throttledCallback]);
}
function flatten(headings) {
const itemsWithNode = [];
headings.forEach((item) => {
itemsWithNode.push(item);
if (item.children.length > 0) {
item.children.forEach((subitem) => {
itemsWithNode.push(subitem);
});
}
});
return itemsWithNode;
}
export default function AppTableOfContents(props) {
const { toc } = props;
const t = useTranslate();
const items = React.useMemo(() => flatten(toc), [toc]);
const [activeState, setActiveState] = React.useState(null);
const clickedRef = React.useRef(false);
const unsetClickedRef = React.useRef(null);
const findActiveIndex = React.useCallback(() => {
// Don't set the active index based on scroll if a link was just clicked
if (clickedRef.current) {
return;
}
let active;
for (let i = items.length - 1; i >= 0; i -= 1) {
// No hash if we're near the top of the page
if (document.documentElement.scrollTop < 200) {
active = { hash: null };
break;
}
const item = items[i];
const node = document.getElementById(item.hash);
if (process.env.NODE_ENV !== 'production') {
if (!node) {
console.error(`Missing node on the item ${JSON.stringify(item, null, 2)}`);
}
}
if (
node &&
node.offsetTop <
document.documentElement.scrollTop + document.documentElement.clientHeight / 8
) {
active = item;
break;
}
}
if (active && activeState !== active.hash) {
setActiveState(active.hash);
}
}, [activeState, items]);
// Corresponds to 10 frames at 60 Hz
useThrottledOnScroll(items.length > 0 ? findActiveIndex : null, 166);
const handleClick = (hash) => (event) => {
// Ignore click for new tab/new window behavior
if (
event.defaultPrevented ||
event.button !== 0 || // ignore everything but left-click
event.metaKey ||
event.ctrlKey ||
event.altKey ||
event.shiftKey
) {
return;
}
// Used to disable findActiveIndex if the page scrolls due to a click
clickedRef.current = true;
unsetClickedRef.current = setTimeout(() => {
clickedRef.current = false;
}, 1000);
if (activeState !== hash) {
setActiveState(hash);
}
};
React.useEffect(
() => () => {
clearTimeout(unsetClickedRef.current);
},
[],
);
const itemLink = (item, secondary) => (
<NavItem
display="block"
href={`#${item.hash}`}
underline="none"
onClick={handleClick(item.hash)}
active={activeState === item.hash}
secondary={secondary}
>
<span dangerouslySetInnerHTML={{ __html: item.text }} />
</NavItem>
);
return (
<Nav aria-label={t('pageTOC')}>
<NoSsr>
<TableOfContentsBanner />
</NoSsr>
{toc.length > 0 ? (
<React.Fragment>
<NavLabel gutterBottom>{t('tableOfContents')}</NavLabel>
<NavList component="ul">
{toc.map((item) => (
<li key={item.text}>
{itemLink(item)}
{item.children.length > 0 ? (
<NavList as="ul">
{item.children.map((subitem) => (
<li key={subitem.text}>{itemLink(subitem, true)}</li>
))}
</NavList>
) : null}
</li>
))}
</NavList>
</React.Fragment>
) : null}
</Nav>
);
}
AppTableOfContents.propTypes = {
toc: PropTypes.array.isRequired,
};