superdesk/superdesk-client-core

View on GitHub
scripts/index.ts

Summary

Maintainability
B
4 hrs
Test Coverage
// extract-text-webpack-plugin messes up the import order
// when importing from SCSS files, but it works when importing from js
// if you need some styles to go at the top/bottom, import it here

import 'app.scss'; // styles

import 'jquery-jcrop/css/jquery.Jcrop.css';
import 'jquery-ui/themes/smoothness/jquery-ui.css';
import 'owl.carousel/dist/assets/owl.carousel.min.css';
import 'superdesk-ui-framework/dist/superdesk-ui.bundle.css';

import 'vendor';
import 'core';
import 'templates-cache.generated'; // generated by grunt 'ngtemplates' task
import 'apps';
import 'external-apps';
import {appConfig, authoringReactViewEnabled} from 'appConfig';
import {IConfigurableUiComponents, IConfigurableAlgorithms, IRestApiResponse, ISubjectCode} from 'superdesk-api';
import {CC} from 'core/ui/configurable-ui-components';
import {IExtensionLoader, registerExtensions} from 'core/register-extensions';
import {setupTansa} from 'apps/tansa';
import {configurableAlgorithms} from 'core/ui/configurable-algorithms';
import {keyBy, merge} from 'lodash';
import {registerAuthoringReactWidgets} from 'apps/authoring-react/manage-widget-registration';
import {registerAuthoringReactFields} from 'apps/authoring-react/fields/register-fields';
import ng from 'core/services/ng';
import {sdApi} from 'api';
import {httpRequestJsonLocal} from 'core/helpers/network';
import {store} from 'core/data';
import {registerGlobalKeybindings} from 'core/keyboard/keyboard';
import {maybeDisplayInvalidInstanceConfigurationMessage} from 'validate-instance-configuration';
import {registerLegacyExtensionCompatibilityLayer} from 'register-legacy-extension-compatibility-layer';

let body = angular.element('body');

function loadConfigs() {
    return fetch(appConfig.server.url + '/client_config', {
        method: 'GET',
        mode: 'cors',
    })
        .then((res) => res.ok ? res.json() : Promise.reject())
        .then((json) => {
            merge(appConfig, json.config);
        });
}

let started = false;

function isDateFormatValid() {
    const {dateformat} = appConfig.view;

    if (
        dateformat.includes('YYYY') !== true
        || dateformat.includes('MM') !== true
        || dateformat.includes('DD') !== true
    ) {
        return false;
    }

    const separators = dateformat
        .replace('YYYY', '')
        .replace('MM', '')
        .replace('DD', '');

    if (separators.length !== 2 || separators[0] !== separators[1]) {
        return false;
    }

    return true;
}

// the application should be started by importing and calling `startApp` from a customer repository
export function startApp(
    extensions: Array<IExtensionLoader>,
    customUiComponents: IConfigurableUiComponents,
    customAlgorithms: IConfigurableAlgorithms = {},
) {
    if (started === true) {
        return;
    }

    started = true;

    for (const key in customUiComponents) {
        if (customUiComponents.hasOwnProperty(key)) {
            CC[key] = customUiComponents[key];
        }
    }

    for (const key in customAlgorithms) {
        if (customAlgorithms.hasOwnProperty(key)) {
            configurableAlgorithms[key] = customAlgorithms[key];
        }
    }

    // update config via config.js
    if (window.superdeskConfig) {
        angular.merge(appConfig, window.superdeskConfig);
    }

    // non-mock app configuration must live here to allow tests to override
    // since tests do not import this file.
    angular.module('superdesk.config').constant('config', appConfig);

    // added to be able to register activities which didn't work using superdesk reference injected in `core.run`.
    var _superdesk;
    var _workspaceMenu;

    angular.module('superdesk.register_extensions', [])
        .config(['superdeskProvider', 'workspaceMenuProvider', (superdesk, workspaceMenu) => {
            _superdesk = superdesk;
            _workspaceMenu = workspaceMenu;
        }])
        .run([
            'modal',
            'privileges',
            'lock',
            'session',
            'authoringWorkspace',
            'config',
            'metadata',
            'preferencesService',
            'vocabularies',
            (
                modal,
                privileges,
                lock,
                session,
                authoringWorkspace,
                config,
                metadata,
                preferencesService,
                vocabularies,
            ) => {
                Promise.all([
                    // preload vocabularies
                    vocabularies.getAllActiveVocabularies(),
                    preferencesService.getPrivileges(),
                ]).then(() => {
                    registerExtensions(
                        extensions,
                        _superdesk,
                        modal,
                        privileges,
                        lock,
                        session,
                        authoringWorkspace,
                        config,
                        metadata,
                        _workspaceMenu,
                        preferencesService,
                    ).then(() => {
                        if (authoringReactViewEnabled) {
                            registerAuthoringReactWidgets();
                            registerAuthoringReactFields();
                        }

                        registerLegacyExtensionCompatibilityLayer();
                    });
                });
            },
        ]);

    loadConfigs()
        .then(() => {
            if (isDateFormatValid() !== true) {
                document.write('Invalid date format specified in config.view.dateFormat');
                return;
            }

            /**
             * @ngdoc module
             * @name superdesk-client
             * @packageName superdesk-client
             * @description The root superdesk module.
             */
            angular.bootstrap(body, [
                'superdesk.config',
                'superdesk.core',
                'superdesk.apps',
                'superdesk.register_extensions',
            ].concat(appConfig.apps || []), {strictDi: true});

            setTimeout(() => { // required to avoid protractor timing out and failing tests
                if (ng.get('session').sessionId != null) { // user logged in
                    maybeDisplayInvalidInstanceConfigurationMessage();
                }
            });

            window['superdeskIsReady'] = true;

            body.attr('data-theme', 'dark-ui');

            if (sdApi.user.isLoggedIn()) {
                if (appConfig.features.useTansaProofing) {
                    setupTansa();
                }

                httpRequestJsonLocal<IRestApiResponse<ISubjectCode>>({method: 'GET', path: '/subjectcodes'})
                    .then(({_items}) => {
                        store.dispatch({
                            type: 'LOAD_SUBJECT_CODES',
                            payload: keyBy(_items, ({qcode}) => qcode),
                        });
                    });

                registerGlobalKeybindings();
            }
        });
}