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.

103 lines
2.8 KiB

6 years ago
import addEventListener from 'rc-util/lib/Dom/addEventListener';
export type BindElement = HTMLElement | Window | null | undefined;
export function getTargetRect(target: BindElement): DOMRect {
return target !== window
? (target as HTMLElement).getBoundingClientRect()
: ({ top: 0, bottom: window.innerHeight } as DOMRect);
}
export function getFixedTop(placeholderReact: DOMRect, targetRect: DOMRect, offsetTop?: number) {
if (offsetTop !== undefined && targetRect.top > placeholderReact.top - offsetTop) {
return offsetTop + targetRect.top;
}
return undefined;
}
export function getFixedBottom(
placeholderReact: DOMRect,
targetRect: DOMRect,
offsetBottom?: number,
) {
if (offsetBottom !== undefined && targetRect.bottom < placeholderReact.bottom + offsetBottom) {
const targetBottomOffset = window.innerHeight - targetRect.bottom;
return offsetBottom + targetBottomOffset;
}
return undefined;
}
6 years ago
// ======================== Observer ========================
const TRIGGER_EVENTS = [
'resize',
'scroll',
'touchstart',
'touchmove',
'touchend',
'pageshow',
'load',
];
interface ObserverEntity {
target: HTMLElement | Window;
affixList: any[];
6 years ago
eventHandlers: { [eventName: string]: any };
}
let observerEntities: ObserverEntity[] = [];
export function getObserverEntities() {
// Only used in test env. Can be removed if refactor.
return observerEntities;
}
export function addObserveTarget<T>(target: HTMLElement | Window | null, affix?: T): void {
if (!target) {
return;
}
6 years ago
let entity: ObserverEntity | undefined = observerEntities.find((item) => item.target === target);
6 years ago
if (entity) {
entity.affixList.push(affix);
} else {
entity = {
target,
affixList: [affix],
eventHandlers: {},
};
observerEntities.push(entity);
// Add listener
TRIGGER_EVENTS.forEach((eventName) => {
entity!.eventHandlers[eventName] = addEventListener(target, eventName, () => {
entity!.affixList.forEach((targetAffix) => {
targetAffix.lazyUpdatePosition();
6 years ago
});
});
});
}
}
export function removeObserveTarget<T>(affix: T): void {
const observerEntity = observerEntities.find((oriObserverEntity) => {
const hasAffix = oriObserverEntity.affixList.some((item) => item === affix);
6 years ago
if (hasAffix) {
oriObserverEntity.affixList = oriObserverEntity.affixList.filter((item) => item !== affix);
6 years ago
}
return hasAffix;
});
if (observerEntity && observerEntity.affixList.length === 0) {
observerEntities = observerEntities.filter((item) => item !== observerEntity);
6 years ago
// Remove listener
TRIGGER_EVENTS.forEach((eventName) => {
6 years ago
const handler = observerEntity.eventHandlers[eventName];
if (handler && handler.remove) {
handler.remove();
}
});
}
}