All files / src/libs/EditableDataView/Components LinkComponent.ts

0% Statements 0/100
0% Branches 0/51
0% Functions 0/21
0% Lines 0/98

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { Component } from 'obsidian';
import BaseComponent from './BaseComponent';
 
/**
 * Represents a link component that can be edited and displayed in different modes.
 */
export default class LinkComponent extends BaseComponent {
    //#region base properties
    protected _isEditable = false;
    onEnableEditCallback: () => void;
    onDisableEditCallback: () => void;
    onSaveCallback: () => Promise<void>;
    onFirstEdit: () => void;
    onFinalize: () => void;
    //#endregion
    //#region extended properties
    private _onPresentation: ((value: string) => Promise<void>) | undefined;
    private _onSave: ((value: string) => Promise<void>) | undefined;
    private _suggester: ((value: string) => string[]) | undefined;
    private _value: string;
    private _placeholder: string;
    private _suggestions: string[];
    private _title: string;
    private _linkType: 'tag' | 'file' | 'external' = 'external';
    //#endregion
    //#region HTML Elements
    private _link: HTMLAnchorElement;
    private _label: HTMLElement;
    private _input: HTMLInputElement;
    private _datalist: HTMLDataListElement;
    //#endregion
 
    /**
     * Creates a new instance of the LinkComponent.
     * @param component The Obsidian component to attach the link to.
     */
    constructor(component: Component) {
        super(component);
        this.onFinalize = this.build;
        this.onFirstEdit = this.buildInput;
        this.onEnableEditCallback = this.enableEdit;
        this.onSaveCallback = this.save;
        this.onDisableEditCallback = this.disableEdit;
    }
 
    //#region Configuration methods
    /**
     * Enables the editability of the component.
     * @returns The component itself.
     */
    public enableEditability(): this {
        this._isEditable = true;
 
        return this;
    }
 
    /**
     * Sets the value of the component.
     * @param value The value to set.
     * @returns The component itself.
     */
    public setValue(value: string): this {
        this._value = value;
 
        return this;
    }
 
    /**
     * Sets the placeholder of the input element.
     * @param placeholder The placeholder to set.
     * @returns The component itself.
     */
    public setPlaceholder(placeholder: string): this {
        this._placeholder = placeholder;
 
        return this;
    }
 
    /**
     * Sets suggestions for the input element.
     * @param suggestions The suggestions to set.
     * @returns The component itself.
     */
    public setSuggestions(suggestions: string[]): this {
        this._suggestions = suggestions;
 
        return this;
    }
 
    /**
     * Sets the title of the component.
     * @param title The title to set.
     * @returns The component itself.
     */
    public setTitle(title: string): this {
        this._title = title;
 
        return this;
    }
 
    /**
     * Sets the type of the link.
     * @param type The type to set. Can be `tag`, `file` or `external`.
     * @returns The component itself.
     */
    public setLinkType(type: 'tag' | 'file' | 'external'): this {
        this._linkType = type;
 
        return this;
    }
 
    /**
     * Sets the suggester of the component.
     * @param suggester The suggester to set.
     * @returns The component itself.
     * @remarks The suggester is called when the user types in the input element.
     */
    public setSuggester(suggester: (value: string) => string[]): this {
        this._suggester = suggester;
 
        return this;
    }
 
    /**
     * Sets the formator of the component.
     * @param formator The formator to set.
     * @returns The component itself.
     * @remarks The formator is called when the component change in `not-edit` mode.
     */
    public setFormator(
        formator: (value: string) => {
            href: string;
            text: string;
            html?: DocumentFragment;
        },
    ): this {
        /**
         * Sets the presentation of the component.
         * @param value The value to present.
         */
        this._onPresentation = async (value: string): Promise<void> => {
            const linkContent = formator(value);
            this._link.href = linkContent.href;
 
            if (linkContent.html) {
                this._link.innerHTML = '';
                this._link.appendChild(linkContent.html);
            } else this._link.textContent = linkContent.text;
 
            switch (this._linkType) {
                case 'tag':
                    break;
                case 'file':
                    this._link.setAttribute('aria-label', linkContent.href);
                    this._link.setAttribute('data-href', linkContent.href);
                    break;
                case 'external':
                    break;
            }
 
            Iif (this._input && this._label) {
                this._input.value = linkContent.text ? linkContent.text : '';
 
                this._label.dataset.value = linkContent.text
                    ? linkContent.text
                    : this._placeholder
                      ? this._placeholder
                      : '';
            }
        };
 
        return this;
    }
 
    /**
     * Sets the saver of the component.
     * @param callback The saver to set.
     * @returns The component itself.
     * @remarks The saver is called when the component save button is clicked.
     */
    public onSave(callback: (value: string) => Promise<void>): this {
        this._onSave = callback;
 
        return this;
    }
    //#endregion
 
    /**
     * Sets the suggestions list for the input element.
     * @param suggestions The suggestions to set.
     */
    private setSuggestionsList(suggestions: string[]): void {
        Iif (!this._datalist) return;
        this._datalist.innerHTML = '';
 
        suggestions.forEach((suggestion) => {
            const option = document.createElement('option');
            option.value = suggestion;
            this._datalist.appendChild(option);
        });
    }
 
    //#region Base Callbacks
    /**
     * Builds the presentation mode of the component.
     */
    private build(): void {
        this._link = document.createElement('a');
        this._presentationContainer.appendChild(this._link);
 
        this._link.title = this._title;
        this._link.classList.add('editable-data-view');
        this._link.classList.add('link-presentation');
 
        switch (this._linkType) {
            case 'tag':
                this._link.classList.add('tag');
                this._link.target = '_blank';
                this._link.rel = 'noopener';
                break;
            case 'file':
                this._link.setAttribute('data-tooltip-position', 'top');
                this._link.classList.add('internal-link');
                this._link.target = '_blank';
                this._link.rel = 'noopener';
                break;
            case 'external':
                break;
        }
 
        this._onPresentation?.(this._value);
    }
 
    /**
     * Builds the input mode of the component.
     */
    private buildInput(): void {
        this._label = document.createElement('label');
        this._label.title = this._title;
        this._dataInputContainer.appendChild(this._label);
        this._label.classList.add('editable-data-view');
        this._label.classList.add('text-input-sizer');
 
        this._input = document.createElement('input');
        this._label.appendChild(this._input);
        this._input.classList.add('editable-data-view');
        this._input.classList.add('text-input');
        this._input.placeholder = this._placeholder ? this._placeholder : '';
 
        this._component.registerDomEvent(this._input, 'input', () => {
            this._label.dataset.value = this._input.value
                ? this._input.value
                : this._placeholder
                  ? this._placeholder
                  : '';
 
            Iif (
                this._suggester &&
                this._label.dataset.value !== this._placeholder &&
                this._label.dataset.value !== ''
            )
                this.setSuggestionsList(this._suggester(this._input.value));
        });
 
        this._component.registerDomEvent(
            this._input,
            'keydown',
            (event: KeyboardEvent) => {
                if (event.key === 'Enter') {
                    this.saveChanges();
                } else Iif (event.key === 'Escape') {
                    this.disableEditMode();
                }
            },
        );
 
        Iif (
            (this._suggestions && this._suggestions.length > 0) ||
            this._suggester
        ) {
            const id = Math.random().toString(36).substring(2, 10);
            this._input.setAttribute('list', id);
            this._datalist = document.createElement('datalist');
            this._datalist.id = id;
            this._input.appendChild(this._datalist);
            this.setSuggestionsList(this._suggestions);
        }
    }
 
    /**
     * Enables the edit mode of the component.
     */
    private enableEdit(): void {
        this._onPresentation?.(this._value);
        this._input.focus();
        this._input.select();
    }
 
    /**
     * Disables the edit mode of the component.
     */
    private disableEdit(): void {
        this._onPresentation?.(this._value);
    }
 
    /**
     * Saves the changes made to the component.
     */
    private async save(): Promise<void> {
        this._value = this._input.value;
        await this._onSave?.(this._value);
    }
    //#endregion
}
 
Zur TypeDoc-Dokumentation