All files / src/libs/SingletonBlockProcessor SingletonBlockProcessor.ts

65.33% Statements 49/75
52.21% Branches 59/113
93.75% Functions 15/16
65.33% Lines 49/75

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 329 330 331 332 333    1x                                                                   1x                               1x     1x             4x             19x             2x                 1x             2x                     2x                                       11x 11x 11x 11x 11x 11x               1x 1x                 1x 1x   1x             1x 1x   1x                       11x 11x                                                                                                                                                 1x       1x           1x                   1x   1x 1x   1x 1x 1x             1x                   1x 1x   1x         1x                 5x 5x   5x 1x             1x 4x 1x             1x     3x      
import { MarkdownPostProcessorContext } from 'obsidian';
import { ILogger } from 'src/interfaces/ILogger';
import CustomizableRenderChild from '../CustomizableRenderChild/CustomizableRenderChild';
 
/**
 * Type for the view state.
 */
type ViewState = 'source' | 'preview';
 
/**
 * Class for the singleton block processor.
 * @remarks - This class is used to create a singleton like container for the block.
 * - Childs from containers with the same uid will be moved between the corosponding containers.
 * Depending on the current view state.
 * @example
 * ```ts
 * //const uid = Create a unique id for the block.
 * const singletonBlockProcessor = new SingletonBlockProcessor(uid, el, ctx);
 *
 * const singleToneBlock = singletonBlockProcessor.singletoneContainer;
 * el.append(singleToneBlock);
 *
 * if (!singletonBlockProcessor.checkForSiblingBlocks()) {
 *    // If the block is not the only one in the workspace leaf,
 *    // return and do nothing in your `MarkdownCodeBlockProcessor`.
 *    return;
 * }
 *
 * // Append your main parent container to the singletone container.
 * // This `mainContainer` container will be moved between the corosponding containers.
 * const mainContainer = document.createElement('div');
 * singleToneBlock.append(mainContainer);
 *
 * // Work with your main container from here..
 * ```
 */
export default class SingletonBlockProcessor {
    private readonly _logger: ILogger | undefined;
    private readonly _uid: string;
    private readonly _el: HTMLElement;
    private readonly _ctx: MarkdownPostProcessorContext;
    private _singletonContainer: HTMLElement | undefined;
    private _observer: MutationObserver | undefined;
    private readonly _onUnload: () => void;
    private _observerChild: CustomizableRenderChild | undefined;
 
    /**
     * Get the singletone container for the block.
     * @remarks - Use this container for all your block content.
     * - Register a component with **this** container.
     */
    public get singletoneContainer(): HTMLElement {
        this._singletonContainer =
            this._singletonContainer ?? this.getSingletoneContainer();
 
        return this._singletonContainer;
    }
 
    /**
     * Get the current code block view state.
     */
    public get codeBlockViewState(): ViewState | undefined {
        return this.getCodeBlockViewState();
    }
 
    /**
     * Get the current workspace leaf content block.
     */
    private get workspaceLeafContent(): Element | undefined {
        return this._el.closest('.workspace-leaf-content') ?? undefined;
    }
 
    /**
     * Get the current workspace leaf state.
     */
    private get workspaceLeafState(): string | undefined {
        return (
            this.workspaceLeafContent?.getAttribute('data-mode') ?? undefined
        );
    }
 
    /**
     * Get all sibling blocks with the uid as id.
     */
    private get siblingBlocks(): NodeListOf<Element> | undefined {
        return this.workspaceLeafContent?.querySelectorAll(`#${this._uid}`);
    }
 
    /**
     * Get the source sibling block.
     */
    private get sourceSiblingBlock(): Element | undefined {
        return (
            this.workspaceLeafContent?.querySelector(
                `#${this._uid}[data-mode='source']`,
            ) ?? undefined
        );
    }
 
    /**
     * Get the preview sibling block.
     */
    private get previewSiblingBlock(): Element | undefined {
        return (
            this.workspaceLeafContent?.querySelector(
                `#${this._uid}[data-mode='preview']`,
            ) ?? undefined
        );
    }
 
    /**
     * Create a new instance of the singleton block processor.
     * @param uid The unique id of the block. Only works between blocks with the same id.
     * @param el The element of the block.
     * @param ctx The markdown post processor context.
     * @param logger The optional logger.
     */
    constructor(
        uid: string,
        el: HTMLElement,
        ctx: MarkdownPostProcessorContext,
        logger?: ILogger,
    ) {
        this._logger = logger ?? undefined;
        this._uid = uid;
        this._el = el;
        this._ctx = ctx;
        this._onUnload = this.onUnloadCallback.bind(this);
        this.createObserver();
    }
 
    /**
     * Callback for the unload event.
     * @remarks Disconnect the observer.
     */
    private onUnloadCallback(): void {
        this._logger?.debug(`On Unload, UID: ${this._uid}`);
        this._observer?.disconnect();
    }
 
    /**
     * Check if the block is the only one in the workspace leaf.
     * @returns True if the block is the only one in the workspace leaf.
     * @remarks If the block is the only one in the workspace leaf, create a new block.
     */
    public checkForSiblingBlocks(): boolean {
        const blockViewState = this.codeBlockViewState;
        const viewState = this.workspaceLeafState;
 
        Iif (
            blockViewState === viewState &&
            this.siblingBlocks &&
            this.siblingBlocks.length == 1
        ) {
            return true;
        } else {
            const source = this.sourceSiblingBlock;
            const preview = this.previewSiblingBlock;
 
            return !this.moveChildrenToCorrespondingViewState(
                blockViewState,
                source,
                preview,
            );
        }
    }
 
    /**
     * Create a observer for the block.
     */
    private createObserver(): void {
        if (!this.workspaceLeafContent) {
            return;
        }
 
        // If a sibling block is available, we dont need to create an observer
        // because one observer is enough for all sibling blocks.
        Iif (this.siblingBlocks && this.siblingBlocks.length === 1) {
            // This test is certainly not sufficient.
            // We now check whether the other container has child elements. If not, we unload it to unload the observer.
            // After that we clone the container and append it to the parent again to use it as a new container.
            if (this.siblingBlocks[0].childNodes.length === 0) {
                const clone = this.siblingBlocks[0].cloneNode(false);
                const parent = this.siblingBlocks[0].parentElement;
                this.siblingBlocks[0].remove();
                parent?.append(clone);
            } else {
                return;
            }
        }
 
        // Create a observer component. To `disconnect` the observer on unload.
        this._observerChild = new CustomizableRenderChild(
            this.singletoneContainer,
            undefined,
            this._onUnload,
            this._logger,
        );
 
        this._observer = new MutationObserver((mutations) => {
            this._logger?.trace(
                'Observer detect changes:',
                mutations,
                `UID: ${this._uid}`,
            );
 
            for (const mutation of mutations) {
                Iif (
                    mutation.type === 'attributes' &&
                    mutation.attributeName === 'data-mode'
                ) {
                    const newViewState = this.workspaceLeafState;
                    const source = this.sourceSiblingBlock;
                    const preview = this.previewSiblingBlock;
 
                    this.moveChildrenToCorrespondingViewState(
                        newViewState,
                        source,
                        preview,
                    );
                }
            }
        });
 
        this._observer.observe(this.workspaceLeafContent, {
            attributes: true,
        });
 
        // Add the observer component to the context.
        this._observerChild.load();
        this._ctx.addChild(this._observerChild);
    }
 
    /**
     * Move the corosponding child elements to the new view state.
     * @param blockViewState The current block view state. Determines the target container.
     * @param source The `source` view state container.
     * @param preview The `preview` view state container.
     * @returns True if elements are moved.
     */
    private moveChildrenToCorrespondingViewState(
        blockViewState: string | undefined,
        source: Element | undefined,
        preview: Element | undefined,
    ): boolean {
        Iif (blockViewState === 'source' && source && preview) {
            this._logger?.debug('Move preview to source', `UID: ${this._uid}`);
 
            return this.moveChilds(preview, source);
        } else Iif (blockViewState === 'preview' && source && preview) {
            this._logger?.debug('Move source to preview', `UID: ${this._uid}`);
 
            return this.moveChilds(source, preview);
        }
 
        return false;
    }
 
    /**
     * Move all childs from one element to another.
     * @param from Source element.
     * @param to Target element.
     * @returns True if elements are moved.
     */
    private moveChilds(from: Element, to: Element): boolean {
        let elementsMoved = false;
 
        while (from.firstChild) {
            const child = from.firstChild;
 
            if (child.childNodes.length > 0) {
                elementsMoved = true;
                to.appendChild(child);
            } else E{
                this._logger?.warn('Child has no child nodes', child);
                from.removeChild(child);
            }
        }
 
        return elementsMoved;
    }
 
    /**
     * Get the singletone container for the block.
     * @returns The singletone container for the block.
     * @remarks - Use this container for all your block content.
     * - Register a component with **this** container.
     */
    private getSingletoneContainer(): HTMLElement {
        const singletoneContainer = document.createElement('div');
        singletoneContainer.id = this._uid;
 
        singletoneContainer.setAttribute(
            'data-mode',
            this.getCodeBlockViewState(true) ?? 'none',
        );
 
        return singletoneContainer;
    }
 
    /**
     * Get the current code block view state.
     * @param logging If true, the function will log the view state.
     * @returns The current code block view state.
     */
    private getCodeBlockViewState(logging = false): ViewState | undefined {
        const sourceView = this._el.closest('.markdown-source-view');
        const readingView = this._el.closest('.markdown-reading-view');
 
        if (sourceView) {
            !logging
                ? this._logger?.debug(
                      `CodeBlock View state: 'source'`,
                      `UID: ${this._uid}`,
                  )
                : undefined;
 
            return 'source';
        } else if (readingView) {
            !logging
                ? this._logger?.debug(
                      `CodeBlock View state: 'preview'`,
                      `UID: ${this._uid}`,
                  )
                : undefined;
 
            return 'preview';
        }
 
        return undefined;
    }
}
 
Zur TypeDoc-Dokumentation