All files / src/libs/Modals/CustomModal CustomModal.ts

99.02% Statements 102/103
88.88% Branches 40/45
100% Functions 19/19
99% Lines 99/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 3291x 1x     1x 1x     1x                                     1x 4x 1x   1x   1x   1x   16x 6x 1x                                     16x 16x   16x                       19x 8x 8x   8x 1x     19x               5x 5x 5x 5x       5x             5x   5x 5x   5x             5x 5x 5x       5x           5x             10x 7x 7x 7x     10x             21x 5x 5x 5x     21x             7x 6x 6x     7x               16x                 8x 1x 1x     7x   7x   1x 1x         5x           5x 5x   5x 1x     5x 5x   1x 1x                 3x           3x 3x   1x 1x   2x 2x             5x   5x 5x   5x 5x 5x 5x   5x   5x 1x                       3x   3x             7x   7x             2x   2x               2x   2x             1x   1x             1x   1x             4x   4x      
import { Component } from 'obsidian';
import { ImplementsStatic } from 'src/classes/decorators/ImplementsStatic';
import type { IApp } from 'src/interfaces/IApp';
import type { ILogger, ILogger_ } from 'src/interfaces/ILogger';
import { Inject } from 'src/libs/DependencyInjection/decorators/Inject';
import { Register } from 'src/libs/DependencyInjection/decorators/Register';
import { ForceConstructor } from 'src/libs/DependencyInjection/types/GenericContructor';
import type { ILifecycleManager_ } from 'src/libs/LifecycleManager/interfaces/ILifecycleManager';
import { CallbackError, MissingCallbackError } from './interfaces/Exceptions';
import {
    ICloseCallback,
    ICustomModal,
    ICustomModal_,
    IOpenCallback,
    IShouldOpenCallback,
} from './interfaces/ICustomModal';
import type {
    IDraggableElement,
    IDraggableElement_,
} from './interfaces/IDraggableElement';
 
/**
 * Represents a custom modal, which can be dragged around
 * and don't dim the background.
 */
@Register('ICustomModal_')
@ImplementsStatic<ICustomModal_>()
export class CustomModal implements ICustomModal {
    @Inject('ILogger_', (x: ILogger_) => x.getLogger('CustomModal'), false)
    protected readonly _logger?: ILogger;
    @Inject('IApp')
    protected readonly _IApp!: IApp;
    @Inject('ILifecycleManager_')
    private readonly _ILifecycleManager!: ILifecycleManager_;
    @Inject('IDraggableElement_')
    private readonly _IDraggableElement_!: IDraggableElement_;
 
    private readonly _beforeUnload: () => void = this.close.bind(this);
    @Inject('Obsidian.Component_', (x: ForceConstructor<Component>) => new x())
    protected _component: Component;
    private _draggableElement?: IDraggableElement;
 
    /**
     * Called before the modal is opened.
     * @returns True if the modal can be opened, otherwise false.
     */
    protected _shouldOpen?: IShouldOpenCallback;
 
    /**
     * Called when the modal is opened.
     */
    protected _onOpen?: IOpenCallback;
 
    /**
     * Called when the modal is closed.
     */
    protected _onClose?: ICloseCallback;
 
    private _isDraggable = false;
    private _willDimBackground = true;
 
    private readonly _body: HTMLElement = document.body;
    private __container?: HTMLElement;
    private __bg?: HTMLElement;
    private __closeButton?: HTMLElement;
    private __title?: HTMLElement;
    private __modal?: HTMLElement;
    private __content?: HTMLElement;
 
    /**
     * The container of the modal.
     */
    private get _container(): HTMLElement {
        if (this.__container == null) {
            this.__container = document.createElement('div');
            this.__container.classList.add('modal-container', 'mod-dim');
 
            if (!this._willDimBackground)
                this.__container.style.pointerEvents = 'none';
        }
 
        return this.__container;
    }
 
    /**
     * The background of the modal, if it will be dimmed
     * else an empty fragment.
     */
    private get _bg(): DocumentFragment {
        if (this._willDimBackground && this.__bg == null) {
            this.__bg = document.createElement('div');
            this.__bg.classList.add('modal-bg');
            this.__bg.style.opacity = '0.85';
 
            // Add event listener to close the modal
            // if the background is clicked
            this._component.registerDomEvent(
                this.__bg,
                'click',
                this.close.bind(this),
            );
        }
 
        const fragment = new DocumentFragment();
 
        if (this._willDimBackground && this.__bg != null)
            fragment.appendChild(this.__bg);
 
        return fragment;
    }
 
    /**
     * The close button of the modal.
     */
    private get _closeButton(): HTMLElement {
        if (this.__closeButton == null) {
            this.__closeButton = document.createElement('div');
            this.__closeButton.classList.add('modal-close-button');
        }
 
        // Add event listener to close the modal
        this._component.registerDomEvent(
            this.__closeButton,
            'click',
            this.close.bind(this),
        );
 
        return this.__closeButton;
    }
 
    /**
     * The title of the modal.
     */
    private get _title(): HTMLElement {
        if (this.__title == null) {
            this.__title = document.createElement('div');
            this.__title.classList.add('modal-title');
            this.__title.innerText = '\u00A0';
        }
 
        return this.__title;
    }
 
    /**
     * The modal element.
     */
    private get _modal(): HTMLElement {
        if (this.__modal == null) {
            this.__modal = document.createElement('div');
            this.__modal.classList.add('modal');
            this.__modal.style.pointerEvents = 'auto';
        }
 
        return this.__modal;
    }
 
    /**
     * @inheritdoc
     */
    public get content(): HTMLElement {
        if (this.__content == null) {
            this.__content = document.createElement('div');
            this.__content.classList.add('modal-content');
        }
 
        return this.__content;
    }
 
    /**
     * Creates a new Modal.
     * @param component The component that the modal belongs to.
     */
    constructor(component?: Component) {
        Iif (component != null) {
            this._component = component;
        }
    }
 
    /**
     * @inheritdoc
     */
    public open(): void {
        if (this._onOpen == null) {
            this._logger?.error('The onOpen callback must be set.');
            throw new MissingCallbackError('onOpen');
        }
 
        try {
            // Check if the modal can be opened
            if (this._shouldOpen?.() === false) return;
        } catch (error) {
            this._logger?.error('Error in shouldOpen callback', error);
            throw new CallbackError('shouldOpen', error);
        }
 
        // Register the before unload event
        // to close the modal when the plugin is unloaded.
        this._ILifecycleManager.register(
            'before',
            'unload',
            this._beforeUnload,
        );
 
        this._component.load();
        this.buildModal();
 
        if (this._isDraggable && this._draggableElement != null) {
            this._draggableElement.enableDragging();
        }
 
        try {
            this._onOpen();
        } catch (error) {
            this._logger?.error('Error in onOpen callback', error);
            throw new CallbackError('onOpen', error);
        }
    }
 
    /**
     * @inheritdoc
     */
    public close(): void {
        // Unregister the before unload event
        this._ILifecycleManager.unregister(
            'before',
            'unload',
            this._beforeUnload,
        );
 
        try {
            this._onClose?.();
        } catch (error) {
            this._logger?.error('Error in onClose callback', error);
            throw new CallbackError('onClose', error);
        }
        this._container.remove();
        this._component.unload();
    }
 
    /**
     * Builds the modal.
     */
    private buildModal(): void {
        const fragment = new DocumentFragment();
 
        this._container.appendChild(this._bg);
        fragment.appendChild(this._container);
 
        this._modal.appendChild(this._closeButton);
        this._modal.appendChild(this._title);
        this._modal.appendChild(this.content);
        this._container.appendChild(this._modal);
 
        this._body.appendChild(fragment);
 
        if (this._isDraggable) {
            this._draggableElement = new this._IDraggableElement_(
                this._modal,
                this._title,
                this._component,
            );
        }
    }
 
    /**
     * @inheritdoc
     */
    public setShouldOpen(shouldOpen: IShouldOpenCallback): this {
        this._shouldOpen = shouldOpen;
 
        return this;
    }
 
    /**
     * @inheritdoc
     */
    public setOnOpen(onOpen: IOpenCallback): this {
        this._onOpen = onOpen;
 
        return this;
    }
 
    /**
     * @inheritdoc
     */
    public setOnClose(onClose: ICloseCallback): this {
        this._onClose = onClose;
 
        return this;
    }
 
    /**
     * @inheritdoc
     */
    public setTitle(title: string): this {
        // The title must never be empty so that it can still serve as a drag handler.
        this._title.innerText = title.trim().length > 0 ? title : '\u00A0';
 
        return this;
    }
 
    /**
     * @inheritdoc
     */
    public setContent(content: DocumentFragment): this {
        this.content.appendChild(content);
 
        return this;
    }
 
    /**
     * @inheritdoc
     */
    public setDraggableEnabled(isDraggable: boolean): this {
        this._isDraggable = isDraggable;
 
        return this;
    }
 
    /**
     * @inheritdoc
     */
    public setBackgroundDimmed(willDimBackground: boolean): this {
        this._willDimBackground = willDimBackground;
 
        return this;
    }
}
 
Zur TypeDoc-Dokumentation