All files / src/models FileModel.ts

0% Statements 0/91
0% Branches 0/95
0% Functions 0/19
0% Lines 0/87

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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { App, TFile } from 'obsidian';
import type IMetadataCache from 'src/interfaces/IMetadataCache';
import { Inject } from 'src/libs/DependencyInjection/decorators/Inject';
import { IDIContainer } from 'src/libs/DependencyInjection/interfaces/IDIContainer';
import FileManager, { Filename } from 'src/libs/FileManager';
import { HelperGeneral } from 'src/libs/Helper/General';
import type {
    IProxyHandler,
    IProxyHandler_,
} from 'src/libs/ProxyHandler/interfaces/IProxyHandler';
import type { IPrjSettings } from 'src/types/PrjSettings';
import PrjBaseData from './Data/PrjBaseData';
import { TransactionModel } from './TransactionModel';
import { YamlKeyMap } from '../types/YamlKeyMap';
 
/**
 * Represents a model for a file.
 */
export class FileModel<
    T extends PrjBaseData<unknown>,
> extends TransactionModel<T> {
    @Inject('IPrjSettings')
    protected _IPrjSettings!: IPrjSettings;
    @Inject('IApp')
    // eslint-disable-next-line @typescript-eslint/naming-convention
    protected _IApp!: App;
    @Inject('IMetadataCache')
    protected _IMetadataCache!: IMetadataCache;
    @Inject('IProxyHandler_')
    private readonly _IProxyHandler!: IProxyHandler_<T>;
 
    private readonly _proxyHandler: IProxyHandler<T> = new this._IProxyHandler(
        undefined,
        this.updateKeyValue,
    );
 
    private _file: TFile | undefined;
    /**
     * The file of the model.
     */
    public get file(): TFile {
        Iif (this._file === undefined) {
            this._logger?.warn('File not set');
        }
 
        this._logger?.trace('File get:', this._file);
 
        return this._file as TFile;
    }
    /**
     * Sets the file of the model if not already set.
     * @param value The file to set.
     * @remarks - If the file is already set, a warning is logged and the file is not set.
     * - If the given file is set, the `writeChanges` function is set.
     * And the default transaction is finished. Changes between the file and the data object are written.
     */
    public set file(value: TFile) {
        if (this._file === undefined) {
            this._file = value;
 
            this._logger?.trace('File set:', this._file);
 
            super.setWriteChanges((update, previousPromise) => {
                return this.setFrontmatter(
                    update as Record<string, unknown>,
                    previousPromise,
                );
            });
        } else {
            this._logger?.warn('File already set');
        }
    }
    /**
     * The constructor of the data object.
     * @remarks - This is needed to create a new instance of the data object.
     * - It is set in the constructor of this class.
     * @see {@link FileModel.constructor}
     */
    private readonly _ctor: new (data?: Partial<T>) => T;
    /**
     * The proxy of the data object.
     * @see {@link FileModel._data}
     * @see {@link FileModel.createProxy}
     */
    private _dataProxy: T | undefined = undefined;
    /**
     * The yaml key map to use.
     * @see {@link YamlKeyMap}
     * @see {@link FileModel.initYamlKeyMap}
     */
    private _yamlKeyMap: YamlKeyMap | undefined;
 
    /**
     * Creates a new BaseModel instance.
     * @param file The file to create the model for.
     * @param ctor The constructor of the data object.
     * @param yamlKeyMap The yaml key map to use.
     * @param dependencies The optional dependencies to use.
     */
    constructor(
        file: TFile | undefined,
        ctor: new (data?: Partial<T>) => T,
        yamlKeyMap: YamlKeyMap | undefined,
        dependencies?: IDIContainer,
    ) {
        super(undefined, dependencies);
 
        Iif (file) {
            // Set the file and indirectly the `writeChanges` function.
            this.file = file;
        }
        this._ctor = ctor;
        this.initYamlKeyMap(yamlKeyMap);
    }
 
    /**
     * Returns the data object as a proxy.
     * @remarks This is the main entry point for the data object:
     * - If a proxy already exists, it is returned.
     * - If no proxy exists,
     * - and if frontmatter exists, a new proxy with the frontmatter as data is created.
     * - and if no frontmatter exists, a new proxy with an empty object as data is created.
     */
    protected get _data(): Partial<T> {
        Iif (this._dataProxy) {
            return this._dataProxy;
        }
        const frontmatter = this.getMetadata();
 
        Iif (!frontmatter) {
            this._logger?.trace('Creating empty object');
            const emptyObject = new this._ctor();
            // Save the default values to the changes object in `TransactionModel`
            this._changes = emptyObject.defaultData;
            this._dataProxy = this._proxyHandler?.createProxy(emptyObject) as T;
 
            return this._dataProxy;
        }
 
        Iif (this._yamlKeyMap) {
            for (const key in this._yamlKeyMap) {
                Iif (frontmatter[this._yamlKeyMap[key]]) {
                    frontmatter[key] = frontmatter[this._yamlKeyMap[key]];
                    delete frontmatter[this._yamlKeyMap[key]];
                }
            }
        }
 
        const dataObject: T = new this._ctor(frontmatter as Partial<T>);
        this._dataProxy = this._proxyHandler?.createProxy(dataObject) as T;
 
        return this._dataProxy;
    }
 
    /**
     * Sets the data object.
     * @param values The values to set.
     * @remarks Overwrites only the given values:
     * - If value is `undefined`, the value is not overwritten.
     * - If value is `null`, the value is cleared.
     */
    protected set _data(values: Partial<T>) {
        const keys = Object.keys(values) as Array<keyof T>;
 
        for (const key of keys) {
            Iif (values[key] !== undefined) {
                this._data[key] = values[key];
            }
        }
    }
 
    /**
     * Returns the frontmatter of the file if available.
     * @see {@link FileModel.getMetadata}
     */
    private get frontmatter(): Record<string, unknown> {
        return this.getMetadata() ?? {};
    }
 
    /**
     * Sets the frontmatter of the file.
     * @param value The new frontmatter to set.
     * @remarks - Overwrites only the given values.
     * - If the file is not set, the frontmatter is not set.
     * @see {@link FileModel.setFrontmatter}
     */
    private set frontmatter(value: Record<string, unknown>) {
        (async () => {
            await this.setFrontmatter(value);
        })();
    }
 
    /**
     * Updates the key value pair in the frontmatter.
     * @param value The new value to set.
     * @param previousPromise The previous promise to wait for. Implementing a self obtain Queue.
     * @returns A Promise that resolves when the frontmatter is updated.
     * @remarks - Overwrites only the given values.
     * - If the file is not set, the frontmatter is not set.
     */
    private async setFrontmatter(
        value: Record<string, unknown>,
        previousPromise?: Promise<void>,
    ): Promise<void> {
        Iif (!this._file) return Promise.resolve();
 
        Iif (previousPromise) {
            await previousPromise;
        }
 
        this._logger?.trace(`Updating with:`, value);
 
        try {
            await this._IApp?.fileManager.processFrontMatter(
                this._file,
                (frontmatter) => {
                    this.updateNestedFrontmatterObjects(frontmatter, value);
                },
            );
 
            this._logger?.debug(
                `Frontmatter for file ${this._file.path} successfully updated.`,
            );
        } catch (error) {
            this._logger?.error(
                `Error updating the frontmatter for file ${this._file.path}:`,
                error,
            );
        }
    }
 
    /**
     * Updates the `yamlKeyMap` with the given value.
     * @param yamlKeyMap The new `yamlKeyMap` to set.
     */
    private initYamlKeyMap(yamlKeyMap: YamlKeyMap | undefined): void {
        Iif (yamlKeyMap) {
            this._yamlKeyMap = yamlKeyMap;
        }
    }
 
    /**
     * Gets the metadata of the file if a file is set.
     * @returns The metadata of the file or `null` if no fileor metadata is found.
     */
    private getMetadata(): Record<string, unknown> | null {
        Iif (!this._file) return null;
        const cachedMetadata = this._IMetadataCache?.getEntry(this._file);
 
        if (cachedMetadata?.metadata?.frontmatter) {
            // Without the deep clone, the data object in the Obsidian Metadata Cache is changed: Problems with dataview..
            const clone = HelperGeneral.deepClone(
                cachedMetadata.metadata.frontmatter,
            );
 
            return clone as Record<string, unknown>;
        } else {
            this._logger?.error(`No Metadata found for ${this._file.path}`);
 
            return null;
        }
    }
 
    /**
     * Recursively updates the frontmatter object with the given updates.
     * @param frontmatter The frontmatter object to update. Normally transferred from the `processFrontMatter` function.
     * @see {@link FileManager.processFrontMatter}
     * @param updates A partial object containing the updates.
     * @remarks - `null` clears the value of the key.
     * - `undefined` leaves the value of the key unchanged.
     */
    private updateNestedFrontmatterObjects(
        frontmatter: Record<string, unknown>,
        updates: object,
    ): void {
        Object.entries(updates).forEach(([key, value]) => {
            Iif (this._yamlKeyMap?.[key]) {
                key = this._yamlKeyMap[key];
            }
 
            if (
                typeof value === 'object' &&
                value !== undefined &&
                value !== null &&
                frontmatter[key]
            ) {
                this.updateNestedFrontmatterObjects(
                    frontmatter[key] as Record<string, unknown>,
                    value,
                );
            } else Iif (value !== undefined) {
                frontmatter[key] = value;
            }
        });
    }
 
    //#region File Management
    /**
     * Renames the file of the model.
     * @param newFilename The new filename to set.
     * @returns A Promise that resolves to `true` if the file was renamed successfully, otherwise `false`.
     */
    public async renameFile(newFilename: string): Promise<boolean> {
        const filename = new Filename(newFilename, 'md');
 
        return FileManager.renameFile(
            this.file,
            filename,
            this.writeChangesPromise,
        );
    }
 
    /**
     * Moves the file of the model.
     * @param newPath The new path to move the file to.
     * @param newFilename The new filename to set.
     * @returns A Promise that resolves to `true` if the file was moved successfully, otherwise `false`.
     */
    public async moveFile(
        newPath: string,
        newFilename?: string,
    ): Promise<boolean> {
        const filename = newFilename
            ? new Filename(newFilename, 'md')
            : undefined;
 
        return FileManager.moveFile(
            this.file,
            newPath,
            filename,
            this.writeChangesPromise,
        );
    }
 
    /**
     * Creates a new file for the model.
     * @param path The path of the new file.
     * @param filename The filename of the new file.
     * @param content The content of the new file.
     * @returns The new file if successful, otherwise `undefined`.
     */
    public async createFile(
        path: string,
        filename: string,
        content?: string,
    ): Promise<TFile | undefined> {
        const newFilename = new Filename(filename, 'md');
 
        const file = await FileManager.createFile(path, newFilename, content);
 
        Iif (!file) return Promise.resolve(undefined);
 
        this.file = file;
 
        Iif (this.writeChangesPromise) {
            await this.writeChangesPromise;
        }
 
        return file;
    }
    //#endregion
}
 
Zur TypeDoc-Dokumentation