You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

291 lines
7.7 KiB

import * as React from 'react';
import classNames from 'classnames';
import omit from 'omit.js';
import ResizeObserver from 'rc-resize-observer';
import { ConfigConsumer, ConfigConsumerProps } from '../config-provider';
import { throttleByAnimationFrameDecorator } from '../_util/throttleByAnimationFrame';
import {
addObserveTarget,
removeObserveTarget,
getTargetRect,
getFixedTop,
getFixedBottom,
} from './utils';
function getDefaultTarget() {
return typeof window !== 'undefined' ? window : null;
}
// Affix
export interface AffixProps {
/**
*
*/
offsetTop?: number;
/** 距离窗口底部达到指定偏移量后触发 */
offsetBottom?: number;
style?: React.CSSProperties;
/** 固定状态改变时触发的回调函数 */
onChange?: (affixed?: boolean) => void;
/** 设置 Affix 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 */
target?: () => Window | HTMLElement | null;
prefixCls?: string;
className?: string;
children: React.ReactElement;
6 years ago
}
enum AffixStatus {
None,
Prepare,
}
export interface AffixState {
6 years ago
affixStyle?: React.CSSProperties;
placeholderStyle?: React.CSSProperties;
status: AffixStatus;
lastAffix: boolean;
prevTarget: Window | HTMLElement | null;
}
6 years ago
class Affix extends React.Component<AffixProps, AffixState> {
static defaultProps = {
target: getDefaultTarget,
};
6 years ago
state: AffixState = {
6 years ago
status: AffixStatus.None,
6 years ago
lastAffix: false,
prevTarget: null,
6 years ago
};
6 years ago
placeholderNode: HTMLDivElement;
6 years ago
fixedNode: HTMLDivElement;
6 years ago
private timeout: number;
6 years ago
// Event handler
componentDidMount() {
const { target } = this.props;
if (target) {
6 years ago
// [Legacy] Wait for parent component ref has its value.
// We should use target as directly element instead of function which makes element check hard.
6 years ago
this.timeout = setTimeout(() => {
addObserveTarget(target(), this);
6 years ago
// Mock Event object.
this.updatePosition();
6 years ago
});
}
}
6 years ago
componentDidUpdate(prevProps: AffixProps) {
const { prevTarget } = this.state;
6 years ago
const { target } = this.props;
let newTarget = null;
if (target) {
newTarget = target() || null;
}
if (prevTarget !== newTarget) {
6 years ago
removeObserveTarget(this);
if (newTarget) {
addObserveTarget(newTarget, this);
6 years ago
// Mock Event object.
this.updatePosition();
6 years ago
}
this.setState({ prevTarget: newTarget });
}
6 years ago
if (
prevProps.offsetTop !== this.props.offsetTop ||
prevProps.offsetBottom !== this.props.offsetBottom
) {
this.updatePosition();
6 years ago
}
6 years ago
this.measure();
}
6 years ago
componentWillUnmount() {
clearTimeout(this.timeout);
removeObserveTarget(this);
6 years ago
(this.updatePosition as any).cancel();
6 years ago
}
9 years ago
getOffsetTop = () => {
const { offsetBottom } = this.props;
let { offsetTop } = this.props;
if (offsetBottom === undefined && offsetTop === undefined) {
offsetTop = 0;
}
return offsetTop;
};
getOffsetBottom = () => {
return this.props.offsetBottom;
};
6 years ago
savePlaceholderNode = (node: HTMLDivElement) => {
this.placeholderNode = node;
};
6 years ago
saveFixedNode = (node: HTMLDivElement) => {
this.fixedNode = node;
};
9 years ago
6 years ago
// =================== Measure ===================
measure = () => {
6 years ago
const { status, lastAffix } = this.state;
const { target, onChange } = this.props;
6 years ago
if (status !== AffixStatus.Prepare || !this.fixedNode || !this.placeholderNode || !target) {
return;
}
6 years ago
const offsetTop = this.getOffsetTop();
const offsetBottom = this.getOffsetBottom();
6 years ago
6 years ago
const targetNode = target();
if (!targetNode) {
return;
}
6 years ago
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) {
6 years ago
newState.affixStyle = {
position: 'fixed',
top: fixedTop,
6 years ago
width: placeholderReact.width,
height: placeholderReact.height,
6 years ago
};
newState.placeholderStyle = {
width: placeholderReact.width,
height: placeholderReact.height,
};
} else if (fixedBottom !== undefined) {
6 years ago
newState.affixStyle = {
position: 'fixed',
bottom: fixedBottom,
6 years ago
width: placeholderReact.width,
height: placeholderReact.height,
6 years ago
};
newState.placeholderStyle = {
width: placeholderReact.width,
height: placeholderReact.height,
};
}
6 years ago
newState.lastAffix = !!newState.affixStyle;
if (onChange && lastAffix !== newState.lastAffix) {
onChange(newState.lastAffix);
}
6 years ago
this.setState(newState as AffixState);
6 years ago
};
// @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;
if (onTestUpdatePosition) {
onTestUpdatePosition();
}
}
};
// Handle realign logic
@throttleByAnimationFrameDecorator()
updatePosition() {
this.prepareMeasure();
}
@throttleByAnimationFrameDecorator()
lazyUpdatePosition() {
const { target } = this.props;
const { affixStyle } = this.state;
// Check position change before measure to make Safari smooth
if (target && affixStyle) {
const offsetTop = this.getOffsetTop();
const offsetBottom = this.getOffsetBottom();
const targetNode = target();
if (targetNode && this.placeholderNode) {
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();
}
6 years ago
// =================== Render ===================
renderAffix = ({ getPrefixCls }: ConfigConsumerProps) => {
5 years ago
const { affixStyle, placeholderStyle } = this.state;
const { prefixCls, children } = this.props;
const className = classNames({
6 years ago
[getPrefixCls('affix', prefixCls)]: affixStyle,
});
9 years ago
6 years ago
let props = omit(this.props, ['prefixCls', 'offsetTop', 'offsetBottom', 'target', 'onChange']);
// Omit this since `onTestUpdatePosition` only works on test.
if (process.env.NODE_ENV === 'test') {
props = omit(props, ['onTestUpdatePosition']);
}
5 years ago
9 years ago
return (
5 years ago
<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>
</div>
5 years ago
</ResizeObserver>
9 years ago
);
};
render() {
return <ConfigConsumer>{this.renderAffix}</ConfigConsumer>;
}
}
6 years ago
export default Affix;