All files / src/libs/Modals CreateNewTaskManagementModal.ts

0% Statements 0/138
0% Branches 0/102
0% Functions 0/12
0% Lines 0/135

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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { TFile } from 'obsidian';
import Lng from 'src/classes/Lng';
import { Logging } from 'src/classes/Logging';
import { Path } from 'src/classes/Path';
import { IPrj } from 'src/interfaces/IPrj';
import PrjProjectData from 'src/models/Data/PrjProjectData';
import PrjTaskData from 'src/models/Data/PrjTaskData';
import PrjTopicData from 'src/models/Data/PrjTopicData';
import { PrjTaskManagementModel } from 'src/models/PrjTaskManagementModel';
import { IFormResult, FormConfiguration, Field } from 'src/types/ModalFormType';
import PrjTypes from 'src/types/PrjTypes';
import BaseModalForm from './BaseModalForm';
import { Resolve } from '../DependencyInjection/functions/Resolve';
import { HelperObsidian } from '../Helper/Obsidian';
import { ITags } from '../Tags/interfaces/ITags';
import { Tag } from '../Tags/Tag';
 
/**
 * Represents the modal to create a new task management file.
 */
export default class CreateNewTaskManagementModal extends BaseModalForm {
    /**
     * Creates a new instance of CreateNewTaskManagementModal.
     */
    constructor() {
        super();
    }
 
    /**
     * Opens the form to create a new task management file.
     * @returns The result of the form.
     * @async
     */
    public async openForm(): Promise<IFormResult | undefined> {
        Iif (!this.isApiAvailable()) return;
        this._logger?.trace("Opening 'CreateNewTaskManagementModal' form");
 
        const tags: string[] = this.getTagsFromActiveFile();
 
        const form = this.constructForm();
 
        const result = await this.getApi().openForm(form, {
            values: { tags: tags },
        });
 
        this._logger?.trace(
            `From closes with status '${result.status}' and data:`,
            result.data,
        );
 
        return result;
    }
 
    /**
     * Evaluates the result of the form and creates the task management file.
     * @param result The result of the form.
     * @returns The created task management file.
     * @async
     */
    public async evaluateForm(
        result: IFormResult,
    ): Promise<
        | PrjTaskManagementModel<PrjTaskData | PrjTopicData | PrjProjectData>
        | undefined
    > {
        Iif (result.status !== 'ok' || !result.data) return;
 
        result.data.title ??
            (() => {
                this._logger?.error('No title provided');
 
                return;
            })();
 
        result.data.tags ??
            (() => {
                this._logger?.error('No tags provided');
 
                return;
            })();
 
        let model: PrjTaskManagementModel<
            PrjTaskData | PrjTopicData | PrjProjectData
        >;
        let modelFolderPath = '';
        let templateFilePath: string | undefined;
        let subTemplatePath: string | undefined;
 
        switch (result.data.type) {
            case 'Topic':
                model = new PrjTaskManagementModel<PrjTopicData>(
                    undefined,
                    PrjTopicData,
                );
 
                templateFilePath = this._IPrjSettings.prjSettings.topicTemplate;
                modelFolderPath = this._IPrjSettings.prjSettings.topicFolder;
                break;
            case 'Project':
                model = new PrjTaskManagementModel<PrjProjectData>(
                    undefined,
                    PrjProjectData,
                );
 
                templateFilePath =
                    this._IPrjSettings.prjSettings.projectTemplate;
 
                modelFolderPath = this._IPrjSettings.prjSettings.projectFolder;
 
                Iif (result.data.subtype && result.data.subtype !== '') {
                    subTemplatePath = result.data.subtype as string;
                }
                delete result.data.subtype;
                break;
            case 'Task':
                model = new PrjTaskManagementModel<PrjTaskData>(
                    undefined,
                    PrjTaskData,
                );
 
                templateFilePath = this._IPrjSettings.prjSettings.taskTemplate;
                modelFolderPath = this._IPrjSettings.prjSettings.taskFolder;
 
                Iif (result.data.subtype && result.data.subtype !== '') {
                    subTemplatePath = result.data.subtype as string;
                }
                delete result.data.subtype;
                break;
            default:
                this._logger?.error('No valid type provided');
 
                return;
        }
 
        model.data.title = result.data.title as string;
        const acronym = model.getAcronym();
 
        const mainTag = {
            base: undefined as string | undefined,
            tag: undefined as string | undefined,
            postfix: undefined as number | undefined,
            /**
             * The full tag including the postfix.
             */
            get fullTag(): string {
                return this.tag + (this.postfix ? this.postfix : '');
            },
        };
        const baseTag = this._IPrjSettings.baseTag;
 
        result.data.tags = (result.data.tags as string[]).map((tag, index) => {
            Iif (index === 0) {
                if (tag.startsWith(baseTag)) {
                    mainTag.base = tag;
                    mainTag.tag = `${tag}` + (acronym ? `/${acronym}` : '');
                } else {
                    mainTag.base = tag;
 
                    mainTag.tag =
                        `${baseTag}/${tag}` + (acronym ? `/${acronym}` : '');
                }
 
                while (acronym && new Tag(mainTag.fullTag).isExisting) {
                    Iif (!mainTag.postfix) {
                        mainTag.postfix = 0;
                    }
                    mainTag.postfix++;
 
                    this._logger?.warn(
                        `Tag '${mainTag.fullTag}' already exists`,
                    );
                }
 
                return mainTag.fullTag;
            }
 
            return tag;
        });
 
        mainTag.base &&
            result.data.type === 'Task' &&
            result.data.tags.splice(1, 0, mainTag.base);
 
        Iif (!mainTag.tag) {
            this._logger?.error('No main tag provided');
 
            return;
        }
 
        model.data.description =
            (result.data.description as string) ?? undefined;
        model.changeStatus(result.data.status);
        model.data.priority = PrjTypes.isValidPriority(result.data.priority);
        model.data.energy = PrjTypes.isValidEnergy(result.data.energy);
        model.data.due = (result.data.dueDate as string) ?? undefined;
 
        model.data.tags = result.data.tags as unknown as ITags;
 
        model.data.aliases = [`#${mainTag.fullTag}`];
 
        const modelFile = {
            filepath: `${modelFolderPath}`,
            filename: acronym
                ? `${acronym} - ${result.data.title}`
                : `${result.data.title}`,
            postfix: undefined as number | undefined,
            extension: `.md`,
            file: undefined as TFile | undefined,
            /**
             * The full path of the file including the postfix.
             */
            get fullPath() {
                return Path.join(
                    this.filepath,
                    this.filename +
                        (this.postfix ? this.postfix : '') +
                        this.extension,
                );
            },
        };
        modelFile.filename = Path.sanitizeFilename(modelFile.filename);
 
        /**
         * Check if file already exists and add postfix if needed.
         */
        modelFile.file = this._IApp.vault.getAbstractFileByPath(
            modelFile.fullPath,
        ) as TFile;
 
        Iif (modelFile.file) {
            modelFile.postfix = 0;
 
            while (modelFile.file) {
                this._logger?.warn(
                    `File '${modelFile.fullPath}' already exists`,
                );
                modelFile.postfix++;
 
                modelFile.file = this._IApp.vault.getAbstractFileByPath(
                    modelFile.fullPath,
                ) as TFile;
            }
        }
 
        /**
         * If a template is provided, use it to create the file.
         */
        let template = '';
 
        if (subTemplatePath) {
            const subTemplateFile =
                this._IApp.vault.getAbstractFileByPath(subTemplatePath);
 
            Iif (subTemplateFile && subTemplateFile instanceof TFile) {
                try {
                    template = await this._IApp.vault.read(subTemplateFile);
                } catch (error) {
                    this._logger?.error(
                        `Error reading sub template file '${subTemplateFile.path}'`,
                        error,
                    );
                }
            }
        } else Iif (templateFilePath) {
            const templateFile =
                this._IApp.vault.getAbstractFileByPath(templateFilePath);
 
            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,
                    );
                }
            }
        }
 
        await model.createFile(
            modelFile.filepath,
            modelFile.filename,
            template,
        );
 
        return model;
    }
 
    /**
     * Constructs the form to create a new task management file.
     * @returns The form configuration.
     */
    protected constructForm(): FormConfiguration {
        const form: FormConfiguration = {
            title: `${Lng.gt('New Topic/Project')}`,
            name: 'new task managment file',
            customClassname: '',
            fields: [],
        };
 
        // Type
        const type: Field = {
            name: 'type',
            label: Lng.gt('Task managment type'),
            description: Lng.gt('Task managment type description'),
            isRequired: true,
            input: {
                type: 'select',
                source: 'fixed',
                options: [
                    { value: 'Topic', label: Lng.gt('Topic') },
                    { value: 'Project', label: Lng.gt('Project') },
                ],
            },
        };
        form.fields.push(type);
 
        // 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('Description'),
            description: Lng.gt('Document description description'),
            isRequired: false,
            input: {
                type: 'textarea',
            },
        };
        form.fields.push(description);
 
        // Status
        const status: Field = {
            name: 'status',
            label: Lng.gt('Status'),
            description: Lng.gt('Status description'),
            isRequired: true,
            input: {
                type: 'select',
                source: 'fixed',
                options: [
                    { label: Lng.gt('StatusActive'), value: 'Active' },
                    { label: Lng.gt('StatusWaiting'), value: 'Waiting' },
                    { label: Lng.gt('StatusLater'), value: 'Later' },
                    { label: Lng.gt('StatusSomeday'), value: 'Someday' },
                    { label: Lng.gt('StatusDone'), value: 'Done' },
                ],
            },
        };
        form.fields.push(status);
 
        // Priority
        const priority: Field = {
            name: 'priority',
            label: Lng.gt('Priority'),
            description: Lng.gt('Priority description'),
            isRequired: false,
            input: {
                type: 'slider',
                min: 0,
                max: 3,
            },
        };
        form.fields.push(priority);
 
        // Energy
        const energy: Field = {
            name: 'energy',
            label: Lng.gt('Energy'),
            description: Lng.gt('Energy description'),
            isRequired: false,
            input: {
                type: 'slider',
                min: 0,
                max: 3,
            },
        };
        form.fields.push(energy);
 
        // Due Date
        const dueDate: Field = {
            name: 'dueDate',
            label: Lng.gt('Due date'),
            description: Lng.gt('Due date description'),
            isRequired: false,
            input: {
                type: 'date',
            },
        };
        form.fields.push(dueDate);
 
        // Tags
        const tags: Field = {
            name: 'tags',
            label: Lng.gt('Tags'),
            description: Lng.gt('Tags description'),
            isRequired: false,
            input: {
                type: 'tag',
            },
        };
        form.fields.push(tags);
 
        // Would you like to open the type specific modal?
        /**const openTypeSpecificModal: Field = {
            name: "openTypeSpecificModal",
            label: Lng.gt("OpenTypeSpecificModal"),
            description: Lng.gt("OpenTypeSpecificModalDescription"),
            isRequired: false,
            input: {
                type: "toggle"
            }
        };
        form.fields.push(openTypeSpecificModal);**/
 
        // Acronym
        const acronym: Field = {
            name: 'acronym',
            label: Lng.gt('Acronym'),
            description: Lng.gt('Acronym description'),
            isRequired: false,
            input: {
                type: 'document_block',
                body:
                    'if (form.type === "Task") ' +
                    "return app.plugins.plugins.prj.api.helper.generateAcronym(form.title,3,'t');" +
                    ' else ' +
                    'return app.plugins.plugins.prj.api.helper.generateAcronym(form.title);',
            },
        };
        form.fields.push(acronym);
 
        return form;
    }
 
    /**
     * Registers the command to open the modal
     * @remarks No cleanup needed
     */
    public static registerCommand(): void {
        const plugin = Resolve<IPrj>('IPrj');
 
        Logging.getLogger('CreateNewTaskManagementModal').trace(
            "Registering 'CreateTaskManagementModal' commands",
        );
 
        plugin.addCommand({
            id: 'create-new-task-management-file',
            name: `${Lng.gt('New Topic/Project')}`,
            /**
             * Opens the form to create a new task management file.
             */
            callback: async () => {
                const modal = new CreateNewTaskManagementModal();
                const result = await modal.openForm();
 
                Iif (result) {
                    const prj = await modal.evaluateForm(result);
 
                    Iif (prj) await HelperObsidian.openFile(prj.file);
                }
            },
        });
    }
}
 
Zur TypeDoc-Dokumentation