summaryrefslogtreecommitdiffstats
path: root/polygerrit-ui/app/elements/shared/gr-lib-loader/gr-lib-loader.ts
blob: fe69a322aed27bbcc56865c81bfc28407f0620dc (plain)
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
/**
 * @license
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

export interface LibraryConfig {
  /** Path to the library to be loaded. */
  src: string;
  /**
   * Optional check to see if the library has already been loaded outside of
   * this class. If this returns true, src will not be loaded, but
   * configureCallback will be run if present.
   */
  checkPresent?: () => boolean;
  /**
   * Optional library initialization to be run once after loading the library,
   * before resolving promises for getLibrary(). Promises returned from
   * getLibrary() will resolve to the return value of this function, if any.
   */
  configureCallback?: () => unknown;
}

export class GrLibLoader {
  /*
   * Pending library loads, keyed by library config, populated when getLibrary()
   * is first called for a given config. This retains the promise for each
   * library so that later calls of getLibrary() for the same config can
   * directly return a resolved promise.
   */
  private readonly libraries = new Map<LibraryConfig, Promise<unknown>>();

  _getPath(src: string) {
    const root = this._getLibRoot();
    return root ? root + src : null;
  }

  getLibrary(config: LibraryConfig): Promise<unknown> {
    if (!this.libraries.has(config)) {
      const loaded =
        config.checkPresent && config.checkPresent()
          ? Promise.resolve()
          : this._loadScript(this._getPath(config.src));
      const configured = loaded.then(() =>
        config.configureCallback ? config.configureCallback() : undefined
      );
      this.libraries.set(config, configured);
    }
    return this.libraries.get(config)!;
  }

  /**
   * Get the resource path used to load the application. If the application
   * was loaded through a CDN, then this will be the path to CDN resources.
   */
  _getLibRoot() {
    if (window.STATIC_RESOURCE_PATH) {
      return window.STATIC_RESOURCE_PATH + '/';
    }
    return '/';
  }

  /**
   * Load and execute a JS file from the lib root.
   *
   * @param src The path to the JS file without the lib root.
   * @return a promise that resolves when the script's onload
   * executes.
   */
  _loadScript(src: string | null) {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');

      if (!src) {
        reject(new Error('Unable to load blank script url.'));
        return;
      }
      script.setAttribute('crossorigin', 'anonymous');
      script.setAttribute('src', src);
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
  }
}