all files / component/editor/ deja-editor.component.ts

36.98% Statements 98/265
9.92% Branches 13/131
33.33% Functions 16/48
35.48% Lines 88/248
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 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556                                                                          23×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
/*
 *  @license
 *  Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
 *
 *  Use of this source code is governed by an Apache-2.0 license that can be
 *  found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
 */
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import {
    AfterViewInit,
    ChangeDetectionStrategy,
    ChangeDetectorRef,
    Component,
    ElementRef,
    EventEmitter,
    forwardRef,
    Input,
    NgZone,
    OnChanges,
    OnDestroy,
    Output,
    SimpleChanges,
    ViewChild,
    ViewEncapsulation
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
 
import { DejaEditorService } from './deja-editor.service';
 
declare var CKEDITOR: any;
 
/**
 * CKEditor component
 * Usage :
 *  <ckeditor [(ngModel)]="data" [config]="{...}" debounce="500"></ckeditor>
 */
@Component({
    selector: 'deja-editor',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => DejaEditorComponent),
            multi: true
        }
    ],
    template: require('./deja-editor.component.html'),
    styles: [require('./deja-editor.component.scss')],
    changeDetection: ChangeDetectionStrategy.OnPush,
    encapsulation: ViewEncapsulation.None
})
export class DejaEditorComponent
    implements OnChanges, AfterViewInit, OnDestroy, ControlValueAccessor {
    @Input() public config: any;
    @Input() public debounce: string;
 
    @Output() public change = new EventEmitter();
    @Output() public ready = new EventEmitter();
    @Output() public blur = new EventEmitter();
    @Output() public focus = new EventEmitter();
    @Output() public disabled = new EventEmitter<boolean>();
 
    @ViewChild('host') public host: ElementRef;
 
    private _readonly: boolean;
    private _inline = true;
 
    @Input()
    public set readonly(value: boolean) {
        this._readonly = coerceBooleanProperty(value);
    }
 
    public get readonly() {
        return this._readonly;
    }
 
    @Input()
    public set inline(value: boolean) {
        this._inline = coerceBooleanProperty(value);
    }
 
    public get inline() {
        return this._inline;
    }
 
    private _value = '';
    public instance: any;
    public debounceTimeout: any;
 
    /**
     * Constructor
     */
    constructor(
        private zone: NgZone,
        private _changeDetectorRef: ChangeDetectorRef,
        private _initializer: DejaEditorService
    ) {}
 
    public get value(): any {
        return this._value;
    }
 
    @Input()
    public set value(v) {
        if (v !== this._value) {
            this._value = v;
            this.onChange(v);
        }
    }
 
    public ngOnChanges(changes: SimpleChanges) {
        Iif (changes.readonly && this.instance) {
            this.instance.setReadOnly(changes.readonly.currentValue);
        }
    }
 
    /**
     * On component destroy
     */
    public ngOnDestroy() {
        this.focus.complete();
        this.blur.complete();
        this.change.complete();
        this.ready.complete();
        this.disabled.complete();
        if (this.instance) {
            this.instance.focusManager.blur(true);
            try {
                // Workaround for a ckEditor bug
                this.instance.destroy();
            } catch (e) {
                console.warn('Error occurred when destroying ckEditor instance');
            }
            this.instance = null;
        }
    }
 
    /**
     * On component view init
     */
    public ngAfterViewInit() {
        this._initializer.initDejaEditorLib().then(() => {
            this.ckeditorInit(this.config || {});
            // Effectively display the editor even if parents component ChangeDetectionStrategy is OnPush
            setTimeout(() => this._changeDetectorRef.markForCheck());
        });
    }
 
    /**
     * Value update process
     */
    public updateValue(value: any) {
        this.zone.run(() => {
            if (!value) {
                value = null;
            }
            if (this.value !== value) {
                this.value = value;
 
                this.onChange(value);
                this.change.emit(value);
            }
        });
    }
 
    public textAreaChange() {
        this.zone.run(() => {
            const value = this.host.nativeElement.value;
 
            this.onChange(value);
            this.change.emit(value);
        });
    }
 
    /**
     * CKEditor init
     */
    public ckeditorInit(config: any) {
        Iif (typeof CKEDITOR === 'undefined') {
            console.warn('CKEditor 4.x is missing (http://ckeditor.com/)');
        } else {
            // Check textarea exists
            Iif (this.instance) {
                return;
            }
 
            Iif (this.readonly) {
                config.readOnly = this.readonly;
            }
 
            const keyEvents = config.on && config.on.key;
            Eif (!config.on) {
                config.on = {};
            }
            config.on.key = (event: any) => {
                // Override CTRL+A event. Native one cause editor switch on first try
                if (event.data.keyCode === 1114177) {
                    // CTRL + A
                    event.cancel();
                    event.stop();
                    this.instance.document.$.execCommand('SelectAll');
                }
                if (keyEvents) {
                    keyEvents(event);
                }
            };
            // CKEditor replace textarea
            Eif (this.inline) {
                this.instance = CKEDITOR.inline(
                    this.host.nativeElement,
                    config
                );
            } else {
                this.instance = CKEDITOR.replace(
                    this.host.nativeElement,
                    config
                );
            }
 
            // Set initial value
            this.instance.setData(this.value);
 
            // listen for instanceReady event
            this.instance.on('instanceReady', (evt: any) => {
                // send the evt to the EventEmitter
                this.ready.emit(evt);
            });
 
            // CKEditor change event
            this.instance.on('change', () => {
                const value = this.instance.getData();
 
                // Debounce update
                if (this.debounce) {
                    if (this.debounceTimeout) {
                        clearTimeout(this.debounceTimeout);
                    }
                    this.debounceTimeout = setTimeout(() => {
                        this.updateValue(value);
                        this.debounceTimeout = null;
                    }, parseInt(this.debounce, 10));
 
                    // Live update
                } else {
                    this.updateValue(value);
                }
            });
 
            // CKEditor blur event
            this.instance.on('blur', (evt: any) => {
                this.blur.emit(evt);
                this.onTouched();
            });
 
            // CKEditor focus event
            this.instance.on('focus', (evt: any) => {
                if (!this.readonly) {
                    this.focus.emit(evt);
                }
            });
        }
    }
 
    /**
     * Implements ControlValueAccessor
     */
    public writeValue(value: any) {
        this._value = value;
        Iif (this.instance) {
            this.instance.setData(value);
        } else {
            this.host.nativeElement.value = value;
        }
    }
 
    public onChange(_: any) {}
 
    public onTouched() {}
 
    public registerOnChange(fn: any) {
        this.onChange = fn;
    }
 
    public registerOnTouched(fn: any) {
        this.onTouched = fn;
    }
 
    public setDisabledState(isDisabled: boolean) {
        this.readonly = isDisabled;
        this.disabled.next(isDisabled);
        if (this.instance) {
            this.instance.setReadOnly(isDisabled);
        }
    }
 
    /**
     * Return the word at cursor position.
     *  - If the cursor is at the end of a word, it return that word.
     *  - If the cursor is at the begining of a word, it return that word.
     *  - If the cursor is in the middle of a word, it return that word.
     *  - If there are no word nearly the cursor, return null
     */
    public getWordAtCursor(): string {
        const range = this.instance.getSelection().getRanges(true)[0];
        const word = this._firstTextNode(range);
        return (word && word.toReplace) || null;
    }
 
    public hasActiveSelection(): boolean {
        return !!this.getSelectedText();
    }
 
    public getSelectedText(): string {
        const selection = this.instance.getSelection();
        return selection.getSelectedText();
    }
 
    /**
     * Replace the content of the editor.
     *  - If there is an active selection, replace this selection
     *  - If the editor is empty, simply insert the text
     *  - If the cursor is near a word, replace this word with the text
     *  - If there is no selection, no word near the cursor, simply insert the text at the cursor position
     * @param replace the string to replace with
     */
    public replace(replace: string): void {
        if (!replace) {
            return;
        }
        const selection = this.getSelectedText();
        if (selection) {
            // Focus is used during the CKEDITOR insertText process and cause deselection of the selected text
            // So we temporarily deactivate it
            const focus = this.instance.focus;
            this.instance.focus = () => {};
            this.instance.insertText(replace);
            this.instance.focus = focus;
            return;
        }
        const range = this.instance.getSelection().getRanges(true)[0];
        if (!range) {
            this.instance.insertText(replace);
            return;
        }
        const text = this._firstTextNode(range);
        if (text) {
            this._replaceWord(text, replace);
        } else {
            this.instance.insertText(replace);
        }
        this.setFocus();
    }
 
    public setFocus(): void {
        if (this.instance) {
            this.instance.focus();
        } else {
            this.host.nativeElement.focus();
        }
    }
 
    private _hasTextNodeAsChild(node: any, reverse = false): any {
        const children: any[] = node.getChildren().toArray();
        if (reverse) {
            for (let i = children.length - 1; i >= 0; i--) {
                const child = children[i];
                if (child.type === CKEDITOR.NODE_TEXT) {
                    return child;
                } else {
                    const inChild = this._hasTextNodeAsChild(child);
                    if (inChild) {
                        return inChild;
                    }
                }
            }
        } else {
            for (const child of children) {
                if (child.type === CKEDITOR.NODE_TEXT) {
                    return child;
                } else {
                    const inChild = this._hasTextNodeAsChild(child);
                    if (inChild) {
                        return inChild;
                    }
                }
            }
        }
        return null;
    }
 
    private _mergeTextNodeAroundWithDirection(
        textNode: any,
        reverse = false
    ): void {
        const toRemove = [];
        let newText = textNode.getText();
        let x = textNode;
        while ((x = reverse ? x.getPrevious() : x.getNext)) {
            if (
                x.type !== CKEDITOR.NODE_TEXT ||
                x
                    .getText()
                    .charAt(reverse ? x.getText().length - 1 : 0)
                    .match(/[\s,;.:!?]/)
            ) {
                break;
            }
            if (reverse) {
                newText = x.getText() + newText;
            } else {
                newText += x.getText();
            }
            toRemove.push(x);
        }
        if (toRemove.length > 0) {
            textNode.setText(newText);
            toRemove.forEach(node => node.remove());
        }
    }
 
    private _mergeTextNodeAround(textNode: any): any {
        this._mergeTextNodeAroundWithDirection(textNode, true);
        this._mergeTextNodeAroundWithDirection(textNode);
        return textNode;
    }
 
    private _firstNonEmptyTextNode(node: any, reverse = false): any {
        let x = node;
        while ((x = reverse ? x.getPrevious() : x.getNext())) {
            if (x.type === CKEDITOR.NODE_TEXT) {
                if (x.getText() !== '') {
                    return x;
                }
            } else {
                return x;
            }
        }
    }
 
    private _trim(text: string): string {
        if (text) {
            text = text.replace(/[\u200b\u00A0]/g, '').trim();
        }
        return text;
    }
 
    private _extractFirstWord(text: string, reverse = false): string {
        if (!text) {
            return text;
        }
        if (text.indexOf(' ') !== -1) {
            const spaceSplit = text.split(' ');
            return this._trim(spaceSplit[reverse ? spaceSplit.length - 1 : 0]);
        } else {
            return this._trim(text);
        }
    }
 
    private _firstTextNodeResult(
        selectedNode: any,
        reverse = false,
        firstNodeIsText = false
    ): {
        textNode: any;
        firstNodeIsText: boolean;
        toReplace: string;
    } {
        if (this._trim(selectedNode.getText())) {
            const node = this._mergeTextNodeAround(selectedNode);
            return {
                textNode: node,
                firstNodeIsText: firstNodeIsText,
                toReplace: this._extractFirstWord(node.getText(), reverse)
            };
        }
        return null;
    }
 
    private _firstTextNodeWithDirection(
        range: any,
        reverse = false
    ): {
        textNode: any;
        firstNodeIsText: boolean;
        toReplace: string;
    } {
        const startContainer: any = range.startContainer;
        if (reverse && startContainer.type === CKEDITOR.NODE_TEXT) {
            return this._firstTextNodeResult(startContainer, reverse, true);
        }
        const startNode: any =
            startContainer.type === CKEDITOR.NODE_TEXT
                ? reverse
                    ? this._firstNonEmptyTextNode(startContainer, true)
                    : this._firstNonEmptyTextNode(startContainer)
                : startContainer.getChildren().getItem(range.startOffset - 1);
        if (startNode) {
            if (startNode.type === CKEDITOR.NODE_TEXT) {
                return this._firstTextNodeResult(startNode, reverse);
            }
            let x = this._hasTextNodeAsChild(startNode, reverse);
            if (x) {
                return this._firstTextNodeResult(x, reverse);
            }
            x = startNode;
            while ((x = reverse ? x.getPrevious() : x.getNext())) {
                if (x.type === CKEDITOR.NODE_TEXT) {
                    return this._firstTextNodeResult(x, reverse);
                }
                const textNode = this._hasTextNodeAsChild(x, reverse);
                if (textNode) {
                    return this._firstTextNodeResult(textNode, reverse);
                }
            }
        }
        return null;
    }
 
    private _firstTextNode(
        range: any
    ): { textNode: any; firstNodeIsText: boolean; toReplace: string } {
        let textNode: {
            textNode: any;
            firstNodeIsText: boolean;
            toReplace: string;
        } = this._firstTextNodeWithDirection(range, true);
        if (!textNode) {
            textNode = this._firstTextNodeWithDirection(range);
        }
        return textNode;
    }
 
    private _replaceWord(
        node: { textNode: any; firstNodeIsText: boolean; toReplace: string },
        replace: string
    ): void {
        const split = node.textNode.getText().split(node.toReplace);
        node.textNode.setText(split[0]);
        const newElement = CKEDITOR.dom.element.createFromHtml(
            `<span>${CKEDITOR.tools.transformPlainTextToHtml(
                replace,
                CKEDITOR.ENTER_BR
            )}</span>`
        );
        newElement.insertAfter(node.textNode);
        if (split.length === 2 && split[1]) {
            const end = new CKEDITOR.dom.text(split[1]);
            end.insertAfter(newElement);
        }
        this.instance.getSelection().selectElement(node.textNode);
        const tmpRange = this.instance.getSelection().getRanges()[0];
        tmpRange.setStartAfter(node.textNode);
        tmpRange.select();
    }
}