Merge remote-tracking branch 'upstream/master' into make-menu-registry-obsolete

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne Savolainen committed 2021-12-15 16:14:08 +02:00
commit 2189679a30
40 files changed
+670 -333

No files matched your search

+5 -1
View File
@@ -90,7 +90,11 @@ export interface ClusterPreferences extends ClusterPrometheusPreferences {
terminalCWD?: string;
clusterName?: string;
iconOrder?: number;
icon?: string;
/**
* The <img> src for the cluster. If set to `null` that means that it was
* cleared by preferences.
*/
icon?: string | null;
httpsProxy?: string;
hiddenMetrics?: string[];
nodeShellImage?: string;
+2 -3
View File
@@ -21,7 +21,6 @@
import { JsonApi, JsonApiData, JsonApiError } from "./json-api";
import type { Response } from "node-fetch";
import type { Cluster } from "../../main/cluster";
import { LensProxy } from "../../main/lens-proxy";
import { apiKubePrefix, isDebugging } from "../vars";
@@ -73,7 +72,7 @@ export interface KubeJsonApiError extends JsonApiError {
}
export class KubeJsonApi extends JsonApi<KubeJsonApiData> {
static forCluster(cluster: Cluster): KubeJsonApi {
static forCluster(clusterId: string): KubeJsonApi {
const port = LensProxy.getInstance().port;
return new this({
@@ -82,7 +81,7 @@ export class KubeJsonApi extends JsonApi<KubeJsonApiData> {
debug: isDebugging,
}, {
headers: {
"Host": `${cluster.id}.localhost:${port}`,
"Host": `${clusterId}.localhost:${port}`,
},
});
}
@@ -19,29 +19,24 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { isCompatibleExtension } from "../extension-compatibility";
import { rawIsCompatibleExtension } from "../extension-compatibility";
import { Console } from "console";
import { stdout, stderr } from "process";
import type { LensExtensionManifest } from "../lens-extension";
import { appSemVer } from "../../common/vars";
import { SemVer } from "semver";
console = new Console(stdout, stderr);
describe("extension compatibility", () => {
describe("appSemVer with no prerelease tag", () => {
beforeAll(() => {
appSemVer.major = 5;
appSemVer.minor = 0;
appSemVer.patch = 3;
appSemVer.prerelease = [];
});
const isCompatibleExtension = rawIsCompatibleExtension(new SemVer("5.0.3"));
it("has no extension comparator", () => {
const manifest = { name: "extensionName", version: "0.0.1" };
expect(isCompatibleExtension(manifest)).toBe(false);
});
it.each([
{
comparator: "",
@@ -83,19 +78,32 @@ describe("extension compatibility", () => {
});
describe("appSemVer with prerelease tag", () => {
beforeAll(() => {
appSemVer.major = 5;
appSemVer.minor = 0;
appSemVer.patch = 3;
appSemVer.prerelease = ["beta", 3];
const isCompatibleExtension = rawIsCompatibleExtension(new SemVer("5.0.3-beta.3"));
it("^5.1.0 should work when lens' version is 5.1.0-latest.123456789", () => {
const comparer = rawIsCompatibleExtension(new SemVer("5.1.0-latest.123456789"));
expect(comparer({ name: "extensionName", version: "0.0.1", engines: { lens: "^5.1.0" }})).toBe(true);
});
it("^5.1.0 should not when lens' version is 5.1.0-beta.1.123456789", () => {
const comparer = rawIsCompatibleExtension(new SemVer("5.1.0-beta.123456789"));
expect(comparer({ name: "extensionName", version: "0.0.1", engines: { lens: "^5.1.0" }})).toBe(false);
});
it("^5.1.0 should not when lens' version is 5.1.0-alpha.1.123456789", () => {
const comparer = rawIsCompatibleExtension(new SemVer("5.1.0-alpha.123456789"));
expect(comparer({ name: "extensionName", version: "0.0.1", engines: { lens: "^5.1.0" }})).toBe(false);
});
it("has no extension comparator", () => {
const manifest = { name: "extensionName", version: "0.0.1" };
expect(isCompatibleExtension(manifest)).toBe(false);
});
it.each([
{
comparator: "",
@@ -130,9 +138,7 @@ describe("extension compatibility", () => {
expected: false,
},
])("extension comparator test: %p", ({ comparator, expected }) => {
const manifest: LensExtensionManifest = { name: "extensionName", version: "0.0.1", engines: { lens: comparator }};
expect(isCompatibleExtension(manifest)).toBe(expected);
expect(isCompatibleExtension({ name: "extensionName", version: "0.0.1", engines: { lens: comparator }})).toBe(expected);
});
});
});
+34 -6
View File
@@ -19,19 +19,47 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import semver from "semver";
import semver, { SemVer } from "semver";
import { appSemVer, isProduction } from "../common/vars";
import type { LensExtensionManifest } from "./lens-extension";
export function isCompatibleExtension(manifest: LensExtensionManifest): boolean {
if (manifest.engines?.lens) {
/* include Lens's prerelease tag in the matching so the extension's compatibility is not limited by it */
return semver.satisfies(appSemVer, manifest.engines.lens, { includePrerelease: true });
export function rawIsCompatibleExtension(version: SemVer): (manifest: LensExtensionManifest) => boolean {
const { major, minor, patch, prerelease: oldPrelease } = version;
let prerelease = "";
if (oldPrelease.length > 0) {
const [first] = oldPrelease;
if (first === "alpha" || first === "beta" || first === "rc") {
/**
* Strip the build IDs and "latest" prerelease tag as that is not really
* a part of API version
*/
prerelease = `-${oldPrelease.slice(0, 2).join(".")}`;
}
}
return false;
/**
* We unfortunately have to format as string because the constructor only
* takes an instance or a string.
*/
const strippedVersion = new SemVer(`${major}.${minor}.${patch}${prerelease}`, { includePrerelease: true });
return (manifest: LensExtensionManifest): boolean => {
if (manifest.engines?.lens) {
/**
* include Lens's prerelease tag in the matching so the extension's
* compatibility is not limited by it
*/
return semver.satisfies(strippedVersion, manifest.engines.lens, { includePrerelease: true });
}
return false;
};
}
export const isCompatibleExtension = rawIsCompatibleExtension(appSemVer);
export function isCompatibleBundledExtension(manifest: LensExtensionManifest): boolean {
return !isProduction || manifest.version === appSemVer.raw;
}
+1
View File
@@ -55,6 +55,7 @@ export { ClusterRole, clusterRoleApi } from "../../common/k8s-api/endpoints";
export { ClusterRoleBinding, clusterRoleBindingApi } from "../../common/k8s-api/endpoints";
export { CustomResourceDefinition, crdApi } from "../../common/k8s-api/endpoints";
export { KubeObjectStatusLevel } from "./kube-object-status";
export { KubeJsonApi } from "../../common/k8s-api/kube-json-api";
// types
export type { ILocalKubeApiConfig, IRemoteKubeApiConfig, IKubeApiCluster } from "../../common/k8s-api/kube-api";
+9 -3
View File
@@ -136,11 +136,16 @@ export class ClusterManager extends Singleton {
entity.spec.metrics.prometheus = prometheus;
}
// Only set the icon if the preference is set. If the preference is not set
// then let the source determine if a cluster has an icon.
if (cluster.preferences.icon) {
entity.spec.icon ??= {};
entity.spec.icon.src = cluster.preferences.icon;
} else if (cluster.preferences.icon === null) {
/**
* NOTE: only clear the icon if set to `null` by ClusterIconSettings.
* We can then also clear that value too
*/
entity.spec.icon = undefined;
cluster.preferences.icon = undefined;
}
catalogEntityRegistry.items.splice(index, 1, entity);
@@ -177,7 +182,8 @@ export class ClusterManager extends Singleton {
}
}
@action syncClustersFromCatalog(entities: KubernetesCluster[]) {
@action
protected syncClustersFromCatalog(entities: KubernetesCluster[]) {
for (const entity of entities) {
const cluster = this.store.getById(entity.metadata.uid);
+4 -3
View File
@@ -102,7 +102,10 @@ configurePackages();
mangleProxyEnv();
logger.debug("[APP-MAIN] initializing ipc main handlers");
initializers.initIpcMainHandlers();
const menuItems = di.inject(electronMenuItemsInjectable);
initializers.initIpcMainHandlers(menuItems);
if (app.commandLine.getSwitchValue("proxy-server") !== "") {
process.env.HTTPS_PROXY = app.commandLine.getSwitchValue("proxy-server");
@@ -239,8 +242,6 @@ app.on("ready", async () => {
logger.info("🖥️ Starting WindowManager");
const windowManager = WindowManager.createInstance();
const menuItems = di.inject(electronMenuItemsInjectable);
onQuitCleanup.push(
initMenu(windowManager, menuItems),
initTray(windowManager),
+18 -3
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { BrowserWindow, dialog, IpcMainInvokeEvent } from "electron";
import { BrowserWindow, dialog, IpcMainInvokeEvent, Menu } from "electron";
import { clusterFrameMap } from "../../common/cluster-frames";
import { clusterActivateHandler, clusterSetFrameIdHandler, clusterVisibilityHandler, clusterRefreshHandler, clusterDisconnectHandler, clusterKubectlApplyAllHandler, clusterKubectlDeleteAllHandler, clusterDeleteHandler, clusterSetDeletingHandler, clusterClearDeletingHandler } from "../../common/cluster-ipc";
import type { ClusterId } from "../../common/cluster-types";
@@ -30,12 +30,15 @@ import { catalogEntityRegistry } from "../catalog";
import { pushCatalogToRenderer } from "../catalog-pusher";
import { ClusterManager } from "../cluster-manager";
import { ResourceApplier } from "../resource-applier";
import { WindowManager } from "../window-manager";
import { IpcMainWindowEvents, WindowManager } from "../window-manager";
import path from "path";
import { remove } from "fs-extra";
import { AppPaths } from "../../common/app-paths";
import { getAppMenu } from "../menu/menu";
import type { MenuRegistration } from "../menu/menu-registration";
import type { IComputedValue } from "mobx";
export function initIpcMainHandlers() {
export function initIpcMainHandlers(electronMenuItems: IComputedValue<MenuRegistration[]>) {
ipcMainHandle(clusterActivateHandler, (event, clusterId: ClusterId, force = false) => {
return ClusterStore.getInstance()
.getById(clusterId)
@@ -148,4 +151,16 @@ export function initIpcMainHandlers() {
return dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), dialogOpts);
});
ipcMainOn(IpcMainWindowEvents.OPEN_CONTEXT_MENU, async (event) => {
const menu = Menu.buildFromTemplate(getAppMenu(WindowManager.getInstance(), electronMenuItems.get()));
const options = {
...BrowserWindow.fromWebContents(event.sender),
// Center of the topbar menu icon
x: 20,
y: 20,
} as Electron.PopupOptions;
menu.popup(options);
});
}
+58 -7
View File
@@ -50,6 +50,24 @@ export function isLongRunningRequest(reqUrl: string) {
return getBoolean(url.searchParams, watchParam) || getBoolean(url.searchParams, followParam);
}
/**
* This is the list of ports that chrome considers unsafe to allow HTTP
* conntections to. Because they are the standard ports for processes that are
* too forgiving in the connection types they accept.
*
* If we get one of these ports, the easiest thing to do is to just try again.
*
* Source: https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/net/base/port_util.cc
*/
const disallowedPorts = new Set([
1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,
87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,
139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,
540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,
2049, 3659, 4045, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669, 6697,
10080,
]);
export class LensProxy extends Singleton {
protected origin: string;
protected proxyServer: http.Server;
@@ -91,12 +109,13 @@ export class LensProxy extends Singleton {
}
/**
* Starts the lens proxy.
* @resolves After the server is listening
* @rejects if there is an error before that happens
* Starts to listen on an OS provided port. Will reject if the server throws
* an error.
*
* Resolves with the port number that was picked
*/
listen(): Promise<void> {
return new Promise<void>((resolve, reject) => {
private attemptToListen(): Promise<number> {
return new Promise<number>((resolve, reject) => {
this.proxyServer.listen(0, "127.0.0.1");
this.proxyServer
@@ -113,7 +132,7 @@ export class LensProxy extends Singleton {
this.port = port;
appEventBus.emit({ name: "lens-proxy", action: "listen", params: { port }});
resolve();
resolve(port);
})
.once("error", (error) => {
logger.info(`[LENS-PROXY]: Proxy server failed to start: ${error}`);
@@ -122,8 +141,40 @@ export class LensProxy extends Singleton {
});
}
/**
* Starts the lens proxy.
* @resolves After the server is listening on a good port
* @rejects if there is an error before that happens
*/
async listen(): Promise<void> {
const seenPorts = new Set<number>();
while(true) {
this.proxyServer?.close();
const port = await this.attemptToListen();
if (!disallowedPorts.has(port)) {
// We didn't get a port that would result in an ERR_UNSAFE_PORT error, use it
return;
}
logger.warn(`[LENS-PROXY]: Proxy server has with port known to be considered unsafe to connect to by chrome, restarting...`);
if (seenPorts.has(port)) {
/**
* Assume that if we have seen the port before, then the OS has looped
* through all the ports possible and we will not be able to get a safe
* port.
*/
throw new Error("Failed to start LensProxy due to seeing too many unsafe ports. Please restart Lens.");
} else {
seenPorts.add(port);
}
}
}
close() {
logger.info("Closing proxy server");
logger.info("[LENS-PROXY]: Closing server");
this.proxyServer.close();
this.closed = true;
}
+12 -2
View File
@@ -63,7 +63,7 @@ export function showAbout(browserWindow: BrowserWindow) {
});
}
export function buildMenu(
export function getAppMenu(
windowManager: WindowManager,
electronMenuItems: MenuRegistration[],
) {
@@ -324,5 +324,15 @@ export function buildMenu(
appMenu.delete("mac");
}
Menu.setApplicationMenu(Menu.buildFromTemplate([...appMenu.values()]));
return [...appMenu.values()];
}
export function buildMenu(
windowManager: WindowManager,
electronMenuItems: MenuRegistration[],
) {
Menu.setApplicationMenu(
Menu.buildFromTemplate(getAppMenu(windowManager, electronMenuItems)),
);
}
+1 -1
View File
@@ -64,7 +64,7 @@ export class NodeShellSession extends ShellSession {
const args = ["exec", "-i", "-t", "-n", "kube-system", this.podName, "--"];
const nodeApi = new NodesApi({
objectConstructor: Node,
request: KubeJsonApi.forCluster(this.cluster),
request: KubeJsonApi.forCluster(this.cluster.id),
});
const node = await nodeApi.get({ name: this.nodeName });
const nodeOs = node.getOperatingSystem();
+2
View File
@@ -158,6 +158,8 @@ export abstract class ShellSession {
cwd,
env,
name: "xterm-256color",
// TODO: Something else is broken here so we need to force the use of winPty on windows
useConpty: false,
}));
}
+7 -2
View File
@@ -29,9 +29,13 @@ import { delay, iter, Singleton } from "../common/utils";
import { ClusterFrameInfo, clusterFrameMap } from "../common/cluster-frames";
import { IpcRendererNavigationEvents } from "../renderer/navigation/events";
import logger from "./logger";
import { productName } from "../common/vars";
import { isMac, productName } from "../common/vars";
import { LensProxy } from "./lens-proxy";
export const enum IpcMainWindowEvents {
OPEN_CONTEXT_MENU = "window:open-context-menu",
}
function isHideable(window: BrowserWindow | null): boolean {
return Boolean(window && !window.isDestroyed());
}
@@ -81,7 +85,8 @@ export class WindowManager extends Singleton {
show: false,
minWidth: 700, // accommodate 800 x 600 display minimum
minHeight: 500, // accommodate 800 x 600 display minimum
titleBarStyle: "hiddenInset",
titleBarStyle: isMac ? "hiddenInset" : "hidden",
frame: isMac,
backgroundColor: "#1e2124",
webPreferences: {
nodeIntegration: true,
-12
View File
@@ -144,18 +144,6 @@ export class TerminalApi extends WebSocketApi<TerminalEvents> {
this.socket.binaryType = "arraybuffer";
}
destroy() {
if (!this.socket) return;
const controlCode = String.fromCharCode(4); // ctrl+d
this.sendMessage({ type: TerminalChannels.STDIN, data: controlCode });
setTimeout(() => super.destroy(), 2000);
}
reconnect() {
super.reconnect();
}
sendMessage(message: TerminalMessage) {
return this.send(serialize(message));
}
-2
View File
@@ -174,8 +174,6 @@ export async function bootstrap(comp: () => Promise<AppComponent>, di: Dependenc
render(
<DiContextProvider value={{ di }}>
{isMac && <div id="draggable-top" />}
{DefaultProps(App)}
</DiContextProvider>,
@@ -53,4 +53,19 @@ describe("NetworkPolicyDetails", () => {
expect(await findByTestId(container, "egress-0")).toBeInstanceOf(HTMLElement);
expect(await findByText(container, "foo: bar")).toBeInstanceOf(HTMLElement);
});
it("should not crash if egress nodeSelector doesn't have matchLabels", async () => {
const spec: NetworkPolicySpec = {
egress: [{
to: [{
namespaceSelector: {},
}],
}],
podSelector: {},
};
const policy = new NetworkPolicy({ metadata: {} as any, spec } as any);
const { container } = render(<NetworkPolicyDetails object={policy} />);
expect(container).toBeInstanceOf(HTMLElement);
});
});
@@ -29,4 +29,13 @@
padding-bottom: 16px;
}
}
ul.policySelectorList {
list-style: disc;
}
.policySelectorList ul {
list-style: circle;
list-style-position: inside;
}
}
@@ -23,13 +23,15 @@ import styles from "./network-policy-details.module.css";
import React from "react";
import { DrawerItem, DrawerTitle } from "../drawer";
import { IPolicyIpBlock, IPolicySelector, NetworkPolicy, NetworkPolicyPeer, NetworkPolicyPort } from "../../../common/k8s-api/endpoints/network-policy.api";
import { IPolicyIpBlock, NetworkPolicy, NetworkPolicyPeer, NetworkPolicyPort } from "../../../common/k8s-api/endpoints/network-policy.api";
import { Badge } from "../badge";
import { SubTitle } from "../layout/sub-title";
import { observer } from "mobx-react";
import type { KubeObjectDetailsProps } from "../kube-object-details";
import { KubeObjectMeta } from "../kube-object-meta";
import logger from "../../../common/logger";
import type { LabelMatchExpression, LabelSelector } from "../../../common/k8s-api/kube-object";
import { isEmpty } from "lodash";
interface Props extends KubeObjectDetailsProps<NetworkPolicy> {
}
@@ -60,20 +62,57 @@ export class NetworkPolicyDetails extends React.Component<Props> {
);
}
renderIPolicySelector(name: string, selector: IPolicySelector | undefined) {
renderMatchLabels(matchLabels: Record<string, string | undefined> | undefined) {
if (!matchLabels) {
return null;
}
return Object.entries(matchLabels)
.map(([key, value]) => <li key={key}>{key}: {value}</li>);
}
renderMatchExpressions(matchExpressions: LabelMatchExpression[] | undefined) {
if (!matchExpressions) {
return null;
}
return matchExpressions.map(expr => {
switch (expr.operator) {
case "DoesNotExist":
case "Exists":
return <li key={expr.key}>{expr.key} ({expr.operator})</li>;
case "In":
case "NotIn":
return (
<li key={expr.key}>
{expr.key}({expr.operator})
<ul>
{expr.values.map((value, index) => <li key={index}>{value}</li>)}
</ul>
</li>
);
}
});
}
renderIPolicySelector(name: string, selector: LabelSelector | undefined) {
if (!selector) {
return null;
}
const { matchLabels, matchExpressions } = selector;
return (
<DrawerItem name={name}>
{
Object
.entries(selector.matchLabels)
.map(data => data.join(": "))
.join(", ")
|| "(empty)"
}
<ul className={styles.policySelectorList}>
{this.renderMatchLabels(matchLabels)}
{this.renderMatchExpressions(matchExpressions)}
{
(isEmpty(matchLabels) && isEmpty(matchExpressions)) && (
<li>(empty)</li>
)
}
</ul>
</DrawerItem>
);
}
-11
View File
@@ -97,17 +97,6 @@ html, body {
}
}
#draggable-top {
@include set-draggable;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: var(--main-layout-header);
z-index: 1000;
pointer-events: none;
}
body {
font: $font-size $font-main;
}
@@ -1,24 +0,0 @@
/**
* 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.
*/
.Clipboard {
cursor: pointer;
}
@@ -1,88 +0,0 @@
/**
* 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 "./clipboard.scss";
import React from "react";
import { findDOMNode } from "react-dom";
import { boundMethod } from "../../../common/utils";
import { Notifications } from "../notifications";
import { copyToClipboard } from "../../utils/copyToClipboard";
import logger from "../../../main/logger";
import { cssNames } from "../../utils";
export interface CopyToClipboardProps {
resetSelection?: boolean;
showNotification?: boolean;
cssSelectorLimit?: string; // allows to copy partial content with css-selector in children-element context
getNotificationMessage?(copiedText: string): React.ReactNode;
}
export const defaultProps: Partial<CopyToClipboardProps> = {
getNotificationMessage(copiedText: string) {
return <p>Copied to clipboard: <em>{copiedText}</em></p>;
},
};
export class Clipboard extends React.Component<CopyToClipboardProps> {
static displayName = "Clipboard";
static defaultProps = defaultProps as object;
get rootElem(): HTMLElement {
// eslint-disable-next-line react/no-find-dom-node
return findDOMNode(this) as HTMLElement;
}
get rootReactElem(): React.ReactElement<React.HTMLProps<any>> {
return React.Children.only(this.props.children) as React.ReactElement;
}
@boundMethod
onClick(evt: React.MouseEvent) {
if (this.rootReactElem.props.onClick) {
this.rootReactElem.props.onClick(evt); // pass event to children-root-element if any
}
const { showNotification, resetSelection, getNotificationMessage, cssSelectorLimit } = this.props;
const contentElem = this.rootElem.querySelector<any>(cssSelectorLimit) || this.rootElem;
if (contentElem) {
const { copiedText, copied } = copyToClipboard(contentElem, { resetSelection });
if (copied && showNotification) {
Notifications.ok(getNotificationMessage(copiedText));
}
}
}
render() {
try {
const rootElem = this.rootReactElem;
return React.cloneElement(rootElem, {
className: cssNames(Clipboard.displayName, rootElem.props.className),
onClick: this.onClick,
});
} catch (err) {
logger.error(`Invalid usage components/CopyToClick usage. Children must contain root html element.`, { err: String(err) });
return this.rootReactElem;
}
}
}
@@ -1,22 +0,0 @@
/**
* 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.
*/
export * from "./clipboard";
@@ -153,7 +153,7 @@ export class ClusterStatus extends React.Component<Props> {
return (
<div className={cssNames(styles.status, "flex column box center align-center justify-center", this.props.className)}>
<div className="flex items-center column gaps">
<h2>{this.entity.getName()}</h2>
<h2>{this.entity?.getName() ?? this.cluster.name}</h2>
{this.renderStatusIcon()}
{this.renderAuthenticationOutput()}
{this.renderReconnectionHelp()}
@@ -65,7 +65,11 @@ export class ClusterIconSetting extends React.Component<Props> {
}
clearIcon() {
this.props.cluster.preferences.icon = undefined;
/**
* NOTE: this needs to be `null` rather than `undefined` so that we can
* tell the difference between it not being there and being cleared.
*/
this.props.cluster.preferences.icon = null;
}
@boundMethod
@@ -24,10 +24,10 @@ import "./logs-dialog.scss";
import React from "react";
import { Dialog, DialogProps } from "../dialog";
import { Wizard, WizardStep } from "../wizard";
import { copyToClipboard } from "../../utils";
import { Notifications } from "../notifications";
import { Button } from "../button";
import { Icon } from "../icon";
import { clipboard } from "electron";
// todo: make as external BrowserWindow (?)
@@ -40,9 +40,8 @@ export class LogsDialog extends React.Component<Props> {
public logsElem: HTMLElement;
copyToClipboard = () => {
if (copyToClipboard(this.logsElem)) {
Notifications.ok(`Logs copied to clipboard.`);
}
clipboard.writeText(this.props.logs);
Notifications.ok(`Logs copied to clipboard.`);
};
render() {
@@ -25,7 +25,7 @@ import { makeObservable, observable } from "mobx";
import { observer } from "mobx-react";
import yaml from "js-yaml";
import type { ServiceAccount } from "../../../common/k8s-api/endpoints";
import { copyToClipboard, saveFileDialog } from "../../utils";
import { saveFileDialog } from "../../utils";
import { Button } from "../button";
import { Dialog, DialogProps } from "../dialog";
import { Icon } from "../icon";
@@ -33,6 +33,7 @@ import { Notifications } from "../notifications";
import { Wizard, WizardStep } from "../wizard";
import { apiBase } from "../../api";
import { MonacoEditor } from "../monaco-editor";
import { clipboard } from "electron";
interface IKubeconfigDialogData {
title?: React.ReactNode;
@@ -49,7 +50,6 @@ const dialogState = observable.object({
@observer
export class KubeConfigDialog extends React.Component<Props> {
@observable.ref configTextArea: HTMLTextAreaElement; // required for coping config text
@observable config = ""; // parsed kubeconfig in yaml format
constructor(props: Props) {
@@ -89,9 +89,8 @@ export class KubeConfigDialog extends React.Component<Props> {
}
copyToClipboard = () => {
if (this.config && copyToClipboard(this.configTextArea)) {
Notifications.ok("Config copied to clipboard");
}
clipboard.writeText(this.config);
Notifications.ok("Config copied to clipboard");
};
download = () => {
@@ -131,11 +130,6 @@ export class KubeConfigDialog extends React.Component<Props> {
className={styles.editor}
value={yamlConfig}
/>
<textarea
className={styles.configCopy}
readOnly defaultValue={yamlConfig}
ref={e => this.configTextArea = e}
/>
</WizardStep>
</Wizard>
</Dialog>
@@ -57,18 +57,25 @@ describe("<SidebarCluster/>", () => {
});
it("renders cluster avatar and name", () => {
const { getByText } = render(<SidebarCluster clusterEntity={clusterEntity}/>);
const { getByText, getAllByText } = render(<SidebarCluster clusterEntity={clusterEntity}/>);
expect(getByText("tc")).toBeInTheDocument();
expect(getByText("test-cluster")).toBeInTheDocument();
const v = getAllByText("test-cluster");
expect(v.length).toBeGreaterThan(0);
for (const e of v) {
expect(e).toBeInTheDocument();
}
});
it("renders cluster menu", async () => {
it("renders cluster menu", () => {
const { getByTestId, getByText } = render(<SidebarCluster clusterEntity={clusterEntity}/>);
const link = getByTestId("sidebar-cluster-dropdown");
fireEvent.click(link);
expect(await getByText("Add to Hotbar")).toBeInTheDocument();
expect(getByText("Add to Hotbar")).toBeInTheDocument();
});
});
@@ -0,0 +1,115 @@
/**
* 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, fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { TopBar } from "../topbar";
import { TopBarRegistry } from "../../../../extensions/registries";
import { IpcMainWindowEvents } from "../../../../main/window-manager";
import { broadcastMessage } from "../../../../common/ipc";
import * as vars from "../../../../common/vars";
const mockConfig = vars as { isWindows: boolean, isLinux: boolean };
jest.mock("../../../../common/ipc");
jest.mock("../../../../common/vars", () => {
return {
__esModule: true,
isWindows: null,
isLinux: null,
};
});
const mockMinimize = jest.fn();
const mockMaximize = jest.fn();
const mockUnmaximize = jest.fn();
const mockClose = jest.fn();
jest.mock("@electron/remote", () => {
return {
getCurrentWindow: () => ({
minimize: () => mockMinimize(),
maximize: () => mockMaximize(),
unmaximize: () => mockUnmaximize(),
close: () => mockClose(),
isMaximized: () => false,
}),
};
});
describe("<Tobar/> in Windows and Linux", () => {
beforeEach(() => {
TopBarRegistry.createInstance();
});
afterEach(() => {
TopBarRegistry.resetInstance();
});
it("shows window controls on Windows", () => {
mockConfig.isWindows = true;
mockConfig.isLinux = false;
const { getByTestId } = render(<TopBar/>);
expect(getByTestId("window-menu")).toBeInTheDocument();
expect(getByTestId("window-minimize")).toBeInTheDocument();
expect(getByTestId("window-maximize")).toBeInTheDocument();
expect(getByTestId("window-close")).toBeInTheDocument();
});
it("shows window controls on Linux", () => {
mockConfig.isWindows = false;
mockConfig.isLinux = true;
const { getByTestId } = render(<TopBar/>);
expect(getByTestId("window-menu")).toBeInTheDocument();
expect(getByTestId("window-minimize")).toBeInTheDocument();
expect(getByTestId("window-maximize")).toBeInTheDocument();
expect(getByTestId("window-close")).toBeInTheDocument();
});
it("triggers ipc events on click", () => {
mockConfig.isWindows = true;
const { getByTestId } = render(<TopBar/>);
const menu = getByTestId("window-menu");
const minimize = getByTestId("window-minimize");
const maximize = getByTestId("window-maximize");
const close = getByTestId("window-close");
fireEvent.click(menu);
expect(broadcastMessage).toHaveBeenCalledWith(IpcMainWindowEvents.OPEN_CONTEXT_MENU);
fireEvent.click(minimize);
expect(mockMinimize).toHaveBeenCalled();
fireEvent.click(maximize);
expect(mockMaximize).toHaveBeenCalled();
fireEvent.click(close);
expect(mockClose).toHaveBeenCalled();
});
});
@@ -25,6 +25,12 @@ import "@testing-library/jest-dom/extend-expect";
import { TopBar } from "../topbar";
import { TopBarRegistry } from "../../../../extensions/registries";
jest.mock("../../../../common/vars", () => {
return {
isMac: true,
};
});
jest.mock(
"electron",
() => ({
@@ -65,6 +71,7 @@ jest.mock("@electron/remote", () => {
}];
},
},
getCurrentWindow: () => jest.fn(),
};
});
@@ -134,4 +141,13 @@ describe("<TopBar/>", () => {
expect(await getByTestId(testId)).toHaveTextContent(text);
});
it("doesn't show windows title buttons", () => {
const { queryByTestId } = render(<TopBar/>);
expect(queryByTestId("window-menu")).not.toBeInTheDocument();
expect(queryByTestId("window-minimize")).not.toBeInTheDocument();
expect(queryByTestId("window-maximize")).not.toBeInTheDocument();
expect(queryByTestId("window-close")).not.toBeInTheDocument();
});
});
@@ -26,6 +26,7 @@ import { observer } from "mobx-react";
import { cssNames, IClassName } from "../../utils";
import { navigation } from "../../navigation";
import { Icon } from "../icon";
import { catalogURL } from "../../../common/routes";
export interface SettingLayoutProps extends React.DOMAttributes<any> {
className?: IClassName;
@@ -39,7 +40,13 @@ export interface SettingLayoutProps extends React.DOMAttributes<any> {
const defaultProps: Partial<SettingLayoutProps> = {
provideBackButtonNavigation: true,
contentGaps: true,
back: () => navigation.goBack(),
back: () => {
if (navigation.length <= 1) {
navigation.push(catalogURL());
} else {
navigation.goBack();
}
},
};
/**
@@ -61,4 +61,51 @@
.avatar {
font-weight: 500;
margin-right: 1.25rem;
}
}
.loadingAvatar {
position: relative;
pointer-events: none;
&:after {
content: "";
position: absolute;
left: 0;
top: 0;
width: 0;
height: 100%;
background: transparentize(white, .85);
animation: waiting 1.5s infinite linear;
}
}
.loadingClusterName {
position: relative;
pointer-events: none;
width: 80%;
height: 16px;
&:after {
content: "";
position: absolute;
left: 0;
top: 0;
width: 0;
height: 100%;
background: transparentize(white, .85);
animation: waiting 1.5s infinite linear;
}
}
@keyframes waiting {
0% {
left: 0;
width: 0;
}
50% {
left: 25%;
width: 75%;
}
75% {
left: 100%;
width: 0;
}
}
@@ -31,6 +31,7 @@ import { Icon } from "../icon";
import { navigate } from "../../navigation";
import { Menu, MenuItem } from "../menu";
import { ConfirmDialog } from "../confirm-dialog";
import { Tooltip } from "../tooltip";
const contextMenu: CatalogEntityContextMenuContext = observable({
menuItems: [],
@@ -60,11 +61,25 @@ function onMenuItemClick(menuItem: CatalogEntityContextMenu) {
}
}
function renderLoadingSidebarCluster() {
return (
<div className={styles.SidebarCluster}>
<Avatar
title="??"
background="var(--halfGray)"
size={40}
className={styles.loadingAvatar}
/>
<div className={styles.loadingClusterName} />
</div>
);
}
export function SidebarCluster({ clusterEntity }: { clusterEntity: CatalogEntity }) {
const [opened, setOpened] = useState(false);
if (!clusterEntity) {
return null;
return renderLoadingSidebarCluster();
}
const onMenuOpen = () => {
@@ -95,6 +110,7 @@ export function SidebarCluster({ clusterEntity }: { clusterEntity: CatalogEntity
const { metadata, spec } = clusterEntity;
const id = `cluster-${metadata.uid}`;
const tooltipId = `tooltip-${id}`;
return (
<div
@@ -112,9 +128,12 @@ export function SidebarCluster({ clusterEntity }: { clusterEntity: CatalogEntity
src={spec.icon?.src}
className={styles.avatar}
/>
<div className={styles.clusterName}>
<div className={styles.clusterName} id={tooltipId}>
{metadata.name}
</div>
<Tooltip targetId={tooltipId}>
{metadata.name}
</Tooltip>
<Icon material="arrow_drop_down" className={styles.dropdown}/>
<Menu
usePortal
@@ -20,22 +20,44 @@
*/
.topBar {
display: grid;
grid-template-columns: [title] 1fr [controls] auto;
grid-template-rows: var(--main-layout-header);
grid-template-areas: "title controls";
display: flex;
background-color: var(--layoutBackground);
z-index: 2;
width: 100%;
grid-area: topbar;
height: var(--main-layout-header);
justify-content: space-between;
/* Use topbar as draggable region */
-webkit-user-select: none;
-webkit-app-region: drag;
}
:global(.is-mac) .topBar {
padding-left: var(--hotbar-width);
}
.winMenu {
width: var(--hotbar-width);
> div {
@apply flex items-center justify-center;
width: 40px;
height: 40px;
&:hover {
background-color: var(--borderFaintColor);
}
&:active {
background-color: var(--borderColor);
}
}
}
.tools {
@apply flex items-center;
-webkit-app-region: no-drag;
}
.controls {
@@ -44,4 +66,63 @@
align-items: center;
display: flex;
height: 100%;
-webkit-app-region: no-drag;
}
.windowButtons {
display: flex;
margin-left: 1.5rem;
margin-right: -1.5rem;
> div {
@apply flex items-center justify-center;
width: 40px;
height: 40px;
svg {
width: 12px;
height: 12px;
}
}
&.linuxButtons {
> div {
width: 16px;
height: 16px;
border-radius: 50%;
margin-right: 1.1rem;
color: var(--textColorAccent);
svg {
width: 8px;
height: 8px;
}
}
.close {
color: white;
background-color: #e63e02; /* Standard close button bg color on ubuntu */
}
.close:hover {
background-color: #ff5a23;
}
}
}
.minimize, .maximize {
&:hover {
background-color: var(--borderFaintColor);
}
&:active {
background-color: var(--borderColor);
}
}
.close {
&:hover {
color: white;
background-color: #ef4b4e;
}
}
+50 -6
View File
@@ -20,16 +20,19 @@
*/
import styles from "./topbar.module.css";
import React, { useEffect } from "react";
import React, { useEffect, useMemo, useRef } from "react";
import { observer } from "mobx-react";
import { TopBarRegistry } from "../../../extensions/registries";
import { Icon } from "../icon";
import { webContents, getCurrentWindow } from "@electron/remote";
import { observable } from "mobx";
import { ipcRendererOn } from "../../../common/ipc";
import { broadcastMessage, ipcRendererOn } from "../../../common/ipc";
import { watchHistoryState } from "../../remote-helpers/history-updater";
import { isActiveRoute, navigate } from "../../navigation";
import { catalogRoute, catalogURL } from "../../../common/routes";
import { IpcMainWindowEvents } from "../../../main/window-manager";
import { isLinux, isWindows } from "../../../common/vars";
import { cssNames } from "../../utils";
interface Props extends React.HTMLAttributes<any> {
}
@@ -46,6 +49,9 @@ ipcRendererOn("history:can-go-forward", (event, state: boolean) => {
});
export const TopBar = observer(({ children, ...rest }: Props) => {
const elem = useRef<HTMLDivElement>();
const window = useMemo(() => getCurrentWindow(), []);
const renderRegisteredItems = () => {
const items = TopBarRegistry.getInstance().getItems();
@@ -70,6 +76,10 @@ export const TopBar = observer(({ children, ...rest }: Props) => {
);
};
const openContextMenu = () => {
broadcastMessage(IpcMainWindowEvents.OPEN_CONTEXT_MENU);
};
const goHome = () => {
navigate(catalogURL());
};
@@ -82,9 +92,20 @@ export const TopBar = observer(({ children, ...rest }: Props) => {
webContents.getAllWebContents().find((webContent) => webContent.getType() === "window")?.goForward();
};
const windowSizeToggle = () => {
const window = getCurrentWindow();
const windowSizeToggle = (evt: React.MouseEvent) => {
if (elem.current != evt.target) {
// Skip clicking on child elements
return;
}
toggleMaximize();
};
const minimizeWindow = () => {
window.minimize();
};
const toggleMaximize = () => {
if (window.isMaximized()) {
window.unmaximize();
} else {
@@ -92,6 +113,10 @@ export const TopBar = observer(({ children, ...rest }: Props) => {
}
};
const closeWindow = () => {
window.close();
};
useEffect(() => {
const disposer = watchHistoryState();
@@ -99,8 +124,15 @@ export const TopBar = observer(({ children, ...rest }: Props) => {
}, []);
return (
<div className={styles.topBar} {...rest}>
<div className={styles.tools} onDoubleClick={windowSizeToggle}>
<div className={styles.topBar} onDoubleClick={windowSizeToggle} ref={elem} {...rest}>
<div className={styles.tools}>
{(isWindows || isLinux) && (
<div className={styles.winMenu}>
<div onClick={openContextMenu} data-testid="window-menu">
<svg width="12" height="12" viewBox="0 0 12 12" shapeRendering="crispEdges"><path fill="currentColor" d="M0,8.5h12v1H0V8.5z"/><path fill="currentColor" d="M0,5.5h12v1H0V5.5z"/><path fill="currentColor" d="M0,2.5h12v1H0V2.5z"/></svg>
</div>
</div>
)}
<Icon
data-testid="home-button"
material="home"
@@ -126,6 +158,18 @@ export const TopBar = observer(({ children, ...rest }: Props) => {
<div className={styles.controls}>
{renderRegisteredItems()}
{children}
{(isWindows || isLinux) && (
<div className={cssNames(styles.windowButtons, { [styles.linuxButtons]: isLinux })}>
<div className={styles.minimize} data-testid="window-minimize" onClick={minimizeWindow}>
<svg shapeRendering="crispEdges" viewBox="0 0 12 12"><rect fill="currentColor" width="10" height="1" x="1" y="9"></rect></svg></div>
<div className={styles.maximize} data-testid="window-maximize" onClick={toggleMaximize}>
<svg shapeRendering="crispEdges" viewBox="0 0 12 12"><rect width="9" height="9" x="1.5" y="1.5" fill="none" stroke="currentColor"></rect></svg>
</div>
<div className={styles.close} data-testid="window-close" onClick={closeWindow}>
<svg shapeRendering="crispEdges" viewBox="0 0 12 12"><polygon fill="currentColor" points="11 1.576 6.583 6 11 10.424 10.424 11 6 6.583 1.576 11 1 10.424 5.417 6 1 1.576 1.576 1 6 5.417 10.424 1"></polygon></svg>
</div>
</div>
)}
</div>
</div>
);
@@ -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,
-52
View File
@@ -1,52 +0,0 @@
/**
* 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.
*/
// Helper for selecting element's text content and copy in clipboard
export function copyToClipboard(elem: HTMLElement, { resetSelection = true } = {}) {
let clearSelection: () => void;
if (isSelectable(elem)) {
elem.select();
clearSelection = () => elem.setSelectionRange(0, 0);
} else {
const selection = window.getSelection();
selection.selectAllChildren(elem);
clearSelection = () => selection.removeAllRanges();
}
const selectedText = document.getSelection().toString();
const isCopied = document.execCommand("copy");
if (resetSelection) {
clearSelection();
}
return {
copied: isCopied,
copiedText: selectedText,
clearSelection,
};
}
function isSelectable(elem: HTMLElement): elem is HTMLInputElement {
return !!(elem as HTMLInputElement).select;
}
-1
View File
@@ -24,7 +24,6 @@
export * from "../../common/utils";
export * from "../../common/event-emitter";
export * from "./copyToClipboard";
export * from "./createStorage";
export * from "./cssNames";
export * from "./cssVar";