ant-design/components/affix/index.tsx

322 lines
9.4 KiB
TypeScript
Raw Normal View History

import classNames from 'classnames';
import ResizeObserver from 'rc-resize-observer';
2022-06-22 14:57:09 +08:00
import omit from 'rc-util/lib/omit';
import React, { createRef, forwardRef, useContext } from 'react';
import throttleByAnimationFrame from '../_util/throttleByAnimationFrame';
import type { ConfigConsumerProps } from '../config-provider';
import { ConfigContext } from '../config-provider';
2022-06-22 15:18:03 +08:00
import useStyle from './style';
import { getFixedBottom, getFixedTop, getTargetRect } from './utils';
const TRIGGER_EVENTS = [
'resize',
'scroll',
'touchstart',
'touchmove',
'touchend',
'pageshow',
'load',
] as const;
function getDefaultTarget() {
2018-05-23 21:03:32 +08:00
return typeof window !== 'undefined' ? window : null;
}
2016-06-22 13:18:43 +08:00
// Affix
export interface AffixProps {
/** Triggered when the specified offset is reached from the top of the window */
2016-07-13 11:14:24 +08:00
offsetTop?: number;
/** Triggered when the specified offset is reached from the bottom of the window */
2016-07-13 11:14:24 +08:00
offsetBottom?: number;
style?: React.CSSProperties;
/** Callback function triggered when fixed state changes */
onChange?: (affixed?: boolean) => void;
/** Set the element that Affix needs to listen to its scroll event, the value is a function that returns the corresponding DOM element */
2017-11-22 11:49:35 +08:00
target?: () => Window | HTMLElement | null;
prefixCls?: string;
2019-01-31 11:20:58 +08:00
className?: string;
rootClassName?: string;
children: React.ReactNode;
2019-03-03 10:04:21 +08:00
}
interface InternalAffixProps extends AffixProps {
affixPrefixCls: string;
}
2019-03-03 10:04:21 +08:00
enum AffixStatus {
None,
Prepare,
2016-06-22 13:18:43 +08:00
}
2017-11-22 11:49:35 +08:00
export interface AffixState {
2019-03-03 10:04:21 +08:00
affixStyle?: React.CSSProperties;
placeholderStyle?: React.CSSProperties;
status: AffixStatus;
lastAffix: boolean;
prevTarget: Window | HTMLElement | null;
2017-11-22 11:49:35 +08:00
}
2023-02-22 10:42:25 +08:00
class InternalAffix extends React.Component<InternalAffixProps, AffixState> {
static contextType = ConfigContext;
2015-09-01 16:18:46 +08:00
2018-11-01 02:46:42 +08:00
state: AffixState = {
2019-03-03 11:40:10 +08:00
status: AffixStatus.None,
2019-03-03 10:04:21 +08:00
lastAffix: false,
prevTarget: null,
2018-11-01 02:46:42 +08:00
};
2016-07-13 17:22:23 +08:00
private placeholderNodeRef = createRef<HTMLDivElement>();
2019-08-05 18:38:10 +08:00
private fixedNodeRef = createRef<HTMLDivElement>();
2019-08-05 18:38:10 +08:00
private timer: NodeJS.Timeout | null;
2017-08-17 11:45:46 +08:00
context: ConfigConsumerProps;
private getTargetFunc() {
const { getTargetContainer } = this.context;
const { target } = this.props;
if (target !== undefined) {
return target;
}
2022-10-06 18:53:06 +08:00
return getTargetContainer ?? getDefaultTarget;
}
addListeners = () => {
const targetFunc = this.getTargetFunc();
const target = targetFunc?.();
const { prevTarget } = this.state;
if (prevTarget !== target) {
TRIGGER_EVENTS.forEach((eventName) => {
prevTarget?.removeEventListener(eventName, this.lazyUpdatePosition);
target?.addEventListener(eventName, this.lazyUpdatePosition);
});
2019-08-05 18:38:10 +08:00
this.updatePosition();
this.setState({ prevTarget: target });
2019-03-03 23:19:07 +08:00
}
};
removeListeners = () => {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
2022-11-24 10:08:44 +08:00
}
const { prevTarget } = this.state;
const targetFunc = this.getTargetFunc();
const newTarget = targetFunc?.();
TRIGGER_EVENTS.forEach((eventName) => {
newTarget?.removeEventListener(eventName, this.lazyUpdatePosition);
prevTarget?.removeEventListener(eventName, this.lazyUpdatePosition);
});
this.updatePosition.cancel();
// https://github.com/ant-design/ant-design/issues/22683
this.lazyUpdatePosition.cancel();
};
// Event handler
componentDidMount() {
// [Legacy] Wait for parent component ref has its value.
// We should use target as directly element instead of function which makes element check hard.
this.timer = setTimeout(this.addListeners);
}
componentDidUpdate(prevProps: AffixProps) {
this.addListeners();
if (
prevProps.offsetTop !== this.props.offsetTop ||
prevProps.offsetBottom !== this.props.offsetBottom
) {
this.updatePosition();
}
this.measure();
}
componentWillUnmount() {
this.removeListeners();
2019-03-03 10:04:21 +08:00
}
2015-08-03 16:49:42 +08:00
getOffsetTop = () => {
const { offsetBottom, offsetTop } = this.props;
return offsetBottom === undefined && offsetTop === undefined ? 0 : offsetTop;
};
2019-08-05 18:38:10 +08:00
getOffsetBottom = () => this.props.offsetBottom;
2019-03-03 10:04:21 +08:00
// =================== Measure ===================
measure = () => {
2019-03-03 11:40:10 +08:00
const { status, lastAffix } = this.state;
const { onChange } = this.props;
const targetFunc = this.getTargetFunc();
if (
status !== AffixStatus.Prepare ||
!this.fixedNodeRef.current ||
!this.placeholderNodeRef.current ||
!targetFunc
) {
2019-03-03 10:04:21 +08:00
return;
2015-08-04 15:03:00 +08:00
}
2019-03-03 11:40:10 +08:00
const offsetTop = this.getOffsetTop();
const offsetBottom = this.getOffsetBottom();
2019-03-03 11:40:10 +08:00
const targetNode = targetFunc();
if (targetNode) {
const newState: Partial<AffixState> = {
status: AffixStatus.None,
2019-03-03 10:04:21 +08:00
};
const placeholderRect = getTargetRect(this.placeholderNodeRef.current);
if (
placeholderRect.top === 0 &&
placeholderRect.left === 0 &&
placeholderRect.width === 0 &&
placeholderRect.height === 0
) {
return;
}
const targetRect = getTargetRect(targetNode);
const fixedTop = getFixedTop(placeholderRect, targetRect, offsetTop);
const fixedBottom = getFixedBottom(placeholderRect, targetRect, offsetBottom);
if (fixedTop !== undefined) {
newState.affixStyle = {
position: 'fixed',
top: fixedTop,
width: placeholderRect.width,
height: placeholderRect.height,
};
newState.placeholderStyle = {
width: placeholderRect.width,
height: placeholderRect.height,
};
} else if (fixedBottom !== undefined) {
newState.affixStyle = {
position: 'fixed',
bottom: fixedBottom,
width: placeholderRect.width,
height: placeholderRect.height,
};
newState.placeholderStyle = {
width: placeholderRect.width,
height: placeholderRect.height,
};
}
2019-03-03 11:40:10 +08:00
newState.lastAffix = !!newState.affixStyle;
if (onChange && lastAffix !== newState.lastAffix) {
onChange(newState.lastAffix);
}
this.setState(newState as AffixState);
}
2019-03-03 11:40:10 +08:00
};
2019-08-05 18:38:10 +08:00
prepareMeasure = () => {
// event param is used before. Keep compatible ts define here.
this.setState({
status: AffixStatus.Prepare,
affixStyle: undefined,
placeholderStyle: undefined,
});
// Test if `updatePosition` called
if (process.env.NODE_ENV === 'test') {
const { onTestUpdatePosition } = this.props as any;
onTestUpdatePosition?.();
2019-08-05 18:38:10 +08:00
}
};
updatePosition = throttleByAnimationFrame(() => {
2019-08-05 18:38:10 +08:00
this.prepareMeasure();
});
2019-08-05 18:38:10 +08:00
lazyUpdatePosition = throttleByAnimationFrame(() => {
const targetFunc = this.getTargetFunc();
2019-08-05 18:38:10 +08:00
const { affixStyle } = this.state;
// Check position change before measure to make Safari smooth
if (targetFunc && affixStyle) {
2019-08-05 18:38:10 +08:00
const offsetTop = this.getOffsetTop();
const offsetBottom = this.getOffsetBottom();
const targetNode = targetFunc();
if (targetNode && this.placeholderNodeRef.current) {
2019-08-05 18:38:10 +08:00
const targetRect = getTargetRect(targetNode);
2023-02-24 09:04:03 +08:00
const placeholderRect = getTargetRect(this.placeholderNodeRef.current);
const fixedTop = getFixedTop(placeholderRect, targetRect, offsetTop);
const fixedBottom = getFixedBottom(placeholderRect, targetRect, offsetBottom);
2019-08-05 18:38:10 +08:00
if (
(fixedTop !== undefined && affixStyle.top === fixedTop) ||
(fixedBottom !== undefined && affixStyle.bottom === fixedBottom)
) {
return;
}
}
}
// Directly call prepare measure since it's already throttled.
this.prepareMeasure();
});
2019-08-05 18:38:10 +08:00
2019-03-03 10:04:21 +08:00
// =================== Render ===================
render() {
2019-07-16 20:48:03 +08:00
const { affixStyle, placeholderStyle } = this.state;
const { affixPrefixCls, rootClassName, children } = this.props;
const className = classNames(affixStyle && rootClassName, {
[affixPrefixCls]: !!affixStyle,
});
2015-08-03 16:49:42 +08:00
let props = omit(this.props, [
'prefixCls',
'offsetTop',
'offsetBottom',
'target',
'onChange',
'affixPrefixCls',
'rootClassName',
]);
2019-04-07 10:06:49 +08:00
// Omit this since `onTestUpdatePosition` only works on test.
if (process.env.NODE_ENV === 'test') {
props = omit(props as typeof props & { onTestUpdatePosition: any }, ['onTestUpdatePosition']);
2019-04-07 10:06:49 +08:00
}
2019-07-16 20:48:03 +08:00
2015-08-03 16:49:42 +08:00
return (
<ResizeObserver onResize={this.updatePosition}>
<div {...props} ref={this.placeholderNodeRef}>
2019-07-16 20:48:03 +08:00
{affixStyle && <div style={placeholderStyle} aria-hidden="true" />}
<div className={className} ref={this.fixedNodeRef} style={affixStyle}>
<ResizeObserver onResize={this.updatePosition}>{children}</ResizeObserver>
2019-07-16 20:48:03 +08:00
</div>
2015-08-04 14:57:18 +08:00
</div>
2019-07-16 20:48:03 +08:00
</ResizeObserver>
2015-08-03 16:49:42 +08:00
);
}
}
// just use in test
2023-02-22 10:42:25 +08:00
export type InternalAffixClass = InternalAffix;
2019-03-03 10:04:21 +08:00
2023-02-22 10:42:25 +08:00
const Affix = forwardRef<InternalAffix, AffixProps>((props, ref) => {
const { prefixCls: customizePrefixCls, rootClassName } = props;
const { getPrefixCls } = useContext<ConfigConsumerProps>(ConfigContext);
const affixPrefixCls = getPrefixCls('affix', customizePrefixCls);
const [wrapSSR, hashId] = useStyle(affixPrefixCls);
const AffixProps: InternalAffixProps = {
...props,
affixPrefixCls,
rootClassName: classNames(rootClassName, hashId),
};
2023-02-22 10:42:25 +08:00
return wrapSSR(<InternalAffix {...AffixProps} ref={ref} />);
});
if (process.env.NODE_ENV !== 'production') {
2023-02-22 10:42:25 +08:00
Affix.displayName = 'Affix';
}
2023-02-22 10:42:25 +08:00
export default Affix;