2020-09-01 14:51:59 +00:00
|
|
|
import React, { Children, useEffect, useState } from "react";
|
2020-09-22 12:43:51 +00:00
|
|
|
import { Grid, GridItem, Title } from "@patternfly/react-core";
|
2020-08-28 05:23:39 +00:00
|
|
|
|
2020-09-01 14:51:59 +00:00
|
|
|
import { FormPanel } from "./FormPanel";
|
|
|
|
import style from "./scroll-form.module.css";
|
2020-08-28 05:23:39 +00:00
|
|
|
|
|
|
|
type ScrollFormProps = {
|
|
|
|
sections: string[];
|
|
|
|
children: React.ReactNode;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const ScrollForm = ({ sections, children }: ScrollFormProps) => {
|
|
|
|
const [active, setActive] = useState(sections[0]);
|
|
|
|
useEffect(() => {
|
2020-09-08 17:20:29 +00:00
|
|
|
const getCurrentSection = () => {
|
|
|
|
for (let sectionName of sections) {
|
|
|
|
const section = document.getElementById(sectionName)!;
|
|
|
|
const startAt = section.offsetTop;
|
|
|
|
const endAt = startAt + section.offsetHeight;
|
|
|
|
const currentPosition =
|
|
|
|
document.documentElement.scrollTop || document.body.scrollTop;
|
|
|
|
const isInView = currentPosition >= startAt && currentPosition < endAt;
|
|
|
|
if (isInView) {
|
|
|
|
return sectionName;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-09-01 14:51:59 +00:00
|
|
|
window.addEventListener("scroll", () => {
|
2020-08-28 05:23:39 +00:00
|
|
|
const active = getCurrentSection();
|
|
|
|
if (active) {
|
|
|
|
setActive(active);
|
|
|
|
}
|
|
|
|
});
|
2020-09-08 17:20:29 +00:00
|
|
|
}, [active, sections]);
|
2020-08-28 05:23:39 +00:00
|
|
|
|
|
|
|
const Nav = () => (
|
|
|
|
<div className={style.sticky}>
|
|
|
|
<Title headingLevel="h5" size="lg">
|
|
|
|
Jump to Section
|
|
|
|
</Title>
|
|
|
|
<div className="pf-c-tabs pf-m-vertical">
|
|
|
|
<ul className="pf-c-tabs__list">
|
|
|
|
{sections.map((cat) => (
|
|
|
|
<li
|
|
|
|
className={
|
2020-09-01 14:51:59 +00:00
|
|
|
"pf-c-tabs__item" + (active === cat ? " pf-m-current" : "")
|
2020-08-28 05:23:39 +00:00
|
|
|
}
|
|
|
|
key={cat}
|
|
|
|
>
|
|
|
|
<button
|
|
|
|
className="pf-c-tabs__link"
|
|
|
|
id={`link-${cat}`}
|
|
|
|
onClick={() =>
|
|
|
|
document
|
|
|
|
.getElementById(cat)
|
2020-09-01 14:51:59 +00:00
|
|
|
?.scrollIntoView({ behavior: "smooth" })
|
2020-08-28 05:23:39 +00:00
|
|
|
}
|
|
|
|
>
|
|
|
|
<span className="pf-c-tabs__item-text">{cat}</span>
|
|
|
|
</button>
|
|
|
|
</li>
|
|
|
|
))}
|
|
|
|
</ul>
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
const nodes = Children.toArray(children);
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
<Grid hasGutter>
|
|
|
|
<GridItem span={8}>
|
2020-09-22 12:43:51 +00:00
|
|
|
{sections.map((cat, index) => (
|
|
|
|
<FormPanel id={cat} key={cat} title={cat}>
|
|
|
|
{nodes[index]}
|
|
|
|
</FormPanel>
|
|
|
|
))}
|
2020-08-28 05:23:39 +00:00
|
|
|
</GridItem>
|
|
|
|
<GridItem span={4}>
|
|
|
|
<Nav />
|
|
|
|
</GridItem>
|
|
|
|
</Grid>
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|