All files / src/display SkillsDisplayJS.js

92.7% Statements 127/137
79.48% Branches 62/78
95.83% Functions 23/24
92.7% Lines 127/137

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                                            1x   1x 1x         42x 42x 42x 42x 42x 42x         5x       2x 2x         19x         19x 19x 19x 1x 1x   19x 2x     17x 17x   17x 17x                               17x 17x 17x   17x 17x 17x     17x 17x   17x   11x 11x 11x               11x 11x 1x 1x 1x 1x   11x 3x 3x 2x   3x 3x 3x 3x 3x   11x 5x 5x 5x 4x 4x     4x 4x 4x 4x       4x         5x 3x   3x 1x 1x 1x   1x 1x   2x 1x   2x           11x 2x 2x 2x 1x   1x 1x     1x   1x 1x 1x         17x 17x       17x 17x 17x 17x 16x 16x   1x 1x     1x   1x 1x 1x 1x 1x             4x   4x 4x       1x 1x 1x       95x       18x       18x       3x       94x 94x 94x 94x       2x 2x 2x       2x 2x 1x   1x 1x 1x   2x 2x 2x 2x      
/*
 * Copyright 2025 SkillTree
 *
 * 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
 *
 *     https://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.
 */
import Postmate from 'postmate';
import log from 'js-logger';
 
import SkillsConfiguration from '../config/SkillsConfiguration';
import ErrorPageUtils from './ErrorPageUtils';
import skillsService from '../SkillsService';
 
let uniqueId = 0;
let popstateListener;
const skillsClientDisplayPath = 'skillsClientDisplayPath';
const markedForDestruction = [];
 
export default class SkillsDisplayJS {
  /* eslint-disable object-curly-newline */
  constructor({ options, theme, version, handleRouteChanged, userId } = {}) {
    log.debug(`SkillsClient::SkillsDisplayJS::Constructing with options [${options}], theme [${theme}], version [${version}], userId [${userId}]`);
    this._options = { ...{ }, ...options };
    this._theme = theme;
    this._version = version;
    this._handleRouteChanged = handleRouteChanged;
    this._userId = userId;
  }
 
  /* eslint-disable class-methods-use-this */
  currentIframeId() {
    return uniqueId;
  }
 
  navigate(path = this.skillsDisplayPath, skipParentHistory = true, replace = true) {
    Eif (this._childFrame && !(path == null)) {
      this._childFrame.call('navigate', { path, replace, query: { skipParentHistory } });
    }
  }
 
  attachTo(selectorOrElement) {
    Iif (SkillsConfiguration.isDisabled()) {
      log.info('SkillsClient::SkillsDisplayJS::attachTo: SkillsConfiguration is disabled Skills Display will not be initialized');
      return;
    }
 
    log.info(`SkillsClient::SkillsDisplayJS::attaching to [${selectorOrElement ? selectorOrElement.toString() : selectorOrElement}]`);
    let iframeContainer = selectorOrElement;
    if (typeof selectorOrElement === 'string') {
      iframeContainer = document.querySelector(selectorOrElement);
      log.debug(`SkillsClient::SkillsDisplayJS::document.querySelector returned [${iframeContainer ? iframeContainer.toString() : iframeContainer}]`);
    }
    if (!iframeContainer) {
      throw new Error(`Can't find element with selector='${selectorOrElement ? selectorOrElement.toString() : selectorOrElement}'`);
    }
 
    uniqueId += 1;
    const className = `client-display-iframe-${uniqueId}`;
 
    const minHeight = this.options.isSummaryOnly ? 600 : 960;
    const handshake = new Postmate({
      container: iframeContainer,
      url: `${this.configuration.serviceUrl}/static/clientPortal/index.html`,
      classListArray: [className],
      model: {
        serviceUrl: this.configuration.serviceUrl,
        projectId: this.configuration.projectId,
        version: this.version,
        userId: this.configuration.authenticator === 'pki' ? this.userId : null,
        theme: this.theme,
        options: this.options,
        minHeight: `${minHeight}px`,
        isSummaryOnly: this.options.isSummaryOnly,
        internalBackButton: this.options.internalBackButton == null ? false : this.options.internalBackButton,
      },
    });
    const iframe = document.querySelector(`.${className}`);
    iframe.setAttribute('style', 'border: 0; height: 100%; width: 100%');
    iframe.setAttribute('aria-label', 'SkillTree Skills Display')
 
    iframeContainer.height = 0;
    iframeContainer.style.height = '0px';
    popstateListener = () => {
      this.navigate(this.skillsDisplayPath || '/', true);
    };
    window.addEventListener('popstate', popstateListener);
    window.addEventListener('hashchange', popstateListener);
 
    handshake.then((child) => {
      // make sure this frame has not already been marked for destruction
      const childFrameClassName = child.frame.className;
      const index = markedForDestruction.indexOf(childFrameClassName);
      Iif (index > -1) {
        log.info(`SkillsClient::SkillsDisplayJS::handshake: child frame [${childFrameClassName}] already marked for destruction, not initializing.`);
        if (child) {
          child.destroy();
          markedForDestruction.splice(index, 1);
        }
        return;
      }
      this._childFrame = child;
      child.on('height-changed', (data) => {
        log.debug(`SkillsClient::SkillsDisplayJS::height-changed: data [${data}]`);
        const adjustedHeight = Math.max(data, minHeight);
        iframeContainer.height = adjustedHeight;
        iframeContainer.style.height = `${adjustedHeight}px`;
      });
      child.on('do-scroll', (data) => {
        let additionalOffset = 0;
        if (this.options.scrollTopOffset) {
          additionalOffset = this.options.scrollTopOffset;
        }
        const fromTopToIframe = Math.max(iframe.getBoundingClientRect().top, 0);
        const withinIframe = data;
        const toScroll = fromTopToIframe + withinIframe - additionalOffset;
        log.debug(`do-scroll fromTopToIframe=[${fromTopToIframe}], withinIframe=[${withinIframe}], additionalOffset=[${additionalOffset}], toScroll=[${toScroll}]`);
        window.scroll({ top: toScroll, behavior: 'smooth' });
      });
      child.on('route-changed', (params) => {
        const newPath = params ? params.path : null;
        log.debug(`SkillsClient::SkillsDisplayJS::route-changed - newPath [${newPath}]`);
        if (!(newPath == null)) {
          const routePath = newPath.endsWith('index.html') ? '/' : newPath;
          Eif (this._shouldUpdateHistory(params)) {
            // put the new path in the URL so that when the page is reloaded or
            // sent as a link the proper route will be set in the child iframe
            const queryParams = new URLSearchParams(window.location.search);
            queryParams.set(skillsClientDisplayPath, routePath);
            const newUrl = `${window.location.pathname}?${queryParams.toString()}${window.location.hash}`;
            window.history.pushState({ skillsClientDisplayPath: newPath }, '', newUrl);
          }
 
          // if the client has configured a handleRouteChanged call back, invoke it
          Iif (this._handleRouteChanged) {
            this._handleRouteChanged(routePath);
          }
        }
 
        if (!this.options.disableAutoScroll) {
          let scrollToElement = iframeContainer;
 
          if (this.options.autoScrollStrategy === 'top-offset') {
            let providedOffset = 0;
            Eif (this.options.scrollTopOffset) {
              providedOffset = this.options.scrollTopOffset;
            }
            const scrollToOffset = scrollToElement.offsetTop - providedOffset;
            window.scroll({ top: scrollToOffset, behavior: 'smooth' });
          } else {
            if (this.options.autoScrollStrategy === 'top-of-page') {
              scrollToElement = document.querySelector('body');
            }
            scrollToElement.scrollIntoView({
              behavior: 'smooth',
            });
          }
        }
      });
      child.on('needs-authentication', () => {
        log.debug('SkillsClient::SkillsDisplayJS::needs-authentication');
        const isPkiMode = this.configuration.authenticator === 'pki';
        if (!this.authenticationPromise && !isPkiMode) {
          this.authenticationPromise = skillsService.getAuthenticationToken(this.configuration.authenticator, this.configuration.serviceUrl, this.configuration.projectId)
            .then((result) => {
              child.call('updateAuthenticationToken', result);
              this.navigate();
            })
            .finally(() => {
              this.authenticationPromise = null;
            });
        } else Eif (isPkiMode) {
          child.call('updateAuthenticationToken', 'pki');
          this.navigate();
        }
      });
    });
 
    log.debug('SkillsClient::SkillsDisplayJS::calling _checkAndHandleServiceStatus');
    this._checkAndHandleServiceStatus(iframeContainer);
  }
 
  _checkAndHandleServiceStatus(iframeContainer) {
    this.status = SkillsConfiguration.getServiceStatus();
    Eif (!this.status) {
      log.info('SkillsClient::SkillsDisplayJS::SkillsConfiguration.configure() was not called, checking status endpoint.');
      skillsService.getServiceStatus(`${this.configuration.serviceUrl}/public/status`).then((response) => {
        this.status = response.status;
        skillsService.configureLogging(this, response);
      }).catch((error) => {
        let errorMessage = 'Please ensure the skilltree server is running';
        Iif (this.configuration.serviceUrl && this.configuration.serviceUrl.startsWith('https')) {
          errorMessage += ' and that your browser trusts the server\'s certificate';
        }
        errorMessage += `. skilltree service URL: ${this.configuration.serviceUrl}`;
        /* eslint-disable no-console */
        console.error(errorMessage);
        log.error(`SkillsClient::SkillsDisplayJS::${errorMessage}`, error);
        ErrorPageUtils.removeAllChildren(iframeContainer);
        iframeContainer.appendChild(ErrorPageUtils.buildErrorPage());
        iframeContainer.setAttribute('style', 'border: 5px; height: 20rem; width: 100%');
      });
    }
  }
 
  _shouldUpdateHistory(params) {
    // if the query param `skipParentHistory` is true then do not update the history (set to true when the user is navigating with the back/forward browser buttons)
    const updateHistoryParam = (params.query.skipParentHistory !== 'true' && params.query.skipParentHistory !== true);
    // also, allow the client app to disable this feature, but enable it by default
    const updateHistoryOption = this.options.updateHistory == null || this.options.updateHistory === true;
    return updateHistoryOption && updateHistoryParam;
  }
 
  set version(version) {
    log.info(`SkillsClient::SkillsDisplayJS::setting version [${version}]`);
    this._version = version;
    this._childFrame.call('updateVersion', version);
  }
 
  get options() {
    return this._options;
  }
 
  get theme() {
    return this._theme;
  }
 
  get version() {
    return this._version;
  }
 
  get userId() {
    return this._userId;
  }
 
  get configuration() {
    const serviceUrl = this._options.serviceUrl ? this._options.serviceUrl : SkillsConfiguration.getServiceUrl();
    const authenticator = this._options.authenticator ? this._options.authenticator : SkillsConfiguration.getAuthenticator();
    const projectId = this._options.projectId ? this._options.projectId : SkillsConfiguration.getProjectId();
    return { serviceUrl, authenticator, projectId };
  }
 
  get skillsDisplayPath() {
    const urlParams = new URLSearchParams(window.location.search);
    const clientDisplayPath = urlParams.get(skillsClientDisplayPath);
    return clientDisplayPath;
  }
 
  destroy() {
    log.info(`SkillsClient::SkillsDisplayJS::destroy called. _childFrame [${this._childFrame}]`);
    if (this._childFrame) {
      this._childFrame.destroy();
    } else {
      const childFrameClassName = `client-display-iframe-${uniqueId}`;
      log.info(`SkillsClient::SkillsDisplayJS::destroy child frame [${childFrameClassName}] not yet initialized, marking for future destruction`);
      markedForDestruction.push(childFrameClassName);
    }
    const queryParams = new URLSearchParams(window.location.search);
    queryParams.delete(skillsClientDisplayPath);
    window.removeEventListener('popstate', popstateListener);
    window.removeEventListener('hashchange', popstateListener);
  }
}