ant-design/components/anchor/Anchor.tsx

327 lines
8.9 KiB
TypeScript
Raw Normal View History

import classNames from 'classnames';
import addEventListener from 'rc-util/lib/Dom/addEventListener';
2022-06-22 14:57:09 +08:00
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';
2022-06-22 14:57:09 +08:00
import scrollTo from '../_util/scrollTo';
import AnchorContext from './context';
import useStyle from './style';
export type AnchorContainer = HTMLElement | Window;
2018-03-30 15:55:54 +08:00
function getDefaultContainer() {
return window;
}
2018-03-30 15:55:54 +08:00
function getOffsetTop(element: HTMLElement, container: AnchorContainer): number {
if (!element.getClientRects().length) {
return 0;
}
const rect = element.getBoundingClientRect();
if (rect.width || rect.height) {
2018-03-30 15:55:54 +08:00
if (container === window) {
2018-09-30 16:07:01 +08:00
container = element.ownerDocument!.documentElement!;
2018-03-30 15:55:54 +08:00
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;
children?: React.ReactNode;
offsetTop?: number;
bounds?: number;
affix?: boolean;
showInkInFixed?: boolean;
2018-03-30 15:55:54 +08:00
getContainer?: () => AnchorContainer;
/** Return customize highlight anchor */
getCurrentAnchor?: (activeLink: string) => string;
2018-12-07 20:02:01 +08:00
onClick?: (
e: React.MouseEvent<HTMLElement>,
link: { title: React.ReactNode; href: string },
) => void;
2019-07-23 20:02:40 +08:00
/** 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;
}
interface InternalAnchorProps extends AnchorProps {
anchorPrefixCls: string;
rootClassName: string;
}
export interface AnchorState {
activeLink: null | string;
2018-03-30 15:55:54 +08:00
}
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;
2018-12-07 20:02:01 +08:00
onClick?: (
e: React.MouseEvent<HTMLElement>,
link: { title: React.ReactNode; href: string },
) => void;
}
const AnchorContent: React.FC<InternalAnchorProps> = (props) => {
const {
2022-11-07 23:32:46 +08:00
rootClassName,
anchorPrefixCls: prefixCls,
className = '',
style,
offsetTop,
affix = true,
showInkInFixed = false,
children,
bounds,
targetOffset,
onClick,
onChange,
getContainer,
getCurrentAnchor,
} = props;
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());
2018-12-07 20:02:01 +08:00
if (!sharpLinkMatch) {
return;
}
const target = document.getElementById(sharpLinkMatch[1]);
2018-03-30 15:55:54 +08:00
if (target) {
const top = getOffsetTop(target, container);
if (top < _offsetTop + _bounds) {
linkSections.push({ link, top });
2018-03-30 15:55:54 +08:00
}
}
});
if (linkSections.length) {
2018-12-07 20:02:01 +08:00
const maxSection = linkSections.reduce((prev, curr) => (curr.top > prev.top ? curr : prev));
return maxSection.link;
}
return '';
};
2019-08-14 17:07:58 +08:00
const setCurrentActiveLink = (link: string) => {
if (activeLinkRef.current === link) {
2019-08-14 17:07:58 +08:00
return;
}
// https://github.com/ant-design/ant-design/issues/30584
const newLink = typeof getCurrentAnchor === 'function' ? getCurrentAnchor(link) : link;
setActiveLink(newLink);
activeLinkRef.current = newLink;
2019-08-14 17:07:58 +08:00
// onChange should respect the original link (which may caused by
// window scroll or user click), not the new link
onChange?.(link);
2019-08-05 18:38:10 +08:00
};
const handleScroll = React.useCallback(() => {
if (animating.current) {
return;
}
if (typeof getCurrentAnchor === 'function') {
2019-08-05 18:38:10 +08:00
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(
2022-11-07 23:32:46 +08:00
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 anchorContent = (
<div ref={wrapperRef} className={wrapperClass} style={wrapperStyle}>
<div className={anchorClass}>
<div className={`${prefixCls}-ink`}>
<span className={inkClass} ref={spanLinkNode} />
</div>
{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);
2022-11-07 23:32:46 +08:00
return wrapSSR(
<AnchorContent {...props} rootClassName={hashId} anchorPrefixCls={anchorPrefixCls} />,
);
};
export default Anchor;