ant-design/components/anchor/Anchor.tsx

363 lines
9.5 KiB
TypeScript
Raw Normal View History

import classNames from 'classnames';
import memoizeOne from 'memoize-one';
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;
}
class Anchor extends React.Component<InternalAnchorProps, AnchorState, ConfigConsumerProps> {
static contextType = ConfigContext;
state = {
activeLink: null,
};
context: ConfigConsumerProps;
private wrapperRef = React.createRef<HTMLDivElement>();
2017-11-22 11:34:46 +08:00
private inkNode: HTMLSpanElement;
2019-08-05 18:38:10 +08:00
// scroll scope's container
private scrollContainer: HTMLElement | Window;
private links: string[] = [];
2019-08-05 18:38:10 +08:00
private scrollEvent: ReturnType<typeof addEventListener>;
2019-08-05 18:38:10 +08:00
private animating: boolean;
private prefixCls?: string;
// Context
registerLink: AntAnchor['registerLink'] = link => {
if (!this.links.includes(link)) {
this.links.push(link);
}
};
unregisterLink: AntAnchor['unregisterLink'] = link => {
const index = this.links.indexOf(link);
if (index !== -1) {
this.links.splice(index, 1);
}
};
getContainer = () => {
const { getTargetContainer } = this.context;
const { getContainer } = this.props;
2022-10-06 18:53:06 +08:00
const getFunc = getContainer ?? getTargetContainer ?? getDefaultContainer;
return getFunc();
};
componentDidMount() {
this.scrollContainer = this.getContainer();
this.scrollEvent = addEventListener(this.scrollContainer, 'scroll', this.handleScroll);
this.handleScroll();
}
componentDidUpdate() {
const { getCurrentAnchor } = this.props;
const { activeLink } = this.state;
if (this.scrollEvent) {
const currentContainer = this.getContainer();
if (this.scrollContainer !== currentContainer) {
this.scrollContainer = currentContainer;
this.scrollEvent.remove();
this.scrollEvent = addEventListener(this.scrollContainer, 'scroll', this.handleScroll);
this.handleScroll();
}
}
if (typeof getCurrentAnchor === 'function') {
this.setCurrentActiveLink(getCurrentAnchor(activeLink || ''), false);
}
this.updateInk();
}
2019-08-05 18:38:10 +08:00
componentWillUnmount() {
if (this.scrollEvent) {
this.scrollEvent.remove();
}
2019-08-14 16:32:54 +08:00
}
getCurrentAnchor(offsetTop = 0, bounds = 5): string {
const linkSections: Array<Section> = [];
const container = this.getContainer();
this.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
handleScrollTo = (link: string) => {
const { offsetTop, targetOffset } = this.props;
2019-08-14 17:07:58 +08:00
this.setCurrentActiveLink(link);
const container = this.getContainer();
2019-08-14 17:07:58 +08:00
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;
this.animating = true;
scrollTo(y, {
callback: () => {
this.animating = false;
},
getContainer: this.getContainer,
2019-08-14 17:07:58 +08:00
});
};
2019-08-05 18:38:10 +08:00
saveInkNode = (node: HTMLSpanElement) => {
this.inkNode = node;
};
setCurrentActiveLink = (link: string, triggerChange = true) => {
const { activeLink } = this.state;
const { onChange, getCurrentAnchor } = this.props;
if (activeLink === link) {
return;
}
// https://github.com/ant-design/ant-design/issues/30584
this.setState({
activeLink: typeof getCurrentAnchor === 'function' ? getCurrentAnchor(link) : link,
});
if (triggerChange) {
onChange?.(link);
}
};
2019-08-05 18:38:10 +08:00
handleScroll = () => {
if (this.animating) {
return;
}
const { offsetTop, bounds, targetOffset } = this.props;
const currentActiveLink = this.getCurrentAnchor(
targetOffset !== undefined ? targetOffset : offsetTop || 0,
bounds,
);
this.setCurrentActiveLink(currentActiveLink);
2019-08-05 18:38:10 +08:00
};
updateInk = () => {
const { prefixCls, wrapperRef } = this;
const anchorNode = wrapperRef.current;
const linkNode = anchorNode?.querySelector<HTMLElement>(`.${prefixCls}-link-title-active`);
if (linkNode) {
this.inkNode.style.top = `${linkNode.offsetTop + linkNode.clientHeight / 2 - 4.5}px`;
}
2018-12-07 20:02:01 +08:00
};
getMemoizedContextValue = memoizeOne(
(link: AntAnchor['activeLink'], onClickFn: AnchorProps['onClick']): AntAnchor => ({
registerLink: this.registerLink,
unregisterLink: this.unregisterLink,
scrollTo: this.handleScrollTo,
activeLink: link,
onClick: onClickFn,
}),
);
render() {
const { direction } = this.context;
const {
anchorPrefixCls: prefixCls,
className = '',
style,
offsetTop,
affix = true,
showInkInFixed = false,
children,
onClick,
rootClassName,
} = this.props;
const { activeLink } = this.state;
// To support old version react.
// Have to add prefixCls on the instance.
// https://github.com/facebook/react/issues/12397
this.prefixCls = prefixCls;
const inkClass = classNames(`${prefixCls}-ink-ball`, {
visible: activeLink,
});
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 anchorContent = (
<div ref={this.wrapperRef} className={wrapperClass} style={wrapperStyle}>
<div className={anchorClass}>
2018-12-07 20:02:01 +08:00
<div className={`${prefixCls}-ink`}>
<span className={inkClass} ref={this.saveInkNode} />
</div>
{children}
</div>
</div>
);
const contextValue = this.getMemoizedContextValue(activeLink, onClick);
return (
<AnchorContext.Provider value={contextValue}>
{affix ? (
<Affix offsetTop={offsetTop} target={this.getContainer}>
{anchorContent}
</Affix>
) : (
anchorContent
)}
</AnchorContext.Provider>
);
}
}
// just use in test
export type InternalAnchorClass = Anchor;
const AnchorFC = React.forwardRef<Anchor, AnchorProps>((props, ref) => {
const { prefixCls: customizePrefixCls } = props;
const { getPrefixCls } = React.useContext(ConfigContext);
const anchorPrefixCls = getPrefixCls('anchor', customizePrefixCls);
const [wrapSSR, hashId] = useStyle(anchorPrefixCls);
const anchorProps: InternalAnchorProps = {
...props,
anchorPrefixCls,
rootClassName: hashId,
};
return wrapSSR(<Anchor {...anchorProps} ref={ref} />);
});
export default AnchorFC;