Navigation menu in Preferences (#2304)

This commit is contained in:
Alex Andreev authored and GitHub committed 2021-03-15 08:57:19 -04:00
1 parent 8e1583a59c
commit 5c373a886c
20 files changed
+838 -254

No files matched your search

@@ -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%;
}
}
}
@@ -0,0 +1,11 @@
.HelmCharts {
.repos {
margin-top: var(--margin);
.Badge {
display: flex;
margin-bottom: 1px!important;
padding: 6px 8px;
}
}
}
@@ -0,0 +1,139 @@
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()}
@@ -1,27 +1,2 @@
.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
}
}
@@ -1,30 +1,24 @@
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}
/>
<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>
<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}/>
<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>
<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}`;
<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>
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>
<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);
@@ -1,4 +1,6 @@
.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;
+79 -26
View File
@@ -1,17 +1,35 @@
.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,37 +37,44 @@
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-wrapper {
overflow: auto;
padding: $spacing * 2;
> .content-navigation {
display: flex;
flex-direction: column;
justify-content: flex-end;
overflow-y: auto;
margin-top: 32px;
> .content {
flex: 1;
margin: 0 auto;
width: var(--width);
min-width: var(--min-width);
max-width: var(--max-width);
ul.TreeView {
width: var(--nav-width);
padding-right: 24px;
}
}
h2:not(:first-of-type) {
margin-top: $spacing;
> .content-wrapper {
padding: 32px;
overflow: auto;
> .content {
width: var(--width);
margin: 0 auto;
}
}
p {
@@ -57,21 +82,49 @@
}
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;
}
}
}
+11 -4
View File
@@ -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>
@@ -0,0 +1,186 @@
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();
});
});
});
@@ -0,0 +1,96 @@
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>
);
});
@@ -0,0 +1 @@
export * from "./tree-view";
@@ -0,0 +1,27 @@
.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;
}
}
}
}
@@ -0,0 +1,100 @@
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>
);
}
+1
View File
@@ -3,3 +3,4 @@
export * from "./useStorage";
export * from "./useOnUnmount";
export * from "./useInterval";
export * from "./useMutationObserver";
+27
View File
@@ -0,0 +1,27 @@
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]);
}