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

-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";