Unverified Commit 5c373a88 authored by Alex Andreev's avatar Alex Andreev Committed by GitHub
Browse files

Navigation menu in Preferences (#2304)

parent 8e1583a5
Showing with 840 additions and 256 deletions
+840 -256
......@@ -487,7 +487,7 @@ export class Extensions extends React.Component {
return (
<DropFileInput onDropFiles={this.installOnDrop}>
<PageLayout showOnTop className="Extensions flex column gaps" header={topHeader} contentGaps={false}>
<PageLayout showOnTop className="Extensions" header={topHeader} contentGaps={false}>
<h2>Lens Extensions</h2>
<div>
Add new features and functionality via Lens Extensions.
......
......@@ -10,6 +10,7 @@
.content {
margin: unset;
max-width: unset;
height: 100%;
}
}
}
.HelmCharts {
.repos {
margin-top: var(--margin);
.Badge {
display: flex;
margin-bottom: 1px!important;
padding: 6px 8px;
}
}
}
\ No newline at end of file
import "./helm-charts.scss";
import React from "react";
import { action, computed, observable } from "mobx";
import { HelmRepo, repoManager } from "../../../main/helm/helm-repo-manager";
import { Badge } from "../badge";
import { Button } from "../button";
import { Icon } from "../icon";
import { Notifications } from "../notifications";
import { Select, SelectOption } from "../select";
import { Tooltip } from "../tooltip";
import { AddHelmRepoDialog } from "./add-helm-repo-dialog";
import { observer } from "mobx-react";
@observer
export class HelmCharts extends React.Component {
@observable loading = false;
@observable repos: HelmRepo[] = [];
@observable addedRepos = observable.map<string, HelmRepo>();
@computed get options(): SelectOption<HelmRepo>[] {
return this.repos.map(repo => ({
label: repo.name,
value: repo,
}));
}
async componentDidMount() {
await this.loadRepos();
}
@action
async loadRepos() {
this.loading = true;
try {
if (!this.repos.length) {
this.repos = await repoManager.loadAvailableRepos(); // via https://helm.sh
}
const repos = await repoManager.repositories(); // via helm-cli
this.addedRepos.clear();
repos.forEach(repo => this.addedRepos.set(repo.name, repo));
} catch (err) {
Notifications.error(String(err));
}
this.loading = false;
}
async addRepo(repo: HelmRepo) {
try {
await repoManager.addRepo(repo);
this.addedRepos.set(repo.name, repo);
} catch (err) {
Notifications.error(<>Adding helm branch <b>{repo.name}</b> has failed: {String(err)}</>);
}
}
async removeRepo(repo: HelmRepo) {
try {
await repoManager.removeRepo(repo);
this.addedRepos.delete(repo.name);
} catch (err) {
Notifications.error(
<>Removing helm branch <b>{repo.name}</b> has failed: {String(err)}</>
);
}
}
onRepoSelect = async ({ value: repo }: SelectOption<HelmRepo>) => {
const isAdded = this.addedRepos.has(repo.name);
if (isAdded) {
Notifications.ok(<>Helm branch <b>{repo.name}</b> already in use</>);
return;
}
this.loading = true;
await this.addRepo(repo);
this.loading = false;
};
formatOptionLabel = ({ value: repo }: SelectOption<HelmRepo>) => {
const isAdded = this.addedRepos.has(repo.name);
return (
<div className="flex gaps">
<span>{repo.name}</span>
{isAdded && <Icon small material="check" className="box right"/>}
</div>
);
};
render() {
return (
<div className="HelmCharts">
<div className="flex gaps">
<Select id="HelmRepoSelect"
placeholder="Repositories"
isLoading={this.loading}
isDisabled={this.loading}
options={this.options}
onChange={this.onRepoSelect}
formatOptionLabel={this.formatOptionLabel}
controlShouldRenderValue={false}
className="box grow"
/>
<Button
primary
label="Add Custom Helm Repo"
onClick={AddHelmRepoDialog.open}
/>
</div>
<AddHelmRepoDialog onAddRepo={() => this.loadRepos()}/>
<div className="repos flex gaps column">
{Array.from(this.addedRepos).map(([name, repo]) => {
const tooltipId = `message-${name}`;
return (
<Badge key={name} className="added-repo flex gaps align-center justify-space-between">
<span id={tooltipId} className="repo">{name}</span>
<Icon
material="delete"
onClick={() => this.removeRepo(repo)}
tooltip="Remove"
/>
<Tooltip targetId={tooltipId} formatters={{ narrow: true }}>
{repo.url}
</Tooltip>
</Badge>
);
})}
</div>
</div>
);
}
}
......@@ -24,15 +24,12 @@ export const KubectlBinaries = observer(({ preferences }: { preferences: UserPre
return (
<>
<h2>Kubectl Binary</h2>
<SubTitle title="Automatic kubectl binary download"/>
<Checkbox
label="Download kubectl binaries"
label="Download kubectl binaries matching the Kubernetes cluster version"
value={preferences.downloadKubectlBinaries}
onChange={downloadKubectlBinaries => preferences.downloadKubectlBinaries = downloadKubectlBinaries}
/>
<small className="hint">
Download kubectl binaries matching to Kubernetes cluster version.
</small>
<SubTitle title="Download mirror" />
<Select
placeholder="Download mirror for kubectl"
......@@ -54,7 +51,7 @@ export const KubectlBinaries = observer(({ preferences }: { preferences: UserPre
<small className="hint">
The directory to download binaries into.
</small>
<SubTitle title="Path to Kubectl binary" />
<SubTitle title="Path to kubectl binary" />
<Input
theme="round-black"
placeholder={bundledKubectlPath()}
......
.Preferences {
$spacing: $padding * 2;
.repos {
position: relative;
.Badge {
display: flex;
margin-bottom: 1px;
padding: $padding $spacing;
}
}
.extensions {
h2 {
margin: $spacing 0;
}
&:empty {
display: none;
}
}
.Checkbox {
align-self: start; // limit clickable area to checkbox + text
}
}
\ No newline at end of file
import "./preferences.scss";
import React from "react";
import { computed, observable } from "mobx";
import { observer } from "mobx-react";
import { action, computed, observable } from "mobx";
import { Icon } from "../icon";
import { Select, SelectOption } from "../select";
import { userStore } from "../../../common/user-store";
import { isWindows } from "../../../common/vars";
import { HelmRepo, repoManager } from "../../../main/helm/helm-repo-manager";
import { Input } from "../input";
import { Checkbox } from "../checkbox";
import { Notifications } from "../notifications";
import { Badge } from "../badge";
import { Button } from "../button";
import { themeStore } from "../../theme.store";
import { Tooltip } from "../tooltip";
import { KubectlBinaries } from "./kubectl-binaries";
import { appPreferenceRegistry } from "../../../extensions/registries/app-preference-registry";
import { themeStore } from "../../theme.store";
import { Checkbox } from "../checkbox";
import { Input } from "../input";
import { PageLayout } from "../layout/page-layout";
import { AddHelmRepoDialog } from "./add-helm-repo-dialog";
import { SubTitle } from "../layout/sub-title";
import { Select, SelectOption } from "../select";
import { HelmCharts } from "./helm-charts";
import { KubectlBinaries } from "./kubectl-binaries";
import { ScrollSpy } from "../scroll-spy/scroll-spy";
@observer
export class Preferences extends React.Component {
@observable helmLoading = false;
@observable helmRepos: HelmRepo[] = [];
@observable helmAddedRepos = observable.map<string, HelmRepo>();
@observable httpProxy = userStore.preferences.httpsProxy || "";
@observable shell = userStore.preferences.shell || "";
......@@ -35,79 +29,6 @@ export class Preferences extends React.Component {
}));
}
@computed get helmOptions(): SelectOption<HelmRepo>[] {
return this.helmRepos.map(repo => ({
label: repo.name,
value: repo,
}));
}
async componentDidMount() {
await this.loadHelmRepos();
}
@action
async loadHelmRepos() {
this.helmLoading = true;
try {
if (!this.helmRepos.length) {
this.helmRepos = await repoManager.loadAvailableRepos(); // via https://helm.sh
}
const repos = await repoManager.repositories(); // via helm-cli
this.helmAddedRepos.clear();
repos.forEach(repo => this.helmAddedRepos.set(repo.name, repo));
} catch (err) {
Notifications.error(String(err));
}
this.helmLoading = false;
}
async addRepo(repo: HelmRepo) {
try {
await repoManager.addRepo(repo);
this.helmAddedRepos.set(repo.name, repo);
} catch (err) {
Notifications.error(<>Adding helm branch <b>{repo.name}</b> has failed: {String(err)}</>);
}
}
async removeRepo(repo: HelmRepo) {
try {
await repoManager.removeRepo(repo);
this.helmAddedRepos.delete(repo.name);
} catch (err) {
Notifications.error(
<>Removing helm branch <b>{repo.name}</b> has failed: {String(err)}</>
);
}
}
onRepoSelect = async ({ value: repo }: SelectOption<HelmRepo>) => {
const isAdded = this.helmAddedRepos.has(repo.name);
if (isAdded) {
Notifications.ok(<>Helm branch <b>{repo.name}</b> already in use</>);
return;
}
this.helmLoading = true;
await this.addRepo(repo);
this.helmLoading = false;
};
formatHelmOptionLabel = ({ value: repo }: SelectOption<HelmRepo>) => {
const isAdded = this.helmAddedRepos.has(repo.name);
return (
<div className="flex gaps">
<span>{repo.name}</span>
{isAdded && <Icon small material="check" className="box right"/>}
</div>
);
};
render() {
const { preferences } = userStore;
const header = <h2>Preferences</h2>;
......@@ -122,110 +43,110 @@ export class Preferences extends React.Component {
}
return (
<PageLayout showOnTop className="Preferences" header={header}>
<h2>Color Theme</h2>
<Select
options={this.themeOptions}
value={preferences.colorTheme}
onChange={({ value }: SelectOption) => preferences.colorTheme = value}
/>
<h2>HTTP Proxy</h2>
<Input
theme="round-black"
placeholder="Type HTTP proxy url (example: http://proxy.acme.org:8080)"
value={this.httpProxy}
onChange={v => this.httpProxy = v}
onBlur={() => preferences.httpsProxy = this.httpProxy}
/>
<small className="hint">
Proxy is used only for non-cluster communication.
</small>
<h2>Terminal Shell</h2>
<Input
theme="round-black"
placeholder={defaultShell}
value={this.shell}
onChange={v => this.shell = v}
onBlur={() => preferences.shell = this.shell}
/>
<small className="hint">
The path of the shell that the terminal uses.
</small>
<KubectlBinaries preferences={preferences}/>
<h2>Helm</h2>
<div className="flex gaps">
<Select id="HelmRepoSelect"
placeholder="Repositories"
isLoading={this.helmLoading}
isDisabled={this.helmLoading}
options={this.helmOptions}
onChange={this.onRepoSelect}
formatOptionLabel={this.formatHelmOptionLabel}
controlShouldRenderValue={false}
className="box grow"
/>
<Button
primary
label="Add Custom Helm Repo"
onClick={AddHelmRepoDialog.open}
/>
</div>
<AddHelmRepoDialog onAddRepo={()=>this.loadHelmRepos()}/>
<div className="repos flex gaps column">
{Array.from(this.helmAddedRepos).map(([name, repo]) => {
const tooltipId = `message-${name}`;
return (
<Badge key={name} className="added-repo flex gaps align-center justify-space-between">
<span id={tooltipId} className="repo">{name}</span>
<Icon
material="delete"
onClick={() => this.removeRepo(repo)}
tooltip="Remove"
/>
<Tooltip targetId={tooltipId} formatters={{ narrow: true }}>
{repo.url}
</Tooltip>
</Badge>
);
})}
</div>
<h2>Auto start-up</h2>
<Checkbox
label="Automatically start Lens on login"
value={preferences.openAtLogin}
onChange={v => preferences.openAtLogin = v}
/>
<h2>Certificate Trust</h2>
<Checkbox
label="Allow untrusted Certificate Authorities"
value={preferences.allowUntrustedCAs}
onChange={v => preferences.allowUntrustedCAs = v}
/>
<small className="hint">
This will make Lens to trust ANY certificate authority without any validations.{" "}
Needed with some corporate proxies that do certificate re-writing.{" "}
Does not affect cluster communications!
</small>
<div className="extensions flex column gaps">
{appPreferenceRegistry.getItems().map(({ title, components: { Hint, Input } }, index) => {
return (
<div key={index} className="preference">
<h2>{title}</h2>
<Input/>
<small className="hint">
<Hint/>
</small>
</div>
);
})}
</div>
</PageLayout>
<ScrollSpy htmlFor="ScrollSpyRoot" render={navigation => (
<PageLayout
showOnTop
navigation={navigation}
className="Preferences"
contentGaps={false}
header={header}
>
<section id="application" title="Application">
<section>
<h1>Application</h1>
</section>
<section id="appearance">
<h2>Appearance</h2>
<SubTitle title="Theme"/>
<Select
options={this.themeOptions}
value={preferences.colorTheme}
onChange={({ value }: SelectOption) => preferences.colorTheme = value}
/>
</section>
<section id="proxy">
<h2>Proxy</h2>
<SubTitle title="HTTP Proxy"/>
<Input
theme="round-black"
placeholder="Type HTTP proxy url (example: http://proxy.acme.org:8080)"
value={this.httpProxy}
onChange={v => this.httpProxy = v}
onBlur={() => preferences.httpsProxy = this.httpProxy}
/>
<small className="hint">
Proxy is used only for non-cluster communication.
</small>
<SubTitle title="Certificate Trust"/>
<Checkbox
label="Allow untrusted Certificate Authorities"
value={preferences.allowUntrustedCAs}
onChange={v => preferences.allowUntrustedCAs = v}
/>
<small className="hint">
This will make Lens to trust ANY certificate authority without any validations.{" "}
Needed with some corporate proxies that do certificate re-writing.{" "}
Does not affect cluster communications!
</small>
</section>
<section id="shell">
<h2>Terminal Shell</h2>
<SubTitle title="Shell Path"/>
<Input
theme="round-black"
placeholder={defaultShell}
value={this.shell}
onChange={v => this.shell = v}
onBlur={() => preferences.shell = this.shell}
/>
<small className="hint">
The path of the shell that the terminal uses.
</small>
</section>
<section id="startup">
<h2>Start-up</h2>
<SubTitle title="Automatic Start-up"/>
<Checkbox
label="Automatically start Lens on login"
value={preferences.openAtLogin}
onChange={v => preferences.openAtLogin = v}
/>
</section>
</section>
<section id="kubernetes">
<section>
<h1>Kubernetes</h1>
</section>
<section id="kubectl">
<h2>Kubectl binary</h2>
<KubectlBinaries preferences={preferences}/>
</section>
<section id="helm">
<h2>Helm Charts</h2>
<HelmCharts/>
</section>
</section>
<section id="extensions">
<section>
<h1>Extensions</h1>
</section>
{appPreferenceRegistry.getItems().map(({ title, components: { Hint, Input } }, index) => {
return (
<section key={index} id={title}>
<h2>{title}</h2>
<Input/>
<small className="hint">
<Hint/>
</small>
</section>
);
})}
</section>
</PageLayout>
)}/>
);
}
}
......@@ -4,7 +4,7 @@
background-color: var(--blue);
padding: 0 2px;
height: 22px;
height: var(--bottom-bar-height);
#current-workspace {
font-size: var(--font-size-small);
......
.ClusterManager {
--bottom-bar-height: 22px;
display: grid;
grid-template-areas: "menu main" "menu main" "bottom-bar bottom-bar";
grid-template-rows: auto 1fr min-content;
......
.PageLayout {
$spacing: $padding * 2;
--width: 60%;
--max-width: 1000px;
--min-width: 570px;
--nav-width: 180px;
--nav-column-width: 30vw;
--spacing: calc(var(--unit) * 2);
--wrapper-padding: calc(var(--spacing) * 2);
--header-height: 64px;
--header-height-mac: 80px;
position: relative;
width: 100%;
height: 100%;
display: grid !important;
grid-template-rows: min-content 1fr;
grid-template-columns: 1fr;
&.showNavigation {
--width: 70%;
grid-template-columns: var(--nav-column-width) 1fr;
> .content-wrapper {
> .content {
width: 100%;
padding-left: 1px; // Fix visual content crop
padding-right: calc(var(--nav-column-width) - var(--nav-width));
}
}
}
// covers whole app view area
&.top {
&.showOnTop {
position: fixed !important; // allow to cover ClustersMenu
z-index: 1;
left: 0;
......@@ -19,59 +37,94 @@
right: 0;
bottom: 24px;
height: unset;
background-color: $mainBackground;
background-color: var(--mainBackground);
// adds extra space for traffic-light top buttons (mac only)
.is-mac & > .header {
padding-top: $spacing * 2;
height: var(--header-height-mac);
padding-top: calc(var(--spacing) * 2);
}
}
> .header {
position: sticky;
padding: $spacing;
background-color: $layoutTabsBackground;
padding: var(--spacing);
background-color: var(--layoutTabsBackground);
height: var(--header-height);
grid-column-start: 1;
grid-column-end: 4;
}
> .content-navigation {
display: flex;
justify-content: flex-end;
overflow-y: auto;
margin-top: 32px;
ul.TreeView {
width: var(--nav-width);
padding-right: 24px;
}
}
> .content-wrapper {
padding: 32px;
overflow: auto;
padding: $spacing * 2;
display: flex;
flex-direction: column;
> .content {
flex: 1;
margin: 0 auto;
width: var(--width);
min-width: var(--min-width);
max-width: var(--max-width);
margin: 0 auto;
}
}
h2:not(:first-of-type) {
margin-top: $spacing;
}
p {
line-height: 140%;
}
a {
color: $colorInfo;
color: var(--colorInfo);
}
.SubTitle {
text-transform: none;
margin-bottom: 0 !important;
+ * + .hint {
margin-top: -$padding / 2;
}
}
.Select {
&__control {
box-shadow: 0 0 0 1px $borderFaintColor;
box-shadow: 0 0 0 1px var(--borderFaintColor);
}
}
section {
display: flex;
flex-direction: column;
margin-bottom: var(--spacing);
> :not(:last-child) {
margin-bottom: var(--spacing);
}
h1, h2 {
color: var(--textColorAccent);
}
h1 {
font-size: x-large;
border-bottom: 1px solid var(--borderFaintColor);
padding-bottom: var(--padding);
}
h2 {
font-size: large;
}
small.hint {
margin-top: calc(var(--unit) * -1.5);
}
.SubTitle {
margin-top: 0;
}
}
}
......@@ -5,6 +5,7 @@ import { observer } from "mobx-react";
import { autobind, cssNames, IClassName } from "../../utils";
import { Icon } from "../icon";
import { navigation } from "../../navigation";
import { NavigationTree, RecursiveTreeView } from "../tree-view";
export interface PageLayoutProps extends React.DOMAttributes<any> {
className?: IClassName;
......@@ -14,6 +15,7 @@ export interface PageLayoutProps extends React.DOMAttributes<any> {
provideBackButtonNavigation?: boolean;
contentGaps?: boolean;
showOnTop?: boolean; // covers whole app view
navigation?: NavigationTree[];
back?: (evt: React.MouseEvent | KeyboardEvent) => void;
}
......@@ -57,9 +59,9 @@ export class PageLayout extends React.Component<PageLayoutProps> {
render() {
const {
contentClass, header, headerClass, provideBackButtonNavigation,
contentGaps, showOnTop, children, ...elemProps
contentGaps, showOnTop, navigation, children, ...elemProps
} = this.props;
const className = cssNames("PageLayout", { top: showOnTop }, this.props.className);
const className = cssNames("PageLayout", { showOnTop, showNavigation: navigation }, this.props.className);
return (
<div {...elemProps} className={className}>
......@@ -73,8 +75,13 @@ export class PageLayout extends React.Component<PageLayoutProps> {
/>
)}
</div>
<div className="content-wrapper">
<div className={cssNames("content", contentGaps && "flex column gaps", contentClass)}>
{ navigation && (
<nav className="content-navigation">
<RecursiveTreeView data={navigation}/>
</nav>
)}
<div className="content-wrapper" id="ScrollSpyRoot">
<div className={cssNames("content", contentClass, contentGaps && "flex column gaps")}>
{children}
</div>
</div>
......
import React from "react";
import "@testing-library/jest-dom/extend-expect";
import { render, waitFor } from "@testing-library/react";
import { ScrollSpy } from "../scroll-spy";
import { RecursiveTreeView } from "../../tree-view";
const observe = jest.fn();
Object.defineProperty(window, "IntersectionObserver", {
writable: true,
value: jest.fn().mockImplementation(() => ({
observe,
unobserve: jest.fn(),
})),
});
describe("<ScrollSpy/>", () => {
it("renders w/o errors", () => {
const { container } = render(<ScrollSpy render={() => (
<div>
<section id="application">
<h1>Application</h1>
</section>
</div>
)}/>);
expect(container).toBeInstanceOf(HTMLElement);
});
it("calls intersection observer", () => {
render(<ScrollSpy render={() => (
<div>
<section id="application">
<h1>Application</h1>
</section>
</div>
)}/>);
expect(observe).toHaveBeenCalled();
});
it("renders dataTree component", async () => {
const { queryByTestId } = render(<ScrollSpy render={dataTree => (
<div>
<nav>
<RecursiveTreeView data={dataTree}/>
</nav>
<section id="application">
<h1>Application</h1>
</section>
</div>
)}/>);
await waitFor(() => {
expect(queryByTestId("TreeView")).toBeInTheDocument();
});
});
it("throws if no sections founded", () => {
// Prevent writing to stderr during this render.
const err = console.error;
console.error = jest.fn();
expect(() => render(<ScrollSpy render={() => (
<div>
Content
</div>
)}/>)).toThrow();
// Restore writing to stderr.
console.error = err;
});
});
describe("<TreeView/> dataTree inside <ScrollSpy/>", () => {
it("contains links to all sections", async () => {
const { queryByTitle } = render(<ScrollSpy render={dataTree => (
<div>
<nav>
<RecursiveTreeView data={dataTree}/>
</nav>
<section id="application">
<h1>Application</h1>
<section id="appearance">
<h2>Appearance</h2>
</section>
<section id="theme">
<h2>Theme</h2>
<div>description</div>
</section>
</section>
</div>
)}/>);
await waitFor(() => {
expect(queryByTitle("Application")).toBeInTheDocument();
expect(queryByTitle("Appearance")).toBeInTheDocument();
expect(queryByTitle("Theme")).toBeInTheDocument();
});
});
it("not showing links to sections without id", async () => {
const { queryByTitle } = render(<ScrollSpy render={dataTree => (
<div>
<nav>
<RecursiveTreeView data={dataTree}/>
</nav>
<section id="application">
<h1>Application</h1>
<section>
<h2>Kubectl</h2>
</section>
<section id="appearance">
<h2>Appearance</h2>
</section>
</section>
</div>
)}/>);
await waitFor(() => {
expect(queryByTitle("Application")).toBeInTheDocument();
expect(queryByTitle("Appearance")).toBeInTheDocument();
expect(queryByTitle("Kubectl")).not.toBeInTheDocument();
});
});
it("expands parent sections", async () => {
const { queryByTitle } = render(<ScrollSpy render={dataTree => (
<div>
<nav>
<RecursiveTreeView data={dataTree}/>
</nav>
<section id="application">
<h1>Application</h1>
<section id="appearance">
<h2>Appearance</h2>
</section>
<section id="theme">
<h2>Theme</h2>
<div>description</div>
</section>
</section>
<section id="Kubernetes">
<h1>Kubernetes</h1>
<section id="kubectl">
<h2>Kubectl</h2>
</section>
</section>
</div>
)}/>);
await waitFor(() => {
expect(queryByTitle("Application")).toHaveAttribute("aria-expanded");
expect(queryByTitle("Kubernetes")).toHaveAttribute("aria-expanded");
});
// console.log(prettyDOM());
});
it("skips sections without headings", async () => {
const { queryByTitle } = render(<ScrollSpy render={dataTree => (
<div>
<nav>
<RecursiveTreeView data={dataTree}/>
</nav>
<section id="application">
<h1>Application</h1>
<section id="appearance">
<p>Appearance</p>
</section>
<section id="theme">
<h2>Theme</h2>
</section>
</section>
</div>
)}/>);
await waitFor(() => {
expect(queryByTitle("Application")).toBeInTheDocument();
expect(queryByTitle("appearance")).not.toBeInTheDocument();
expect(queryByTitle("Appearance")).not.toBeInTheDocument();
});
});
});
import { observer } from "mobx-react";
import React, { useEffect, useRef, useState } from "react";
import { useMutationObserver } from "../../hooks";
import { NavigationTree } from "../tree-view";
interface Props extends React.DOMAttributes<HTMLElement> {
render: (data: NavigationTree[]) => JSX.Element
htmlFor?: string // Id of the element to put observers on
rootMargin?: string // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#creating_an_intersection_observer
}
export const ScrollSpy = observer(({ render, htmlFor, rootMargin = "0px 0px -100% 0px" }: Props) => {
const parent = useRef<HTMLDivElement>();
const sections = useRef<NodeListOf<HTMLElement>>();
const [tree, setTree] = useState<NavigationTree[]>([]);
const [activeElementId, setActiveElementId] = useState("");
const setSections = () => {
sections.current = parent.current.querySelectorAll("section");
if (!sections.current.length) {
throw new Error("No <section/> tag founded! Content should be placed inside <section></section> elements to activate navigation.");
}
};
const getSectionsParentElement = () => {
return sections.current?.[0].parentElement;
};
const updateNavigation = () => {
setTree(getNavigation(getSectionsParentElement()));
};
const getNavigation = (element: Element) => {
const sections = element.querySelectorAll(":scope > section"); // Searching only direct children of an element. Impossible without :scope
const children: NavigationTree[] = [];
sections.forEach(section => {
const id = section.getAttribute("id");
const parentId = section.parentElement.id;
const name = section.querySelector("h1, h2, h3, h4, h5, h6")?.textContent;
const selected = id === activeElementId;
if (!name || !id) {
return;
}
children.push({
id,
parentId,
name,
selected,
children: getNavigation(section)
});
});
return children;
};
const handleIntersect = ([entry]: IntersectionObserverEntry[]) => {
if (entry.isIntersecting) {
setActiveElementId(entry.target.closest("section[id]").id);
}
};
const observeSections = () => {
const options: IntersectionObserverInit = {
root: document.getElementById(htmlFor) || getSectionsParentElement(),
rootMargin
};
sections.current.forEach((section) => {
const observer = new IntersectionObserver(handleIntersect, options);
const target = section.querySelector("section") || section;
observer.observe(target);
});
};
useEffect(() => {
setSections();
observeSections();
}, []);
useEffect(() => {
updateNavigation();
}, [activeElementId]);
useMutationObserver(getSectionsParentElement(), updateNavigation);
return (
<div className="ScrollSpy" ref={parent}>
{render(tree)}
</div>
);
});
export * from "./tree-view";
.TreeView {
.MuiTypography-body1 {
font-size: var(--font-size);
color: var(--textColorAccent);
}
.MuiTreeItem-root {
> .MuiTreeItem-content .MuiTreeItem-label {
border-radius: 4px;
border: 1px solid transparent;
}
&.selected {
> .MuiTreeItem-content .MuiTreeItem-label {
border-color: var(--blue);
font-weight: bold;
}
}
// Make inner component selected state invisible
&.Mui-selected, &.Mui-selected:focus {
> .MuiTreeItem-content .MuiTreeItem-label {
background-color: transparent;
}
}
}
}
\ No newline at end of file
import "./tree-view.scss";
import React, { useEffect, useRef } from "react";
import { Icon } from "../icon";
import TreeView from "@material-ui/lab/TreeView";
import TreeItem from "@material-ui/lab/TreeItem";
import { cssNames } from "../../utils";
import _ from "lodash";
import getDeepDash from "deepdash";
const deepDash = getDeepDash(_);
export interface NavigationTree {
id: string;
parentId: string;
name: string;
selected?: boolean;
children?: NavigationTree[];
}
interface Props {
data: NavigationTree[]
}
function scrollToItem(id: string) {
document.getElementById(id)?.scrollIntoView();
}
function getSelectedNode(data: NavigationTree[]) {
return deepDash.findDeep(data, (value, key) => key === "selected" && value === true)?.parent;
}
export function RecursiveTreeView({ data }: Props) {
const [expanded, setExpanded] = React.useState<string[]>([]);
const prevData = useRef<NavigationTree[]>(data);
const handleToggle = (event: React.ChangeEvent<{}>, nodeIds: string[]) => {
setExpanded(nodeIds);
};
const expandTopLevelNodes = () => {
setExpanded(data.map(node => node.id));
};
const expandParentNode = () => {
const node = getSelectedNode(data) as any as NavigationTree;
const id = node?.parentId;
if (id && !expanded.includes(id)) {
setExpanded([...expanded, id]);
}
};
const onLabelClick = (event: React.MouseEvent, nodeId: string) => {
event.preventDefault();
scrollToItem(nodeId);
};
const renderTree = (nodes: NavigationTree[]) => {
return nodes.map(node => (
<TreeItem
key={node.id}
nodeId={node.id}
label={node.name}
onLabelClick={(event) => onLabelClick(event, node.id)}
className={cssNames({selected: node.selected})}
title={node.name}
>
{Array.isArray(node.children) ? node.children.map((node) => renderTree([node])) : null}
</TreeItem>
));
};
useEffect(() => {
if (!prevData.current.length) {
expandTopLevelNodes();
} else {
expandParentNode();
}
prevData.current = data;
}, [data]);
if (!data.length) {
return null;
}
return (
<TreeView
data-testid="TreeView"
className="TreeView"
expanded={expanded}
onNodeToggle={handleToggle}
defaultCollapseIcon={<Icon material="expand_more"/>}
defaultExpandIcon={<Icon material="chevron_right" />}
>
{renderTree(data)}
</TreeView>
);
}
......@@ -3,3 +3,4 @@
export * from "./useStorage";
export * from "./useOnUnmount";
export * from "./useInterval";
export * from "./useMutationObserver";
import { useEffect } from "react";
const config: MutationObserverInit = {
subtree: true,
childList: true,
attributes: false,
characterData: false
};
export function useMutationObserver(
root: Element,
callback: MutationCallback,
options: MutationObserverInit = config
) {
useEffect(() => {
if (root) {
const observer = new MutationObserver(callback);
observer.observe(root, options);
return () => {
observer.disconnect();
};
}
}, [callback, options]);
}
......@@ -834,6 +834,17 @@
react-is "^16.8.0"
react-transition-group "^4.4.0"
 
"@material-ui/lab@^4.0.0-alpha.57":
version "4.0.0-alpha.57"
resolved "https://registry.yarnpkg.com/@material-ui/lab/-/lab-4.0.0-alpha.57.tgz#e8961bcf6449e8a8dabe84f2700daacfcafbf83a"
integrity sha512-qo/IuIQOmEKtzmRD2E4Aa6DB4A87kmY6h0uYhjUmrrgmEAgbbw9etXpWPVXuRK6AGIQCjFzV6WO2i21m1R4FCw==
dependencies:
"@babel/runtime" "^7.4.4"
"@material-ui/utils" "^4.11.2"
clsx "^1.0.4"
prop-types "^15.7.2"
react-is "^16.8.0 || ^17.0.0"
"@material-ui/styles@^4.10.0":
version "4.10.0"
resolved "https://registry.yarnpkg.com/@material-ui/styles/-/styles-4.10.0.tgz#2406dc23aa358217aa8cc772e6237bd7f0544071"
......@@ -871,6 +882,15 @@
resolved "https://registry.yarnpkg.com/@material-ui/types/-/types-5.1.0.tgz#efa1c7a0b0eaa4c7c87ac0390445f0f88b0d88f2"
integrity sha512-7cqRjrY50b8QzRSYyhSpx4WRw2YuO0KKIGQEVk5J8uoz2BanawykgZGoWEqKm7pVIbzFDN0SpPcVV4IhOFkl8A==
 
"@material-ui/utils@^4.11.2":
version "4.11.2"
resolved "https://registry.yarnpkg.com/@material-ui/utils/-/utils-4.11.2.tgz#f1aefa7e7dff2ebcb97d31de51aecab1bb57540a"
integrity sha512-Uul8w38u+PICe2Fg2pDKCaIG7kOyhowZ9vjiC1FsVwPABTW8vPPKfF6OvxRq3IiBaI1faOJmgdvMG7rMJARBhA==
dependencies:
"@babel/runtime" "^7.4.4"
prop-types "^15.7.2"
react-is "^16.8.0 || ^17.0.0"
"@material-ui/utils@^4.9.12", "@material-ui/utils@^4.9.6":
version "4.9.12"
resolved "https://registry.yarnpkg.com/@material-ui/utils/-/utils-4.9.12.tgz#0d639f1c1ed83fffb2ae10c21d15a938795d9e65"
......@@ -4373,6 +4393,14 @@ deep-is@^0.1.3, deep-is@~0.1.3:
resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34"
integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=
 
deepdash@^5.3.5:
version "5.3.5"
resolved "https://registry.yarnpkg.com/deepdash/-/deepdash-5.3.5.tgz#611bec9c1f2829832d21971dcbefe712e408647d"
integrity sha512-1ZdPPCI1pCEqeAWGSw+Nbpb/2iIV4w3sGPc22H/PDtcApb8+psTzPIoOVD040iBaT2wqZab29Kjrz6G+cd5mqQ==
dependencies:
lodash "^4.17.20"
lodash-es "^4.17.20"
deepmerge@^4.2.2:
version "4.2.2"
resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955"
......@@ -8634,6 +8662,11 @@ lockfile@^1.0.4:
dependencies:
signal-exit "^3.0.2"
 
lodash-es@^4.17.20:
version "4.17.21"
resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.21.tgz#43e626c46e6591b7750beb2b50117390c609e3ee"
integrity sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==
lodash._baseuniq@~4.6.0:
version "4.6.0"
resolved "https://registry.yarnpkg.com/lodash._baseuniq/-/lodash._baseuniq-4.6.0.tgz#0ebb44e456814af7905c6212fa2c9b2d51b841e8"
......@@ -8692,6 +8725,11 @@ lodash@^4.0.0, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.13, lodash@^4.17.1
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52"
integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==
 
lodash@^4.17.20:
version "4.17.21"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
logform@^2.1.1:
version "2.1.2"
resolved "https://registry.yarnpkg.com/logform/-/logform-2.1.2.tgz#957155ebeb67a13164069825ce67ddb5bb2dd360"
......@@ -11226,7 +11264,7 @@ react-is@^16.12.0, react-is@^16.6.0, react-is@^16.7.0, react-is@^16.8.0, react-i
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==
 
react-is@^17.0.1:
"react-is@^16.8.0 || ^17.0.0", react-is@^17.0.1:
version "17.0.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.1.tgz#5b3531bd76a645a4c9fb6e693ed36419e3301339"
integrity sha512-NAnt2iGDXohE5LI7uBnLnqvLQMtzhkiAOLXTmv+qnF9Ky7xAPcX8Up/xWIhxvLVGJvuLiNc4xQLtuqDRzb4fSA==
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment