Merge branch 'master' into pages-url-params

# Conflicts:
#	src/renderer/components/app.tsx
This commit is contained in:
Roman committed 2020-12-08 15:24:23 +02:00
commit a9d0af1656
39 files changed
+1452 -259

No files matched your search

+11 -9
View File
@@ -3,19 +3,20 @@ import "./components/app.scss";
import React from "react";
import * as Mobx from "mobx";
import * as MobxReact from "mobx-react";
import * as LensExtensions from "../extensions/extension-api";
import { App } from "./components/app";
import { LensApp } from "./lens-app";
import { render, unmountComponentAtNode } from "react-dom";
import { isMac } from "../common/vars";
import { userStore } from "../common/user-store";
import { workspaceStore } from "../common/workspace-store";
import { clusterStore } from "../common/cluster-store";
import { i18nStore } from "./i18n";
import { themeStore } from "./theme.store";
import { extensionsStore } from "../extensions/extensions-store";
import { userStore } from "../common/user-store";
import { isMac } from "../common/vars";
import { workspaceStore } from "../common/workspace-store";
import * as LensExtensions from "../extensions/extension-api";
import { extensionDiscovery } from "../extensions/extension-discovery";
import { extensionLoader } from "../extensions/extension-loader";
import { extensionsStore } from "../extensions/extensions-store";
import { filesystemProvisionerStore } from "../main/extension-filesystem";
import { App } from "./components/app";
import { i18nStore } from "./i18n";
import { LensApp } from "./lens-app";
import { themeStore } from "./theme.store";
type AppComponent = React.ComponentType & {
init?(): Promise<void>;
@@ -34,6 +35,7 @@ export async function bootstrap(App: AppComponent) {
rootElem.classList.toggle("is-mac", isMac);
extensionLoader.init();
extensionDiscovery.init();
// preload common stores
await Promise.all([
@@ -12,6 +12,7 @@ import { apiManager } from "../../api/api-manager";
export class EventStore extends KubeObjectStore<KubeEvent> {
api = eventApi;
limit = 1000;
saveLimit = 50000;
protected bindWatchEventsUpdater() {
return super.bindWatchEventsUpdater(5000);
@@ -5,6 +5,7 @@ import React from "react";
import { extensionDiscovery } from "../../../../extensions/extension-discovery";
import { ConfirmDialog } from "../../confirm-dialog";
import { Notifications } from "../../notifications";
import { ExtensionStateStore } from "../extension-install.store";
import { Extensions } from "../extensions";
jest.mock("fs-extra");
@@ -21,7 +22,8 @@ jest.mock("../../../../extensions/extension-discovery", () => ({
...jest.requireActual("../../../../extensions/extension-discovery"),
extensionDiscovery: {
localFolderPath: "/fake/path",
uninstallExtension: jest.fn(() => Promise.resolve())
uninstallExtension: jest.fn(() => Promise.resolve()),
isLoaded: true
}
}));
@@ -51,6 +53,10 @@ jest.mock("../../notifications", () => ({
}));
describe("Extensions", () => {
beforeEach(() => {
ExtensionStateStore.resetInstance();
});
it("disables uninstall and disable buttons while uninstalling", async () => {
render(<><Extensions /><ConfirmDialog/></>);
@@ -61,14 +67,14 @@ describe("Extensions", () => {
// Approve confirm dialog
fireEvent.click(screen.getByText("Yes"));
expect(extensionDiscovery.uninstallExtension).toHaveBeenCalledWith("/absolute/path");
expect(screen.getByText("Disable").closest("button")).toBeDisabled();
expect(screen.getByText("Uninstall").closest("button")).toBeDisabled();
});
it("displays error notification on uninstall error", () => {
(extensionDiscovery.uninstallExtension as any).mockImplementationOnce(() =>
(extensionDiscovery.uninstallExtension as any).mockImplementationOnce(() =>
Promise.reject()
);
render(<><Extensions /><ConfirmDialog/></>);
@@ -107,4 +113,17 @@ describe("Extensions", () => {
expect(Notifications.error).not.toHaveBeenCalled();
});
});
it("displays spinner while extensions are loading", () => {
extensionDiscovery.isLoaded = false;
const { container } = render(<Extensions />);
expect(container.querySelector(".Spinner")).toBeInTheDocument();
extensionDiscovery.isLoaded = true;
waitFor(() =>
expect(container.querySelector(".Spinner")).not.toBeInTheDocument()
);
});
});
@@ -0,0 +1,13 @@
import { observable } from "mobx";
import { autobind, Singleton } from "../../utils";
interface ExtensionState {
displayName: string;
// Possible states the extension can be
state: "installing" | "uninstalling";
}
@autobind()
export class ExtensionStateStore extends Singleton {
extensionState = observable.map<string, ExtensionState>();
}
@@ -37,6 +37,11 @@
font-weight: bold;
}
}
> .spinner-wrapper {
display: flex;
justify-content: center;
}
}
.SearchInput {
@@ -21,7 +21,9 @@ import { DropFileInput, Input, InputValidator, InputValidators, SearchInput } fr
import { PageLayout } from "../layout/page-layout";
import { SubTitle } from "../layout/sub-title";
import { Notifications } from "../notifications";
import { Spinner } from "../spinner/spinner";
import { TooltipPosition } from "../tooltip";
import { ExtensionStateStore } from "./extension-install.store";
import "./extensions.scss";
interface InstallRequest {
@@ -39,25 +41,20 @@ interface InstallRequestValidated extends InstallRequestPreloaded {
tempFile: string; // temp system path to packed extension for unpacking
}
interface ExtensionState {
displayName: string;
// Possible states the extension can be
state: "installing" | "uninstalling";
}
@observer
export class Extensions extends React.Component {
private supportedFormats = ["tar", "tgz"];
private static supportedFormats = ["tar", "tgz"];
private installPathValidator: InputValidator = {
private static installPathValidator: InputValidator = {
message: <Trans>Invalid URL or absolute path</Trans>,
validate(value: string) {
return InputValidators.isUrl.validate(value) || InputValidators.isPath.validate(value);
}
};
@observable
extensionState = observable.map<string, ExtensionState>();
get extensionStateStore() {
return ExtensionStateStore.getInstance<ExtensionStateStore>();
}
@observable search = "";
@observable installPath = "";
@@ -69,18 +66,24 @@ export class Extensions extends React.Component {
* Extensions that were removed from extensions but are still in "uninstalling" state
*/
@computed get removedUninstalling() {
return Array.from(this.extensionState.entries()).filter(([id, extension]) =>
extension.state === "uninstalling" && !this.extensions.find(extension => extension.id === id)
).map(([id, extension]) => ({ ...extension, id }));
return Array.from(this.extensionStateStore.extensionState.entries())
.filter(([id, extension]) =>
extension.state === "uninstalling"
&& !this.extensions.find(extension => extension.id === id)
)
.map(([id, extension]) => ({ ...extension, id }));
}
/**
* Extensions that were added to extensions but are still in "installing" state
*/
@computed get addedInstalling() {
return Array.from(this.extensionState.entries()).filter(([id, extension]) =>
extension.state === "installing" && this.extensions.find(extension => extension.id === id)
).map(([id, extension]) => ({ ...extension, id }));
return Array.from(this.extensionStateStore.extensionState.entries())
.filter(([id, extension]) =>
extension.state === "installing"
&& this.extensions.find(extension => extension.id === id)
)
.map(([id, extension]) => ({ ...extension, id }));
}
componentDidMount() {
@@ -90,7 +93,7 @@ export class Extensions extends React.Component {
Notifications.ok(
<p>Extension <b>{displayName}</b> successfully uninstalled!</p>
);
this.extensionState.delete(id);
this.extensionStateStore.extensionState.delete(id);
});
this.addedInstalling.forEach(({ id, displayName }) => {
@@ -103,7 +106,7 @@ export class Extensions extends React.Component {
Notifications.ok(
<p>Extension <b>{displayName}</b> successfully installed!</p>
);
this.extensionState.delete(id);
this.extensionStateStore.extensionState.delete(id);
this.installPath = "";
// Enable installed extensions by default.
@@ -116,14 +119,11 @@ export class Extensions extends React.Component {
@computed get extensions() {
const searchText = this.search.toLowerCase();
return Array.from(extensionLoader.userExtensions.values()).filter(ext => {
const { name, description } = ext.manifest;
return [
name.toLowerCase().includes(searchText),
description?.toLowerCase().includes(searchText),
].some(value => value);
});
return Array.from(extensionLoader.userExtensions.values())
.filter(({ manifest: { name, description }}) => (
name.toLowerCase().includes(searchText)
|| description?.toLowerCase().includes(searchText)
));
}
get extensionsPath() {
@@ -143,10 +143,10 @@ export class Extensions extends React.Component {
const { canceled, filePaths } = await dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), {
defaultPath: app.getPath("downloads"),
properties: ["openFile", "multiSelections"],
message: _i18n._(t`Select extensions to install (formats: ${this.supportedFormats.join(", ")}), `),
message: _i18n._(t`Select extensions to install (formats: ${Extensions.supportedFormats.join(", ")}), `),
buttonLabel: _i18n._(t`Use configuration`),
filters: [
{ name: "tarball", extensions: this.supportedFormats }
{ name: "tarball", extensions: Extensions.supportedFormats }
]
});
@@ -346,7 +346,9 @@ export class Extensions extends React.Component {
const displayName = extensionDisplayName(name, version);
const extensionId = path.join(extensionDiscovery.nodeModulesPath, name, "package.json");
this.extensionState.set(extensionId, {
logger.info(`Unpacking extension ${displayName}`, { fileName, tempFile });
this.extensionStateStore.extensionState.set(extensionId, {
state: "installing",
displayName
});
@@ -381,8 +383,8 @@ export class Extensions extends React.Component {
);
// Remove install state on install failure
if (this.extensionState.get(extensionId)?.state === "installing") {
this.extensionState.delete(extensionId);
if (this.extensionStateStore.extensionState.get(extensionId)?.state === "installing") {
this.extensionStateStore.extensionState.delete(extensionId);
}
} finally {
// clean up
@@ -406,7 +408,7 @@ export class Extensions extends React.Component {
const displayName = extensionDisplayName(extension.manifest.name, extension.manifest.version);
try {
this.extensionState.set(extension.id, {
this.extensionStateStore.extensionState.set(extension.id, {
state: "uninstalling",
displayName
});
@@ -418,8 +420,8 @@ export class Extensions extends React.Component {
);
// Remove uninstall state on uninstall failure
if (this.extensionState.get(extension.id)?.state === "uninstalling") {
this.extensionState.delete(extension.id);
if (this.extensionStateStore.extensionState.get(extension.id)?.state === "uninstalling") {
this.extensionStateStore.extensionState.delete(extension.id);
}
}
}
@@ -445,7 +447,7 @@ export class Extensions extends React.Component {
return extensions.map(extension => {
const { id, isEnabled, manifest } = extension;
const { name, description } = manifest;
const isUninstalling = this.extensionState.get(id)?.state === "uninstalling";
const isUninstalling = this.extensionStateStore.extensionState.get(id)?.state === "uninstalling";
return (
<div key={id} className="extension flex gaps align-center">
@@ -481,7 +483,7 @@ export class Extensions extends React.Component {
* True if at least one extension is in installing state
*/
@computed get isInstalling() {
return this.startingInstall || [...this.extensionState.values()].some(extension => extension.state === "installing");
return [...this.extensionStateStore.extensionState.values()].some(extension => extension.state === "installing");
}
render() {
@@ -504,9 +506,9 @@ export class Extensions extends React.Component {
className="box grow"
theme="round-black"
disabled={this.isInstalling}
placeholder={`Path or URL to an extension package (${this.supportedFormats.join(", ")})`}
placeholder={`Path or URL to an extension package (${Extensions.supportedFormats.join(", ")})`}
showErrorsAsTooltip={{ preferredPositions: TooltipPosition.BOTTOM }}
validators={installPath ? this.installPathValidator : undefined}
validators={installPath ? Extensions.installPathValidator : undefined}
value={installPath}
onChange={value => this.installPath = value}
onSubmit={this.installFromUrlOrPath}
@@ -524,7 +526,7 @@ export class Extensions extends React.Component {
<Button
primary
label="Install"
disabled={this.isInstalling || !this.installPathValidator.validate(installPath)}
disabled={this.isInstalling || !Extensions.installPathValidator.validate(installPath)}
waiting={this.isInstalling}
onClick={this.installFromUrlOrPath}
/>
@@ -540,7 +542,7 @@ export class Extensions extends React.Component {
value={this.search}
onChange={(value) => this.search = value}
/>
{this.renderExtensions()}
{extensionDiscovery.isLoaded ? this.renderExtensions() : <div className="spinner-wrapper"><Spinner/></div>}
</div>
</PageLayout>
</DropFileInput>
+9 -9
View File
@@ -61,12 +61,14 @@ export class App extends React.Component {
await requestMain(clusterSetFrameIdHandler, clusterId, frameId);
await getHostedCluster().whenReady; // cluster.activate() is done at this point
extensionLoader.loadOnClusterRenderer();
appEventBus.emit({
name: "cluster",
action: "open",
params: {
clusterId
}
setTimeout(() => {
appEventBus.emit({
name: "cluster",
action: "open",
params: {
clusterId
}
});
});
window.addEventListener("online", () => {
window.location.reload();
@@ -154,9 +156,7 @@ export class App extends React.Component {
const page = clusterPageRegistry.getByPageTarget(menu.target);
if (page) {
const pageComponent = () => <page.components.Page/>;
return <Route key={`extension-tab-layout-route-${index}`} path={page.url} component={pageComponent}/>;
return <Route key={`extension-tab-layout-route-${index}`} path={page.url} component={page.components.Page}/>;
}
}
});
@@ -0,0 +1,49 @@
jest.mock("../../../../common/ipc");
import React from "react";
import { fireEvent, render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { MainLayoutHeader } from "../main-layout-header";
import { Cluster } from "../../../../main/cluster";
import { workspaceStore } from "../../../../common/workspace-store";
import { broadcastMessage } from "../../../../common/ipc";
const mockBroadcastIpc = broadcastMessage as jest.MockedFunction<typeof broadcastMessage>;
const cluster: Cluster = new Cluster({
id: "foo",
contextName: "minikube",
kubeConfigPath: "minikube-config.yml",
workspace: workspaceStore.currentWorkspaceId
});
describe("<MainLayoutHeader />", () => {
it("renders w/o errors", () => {
const { container } = render(<MainLayoutHeader cluster={cluster} />);
expect(container).toBeInstanceOf(HTMLElement);
});
it("renders gear icon", () => {
const { container } = render(<MainLayoutHeader cluster={cluster} />);
const icon = container.querySelector(".Icon .icon");
expect(icon).toBeInstanceOf(HTMLElement);
expect(icon).toHaveTextContent("settings");
});
it("navigates to cluster settings", () => {
const { container } = render(<MainLayoutHeader cluster={cluster} />);
const icon = container.querySelector(".Icon");
fireEvent.click(icon);
expect(mockBroadcastIpc).toBeCalledWith("renderer:navigate", "/cluster/foo/settings");
});
it("renders cluster name", async () => {
const { getByText } = render(<MainLayoutHeader cluster={cluster} />);
expect(await getByText("minikube")).toBeTruthy();
});
});
@@ -0,0 +1,33 @@
import React from "react";
import { Trans } from "@lingui/macro";
import { clusterSettingsURL } from "../+cluster-settings";
import { broadcastMessage } from "../../../common/ipc";
import { Cluster } from "../../../main/cluster";
import { cssNames } from "../../utils";
import { Icon } from "../icon";
interface Props {
cluster: Cluster
className?: string
}
export function MainLayoutHeader({ cluster, className }: Props) {
return (
<header className={cssNames("flex gaps align-center justify-space-between", className)}>
<span className="cluster">{cluster.name}</span>
<Icon
material="settings"
tooltip={<Trans>Open cluster settings</Trans>}
interactive
onClick={() => {
broadcastMessage("renderer:navigate", clusterSettingsURL({
params: {
clusterId: cluster.id
}
}));
}}
/>
</header>
);
}
@@ -14,15 +14,6 @@
grid-area: header;
background: $layoutBackground;
padding: $padding $padding * 2;
span + .lens-version {
margin-left: $margin;
}
.lens-version {
font-size: x-small;
text-transform: uppercase;
}
}
> aside {
@@ -3,12 +3,13 @@ import "./main-layout.scss";
import React from "react";
import { observable, reaction } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import { autobind, createStorage, cssNames } from "../../utils";
import { Sidebar } from "./sidebar";
import { ErrorBoundary } from "../error-boundary";
import { Dock } from "../dock";
import { getHostedCluster } from "../../../common/cluster-store";
import { autobind, createStorage, cssNames } from "../../utils";
import { Dock } from "../dock";
import { ErrorBoundary } from "../error-boundary";
import { ResizeDirection, ResizeGrowthDirection, ResizeSide, ResizingAnchor } from "../resizing-anchor";
import { MainLayoutHeader } from "./main-layout-header";
import { Sidebar } from "./sidebar";
export interface MainLayoutProps {
className?: any;
@@ -66,9 +67,7 @@ export class MainLayout extends React.Component<MainLayoutProps> {
return (
<div className={cssNames("MainLayout", className)} style={this.getSidebarSize() as any}>
<header className={cssNames("flex gaps align-center", headerClass)}>
<span className="cluster">{cluster.name}</span>
</header>
<MainLayoutHeader className={headerClass} cluster={cluster} />
<aside className={cssNames("flex column", { pinned: this.isPinned, accessible: this.isAccessible })}>
<Sidebar className="box grow" isPinned={this.isPinned} toggle={this.toggleSidebar} />
+3 -1
View File
@@ -279,7 +279,9 @@ class SidebarNavItem extends React.Component<SidebarNavItemProps> {
public context: SidebarContextValue;
get itemId() {
return this.props.url;
const url = new URL(this.props.url, `${window.location.protocol}//${window.location.host}`);
return url.pathname; // pathname without get params
}
@computed get isExpanded() {
+16 -13
View File
@@ -11,7 +11,8 @@ import { getHostedCluster } from "../common/cluster-store";
@autobind()
export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemStore<T> {
abstract api: KubeApi<T>;
public limit: number;
public readonly limit?: number;
public readonly bufferSize: number = 50000;
constructor() {
super();
@@ -19,6 +20,16 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
kubeWatchApi.addListener(this, this.onWatchApiEvent);
}
get query(): IKubeApiQueryParams {
const { limit } = this;
if (!limit) {
return {};
}
return { limit };
}
getStatuses?(items: T[]): Record<string, number>;
getAllByNs(namespace: string | string[], strict = false): T[] {
@@ -62,10 +73,7 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
protected async loadItems(allowedNamespaces?: string[]): Promise<T[]> {
if (!this.api.isNamespaced || !allowedNamespaces) {
const { limit } = this;
const query: IKubeApiQueryParams = limit ? { limit } : {};
return this.api.list({}, query);
return this.api.list({}, this.query);
} else {
return Promise
.all(allowedNamespaces.map(namespace => this.api.list({ namespace })))
@@ -179,9 +187,9 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
return;
}
// create latest non-observable copy of items to apply updates in one action (==single render)
let items = this.items.toJS();
const items = this.items.toJS();
this.eventsBuffer.clear().forEach(({ type, object }) => {
for (const {type, object} of this.eventsBuffer.clear()) {
const { uid, selfLink } = object.metadata;
const index = items.findIndex(item => item.getId() === uid);
const item = items[index];
@@ -204,14 +212,9 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
}
break;
}
});
// slice to max allowed items
if (this.limit && items.length > this.limit) {
items = items.slice(-this.limit);
}
// update items
this.items.replace(this.sortItems(items));
this.items.replace(this.sortItems(items.slice(-this.bufferSize)));
}
}