all files / component/monaco-editor/ monaco-editor.service.ts

96.3% Statements 26/27
70% Branches 7/10
100% Functions 7/7
95.83% Lines 23/24
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                                                                                           
/*
 *  @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 { Injectable } from '@angular/core';
 
/**
 * Monaco Editor Service
 *
 * Service used by Monaco Editor Component to load only once instance of the Monaco Editor Library
 */
@Injectable()
export class MonacoEditorService {
 
    private _loading: boolean;
    private _loader: Promise<any>;
 
    /**
     * Constructor
     */
    constructor() { }
 
    /**
     * Load the Monaco Editor Library
     *
     * @return Resolved promise when the library is loaded
     */
    public initMonacoLib(): Promise<any> {
        Eif (!this._loading) {
            this.init();
        }
 
        return this._loader;
    }
 
    private init() {
        this._loader = new Promise((resolve) => {
            this._loading = true;
            const baseElement = document.getElementsByTagName('base')[0] || {} as HTMLBaseElement;
            const baseHref = baseElement.href;
            const basePath = (<any>window).MONACOEDITOR_BASEPATH || `${baseHref}assets/monaco/vs`;
 
            const onGotAmdLoader = () => {
                // Load monaco
                (<any>window).require.config({ paths: { 'vs': basePath } });
                (<any>window).require(['vs/editor/editor.main'], () => {
                    resolve();
                });
            };
 
            // Load AMD loader if necessary
            Eif (!(<any>window).require && !(<any>window).monaco) {
                const loaderScript = document.createElement('script');
                loaderScript.type = 'text/javascript';
                loaderScript.src = `${basePath}/loader.js`;
                loaderScript.addEventListener('load', onGotAmdLoader);
                document.body.appendChild(loaderScript);
            } else {
                onGotAmdLoader();
            }
        });
    }
}