Replace TopBarRegistry with reactive solution

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>
Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne SavolainenandMikko Aspiala committed 2021-12-31 09:32:19 +02:00
1 parent ed7d2889e2
commit 6ca58570b0
12 files changed
+124 -79

No files matched your search

@@ -0,0 +1,37 @@
/**
* 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 { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
import { computed } from "mobx";
import rendererExtensionsInjectable from "../../../../../extensions/renderer-extensions.injectable";
const topBarItemsInjectable = getInjectable({
instantiate: (di) => {
const extensions = di.inject(rendererExtensionsInjectable);
return computed(() =>
extensions.get().flatMap((extension) => extension.topBarItems),
);
},
lifecycle: lifecycleEnum.singleton,
});
export default topBarItemsInjectable;
@@ -0,0 +1,27 @@
/**
* 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.
*/
interface TopBarComponents {
Item: React.ComponentType;
}
export interface TopBarRegistration {
components: TopBarComponents;
}
@@ -0,0 +1,121 @@
/**
* 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 { fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { TopBar } from "./top-bar";
import { IpcMainWindowEvents } from "../../../../main/window-manager";
import { broadcastMessage } from "../../../../common/ipc";
import * as vars from "../../../../common/vars";
import { getDiForUnitTesting } from "../../getDiForUnitTesting";
import { DiRender, renderFor } from "../../test-utils/renderFor";
const mockConfig = vars as { isWindows: boolean; isLinux: boolean };
jest.mock("../../../../common/ipc");
jest.mock("../../../../common/vars", () => {
const SemVer = require("semver").SemVer;
const versionStub = new SemVer("1.0.0");
return {
__esModule: true,
isWindows: null,
isLinux: null,
appSemVer: versionStub,
};
});
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("<TopBar/> in Windows and Linux", () => {
let render: DiRender;
beforeEach(() => {
const di = getDiForUnitTesting();
render = renderFor(di);
});
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();
});
});
@@ -0,0 +1,128 @@
/**
* 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.
*/
.topBar {
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 {
align-self: flex-end;
padding-right: 1.5rem;
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;
}
}
@@ -0,0 +1,163 @@
/**
* 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 { fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { TopBar } from "./top-bar";
import { getDiForUnitTesting } from "../../getDiForUnitTesting";
import type { ConfigurableDependencyInjectionContainer } from "@ogre-tools/injectable";
import { DiRender, renderFor } from "../../test-utils/renderFor";
import topBarItemsInjectable from "./top-bar-items/top-bar-items.injectable";
import { computed } from "mobx";
jest.mock("../../../../common/vars", () => {
const SemVer = require("semver").SemVer;
const versionStub = new SemVer("1.0.0");
return {
isMac: true,
appSemVer: versionStub,
};
});
jest.mock(
"electron",
() => ({
ipcRenderer: {
on: jest.fn(
(channel: string, listener: (event: any, ...args: any[]) => void) => {
if (channel === "history:can-go-back") {
listener({}, true);
}
if (channel === "history:can-go-forward") {
listener({}, true);
}
},
),
},
app: {
getPath: () => "tmp",
},
}),
);
jest.mock("../../+catalog", () => ({
previousActiveTab: jest.fn(),
}));
const goBack = jest.fn();
const goForward = jest.fn();
jest.mock("@electron/remote", () => {
return {
webContents: {
getAllWebContents: () => {
return [{
getType: () => "window",
goBack,
goForward,
}];
},
},
getCurrentWindow: () => jest.fn(),
};
});
describe("<TopBar/>", () => {
let di: ConfigurableDependencyInjectionContainer;
let render: DiRender;
beforeEach(() => {
di = getDiForUnitTesting();
render = renderFor(di);
});
it("renders w/o errors", () => {
const { container } = render(<TopBar/>);
expect(container).toBeInstanceOf(HTMLElement);
});
it("renders home button", async () => {
const { getByTestId } = render(<TopBar/>);
expect(await getByTestId("home-button")).toBeInTheDocument();
});
it("renders history arrows", async () => {
const { getByTestId } = render(<TopBar/>);
expect(await getByTestId("history-back")).toBeInTheDocument();
expect(await getByTestId("history-forward")).toBeInTheDocument();
});
it("enables arrow by ipc event", async () => {
const { getByTestId } = render(<TopBar/>);
expect(await getByTestId("history-back")).not.toHaveClass("disabled");
expect(await getByTestId("history-forward")).not.toHaveClass("disabled");
});
it("triggers browser history back and forward", async () => {
const { getByTestId } = render(<TopBar/>);
const prevButton = await getByTestId("history-back");
const nextButton = await getByTestId("history-forward");
fireEvent.click(prevButton);
expect(goBack).toBeCalled();
fireEvent.click(nextButton);
expect(goForward).toBeCalled();
});
it("renders items", async () => {
const testId = "testId";
const text = "an item";
di.override(topBarItemsInjectable, () => computed(() => [
{
components: {
Item: () => <span data-testid={testId}>{text}</span>,
},
},
]));
const { getByTestId } = render(<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();
});
});
@@ -0,0 +1,184 @@
/**
* 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 styles from "./top-bar.module.scss";
import React, { useEffect, useMemo, useRef } from "react";
import { observer } from "mobx-react";
import type { IComputedValue } from "mobx";
import { Icon } from "../../icon";
import { webContents, getCurrentWindow } from "@electron/remote";
import { observable } from "mobx";
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";
import topBarItemsInjectable from "./top-bar-items/top-bar-items.injectable";
import { withInjectables } from "@ogre-tools/injectable-react";
import type { TopBarRegistration } from "./top-bar-registration";
interface Props extends React.HTMLAttributes<any> {}
interface Dependencies {
items: IComputedValue<TopBarRegistration[]>;
}
const prevEnabled = observable.box(false);
const nextEnabled = observable.box(false);
ipcRendererOn("history:can-go-back", (event, state: boolean) => {
prevEnabled.set(state);
});
ipcRendererOn("history:can-go-forward", (event, state: boolean) => {
nextEnabled.set(state);
});
const NonInjectedTopBar: React.FC<Props & Dependencies> = (({ items, children, ...rest }) => {
const elem = useRef<HTMLDivElement>();
const window = useMemo(() => getCurrentWindow(), []);
const openContextMenu = () => {
broadcastMessage(IpcMainWindowEvents.OPEN_CONTEXT_MENU);
};
const goHome = () => {
navigate(catalogURL());
};
const goBack = () => {
webContents.getAllWebContents().find((webContent) => webContent.getType() === "window")?.goBack();
};
const goForward = () => {
webContents.getAllWebContents().find((webContent) => webContent.getType() === "window")?.goForward();
};
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 {
window.maximize();
}
};
const closeWindow = () => {
window.close();
};
useEffect(() => {
const disposer = watchHistoryState();
return () => disposer();
}, []);
return (
<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"
className="ml-4"
onClick={goHome}
disabled={isActiveRoute(catalogRoute)}
/>
<Icon
data-testid="history-back"
material="arrow_back"
className="ml-5"
onClick={goBack}
disabled={!prevEnabled.get()}
/>
<Icon
data-testid="history-forward"
material="arrow_forward"
className="ml-5"
onClick={goForward}
disabled={!nextEnabled.get()}
/>
</div>
<div className={styles.controls}>
{renderRegisteredItems(items.get())}
{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>
);
});
const renderRegisteredItems = (items: TopBarRegistration[]) => (
<div>
{items.map((registration, index) => {
if (!registration?.components?.Item) {
return null;
}
return (
<div key={index}>
<registration.components.Item />
</div>
);
})}
</div>
);
export const TopBar = withInjectables(observer(NonInjectedTopBar), {
getProps: (di, props) => ({
items: di.inject(topBarItemsInjectable),
...props,
}),
});