UNPKG

@etsoo/react

Version:

TypeScript ReactJs UI Independent Framework

101 lines (100 loc) 3.07 kB
import React from "react"; import { Notification, NotificationContainer } from "@etsoo/notificationbase"; import { State } from "../states/State"; /** * React notification */ export class NotificationReact extends Notification { } /** * Notifier for React */ export class NotifierReact extends NotificationContainer { // Instance static _instance; /** * Singleton instance */ static get instance() { return NotifierReact._instance; } // Cache static _cache = {}; /** * Update notifier * @param notifier Notifier */ static updateInstance(notifier) { NotifierReact._instance = notifier; } /** * Constructor */ constructor() { super((notification, dismiss) => { // Debug if (this.debug) { console.debug("NotifierReact.updateCallback", notification, dismiss, this.loadingCount); } // Make sure the state update is set if (this.stateUpdate) this.stateUpdate({ notification, dismiss }); }); } /** * State update */ stateUpdate; /** * Create state provider * @param className Style class name * @returns Provider */ createProvider(className, debug) { // Custom creator const creator = (state, update, props) => { // Hold the current state update this.stateUpdate = update; // Aligns collection const aligns = []; for (const align in state) { // Notifications under the align const notifications = state[align]; // UI collections const ui = notifications.map((notification) => { // Id const id = notification.id; // Try cache const cache = NotifierReact._cache[id]; if (cache) return cache; const element = notification.render(props, className ? className + "-item" : className); // Cache the element NotifierReact._cache[id] = element; return element; }); // Add to the collection aligns.push(this.createContainer(Number(align), ui)); } // Debug if (debug) { console.debug("NotifierReact.createProvider", className, state, aligns); } // Generate the component return React.createElement("div", { className }, aligns); }; // Create state const { provider } = State.create((state, _action) => { // Collection update is done with NotificationContainer return { ...state }; }, this.notifications, {}, creator); return provider; } /** * Remove cache * @param id Notification id */ removeCache(id) { delete NotifierReact._cache[id]; } }