|
| 1 | +import { Hidable, Renderable } from 'util/renderable'; |
| 2 | +import { AlertType } from './types'; |
| 3 | + |
| 4 | +export abstract class AlertBase extends Hidable implements Renderable<HTMLDivElement> { |
| 5 | + /** |
| 6 | + * Create an instance of AlertBase. |
| 7 | + * This class serves as a base for alert components. |
| 8 | + * It implements the Renderable interface, which requires a render method. |
| 9 | + * The render method should be implemented by subclasses to provide specific rendering logic. |
| 10 | + * @implements {Renderable<HTMLDivElement>} |
| 11 | + * @param {string} message - The message to be displayed in the alert. |
| 12 | + * @param {AlertType} type - The type of alert, which determines its styling and behavior. |
| 13 | + * @see Renderable |
| 14 | + * @see Hidable |
| 15 | + * @see AlertType |
| 16 | + * @example |
| 17 | + * const alert = new AlertBase('This is an alert message', AlertType.INFO); |
| 18 | + * document.body.appendChild(alert.render()); |
| 19 | + */ |
| 20 | + constructor(private readonly message: string, private readonly type: AlertType, private readonly transparent: boolean = false) { |
| 21 | + super(); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Render the alert as an HTMLDivElement. |
| 26 | + * @returns {HTMLDivElement} The rendered HTML element representing the alert. |
| 27 | + */ |
| 28 | + render(): HTMLDivElement { |
| 29 | + if(this.element) throw new Error('AlertBase.render() should not be called multiple times without resetting the element.'); |
| 30 | + const alertDiv = document.createElement('div'); |
| 31 | + alertDiv.classList.add('alert', `alert-${this.type}`); |
| 32 | + if(this.transparent) { |
| 33 | + alertDiv.classList.add('alert-no-bg'); |
| 34 | + } |
| 35 | + for(const item of this.message.split('\n')) { |
| 36 | + const pDiv = document.createElement('p'); |
| 37 | + pDiv.textContent = item; |
| 38 | + alertDiv.appendChild(pDiv); |
| 39 | + } |
| 40 | + this.element = alertDiv; |
| 41 | + return alertDiv; |
| 42 | + } |
| 43 | +} |
0 commit comments