All files / src/libs/Modals CreateNewNoteModal.ts

0% Statements 0/65
0% Branches 0/45
0% Functions 0/7
0% Lines 0/61

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                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { TFile } from 'obsidian';
import API from 'src/classes/API';
import Lng from 'src/classes/Lng';
import { ILogger_ } from 'src/interfaces/ILogger';
import { IPrj } from 'src/interfaces/IPrj';
import PrjNoteData from 'src/models/Data/PrjNoteData';
import { NoteModel } from 'src/models/NoteModel';
import {
    Field,
    FormConfiguration,
    IFormResult,
    IResultData,
} from 'src/types/ModalFormType';
import BaseModalForm from './BaseModalForm';
import { Resolve } from '../DependencyInjection/functions/Resolve';
import { HelperObsidian } from '../Helper/Obsidian';
 
/**
 * Modal to create a new metadata file
 */
export default class CreateNewNoteModal extends BaseModalForm {
    /**
     * 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('CreateNewNoteModal');
        logger.trace("Registering 'CreateNewNoteModal' commands");
 
        plugin.addCommand({
            id: 'create-new-note-file',
            name: `${Lng.gt('Create new note')}`,
            /**
             *
             */
            callback: async () => {
                const modal = new CreateNewNoteModal();
                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<PrjNoteData>,
    ): Promise<IFormResult | undefined> {
        Iif (!this.isApiAvailable()) return;
        this._logger?.trace("Opening 'CreateNewNoteModal' 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 currentDate = new Date();
        const formattedDate = currentDate.toISOString().split('T')[0];
 
        convertedPreset.date = formattedDate;
 
        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 or renames a note accordingly.
     * @param result - The form result containing the data.
     * @param existingFile - The existing file to be renamed, if applicable.
     * @returns A Promise that resolves to the created or renamed NoteModel, or undefined if the API is not available or the form result is invalid.
     */
    public async evaluateForm(
        result: IFormResult,
        existingFile?: TFile,
    ): Promise<NoteModel | undefined> {
        Iif (!this.isApiAvailable()) return;
 
        Iif (result.status !== 'ok' || !result.data) return;
 
        const note = new NoteModel(existingFile ? existingFile : undefined);
 
        const folder = existingFile?.parent?.path
            ? existingFile.parent?.path
            : this._IPrjSettings.noteSettings.defaultFolder;
 
        note.data = result.data as Partial<PrjNoteData>;
 
        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.noteSettings.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.noteModel.generateFilename(note);
 
            await note.createFile(folder, newFileName, template);
        } else {
            // Existing file, rename it properly
            const newFileName = API.noteModel.generateFilename(note);
            note.moveFile(folder, newFileName);
        }
 
        return note;
    }
 
    /**
     * Constructs the form
     * @returns Form configuration
     */
    protected constructForm(): FormConfiguration {
        const form: FormConfiguration = {
            title: `${Lng.gt('Create new note')}`,
            name: 'new metadata file',
            customClassname: '',
            fields: [],
        };
 
        // Title
        const title: Field = {
            name: 'title',
            label: Lng.gt('Title'),
            description: Lng.gt('Title description'),
            isRequired: true,
            input: {
                type: 'text',
            },
        };
        form.fields.push(title);
 
        // Date
        const date: Field = {
            name: 'date',
            label: Lng.gt('Date'),
            description: Lng.gt('DocDateDescription'),
            isRequired: false,
            input: {
                type: 'date',
            },
        };
        form.fields.push(date);
 
        // 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);
 
        // Tags
        const tags: Field = {
            name: 'tags',
            label: Lng.gt('Tags'),
            description: Lng.gt('Tags description'),
            isRequired: false,
            input: {
                type: 'tag',
            },
        };
        form.fields.push(tags);
 
        return form;
    }
}
 
Zur TypeDoc-Dokumentation