ant-design/components/affix/index.tsx

282 lines
8.2 KiB
TypeScript
Raw Normal View History

import React from 'react';
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 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
}
enum AffixStatus {
None,
Prepare,
2016-06-22 13:18:43 +08:00
}
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
}
export interface AffixRef {
updatePosition: ReturnType<typeof throttleByAnimationFrame>;
}
2023-10-14 11:57:53 +08:00
const Affix = React.forwardRef<AffixRef, AffixProps>((props, ref) => {
const {
style,
offsetTop,
offsetBottom,
2023-10-14 11:57:53 +08:00
prefixCls,
className,
rootClassName,
children,
target,
onChange,
} = props;
2023-10-14 11:57:53 +08:00
const { getPrefixCls, getTargetContainer } = React.useContext<ConfigConsumerProps>(ConfigContext);
const affixPrefixCls = getPrefixCls('affix', prefixCls);
const [lastAffix, setLastAffix] = React.useState(false);
const [affixStyle, setAffixStyle] = React.useState<React.CSSProperties>();
const [placeholderStyle, setPlaceholderStyle] = React.useState<React.CSSProperties>();
const status = React.useRef<AffixStatus>(AffixStatus.None);
const prevTarget = React.useRef<Window | HTMLElement | null>(null);
const prevListener = React.useRef<EventListener>();
const placeholderNodeRef = React.useRef<HTMLDivElement>(null);
const fixedNodeRef = React.useRef<HTMLDivElement>(null);
const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const targetFunc = target ?? getTargetContainer ?? getDefaultTarget;
2019-08-05 18:38:10 +08:00
const internalOffsetTop = offsetBottom === undefined && offsetTop === undefined ? 0 : offsetTop;
2019-03-03 10:04:21 +08:00
// =================== Measure ===================
const measure = () => {
if (
status.current !== AffixStatus.Prepare ||
!fixedNodeRef.current ||
!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 targetNode = targetFunc();
if (targetNode) {
const newState: Partial<AffixState> = {
status: AffixStatus.None,
2019-03-03 10:04:21 +08:00
};
const placeholderRect = getTargetRect(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, internalOffsetTop);
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 (lastAffix !== newState.lastAffix) {
onChange?.(newState.lastAffix);
}
status.current = newState.status!;
setAffixStyle(newState.affixStyle);
setPlaceholderStyle(newState.placeholderStyle);
setLastAffix(newState.lastAffix);
}
2019-03-03 11:40:10 +08:00
};
const prepareMeasure = () => {
status.current = AffixStatus.Prepare;
measure();
2019-08-05 18:38:10 +08:00
if (process.env.NODE_ENV === 'test') {
(props as any)?.onTestUpdatePosition?.();
2019-08-05 18:38:10 +08:00
}
};
const updatePosition = throttleByAnimationFrame(() => {
prepareMeasure();
});
2019-08-05 18:38:10 +08:00
const lazyUpdatePosition = throttleByAnimationFrame(() => {
2019-08-05 18:38:10 +08:00
// Check position change before measure to make Safari smooth
if (targetFunc && affixStyle) {
const targetNode = targetFunc();
if (targetNode && placeholderNodeRef.current) {
2019-08-05 18:38:10 +08:00
const targetRect = getTargetRect(targetNode);
const placeholderRect = getTargetRect(placeholderNodeRef.current);
const fixedTop = getFixedTop(placeholderRect, targetRect, internalOffsetTop);
2023-02-24 09:04:03 +08:00
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.
prepareMeasure();
});
2019-08-05 18:38:10 +08:00
const addListeners = () => {
const listenerTarget = targetFunc?.();
if (!listenerTarget) {
return;
}
TRIGGER_EVENTS.forEach((eventName) => {
if (prevListener.current) {
prevTarget.current?.removeEventListener(eventName, prevListener.current);
}
listenerTarget?.addEventListener(eventName, lazyUpdatePosition);
});
prevTarget.current = listenerTarget;
prevListener.current = lazyUpdatePosition;
};
2015-08-03 16:49:42 +08:00
const removeListeners = () => {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
2019-04-07 10:06:49 +08:00
}
const newTarget = targetFunc?.();
TRIGGER_EVENTS.forEach((eventName) => {
newTarget?.removeEventListener(eventName, lazyUpdatePosition);
if (prevListener.current) {
prevTarget.current?.removeEventListener(eventName, prevListener.current);
}
});
updatePosition.cancel();
lazyUpdatePosition.cancel();
};
2019-07-16 20:48:03 +08:00
React.useImperativeHandle(ref, () => ({ updatePosition }));
// mount & unmount
React.useEffect(() => {
// [Legacy] Wait for parent component ref has its value.
// We should use target as directly element instead of function which makes element check hard.
timer.current = setTimeout(addListeners);
return () => removeListeners();
}, []);
React.useEffect(() => {
addListeners();
}, [target, affixStyle]);
React.useEffect(() => {
updatePosition();
}, [target, offsetTop, offsetBottom]);
const [wrapCSSVar, hashId, cssVarCls] = useStyle(affixPrefixCls);
2023-10-14 11:57:53 +08:00
const rootCls = classNames(rootClassName, hashId, affixPrefixCls, cssVarCls);
2023-10-14 11:57:53 +08:00
const mergedCls = classNames({ [rootCls]: affixStyle });
let otherProps = omit(props, [
'prefixCls',
'offsetTop',
'offsetBottom',
'target',
'onChange',
'rootClassName',
]);
if (process.env.NODE_ENV === 'test') {
2023-10-14 11:57:53 +08:00
otherProps = omit(otherProps, ['onTestUpdatePosition' as any]);
}
2019-03-03 10:04:21 +08:00
return wrapCSSVar(
<ResizeObserver onResize={updatePosition}>
2023-10-14 11:57:53 +08:00
<div style={style} className={className} ref={placeholderNodeRef} {...otherProps}>
{affixStyle && <div style={placeholderStyle} aria-hidden="true" />}
2023-10-14 11:57:53 +08:00
<div className={mergedCls} ref={fixedNodeRef} style={affixStyle}>
<ResizeObserver onResize={updatePosition}>{children}</ResizeObserver>
</div>
</div>
2023-10-14 11:57:53 +08:00
</ResizeObserver>,
);
});
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;