forked from ant-design/ant-design
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Anchor.tsx
353 lines (305 loc) · 9.76 KB
/
Anchor.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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import classNames from 'classnames';
import addEventListener from 'rc-util/lib/Dom/addEventListener';
import * as React from 'react';
import Affix from '../affix';
import type { ConfigConsumerProps } from '../config-provider';
import { ConfigContext } from '../config-provider';
import getScroll from '../_util/getScroll';
import scrollTo from '../_util/scrollTo';
import warning from '../_util/warning';
import AnchorContext from './context';
import type { AnchorLinkBaseProps } from './AnchorLink';
import AnchorLink from './AnchorLink';
import useStyle from './style';
export interface AnchorLinkItemProps extends AnchorLinkBaseProps {
key: React.Key;
children?: AnchorLinkItemProps[];
}
export type AnchorContainer = HTMLElement | Window;
function getDefaultContainer() {
return window;
}
function getOffsetTop(element: HTMLElement, container: AnchorContainer): number {
if (!element.getClientRects().length) {
return 0;
}
const rect = element.getBoundingClientRect();
if (rect.width || rect.height) {
if (container === window) {
container = element.ownerDocument!.documentElement!;
return rect.top - container.clientTop;
}
return rect.top - (container as HTMLElement).getBoundingClientRect().top;
}
return rect.top;
}
const sharpMatcherRegx = /#([\S ]+)$/;
interface Section {
link: string;
top: number;
}
export interface AnchorProps {
prefixCls?: string;
className?: string;
style?: React.CSSProperties;
/**
* @deprecated Please use `items` instead.
*/
children?: React.ReactNode;
offsetTop?: number;
bounds?: number;
affix?: boolean;
showInkInFixed?: boolean;
getContainer?: () => AnchorContainer;
/** Return customize highlight anchor */
getCurrentAnchor?: (activeLink: string) => string;
onClick?: (
e: React.MouseEvent<HTMLElement>,
link: { title: React.ReactNode; href: string },
) => void;
/** Scroll to target offset value, if none, it's offsetTop prop value or 0. */
targetOffset?: number;
/** Listening event when scrolling change active link */
onChange?: (currentActiveLink: string) => void;
items?: AnchorLinkItemProps[];
}
interface InternalAnchorProps extends AnchorProps {
anchorPrefixCls: string;
rootClassName: string;
}
export interface AnchorState {
activeLink: null | string;
}
export interface AnchorDefaultProps extends AnchorProps {
prefixCls: string;
affix: boolean;
showInkInFixed: boolean;
getContainer: () => AnchorContainer;
}
export interface AntAnchor {
registerLink: (link: string) => void;
unregisterLink: (link: string) => void;
activeLink: string | null;
scrollTo: (link: string) => void;
onClick?: (
e: React.MouseEvent<HTMLElement>,
link: { title: React.ReactNode; href: string },
) => void;
}
const AnchorContent: React.FC<InternalAnchorProps> = (props) => {
const {
rootClassName,
anchorPrefixCls: prefixCls,
className = '',
style,
offsetTop,
affix = true,
showInkInFixed = false,
children,
items,
bounds,
targetOffset,
onClick,
onChange,
getContainer,
getCurrentAnchor,
} = props;
// =================== Warning =====================
if (process.env.NODE_ENV !== 'production') {
warning(!children, 'Anchor', '`Anchor children` is deprecated. Please use `items` instead.');
}
const [links, setLinks] = React.useState<string[]>([]);
const [activeLink, setActiveLink] = React.useState<string | null>(null);
const activeLinkRef = React.useRef<string | null>(activeLink);
const wrapperRef = React.useRef<HTMLDivElement>(null);
const spanLinkNode = React.useRef<HTMLSpanElement>(null);
const animating = React.useRef<boolean>(false);
const { direction, getTargetContainer } = React.useContext<ConfigConsumerProps>(ConfigContext);
const getCurrentContainer = getContainer ?? getTargetContainer ?? getDefaultContainer;
const dependencyListItem: React.DependencyList[number] = JSON.stringify(links);
const registerLink = React.useCallback<AntAnchor['registerLink']>(
(link) => {
if (!links.includes(link)) {
setLinks((prev) => [...prev, link]);
}
},
[dependencyListItem],
);
const unregisterLink = React.useCallback<AntAnchor['unregisterLink']>(
(link) => {
if (links.includes(link)) {
setLinks((prev) => prev.filter((i) => i !== link));
}
},
[dependencyListItem],
);
const updateInk = () => {
const linkNode = wrapperRef.current?.querySelector<HTMLElement>(
`.${prefixCls}-link-title-active`,
);
if (linkNode && spanLinkNode.current) {
spanLinkNode.current.style.top = `${linkNode.offsetTop + linkNode.clientHeight / 2}px`;
spanLinkNode.current.style.height = `${linkNode.clientHeight}px`;
}
};
const getInternalCurrentAnchor = (_links: string[], _offsetTop = 0, _bounds = 5): string => {
const linkSections: Section[] = [];
const container = getCurrentContainer();
_links.forEach((link) => {
const sharpLinkMatch = sharpMatcherRegx.exec(link?.toString());
if (!sharpLinkMatch) {
return;
}
const target = document.getElementById(sharpLinkMatch[1]);
if (target) {
const top = getOffsetTop(target, container);
if (top < _offsetTop + _bounds) {
linkSections.push({ link, top });
}
}
});
if (linkSections.length) {
const maxSection = linkSections.reduce((prev, curr) => (curr.top > prev.top ? curr : prev));
return maxSection.link;
}
return '';
};
const setCurrentActiveLink = (link: string) => {
if (activeLinkRef.current === link) {
return;
}
// https://github.com/ant-design/ant-design/issues/30584
const newLink = typeof getCurrentAnchor === 'function' ? getCurrentAnchor(link) : link;
setActiveLink(newLink);
activeLinkRef.current = newLink;
// onChange should respect the original link (which may caused by
// window scroll or user click), not the new link
onChange?.(link);
};
const handleScroll = React.useCallback(() => {
if (animating.current) {
return;
}
if (typeof getCurrentAnchor === 'function') {
return;
}
const currentActiveLink = getInternalCurrentAnchor(
links,
targetOffset !== undefined ? targetOffset : offsetTop || 0,
bounds,
);
setCurrentActiveLink(currentActiveLink);
}, [dependencyListItem, targetOffset, offsetTop]);
const handleScrollTo = React.useCallback<(link: string) => void>(
(link) => {
setCurrentActiveLink(link);
const container = getCurrentContainer();
const scrollTop = getScroll(container, true);
const sharpLinkMatch = sharpMatcherRegx.exec(link);
if (!sharpLinkMatch) {
return;
}
const targetElement = document.getElementById(sharpLinkMatch[1]);
if (!targetElement) {
return;
}
const eleOffsetTop = getOffsetTop(targetElement, container);
let y = scrollTop + eleOffsetTop;
y -= targetOffset !== undefined ? targetOffset : offsetTop || 0;
animating.current = true;
scrollTo(y, {
getContainer: getCurrentContainer,
callback() {
animating.current = false;
},
});
},
[targetOffset, offsetTop],
);
const inkClass = classNames(
{
[`${prefixCls}-ink-ball-visible`]: activeLink,
},
`${prefixCls}-ink-ball`,
);
const wrapperClass = classNames(
rootClassName,
`${prefixCls}-wrapper`,
{
[`${prefixCls}-rtl`]: direction === 'rtl',
},
className,
);
const anchorClass = classNames(prefixCls, {
[`${prefixCls}-fixed`]: !affix && !showInkInFixed,
});
const wrapperStyle: React.CSSProperties = {
maxHeight: offsetTop ? `calc(100vh - ${offsetTop}px)` : '100vh',
...style,
};
const createNestedLink = (options?: AnchorLinkItemProps[]) =>
Array.isArray(options)
? options.map((item) => (
<AnchorLink {...item} key={item.key}>
{createNestedLink(item.children)}
</AnchorLink>
))
: null;
const anchorContent = (
<div ref={wrapperRef} className={wrapperClass} style={wrapperStyle}>
<div className={anchorClass}>
<div className={`${prefixCls}-ink`}>
<span className={inkClass} ref={spanLinkNode} />
</div>
{'items' in props ? createNestedLink(items) : children}
</div>
</div>
);
React.useEffect(() => {
const scrollContainer = getCurrentContainer();
const scrollEvent = addEventListener(scrollContainer, 'scroll', handleScroll);
handleScroll();
return () => {
scrollEvent?.remove();
};
}, [dependencyListItem]);
React.useEffect(() => {
if (typeof getCurrentAnchor === 'function') {
setCurrentActiveLink(getCurrentAnchor(activeLinkRef.current || ''));
}
}, [getCurrentAnchor]);
React.useEffect(() => {
updateInk();
}, [getCurrentAnchor, dependencyListItem, activeLink]);
const memoizedContextValue = React.useMemo<AntAnchor>(
() => ({
registerLink,
unregisterLink,
scrollTo: handleScrollTo,
activeLink,
onClick,
}),
[activeLink, onClick, handleScrollTo],
);
return (
<AnchorContext.Provider value={memoizedContextValue}>
{affix ? (
<Affix offsetTop={offsetTop} target={getCurrentContainer}>
{anchorContent}
</Affix>
) : (
anchorContent
)}
</AnchorContext.Provider>
);
};
const Anchor: React.FC<AnchorProps> = (props) => {
const { prefixCls: customizePrefixCls } = props;
const { getPrefixCls } = React.useContext<ConfigConsumerProps>(ConfigContext);
const anchorPrefixCls = getPrefixCls('anchor', customizePrefixCls);
const [wrapSSR, hashId] = useStyle(anchorPrefixCls);
return wrapSSR(
<AnchorContent {...props} rootClassName={hashId} anchorPrefixCls={anchorPrefixCls} />,
);
};
export default Anchor;