organism-react-scroll-nav
Version:
A React scroll spy library with flux
96 lines (91 loc) • 2.54 kB
JavaScript
import _objectSpread from "reshow-runtime/es/helpers/objectSpread2";
import _objectWithoutProperties from "reshow-runtime/es/helpers/objectWithoutProperties";
var _excluded = ["scrollMargin", "noDelay", "targetId", "container", "children"];
//@ts-check
import React from "react";
var {
isValidElement,
useRef
} = React;
import { useReturn } from "reshow-return";
import { build } from "react-atomic-molecule";
import { UNDEFINED, DEFAULT } from "reshow-constant";
import scrollStore from "../../stores/scrollStore.mjs";
import fastScrollStore from "../../stores/fastScrollStore.mjs";
/**
* @typedef {any} ScrollReceiverProps
*/
/**
* @param {ScrollReceiverProps} props
*/
var useScrollReceiver = function useScrollReceiver(props) {
var {
scrollMargin = DEFAULT,
noDelay = false,
targetId,
container,
children
} = props,
restProps = _objectWithoutProperties(props, _excluded);
/** @type {React.RefObject<boolean>} */
var lastIsShown = useRef(false);
var store = noDelay ? fastScrollStore : scrollStore;
var {
scroll: scrollInfo = {}
} = useReturn(["scroll"], store);
var activeId = store.getState().get("m" + scrollMargin);
var scrollTop = scrollInfo.top;
var pos = store.scroller.getOffset(targetId) || {};
var isShown = lastIsShown.current || false;
var active = UNDEFINED !== typeof targetId && targetId === activeId;
var targetInfo = _objectSpread(_objectSpread({}, pos), {}, {
active,
scrollTop,
scrollInfo,
scrollMargin,
isShown,
targetId
});
if (pos.isOnScreen) {
targetInfo.isShown = true;
lastIsShown.current = true;
}
if (!isNaN(scrollMargin)) {
store.scroller.addMargin(scrollMargin);
}
return {
targetInfo,
container,
children,
restProps
};
};
/**
* @param {ScrollReceiverProps} props
*/
var ScrollReceiver = function ScrollReceiver(props) {
var {
targetInfo,
container,
children,
restProps
} = useScrollReceiver(props);
var nextContainer = container;
var nextChildren = children;
if (!nextContainer) {
nextContainer = children;
nextChildren = null;
}
if (!nextChildren && isValidElement(nextContainer)) {
nextChildren = nextContainer.props.children;
}
return build(nextContainer)(_objectSpread(_objectSpread({}, restProps), {}, {
targetInfo
}),
/**
* sould not use build here, let nextContainer handle children by itself.
*/
nextChildren);
};
ScrollReceiver.displayName = "ScrollReceiver";
export default ScrollReceiver;