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,6 @@
{
"extends": "@k8slens/eslint-config/eslint",
"parserOptions": {
"project": "./tsconfig.json"
}
}
@@ -0,0 +1 @@
"@k8slens/eslint-config/prettier"
@@ -0,0 +1,4 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
@@ -0,0 +1,19 @@
# @k8slens/notifications
This package contains stuff related to creating Lens-applications.
# Usage
```bash
$ npm install @k8slens/notifications
```
```typescript
export type { notificationsName, notificationsProps } from "@k8slens/button";
export type { notifications } from "@k8slens/button";
export { defaultEnterDurationFornotificationsdInjectable } from "@k8slens/button";
export { defaultLeaveDurationFornotificationsdInjectable } from "@k8slens/button";
export { requestAnimationFrameInjectable } from "@k8slens/button";
```
## Extendability
@@ -0,0 +1,25 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
export type {
NotificationId,
NotificationMessage,
NotificationStatus,
CreateNotificationOptions,
Notification,
NotificationsStore,
} from "./src/notifications.store";
export type { ShowNotification } from "./src/notifications";
export { Notifications } from "./src/notifications";
export { notificationsClusterFrameChildComponentInjectable } from "./src/notifications-cluster-frame-child-component.injectable";
export { notificationsRootFrameChildComponentInjectable } from "./src/notifications-root-frame-child-component.injectable";
export { notificationsStoreInjectable } from "./src/notifications-store.injectable";
export type { ShowCheckedErrorNotification } from "./src/show-checked-error.injectable";
export { showCheckedErrorNotificationInjectable } from "./src/show-checked-error.injectable";
export { showErrorNotificationInjectable } from "./src/show-error-notification.injectable";
export { showInfoNotificationInjectable } from "./src/show-info-notification.injectable";
export { showShortInfoNotificationInjectable } from "./src/show-short-info.injectable";
export { showSuccessNotificationInjectable } from "./src/show-success-notification.injectable";
export { notificationsFeature } from "./src/feature";
@@ -0,0 +1,3 @@
const { configForReact } = require("@k8slens/jest").monorepoPackageConfig(__dirname);
module.exports = configForReact;
@@ -0,0 +1,66 @@
{
"name": "@k8slens/notifications",
"private": false,
"version": "1.0.0",
"description": "Highly extendable notifications in the Lens.",
"type": "commonjs",
"files": [
"dist"
],
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},
"repository": {
"type": "git",
"url": "git+https://github.com/lensapp/lens.git"
},
"main": "dist/index.js",
"exports": {
".": "./dist/index.js",
"./styles": "./dist/index.css"
},
"types": "dist/index.d.ts",
"author": {
"name": "OpenLens Authors",
"email": "info@k8slens.dev"
},
"license": "MIT",
"homepage": "https://github.com/lensapp/lens",
"scripts": {
"build": "lens-webpack-build",
"lint": "lens-lint",
"lint:fix": "lens-lint --fix"
},
"peerDependencies": {
"@k8slens/react-application": "^1.0.0-alpha.5",
"@k8slens/animate": "^1.0.0-alpha.0",
"@k8slens/application": "^6.5.0",
"@k8slens/event-emitter": "^1.0.0",
"@k8slens/feature-core": "^6.5.0-alpha.0",
"@k8slens/json-api": "^1.0.0-alpha.3",
"@k8slens/icon": "^1.0.0-alpha.7",
"@k8slens/run-many": "^1.0.0",
"@k8slens/logger": "^1.0.0",
"@k8slens/tooltip": "^1.0.0",
"@k8slens/utilities": "^1.0.0-alpha.1",
"@ogre-tools/injectable-react": "^17.2.0",
"@ogre-tools/injectable": "^17.2.0",
"@ogre-tools/fp": "^17.2.0",
"@ogre-tools/injectable-extension-for-auto-registration": "^17.2.0",
"@ogre-tools/injectable-extension-for-mobx": "^17.2.0",
"auto-bind": "^4.0.0",
"lodash": "^4.17.21",
"mobx": "^6.8.0",
"mobx-react": "^7.6.0",
"react-router-dom": "^5.3.4",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"winston": "^3.8.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"@k8slens/eslint-config": "^6.5.0",
"@k8slens/webpack": "^6.5.0"
}
}
@@ -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,
});
},
});
@@ -0,0 +1,28 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
const path = require("path");
module.exports = {
content: [path.join(__dirname, "src/**/*.tsx")],
darkMode: "class",
theme: {
fontFamily: {
sans: ["Roboto", "Helvetica", "Arial", "sans-serif"],
},
extend: {
colors: {
textAccent: "var(--textColorAccent)",
textPrimary: "var(--textColorPrimary)",
textTertiary: "var(--textColorTertiary)",
textDimmed: "var(--textColorDimmed)",
},
},
},
variants: {
extend: {},
},
plugins: [],
};
@@ -0,0 +1,4 @@
{
"extends": "@k8slens/typescript/config/base.json",
"include": ["**/*.ts", "**/*.tsx"],
}
@@ -0,0 +1 @@
module.exports = require("@k8slens/webpack").configForReact;