ant-design/components/affix/index.tsx

319 lines
8.6 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
import classNames from 'classnames';
import omit from 'rc-util/lib/omit';
import ResizeObserver from 'rc-resize-observer';
import { ConfigContext, ConfigConsumerProps } from '../config-provider';
import { throttleByAnimationFrameDecorator } from '../_util/throttleByAnimationFrame';
2015-08-04 14:57:18 +08:00
import {
addObserveTarget,
removeObserveTarget,
getTargetRect,
getFixedTop,
getFixedBottom,
} from './utils';
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 {
/** 距离窗口顶部达到指定偏移量后触发 */
2016-07-13 11:14:24 +08:00
offsetTop?: number;
/** 距离窗口底部达到指定偏移量后触发 */
2016-07-13 11:14:24 +08:00
offsetBottom?: number;
style?: React.CSSProperties;
/** 固定状态改变时触发的回调函数 */
onChange?: (affixed?: boolean) => void;
/** 设置 Affix 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 */
2017-11-22 11:49:35 +08:00
target?: () => Window | HTMLElement | null;
prefixCls?: string;
2019-01-31 11:20:58 +08:00
className?: string;
children: React.ReactNode;
2019-03-03 10:04:21 +08:00
}
export 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
}
class Affix 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
2019-03-03 10:04:21 +08:00
placeholderNode: HTMLDivElement;
2019-08-05 18:38:10 +08:00
2019-03-03 10:04:21 +08:00
fixedNode: HTMLDivElement;
2019-08-05 18:38:10 +08:00
2021-02-20 14:08:49 +08:00
private timeout: any;
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;
}
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.
2019-03-03 10:04:21 +08:00
this.timeout = setTimeout(() => {
addObserveTarget(targetFunc(), this);
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) {
2019-03-03 10:04:21 +08:00
removeObserveTarget(this);
if (newTarget) {
addObserveTarget(newTarget, this);
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() {
clearTimeout(this.timeout);
removeObserveTarget(this);
2019-03-03 11:40:10 +08:00
(this.updatePosition as any).cancel();
// https://github.com/ant-design/ant-design/issues/22683
(this.lazyUpdatePosition as any).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
savePlaceholderNode = (node: HTMLDivElement) => {
this.placeholderNode = node;
};
2019-03-03 10:04:21 +08:00
saveFixedNode = (node: HTMLDivElement) => {
this.fixedNode = node;
};
2015-08-03 16:49:42 +08:00
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.fixedNode || !this.placeholderNode || !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,
};
const targetRect = getTargetRect(targetNode);
const placeholderReact = getTargetRect(this.placeholderNode);
const fixedTop = getFixedTop(placeholderReact, targetRect, offsetTop);
const fixedBottom = getFixedBottom(placeholderReact, targetRect, offsetBottom);
if (fixedTop !== undefined) {
2019-03-03 10:04:21 +08:00
newState.affixStyle = {
position: 'fixed',
top: fixedTop,
2019-03-03 23:25:52 +08:00
width: placeholderReact.width,
height: placeholderReact.height,
2019-03-03 10:04:21 +08:00
};
newState.placeholderStyle = {
width: placeholderReact.width,
height: placeholderReact.height,
};
} else if (fixedBottom !== undefined) {
2019-03-03 10:04:21 +08:00
newState.affixStyle = {
position: 'fixed',
bottom: fixedBottom,
2019-03-03 23:25:52 +08:00
width: placeholderReact.width,
height: placeholderReact.height,
2019-03-03 10:04:21 +08:00
};
newState.placeholderStyle = {
width: placeholderReact.width,
height: placeholderReact.height,
};
}
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
// @ts-ignore TS6133
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
}
};
// Handle realign logic
@throttleByAnimationFrameDecorator()
updatePosition() {
this.prepareMeasure();
}
@throttleByAnimationFrameDecorator()
lazyUpdatePosition() {
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.placeholderNode) {
2019-08-05 18:38:10 +08:00
const targetRect = getTargetRect(targetNode);
const placeholderReact = getTargetRect(this.placeholderNode);
const fixedTop = getFixedTop(placeholderReact, targetRect, offsetTop);
const fixedBottom = getFixedBottom(placeholderReact, targetRect, offsetBottom);
if (
(fixedTop !== undefined && affixStyle.top === fixedTop) ||
(fixedBottom !== undefined && affixStyle.bottom === fixedBottom)
) {
return;
}
}
}
// Directly call prepare measure since it's already throttled.
this.prepareMeasure();
}
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, children } = this.props;
const className = classNames({
[affixPrefixCls]: !!affixStyle,
});
2015-08-03 16:49:42 +08:00
let props = omit(this.props, [
'prefixCls',
'offsetTop',
'offsetBottom',
'target',
'onChange',
'affixPrefixCls',
]);
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 (
2019-07-16 20:48:03 +08:00
<ResizeObserver
onResize={() => {
this.updatePosition();
}}
>
<div {...props} ref={this.savePlaceholderNode}>
{affixStyle && <div style={placeholderStyle} aria-hidden="true" />}
<div className={className} ref={this.saveFixedNode} style={affixStyle}>
<ResizeObserver
onResize={() => {
this.updatePosition();
}}
>
{children}
</ResizeObserver>
</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
);
}
}
2019-03-03 10:04:21 +08:00
const AffixFC = React.forwardRef<Affix, AffixProps>((props, ref) => {
const { prefixCls: customizePrefixCls } = props;
const { getPrefixCls } = React.useContext(ConfigContext);
const affixPrefixCls = getPrefixCls('affix', customizePrefixCls);
const AffixProps: InternalAffixProps = {
...props,
affixPrefixCls,
};
return <Affix {...AffixProps} ref={ref} />;
});
if (process.env.NODE_ENV !== 'production') {
AffixFC.displayName = 'Affix';
}
export default AffixFC;