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

0% Statements 0/117
0% Branches 0/127
0% Functions 0/21
0% Lines 0/117

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { Component } from 'obsidian';
import CustomizableRenderChild from 'src/libs/CustomizableRenderChild/CustomizableRenderChild';
 
/**
 * A suggestion.
 */
export interface Suggestion {
    value: string;
    label: string;
}
 
/**
 * A list of suggestions.
 */
export type Suggestions = Suggestion[];
 
/**
 * A cursor position.
 * @remarks - The cursor position can be a number, 'start' or 'end'.
 * @see {@link SuggestionComponent.getCursorPositionNumber}
 */
type CursorPosition = number | 'start' | 'end';
/**
 * Represents a suggestion component.
 */
export default class SuggestionComponent {
    private readonly _component: Component;
    private _suggester: ((value: string) => Suggestions) | undefined;
 
    private _suggestionsContainer: HTMLSpanElement;
    private readonly _inputElement: HTMLElement;
 
    private _suggestions: Suggestions;
    private _activeSuggestions: Suggestions;
    private _suggestorChild: CustomizableRenderChild | undefined;
    private _suggestionIndex = 0;
    private _isScrollModeActive: boolean;
 
    /**
     * Creates a new instance of the suggestion component.
     * @param inputElement The input element to register the suggestor to.
     * @param component The component to register the suggestor to.
     * @remarks - The input element should have a parent element, on which the suggestions container is appended.
     */
    constructor(inputElement: HTMLElement, component: Component) {
        this._inputElement = inputElement;
        this._component = component;
    }
 
    /**
     * Sets the suggestions.
     * @param suggestions The suggestions to set.
     * @returns The component itself.
     * @remarks If the suggestions are set, a suggestor is not needed.
     */
    public setSuggestions(suggestions: Suggestions): this {
        this._suggestions = suggestions;
 
        return this;
    }
 
    /**
     * Sets the suggester.
     * @param suggester The suggester to set.
     * @returns The component itself.
     * @remarks If the suggester is set, the suggestions are not needed and will be ignored.
     */
    public setSuggester(suggester: (value: string) => Suggestions): this {
        this._suggester = suggester;
 
        return this;
    }
 
    /**
     * Initializes the suggestion component.
     */
    private setSuggestion(): void {
        let suggestion: Suggestion | undefined;
 
        if (!this._isScrollModeActive) {
            // If the scroll mode is disabled, the first suggestion is shown.
            // The first suggestion is the suggestion that starts with the text in the input element. (case insensitive)
            suggestion = this._activeSuggestions
                .filter((suggestion) =>
                    suggestion.value
                        .toLowerCase()
                        .startsWith(
                            this._inputElement.textContent?.toLowerCase() ?? '',
                        ),
                )
                .first();
            this._suggestionIndex = 0;
        } else {
            // In scroll mode, the suggestion at the index is displayed. This index can be changed beforehand using the arrow buttons.
            const index = this._suggestionIndex;
 
            if (index < 0) {
                suggestion = this._activeSuggestions.last();
                this._suggestionIndex = this._activeSuggestions.length - 1;
            } else if (index >= this._activeSuggestions.length) {
                suggestion = this._activeSuggestions.first();
                this._suggestionIndex = 0;
            } else {
                suggestion = this._activeSuggestions[index];
                this._suggestionIndex = index;
            }
        }
 
        Iif (suggestion) {
            if (
                suggestion.value
                    .toLowerCase()
                    .startsWith(
                        this._inputElement.textContent?.toLowerCase() ?? '',
                    )
            ) {
                // If the suggestion starts with the text in the input element, the text in the input element is adopted.
                const suggestionText = suggestion.value.slice(
                    this.inputTextLength,
                );
                this._suggestionsContainer.innerText = suggestionText;
            } else {
                // If the suggestion does not start with the text in the input element, the text in the input element is replaced with the suggestion.
                const length = this._inputElement.textContent?.length ?? 1;
 
                this._inputElement.textContent = suggestion.value.slice(
                    0,
                    length,
                );
 
                this._suggestionsContainer.innerText =
                    suggestion.value.slice(length);
                this.setInputCursorAbsolutePosition(length);
            }
        }
 
        if (this._activeSuggestions.length > 0) {
            this._suggestionsContainer.style.display = '';
        } else {
            this._suggestionsContainer.style.display = 'none';
        }
    }
 
    /**
     * Refreshes the active suggestions.
     */
    private refreshActiveSuggestions(): void {
        this._activeSuggestions = this._suggester
            ? this._suggester(this._inputElement.textContent ?? '')
            : this._suggestions;
    }
 
    /**
     * Enables the suggestor.
     * @remarks Run this, if you want to enable the suggestor. (e.g. on enable edit mode)
     * @remarks - The suggestor is a child of the component.
     * - The suggestor is used to display the suggestions.
     * - The suggestor has the css class `suggestions-container`.
     * - The suggestor is loaded and registered to the input element.
     */
    public enableSuggestior(): void {
        this._suggestorChild = new CustomizableRenderChild(
            this._suggestionsContainer,
        );
        this._suggestorChild.load();
        this._component.addChild(this._suggestorChild);
 
        // Set the cursor to the end of the input element.
        this.setInputCursorAbsolutePosition('end');
 
        this.buildSuggestionsContainer();
 
        this._suggestorChild.registerDomEvent(
            this._inputElement,
            'input',
            this.onInput.bind(this),
        );
 
        this._suggestorChild.registerDomEvent(
            this._inputElement,
            'keydown',
            this.onKeydown.bind(this),
        );
    }
 
    /**
     * Handles the input event for the suggestion component.
     * @remarks Disables the scroll mode, refreshes the active suggestions, and sets the suggestion.
     */
    private onInput(): void {
        // Disable the scroll mode.
        this._isScrollModeActive = false;
 
        // Refresh the active suggestions and the shown suggestion.
        this.refreshActiveSuggestions();
        this.setSuggestion();
    }
 
    /**
     * Handles the keydown event for the suggestion component.
     * @param event The keyboard event.
     * @remarks - The 'ArrowUp' and 'ArrowDown' buttons are used to scroll through the suggestions.
     * - The 'ArrowLeft' and 'ArrowRight' buttons are used to move the cursor in the input element.
     * If the cursor is at the end of the input element, the first character of the suggestions container is adopted.
     * - The 'Tab' button is used to adopt the complete suggestion.
     * - The 'Ctrl' + 'a' button is used to select the text in the input element.
     */
    private onKeydown(event: KeyboardEvent): void {
        if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
            // If the 'ArrowUp' or 'ArrowDown' button is pressed, the suggestions are scrolled through.
            event.preventDefault();
 
            this._isScrollModeActive = true;
 
            if (event.key === 'ArrowUp') {
                this._suggestionIndex++;
            } else Iif (event.key === 'ArrowDown') {
                this._suggestionIndex--;
            }
            // Refresh the shown suggestion.
            this.setSuggestion();
        } else if (event.key === 'ArrowLeft') {
            // If the 'ArrowLeft' button is pressed, the cursor is moved to the left.
            event.preventDefault();
 
            this.setInputCursorRelativePosition(-1);
 
            this.refreshActiveSuggestions();
        } else if (event.key === 'ArrowRight') {
            // If the 'ArrowRight' button is pressed, the cursor is moved to the right.
            event.preventDefault();
 
            // If the cursor is at the end of the input element, the first character of the suggestions container is adopted.
            this.adoptSuggestionCharacter()
                ? this.setInputCursorAbsolutePosition(this.inputTextLength)
                : this.setInputCursorRelativePosition(1);
 
            this.refreshActiveSuggestions();
        } else if (event.key === 'Tab') {
            // If the 'Tab' button is pressed, the complete suggestion is adopted.
            event.preventDefault();
 
            this.adoptSuggestion();
        } else Iif (event.ctrlKey && event.key === 'a') {
            // If the 'Ctrl' + 'a' button is pressed, the text in the input element is selected.
            event.preventDefault();
 
            this.selectText(0, 'end');
        }
    }
 
    /**
     * Adopts the complete suggestion in the suggestions container.
     */
    private adoptSuggestion(): void {
        this._inputElement.textContent += this._suggestionsContainer.innerText;
 
        const suggestion = this._activeSuggestions.find((suggestion) =>
            suggestion.value
                .toLowerCase()
                .startsWith(
                    this._inputElement.textContent?.toLowerCase() ?? '',
                ),
        );
 
        this._inputElement.textContent = suggestion
            ? suggestion.value
            : this._inputElement.textContent;
        this._suggestionsContainer.innerText = '';
        this.setInputCursorAbsolutePosition('end');
    }
 
    /**
     * Adopts the first character of the suggestions container if the cursor is at the end of the input element.
     * @returns `true` if the character was adopted, otherwise `false`.
     */
    private adoptSuggestionCharacter(): boolean {
        Iif (this.cursorPosition === this.inputTextLength) {
            this._inputElement.textContent +=
                this._suggestionsContainer.innerText.slice(0, 1);
 
            this._suggestionsContainer.innerText =
                this._suggestionsContainer.innerText.slice(1);
 
            return true;
        }
 
        return false;
    }
 
    /**
     * Returns the length of the text in the input element.
     */
    private get inputTextLength(): number {
        return this._inputElement.textContent?.length ?? 0;
    }
 
    /**
     * Returns the current cursor position in the input element.
     */
    private get cursorPosition(): number {
        const selection = window.getSelection();
 
        Iif (selection && selection.rangeCount > 0) {
            const currentRange = selection.getRangeAt(0);
 
            return currentRange.endOffset;
        }
 
        return 0;
    }
 
    /**
     * Sets the cursor position relative to the current cursor position.
     * @param relativPosition Relative position to set the cursor to.
     * @remarks The position is clamped to the length of the input element and minimum 0.
     */
    private setInputCursorRelativePosition(relativPosition: number): void {
        this.setInputCursorAbsolutePosition(
            this.cursorPosition + relativPosition,
        );
    }
 
    /**
     * Sets the cursor position in the input element.
     * @param position Position to set the cursor to.
     * @remarks The position is clamped to the length of the input element.
     */
    private setInputCursorAbsolutePosition(position: CursorPosition): void {
        position = this.getCursorPositionNumber(position);
 
        const selection = window.getSelection();
        const range = document.createRange();
 
        Iif (selection && selection.rangeCount > 0) {
            const safePosition = Math.max(
                0,
                Math.min(position, this._inputElement.textContent?.length ?? 0),
            );
 
            Iif (this._inputElement.firstChild) {
                range.setStart(this._inputElement.firstChild, safePosition);
                range.setEnd(this._inputElement.firstChild, safePosition);
            }
 
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }
 
    /**
     * Returns the cursor position as a number.
     * @param position Position to convert. Can be a number, 'start' or 'end'.
     * @returns The cursor position as a number.
     */
    private getCursorPositionNumber(position: CursorPosition): number {
        if (position === 'start') {
            position = 0;
        } else Iif (position === 'end') {
            position = Number.MAX_SAFE_INTEGER;
        }
 
        return position;
    }
 
    /**
     * Selects the text in the input element.
     * @param startPosition Start position of the selection.
     * @param endPosition End position of the selection.
     */
    private selectText(
        startPosition: CursorPosition,
        endPosition: CursorPosition,
    ): void {
        startPosition = this.getCursorPositionNumber(startPosition);
        endPosition = this.getCursorPositionNumber(endPosition);
 
        const selection = window.getSelection();
        const range = document.createRange();
 
        Iif (selection && this._inputElement.firstChild) {
            const safeStartPosition = Math.max(
                0,
                Math.min(
                    startPosition,
                    this._inputElement.textContent?.length ?? 0,
                ),
            );
 
            const safeEndPosition = Math.max(
                0,
                Math.min(
                    endPosition,
                    this._inputElement.textContent?.length ?? 0,
                ),
            );
 
            range.setStart(this._inputElement.firstChild, safeStartPosition);
            range.setEnd(this._inputElement.firstChild, safeEndPosition);
 
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }
 
    /**
     * Builds the suggestions container.
     * @remarks - The suggestions container is a span element that is appended to the parent of the input element.
     * - The suggestions container is used to display the suggestions.
     * - The suggestions container has a click event listener that sets the cursor to the end of the input element.
     * - The suggestions container has the css classes `editable-data-view` & `suggestions-container`.
     */
    private buildSuggestionsContainer(): void {
        this._suggestionsContainer = document.createElement('span');
 
        this._suggestionsContainer.classList.add(
            'editable-data-view',
            'suggestions-container',
        );
 
        this._inputElement.parentElement?.appendChild(
            this._suggestionsContainer,
        );
 
        // On click on the suggestions container, the cursor should be set to the end of the input element.
        this._suggestorChild?.registerDomEvent(
            this._suggestionsContainer,
            'click',
            () => {
                this.setInputCursorAbsolutePosition('end');
            },
        );
    }
 
    /**
     * Disables the suggestor.
     * @remarks Run this, if you want to disable the suggestor. (e.g. on disable edit mode)
     * @remarks Removes the suggestions container and unload the suggestor child.
     */
    public disableSuggestor(): void {
        this._suggestorChild?.unload();
        this._suggestionsContainer.remove();
    }
}
 
Zur TypeDoc-Dokumentation