All files / src/libs/Modals AddAnnotationModal.ts

92.53% Statements 62/67
75.6% Branches 31/41
87.5% Functions 21/24
93.93% Lines 62/66

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                  1x 1x   1x               1x           1x   1x   1x   1x   1x   1x   1x     1x   11x     11x             1x   1x               11x                         3x   3x 1x   1x   2x 2x   2x 1x         1x     1x   1x             1x         1x   1x 1x                 2x                                       1x   1x       1x           1x     1x       1x         1x     1x       1x           1x     1x       1x       1x     1x       1x         1x     1x       1x   1x                 1x                         3x   3x         3x   3x 3x           1x 1x       2x       1x                                              
import { Setting, TFile } from 'obsidian';
import type { IApp } from 'src/interfaces/IApp';
import type { ILogger_, ILogger } from 'src/interfaces/ILogger';
import type IMetadataCache from 'src/interfaces/IMetadataCache';
import { IPrj } from 'src/interfaces/IPrj';
import type {
    ICustomModal_,
    ICustomModal,
} from './CustomModal/interfaces/ICustomModal';
import { Inject } from '../DependencyInjection/decorators/Inject';
import { Resolve } from '../DependencyInjection/functions/Resolve';
import type { ForceConstructor } from '../DependencyInjection/types/GenericContructor';
import { FileType } from '../FileType/FileType';
import type { IHelperGeneral_ } from '../Helper/General';
import type { IHelperObsidian } from '../Helper/interfaces/IHelperObsidian';
import type ITranslationService from '../TranslationService/interfaces/ITranslationService';
 
/**
 * Modal to create a new annotation
 */
export default class AddAnnotationModal {
    @Inject(
        'ILogger_',
        (x: ILogger_) => x.getLogger('AddAnnotationModal'),
        false,
    )
    protected readonly _logger?: ILogger;
    @Inject('IApp')
    protected readonly _IApp!: IApp;
    @Inject('IMetadataCache')
    private readonly _IMetadataCache!: IMetadataCache;
    @Inject('IHelperGeneral_')
    private readonly _IHelperGeneral!: IHelperGeneral_;
    @Inject('IHelperObsidian')
    private readonly _IHelperObsidian!: IHelperObsidian;
    @Inject('ICustomModal_')
    private readonly _ICustomModal_!: ICustomModal_;
    @Inject('ITranslationService')
    private readonly _ITranslationService!: ITranslationService;
    @Inject('Obsidian.Setting_')
    // eslint-disable-next-line @typescript-eslint/naming-convention
    private readonly _Setting_!: ForceConstructor<Setting>;
 
    private readonly _customModal: ICustomModal = new this._ICustomModal_();
 
    private _activeFile?: TFile;
    protected _annotation: Annotation = {
        prefix: '',
        citation: '',
        postfix: '',
        place: '',
        comment: '',
        toString: () => {
            const text = this._annotation;
 
            return `${text.prefix} ${text.citation} ${text.postfix} ${text.place} ${text.comment}`;
        },
    };
 
    /**
     * Creates and opens a Add Annotation modal.
     */
    constructor() {
        this._customModal
            .setBackgroundDimmed(false)
            .setDraggableEnabled(true)
            .setShouldOpen(this.shouldOpen.bind(this))
            .setOnOpen(this.onOpen.bind(this))
            .open();
    }
 
    /**
     * Checks if the active file is a metadata file
     * @returns True if the active file is a metadata file
     */
    private shouldOpen(): boolean {
        const activeFile = this._IHelperObsidian.getActiveFile();
 
        if (!activeFile) {
            this._IHelperObsidian.showNotice('No active file found', 2500);
 
            return false;
        }
        const activeFileMetadata = this._IMetadataCache.getEntry(activeFile);
        const type = activeFileMetadata?.metadata.frontmatter?.type;
 
        if (!FileType.isValidOf(type, ['Metadata'])) {
            this._IHelperObsidian.showNotice(
                'The active file is not a metadata file',
                2500,
            );
 
            return false;
        }
 
        this._activeFile = activeFile;
 
        return true;
    }
 
    /**
     * Saves the annotation to the active file
     */
    private save(): void {
        const id = this._IHelperGeneral.generateUID(
            this._annotation.toString(),
            11,
        );
 
        const template = this.generateAnnotationTemplate(id);
 
        Iif (!this._activeFile) return;
        this._IApp.vault.append(this._activeFile, template);
    }
 
    /**
     * Generates the annotation template
     * @param id The unique id of the annotation
     * @returns The annotation template
     */
    private generateAnnotationTemplate(id: string): string {
        return `
>_${this._annotation.prefix ?? ' '}_
>==${this._annotation.citation ?? ' '}== 
>_${this._annotation.postfix ?? ' '}_
>
>Link: [[#^${id}|Zeige Zitat]]
><!-- [[${this._activeFile?.basename}#^${id}|ZitierterText]] -->
>Kommentar: 
>**${this._annotation.comment ?? ' '}**
>
>Stelle:
>${this._annotation.place ? `##${this._annotation.place}` : ''}
^${id}
`;
    }
 
    /**
     * Builds the content of the modal
     */
    private onOpen(): void {
        this._customModal.content.addClass('custom-form');
 
        this._customModal.setTitle(
            this._ITranslationService.get('Add annotation'),
        );
 
        new this._Setting_(this._customModal.content)
            .setName(this._ITranslationService.get('Prefix'))
            .setDesc(this._ITranslationService.get('Prefix description'))
            .setClass('custom-form-textarea')
            .setClass('smalerHeight')
            .addTextArea((text) => {
                text.setPlaceholder(this._ITranslationService.get('Prefix'))
                    .setValue('')
                    .onChange((value) => {
                        this._annotation.prefix = value;
                    });
            });
 
        new this._Setting_(this._customModal.content)
            .setName(this._ITranslationService.get('Citation'))
            .setDesc(this._ITranslationService.get('Citation description'))
            .setClass('custom-form-textarea')
            .addTextArea((text) => {
                text.setPlaceholder(this._ITranslationService.get('Citation'))
                    .setValue('')
                    .onChange((value) => {
                        this._annotation.citation = value;
                    });
            });
 
        new this._Setting_(this._customModal.content)
            .setName(this._ITranslationService.get('Postfix'))
            .setDesc(this._ITranslationService.get('Postfix description'))
            .setClass('custom-form-textarea')
            .setClass('smalerHeight')
            .addTextArea((text) => {
                text.setPlaceholder(this._ITranslationService.get('Postfix'))
                    .setValue('')
                    .onChange((value) => {
                        this._annotation.postfix = value;
                    });
            });
 
        new this._Setting_(this._customModal.content)
            .setName(this._ITranslationService.get('Place'))
            .setDesc(this._ITranslationService.get('Place description'))
            .addText((text) => {
                text.setPlaceholder(this._ITranslationService.get('Place'))
                    .setValue('')
                    .onChange((value) => {
                        this._annotation.place = value;
                    });
            });
 
        new this._Setting_(this._customModal.content)
            .setName(this._ITranslationService.get('Comment'))
            .setDesc(this._ITranslationService.get('Comment description'))
            .setClass('custom-form-textarea')
            .addTextArea((text) => {
                text.setPlaceholder(this._ITranslationService.get('Comment'))
                    .setValue('')
                    .onChange((value) => {
                        this._annotation.comment = value;
                    });
            });
 
        new this._Setting_(this._customModal.content)
            .addButton((btn) =>
                btn
                    .setButtonText(this._ITranslationService.get('Save'))
                    .setCta()
                    .onClick(() => {
                        this.save();
                        this._customModal.close();
                    }),
            )
            .addButton((btn) =>
                btn
                    .setButtonText(this._ITranslationService.get('Cancel'))
                    .setCta()
                    .onClick(() => {
                        this._customModal.close();
                    }),
            );
    }
 
    /**
     * Registers the command to open the modal
     */
    public static registerCommand(): void {
        const plugin = Resolve<IPrj>('IPrj');
 
        const iTranslationService = Resolve<ITranslationService>(
            'ITranslationService',
        );
 
        const logger =
            Resolve<ILogger_>('ILogger_').getLogger('AddAnnotationModal');
 
        try {
            plugin.addCommand({
                id: 'add-annotation-modal',
                name: `${iTranslationService.get('Add annotation')}`,
                /**
                 * Callback function for the command
                 */
                callback: async () => {
                    new AddAnnotationModal();
                },
            });
 
            logger?.trace(
                "Registered 'Add Annotation Modal' command successfully",
            );
        } catch (error) {
            logger?.error(
                "Failed to register 'Add Annotation Modal' command",
                error,
            );
        }
    }
}
 
/**
 * The annotation object
 */
interface Annotation {
    prefix: string;
    citation: string;
    postfix: string;
    place: string;
    comment: string;
    /**
     * Converts the annotation to a string
     * @returns The annotation as a concatenated string
     */
    toString: () => string;
}
 
Zur TypeDoc-Dokumentation