chore: extract @k8slens/notifications

Signed-off-by: Gabriel <gaccettola@mirantis.com>
This commit is contained in:
Gabriel authored and Gabriel Accettola committed 2023-06-01 23:38:14 +02:00
1 parent f602ce8f46
commit 8b69c12ed4
102 files changed
+399 -192

No files matched your search

@@ -0,0 +1,14 @@
import { getFeature } from "@k8slens/feature-core";
import { autoRegister } from "@ogre-tools/injectable-extension-for-auto-registration";
export const notificationsFeature = getFeature({
id: "notifications-feature",
register: (di) => {
autoRegister({
di,
targetModule: module,
getRequireContexts: () => [require.context("./", true, /\.injectable\.(ts|tsx)$/)],
});
},
});
@@ -0,0 +1,20 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { computed } from "mobx";
import { Notifications } from "./notifications";
import { clusterFrameChildComponentInjectionToken } from "@k8slens/react-application";
export const notificationsClusterFrameChildComponentInjectable = getInjectable({
id: "notifications-cluster-frame-child-component",
instantiate: () => ({
id: "notifications",
shouldRender: computed(() => true),
Component: Notifications,
}),
injectionToken: clusterFrameChildComponentInjectionToken,
});
@@ -0,0 +1,20 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { rootFrameChildComponentInjectionToken } from "@k8slens/react-application";
import { computed } from "mobx";
import { Notifications } from "./notifications";
export const notificationsRootFrameChildComponentInjectable = getInjectable({
id: "notifications-root-frame-child-component",
instantiate: () => ({
id: "notifications",
shouldRender: computed(() => true),
Component: Notifications,
}),
injectionToken: rootFrameChildComponentInjectionToken,
});
@@ -0,0 +1,11 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { NotificationsStore } from "./notifications.store";
export const notificationsStoreInjectable = getInjectable({
id: "notifications-store",
instantiate: () => new NotificationsStore(),
});
@@ -0,0 +1,64 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
$color-white: rgb(255,255,255);
@mixin hidden-scrollbar {
overflow: auto;
// Chrome, Safari
&::-webkit-scrollbar {
width: 0;
height: 0;
background: transparent;
}
}
.Notifications {
@include hidden-scrollbar;
position: absolute;
right: 0;
top: 0;
padding: 8px * 2;
max-height: 100vh;
z-index: 100000;
height: min-content!important;
&:empty {
display: none;
}
.notification {
flex: 0 0;
padding: 8px * 1.5;
border-radius: 3px;
min-width: 350px;
max-width: 35vw;
word-break: break-word;
&:not(:last-child) {
margin-bottom: 8px * 2;
}
> .message {
white-space: pre-line;
padding-left: 8px;
padding-right: 8px * 2;
align-self: center;
a {
color: inherit;
}
}
@each $status, $color in (ok: var(--colorOk), error: var(--colorError), info: var(--colorInfo)) {
&.#{$status} {
background: $color;
color: $color-white;
box-shadow: 0 0 20px var(--boxShadow);
}
}
}
}
@@ -0,0 +1,101 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type React from "react";
import { action, observable, makeObservable } from "mobx";
import uniqueId from "lodash/uniqueId";
import type { JsonApiErrorParsed } from "@k8slens/json-api";
import type { SetRequired } from "type-fest";
import autoBind from "auto-bind";
export type NotificationId = string | number;
export type NotificationMessage = string | React.ReactElement | React.ReactElement[] | JsonApiErrorParsed | Error;
export enum NotificationStatus {
OK = "ok",
ERROR = "error",
INFO = "info",
}
export interface CreateNotificationOptions {
id?: NotificationId;
timeout?: number;
onClose?(): void;
}
export interface Notification {
id?: NotificationId;
message: NotificationMessage;
status?: NotificationStatus;
timeout?: number; // auto-hiding timeout in milliseconds, 0 = no hide
onClose?(): void; // additional logic on when the notification times out or is closed by the "x"
}
export class NotificationsStore {
public notifications = observable.array<SetRequired<Notification, "id">>([], { deep: false });
protected autoHideTimers = new Map<NotificationId, number>();
constructor() {
makeObservable(this);
autoBind(this);
}
getById(id: NotificationId) {
return this.notifications.find((item) => item.id === id);
}
addAutoHideTimer(id: NotificationId) {
const notification = this.getById(id);
if (!notification) {
return;
}
this.removeAutoHideTimer(id);
if (notification?.timeout) {
const timer = window.setTimeout(() => this.remove(id), notification.timeout);
this.autoHideTimers.set(id, timer);
}
}
removeAutoHideTimer(id: NotificationId) {
if (this.autoHideTimers.has(id)) {
clearTimeout(this.autoHideTimers.get(id));
this.autoHideTimers.delete(id);
}
}
@action
add(rawNotification: Notification): () => void {
const notification = {
id: uniqueId("notification_"),
...rawNotification,
};
const id = notification.id;
const index = this.notifications.findIndex((item) => item.id === id);
if (index > -1) {
this.notifications.splice(index, 1, notification); // update existing with same id
} else {
this.notifications.push(notification); // add new
}
this.addAutoHideTimer(id);
return () => this.remove(id);
}
@action
remove(id: NotificationId) {
this.removeAutoHideTimer(id);
const notification = this.getById(id);
if (notification) {
this.notifications.remove(notification);
}
}
}
@@ -0,0 +1,111 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import "./notifications.scss";
import React from "react";
import { reaction } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import { JsonApiErrorParsed } from "@k8slens/json-api";
import type { Disposer } from "@k8slens/utilities";
import { cssNames, prevDefault } from "@k8slens/utilities";
import type {
CreateNotificationOptions,
Notification,
NotificationMessage,
NotificationsStore,
} from "./notifications.store";
import { Animate } from "@k8slens/animate";
import { Icon } from "@k8slens/icon";
import { withInjectables } from "@ogre-tools/injectable-react";
import { notificationsStoreInjectable } from "./notifications-store.injectable";
export type ShowNotification = (message: NotificationMessage, opts?: CreateNotificationOptions) => Disposer;
interface Dependencies {
store: NotificationsStore;
}
@observer
class NonInjectedNotifications extends React.Component<Dependencies> {
public elem: HTMLDivElement | null = null;
componentDidMount() {
disposeOnUnmount(this, [
reaction(
() => this.props.store.notifications.length,
() => {
this.scrollToLastNotification();
},
{ delay: 250 },
),
]);
}
scrollToLastNotification() {
if (!this.elem) {
return;
}
this.elem.scrollTo?.({
top: this.elem.scrollHeight,
behavior: "smooth",
});
}
getMessage(notification: Notification) {
let { message } = notification;
if (message instanceof JsonApiErrorParsed || message instanceof Error) {
message = message.toString();
}
return React.Children.toArray(message);
}
render() {
const { notifications, remove, addAutoHideTimer, removeAutoHideTimer } = this.props.store;
return (
<div className="Notifications flex column align-flex-end" ref={(e) => (this.elem = e)}>
{notifications.map((notification) => {
const { id, status, onClose } = notification;
const msgText = this.getMessage(notification);
return (
<Animate key={id}>
<div
className={cssNames("notification flex", status)}
onMouseLeave={() => addAutoHideTimer(id)}
onMouseEnter={() => removeAutoHideTimer(id)}
>
<div className="box">
<Icon material="info_outline" />
</div>
<div className="message box grow">{msgText}</div>
<div className="box">
<Icon
material="close"
className="close"
data-testid={`close-notification-for-${id}`}
onClick={prevDefault(() => {
remove(id);
onClose?.();
})}
/>
</div>
</div>
</Animate>
);
})}
</div>
);
}
}
export const Notifications = withInjectables<Dependencies>(NonInjectedNotifications, {
getProps: (di) => ({
store: di.inject(notificationsStoreInjectable),
}),
});
@@ -0,0 +1,34 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { JsonApiErrorParsed } from "@k8slens/json-api";
import { loggerInjectionToken } from "@k8slens/logger";
import type { Disposer } from "@k8slens/utilities";
import type { CreateNotificationOptions } from "./notifications.store";
import { showErrorNotificationInjectable } from "./show-error-notification.injectable";
export type ShowCheckedErrorNotification = (
message: unknown,
fallback: string,
opts?: CreateNotificationOptions,
) => Disposer;
export const showCheckedErrorNotificationInjectable = getInjectable({
id: "show-checked-error-notififcation",
instantiate: (di): ShowCheckedErrorNotification => {
const showErrorNotification = di.inject(showErrorNotificationInjectable);
const logger = di.inject(loggerInjectionToken);
return (message, fallback, opts) => {
if (typeof message === "string" || message instanceof Error || message instanceof JsonApiErrorParsed) {
return showErrorNotification(message, opts);
}
logger.warn("[NOTIFICATIONS]: Unknown notification error message, falling back to default", message);
return showErrorNotification(fallback, opts);
};
},
});
@@ -0,0 +1,23 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { ShowNotification } from "./notifications";
import { NotificationStatus } from "./notifications.store";
import { notificationsStoreInjectable } from "./notifications-store.injectable";
export const showErrorNotificationInjectable = getInjectable({
id: "show-error-notification",
instantiate: (di): ShowNotification => {
const notificationsStore = di.inject(notificationsStoreInjectable);
return (message, customOpts = {}) =>
notificationsStore.add({
status: NotificationStatus.ERROR,
message,
...customOpts,
});
},
});
@@ -0,0 +1,23 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { ShowNotification } from "./notifications";
import { NotificationStatus } from "./notifications.store";
import { notificationsStoreInjectable } from "./notifications-store.injectable";
export const showInfoNotificationInjectable = getInjectable({
id: "show-info-notification",
instantiate: (di): ShowNotification => {
const notificationsStore = di.inject(notificationsStoreInjectable);
return (message, customOpts = {}) =>
notificationsStore.add({
status: NotificationStatus.INFO,
message,
...customOpts,
});
},
});
@@ -0,0 +1,22 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { ShowNotification } from "./notifications";
import { showInfoNotificationInjectable } from "./show-info-notification.injectable";
export const showShortInfoNotificationInjectable = getInjectable({
id: "show-short-info-notification",
instantiate: (di): ShowNotification => {
const showInfoNotification = di.inject(showInfoNotificationInjectable);
return (message, customOpts = {}) => {
return showInfoNotification(message, {
timeout: 5_000,
...customOpts,
});
};
},
});
@@ -0,0 +1,24 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { ShowNotification } from "./notifications";
import { NotificationStatus } from "./notifications.store";
import { notificationsStoreInjectable } from "./notifications-store.injectable";
export const showSuccessNotificationInjectable = getInjectable({
id: "show-success-notification",
instantiate: (di): ShowNotification => {
const notificationsStore = di.inject(notificationsStoreInjectable);
return (message, customOpts = {}) =>
notificationsStore.add({
status: NotificationStatus.OK,
timeout: 5000,
message,
...customOpts,
});
},
});