Merge branch 'master' into windows-hidden-title-and-menu

This commit is contained in:
Alex Andreev committed 2021-12-09 14:39:52 +03:00
commit 3a08c30eb4
43 files changed
+1765 -265

No files matched your search

+99 -1
View File
@@ -26,6 +26,12 @@ import { KubeObject } from "../kube-object";
import AbortController from "abort-controller";
import { delay } from "../../utils/delay";
import { PassThrough } from "stream";
import { ApiManager, apiManager } from "../api-manager";
import { Ingress, Pod } from "../endpoints";
jest.mock("../api-manager");
const mockApiManager = apiManager as jest.Mocked<ApiManager>;
class TestKubeObject extends KubeObject {
static kind = "Pod";
@@ -33,7 +39,11 @@ class TestKubeObject extends KubeObject {
static apiBase = "/api/v1/pods";
}
class TestKubeApi extends KubeApi<TestKubeObject> { }
class TestKubeApi extends KubeApi<TestKubeObject> {
public async checkPreferredVersion() {
return super.checkPreferredVersion();
}
}
describe("forRemoteCluster", () => {
it("builds api client for KubeObject", async () => {
@@ -184,6 +194,94 @@ describe("KubeApi", () => {
expect(kubeApi.apiGroup).toEqual("extensions");
});
describe("checkPreferredVersion", () => {
it("registers with apiManager if checkPreferredVersion changes apiVersionPreferred", async () => {
expect.hasAssertions();
const api = new TestKubeApi({
objectConstructor: Ingress,
checkPreferredVersion: true,
fallbackApiBases: ["/apis/extensions/v1beta1/ingresses"],
request: {
get: jest.fn()
.mockImplementationOnce((path: string) => {
expect(path).toBe("/apis/networking.k8s.io/v1");
throw new Error("no");
})
.mockImplementationOnce((path: string) => {
expect(path).toBe("/apis/extensions/v1beta1");
return {
resources: [
{
name: "ingresses",
},
],
};
})
.mockImplementationOnce((path: string) => {
expect(path).toBe("/apis/extensions");
return {
preferredVersion: {
version: "v1beta1",
},
};
}),
} as any,
});
await api.checkPreferredVersion();
expect(api.apiVersionPreferred).toBe("v1beta1");
expect(mockApiManager.registerApi).toBeCalledWith("/apis/extensions/v1beta1/ingresses", expect.anything());
});
it("registers with apiManager if checkPreferredVersion changes apiVersionPreferred with non-grouped apis", async () => {
expect.hasAssertions();
const api = new TestKubeApi({
objectConstructor: Pod,
checkPreferredVersion: true,
fallbackApiBases: ["/api/v1beta1/pods"],
request: {
get: jest.fn()
.mockImplementationOnce((path: string) => {
expect(path).toBe("/api/v1");
throw new Error("no");
})
.mockImplementationOnce((path: string) => {
expect(path).toBe("/api/v1beta1");
return {
resources: [
{
name: "pods",
},
],
};
})
.mockImplementationOnce((path: string) => {
expect(path).toBe("/api");
return {
preferredVersion: {
version: "v1beta1",
},
};
}),
} as any,
});
await api.checkPreferredVersion();
expect(api.apiVersionPreferred).toBe("v1beta1");
expect(mockApiManager.registerApi).toBeCalledWith("/api/v1beta1/pods", expect.anything());
});
});
describe("patch", () => {
let api: TestKubeApi;
+11 -8
View File
@@ -37,7 +37,7 @@ export interface IKubeApiLinkRef {
apiPrefix?: string;
apiVersion: string;
resource: string;
name: string;
name?: string;
namespace?: string;
}
@@ -145,15 +145,18 @@ function _parseKubeApi(path: string): IKubeApiParsed {
};
}
export function createKubeApiURL(ref: IKubeApiLinkRef): string {
const { apiPrefix = "/apis", resource, apiVersion, name } = ref;
let { namespace } = ref;
export function createKubeApiURL({ apiPrefix = "/apis", resource, apiVersion, name, namespace }: IKubeApiLinkRef): string {
const parts = [apiPrefix, apiVersion];
if (namespace) {
namespace = `namespaces/${namespace}`;
parts.push("namespaces", namespace);
}
return [apiPrefix, apiVersion, namespace, resource, name]
.filter(v => v)
.join("/");
parts.push(resource);
if (name) {
parts.push(name);
}
return parts.join("/");
}
+55 -30
View File
@@ -38,9 +38,14 @@ import AbortController from "abort-controller";
import { Agent, AgentOptions } from "https";
import type { Patch } from "rfc6902";
/**
* The options used for creating a `KubeApi`
*/
export interface IKubeApiOptions<T extends KubeObject> {
/**
* base api-path for listing all resources, e.g. "/api/v1/pods"
*
* If not specified then will be the one on the `objectConstructor`
*/
apiBase?: string;
@@ -52,11 +57,33 @@ export interface IKubeApiOptions<T extends KubeObject> {
*/
fallbackApiBases?: string[];
objectConstructor: KubeObjectConstructor<T>;
request?: KubeJsonApi;
isNamespaced?: boolean;
kind?: string;
/**
* If `true` then will check all declared apiBases against the kube api server
* for the first accepted one.
*/
checkPreferredVersion?: boolean;
/**
* The constructor for the kube objects returned from the API
*/
objectConstructor: KubeObjectConstructor<T>;
/**
* The api instance to use for making requests
*
* @default apiKube
*/
request?: KubeJsonApi;
/**
* @deprecated should be specified by `objectConstructor`
*/
isNamespaced?: boolean;
/**
* @deprecated should be specified by `objectConstructor`
*/
kind?: string;
}
export interface IKubeApiQueryParams {
@@ -249,11 +276,11 @@ export interface DeleteResourceDescriptor extends ResourceDescriptor {
export class KubeApi<T extends KubeObject> {
readonly kind: string;
readonly apiBase: string;
readonly apiPrefix: string;
readonly apiGroup: string;
readonly apiVersion: string;
readonly apiVersionPreferred?: string;
apiBase: string;
apiPrefix: string;
apiGroup: string;
apiVersionPreferred?: string;
readonly apiResource: string;
readonly isNamespaced: boolean;
@@ -264,23 +291,18 @@ export class KubeApi<T extends KubeObject> {
private watchId = 1;
constructor(protected options: IKubeApiOptions<T>) {
const {
objectConstructor,
request = apiKube,
kind = options.objectConstructor?.kind,
isNamespaced = options.objectConstructor?.namespaced,
} = options || {};
const { objectConstructor, request, kind, isNamespaced } = options;
const { apiBase, apiPrefix, apiGroup, apiVersion, resource } = parseKubeApi(options.apiBase || objectConstructor.apiBase);
this.kind = kind;
this.isNamespaced = isNamespaced;
this.options = options;
this.kind = kind ?? objectConstructor.kind;
this.isNamespaced = isNamespaced ?? objectConstructor.namespaced ?? false;
this.apiBase = apiBase;
this.apiPrefix = apiPrefix;
this.apiGroup = apiGroup;
this.apiVersion = apiVersion;
this.apiResource = resource;
this.request = request;
this.request = request ?? apiKube;
this.objectConstructor = objectConstructor;
this.parseResponse = this.parseResponse.bind(this);
@@ -353,21 +375,16 @@ export class KubeApi<T extends KubeObject> {
const { apiPrefix, apiGroup } = await this.getPreferredVersionPrefixGroup();
// The apiPrefix and apiGroup might change due to fallbackApiBases, so we must override them
Object.defineProperty(this, "apiPrefix", {
value: apiPrefix,
});
Object.defineProperty(this, "apiGroup", {
value: apiGroup,
});
this.apiPrefix = apiPrefix;
this.apiGroup = apiGroup;
const res = await this.request.get<IKubePreferredVersion>(`${this.apiPrefix}/${this.apiGroup}`);
const url = [apiPrefix, apiGroup].filter(Boolean).join("/");
const res = await this.request.get<IKubePreferredVersion>(url);
Object.defineProperty(this, "apiVersionPreferred", {
value: res?.preferredVersion?.version ?? null,
});
this.apiVersionPreferred = res?.preferredVersion?.version ?? null;
if (this.apiVersionPreferred) {
Object.defineProperty(this, "apiBase", { value: this.getUrl() });
this.apiBase = this.computeApiBase();
apiManager.registerApi(this.apiBase, this);
}
}
@@ -385,7 +402,15 @@ export class KubeApi<T extends KubeObject> {
return this.list(params, { limit: 1 });
}
getUrl({ name, namespace = "default" }: Partial<ResourceDescriptor> = {}, query?: Partial<IKubeApiQueryParams>) {
private computeApiBase(): string {
return createKubeApiURL({
apiPrefix: this.apiPrefix,
apiVersion: this.apiVersionWithGroup,
resource: this.apiResource,
});
}
getUrl({ name, namespace }: Partial<ResourceDescriptor> = {}, query?: Partial<IKubeApiQueryParams>) {
const resourcePath = createKubeApiURL({
apiPrefix: this.apiPrefix,
apiVersion: this.apiVersionWithGroup,
+2 -2
View File
@@ -30,13 +30,13 @@ export enum RoutingErrorType {
MISSING_EXTENSION = "missing-ext",
}
export class RoutingError extends Error {
export class RoutingError<Query> extends Error {
/**
* Will be set if the routing error originated in an extension route table
*/
public extensionName?: string;
constructor(public type: RoutingErrorType, public url: Url) {
constructor(public type: RoutingErrorType, public url: Url<Query>) {
super("routing error");
}
+5 -5
View File
@@ -91,7 +91,7 @@ export abstract class LensProtocolRouter extends Singleton {
* @param url the parsed URL that initiated the `lens://` protocol
* @returns true if a route has been found
*/
protected _routeToInternal(url: Url): RouteAttempt {
protected _routeToInternal(url: Url<Record<string, string>>): RouteAttempt {
return this._route(this.internalRoutes.entries(), url);
}
@@ -101,7 +101,7 @@ export abstract class LensProtocolRouter extends Singleton {
* @param routes the array of path schemas, handler pairs to match against
* @param url the url (in its current state)
*/
protected _findMatchingRoute(routes: Iterable<[string, RouteHandler]>, url: Url): null | [match<Record<string, string>>, RouteHandler] {
protected _findMatchingRoute(routes: Iterable<[string, RouteHandler]>, url: Url<Record<string, string>>): null | [match<Record<string, string>>, RouteHandler] {
const matches: [match<Record<string, string>>, RouteHandler][] = [];
for (const [schema, handler] of routes) {
@@ -128,7 +128,7 @@ export abstract class LensProtocolRouter extends Singleton {
* @param routes the array of (path schemas, handler) pairs to match against
* @param url the url (in its current state)
*/
protected _route(routes: Iterable<[string, RouteHandler]>, url: Url, extensionName?: string): RouteAttempt {
protected _route(routes: Iterable<[string, RouteHandler]>, url: Url<Record<string, string>>, extensionName?: string): RouteAttempt {
const route = this._findMatchingRoute(routes, url);
if (!route) {
@@ -166,7 +166,7 @@ export abstract class LensProtocolRouter extends Singleton {
* @param url the protocol request URI that was "open"-ed
* @returns either the found name or the instance of `LensExtension`
*/
protected async _findMatchingExtensionByName(url: Url): Promise<LensExtension | string> {
protected async _findMatchingExtensionByName(url: Url<Record<string, string>>): Promise<LensExtension | string> {
interface ExtensionUrlMatch {
[EXTENSION_PUBLISHER_MATCH]: string;
[EXTENSION_NAME_MATCH]: string;
@@ -222,7 +222,7 @@ export abstract class LensProtocolRouter extends Singleton {
* Note: this function modifies its argument, do not reuse
* @param url the protocol request URI that was "open"-ed
*/
protected async _routeToExtension(url: Url): Promise<RouteAttempt> {
protected async _routeToExtension(url: Url<Record<string, string>>): Promise<RouteAttempt> {
const extension = await this._findMatchingExtensionByName(url);
if (typeof extension === "string") {
@@ -26,6 +26,12 @@ import { BaseRegistry } from "./base-registry";
interface StatusBarComponents {
Item?: React.ComponentType;
/**
* The side of the bottom bar to place this component.
*
* @default "right"
*/
position?: "left" | "right";
}
interface StatusBarRegistrationV2 {
+4 -4
View File
@@ -39,7 +39,7 @@ export interface FallbackHandler {
* @returns `true` if it should be routed internally to Lens, `false` if to an extension
* @throws if `host` is not valid
*/
function checkHost(url: URLParse): boolean {
function checkHost<Query>(url: URLParse<Query>): boolean {
switch (url.host) {
case "app":
return true;
@@ -112,7 +112,7 @@ export class LensProtocolRouterMain extends proto.LensProtocolRouter {
return false;
}
protected async _findMatchingExtensionByName(url: URLParse): Promise<LensExtension | string> {
protected async _findMatchingExtensionByName(url: URLParse<Record<string, string>>): Promise<LensExtension | string> {
const firstAttempt = await super._findMatchingExtensionByName(url);
if (typeof firstAttempt !== "string") {
@@ -126,7 +126,7 @@ export class LensProtocolRouterMain extends proto.LensProtocolRouter {
return "";
}
protected _routeToInternal(url: URLParse): RouteAttempt {
protected _routeToInternal(url: URLParse<Record<string, string>>): RouteAttempt {
const rawUrl = url.toString(); // for sending to renderer
const attempt = super._routeToInternal(url);
@@ -135,7 +135,7 @@ export class LensProtocolRouterMain extends proto.LensProtocolRouter {
return attempt;
}
protected async _routeToExtension(url: URLParse): Promise<RouteAttempt> {
protected async _routeToExtension(url: URLParse<Record<string, string>>): Promise<RouteAttempt> {
const rawUrl = url.toString(); // for sending to renderer
/**
+5 -2
View File
@@ -104,13 +104,13 @@ export async function bootstrap(comp: () => Promise<AppComponent>, di: Dependenc
logger.info(`${logPrefix} initializing WelcomeMenuRegistry`);
initializers.initWelcomeMenuRegistry();
logger.info(`${logPrefix} initializing WorkloadsOverviewDetailRegist`);
logger.info(`${logPrefix} initializing WorkloadsOverviewDetailRegistry`);
initializers.initWorkloadsOverviewDetailRegistry();
logger.info(`${logPrefix} initializing CatalogEntityDetailRegistry`);
initializers.initCatalogEntityDetailRegistry();
logger.info(`${logPrefix} initializing CatalogCategoryRegistryEntrie`);
logger.info(`${logPrefix} initializing CatalogCategoryRegistryEntries`);
initializers.initCatalogCategoryRegistryEntries();
logger.info(`${logPrefix} initializing Catalog`);
@@ -119,6 +119,9 @@ export async function bootstrap(comp: () => Promise<AppComponent>, di: Dependenc
logger.info(`${logPrefix} initializing IpcRendererListeners`);
initializers.initIpcRendererListeners();
logger.info(`${logPrefix} initializing StatusBarRegistry`);
initializers.initStatusBarRegistry();
ExtensionLoader.createInstance().init();
ExtensionDiscovery.createInstance().init();
@@ -57,9 +57,7 @@ export class CrdResources extends React.Component<Props> {
}
@computed get store() {
if (!this.crd) return null;
return apiManager.getStore(this.crd.getResourceApiBase());
return apiManager.getStore(this.crd?.getResourceApiBase());
}
render() {
@@ -29,15 +29,14 @@ import { CRDResourceStore } from "./crd-resource.store";
import { KubeObject } from "../../../common/k8s-api/kube-object";
function initStore(crd: CustomResourceDefinition) {
const apiBase = crd.getResourceApiBase();
const kind = crd.getResourceKind();
const isNamespaced = crd.isNamespaced();
const api = apiManager.getApi(apiBase) ?? new KubeApi({
objectConstructor: KubeObject,
apiBase,
kind,
isNamespaced,
});
const objectConstructor = class extends KubeObject {
static readonly kind = crd.getResourceKind();
static readonly namespaced = crd.isNamespaced();
static readonly apiBase = crd.getResourceApiBase();
};
const api = apiManager.getApi(objectConstructor.apiBase)
?? new KubeApi({ objectConstructor });
if (!apiManager.getStore(api)) {
apiManager.registerStore(new CRDResourceStore(api));
@@ -0,0 +1,40 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import { observer } from "mobx-react";
import { Icon } from "../icon";
import { HotbarStore } from "../../../common/hotbar-store";
import { CommandOverlay } from "../command-palette";
import { HotbarSwitchCommand } from "../hotbar/hotbar-switch-command";
export const ActiveHotbarName = observer(() => {
return (
<div
className="flex items-center"
data-testid="current-hotbar-name"
onClick={() => CommandOverlay.open(<HotbarSwitchCommand />)}
>
<Icon material="bookmarks" className="mr-2" size={14}/>
{HotbarStore.getInstance().getActive()?.name}
</div>
);
});
@@ -20,22 +20,26 @@
*/
.BottomBar {
$spacing: $padding * 0.5;
--flex-gap: #{$spacing};
@apply flex px-2 text-white;
grid-area: bottom-bar;
background-color: var(--blue);
padding: 0 2px;
height: var(--bottom-bar-height);
font-size: var(--font-size-small);
}
.extensions {
font-size: var(--font-size-small);
color: white;
.item {
padding: $padding * 0.25 $padding * 0.5;
&:hover {
background-color: #ffffff33;
cursor: pointer;
}
}
.item {
@apply flex items-center mr-2 h-full px-2 last:mr-0;
&:hover {
@apply cursor-pointer;
background-color: #ffffff33;
}
}
.onLeft + .onRight {
@apply ml-auto;
}
.onRight {}
@@ -20,25 +20,58 @@
*/
import React from "react";
import { render } from "@testing-library/react";
import mockFs from "mock-fs";
import { render, fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { BottomBar } from "./bottom-bar";
import { StatusBarRegistry } from "../../../extensions/registries";
import { HotbarStore } from "../../../common/hotbar-store";
import { AppPaths } from "../../../common/app-paths";
import { CommandOverlay } from "../command-palette";
import { HotbarSwitchCommand } from "../hotbar/hotbar-switch-command";
import { ActiveHotbarName } from "./active-hotbar-name";
jest.mock("electron", () => ({
app: {
getPath: () => "/foo",
jest.mock("../command-palette", () => ({
CommandOverlay: {
open: jest.fn(),
},
}));
import { BottomBar } from "./bottom-bar";
import { StatusBarRegistry } from "../../../extensions/registries";
AppPaths.init();
jest.mock("electron", () => ({
app: {
getName: () => "lens",
setName: jest.fn(),
setPath: jest.fn(),
getPath: () => "tmp",
},
ipcMain: {
handle: jest.fn(),
on: jest.fn(),
removeAllListeners: jest.fn(),
off: jest.fn(),
send: jest.fn(),
},
}));
describe("<BottomBar />", () => {
beforeEach(() => {
const mockOpts = {
"tmp": {
"test-store.json": JSON.stringify({}),
},
};
mockFs(mockOpts);
StatusBarRegistry.createInstance();
HotbarStore.createInstance();
});
afterEach(() => {
StatusBarRegistry.resetInstance();
HotbarStore.resetInstance();
mockFs.restore();
});
it("renders w/o errors", () => {
@@ -87,4 +120,73 @@ describe("<BottomBar />", () => {
expect(await getByTestId(testId)).toHaveTextContent(text);
});
it("show default hotbar name", () => {
StatusBarRegistry.getInstance().getItems = jest.fn().mockImplementationOnce(() => [
{ item: () => <ActiveHotbarName/> },
]);
const { getByTestId } = render(<BottomBar />);
expect(getByTestId("current-hotbar-name")).toHaveTextContent("default");
});
it("show active hotbar name", () => {
StatusBarRegistry.getInstance().getItems = jest.fn().mockImplementationOnce(() => [
{ item: () => <ActiveHotbarName/> },
]);
const { getByTestId } = render(<BottomBar />);
HotbarStore.getInstance().add({
id: "new",
name: "new",
}, { setActive: true });
expect(getByTestId("current-hotbar-name")).toHaveTextContent("new");
});
it("opens command palette on click", () => {
StatusBarRegistry.getInstance().getItems = jest.fn().mockImplementationOnce(() => [
{ item: () => <ActiveHotbarName/> },
]);
const { getByTestId } = render(<BottomBar />);
const activeHotbar = getByTestId("current-hotbar-name");
fireEvent.click(activeHotbar);
expect(CommandOverlay.open).toHaveBeenCalledWith(<HotbarSwitchCommand />);
});
it("sort positioned items properly", () => {
StatusBarRegistry.getInstance().getItems = jest.fn().mockImplementationOnce(() => [
{
components: {
Item: () => <div data-testid="sortedElem">right</div>,
},
},
{
components: {
Item: () => <div data-testid="sortedElem">right</div>,
position: "right",
},
},
{
components: {
Item: () => <div data-testid="sortedElem">left</div>,
position: "left",
},
},
{
components: {
Item: () => <div data-testid="sortedElem">left</div>,
position: "left",
},
},
]);
const { getAllByTestId } = render(<BottomBar />);
const elems = getAllByTestId("sortedElem");
const positions = elems.map(elem => elem.textContent);
expect(positions).toEqual(["left", "left", "right", "right"]);
});
});
@@ -19,11 +19,12 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import "./bottom-bar.scss";
import styles from "./bottom-bar.module.css";
import React from "react";
import { observer } from "mobx-react";
import { StatusBarRegistration, StatusBarRegistry } from "../../../extensions/registries";
import { cssNames } from "../../utils";
@observer
export class BottomBar extends React.Component {
@@ -44,26 +45,36 @@ export class BottomBar extends React.Component {
return null;
}
items.sort(function sortLeftPositionFirst(a, b) {
return a.components?.position?.localeCompare(b.components?.position);
});
return (
<div className="extensions box grow flex gaps justify-flex-end">
<>
{items.map((registration, index) => {
if (!registration?.item && !registration?.components?.Item) {
return null;
}
return (
<div className="flex align-center gaps item" key={index}>
<div
className={cssNames(styles.item, {
[styles.onLeft]: registration.components?.position == "left",
[styles.onRight]: registration.components?.position != "left",
})}
key={index}
>
{this.renderRegisteredItem(registration)}
</div>
);
})}
</div>
</>
);
}
render() {
return (
<div className="BottomBar flex gaps">
<div className={styles.BottomBar}>
{this.renderRegisteredItems()}
</div>
);
@@ -20,7 +20,7 @@
*/
.ClusterManager {
--bottom-bar-height: 22px;
--bottom-bar-height: 21px;
--hotbar-width: 75px;
display: grid;
@@ -140,6 +140,7 @@ export class ConfirmDialog extends React.Component<ConfirmDialogProps> {
isOpen={dialogState.isOpen}
onClose={this.onClose}
close={this.close}
{...(dialogState.isOpen ? { "data-testid":"confirmation-dialog" } : {})}
>
<div className="confirm-content">
{icon} {message}
@@ -158,6 +159,7 @@ export class ConfirmDialog extends React.Component<ConfirmDialogProps> {
label={labelOk}
onClick={prevDefault(this.ok)}
waiting={this.isSaving}
data-testid="confirm"
{...okButtonProps}
/>
</div>
+3 -1
View File
@@ -41,6 +41,7 @@ export interface DialogProps {
modal?: boolean;
pinned?: boolean;
animated?: boolean;
"data-testid"?: string;
}
interface DialogState {
@@ -149,7 +150,7 @@ export class Dialog extends React.PureComponent<DialogProps, DialogState> {
};
render() {
const { modal, animated, pinned } = this.props;
const { modal, animated, pinned, "data-testid": testId } = this.props;
let { className } = this.props;
className = cssNames("Dialog flex center", className, { modal, pinned });
@@ -158,6 +159,7 @@ export class Dialog extends React.PureComponent<DialogProps, DialogState> {
className={className}
onClick={stopPropagation}
ref={this.ref}
data-testid={testId}
>
<div className="box" ref={e => this.contentElem = e}>
{this.props.children}
@@ -35,7 +35,7 @@ import { InfoPanel } from "./info-panel";
import * as resourceApplierApi from "../../../common/k8s-api/endpoints/resource-applier.api";
import { Notifications } from "../notifications";
import logger from "../../../common/logger";
import type { KubeJsonApiData, KubeJsonApiError } from "../../../common/k8s-api/kube-json-api";
import type { KubeJsonApiData } from "../../../common/k8s-api/kube-json-api";
import { getDetailsUrl } from "../kube-detail-params";
import { apiManager } from "../../../common/k8s-api/api-manager";
import { prevDefault } from "../../utils";
@@ -130,9 +130,7 @@ export class CreateResource extends React.Component<Props> {
</p>,
);
} catch (error) {
const failureReason = (error as KubeJsonApiError).reason.toString();
Notifications.error(failureReason);
Notifications.error(error?.toString() ?? "Unknown error occured");
}
});
@@ -43,7 +43,8 @@
.Icon {
--size: 16px;
padding: 0 4px;
padding: 0 4px 0 0px;
margin: 0px 4px;
&:hover {
box-shadow: none;
@@ -0,0 +1,371 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`kube-object-menu given kube object renders 1`] = `
<body>
<div>
<div>
<ul
class="Animate opacity Menu MenuActions flex KubeObjectMenu toolbar gaps right bottom"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
>
<li>
Some menu item
</li>
<li
class="MenuItem"
data-testid="menu-action-remove"
tabindex="0"
>
<i
class="Icon material interactive focusable"
id="tooltip_target_4"
tabindex="0"
>
<span
class="icon"
data-icon-name="delete"
>
delete
</span>
<div />
</i>
<span
class="title"
>
Delete
</span>
</li>
</ul>
</div>
</div>
<div
class="Animate opacity-scale Dialog flex center ConfirmDialog modal"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
/>
<div
class="Tooltip narrow invisible formatter"
>
Delete
</div>
</body>
`;
exports[`kube-object-menu given kube object when removing kube object renders 1`] = `
<body>
<div>
<div>
<ul
class="Animate opacity Menu MenuActions flex KubeObjectMenu toolbar gaps right bottom"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
>
<li>
Some menu item
</li>
<li
class="MenuItem"
data-testid="menu-action-remove"
tabindex="0"
>
<i
class="Icon material interactive focusable"
id="tooltip_target_8"
tabindex="0"
>
<span
class="icon"
data-icon-name="delete"
>
delete
</span>
<div />
</i>
<span
class="title"
>
Delete
</span>
</li>
</ul>
</div>
</div>
<div
class="Animate opacity-scale Dialog flex center ConfirmDialog modal"
data-testid="confirmation-dialog"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
>
<div
class="box"
>
<div
class="confirm-content"
>
<i
class="Icon material focusable big"
>
<span
class="icon"
data-icon-name="warning"
>
warning
</span>
</i>
<div>
<p>
Remove
some-kind
<b>
some-namespace/some-name
</b>
from
<b>
Some name
</b>
?
</p>
</div>
</div>
<div
class="confirm-buttons"
>
<button
class="Button cancel plain"
type="button"
>
Cancel
</button>
<button
class="Button ok primary"
data-testid="confirm"
type="button"
>
Remove
</button>
</div>
</div>
</div>
<div
class="Tooltip narrow invisible formatter"
>
Delete
</div>
</body>
`;
exports[`kube-object-menu given kube object with namespace when removing kube object, renders confirmation dialog with namespace 1`] = `
<body>
<div>
<div>
<ul
class="Animate opacity Menu MenuActions flex KubeObjectMenu toolbar gaps right bottom"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
>
<li>
Some menu item
</li>
<li
class="MenuItem"
data-testid="menu-action-remove"
tabindex="0"
>
<i
class="Icon material interactive focusable"
id="tooltip_target_33"
tabindex="0"
>
<span
class="icon"
data-icon-name="delete"
>
delete
</span>
<div />
</i>
<span
class="title"
>
Delete
</span>
</li>
</ul>
</div>
</div>
<div
class="Animate opacity-scale Dialog flex center ConfirmDialog modal"
data-testid="confirmation-dialog"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
>
<div
class="box"
>
<div
class="confirm-content"
>
<i
class="Icon material focusable big"
>
<span
class="icon"
data-icon-name="warning"
>
warning
</span>
</i>
<div>
<p>
Remove
some-kind
<b>
some-namespace/some-name
</b>
from
<b>
Some name
</b>
?
</p>
</div>
</div>
<div
class="confirm-buttons"
>
<button
class="Button cancel plain"
type="button"
>
Cancel
</button>
<button
class="Button ok primary"
data-testid="confirm"
type="button"
>
Remove
</button>
</div>
</div>
</div>
<div
class="Tooltip narrow invisible formatter"
>
Delete
</div>
</body>
`;
exports[`kube-object-menu given kube object without namespace when removing kube object, renders confirmation dialog without namespace 1`] = `
<body>
<div>
<div>
<ul
class="Animate opacity Menu MenuActions flex KubeObjectMenu toolbar gaps right bottom"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
>
<li>
Some menu item
</li>
<li
class="MenuItem"
data-testid="menu-action-remove"
tabindex="0"
>
<i
class="Icon material interactive focusable"
id="tooltip_target_41"
tabindex="0"
>
<span
class="icon"
data-icon-name="delete"
>
delete
</span>
<div />
</i>
<span
class="title"
>
Delete
</span>
</li>
</ul>
</div>
</div>
<div
class="Animate opacity-scale Dialog flex center ConfirmDialog modal"
data-testid="confirmation-dialog"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
>
<div
class="box"
>
<div
class="confirm-content"
>
<i
class="Icon material focusable big"
>
<span
class="icon"
data-icon-name="warning"
>
warning
</span>
</i>
<div>
<p>
Remove
some-kind
<b>
some-name
</b>
from
<b>
Some name
</b>
?
</p>
</div>
</div>
<div
class="confirm-buttons"
>
<button
class="Button cancel plain"
type="button"
>
Cancel
</button>
<button
class="Button ok primary"
data-testid="confirm"
type="button"
>
Remove
</button>
</div>
</div>
</div>
<div
class="Tooltip narrow invisible formatter"
>
Delete
</div>
</body>
`;
exports[`kube-object-menu given no kube object, renders 1`] = `
<body>
<div>
<ul
class="Animate opacity Menu MenuActions flex KubeObjectMenu toolbar gaps right bottom"
style="--enter-duration: 100ms; --leave-duration: 100ms;"
/>
</div>
</body>
`;
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { ApiManager } from "../../../../common/k8s-api/api-manager";
import { apiManager } from "../../../../common/k8s-api/api-manager";
import type { Injectable } from "@ogre-tools/injectable";
import { lifecycleEnum } from "@ogre-tools/injectable";
const apiManagerInjectable: Injectable<ApiManager> = {
getDependencies: () => ({}),
instantiate: () => apiManager,
lifecycle: lifecycleEnum.singleton,
};
export default apiManagerInjectable;
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { Injectable } from "@ogre-tools/injectable";
import { lifecycleEnum } from "@ogre-tools/injectable";
import type { Cluster } from "../../../../main/cluster";
import clusterInjectable from "./cluster.injectable";
interface Dependencies {
cluster: Cluster;
}
const clusterNameInjectable: Injectable<string | undefined, Dependencies> = {
getDependencies: di => ({
cluster: di.inject(clusterInjectable),
}),
instantiate: ({ cluster }) => cluster?.name,
lifecycle: lifecycleEnum.transient,
};
export default clusterNameInjectable;
@@ -0,0 +1,33 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { getActiveClusterEntity } from "../../../api/catalog-entity-registry";
import type { Injectable } from "@ogre-tools/injectable";
import { lifecycleEnum } from "@ogre-tools/injectable";
import type { Cluster } from "../../../../main/cluster";
const clusterInjectable: Injectable<Cluster | null> = {
getDependencies: () => ({}),
instantiate: () => getActiveClusterEntity(),
lifecycle: lifecycleEnum.transient,
};
export default clusterInjectable;
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { editResourceTab } from "../../dock/edit-resource.store";
import type { Injectable } from "@ogre-tools/injectable";
import { lifecycleEnum } from "@ogre-tools/injectable";
const editResourceTabInjectable: Injectable<typeof editResourceTab> = {
getDependencies: () => ({}),
instantiate: () => editResourceTab,
lifecycle: lifecycleEnum.singleton,
};
export default editResourceTabInjectable;
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { hideDetails } from "../../kube-detail-params";
import type { Injectable } from "@ogre-tools/injectable";
import { lifecycleEnum } from "@ogre-tools/injectable";
export const hideDetailsInjectable: Injectable<typeof hideDetails> = {
getDependencies: () => ({}),
instantiate: () => hideDetails,
lifecycle: lifecycleEnum.singleton,
};
export default hideDetailsInjectable;
@@ -0,0 +1,43 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { KubeObjectMenuRegistry } from "../../../../../extensions/registries";
import type { KubeObject } from "../../../../../common/k8s-api/kube-object";
export interface Dependencies {
kubeObjectMenuRegistry: KubeObjectMenuRegistry;
}
export interface InstantiationParameter {
kubeObject: KubeObject;
}
export const getKubeObjectMenuItems = (
{ kubeObjectMenuRegistry }: Dependencies,
{ kubeObject }: InstantiationParameter,
) => {
if (!kubeObject) {
return [];
}
return kubeObjectMenuRegistry
.getItemsForKind(kubeObject.kind, kubeObject.apiVersion)
.map(item => item.components.MenuItem);
};
@@ -0,0 +1,44 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Injectable, lifecycleEnum } from "@ogre-tools/injectable";
import kubeObjectMenuRegistryInjectable from "./kube-object-menu-registry.injectable";
import {
InstantiationParameter,
Dependencies,
getKubeObjectMenuItems,
} from "./get-kube-object-menu-items";
const kubeObjectMenuItemsInjectable: Injectable<
ReturnType<typeof getKubeObjectMenuItems>,
Dependencies,
InstantiationParameter
> = {
getDependencies: di => ({
kubeObjectMenuRegistry: di.inject(kubeObjectMenuRegistryInjectable),
}),
instantiate: getKubeObjectMenuItems,
lifecycle: lifecycleEnum.transient,
};
export default kubeObjectMenuItemsInjectable;
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { KubeObjectMenuRegistry } from "../../../../../extensions/registries";
import type { Injectable } from "@ogre-tools/injectable";
import { lifecycleEnum } from "@ogre-tools/injectable";
const kubeObjectMenuRegistryInjectable: Injectable<KubeObjectMenuRegistry> = {
getDependencies: () => ({}),
instantiate: () => KubeObjectMenuRegistry.getInstance(),
lifecycle: lifecycleEnum.singleton,
};
export default kubeObjectMenuRegistryInjectable;
@@ -19,4 +19,5 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
export * from "./kube-object-menu";
export type { KubeObjectMenuProps } from "./kube-object-menu";
export { KubeObjectMenu } from "./kube-object-menu-container";
@@ -0,0 +1,24 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { getInjectedComponent } from "@ogre-tools/injectable-react";
import KubeObjectMenuInjectable from "./kube-object-menu.injectable";
export const KubeObjectMenu = getInjectedComponent(KubeObjectMenuInjectable);
@@ -0,0 +1,60 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import {
KubeObjectMenu,
KubeObjectMenuDependencies,
KubeObjectMenuProps,
} from "./kube-object-menu";
import type { KubeObject } from "../../../common/k8s-api/kube-object";
import { lifecycleEnum, Injectable } from "@ogre-tools/injectable";
import apiManagerInjectable from "./dependencies/api-manager.injectable";
import clusterNameInjectable from "./dependencies/cluster-name.injectable";
import editResourceTabInjectable from "./dependencies/edit-resource-tab.injectable";
import hideDetailsInjectable from "./dependencies/hide-details.injectable";
import kubeObjectMenuItemsInjectable from "./dependencies/kube-object-menu-items/kube-object-menu-items.injectable";
const KubeObjectMenuInjectable: Injectable<
JSX.Element,
KubeObjectMenuDependencies<KubeObject>,
KubeObjectMenuProps<KubeObject>
> = {
getDependencies: (di, props) => ({
clusterName: di.inject(clusterNameInjectable),
apiManager: di.inject(apiManagerInjectable),
editResourceTab: di.inject(editResourceTabInjectable),
hideDetails: di.inject(hideDetailsInjectable),
kubeObjectMenuItems: di.inject(kubeObjectMenuItemsInjectable, {
kubeObject: props.object,
}),
}),
instantiate: (dependencies, props) => (
<KubeObjectMenu {...dependencies} {...props} />
),
lifecycle: lifecycleEnum.transient,
};
export default KubeObjectMenuInjectable;
@@ -0,0 +1,284 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import { screen } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { KubeObject } from "../../../common/k8s-api/kube-object";
import userEvent from "@testing-library/user-event";
import type { ConfigurableDependencyInjectionContainer } from "@ogre-tools/injectable";
import type { KubeObjectMenuRegistration } from "../../../extensions/registries";
import { KubeObjectMenuRegistry } from "../../../extensions/registries";
import { ConfirmDialog } from "../confirm-dialog";
import asyncFn, { AsyncFnMock } from "@async-fn/jest";
import { getDiForUnitTesting } from "../getDiForUnitTesting";
import clusterInjectable from "./dependencies/cluster.injectable";
import hideDetailsInjectable from "./dependencies/hide-details.injectable";
import editResourceTabInjectable from "./dependencies/edit-resource-tab.injectable";
import { TabKind } from "../dock/dock.store";
import kubeObjectMenuRegistryInjectable from "./dependencies/kube-object-menu-items/kube-object-menu-registry.injectable";
import { DiRender, renderFor } from "../test-utils/renderFor";
import type { Cluster } from "../../../main/cluster";
import type { ApiManager } from "../../../common/k8s-api/api-manager";
import apiManagerInjectable from "./dependencies/api-manager.injectable";
import { KubeObjectMenu } from "./index";
describe("kube-object-menu", () => {
let di: ConfigurableDependencyInjectionContainer;
let render: DiRender;
beforeEach(() => {
di = getDiForUnitTesting();
// TODO: Remove global shared state
KubeObjectMenuRegistry.resetInstance();
KubeObjectMenuRegistry.createInstance();
render = renderFor(di);
di.override(clusterInjectable, {
name: "Some name",
} as Cluster);
di.override(apiManagerInjectable, {
// eslint-disable-next-line unused-imports/no-unused-vars-ts
getStore: api => undefined,
} as ApiManager);
di.override(hideDetailsInjectable, () => {});
di.override(editResourceTabInjectable, () => ({
id: "irrelevant",
kind: TabKind.TERMINAL,
pinned: false,
title: "irrelevant",
}));
addDynamicMenuItem({
di,
apiVersions: ["some-api-version"],
kind: "some-kind",
});
addDynamicMenuItem({
di,
apiVersions: ["some-unrelated-api-version"],
kind: "some-kind",
});
addDynamicMenuItem({
di,
apiVersions: ["some-api-version"],
kind: "some-unrelated-kind",
});
});
it("given no cluster, does not crash", () => {
di.override(clusterInjectable, null);
expect(() => {
render(<KubeObjectMenu object={null} toolbar={true} />);
}).not.toThrow();
});
it("given no kube object, renders", () => {
const { baseElement } = render(
<KubeObjectMenu object={null} toolbar={true} />,
);
expect(baseElement).toMatchSnapshot();
});
describe("given kube object", () => {
let baseElement: Element;
let removeActionMock: AsyncFnMock<Function>;
beforeEach(async () => {
const objectStub = KubeObject.create({
apiVersion: "some-api-version",
kind: "some-kind",
metadata: {
uid: "some-uid",
name: "some-name",
resourceVersion: "some-resource-version",
namespace: "some-namespace",
},
});
removeActionMock = asyncFn();
({ baseElement } = render(
<div>
<ConfirmDialog />
<KubeObjectMenu
object={objectStub}
toolbar={true}
removeAction={removeActionMock}
/>
</div>,
));
});
it("renders", () => {
expect(baseElement).toMatchSnapshot();
});
it("does not open a confirmation dialog yet", () => {
expect(screen.queryByTestId("confirmation-dialog")).toBeNull();
});
describe("when removing kube object", () => {
beforeEach(() => {
const menuItem = screen.getByTestId("menu-action-remove");
userEvent.click(menuItem);
});
it("renders", () => {
expect(baseElement).toMatchSnapshot();
});
it("opens a confirmation dialog", () => {
screen.getByTestId("confirmation-dialog");
});
describe("when remove is confirmed", () => {
beforeEach(() => {
const confirmRemovalButton = screen.getByTestId("confirm");
userEvent.click(confirmRemovalButton);
});
it("calls for removal of the kube object", () => {
expect(removeActionMock).toHaveBeenCalledWith();
});
it("does not close the confirmation dialog yet", () => {
screen.getByTestId("confirmation-dialog");
});
it("when removal resolves, closes the confirmation dialog", async () => {
await removeActionMock.resolve();
expect(screen.queryByTestId("confirmation-dialog")).toBeNull();
});
});
});
});
describe("given kube object with namespace", () => {
let baseElement: Element;
beforeEach(async () => {
const objectStub = KubeObject.create({
apiVersion: "some-api-version",
kind: "some-kind",
metadata: {
uid: "some-uid",
name: "some-name",
resourceVersion: "some-resource-version",
namespace: "some-namespace",
},
});
({ baseElement } = render(
<div>
<ConfirmDialog />
<KubeObjectMenu
object={objectStub}
toolbar={true}
removeAction={() => {}}
/>
</div>,
));
});
it("when removing kube object, renders confirmation dialog with namespace", () => {
const menuItem = screen.getByTestId("menu-action-remove");
userEvent.click(menuItem);
expect(baseElement).toMatchSnapshot();
});
});
describe("given kube object without namespace", () => {
let baseElement: Element;
beforeEach(async () => {
const objectStub = KubeObject.create({
apiVersion: "some-api-version",
kind: "some-kind",
metadata: {
uid: "some-uid",
name: "some-name",
resourceVersion: "some-resource-version",
namespace: undefined,
},
});
({ baseElement } = render(
<div>
<ConfirmDialog />
<KubeObjectMenu
object={objectStub}
toolbar={true}
removeAction={() => {}}
/>
</div>,
));
});
it("when removing kube object, renders confirmation dialog without namespace", () => {
const menuItem = screen.getByTestId("menu-action-remove");
userEvent.click(menuItem);
expect(baseElement).toMatchSnapshot();
});
});
});
const addDynamicMenuItem = ({
di,
apiVersions,
kind,
}: {
di: ConfigurableDependencyInjectionContainer;
apiVersions: string[];
kind: string;
}) => {
const MenuItemComponent: React.FC = () => <li>Some menu item</li>;
const dynamicMenuItemStub: KubeObjectMenuRegistration = {
apiVersions,
kind,
components: { MenuItem: MenuItemComponent },
};
const kubeObjectMenuRegistry = di.inject(kubeObjectMenuRegistryInjectable);
kubeObjectMenuRegistry.add(dynamicMenuItemStub);
};
@@ -22,25 +22,37 @@
import React from "react";
import { boundMethod, cssNames } from "../../utils";
import type { KubeObject } from "../../../common/k8s-api/kube-object";
import { editResourceTab } from "../dock/edit-resource.store";
import { MenuActions, MenuActionsProps } from "../menu/menu-actions";
import { hideDetails } from "../kube-detail-params";
import { apiManager } from "../../../common/k8s-api/api-manager";
import { KubeObjectMenuRegistry } from "../../../extensions/registries/kube-object-menu-registry";
import { MenuActions, MenuActionsProps } from "../menu";
import identity from "lodash/identity";
import type { ApiManager } from "../../../common/k8s-api/api-manager";
export interface KubeObjectMenuProps<T> extends MenuActionsProps {
object: T | null | undefined;
export interface KubeObjectMenuDependencies<TKubeObject> {
apiManager: ApiManager;
kubeObjectMenuItems: React.ElementType[];
clusterName: string;
hideDetails: () => void;
editResourceTab: (kubeObject: TKubeObject) => void;
}
export interface KubeObjectMenuProps<TKubeObject> extends MenuActionsProps {
object: TKubeObject | null | undefined;
editable?: boolean;
removable?: boolean;
}
export class KubeObjectMenu<T extends KubeObject> extends React.Component<KubeObjectMenuProps<T>> {
export interface KubeObjectMenuPropsAndDependencies<TKubeObject>
extends KubeObjectMenuProps<TKubeObject>,
KubeObjectMenuDependencies<TKubeObject> {}
export class KubeObjectMenu<
TKubeObject extends KubeObject,
> extends React.Component<KubeObjectMenuPropsAndDependencies<TKubeObject>> {
get store() {
const { object } = this.props;
if (!object) return null;
return apiManager.getStore(object.selfLink);
return this.props.apiManager.getStore(object.selfLink);
}
get isEditable() {
@@ -53,13 +65,13 @@ export class KubeObjectMenu<T extends KubeObject> extends React.Component<KubeOb
@boundMethod
async update() {
hideDetails();
editResourceTab(this.props.object);
this.props.hideDetails();
this.props.editResourceTab(this.props.object);
}
@boundMethod
async remove() {
hideDetails();
this.props.hideDetails();
const { object, removeAction } = this.props;
if (removeAction) await removeAction();
@@ -74,28 +86,27 @@ export class KubeObjectMenu<T extends KubeObject> extends React.Component<KubeOb
return null;
}
const breadcrumbParts = [object.getNs(), object.getName()];
const breadcrumb = breadcrumbParts.filter(identity).join("/");
return (
<p>Remove {object.kind} <b>{object.getName()}</b>?</p>
<p>
Remove {object.kind} <b>{breadcrumb}</b> from <b>{this.props.clusterName}</b>?
</p>
);
}
getMenuItems(): React.ReactChild[] {
const { object, toolbar } = this.props;
if (!object) {
return [];
}
return KubeObjectMenuRegistry
.getInstance()
.getItemsForKind(object.kind, object.apiVersion)
.map(({ components: { MenuItem }}, index) => (
<MenuItem
object={object}
key={`menu-item-${index}`}
toolbar={toolbar}
/>
));
return this.props.kubeObjectMenuItems.map((MenuItem, index) => (
<MenuItem
object={object}
toolbar={toolbar}
key={`menu-item-${index}`}
/>
));
}
render() {
+25 -27
View File
@@ -30,7 +30,6 @@ import { Icon, IconProps } from "../icon";
import { Menu, MenuItem, MenuProps } from "../menu";
import uniqueId from "lodash/uniqueId";
import isString from "lodash/isString";
import { RenderDelay } from "../render-delay/render-delay";
export interface MenuActionsProps extends Partial<MenuProps> {
className?: string;
@@ -125,32 +124,31 @@ export class MenuActions extends React.Component<MenuActionsProps> {
return (
<>
{this.renderTriggerIcon()}
<RenderDelay>
<Menu
htmlFor={this.id}
isOpen={this.isOpen} open={this.toggle} close={this.toggle}
className={menuClassName}
usePortal={autoClose}
closeOnScroll={autoClose}
closeOnClickItem={autoCloseOnSelect ?? autoClose }
closeOnClickOutside={autoClose}
{...menuProps}
>
{children}
{updateAction && (
<MenuItem onClick={updateAction}>
<Icon material="edit" interactive={toolbar} tooltip="Edit"/>
<span className="title">Edit</span>
</MenuItem>
)}
{removeAction && (
<MenuItem onClick={this.remove}>
<Icon material="delete" interactive={toolbar} tooltip="Delete"/>
<span className="title">Delete</span>
</MenuItem>
)}
</Menu>
</RenderDelay>
<Menu
htmlFor={this.id}
isOpen={this.isOpen} open={this.toggle} close={this.toggle}
className={menuClassName}
usePortal={autoClose}
closeOnScroll={autoClose}
closeOnClickItem={autoCloseOnSelect ?? autoClose }
closeOnClickOutside={autoClose}
{...menuProps}
>
{children}
{updateAction && (
<MenuItem onClick={updateAction}>
<Icon material="edit" interactive={toolbar} tooltip="Edit"/>
<span className="title">Edit</span>
</MenuItem>
)}
{removeAction && (
<MenuItem onClick={this.remove} data-testid="menu-action-remove">
<Icon material="delete" interactive={toolbar} tooltip="Delete"/>
<span className="title">Delete</span>
</MenuItem>
)}
</Menu>
</>
);
}
@@ -0,0 +1,42 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import {
render as testingLibraryRender,
RenderResult,
} from "@testing-library/react";
import type { ConfigurableDependencyInjectionContainer } from "@ogre-tools/injectable";
import { DiContextProvider } from "@ogre-tools/injectable-react";
export type DiRender = (ui: React.ReactElement) => RenderResult;
type DiRenderFor = (
di: ConfigurableDependencyInjectionContainer,
) => DiRender;
export const renderFor: DiRenderFor = di => ui =>
testingLibraryRender(
<DiContextProvider value={{ di }}>{ui}</DiContextProvider>,
);
@@ -61,11 +61,11 @@ export function initCatalogCategoryRegistryEntries() {
ctx.menuItems.push(
{
icon: "create_new_folder",
title: "Sync kubeconfig folders(s)",
title: "Sync kubeconfig folder(s)",
defaultAction: true,
onClick: async () => {
await PathPicker.pick({
label: "Sync folders(s)",
label: "Sync folder(s)",
buttonLabel: "Sync",
properties: ["showHiddenFiles", "multiSelections", "openDirectory"],
onPick: addSyncEntries,
+1
View File
@@ -30,3 +30,4 @@ export * from "./registries";
export * from "./welcome-menu-registry";
export * from "./workloads-overview-detail-registry";
export * from "./catalog-category-registry";
export * from "./status-bar-registry";
@@ -0,0 +1,35 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import { StatusBarRegistry } from "../../extensions/registries";
import { ActiveHotbarName } from "../components/cluster-manager/active-hotbar-name";
export function initStatusBarRegistry() {
StatusBarRegistry.getInstance().add([
{
components: {
Item: () => <ActiveHotbarName/>,
position: "left",
},
},
]);
}