ant-design/components/affix/index.tsx

337 lines
9.7 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;
}
2019-03-03 10:04:21 +08:00
// Event handler
componentDidMount() {
const targetFunc = this.getTargetFunc();
if (targetFunc) {
2019-03-03 23:19:07 +08:00
// [Legacy] Wait for parent component ref has its value.
// We should use target as directly element instead of function which makes element check hard.
const target = targetFunc?.() || null;
this.timer = setTimeout(() => {
TRIGGER_EVENTS.forEach((eventName) => {
target?.addEventListener(eventName, this.lazyUpdatePosition);
});
2019-03-03 11:40:10 +08:00
// Mock Event object.
2019-08-05 18:38:10 +08:00
this.updatePosition();
2019-03-03 10:04:21 +08:00
});
2016-07-09 16:00:05 +08:00
}
}
2019-03-03 10:04:21 +08:00
componentDidUpdate(prevProps: AffixProps) {
const { prevTarget } = this.state;
const targetFunc = this.getTargetFunc();
const newTarget = targetFunc?.() || null;
if (prevTarget !== newTarget) {
if (newTarget) {
TRIGGER_EVENTS.forEach((eventName) => {
prevTarget?.removeEventListener(eventName, this.lazyUpdatePosition);
newTarget?.addEventListener(eventName, this.lazyUpdatePosition);
});
2019-03-03 11:40:10 +08:00
// Mock Event object.
2019-08-05 18:38:10 +08:00
this.updatePosition();
2019-03-03 10:04:21 +08:00
}
// eslint-disable-next-line react/no-did-update-set-state
this.setState({ prevTarget: newTarget });
2016-07-11 14:52:21 +08:00
}
2019-03-03 23:19:07 +08:00
if (
prevProps.offsetTop !== this.props.offsetTop ||
prevProps.offsetBottom !== this.props.offsetBottom
) {
2019-08-05 18:38:10 +08:00
this.updatePosition();
2019-03-03 23:19:07 +08:00
}
2019-03-03 10:04:21 +08:00
this.measure();
}
2019-03-03 10:04:21 +08:00
componentWillUnmount() {
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);
});
if (prevTarget !== newTarget) {
TRIGGER_EVENTS.forEach((eventName) => {
prevTarget?.removeEventListener(eventName, this.lazyUpdatePosition);
});
}
this.updatePosition.cancel();
// https://github.com/ant-design/ant-design/issues/22683
this.lazyUpdatePosition.cancel();
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();
2019-03-03 10:04:21 +08:00
if (!targetNode) {
return;
}
2019-03-03 10:04:21 +08:00
const newState: Partial<AffixState> = {
status: AffixStatus.None,
};
2023-02-24 09:04:03 +08:00
const placeholderRect = getTargetRect(this.placeholderNodeRef.current);
if (
2023-02-24 09:04:03 +08:00
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) {
2019-03-03 10:04:21 +08:00
newState.affixStyle = {
position: 'fixed',
top: fixedTop,
2023-02-24 09:04:03 +08:00
width: placeholderRect.width,
height: placeholderRect.height,
2019-03-03 10:04:21 +08:00
};
newState.placeholderStyle = {
2023-02-24 09:04:03 +08:00
width: placeholderRect.width,
height: placeholderRect.height,
2019-03-03 10:04:21 +08:00
};
} else if (fixedBottom !== undefined) {
2019-03-03 10:04:21 +08:00
newState.affixStyle = {
position: 'fixed',
bottom: fixedBottom,
2023-02-24 09:04:03 +08:00
width: placeholderRect.width,
height: placeholderRect.height,
2019-03-03 10:04:21 +08:00
};
newState.placeholderStyle = {
2023-02-24 09:04:03 +08:00
width: placeholderRect.width,
height: placeholderRect.height,
2019-03-03 10:04:21 +08:00
};
}
2019-03-03 11:40:10 +08:00
newState.lastAffix = !!newState.affixStyle;
if (onChange && lastAffix !== newState.lastAffix) {
onChange(newState.lastAffix);
}
2019-03-03 10:04:21 +08:00
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;