All files / src/libs/Modals CreateNewMetadataModal.ts

0% Statements 0/81
0% Branches 0/47
0% Functions 0/7
0% Lines 0/77

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { TFile } from 'obsidian';
import API from 'src/classes/API';
import Lng from 'src/classes/Lng';
import { ILogger_ } from 'src/interfaces/ILogger';
import type IMetadataCache from 'src/interfaces/IMetadataCache';
import { IPrj } from 'src/interfaces/IPrj';
import { IPrjDocument } from 'src/models/Data/interfaces/IPrjDocument';
import { DocumentModel } from 'src/models/DocumentModel';
import {
    Field,
    FormConfiguration,
    IFormResult,
    IResultData,
} from 'src/types/ModalFormType';
import PrjTypes, { FileSubType } from 'src/types/PrjTypes';
import BaseModalForm from './BaseModalForm';
import { Inject } from '../DependencyInjection/decorators/Inject';
import { Resolve } from '../DependencyInjection/functions/Resolve';
import { HelperObsidian } from '../Helper/Obsidian';
 
/**
 * Modal to create a new metadata file
 */
export default class CreateNewMetadataModal extends BaseModalForm {
    @Inject('IMetadataCache')
    private readonly _IMetadataCache: IMetadataCache;
 
    /**
     * Creates an instance of CreateNewMetadataModal.
     */
    constructor() {
        super();
    }
 
    /**
     * Registers the command to open the modal
     * @remarks No cleanup needed
     */
    public static registerCommand(): void {
        const plugin = Resolve<IPrj>('IPrj');
 
        const logger = Resolve<ILogger_>('ILogger_').getLogger(
            'CreateNewMetadataModal',
        );
        logger.trace("Registering 'CreateNewMetadataModal' commands");
 
        plugin.addCommand({
            id: 'create-new-metadata-file',
            name: `${Lng.gt('Create new metadata')}`,
            /**
             *
             */
            callback: async () => {
                const modal = new CreateNewMetadataModal();
                const result = await modal.openForm();
 
                Iif (result) {
                    const document = await modal.evaluateForm(result);
 
                    Iif (document) await HelperObsidian.openFile(document.file);
                }
            },
        });
    }
 
    /**
     * Opens the modal form
     * @param [preset] Preset values for the form
     * @returns Result of the form
     */
    public async openForm(
        preset?: Partial<IPrjDocument>,
    ): Promise<IFormResult | undefined> {
        Iif (!this.isApiAvailable()) return;
        this._logger?.trace("Opening 'CreateNewMetadataModal' form");
 
        const convertedPreset: IResultData =
            this.convertPresetToIResultData(preset);
 
        const tags: string[] = this.getTagsFromActiveFile();
 
        Iif (convertedPreset) {
            if (convertedPreset.tags && Array.isArray(convertedPreset.tags)) {
                convertedPreset.tags = [...convertedPreset.tags, ...tags];
            } else {
                convertedPreset.tags = [...tags];
            }
        }
 
        const form = this.constructForm();
 
        const result = await this.getApi().openForm(form, {
            values: convertedPreset,
        });
 
        this._logger?.trace(
            `From closes with status '${result.status}' and data:`,
            result.data,
        );
 
        return result;
    }
 
    /**
     * Evaluates the form result and creates a new metadata file
     * @param result Result of the form
     * @param existingFile A optional existing file to use
     * @returns The created metadata file
     * @remarks 1. Creates a new Document model with the give file or no file.
     * 2. Sets the data of the document model to the form result.
     * 3. Creates a new file with the metadata filename or uses the existing file and rename it.
     */
    public async evaluateForm(
        result: IFormResult,
        existingFile?: TFile,
    ): Promise<DocumentModel | undefined> {
        Iif (!this.isApiAvailable()) return;
 
        Iif (result.status !== 'ok' || !result.data) return;
 
        const document = new DocumentModel(
            existingFile ? existingFile : undefined,
        );
 
        const folder = existingFile?.parent?.path
            ? existingFile.parent?.path
            : this._IPrjSettings.documentSettings.defaultFolder;
 
        (result.data.subType as FileSubType | undefined) =
            PrjTypes.isValidFileSubType(result.data.subType);
 
        const linkedFile = this._IMetadataCache.getFileByLink(
            result.data.file as string,
            '',
        );
 
        (result.data.file as string | undefined) = result.data.file
            ? document.setLinkedFile(linkedFile, folder)
            : undefined;
 
        document.data = result.data as Partial<IPrjDocument>;
 
        if (!existingFile) {
            // No existing file, create a new one
            let template = '';
 
            // If a template is set, use it
            const templateFile = this._IApp.vault.getAbstractFileByPath(
                this._IPrjSettings.documentSettings.template,
            );
 
            Iif (templateFile && templateFile instanceof TFile) {
                try {
                    template = await this._IApp.vault.read(templateFile);
                } catch (error) {
                    this._logger?.error(
                        `Error reading template file '${templateFile.path}'`,
                        error,
                    );
                }
            }
 
            const newFileName =
                API.documentModel.generateMetadataFilename(document);
 
            await document.createFile(folder, newFileName, template);
        } else {
            // Existing file, rename it properly
            await API.documentModel.syncMetadataToFile(document.file);
        }
 
        return document;
    }
 
    /**
     * Constructs the form
     * @returns Form configuration
     */
    protected constructForm(): FormConfiguration {
        const form: FormConfiguration = {
            title: `${Lng.gt('Create new metadata')}`,
            name: 'new metadata file',
            customClassname: '',
            fields: [],
        };
 
        // Sub type
        const subType: Field = {
            name: 'subType',
            label: Lng.gt('Metadata sub type'),
            description: Lng.gt('Metadata sub type description'),
            isRequired: true,
            input: {
                type: 'select',
                source: 'fixed',
                options: [
                    { value: 'none', label: Lng.gt('None') },
                    { value: 'Cluster', label: Lng.gt('Metadata Cluster') },
                ],
            },
        };
        form.fields.push(subType);
 
        // Date
        const date: Field = {
            name: 'date',
            label: Lng.gt('Document date'),
            description: Lng.gt('Document date description'),
            isRequired: false,
            input: {
                type: 'date',
            },
        };
        form.fields.push(date);
 
        // Date of delivery
        const dateOfDelivery: Field = {
            name: 'dateOfDelivery',
            label: Lng.gt('Date of delivery'),
            description: Lng.gt('Date of delivery description'),
            isRequired: false,
            input: {
                type: 'date',
            },
        };
        form.fields.push(dateOfDelivery);
 
        // Title
        const title: Field = {
            name: 'title',
            label: Lng.gt('Title'),
            description: Lng.gt('Title description'),
            isRequired: true,
            input: {
                type: 'text',
            },
        };
        form.fields.push(title);
 
        // Description
        const description: Field = {
            name: 'description',
            label: Lng.gt('Document description'),
            description: Lng.gt('Document description description'),
            isRequired: false,
            input: {
                type: 'textarea',
            },
        };
        form.fields.push(description);
 
        // Sender
        const sender: Field = {
            name: 'sender',
            label: Lng.gt('Sender'),
            description: Lng.gt('Sender description'),
            isRequired: false,
            input: {
                type: 'dataview',
                query: 'app.plugins.plugins.prj.api.documentModel.getAllSenderRecipients()',
            },
        };
        form.fields.push(sender);
 
        // Recipient
        const recipient: Field = {
            name: 'recipient',
            label: Lng.gt('Recipient'),
            description: Lng.gt('Recipient description'),
            isRequired: false,
            input: {
                type: 'dataview',
                query: 'app.plugins.plugins.prj.api.documentModel.getAllSenderRecipients()',
            },
        };
        form.fields.push(recipient);
 
        // Hide
        const hide: Field = {
            name: 'hide',
            label: Lng.gt('Hide'),
            description: Lng.gt('Hide description'),
            isRequired: false,
            input: {
                type: 'toggle',
            },
        };
        form.fields.push(hide);
 
        // Dont change PDF path
        const dontChangePdfPath: Field = {
            name: 'dontChangePdfPath',
            label: Lng.gt('Dont change PDF Path'),
            description: Lng.gt('Dont change PDF Path description'),
            isRequired: false,
            input: {
                type: 'toggle',
            },
        };
        form.fields.push(dontChangePdfPath);
 
        // Tags
        const tags: Field = {
            name: 'tags',
            label: Lng.gt('Tags'),
            description: Lng.gt('Tags description'),
            isRequired: false,
            input: {
                type: 'tag',
            },
        };
        form.fields.push(tags);
 
        // File
        const file: Field = {
            name: 'file',
            label: Lng.gt('PDF file'),
            description: Lng.gt('PDF file description'),
            isRequired: false,
            input: {
                type: 'dataview',
                query: 'app.plugins.plugins.prj.api.documentModel.getAllPDFsWithoutMetadata().map(file => file.name)',
            },
        };
        form.fields.push(file);
 
        return form;
    }
}
 
Zur TypeDoc-Dokumentation