adwaita-web
Version:
A GTK inspired toolkit designed to build awesome web apps
103 lines (102 loc) • 3.14 kB
JavaScript
import cx from "clsx";
import React from "react";
class PageSwitcher extends React.Component {
static defaultProps = {
transition: "horizontal",
expand: false,
useMainPageDimensions: false
};
activePage;
mustSetIsSwitching;
state;
constructor(props) {
super(props);
this.activePage = React.createRef();
this.state = {
activePage: props.activePage,
isSwitching: false,
width: void 0,
height: void 0
};
}
getPagesToRender() {
const { activePage: activePageProp, transition } = this.props;
const { activePage } = this.state;
if (transition === false)
return activePageProp !== void 0 ? [activePageProp] : [];
const pages = Array.from(new Set([activePage, activePageProp].filter((n) => n !== void 0)));
pages.sort(compare);
return pages;
}
componentDidUpdate() {
if (this.mustSetIsSwitching) {
this.mustSetIsSwitching = false;
requestAnimationFrame(() => {
this.setState({ isSwitching: true });
});
}
}
onTransitionEnd = () => {
this.setState({
isSwitching: false,
activePage: this.props.activePage
});
};
onRef = (ref) => {
this.activePage.current = ref;
if (!ref)
return;
const { activePage, useMainPageDimensions, mainPage } = this.props;
const isMainPage = activePage === mainPage;
if (useMainPageDimensions === false && !isMainPage)
return;
const { width, height } = this.activePage.current.getBoundingClientRect();
const state = {};
if (isMainPage || useMainPageDimensions === true || useMainPageDimensions !== "width")
state.width = width;
if (isMainPage || useMainPageDimensions === true || useMainPageDimensions !== "height")
state.height = height;
this.setState(state);
};
render() {
const {
className,
pages,
activePage: activePageProp,
mainPage,
transition,
expand,
padded,
style,
useMainPageDimensions,
...rest
} = this.props;
const { activePage, isSwitching, width, height } = this.state;
const renderedPages = this.getPagesToRender();
const activePageValue = isSwitching ? activePageProp : activePage;
if (activePage !== activePageProp && !isSwitching) {
this.mustSetIsSwitching = true;
}
const containerStyle = !expand ? style : { width, height, ...style };
return /* @__PURE__ */ React.createElement("div", {
className: cx("PageSwitcher", className, transition, !useMainPageDimensions ? void 0 : useMainPageDimensions === true ? "use-both" : `use-${useMainPageDimensions}`, { expand }),
style: containerStyle,
...rest
}, renderedPages.map((n) => /* @__PURE__ */ React.createElement("div", {
key: pages[n]?.key || n,
className: cx("PageSwitcher__page", {
active: n === activePageValue,
main: n === mainPage,
padded
}),
onTransitionEnd: this.onTransitionEnd,
ref: expand && n === activePageValue ? this.onRef : void 0
}, pages[n]?.content)));
}
}
function compare(a, b) {
return a - b;
}
export {
PageSwitcher
};