From e5ae5c5541e178f0948538c6c6def471e2441448 Mon Sep 17 00:00:00 2001 From: Doris Lam Date: Mon, 1 May 2023 12:40:04 -0700 Subject: [PATCH 01/31] update report issue link --- src/ve-app/main/components/nav-bar.component.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ve-app/main/components/nav-bar.component.ts b/src/ve-app/main/components/nav-bar.component.ts index 141a68bcc..e30dc6e0b 100644 --- a/src/ve-app/main/components/nav-bar.component.ts +++ b/src/ve-app/main/components/nav-bar.component.ts @@ -214,7 +214,7 @@ const NavBarComponent: VeComponentOptions = { View Editor Help
  • - Report Issue + Report Issue
  • From cde123e85f1439a442b089b10d7f88d29a38114c Mon Sep 17 00:00:00 2001 From: Enquier Date: Tue, 2 May 2023 11:39:47 -0600 Subject: [PATCH 02/31] update README.md --- README.md | 130 ++++++++++++++++++++++++------------------------------ 1 file changed, 58 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index 6853db11b..ec0fbff0d 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,55 @@ # View Editor (VE) -## Usage -https://github.com/Open-MBEE/ve/blob/develop/Documents/ViewEditorUserGuide.pdf +View Editor (VE) is a web-based environment designed to interact with a +systems model. VE is a document oriented view of the model elements, +which are stored in [OpenMBEE's Model Management Server (MMS)](https://github.com/Open-MBEE/mms). Its purpose is to provide real and +true data through the web so that users may interact with actual model +elements without having to open a modeling software (e.g. MagicDraw ). +This allows users of all levels, including non-modelers, to view or +modify live documents and values of a singular source of truth. + +### Users Guide +http://docs.openmbee.org/projects/ve + ## File Structure * /package.json - Manifest file specifying node module dependencies required to build and bundle the app * /app/bower.json - Manifest file specifying bower dependencies (js/css library dependencies) -* /Gruntfile.js - build file -* /src/services - services for the mms module, these mostly wrap the rest services of the EMS -* /src/directives - common components for mms.directives module, these provide common ui and behavior -* /src/directives/templates - html templates for our directives plus common styling -* /app - MDEV developed application, this will be separated out in the future +* /webpack.config.ts - Webpack build file +* /src/ve-app - services for the running and operation of the View-Editor Application +* /src/ve-core - common components for the view editor, these provide common ui and behavior +* /src/ve-components - components for the modification and display of information inside view editor, these consist + of several extensible controllers + * `transclusions` allow display of specific model content within a view + * `spec-tools` allow display of relevant model inspection information within the right-pane's "tool window" + * `insertions` allow users to insert model data + * `trees` allow creation different tree structures to be displayed in the left-pane + * `presentations` define different types of content and how they should be displayed in the context of a view (eg. Tables, + Paragraphs and Images) + * `diffs` allow display of model content differentiated by version or branch + + All of these controllers are developer extensible and new ones can be added via the new "VE Extension" Mechanism. Note: + for security and practical reasons extensions can only be loaded at compile, you are unabe to "hot swap" new components +* /src/ve-utils - services for the generic operation of view-editor components + * `core` - services providing the core capabilities for the application including `editSvc`, `eventSvc`, and `cacheSvc` + * `mms-api-client` - services providing access to MMS API endpoints. These generally return promises + * `application` - services providing specific capabilities for the View Editor application (which may also use + MMS API Client to function) ## Configuration -_(View Editor 4.0.0 and newer)_ +_(View Editor 4.x and newer)_ You can now configure view editor to work with external sites without using Grunt. This file also allows the configuration of certain branding and other features that will be expanded in future versions -1. In the `app/config` directory copy `config.example.js` into a new file and rename it to `config..js` +1. In the `config` directory copy `example.json` into a new file and rename it to `.json` 2. You should update the `baseUrl` and `apiUrl` fields to point to your MMS server (eg. `apiURL: 'https://localhost:8080'` & (`baseUrl: ''`) -3. To deploy view editor using this custom file, use `--env ` - appended to your `grunt` command (e.g. `grunt release:docker --env=prod`). +3. To deploy view editor using this custom file, use `VE_ENV=` + prepended to your `npm` command (e.g. `export VE_ENV= & npm build --mode=production/development`). 3. For more information regarding the available configuration options see [Config](docs/Config.md). -_Versions Prior to 4.0.0_ +_Versions Prior to 4.x_ 5. Create a file named `angular-mms-grunt-servers.json`. This is where you will add server mappings. * The _grunt_ command will build with these default and fake values, but will not be runnable. * You should update "ems" key to point to the value of the **actual** hostname serving the Model Management Server (MMS). @@ -34,59 +58,36 @@ _Versions Prior to 4.0.0_ "ems": "hostnameurl" } ``` -## Installation and Building -1. Install the latest stable version of Node ( at the time of this writing 8.9.4 ) -2. To install grunt cli: - - npm install -g grunt-cli - -3. cd into angular-mms directory -4. to install all node module dependencies specified in package.json - - npm install +## Installation and Building (pre 5.x) +For instructions for building versions prior to 5.x see the [4.x Support Branch](https://github.com/Open-MBEE/ve/tree/support/4.x) +1. Install the latest stable version of Node ( at the time of this writing 18.x ) -6. In the root directory, run. . . -* . . .to build and bundle the app in development mode. The final artifact will be available in the dist folder: - - grunt - -* . . .to build and bundle the app in production mode. The final artifact will be available in the dist folder: - - grunt release-build - -* . . .to build and bundle the app in development mode. This will also launch a web server at localhost:9000 for serving static resources from dist folder and a proxy server for any other resources with path starting with /alfresco. This allows us to test with real service endpoints defined in `angular-mms-grunt-servers.json`. The default server is opencaeuat: - - grunt server - -* . . .to build a proxied service in develop mode with default configuration: +2. (optional) To install yarn cli: - grunt server:docker - -* . . .to build and bundle the app in production mode as well as launching a web server locally and a proxy: + npm install -g yarn-cli - grunt release - -* . . .to build and bundle the app in production mode as well as launching a webserver locally with default configuration: +3. to install all node module dependencies specified in package.json - grunt release:docker + npm install -* . . .to build and bundle the app with a custom configuration in dev/production mode as well as launching a webserver locally (defaults to `example`): +4. Use the following commands using webpack/npm to build and bundle the app in: + * . . . development mode. The final artifact will be available in the dist folder: + + export VE_ENV= & npm build --mode=development - grunt :docker --env= + * . . .production mode. The final artifact will be available in the dist folder: + + export VE_ENV= & npm build --mode=production -* . . .to build and bundle the app in production modes, generate documentation and publish the final artifact to Artifactory: +5. Use the following to test launch a web server at localhost:9000 for serving static resources from dist folder: - grunt deploy - -* . . .to run unit tests: + npm start - grunt test - -7. To deploy, zip up the dist folder, it can be served as static files from a web server. For convenience, can unzip it to where mms is hosted (ex. {tomcatDir}/webapps/ve, {mmshost}/ve/mms.html to access) +## Building and Running standalone -For more information, please consult the Gruntfile.js and the links at the bottom. +To deploy standalone, build in production mode & zip up the dist folder, it can be served as static files from a web server. ## Building and Running with Docker @@ -107,20 +108,6 @@ To use a custom configuration file with the docker container you can mount the d Using your custom configuration can be done by specifying `--env VE_ENV=` or adding `VE_ENV` to your compose file. ## Problems? -If you see some error after updating, try cleaning out the bower_components and bower_components_target folders under /app and do a _grunt clean_ - -### SASS Won't load -If you get `Loading "sass.js" tasks...ERROR` - -Perform the following steps to resolve: -1. cd to the project directory -2. `npm update && npm install` -3. Then `node ./node_modules/node-sass/scripts/install.js` -4. Finally `npm rebuild node-sass` -5. Execute Grunt - -### Rendering problems - clear bower cache -If you're sure everything is right, try running _bower cache clean_ ## Note on debugging VE has source-mapping enabled. When developing and debugging it using Chrome, make sure to disable caching in the @@ -150,8 +137,7 @@ For Karma - place new tests within test/develop/unit/DirectiveSpecs or test/deve For Protractor - place new tests within test/develop/e2e ## Generating Docs -* _grunt ngdocs_ - this would generate html docs based on code comments written in ngdocs style into docs/. The generated files need to be served through a webserver to work. -* _grunt docs_ - this would generate the docs and run the server at localhost:10000 +Docs are now automatically generated and posted to ## Contributing and Experimenting, Add Components For general contributing guidelines, please see @@ -195,7 +181,7 @@ Put core [Directives](https://docs.angularjs.org/guide/directive "Angular Docume 'use strict'; - angular.module('veDirectives') + angular.module('veUtils') .directive('mmsElementName', ['ElementService', mmsElementName]); function mmsElementName(ElementService) { @@ -266,8 +252,8 @@ see src/services/UtilsService.getPrintCss ## Links * [node.js](http://nodejs.org/) -* [angular](https://docs.angularjs.org/guide/directive) -* [grunt](http://gruntjs.com/) +* [angular,js](https://docs.angularjs.org/guide/directive) +* [webpack](http://gruntjs.com/) * [sass](http://sass-lang.com/) * [ngdocs](https://github.com/idanush/ngdocs/wiki/API-Docs-Syntax) * [grunt-ngdocs](https://github.com/m7r/grunt-ngdocs) From 14b241fed8aaee7164c17731143afaadbcc91fd1 Mon Sep 17 00:00:00 2001 From: Enquier Date: Tue, 2 May 2023 11:54:17 -0600 Subject: [PATCH 03/31] re-add VE Logo, update readm --- README.md | 7 +++++-- src/assets/ve-logo.svg | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 src/assets/ve-logo.svg diff --git a/README.md b/README.md index ec0fbff0d..77dc7dd0d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -# View Editor (VE) +OpenMBEE +View Editor (VE) +# About View Editor (VE) is a web-based environment designed to interact with a systems model. VE is a document oriented view of the model elements, @@ -8,10 +10,11 @@ elements without having to open a modeling software (e.g. MagicDraw ). This allows users of all levels, including non-modelers, to view or modify live documents and values of a singular source of truth. -### Users Guide +# Users Guide http://docs.openmbee.org/projects/ve +# Deployment Guide ## File Structure * /package.json - Manifest file specifying node module dependencies required to build and bundle the app * /app/bower.json - Manifest file specifying bower dependencies (js/css library dependencies) diff --git a/src/assets/ve-logo.svg b/src/assets/ve-logo.svg new file mode 100644 index 000000000..0dd59dc63 --- /dev/null +++ b/src/assets/ve-logo.svg @@ -0,0 +1,15 @@ + + + + logo2 copy 2 + Created with Sketch. + + + + + + + + + + \ No newline at end of file From 00f1adfdfed281533071b6272469a5085b54f836 Mon Sep 17 00:00:00 2001 From: Enquier Date: Tue, 2 May 2023 12:05:18 -0600 Subject: [PATCH 04/31] commit readme changes --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 77dc7dd0d..3c75077e4 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ -OpenMBEE -View Editor (VE) +OpenMBEE    +View Editor (VE) + + # About View Editor (VE) is a web-based environment designed to interact with a From 7fe2209f63cea613a66abbe23f9be7e181fd86a4 Mon Sep 17 00:00:00 2001 From: Enquier Date: Tue, 2 May 2023 15:27:47 -0600 Subject: [PATCH 05/31] add dark logo --- README.md | 6 +++- src/assets/logo-dark.svg | 70 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 src/assets/logo-dark.svg diff --git a/README.md b/README.md index 3c75077e4..a203c123b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,8 @@ -OpenMBEE    + + + +OpenMBEE    + View Editor (VE) diff --git a/src/assets/logo-dark.svg b/src/assets/logo-dark.svg new file mode 100644 index 000000000..04a601de6 --- /dev/null +++ b/src/assets/logo-dark.svg @@ -0,0 +1,70 @@ + + + + + + + + From c14594e6b882f63a06fd33f9fafa6e9ad3f6fcc9 Mon Sep 17 00:00:00 2001 From: Enquier Date: Tue, 2 May 2023 15:31:08 -0600 Subject: [PATCH 06/31] dark ve logo --- README.md | 7 +++++-- src/assets/logo-dark.svg | 4 ++-- src/assets/ve-logo-dark.svg | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 src/assets/ve-logo-dark.svg diff --git a/README.md b/README.md index a203c123b..de070e1be 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@ -OpenMBEE    +OpenMBEE +    + + +View Editor -View Editor (VE) # About diff --git a/src/assets/logo-dark.svg b/src/assets/logo-dark.svg index 04a601de6..79c0029b4 100644 --- a/src/assets/logo-dark.svg +++ b/src/assets/logo-dark.svg @@ -4,8 +4,8 @@ viewBox="0 0 346 120" style="enable-background:new 0 0 346 120;" xml:space="preserve">
  • ${anchor}${branch.data._veNumber} ${branch.data.name}` + const anchor: string = ''; + result += `
  • ${anchor}${branch.data._veNumber} ${branch.data.name}`; } - let ulAdded = false + let ulAdded = false; for (const child of branch.children) { if (child.type !== 'view' && child.type !== 'section') { - continue + continue; } if (!ulAdded) { - result += '
      ' - ulAdded = true + result += '
        '; + ulAdded = true; } - result += this.makeHtmlTOCChild(child) + result += this.makeHtmlTOCChild(child); } if (ulAdded) { - result += '
      ' + result += '
    '; } if (!skip) { - result += '
  • ' + result += ''; } - return result - } + return result; + }; /** * @name veUtils/UtilsService#makeTablesAndFiguresTOC @@ -108,27 +108,27 @@ export class UtilsService { tableCount: 0, figureCount: 0, equationCount: 0, - } + }; // If both "Generate List of Tables and Figures" && "Use HTML for List of Tables and Figures " options are checked... if (html) { - ob = this.generateTOCHtmlOption(ob, rootBranch, printElement) + ob = this.generateTOCHtmlOption(ob, rootBranch, printElement); // return obHTML; } else { for (let i = 0; i < rootBranch.children.length; i++) { - this.makeTablesAndFiguresTOCChild(rootBranch.children[i], printElement, ob, live, false) + this.makeTablesAndFiguresTOCChild(rootBranch.children[i], printElement, ob, live, false); } } ob.tables = ob.tables.length ? '

    List of Tables

      ' + ob.tables + '
    ' - : '' + : ''; ob.figures = ob.figures.length ? '

    List of Figures

      ' + ob.figures + '
    ' - : '' + : ''; ob.equations = ob.equations.length ? '

    List of Equations

      ' + ob.equations + '
    ' - : '' - return ob + : ''; + return ob; } /** @@ -149,153 +149,153 @@ export class UtilsService { live: boolean, showRefName: boolean ): void { - const pe = child.data - const sysmlId = pe.id - const veNumber = pe._veNumber - let prefix = '' - const el = printElement.find('#' + sysmlId) + const pe = child.data; + const sysmlId = pe.id; + const veNumber = pe._veNumber; + let prefix = ''; + const el = printElement.find('#' + sysmlId); const refs = printElement.find( 'mms-view-link[mms-pe-id="' + sysmlId + '"], mms-view-link[data-mms-pe-id="' + sysmlId + '"]' - ) - let cap = '' - let name = '' + ); + let cap = ''; + let name = ''; if (child.type === 'table') { - ob.tableCount++ - prefix = 'Table ' + veNumber + '. ' - const capTbl = el.find('table > caption') - name = capTbl.text() + ob.tableCount++; + prefix = 'Table ' + veNumber + '. '; + const capTbl = el.find('table > caption'); + name = capTbl.text(); if (name !== '' && name.indexOf('Table') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length) + name = name.substring(name.indexOf(prefix) + prefix.length); } else if (name === '') { - name = pe.name + name = pe.name; } - cap = veNumber + '. ' + name - ob.tables += '
  • ' + cap + '
  • ' - capTbl.html('Table ' + cap) + cap = veNumber + '. ' + name; + ob.tables += '
  • ' + cap + '
  • '; + capTbl.html('Table ' + cap); // If caption does not exist, add to html if (capTbl.length === 0) { - el.find('table').prepend('Table ' + cap + '') + el.find('table').prepend('Table ' + cap + ''); } // Change cap value based on showRefName true/false if (!showRefName) { - cap = veNumber + cap = veNumber; } if (!live) { - refs.find('a').attr('href', '#' + sysmlId) + refs.find('a').attr('href', '#' + sysmlId); } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Table ' + cap) + .html('Table ' + cap); } if (child.type === 'figure') { - ob.figureCount++ - prefix = 'Figure ' + veNumber + '. ' - const capFig = el.find('figure > figcaption') - name = capFig.text() + ob.figureCount++; + prefix = 'Figure ' + veNumber + '. '; + const capFig = el.find('figure > figcaption'); + name = capFig.text(); if (name !== '' && name.indexOf('Figure') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length) + name = name.substring(name.indexOf(prefix) + prefix.length); } else if (name === '') { - name = pe.name + name = pe.name; } - cap = veNumber + '. ' + name - ob.figures += '
  • ' + cap + '
  • ' - capFig.html('Figure ' + cap) + cap = veNumber + '. ' + name; + ob.figures += '
  • ' + cap + '
  • '; + capFig.html('Figure ' + cap); // If caption does not exist, add to html if (capFig.length === 0) { el.find('img') .wrap('
    ') - .after('
    Figure ' + cap + '
    ') + .after('
    Figure ' + cap + '
    '); } // Change cap value based on showRefName true/false if (!showRefName) { - cap = veNumber + cap = veNumber; } if (!live) { - refs.find('a').attr('href', '#' + sysmlId) + refs.find('a').attr('href', '#' + sysmlId); } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Fig. ' + cap) + .html('Fig. ' + cap); } if (child.type === 'equation') { - ob.equationCount++ - cap = veNumber + '. ' + pe.name - ob.equations += '
  • ' + cap + '
  • ' - const equationCap = '(' + veNumber + ')' - const capEq = el.find('.caption-type-equation') - capEq.html(equationCap) + ob.equationCount++; + cap = veNumber + '. ' + pe.name; + ob.equations += '
  • ' + cap + '
  • '; + const equationCap = '(' + veNumber + ')'; + const capEq = el.find('.caption-type-equation'); + capEq.html(equationCap); // If caption does not exist, add to html if (capEq.length === 0) { el.find('present-equation > transclude > transclude-doc > p') .last() - .append('' + equationCap + '') + .append('' + equationCap + ''); } if (!live) { - refs.find('a').attr('href', '#' + sysmlId) + refs.find('a').attr('href', '#' + sysmlId); } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Eq. ' + equationCap) + .html('Eq. ' + equationCap); } for (let i = 0; i < child.children.length; i++) { - this.makeTablesAndFiguresTOCChild(child.children[i], printElement, ob, live, showRefName) + this.makeTablesAndFiguresTOCChild(child.children[i], printElement, ob, live, showRefName); } } public addLiveNumbering(pe: ViewObject, el: JQuery, type: string): void { - const veNumber = pe._veNumber + const veNumber = pe._veNumber; if (!veNumber) { - return + return; } - let prefix = '' - let name = '' - let cap = '' + let prefix = ''; + let name = ''; + let cap = ''; if (type === 'table') { - prefix = 'Table ' + veNumber + '. ' - const capTbl = el.find('table > caption') - name = capTbl.text() + prefix = 'Table ' + veNumber + '. '; + const capTbl = el.find('table > caption'); + name = capTbl.text(); if (name !== '' && name.indexOf('Table') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length) + name = name.substring(name.indexOf(prefix) + prefix.length); } else if (name === '') { - name = pe.name + name = pe.name; } - cap = veNumber + '. ' + name - capTbl.html('Table ' + cap) + cap = veNumber + '. ' + name; + capTbl.html('Table ' + cap); // If caption does not exist, add to html if (capTbl.length === 0) { - el.find('table').prepend('Table ' + cap + '') + el.find('table').prepend('Table ' + cap + ''); } } if (type === 'figure') { - prefix = 'Figure ' + veNumber + '. ' - const capFig = el.find('figure > figcaption') - name = capFig.text() + prefix = 'Figure ' + veNumber + '. '; + const capFig = el.find('figure > figcaption'); + name = capFig.text(); if (name !== '' && name.indexOf('Figure') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length) + name = name.substring(name.indexOf(prefix) + prefix.length); } else if (name === '') { - name = pe.name + name = pe.name; } - cap = veNumber + '. ' + name - capFig.html('Figure ' + cap) + cap = veNumber + '. ' + name; + capFig.html('Figure ' + cap); // If caption does not exist, add to html if (capFig.length === 0) { el.find('img') .wrap('
    ') - .after('
    Figure ' + cap + '
    ') + .after('
    Figure ' + cap + '
    '); } } if (type === 'equation') { - const equationCap = '(' + veNumber + ')' - const capEq = el.find('.caption-type-equation') - capEq.html(equationCap) + const equationCap = '(' + veNumber + ')'; + const capEq = el.find('.caption-type-equation'); + capEq.html(equationCap); // If caption does not exist, add to html if (capEq.length === 0) { el.find('present-equation > mms-cf > transclude-doc > p') .last() - .append('' + equationCap + '') + .append('' + equationCap + ''); } } } @@ -308,8 +308,8 @@ export class UtilsService { * @returns {string} unique ID wit prefix, tbl_ or fig_ */ public generateAnchorId = (prefix: string): string => { - return `${prefix}${this.apiSvc.createUniqueId()}` - } + return `${prefix}${this.apiSvc.createUniqueId()}`; + }; /** * @name veUtils/UtilsService#generateTOCHtmlOption @@ -327,52 +327,52 @@ export class UtilsService { ): TOCHtmlObject { // Grab all existing tables and figures inside the center pane, and assign them to tables and figures const tables = printElement.find('table'), - figures = printElement.find('figure') + figures = printElement.find('figure'); // equations = printElement.find('.math-tex'); let anchorId = '', thisCap = '', tblCap: JQuery, tbl: JQuery, - fig: JQuery + fig: JQuery; - ob.tableCount = tables.length - ob.figureCount = figures.length + ob.tableCount = tables.length; + ob.figureCount = figures.length; // Tables for (let j = 0; j < tables.length; j++) { - tbl = $(tables[j]) - tblCap = $('caption', tbl) + tbl = $(tables[j]); + tblCap = $('caption', tbl); // Set the link from the List of Tables to the actual tables - anchorId = this.generateAnchorId('tbl_') - tbl.attr('id', anchorId) + anchorId = this.generateAnchorId('tbl_'); + tbl.attr('id', anchorId); // Append li to the List of Tables - thisCap = tblCap && tblCap.text() !== '' ? `${j + 1}. ${tblCap.text()}` : `${j + 1}. ` - ob.tables += '
  • ' + thisCap + '
  • ' + thisCap = tblCap && tblCap.text() !== '' ? `${j + 1}. ${tblCap.text()}` : `${j + 1}. `; + ob.tables += '
  • ' + thisCap + '
  • '; // If no caption exists, add empty caption for numbering if (tblCap.length === 0) { - tbl.prepend(' ') + tbl.prepend(' '); } } // Figures for (let j = 0; j < figures.length; j++) { - fig = $(figures[j]) - const figcap = $('figcaption', fig) + fig = $(figures[j]); + const figcap = $('figcaption', fig); // Set the link from the List of Tables to the actual tables - anchorId = this.generateAnchorId('fig_') - fig.attr('id', anchorId) + anchorId = this.generateAnchorId('fig_'); + fig.attr('id', anchorId); // Append li to the List of Figures - thisCap = figcap && figcap.text() !== '' ? `${j + 1}. ${figcap.text()}` : `${j + 1}` - ob.figures += '
  • ' + thisCap + '
  • ' + thisCap = figcap && figcap.text() !== '' ? `${j + 1}. ${figcap.text()}` : `${j + 1}`; + ob.figures += '
  • ' + thisCap + '
  • '; // If no caption exists, add empty caption for numbering if (figcap.length === 0) { - fig.append('
     
    ') + fig.append('
     
    '); } } @@ -391,7 +391,7 @@ export class UtilsService { // eq.append(' '); // } // } - return ob + return ob; } /** @@ -403,17 +403,17 @@ export class UtilsService { */ public convertViewLinks(printElement: JQuery): void { printElement.find('mms-view-link').each((index) => { - const $this = $(this) - let elementId = $this.attr('mms-element-id') || $this.attr('data-mms-element-id') + const $this = $(this); + let elementId = $this.attr('mms-element-id') || $this.attr('data-mms-element-id'); if (!elementId) { - return + return; } - elementId = elementId.replace(/[^\w\-]/gi, '') - const isElementInDoc = printElement.find('#' + elementId) + elementId = elementId.replace(/[^\w\-]/gi, ''); + const isElementInDoc = printElement.find('#' + elementId); if (isElementInDoc.length) { - $this.find('a').attr('href', '#' + elementId) + $this.find('a').attr('href', '#' + elementId); } - }) + }); } /** @@ -531,10 +531,10 @@ p, div {widows: 2; orphans: 2;} /*------------------------------------------------------------------ 8. Signature Box -` +`; for (let i = 1; i < 10; i++) { ret += `.h${i} {bookmark-level: ${i};} -` +`; } if (htmlFlag) { ret += ` @@ -543,27 +543,27 @@ figure { counter-increment: figure-counter; } figcaption::before {content: "Figure " counter(figure-counter) ". "; } table { counter-increment: table-counter; } caption::before {content: "Table " counter(table-counter) ". "; } -` +`; } if (meta) { Object.keys(meta).forEach((key) => { if (meta[key]) { - let content: string + let content: string; if (meta[key] === 'counter(page)') { - content = meta[key] as string + content = meta[key] as string; } else { - content = `"${(meta[key] as string | number).toString()}"` + content = `"${(meta[key] as string | number).toString()}"`; } ret += `@page {@${key} {font-size: 9px; content: ${content};}} -` +`; } - }) + }); } if (landscape) { - ret += '@page {size: 11in 8.5in;}' + ret += '@page {size: 11in 8.5in;}'; } - return ret - } + return ret; + }; /** * @name veUtils/UtilsService#exportHtmlAs @@ -576,25 +576,25 @@ caption::before {content: "Table " counter(table-counter) ". "; } public exportHtmlAs( exportType: number, data: { - htmlString: string - name: string - projectId: string - refId: string - css: string + htmlString: string; + name: string; + projectId: string; + refId: string; + css: string; } ): VePromise { - let accept: string + let accept: string; switch (exportType) { case 2: - accept = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - break + accept = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; + break; case 3: - accept = 'application/pdf' - break + accept = 'application/pdf'; + break; default: - accept = 'application/pdf' + accept = 'application/pdf'; } - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.$http .post( this.uRLSvc.getExportHtmlUrl(), @@ -609,31 +609,31 @@ caption::before {content: "Table " counter(table-counter) ". "; } ) .then( (data2) => { - const blob = new Blob([data2.data as BlobPart], { type: accept }) - const a = window.document.createElement('a') - const url = window.URL.createObjectURL(blob) - a.href = url - a.download = data.name + (exportType == 2 ? '.docx' : '.pdf') - a.click() - window.URL.revokeObjectURL(url) - deferred.resolve('ok') + const blob = new Blob([data2.data as BlobPart], { type: accept }); + const a = window.document.createElement('a'); + const url = window.URL.createObjectURL(blob); + a.href = url; + a.download = data.name + (exportType == 2 ? '.docx' : '.pdf'); + a.click(); + window.URL.revokeObjectURL(url); + deferred.resolve('ok'); }, (error: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(error)) + deferred.reject(this.uRLSvc.handleHttpStatus(error)); } - ) - return deferred.promise + ); + return deferred.promise; } public getElementTypeClass = (element: ElementObject, elementType: string): string => { - let elementTypeClass = '' + let elementTypeClass = ''; if (element.type === 'InstanceSpecification') { - elementTypeClass = 'pe-type-' + _.kebabCase(elementType) + elementTypeClass = 'pe-type-' + _.kebabCase(elementType); } else { - elementTypeClass = 'item-type-' + _.kebabCase(elementType) + elementTypeClass = 'item-type-' + _.kebabCase(elementType); } - return elementTypeClass - } + return elementTypeClass; + }; } -veUtils.service('UtilsService', UtilsService) +veUtils.service('UtilsService', UtilsService); diff --git a/src/ve-utils/application/index.ts b/src/ve-utils/application/index.ts index e19d6419d..b31dfe142 100644 --- a/src/ve-utils/application/index.ts +++ b/src/ve-utils/application/index.ts @@ -1,15 +1,15 @@ -import './RootScope.service' -import './Application.service' -import './Branding.service' -import './Math.service' -import './ShortUrl.service' -import './Utils.service' -import './Image.service' +import './RootScope.service'; +import './Application.service'; +import './Branding.service'; +import './Math.service'; +import './ShortUrl.service'; +import './Utils.service'; +import './Image.service'; -export * from './RootScope.service' -export * from './Application.service' -export * from './Branding.service' -export * from './Math.service' -export * from './ShortUrl.service' -export * from './Utils.service' -export * from './Image.service' +export * from './RootScope.service'; +export * from './Application.service'; +export * from './Branding.service'; +export * from './Math.service'; +export * from './ShortUrl.service'; +export * from './Utils.service'; +export * from './Image.service'; diff --git a/src/ve-utils/core/Cache.service.ts b/src/ve-utils/core/Cache.service.ts index 9333b8a99..9bd9d5fbc 100644 --- a/src/ve-utils/core/Cache.service.ts +++ b/src/ve-utils/core/Cache.service.ts @@ -1,40 +1,40 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { ElementObject, MmsObject } from '@ve-types/mms' +import { ElementObject, MmsObject } from '@ve-types/mms'; export class CacheService { - public cache: { [key: string]: string | unknown | unknown[] } = {} + public cache: { [key: string]: string | unknown | unknown[] } = {}; - static $inject = [] + static $inject = []; get(key: string | string[], noCopy?: boolean): T | undefined { - const realKey: string = this._makeKey(key) - const result: T = this._get(realKey) + const realKey: string = this._makeKey(key); + const result: T = this._get(realKey); - return result + return result; //else return _.cloneDeep(result) } private _get = (realKey: string): T => { const recurse = (key: string): string | T => { if (typeof this.cache[key] === 'string') { - return recurse(this.cache[key] as string) + return recurse(this.cache[key] as string); } - return this.cache[key] as T - } + return this.cache[key] as T; + }; if (this.cache.hasOwnProperty(realKey)) { - let result: T + let result: T; if (typeof this.cache[realKey] === 'string') { - result = recurse(this.cache[realKey] as string) as T + result = recurse(this.cache[realKey] as string) as T; } else { - result = this.cache[realKey] as T + result = this.cache[realKey] as T; } - return result + return result; } - return - } + return; + }; /** * @name CacheService#getElements @@ -45,10 +45,10 @@ export class CacheService { * @returns {Object} Value if found, empty array if not found */ getLatestElements(projectId: string, refId: string): T[] { - const latestElements: T[] = [] + const latestElements: T[] = []; for (const key in this.cache) { if (!this.cache.hasOwnProperty(key)) { - continue + continue; } if ( key.indexOf('|latest') >= 0 && @@ -58,13 +58,13 @@ export class CacheService { key.indexOf(refId) >= 0 && key.indexOf(projectId) >= 0 ) { - const val: T | T[] = this._get(key) + const val: T | T[] = this._get(key); if (val) { - Array.isArray(val) ? latestElements.push(...val) : latestElements.push(val) + Array.isArray(val) ? latestElements.push(...val) : latestElements.push(val); } } } - return latestElements + return latestElements; } /** @@ -77,29 +77,29 @@ export class CacheService { * @returns {Object} the original value */ put(key: string | string[], value: T, merge?: boolean): T { - const m = typeof merge === 'undefined' ? false : merge - const realKey = this._makeKey(key) - let currentValue: T = this.get(realKey, true) + const m = typeof merge === 'undefined' ? false : merge; + const realKey = this._makeKey(key); + let currentValue: T = this.get(realKey, true); if (currentValue && m) { _.mergeWith(currentValue, value, (a: unknown, b: unknown, id: string) => { if ((id === '_contents' || id === 'specification') && b && (b as ElementObject).type === 'Expression') { - return b + return b; } if (Array.isArray(a) && Array.isArray(b) && b.length < a.length) { - a.length = 0 - a.push(...(b as unknown[])) - return a as unknown[] + a.length = 0; + a.push(...(b as unknown[])); + return a as unknown[]; } if (id === '_displayedElementIds' && b) { - return b + return b; } - return undefined - }) + return undefined; + }); } else { - this.cache[realKey] = value - currentValue = value + this.cache[realKey] = value; + currentValue = value; } - return currentValue + return currentValue; } /** @@ -110,12 +110,12 @@ export class CacheService { * @param {string | string[]} targetKey */ public link(sourceKey: string | string[], targetKey: string | string[]): void { - const realSourceKey: string = this._makeKey(sourceKey) + const realSourceKey: string = this._makeKey(sourceKey); if (this.cache.hasOwnProperty(realSourceKey) && typeof this.cache[realSourceKey] !== 'string') { - delete this.cache[realSourceKey] + delete this.cache[realSourceKey]; } - this.cache[realSourceKey] = this._makeKey(targetKey) + this.cache[realSourceKey] = this._makeKey(targetKey); } /** @@ -126,21 +126,21 @@ export class CacheService { * @returns {Object} value that was removed or undefined */ remove(key: string | string[]): T { - let realKey: string + let realKey: string; if (Array.isArray(key)) { - realKey = this._makeKey(key) + realKey = this._makeKey(key); } else { - realKey = key + realKey = key; } if (!this.cache.hasOwnProperty(realKey)) { - return null + return null; } - const removed = this.cache[realKey] - delete this.cache[realKey] + const removed = this.cache[realKey]; + delete this.cache[realKey]; if (typeof removed === 'string') { - return this.remove(removed) + return this.remove(removed); } - return removed as T + return removed as T; } /** @@ -151,39 +151,39 @@ export class CacheService { * @returns {boolean} whether value exists for key */ exists(key: string | string[]): boolean { - let realKey = '' + let realKey = ''; if (Array.isArray(key)) { - realKey = this._makeKey(key) + realKey = this._makeKey(key); } else { - realKey = key + realKey = key; } if (!this.cache.hasOwnProperty(realKey)) { - return false + return false; } - const val = this.cache[realKey] + const val = this.cache[realKey]; if (typeof val === 'object') { - return true + return true; } if (typeof val === 'string') { - return this.exists(val) + return this.exists(val); } - return false + return false; } private _makeKey(keys: string | string[]): string { if (Array.isArray(keys)) { - return keys.join('|') + return keys.join('|'); } else { - return keys + return keys; } } reset = (): void => { - const keys = Object.keys(this.cache) + const keys = Object.keys(this.cache); for (let i = 0; i < keys.length; i++) { - delete this.cache[keys[i]] + delete this.cache[keys[i]]; } - } + }; } -veUtils.service('CacheService', CacheService) +veUtils.service('CacheService', CacheService); diff --git a/src/ve-utils/core/Edit.service.ts b/src/ve-utils/core/Edit.service.ts index b686862c3..fc6adc076 100644 --- a/src/ve-utils/core/Edit.service.ts +++ b/src/ve-utils/core/Edit.service.ts @@ -1,75 +1,75 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { EventService } from './Event.service' +import { EventService } from './Event.service'; -import { ElementObject, ValueObject } from '@ve-types/mms' +import { ElementObject, ValueObject } from '@ve-types/mms'; export interface EditObject { - element: T - values?: ValueObject[] - key: string + element: T; + values?: ValueObject[]; + key: string; } export class EditService { - private edits: { [editKey: string]: EditObject } = {} + private edits: { [editKey: string]: EditObject } = {}; - public EVENT = 've-edits' + public EVENT = 've-edits'; - static $inject = ['EventService'] + static $inject = ['EventService']; constructor(private eventSvc: EventService) {} trigger = (): void => { - this.eventSvc.$broadcast(this.EVENT) - } + this.eventSvc.$broadcast(this.EVENT); + }; get(key: string | string[]): EditObject { - key = this.makeKey(key) - return this.edits[key] as EditObject + key = this.makeKey(key); + return this.edits[key] as EditObject; } getAll(): { [key: string]: EditObject } { - return this.edits + return this.edits; } openEdits = (): number => { - return Object.keys(this.edits).length - } + return Object.keys(this.edits).length; + }; addOrUpdate = (key: string | string[], data: ElementObject, overwrite?: boolean): EditObject => { - key = this.makeKey(key) + key = this.makeKey(key); if (overwrite) { - delete this.edits[key] + delete this.edits[key]; } - this.edits[key] = { key, element: data } + this.edits[key] = { key, element: data }; - this.trigger() - return this.edits[key] - } + this.trigger(); + return this.edits[key]; + }; remove = (key: string | string[]): void => { - key = this.makeKey(key) + key = this.makeKey(key); if (this.edits[key]) { - delete this.edits[key] - this.trigger() + delete this.edits[key]; + this.trigger(); } - } + }; // getKey(): string {} reset = (): void => { - const keys = Object.keys(this.edits) + const keys = Object.keys(this.edits); for (let i = 0; i < keys.length; i++) { - delete this.edits[keys[i]] + delete this.edits[keys[i]]; } - } + }; public makeKey(keys: string | string[]): string { if (Array.isArray(keys)) { - return keys.join('|') + return keys.join('|'); } else { - return keys + return keys; } } } -veUtils.service('EditService', EditService) +veUtils.service('EditService', EditService); diff --git a/src/ve-utils/core/Event.service.ts b/src/ve-utils/core/Event.service.ts index bbc257ade..8a9230be0 100644 --- a/src/ve-utils/core/Event.service.ts +++ b/src/ve-utils/core/Event.service.ts @@ -1,62 +1,62 @@ -import Rx from 'rx-lite' +import Rx from 'rx-lite'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -export type eventHandlerFn = (data: T) => void +export type eventHandlerFn = (data: T) => void; export class EventService { - private subjects: { [key: string]: Rx.ISubject } = {} - private bindings: { [key: string]: Rx.ISubject } = {} + private subjects: { [key: string]: Rx.ISubject } = {}; + private bindings: { [key: string]: Rx.ISubject } = {}; //API - public $broadcast = (name: string, data?: T): void => this.emit(name, data) - public $on = (name: string, handler: eventHandlerFn): Rx.IDisposable => this.listen(name, handler) - public $destroy = (subs: Rx.IDisposable[]): void => this.destroy(subs) - public $init = (ctrl: { subs: Rx.IDisposable[] } & angular.IComponentController): void => this.initEventSvc(ctrl) + public $broadcast = (name: string, data?: T): void => this.emit(name, data); + public $on = (name: string, handler: eventHandlerFn): Rx.IDisposable => this.listen(name, handler); + public $destroy = (subs: Rx.IDisposable[]): void => this.destroy(subs); + public $init = (ctrl: { subs: Rx.IDisposable[] } & angular.IComponentController): void => this.initEventSvc(ctrl); createName = (name: string): string => { - return `$ ${name}` - } + return `$ ${name}`; + }; resolve(name: string, data?: T): void { - const fnName = this.createName(name) + const fnName = this.createName(name); //$rootScope.$broadcast(name,data); if (!this.bindings[fnName]) { - this.bindings[fnName] = new Rx.BehaviorSubject(data) + this.bindings[fnName] = new Rx.BehaviorSubject(data); } else { - this.bindings[fnName].onNext(data) + this.bindings[fnName].onNext(data); } } binding(name: string, handler: eventHandlerFn): Rx.IDisposable { - const fnName = this.createName(name) + const fnName = this.createName(name); if (!this.bindings[fnName]) { - throw Error('Binding ' + name + ' subscribed before initialization!') + throw Error('Binding ' + name + ' subscribed before initialization!'); } - return this.bindings[fnName].subscribe(handler) + return this.bindings[fnName].subscribe(handler); } emit(name: string, data?: T): void { - const fnName = this.createName(name) + const fnName = this.createName(name); //$rootScope.$broadcast(name,data); if (!this.subjects[fnName]) { - this.subjects[fnName] = new Rx.Subject() + this.subjects[fnName] = new Rx.Subject(); } - this.subjects[fnName].onNext(data) + this.subjects[fnName].onNext(data); } listen(name: string, handler: eventHandlerFn): Rx.IDisposable { - const fnName = this.createName(name) + const fnName = this.createName(name); if (!this.subjects[fnName]) { - this.subjects[fnName] = new Rx.Subject() + this.subjects[fnName] = new Rx.Subject(); } - return this.subjects[fnName].subscribe(handler) + return this.subjects[fnName].subscribe(handler); } destroy(subs: Rx.IDisposable[]): void { if (subs.length > 0) { for (let i = 0; i < subs.length; i++) { if (typeof subs[i].dispose === 'function') { - subs[i].dispose() + subs[i].dispose(); } } } @@ -64,21 +64,21 @@ export class EventService { initEventSvc( componentOrScope: { - subs: Rx.IDisposable[] + subs: Rx.IDisposable[]; } & angular.IComponentController ): void { - componentOrScope.subs = [] + componentOrScope.subs = []; if (!componentOrScope.$onDestroy) { componentOrScope.$onDestroy = (): void => { - this.destroy(componentOrScope.subs) - } + this.destroy(componentOrScope.subs); + }; } } exists(eventOrBinding: string): boolean { - const name = this.createName(eventOrBinding) - return this.subjects.hasOwnProperty(name) || this.bindings.hasOwnProperty(name) + const name = this.createName(eventOrBinding); + return this.subjects.hasOwnProperty(name) || this.bindings.hasOwnProperty(name); } } -veUtils.service('EventService', EventService) +veUtils.service('EventService', EventService); diff --git a/src/ve-utils/core/Session.service.ts b/src/ve-utils/core/Session.service.ts index 81c584050..a4f4dd36a 100644 --- a/src/ve-utils/core/Session.service.ts +++ b/src/ve-utils/core/Session.service.ts @@ -1,50 +1,50 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { EventService } from './Event.service' +import { EventService } from './Event.service'; export class SessionService { - static $inject = ['EventService'] + static $inject = ['EventService']; constructor(private eventSvc: EventService) {} private static _setStorage(key: string, realValue: T): void { - const value = realValue == null ? null : JSON.stringify(realValue) - sessionStorage.setItem(key, value) + const value = realValue == null ? null : JSON.stringify(realValue); + sessionStorage.setItem(key, value); } private static _getStorage(key: string): T { - const sessionValue = sessionStorage.getItem(key) + const sessionValue = sessionStorage.getItem(key); if (sessionValue === null) { - return null + return null; } else { - return JSON.parse(sessionValue) as T + return JSON.parse(sessionValue) as T; } } private static _removeStorage(key: string): void { - sessionStorage.removeItem(key) + sessionStorage.removeItem(key); } public clear = (): void => { - sessionStorage.clear() - } + sessionStorage.clear(); + }; public accessor = (name: string, value: T, defaultValue: T = null): T => { if (value === undefined) { - let val = SessionService._getStorage(name) + let val = SessionService._getStorage(name); if (val == null) { - val = defaultValue - SessionService._setStorage(name, val) + val = defaultValue; + SessionService._setStorage(name, val); } if (!this.eventSvc.exists(name)) { - this.eventSvc.resolve(name, val) + this.eventSvc.resolve(name, val); } - return val + return val; } - this.eventSvc.resolve(name, value) - SessionService._setStorage(name, value) - return value - } + this.eventSvc.resolve(name, value); + SessionService._setStorage(name, value); + return value; + }; } -veUtils.service('SessionService', SessionService) +veUtils.service('SessionService', SessionService); diff --git a/src/ve-utils/core/index.ts b/src/ve-utils/core/index.ts index 44d28a73e..15fc54501 100644 --- a/src/ve-utils/core/index.ts +++ b/src/ve-utils/core/index.ts @@ -1,9 +1,9 @@ -import './Cache.service' -import './Edit.service' -import './Event.service' -import './Session.service' +import './Cache.service'; +import './Edit.service'; +import './Event.service'; +import './Session.service'; -export * from './Cache.service' -export * from './Edit.service' -export * from './Event.service' -export * from './Session.service' +export * from './Cache.service'; +export * from './Edit.service'; +export * from './Event.service'; +export * from './Session.service'; diff --git a/src/ve-utils/index.ts b/src/ve-utils/index.ts index 7ded81b91..7298c68d2 100644 --- a/src/ve-utils/index.ts +++ b/src/ve-utils/index.ts @@ -1,15 +1,15 @@ //Libraries //import 'angular' -import './ve-utils.module' +import './ve-utils.module'; -import './third-party' +import './third-party'; -import './core' -import './model-schema' -import './application' -import './mms-api-client' +import './core'; +import './model-schema'; +import './application'; +import './mms-api-client'; -export * from './ve-utils.module' +export * from './ve-utils.module'; -export default 've-utils' +export default 've-utils'; diff --git a/src/ve-utils/mms-api-client/Api.service.ts b/src/ve-utils/mms-api-client/Api.service.ts index 53ebf0c4a..28f621c3d 100644 --- a/src/ve-utils/mms-api-client/Api.service.ts +++ b/src/ve-utils/mms-api-client/Api.service.ts @@ -1,13 +1,13 @@ -import _ from 'lodash' -import * as uuid from 'uuid' +import _ from 'lodash'; +import * as uuid from 'uuid'; -import { URLService } from '@ve-utils/mms-api-client/URL.service' -import { SchemaService } from '@ve-utils/model-schema' +import { URLService } from '@ve-utils/mms-api-client/URL.service'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { VeConfig } from '@ve-types/config' +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { VeConfig } from '@ve-types/config'; import { BasicResponse, ElementObject, @@ -20,7 +20,7 @@ import { ValueObject, VersionResponse, ViewObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; export class ApiService { private editKeys = [ @@ -34,13 +34,13 @@ export class ApiService { '_projectId', '_refId', 'type', - ] + ]; - schema: string = 'cameo' + schema: string = 'cameo'; - public veConfig: VeConfig = window.__env + public veConfig: VeConfig = window.__env; - static $inject = ['$q', '$http', 'URLService', 'SchemaService'] + static $inject = ['$q', '$http', 'URLService', 'SchemaService']; constructor( private $q: VeQService, @@ -50,21 +50,21 @@ export class ApiService { ) {} public getMmsVersion(): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.$http.get(this.uRLSvc.getMmsVersionURL()).then( (response) => { - deferred.resolve(response.data.mmsVersion) + deferred.resolve(response.data.mmsVersion); }, (response: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(response)) + deferred.reject(this.uRLSvc.handleHttpStatus(response)); } - ) - return deferred.promise + ); + return deferred.promise; } public getVeVersion = (): string => { - return this.veConfig.version - } + return this.veConfig.version; + }; /** * @name veUtils/ApiService#handleErrorCallback @@ -78,14 +78,14 @@ export class ApiService { deferredOrReject: angular.IDeferred | angular.IQResolveReject>, type?: 'error' | 'warning' | 'info' ): void { - const res = this.uRLSvc.handleHttpStatus(response) + const res = this.uRLSvc.handleHttpStatus(response); if (type) { - res.type = type + res.type = type; } if ((deferredOrReject as angular.IDeferred).reject) { - ;(deferredOrReject as angular.IDeferred).reject(res) + (deferredOrReject as angular.IDeferred).reject(res); } else { - ;(deferredOrReject as angular.IQResolveReject>)(res) + (deferredOrReject as angular.IQResolveReject>)(res); } } @@ -98,13 +98,13 @@ export class ApiService { */ private _cleanValueSpec = (vs: ValueObject): void => { - if (vs.hasOwnProperty('valueExpression')) delete vs.valueExpression + if (vs.hasOwnProperty('valueExpression')) delete vs.valueExpression; if (vs.operand && Array.isArray(vs.operand)) { for (let i = 0; i < vs.operand.length; i++) { - this._cleanValueSpec(vs.operand[i] as ValueObject) + this._cleanValueSpec(vs.operand[i] as ValueObject); } } - } + }; /** * @name veUtils/UtilsService#cleanElement @@ -117,50 +117,50 @@ export class ApiService { public cleanElement(elem: T, forEdit?: boolean): T { if (elem.type === 'Property' || elem.type === 'Port') { if (!elem.defaultValue) { - elem.defaultValue = null + elem.defaultValue = null; } } if (elem.type === 'Slot') { - if (!Array.isArray(elem.value)) (elem as LiteralObject).value = [] + if (!Array.isArray(elem.value)) (elem as LiteralObject).value = []; } if (elem.value && Array.isArray(elem.value)) { - ;(elem as LiteralObject).value.forEach((value: unknown) => { + (elem as LiteralObject).value.forEach((value: unknown) => { if (typeof value === 'object' && value !== null) - this._cleanValueSpec(value as ExpressionObject) - }) + this._cleanValueSpec(value as ExpressionObject); + }); } if (elem._contents) { - this._cleanValueSpec((elem as ViewObject)._contents) + this._cleanValueSpec((elem as ViewObject)._contents); } if (elem.specification) { - this._cleanValueSpec((elem as InstanceSpecObject).specification) + this._cleanValueSpec((elem as InstanceSpecObject).specification); } if (elem.type === 'Class') { if (elem._contents && elem.contains) { - delete elem.contains + delete elem.contains; } if (elem._allowedElementIds) { - delete elem._allowedElementIds + delete elem._allowedElementIds; } } if (elem.hasOwnProperty('specialization')) { - delete elem.specialization + delete elem.specialization; } if (!elem.hasOwnProperty('appliedStereotypeIds') && elem._appliedStereotypeIds) { - elem.appliedStereotypeIds = elem._appliedStereotypeIds + elem.appliedStereotypeIds = elem._appliedStereotypeIds; } if (forEdit) { //only keep editable or needed keys in edit object instead of everything - const keys = Object.keys(elem) + const keys = Object.keys(elem); keys.forEach((key) => { if (this.editKeys.indexOf(key) >= 0) { - return + return; } - delete elem[key] - }) + delete elem[key]; + }); } - return elem + return elem; } /** @@ -171,10 +171,10 @@ export class ApiService { * @returns {RequestObject} with default values for ref and commit */ public normalize = (reqOb: RequestObject): RequestObject => { - reqOb.refId = !reqOb.refId ? 'master' : reqOb.refId - reqOb.commitId = !reqOb.commitId ? 'latest' : reqOb.commitId - return reqOb - } + reqOb.refId = !reqOb.refId ? 'master' : reqOb.refId; + reqOb.commitId = !reqOb.commitId ? 'latest' : reqOb.commitId; + return reqOb; + }; /** * @name veUtils/UtilsService#makeRequestObject @@ -188,8 +188,8 @@ export class ApiService { projectId: elementOb._projectId, refId: elementOb._refId, commitId: elementOb._commitId, - } - } + }; + }; /** * @name veUtils/UtilsService#makeElementRequestObject @@ -204,7 +204,7 @@ export class ApiService { projectId: elementOb._projectId, refId: elementOb._refId, commitId: elementOb._commitId, - } + }; } /** @@ -218,18 +218,18 @@ export class ApiService { * @returns {Array} key to be used in CacheService */ public makeCacheKey(reqOb: RequestObject | null, elementId: string, edit?: boolean, type?: string): string[] { - const key: string[] = [] - const keyType: string = type ? type : 'element' - key.push(keyType) + const key: string[] = []; + const keyType: string = type ? type : 'element'; + key.push(keyType); if (reqOb !== null) { - if (reqOb.projectId) key.push(reqOb.projectId) - if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId) + if (reqOb.projectId) key.push(reqOb.projectId); + if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId); if (!keyType.includes('history') && reqOb.commitId !== null) - key.push(!reqOb.commitId ? 'latest' : reqOb.commitId) + key.push(!reqOb.commitId ? 'latest' : reqOb.commitId); } - if (elementId !== '') key.push(elementId) - if (edit) key.push('edit') - return key + if (elementId !== '') key.push(elementId); + if (edit) key.push('edit'); + return key; } /** @@ -277,16 +277,16 @@ export class ApiService { i === '_created' || i === '_commitId' ) { - continue + continue; } if (edit.hasOwnProperty(i) && orig.hasOwnProperty(i) && server.hasOwnProperty(i)) { if (!_.isEqual(orig[i], server[i])) { - return true + return true; } } } - return false - } + return false; + }; /** * @name veUtils/UtilsService#isRestrictedValue @@ -320,8 +320,8 @@ export class ApiService { * */ public createUUID = (): string => { - return uuid.v4() - } + return uuid.v4(); + }; /** * @name veUtils/UtilsService#createUniqueId @@ -330,8 +330,8 @@ export class ApiService { * @returns {string} unique SysML element ID */ public createUniqueId = (): string => { - return `ve-${this.getVeVersion().replace(/\./g, '-')}-${this.createUUID()}` - } + return `ve-${this.getVeVersion().replace(/\./g, '-')}-${this.createUUID()}`; + }; /** * @name veUtils/UtilsService#isView @@ -346,17 +346,17 @@ export class ApiService { e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('VIEW_SID', this.schema)) >= 0 || e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('DOCUMENT_SID', this.schema)) >= 0 ) { - return true + return true; } - const otherViewSids: string[] = this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema) + const otherViewSids: string[] = this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema); for (const otherViewSid of otherViewSids) { if (e.appliedStereotypeIds.indexOf(otherViewSid) >= 0) { - return true + return true; } } } - return false - } + return false; + }; /** * @name veUtils/UtilsService#isDocument @@ -369,8 +369,8 @@ export class ApiService { return ( e.appliedStereotypeIds && e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('DOCUMENT_SID', this.schema)) >= 0 - ) - } + ); + }; /** * @name veUtils/UtilsService#isRequirement @@ -381,15 +381,15 @@ export class ApiService { */ public isRequirement = (e: ElementObject): boolean => { if (e.appliedStereotypeIds) { - const reqSids = this.schemaSvc.getSchema('REQUIREMENT_SID', this.schema) + const reqSids = this.schemaSvc.getSchema('REQUIREMENT_SID', this.schema); for (const reqSid of reqSids) { if (e.appliedStereotypeIds.indexOf(reqSid) >= 0) { - return true + return true; } } } - return false - } + return false; + }; } -veUtils.service('ApiService', ApiService) +veUtils.service('ApiService', ApiService); diff --git a/src/ve-utils/mms-api-client/Authorization.service.ts b/src/ve-utils/mms-api-client/Authorization.service.ts index 85bb4a34b..da0b5ec12 100644 --- a/src/ve-utils/mms-api-client/Authorization.service.ts +++ b/src/ve-utils/mms-api-client/Authorization.service.ts @@ -1,10 +1,10 @@ -import { CacheService, EditService, SessionService } from '@ve-utils/core' -import { ElementService, HttpService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client' +import { CacheService, EditService, SessionService } from '@ve-utils/core'; +import { ElementService, HttpService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms'; /** * @ngdoc service @@ -19,7 +19,7 @@ import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms' * * Provide general authorization functions. I.e. login, logout, etc... */ export class AuthService { - private token: string | null + private token: string | null; static $inject = [ '$q', '$http', @@ -31,7 +31,7 @@ export class AuthService { 'ProjectService', 'SessionService', 'EditService', - ] + ]; constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -44,64 +44,64 @@ export class AuthService { private sessionSvc: SessionService, private autosaveSvc: EditService ) { - this.token = localStorage.getItem('token') + this.token = localStorage.getItem('token'); } getAuthorized(credentialsJSON: AuthRequest): VePromise { - const deferred = this.$q.defer() - const loginURL = this.uRLSvc.getAuthenticationUrl() + const deferred = this.$q.defer(); + const loginURL = this.uRLSvc.getAuthenticationUrl(); this.$http.post(loginURL, credentialsJSON).then( (success) => { - this.uRLSvc.setToken(success.data.token) - this.token = success.data.token - localStorage.setItem('token', this.token) - deferred.resolve(this.token) + this.uRLSvc.setToken(success.data.token); + this.token = success.data.token; + localStorage.setItem('token', this.token); + deferred.resolve(this.token); }, (fail: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(fail)) + deferred.reject(this.uRLSvc.handleHttpStatus(fail)); } - ) - return deferred.promise + ); + return deferred.promise; } removeToken = (): void => { - localStorage.removeItem('token') - this.token = undefined - this.uRLSvc.setToken(null) - this.httpSvc.dropAll() - this.elementSvc.reset() - this.projectSvc.reset() - this.viewSvc.reset() - this.cacheSvc.reset() - this.autosaveSvc.reset() - this.sessionSvc.clear() - } + localStorage.removeItem('token'); + this.token = undefined; + this.uRLSvc.setToken(null); + this.httpSvc.dropAll(); + this.elementSvc.reset(); + this.projectSvc.reset(); + this.viewSvc.reset(); + this.cacheSvc.reset(); + this.autosaveSvc.reset(); + this.sessionSvc.clear(); + }; getToken = (): string => { - return this.token - } + return this.token; + }; checkLogin(): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); if (!this.token) { - deferred.reject(false) - return deferred.promise + deferred.reject(false); + return deferred.promise; } - this.uRLSvc.setToken(this.token) + this.uRLSvc.setToken(this.token); this.$http.get(this.uRLSvc.getCheckTokenURL()).then( (response: angular.IHttpResponse) => { if (response.status === 401) { - deferred.reject(response) + deferred.reject(response); } else { - deferred.resolve(response.data) + deferred.resolve(response.data); } }, (fail) => { - deferred.reject(fail) - this.removeToken() + deferred.reject(fail); + this.removeToken(); } - ) - return deferred.promise + ); + return deferred.promise; } // async isAuthenticated(): Promise { @@ -125,22 +125,22 @@ export class AuthService { // } logout(): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.checkLogin() .then( () => { - this.removeToken() + this.removeToken(); //$cookies.remove('com.tomsawyer.web.license.user'); }, () => { - this.removeToken() + this.removeToken(); } ) .finally(() => { - deferred.resolve(true) - }) - return deferred.promise + deferred.resolve(true); + }); + return deferred.promise; } } -veUtils.service('AuthService', AuthService) +veUtils.service('AuthService', AuthService); diff --git a/src/ve-utils/mms-api-client/Base.service.ts b/src/ve-utils/mms-api-client/Base.service.ts index fd017847a..f42ead346 100644 --- a/src/ve-utils/mms-api-client/Base.service.ts +++ b/src/ve-utils/mms-api-client/Base.service.ts @@ -1,32 +1,32 @@ -import { VePromise } from '@ve-types/angular' -import { BasicResponse, MmsObject } from '@ve-types/mms' +import { VePromise } from '@ve-types/angular'; +import { BasicResponse, MmsObject } from '@ve-types/mms'; export class BaseApiService { protected inProgress: { - [key: string]: VePromise> - } = {} + [key: string]: VePromise>; + } = {}; protected _isInProgress = (key: string): boolean => { - return this.inProgress.hasOwnProperty(key) - } + return this.inProgress.hasOwnProperty(key); + }; protected _getInProgress>(key: string): VePromise { - if (this._isInProgress(key)) return this.inProgress[key] as unknown as VePromise - else return + if (this._isInProgress(key)) return this.inProgress[key] as unknown as VePromise; + else return; } protected _addInProgress>( key: string, promise: VePromise ): void { - this.inProgress[key] = promise as unknown as VePromise> + this.inProgress[key] = promise as unknown as VePromise>; } protected _removeInProgress = (key: string): void => { - delete this.inProgress[key] - } + delete this.inProgress[key]; + }; public reset = (): void => { - this.inProgress = {} - } + this.inProgress = {}; + }; } diff --git a/src/ve-utils/mms-api-client/Element.service.ts b/src/ve-utils/mms-api-client/Element.service.ts index b97b1ea90..f0c83d5cb 100644 --- a/src/ve-utils/mms-api-client/Element.service.ts +++ b/src/ve-utils/mms-api-client/Element.service.ts @@ -1,12 +1,12 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { CacheService, EditObject, EditService } from '@ve-utils/core' -import { ApiService, httpCallback, HttpService, URLService } from '@ve-utils/mms-api-client' -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' +import { CacheService, EditObject, EditService } from '@ve-utils/core'; +import { ApiService, httpCallback, HttpService, URLService } from '@ve-utils/mms-api-client'; +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular' +import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular'; import { CommitObject, CommitResponse, @@ -21,7 +21,7 @@ import { RequestObject, SearchResponse, TaggedValueObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc service @@ -35,7 +35,7 @@ import { * * An element CRUD service with additional convenience methods for managing edits. */ export class ElementService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'EditService', 'URLService', 'ApiService', 'HttpService'] + static $inject = ['$q', '$http', 'CacheService', 'EditService', 'URLService', 'ApiService', 'HttpService']; constructor( private $q: VeQService, @@ -46,7 +46,7 @@ export class ElementService extends BaseApiService { private apiSvc: ApiService, private httpSvc: HttpService ) { - super() + super(); } /** @@ -105,71 +105,71 @@ export class ElementService extends BaseApiService { refresh?: boolean, allowEmpty?: boolean ): VePromise { - this.apiSvc.normalize(reqOb) - const requestCacheKey = this.getRequestKey(reqOb, reqOb.elementId) + this.apiSvc.normalize(reqOb); + const requestCacheKey = this.getRequestKey(reqOb, reqOb.elementId); if (!reqOb.projectId) { - console.log('foo') + console.log('foo'); } - const url = this.uRLSvc.getElementURL(reqOb) - const cached: T = this.cacheSvc.get(requestCacheKey) + const url = this.uRLSvc.getElementURL(reqOb); + const cached: T = this.cacheSvc.get(requestCacheKey); // if it's in the this.inProgress queue get it immediately if (this._isInProgress(url)) { //change to change priority if it's already in the queue - this.httpSvc.ping(url, weight) - return this._getInProgress(url) as VePromise + this.httpSvc.ping(url, weight); + return this._getInProgress(url) as VePromise; } - const deletedRequestCacheKey = this.getRequestKey(reqOb, reqOb.elementId) - deletedRequestCacheKey.push('deleted') - const deleted = this.cacheSvc.get(deletedRequestCacheKey) + const deletedRequestCacheKey = this.getRequestKey(reqOb, reqOb.elementId); + deletedRequestCacheKey.push('deleted'); + const deleted = this.cacheSvc.get(deletedRequestCacheKey); if (deleted && !refresh) { return new this.$q((resolve, reject) => { return reject({ status: 410, recentVersionOfElement: deleted, message: 'Deleted', - }) - }) + }); + }); } if (cached && !refresh) { return new this.$q((resolve, reject) => { - return resolve(cached) - }) + return resolve(cached); + }); } this._addInProgress( url, new this.$q((resolve, reject) => { const successCallback: httpCallback> = (response) => { - const data = response.data - this._removeInProgress(url) + const data = response.data; + this._removeInProgress(url); if (Array.isArray(data.elements) && data.elements.length > 0) { - resolve(this.cacheElement(reqOb, data.elements[0])) + resolve(this.cacheElement(reqOb, data.elements[0])); } else if (allowEmpty) { - resolve(null) + resolve(null); } else { reject({ status: 500, message: 'Server Error: empty response', - }) //TODO + }); //TODO } - } + }; const errorCallback: httpCallback> = (response) => { - const data = response.data - const reason = this.uRLSvc.handleHttpStatus(response) - this._removeInProgress(url) + const data = response.data; + const reason = this.uRLSvc.handleHttpStatus(response); + this._removeInProgress(url); if (data && data.deleted && data.deleted.length > 0 && data.deleted[0].id === reqOb.elementId) { - reason.recentVersionOfElement = data.deleted[0] - this.cacheDeletedElement(reqOb, data.deleted[0]) + reason.recentVersionOfElement = data.deleted[0]; + this.cacheDeletedElement(reqOb, data.deleted[0]); } if (allowEmpty && response.status == 404) { - resolve(null) + resolve(null); } else { - reject(reason) + reject(reason); } - } - this.httpSvc.get>(url, successCallback, errorCallback, weight) + }; + this.httpSvc.get>(url, successCallback, errorCallback, weight); }) - ) - return this._getInProgress(url) as VePromise + ); + return this._getInProgress(url) as VePromise; } /** @@ -190,44 +190,44 @@ export class ElementService extends BaseApiService { refresh?: boolean ): VePromise> { return new this.$q>((resolve, reject) => { - const request: { elements: { id: string }[] } = { elements: [] } - const existing: T[] = [] - this.apiSvc.normalize(reqOb) + const request: { elements: { id: string }[] } = { elements: [] }; + const existing: T[] = []; + this.apiSvc.normalize(reqOb); for (let i = 0; i < reqOb.elementId.length; i++) { - const id = reqOb.elementId[i] - const requestCacheKey = this.getRequestKey(reqOb, id) - const exist = this.cacheSvc.get(requestCacheKey) + const id = reqOb.elementId[i]; + const requestCacheKey = this.getRequestKey(reqOb, id); + const exist = this.cacheSvc.get(requestCacheKey); if (exist && !refresh) { - existing.push(exist) - continue + existing.push(exist); + continue; } - request.elements.push({ id: id }) + request.elements.push({ id: id }); } if (request.elements.length === 0) { - resolve(existing) - return + resolve(existing); + return; } this.$http.put>(this.uRLSvc.getPutElementsURL(reqOb), request).then( (response) => { - const data = response.data.elements - let i + const data = response.data.elements; + let i; if (data && data.length > 0) { for (let i = 0; i < data.length; i++) { - existing.push(this.cacheElement(reqOb, data[i])) + existing.push(this.cacheElement(reqOb, data[i])); } } - const deleted = response.data.deleted + const deleted = response.data.deleted; if (deleted && deleted.length > 0) { for (let i = 0; i < deleted.length; i++) { - this.cacheDeletedElement(reqOb, deleted[i]) + this.cacheDeletedElement(reqOb, deleted[i]); } } - resolve(existing) + resolve(existing); }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ) - }) + ); + }); } /** @@ -242,45 +242,45 @@ export class ElementService extends BaseApiService { * @returns {object} cached object */ cacheElement(reqOb: RequestObject, elementOb: T): T { - let result: T = this.apiSvc.cleanElement(elementOb) - const requestCacheKey = this.getRequestKey(reqOb, result.id) - const origResultCommit = result._commitId + let result: T = this.apiSvc.cleanElement(elementOb); + const requestCacheKey = this.getRequestKey(reqOb, result.id); + const origResultCommit = result._commitId; if (reqOb.commitId === 'latest') { - const resultCommitCopy: T = _.cloneDeep(result) - result._commitId = 'latest' //so realCacheKey is right later - const commitCacheKey = this.apiSvc.makeCacheKey(this.apiSvc.makeRequestObject(resultCommitCopy), result.id) //save historic element - this.cacheSvc.put(commitCacheKey, resultCommitCopy, true) + const resultCommitCopy: T = _.cloneDeep(result); + result._commitId = 'latest'; //so realCacheKey is right later + const commitCacheKey = this.apiSvc.makeCacheKey(this.apiSvc.makeRequestObject(resultCommitCopy), result.id); //save historic element + this.cacheSvc.put(commitCacheKey, resultCommitCopy, true); } - const realCacheKey = this.getElementKey(result) - result._commitId = origResultCommit //restore actual commitId + const realCacheKey = this.getElementKey(result); + result._commitId = origResultCommit; //restore actual commitId if (!_.isEqual(realCacheKey, requestCacheKey)) { - this.cacheSvc.link(requestCacheKey, realCacheKey) + this.cacheSvc.link(requestCacheKey, realCacheKey); } - result = this.cacheSvc.put(realCacheKey, result, true) - return result + result = this.cacheSvc.put(realCacheKey, result, true); + return result; } openEdit(elementOb: T, clean: boolean): EditObject { - const result: T = clean ? this.apiSvc.cleanElement(elementOb, true) : elementOb - result._commitId = 'latest' - const editKey = this.getEditElementKey(elementOb) + const result: T = clean ? this.apiSvc.cleanElement(elementOb, true) : elementOb; + result._commitId = 'latest'; + const editKey = this.getEditElementKey(elementOb); - return this.editSvc.addOrUpdate(editKey, result) as EditObject + return this.editSvc.addOrUpdate(editKey, result) as EditObject; } cacheDeletedElement = (reqOb: RequestObject, deletedOb: ElementObject): void => { - const requestCacheKey = this.getRequestKey(reqOb, deletedOb.id) - requestCacheKey.push('deleted') + const requestCacheKey = this.getRequestKey(reqOb, deletedOb.id); + requestCacheKey.push('deleted'); const deletedReqOb: RequestObject = { projectId: deletedOb._projectId, refId: deletedOb._refId, commitId: deletedOb._commitId, - } - const commitCacheKey = this.apiSvc.makeCacheKey(deletedReqOb, deletedOb.id) - this.cacheSvc.link(requestCacheKey, commitCacheKey) - this.cacheSvc.put(commitCacheKey, deletedOb, true) - } + }; + const commitCacheKey = this.apiSvc.makeCacheKey(deletedReqOb, deletedOb.id); + this.cacheSvc.link(requestCacheKey, commitCacheKey); + this.cacheSvc.put(commitCacheKey, deletedOb, true); + }; /** * @name veUtils/ElementService#getElementForEdit @@ -322,15 +322,15 @@ export class ElementService extends BaseApiService { weight?: number, overwrite?: boolean ): VePromise, ElementsResponse> { - this.apiSvc.normalize(reqOb) - const requestCacheKey = this.getEditKey(reqOb) - const url = this.uRLSvc.getElementURL(reqOb) + 'edit' + this.apiSvc.normalize(reqOb); + const requestCacheKey = this.getEditKey(reqOb); + const url = this.uRLSvc.getElementURL(reqOb) + 'edit'; if (!this._isInProgress(url)) { - const openEdit = this.editSvc.get(requestCacheKey) + const openEdit = this.editSvc.get(requestCacheKey); if (openEdit && !overwrite) { return new this.$q, ElementsResponse>((resolve, reject) => { - return resolve(openEdit) - }) + return resolve(openEdit); + }); } this._addInProgress( url, @@ -338,20 +338,20 @@ export class ElementService extends BaseApiService { this.getElement(reqOb, weight) .then( (result) => { - const copy = this.apiSvc.cleanElement(_.cloneDeep(result), true) - resolve(this.editSvc.addOrUpdate(requestCacheKey, copy, overwrite) as EditObject) + const copy = this.apiSvc.cleanElement(_.cloneDeep(result), true); + resolve(this.editSvc.addOrUpdate(requestCacheKey, copy, overwrite) as EditObject); }, (reason) => { - reject(reason) + reject(reason); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); }) - ) + ); } - return this._getInProgress(url) as VePromise, ElementsResponse> + return this._getInProgress(url) as VePromise, ElementsResponse>; } /** @@ -370,11 +370,11 @@ export class ElementService extends BaseApiService { weight?: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); if (!reqOb.depth) { - reqOb.depth = -1 + reqOb.depth = -1; } - return this.getGenericElements(this.uRLSvc.getOwnedElementURL(reqOb), reqOb, 'elements', weight, refresh) + return this.getGenericElements(this.uRLSvc.getOwnedElementURL(reqOb), reqOb, 'elements', weight, refresh); } /** @@ -395,17 +395,17 @@ export class ElementService extends BaseApiService { weight: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb) - const requestCacheKey = this.getRequestKey(reqOb, jsonKey) + this.apiSvc.normalize(reqOb); + const requestCacheKey = this.getRequestKey(reqOb, jsonKey); if (this._isInProgress(url)) { - this.httpSvc.ping(url, weight) - return this._getInProgress(url) as VePromise> + this.httpSvc.ping(url, weight); + return this._getInProgress(url) as VePromise>; } - const cached = this.cacheSvc.get(requestCacheKey) + const cached = this.cacheSvc.get(requestCacheKey); if (cached && !refresh) { return new this.$q>((resolve, reject) => { - return resolve(cached) - }) + return resolve(cached); + }); } this._addInProgress( url, @@ -413,29 +413,29 @@ export class ElementService extends BaseApiService { this.httpSvc.get>( url, (response) => { - const results: T[] = [] - const elements: T[] = response.data[jsonKey] + const results: T[] = []; + const elements: T[] = response.data[jsonKey]; for (let i = 0; i < elements.length; i++) { - const element = elements[i] + const element = elements[i]; if (!element) { //check for possible null - continue + continue; } - results.push(this.cacheElement(reqOb, element)) + results.push(this.cacheElement(reqOb, element)); } - this._removeInProgress(url) - resolve(results) - return + this._removeInProgress(url); + resolve(results); + return; }, (response: angular.IHttpResponse>) => { - this._removeInProgress(url) - reject(this.uRLSvc.handleHttpStatus(response)) + this._removeInProgress(url); + reject(this.uRLSvc.handleHttpStatus(response)); }, weight - ) + ); }) - ) - return this._getInProgress>(url) as VePromise> + ); + return this._getInProgress>(url) as VePromise>; } //called by updateElement, fills in all keys for element to be updated @@ -451,45 +451,45 @@ export class ElementService extends BaseApiService { }, 2) .then((data) => { */ - const ob = _.cloneDeep(elementOb) //make a copy - ob._commitId = 'latest' - const editOb = this.editSvc.get(this.getEditElementKey(elementOb)) + const ob = _.cloneDeep(elementOb); //make a copy + ob._commitId = 'latest'; + const editOb = this.editSvc.get(this.getEditElementKey(elementOb)); if (editOb && editOb.element) { Object.keys(editOb.element).forEach((key) => { if (!elementOb.hasOwnProperty(key)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - ob[key] = editOb.element[key] + ob[key] = editOb.element[key]; } - }) + }); } if (ob._displayedElementIds) { - delete ob._displayedElementIds + delete ob._displayedElementIds; } if (ob._allowedElementIds) { - delete ob._allowedElementIds + delete ob._allowedElementIds; } if (ob._childViews && !elementOb._childViews) { - delete ob._childViews + delete ob._childViews; } if (ob.type && ob.type.endsWith('TaggedValue') && ob.value && (ob as TaggedValueObject).value.length > 0) { // make sure value array only has the value - const newvalues = [] + const newvalues = []; for (const val of (ob as TaggedValueObject).value) { if (ob.type === 'ElementTaggedValue') { - newvalues.push(val.elementId) + newvalues.push(val.elementId); } else { - newvalues.push({ value: val.value }) + newvalues.push({ value: val.value }); } } if (ob.type === 'ElementTaggedValue') { - ob.valueIds = newvalues - delete ob.value + ob.valueIds = newvalues; + delete ob.value; } else { - ob.value = newvalues + ob.value = newvalues; } } - delete ob._commitId - return ob + delete ob._commitId; + return ob; /* resolve(ob); }, () => { @@ -497,7 +497,7 @@ export class ElementService extends BaseApiService { }); }); */ - } + }; /** * @name veUtils/ElementService#updateElement @@ -521,12 +521,12 @@ export class ElementService extends BaseApiService { return new this.$q((resolve, reject) => { const handleSuccess = (data: ElementsResponse): void => { - let e: T = data.elements[0] + let e: T = data.elements[0]; if (data.elements.length > 1 && elementOb.id) { for (let i = 0; i < data.elements.length; i++) { if (data.elements[i].id === elementOb.id) { - e = data.elements[i] + e = data.elements[i]; } } } @@ -535,33 +535,33 @@ export class ElementService extends BaseApiService { refId: e._refId, commitId: 'latest', elementId: e.id, - } - const resp: T = this.cacheElement(metaOb, e) + }; + const resp: T = this.cacheElement(metaOb, e); // const editCopy = _.cloneDeep(e) // this.cacheElement(metaOb, editCopy, true) const history = this.cacheSvc.get( this.apiSvc.makeCacheKey(metaOb, metaOb.elementId, false, 'history') - ) + ); if (history) { - const id = e._commitId ? e._commitId : 'latest' + const id = e._commitId ? e._commitId : 'latest'; history.unshift({ _creator: e._modifier, _created: e._modified, id: id, _refId: e._refId, _projectId: e._projectId, - }) + }); } - resolve(resp) - } + resolve(resp); + }; if (!elementOb.hasOwnProperty('id')) { reject({ status: 400, message: 'Element id not found, create element first!', - }) + }); } - const postElem = this.fillInElement(elementOb) + const postElem = this.fillInElement(elementOb); //.then((postElem) => { this.$http .post>( @@ -578,32 +578,32 @@ export class ElementService extends BaseApiService { ) .then( (response) => { - const rejected = response.data.rejected + const rejected = response.data.rejected; if (rejected && rejected.length > 0 && rejected[0].code === 304 && rejected[0].object) { //elem will be rejected if server detects no changes - resolve(rejected[0].object) - return + resolve(rejected[0].object); + return; } if (!Array.isArray(response.data.elements) || response.data.elements.length === 0) { if (allowEmpty) { - resolve(null) + resolve(null); } else { reject({ status: 500, message: 'Server Error: empty response', - }) + }); } - return + return; } - handleSuccess(response.data) + handleSuccess(response.data); }, (response: angular.IHttpResponse>) => { if (response.status === 409) { - const serverOb = response.data.elements[0] - this.apiSvc.cleanElement(serverOb) - const origCommit = elementOb._commitId - elementOb._commitId = 'latest' + const serverOb = response.data.elements[0]; + this.apiSvc.cleanElement(serverOb); + const origCommit = elementOb._commitId; + elementOb._commitId = 'latest'; const origOb = this.cacheSvc.get( this.apiSvc.makeCacheKey( { @@ -613,29 +613,29 @@ export class ElementService extends BaseApiService { }, elementOb.id ) - ) - elementOb._commitId = origCommit + ); + elementOb._commitId = origCommit; if (!origOb) { - reject(this.uRLSvc.handleHttpStatus(response)) - return + reject(this.uRLSvc.handleHttpStatus(response)); + return; } if (!this.apiSvc.hasConflict(postElem, origOb, serverOb)) { - elementOb._modified = serverOb._modified + elementOb._modified = serverOb._modified; this.updateElement(elementOb, returnChildViews).then( (good) => { - resolve(good) + resolve(good); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); } else { - reject(this.uRLSvc.handleHttpStatus(response)) + reject(this.uRLSvc.handleHttpStatus(response)); } - } else reject(this.uRLSvc.handleHttpStatus(response)) + } else reject(this.uRLSvc.handleHttpStatus(response)); } - ) - }) + ); + }); } /** @@ -655,15 +655,15 @@ export class ElementService extends BaseApiService { return new this.$q>((resolve, reject) => { if (this._validate(elementObs)) { const postElements = elementObs.map((elementOb) => { - return this.fillInElement(elementOb) as T - }) + return this.fillInElement(elementOb) as T; + }); - const groupOfElements = this._groupElementsByProjectIdAndRefId(postElements) - const promises: VePromise>[] = [] + const groupOfElements = this._groupElementsByProjectIdAndRefId(postElements); + const promises: VePromise>[] = []; Object.keys(groupOfElements).forEach((key) => { - promises.push(this._bulkUpdate(groupOfElements[key], returnChildViews)) - }) + promises.push(this._bulkUpdate(groupOfElements[key], returnChildViews)); + }); // responses is an array of response corresponding to both successful and failed requests with the following format // [ { state: 'fulfilled', value: the value returned by the server }, @@ -672,27 +672,27 @@ export class ElementService extends BaseApiService { this.$q.allSettled(promises).then((responses) => { // get all the successful requests const successfulRequests = responses.filter((response) => { - return response.state === 'fulfilled' - }) + return response.state === 'fulfilled'; + }); const successValues = _.flatten( successfulRequests.map((response) => { - return response.value + return response.value; }) - ) + ); if (successfulRequests.length === promises.length) { // All requests succeeded - resolve(successValues) + resolve(successValues); } else { // some requests failed const rejectionReasons: VePromiseReason>[] = responses .filter((response) => { - return response.state === 'rejected' + return response.state === 'rejected'; }) .map((response): unknown => { - return response.reason as VePromiseReason> - }) as VePromiseReason>[] + return response.reason as VePromiseReason>; + }) as VePromiseReason>[]; // since we could have multiple failed requests when having some successful requests, // reject with the following format so that the client can deal with them at a granular level if @@ -704,18 +704,18 @@ export class ElementService extends BaseApiService { failedRequests: rejectionReasons, successfulRequests: successValues, }, - }) + }); } - }, reject) + }, reject); } else { const response: VePromiseReason> = { status: 400, message: 'Some of the elements do not have id, _projectId, _refId', data: {}, - } - reject(response) + }; + reject(response); } - }) + }); } /** @@ -728,9 +728,9 @@ export class ElementService extends BaseApiService { * create is successful. */ createElement(reqOb: ElementCreationRequest): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getPostElementsURL(reqOb) + const url = this.uRLSvc.getPostElementsURL(reqOb); this.$http .post>(url, { elements: reqOb.elements, @@ -743,23 +743,23 @@ export class ElementService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }) - return + }); + return; } - let resp: T = response.data.elements[0] + let resp: T = response.data.elements[0]; if (response.data.elements.length > 1 && reqOb.elements[0].id) { for (let i = 0; i < response.data.elements.length; i++) { if (response.data.elements[i].id === reqOb.elements[0].id) { - resp = response.data.elements[i] + resp = response.data.elements[i]; } } } - resolve(this.cacheElement(reqOb, resp)) + resolve(this.cacheElement(reqOb, resp)); }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ) - }) + ); + }); } /** @@ -772,9 +772,9 @@ export class ElementService extends BaseApiService { * create is successful. */ createElements(reqOb: ElementCreationRequest): VePromise> { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q>((resolve, reject) => { - const url = this.uRLSvc.getPostElementsURL(reqOb) + const url = this.uRLSvc.getPostElementsURL(reqOb); this.$http .post>(url, { elements: reqOb.elements, @@ -787,22 +787,22 @@ export class ElementService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }) - return + }); + return; } - const results: T[] = [] + const results: T[] = []; for (let i = 0; i < response.data.elements.length; i++) { - results.push(this.cacheElement(reqOb, response.data.elements[i])) + results.push(this.cacheElement(reqOb, response.data.elements[i])); // const editCopy = _.cloneDeep(response.data.elements[i]) // this.cacheElement(reqOb, editCopy, true) } - resolve(results) + resolve(results); }, (response: angular.IHttpResponse>) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } /** @@ -818,9 +818,9 @@ export class ElementService extends BaseApiService { elementOb: T ): VePromise< { - status?: boolean - server?: T - cache?: T + status?: boolean; + server?: T; + cache?: T; }, ElementsResponse > { @@ -828,46 +828,46 @@ export class ElementService extends BaseApiService { projectId: elementOb._projectId, refId: elementOb._refId, elementId: elementOb.id, - } + }; return new this.$q< { - status?: boolean - server?: T - cache?: T + status?: boolean; + server?: T; + cache?: T; }, ElementsResponse >((resolve, reject) => { - const orig = this.cacheSvc.get(this.apiSvc.makeCacheKey(reqOb, elementOb.id, false)) + const orig = this.cacheSvc.get(this.apiSvc.makeCacheKey(reqOb, elementOb.id, false)); if (!orig) { - return resolve({ status: false }) + return resolve({ status: false }); } this.$http.get>(this.uRLSvc.getElementURL(reqOb)).then( (response) => { - let server = _.cloneDeep(response.data.elements[0]) - delete server._modified - delete server._read - delete server._creator - server = this.apiSvc.cleanElement(server) - let current: ElementObject = _.cloneDeep(orig) - delete current._modified - delete current._read - delete current._creator - current = this.apiSvc.cleanElement(current) + let server = _.cloneDeep(response.data.elements[0]); + delete server._modified; + delete server._read; + delete server._creator; + server = this.apiSvc.cleanElement(server); + let current: ElementObject = _.cloneDeep(orig); + delete current._modified; + delete current._read; + delete current._creator; + current = this.apiSvc.cleanElement(current); if (_.isEqual(server, current)) { - resolve({ status: false }) + resolve({ status: false }); } else { resolve({ status: true, server: response.data.elements[0], cache: orig, - }) + }); } }, (response: angular.IHttpResponse>) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } /** @@ -887,8 +887,8 @@ export class ElementService extends BaseApiService { queryParams?: QueryParams, weight? ): VePromise, SearchResponse> { - this.apiSvc.normalize(reqOb) - const url = this.uRLSvc.getElementSearchURL(reqOb, queryParams) + this.apiSvc.normalize(reqOb); + const url = this.uRLSvc.getElementSearchURL(reqOb, queryParams); return new this.$q, SearchResponse>((resolve, reject) => { this.$http.post(url, query).then( (response: angular.IHttpResponse>) => { @@ -901,12 +901,12 @@ export class ElementService extends BaseApiService { // result.push(toAdd); //} //resolve(result); - resolve(response.data) + resolve(response.data); }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ) - }) + ); + }); } /** @@ -923,62 +923,62 @@ export class ElementService extends BaseApiService { weight: number, update?: boolean ): VePromise { - this.apiSvc.normalize(reqOb) - const url = this.uRLSvc.getElementHistoryURL(reqOb) + this.apiSvc.normalize(reqOb); + const url = this.uRLSvc.getElementHistoryURL(reqOb); if (this._isInProgress(url)) { - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } - const requestCacheKey: string[] = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'history') + const requestCacheKey: string[] = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'history'); if (this.cacheSvc.exists(requestCacheKey) && !update) { return new this.$q((resolve, reject) => { - return resolve(this.cacheSvc.get(requestCacheKey)) - }) + return resolve(this.cacheSvc.get(requestCacheKey)); + }); } this._addInProgress( url, new this.$q((resolve, reject) => { this.$http.get(this.uRLSvc.getElementHistoryURL(reqOb)).then( (response: angular.IHttpResponse) => { - this.cacheSvc.put(requestCacheKey, response.data.commits, true) - this._removeInProgress(url) - resolve(this.cacheSvc.get(requestCacheKey)) + this.cacheSvc.put(requestCacheKey, response.data.commits, true); + this._removeInProgress(url); + resolve(this.cacheSvc.get(requestCacheKey)); }, (response: angular.IHttpResponse) => { - this._removeInProgress(url) - this.apiSvc.handleErrorCallback(response, reject) + this._removeInProgress(url); + this.apiSvc.handleErrorCallback(response, reject); } - ) + ); }) - ) - return this._getInProgress(url) as VePromise + ); + return this._getInProgress(url) as VePromise; } public getRequestKey(reqOb: RequestObject, id: string, edit?: boolean): string[] { - return this.apiSvc.makeCacheKey(reqOb, id, edit) + return this.apiSvc.makeCacheKey(reqOb, id, edit); } public getElementRequest(elementOb: ElementObject): ElementsRequest { - const req = this.apiSvc.makeRequestObject(elementOb) - ;(req as ElementsRequest).elementId = elementOb.id - return req as ElementsRequest + const req = this.apiSvc.makeRequestObject(elementOb); + (req as ElementsRequest).elementId = elementOb.id; + return req as ElementsRequest; } public getElementKey(elementOb: ElementObject, edit?: boolean): string[] { - return this.getRequestKey(this.getElementRequest(elementOb), elementOb.id, edit) + return this.getRequestKey(this.getElementRequest(elementOb), elementOb.id, edit); } public getEditKey(reqOb: ElementsRequest): string[] { - const key: string[] = [] + const key: string[] = []; if (reqOb !== null) { - if (reqOb.projectId) key.push(reqOb.projectId) - if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId) + if (reqOb.projectId) key.push(reqOb.projectId); + if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId); } - key.push(reqOb.elementId) - return key + key.push(reqOb.elementId); + return key; } public getEditElementKey(e: ElementObject): string[] { - return [e._projectId, e._refId, e.id] + return [e._projectId, e._refId, e.id]; } public getElementQualifiedName(reqOb: ElementsRequest): VePromise> { @@ -991,33 +991,33 @@ export class ElementService extends BaseApiService { recurse: { ownerId: 'id', }, - } + }; this.search(reqOb, queryOb).then( (data) => { - let qualifiedName = '' - const elements = data.elements.reverse() - const entries = elements.entries() + let qualifiedName = ''; + const elements = data.elements.reverse(); + const entries = elements.entries(); for (const [i, element] of entries) { if (element.hasOwnProperty('name')) { - qualifiedName += element.name + qualifiedName += element.name; } if (i != elements.length - 1) { - qualifiedName += '/' + qualifiedName += '/'; } } - return resolve(qualifiedName) + return resolve(qualifiedName); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } private _groupElementsByProjectIdAndRefId(elementObs: T[]): _.Dictionary { return _.groupBy(elementObs, (element) => { - return element._projectId + '|' + element._refId - }) + return element._projectId + '|' + element._refId; + }); } private _createMetaOb(element: ElementObject): ElementsRequest { @@ -1026,7 +1026,7 @@ export class ElementService extends BaseApiService { refId: element._refId, commitId: 'latest', elementId: element.id, - } + }; } private _validate(elementObs: ElementObject[]): boolean { @@ -1035,8 +1035,8 @@ export class ElementService extends BaseApiService { elementOb.hasOwnProperty('id') && elementOb.hasOwnProperty('_projectId') && elementOb.hasOwnProperty('_refId') - ) - }) + ); + }); } private _bulkUpdate>( @@ -1053,7 +1053,7 @@ export class ElementService extends BaseApiService { : this.uRLSvc.getPostElementsURL({ projectId: elements[0]._projectId, refId: elements[0]._refId, - }) + }); this.$http .post>( url, @@ -1065,32 +1065,32 @@ export class ElementService extends BaseApiService { ) .then( (response) => { - this._bulkUpdateSuccessHandler(response, resolve) + this._bulkUpdateSuccessHandler(response, resolve); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } private _bulkUpdateSuccessHandler( serverResponse: angular.IHttpResponse>, resolve: angular.IQResolveReject ): void { - const results: T[] = [] - const elements = serverResponse.data.elements + const results: T[] = []; + const elements = serverResponse.data.elements; if (elements && elements.length > 0) { elements.forEach((e) => { - const metaOb = this._createMetaOb(e) + const metaOb = this._createMetaOb(e); //const editCopy = _.cloneDeep(e) - results.push(this.cacheElement(metaOb, e)) + results.push(this.cacheElement(metaOb, e)); //this.cacheElement(metaOb, editCopy, true) const history = this.cacheSvc.get( this.apiSvc.makeCacheKey(metaOb, metaOb.elementId, false, 'history') - ) + ); if (history) { history.unshift({ _creator: e._modifier, @@ -1098,22 +1098,22 @@ export class ElementService extends BaseApiService { id: e._commitId, _refId: e._refId, _projectId: e._projectId, - }) + }); } - }) + }); } - const rejected: RejectedObject[] = serverResponse.data.rejected + const rejected: RejectedObject[] = serverResponse.data.rejected; if (rejected && rejected.length > 0) { rejected.forEach((e) => { if (e.code === 304 && e.object) { - results.push(e.object) //add any server rejected elements because they haven't changed - console.log(`[BULK UPDATE ELEMENT REJECTED]: ${e.code}: ${e.message}`) - console.log(e.object.id) + results.push(e.object); //add any server rejected elements because they haven't changed + console.log(`[BULK UPDATE ELEMENT REJECTED]: ${e.code}: ${e.message}`); + console.log(e.object.id); } - }) + }); } - resolve(results) + resolve(results); } } -veUtils.service('ElementService', ElementService) +veUtils.service('ElementService', ElementService); diff --git a/src/ve-utils/mms-api-client/Http.service.ts b/src/ve-utils/mms-api-client/Http.service.ts index aa84d7b37..601eff2ba 100644 --- a/src/ve-utils/mms-api-client/Http.service.ts +++ b/src/ve-utils/mms-api-client/Http.service.ts @@ -1,12 +1,12 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -export type httpCallback = (response: angular.IHttpResponse) => void +export type httpCallback = (response: angular.IHttpResponse) => void; export interface HttpServiceRequest { - url: string - successCallback: httpCallback - errorCallback: httpCallback - weight: number + url: string; + successCallback: httpCallback; + errorCallback: httpCallback; + weight: number; } /** @@ -15,24 +15,24 @@ export interface HttpServiceRequest { * * Provides prioritization and caching for $http service calls */ export class HttpService { - private queue: HttpServiceRequest[][] = [] - cache: { [key: string]: HttpServiceRequest } = {} - inProgress = 0 - getLimit = 20 + private queue: HttpServiceRequest[][] = []; + cache: { [key: string]: HttpServiceRequest } = {}; + inProgress = 0; + getLimit = 20; - static $inject = ['$http'] + static $inject = ['$http']; constructor(private $http: angular.IHttpService) { - this.queue[0] = [] //high proirity - this.queue[1] = [] //low prority + this.queue[0] = []; //high proirity + this.queue[1] = []; //low prority } setOutboundLimit = (limit: number): void => { - this.getLimit = limit - } + this.getLimit = limit; + }; getQueue(): HttpServiceRequest[][] { - return this.queue + return this.queue; } /** @@ -47,68 +47,68 @@ export class HttpService { */ get(url: string, successCallback: httpCallback, errorCallback: httpCallback, weight: number): void { if (weight === undefined) { - weight = 1 + weight = 1; } const request: HttpServiceRequest = { url: url, successCallback: successCallback, errorCallback: errorCallback, weight: weight, - } + }; if (this.inProgress >= this.getLimit) { if (request.weight === 2) { this.$http .get(url) .then( (response: angular.IHttpResponse) => { - successCallback(response) + successCallback(response); }, (response: angular.IHttpResponse) => { - errorCallback(response) + errorCallback(response); } ) .finally(() => { if (this.cache.hasOwnProperty(url)) { - delete this.cache[url] + delete this.cache[url]; } - }) + }); } else if (request.weight === 0) { - this.queue[0].push(request) + this.queue[0].push(request); } else { - this.queue[1].push(request) + this.queue[1].push(request); } if (this.cache.hasOwnProperty(url)) { - if (this.cache[url].weight < request.weight) this.cache[url].weight = request.weight + if (this.cache[url].weight < request.weight) this.cache[url].weight = request.weight; } else { - this.cache[url] = request + this.cache[url] = request; } } else { - this.inProgress++ - this.cache[url] = request + this.inProgress++; + this.cache[url] = request; this.$http .get(url) .then( (response: angular.IHttpResponse) => { - successCallback(response) + successCallback(response); }, (response: angular.IHttpResponse) => { - errorCallback(response) + errorCallback(response); } ) .finally(() => { - this.inProgress-- - let next: HttpServiceRequest + this.inProgress--; + let next: HttpServiceRequest; if (this.cache.hasOwnProperty(url)) { - delete this.cache[url] + delete this.cache[url]; } if (this.queue[1].length > 0) { - next = this.queue[1].shift() - this.get(next.url, next.successCallback, next.errorCallback, next.weight) + next = this.queue[1].shift(); + this.get(next.url, next.successCallback, next.errorCallback, next.weight); } else if (this.queue[0].length > 0) { - next = this.queue[0].shift() - this.get(next.url, next.successCallback, next.errorCallback, next.weight) + next = this.queue[0].shift(); + this.get(next.url, next.successCallback, next.errorCallback, next.weight); } - }) + }); } } @@ -122,29 +122,29 @@ export class HttpService { ping = (url: string, weight?: number): void => { // ping should simply change the weight if (weight === undefined) { - weight = 1 + weight = 1; } if (this.cache.hasOwnProperty(url)) { if (weight > this.cache[url].weight) { - const request = this.cache[url] - let index: number - if (request.weight === 0) index = this.queue[0].indexOf(request) - else index = this.queue[1].indexOf(request) + const request = this.cache[url]; + let index: number; + if (request.weight === 0) index = this.queue[0].indexOf(request); + else index = this.queue[1].indexOf(request); if (weight === 1 && index !== -1) { - request.weight = 1 - this.queue[1].push(request) - this.queue[0].splice(index, 1) + request.weight = 1; + this.queue[1].push(request); + this.queue[0].splice(index, 1); } else if (weight === 2 && index !== -1) { if (request.weight === 0) { - this.queue[0].splice(index, 1) + this.queue[0].splice(index, 1); } else { - this.queue[1].splice(index, 1) + this.queue[1].splice(index, 1); } - this.get(request.url, request.successCallback, request.errorCallback, weight) + this.get(request.url, request.successCallback, request.errorCallback, weight); } } } - } + }; /** * @name veUtils/HttpService#ping @@ -155,23 +155,23 @@ export class HttpService { if (this.queue[1].length > 0) { //will the queue ever be defined? for (let i = 0; i < this.queue[1].length; i++) { - this.queue[1][i].weight = 0 + this.queue[1][i].weight = 0; // if(cache.hasOwnProperty(queue[1][i].request.url)) // cache[queue[1][i].request.url].weight = 0; - this.queue[0].push(this.queue[1][i]) + this.queue[0].push(this.queue[1][i]); //queue[1][i].shift(); } //queue[0] = queue[0].concat(queue[1]); - this.queue[1] = [] + this.queue[1] = []; } - } + }; dropAll = (): void => { - this.queue[1].length = 0 - this.queue[0].length = 0 - this.cache = {} - this.inProgress = 0 - } + this.queue[1].length = 0; + this.queue[0].length = 0; + this.cache = {}; + this.inProgress = 0; + }; } -veUtils.service('HttpService', HttpService) +veUtils.service('HttpService', HttpService); diff --git a/src/ve-utils/mms-api-client/Permissions.service.ts b/src/ve-utils/mms-api-client/Permissions.service.ts index e49f41a54..6ffa7d5bc 100644 --- a/src/ve-utils/mms-api-client/Permissions.service.ts +++ b/src/ve-utils/mms-api-client/Permissions.service.ts @@ -1,13 +1,13 @@ -import { URLService } from '@ve-utils/mms-api-client' +import { URLService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { PermissionsObject, PermissionsResponse, ProjectObject, RefObject } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { PermissionsObject, PermissionsResponse, ProjectObject, RefObject } from '@ve-types/mms'; export interface PermissionCache { - project: { [id: string]: boolean } - ref: { [id: string]: boolean } + project: { [id: string]: boolean }; + ref: { [id: string]: boolean }; } /** @@ -20,9 +20,9 @@ export interface PermissionCache { * * This utility service handles permissions inquiries */ export class PermissionsService { - private permissions: PermissionCache = { project: {}, ref: {} } + private permissions: PermissionCache = { project: {}, ref: {} }; - static $inject = ['$q', '$http', 'URLService'] + static $inject = ['$q', '$http', 'URLService']; constructor(private $q: VeQService, private $http: angular.IHttpService, private uRLSvc: URLService) {} @@ -30,15 +30,15 @@ export class PermissionsService { projectOb: ProjectObject, refOb: RefObject ): VePromise { - const url = this.uRLSvc.getPermissionsLookupURL() + const url = this.uRLSvc.getPermissionsLookupURL(); - const deferred = this.$q.defer() + const deferred = this.$q.defer(); if ( this.permissions.project[projectOb.id] !== undefined && this.permissions.ref[projectOb.id + '/' + refOb.id] !== undefined ) { - deferred.resolve(this.permissions) - return deferred.promise + deferred.resolve(this.permissions); + return deferred.promise; } this.$http .put(url, { @@ -58,39 +58,39 @@ export class PermissionsService { }) .then( (response) => { - const data: PermissionsObject[] = response.data.lookups + const data: PermissionsObject[] = response.data.lookups; if (Array.isArray(data) && data.length > 0) { data.forEach((d) => { if (d.type == 'PROJECT') { - this.permissions.project[d.projectId] = d.hasPrivilege + this.permissions.project[d.projectId] = d.hasPrivilege; } else { - this.permissions.ref[d.projectId + '/' + d.refId] = d.hasPrivilege + this.permissions.ref[d.projectId + '/' + d.refId] = d.hasPrivilege; } - }) - deferred.resolve(this.permissions) + }); + deferred.resolve(this.permissions); } else { deferred.reject({ status: 500, data: '', message: 'Server Error: empty response', - }) + }); } }, (response: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(response)) + deferred.reject(this.uRLSvc.handleHttpStatus(response)); } - ) + ); - return deferred.promise + return deferred.promise; } public hasProjectEditPermission = (projectId: string): boolean => { - return this.permissions.project[projectId] - } + return this.permissions.project[projectId]; + }; public hasBranchEditPermission = (projectId: string, refId: string): boolean => { - return this.permissions.ref[projectId + '/' + refId] - } + return this.permissions.ref[projectId + '/' + refId]; + }; } -veUtils.service('PermissionsService', PermissionsService) +veUtils.service('PermissionsService', PermissionsService); diff --git a/src/ve-utils/mms-api-client/Project.service.ts b/src/ve-utils/mms-api-client/Project.service.ts index 479fb6334..568bc96e5 100644 --- a/src/ve-utils/mms-api-client/Project.service.ts +++ b/src/ve-utils/mms-api-client/Project.service.ts @@ -1,10 +1,10 @@ -import { CacheService } from '@ve-utils/core' -import { ApiService, ElementService, URLService } from '@ve-utils/mms-api-client' -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' +import { CacheService } from '@ve-utils/core'; +import { ApiService, ElementService, URLService } from '@ve-utils/mms-api-client'; +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' +import { VePromise, VeQService } from '@ve-types/angular'; import { CommitObject, CommitResponse, @@ -18,7 +18,7 @@ import { ProjectsResponse, RefObject, RefsResponse, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc service @@ -33,7 +33,7 @@ import { * * This is a utility service for getting project, ref, commit information */ export class ProjectService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'ElementService', 'URLService', 'ApiService'] + static $inject = ['$q', '$http', 'CacheService', 'ElementService', 'URLService', 'ApiService']; constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -42,7 +42,7 @@ export class ProjectService extends BaseApiService { private uRLSvc: URLService, private apiSvc: ApiService ) { - super() + super(); } /** @@ -53,16 +53,16 @@ export class ProjectService extends BaseApiService { * @returns {Promise} Resolves to the org object. */ public getOrg(orgId: string): VePromise { - const key = ['org', orgId] - const url = this.uRLSvc.getOrgURL(orgId) + const key = ['org', orgId]; + const url = this.uRLSvc.getOrgURL(orgId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(key)) { - resolve(this.cacheSvc.get(key)) - this._removeInProgress(url) - return + resolve(this.cacheSvc.get(key)); + this._removeInProgress(url); + return; } else { this.$http .get(url) @@ -73,23 +73,23 @@ export class ProjectService extends BaseApiService { status: 404, message: 'Org not found', type: 'error', - }) + }); } else { - this.cacheSvc.put(key, response.data.orgs[0], true) - resolve(this.cacheSvc.get(key)) + this.cacheSvc.put(key, response.data.orgs[0], true); + resolve(this.cacheSvc.get(key)); } }, (response: angular.IHttpResponse) => this.apiSvc.handleErrorCallback(response, reject) ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } /** @@ -99,46 +99,46 @@ export class ProjectService extends BaseApiService { * @returns {Promise} Resolves into array of org objects. */ public getOrgs(updateCache?: boolean): VePromise { - const key = 'orgs' + const key = 'orgs'; if (!this._isInProgress(key)) { this._addInProgress( key, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(key) && !updateCache) { - resolve(this.cacheSvc.get(key)) - this._removeInProgress(key) - return + resolve(this.cacheSvc.get(key)); + this._removeInProgress(key); + return; } else { this.$http .get(this.uRLSvc.getOrgsURL()) .then( (response) => { - const orgs: OrgObject[] = [] + const orgs: OrgObject[] = []; for (let i = 0; i < response.data.orgs.length; i++) { - const org = response.data.orgs[i] - this.cacheSvc.put(['org', org.id], org, true) - orgs.push(this.cacheSvc.get(['org', org.id])) + const org = response.data.orgs[i]; + this.cacheSvc.put(['org', org.id], org, true); + orgs.push(this.cacheSvc.get(['org', org.id])); } - this.cacheSvc.put(key, orgs, false) - resolve(this.cacheSvc.get(key)) + this.cacheSvc.put(key, orgs, false); + resolve(this.cacheSvc.get(key)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(key) - }) + this._removeInProgress(key); + }); } }) - ) + ); } - return this._getInProgress(key) as VePromise + return this._getInProgress(key) as VePromise; } public createOrg(name: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getOrgsURL() + const url = this.uRLSvc.getOrgsURL(); this.$http .post(url, { orgs: { name: name }, @@ -146,29 +146,29 @@ export class ProjectService extends BaseApiService { }) .then( (response) => { - const org = response.data.orgs[0] - const key = ['org', org.id] - this.cacheSvc.put(key, response.data.orgs[0], true) - resolve(this.cacheSvc.get(key)) + const org = response.data.orgs[0]; + const key = ['org', org.id]; + this.cacheSvc.put(key, response.data.orgs[0], true); + resolve(this.cacheSvc.get(key)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } public getProjects(orgId?: string, updateCache?: boolean): VePromise { - const url = this.uRLSvc.getProjectsURL(orgId) + const url = this.uRLSvc.getProjectsURL(orgId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = !orgId ? 'projects' : ['projects', orgId] + const cacheKey = !orgId ? 'projects' : ['projects', orgId]; if (this.cacheSvc.exists(cacheKey) && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)) - this._removeInProgress(url) - return + resolve(this.cacheSvc.get(cacheKey)); + this._removeInProgress(url); + return; } else { this.$http .get(url) @@ -179,62 +179,62 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } if (!orgId) { const orgProjects: { - [orgId: string]: ProjectObject[] - } = {} + [orgId: string]: ProjectObject[]; + } = {}; response.data.projects.forEach((project) => { - const porg = project.orgId + const porg = project.orgId; const pCacheKey = this.apiSvc.makeCacheKey( null, project.id, false, 'project' - ) + ); if (orgProjects[porg] === undefined) { - orgProjects[porg] = [] + orgProjects[porg] = []; } - orgProjects[porg].push(this.cacheSvc.put(pCacheKey, project, true)) + orgProjects[porg].push(this.cacheSvc.put(pCacheKey, project, true)); Object.keys(orgProjects).forEach((orgId) => { this.cacheSvc.put( this.apiSvc.makeCacheKey(null, orgId, false, 'projects'), orgProjects[orgId], false - ) - }) - }) + ); + }); + }); } - resolve(this.cacheSvc.put(cacheKey, response.data.projects)) + resolve(this.cacheSvc.put(cacheKey, response.data.projects)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as angular.IPromise + return this._getInProgress(url) as angular.IPromise; } public getProject(projectId: string, updateCache?: string): VePromise { - const url = this.uRLSvc.getProjectURL(projectId) + const url = this.uRLSvc.getProjectURL(projectId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = ['project', projectId] - const cached = this.cacheSvc.get(cacheKey) + const cacheKey = ['project', projectId]; + const cached = this.cacheSvc.get(cacheKey); if (cached && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)) - this._removeInProgress(url) + resolve(this.cacheSvc.get(cacheKey)); + this._removeInProgress(url); } else { this.$http .get(url) @@ -245,24 +245,24 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } - this.cacheSvc.put(cacheKey, response.data.projects[0], true) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, response.data.projects[0], true); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as angular.IPromise + return this._getInProgress(url) as angular.IPromise; } public getProjectMounts( @@ -270,12 +270,12 @@ export class ProjectService extends BaseApiService { refId: string, updateCache?: boolean ): VePromise { - const url = this.uRLSvc.getProjectMountsURL(projectId, refId) + const url = this.uRLSvc.getProjectMountsURL(projectId, refId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'project-mounts') + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'project-mounts'); this.getProject(projectId).then( (response: ProjectObject) => { @@ -284,14 +284,14 @@ export class ProjectService extends BaseApiService { _mounts: [], _projectId: response.id, _refId: refId, - } - const result: MountObject = Object.assign(mountOb, response) - const cached: MountObject = this.cacheSvc.get(cacheKey) + }; + const result: MountObject = Object.assign(mountOb, response); + const cached: MountObject = this.cacheSvc.get(cacheKey); if (this.cacheSvc.exists(cacheKey) && !updateCache) { - result._mounts.push(...cached._mounts) - resolve(result) - this._removeInProgress(url) - return + result._mounts.push(...cached._mounts); + resolve(result); + this._removeInProgress(url); + return; } else { this.$http .get(url) @@ -305,62 +305,62 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } if (response.data.projects[0]._mounts) { - result._mounts = (response.data.projects[0] as MountObject)._mounts + result._mounts = (response.data.projects[0] as MountObject)._mounts; } - resolve(this.cacheSvc.put(cacheKey, result, false)) + resolve(this.cacheSvc.put(cacheKey, result, false)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }, (response) => { - reject(response) - this._removeInProgress(url) + reject(response); + this._removeInProgress(url); } - ) + ); }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getAllMountsAsArray = (project: MountObject): MountObject[] => { - const projectsList: MountObject[] = [project] - const mounts = project._mounts + const projectsList: MountObject[] = [project]; + const mounts = project._mounts; const getMountsArray = (mounts: MountObject[], projectsList: MountObject[]): void => { if (Array.isArray(mounts) && mounts.length !== 0) { for (let i = 0; i < mounts.length; i++) { - projectsList.push(mounts[i]) + projectsList.push(mounts[i]); if (mounts[i]._mounts) { - getMountsArray(mounts[i]._mounts, projectsList) + getMountsArray(mounts[i]._mounts, projectsList); } } } - } - getMountsArray(mounts, projectsList) - return projectsList - } + }; + getMountsArray(mounts, projectsList); + return projectsList; + }; public getRefs(projectId: string): VePromise { - const cacheKey = this.apiSvc.makeCacheKey(null, projectId, false, 'refs') - const url = this.uRLSvc.getRefsURL(projectId) + const cacheKey = this.apiSvc.makeCacheKey(null, projectId, false, 'refs'); + const url = this.uRLSvc.getRefsURL(projectId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(cacheKey)) { - resolve(this.cacheSvc.get(cacheKey)) - this._removeInProgress(url) - return + resolve(this.cacheSvc.get(cacheKey)); + this._removeInProgress(url); + return; } else { this.$http .get(url) @@ -371,73 +371,73 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }) - return + }); + return; } - const refs: RefObject[] = [] + const refs: RefObject[] = []; for (let index = 0; index < response.data.refs.length; index++) { - const ref: RefObject = response.data.refs[index] + const ref: RefObject = response.data.refs[index]; if (ref.id === 'master') { - ref.type = 'Branch' + ref.type = 'Branch'; } const refCacheKey: string[] = this.apiSvc.makeCacheKey( { projectId: projectId, refId: ref.id }, '', false, 'ref' - ) - this.cacheSvc.put(refCacheKey, ref, true) - refs.push(this.cacheSvc.get(refCacheKey)) + ); + this.cacheSvc.put(refCacheKey, ref, true); + refs.push(this.cacheSvc.get(refCacheKey)); } - this.cacheSvc.put(cacheKey, refs, false) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, refs, false); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getRef(refId: string, projectId: string, updateCache?: boolean): VePromise { - const url = this.uRLSvc.getRefURL(projectId, refId) + const url = this.uRLSvc.getRefURL(projectId, refId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'ref') - const cached = this.cacheSvc.get(cacheKey) + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'ref'); + const cached = this.cacheSvc.get(cacheKey); if (cached && !updateCache) { - this._removeInProgress(url) - resolve(cached) + this._removeInProgress(url); + resolve(cached); } else { this.$http .get(url) .then( (response) => { - this.cacheSvc.put(cacheKey, response.data.refs[0]) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, response.data.refs[0]); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getCommits( @@ -446,11 +446,11 @@ export class ProjectService extends BaseApiService { timestamp?: string, limit?: number ): VePromise { - let url: string + let url: string; if (timestamp !== null) { - url = this.uRLSvc.getCommitsURL(projectId, refId, timestamp, limit) + url = this.uRLSvc.getCommitsURL(projectId, refId, timestamp, limit); } else { - url = this.uRLSvc.getCommitsURL(projectId, refId, null, limit) + url = this.uRLSvc.getCommitsURL(projectId, refId, null, limit); } if (!this._isInProgress(url)) { this._addInProgress( @@ -466,63 +466,63 @@ export class ProjectService extends BaseApiService { message: 'Project does not exist at specified time.', type: 'error', - }) - return + }); + return; } - resolve(response.data.commits) + resolve(response.data.commits); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getCommit(projectId: string, refId: string, commitId: string): VePromise { - const url = this.uRLSvc.getCommitUrl(projectId, refId, commitId) + const url = this.uRLSvc.getCommitUrl(projectId, refId, commitId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId, commitId }, '', false, 'commit') + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId, commitId }, '', false, 'commit'); if (this.cacheSvc.exists(cacheKey)) { - resolve(this.cacheSvc.get(cacheKey)) + resolve(this.cacheSvc.get(cacheKey)); } else { this.$http .get(url) .then( (response) => { - resolve(this.cacheSvc.put(cacheKey, response.data.commits[0])) + resolve(this.cacheSvc.put(cacheKey, response.data.commits[0])); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public createRef(refOb: RefObject, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefsURL(projectId) + const url = this.uRLSvc.getRefsURL(projectId); const cacheKey = this.apiSvc.makeCacheKey( { projectId: refOb._projectId, refId: refOb.id }, '', false, 'ref' - ) + ); this.$http .post(url, { refs: [refOb], @@ -536,30 +536,30 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } - const createdRef = response.data.refs[0] + const createdRef = response.data.refs[0]; const list = this.cacheSvc.get( this.apiSvc.makeCacheKey(null, projectId, false, 'refs'), true - ) + ); if (list) { - list.push(createdRef) + list.push(createdRef); } - this.cacheSvc.put(cacheKey, createdRef) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, createdRef); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } public updateRef(refOb: RefObject, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefsURL(projectId) + const url = this.uRLSvc.getRefsURL(projectId); this.$http .post(url, { refs: [refOb], @@ -573,49 +573,49 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } - const resp = response.data.refs[0] - this.cacheSvc.put(['ref', projectId, resp.id], resp, true) - resolve(this.cacheSvc.get(['ref', projectId, resp.id])) + const resp = response.data.refs[0]; + this.cacheSvc.put(['ref', projectId, resp.id], resp, true); + resolve(this.cacheSvc.get(['ref', projectId, resp.id])); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } public deleteRef(refId: string, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefURL(projectId, refId) + const url = this.uRLSvc.getRefURL(projectId, refId); this.$http.delete(url).then( (response) => { - const key = this.apiSvc.makeCacheKey({ refId, projectId }, '', false, 'ref') - const refOb = this.cacheSvc.get(key) + const key = this.apiSvc.makeCacheKey({ refId, projectId }, '', false, 'ref'); + const refOb = this.cacheSvc.get(key); if (refOb) { - this.cacheSvc.remove(key) + this.cacheSvc.remove(key); const list = this.cacheSvc.get( this.apiSvc.makeCacheKey(null, projectId, false, 'refs'), true - ) + ); if (list) { for (let i = 0; i < list.length; i++) { if (list[i].id === refOb.id) { - list.splice(i, 1) - break + list.splice(i, 1); + break; } } } } - resolve() + resolve(); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } public getGroups( @@ -623,14 +623,14 @@ export class ProjectService extends BaseApiService { refId: string, updateCache?: boolean ): VePromise { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'groups') - const url = this.uRLSvc.getGroupsURL(projectId, refId) + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'groups'); + const url = this.uRLSvc.getGroupsURL(projectId, refId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(cacheKey) && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)) + resolve(this.cacheSvc.get(cacheKey)); } else { this.$http .get(url) @@ -642,64 +642,64 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } - const groups: GroupObject[] = [] + const groups: GroupObject[] = []; const reqOb = { projectId: projectId, refId: refId, commitId: 'latest', elementId: '', - } + }; for (let i = 0; i < response.data.groups.length; i++) { - let group: GroupObject = response.data.groups[i] - reqOb.elementId = group.id - group = this.elementSvc.cacheElement(reqOb, group) - this.cacheSvc.put(['group', projectId, refId, group.id], group, true) + let group: GroupObject = response.data.groups[i]; + reqOb.elementId = group.id; + group = this.elementSvc.cacheElement(reqOb, group); + this.cacheSvc.put(['group', projectId, refId, group.id], group, true); groups.push( this.cacheSvc.get(['group', projectId, refId, group.id]) - ) + ); } - this.cacheSvc.put(cacheKey, groups, false) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, groups, false); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getGroup(id: string, projectId: string, refId: string): VePromise { return new this.$q((resolve, reject) => { this.getGroups(projectId, refId).then( (data) => { - const result = this.cacheSvc.get(['group', projectId, refId, id]) + const result = this.cacheSvc.get(['group', projectId, refId, id]); if (result) { - resolve(result) + resolve(result); } else { reject({ status: 404, message: 'Group not found', type: 'error', - }) + }); } }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } } -veUtils.service('ProjectService', ProjectService) +veUtils.service('ProjectService', ProjectService); diff --git a/src/ve-utils/mms-api-client/URL.service.ts b/src/ve-utils/mms-api-client/URL.service.ts index 11e0a3684..a024dbeaf 100644 --- a/src/ve-utils/mms-api-client/URL.service.ts +++ b/src/ve-utils/mms-api-client/URL.service.ts @@ -1,7 +1,7 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromiseReason } from '@ve-types/angular' -import { VeConfig } from '@ve-types/config' +import { VePromiseReason } from '@ve-types/angular'; +import { VeConfig } from '@ve-types/config'; import { ArtifactsRequest, BasicResponse, @@ -10,7 +10,7 @@ import { QueryParams, RequestObject, ViewsRequest, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc service @@ -33,63 +33,63 @@ import { * actually getting the resources from a different server, solution TBD) */ export class URLService { - readonly root: string - readonly url: URL - private token: string - private veConfig: VeConfig = window.__env + readonly root: string; + readonly url: URL; + private token: string; + private veConfig: VeConfig = window.__env; - static $inject = [] + static $inject = []; constructor(readonly basePath?: string, readonly apiUrl?: string) { if (!this.apiUrl) { - this.apiUrl = this.veConfig.apiUrl + this.apiUrl = this.veConfig.apiUrl; } if (!this.apiUrl) { - throw new Error('Unable to find "apiUrl" configuration for MMS. Please check your configuration file.') + throw new Error('Unable to find "apiUrl" configuration for MMS. Please check your configuration file.'); } - this.url = new URL(this.apiUrl) - this.url.pathname = this.veConfig.basePath ? this.veConfig.basePath : '/' + this.url = new URL(this.apiUrl); + this.url.pathname = this.veConfig.basePath ? this.veConfig.basePath : '/'; - this.root = `${this.apiUrl}${this.basePath ? this.basePath : ''}` - const token = localStorage.getItem('token') - this.token = `${token}` + this.root = `${this.apiUrl}${this.basePath ? this.basePath : ''}`; + const token = localStorage.getItem('token'); + this.token = `${token}`; } getRoot = (): string => { - return this.root - } + return this.root; + }; getUrl = (): URL => { - return Object.assign({}, this.url) - } + return Object.assign({}, this.url); + }; setToken = (t: string): void => { - this.token = t - } + this.token = t; + }; getAuthorizationHeaderValue = (): string => { - return 'Bearer ' + this.token - } + return 'Bearer ' + this.token; + }; getAuthorizationHeader = (headers: angular.HttpHeaderType): angular.HttpHeaderType => { if (!this.token) { - const token = localStorage.getItem('token') + const token = localStorage.getItem('token'); if (!token) { - return headers + return headers; } else { - this.setToken(token) + this.setToken(token); } } if (!headers) { - headers = this.getHeaders() + headers = this.getHeaders(); } - headers.Authorization = this.getAuthorizationHeaderValue() - return headers - } + headers.Authorization = this.getAuthorizationHeaderValue(); + return headers; + }; getMmsServer = (): string => { - return this.apiUrl - } + return this.apiUrl; + }; /** * @name veUtils/URLService#setHeader @@ -101,7 +101,7 @@ export class URLService { return { 'Content-Type': 'application/json', Authorization: 'Bearer ' + this.token, - } + }; } /** @@ -112,10 +112,10 @@ export class URLService { * @returns {boolean} Returns true if the string has '-' in it */ isTimestamp = (version?: string): boolean => { - if (!version) return false - else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}[+]?-\d{4}$/.test(version.trim())) return true - return false - } + if (!version) return false; + else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}[+]?-\d{4}$/.test(version.trim())) return true; + return false; + }; /** * @name veUtils/URLService#getMmsVersionURL @@ -124,8 +124,8 @@ export class URLService { * @returns {object} Returns object with mmsversion */ getMmsVersionURL = (): string => { - return `${this.root}/mmsversion` - } + return `${this.root}/mmsversion`; + }; /** * @name veUtils/URLService#getSiteDashboardURL @@ -135,8 +135,8 @@ export class URLService { * @returns {string} The path for site dashboard. */ getSiteDashboardURL = (site: string): string => { - return `${this.root}/orgs/${site}/projects/${site}/branches/master/elements` - } + return `${this.root}/orgs/${site}/projects/${site}/branches/master/elements`; + }; /** * @name veUtils/URLService#getExportHtmlUrl @@ -146,67 +146,67 @@ export class URLService { * @returns {string} The url */ getExportHtmlUrl = (): string => { - return this.veConfig.printUrl - } + return this.veConfig.printUrl; + }; getAuthenticationUrl = (): string => { - return `${this.root}/authentication` - } + return `${this.root}/authentication`; + }; getPermissionsLookupURL = (): string => { - return `${this.root}/permissions` - } + return `${this.root}/permissions`; + }; getOrgURL = (orgId: string): string => { - return `${this.root}/orgs/${orgId}` - } + return `${this.root}/orgs/${orgId}`; + }; getOrgsURL = (): string => { - return `${this.root}/orgs` - } + return `${this.root}/orgs`; + }; getProjectsURL = (orgId?: string): string => { - if (orgId) return `${this.root}/projects?orgId=${orgId}` - return `${this.root}/projects` - } + if (orgId) return `${this.root}/projects?orgId=${orgId}`; + return `${this.root}/projects`; + }; getProjectURL = (projectId: string): string => { - return `${this.root}/projects/${projectId}` - } + return `${this.root}/projects/${projectId}`; + }; getProjectMountsURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/mounts` - } + return `${this.root}/projects/${projectId}/refs/${refId}/mounts`; + }; getRefsURL = (projectId: string): string => { - return `${this.root}/projects/${projectId}/refs` - } + return `${this.root}/projects/${projectId}/refs`; + }; getRefURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}` - } + return `${this.root}/projects/${projectId}/refs/${refId}`; + }; getCommitsURL = (projectId: string, refId: string, timestamp?: string, limit?: number): string => { - let r = `${this.root}/projects/${projectId}/refs/${refId}/commits` + let r = `${this.root}/projects/${projectId}/refs/${refId}/commits`; if (timestamp && this.isTimestamp(timestamp)) { - r = this._addUrlParam({ maxTimestamp: timestamp }, r) + r = this._addUrlParam({ maxTimestamp: timestamp }, r); if (!limit) { - limit = 1 + limit = 1; } } if (limit) { - r = this._addUrlParam({ limit: limit }, r) + r = this._addUrlParam({ limit: limit }, r); } - return r - } + return r; + }; getCommitUrl = (projectId: string, refId: string, commitId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/commits/${commitId}` - } + return `${this.root}/projects/${projectId}/refs/${refId}/commits/${commitId}`; + }; getGroupsURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/groups` - } + return `${this.root}/projects/${projectId}/refs/${refId}/groups`; + }; /** * @name veUtils/URLService#getProjectDocumentsURL @@ -216,9 +216,9 @@ export class URLService { * @returns {string} The url */ getProjectDocumentsURL = (reqOb: RequestObject): string => { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/documents` - return this.addVersion(r, reqOb.commitId) - } + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/documents`; + return this.addVersion(r, reqOb.commitId); + }; /** * @name veUtils/URLService#getImageURL @@ -228,8 +228,8 @@ export class URLService { * @returns {string} The path for image url queries. */ getImageURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` - return this.addVersion(r, reqOb.commitId) + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; + return this.addVersion(r, reqOb.commitId); } /** @@ -240,8 +240,8 @@ export class URLService { * @returns {string} The url. */ getElementURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views/${reqOb.elementId}` - return this.addVersion(r, reqOb.commitId) + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views/${reqOb.elementId}`; + return this.addVersion(r, reqOb.commitId); } // getViewDataIdsURL (reqOb: RequestObject): string { @@ -270,16 +270,16 @@ export class URLService { // } getOwnedElementURL(reqOb: ElementsRequest): string { - let recurseString = 'recurse=true' - if (reqOb.depth) recurseString = `depth=${reqOb.depth}` - let r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` - r = this.addVersion(r, reqOb.commitId) + let recurseString = 'recurse=true'; + if (reqOb.depth) recurseString = `depth=${reqOb.depth}`; + let r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; + r = this.addVersion(r, reqOb.commitId); if (r.indexOf('?') > 0) { - r += '&' + recurseString + r += '&' + recurseString; } else { - r += '?' + recurseString + r += '?' + recurseString; } - return r + return r; } /** @@ -290,7 +290,7 @@ export class URLService { * @returns {string} The url. */ getElementHistoryURL(reqOb: ElementsRequest): string { - return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/commits` + return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/commits`; } /** @@ -303,8 +303,8 @@ export class URLService { return this.addChildViews( `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views`, reqOb.returnChildViews - ) - } + ); + }; /** * @name veUtils/URLService#getPostElementsURL @@ -314,8 +314,8 @@ export class URLService { * @returns {string} The post elements url. */ getPostElementsURL = (reqOb: RequestObject): string => { - return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements` - } + return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements`; + }; /** * @name veUtils/URLService#getPutElementsURL @@ -325,9 +325,9 @@ export class URLService { * @returns {string} The post elements url. */ getPutElementsURL = (reqOb: RequestObject): string => { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views` - return this.addVersion(r, reqOb.commitId) - } + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views`; + return this.addVersion(r, reqOb.commitId); + }; /** * @name veUtils/URLService#getElementSearchURL @@ -338,18 +338,18 @@ export class URLService { * @returns {string} The post elements url. */ getElementSearchURL = (reqOb: RequestObject, queryParams?: QueryParams): string => { - let r: string - let urlParams = '' + let r: string; + let urlParams = ''; if (queryParams) { - urlParams = this._addUrlParam(queryParams) + urlParams = this._addUrlParam(queryParams); } if (urlParams !== '') { - r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search${urlParams}` + r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search${urlParams}`; } else { - r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search` + r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search`; } - return r - } + return r; + }; /** * @ngdocs method @@ -362,9 +362,9 @@ export class URLService { */ getArtifactURL(reqOb: ElementsRequest | ArtifactsRequest, artifactExtension?: string): string { const ext = - artifactExtension !== undefined ? artifactExtension : (reqOb as ArtifactsRequest).artifactExtension - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}` - return this.addToken(this.addVersion(r, reqOb.commitId)) + artifactExtension !== undefined ? artifactExtension : (reqOb as ArtifactsRequest).artifactExtension; + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}`; + return this.addToken(this.addVersion(r, reqOb.commitId)); } /** @@ -377,9 +377,9 @@ export class URLService { * @returns {string} url */ getArtifactEmbedURL(reqOb: ArtifactsRequest, artifactExtension: string): string { - const ext = artifactExtension !== undefined ? artifactExtension : 'undefined' - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}` - return this.addVersion(r, reqOb.commitId) + const ext = artifactExtension !== undefined ? artifactExtension : 'undefined'; + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}`; + return this.addVersion(r, reqOb.commitId); } /** @@ -391,8 +391,8 @@ export class URLService { * @returns {string} url */ getPutArtifactsURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` - return this.addVersion(r, reqOb.commitId) + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; + return this.addVersion(r, reqOb.commitId); } /** @@ -404,16 +404,16 @@ export class URLService { * @returns {string} url */ getArtifactHistoryURL(reqOb: ElementsRequest): string { - return this.getElementHistoryURL(reqOb) + return this.getElementHistoryURL(reqOb); } getCheckTokenURL = (): string => { - return `${this.root}/checkAuth` //TODO remove when server returns 404 - } + return `${this.root}/checkAuth`; //TODO remove when server returns 404 + }; getPersonURL = (username: string): string => { - return `${this.root}/users?user=${username}` - } + return `${this.root}/users?user=${username}`; + }; /** * @name veUtils/URLService#handleHttpStatus @@ -435,22 +435,22 @@ export class URLService { handleHttpStatus>( response: angular.IHttpResponse ): VePromiseReason { - const result: VePromiseReason = response - const data: U = result.data - if (result.status === 404) result.message = 'Not Found' + const result: VePromiseReason = response; + const data: U = result.data; + if (result.status === 404) result.message = 'Not Found'; else if (result.status === 500) { if (typeof data === 'string' && data.indexOf('ENOTFOUND') >= 0) - result.message = 'Network Error (Please check network)' - else result.message = 'Server Error' - } else if (result.status === 401 || result.status === 403) result.message = 'Permission Error' - else if (result.status === 409) result.message = 'Conflict' - else if (result.status === 400) result.message = 'BadRequestObject' - else if (result.status === 410) result.message = 'Deleted' - else if (result.status === 408) result.message = 'Timed Out' + result.message = 'Network Error (Please check network)'; + else result.message = 'Server Error'; + } else if (result.status === 401 || result.status === 403) result.message = 'Permission Error'; + else if (result.status === 409) result.message = 'Conflict'; + else if (result.status === 400) result.message = 'BadRequestObject'; + else if (result.status === 410) result.message = 'Deleted'; + else if (result.status === 408) result.message = 'Timed Out'; else if (result.status === 501) { - result.message = 'Caching' - } else result.message = 'Timed Out (Please check network)' - return result + result.message = 'Caching'; + } else result.message = 'Timed Out (Please check network)'; + return result; } /** @@ -462,18 +462,18 @@ export class URLService { * @returns {string} The url with commitId parameter added. */ private addVersion = (url: string, version: string): string => { - const r = url + const r = url; if (version && version !== 'latest') { - return this._addUrlParam({ commitId: version }, url) + return this._addUrlParam({ commitId: version }, url); } - return r - } + return r; + }; private addChildViews = (url: string, add: boolean): string => { - const r = url - if (!add) return r - return this._addUrlParam({ childviews: true }, r) - } + const r = url; + if (!add) return r; + return this._addUrlParam({ childviews: true }, r); + }; /** * @name veUtils/URLService#addToken @@ -483,31 +483,31 @@ export class URLService { * @returns {string} The url with commitId parameter added. */ private addToken = (url: string): string => { - return this._addUrlParam({ token: this.token }, url) - } + return this._addUrlParam({ token: this.token }, url); + }; private _addUrlParam( paramOb: { - [key: string]: string | boolean | number + [key: string]: string | boolean | number; }, url?: string ): string { - let urlParams = '' + let urlParams = ''; if (url) { - urlParams = url + urlParams = url; } for (const [key, value] of Object.entries(paramOb)) { - let v: string - if (typeof value === 'string') v = value - else v = value.toString() + let v: string; + if (typeof value === 'string') v = value; + else v = value.toString(); if (urlParams.indexOf('?') > 0) { - urlParams += `&${key}=${v}` + urlParams += `&${key}=${v}`; } else { - urlParams += `?${key}=${v}` + urlParams += `?${key}=${v}`; } } - return urlParams + return urlParams; } } -veUtils.service('URLService', URLService) +veUtils.service('URLService', URLService); diff --git a/src/ve-utils/mms-api-client/User.service.ts b/src/ve-utils/mms-api-client/User.service.ts index 74108055a..e14a27a69 100644 --- a/src/ve-utils/mms-api-client/User.service.ts +++ b/src/ve-utils/mms-api-client/User.service.ts @@ -1,14 +1,14 @@ -import { CacheService } from '@ve-utils/core' -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' -import { URLService } from '@ve-utils/mms-api-client/URL.service' +import { CacheService } from '@ve-utils/core'; +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; +import { URLService } from '@ve-utils/mms-api-client/URL.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { UserObject, UsersResponse } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { UserObject, UsersResponse } from '@ve-types/mms'; export class UserService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'URLService'] + static $inject = ['$q', '$http', 'CacheService', 'URLService']; constructor( private $q: VeQService, @@ -16,20 +16,20 @@ export class UserService extends BaseApiService { private cacheSvc: CacheService, private uRLSvc: URLService ) { - super() + super(); } getUserData(username: string): VePromise { - const key = ['user', username] - const url = this.uRLSvc.getPersonURL(username) - const cached = this.cacheSvc.get(key) + const key = ['user', username]; + const url = this.uRLSvc.getPersonURL(username); + const cached = this.cacheSvc.get(key); if (this._isInProgress(url)) { - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } if (cached) { return new this.$q((resolve, reject) => { - return resolve(cached) - }) + return resolve(cached); + }); } this._addInProgress( url, @@ -42,25 +42,25 @@ export class UserService extends BaseApiService { reject({ status: 404, message: 'User not found', - }) + }); } else { - this.cacheSvc.put(key, response.data.users[0], false) - resolve(this.cacheSvc.get(key)) + this.cacheSvc.put(key, response.data.users[0], false); + resolve(this.cacheSvc.get(key)); } }, (response: angular.IHttpResponse) => { - this.uRLSvc.handleHttpStatus(response) - reject(response) + this.uRLSvc.handleHttpStatus(response); + reject(response); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); }) - ) + ); - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } } -veUtils.service('UserService', UserService) +veUtils.service('UserService', UserService); diff --git a/src/ve-utils/mms-api-client/Value.service.ts b/src/ve-utils/mms-api-client/Value.service.ts index 411231339..2c52cdd83 100644 --- a/src/ve-utils/mms-api-client/Value.service.ts +++ b/src/ve-utils/mms-api-client/Value.service.ts @@ -1,15 +1,15 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { EditObject } from '@ve-utils/core' -import { ApiService } from '@ve-utils/mms-api-client/Api.service' -import { ElementService } from '@ve-utils/mms-api-client/Element.service' -import { ValueSpec } from '@ve-utils/utils' +import { EditObject } from '@ve-utils/core'; +import { ApiService } from '@ve-utils/mms-api-client/Api.service'; +import { ElementService } from '@ve-utils/mms-api-client/Element.service'; +import { ValueSpec } from '@ve-utils/utils'; -import { PropertySpec } from '@ve-components' +import { PropertySpec } from '@ve-components'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' +import { VePromise, VeQService } from '@ve-types/angular'; import { ConstraintObject, ElementObject, @@ -22,7 +22,7 @@ import { SlotObject, TaggedValueObject, ValueObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; export class ValueService { private valueTypes: { [type: string]: string } = { @@ -30,28 +30,28 @@ export class ValueService { port: 'defaultValue', slot: 'value', constraint: 'specification', - } + }; public addValueTypes: { [primitiveType: string]: string } = { string: 'LiteralString', boolean: 'LiteralBoolean', integer: 'LiteralInteger', real: 'LiteralReal', - } + }; - private taggedValue: string = 'value' - static $inject = ['$q', 'ApiService', 'ElementService'] + private taggedValue: string = 'value'; + static $inject = ['$q', 'ApiService', 'ElementService']; constructor(private $q: VeQService, private apiSvc: ApiService, private elementSvc: ElementService) {} public addValue = (editOb: EditObject, type: string): LiteralObject => { - const edit = editOb.element - let newValueSpec: ValueSpec + const edit = editOb.element; + let newValueSpec: ValueSpec; let elementOb: LiteralObject = { id: '', _projectId: edit._projectId, _refId: edit._refId, type: '', - } + }; switch (type) { case 'LiteralBoolean': { elementOb = Object.assign(elementOb, { @@ -59,9 +59,9 @@ export class ValueService { value: false, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) - newValueSpec = new ValueSpec(elementOb) - break + }); + newValueSpec = new ValueSpec(elementOb); + break; } case 'LiteralInteger': { elementOb = Object.assign(elementOb, { @@ -69,9 +69,9 @@ export class ValueService { value: 0, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) - newValueSpec = new ValueSpec(elementOb) - break + }); + newValueSpec = new ValueSpec(elementOb); + break; } case 'LiteralString': { elementOb = Object.assign(elementOb, { @@ -79,9 +79,9 @@ export class ValueService { value: '', id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) - newValueSpec = new ValueSpec(elementOb) - break + }); + newValueSpec = new ValueSpec(elementOb); + break; } case 'LiteralReal': { elementOb = Object.assign(elementOb, { @@ -89,9 +89,9 @@ export class ValueService { value: 0.0, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) - newValueSpec = new ValueSpec(elementOb) - break + }); + newValueSpec = new ValueSpec(elementOb); + break; } default: { elementOb = Object.assign(elementOb, { @@ -99,21 +99,21 @@ export class ValueService { value: {}, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) + }); } } if (edit.type == 'Property' || edit.type == 'Port') { - edit.defaultValue = newValueSpec + edit.defaultValue = newValueSpec; } - return newValueSpec - } + return newValueSpec; + }; public addEnumerationValue = ( propertySpec: PropertySpec, editOb: EditObject ): InstanceValueObject | ElementValueObject => { - const elementOb = editOb.element + const elementOb = editOb.element; let newValueSpec: InstanceValueObject | ElementValueObject = new ValueSpec({ type: 'InstanceValue', instanceId: propertySpec.options[0], @@ -121,7 +121,7 @@ export class ValueService { _refId: elementOb._refId, id: this.apiSvc.createUniqueId(), ownerId: elementOb.id, - }) + }); if (propertySpec.isTaggedValue) { newValueSpec = new ValueSpec({ type: 'ElementValue', @@ -130,51 +130,51 @@ export class ValueService { _refId: elementOb._refId, id: this.apiSvc.createUniqueId(), ownerId: elementOb.id, - }) + }); } - return newValueSpec - } + return newValueSpec; + }; public getValues(elementOb: ElementObject): ValueObject[] { if (elementOb.type === 'Property' || elementOb.type === 'Port') { if (elementOb.defaultValue) { - return [elementOb.defaultValue] as ValueObject[] + return [elementOb.defaultValue] as ValueObject[]; } else { - return [] + return []; } } if (elementOb.type === 'Slot') { - return (elementOb as SlotObject).value + return (elementOb as SlotObject).value; } if (elementOb.type === 'Constraint' && elementOb.specification) { - return [(elementOb as ConstraintObject).specification] + return [(elementOb as ConstraintObject).specification]; } if (elementOb.type === 'Expression') { - return (elementOb as ExpressionObject).operand + return (elementOb as ExpressionObject).operand; } - const i = elementOb.type.indexOf('TaggedValue') + const i = elementOb.type.indexOf('TaggedValue'); if (i > 0) { - let spoofType = '' - const type = elementOb.type.slice(0, i) + let spoofType = ''; + const type = elementOb.type.slice(0, i); if (type === 'Element') { - spoofType = 'ElementValue' - elementOb.value = [] + spoofType = 'ElementValue'; + elementOb.value = []; for (const [index, val] of (elementOb as ElementTaggedValueObject).valueIds.entries()) { - ;(elementOb as ElementTaggedValueObject).value.push({ + (elementOb as ElementTaggedValueObject).value.push({ id: `${elementOb.id}-slotvalue-${index}-elementvalue`, type: spoofType, elementId: val, _projectId: elementOb._projectId, _refId: elementOb._refId, - } as ElementValueObject) + } as ElementValueObject); } } else { - spoofType = `Literal${type}` + spoofType = `Literal${type}`; for (const val of (elementOb as TaggedValueObject).value) { - val.type = spoofType + val.type = spoofType; } } - return (elementOb as TaggedValueObject).value + return (elementOb as TaggedValueObject).value; } } @@ -187,53 +187,53 @@ export class ValueService { * For unsuccessful saves, it will be rejected with an object with reason. */ public isEnumeration(elementOb: ElementObject): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); if (elementOb.type === 'Enumeration') { - const isEnumeration = true + const isEnumeration = true; const reqOb: ElementsRequest = { elementId: elementOb.id, projectId: elementOb._projectId, refId: elementOb._refId, - } + }; const query = { params: { ownerId: elementOb.id, }, - } + }; this.elementSvc.search(reqOb, query).then( (val) => { - const newArray: ElementObject[] = [] + const newArray: ElementObject[] = []; // Filter for enumeration type for (let i = 0; i < val.elements.length; i++) { if (val.elements[i].type === 'EnumerationLiteral') { - newArray.push(val.elements[i]) + newArray.push(val.elements[i]); } } newArray.sort((a, b) => { - return a.name.localeCompare(b.name) - }) + return a.name.localeCompare(b.name); + }); deferred.resolve({ options: newArray, isEnumeration: isEnumeration, - }) + }); }, (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } else { - deferred.resolve({ options: [], isEnumeration: false }) + deferred.resolve({ options: [], isEnumeration: false }); } - return deferred.promise + return deferred.promise; } public isValue(elementOb: ElementObject): boolean { - const type = elementOb.type - return Object.keys(this.valueTypes).includes(type.toLowerCase()) || this.isTaggedValue(elementOb) + const type = elementOb.type; + return Object.keys(this.valueTypes).includes(type.toLowerCase()) || this.isTaggedValue(elementOb); } public isTaggedValue(elementOb: ElementObject): boolean { - return elementOb.type.endsWith('TaggedValue') + return elementOb.type.endsWith('TaggedValue'); } public hasValue(elementOb: ElementObject): boolean { @@ -245,92 +245,92 @@ export class ValueService { (elementOb.specification && Object.keys((elementOb as ConstraintObject).specification).length !== 0) || // Check if Slots and Tagged Values have any entries (elementOb.value && (elementOb as LiteralObject[]>).value.length > 0)) - ) + ); } public isEqual(a: ElementObject, b: ElementObject): boolean { if (this.valueTypes[a.type.toLowerCase()]) { - return _.isEqual(a[this.valueTypes[a.type.toLowerCase()]], b[this.valueTypes[a.type.toLowerCase()]]) + return _.isEqual(a[this.valueTypes[a.type.toLowerCase()]], b[this.valueTypes[a.type.toLowerCase()]]); } else if (this.isTaggedValue(a)) { - return _.isEqual(a[this.taggedValue], b[this.taggedValue]) + return _.isEqual(a[this.taggedValue], b[this.taggedValue]); } } public getPropertySpec(elementOb: ElementObject): VePromise { - const deferred = this.$q.defer() - let id: string = elementOb.typeId - let isSlot = false - let isEnumeration = false - let isTaggedValue = false - let options: ElementObject[] = [] + const deferred = this.$q.defer(); + let id: string = elementOb.typeId; + let isSlot = false; + let isEnumeration = false; + let isTaggedValue = false; + let options: ElementObject[] = []; if (elementOb.type === 'Slot') { - isSlot = true - id = (elementOb as SlotObject).definingFeatureId + isSlot = true; + id = (elementOb as SlotObject).definingFeatureId; } if (elementOb.type.includes('TaggedValue')) { - isTaggedValue = true - id = (elementOb as TaggedValueObject).tagDefinitionId + isTaggedValue = true; + id = (elementOb as TaggedValueObject).tagDefinitionId; } if (!id) { //no property type, will not be enum - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) - return deferred.promise + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + return deferred.promise; } // Get defining feature or type info const reqOb = { elementId: id, projectId: elementOb._projectId, refId: elementOb._refId, - } + }; this.elementSvc.getElement(reqOb).then( (value) => { if (isSlot || isTaggedValue) { if (!value.typeId) { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) - return + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + return; } //if it is a slot or tagged value check if the definition type is enumeration - reqOb.elementId = value.typeId + reqOb.elementId = value.typeId; this.elementSvc.getElement(reqOb).then( (val) => { this.isEnumeration(val).then( (enumValue: PropertySpec) => { if (enumValue.isEnumeration) { - isEnumeration = enumValue.isEnumeration - options = enumValue.options + isEnumeration = enumValue.isEnumeration; + options = enumValue.options; } - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); }, () => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); } - ) + ); }, () => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); } - ) + ); } else { this.isEnumeration(value).then( (enumValue) => { if (enumValue.isEnumeration) { - isEnumeration = enumValue.isEnumeration - options = enumValue.options + isEnumeration = enumValue.isEnumeration; + options = enumValue.options; } - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); }, (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } }, (reason) => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); } - ) - return deferred.promise + ); + return deferred.promise; } } -veUtils.service('ValueService', ValueService) +veUtils.service('ValueService', ValueService); diff --git a/src/ve-utils/mms-api-client/View.service.ts b/src/ve-utils/mms-api-client/View.service.ts index b01678771..931db9dcd 100644 --- a/src/ve-utils/mms-api-client/View.service.ts +++ b/src/ve-utils/mms-api-client/View.service.ts @@ -1,15 +1,15 @@ -import { IQResolveReject } from 'angular' -import _ from 'lodash' +import { IQResolveReject } from 'angular'; +import _ from 'lodash'; -import { CacheService } from '@ve-utils/core' -import { ElementService, URLService, ApiService } from '@ve-utils/mms-api-client' -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' -import { SchemaService } from '@ve-utils/model-schema' -import { Class, Expression, InstanceSpec, Package, ValueSpec } from '@ve-utils/utils' +import { CacheService } from '@ve-utils/core'; +import { ElementService, URLService, ApiService } from '@ve-utils/mms-api-client'; +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; +import { SchemaService } from '@ve-utils/model-schema'; +import { Class, Expression, InstanceSpec, Package, ValueSpec } from '@ve-utils/utils'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular' +import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular'; import { DocumentObject, ElementObject, @@ -35,32 +35,32 @@ import { ElementsResponse, GenericResponse, BasicResponse, -} from '@ve-types/mms' -import { TreeBranch, View2NodeMap } from '@ve-types/tree' +} from '@ve-types/mms'; +import { TreeBranch, View2NodeMap } from '@ve-types/tree'; export interface ViewData { - id: string - api: ViewApi - number?: string - topLevel?: boolean - first?: boolean - data?: ViewObject + id: string; + api: ViewApi; + number?: string; + topLevel?: boolean; + first?: boolean; + data?: ViewObject; } export interface ViewApi { - elementClicked(elementOb: ElementObject): void - elementTranscluded(elementOb: ElementObject, type: string): void + elementClicked(elementOb: ElementObject): void; + elementTranscluded(elementOb: ElementObject, type: string): void; } export interface DocumentMetadata { - numberingDepth: number - numberingSeparator: string - 'top-left'?: string - top?: string - 'top-right'?: string - 'bottom-left'?: string - bottom?: string - 'bottom-right'?: string + numberingDepth: number; + numberingSeparator: string; + 'top-left'?: string; + top?: string; + 'top-right'?: string; + 'bottom-left'?: string; + bottom?: string; + 'bottom-right'?: string; } /** @@ -78,9 +78,9 @@ export interface DocumentMetadata { * */ export class ViewService extends BaseApiService { - private schema: string = 'cameo' + private schema: string = 'cameo'; - static $inject = ['$q', '$http', 'URLService', 'ElementService', 'ApiService', 'CacheService', 'SchemaService'] + static $inject = ['$q', '$http', 'URLService', 'ElementService', 'ApiService', 'CacheService', 'SchemaService']; constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -90,7 +90,7 @@ export class ViewService extends BaseApiService { private cacheSvc: CacheService, private schemaSvc: SchemaService ) { - super() + super(); } /** @@ -102,86 +102,86 @@ export class ViewService extends BaseApiService { */ public downgradeDocument(elementOb: ViewObject): VePromise> { return new this.$q>((resolve, reject) => { - const clone = _.cloneDeep(elementOb) - clone.appliedStereotypeIds = [this.schemaSvc.getSchema('VIEW_SID', this.schema)] + const clone = _.cloneDeep(elementOb); + clone.appliedStereotypeIds = [this.schemaSvc.getSchema('VIEW_SID', this.schema)]; this.elementSvc.updateElements([clone], false).then( (data) => { - const cacheKey = ['documents', elementOb._projectId, elementOb._refId] - let index = -1 - const projectDocs: ViewObject[] = this.cacheSvc.get(cacheKey) + const cacheKey = ['documents', elementOb._projectId, elementOb._refId]; + let index = -1; + const projectDocs: ViewObject[] = this.cacheSvc.get(cacheKey); if (projectDocs) { for (let i = 0; i < projectDocs.length; i++) { if (projectDocs[i].id === elementOb.id) { - index = i - break + index = i; + break; } } if (index >= 0) { - projectDocs.splice(index, 1) + projectDocs.splice(index, 1); } } return resolve( data.filter((returnOb) => { - return returnOb.id === elementOb.id + return returnOb.id === elementOb.id; })[0] - ) + ); }, (reason) => { - return reject(reason) + return reject(reason); } - ) - }) + ); + }); } public getAllViews(reqOb: RequestObject, update?: boolean): VePromise { - const key = this.apiSvc.makeCacheKey(reqOb, '', false, 'views') - const inProgKey = key.join('-') + const key = this.apiSvc.makeCacheKey(reqOb, '', false, 'views'); + const inProgKey = key.join('-'); if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q((resolve, reject) => { - const cached = this.cacheSvc.get(key) + const cached = this.cacheSvc.get(key); if (cached && !update) { - resolve(cached) - this._removeInProgress(inProgKey) + resolve(cached); + this._removeInProgress(inProgKey); } else { - const searchTerms: VePromise, SearchResponse>[] = [] + const searchTerms: VePromise, SearchResponse>[] = []; const stereoIds = [ this.schemaSvc.getSchema('VIEW_SID', this.schema), this.schemaSvc.getSchema('DOCUMENT_SID', this.schema), ...this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema), - ] + ]; stereoIds.forEach((stId) => { searchTerms.push( this.elementSvc.search(reqOb, { params: { appliedStereotypeIds: stId }, }) - ) - }) + ); + }); this.$q .all(searchTerms) .then( (results) => { - let viewKeys = {} + let viewKeys = {}; results.forEach((result) => { - viewKeys = _(viewKeys).merge(_.keyBy(result.elements, 'id')) - }) - const views = _(viewKeys).values().value() as ViewObject[] - resolve(this.cacheSvc.put(key, views)) + viewKeys = _(viewKeys).merge(_.keyBy(result.elements, 'id')); + }); + const views = _(viewKeys).values().value() as ViewObject[]; + resolve(this.cacheSvc.put(key, views)); }, (reason: VePromiseReason>) => { - reject(reason) + reject(reason); } ) .finally(() => { - this._removeInProgress(inProgKey) - }) + this._removeInProgress(inProgKey); + }); } }) - ) + ); } - return this._getInProgress(inProgKey) as VePromise + return this._getInProgress(inProgKey) as VePromise; } /** @@ -201,46 +201,46 @@ export class ViewService extends BaseApiService { weight: number, update?: boolean ): VePromise { - this.apiSvc.normalize(reqOb) - const key = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'viewElements').join('-') + this.apiSvc.normalize(reqOb); + const key = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'viewElements').join('-'); if (this._isInProgress(key)) { - return this._getInProgress(key) as VePromise + return this._getInProgress(key) as VePromise; } - const cached = this.cacheSvc.get(key) + const cached = this.cacheSvc.get(key); if (cached && !update) { - return this.$q.resolve(cached) + return this.$q.resolve(cached); } this._addInProgress( key, new this.$q((resolve, reject) => { this.elementSvc.getElement(reqOb, weight, update).then( (viewOrInstance: ViewObject | ViewInstanceSpec) => { - const toGet: string[] = [] - let results: ElementObject[] = [] + const toGet: string[] = []; + let results: ElementObject[] = []; if (viewOrInstance.type === 'Class') { - const view: ViewObject = viewOrInstance as ViewObject + const view: ViewObject = viewOrInstance as ViewObject; if (view._displayedElementIds) { - const displayed: string[] = view._displayedElementIds + const displayed: string[] = view._displayedElementIds; if (Array.isArray(displayed) && displayed.length > 0) { - toGet.push(...displayed) + toGet.push(...displayed); } } if (view._contents && view._contents.operand) { - const contents = view._contents.operand + const contents = view._contents.operand; for (let i = 0; i < contents.length; i++) { if (contents[i] && contents[i].instanceId) { - toGet.push(contents[i].instanceId) + toGet.push(contents[i].instanceId); } } } } else if (viewOrInstance.type === 'InstanceSpecification') { - const view = viewOrInstance as ViewInstanceSpec + const view = viewOrInstance as ViewInstanceSpec; if (view.specification) { if (view.specification.operand) { - const specContents = view.specification.operand as InstanceValueObject[] + const specContents = view.specification.operand as InstanceValueObject[]; for (let j = 0; j < specContents.length; j++) { if (specContents[j] && specContents[j].instanceId) { - toGet.push(specContents[j].instanceId) + toGet.push(specContents[j].instanceId); } } } @@ -252,51 +252,51 @@ export class ViewService extends BaseApiService { ) { const tableJson: PresentTableObject = JSON.parse( view.specification.value - ) as PresentTableObject + ) as PresentTableObject; if (tableJson.body) { - toGet.push(...this.collectTableSources(tableJson)) + toGet.push(...this.collectTableSources(tableJson)); } } } } - const toGetReqOb: ElementsRequest = Object.assign(reqOb, { elementId: toGet }) + const toGetReqOb: ElementsRequest = Object.assign(reqOb, { elementId: toGet }); this.elementSvc .getElements(toGetReqOb, weight, update) .then((data) => { - results = data + results = data; }) .finally(() => { - this.cacheSvc.put(key, results) - this._removeInProgress(key) - resolve(results) - }) + this.cacheSvc.put(key, results); + this._removeInProgress(key); + resolve(results); + }); }, (reason) => { - this._removeInProgress(key) - reject(reason) + this._removeInProgress(key); + reject(reason); } - ) + ); }) - ) - return this._getInProgress(key) as VePromise + ); + return this._getInProgress(key) as VePromise; } public collectTableSources(table: PresentTableObject): string[] { - const sources: string[] = [] - const body = table.body + const sources: string[] = []; + const body = table.body; body.forEach((row) => { row.forEach((cell) => { cell.content.forEach((thing) => { if (thing.type === 'Table' && thing.body) { - sources.push(...this.collectTableSources(thing as PresentTableObject)) + sources.push(...this.collectTableSources(thing as PresentTableObject)); } else if (thing.type === 'Paragraph' && thing.source) { - sources.push((thing as PresentTextObject).source) + sources.push((thing as PresentTextObject).source); } - }) - }) - }) - return sources + }); + }); + }); + return sources; } /** @@ -330,26 +330,26 @@ export class ViewService extends BaseApiService { ) => void, seen?: { [key: string]: ViewObject } ): VePromise { - let seenViews = seen - if (!seenViews) seenViews = {} + let seenViews = seen; + if (!seenViews) seenViews = {}; return new this.$q((resolve, reject) => { - const curItem: TreeBranch | string[] = curItemFunc(v, aggr, propId) - seenViews[v.id] = v - const childIds: string[] = [] - const childAggrs: string[] = [] - const childPropIds: string[] = [] + const curItem: TreeBranch | string[] = curItemFunc(v, aggr, propId); + seenViews[v.id] = v; + const childIds: string[] = []; + const childAggrs: string[] = []; + const childPropIds: string[] = []; if (!v._childViews || v._childViews.length === 0 || aggr === 'none') { if (!Array.isArray(curItem) && curItem.loading) { - curItem.loading = false + curItem.loading = false; } - resolve(curItem) - return + resolve(curItem); + return; } for (let i = 0; i < v._childViews.length; i++) { - if (seenViews[v._childViews[i].id]) continue - childIds.push(v._childViews[i].id) - childAggrs.push(v._childViews[i].aggregation) - childPropIds.push(v._childViews[i].propertyId) + if (seenViews[v._childViews[i].id]) continue; + childIds.push(v._childViews[i].id); + childAggrs.push(v._childViews[i].aggregation); + childPropIds.push(v._childViews[i].propertyId); } this.elementSvc .getElements( @@ -361,15 +361,15 @@ export class ViewService extends BaseApiService { 2 ) .then((childViews: ViewObject[]) => { - const mapping: { [id: string]: ViewObject } = {} + const mapping: { [id: string]: ViewObject } = {}; for (let i = 0; i < childViews.length; i++) { - mapping[childViews[i].id] = childViews[i] + mapping[childViews[i].id] = childViews[i]; } - const childPromises: VePromise[] = [] - const childNodes: (string[] | TreeBranch)[] = [] - const processedChildViews: ViewObject[] = [] + const childPromises: VePromise[] = []; + const childNodes: (string[] | TreeBranch)[] = []; + const processedChildViews: ViewObject[] = []; for (let i = 0; i < childIds.length; i++) { - const child = mapping[childIds[i]] + const child = mapping[childIds[i]]; if (child && this.apiSvc.isView(child)) { //what if not found?? childPromises.push( @@ -384,26 +384,26 @@ export class ViewService extends BaseApiService { childrenFunc, seenViews ) - ) - childNodes.push(curItemFunc(child, childAggrs[i], childPropIds[i])) + ); + childNodes.push(curItemFunc(child, childAggrs[i], childPropIds[i])); processedChildViews.push({ id: child.id, _projectId: child._projectId, _refId: child._refId, aggregation: childAggrs[i], propertyId: childPropIds[i], - }) + }); } } - v._childViews = processedChildViews + v._childViews = processedChildViews; if (childrenFunc) { - childrenFunc(curItem, childNodes, reject) + childrenFunc(curItem, childNodes, reject); } this.$q.all(childPromises).then(() => { - resolve(curItem) - }, reject) - }, reject) - }) + resolve(curItem); + }, reject); + }, reject); + }); } /** @@ -416,7 +416,7 @@ export class ViewService extends BaseApiService { * @returns {Promise} The promise would be resolved with updated parent view object */ public addViewToParentView(reqOb: ViewCreationRequest): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -436,10 +436,10 @@ export class ViewService extends BaseApiService { id: data.id, _childViews: [], type: data.type, - } - clone._childViews = [] + }; + clone._childViews = []; if (data._childViews) { - clone._childViews.push(..._.cloneDeep(data._childViews)) + clone._childViews.push(..._.cloneDeep(data._childViews)); } clone._childViews.push({ id: reqOb.viewId, @@ -447,21 +447,21 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, type: data.type, - }) + }); this.elementSvc.updateElement(clone, true).then( (data2) => { - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -472,7 +472,7 @@ export class ViewService extends BaseApiService { * @returns {IPromise} The promise would be resolved with updated parent View object */ public removeViewFromParentView(reqOb: ViewsRequest): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -494,30 +494,30 @@ export class ViewService extends BaseApiService { id: data.id, type: data.type, _childViews: _.cloneDeep(data._childViews), - } + }; for (let i = 0; i < clone._childViews.length; i++) { if (clone._childViews[i].id === reqOb.viewId) { - clone._childViews.splice(i, 1) - break + clone._childViews.splice(i, 1); + break; } } this.elementSvc.updateElement(clone, true).then( (data2) => { - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); } else { - resolve(data) + resolve(data); } }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -537,7 +537,7 @@ export class ViewService extends BaseApiService { instanceValOb: InstanceValueObject, addPeIndex: number ): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -555,20 +555,20 @@ export class ViewService extends BaseApiService { _refId: data._refId, type: data.type, id: data.id, - } - let key = '_contents' + }; + let key = '_contents'; if (this.isSection(data)) { - key = 'specification' + key = 'specification'; } - const keyValue: ValueObject = data[key] as ValueObject - let cloneValue: ValueObject + const keyValue: ValueObject = data[key] as ValueObject; + let cloneValue: ValueObject; if (keyValue) { - cloneValue = _.cloneDeep(keyValue) + cloneValue = _.cloneDeep(keyValue); if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(data) ? this.apiSvc.createUniqueId() - : data.id + '_vc_expression' - cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc' + : data.id + '_vc_expression'; + cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc'; } } else { cloneValue = new Expression({ @@ -578,39 +578,39 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, ownerId: this.isSection(data) ? data.id : data.id + '_vc', - }) + }); } - instanceValOb.ownerId = cloneValue.id + instanceValOb.ownerId = cloneValue.id; if (!instanceValOb.id) { - instanceValOb.id = this.apiSvc.createUniqueId() + instanceValOb.id = this.apiSvc.createUniqueId(); } if (addPeIndex >= -1) (cloneValue as ExpressionObject).operand.splice( addPeIndex + 1, 0, new ValueSpec(instanceValOb) - ) + ); else { - ;(cloneValue as ExpressionObject).operand.push( + (cloneValue as ExpressionObject).operand.push( new ValueSpec(instanceValOb) - ) + ); } - clone[key] = cloneValue + clone[key] = cloneValue; this.elementSvc.updateElement(clone, false).then( (data2) => { - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -625,7 +625,7 @@ export class ViewService extends BaseApiService { reqOb: ElementsRequest, instanceVal?: InstanceValueObject ): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { if (instanceVal) { this.elementSvc.getElement(reqOb, 2).then( @@ -636,20 +636,20 @@ export class ViewService extends BaseApiService { type: data.type, //_modified: data._modified, id: data.id, - } - let key = '_contents' + }; + let key = '_contents'; if (this.isSection(data)) { - key = 'specification' + key = 'specification'; } - const keyValue = data[key] as ValueObject - let cloneValue: ValueObject + const keyValue = data[key] as ValueObject; + let cloneValue: ValueObject; if (keyValue) { - cloneValue = _.cloneDeep(keyValue) + cloneValue = _.cloneDeep(keyValue); if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(data) ? this.apiSvc.createUniqueId() - : data.id + '_vc_expression' - cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc' + : data.id + '_vc_expression'; + cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc'; } } else { cloneValue = new Expression({ @@ -659,34 +659,34 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, ownerId: this.isSection(data) ? data.id : data.id + '_vc', - }) + }); } if (cloneValue && cloneValue.operand) { const operands: InstanceValueObject[] = (keyValue as ExpressionObject) - .operand + .operand; for (let i = 0; i < operands.length; i++) { if (instanceVal.instanceId === operands[i].instanceId) { - ;(cloneValue as ExpressionObject).operand.splice(i, 1) - break + (cloneValue as ExpressionObject).operand.splice(i, 1); + break; } } } - clone[key] = cloneValue + clone[key] = cloneValue; this.elementSvc.updateElement(clone, false).then( (data2) => { - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); } - }) + }); } /** @@ -705,23 +705,23 @@ export class ViewService extends BaseApiService { name: string, addPeIndex: number ): VePromise { - let newInstanceId = this.apiSvc.createUniqueId() - newInstanceId = '_hidden_' + newInstanceId + '_pei' + let newInstanceId = this.apiSvc.createUniqueId(); + newInstanceId = '_hidden_' + newInstanceId + '_pei'; return new this.$q((resolve, reject) => { const realType: string = this.schemaSvc.getValue( 'TYPE_TO_CLASSIFIER_TYPE', type, this.schema, viewOrSectionOb.id - ) - let jsonType = realType - if (type === 'Comment' || type === 'Paragraph') jsonType = type + ); + let jsonType = realType; + if (type === 'Comment' || type === 'Paragraph') jsonType = type; const instanceSpecSpec = { type: jsonType, sourceType: 'reference', source: newInstanceId, sourceProperty: 'documentation', - } + }; let instanceSpec: InstanceSpecObject = { id: newInstanceId, ownerId: 'view_instances_bin_' + viewOrSectionOb._projectId, @@ -742,8 +742,8 @@ export class ViewService extends BaseApiService { _refId: viewOrSectionOb._refId, }), appliedStereotypeIds: [], - } - instanceSpec = new InstanceSpec(instanceSpec) + }; + instanceSpec = new InstanceSpec(instanceSpec); if (type === 'Section') { //newData = newDataSInstance = null; instanceSpec.specification = new ValueSpec({ @@ -753,20 +753,20 @@ export class ViewService extends BaseApiService { id: this.apiSvc.createUniqueId(), _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, - }) + }); } let clone: ElementObject = { _projectId: viewOrSectionOb._projectId, id: viewOrSectionOb.id, _refId: viewOrSectionOb._refId, type: viewOrSectionOb.type, - } - let key = '_contents' + }; + let key = '_contents'; if (this.isSection(viewOrSectionOb)) { - key = 'specification' + key = 'specification'; } - const keyValue: ValueObject = viewOrSectionOb[key] as ValueObject - let cloneValue: ValueObject + const keyValue: ValueObject = viewOrSectionOb[key] as ValueObject; + let cloneValue: ValueObject; if (!keyValue) { cloneValue = new ValueSpec({ operand: [], @@ -777,20 +777,20 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, ownerId: this.isSection(viewOrSectionOb) ? viewOrSectionOb.id : viewOrSectionOb.id + '_vc', - }) + }); } else { - cloneValue = _.cloneDeep(keyValue) + cloneValue = _.cloneDeep(keyValue); if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(viewOrSectionOb) ? this.apiSvc.createUniqueId() - : viewOrSectionOb.id + '_vc_expression' + : viewOrSectionOb.id + '_vc_expression'; cloneValue.ownerId = this.isSection(viewOrSectionOb) ? viewOrSectionOb.id - : viewOrSectionOb.id + '_vc' + : viewOrSectionOb.id + '_vc'; } } if (addPeIndex >= -1) { - ;(cloneValue as ExpressionObject).operand.splice( + (cloneValue as ExpressionObject).operand.splice( addPeIndex + 1, 0, new ValueSpec({ @@ -801,9 +801,9 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, }) - ) + ); } else { - ;(cloneValue as ExpressionObject).operand.push( + (cloneValue as ExpressionObject).operand.push( new ValueSpec({ instanceId: newInstanceId, type: 'InstanceValue', @@ -812,11 +812,11 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, }) - ) + ); } - clone[key] = cloneValue - clone = this.elementSvc.fillInElement(clone) - const toCreate: ElementObject[] = [instanceSpec, clone] + clone[key] = cloneValue; + clone = this.elementSvc.fillInElement(clone); + const toCreate: ElementObject[] = [instanceSpec, clone]; /* if (newData && newDataSInstance) { toCreate.push(newData); @@ -828,22 +828,22 @@ export class ViewService extends BaseApiService { refId: viewOrSectionOb._refId, elements: toCreate, elementId: '', - } + }; this.elementSvc.createElements(reqOb).then( (data) => { for (let i = 0; i < data.length; i++) { - const elem = data[i] + const elem = data[i]; if (elem.id === newInstanceId) { - resolve(elem) - return + resolve(elem); + return; } } }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -863,9 +863,9 @@ export class ViewService extends BaseApiService { */ public createView(ownerOb: ViewObject, viewOb: ViewObject, peDoc?: string): VePromise { return new this.$q((resolve, reject) => { - const newViewId: string = viewOb.id && viewOb.id !== '' ? viewOb.id : this.apiSvc.createUniqueId() - const newInstanceId = '_hidden_' + this.apiSvc.createUniqueId() + '_pei' - const untitledName = viewOb.isDoc ? 'Untitled Document' : 'Untitled View' + const newViewId: string = viewOb.id && viewOb.id !== '' ? viewOb.id : this.apiSvc.createUniqueId(); + const newInstanceId = '_hidden_' + this.apiSvc.createUniqueId() + '_pei'; + const untitledName = viewOb.isDoc ? 'Untitled Document' : 'Untitled View'; const view = new Class({ id: newViewId, _projectId: viewOb._projectId, @@ -898,22 +898,22 @@ export class ViewService extends BaseApiService { ? this.schemaSvc.getSchema('DOCUMENT_SID', this.schema) : this.schemaSvc.getSchema('VIEW_SID', this.schema), ], - }) + }); let parentView: ViewObject = { _projectId: '', _refId: '', id: '', type: 'Class', - } + }; if (ownerOb && (ownerOb._childViews || this.apiSvc.isView(ownerOb))) { parentView = Object.assign(parentView, { _projectId: ownerOb._projectId, _refId: ownerOb._refId, id: ownerOb.id, - }) - parentView._childViews = [] + }); + parentView._childViews = []; if (ownerOb._childViews) { - parentView._childViews.push(..._.cloneDeep(ownerOb._childViews)) + parentView._childViews.push(..._.cloneDeep(ownerOb._childViews)); } parentView._childViews.push({ id: newViewId, @@ -921,14 +921,14 @@ export class ViewService extends BaseApiService { _refId: ownerOb._refId, aggregation: 'composite', type: 'Class', - }) + }); } const peSpec: PresentationInstanceObject = { type: 'Paragraph', sourceType: 'reference', source: newViewId, sourceProperty: 'documentation', - } + }; const pe = new InstanceSpec({ id: newInstanceId, _projectId: viewOb._projectId, @@ -946,11 +946,11 @@ export class ViewService extends BaseApiService { _refId: viewOb._refId, }), appliedStereotypeIds: [], - }) - const toCreate: ElementObject[] = [pe, view] + }); + const toCreate: ElementObject[] = [pe, view]; if (parentView.id !== '') { - const parentViewClass: ElementObject = this.elementSvc.fillInElement(parentView) - toCreate.push(parentViewClass) + const parentViewClass: ElementObject = this.elementSvc.fillInElement(parentView); + toCreate.push(parentViewClass); } const reqOb = { projectId: ownerOb._projectId, @@ -958,20 +958,20 @@ export class ViewService extends BaseApiService { elements: toCreate, returnChildViews: true, elementId: '', - } + }; this.elementSvc.createElements(reqOb).then( (data) => { data.forEach((elem) => { if (elem.id === newViewId) { - resolve(elem) + resolve(elem); } - }) + }); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -986,27 +986,27 @@ export class ViewService extends BaseApiService { */ public createDocument(ownerOb: ViewObject, docOb: ViewObject): VePromise { return new this.$q((resolve, reject) => { - docOb.isDoc = true + docOb.isDoc = true; this.createView(ownerOb, docOb).then( (data2: DocumentObject) => { if (ownerOb && ownerOb.id.indexOf('holding_bin') < 0) { - data2._groupId = ownerOb.id + data2._groupId = ownerOb.id; } - const cacheKey = ['documents', ownerOb._projectId, ownerOb._refId] - const cachedView: ViewObject[] = this.cacheSvc.get(cacheKey, true) + const cacheKey = ['documents', ownerOb._projectId, ownerOb._refId]; + const cachedView: ViewObject[] = this.cacheSvc.get(cacheKey, true); if (cachedView) { cachedView.forEach((document: DocumentObject, index) => { - if (document.id === data2.id) delete cachedView[index] - }) - cachedView.push(data2) + if (document.id === data2.id) delete cachedView[index]; + }); + cachedView.push(data2); } - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -1026,7 +1026,7 @@ export class ViewService extends BaseApiService { */ public createGroup(name: string, ownerOb: ViewObject): VePromise { return new this.$q((resolve, reject) => { - const PACKAGE_ID = this.apiSvc.createUniqueId() + const PACKAGE_ID = this.apiSvc.createUniqueId(); // Our Group package element const group: GroupObject = new Package({ id: PACKAGE_ID, @@ -1037,38 +1037,38 @@ export class ViewService extends BaseApiService { ownerId: ownerOb.id, _isGroup: true, appliedStereotypeIds: [this.schemaSvc.getSchema('GROUP_ST_ID', this.schema)], - }) - const toCreate = [group] + }); + const toCreate = [group]; const reqOb = { projectId: ownerOb._projectId, refId: ownerOb._refId, elements: toCreate, elementId: '', - } + }; this.elementSvc.createElements(reqOb).then( (data) => { - const cacheKey = ['groups', ownerOb._projectId, ownerOb._refId] - const groupObj = _.find(data, { id: PACKAGE_ID }) + const cacheKey = ['groups', ownerOb._projectId, ownerOb._refId]; + const groupObj = _.find(data, { id: PACKAGE_ID }); if (groupObj) { - groupObj._parentId = ownerOb.id.indexOf('holding') != -1 ? null : ownerOb.id + groupObj._parentId = ownerOb.id.indexOf('holding') != -1 ? null : ownerOb.id; if (this.cacheSvc.exists(cacheKey)) { - this.cacheSvc.get(cacheKey).push(groupObj) + this.cacheSvc.get(cacheKey).push(groupObj); } - this.cacheSvc.put(['group', groupObj.projectId, groupObj.refId, groupObj.id], groupObj, true) - resolve(groupObj) + this.cacheSvc.put(['group', groupObj.projectId, groupObj.refId, groupObj.id], groupObj, true); + resolve(groupObj); } else { reject({ status: 500, message: 'Failed to create group', - }) + }); } }, (reason) => { - console.log('POST failed:', reason) - reject(reason) + console.log('POST failed:', reason); + reject(reason); } - ) - }) + ); + }); } /** @@ -1088,43 +1088,43 @@ export class ViewService extends BaseApiService { _refId: packageOb._refId, appliedStereotypeIds: [], classifierIds: null, - } + }; - updatedPackage._isGroup = false + updatedPackage._isGroup = false; _.remove(packageOb.appliedStereotypeIds, (id: string): boolean => { - return id === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema) - }) + return id === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema); + }); if (packageOb.appliedStereotypeIds.length === 0) { - updatedPackage.appliedStereotypeIds = packageOb.appliedStereotypeIds + updatedPackage.appliedStereotypeIds = packageOb.appliedStereotypeIds; } - const toUpdate = [updatedPackage] + const toUpdate = [updatedPackage]; this.elementSvc.updateElements(toUpdate, false).then( (data) => { // remove this group for cache - const cacheKey = ['groups', packageOb._projectId, packageOb._refId] - const groups: ElementObject[] = this.cacheSvc.get(cacheKey, true) || [] + const cacheKey = ['groups', packageOb._projectId, packageOb._refId]; + const groups: ElementObject[] = this.cacheSvc.get(cacheKey, true) || []; _.remove(groups, (group: PackageObject) => { - return group.id === packageOb.id - }) + return group.id === packageOb.id; + }); data.forEach((elOb: ElementObject) => { if (elOb.id === updatedPackage.id) { - resolve(elOb) + resolve(elOb); } - }) + }); }, (reason) => { if (reason.data.failedRequests) { - reject(reason.data.failedRequests[0]) + reject(reason.data.failedRequests[0]); } else { reject({ status: 400, message: 'Something went wrong. Please try your action again', - }) + }); } } - ) - }) + ); + }); } /** @@ -1141,40 +1141,40 @@ export class ViewService extends BaseApiService { weight?: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb) - const url = this.uRLSvc.getProjectDocumentsURL(reqOb) - const cacheKey = ['documents', reqOb.projectId, reqOb.refId] - const inProgKey = cacheKey.join('-') + this.apiSvc.normalize(reqOb); + const url = this.uRLSvc.getProjectDocumentsURL(reqOb); + const cacheKey = ['documents', reqOb.projectId, reqOb.refId]; + const inProgKey = cacheKey.join('-'); if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q>((resolve, reject) => { if (this.cacheSvc.exists(cacheKey) && !refresh) { - resolve(this.cacheSvc.get(cacheKey)) - this._removeInProgress(inProgKey) + resolve(this.cacheSvc.get(cacheKey)); + this._removeInProgress(inProgKey); } else { if (refresh === undefined) { - refresh = false + refresh = false; } this.elementSvc .getGenericElements(url, reqOb, 'documents', weight, refresh) .then( (data) => { - this.cacheSvc.put(cacheKey, data, false) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, data, false); + resolve(this.cacheSvc.get(cacheKey)); }, (reason) => { - reject(reason) + reject(reason); } ) .finally(() => { - this._removeInProgress(inProgKey) - }) + this._removeInProgress(inProgKey); + }); } }) - ) + ); } - return this._getInProgress(inProgKey) as VePromise> + return this._getInProgress(inProgKey) as VePromise>; } /** @@ -1191,35 +1191,35 @@ export class ViewService extends BaseApiService { weight: number, refresh?: boolean ): VePromise { - const cacheKey = this.elementSvc.getRequestKey(reqOb, reqOb.elementId) - const inProgKey = cacheKey.join('-') + const cacheKey = this.elementSvc.getRequestKey(reqOb, reqOb.elementId); + const inProgKey = cacheKey.join('-'); if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q((resolve, reject) => { - const cached = this.cacheSvc.get(cacheKey) + const cached = this.cacheSvc.get(cacheKey); if (cached && !refresh) { - resolve(cached) - this._removeInProgress(inProgKey) + resolve(cached); + this._removeInProgress(inProgKey); } this.getProjectDocuments(reqOb, weight, refresh) .then( (result: DocumentObject[]) => { const documentOb = result.filter((resultOb) => { - return resultOb.id === reqOb.elementId - })[0] - this.cacheSvc.put(cacheKey, documentOb, true) - resolve(this.cacheSvc.get(cacheKey)) + return resultOb.id === reqOb.elementId; + })[0]; + this.cacheSvc.put(cacheKey, documentOb, true); + resolve(this.cacheSvc.get(cacheKey)); }, (reason) => { - reject({ message: reason.message, status: reason.status }) + reject({ message: reason.message, status: reason.status }); } ) - .finally(() => this._removeInProgress(inProgKey)) + .finally(() => this._removeInProgress(inProgKey)); }) - ) + ); } - return this._getInProgress(inProgKey) as VePromise + return this._getInProgress(inProgKey) as VePromise; } /** @@ -1233,31 +1233,31 @@ export class ViewService extends BaseApiService { public getPresentationInstanceObject = ( instanceSpec: InstanceSpecObject ): PresentationInstanceObject | InstanceSpecObject => { - const instanceSpecSpec: ValueObject = instanceSpec.specification + const instanceSpecSpec: ValueObject = instanceSpec.specification; if (!instanceSpecSpec) { return { type: 'Paragraph', sourceType: 'text', text: '', - } + }; } - const type = instanceSpecSpec.type + const type = instanceSpecSpec.type; if (type === 'LiteralString') { // If it is an Opaque List, Paragraph, Table, Image, List: - const jsonString = (instanceSpecSpec as LiteralObject).value - return JSON.parse(jsonString) as PresentationInstanceObject + const jsonString = (instanceSpecSpec as LiteralObject).value; + return JSON.parse(jsonString) as PresentationInstanceObject; } else if (type === 'Expression') { // If it is a Opaque Section, or a Expression: // If it is a Opaque Section then we want the instanceSpec: if (this.isSection(instanceSpec)) { - return instanceSpec + return instanceSpec; } else { //?? - return instanceSpecSpec + return instanceSpecSpec; } } - } + }; /** * @name ViewService#getElementReferenceTree @@ -1283,11 +1283,11 @@ export class ViewService extends BaseApiService { contents: ExpressionObject, weight?: number ): VePromise> { - const promises: VePromise>[] = [] + const promises: VePromise>[] = []; for (let i = 0; i < contents.operand.length; i++) { - promises.push(this.getElementReference(reqOb, contents.operand[i], weight)) + promises.push(this.getElementReference(reqOb, contents.operand[i], weight)); } - return this.$q.all(promises) + return this.$q.all(promises); } public getElementReference( @@ -1301,37 +1301,37 @@ export class ViewService extends BaseApiService { sectionElements: [], instanceVal: instanceVal, isOpaque: false, - } + }; - const req = _.cloneDeep(reqOb) - req.elementId = instanceVal.instanceId + const req = _.cloneDeep(reqOb); + req.elementId = instanceVal.instanceId; this.elementSvc.getElement(req, weight).then( (instanceSpecification) => { - presentationRef.instanceSpecification = instanceSpecification + presentationRef.instanceSpecification = instanceSpecification; presentationRef.isOpaque = instanceSpecification.classifierIds && instanceSpecification.classifierIds.length > 0 && this.schemaSvc .getMap('OPAQUE_CLASSIFIERS', this.schema) - .indexOf(instanceSpecification.classifierIds[0]) >= 0 - presentationRef.presentationElement = this.getPresentationInstanceObject(instanceSpecification) + .indexOf(instanceSpecification.classifierIds[0]) >= 0; + presentationRef.presentationElement = this.getPresentationInstanceObject(instanceSpecification); if (this.isSection(instanceSpecification)) { this.getElementReferenceTree(req, instanceSpecification.specification).then( (sectionElementReferenceTree) => { - presentationRef.sectionElements = sectionElementReferenceTree - resolve(presentationRef) + presentationRef.sectionElements = sectionElementReferenceTree; + resolve(presentationRef); }, (reason) => { - reject(reason) + reject(reason); } - ) - } else resolve(presentationRef) + ); + } else resolve(presentationRef); }, (reason) => { - reject({ status: reason.status, message: reason.message }) + reject({ status: reason.status, message: reason.message }); } - ) - }) + ); + }); } /** @@ -1349,8 +1349,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Section', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'SectionT', this.schema, instanceSpec.id)) - ) - } + ); + }; public isTable = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1360,8 +1360,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Table', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'TableT', this.schema, instanceSpec.id)) - ) - } + ); + }; public isFigure = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1375,8 +1375,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Figure', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'FigureT', this.schema, instanceSpec.id)) - ) - } + ); + }; public isEquation = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1384,27 +1384,27 @@ export class ViewService extends BaseApiService { instanceSpec.classifierIds.length > 0 && instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Equation', this.schema, instanceSpec.id) - ) - } + ); + }; public getTreeType = (instanceSpec: ViewInstanceSpec): string => { - if (this.isSection(instanceSpec)) return 'section' + if (this.isSection(instanceSpec)) return 'section'; if ( instanceSpec.specification && instanceSpec.specification.value && typeof instanceSpec.specification.value === 'string' && (JSON.parse(instanceSpec.specification.value) as PresentationInstanceObject).excludeFromList ) { - return 'none' + return 'none'; } - if (this.isTable(instanceSpec)) return 'table' - if (this.isFigure(instanceSpec)) return 'figure' - if (this.isEquation(instanceSpec)) return 'equation' - let result = 'none' + if (this.isTable(instanceSpec)) return 'table'; + if (this.isFigure(instanceSpec)) return 'figure'; + if (this.isEquation(instanceSpec)) return 'equation'; + let result = 'none'; if (instanceSpec.classifierIds && instanceSpec.classifierIds.length > 0) { const peSids = this.schemaSvc.getSchema<{ - [peType: string]: string - }>('TYPE_TO_CLASSIFIER_ID', this.schema) + [peType: string]: string; + }>('TYPE_TO_CLASSIFIER_ID', this.schema); for (const peType of Object.keys(peSids)) { if ( @@ -1412,43 +1412,43 @@ export class ViewService extends BaseApiService { instanceSpec.classifierIds.length > 0 && instanceSpec.classifierIds.includes(peSids[peType]) ) { - result = peType.toLowerCase() - break + result = peType.toLowerCase(); + break; } } } - return result - } + return result; + }; public processSlotStrings(values: LiteralObject[]): string[] { - const res: string[] = [] + const res: string[] = []; if (!values || values.length === 0) { - return res + return res; } values.forEach((value) => { - if (value.type !== 'LiteralString' || !value.value) return - res.push(value.value as string) - }) - return res + if (value.type !== 'LiteralString' || !value.value) return; + res.push(value.value as string); + }); + return res; } public processSlotIntegers(values: LiteralObject[]): number[] { - const res: number[] = [] + const res: number[] = []; if (!values || values.length === 0) { - return res + return res; } values.forEach((value) => { if (Number.isInteger(value.value)) { - res.push(value.value as number) + res.push(value.value as number); } else if (typeof value.value === 'string') { - const val = parseInt(value.value) + const val = parseInt(value.value); if (!isNaN(val)) { - res.push(val) + res.push(val); } } - }) - return res + }); + return res; } /** @@ -1465,7 +1465,7 @@ export class ViewService extends BaseApiService { const metadata: DocumentMetadata = { numberingDepth: 0, numberingSeparator: '.', - } + }; const elementIds = [ `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'Header', this.schema)}`, //header `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'Footer', this.schema)}`, //footer @@ -1475,51 +1475,51 @@ export class ViewService extends BaseApiService { this.schema )}`, //numbering depth `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'NumSep', this.schema)}`, //numbering separator - ] + ]; const metaReqOb: ElementsRequest = Object.assign(reqOb, { elementId: elementIds, - }) + }); this.elementSvc .getElements(metaReqOb, weight) .then( (data) => { if (data.length === 0) { - return + return; } for (let i = 0; i < data.length; i++) { - const prop = data[i] - const feature: string = prop.definingFeatureId ? prop.definingFeatureId : null - const value: LiteralObject[] = prop.value ? prop.value : null + const prop = data[i]; + const feature: string = prop.definingFeatureId ? prop.definingFeatureId : null; + const value: LiteralObject[] = prop.value ? prop.value : null; if (!feature || !value || !Array.isArray(value)) { - continue + continue; } - let result: string[] | number[] = [] + let result: string[] | number[] = []; if (feature === this.schemaSvc.getValue('DOCUMENT_IDS', 'Header', this.schema, prop.id)) { //header - result = this.processSlotStrings(value) - metadata.top = result.length > 0 ? result[0] : '' - metadata['top-left'] = result.length > 1 ? result[1] : '' - metadata['top-right'] = result.length > 2 ? result[2] : '' + result = this.processSlotStrings(value); + metadata.top = result.length > 0 ? result[0] : ''; + metadata['top-left'] = result.length > 1 ? result[1] : ''; + metadata['top-right'] = result.length > 2 ? result[2] : ''; } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'Footer', this.schema, prop.id) ) { //footer - result = this.processSlotStrings(value) - metadata.bottom = result.length > 0 ? result[0] : '' - metadata['bottom-left'] = result.length > 1 ? result[1] : '' - metadata['bottom-right'] = result.length > 2 ? result[2] : '' + result = this.processSlotStrings(value); + metadata.bottom = result.length > 0 ? result[0] : ''; + metadata['bottom-left'] = result.length > 1 ? result[1] : ''; + metadata['bottom-right'] = result.length > 2 ? result[2] : ''; } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'NumDepth', this.schema, prop.id) ) { //depth - result = this.processSlotIntegers(value) - metadata.numberingDepth = result.length > 0 ? result[0] : 0 + result = this.processSlotIntegers(value); + metadata.numberingDepth = result.length > 0 ? result[0] : 0; } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'NumSep', this.schema, prop.id) ) { //separator - result = this.processSlotStrings(value) - metadata.numberingSeparator = result.length > 0 ? result[0] : '.' + result = this.processSlotStrings(value); + metadata.numberingSeparator = result.length > 0 ? result[0] : '.'; } } }, @@ -1528,63 +1528,63 @@ export class ViewService extends BaseApiService { } ) .finally(() => { - resolve(metadata) - }) - }) + resolve(metadata); + }); + }); } public getPresentationElementType = (instanceSpec: ViewInstanceSpec): string => { if (instanceSpec.type === 'InstanceSpecification') { if (this.isSection(instanceSpec)) { - return 'Section' + return 'Section'; } else if (this.isTable(instanceSpec)) { - return 'Table' + return 'Table'; } else if (this.isFigure(instanceSpec)) { - return 'Image' + return 'Image'; } else if (this.isEquation(instanceSpec)) { - return 'Equation' + return 'Equation'; } else if (instanceSpec.specification && instanceSpec.specification.value) { return ( JSON.parse( (instanceSpec.specification as LiteralObject).value ) as PresentationInstanceObject - ).type + ).type; } } - return - } + return; + }; public isGroup(ob: InstanceSpecObject | GroupObject): boolean { - if (ob._isGroup) return (ob as GroupObject)._isGroup + if (ob._isGroup) return (ob as GroupObject)._isGroup; else { return ( ob.appliedStereotypeIds !== undefined && ob.appliedStereotypeIds.length > 0 && ob.appliedStereotypeIds[0] === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema) - ) + ); } } public getElementType = (element: ElementObject): string => { // Get Type - let elementType = '' + let elementType = ''; if (this.apiSvc.isRequirement(element)) { - elementType = 'Requirement' + elementType = 'Requirement'; } else if (this.apiSvc.isDocument(element)) { - elementType = 'Document' + elementType = 'Document'; } else if (this.apiSvc.isView(element)) { - elementType = 'View' + elementType = 'View'; } else if (this.isGroup(element)) { - elementType = 'Group' + elementType = 'Group'; } else { - elementType = this.getPresentationElementType(element) + elementType = this.getPresentationElementType(element); } - return elementType - } + return elementType; + }; public reset = (): void => { - this.inProgress = {} - } + this.inProgress = {}; + }; } -veUtils.service('ViewService', ViewService) +veUtils.service('ViewService', ViewService); diff --git a/src/ve-utils/mms-api-client/index.ts b/src/ve-utils/mms-api-client/index.ts index 579288e4e..5da2df6b5 100644 --- a/src/ve-utils/mms-api-client/index.ts +++ b/src/ve-utils/mms-api-client/index.ts @@ -1,21 +1,21 @@ -import './Api.service' -import './URL.service' -import './Authorization.service' -import './Element.service' -import './Http.service' -import './Permissions.service' -import './Project.service' -import './View.service' -import './User.service' -import './Value.service' +import './Api.service'; +import './URL.service'; +import './Authorization.service'; +import './Element.service'; +import './Http.service'; +import './Permissions.service'; +import './Project.service'; +import './View.service'; +import './User.service'; +import './Value.service'; -export * from './URL.service' -export * from './Authorization.service' -export * from './Element.service' -export * from './Http.service' -export * from './Permissions.service' -export * from './Project.service' -export * from './View.service' -export * from './Api.service' -export * from './User.service' -export * from './Value.service' +export * from './URL.service'; +export * from './Authorization.service'; +export * from './Element.service'; +export * from './Http.service'; +export * from './Permissions.service'; +export * from './Project.service'; +export * from './View.service'; +export * from './Api.service'; +export * from './User.service'; +export * from './Value.service'; diff --git a/src/ve-utils/modals/ve-modal.controller.ts b/src/ve-utils/modals/ve-modal.controller.ts index 54e4f0919..1e140c1c5 100644 --- a/src/ve-utils/modals/ve-modal.controller.ts +++ b/src/ve-utils/modals/ve-modal.controller.ts @@ -1,10 +1,10 @@ -import { VeModalResolve, VeModalController, VeModalInstanceService } from '@ve-types/view-editor' +import { VeModalResolve, VeModalController, VeModalInstanceService } from '@ve-types/view-editor'; export class VeModalControllerImpl implements VeModalController { // public close($value?: any): void {}; // // public dismiss($value?: any): void {}; - modalInstance: VeModalInstanceService - protected resolve: U + modalInstance: VeModalInstanceService; + protected resolve: U; } diff --git a/src/ve-utils/model-schema/CameoSchema.service.ts b/src/ve-utils/model-schema/CameoSchema.service.ts index 9f051b0cf..7ee06d610 100644 --- a/src/ve-utils/model-schema/CameoSchema.service.ts +++ b/src/ve-utils/model-schema/CameoSchema.service.ts @@ -1,9 +1,9 @@ -import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service' +import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; export class CameoSchema implements Schema { - jsonName = 'cameo' + jsonName = 'cameo'; schema: SchemaMapping = { VIEW_SID: '_11_5EAPbeta_be00301_1147420760998_43940_227', OTHER_VIEW_SID: [ @@ -52,7 +52,7 @@ export class CameoSchema implements Schema { NumSep: '_18_5_3_8bf0285_1526605817077_688557_15755', }, GROUP_ST_ID: '_18_5_3_8bf0285_1520469040211_2821_15754', - } + }; map: SchemaMapping = { OPAQUE_CLASSIFIERS: [ this.schema.TYPE_TO_CLASSIFIER_ID['Image'], @@ -62,10 +62,10 @@ export class CameoSchema implements Schema { this.schema.TYPE_TO_CLASSIFIER_ID['Table'], this.schema.TYPE_TO_CLASSIFIER_ID['Figure'], ], - } + }; } -veUtils.service('CameoSchema', CameoSchema) +veUtils.service('CameoSchema', CameoSchema); // TODO: Create Cameo Project Creation Service // { diff --git a/src/ve-utils/model-schema/JupyterSchema.service.ts b/src/ve-utils/model-schema/JupyterSchema.service.ts index 5cf11557e..7dfe4e420 100644 --- a/src/ve-utils/model-schema/JupyterSchema.service.ts +++ b/src/ve-utils/model-schema/JupyterSchema.service.ts @@ -1,12 +1,12 @@ -import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service' +import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; export class JupyterSchema implements Schema { - static $inject = [] + static $inject = []; - jsonName: string = 'jupyter' - schema: SchemaMapping = {} + jsonName: string = 'jupyter'; + schema: SchemaMapping = {}; } -veUtils.service('JupyterSchema', JupyterSchema) +veUtils.service('JupyterSchema', JupyterSchema); diff --git a/src/ve-utils/model-schema/Schema.service.ts b/src/ve-utils/model-schema/Schema.service.ts index 911486f7c..97826883d 100644 --- a/src/ve-utils/model-schema/Schema.service.ts +++ b/src/ve-utils/model-schema/Schema.service.ts @@ -1,112 +1,112 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VeConfig } from '@ve-types/config' +import { VeConfig } from '@ve-types/config'; export interface SchemaMapping { - [key: string]: unknown + [key: string]: unknown; } export interface Schema { - jsonName: string - schema: SchemaMapping - map?: SchemaMapping + jsonName: string; + schema: SchemaMapping; + map?: SchemaMapping; } export class SchemaService { - static $inject = ['$q', '$injector'] + static $inject = ['$q', '$injector']; - public veConfig: VeConfig = window.__env - public defaultSchema: 'cameo' + public veConfig: VeConfig = window.__env; + public defaultSchema: 'cameo'; public schemaList: { [key: string]: string } = { cameo: 'CameoSchema', jupyter: 'JupyterSchema', - } + }; - public schemas: { [key: string]: Schema } = {} + public schemas: { [key: string]: Schema } = {}; constructor(private $q, private $injector: angular.auto.IInjectorService) { for (const [key, value] of Object.entries(this.schemaList)) { - this.schemas[key] = this.$injector.get(value) + this.schemas[key] = this.$injector.get(value); } } getSchema = (name: string, schemaName?: string, sourceId?: string): T => { - const schema: Schema = this._getSchema(schemaName, sourceId) + const schema: Schema = this._getSchema(schemaName, sourceId); if (schema.schema[name]) { - return schema.schema[name] as T + return schema.schema[name] as T; } else { - this._schemaError(name, schemaName) + this._schemaError(name, schemaName); } - } + }; getValue = (name: string, key: string, schemaName?: string, sourceId?: string): T => { - const lookup = this.getSchema(name, schemaName, sourceId) + const lookup = this.getSchema(name, schemaName, sourceId); if (lookup && typeof lookup === 'object') { - return lookup[key] as T + return lookup[key] as T; } - } + }; getValues(name: string, keys: string[], schemaName?: string, sourceId?: string): T[] | null { - const lookup = this.getSchema(name, schemaName, sourceId) + const lookup = this.getSchema(name, schemaName, sourceId); if (lookup && typeof lookup === 'object') { - const response: T[] = [] + const response: T[] = []; keys.forEach((key) => { if (lookup.hasOwnProperty(key)) { - response.push(lookup[key] as T) + response.push(lookup[key] as T); } - }) - return response + }); + return response; } } getMap = (name: string, schemaName?: string, sourceId?: string): T => { - const schema: Schema = this._getSchema(schemaName, sourceId) + const schema: Schema = this._getSchema(schemaName, sourceId); if (schema.map && schema.map[name]) { - return schema.map[name] as T + return schema.map[name] as T; } else { - this._schemaError(name, schemaName) - return null + this._schemaError(name, schemaName); + return null; } - } + }; getMappedValue = (name: string, key: string, schemaName?: string, sourceId?: string): T => { - const lookup = this.getMap(name, schemaName, sourceId) + const lookup = this.getMap(name, schemaName, sourceId); if (lookup && typeof lookup === 'object') { - return lookup[key] as T + return lookup[key] as T; } - } + }; getKeyByValue = (name: string, value: T, schemaName?: string, sourceId?: string): string => { - const lookup = this.getSchema(name, schemaName, sourceId) + const lookup = this.getSchema(name, schemaName, sourceId); if (lookup && typeof lookup === 'object') { - let response = '' + let response = ''; Object.keys(lookup).some((key) => { if (lookup[key] === value) { - response = key - return true + response = key; + return true; } - return false - }) - return response + return false; + }); + return response; } - } + }; private _schemaError = (name: string, schemaName?: string): void => { - schemaName = schemaName ? schemaName : this.defaultSchema + schemaName = schemaName ? schemaName : this.defaultSchema; if (this.veConfig.enableDebug) { - console.log(schemaName + ' does not have table' + name + 'or it is not properly configured') + console.log(schemaName + ' does not have table' + name + 'or it is not properly configured'); } - } + }; private _getSchema = (schemaName?: string, id?: string): Schema | null => { - schemaName = schemaName ? schemaName : this.defaultSchema - id = id ? id : 'error: unknown' + schemaName = schemaName ? schemaName : this.defaultSchema; + id = id ? id : 'error: unknown'; if (this.schemas.hasOwnProperty(schemaName)) { - return this.schemas[schemaName] + return this.schemas[schemaName]; } else { - console.log(`Object ${id} uses an unknown schema ${schemaName}`) + console.log(`Object ${id} uses an unknown schema ${schemaName}`); } - } + }; } -veUtils.service('SchemaService', SchemaService) +veUtils.service('SchemaService', SchemaService); diff --git a/src/ve-utils/model-schema/index.ts b/src/ve-utils/model-schema/index.ts index 94a6af9a4..c17dcefdc 100644 --- a/src/ve-utils/model-schema/index.ts +++ b/src/ve-utils/model-schema/index.ts @@ -1,7 +1,7 @@ -import './CameoSchema.service' -import './JupyterSchema.service' -import './Schema.service' +import './CameoSchema.service'; +import './JupyterSchema.service'; +import './Schema.service'; -export * from './CameoSchema.service' -export * from './JupyterSchema.service' -export * from './Schema.service' +export * from './CameoSchema.service'; +export * from './JupyterSchema.service'; +export * from './Schema.service'; diff --git a/src/ve-utils/third-party/index.ts b/src/ve-utils/third-party/index.ts index 0bdc684bd..8b138df6a 100644 --- a/src/ve-utils/third-party/index.ts +++ b/src/ve-utils/third-party/index.ts @@ -1 +1 @@ -import './jquery' +import './jquery'; diff --git a/src/ve-utils/third-party/jquery/index.ts b/src/ve-utils/third-party/jquery/index.ts index 480e6ad63..9c558addc 100644 --- a/src/ve-utils/third-party/jquery/index.ts +++ b/src/ve-utils/third-party/jquery/index.ts @@ -1,2 +1,2 @@ -import './isOnScreen.jquery' -import './table2CSV.jquery' +import './isOnScreen.jquery'; +import './table2CSV.jquery'; diff --git a/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts b/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts index 5f01e1ca1..d2eba58d2 100644 --- a/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts +++ b/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts @@ -1,43 +1,43 @@ -import jQuery from 'jquery' +import jQuery from 'jquery'; jQuery.fn.isOnScreen = (x?, y?): boolean => { - if (x == null || typeof x == 'undefined') x = 1 - if (y == null || typeof y == 'undefined') y = 1 + if (x == null || typeof x == 'undefined') x = 1; + if (y == null || typeof y == 'undefined') y = 1; - const win = $(window) + const win = $(window); const viewport = { top: win.scrollTop(), left: win.scrollLeft(), right: win.scrollLeft() + win.width(), bottom: win.scrollTop() + win.height(), - } + }; - const height = jQuery.fn.outerHeight() - const width = jQuery.fn.outerWidth() + const height = jQuery.fn.outerHeight(); + const width = jQuery.fn.outerWidth(); if (!width || !height) { - return false + return false; } const bounds: { - right?: number - left: number - bottom?: number - top: number - } = jQuery.fn.offset() - bounds.right = bounds.left + width - bounds.bottom = bounds.top + height + right?: number; + left: number; + bottom?: number; + top: number; + } = jQuery.fn.offset(); + bounds.right = bounds.left + width; + bounds.bottom = bounds.top + height; const visible = !( viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom - ) + ); if (!visible) { - return false + return false; } const deltas = { @@ -45,7 +45,7 @@ jQuery.fn.isOnScreen = (x?, y?): boolean => { bottom: Math.min(1, (viewport.bottom - bounds.top) / height), left: Math.min(1, (bounds.right - viewport.left) / width), right: Math.min(1, (viewport.right - bounds.left) / width), - } + }; - return deltas.left * deltas.right >= x && deltas.top * deltas.bottom >= y -} + return deltas.left * deltas.right >= x && deltas.top * deltas.bottom >= y; +}; diff --git a/src/ve-utils/third-party/jquery/table2CSV.jquery.ts b/src/ve-utils/third-party/jquery/table2CSV.jquery.ts index 356db3384..3cda1b948 100644 --- a/src/ve-utils/third-party/jquery/table2CSV.jquery.ts +++ b/src/ve-utils/third-party/jquery/table2CSV.jquery.ts @@ -1,4 +1,4 @@ -import jQuery from 'jquery' +import jQuery from 'jquery'; jQuery.fn.table2CSV = (inputOptions: JQuery.table2CSV.inputOptions): string => { const options = jQuery.extend( @@ -8,111 +8,111 @@ jQuery.fn.table2CSV = (inputOptions: JQuery.table2CSV.inputOptions): string => { delivery: 'popup', // popup, value }, inputOptions - ) + ); - const csvData: string[] = [] + const csvData: string[] = []; // const el = this const row2CSV = (tmpRow: string[]): void => { - const tmp = tmpRow.join('') // to remove any blank rows + const tmp = tmpRow.join(''); // to remove any blank rows if (tmpRow.length > 0 && tmp != '') { - csvData[csvData.length] = tmpRow.join(options.separator) + csvData[csvData.length] = tmpRow.join(options.separator); } - } + }; const formatData = (input: string): string => { // replace " with “ - const regexp = new RegExp(/["]/g) - let output = input.replace(regexp, '“') + const regexp = new RegExp(/["]/g); + let output = input.replace(regexp, '“'); //HTML // var regexp = new RegExp(/\<[^\<]+\>/g); // var output = output.replace(regexp, ""); - const i = output.search(/\S/) //index of first non whitespace char + const i = output.search(/\S/); //index of first non whitespace char if (i > 0) { - output = '_'.repeat(i) + $.trim(output) + output = '_'.repeat(i) + $.trim(output); } - output = $.trim(output) - if (output == '') return '' + output = $.trim(output); + if (output == '') return ''; if (output[0] == '+' || output[0] == '=' || output[0] == '-') { - output = ' ' + output + output = ' ' + output; } - return `"${output}"` - } + return `"${output}"`; + }; const popup = (data: string): string => { - const generator = window.open('', 'csv', 'height=400,width=600') - generator.document.write('CSV') - generator.document.write('') - generator.document.write('') - generator.document.write('') - generator.document.close() - return 'ok' - } + const generator = window.open('', 'csv', 'height=400,width=600'); + generator.document.write('CSV'); + generator.document.write(''); + generator.document.write(''); + generator.document.write(''); + generator.document.close(); + return 'ok'; + }; const handleMatrix = (bodyTag: string, cellTag: string): void => { - const spanData: { [row: number]: { [column: number]: unknown } } = {} //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell - let curRow = 0 + const spanData: { [row: number]: { [column: number]: unknown } } = {}; //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell + let curRow = 0; $(this) .children(bodyTag) .children('tr') .each((index, element) => { - tmpRow = [] - let curCol = 0 + tmpRow = []; + let curCol = 0; $(element) .children(cellTag) .each((index, element) => { while (spanData[curRow] && spanData[curRow][curCol]) { - tmpRow.push('""') - curCol++ + tmpRow.push('""'); + curCol++; } - tmpRow.push(formatData($(element).text())) - const rowstring = $(element).attr('rowspan') - const rowspan = parseInt(rowstring) + tmpRow.push(formatData($(element).text())); + const rowstring = $(element).attr('rowspan'); + const rowspan = parseInt(rowstring); if (rowspan && rowspan > 1) { for (let i = 1; i < rowspan; i++) { if (!spanData[curRow + i]) { - spanData[curRow + i] = {} + spanData[curRow + i] = {}; } - spanData[curRow + i][curCol] = true + spanData[curRow + i][curCol] = true; } } - const colstring = $(element).attr('colspan') + const colstring = $(element).attr('colspan'); if (!colstring) { - curCol++ - return + curCol++; + return; } - let colspan = parseInt(colstring) + let colspan = parseInt(colstring); while (colspan > 1) { - curCol++ - tmpRow.push('""') - colspan-- + curCol++; + tmpRow.push('""'); + colspan--; if (rowspan > 1) { for (let i = 1; i < rowspan; i++) { - spanData[curRow + i][curCol] = true + spanData[curRow + i][curCol] = true; } } } - curCol++ - }) - row2CSV(tmpRow) - curRow++ - }) - } + curCol++; + }); + row2CSV(tmpRow); + curRow++; + }); + }; //header - const numCols = options.header.length - let tmpRow: string[] = [] + const numCols = options.header.length; + let tmpRow: string[] = []; if (numCols > 0) { for (let i = 0; i < numCols; i++) { - tmpRow[tmpRow.length] = formatData(options.header[i]) + tmpRow[tmpRow.length] = formatData(options.header[i]); } } else { - handleMatrix('thead', 'th') + handleMatrix('thead', 'th'); } // actual data - handleMatrix('tbody', 'td') - const mydata = csvData.join('\n') + handleMatrix('tbody', 'td'); + const mydata = csvData.join('\n'); if (options.delivery == 'popup') { - return popup(mydata) + return popup(mydata); } else { - return mydata + return mydata; } -} +}; diff --git a/src/ve-utils/utils/change.util.ts b/src/ve-utils/utils/change.util.ts index 42d5da391..8753aaa54 100644 --- a/src/ve-utils/utils/change.util.ts +++ b/src/ve-utils/utils/change.util.ts @@ -1,8 +1,8 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { EventService } from '@ve-utils/core' +import { EventService } from '@ve-utils/core'; -import { VeQService } from '@ve-types/angular' +import { VeQService } from '@ve-types/angular'; /** * @name onChangesCallback @@ -17,7 +17,7 @@ import { VeQService } from '@ve-types/angular' * } * */ -export type onChangesCallback = (newVal?: T, oldVal?: T, firstChange?: boolean) => U +export type onChangesCallback = (newVal?: T, oldVal?: T, firstChange?: boolean) => U; /** * @name change.utils#handleChange: @@ -48,23 +48,23 @@ export function handleChange( ignoreFirst?: boolean ): void { if (watch === '') { - return callback() + return callback(); } else if (changesObj[watch]) { if (ignoreFirst && changesObj[watch].isFirstChange()) { - return + return; } - const newVal: T = changesObj[watch].currentValue as T - const oldVal: T = changesObj[watch].previousValue as T - const firstChange = changesObj[watch].isFirstChange() - callback(newVal, oldVal, firstChange) + const newVal: T = changesObj[watch].currentValue as T; + const oldVal: T = changesObj[watch].previousValue as T; + const firstChange = changesObj[watch].isFirstChange(); + callback(newVal, oldVal, firstChange); } - return + return; } interface EventWatcher { - $q: VeQService - eventSvc: EventService - subs: Rx.IDisposable[] + $q: VeQService; + eventSvc: EventService; + subs: Rx.IDisposable[]; } export function watchChangeEvent( @@ -79,15 +79,15 @@ export function watchChangeEvent( currentValue: data, previousValue: _.cloneDeep($ctrl[name] as T), isFirstChange: () => { - return typeof $ctrl[name] === 'undefined' + return typeof $ctrl[name] === 'undefined'; }, - } + }; if (data !== $ctrl[name]) { if (update) { - $ctrl[name] = data + $ctrl[name] = data; } - changeAction(change.currentValue, change.previousValue, change.isFirstChange()) + changeAction(change.currentValue, change.previousValue, change.isFirstChange()); } }) - ) + ); } diff --git a/src/ve-utils/utils/emf.util.ts b/src/ve-utils/utils/emf.util.ts index b0423f4c1..1c761b7a8 100644 --- a/src/ve-utils/utils/emf.util.ts +++ b/src/ve-utils/utils/emf.util.ts @@ -1,172 +1,172 @@ -import { ElementObject, ExpressionObject, PackageObject, ValueObject } from '@ve-types/mms' +import { ElementObject, ExpressionObject, PackageObject, ValueObject } from '@ve-types/mms'; export class Element implements ElementObject { - id: string = '' - _projectId: string = '' - _refId: string = '' - appliedStereotypeIds: string[] = [] - documentation: string = '' - mdExtensionsIds: string[] = [] - syncElementId: string = null - type: string = 'Element' + id: string = ''; + _projectId: string = ''; + _refId: string = ''; + appliedStereotypeIds: string[] = []; + documentation: string = ''; + mdExtensionsIds: string[] = []; + syncElementId: string = null; + type: string = 'Element'; constructor(elementOb?: ElementObject) { if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class NamedElement extends Element { - name: string = '' - nameExpression: string = null - clientDependencyIds: string[] = [] - supplierDependencyIds: string[] = [] + name: string = ''; + nameExpression: string = null; + clientDependencyIds: string[] = []; + supplierDependencyIds: string[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } class PackageableElement extends NamedElement { - ownerId: string = null - visibility: string = 'public' - templateParameterId: string = null + ownerId: string = null; + visibility: string = 'public'; + templateParameterId: string = null; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } class TypedElement extends PackageableElement { - typeId: string = null + typeId: string = null; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } class TemplateableElement extends PackageableElement { - templateBindingIds: string[] = [] + templateBindingIds: string[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Property extends TypedElement { - type = 'Property' - defaultValue: any[] = [] + type = 'Property'; + defaultValue: any[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Class extends TemplateableElement { - classifierBehaviorId: string = null - collaborationUseIds: string[] = [] - elementImportIds: string[] = [] - generalizationIds: string[] = [] - classRealizationIds: string[] = [] - isAbstract: boolean = false - isActive: boolean = false - isFinalSpecialization: boolean = false - isLeaf: boolean = false - ownedAttributeIds: string[] = [] - ownedOperationIds: string[] = [] - packageImportIds: string[] = [] - powertypeExtentIds: string[] = [] - redefinedClassifierIds: string[] = [] - representationI: string[] = [] - type = 'Class' - useCaseIds: string[] = [] + classifierBehaviorId: string = null; + collaborationUseIds: string[] = []; + elementImportIds: string[] = []; + generalizationIds: string[] = []; + classRealizationIds: string[] = []; + isAbstract: boolean = false; + isActive: boolean = false; + isFinalSpecialization: boolean = false; + isLeaf: boolean = false; + ownedAttributeIds: string[] = []; + ownedOperationIds: string[] = []; + packageImportIds: string[] = []; + powertypeExtentIds: string[] = []; + redefinedClassifierIds: string[] = []; + representationI: string[] = []; + type = 'Class'; + useCaseIds: string[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class InstanceSpec extends PackageableElement { - classifierIds: string[] = [] - deploymentIds: string[] = [] - slotIds: string[] = [] - specification: Element = null - stereotypedElementId: string = null - type = 'InstanceSpecification' + classifierIds: string[] = []; + deploymentIds: string[] = []; + slotIds: string[] = []; + specification: Element = null; + stereotypedElementId: string = null; + type = 'InstanceSpecification'; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class ValueSpec extends TypedElement implements ValueObject { - valueExpression: string = '' - type = 'ValueSpecification' + valueExpression: string = ''; + type = 'ValueSpecification'; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Expression extends ValueSpec implements ExpressionObject { - operand: T[] = [] - type = 'Expression' + operand: T[] = []; + type = 'Expression'; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Package extends TemplateableElement implements PackageObject { - type = 'Package' - visibility = null - elementImportIds: string[] = [] - packageImportIds: string[] = [] - URI: string = '' - packageMergeIds: string[] = [] - profileApplicationIds: string[] = [] + type = 'Package'; + visibility = null; + elementImportIds: string[] = []; + packageImportIds: string[] = []; + URI: string = ''; + packageMergeIds: string[] = []; + profileApplicationIds: string[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Generalization extends Element { - generalizationSetIds: string[] = [] - isSubstitutable: boolean = true - type = 'Generalization' + generalizationSetIds: string[] = []; + isSubstitutable: boolean = true; + type = 'Generalization'; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Dependency extends PackageableElement { - type = 'Dependency' - visibility = null + type = 'Dependency'; + visibility = null; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } diff --git a/src/ve-utils/utils/index.ts b/src/ve-utils/utils/index.ts index 6eae2b6fd..847dc55d5 100644 --- a/src/ve-utils/utils/index.ts +++ b/src/ve-utils/utils/index.ts @@ -1,2 +1,2 @@ -export * from './change.util' -export * from './emf.util' +export * from './change.util'; +export * from './emf.util'; diff --git a/src/ve-utils/ve-utils.module.ts b/src/ve-utils/ve-utils.module.ts index 11895ab96..5408eac8c 100644 --- a/src/ve-utils/ve-utils.module.ts +++ b/src/ve-utils/ve-utils.module.ts @@ -1,4 +1,4 @@ -import angular from 'angular' +import angular from 'angular'; /** * @ngdoc overview @@ -55,14 +55,14 @@ import angular from 'angular' ]); */ -export const veUtils = angular.module('ve-utils', []) +export const veUtils = angular.module('ve-utils', []); veUtils .config([ '$sceProvider', ($sceProvider: angular.ISCEProvider): void => { - $sceProvider.enabled(false) + $sceProvider.enabled(false); }, ]) //.constant('HtmlRenderedDiff', window.HtmlRenderedDiff) - .constant('moment', window.moment) + .constant('moment', window.moment); diff --git a/tsconfig.json b/tsconfig.json index fb1e8fa39..c5b997451 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,7 +18,8 @@ "typeRoots": [ "node_modules/@types", "node_modules/type-fest/index.d.ts", - "src/lib" + "src/lib", + "node_modules/flatpickr/dist/typings.d.ts" ], "rootDir": "src", "paths": { From f3d98a94ddf7a4d7a8addc4e3640deddbbed9b88 Mon Sep 17 00:00:00 2001 From: Enquier Date: Mon, 15 May 2023 12:45:29 -0600 Subject: [PATCH 19/31] Revert "global prettier reformat" This reverts commit bba14eef4f07c5025a9f9cc129f01f42de733c01. --- .eslintrc | 210 +- .prettierrc.js | 1 + package.json | 4 +- src/errors/configError.html | 28 +- src/filters/underlineMatch.js | 14 +- src/index.html | 105 +- src/lib/angular-flatpickr/ngFlatpickr.main.ts | 2 +- .../angular-flatpickr/ngFlatpickr.module.ts | 82 +- .../angular-promise-extras.d.ts | 38 +- .../angular-promise-extras.js | 84 +- .../angular-ui-tree-filter.d.ts | 2 +- .../angular-ui-tree-filter.js | 68 +- .../autosave/css/autosave.min.css | 95 +- .../autosave/js/extensions.min.js | 12956 +------- src/lib/ckeditor-plugins/autosave/lang/en.js | 18 +- src/lib/ckeditor-plugins/autosave/plugin.js | 296 +- .../mathjax/dialogs/mathjax.js | 62 +- src/lib/ckeditor-plugins/mathjax/plugin.js | 190 +- src/lib/ckeditor-plugins/mmscf/plugin.js | 14 +- src/lib/ckeditor-plugins/mmscomment/plugin.js | 14 +- .../ckeditor-plugins/mmsdropdown/plugin.js | 86 +- src/lib/ckeditor-plugins/mmsreset/plugin.js | 18 +- .../ckeditor-plugins/mmssignature/plugin.js | 8 +- src/lib/ckeditor-plugins/mmsvlink/plugin.js | 14 +- .../ckeditor-plugins/ve-ckeditor-plugins.d.ts | 28 +- src/lib/ckeditor/CHANGES.md | 4474 +-- src/lib/ckeditor/LICENSE.md | 2860 +- src/lib/ckeditor/README.md | 11 +- src/lib/ckeditor/SECURITY.md | 20 +- src/lib/ckeditor/adapters/jquery.js | 163 +- src/lib/ckeditor/bender-runner.config.json | 28 +- src/lib/ckeditor/build-config.js | 166 +- src/lib/ckeditor/ckeditor4.js | 24757 ++++++++-------- src/lib/ckeditor/config.js | 42 +- src/lib/ckeditor/contents.css | 397 +- src/lib/ckeditor/lang/en.js | 526 +- .../plugins/a11yhelp/dialogs/a11yhelp.js | 151 +- .../plugins/a11yhelp/dialogs/lang/af.js | 118 +- .../plugins/a11yhelp/dialogs/lang/ar.js | 119 +- .../plugins/a11yhelp/dialogs/lang/az.js | 118 +- .../plugins/a11yhelp/dialogs/lang/bg.js | 119 +- .../plugins/a11yhelp/dialogs/lang/ca.js | 120 +- .../plugins/a11yhelp/dialogs/lang/cs.js | 119 +- .../plugins/a11yhelp/dialogs/lang/cy.js | 118 +- .../plugins/a11yhelp/dialogs/lang/da.js | 118 +- .../plugins/a11yhelp/dialogs/lang/de-ch.js | 120 +- .../plugins/a11yhelp/dialogs/lang/de.js | 120 +- .../plugins/a11yhelp/dialogs/lang/el.js | 120 +- .../plugins/a11yhelp/dialogs/lang/en-au.js | 118 +- .../plugins/a11yhelp/dialogs/lang/en-gb.js | 119 +- .../plugins/a11yhelp/dialogs/lang/en.js | 119 +- .../plugins/a11yhelp/dialogs/lang/eo.js | 120 +- .../plugins/a11yhelp/dialogs/lang/es-mx.js | 120 +- .../plugins/a11yhelp/dialogs/lang/es.js | 120 +- .../plugins/a11yhelp/dialogs/lang/et.js | 118 +- .../plugins/a11yhelp/dialogs/lang/eu.js | 119 +- .../plugins/a11yhelp/dialogs/lang/fa.js | 118 +- .../plugins/a11yhelp/dialogs/lang/fi.js | 119 +- .../plugins/a11yhelp/dialogs/lang/fo.js | 119 +- .../plugins/a11yhelp/dialogs/lang/fr-ca.js | 119 +- .../plugins/a11yhelp/dialogs/lang/fr.js | 120 +- .../plugins/a11yhelp/dialogs/lang/gl.js | 119 +- .../plugins/a11yhelp/dialogs/lang/gu.js | 119 +- .../plugins/a11yhelp/dialogs/lang/he.js | 118 +- .../plugins/a11yhelp/dialogs/lang/hi.js | 119 +- .../plugins/a11yhelp/dialogs/lang/hr.js | 118 +- .../plugins/a11yhelp/dialogs/lang/hu.js | 119 +- .../plugins/a11yhelp/dialogs/lang/id.js | 118 +- .../plugins/a11yhelp/dialogs/lang/it.js | 120 +- .../plugins/a11yhelp/dialogs/lang/ja.js | 116 +- .../plugins/a11yhelp/dialogs/lang/km.js | 119 +- .../plugins/a11yhelp/dialogs/lang/ko.js | 117 +- .../plugins/a11yhelp/dialogs/lang/ku.js | 118 +- .../plugins/a11yhelp/dialogs/lang/lt.js | 119 +- .../plugins/a11yhelp/dialogs/lang/lv.js | 120 +- .../plugins/a11yhelp/dialogs/lang/mk.js | 119 +- .../plugins/a11yhelp/dialogs/lang/mn.js | 119 +- .../plugins/a11yhelp/dialogs/lang/nb.js | 119 +- .../plugins/a11yhelp/dialogs/lang/nl.js | 119 +- .../plugins/a11yhelp/dialogs/lang/no.js | 119 +- .../plugins/a11yhelp/dialogs/lang/oc.js | 119 +- .../plugins/a11yhelp/dialogs/lang/pl.js | 120 +- .../plugins/a11yhelp/dialogs/lang/pt-br.js | 120 +- .../plugins/a11yhelp/dialogs/lang/pt.js | 119 +- .../plugins/a11yhelp/dialogs/lang/ro.js | 119 +- .../plugins/a11yhelp/dialogs/lang/ru.js | 118 +- .../plugins/a11yhelp/dialogs/lang/si.js | 111 +- .../plugins/a11yhelp/dialogs/lang/sk.js | 118 +- .../plugins/a11yhelp/dialogs/lang/sl.js | 119 +- .../plugins/a11yhelp/dialogs/lang/sq.js | 119 +- .../plugins/a11yhelp/dialogs/lang/sr-latn.js | 119 +- .../plugins/a11yhelp/dialogs/lang/sr.js | 119 +- .../plugins/a11yhelp/dialogs/lang/sv.js | 118 +- .../plugins/a11yhelp/dialogs/lang/th.js | 119 +- .../plugins/a11yhelp/dialogs/lang/tr.js | 119 +- .../plugins/a11yhelp/dialogs/lang/tt.js | 119 +- .../plugins/a11yhelp/dialogs/lang/ug.js | 119 +- .../plugins/a11yhelp/dialogs/lang/uk.js | 119 +- .../plugins/a11yhelp/dialogs/lang/vi.js | 118 +- .../plugins/a11yhelp/dialogs/lang/zh-cn.js | 112 +- .../plugins/a11yhelp/dialogs/lang/zh.js | 112 +- .../plugins/clipboard/dialogs/paste.js | 178 +- .../codesnippet/dialogs/codesnippet.js | 59 +- .../codesnippet/lib/highlight/CHANGES.md | 1612 +- .../codesnippet/lib/highlight/README.md | 332 +- .../codesnippet/lib/highlight/README.ru.md | 339 +- .../lib/highlight/highlight.pack.js | 1317 +- .../codesnippet/lib/highlight/styles/arta.css | 310 +- .../lib/highlight/styles/ascetic.css | 102 +- .../highlight/styles/atelier-dune.dark.css | 186 +- .../highlight/styles/atelier-dune.light.css | 186 +- .../highlight/styles/atelier-forest.dark.css | 186 +- .../highlight/styles/atelier-forest.light.css | 186 +- .../highlight/styles/atelier-heath.dark.css | 186 +- .../highlight/styles/atelier-heath.light.css | 186 +- .../styles/atelier-lakeside.dark.css | 186 +- .../styles/atelier-lakeside.light.css | 186 +- .../highlight/styles/atelier-seaside.dark.css | 186 +- .../styles/atelier-seaside.light.css | 186 +- .../lib/highlight/styles/brown_paper.css | 211 +- .../codesnippet/lib/highlight/styles/dark.css | 211 +- .../lib/highlight/styles/default.css | 307 +- .../lib/highlight/styles/docco.css | 265 +- .../codesnippet/lib/highlight/styles/far.css | 227 +- .../lib/highlight/styles/foundation.css | 267 +- .../lib/highlight/styles/github.css | 251 +- .../lib/highlight/styles/googlecode.css | 296 +- .../codesnippet/lib/highlight/styles/idea.css | 245 +- .../lib/highlight/styles/ir_black.css | 212 +- .../lib/highlight/styles/magula.css | 245 +- .../lib/highlight/styles/mono-blue.css | 126 +- .../lib/highlight/styles/monokai.css | 255 +- .../lib/highlight/styles/monokai_sublime.css | 297 +- .../lib/highlight/styles/obsidian.css | 309 +- .../lib/highlight/styles/paraiso.dark.css | 186 +- .../lib/highlight/styles/paraiso.light.css | 186 +- .../lib/highlight/styles/pojoaque.css | 213 +- .../lib/highlight/styles/railscasts.css | 361 +- .../lib/highlight/styles/rainbow.css | 225 +- .../lib/highlight/styles/school_book.css | 227 +- .../lib/highlight/styles/solarized_dark.css | 214 +- .../lib/highlight/styles/solarized_light.css | 214 +- .../lib/highlight/styles/sunburst.css | 322 +- .../highlight/styles/tomorrow-night-blue.css | 186 +- .../styles/tomorrow-night-bright.css | 184 +- .../styles/tomorrow-night-eighties.css | 184 +- .../lib/highlight/styles/tomorrow-night.css | 186 +- .../lib/highlight/styles/tomorrow.css | 180 +- .../codesnippet/lib/highlight/styles/vs.css | 190 +- .../lib/highlight/styles/xcode.css | 318 +- .../lib/highlight/styles/zenburn.css | 233 +- .../colordialog/dialogs/colordialog.css | 40 +- .../colordialog/dialogs/colordialog.js | 258 +- .../ckeditor/plugins/dialog/styles/dialog.css | 36 +- src/lib/ckeditor/plugins/find/dialogs/find.js | 604 +- .../ckeditor/plugins/iframe/dialogs/iframe.js | 204 +- .../ckeditor/plugins/image2/dialogs/image2.js | 344 +- .../ckeditor/plugins/link/dialogs/anchor.js | 86 +- src/lib/ckeditor/plugins/link/dialogs/link.js | 880 +- .../plugins/liststyle/dialogs/liststyle.js | 171 +- .../plugins/pastefromword/filter/default.js | 921 +- .../plugins/pastetools/filter/common.js | 468 +- .../plugins/pastetools/filter/image.js | 166 +- .../sourcedialog/dialogs/sourcedialog.js | 51 +- .../plugins/specialchar/dialogs/lang/af.js | 129 +- .../plugins/specialchar/dialogs/lang/ar.js | 129 +- .../plugins/specialchar/dialogs/lang/az.js | 126 +- .../plugins/specialchar/dialogs/lang/bg.js | 129 +- .../plugins/specialchar/dialogs/lang/ca.js | 130 +- .../plugins/specialchar/dialogs/lang/cs.js | 129 +- .../plugins/specialchar/dialogs/lang/cy.js | 130 +- .../plugins/specialchar/dialogs/lang/da.js | 127 +- .../plugins/specialchar/dialogs/lang/de-ch.js | 129 +- .../plugins/specialchar/dialogs/lang/de.js | 129 +- .../plugins/specialchar/dialogs/lang/el.js | 129 +- .../plugins/specialchar/dialogs/lang/en-au.js | 129 +- .../plugins/specialchar/dialogs/lang/en-ca.js | 129 +- .../plugins/specialchar/dialogs/lang/en-gb.js | 129 +- .../plugins/specialchar/dialogs/lang/en.js | 129 +- .../plugins/specialchar/dialogs/lang/eo.js | 128 +- .../plugins/specialchar/dialogs/lang/es-mx.js | 129 +- .../plugins/specialchar/dialogs/lang/es.js | 129 +- .../plugins/specialchar/dialogs/lang/et.js | 127 +- .../plugins/specialchar/dialogs/lang/eu.js | 129 +- .../plugins/specialchar/dialogs/lang/fa.js | 128 +- .../plugins/specialchar/dialogs/lang/fi.js | 129 +- .../plugins/specialchar/dialogs/lang/fr-ca.js | 126 +- .../plugins/specialchar/dialogs/lang/fr.js | 128 +- .../plugins/specialchar/dialogs/lang/gl.js | 129 +- .../plugins/specialchar/dialogs/lang/he.js | 128 +- .../plugins/specialchar/dialogs/lang/hr.js | 129 +- .../plugins/specialchar/dialogs/lang/hu.js | 128 +- .../plugins/specialchar/dialogs/lang/id.js | 129 +- .../plugins/specialchar/dialogs/lang/it.js | 130 +- .../plugins/specialchar/dialogs/lang/ja.js | 125 +- .../plugins/specialchar/dialogs/lang/km.js | 129 +- .../plugins/specialchar/dialogs/lang/ko.js | 126 +- .../plugins/specialchar/dialogs/lang/ku.js | 129 +- .../plugins/specialchar/dialogs/lang/lt.js | 129 +- .../plugins/specialchar/dialogs/lang/lv.js | 129 +- .../plugins/specialchar/dialogs/lang/nb.js | 127 +- .../plugins/specialchar/dialogs/lang/nl.js | 129 +- .../plugins/specialchar/dialogs/lang/no.js | 127 +- .../plugins/specialchar/dialogs/lang/oc.js | 128 +- .../plugins/specialchar/dialogs/lang/pl.js | 128 +- .../plugins/specialchar/dialogs/lang/pt-br.js | 127 +- .../plugins/specialchar/dialogs/lang/pt.js | 129 +- .../plugins/specialchar/dialogs/lang/ro.js | 129 +- .../plugins/specialchar/dialogs/lang/ru.js | 129 +- .../plugins/specialchar/dialogs/lang/si.js | 129 +- .../plugins/specialchar/dialogs/lang/sk.js | 129 +- .../plugins/specialchar/dialogs/lang/sl.js | 128 +- .../plugins/specialchar/dialogs/lang/sq.js | 129 +- .../specialchar/dialogs/lang/sr-latn.js | 129 +- .../plugins/specialchar/dialogs/lang/sr.js | 129 +- .../plugins/specialchar/dialogs/lang/sv.js | 127 +- .../plugins/specialchar/dialogs/lang/th.js | 129 +- .../plugins/specialchar/dialogs/lang/tr.js | 128 +- .../plugins/specialchar/dialogs/lang/tt.js | 129 +- .../plugins/specialchar/dialogs/lang/ug.js | 129 +- .../plugins/specialchar/dialogs/lang/uk.js | 128 +- .../plugins/specialchar/dialogs/lang/vi.js | 130 +- .../plugins/specialchar/dialogs/lang/zh-cn.js | 125 +- .../plugins/specialchar/dialogs/lang/zh.js | 125 +- .../specialchar/dialogs/specialchar.js | 224 +- .../ckeditor/plugins/table/dialogs/table.js | 449 +- .../tableselection/styles/tableselection.css | 75 +- .../plugins/tabletools/dialogs/tableCell.js | 383 +- src/lib/ckeditor/skins/moono-lisa/dialog.css | 693 +- .../ckeditor/skins/moono-lisa/dialog_ie.css | 729 +- .../ckeditor/skins/moono-lisa/dialog_ie8.css | 754 +- .../skins/moono-lisa/dialog_iequirks.css | 732 +- src/lib/ckeditor/skins/moono-lisa/editor.css | 1596 +- .../skins/moono-lisa/editor_gecko.css | 1603 +- .../ckeditor/skins/moono-lisa/editor_ie.css | 1635 +- .../ckeditor/skins/moono-lisa/editor_ie8.css | 1686 +- .../skins/moono-lisa/editor_iequirks.css | 1678 +- src/lib/ckeditor/skins/moono-lisa/readme.md | 91 +- src/lib/ckeditor/styles.js | 272 +- src/lib/ckeditor/vendor/promise.js | 402 +- src/lib/environment.ts | 4 +- src/lib/html-rendered-diff/index.d.ts | 24 +- src/lib/html-rendered-diff/index.js | 395 +- src/main.ts | 10 +- src/styles/globals.scss | 78 +- src/styles/main.scss | 14 +- .../third-party/_bootstrap-variables.scss | 8 +- src/styles/third-party/_bootstrap.scss | 4 +- src/styles/third-party/bootstrap-main.scss | 78 +- src/styles/third-party/bootstrap/_alerts.scss | 95 +- src/styles/third-party/bootstrap/_badges.scss | 98 +- .../third-party/bootstrap/_breadcrumbs.scss | 38 +- .../third-party/bootstrap/_button-groups.scss | 264 +- .../third-party/bootstrap/_buttons.scss | 261 +- .../third-party/bootstrap/_carousel.scss | 458 +- src/styles/third-party/bootstrap/_close.scss | 44 +- src/styles/third-party/bootstrap/_code.scss | 82 +- .../bootstrap/_component-animations.scss | 44 +- .../third-party/bootstrap/_dropdowns.scss | 278 +- src/styles/third-party/bootstrap/_forms.scss | 786 +- src/styles/third-party/bootstrap/_grid.scss | 38 +- .../third-party/bootstrap/_input-groups.scss | 199 +- .../third-party/bootstrap/_jumbotron.scss | 86 +- src/styles/third-party/bootstrap/_labels.scss | 68 +- .../third-party/bootstrap/_list-group.scss | 154 +- src/styles/third-party/bootstrap/_media.scss | 46 +- src/styles/third-party/bootstrap/_mixins.scss | 60 +- src/styles/third-party/bootstrap/_modals.scss | 202 +- src/styles/third-party/bootstrap/_navbar.scss | 921 +- src/styles/third-party/bootstrap/_navs.scss | 340 +- .../third-party/bootstrap/_normalize.scss | 134 +- src/styles/third-party/bootstrap/_pager.scss | 92 +- .../third-party/bootstrap/_pagination.scss | 150 +- src/styles/third-party/bootstrap/_panels.scss | 426 +- .../third-party/bootstrap/_popovers.scss | 226 +- src/styles/third-party/bootstrap/_print.scss | 190 +- .../third-party/bootstrap/_progress-bars.scss | 72 +- .../bootstrap/_responsive-embed.scss | 40 +- .../bootstrap/_responsive-utilities.scss | 140 +- .../third-party/bootstrap/_scaffolding.scss | 124 +- src/styles/third-party/bootstrap/_tables.scss | 310 +- src/styles/third-party/bootstrap/_theme.scss | 339 +- .../third-party/bootstrap/_thumbnails.scss | 58 +- .../third-party/bootstrap/_tooltip.scss | 208 +- src/styles/third-party/bootstrap/_type.scss | 336 +- .../third-party/bootstrap/_utilities.scss | 30 +- .../third-party/bootstrap/_variables.scss | 22 +- src/styles/third-party/bootstrap/_wells.scss | 34 +- .../third-party/bootstrap/mixins/_alerts.scss | 22 +- .../bootstrap/mixins/_background-variant.scss | 18 +- .../bootstrap/mixins/_border-radius.scss | 16 +- .../bootstrap/mixins/_buttons.scss | 96 +- .../bootstrap/mixins/_center-block.scss | 6 +- .../bootstrap/mixins/_clearfix.scss | 16 +- .../third-party/bootstrap/mixins/_forms.scss | 138 +- .../bootstrap/mixins/_gradients.scss | 100 +- .../bootstrap/mixins/_grid-framework.scss | 106 +- .../third-party/bootstrap/mixins/_grid.scss | 142 +- .../bootstrap/mixins/_hide-text.scss | 12 +- .../third-party/bootstrap/mixins/_image.scss | 27 +- .../third-party/bootstrap/mixins/_labels.scss | 16 +- .../bootstrap/mixins/_list-group.scss | 50 +- .../bootstrap/mixins/_nav-divider.scss | 10 +- .../bootstrap/mixins/_nav-vertical-align.scss | 6 +- .../bootstrap/mixins/_opacity.scss | 8 +- .../bootstrap/mixins/_pagination.scss | 42 +- .../third-party/bootstrap/mixins/_panels.scss | 34 +- .../bootstrap/mixins/_progress-bar.scss | 12 +- .../bootstrap/mixins/_reset-filter.scss | 2 +- .../bootstrap/mixins/_reset-text.scss | 34 +- .../third-party/bootstrap/mixins/_resize.scss | 4 +- .../mixins/_responsive-visibility.scss | 27 +- .../third-party/bootstrap/mixins/_size.scss | 6 +- .../bootstrap/mixins/_tab-focus.scss | 10 +- .../bootstrap/mixins/_table-row.scss | 46 +- .../bootstrap/mixins/_text-emphasis.scss | 18 +- .../bootstrap/mixins/_text-overflow.scss | 6 +- .../bootstrap/mixins/_vendor-prefixes.scss | 220 +- src/styles/ve-app/layout/_login-select.scss | 214 +- src/styles/ve-app/layout/_pane-center.scss | 224 +- src/styles/ve-app/layout/_pane-left.scss | 116 +- src/styles/ve-app/layout/_pane-right.scss | 218 +- src/styles/ve-app/layout/_panes.scss | 126 +- src/styles/ve-app/layout/_ve-dropdowns.scss | 568 +- src/styles/ve-app/layout/_ve-footer.scss | 28 +- src/styles/ve-app/layout/_ve-nav.scss | 482 +- src/styles/ve-app/layout/_ve-no-panes.scss | 356 +- .../ve-app/layout/_ve-table-filter.scss | 162 +- src/styles/ve-app/layout/_ve-tabs.scss | 196 +- .../ve-app/thirdparty/_autosave-plugin.scss | 324 +- src/styles/ve-app/ve-app-main.scss | 726 +- src/styles/ve-base/_ve-colors.scss | 2 +- src/styles/ve-base/_ve-mixins.scss | 62 +- src/styles/ve-base/_ve-typography.scss | 9 +- .../components/_mms-add-pe-button.scss | 174 +- .../components/_mms-autocomplete-modal.scss | 8 +- .../components/_mms-buttons.scss | 74 +- .../ve-components/components/_mms-editor.scss | 38 +- .../components/_mms-history.scss | 216 +- .../ve-components/components/_mms-jobs.scss | 114 +- .../components/_mms-mention.scss | 111 +- .../components/_mms-misc-components.scss | 168 +- .../ve-components/components/_mms-search.scss | 570 +- .../ve-components/components/_mms-tree.scss | 76 +- .../components/_mms-tsp-view.scss | 58 +- .../ve-components/components/_mms-view.scss | 129 +- .../ve-components/components/_spec.scss | 324 +- .../ve-components/components/_transclude.scss | 271 +- .../ve-components/components/_ve-toolbar.scss | 244 +- .../ve-components/ve-components-main.scss | 30 +- src/ve-app/events.d.ts | 14 +- src/ve-app/index.ts | 76 +- src/ve-app/login/index.ts | 12 +- src/ve-app/login/login-banner.component.ts | 32 +- src/ve-app/login/login.component.ts | 84 +- .../login/modals/login-warning.modal.ts | 42 +- src/ve-app/login/redirect.component.ts | 196 +- src/ve-app/login/select.component.ts | 178 +- src/ve-app/login/short-url.component.ts | 70 +- src/ve-app/main/components/index.ts | 8 +- .../main/components/main-menu.component.ts | 194 +- .../main/components/nav-bar.component.ts | 124 +- .../components/system-banner.component.ts | 30 +- .../components/system-footer.component.ts | 30 +- src/ve-app/main/index.ts | 8 +- src/ve-app/main/main.component.ts | 204 +- .../main/modals/about-modal.component.ts | 36 +- src/ve-app/main/modals/index.ts | 12 +- .../main/modals/login-modal.component.ts | 52 +- .../modals/print-confirm-modal.component.ts | 220 +- .../main/modals/select-modal.component.ts | 130 +- .../modals/table-export-modal.component.ts | 26 +- .../main/modals/working-modal.component.ts | 22 +- src/ve-app/main/services/AppUtils.service.ts | 296 +- .../main/services/FullDocument.service.ts | 182 +- src/ve-app/main/services/Resolve.service.ts | 260 +- src/ve-app/main/services/index.ts | 12 +- src/ve-app/pane-center/document.component.ts | 362 +- src/ve-app/pane-center/index.ts | 14 +- .../pane-center/pane-center-buttons.config.ts | 4 +- src/ve-app/pane-center/refs.component.ts | 236 +- .../pane-center/reorder-group.component.ts | 230 +- src/ve-app/pane-center/reorder.component.ts | 204 +- src/ve-app/pane-center/search.component.ts | 46 +- .../services/ContentWindow.service.ts | 16 +- src/ve-app/pane-center/slideshow.component.ts | 335 +- src/ve-app/pane-left/index.ts | 4 +- src/ve-app/pane-left/left-buttons.config.ts | 10 +- src/ve-app/pane-left/left-pane.component.ts | 404 +- .../pane-left/left-toolbar.component.ts | 80 +- src/ve-app/pane-right/index.ts | 4 +- src/ve-app/pane-right/right-buttons.config.ts | 6 +- src/ve-app/pane-right/right-pane.component.ts | 152 +- .../pane-right/right-toolbar.component.ts | 76 +- src/ve-app/ve-app.module.ts | 266 +- .../components/annotation.component.ts | 132 +- .../components/error.component.ts | 50 +- src/ve-components/components/index.ts | 4 +- .../diffs/components/diff-attr.component.ts | 196 +- .../diffs/components/diff-html.component.ts | 80 +- src/ve-components/diffs/components/index.ts | 4 +- src/ve-components/diffs/index.ts | 10 +- src/ve-components/diffs/modals/index.ts | 12 +- .../modals/merge-confirm-modal.component.ts | 58 +- .../diffs/modals/revert-confirm.component.ts | 100 +- .../diffs/modals/save-conflict.component.ts | 34 +- .../diffs/services/DiffMerge.service.ts | 100 +- src/ve-components/index.ts | 34 +- .../insertions/components/index.ts | 10 +- .../components/insert-comment.component.ts | 52 +- .../components/insert-element.component.ts | 70 +- .../components/insert-pe.component.ts | 84 +- .../components/insert-ref.component.ts | 76 +- .../components/insert-view.component.ts | 104 +- src/ve-components/insertions/index.ts | 10 +- .../insert-element-modal.component.ts | 80 +- .../insertions/insertion.controller.ts | 194 +- .../insertions/services/Insertion.service.ts | 60 +- .../insertions/services/index.ts | 4 +- .../presentations/add-pe-menu.component.ts | 40 +- .../components/present-comment.component.ts | 10 +- .../components/present-equation.component.ts | 10 +- .../components/present-figure.component.ts | 10 +- .../components/present-image.component.ts | 10 +- .../components/present-list-t.component.ts | 10 +- .../components/present-list.component.ts | 32 +- .../components/present-paragraph.component.ts | 32 +- .../components/present-section.component.ts | 10 +- .../components/present-table-t.component.ts | 10 +- .../components/present-table.component.ts | 560 +- src/ve-components/presentations/index.ts | 42 +- .../presentations/mms-view-link.component.ts | 204 +- .../presentations/mmsMaturityBar.directive.ts | 46 +- .../presentation-element.controller.ts | 134 +- .../services/Presentation.service.ts | 76 +- .../services/Table2CSV.service.ts | 118 +- .../services/ViewHtml.service.ts | 166 +- .../presentations/view-pe.component.ts | 126 +- .../presentations/view.component.ts | 240 +- .../services/Component.service.ts | 40 +- .../services/Extension.service.ts | 70 +- src/ve-components/services/index.ts | 8 +- .../components/spec-editor.component.ts | 72 +- .../components/spec-history.component.ts | 172 +- .../components/spec-inspector.component.ts | 36 +- .../components/spec-ref-list.component.ts | 98 +- .../components/spec-reorder.component.ts | 200 +- src/ve-components/spec-tools/index.ts | 18 +- .../spec-tools/mms-tools.component.ts | 280 +- .../spec-tools/services/Spec.service.ts | 242 +- .../spec-tools/spec-tool.controller.ts | 178 +- .../transclusions/components/index.ts | 24 +- .../components/transclude-art.component.ts | 72 +- .../components/transclude-attr.component.ts | 102 +- .../components/transclude-com.component.ts | 72 +- .../components/transclude-doc.component.ts | 118 +- .../components/transclude-enum.component.ts | 74 +- .../transclude-group-docs.component.ts | 90 +- .../components/transclude-img.component.ts | 68 +- .../components/transclude-name.component.ts | 78 +- .../transclude-section.component.ts | 86 +- .../components/transclude-val.component.ts | 216 +- .../transclude-value-link.component.ts | 60 +- .../components/transclude-view.component.ts | 50 +- .../deletable-transclusion.controller.ts | 72 +- src/ve-components/transclusions/index.ts | 18 +- .../transclusions/mms-cf.component.ts | 104 +- .../mms-transclude-compatibility.component.ts | 18 +- .../modals/create-transclusion.modal.ts | 202 +- .../services/Transclusion.service.ts | 74 +- .../transclusions/transclusion.controller.ts | 492 +- src/ve-components/trees/components/index.ts | 12 +- .../components/tree-of-contents.component.ts | 30 +- .../components/tree-of-documents.component.ts | 48 +- .../components/tree-of-equations.component.ts | 28 +- .../components/tree-of-favorites.component.ts | 26 +- .../components/tree-of-figures.component.ts | 28 +- .../components/tree-of-tables.component.ts | 28 +- src/ve-components/trees/index.ts | 10 +- .../trees/mms-trees.component.ts | 352 +- .../trees/services/Tree.service.ts | 848 +- src/ve-components/trees/tree.controller.ts | 166 +- src/ve-components/ve-components.module.ts | 12 +- .../button-bar/button-bar.component.ts | 78 +- src/ve-core/button-bar/index.ts | 10 +- .../button-bar/services/BarButton.api.ts | 118 +- .../button-bar/services/ButtonBar.api.ts | 90 +- .../button-bar/services/ButtonBar.service.ts | 116 +- .../components/mention-intercept.component.ts | 24 +- .../editor/components/mention.component.ts | 36 +- src/ve-core/editor/editor-buttons.config.ts | 4 +- src/ve-core/editor/editor.component.ts | 522 +- src/ve-core/editor/index.ts | 12 +- .../editor/services/EditDialog.service.ts | 12 +- src/ve-core/editor/services/Editor.service.ts | 286 +- .../editor/services/Mention.service.ts | 308 +- src/ve-core/editor/services/index.ts | 12 +- src/ve-core/events.d.ts | 36 +- src/ve-core/index.ts | 14 +- .../modals/confirm-delete-modal.component.ts | 72 +- src/ve-core/modals/index.ts | 4 +- src/ve-core/search/index.ts | 6 +- .../search/mms-search-buttons.config.ts | 4 +- .../search/mms-search-results.component.ts | 20 +- src/ve-core/search/mms-search.component.ts | 518 +- src/ve-core/toolbar/index.ts | 8 +- src/ve-core/toolbar/services/Toolbar.api.ts | 76 +- .../toolbar/services/Toolbar.service.ts | 186 +- src/ve-core/toolbar/tool-bar.component.ts | 82 +- src/ve-core/ve-core.module.ts | 18 +- src/ve-extensions/experimental-magic/index.ts | 2 +- .../spec-tools/spec-magic.component.ts | 32 +- src/ve-extensions/index.ts | 2 +- .../present-plots/Plot.service.ts | 246 +- src/ve-extensions/present-plots/config.json | 14 +- .../presentations/components/index.ts | 14 +- .../components/mmsC3Plot.directive.ts | 76 +- ...mmsD3GroupedHorizontalBarPlot.directive.ts | 298 +- ...mmsD3NormalizedStackedBarPlot.directive.ts | 118 +- .../mmsD3ParallelAxisPlot.directive.ts | 218 +- .../components/mmsD3RadarPlot.directive.ts | 262 +- .../presentations/present-plot.component.ts | 54 +- .../ts-diagram/mmsTsDiagram.directive.ts | 156 +- src/ve-types/angular.d.ts | 47 +- src/ve-types/components/index.d.ts | 52 +- src/ve-types/components/insertions.d.ts | 36 +- src/ve-types/components/presentation.d.ts | 38 +- src/ve-types/config.d.ts | 30 +- src/ve-types/core/editor.d.ts | 12 +- src/ve-types/mms/index.d.ts | 54 +- src/ve-types/mms/mms.d.ts | 204 +- src/ve-types/mms/orgsAndProjects.d.ts | 60 +- src/ve-types/mms/valuesAndInstances.d.ts | 24 +- src/ve-types/mms/views.d.ts | 104 +- src/ve-types/third-party/angular.d.ts | 8 +- src/ve-types/third-party/jquery.d.ts | 12 +- src/ve-types/third-party/mathjax.d.ts | 2 +- src/ve-types/tree.d.ts | 204 +- src/ve-types/view-editor.d.ts | 84 +- src/ve-types/window.d.ts | 18 +- .../application/Application.service.ts | 112 +- src/ve-utils/application/Branding.service.ts | 94 +- src/ve-utils/application/Image.service.ts | 40 +- src/ve-utils/application/Math.service.ts | 22 +- src/ve-utils/application/RootScope.service.ts | 92 +- src/ve-utils/application/ShortUrl.service.ts | 194 +- src/ve-utils/application/Utils.service.ts | 348 +- src/ve-utils/application/index.ts | 28 +- src/ve-utils/core/Cache.service.ts | 120 +- src/ve-utils/core/Edit.service.ts | 64 +- src/ve-utils/core/Event.service.ts | 62 +- src/ve-utils/core/Session.service.ts | 42 +- src/ve-utils/core/index.ts | 16 +- src/ve-utils/index.ts | 16 +- src/ve-utils/mms-api-client/Api.service.ts | 156 +- .../mms-api-client/Authorization.service.ts | 94 +- src/ve-utils/mms-api-client/Base.service.ts | 26 +- .../mms-api-client/Element.service.ts | 590 +- src/ve-utils/mms-api-client/Http.service.ts | 120 +- .../mms-api-client/Permissions.service.ts | 52 +- .../mms-api-client/Project.service.ts | 436 +- src/ve-utils/mms-api-client/URL.service.ts | 296 +- src/ve-utils/mms-api-client/User.service.ts | 48 +- src/ve-utils/mms-api-client/Value.service.ts | 206 +- src/ve-utils/mms-api-client/View.service.ts | 828 +- src/ve-utils/mms-api-client/index.ts | 40 +- src/ve-utils/modals/ve-modal.controller.ts | 6 +- .../model-schema/CameoSchema.service.ts | 12 +- .../model-schema/JupyterSchema.service.ts | 12 +- src/ve-utils/model-schema/Schema.service.ts | 98 +- src/ve-utils/model-schema/index.ts | 12 +- src/ve-utils/third-party/index.ts | 2 +- src/ve-utils/third-party/jquery/index.ts | 4 +- .../third-party/jquery/isOnScreen.jquery.ts | 40 +- .../third-party/jquery/table2CSV.jquery.ts | 118 +- src/ve-utils/utils/change.util.ts | 38 +- src/ve-utils/utils/emf.util.ts | 168 +- src/ve-utils/utils/index.ts | 4 +- src/ve-utils/ve-utils.module.ts | 8 +- tsconfig.json | 3 +- 580 files changed, 44108 insertions(+), 89215 deletions(-) diff --git a/.eslintrc b/.eslintrc index a162b2a8c..0a021a2ea 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,119 +1,105 @@ { - "root": true, - "extends": ["eslint:recommended"], - "env": { - "browser": true, - "es2021": true + "settings": { + "import/extensions": [".js", ".ts"], + "import/parsers": { + "@typescript-eslint/parser": [ + ".ts" + ] + }, + "import/resolver": { + "typescript": { + "alwaysCheckTypes": true, + "project": "./tsconfig.json", + "extensions": [".js", ".jsx", ".ts", ".tsx"] + }, + "node": { + "extensions": [".js", ".jsx", ".ts", ".tsx"], + "moduleDirectory": ["node_modules"] + } + } }, + "parser": "@typescript-eslint/parser", "parserOptions": { - "ecmaVersion": 12, - "sourceType": "module" + "project": "./tsconfig.json", + "tsconfigRootDir": "./" }, - "overrides": [ + "plugins": ["unused-imports"], + "extends": [ + "plugin:@typescript-eslint/recommended", + "plugin:@typescript-eslint/recommended-requiring-type-checking", + "plugin:import/errors", + "plugin:import/warnings", + "plugin:import/typescript", + "plugin:prettier/recommended" + ], + "rules": { + "@typescript-eslint/no-unused-vars": "off", + "unused-imports/no-unused-imports": "error", + "no-multiple-empty-lines": 2, + "import/newline-after-import": [ + 2 + ], + "@typescript-eslint/explicit-function-return-type": 2, + "@typescript-eslint/no-inferrable-types": [ + 2, + { + "ignoreProperties": true + } + ], + "import/order": ["error", { + "newlines-between": "always", + "alphabetize": { + "order": "asc", + "caseInsensitive": true + }, + "pathGroups": [ { - "files": ["**/*.ts"], - "settings": { - "import/extensions": [".js", ".ts"], - "import/parsers": { - "@typescript-eslint/parser": [".ts"] - }, - "import/resolver": { - "typescript": { - "alwaysCheckTypes": true, - "project": "./tsconfig.json", - "extensions": [".ts", ".tsx"] - }, - "node": { - "extensions": [".js", ".jsx", ".ts", ".tsx"], - "moduleDirectory": ["node_modules"] - } - } - }, - "parser": "@typescript-eslint/parser", - "parserOptions": { - "project": "./tsconfig.json", - "tsconfigRootDir": "./" - }, - "plugins": ["unused-imports"], - "extends": [ - "plugin:@typescript-eslint/recommended", - "plugin:@typescript-eslint/recommended-requiring-type-checking", - "plugin:import/errors", - "plugin:import/warnings", - "plugin:import/typescript", - "plugin:prettier/recommended" - ], - "rules": { - "@typescript-eslint/no-unused-vars": "off", - "unused-imports/no-unused-imports": "error", - "no-multiple-empty-lines": 2, - "import/newline-after-import": [2], - "@typescript-eslint/explicit-function-return-type": 2, - "@typescript-eslint/no-inferrable-types": [ - 2, - { - "ignoreProperties": true - } - ], - "import/order": [ - "error", - { - "newlines-between": "always", - "alphabetize": { - "order": "asc", - "caseInsensitive": true - }, - "pathGroups": [ - { - "pattern": "@/**", - "group": "external", - "position": "after" - }, - { - "pattern": "@ve-app", - "group": "internal", - "position": "after" - }, - { - "pattern": "@ve-components", - "group": "internal", - "position": "after" - }, - { - "pattern": "@ve-core", - "group": "internal", - "position": "after" - }, - { - "pattern": "@ve-utils", - "group": "internal", - "position": "after" - }, - { - "pattern": "@ve-types/**", - "group": "type", - "position": "after" - }, - { - "pattern": "../../lib/**", - "group": "external", - "position": "after" - } - ], - "groups": [ - "builtin", - "external", - "internal", - "unknown", - "parent", - "sibling", - "index", - "object", - "type" - ] - } - ] - } + "pattern": "@/**", + "group": "external", + "position": "after" + }, + { + "pattern": "@ve-app", + "group": "internal", + "position": "after" + }, + { + "pattern": "@ve-components", + "group": "internal", + "position": "after" + }, + { + "pattern": "@ve-core", + "group": "internal", + "position": "after" + }, + { + "pattern": "@ve-utils", + "group": "internal", + "position": "after" + }, + { + "pattern": "@ve-types/**", + "group": "type", + "position": "after" + }, + { + "pattern": "../../lib/**", + "group": "external", + "position": "after" } - ] + ], + "groups": [ + "builtin", + "external", + "internal", + "unknown", + "parent", + "sibling", + "index", + "object", + "type" + ] + }] + } } diff --git a/.prettierrc.js b/.prettierrc.js index 03ce334bd..fc669ac24 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -2,6 +2,7 @@ module.exports = { trailingComma: 'es5', tabWidth: 4, + semi: false, singleQuote: true, printWidth: 120, } diff --git a/package.json b/package.json index 9ba098ed4..5f8e3ca99 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,8 @@ "format": "prettier --write \"**/*.ts\" \"**/*.js\"", "lint": "DEBUG=eslint:cli-engine eslint ./src", "prebuild": "yarn lint && yarn format", - "build": "webpack --config webpack.config.ts --mode=production --bail", - "watch": "webpack --config webpack.config.ts --mode=development --watch --progress", + "build": "webpack --config webpack.config.js --mode=production --bail", + "watch": "webpack --config webpack.config.js --mode=development --watch --progress", "test": "yarn prebuild && yarn build" }, "devDependencies": { diff --git a/src/errors/configError.html b/src/errors/configError.html index 556a53664..24cb93aed 100644 --- a/src/errors/configError.html +++ b/src/errors/configError.html @@ -1,15 +1,15 @@ - - Configuration Error - - -

    Configuration Error

    -
    -

    There was a problem loading View Editor due to a configuration error, please contact your administrator.

    -

    Error:

    - - - + + Configuration Error + + +

    Configuration Error

    +
    +

    There was a problem loading View Editor due to a configuration error, please contact your administrator.

    +

    Error:

    + + + \ No newline at end of file diff --git a/src/filters/underlineMatch.js b/src/filters/underlineMatch.js index 51d74227e..97255c318 100644 --- a/src/filters/underlineMatch.js +++ b/src/filters/underlineMatch.js @@ -1,11 +1,9 @@ -import angular from 'angular'; - -angular.module('ve-utils').filter('underlineMatch', ['$filter', partialMatch]); +angular.module('ve-utils').filter('underlineMatch', ['$filter', partialMatch]) function partialMatch($filter) { - var uibTypeaheadHighlightFn = $filter('uibTypeaheadHighlight'); + var uibTypeaheadHighlightFn = $filter('uibTypeaheadHighlight') return function (match, query) { - var result = uibTypeaheadHighlightFn(match, query); - result = result.replace('', '').replace('', ''); - return result; - }; + var result = uibTypeaheadHighlightFn(match, query) + result = result.replace('', '').replace('', '') + return result + } } diff --git a/src/index.html b/src/index.html index 4aa2129ee..e4c3245ee 100644 --- a/src/index.html +++ b/src/index.html @@ -10,59 +10,62 @@ - + - - - - - View Editor - - - - - - - + + + + + View Editor + + + + + + - - + - - + + - - - - - + + + + + + + + + + \ No newline at end of file diff --git a/src/lib/angular-flatpickr/ngFlatpickr.main.ts b/src/lib/angular-flatpickr/ngFlatpickr.main.ts index 3be8c2771..9dce981e6 100644 --- a/src/lib/angular-flatpickr/ngFlatpickr.main.ts +++ b/src/lib/angular-flatpickr/ngFlatpickr.main.ts @@ -1 +1 @@ -import './ngFlatpickr.module'; +import './ngFlatpickr.module' diff --git a/src/lib/angular-flatpickr/ngFlatpickr.module.ts b/src/lib/angular-flatpickr/ngFlatpickr.module.ts index 273e73fbe..bdb469d04 100644 --- a/src/lib/angular-flatpickr/ngFlatpickr.module.ts +++ b/src/lib/angular-flatpickr/ngFlatpickr.module.ts @@ -1,13 +1,10 @@ -import angular, { IComponentController } from 'angular'; -import flatpickr from 'flatpickr'; +import angular from 'angular' +import * as _flatpickr from 'flatpickr' +import { FlatpickrFn, Instance } from 'flatpickr/dist/types/instance' -import { VeComponentOptions } from '@ve-types/angular'; +import { VeComponentOptions } from '@ve-types/angular' -export interface ngFlatpickrOptions extends flatpickr.Options.Options { - placeholder: string; -} - -export type ngFlatpickrCallback = (fpInstance: flatpickr.Instance) => void; +const flatpickr: FlatpickrFn = _flatpickr.default const ngFlatpickrComponent: VeComponentOptions = { selector: 'ngFlatpickr', @@ -22,63 +19,74 @@ const ngFlatpickrComponent: VeComponentOptions = { fpOpts: '<', fpOnSetup: '&', }, - controller: class ngFlatpickrCtrl implements IComponentController { - static $inject = ['$element', '$timeout', '$scope']; + controller: class ngFlatpickrCtrl implements angular.IComponentController { + static $inject = ['$element', '$timeout', '$scope'] //Bindings - private fpOpts: ngFlatpickrOptions; - private fpOnSetup: ngFlatpickrCallback; + private fpOpts + private fpOnSetup - private inputDate: number; + private inputDate - constructor(private $element: JQuery, private $timeout: angular.ITimeoutService) {} + constructor( + private $element: JQuery, + private $timeout: angular.ITimeoutService, + private $scope: angular.IScope + ) {} - $onInit(): void { - this.fpOpts.placeholder = this.fpOpts.placeholder || 'Select Date..'; + $onInit() { + this.fpOpts.placeholder = this.fpOpts.placeholder || 'Select Date..' } $postLink(): void { - this.grabElementAndRunFlatpickr(); + this.grabElementAndRunFlatpickr() } - $onChanges(): void { - this.grabElementAndRunFlatpickr(); + $onChanges() { + this.grabElementAndRunFlatpickr() } - grabElementAndRunFlatpickr = (): void => { - void this.$timeout( + grabElementAndRunFlatpickr = () => { + this.$timeout( () => { - const transcludeEl = this.$element.find('ng-transclude')[0]; - const element = transcludeEl.children[0]; + const transcludeEl = this.$element.find('ng-transclude')[0] + const element = transcludeEl.children[0] - this.setDatepicker(element); + this.setDatepicker(element) }, 0, true - ); - }; + ) + } + + setDatepicker = (element) => { + const fpLib = flatpickr - setDatepicker = (element: Element): void => { - if (!flatpickr) { - return console.warn('Unable to find any flatpickr installation'); + if (!fpLib) { + return console.warn('Unable to find any flatpickr installation') } - const fpInstance: flatpickr.Instance = flatpickr(element, this.fpOpts); + const fpInstance: Instance = fpLib(element, this.fpOpts) if (this.fpOnSetup) { - this.fpOnSetup(fpInstance); + this.fpOnSetup({ + fpItem: fpInstance, + }) } // If has ngModel set the date if (this.inputDate) { - fpInstance.setDate(this.inputDate); + fpInstance.setDate(this.inputDate) } // destroy the flatpickr instance when the dom element is removed angular.element(element).on('$destroy', () => { - fpInstance.destroy(); - }); - }; + fpInstance.destroy() + }) + + // Refresh the scope + //this.$scope.$applyAsync(); + } }, -}; -angular.module('angular-flatpickr', []).component(ngFlatpickrComponent.selector, ngFlatpickrComponent); +} +angular.module('angular-flatpickr', []).component(ngFlatpickrComponent.selector, ngFlatpickrComponent) diff --git a/src/lib/angular-promise-extras/angular-promise-extras.d.ts b/src/lib/angular-promise-extras/angular-promise-extras.d.ts index edb93abfe..e94b9231b 100644 --- a/src/lib/angular-promise-extras/angular-promise-extras.d.ts +++ b/src/lib/angular-promise-extras/angular-promise-extras.d.ts @@ -1,12 +1,12 @@ -import { VePromise } from '@ve-types/angular'; +import { VePromise } from '@ve-types/angular' declare module 'angular' { - type PromiseState = 'pending' | 'fulfilled' | 'rejected'; + type PromiseState = 'pending' | 'fulfilled' | 'rejected' interface PromiseValue { - state: PromiseState; - value?: T | undefined; - reason?: unknown; + state: PromiseState + value?: T | undefined + reason?: unknown } // tslint:disable-next-line interface-name @@ -50,7 +50,7 @@ declare module 'angular' { PromiseValue, PromiseValue ] - >; + > allSettled( values: [ T1 | VePromise, @@ -86,7 +86,7 @@ declare module 'angular' { PromiseValue, PromiseValue ] - >; + > allSettled( values: [ T1 | VePromise, @@ -119,7 +119,7 @@ declare module 'angular' { PromiseValue, PromiseValue ] - >; + > allSettled( values: [ T1 | VePromise, @@ -149,7 +149,7 @@ declare module 'angular' { PromiseValue, PromiseValue ] - >; + > allSettled( values: [ T1 | VePromise, @@ -169,7 +169,7 @@ declare module 'angular' { PromiseValue ], [PromiseValue, PromiseValue, PromiseValue, PromiseValue, PromiseValue, PromiseValue] - >; + > allSettled( values: [ T1 | VePromise, @@ -181,33 +181,33 @@ declare module 'angular' { ): VePromise< [PromiseValue, PromiseValue, PromiseValue, PromiseValue, PromiseValue], [PromiseValue, PromiseValue, PromiseValue, PromiseValue, PromiseValue] - >; + > allSettled( values: [T1 | VePromise, T2 | VePromise, T3 | VePromise, T4 | VePromise] ): VePromise< [PromiseValue, PromiseValue, PromiseValue, PromiseValue], [PromiseValue, PromiseValue, PromiseValue, PromiseValue] - >; + > allSettled( values: [T1 | VePromise, T2 | VePromise, T3 | VePromise] ): VePromise< [PromiseValue, PromiseValue, PromiseValue], [PromiseValue, PromiseValue, PromiseValue] - >; + > allSettled( values: [T1 | VePromise, T2 | VePromise] - ): VePromise<[PromiseValue, PromiseValue], [PromiseValue, PromiseValue]>; + ): VePromise<[PromiseValue, PromiseValue], [PromiseValue, PromiseValue]> // tslint:enable:max-line-length allSettled( promises: Array> - ): VePromise>, Array>>; + ): VePromise>, Array>> allSettled(promises: { - [K in keyof T]: T[K] | VePromise; - }): VePromise<{ [K in keyof T]: PromiseValue }>; + [K in keyof T]: T[K] | VePromise + }): VePromise<{ [K in keyof T]: PromiseValue }> - isFulfilledState(promise: PromiseValue): boolean; - isRejectedState(promise: PromiseValue): boolean; + isFulfilledState(promise: PromiseValue): boolean + isRejectedState(promise: PromiseValue): boolean } } diff --git a/src/lib/angular-promise-extras/angular-promise-extras.js b/src/lib/angular-promise-extras/angular-promise-extras.js index 3d9c9fba6..1fe2f2b67 100644 --- a/src/lib/angular-promise-extras/angular-promise-extras.js +++ b/src/lib/angular-promise-extras/angular-promise-extras.js @@ -1,5 +1,5 @@ -(function (angular) { - 'use strict'; +;(function (angular) { + 'use strict' /** * Called with an array this acts like map, otherwise it acts like _.mapValues @@ -7,14 +7,14 @@ * @return {Array|Object} The same type as the input argument. */ var mapValues = function (obj, callback) { - if (Array.isArray(obj)) return obj.map(callback); + if (Array.isArray(obj)) return obj.map(callback) - var ret = {}; + var ret = {} Object.keys(obj).forEach(function (key, val) { - ret[key] = callback(obj[key], key); - }); - return ret; - }; + ret[key] = callback(obj[key], key) + }) + return ret + } angular .module('ngPromiseExtras', []) @@ -24,7 +24,7 @@ $provide.decorator('$q', [ '$delegate', function ($delegate) { - var $q = $delegate; + var $q = $delegate $q.allSettled = function (promises) { return $q.all( @@ -33,50 +33,50 @@ return { state: 'pending', value: promiseOrValue, - }; + } return promiseOrValue.then( function (value) { return { state: 'fulfilled', value: value, - }; + } }, function (reason) { return { state: 'rejected', reason: reason, - }; + } } - ); + ) }) - ); - }; + ) + } $q.map = function (values, callback) { - return $q.all(mapValues(values, callback)); - }; + return $q.all(mapValues(values, callback)) + } $q.mapSettled = function (values, callback) { - return $q.allSettled(mapValues(values, callback)); - }; + return $q.allSettled(mapValues(values, callback)) + } if (!$q.resolve) { /** * Like Bluebird.resolve (was introduced in angular 1.4). */ $q.resolve = function (value) { - if (value && value.then) return value; + if (value && value.then) return value else return $q(function (resolve) { - resolve(value); - }); - }; + resolve(value) + }) + } } - return $q; + return $q }, - ]); + ]) }, ]) .run([ @@ -84,35 +84,35 @@ '$window', function ($q, $window) { $window.Promise = function (executor) { - return $q(executor); - }; + return $q(executor) + } - $window.Promise.all = $q.all.bind($q); - $window.Promise.reject = $q.reject.bind($q); - $window.Promise.resolve = $q.when.bind($q); - $window.Promise.allSettled = $q.allSettled.bind($q); + $window.Promise.all = $q.all.bind($q) + $window.Promise.reject = $q.reject.bind($q) + $window.Promise.resolve = $q.when.bind($q) + $window.Promise.allSettled = $q.allSettled.bind($q) $window.Promise.race = function (promises) { - var promiseMgr = $q.defer(); + var promiseMgr = $q.defer() for (var i = 0; i < promises.length; i++) { promises[i].then(function (result) { if (promiseMgr) { - promiseMgr.resolve(result); - promiseMgr = null; + promiseMgr.resolve(result) + promiseMgr = null } - }); + }) promises[i].catch(function (result) { if (promiseMgr) { - promiseMgr.reject(result); - promiseMgr = null; + promiseMgr.reject(result) + promiseMgr = null } - }); + }) } - return promiseMgr.promise; - }; + return promiseMgr.promise + } }, - ]); -})(window.angular); + ]) +})(window.angular) diff --git a/src/lib/angular-ui-tree-filter/angular-ui-tree-filter.d.ts b/src/lib/angular-ui-tree-filter/angular-ui-tree-filter.d.ts index 319de5dca..0ecc1cf32 100644 --- a/src/lib/angular-ui-tree-filter/angular-ui-tree-filter.d.ts +++ b/src/lib/angular-ui-tree-filter/angular-ui-tree-filter.d.ts @@ -1,7 +1,7 @@ declare namespace angular { namespace uiTreeFilter { interface IFilterUiTree { - (collection: T, pattern: string, address?: string): T; + (collection: T, pattern: string, address?: string): T } } } diff --git a/src/lib/angular-ui-tree-filter/angular-ui-tree-filter.js b/src/lib/angular-ui-tree-filter/angular-ui-tree-filter.js index 315e049b6..92502337d 100644 --- a/src/lib/angular-ui-tree-filter/angular-ui-tree-filter.js +++ b/src/lib/angular-ui-tree-filter/angular-ui-tree-filter.js @@ -1,5 +1,5 @@ -import angular from 'angular'; -('use strict'); +import angular from 'angular' +;('use strict') angular .module('ui.tree-filter', []) @@ -7,19 +7,19 @@ angular * @name ui.tree-filter.provider:uiTreeFilterSettings */ .provider('uiTreeFilterSettings', function () { - var uiTreeFilterSettings = this; + var uiTreeFilterSettings = this - this.addresses = ['title']; - this.regexFlags = 'gi'; - this.descendantCollection = 'items'; + this.addresses = ['title'] + this.regexFlags = 'gi' + this.descendantCollection = 'items' this.$get = () => { return { addresses: uiTreeFilterSettings.addresses, regexFlags: uiTreeFilterSettings.regexFlags, descendantCollection: uiTreeFilterSettings.descendantCollection, - }; - }; + } + } }) /** * @name ui.tree-filter.factory:uiTreeFilter @@ -37,14 +37,16 @@ angular * @returns {boolean} */ function visit(collection, pattern, address) { - collection = collection || []; - var foundSoFar = false; + collection = collection || [] + var foundSoFar = false collection.forEach((collectionItem) => { - foundSoFar = foundSoFar || testForField(collectionItem, pattern, address); - }); + foundSoFar = + foundSoFar || + testForField(collectionItem, pattern, address) + }) - return foundSoFar; + return foundSoFar } /** @@ -55,13 +57,15 @@ angular * @returns {*} */ function resolveAddress(object, path) { - var parts = path.split('.'); + var parts = path.split('.') if (object === undefined) { - return; + return } - return parts.length < 2 ? object[parts[0]] : resolveAddress(object[parts[0]], parts.slice(1).join('.')); + return parts.length < 2 + ? object[parts[0]] + : resolveAddress(object[parts[0]], parts.slice(1).join('.')) } /** @@ -79,12 +83,24 @@ angular * @returns {boolean} */ function testForField(item, pattern, address) { - var value = resolveAddress(item, address); + var value = resolveAddress(item, address) var found = typeof value === 'string' - ? !!value.match(new RegExp(pattern, uiTreeFilterSettings.regexFlags)) - : false; - return found || visit(item[uiTreeFilterSettings.descendantCollection], pattern, address); + ? !!value.match( + new RegExp( + pattern, + uiTreeFilterSettings.regexFlags + ) + ) + : false + return ( + found || + visit( + item[uiTreeFilterSettings.descendantCollection], + pattern, + address + ) + ) } /** @@ -96,13 +112,15 @@ angular * @returns {boolean} */ return (item, pattern, addresses) => { - addresses = addresses || uiTreeFilterSettings.addresses; + addresses = addresses || uiTreeFilterSettings.addresses return ( pattern === undefined || addresses.reduce((foundSoFar, fieldName) => { - return foundSoFar || testForField(item, pattern, fieldName); + return ( + foundSoFar || testForField(item, pattern, fieldName) + ) }, false) - ); - }; + ) + } }, - ]); + ]) diff --git a/src/lib/ckeditor-plugins/autosave/css/autosave.min.css b/src/lib/ckeditor-plugins/autosave/css/autosave.min.css index db543ef1f..bcd0a0a98 100644 --- a/src/lib/ckeditor-plugins/autosave/css/autosave.min.css +++ b/src/lib/ckeditor-plugins/autosave/css/autosave.min.css @@ -1,94 +1 @@ -.diffContent { - height: 300px; - overflow: auto; -} -.diff * { - white-space: pre-wrap !important; -} -table.diff { - border-collapse: collapse; - border: 1px solid darkgray; -} -table.diff tbody { - font-family: Courier, monospace; -} -table.diff tbody th { - font-family: verdana, arial, 'Bitstream Vera Sans', helvetica, sans-serif; - background: #eed; - font-size: 11px; - font-weight: normal; - border: 1px solid #bbc; - color: #886; - padding: 0.3em 0.5em 0.1em 2em; - text-align: right; - vertical-align: top; -} -table.diff thead { - border-bottom: 1px solid #bbc; - background: #efefef; - font-family: Verdana; -} -table.diff thead th.texttitle { - text-align: left; -} -table.diff tbody td { - padding: 0 0.4em; - vertical-align: top; -} -table.diff .empty { - background-color: #ddd; -} -table.diff .replace { - background-color: #ffc; -} -table.diff .delete { - background-color: #fcc; - width: 380px; - -ms-word-break: break-word; - word-break: break-word; -} -table.diff .skip { - background-color: #efefef; - border: 1px solid #aaa; - border-right: 1px solid #bbc; -} -table.diff .insert { - background-color: #cfc; - width: 380px; - -ms-word-break: break-word; - word-break: break-word; -} -table.diff th.author { - text-align: right; - border-top: 1px solid #bbc; - background: #efefef; -} -del { - background-color: #e99; -} -ins { - background-color: #9e9; - text-decoration: underline; -} -a.cke_dialog_autosave_ok span { - width: auto !important; -} -div.autoSaveMessage div { - left: 42%; - position: absolute; - padding: 2px; - top: 4px; - font-weight: bold; -} -.cke .hidden { - opacity: 0; - visibility: hidden; -} -.cke .show { - opacity: 1; - visibility: visible; - -moz-transition: visibility 0.2s linear, opacity 0.2s linear; - -o-transition: visibility 0.2s linear, opacity 0.2s linear; - -webkit-transition: visibility 0.2s linear, opacity 0.2s linear; - transition: visibility 0.2s linear, opacity 0.2s linear; -} +.diffContent{height:300px;overflow:auto}.diff *{white-space:pre-wrap!important}table.diff{border-collapse:collapse;border:1px solid darkgray}table.diff tbody{font-family:Courier,monospace}table.diff tbody th{font-family:verdana,arial,'Bitstream Vera Sans',helvetica,sans-serif;background:#EED;font-size:11px;font-weight:normal;border:1px solid #BBC;color:#886;padding:.3em .5em .1em 2em;text-align:right;vertical-align:top}table.diff thead{border-bottom:1px solid #BBC;background:#efefef;font-family:Verdana}table.diff thead th.texttitle{text-align:left}table.diff tbody td{padding:0 .4em;vertical-align:top}table.diff .empty{background-color:#DDD}table.diff .replace{background-color:#FFC}table.diff .delete{background-color:#FCC;width:380px;-ms-word-break:break-word;word-break:break-word}table.diff .skip{background-color:#efefef;border:1px solid #AAA;border-right:1px solid #BBC}table.diff .insert{background-color:#CFC;width:380px;-ms-word-break:break-word;word-break:break-word}table.diff th.author{text-align:right;border-top:1px solid #BBC;background:#efefef}del{background-color:#e99;}ins{background-color:#9e9;text-decoration:underline}a.cke_dialog_autosave_ok span{width:auto!important}div.autoSaveMessage div{left:42%;position:absolute;padding:2px;top:4px;font-weight:bold}.cke .hidden{opacity:0;visibility:hidden}.cke .show{opacity:1;visibility:visible;-moz-transition:visibility .2s linear,opacity .2s linear;-o-transition:visibility .2s linear,opacity .2s linear;-webkit-transition:visibility .2s linear,opacity .2s linear;transition:visibility .2s linear,opacity .2s linear} \ No newline at end of file diff --git a/src/lib/ckeditor-plugins/autosave/js/extensions.min.js b/src/lib/ckeditor-plugins/autosave/js/extensions.min.js index 412d9680a..3c1ed254d 100644 --- a/src/lib/ckeditor-plugins/autosave/js/extensions.min.js +++ b/src/lib/ckeditor-plugins/autosave/js/extensions.min.js @@ -1,12955 +1 @@ -__whitespace = { ' ': true, '\t': true, '\n': true, '\f': true, '\r': true }; -difflib = { - defaultJunkFunction: function (a) { - return a in __whitespace; - }, - stripLinebreaks: function (a) { - return a.replace(/^[\n\r]*|[\n\r]*$/g, ''); - }, - stringAsLines: function (f) { - var a = f.indexOf('\n'); - var e = f.indexOf('\r'); - var d = (a > -1 && e > -1) || e < 0 ? '\n' : '\r'; - var b = f.split(d); - for (var c = 0; c < b.length; c++) { - b[c] = difflib.stripLinebreaks(b[c]); - } - return b; - }, - __reduce: function (c, e, b) { - if (b != null) { - var d = b; - var a = 0; - } else { - if (e) { - var d = e[0]; - var a = 1; - } else { - return null; - } - } - for (; a < e.length; a++) { - d = c(d, e[a]); - } - return d; - }, - __ntuplecomp: function (d, c) { - var e = Math.max(d.length, c.length); - for (var f = 0; f < e; f++) { - if (d[f] < c[f]) { - return -1; - } - if (d[f] > c[f]) { - return 1; - } - } - return d.length == c.length ? 0 : d.length < c.length ? -1 : 1; - }, - __calculate_ratio: function (b, a) { - return a ? (2 * b) / a : 1; - }, - __isindict: function (a) { - return function (b) { - return b in a; - }; - }, - __dictget: function (c, b, a) { - return b in c ? c[b] : a; - }, - SequenceMatcher: function (e, c, d) { - this.set_seqs = function (g, f) { - this.set_seq1(g); - this.set_seq2(f); - }; - this.set_seq1 = function (b) { - if (b == this.a) { - return; - } - this.a = b; - this.matching_blocks = this.opcodes = null; - }; - this.set_seq2 = function (a) { - if (a == this.b) { - return; - } - this.b = a; - this.matching_blocks = this.opcodes = this.fullbcount = null; - this.__chain_b(); - }; - this.__chain_b = function () { - var o = this.b; - var g = o.length; - var h = (this.b2j = {}); - var j = {}; - for (var m = 0; m < o.length; m++) { - var l = o[m]; - if (l in h) { - var p = h[l]; - if (g >= 200 && p.length * 100 > g) { - j[l] = 1; - delete h[l]; - } else { - p.push(m); - } - } else { - h[l] = [m]; - } - } - for (var l in j) { - delete h[l]; - } - var f = this.isjunk; - var a = {}; - if (f) { - for (var l in j) { - if (f(l)) { - a[l] = 1; - delete j[l]; - } - } - for (var l in h) { - if (f(l)) { - a[l] = 1; - delete h[l]; - } - } - } - this.isbjunk = difflib.__isindict(a); - this.isbpopular = difflib.__isindict(j); - }; - this.find_longest_match = function (g, w, q, n) { - var y = this.a; - var x = this.b; - var z = this.b2j; - var f = this.isbjunk; - var o = g; - var m = q; - var l = 0; - var t = null; - var s = {}; - var p = []; - for (var u = g; u < w; u++) { - var h = {}; - var r = difflib.__dictget(z, y[u], p); - for (var v in r) { - t = r[v]; - if (t < q) { - continue; - } - if (t >= n) { - break; - } - h[t] = k = difflib.__dictget(s, t - 1, 0) + 1; - if (k > l) { - o = u - k + 1; - m = t - k + 1; - l = k; - } - } - s = h; - } - while (o > g && m > q && !f(x[m - 1]) && y[o - 1] == x[m - 1]) { - o--; - m--; - l++; - } - while (o + l < w && m + l < n && !f(x[m + l]) && y[o + l] == x[m + l]) { - l++; - } - while (o > g && m > q && f(x[m - 1]) && y[o - 1] == x[m - 1]) { - o--; - m--; - l++; - } - while (o + l < w && m + l < n && f(x[m + l]) && y[o + l] == x[m + l]) { - l++; - } - return [o, m, l]; - }; - this.get_matching_blocks = function () { - if (this.matching_blocks != null) { - return this.matching_blocks; - } - var f = this.a.length; - var b = this.b.length; - var q = [[0, f, 0, b]]; - var l = []; - var s, m, v, r, a, p, n, h, t; - while (q.length) { - a = q.pop(); - s = a[0]; - m = a[1]; - v = a[2]; - r = a[3]; - t = this.find_longest_match(s, m, v, r); - p = t[0]; - n = t[1]; - h = t[2]; - if (h) { - l.push(t); - if (s < p && v < n) { - q.push([s, p, v, n]); - } - if (p + h < m && n + h < r) { - q.push([p + h, m, n + h, r]); - } - } - } - l.sort(difflib.__ntuplecomp); - var g = (j1 = k1 = block = 0); - var o = []; - for (var u in l) { - block = l[u]; - i2 = block[0]; - j2 = block[1]; - k2 = block[2]; - if (g + k1 == i2 && j1 + k1 == j2) { - k1 += k2; - } else { - if (k1) { - o.push([g, j1, k1]); - } - g = i2; - j1 = j2; - k1 = k2; - } - } - if (k1) { - o.push([g, j1, k1]); - } - o.push([f, b, 0]); - this.matching_blocks = o; - return this.matching_blocks; - }; - this.get_opcodes = function () { - if (this.opcodes != null) { - return this.opcodes; - } - var h = 0; - var g = 0; - var n = []; - this.opcodes = n; - var f, l, b, o, p; - var a = this.get_matching_blocks(); - for (var m in a) { - f = a[m]; - l = f[0]; - b = f[1]; - o = f[2]; - p = ''; - if (h < l && g < b) { - p = 'replace'; - } else { - if (h < l) { - p = 'delete'; - } else { - if (g < b) { - p = 'insert'; - } - } - } - if (p) { - n.push([p, h, l, g, b]); - } - h = l + o; - g = b + o; - if (o) { - n.push(['equal', l, h, b, g]); - } - } - return n; - }; - this.get_grouped_opcodes = function (g) { - if (!g) { - g = 3; - } - var a = this.get_opcodes(); - if (!a) { - a = [['equal', 0, 1, 0, 1]]; - } - var b, p, i, h, o, m; - if (a[0][0] == 'equal') { - b = a[0]; - p = b[0]; - i = b[1]; - h = b[2]; - o = b[3]; - m = b[4]; - a[0] = [p, Math.max(i, h - g), h, Math.max(o, m - g), m]; - } - if (a[a.length - 1][0] == 'equal') { - b = a[a.length - 1]; - p = b[0]; - i = b[1]; - h = b[2]; - o = b[3]; - m = b[4]; - a[a.length - 1] = [p, i, Math.min(h, i + g), o, Math.min(m, o + g)]; - } - var l = g + g; - var f = []; - for (var j in a) { - b = a[j]; - p = b[0]; - i = b[1]; - h = b[2]; - o = b[3]; - m = b[4]; - if (p == 'equal' && h - i > l) { - f.push([p, i, Math.min(h, i + g), o, Math.min(m, o + g)]); - i = Math.max(i, h - g); - o = Math.max(o, m - g); - } - f.push([p, i, h, o, m]); - } - if (f && f[f.length - 1][0] == 'equal') { - f.pop(); - } - return f; - }; - this.ratio = function () { - matches = difflib.__reduce( - function (a, b) { - return a + b[b.length - 1]; - }, - this.get_matching_blocks(), - 0 - ); - return difflib.__calculate_ratio(matches, this.a.length + this.b.length); - }; - this.quick_ratio = function () { - var a, b; - if (this.fullbcount == null) { - this.fullbcount = a = {}; - for (var g = 0; g < this.b.length; g++) { - b = this.b[g]; - a[b] = difflib.__dictget(a, b, 0) + 1; - } - } - a = this.fullbcount; - var j = {}; - var f = difflib.__isindict(j); - var h = (numb = 0); - for (var g = 0; g < this.a.length; g++) { - b = this.a[g]; - if (f(b)) { - numb = j[b]; - } else { - numb = difflib.__dictget(a, b, 0); - } - j[b] = numb - 1; - if (numb > 0) { - h++; - } - } - return difflib.__calculate_ratio(h, this.a.length + this.b.length); - }; - this.real_quick_ratio = function () { - var b = this.a.length; - var a = this.b.length; - return _calculate_ratio(Math.min(b, a), b + a); - }; - this.isjunk = d ? d : difflib.defaultJunkFunction; - this.a = this.b = null; - this.set_seqs(e, c); - }, -}; -diffview = { - buildView: function (C) { - var u = C.baseTextLines; - var e = C.newTextLines; - var o = C.opcodes; - var h = C.baseTextName ? C.baseTextName : 'Base Text'; - var v = C.newTextName ? C.newTextName : 'New Text'; - var q = C.contextSize; - var d = C.viewType == 0 || C.viewType == 1 ? C.viewType : 0; - if (u == null) { - throw 'Cannot build diff view; baseTextLines is not defined.'; - } - if (e == null) { - throw 'Cannot build diff view; newTextLines is not defined.'; - } - if (!o) { - throw 'Canno build diff view; opcodes is not defined.'; - } - function E(i, b) { - var n = document.createElement(i); - n.className = b; - return n; - } - function p(b, n) { - var i = document.createElement(b); - i.appendChild(document.createTextNode(n)); - return i; - } - function r(i, b, H) { - var n = document.createElement(i); - n.className = b; - n.innerHTML = H; - return n; - } - var s = document.createElement('thead'); - var y = document.createElement('tr'); - s.appendChild(y); - if (d) { - y.appendChild(document.createElement('th')); - y.appendChild(document.createElement('th')); - y.appendChild(r('th', 'texttitle', h + ' vs. ' + v)); - } else { - y.appendChild(document.createElement('th')); - y.appendChild(r('th', 'texttitle', h)); - y.appendChild(document.createElement('th')); - y.appendChild(r('th', 'texttitle', v)); - } - s = [s]; - var m = []; - var a; - function c(H, b, n, i, I) { - if (b < n) { - H.appendChild(p('th', (b + 1).toString())); - H.appendChild(r('td', I, i[b].replace(/\t/g, '\u00a0\u00a0\u00a0\u00a0'))); - return b + 1; - } else { - H.appendChild(document.createElement('th')); - H.appendChild(E('td', 'empty')); - return b; - } - } - function B(H, b, n, i, I) { - H.appendChild(p('th', b == null ? '' : (b + 1).toString())); - H.appendChild(p('th', n == null ? '' : (n + 1).toString())); - H.appendChild(r('td', I, i[b != null ? b : n].replace(/\t/g, '\u00a0\u00a0\u00a0\u00a0'))); - } - for (var t = 0; t < o.length; t++) { - code = o[t]; - change = code[0]; - var D = code[1]; - var f = code[2]; - var w = code[3]; - var l = code[4]; - var G = Math.max(f - D, l - w); - var x = []; - var A = []; - for (var z = 0; z < G; z++) { - if (q && o.length > 1 && ((t > 0 && z == q) || (t == 0 && z == 0)) && change == 'equal') { - var g = G - (t == 0 ? 1 : 2) * q; - if (g > 1) { - x.push((y = document.createElement('tr'))); - D += g; - w += g; - z += g - 1; - y.appendChild(p('th', '...')); - if (!d) { - y.appendChild(r('td', 'skip', '')); - } - y.appendChild(p('th', '...')); - y.appendChild(r('td', 'skip', '')); - if (t + 1 == o.length) { - break; - } else { - continue; - } - } - } - x.push((y = document.createElement('tr'))); - if (d) { - if (change == 'insert') { - B(y, null, w++, e, change); - } else { - if (change == 'replace') { - A.push((a = document.createElement('tr'))); - if (D < f) { - B(y, D++, null, u, 'delete'); - } - if (w < l) { - B(a, null, w++, e, 'insert'); - } - } else { - if (change == 'delete') { - B(y, D++, null, u, change); - } else { - B(y, D++, w++, u, change); - } - } - } - } else { - var F = diffString2(D < f ? u[D] : '', w < l ? e[w] : ''); - if (D < f) { - u[D] = F.o; - } - if (w < l) { - e[w] = F.n; - } - D = c(y, D, f, u, change == 'replace' ? 'delete' : change); - w = c(y, w, l, e, change == 'replace' ? 'insert' : change); - } - } - for (var z = 0; z < x.length; z++) { - m.push(x[z]); - } - for (var z = 0; z < A.length; z++) { - m.push(A[z]); - } - } - var j = "combined jsdifflib "; - j += "and John Resig's diff "; - j += "by Richard Bondi"; - m.push((y = r('th', 'author', j))); - y.setAttribute('colspan', d ? 3 : 4); - s.push((y = document.createElement('tbody'))); - for (var t in m) { - m.hasOwnProperty(t) && y.appendChild(m[t]); - } - y = E('table', 'diff' + (d ? ' inlinediff' : '')); - for (var t in s) { - s.hasOwnProperty(t) && y.appendChild(s[t]); - } - return y; - }, -}; -function escape_jsdiff(a) { - var b = a; - b = b.replace(/&/g, '&'); - b = b.replace(//g, '>'); - b = b.replace(/"/g, '"'); - return b; -} -function diffString(g, h) { - g = g.replace(/\s+$/, ''); - h = h.replace(/\s+$/, ''); - var b = diff(g == '' ? [] : g.split(/\s+/), h == '' ? [] : h.split(/\s+/)); - var f = ''; - var a = g.match(/\s+/g); - if (a == null) { - a = ['\n']; - } else { - a.push('\n'); - } - var d = h.match(/\s+/g); - if (d == null) { - d = ['\n']; - } else { - d.push('\n'); - } - if (b.n.length == 0) { - for (var c = 0; c < b.o.length; c++) { - f += '' + escape_jsdiff(b.o[c]) + a[c] + ''; - } - } else { - if (b.n[0].text == null) { - for (h = 0; h < b.o.length && b.o[h].text == null; h++) { - f += '' + escape_jsdiff(b.o[h]) + a[h] + ''; - } - } - for (var c = 0; c < b.n.length; c++) { - if (b.n[c].text == null) { - f += '' + escape_jsdiff(b.n[c]) + d[c] + ''; - } else { - var e = ''; - for (h = b.n[c].row + 1; h < b.o.length && b.o[h].text == null; h++) { - e += '' + escape_jsdiff(b.o[h]) + a[h] + ''; - } - f += ' ' + b.n[c].text + d[c] + e; - } - } - } - return f; -} -function randomColor() { - return 'rgb(' + Math.random() * 100 + '%, ' + Math.random() * 100 + '%, ' + Math.random() * 100 + '%)'; -} -function diffString2(b, c) { - b = b.replace(/\s+$/, ''); - c = c.replace(/\s+$/, ''); - var e = diff(b == '' ? [] : b.split(/\s+/), c == '' ? [] : c.split(/\s+/)); - var j = b.match(/\s+/g); - if (j == null) { - j = ['\n']; - } else { - j.push('\n'); - } - var g = c.match(/\s+/g); - if (g == null) { - g = ['\n']; - } else { - g.push('\n'); - } - var d = ''; - var a = new Array(); - for (var f = 0; f < e.o.length; f++) { - a[f] = randomColor(); - if (e.o[f].text != null) { - d += escape_jsdiff(e.o[f].text) + j[f]; - } else { - d += '' + escape_jsdiff(e.o[f]) + j[f] + ''; - } - } - var h = ''; - for (var f = 0; f < e.n.length; f++) { - if (e.n[f].text != null) { - h += escape_jsdiff(e.n[f].text) + g[f]; - } else { - h += '' + escape_jsdiff(e.n[f]) + g[f] + ''; - } - } - return { o: d, n: h }; -} -function diff(d, e) { - var b = new Object(); - var c = new Object(); - for (var a = 0; a < e.length; a++) { - if (b[e[a]] == null) { - b[e[a]] = { rows: new Array(), o: null }; - } - b[e[a]].rows.push(a); - } - for (var a = 0; a < d.length; a++) { - if (c[d[a]] == null) { - c[d[a]] = { rows: new Array(), n: null }; - } - c[d[a]].rows.push(a); - } - for (var a in b) { - if (b[a].rows.length == 1 && typeof c[a] != 'undefined' && c[a].rows.length == 1) { - e[b[a].rows[0]] = { text: e[b[a].rows[0]], row: c[a].rows[0] }; - d[c[a].rows[0]] = { text: d[c[a].rows[0]], row: b[a].rows[0] }; - } - } - for (var a = 0; a < e.length - 1; a++) { - if ( - e[a].text != null && - e[a + 1].text == null && - e[a].row + 1 < d.length && - d[e[a].row + 1].text == null && - e[a + 1] == d[e[a].row + 1] - ) { - e[a + 1] = { text: e[a + 1], row: e[a].row + 1 }; - d[e[a].row + 1] = { text: d[e[a].row + 1], row: a + 1 }; - } - } - for (var a = e.length - 1; a > 0; a--) { - if ( - e[a].text != null && - e[a - 1].text == null && - e[a].row > 0 && - d[e[a].row - 1].text == null && - e[a - 1] == d[e[a].row - 1] - ) { - e[a - 1] = { text: e[a - 1], row: e[a].row - 1 }; - d[e[a].row - 1] = { text: d[e[a].row - 1], row: a - 1 }; - } - } - return { o: d, n: e }; -} -(function (b, a) { - typeof exports === 'object' && typeof module !== 'undefined' - ? (module.exports = a()) - : typeof define === 'function' && define.amd - ? define(a) - : (b.moment = a()); -})(this, function () { - var cT; - function gm() { - return cT.apply(null, arguments); - } - function bi(g5) { - cT = g5; - } - function ag(g5) { - return g5 instanceof Array || Object.prototype.toString.call(g5) === '[object Array]'; - } - function E(g5) { - return g5 != null && Object.prototype.toString.call(g5) === '[object Object]'; - } - function c6(g6) { - var g5; - for (g5 in g6) { - return false; - } - return true; - } - function P(g5) { - return g5 === void 0; - } - function z(g5) { - return typeof g5 === 'number' || Object.prototype.toString.call(g5) === '[object Number]'; - } - function gc(g5) { - return g5 instanceof Date || Object.prototype.toString.call(g5) === '[object Date]'; - } - function bT(g5, g8) { - var g7 = [], - g6; - for (g6 = 0; g6 < g5.length; ++g6) { - g7.push(g8(g5[g6], g6)); - } - return g7; - } - function eJ(g6, g5) { - return Object.prototype.hasOwnProperty.call(g6, g5); - } - function gO(g6, g5) { - for (var g7 in g5) { - if (eJ(g5, g7)) { - g6[g7] = g5[g7]; - } - } - if (eJ(g5, 'toString')) { - g6.toString = g5.toString; - } - if (eJ(g5, 'valueOf')) { - g6.valueOf = g5.valueOf; - } - return g6; - } - function du(g7, g8, g5, g6) { - return au(g7, g8, g5, g6, true).utc(); - } - function dn() { - return { - empty: false, - unusedTokens: [], - unusedInput: [], - overflow: -2, - charsLeftOver: 0, - nullInput: false, - invalidMonth: null, - invalidFormat: false, - userInvalidated: false, - iso: false, - parsedDateParts: [], - meridiem: null, - rfc2822: false, - weekdayMismatch: false, - }; - } - function bE(g5) { - if (g5._pf == null) { - g5._pf = dn(); - } - return g5._pf; - } - var eN; - if (Array.prototype.some) { - eN = Array.prototype.some; - } else { - eN = function (g6) { - var g8 = Object(this); - var g5 = g8.length >>> 0; - for (var g7 = 0; g7 < g5; g7++) { - if (g7 in g8 && g6.call(this, g8[g7], g7, g8)) { - return true; - } - } - return false; - }; - } - var dN = eN; - function aM(g6) { - if (g6._isValid == null) { - var g7 = bE(g6); - var g8 = dN.call(g7.parsedDateParts, function (g9) { - return g9 != null; - }); - var g5 = - !isNaN(g6._d.getTime()) && - g7.overflow < 0 && - !g7.empty && - !g7.invalidMonth && - !g7.invalidWeekday && - !g7.nullInput && - !g7.invalidFormat && - !g7.userInvalidated && - (!g7.meridiem || (g7.meridiem && g8)); - if (g6._strict) { - g5 = g5 && g7.charsLeftOver === 0 && g7.unusedTokens.length === 0 && g7.bigHour === undefined; - } - if (Object.isFrozen == null || !Object.isFrozen(g6)) { - g6._isValid = g5; - } else { - return g5; - } - } - return g6._isValid; - } - function X(g6) { - var g5 = du(NaN); - if (g6 != null) { - gO(bE(g5), g6); - } else { - bE(g5).userInvalidated = true; - } - return g5; - } - var d2 = (gm.momentProperties = []); - function y(g9, g8) { - var g5, g7, g6; - if (!P(g8._isAMomentObject)) { - g9._isAMomentObject = g8._isAMomentObject; - } - if (!P(g8._i)) { - g9._i = g8._i; - } - if (!P(g8._f)) { - g9._f = g8._f; - } - if (!P(g8._l)) { - g9._l = g8._l; - } - if (!P(g8._strict)) { - g9._strict = g8._strict; - } - if (!P(g8._tzm)) { - g9._tzm = g8._tzm; - } - if (!P(g8._isUTC)) { - g9._isUTC = g8._isUTC; - } - if (!P(g8._offset)) { - g9._offset = g8._offset; - } - if (!P(g8._pf)) { - g9._pf = bE(g8); - } - if (!P(g8._locale)) { - g9._locale = g8._locale; - } - if (d2.length > 0) { - for (g5 = 0; g5 < d2.length; g5++) { - g7 = d2[g5]; - g6 = g8[g7]; - if (!P(g6)) { - g9[g7] = g6; - } - } - } - return g9; - } - var eC = false; - function f7(g5) { - y(this, g5); - this._d = new Date(g5._d != null ? g5._d.getTime() : NaN); - if (!this.isValid()) { - this._d = new Date(NaN); - } - if (eC === false) { - eC = true; - gm.updateOffset(this); - eC = false; - } - } - function cU(g5) { - return g5 instanceof f7 || (g5 != null && g5._isAMomentObject != null); - } - function eG(g5) { - if (g5 < 0) { - return Math.ceil(g5) || 0; - } else { - return Math.floor(g5); - } - } - function dZ(g5) { - var g7 = +g5, - g6 = 0; - if (g7 !== 0 && isFinite(g7)) { - g6 = eG(g7); - } - return g6; - } - function cy(ha, g9, g6) { - var g5 = Math.min(ha.length, g9.length), - g7 = Math.abs(ha.length - g9.length), - hb = 0, - g8; - for (g8 = 0; g8 < g5; g8++) { - if ((g6 && ha[g8] !== g9[g8]) || (!g6 && dZ(ha[g8]) !== dZ(g9[g8]))) { - hb++; - } - } - return hb + g7; - } - function et(g5) { - if (gm.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { - console.warn('Deprecation warning: ' + g5); - } - } - function fK(g6, g5) { - var g7 = true; - return gO(function () { - if (gm.deprecationHandler != null) { - gm.deprecationHandler(null, g6); - } - if (g7) { - var g9 = []; - var g8; - for (var hb = 0; hb < arguments.length; hb++) { - g8 = ''; - if (typeof arguments[hb] === 'object') { - g8 += '\n[' + hb + '] '; - for (var ha in arguments[0]) { - g8 += ha + ': ' + arguments[0][ha] + ', '; - } - g8 = g8.slice(0, -2); - } else { - g8 = arguments[hb]; - } - g9.push(g8); - } - et(g6 + '\nArguments: ' + Array.prototype.slice.call(g9).join('') + '\n' + new Error().stack); - g7 = false; - } - return g5.apply(this, arguments); - }, g5); - } - var an = {}; - function gD(g5, g6) { - if (gm.deprecationHandler != null) { - gm.deprecationHandler(g5, g6); - } - if (!an[g5]) { - et(g6); - an[g5] = true; - } - } - gm.suppressDeprecationWarnings = false; - gm.deprecationHandler = null; - function bz(g5) { - return g5 instanceof Function || Object.prototype.toString.call(g5) === '[object Function]'; - } - function eL(g5) { - var g7, g6; - for (g6 in g5) { - g7 = g5[g6]; - if (bz(g7)) { - this[g6] = g7; - } else { - this['_' + g6] = g7; - } - } - this._config = g5; - this._dayOfMonthOrdinalParseLenient = new RegExp( - (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source - ); - } - function fA(g7, g5) { - var g6 = gO({}, g7), - g8; - for (g8 in g5) { - if (eJ(g5, g8)) { - if (E(g7[g8]) && E(g5[g8])) { - g6[g8] = {}; - gO(g6[g8], g7[g8]); - gO(g6[g8], g5[g8]); - } else { - if (g5[g8] != null) { - g6[g8] = g5[g8]; - } else { - delete g6[g8]; - } - } - } - } - for (g8 in g7) { - if (eJ(g7, g8) && !eJ(g5, g8) && E(g7[g8])) { - g6[g8] = gO({}, g6[g8]); - } - } - return g6; - } - function dE(g5) { - if (g5 != null) { - this.set(g5); - } - } - var cu; - if (Object.keys) { - cu = Object.keys; - } else { - cu = function (g7) { - var g6, - g5 = []; - for (g6 in g7) { - if (eJ(g7, g6)) { - g5.push(g6); - } - } - return g5; - }; - } - var fe = cu; - var de = { - sameDay: '[Today at] LT', - nextDay: '[Tomorrow at] LT', - nextWeek: 'dddd [at] LT', - lastDay: '[Yesterday at] LT', - lastWeek: '[Last] dddd [at] LT', - sameElse: 'L', - }; - function d(g7, g8, g6) { - var g5 = this._calendar[g7] || this._calendar.sameElse; - return bz(g5) ? g5.call(g8, g6) : g5; - } - var fp = { - LTS: 'h:mm:ss A', - LT: 'h:mm A', - L: 'MM/DD/YYYY', - LL: 'MMMM D, YYYY', - LLL: 'MMMM D, YYYY h:mm A', - LLLL: 'dddd, MMMM D, YYYY h:mm A', - }; - function dR(g5) { - var g6 = this._longDateFormat[g5], - g7 = this._longDateFormat[g5.toUpperCase()]; - if (g6 || !g7) { - return g6; - } - this._longDateFormat[g5] = g7.replace(/MMMM|MM|DD|dddd/g, function (g8) { - return g8.slice(1); - }); - return this._longDateFormat[g5]; - } - var aK = 'Invalid date'; - function f5() { - return this._invalidDate; - } - var cO = '%d'; - var g0 = /\d{1,2}/; - function gj(g5) { - return this._ordinal.replace('%d', g5); - } - var gi = { - future: 'in %s', - past: '%s ago', - s: 'a few seconds', - ss: '%d seconds', - m: 'a minute', - mm: '%d minutes', - h: 'an hour', - hh: '%d hours', - d: 'a day', - dd: '%d days', - M: 'a month', - MM: '%d months', - y: 'a year', - yy: '%d years', - }; - function ae(g8, g7, g6, g9) { - var g5 = this._relativeTime[g6]; - return bz(g5) ? g5(g8, g7, g6, g9) : g5.replace(/%d/i, g8); - } - function fq(g7, g5) { - var g6 = this._relativeTime[g7 > 0 ? 'future' : 'past']; - return bz(g6) ? g6(g5) : g6.replace(/%s/i, g5); - } - var dT = {}; - function c0(g7, g5) { - var g6 = g7.toLowerCase(); - dT[g6] = dT[g6 + 's'] = dT[g5] = g7; - } - function dY(g5) { - return typeof g5 === 'string' ? dT[g5] || dT[g5.toLowerCase()] : undefined; - } - function fb(g7) { - var g6 = {}, - g5, - g8; - for (g8 in g7) { - if (eJ(g7, g8)) { - g5 = dY(g8); - if (g5) { - g6[g5] = g7[g8]; - } - } - } - return g6; - } - var bY = {}; - function fo(g6, g5) { - bY[g6] = g5; - } - function bV(g5) { - var g6 = []; - for (var g7 in g5) { - g6.push({ unit: g7, priority: bY[g7] }); - } - g6.sort(function (g9, g8) { - return g9.priority - g8.priority; - }); - return g6; - } - function fH(g5, g6) { - return function (g7) { - if (g7 != null) { - bc(this, g5, g7); - gm.updateOffset(this, g6); - return this; - } else { - return eY(this, g5); - } - }; - } - function eY(g6, g5) { - return g6.isValid() ? g6._d['get' + (g6._isUTC ? 'UTC' : '') + g5]() : NaN; - } - function bc(g6, g5, g7) { - if (g6.isValid()) { - g6._d['set' + (g6._isUTC ? 'UTC' : '') + g5](g7); - } - } - function a0(g5) { - g5 = dY(g5); - if (bz(this[g5])) { - return this[g5](); - } - return this; - } - function aR(g5, g8) { - if (typeof g5 === 'object') { - g5 = fb(g5); - var g7 = bV(g5); - for (var g6 = 0; g6 < g7.length; g6++) { - this[g7[g6].unit](g5[g7[g6].unit]); - } - } else { - g5 = dY(g5); - if (bz(this[g5])) { - return this[g5](g8); - } - } - return this; - } - function dk(ha, g9, g6) { - var g8 = '' + Math.abs(ha), - g7 = g9 - g8.length, - g5 = ha >= 0; - return (g5 ? (g6 ? '+' : '') : '-') + Math.pow(10, Math.max(0, g7)).toString().substr(1) + g8; - } - var co = - /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; - var cn = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; - var cm = {}; - var bC = {}; - function dy(g6, g7, g5, g9) { - var g8 = g9; - if (typeof g9 === 'string') { - g8 = function () { - return this[g9](); - }; - } - if (g6) { - bC[g6] = g8; - } - if (g7) { - bC[g7[0]] = function () { - return dk(g8.apply(this, arguments), g7[1], g7[2]); - }; - } - if (g5) { - bC[g5] = function () { - return this.localeData().ordinal(g8.apply(this, arguments), g6); - }; - } - } - function aT(g5) { - if (g5.match(/\[[\s\S]/)) { - return g5.replace(/^\[|\]$/g, ''); - } - return g5.replace(/\\/g, ''); - } - function b2(g7) { - var g8 = g7.match(co), - g5, - g6; - for (g5 = 0, g6 = g8.length; g5 < g6; g5++) { - if (bC[g8[g5]]) { - g8[g5] = bC[g8[g5]]; - } else { - g8[g5] = aT(g8[g5]); - } - } - return function (hb) { - var g9 = '', - ha; - for (ha = 0; ha < g6; ha++) { - g9 += bz(g8[ha]) ? g8[ha].call(hb, g7) : g8[ha]; - } - return g9; - }; - } - function aA(g5, g6) { - if (!g5.isValid()) { - return g5.localeData().invalidDate(); - } - g6 = cc(g6, g5.localeData()); - cm[g6] = cm[g6] || b2(g6); - return cm[g6](g5); - } - function cc(g8, g5) { - var g6 = 5; - function g7(g9) { - return g5.longDateFormat(g9) || g9; - } - cn.lastIndex = 0; - while (g6 >= 0 && cn.test(g8)) { - g8 = g8.replace(cn, g7); - cn.lastIndex = 0; - g6 -= 1; - } - return g8; - } - var bb = /\d/; - var ba = /\d\d/; - var a9 = /\d{3}/; - var a8 = /\d{4}/; - var a7 = /[+-]?\d{6}/; - var aP = /\d\d?/; - var dh = /\d\d\d\d?/; - var fJ = /\d\d\d\d\d\d?/; - var aO = /\d{1,3}/; - var aN = /\d{1,4}/; - var aL = /[+-]?\d{1,6}/; - var A = /\d+/; - var L = /[+-]?\d+/; - var cf = /Z|[+-]\d\d:?\d\d/gi; - var dK = /Z|[+-]\d\d(?::?\d\d)?/gi; - var gE = /[+-]?\d+(\.\d{1,3})?/; - var bB = - /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; - var bv = {}; - function bG(g5, g6, g7) { - bv[g5] = bz(g6) - ? g6 - : function (g9, g8) { - return g9 && g7 ? g7 : g6; - }; - } - function b9(g6, g5) { - if (!eJ(bv, g6)) { - return new RegExp(eH(g6)); - } - return bv[g6](g5._strict, g5._locale); - } - function eH(g5) { - return c3( - g5.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (g6, ha, g9, g8, g7) { - return ha || g9 || g8 || g7; - }) - ); - } - function c3(g5) { - return g5.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); - } - var i = {}; - function cs(g6, g8) { - var g5, - g7 = g8; - if (typeof g6 === 'string') { - g6 = [g6]; - } - if (z(g8)) { - g7 = function (g9, ha) { - ha[g8] = dZ(g9); - }; - } - for (g5 = 0; g5 < g6.length; g5++) { - i[g6[g5]] = g7; - } - } - function aj(g5, g6) { - cs(g5, function (g7, ha, g8, g9) { - g8._w = g8._w || {}; - g6(g7, g8._w, g8, g9); - }); - } - function D(g7, g5, g6) { - if (g5 != null && eJ(i, g7)) { - i[g7](g5, g6._a, g6, g7); - } - } - var gF = 0; - var o = 1; - var ga = 2; - var gr = 3; - var e6 = 4; - var aH = 5; - var ch = 6; - var da = 7; - var l = 8; - var d0; - if (Array.prototype.indexOf) { - d0 = Array.prototype.indexOf; - } else { - d0 = function (g6) { - var g5; - for (g5 = 0; g5 < this.length; ++g5) { - if (this[g5] === g6) { - return g5; - } - } - return -1; - }; - } - var el = d0; - function ce(g5, g6) { - return new Date(Date.UTC(g5, g6 + 1, 0)).getUTCDate(); - } - dy('M', ['MM', 2], 'Mo', function () { - return this.month() + 1; - }); - dy('MMM', 0, 0, function (g5) { - return this.localeData().monthsShort(this, g5); - }); - dy('MMMM', 0, 0, function (g5) { - return this.localeData().months(this, g5); - }); - c0('month', 'M'); - fo('month', 8); - bG('M', aP); - bG('MM', aP, ba); - bG('MMM', function (g6, g5) { - return g5.monthsShortRegex(g6); - }); - bG('MMMM', function (g6, g5) { - return g5.monthsRegex(g6); - }); - cs(['M', 'MM'], function (g5, g6) { - g6[o] = dZ(g5) - 1; - }); - cs(['MMM', 'MMMM'], function (g5, g9, g6, g7) { - var g8 = g6._locale.monthsParse(g5, g7, g6._strict); - if (g8 != null) { - g9[o] = g8; - } else { - bE(g6).invalidMonth = g5; - } - }); - var cL = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; - var Z = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); - function bt(g5, g6) { - if (!g5) { - return ag(this._months) ? this._months : this._months.standalone; - } - return ag(this._months) - ? this._months[g5.month()] - : this._months[(this._months.isFormat || cL).test(g6) ? 'format' : 'standalone'][g5.month()]; - } - var ft = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); - function bD(g5, g6) { - if (!g5) { - return ag(this._monthsShort) ? this._monthsShort : this._monthsShort.standalone; - } - return ag(this._monthsShort) - ? this._monthsShort[g5.month()] - : this._monthsShort[cL.test(g6) ? 'format' : 'standalone'][g5.month()]; - } - function b7(g6, hb, g5) { - var g8, - g9, - ha, - g7 = g6.toLocaleLowerCase(); - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - for (g8 = 0; g8 < 12; ++g8) { - ha = du([2000, g8]); - this._shortMonthsParse[g8] = this.monthsShort(ha, '').toLocaleLowerCase(); - this._longMonthsParse[g8] = this.months(ha, '').toLocaleLowerCase(); - } - } - if (g5) { - if (hb === 'MMM') { - g9 = el.call(this._shortMonthsParse, g7); - return g9 !== -1 ? g9 : null; - } else { - g9 = el.call(this._longMonthsParse, g7); - return g9 !== -1 ? g9 : null; - } - } else { - if (hb === 'MMM') { - g9 = el.call(this._shortMonthsParse, g7); - if (g9 !== -1) { - return g9; - } - g9 = el.call(this._longMonthsParse, g7); - return g9 !== -1 ? g9 : null; - } else { - g9 = el.call(this._longMonthsParse, g7); - if (g9 !== -1) { - return g9; - } - g9 = el.call(this._shortMonthsParse, g7); - return g9 !== -1 ? g9 : null; - } - } - } - function ep(g6, ha, g5) { - var g7, g9, g8; - if (this._monthsParseExact) { - return b7.call(this, g6, ha, g5); - } - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - } - for (g7 = 0; g7 < 12; g7++) { - g9 = du([2000, g7]); - if (g5 && !this._longMonthsParse[g7]) { - this._longMonthsParse[g7] = new RegExp('^' + this.months(g9, '').replace('.', '') + '$', 'i'); - this._shortMonthsParse[g7] = new RegExp('^' + this.monthsShort(g9, '').replace('.', '') + '$', 'i'); - } - if (!g5 && !this._monthsParse[g7]) { - g8 = '^' + this.months(g9, '') + '|^' + this.monthsShort(g9, ''); - this._monthsParse[g7] = new RegExp(g8.replace('.', ''), 'i'); - } - if (g5 && ha === 'MMMM' && this._longMonthsParse[g7].test(g6)) { - return g7; - } else { - if (g5 && ha === 'MMM' && this._shortMonthsParse[g7].test(g6)) { - return g7; - } else { - if (!g5 && this._monthsParse[g7].test(g6)) { - return g7; - } - } - } - } - } - function bn(g5, g6) { - var g7; - if (!g5.isValid()) { - return g5; - } - if (typeof g6 === 'string') { - if (/^\d+$/.test(g6)) { - g6 = dZ(g6); - } else { - g6 = g5.localeData().monthsParse(g6); - if (!z(g6)) { - return g5; - } - } - } - g7 = Math.min(g5.date(), ce(g5.year(), g6)); - g5._d['set' + (g5._isUTC ? 'UTC' : '') + 'Month'](g6, g7); - return g5; - } - function gq(g5) { - if (g5 != null) { - bn(this, g5); - gm.updateOffset(this, true); - return this; - } else { - return eY(this, 'Month'); - } - } - function ck() { - return ce(this.year(), this.month()); - } - var eF = bB; - function eI(g5) { - if (this._monthsParseExact) { - if (!eJ(this, '_monthsRegex')) { - eK.call(this); - } - if (g5) { - return this._monthsShortStrictRegex; - } else { - return this._monthsShortRegex; - } - } else { - if (!eJ(this, '_monthsShortRegex')) { - this._monthsShortRegex = eF; - } - return this._monthsShortStrictRegex && g5 ? this._monthsShortStrictRegex : this._monthsShortRegex; - } - } - var gf = bB; - function d8(g5) { - if (this._monthsParseExact) { - if (!eJ(this, '_monthsRegex')) { - eK.call(this); - } - if (g5) { - return this._monthsStrictRegex; - } else { - return this._monthsRegex; - } - } else { - if (!eJ(this, '_monthsRegex')) { - this._monthsRegex = gf; - } - return this._monthsStrictRegex && g5 ? this._monthsStrictRegex : this._monthsRegex; - } - } - function eK() { - function ha(hc, hb) { - return hb.length - hc.length; - } - var g9 = [], - g5 = [], - g8 = [], - g6, - g7; - for (g6 = 0; g6 < 12; g6++) { - g7 = du([2000, g6]); - g9.push(this.monthsShort(g7, '')); - g5.push(this.months(g7, '')); - g8.push(this.months(g7, '')); - g8.push(this.monthsShort(g7, '')); - } - g9.sort(ha); - g5.sort(ha); - g8.sort(ha); - for (g6 = 0; g6 < 12; g6++) { - g9[g6] = c3(g9[g6]); - g5[g6] = c3(g5[g6]); - } - for (g6 = 0; g6 < 24; g6++) { - g8[g6] = c3(g8[g6]); - } - this._monthsRegex = new RegExp('^(' + g8.join('|') + ')', 'i'); - this._monthsShortRegex = this._monthsRegex; - this._monthsStrictRegex = new RegExp('^(' + g5.join('|') + ')', 'i'); - this._monthsShortStrictRegex = new RegExp('^(' + g9.join('|') + ')', 'i'); - } - dy('Y', 0, 0, function () { - var g5 = this.year(); - return g5 <= 9999 ? '' + g5 : '+' + g5; - }); - dy(0, ['YY', 2], 0, function () { - return this.year() % 100; - }); - dy(0, ['YYYY', 4], 0, 'year'); - dy(0, ['YYYYY', 5], 0, 'year'); - dy(0, ['YYYYYY', 6, true], 0, 'year'); - c0('year', 'y'); - fo('year', 1); - bG('Y', L); - bG('YY', aP, ba); - bG('YYYY', aN, a8); - bG('YYYYY', aL, a7); - bG('YYYYYY', aL, a7); - cs(['YYYYY', 'YYYYYY'], gF); - cs('YYYY', function (g5, g6) { - g6[gF] = g5.length === 2 ? gm.parseTwoDigitYear(g5) : dZ(g5); - }); - cs('YY', function (g5, g6) { - g6[gF] = gm.parseTwoDigitYear(g5); - }); - cs('Y', function (g5, g6) { - g6[gF] = parseInt(g5, 10); - }); - function e3(g5) { - return fs(g5) ? 366 : 365; - } - function fs(g5) { - return (g5 % 4 === 0 && g5 % 100 !== 0) || g5 % 400 === 0; - } - gm.parseTwoDigitYear = function (g5) { - return dZ(g5) + (dZ(g5) > 68 ? 1900 : 2000); - }; - var dM = fH('FullYear', true); - function d5() { - return fs(this.year()); - } - function fB(hc, g5, ha, g9, hb, g8, g7) { - var g6 = new Date(hc, g5, ha, g9, hb, g8, g7); - if (hc < 100 && hc >= 0 && isFinite(g6.getFullYear())) { - g6.setFullYear(hc); - } - return g6; - } - function eS(g6) { - var g5 = new Date(Date.UTC.apply(null, arguments)); - if (g6 < 100 && g6 >= 0 && isFinite(g5.getUTCFullYear())) { - g5.setUTCFullYear(g6); - } - return g5; - } - function bM(g6, g9, g8) { - var g5 = 7 + g9 - g8, - g7 = (7 + eS(g6, 0, g5).getUTCDay() - g9) % 7; - return -g7 + g5 - 1; - } - function b5(g8, g6, g7, he, hc) { - var hd = (7 + g7 - he) % 7, - g5 = bM(g8, he, hc), - ha = 1 + 7 * (g6 - 1) + hd + g5, - hb, - g9; - if (ha <= 0) { - hb = g8 - 1; - g9 = e3(hb) + ha; - } else { - if (ha > e3(g8)) { - hb = g8 + 1; - g9 = ha - e3(g8); - } else { - hb = g8; - g9 = ha; - } - } - return { year: hb, dayOfYear: g9 }; - } - function f8(g9, hb, ha) { - var g7 = bM(g9.year(), hb, ha), - g8 = Math.floor((g9.dayOfYear() - g7 - 1) / 7) + 1, - g5, - g6; - if (g8 < 1) { - g6 = g9.year() - 1; - g5 = g8 + O(g6, hb, ha); - } else { - if (g8 > O(g9.year(), hb, ha)) { - g5 = g8 - O(g9.year(), hb, ha); - g6 = g9.year() + 1; - } else { - g6 = g9.year(); - g5 = g8; - } - } - return { week: g5, year: g6 }; - } - function O(g6, g9, g7) { - var g5 = bM(g6, g9, g7), - g8 = bM(g6 + 1, g9, g7); - return (e3(g6) - g5 + g8) / 7; - } - dy('w', ['ww', 2], 'wo', 'week'); - dy('W', ['WW', 2], 'Wo', 'isoWeek'); - c0('week', 'w'); - c0('isoWeek', 'W'); - fo('week', 5); - fo('isoWeek', 5); - bG('w', aP); - bG('ww', aP, ba); - bG('W', aP); - bG('WW', aP, ba); - aj(['w', 'ww', 'W', 'WW'], function (g5, g8, g6, g7) { - g8[g7.substr(0, 1)] = dZ(g5); - }); - function bU(g5) { - return f8(g5, this._week.dow, this._week.doy).week; - } - var cK = { dow: 0, doy: 6 }; - function aE() { - return this._week.dow; - } - function em() { - return this._week.doy; - } - function T(g5) { - var g6 = this.localeData().week(this); - return g5 == null ? g6 : this.add((g5 - g6) * 7, 'd'); - } - function H(g5) { - var g6 = f8(this, 1, 4).week; - return g5 == null ? g6 : this.add((g5 - g6) * 7, 'd'); - } - dy('d', 0, 'do', 'day'); - dy('dd', 0, 0, function (g5) { - return this.localeData().weekdaysMin(this, g5); - }); - dy('ddd', 0, 0, function (g5) { - return this.localeData().weekdaysShort(this, g5); - }); - dy('dddd', 0, 0, function (g5) { - return this.localeData().weekdays(this, g5); - }); - dy('e', 0, 0, 'weekday'); - dy('E', 0, 0, 'isoWeekday'); - c0('day', 'd'); - c0('weekday', 'e'); - c0('isoWeekday', 'E'); - fo('day', 11); - fo('weekday', 11); - fo('isoWeekday', 11); - bG('d', aP); - bG('e', aP); - bG('E', aP); - bG('dd', function (g6, g5) { - return g5.weekdaysMinRegex(g6); - }); - bG('ddd', function (g6, g5) { - return g5.weekdaysShortRegex(g6); - }); - bG('dddd', function (g6, g5) { - return g5.weekdaysRegex(g6); - }); - aj(['dd', 'ddd', 'dddd'], function (g5, g8, g6, g7) { - var g9 = g6._locale.weekdaysParse(g5, g7, g6._strict); - if (g9 != null) { - g8.d = g9; - } else { - bE(g6).invalidWeekday = g5; - } - }); - aj(['d', 'e', 'E'], function (g5, g8, g6, g7) { - g8[g7] = dZ(g5); - }); - function bL(g6, g5) { - if (typeof g6 !== 'string') { - return g6; - } - if (!isNaN(g6)) { - return parseInt(g6, 10); - } - g6 = g5.weekdaysParse(g6); - if (typeof g6 === 'number') { - return g6; - } - return null; - } - function b8(g6, g5) { - if (typeof g6 === 'string') { - return g5.weekdaysParse(g6) % 7 || 7; - } - return isNaN(g6) ? null : g6; - } - var ad = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); - function aU(g5, g6) { - if (!g5) { - return ag(this._weekdays) ? this._weekdays : this._weekdays.standalone; - } - return ag(this._weekdays) - ? this._weekdays[g5.day()] - : this._weekdays[this._weekdays.isFormat.test(g6) ? 'format' : 'standalone'][g5.day()]; - } - var s = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); - function W(g5) { - return g5 ? this._weekdaysShort[g5.day()] : this._weekdaysShort; - } - var bZ = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); - function gn(g5) { - return g5 ? this._weekdaysMin[g5.day()] : this._weekdaysMin; - } - function ff(ha, hb, g5) { - var g7, - g8, - g9, - g6 = ha.toLocaleLowerCase(); - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._shortWeekdaysParse = []; - this._minWeekdaysParse = []; - for (g7 = 0; g7 < 7; ++g7) { - g9 = du([2000, 1]).day(g7); - this._minWeekdaysParse[g7] = this.weekdaysMin(g9, '').toLocaleLowerCase(); - this._shortWeekdaysParse[g7] = this.weekdaysShort(g9, '').toLocaleLowerCase(); - this._weekdaysParse[g7] = this.weekdays(g9, '').toLocaleLowerCase(); - } - } - if (g5) { - if (hb === 'dddd') { - g8 = el.call(this._weekdaysParse, g6); - return g8 !== -1 ? g8 : null; - } else { - if (hb === 'ddd') { - g8 = el.call(this._shortWeekdaysParse, g6); - return g8 !== -1 ? g8 : null; - } else { - g8 = el.call(this._minWeekdaysParse, g6); - return g8 !== -1 ? g8 : null; - } - } - } else { - if (hb === 'dddd') { - g8 = el.call(this._weekdaysParse, g6); - if (g8 !== -1) { - return g8; - } - g8 = el.call(this._shortWeekdaysParse, g6); - if (g8 !== -1) { - return g8; - } - g8 = el.call(this._minWeekdaysParse, g6); - return g8 !== -1 ? g8 : null; - } else { - if (hb === 'ddd') { - g8 = el.call(this._shortWeekdaysParse, g6); - if (g8 !== -1) { - return g8; - } - g8 = el.call(this._weekdaysParse, g6); - if (g8 !== -1) { - return g8; - } - g8 = el.call(this._minWeekdaysParse, g6); - return g8 !== -1 ? g8 : null; - } else { - g8 = el.call(this._minWeekdaysParse, g6); - if (g8 !== -1) { - return g8; - } - g8 = el.call(this._weekdaysParse, g6); - if (g8 !== -1) { - return g8; - } - g8 = el.call(this._shortWeekdaysParse, g6); - return g8 !== -1 ? g8 : null; - } - } - } - } - function cj(g9, ha, g5) { - var g6, g8, g7; - if (this._weekdaysParseExact) { - return ff.call(this, g9, ha, g5); - } - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._minWeekdaysParse = []; - this._shortWeekdaysParse = []; - this._fullWeekdaysParse = []; - } - for (g6 = 0; g6 < 7; g6++) { - g8 = du([2000, 1]).day(g6); - if (g5 && !this._fullWeekdaysParse[g6]) { - this._fullWeekdaysParse[g6] = new RegExp('^' + this.weekdays(g8, '').replace('.', '.?') + '$', 'i'); - this._shortWeekdaysParse[g6] = new RegExp( - '^' + this.weekdaysShort(g8, '').replace('.', '.?') + '$', - 'i' - ); - this._minWeekdaysParse[g6] = new RegExp('^' + this.weekdaysMin(g8, '').replace('.', '.?') + '$', 'i'); - } - if (!this._weekdaysParse[g6]) { - g7 = '^' + this.weekdays(g8, '') + '|^' + this.weekdaysShort(g8, '') + '|^' + this.weekdaysMin(g8, ''); - this._weekdaysParse[g6] = new RegExp(g7.replace('.', ''), 'i'); - } - if (g5 && ha === 'dddd' && this._fullWeekdaysParse[g6].test(g9)) { - return g6; - } else { - if (g5 && ha === 'ddd' && this._shortWeekdaysParse[g6].test(g9)) { - return g6; - } else { - if (g5 && ha === 'dd' && this._minWeekdaysParse[g6].test(g9)) { - return g6; - } else { - if (!g5 && this._weekdaysParse[g6].test(g9)) { - return g6; - } - } - } - } - } - } - function fZ(g6) { - if (!this.isValid()) { - return g6 != null ? this : NaN; - } - var g5 = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); - if (g6 != null) { - g6 = bL(g6, this.localeData()); - return this.add(g6 - g5, 'd'); - } else { - return g5; - } - } - function av(g5) { - if (!this.isValid()) { - return g5 != null ? this : NaN; - } - var g6 = (this.day() + 7 - this.localeData()._week.dow) % 7; - return g5 == null ? g6 : this.add(g5 - g6, 'd'); - } - function ds(g5) { - if (!this.isValid()) { - return g5 != null ? this : NaN; - } - if (g5 != null) { - var g6 = b8(g5, this.localeData()); - return this.day(this.day() % 7 ? g6 : g6 - 7); - } else { - return this.day() || 7; - } - } - var aq = bB; - function gH(g5) { - if (this._weekdaysParseExact) { - if (!eJ(this, '_weekdaysRegex')) { - J.call(this); - } - if (g5) { - return this._weekdaysStrictRegex; - } else { - return this._weekdaysRegex; - } - } else { - if (!eJ(this, '_weekdaysRegex')) { - this._weekdaysRegex = aq; - } - return this._weekdaysStrictRegex && g5 ? this._weekdaysStrictRegex : this._weekdaysRegex; - } - } - var F = bB; - function a6(g5) { - if (this._weekdaysParseExact) { - if (!eJ(this, '_weekdaysRegex')) { - J.call(this); - } - if (g5) { - return this._weekdaysShortStrictRegex; - } else { - return this._weekdaysShortRegex; - } - } else { - if (!eJ(this, '_weekdaysShortRegex')) { - this._weekdaysShortRegex = F; - } - return this._weekdaysShortStrictRegex && g5 ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; - } - } - var fm = bB; - function N(g5) { - if (this._weekdaysParseExact) { - if (!eJ(this, '_weekdaysRegex')) { - J.call(this); - } - if (g5) { - return this._weekdaysMinStrictRegex; - } else { - return this._weekdaysMinRegex; - } - } else { - if (!eJ(this, '_weekdaysMinRegex')) { - this._weekdaysMinRegex = fm; - } - return this._weekdaysMinStrictRegex && g5 ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; - } - } - function J() { - function g8(hg, hf) { - return hf.length - hg.length; - } - var ha = [], - hb = [], - he = [], - g5 = [], - g9, - g7, - g6, - hc, - hd; - for (g9 = 0; g9 < 7; g9++) { - g7 = du([2000, 1]).day(g9); - g6 = this.weekdaysMin(g7, ''); - hc = this.weekdaysShort(g7, ''); - hd = this.weekdays(g7, ''); - ha.push(g6); - hb.push(hc); - he.push(hd); - g5.push(g6); - g5.push(hc); - g5.push(hd); - } - ha.sort(g8); - hb.sort(g8); - he.sort(g8); - g5.sort(g8); - for (g9 = 0; g9 < 7; g9++) { - hb[g9] = c3(hb[g9]); - he[g9] = c3(he[g9]); - g5[g9] = c3(g5[g9]); - } - this._weekdaysRegex = new RegExp('^(' + g5.join('|') + ')', 'i'); - this._weekdaysShortRegex = this._weekdaysRegex; - this._weekdaysMinRegex = this._weekdaysRegex; - this._weekdaysStrictRegex = new RegExp('^(' + he.join('|') + ')', 'i'); - this._weekdaysShortStrictRegex = new RegExp('^(' + hb.join('|') + ')', 'i'); - this._weekdaysMinStrictRegex = new RegExp('^(' + ha.join('|') + ')', 'i'); - } - function eW() { - return this.hours() % 12 || 12; - } - function Y() { - return this.hours() || 24; - } - dy('H', ['HH', 2], 0, 'hour'); - dy('h', ['hh', 2], 0, eW); - dy('k', ['kk', 2], 0, Y); - dy('hmm', 0, 0, function () { - return '' + eW.apply(this) + dk(this.minutes(), 2); - }); - dy('hmmss', 0, 0, function () { - return '' + eW.apply(this) + dk(this.minutes(), 2) + dk(this.seconds(), 2); - }); - dy('Hmm', 0, 0, function () { - return '' + this.hours() + dk(this.minutes(), 2); - }); - dy('Hmmss', 0, 0, function () { - return '' + this.hours() + dk(this.minutes(), 2) + dk(this.seconds(), 2); - }); - function f3(g5, g6) { - dy(g5, 0, 0, function () { - return this.localeData().meridiem(this.hours(), this.minutes(), g6); - }); - } - f3('a', true); - f3('A', false); - c0('hour', 'h'); - fo('hour', 13); - function ac(g6, g5) { - return g5._meridiemParse; - } - bG('a', ac); - bG('A', ac); - bG('H', aP); - bG('h', aP); - bG('k', aP); - bG('HH', aP, ba); - bG('hh', aP, ba); - bG('kk', aP, ba); - bG('hmm', dh); - bG('hmmss', fJ); - bG('Hmm', dh); - bG('Hmmss', fJ); - cs(['H', 'HH'], gr); - cs(['k', 'kk'], function (g6, g8, g7) { - var g5 = dZ(g6); - g8[gr] = g5 === 24 ? 0 : g5; - }); - cs(['a', 'A'], function (g5, g7, g6) { - g6._isPm = g6._locale.isPM(g5); - g6._meridiem = g5; - }); - cs(['h', 'hh'], function (g5, g7, g6) { - g7[gr] = dZ(g5); - bE(g6).bigHour = true; - }); - cs('hmm', function (g5, g8, g6) { - var g7 = g5.length - 2; - g8[gr] = dZ(g5.substr(0, g7)); - g8[e6] = dZ(g5.substr(g7)); - bE(g6).bigHour = true; - }); - cs('hmmss', function (g5, g9, g6) { - var g8 = g5.length - 4; - var g7 = g5.length - 2; - g9[gr] = dZ(g5.substr(0, g8)); - g9[e6] = dZ(g5.substr(g8, 2)); - g9[aH] = dZ(g5.substr(g7)); - bE(g6).bigHour = true; - }); - cs('Hmm', function (g5, g8, g6) { - var g7 = g5.length - 2; - g8[gr] = dZ(g5.substr(0, g7)); - g8[e6] = dZ(g5.substr(g7)); - }); - cs('Hmmss', function (g5, g9, g6) { - var g8 = g5.length - 4; - var g7 = g5.length - 2; - g9[gr] = dZ(g5.substr(0, g8)); - g9[e6] = dZ(g5.substr(g8, 2)); - g9[aH] = dZ(g5.substr(g7)); - }); - function cW(g5) { - return (g5 + '').toLowerCase().charAt(0) === 'p'; - } - var cN = /[ap]\.?m?\.?/i; - function bk(g5, g6, g7) { - if (g5 > 11) { - return g7 ? 'pm' : 'PM'; - } else { - return g7 ? 'am' : 'AM'; - } - } - var dl = fH('Hours', true); - var cH = { - calendar: de, - longDateFormat: fp, - invalidDate: aK, - ordinal: cO, - dayOfMonthOrdinalParse: g0, - relativeTime: gi, - months: Z, - monthsShort: ft, - week: cK, - weekdays: ad, - weekdaysMin: bZ, - weekdaysShort: s, - meridiemParse: cN, - }; - var b3 = {}; - var t = {}; - var d7; - function eM(g5) { - return g5 ? g5.toLowerCase().replace('_', '-') : g5; - } - function d6(ha) { - var g8 = 0, - g6, - g9, - g5, - g7; - while (g8 < ha.length) { - g7 = eM(ha[g8]).split('-'); - g6 = g7.length; - g9 = eM(ha[g8 + 1]); - g9 = g9 ? g9.split('-') : null; - while (g6 > 0) { - g5 = a2(g7.slice(0, g6).join('-')); - if (g5) { - return g5; - } - if (g9 && g9.length >= g6 && cy(g7, g9, true) >= g6 - 1) { - break; - } - g6--; - } - g8++; - } - return null; - } - function a2(g5) { - var g7 = null; - if (!b3[g5] && typeof module !== 'undefined' && module && module.exports) { - try { - g7 = d7._abbr; - require('./locale/' + g5); - K(g7); - } catch (g6) {} - } - return b3[g5]; - } - function K(g6, g5) { - var g7; - if (g6) { - if (P(g5)) { - g7 = aa(g6); - } else { - g7 = dC(g6, g5); - } - if (g7) { - d7 = g7; - } - } - return d7._abbr; - } - function dC(g6, g5) { - if (g5 !== null) { - var g7 = cH; - g5.abbr = g6; - if (b3[g6] != null) { - gD( - 'defineLocaleOverride', - 'use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info.' - ); - g7 = b3[g6]._config; - } else { - if (g5.parentLocale != null) { - if (b3[g5.parentLocale] != null) { - g7 = b3[g5.parentLocale]._config; - } else { - if (!t[g5.parentLocale]) { - t[g5.parentLocale] = []; - } - t[g5.parentLocale].push({ name: g6, config: g5 }); - return null; - } - } - } - b3[g6] = new dE(fA(g7, g5)); - if (t[g6]) { - t[g6].forEach(function (g8) { - dC(g8.name, g8.config); - }); - } - K(g6); - return b3[g6]; - } else { - delete b3[g6]; - return null; - } - } - function f0(g7, g6) { - if (g6 != null) { - var g5, - g8 = cH; - if (b3[g7] != null) { - g8 = b3[g7]._config; - } - g6 = fA(g8, g6); - g5 = new dE(g6); - g5.parentLocale = b3[g7]; - b3[g7] = g5; - K(g7); - } else { - if (b3[g7] != null) { - if (b3[g7].parentLocale != null) { - b3[g7] = b3[g7].parentLocale; - } else { - if (b3[g7] != null) { - delete b3[g7]; - } - } - } - } - return b3[g7]; - } - function aa(g6) { - var g5; - if (g6 && g6._locale && g6._locale._abbr) { - g6 = g6._locale._abbr; - } - if (!g6) { - return d7; - } - if (!ag(g6)) { - g5 = a2(g6); - if (g5) { - return g5; - } - g6 = [g6]; - } - return d6(g6); - } - function cM() { - return fe(b3); - } - function dX(g5) { - var g7; - var g6 = g5._a; - if (g6 && bE(g5).overflow === -2) { - g7 = - g6[o] < 0 || g6[o] > 11 - ? o - : g6[ga] < 1 || g6[ga] > ce(g6[gF], g6[o]) - ? ga - : g6[gr] < 0 || g6[gr] > 24 || (g6[gr] === 24 && (g6[e6] !== 0 || g6[aH] !== 0 || g6[ch] !== 0)) - ? gr - : g6[e6] < 0 || g6[e6] > 59 - ? e6 - : g6[aH] < 0 || g6[aH] > 59 - ? aH - : g6[ch] < 0 || g6[ch] > 999 - ? ch - : -1; - if (bE(g5)._overflowDayOfYear && (g7 < gF || g7 > ga)) { - g7 = ga; - } - if (bE(g5)._overflowWeeks && g7 === -1) { - g7 = da; - } - if (bE(g5)._overflowWeekday && g7 === -1) { - g7 = l; - } - bE(g5).overflow = g7; - } - return g5; - } - var p = - /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; - var bj = - /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; - var dL = /Z|[+-]\d\d(?::?\d\d)?/; - var d1 = [ - ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], - ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], - ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], - ['GGGG-[W]WW', /\d{4}-W\d\d/, false], - ['YYYY-DDD', /\d{4}-\d{3}/], - ['YYYY-MM', /\d{4}-\d\d/, false], - ['YYYYYYMMDD', /[+-]\d{10}/], - ['YYYYMMDD', /\d{8}/], - ['GGGG[W]WWE', /\d{4}W\d{3}/], - ['GGGG[W]WW', /\d{4}W\d{2}/, false], - ['YYYYDDD', /\d{7}/], - ]; - var dm = [ - ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], - ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], - ['HH:mm:ss', /\d\d:\d\d:\d\d/], - ['HH:mm', /\d\d:\d\d/], - ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], - ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], - ['HHmmss', /\d\d\d\d\d\d/], - ['HHmm', /\d\d\d\d/], - ['HH', /\d\d/], - ]; - var ct = /^\/?Date\((\-?\d+)/i; - function M(g6) { - var ha, - g8, - hc = g6._i, - hb = p.exec(hc) || bj.exec(hc), - hd, - g5, - g9, - g7; - if (hb) { - bE(g6).iso = true; - for (ha = 0, g8 = d1.length; ha < g8; ha++) { - if (d1[ha][1].exec(hb[1])) { - g5 = d1[ha][0]; - hd = d1[ha][2] !== false; - break; - } - } - if (g5 == null) { - g6._isValid = false; - return; - } - if (hb[3]) { - for (ha = 0, g8 = dm.length; ha < g8; ha++) { - if (dm[ha][1].exec(hb[3])) { - g9 = (hb[2] || ' ') + dm[ha][0]; - break; - } - } - if (g9 == null) { - g6._isValid = false; - return; - } - } - if (!hd && g9 != null) { - g6._isValid = false; - return; - } - if (hb[4]) { - if (dL.exec(hb[4])) { - g7 = 'Z'; - } else { - g6._isValid = false; - return; - } - } - g6._f = g5 + (g9 || '') + (g7 || ''); - cv(g6); - } else { - g6._isValid = false; - } - } - var cd = - /^((?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d?\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(?:\d\d)?\d\d\s)(\d\d:\d\d)(\:\d\d)?(\s(?:UT|GMT|[ECMP][SD]T|[A-IK-Za-ik-z]|[+-]\d{4}))$/; - function cr(g8) { - var hf, he, hd, g5, hc, g9; - var hh = { - ' GMT': ' +0000', - ' EDT': ' -0400', - ' EST': ' -0500', - ' CDT': ' -0500', - ' CST': ' -0600', - ' MDT': ' -0600', - ' MST': ' -0700', - ' PDT': ' -0700', - ' PST': ' -0800', - }; - var hb = 'YXWVUTSRQPONZABCDEFGHIKLM'; - var hg, g6; - hf = g8._i - .replace(/\([^\)]*\)|[\n\t]/g, ' ') - .replace(/(\s\s+)/g, ' ') - .replace(/^\s|\s$/g, ''); - he = cd.exec(hf); - if (he) { - hd = he[1] ? 'ddd' + (he[1].length === 5 ? ', ' : ' ') : ''; - g5 = 'D MMM ' + (he[2].length > 10 ? 'YYYY ' : 'YY '); - hc = 'HH:mm' + (he[4] ? ':ss' : ''); - if (he[1]) { - var ha = new Date(he[2]); - var g7 = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][ha.getDay()]; - if (he[1].substr(0, 3) !== g7) { - bE(g8).weekdayMismatch = true; - g8._isValid = false; - return; - } - } - switch (he[5].length) { - case 2: - if (g6 === 0) { - hg = ' +0000'; - } else { - g6 = hb.indexOf(he[5][1].toUpperCase()) - 12; - hg = (g6 < 0 ? ' -' : ' +') + ('' + g6).replace(/^-?/, '0').match(/..$/)[0] + '00'; - } - break; - case 4: - hg = hh[he[5]]; - break; - default: - hg = hh[' GMT']; - } - he[5] = hg; - g8._i = he.splice(1).join(''); - g9 = ' ZZ'; - g8._f = hd + g5 + hc + g9; - cv(g8); - bE(g8).rfc2822 = true; - } else { - g8._isValid = false; - } - } - function bF(g6) { - var g5 = ct.exec(g6._i); - if (g5 !== null) { - g6._d = new Date(+g5[1]); - return; - } - M(g6); - if (g6._isValid === false) { - delete g6._isValid; - } else { - return; - } - cr(g6); - if (g6._isValid === false) { - delete g6._isValid; - } else { - return; - } - gm.createFromInputFallback(g6); - } - gm.createFromInputFallback = fK( - 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.', - function (g5) { - g5._d = new Date(g5._i + (g5._useUTC ? ' UTC' : '')); - } - ); - function fC(g6, g5, g7) { - if (g6 != null) { - return g6; - } - if (g5 != null) { - return g5; - } - return g7; - } - function bu(g6) { - var g5 = new Date(gm.now()); - if (g6._useUTC) { - return [g5.getUTCFullYear(), g5.getUTCMonth(), g5.getUTCDate()]; - } - return [g5.getFullYear(), g5.getMonth(), g5.getDate()]; - } - function g(g9) { - var ha, - g8, - g7 = [], - g6, - g5; - if (g9._d) { - return; - } - g6 = bu(g9); - if (g9._w && g9._a[ga] == null && g9._a[o] == null) { - eb(g9); - } - if (g9._dayOfYear != null) { - g5 = fC(g9._a[gF], g6[gF]); - if (g9._dayOfYear > e3(g5) || g9._dayOfYear === 0) { - bE(g9)._overflowDayOfYear = true; - } - g8 = eS(g5, 0, g9._dayOfYear); - g9._a[o] = g8.getUTCMonth(); - g9._a[ga] = g8.getUTCDate(); - } - for (ha = 0; ha < 3 && g9._a[ha] == null; ++ha) { - g9._a[ha] = g7[ha] = g6[ha]; - } - for (; ha < 7; ha++) { - g9._a[ha] = g7[ha] = g9._a[ha] == null ? (ha === 2 ? 1 : 0) : g9._a[ha]; - } - if (g9._a[gr] === 24 && g9._a[e6] === 0 && g9._a[aH] === 0 && g9._a[ch] === 0) { - g9._nextDay = true; - g9._a[gr] = 0; - } - g9._d = (g9._useUTC ? eS : fB).apply(null, g7); - if (g9._tzm != null) { - g9._d.setUTCMinutes(g9._d.getUTCMinutes() - g9._tzm); - } - if (g9._nextDay) { - g9._a[gr] = 24; - } - } - function eb(g8) { - var hb, g5, g6, g9, he, hc, hd, ha; - hb = g8._w; - if (hb.GG != null || hb.W != null || hb.E != null) { - he = 1; - hc = 4; - g5 = fC(hb.GG, g8._a[gF], f8(eZ(), 1, 4).year); - g6 = fC(hb.W, 1); - g9 = fC(hb.E, 1); - if (g9 < 1 || g9 > 7) { - ha = true; - } - } else { - he = g8._locale._week.dow; - hc = g8._locale._week.doy; - var g7 = f8(eZ(), he, hc); - g5 = fC(hb.gg, g8._a[gF], g7.year); - g6 = fC(hb.w, g7.week); - if (hb.d != null) { - g9 = hb.d; - if (g9 < 0 || g9 > 6) { - ha = true; - } - } else { - if (hb.e != null) { - g9 = hb.e + he; - if (hb.e < 0 || hb.e > 6) { - ha = true; - } - } else { - g9 = he; - } - } - } - if (g6 < 1 || g6 > O(g5, he, hc)) { - bE(g8)._overflowWeeks = true; - } else { - if (ha != null) { - bE(g8)._overflowWeekday = true; - } else { - hd = b5(g5, g6, g9, he, hc); - g8._a[gF] = hd.year; - g8._dayOfYear = hd.dayOfYear; - } - } - } - gm.ISO_8601 = function () {}; - gm.RFC_2822 = function () {}; - function cv(g7) { - if (g7._f === gm.ISO_8601) { - M(g7); - return; - } - if (g7._f === gm.RFC_2822) { - cr(g7); - return; - } - g7._a = []; - bE(g7).empty = true; - var ha = '' + g7._i, - g9, - g6, - hd, - g8, - hc, - g5 = ha.length, - hb = 0; - hd = cc(g7._f, g7._locale).match(co) || []; - for (g9 = 0; g9 < hd.length; g9++) { - g8 = hd[g9]; - g6 = (ha.match(b9(g8, g7)) || [])[0]; - if (g6) { - hc = ha.substr(0, ha.indexOf(g6)); - if (hc.length > 0) { - bE(g7).unusedInput.push(hc); - } - ha = ha.slice(ha.indexOf(g6) + g6.length); - hb += g6.length; - } - if (bC[g8]) { - if (g6) { - bE(g7).empty = false; - } else { - bE(g7).unusedTokens.push(g8); - } - D(g8, g6, g7); - } else { - if (g7._strict && !g6) { - bE(g7).unusedTokens.push(g8); - } - } - } - bE(g7).charsLeftOver = g5 - hb; - if (ha.length > 0) { - bE(g7).unusedInput.push(ha); - } - if (g7._a[gr] <= 12 && bE(g7).bigHour === true && g7._a[gr] > 0) { - bE(g7).bigHour = undefined; - } - bE(g7).parsedDateParts = g7._a.slice(0); - bE(g7).meridiem = g7._meridiem; - g7._a[gr] = fL(g7._locale, g7._a[gr], g7._meridiem); - g(g7); - dX(g7); - } - function fL(g5, g7, g8) { - var g6; - if (g8 == null) { - return g7; - } - if (g5.meridiemHour != null) { - return g5.meridiemHour(g7, g8); - } else { - if (g5.isPM != null) { - g6 = g5.isPM(g8); - if (g6 && g7 < 12) { - g7 += 12; - } - if (!g6 && g7 === 12) { - g7 = 0; - } - return g7; - } else { - return g7; - } - } - } - function e1(g5) { - var g9, g7, g8, g6, ha; - if (g5._f.length === 0) { - bE(g5).invalidFormat = true; - g5._d = new Date(NaN); - return; - } - for (g6 = 0; g6 < g5._f.length; g6++) { - ha = 0; - g9 = y({}, g5); - if (g5._useUTC != null) { - g9._useUTC = g5._useUTC; - } - g9._f = g5._f[g6]; - cv(g9); - if (!aM(g9)) { - continue; - } - ha += bE(g9).charsLeftOver; - ha += bE(g9).unusedTokens.length * 10; - bE(g9).score = ha; - if (g8 == null || ha < g8) { - g8 = ha; - g7 = g9; - } - } - gO(g5, g7 || g9); - } - function bw(g5) { - if (g5._d) { - return; - } - var g6 = fb(g5._i); - g5._a = bT( - [g6.year, g6.month, g6.day || g6.date, g6.hour, g6.minute, g6.second, g6.millisecond], - function (g7) { - return g7 && parseInt(g7, 10); - } - ); - g(g5); - } - function aJ(g5) { - var g6 = new f7(dX(bX(g5))); - if (g6._nextDay) { - g6.add(1, 'd'); - g6._nextDay = undefined; - } - return g6; - } - function bX(g6) { - var g5 = g6._i, - g7 = g6._f; - g6._locale = g6._locale || aa(g6._l); - if (g5 === null || (g7 === undefined && g5 === '')) { - return X({ nullInput: true }); - } - if (typeof g5 === 'string') { - g6._i = g5 = g6._locale.preparse(g5); - } - if (cU(g5)) { - return new f7(dX(g5)); - } else { - if (gc(g5)) { - g6._d = g5; - } else { - if (ag(g7)) { - e1(g6); - } else { - if (g7) { - cv(g6); - } else { - dt(g6); - } - } - } - } - if (!aM(g6)) { - g6._d = null; - } - return g6; - } - function dt(g6) { - var g5 = g6._i; - if (P(g5)) { - g6._d = new Date(gm.now()); - } else { - if (gc(g5)) { - g6._d = new Date(g5.valueOf()); - } else { - if (typeof g5 === 'string') { - bF(g6); - } else { - if (ag(g5)) { - g6._a = bT(g5.slice(0), function (g7) { - return parseInt(g7, 10); - }); - g(g6); - } else { - if (E(g5)) { - bw(g6); - } else { - if (z(g5)) { - g6._d = new Date(g5); - } else { - gm.createFromInputFallback(g6); - } - } - } - } - } - } - } - function au(g8, g9, g5, g7, g6) { - var ha = {}; - if (g5 === true || g5 === false) { - g7 = g5; - g5 = undefined; - } - if ((E(g8) && c6(g8)) || (ag(g8) && g8.length === 0)) { - g8 = undefined; - } - ha._isAMomentObject = true; - ha._useUTC = ha._isUTC = g6; - ha._l = g5; - ha._i = g8; - ha._f = g9; - ha._strict = g7; - return aJ(ha); - } - function eZ(g7, g8, g5, g6) { - return au(g7, g8, g5, g6, false); - } - var dQ = fK( - 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', - function () { - var g5 = eZ.apply(null, arguments); - if (this.isValid() && g5.isValid()) { - return g5 < this ? this : g5; - } else { - return X(); - } - } - ); - var f4 = fK( - 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', - function () { - var g5 = eZ.apply(null, arguments); - if (this.isValid() && g5.isValid()) { - return g5 > this ? this : g5; - } else { - return X(); - } - } - ); - function gR(g7, g8) { - var g6, g5; - if (g8.length === 1 && ag(g8[0])) { - g8 = g8[0]; - } - if (!g8.length) { - return eZ(); - } - g6 = g8[0]; - for (g5 = 1; g5 < g8.length; ++g5) { - if (!g8[g5].isValid() || g8[g5][g7](g6)) { - g6 = g8[g5]; - } - } - return g6; - } - function w() { - var g5 = [].slice.call(arguments, 0); - return gR('isBefore', g5); - } - function bQ() { - var g5 = [].slice.call(arguments, 0); - return gR('isAfter', g5); - } - var dA = function () { - return Date.now ? Date.now() : +new Date(); - }; - var gM = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; - function aQ(g6) { - for (var g8 in g6) { - if (!(gM.indexOf(g8) !== -1 && (g6[g8] == null || !isNaN(g6[g8])))) { - return false; - } - } - var g5 = false; - for (var g7 = 0; g7 < gM.length; ++g7) { - if (g6[gM[g7]]) { - if (g5) { - return false; - } - if (parseFloat(g6[gM[g7]]) !== dZ(g6[gM[g7]])) { - g5 = true; - } - } - } - return true; - } - function B() { - return this._isValid; - } - function bo() { - return eD(NaN); - } - function fg(ha) { - var hc = fb(ha), - hb = hc.year || 0, - g6 = hc.quarter || 0, - g7 = hc.month || 0, - g5 = hc.week || 0, - hf = hc.day || 0, - hd = hc.hour || 0, - g9 = hc.minute || 0, - he = hc.second || 0, - g8 = hc.millisecond || 0; - this._isValid = aQ(hc); - this._milliseconds = +g8 + he * 1000 + g9 * 60000 + hd * 1000 * 60 * 60; - this._days = +hf + g5 * 7; - this._months = +g7 + g6 * 3 + hb * 12; - this._data = {}; - this._locale = aa(); - this._bubble(); - } - function az(g5) { - return g5 instanceof fg; - } - function fX(g5) { - if (g5 < 0) { - return Math.round(-1 * g5) * -1; - } else { - return Math.round(g5); - } - } - function b1(g5, g6) { - dy(g5, 0, 0, function () { - var g8 = this.utcOffset(); - var g7 = '+'; - if (g8 < 0) { - g8 = -g8; - g7 = '-'; - } - return g7 + dk(~~(g8 / 60), 2) + g6 + dk(~~g8 % 60, 2); - }); - } - b1('Z', ':'); - b1('ZZ', ''); - bG('Z', dK); - bG('ZZ', dK); - cs(['Z', 'ZZ'], function (g5, g7, g6) { - g6._useUTC = true; - g6._tzm = v(dK, g5); - }); - var gl = /([\+\-]|\d\d)/gi; - function v(ha, g6) { - var g8 = (g6 || '').match(ha); - if (g8 === null) { - return null; - } - var g5 = g8[g8.length - 1] || []; - var g9 = (g5 + '').match(gl) || ['-', 0, 0]; - var g7 = +(g9[1] * 60) + dZ(g9[2]); - return g7 === 0 ? 0 : g9[0] === '+' ? g7 : -g7; - } - function a3(g5, g6) { - var g7, g8; - if (g6._isUTC) { - g7 = g6.clone(); - g8 = (cU(g5) || gc(g5) ? g5.valueOf() : eZ(g5).valueOf()) - g7.valueOf(); - g7._d.setTime(g7._d.valueOf() + g8); - gm.updateOffset(g7, false); - return g7; - } else { - return eZ(g5).local(); - } - } - function be(g5) { - return -Math.round(g5._d.getTimezoneOffset() / 15) * 15; - } - gm.updateOffset = function () {}; - function eT(g5, g8, g9) { - var g7 = this._offset || 0, - g6; - if (!this.isValid()) { - return g5 != null ? this : NaN; - } - if (g5 != null) { - if (typeof g5 === 'string') { - g5 = v(dK, g5); - if (g5 === null) { - return this; - } - } else { - if (Math.abs(g5) < 16 && !g9) { - g5 = g5 * 60; - } - } - if (!this._isUTC && g8) { - g6 = be(this); - } - this._offset = g5; - this._isUTC = true; - if (g6 != null) { - this.add(g6, 'm'); - } - if (g7 !== g5) { - if (!g8 || this._changeInProgress) { - br(this, eD(g5 - g7, 'm'), 1, false); - } else { - if (!this._changeInProgress) { - this._changeInProgress = true; - gm.updateOffset(this, true); - this._changeInProgress = null; - } - } - } - return this; - } else { - return this._isUTC ? g7 : be(this); - } - } - function eO(g5, g6) { - if (g5 != null) { - if (typeof g5 !== 'string') { - g5 = -g5; - } - this.utcOffset(g5, g6); - return this; - } else { - return -this.utcOffset(); - } - } - function bs(g5) { - return this.utcOffset(0, g5); - } - function eQ(g5) { - if (this._isUTC) { - this.utcOffset(0, g5); - this._isUTC = false; - if (g5) { - this.subtract(be(this), 'm'); - } - } - return this; - } - function cR() { - if (this._tzm != null) { - this.utcOffset(this._tzm, false, true); - } else { - if (typeof this._i === 'string') { - var g5 = v(cf, this._i); - if (g5 != null) { - this.utcOffset(g5); - } else { - this.utcOffset(0, true); - } - } - } - return this; - } - function a1(g5) { - if (!this.isValid()) { - return false; - } - g5 = g5 ? eZ(g5).utcOffset() : 0; - return (this.utcOffset() - g5) % 60 === 0; - } - function bd() { - return ( - this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() - ); - } - function b() { - if (!P(this._isDSTShifted)) { - return this._isDSTShifted; - } - var g6 = {}; - y(g6, this); - g6 = bX(g6); - if (g6._a) { - var g5 = g6._isUTC ? du(g6._a) : eZ(g6._a); - this._isDSTShifted = this.isValid() && cy(g6._a, g5.toArray()) > 0; - } else { - this._isDSTShifted = false; - } - return this._isDSTShifted; - } - function eU() { - return this.isValid() ? !this._isUTC : false; - } - function cp() { - return this.isValid() ? this._isUTC : false; - } - function e0() { - return this.isValid() ? this._isUTC && this._offset === 0 : false; - } - var al = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; - var dx = - /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/; - function eD(g7, ha) { - var hb = g7, - g9 = null, - g6, - g8, - g5; - if (az(g7)) { - hb = { ms: g7._milliseconds, d: g7._days, M: g7._months }; - } else { - if (z(g7)) { - hb = {}; - if (ha) { - hb[ha] = g7; - } else { - hb.milliseconds = g7; - } - } else { - if (!!(g9 = al.exec(g7))) { - g6 = g9[1] === '-' ? -1 : 1; - hb = { - y: 0, - d: dZ(g9[ga]) * g6, - h: dZ(g9[gr]) * g6, - m: dZ(g9[e6]) * g6, - s: dZ(g9[aH]) * g6, - ms: dZ(fX(g9[ch] * 1000)) * g6, - }; - } else { - if (!!(g9 = dx.exec(g7))) { - g6 = g9[1] === '-' ? -1 : 1; - hb = { - y: gG(g9[2], g6), - M: gG(g9[3], g6), - w: gG(g9[4], g6), - d: gG(g9[5], g6), - h: gG(g9[6], g6), - m: gG(g9[7], g6), - s: gG(g9[8], g6), - }; - } else { - if (hb == null) { - hb = {}; - } else { - if (typeof hb === 'object' && ('from' in hb || 'to' in hb)) { - g5 = cl(eZ(hb.from), eZ(hb.to)); - hb = {}; - hb.ms = g5.milliseconds; - hb.M = g5.months; - } - } - } - } - } - } - g8 = new fg(hb); - if (az(g7) && eJ(g7, '_locale')) { - g8._locale = g7._locale; - } - return g8; - } - eD.fn = fg.prototype; - eD.invalid = bo; - function gG(g7, g5) { - var g6 = g7 && parseFloat(g7.replace(',', '.')); - return (isNaN(g6) ? 0 : g6) * g5; - } - function eX(g7, g5) { - var g6 = { milliseconds: 0, months: 0 }; - g6.months = g5.month() - g7.month() + (g5.year() - g7.year()) * 12; - if (g7.clone().add(g6.months, 'M').isAfter(g5)) { - --g6.months; - } - g6.milliseconds = +g5 - +g7.clone().add(g6.months, 'M'); - return g6; - } - function cl(g7, g5) { - var g6; - if (!(g7.isValid() && g5.isValid())) { - return { milliseconds: 0, months: 0 }; - } - g5 = a3(g5, g7); - if (g7.isBefore(g5)) { - g6 = eX(g7, g5); - } else { - g6 = eX(g5, g7); - g6.milliseconds = -g6.milliseconds; - g6.months = -g6.months; - } - return g6; - } - function bx(g6, g5) { - return function (ha, g9) { - var g8, g7; - if (g9 !== null && !isNaN(+g9)) { - gD( - g5, - 'moment().' + - g5 + - '(period, number) is deprecated. Please use moment().' + - g5 + - '(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.' - ); - g7 = ha; - ha = g9; - g9 = g7; - } - ha = typeof ha === 'string' ? +ha : ha; - g8 = eD(ha, g9); - br(this, g8, g6); - return this; - }; - } - function br(g7, ha, g9, g8) { - var g6 = ha._milliseconds, - hb = fX(ha._days), - g5 = fX(ha._months); - if (!g7.isValid()) { - return; - } - g8 = g8 == null ? true : g8; - if (g6) { - g7._d.setTime(g7._d.valueOf() + g6 * g9); - } - if (hb) { - bc(g7, 'Date', eY(g7, 'Date') + hb * g9); - } - if (g5) { - bn(g7, eY(g7, 'Month') + g5 * g9); - } - if (g8) { - gm.updateOffset(g7, hb || g5); - } - } - var bq = bx(1, 'add'); - var aV = bx(-1, 'subtract'); - function aS(g7, g5) { - var g6 = g7.diff(g5, 'days', true); - return g6 < -6 - ? 'sameElse' - : g6 < -1 - ? 'lastWeek' - : g6 < 0 - ? 'lastDay' - : g6 < 1 - ? 'sameDay' - : g6 < 2 - ? 'nextDay' - : g6 < 7 - ? 'nextWeek' - : 'sameElse'; - } - function c2(ha, g5) { - var g8 = ha || eZ(), - g7 = a3(g8, this).startOf('day'), - g9 = gm.calendarFormat(this, g7) || 'sameElse'; - var g6 = g5 && (bz(g5[g9]) ? g5[g9].call(this, g8) : g5[g9]); - return this.format(g6 || this.localeData().calendar(g9, this, eZ(g8))); - } - function eP() { - return new f7(this); - } - function dH(g6, g5) { - var g7 = cU(g6) ? g6 : eZ(g6); - if (!(this.isValid() && g7.isValid())) { - return false; - } - g5 = dY(!P(g5) ? g5 : 'millisecond'); - if (g5 === 'millisecond') { - return this.valueOf() > g7.valueOf(); - } else { - return g7.valueOf() < this.clone().startOf(g5).valueOf(); - } - } - function gA(g6, g5) { - var g7 = cU(g6) ? g6 : eZ(g6); - if (!(this.isValid() && g7.isValid())) { - return false; - } - g5 = dY(!P(g5) ? g5 : 'millisecond'); - if (g5 === 'millisecond') { - return this.valueOf() < g7.valueOf(); - } else { - return this.clone().endOf(g5).valueOf() < g7.valueOf(); - } - } - function f6(g8, g7, g5, g6) { - g6 = g6 || '()'; - return ( - (g6[0] === '(' ? this.isAfter(g8, g5) : !this.isBefore(g8, g5)) && - (g6[1] === ')' ? this.isBefore(g7, g5) : !this.isAfter(g7, g5)) - ); - } - function dO(g6, g5) { - var g8 = cU(g6) ? g6 : eZ(g6), - g7; - if (!(this.isValid() && g8.isValid())) { - return false; - } - g5 = dY(g5 || 'millisecond'); - if (g5 === 'millisecond') { - return this.valueOf() === g8.valueOf(); - } else { - g7 = g8.valueOf(); - return this.clone().startOf(g5).valueOf() <= g7 && g7 <= this.clone().endOf(g5).valueOf(); - } - } - function gt(g6, g5) { - return this.isSame(g6, g5) || this.isAfter(g6, g5); - } - function gx(g6, g5) { - return this.isSame(g6, g5) || this.isBefore(g6, g5); - } - function U(g8, g7, g5) { - var ha, g9, hb, g6; - if (!this.isValid()) { - return NaN; - } - ha = a3(g8, this); - if (!ha.isValid()) { - return NaN; - } - g9 = (ha.utcOffset() - this.utcOffset()) * 60000; - g7 = dY(g7); - if (g7 === 'year' || g7 === 'month' || g7 === 'quarter') { - g6 = f1(this, ha); - if (g7 === 'quarter') { - g6 = g6 / 3; - } else { - if (g7 === 'year') { - g6 = g6 / 12; - } - } - } else { - hb = this - ha; - g6 = - g7 === 'second' - ? hb / 1000 - : g7 === 'minute' - ? hb / 60000 - : g7 === 'hour' - ? hb / 3600000 - : g7 === 'day' - ? (hb - g9) / 86400000 - : g7 === 'week' - ? (hb - g9) / 604800000 - : hb; - } - return g5 ? g6 : eG(g6); - } - function f1(g6, g5) { - var ha = (g5.year() - g6.year()) * 12 + (g5.month() - g6.month()), - g7 = g6.clone().add(ha, 'months'), - g8, - g9; - if (g5 - g7 < 0) { - g8 = g6.clone().add(ha - 1, 'months'); - g9 = (g5 - g7) / (g7 - g8); - } else { - g8 = g6.clone().add(ha + 1, 'months'); - g9 = (g5 - g7) / (g8 - g7); - } - return -(ha + g9) || 0; - } - gm.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; - gm.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; - function fu() { - return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); - } - function ee() { - if (!this.isValid()) { - return null; - } - var g5 = this.clone().utc(); - if (g5.year() < 0 || g5.year() > 9999) { - return aA(g5, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); - } - if (bz(Date.prototype.toISOString)) { - return this.toDate().toISOString(); - } - return aA(g5, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); - } - function bh() { - if (!this.isValid()) { - return 'moment.invalid(/* ' + this._i + ' */)'; - } - var g7 = 'moment'; - var g5 = ''; - if (!this.isLocal()) { - g7 = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; - g5 = 'Z'; - } - var g8 = '[' + g7 + '("]'; - var g6 = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY'; - var ha = '-MM-DD[T]HH:mm:ss.SSS'; - var g9 = g5 + '[")]'; - return this.format(g8 + g6 + ha + g9); - } - function ei(g6) { - if (!g6) { - g6 = this.isUtc() ? gm.defaultFormatUtc : gm.defaultFormat; - } - var g5 = aA(this, g6); - return this.localeData().postformat(g5); - } - function fj(g6, g5) { - if (this.isValid() && ((cU(g6) && g6.isValid()) || eZ(g6).isValid())) { - return eD({ to: this, from: g6 }).locale(this.locale()).humanize(!g5); - } else { - return this.localeData().invalidDate(); - } - } - function fc(g5) { - return this.from(eZ(), g5); - } - function aF(g6, g5) { - if (this.isValid() && ((cU(g6) && g6.isValid()) || eZ(g6).isValid())) { - return eD({ from: this, to: g6 }).locale(this.locale()).humanize(!g5); - } else { - return this.localeData().invalidDate(); - } - } - function bg(g5) { - return this.to(eZ(), g5); - } - function g4(g6) { - var g5; - if (g6 === undefined) { - return this._locale._abbr; - } else { - g5 = aa(g6); - if (g5 != null) { - this._locale = g5; - } - return this; - } - } - var I = fK( - 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', - function (g5) { - if (g5 === undefined) { - return this.localeData(); - } else { - return this.locale(g5); - } - } - ); - function fk() { - return this._locale; - } - function cQ(g5) { - g5 = dY(g5); - switch (g5) { - case 'year': - this.month(0); - case 'quarter': - case 'month': - this.date(1); - case 'week': - case 'isoWeek': - case 'day': - case 'date': - this.hours(0); - case 'hour': - this.minutes(0); - case 'minute': - this.seconds(0); - case 'second': - this.milliseconds(0); - } - if (g5 === 'week') { - this.weekday(0); - } - if (g5 === 'isoWeek') { - this.isoWeekday(1); - } - if (g5 === 'quarter') { - this.month(Math.floor(this.month() / 3) * 3); - } - return this; - } - function ge(g5) { - g5 = dY(g5); - if (g5 === undefined || g5 === 'millisecond') { - return this; - } - if (g5 === 'date') { - g5 = 'day'; - } - return this.startOf(g5) - .add(1, g5 === 'isoWeek' ? 'week' : g5) - .subtract(1, 'ms'); - } - function fn() { - return this._d.valueOf() - (this._offset || 0) * 60000; - } - function b4() { - return Math.floor(this.valueOf() / 1000); - } - function ea() { - return new Date(this.valueOf()); - } - function e9() { - var g5 = this; - return [g5.year(), g5.month(), g5.date(), g5.hour(), g5.minute(), g5.second(), g5.millisecond()]; - } - function fl() { - var g5 = this; - return { - years: g5.year(), - months: g5.month(), - date: g5.date(), - hours: g5.hours(), - minutes: g5.minutes(), - seconds: g5.seconds(), - milliseconds: g5.milliseconds(), - }; - } - function ej() { - return this.isValid() ? this.toISOString() : null; - } - function x() { - return aM(this); - } - function e2() { - return gO({}, bE(this)); - } - function dB() { - return bE(this).overflow; - } - function gC() { - return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict }; - } - dy(0, ['gg', 2], 0, function () { - return this.weekYear() % 100; - }); - dy(0, ['GG', 2], 0, function () { - return this.isoWeekYear() % 100; - }); - function ai(g6, g5) { - dy(0, [g6, g6.length], 0, g5); - } - ai('gggg', 'weekYear'); - ai('ggggg', 'weekYear'); - ai('GGGG', 'isoWeekYear'); - ai('GGGGG', 'isoWeekYear'); - c0('weekYear', 'gg'); - c0('isoWeekYear', 'GG'); - fo('weekYear', 1); - fo('isoWeekYear', 1); - bG('G', L); - bG('g', L); - bG('GG', aP, ba); - bG('gg', aP, ba); - bG('GGGG', aN, a8); - bG('gggg', aN, a8); - bG('GGGGG', aL, a7); - bG('ggggg', aL, a7); - aj(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (g5, g8, g6, g7) { - g8[g7.substr(0, 2)] = dZ(g5); - }); - aj(['gg', 'GG'], function (g5, g8, g6, g7) { - g8[g7] = gm.parseTwoDigitYear(g5); - }); - function bW(g5) { - return dp.call(this, g5, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy); - } - function fr(g5) { - return dp.call(this, g5, this.isoWeek(), this.isoWeekday(), 1, 4); - } - function eo() { - return O(this.year(), 1, 4); - } - function S() { - var g5 = this.localeData()._week; - return O(this.year(), g5.dow, g5.doy); - } - function dp(g5, g6, g8, ha, g9) { - var g7; - if (g5 == null) { - return f8(this, ha, g9).year; - } else { - g7 = O(g5, ha, g9); - if (g6 > g7) { - g6 = g7; - } - return bA.call(this, g5, g6, g8, ha, g9); - } - } - function bA(g7, g6, g9, hb, ha) { - var g8 = b5(g7, g6, g9, hb, ha), - g5 = eS(g8.year, 0, g8.dayOfYear); - this.year(g5.getUTCFullYear()); - this.month(g5.getUTCMonth()); - this.date(g5.getUTCDate()); - return this; - } - dy('Q', 0, 'Qo', 'quarter'); - c0('quarter', 'Q'); - fo('quarter', 7); - bG('Q', bb); - cs('Q', function (g5, g6) { - g6[o] = (dZ(g5) - 1) * 3; - }); - function cz(g5) { - return g5 == null ? Math.ceil((this.month() + 1) / 3) : this.month((g5 - 1) * 3 + (this.month() % 3)); - } - dy('D', ['DD', 2], 'Do', 'date'); - c0('date', 'D'); - fo('date', 9); - bG('D', aP); - bG('DD', aP, ba); - bG('Do', function (g6, g5) { - return g6 ? g5._dayOfMonthOrdinalParse || g5._ordinalParse : g5._dayOfMonthOrdinalParseLenient; - }); - cs(['D', 'DD'], ga); - cs('Do', function (g5, g6) { - g6[ga] = dZ(g5.match(aP)[0], 10); - }); - var dj = fH('Date', true); - dy('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); - c0('dayOfYear', 'DDD'); - fo('dayOfYear', 4); - bG('DDD', aO); - bG('DDDD', a9); - cs(['DDD', 'DDDD'], function (g5, g7, g6) { - g6._dayOfYear = dZ(g5); - }); - function bI(g5) { - var g6 = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 86400000) + 1; - return g5 == null ? g6 : this.add(g5 - g6, 'd'); - } - dy('m', ['mm', 2], 0, 'minute'); - c0('minute', 'm'); - fo('minute', 14); - bG('m', aP); - bG('mm', aP, ba); - cs(['m', 'mm'], e6); - var gz = fH('Minutes', false); - dy('s', ['ss', 2], 0, 'second'); - c0('second', 's'); - fo('second', 15); - bG('s', aP); - bG('ss', aP, ba); - cs(['s', 'ss'], aH); - var b0 = fH('Seconds', false); - dy('S', 0, 0, function () { - return ~~(this.millisecond() / 100); - }); - dy(0, ['SS', 2], 0, function () { - return ~~(this.millisecond() / 10); - }); - dy(0, ['SSS', 3], 0, 'millisecond'); - dy(0, ['SSSS', 4], 0, function () { - return this.millisecond() * 10; - }); - dy(0, ['SSSSS', 5], 0, function () { - return this.millisecond() * 100; - }); - dy(0, ['SSSSSS', 6], 0, function () { - return this.millisecond() * 1000; - }); - dy(0, ['SSSSSSS', 7], 0, function () { - return this.millisecond() * 10000; - }); - dy(0, ['SSSSSSSS', 8], 0, function () { - return this.millisecond() * 100000; - }); - dy(0, ['SSSSSSSSS', 9], 0, function () { - return this.millisecond() * 1000000; - }); - c0('millisecond', 'ms'); - fo('millisecond', 16); - bG('S', aO, bb); - bG('SS', aO, ba); - bG('SSS', aO, a9); - var bP; - for (bP = 'SSSS'; bP.length <= 9; bP += 'S') { - bG(bP, A); - } - function eg(g5, g6) { - g6[ch] = dZ(('0.' + g5) * 1000); - } - for (bP = 'S'; bP.length <= 9; bP += 'S') { - cs(bP, eg); - } - var cx = fH('Milliseconds', false); - dy('z', 0, 0, 'zoneAbbr'); - dy('zz', 0, 0, 'zoneName'); - function gu() { - return this._isUTC ? 'UTC' : ''; - } - function fM() { - return this._isUTC ? 'Coordinated Universal Time' : ''; - } - var cV = f7.prototype; - cV.add = bq; - cV.calendar = c2; - cV.clone = eP; - cV.diff = U; - cV.endOf = ge; - cV.format = ei; - cV.from = fj; - cV.fromNow = fc; - cV.to = aF; - cV.toNow = bg; - cV.get = a0; - cV.invalidAt = dB; - cV.isAfter = dH; - cV.isBefore = gA; - cV.isBetween = f6; - cV.isSame = dO; - cV.isSameOrAfter = gt; - cV.isSameOrBefore = gx; - cV.isValid = x; - cV.lang = I; - cV.locale = g4; - cV.localeData = fk; - cV.max = f4; - cV.min = dQ; - cV.parsingFlags = e2; - cV.set = aR; - cV.startOf = cQ; - cV.subtract = aV; - cV.toArray = e9; - cV.toObject = fl; - cV.toDate = ea; - cV.toISOString = ee; - cV.inspect = bh; - cV.toJSON = ej; - cV.toString = fu; - cV.unix = b4; - cV.valueOf = fn; - cV.creationData = gC; - cV.year = dM; - cV.isLeapYear = d5; - cV.weekYear = bW; - cV.isoWeekYear = fr; - cV.quarter = cV.quarters = cz; - cV.month = gq; - cV.daysInMonth = ck; - cV.week = cV.weeks = T; - cV.isoWeek = cV.isoWeeks = H; - cV.weeksInYear = S; - cV.isoWeeksInYear = eo; - cV.date = dj; - cV.day = cV.days = fZ; - cV.weekday = av; - cV.isoWeekday = ds; - cV.dayOfYear = bI; - cV.hour = cV.hours = dl; - cV.minute = cV.minutes = gz; - cV.second = cV.seconds = b0; - cV.millisecond = cV.milliseconds = cx; - cV.utcOffset = eT; - cV.utc = bs; - cV.local = eQ; - cV.parseZone = cR; - cV.hasAlignedHourOffset = a1; - cV.isDST = bd; - cV.isLocal = eU; - cV.isUtcOffset = cp; - cV.isUtc = e0; - cV.isUTC = e0; - cV.zoneAbbr = gu; - cV.zoneName = fM; - cV.dates = fK('dates accessor is deprecated. Use date instead.', dj); - cV.months = fK('months accessor is deprecated. Use month instead', gq); - cV.years = fK('years accessor is deprecated. Use year instead', dM); - cV.zone = fK( - 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', - eO - ); - cV.isDSTShifted = fK( - 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', - b - ); - function er(g5) { - return eZ(g5 * 1000); - } - function dW() { - return eZ.apply(null, arguments).parseZone(); - } - function eV(g5) { - return g5; - } - var fx = dE.prototype; - fx.calendar = d; - fx.longDateFormat = dR; - fx.invalidDate = f5; - fx.ordinal = gj; - fx.preparse = eV; - fx.postformat = eV; - fx.relativeTime = ae; - fx.pastFuture = fq; - fx.set = eL; - fx.months = bt; - fx.monthsShort = bD; - fx.monthsParse = ep; - fx.monthsRegex = d8; - fx.monthsShortRegex = eI; - fx.week = bU; - fx.firstDayOfYear = em; - fx.firstDayOfWeek = aE; - fx.weekdays = aU; - fx.weekdaysMin = gn; - fx.weekdaysShort = W; - fx.weekdaysParse = cj; - fx.weekdaysRegex = gH; - fx.weekdaysShortRegex = a6; - fx.weekdaysMinRegex = N; - fx.isPM = cW; - fx.meridiem = bk; - function R(g9, g6, g8, ha) { - var g5 = aa(); - var g7 = du().set(ha, g6); - return g5[g8](g7, g9); - } - function bp(g9, g6, g8) { - if (z(g9)) { - g6 = g9; - g9 = undefined; - } - g9 = g9 || ''; - if (g6 != null) { - return R(g9, g6, g8, 'month'); - } - var g7; - var g5 = []; - for (g7 = 0; g7 < 12; g7++) { - g5[g7] = R(g9, g7, g8, 'month'); - } - return g5; - } - function gJ(ha, hc, g8, hb) { - if (typeof ha === 'boolean') { - if (z(hc)) { - g8 = hc; - hc = undefined; - } - hc = hc || ''; - } else { - hc = ha; - g8 = hc; - ha = false; - if (z(hc)) { - g8 = hc; - hc = undefined; - } - hc = hc || ''; - } - var g5 = aa(), - g6 = ha ? g5._week.dow : 0; - if (g8 != null) { - return R(hc, (g8 + g6) % 7, hb, 'day'); - } - var g9; - var g7 = []; - for (g9 = 0; g9 < 7; g9++) { - g7[g9] = R(hc, (g9 + g6) % 7, hb, 'day'); - } - return g7; - } - function d3(g6, g5) { - return bp(g6, g5, 'months'); - } - function dD(g6, g5) { - return bp(g6, g5, 'monthsShort'); - } - function eh(g6, g7, g5) { - return gJ(g6, g7, g5, 'weekdays'); - } - function dV(g6, g7, g5) { - return gJ(g6, g7, g5, 'weekdaysShort'); - } - function ak(g6, g7, g5) { - return gJ(g6, g7, g5, 'weekdaysMin'); - } - K('en', { - dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = dZ((g7 % 100) / 10) === 1 ? 'th' : g5 === 1 ? 'st' : g5 === 2 ? 'nd' : g5 === 3 ? 'rd' : 'th'; - return g7 + g6; - }, - }); - gm.lang = fK('moment.lang is deprecated. Use moment.locale instead.', K); - gm.langData = fK('moment.langData is deprecated. Use moment.localeData instead.', aa); - var gg = Math.abs; - function bR() { - var g5 = this._data; - this._milliseconds = gg(this._milliseconds); - this._days = gg(this._days); - this._months = gg(this._months); - g5.milliseconds = gg(g5.milliseconds); - g5.seconds = gg(g5.seconds); - g5.minutes = gg(g5.minutes); - g5.hours = gg(g5.hours); - g5.months = gg(g5.months); - g5.years = gg(g5.years); - return this; - } - function a5(g9, g6, g7, g8) { - var g5 = eD(g6, g7); - g9._milliseconds += g8 * g5._milliseconds; - g9._days += g8 * g5._days; - g9._months += g8 * g5._months; - return g9._bubble(); - } - function b6(g5, g6) { - return a5(this, g5, g6, 1); - } - function fh(g5, g6) { - return a5(this, g5, g6, -1); - } - function go(g5) { - if (g5 < 0) { - return Math.floor(g5); - } else { - return Math.ceil(g5); - } - } - function d4() { - var g7 = this._milliseconds; - var hd = this._days; - var g5 = this._months; - var g9 = this._data; - var hc, g8, hb, ha, g6; - if (!((g7 >= 0 && hd >= 0 && g5 >= 0) || (g7 <= 0 && hd <= 0 && g5 <= 0))) { - g7 += go(gT(g5) + hd) * 86400000; - hd = 0; - g5 = 0; - } - g9.milliseconds = g7 % 1000; - hc = eG(g7 / 1000); - g9.seconds = hc % 60; - g8 = eG(hc / 60); - g9.minutes = g8 % 60; - hb = eG(g8 / 60); - g9.hours = hb % 24; - hd += eG(hb / 24); - g6 = eG(h(hd)); - g5 += g6; - hd -= go(gT(g6)); - ha = eG(g5 / 12); - g5 %= 12; - g9.days = hd; - g9.months = g5; - g9.years = ha; - return this; - } - function h(g5) { - return (g5 * 4800) / 146097; - } - function gT(g5) { - return (g5 * 146097) / 4800; - } - function gs(g6) { - if (!this.isValid()) { - return NaN; - } - var g8; - var g5; - var g7 = this._milliseconds; - g6 = dY(g6); - if (g6 === 'month' || g6 === 'year') { - g8 = this._days + g7 / 86400000; - g5 = this._months + h(g8); - return g6 === 'month' ? g5 : g5 / 12; - } else { - g8 = this._days + Math.round(gT(this._months)); - switch (g6) { - case 'week': - return g8 / 7 + g7 / 604800000; - case 'day': - return g8 + g7 / 86400000; - case 'hour': - return g8 * 24 + g7 / 3600000; - case 'minute': - return g8 * 1440 + g7 / 60000; - case 'second': - return g8 * 86400 + g7 / 1000; - case 'millisecond': - return Math.floor(g8 * 86400000) + g7; - default: - throw new Error('Unknown unit ' + g6); - } - } - } - function ed() { - if (!this.isValid()) { - return NaN; - } - return ( - this._milliseconds + - this._days * 86400000 + - (this._months % 12) * 2592000000 + - dZ(this._months / 12) * 31536000000 - ); - } - function fz(g5) { - return function () { - return this.as(g5); - }; - } - var gV = fz('ms'); - var V = fz('s'); - var eR = fz('m'); - var C = fz('h'); - var fG = fz('d'); - var fi = fz('w'); - var fy = fz('M'); - var bO = fz('y'); - function Q(g5) { - g5 = dY(g5); - return this.isValid() ? this[g5 + 's']() : NaN; - } - function cS(g5) { - return function () { - return this.isValid() ? this._data[g5] : NaN; - }; - } - var c = cS('milliseconds'); - var bJ = cS('seconds'); - var a4 = cS('minutes'); - var af = cS('hours'); - var bH = cS('days'); - var gw = cS('months'); - var ci = cS('years'); - function fI() { - return eG(this.days() / 7); - } - var d9 = Math.round; - var e5 = { ss: 44, s: 45, m: 45, h: 22, d: 26, M: 11 }; - function aI(g6, g8, g7, g9, g5) { - return g5.relativeTime(g8 || 1, !!g7, g6, g9); - } - function e8(g9, g6, hd) { - var g7 = eD(g9).abs(); - var he = d9(g7.as('s')); - var g8 = d9(g7.as('m')); - var hc = d9(g7.as('h')); - var hf = d9(g7.as('d')); - var g5 = d9(g7.as('M')); - var ha = d9(g7.as('y')); - var hb = (he <= e5.ss && ['s', he]) || - (he < e5.s && ['ss', he]) || - (g8 <= 1 && ['m']) || - (g8 < e5.m && ['mm', g8]) || - (hc <= 1 && ['h']) || - (hc < e5.h && ['hh', hc]) || - (hf <= 1 && ['d']) || - (hf < e5.d && ['dd', hf]) || - (g5 <= 1 && ['M']) || - (g5 < e5.M && ['MM', g5]) || - (ha <= 1 && ['y']) || ['yy', ha]; - hb[2] = g6; - hb[3] = +g9 > 0; - hb[4] = hd; - return aI.apply(null, hb); - } - function gb(g5) { - if (g5 === undefined) { - return d9; - } - if (typeof g5 === 'function') { - d9 = g5; - return true; - } - return false; - } - function di(g5, g6) { - if (e5[g5] === undefined) { - return false; - } - if (g6 === undefined) { - return e5[g5]; - } - e5[g5] = g6; - if (g5 === 's') { - e5.ss = g6 - 1; - } - return true; - } - function a(g7) { - if (!this.isValid()) { - return this.localeData().invalidDate(); - } - var g5 = this.localeData(); - var g6 = e8(this, !g7, g5); - if (g7) { - g6 = g5.pastFuture(+this, g6); - } - return g5.postformat(g6); - } - var bl = Math.abs; - function cg() { - if (!this.isValid()) { - return this.localeData().invalidDate(); - } - var hf = bl(this._milliseconds) / 1000; - var hg = bl(this._days); - var g7 = bl(this._months); - var g9, he, hb; - g9 = eG(hf / 60); - he = eG(g9 / 60); - hf %= 60; - g9 %= 60; - hb = eG(g7 / 12); - g7 %= 12; - var g6 = hb; - var hc = g7; - var g5 = hg; - var ha = he; - var g8 = g9; - var hh = hf; - var hd = this.asSeconds(); - if (!hd) { - return 'P0D'; - } - return ( - (hd < 0 ? '-' : '') + - 'P' + - (g6 ? g6 + 'Y' : '') + - (hc ? hc + 'M' : '') + - (g5 ? g5 + 'D' : '') + - (ha || g8 || hh ? 'T' : '') + - (ha ? ha + 'H' : '') + - (g8 ? g8 + 'M' : '') + - (hh ? hh + 'S' : '') - ); - } - var fw = fg.prototype; - fw.isValid = B; - fw.abs = bR; - fw.add = b6; - fw.subtract = fh; - fw.as = gs; - fw.asMilliseconds = gV; - fw.asSeconds = V; - fw.asMinutes = eR; - fw.asHours = C; - fw.asDays = fG; - fw.asWeeks = fi; - fw.asMonths = fy; - fw.asYears = bO; - fw.valueOf = ed; - fw._bubble = d4; - fw.get = Q; - fw.milliseconds = c; - fw.seconds = bJ; - fw.minutes = a4; - fw.hours = af; - fw.days = bH; - fw.weeks = fI; - fw.months = gw; - fw.years = ci; - fw.humanize = a; - fw.toISOString = cg; - fw.toString = cg; - fw.toJSON = cg; - fw.locale = g4; - fw.localeData = fk; - fw.toIsoString = fK('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', cg); - fw.lang = I; - dy('X', 0, 0, 'unix'); - dy('x', 0, 0, 'valueOf'); - bG('x', L); - bG('X', gE); - cs('X', function (g5, g7, g6) { - g6._d = new Date(parseFloat(g5, 10) * 1000); - }); - cs('x', function (g5, g7, g6) { - g6._d = new Date(dZ(g5)); - }); - gm.version = '2.18.1'; - bi(eZ); - gm.fn = cV; - gm.min = w; - gm.max = bQ; - gm.now = dA; - gm.utc = du; - gm.unix = er; - gm.months = d3; - gm.isDate = gc; - gm.locale = K; - gm.invalid = X; - gm.duration = eD; - gm.isMoment = cU; - gm.weekdays = eh; - gm.parseZone = dW; - gm.localeData = aa; - gm.isDuration = az; - gm.monthsShort = dD; - gm.weekdaysMin = ak; - gm.defineLocale = dC; - gm.updateLocale = f0; - gm.locales = cM; - gm.weekdaysShort = dV; - gm.normalizeUnits = dY; - gm.relativeTimeRounding = gb; - gm.relativeTimeThreshold = di; - gm.calendarFormat = aS; - gm.prototype = cV; - gm.defineLocale('af', { - months: 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split( - '_' - ), - monthsShort: 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'), - weekdays: 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'), - weekdaysShort: 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'), - weekdaysMin: 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'), - meridiemParse: /vm|nm/i, - isPM: function (g5) { - return /^nm$/i.test(g5); - }, - meridiem: function (g5, g6, g7) { - if (g5 < 12) { - return g7 ? 'vm' : 'VM'; - } else { - return g7 ? 'nm' : 'NM'; - } - }, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Vandag om] LT', - nextDay: '[Môre om] LT', - nextWeek: 'dddd [om] LT', - lastDay: '[Gister om] LT', - lastWeek: '[Laas] dddd [om] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'oor %s', - past: '%s gelede', - s: "'n paar sekondes", - m: "'n minuut", - mm: '%d minute', - h: "'n uur", - hh: '%d ure', - d: "'n dag", - dd: '%d dae', - M: "'n maand", - MM: '%d maande', - y: "'n jaar", - yy: '%d jaar', - }, - dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, - ordinal: function (g5) { - return g5 + (g5 === 1 || g5 === 8 || g5 >= 20 ? 'ste' : 'de'); - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('ar-dz', { - months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort: 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin: 'أح_إث_ثلا_أر_خم_جم_سب'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'في %s', - past: 'منذ %s', - s: 'ثوان', - m: 'دقيقة', - mm: '%d دقائق', - h: 'ساعة', - hh: '%d ساعات', - d: 'يوم', - dd: '%d أيام', - M: 'شهر', - MM: '%d أشهر', - y: 'سنة', - yy: '%d سنوات', - }, - week: { dow: 0, doy: 4 }, - }); - gm.defineLocale('ar-kw', { - months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), - monthsShort: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), - weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'في %s', - past: 'منذ %s', - s: 'ثوان', - m: 'دقيقة', - mm: '%d دقائق', - h: 'ساعة', - hh: '%d ساعات', - d: 'يوم', - dd: '%d أيام', - M: 'شهر', - MM: '%d أشهر', - y: 'سنة', - yy: '%d سنوات', - }, - week: { dow: 0, doy: 12 }, - }); - var dq = { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 0: '0' }; - var aZ = function (g5) { - return g5 === 0 - ? 0 - : g5 === 1 - ? 1 - : g5 === 2 - ? 2 - : g5 % 100 >= 3 && g5 % 100 <= 10 - ? 3 - : g5 % 100 >= 11 - ? 4 - : 5; - }; - var cJ = { - s: ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], - m: ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], - h: ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], - d: ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], - M: ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], - y: ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'], - }; - var e7 = function (g5) { - return function (g8, g7, g6, ha) { - var g9 = aZ(g8), - hb = cJ[g5][aZ(g8)]; - if (g9 === 2) { - hb = hb[g7 ? 0 : 1]; - } - return hb.replace(/%d/i, g8); - }; - }; - var eB = [ - 'يناير', - 'فبراير', - 'مارس', - 'أبريل', - 'مايو', - 'يونيو', - 'يوليو', - 'أغسطس', - 'سبتمبر', - 'أكتوبر', - 'نوفمبر', - 'ديسمبر', - ]; - gm.defineLocale('ar-ly', { - months: eB, - monthsShort: eB, - weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'D/\u200FM/\u200FYYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - meridiemParse: /ص|م/, - isPM: function (g5) { - return 'م' === g5; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'ص'; - } else { - return 'م'; - } - }, - calendar: { - sameDay: '[اليوم عند الساعة] LT', - nextDay: '[غدًا عند الساعة] LT', - nextWeek: 'dddd [عند الساعة] LT', - lastDay: '[أمس عند الساعة] LT', - lastWeek: 'dddd [عند الساعة] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'بعد %s', - past: 'منذ %s', - s: e7('s'), - m: e7('m'), - mm: e7('m'), - h: e7('h'), - hh: e7('h'), - d: e7('d'), - dd: e7('d'), - M: e7('M'), - MM: e7('M'), - y: e7('y'), - yy: e7('y'), - }, - preparse: function (g5) { - return g5.replace(/\u200f/g, '').replace(/،/g, ','); - }, - postformat: function (g5) { - return g5 - .replace(/\d/g, function (g6) { - return dq[g6]; - }) - .replace(/,/g, '،'); - }, - week: { dow: 6, doy: 12 }, - }); - gm.defineLocale('ar-ma', { - months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), - monthsShort: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), - weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'في %s', - past: 'منذ %s', - s: 'ثوان', - m: 'دقيقة', - mm: '%d دقائق', - h: 'ساعة', - hh: '%d ساعات', - d: 'يوم', - dd: '%d أيام', - M: 'شهر', - MM: '%d أشهر', - y: 'سنة', - yy: '%d سنوات', - }, - week: { dow: 6, doy: 12 }, - }); - var c9 = { 1: '١', 2: '٢', 3: '٣', 4: '٤', 5: '٥', 6: '٦', 7: '٧', 8: '٨', 9: '٩', 0: '٠' }; - var ef = { '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9', '٠': '0' }; - gm.defineLocale('ar-sa', { - months: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - monthsShort: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - meridiemParse: /ص|م/, - isPM: function (g5) { - return 'م' === g5; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'ص'; - } else { - return 'م'; - } - }, - calendar: { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'في %s', - past: 'منذ %s', - s: 'ثوان', - m: 'دقيقة', - mm: '%d دقائق', - h: 'ساعة', - hh: '%d ساعات', - d: 'يوم', - dd: '%d أيام', - M: 'شهر', - MM: '%d أشهر', - y: 'سنة', - yy: '%d سنوات', - }, - preparse: function (g5) { - return g5 - .replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (g6) { - return ef[g6]; - }) - .replace(/،/g, ','); - }, - postformat: function (g5) { - return g5 - .replace(/\d/g, function (g6) { - return c9[g6]; - }) - .replace(/,/g, '،'); - }, - week: { dow: 0, doy: 6 }, - }); - gm.defineLocale('ar-tn', { - months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'في %s', - past: 'منذ %s', - s: 'ثوان', - m: 'دقيقة', - mm: '%d دقائق', - h: 'ساعة', - hh: '%d ساعات', - d: 'يوم', - dd: '%d أيام', - M: 'شهر', - MM: '%d أشهر', - y: 'سنة', - yy: '%d سنوات', - }, - week: { dow: 1, doy: 4 }, - }); - var c8 = { 1: '١', 2: '٢', 3: '٣', 4: '٤', 5: '٥', 6: '٦', 7: '٧', 8: '٨', 9: '٩', 0: '٠' }; - var fW = { '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9', '٠': '0' }; - var dg = function (g5) { - return g5 === 0 - ? 0 - : g5 === 1 - ? 1 - : g5 === 2 - ? 2 - : g5 % 100 >= 3 && g5 % 100 <= 10 - ? 3 - : g5 % 100 >= 11 - ? 4 - : 5; - }; - var fd = { - s: ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], - m: ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], - h: ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], - d: ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], - M: ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], - y: ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'], - }; - var gB = function (g5) { - return function (g8, g7, g6, ha) { - var g9 = dg(g8), - hb = fd[g5][dg(g8)]; - if (g9 === 2) { - hb = hb[g7 ? 0 : 1]; - } - return hb.replace(/%d/i, g8); - }; - }; - var eA = [ - 'كانون الثاني يناير', - 'شباط فبراير', - 'آذار مارس', - 'نيسان أبريل', - 'أيار مايو', - 'حزيران يونيو', - 'تموز يوليو', - 'آب أغسطس', - 'أيلول سبتمبر', - 'تشرين الأول أكتوبر', - 'تشرين الثاني نوفمبر', - 'كانون الأول ديسمبر', - ]; - gm.defineLocale('ar', { - months: eA, - monthsShort: eA, - weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'D/\u200FM/\u200FYYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - meridiemParse: /ص|م/, - isPM: function (g5) { - return 'م' === g5; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'ص'; - } else { - return 'م'; - } - }, - calendar: { - sameDay: '[اليوم عند الساعة] LT', - nextDay: '[غدًا عند الساعة] LT', - nextWeek: 'dddd [عند الساعة] LT', - lastDay: '[أمس عند الساعة] LT', - lastWeek: 'dddd [عند الساعة] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'بعد %s', - past: 'منذ %s', - s: gB('s'), - m: gB('m'), - mm: gB('m'), - h: gB('h'), - hh: gB('h'), - d: gB('d'), - dd: gB('d'), - M: gB('M'), - MM: gB('M'), - y: gB('y'), - yy: gB('y'), - }, - preparse: function (g5) { - return g5 - .replace(/\u200f/g, '') - .replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (g6) { - return fW[g6]; - }) - .replace(/،/g, ','); - }, - postformat: function (g5) { - return g5 - .replace(/\d/g, function (g6) { - return c8[g6]; - }) - .replace(/,/g, '،'); - }, - week: { dow: 6, doy: 12 }, - }); - var bm = { - 1: '-inci', - 5: '-inci', - 8: '-inci', - 70: '-inci', - 80: '-inci', - 2: '-nci', - 7: '-nci', - 20: '-nci', - 50: '-nci', - 3: '-üncü', - 4: '-üncü', - 100: '-üncü', - 6: '-ncı', - 9: '-uncu', - 10: '-uncu', - 30: '-uncu', - 60: '-ıncı', - 90: '-ıncı', - }; - gm.defineLocale('az', { - months: 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'), - monthsShort: 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'), - weekdays: 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'), - weekdaysShort: 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'), - weekdaysMin: 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[bugün saat] LT', - nextDay: '[sabah saat] LT', - nextWeek: '[gələn həftə] dddd [saat] LT', - lastDay: '[dünən] LT', - lastWeek: '[keçən həftə] dddd [saat] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s sonra', - past: '%s əvvəl', - s: 'birneçə saniyyə', - m: 'bir dəqiqə', - mm: '%d dəqiqə', - h: 'bir saat', - hh: '%d saat', - d: 'bir gün', - dd: '%d gün', - M: 'bir ay', - MM: '%d ay', - y: 'bir il', - yy: '%d il', - }, - meridiemParse: /gecə|səhər|gündüz|axşam/, - isPM: function (g5) { - return /^(gündüz|axşam)$/.test(g5); - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'gecə'; - } else { - if (g5 < 12) { - return 'səhər'; - } else { - if (g5 < 17) { - return 'gündüz'; - } else { - return 'axşam'; - } - } - } - }, - dayOfMonthOrdinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/, - ordinal: function (g7) { - if (g7 === 0) { - return g7 + '-ıncı'; - } - var g6 = g7 % 10, - g5 = (g7 % 100) - g6, - g8 = g7 >= 100 ? 100 : null; - return g7 + (bm[g6] || bm[g5] || bm[g8]); - }, - week: { dow: 1, doy: 7 }, - }); - function en(g7, g6) { - var g5 = g7.split('_'); - return g6 % 10 === 1 && g6 % 100 !== 11 - ? g5[0] - : g6 % 10 >= 2 && g6 % 10 <= 4 && (g6 % 100 < 10 || g6 % 100 >= 20) - ? g5[1] - : g5[2]; - } - function ek(g7, g6, g5) { - var g8 = { - mm: g6 ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін', - hh: g6 ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін', - dd: 'дзень_дні_дзён', - MM: 'месяц_месяцы_месяцаў', - yy: 'год_гады_гадоў', - }; - if (g5 === 'm') { - return g6 ? 'хвіліна' : 'хвіліну'; - } else { - if (g5 === 'h') { - return g6 ? 'гадзіна' : 'гадзіну'; - } else { - return g7 + ' ' + en(g8[g5], +g7); - } - } - } - gm.defineLocale('be', { - months: { - format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split( - '_' - ), - standalone: - 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split( - '_' - ), - }, - monthsShort: 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'), - weekdays: { - format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_'), - standalone: 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'), - isFormat: /\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/, - }, - weekdaysShort: 'нд_пн_ат_ср_чц_пт_сб'.split('_'), - weekdaysMin: 'нд_пн_ат_ср_чц_пт_сб'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY г.', - LLL: 'D MMMM YYYY г., HH:mm', - LLLL: 'dddd, D MMMM YYYY г., HH:mm', - }, - calendar: { - sameDay: '[Сёння ў] LT', - nextDay: '[Заўтра ў] LT', - lastDay: '[Учора ў] LT', - nextWeek: function () { - return '[У] dddd [ў] LT'; - }, - lastWeek: function () { - switch (this.day()) { - case 0: - case 3: - case 5: - case 6: - return '[У мінулую] dddd [ў] LT'; - case 1: - case 2: - case 4: - return '[У мінулы] dddd [ў] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'праз %s', - past: '%s таму', - s: 'некалькі секунд', - m: ek, - mm: ek, - h: ek, - hh: ek, - d: 'дзень', - dd: ek, - M: 'месяц', - MM: ek, - y: 'год', - yy: ek, - }, - meridiemParse: /ночы|раніцы|дня|вечара/, - isPM: function (g5) { - return /^(дня|вечара)$/.test(g5); - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'ночы'; - } else { - if (g5 < 12) { - return 'раніцы'; - } else { - if (g5 < 17) { - return 'дня'; - } else { - return 'вечара'; - } - } - } - }, - dayOfMonthOrdinalParse: /\d{1,2}-(і|ы|га)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'M': - case 'd': - case 'DDD': - case 'w': - case 'W': - return (g5 % 10 === 2 || g5 % 10 === 3) && g5 % 100 !== 12 && g5 % 100 !== 13 - ? g5 + '-і' - : g5 + '-ы'; - case 'D': - return g5 + '-га'; - default: - return g5; - } - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('bg', { - months: 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'), - monthsShort: 'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'), - weekdays: 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'), - weekdaysShort: 'нед_пон_вто_сря_чет_пет_съб'.split('_'), - weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'D.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY H:mm', - LLLL: 'dddd, D MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[Днес в] LT', - nextDay: '[Утре в] LT', - nextWeek: 'dddd [в] LT', - lastDay: '[Вчера в] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - case 3: - case 6: - return '[В изминалата] dddd [в] LT'; - case 1: - case 2: - case 4: - case 5: - return '[В изминалия] dddd [в] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'след %s', - past: 'преди %s', - s: 'няколко секунди', - m: 'минута', - mm: '%d минути', - h: 'час', - hh: '%d часа', - d: 'ден', - dd: '%d дни', - M: 'месец', - MM: '%d месеца', - y: 'година', - yy: '%d години', - }, - dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, - ordinal: function (g7) { - var g6 = g7 % 10, - g5 = g7 % 100; - if (g7 === 0) { - return g7 + '-ев'; - } else { - if (g5 === 0) { - return g7 + '-ен'; - } else { - if (g5 > 10 && g5 < 20) { - return g7 + '-ти'; - } else { - if (g6 === 1) { - return g7 + '-ви'; - } else { - if (g6 === 2) { - return g7 + '-ри'; - } else { - if (g6 === 7 || g6 === 8) { - return g7 + '-ми'; - } else { - return g7 + '-ти'; - } - } - } - } - } - } - }, - week: { dow: 1, doy: 7 }, - }); - var c7 = { 1: '১', 2: '২', 3: '৩', 4: '৪', 5: '৫', 6: '৬', 7: '৭', 8: '৮', 9: '৯', 0: '০' }; - var fV = { '১': '1', '২': '2', '৩': '3', '৪': '4', '৫': '5', '৬': '6', '৭': '7', '৮': '8', '৯': '9', '০': '0' }; - gm.defineLocale('bn', { - months: 'জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'), - monthsShort: 'জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে'.split('_'), - weekdays: 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split('_'), - weekdaysShort: 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'), - weekdaysMin: 'রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি'.split('_'), - longDateFormat: { - LT: 'A h:mm সময়', - LTS: 'A h:mm:ss সময়', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm সময়', - LLLL: 'dddd, D MMMM YYYY, A h:mm সময়', - }, - calendar: { - sameDay: '[আজ] LT', - nextDay: '[আগামীকাল] LT', - nextWeek: 'dddd, LT', - lastDay: '[গতকাল] LT', - lastWeek: '[গত] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s পরে', - past: '%s আগে', - s: 'কয়েক সেকেন্ড', - m: 'এক মিনিট', - mm: '%d মিনিট', - h: 'এক ঘন্টা', - hh: '%d ঘন্টা', - d: 'এক দিন', - dd: '%d দিন', - M: 'এক মাস', - MM: '%d মাস', - y: 'এক বছর', - yy: '%d বছর', - }, - preparse: function (g5) { - return g5.replace(/[১২৩৪৫৬৭৮৯০]/g, function (g6) { - return fV[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return c7[g6]; - }); - }, - meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if ((g6 === 'রাত' && g5 >= 4) || (g6 === 'দুপুর' && g5 < 5) || g6 === 'বিকাল') { - return g5 + 12; - } else { - return g5; - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'রাত'; - } else { - if (g5 < 10) { - return 'সকাল'; - } else { - if (g5 < 17) { - return 'দুপুর'; - } else { - if (g5 < 20) { - return 'বিকাল'; - } else { - return 'রাত'; - } - } - } - } - }, - week: { dow: 0, doy: 6 }, - }); - var c5 = { 1: '༡', 2: '༢', 3: '༣', 4: '༤', 5: '༥', 6: '༦', 7: '༧', 8: '༨', 9: '༩', 0: '༠' }; - var fU = { '༡': '1', '༢': '2', '༣': '3', '༤': '4', '༥': '5', '༦': '6', '༧': '7', '༨': '8', '༩': '9', '༠': '0' }; - gm.defineLocale('bo', { - months: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split( - '_' - ), - monthsShort: - 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split( - '_' - ), - weekdays: 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split('_'), - weekdaysShort: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), - weekdaysMin: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), - longDateFormat: { - LT: 'A h:mm', - LTS: 'A h:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm', - LLLL: 'dddd, D MMMM YYYY, A h:mm', - }, - calendar: { - sameDay: '[དི་རིང] LT', - nextDay: '[སང་ཉིན] LT', - nextWeek: '[བདུན་ཕྲག་རྗེས་མ], LT', - lastDay: '[ཁ་སང] LT', - lastWeek: '[བདུན་ཕྲག་མཐའ་མ] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s ལ་', - past: '%s སྔན་ལ', - s: 'ལམ་སང', - m: 'སྐར་མ་གཅིག', - mm: '%d སྐར་མ', - h: 'ཆུ་ཚོད་གཅིག', - hh: '%d ཆུ་ཚོད', - d: 'ཉིན་གཅིག', - dd: '%d ཉིན་', - M: 'ཟླ་བ་གཅིག', - MM: '%d ཟླ་བ', - y: 'ལོ་གཅིག', - yy: '%d ལོ', - }, - preparse: function (g5) { - return g5.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (g6) { - return fU[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return c5[g6]; - }); - }, - meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if ((g6 === 'མཚན་མོ' && g5 >= 4) || (g6 === 'ཉིན་གུང' && g5 < 5) || g6 === 'དགོང་དག') { - return g5 + 12; - } else { - return g5; - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'མཚན་མོ'; - } else { - if (g5 < 10) { - return 'ཞོགས་ཀས'; - } else { - if (g5 < 17) { - return 'ཉིན་གུང'; - } else { - if (g5 < 20) { - return 'དགོང་དག'; - } else { - return 'མཚན་མོ'; - } - } - } - } - }, - week: { dow: 0, doy: 6 }, - }); - function f(g7, g6, g5) { - var g8 = { mm: 'munutenn', MM: 'miz', dd: 'devezh' }; - return g7 + ' ' + gh(g8[g5], g7); - } - function aG(g5) { - switch (dS(g5)) { - case 1: - case 3: - case 4: - case 5: - case 9: - return g5 + ' bloaz'; - default: - return g5 + ' vloaz'; - } - } - function dS(g5) { - if (g5 > 9) { - return dS(g5 % 10); - } - return g5; - } - function gh(g6, g5) { - if (g5 === 2) { - return fY(g6); - } - return g6; - } - function fY(g6) { - var g5 = { m: 'v', b: 'v', d: 'z' }; - if (g5[g6.charAt(0)] === undefined) { - return g6; - } - return g5[g6.charAt(0)] + g6.substring(1); - } - gm.defineLocale('br', { - months: "Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split('_'), - monthsShort: "Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split('_'), - weekdays: "Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split('_'), - weekdaysShort: 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'), - weekdaysMin: 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'h[e]mm A', - LTS: 'h[e]mm:ss A', - L: 'DD/MM/YYYY', - LL: 'D [a viz] MMMM YYYY', - LLL: 'D [a viz] MMMM YYYY h[e]mm A', - LLLL: 'dddd, D [a viz] MMMM YYYY h[e]mm A', - }, - calendar: { - sameDay: '[Hiziv da] LT', - nextDay: "[Warc'hoazh da] LT", - nextWeek: 'dddd [da] LT', - lastDay: "[Dec'h da] LT", - lastWeek: 'dddd [paset da] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'a-benn %s', - past: "%s 'zo", - s: 'un nebeud segondennoù', - m: 'ur vunutenn', - mm: f, - h: 'un eur', - hh: '%d eur', - d: 'un devezh', - dd: f, - M: 'ur miz', - MM: f, - y: 'ur bloaz', - yy: aG, - }, - dayOfMonthOrdinalParse: /\d{1,2}(añ|vet)/, - ordinal: function (g6) { - var g5 = g6 === 1 ? 'añ' : 'vet'; - return g6 + g5; - }, - week: { dow: 1, doy: 4 }, - }); - function dU(g8, g7, g6) { - var g5 = g8 + ' '; - switch (g6) { - case 'm': - return g7 ? 'jedna minuta' : 'jedne minute'; - case 'mm': - if (g8 === 1) { - g5 += 'minuta'; - } else { - if (g8 === 2 || g8 === 3 || g8 === 4) { - g5 += 'minute'; - } else { - g5 += 'minuta'; - } - } - return g5; - case 'h': - return g7 ? 'jedan sat' : 'jednog sata'; - case 'hh': - if (g8 === 1) { - g5 += 'sat'; - } else { - if (g8 === 2 || g8 === 3 || g8 === 4) { - g5 += 'sata'; - } else { - g5 += 'sati'; - } - } - return g5; - case 'dd': - if (g8 === 1) { - g5 += 'dan'; - } else { - g5 += 'dana'; - } - return g5; - case 'MM': - if (g8 === 1) { - g5 += 'mjesec'; - } else { - if (g8 === 2 || g8 === 3 || g8 === 4) { - g5 += 'mjeseca'; - } else { - g5 += 'mjeseci'; - } - } - return g5; - case 'yy': - if (g8 === 1) { - g5 += 'godina'; - } else { - if (g8 === 2 || g8 === 3 || g8 === 4) { - g5 += 'godine'; - } else { - g5 += 'godina'; - } - } - return g5; - } - } - gm.defineLocale('bs', { - months: 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'), - monthsShort: 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), - weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), - weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[danas u] LT', - nextDay: '[sutra u] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[u] [nedjelju] [u] LT'; - case 3: - return '[u] [srijedu] [u] LT'; - case 6: - return '[u] [subotu] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[u] dddd [u] LT'; - } - }, - lastDay: '[jučer u] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - case 3: - return '[prošlu] dddd [u] LT'; - case 6: - return '[prošle] [subote] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[prošli] dddd [u] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'za %s', - past: 'prije %s', - s: 'par sekundi', - m: dU, - mm: dU, - h: dU, - hh: dU, - d: 'dan', - dd: dU, - M: 'mjesec', - MM: dU, - y: 'godinu', - yy: dU, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('ca', { - months: { - standalone: 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'), - format: "de gener_de febrer_de març_d'abril_de maig_de juny_de juliol_d'agost_de setembre_d'octubre_de novembre_de desembre".split( - '_' - ), - isFormat: /D[oD]?(\s)+MMMM/, - }, - monthsShort: 'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split('_'), - monthsParseExact: true, - weekdays: 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'), - weekdaysShort: 'dg._dl._dt._dc._dj._dv._ds.'.split('_'), - weekdaysMin: 'Dg_Dl_Dt_Dc_Dj_Dv_Ds'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD/MM/YYYY', - LL: '[el] D MMMM [de] YYYY', - ll: 'D MMM YYYY', - LLL: '[el] D MMMM [de] YYYY [a les] H:mm', - lll: 'D MMM YYYY, H:mm', - LLLL: '[el] dddd D MMMM [de] YYYY [a les] H:mm', - llll: 'ddd D MMM YYYY, H:mm', - }, - calendar: { - sameDay: function () { - return '[avui a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; - }, - nextDay: function () { - return '[demà a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; - }, - nextWeek: function () { - return 'dddd [a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; - }, - lastDay: function () { - return '[ahir a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; - }, - lastWeek: function () { - return '[el] dddd [passat a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; - }, - sameElse: 'L', - }, - relativeTime: { - future: "d'aquí %s", - past: 'fa %s', - s: 'uns segons', - m: 'un minut', - mm: '%d minuts', - h: 'una hora', - hh: '%d hores', - d: 'un dia', - dd: '%d dies', - M: 'un mes', - MM: '%d mesos', - y: 'un any', - yy: '%d anys', - }, - dayOfMonthOrdinalParse: /\d{1,2}(r|n|t|è|a)/, - ordinal: function (g6, g7) { - var g5 = g6 === 1 ? 'r' : g6 === 2 ? 'n' : g6 === 3 ? 'r' : g6 === 4 ? 't' : 'è'; - if (g7 === 'w' || g7 === 'W') { - g5 = 'a'; - } - return g6 + g5; - }, - week: { dow: 1, doy: 4 }, - }); - var ez = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'); - var cP = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_'); - function cI(g5) { - return g5 > 1 && g5 < 5 && ~~(g5 / 10) !== 1; - } - function g2(g8, g7, g6, g9) { - var g5 = g8 + ' '; - switch (g6) { - case 's': - return g7 || g9 ? 'pár sekund' : 'pár sekundami'; - case 'm': - return g7 ? 'minuta' : g9 ? 'minutu' : 'minutou'; - case 'mm': - if (g7 || g9) { - return g5 + (cI(g8) ? 'minuty' : 'minut'); - } else { - return g5 + 'minutami'; - } - break; - case 'h': - return g7 ? 'hodina' : g9 ? 'hodinu' : 'hodinou'; - case 'hh': - if (g7 || g9) { - return g5 + (cI(g8) ? 'hodiny' : 'hodin'); - } else { - return g5 + 'hodinami'; - } - break; - case 'd': - return g7 || g9 ? 'den' : 'dnem'; - case 'dd': - if (g7 || g9) { - return g5 + (cI(g8) ? 'dny' : 'dní'); - } else { - return g5 + 'dny'; - } - break; - case 'M': - return g7 || g9 ? 'měsíc' : 'měsícem'; - case 'MM': - if (g7 || g9) { - return g5 + (cI(g8) ? 'měsíce' : 'měsíců'); - } else { - return g5 + 'měsíci'; - } - break; - case 'y': - return g7 || g9 ? 'rok' : 'rokem'; - case 'yy': - if (g7 || g9) { - return g5 + (cI(g8) ? 'roky' : 'let'); - } else { - return g5 + 'lety'; - } - break; - } - } - gm.defineLocale('cs', { - months: ez, - monthsShort: cP, - monthsParse: (function (g5, g7) { - var g6, - g8 = []; - for (g6 = 0; g6 < 12; g6++) { - g8[g6] = new RegExp('^' + g5[g6] + '$|^' + g7[g6] + '$', 'i'); - } - return g8; - })(ez, cP), - shortMonthsParse: (function (g6) { - var g5, - g7 = []; - for (g5 = 0; g5 < 12; g5++) { - g7[g5] = new RegExp('^' + g6[g5] + '$', 'i'); - } - return g7; - })(cP), - longMonthsParse: (function (g5) { - var g6, - g7 = []; - for (g6 = 0; g6 < 12; g6++) { - g7[g6] = new RegExp('^' + g5[g6] + '$', 'i'); - } - return g7; - })(ez), - weekdays: 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'), - weekdaysShort: 'ne_po_út_st_čt_pá_so'.split('_'), - weekdaysMin: 'ne_po_út_st_čt_pá_so'.split('_'), - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd D. MMMM YYYY H:mm', - l: 'D. M. YYYY', - }, - calendar: { - sameDay: '[dnes v] LT', - nextDay: '[zítra v] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[v neděli v] LT'; - case 1: - case 2: - return '[v] dddd [v] LT'; - case 3: - return '[ve středu v] LT'; - case 4: - return '[ve čtvrtek v] LT'; - case 5: - return '[v pátek v] LT'; - case 6: - return '[v sobotu v] LT'; - } - }, - lastDay: '[včera v] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[minulou neděli v] LT'; - case 1: - case 2: - return '[minulé] dddd [v] LT'; - case 3: - return '[minulou středu v] LT'; - case 4: - case 5: - return '[minulý] dddd [v] LT'; - case 6: - return '[minulou sobotu v] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'za %s', - past: 'před %s', - s: g2, - m: g2, - mm: g2, - h: g2, - hh: g2, - d: g2, - dd: g2, - M: g2, - MM: g2, - y: g2, - yy: g2, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('cv', { - months: 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'), - monthsShort: 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'), - weekdays: 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'), - weekdaysShort: 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'), - weekdaysMin: 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD-MM-YYYY', - LL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]', - LLL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', - LLLL: 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', - }, - calendar: { - sameDay: '[Паян] LT [сехетре]', - nextDay: '[Ыран] LT [сехетре]', - lastDay: '[Ӗнер] LT [сехетре]', - nextWeek: '[Ҫитес] dddd LT [сехетре]', - lastWeek: '[Иртнӗ] dddd LT [сехетре]', - sameElse: 'L', - }, - relativeTime: { - future: function (g6) { - var g5 = /сехет$/i.exec(g6) ? 'рен' : /ҫул$/i.exec(g6) ? 'тан' : 'ран'; - return g6 + g5; - }, - past: '%s каялла', - s: 'пӗр-ик ҫеккунт', - m: 'пӗр минут', - mm: '%d минут', - h: 'пӗр сехет', - hh: '%d сехет', - d: 'пӗр кун', - dd: '%d кун', - M: 'пӗр уйӑх', - MM: '%d уйӑх', - y: 'пӗр ҫул', - yy: '%d ҫул', - }, - dayOfMonthOrdinalParse: /\d{1,2}-мӗш/, - ordinal: '%d-мӗш', - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('cy', { - months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'), - monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'), - weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'), - weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'), - weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Heddiw am] LT', - nextDay: '[Yfory am] LT', - nextWeek: 'dddd [am] LT', - lastDay: '[Ddoe am] LT', - lastWeek: 'dddd [diwethaf am] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'mewn %s', - past: '%s yn ôl', - s: 'ychydig eiliadau', - m: 'munud', - mm: '%d munud', - h: 'awr', - hh: '%d awr', - d: 'diwrnod', - dd: '%d diwrnod', - M: 'mis', - MM: '%d mis', - y: 'blwyddyn', - yy: '%d flynedd', - }, - dayOfMonthOrdinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/, - ordinal: function (g7) { - var g5 = g7, - g6 = '', - g8 = [ - '', - 'af', - 'il', - 'ydd', - 'ydd', - 'ed', - 'ed', - 'ed', - 'fed', - 'fed', - 'fed', - 'eg', - 'fed', - 'eg', - 'eg', - 'fed', - 'eg', - 'eg', - 'fed', - 'eg', - 'fed', - ]; - if (g5 > 20) { - if (g5 === 40 || g5 === 50 || g5 === 60 || g5 === 80 || g5 === 100) { - g6 = 'fed'; - } else { - g6 = 'ain'; - } - } else { - if (g5 > 0) { - g6 = g8[g5]; - } - } - return g7 + g6; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('da', { - months: 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'), - monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), - weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), - weekdaysShort: 'søn_man_tir_ons_tor_fre_lør'.split('_'), - weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY HH:mm', - LLLL: 'dddd [d.] D. MMMM YYYY [kl.] HH:mm', - }, - calendar: { - sameDay: '[i dag kl.] LT', - nextDay: '[i morgen kl.] LT', - nextWeek: 'på dddd [kl.] LT', - lastDay: '[i går kl.] LT', - lastWeek: '[i] dddd[s kl.] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'om %s', - past: '%s siden', - s: 'få sekunder', - m: 'et minut', - mm: '%d minutter', - h: 'en time', - hh: '%d timer', - d: 'en dag', - dd: '%d dage', - M: 'en måned', - MM: '%d måneder', - y: 'et år', - yy: '%d år', - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - function ah(g7, g6, g5, g9) { - var g8 = { - m: ['eine Minute', 'einer Minute'], - h: ['eine Stunde', 'einer Stunde'], - d: ['ein Tag', 'einem Tag'], - dd: [g7 + ' Tage', g7 + ' Tagen'], - M: ['ein Monat', 'einem Monat'], - MM: [g7 + ' Monate', g7 + ' Monaten'], - y: ['ein Jahr', 'einem Jahr'], - yy: [g7 + ' Jahre', g7 + ' Jahren'], - }; - return g6 ? g8[g5][0] : g8[g5][1]; - } - gm.defineLocale('de-at', { - months: 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), - monthsShort: 'Jän._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), - monthsParseExact: true, - weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), - weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), - weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY HH:mm', - LLLL: 'dddd, D. MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[heute um] LT [Uhr]', - sameElse: 'L', - nextDay: '[morgen um] LT [Uhr]', - nextWeek: 'dddd [um] LT [Uhr]', - lastDay: '[gestern um] LT [Uhr]', - lastWeek: '[letzten] dddd [um] LT [Uhr]', - }, - relativeTime: { - future: 'in %s', - past: 'vor %s', - s: 'ein paar Sekunden', - m: ah, - mm: '%d Minuten', - h: ah, - hh: '%d Stunden', - d: ah, - dd: ah, - M: ah, - MM: ah, - y: ah, - yy: ah, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - function ax(g7, g6, g5, g9) { - var g8 = { - m: ['eine Minute', 'einer Minute'], - h: ['eine Stunde', 'einer Stunde'], - d: ['ein Tag', 'einem Tag'], - dd: [g7 + ' Tage', g7 + ' Tagen'], - M: ['ein Monat', 'einem Monat'], - MM: [g7 + ' Monate', g7 + ' Monaten'], - y: ['ein Jahr', 'einem Jahr'], - yy: [g7 + ' Jahre', g7 + ' Jahren'], - }; - return g6 ? g8[g5][0] : g8[g5][1]; - } - gm.defineLocale('de-ch', { - months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), - monthsShort: 'Jan._Febr._März_April_Mai_Juni_Juli_Aug._Sept._Okt._Nov._Dez.'.split('_'), - monthsParseExact: true, - weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), - weekdaysShort: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), - weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH.mm', - LTS: 'HH.mm.ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY HH.mm', - LLLL: 'dddd, D. MMMM YYYY HH.mm', - }, - calendar: { - sameDay: '[heute um] LT [Uhr]', - sameElse: 'L', - nextDay: '[morgen um] LT [Uhr]', - nextWeek: 'dddd [um] LT [Uhr]', - lastDay: '[gestern um] LT [Uhr]', - lastWeek: '[letzten] dddd [um] LT [Uhr]', - }, - relativeTime: { - future: 'in %s', - past: 'vor %s', - s: 'ein paar Sekunden', - m: ax, - mm: '%d Minuten', - h: ax, - hh: '%d Stunden', - d: ax, - dd: ax, - M: ax, - MM: ax, - y: ax, - yy: ax, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - function aw(g7, g6, g5, g9) { - var g8 = { - m: ['eine Minute', 'einer Minute'], - h: ['eine Stunde', 'einer Stunde'], - d: ['ein Tag', 'einem Tag'], - dd: [g7 + ' Tage', g7 + ' Tagen'], - M: ['ein Monat', 'einem Monat'], - MM: [g7 + ' Monate', g7 + ' Monaten'], - y: ['ein Jahr', 'einem Jahr'], - yy: [g7 + ' Jahre', g7 + ' Jahren'], - }; - return g6 ? g8[g5][0] : g8[g5][1]; - } - gm.defineLocale('de', { - months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), - monthsShort: 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), - monthsParseExact: true, - weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), - weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), - weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY HH:mm', - LLLL: 'dddd, D. MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[heute um] LT [Uhr]', - sameElse: 'L', - nextDay: '[morgen um] LT [Uhr]', - nextWeek: 'dddd [um] LT [Uhr]', - lastDay: '[gestern um] LT [Uhr]', - lastWeek: '[letzten] dddd [um] LT [Uhr]', - }, - relativeTime: { - future: 'in %s', - past: 'vor %s', - s: 'ein paar Sekunden', - m: aw, - mm: '%d Minuten', - h: aw, - hh: '%d Stunden', - d: aw, - dd: aw, - M: aw, - MM: aw, - y: aw, - yy: aw, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - var ex = [ - 'ޖެނުއަރީ', - 'ފެބްރުއަރީ', - 'މާރިޗު', - 'އޭޕްރީލު', - 'މޭ', - 'ޖޫން', - 'ޖުލައި', - 'އޯގަސްޓު', - 'ސެޕްޓެމްބަރު', - 'އޮކްޓޯބަރު', - 'ނޮވެމްބަރު', - 'ޑިސެމްބަރު', - ]; - var fF = ['އާދިއްތަ', 'ހޯމަ', 'އަންގާރަ', 'ބުދަ', 'ބުރާސްފަތި', 'ހުކުރު', 'ހޮނިހިރު']; - gm.defineLocale('dv', { - months: ex, - monthsShort: ex, - weekdays: fF, - weekdaysShort: fF, - weekdaysMin: 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'D/M/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - meridiemParse: /މކ|މފ/, - isPM: function (g5) { - return 'މފ' === g5; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'މކ'; - } else { - return 'މފ'; - } - }, - calendar: { - sameDay: '[މިއަދު] LT', - nextDay: '[މާދަމާ] LT', - nextWeek: 'dddd LT', - lastDay: '[އިއްޔެ] LT', - lastWeek: '[ފާއިތުވި] dddd LT', - sameElse: 'L', - }, - relativeTime: { - future: 'ތެރޭގައި %s', - past: 'ކުރިން %s', - s: 'ސިކުންތުކޮޅެއް', - m: 'މިނިޓެއް', - mm: 'މިނިޓު %d', - h: 'ގަޑިއިރެއް', - hh: 'ގަޑިއިރު %d', - d: 'ދުވަހެއް', - dd: 'ދުވަސް %d', - M: 'މަހެއް', - MM: 'މަސް %d', - y: 'އަހަރެއް', - yy: 'އަހަރު %d', - }, - preparse: function (g5) { - return g5.replace(/،/g, ','); - }, - postformat: function (g5) { - return g5.replace(/,/g, '،'); - }, - week: { dow: 7, doy: 12 }, - }); - gm.defineLocale('el', { - monthsNominativeEl: - 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split( - '_' - ), - monthsGenitiveEl: - 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split( - '_' - ), - months: function (g6, g5) { - if (!g6) { - return this._monthsNominativeEl; - } else { - if (/D/.test(g5.substring(0, g5.indexOf('MMMM')))) { - return this._monthsGenitiveEl[g6.month()]; - } else { - return this._monthsNominativeEl[g6.month()]; - } - } - }, - monthsShort: 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'), - weekdays: 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'), - weekdaysShort: 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'), - weekdaysMin: 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'), - meridiem: function (g5, g6, g7) { - if (g5 > 11) { - return g7 ? 'μμ' : 'ΜΜ'; - } else { - return g7 ? 'πμ' : 'ΠΜ'; - } - }, - isPM: function (g5) { - return (g5 + '').toLowerCase()[0] === 'μ'; - }, - meridiemParse: /[ΠΜ]\.?Μ?\.?/i, - longDateFormat: { - LT: 'h:mm A', - LTS: 'h:mm:ss A', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY h:mm A', - LLLL: 'dddd, D MMMM YYYY h:mm A', - }, - calendarEl: { - sameDay: '[Σήμερα {}] LT', - nextDay: '[Αύριο {}] LT', - nextWeek: 'dddd [{}] LT', - lastDay: '[Χθες {}] LT', - lastWeek: function () { - switch (this.day()) { - case 6: - return '[το προηγούμενο] dddd [{}] LT'; - default: - return '[την προηγούμενη] dddd [{}] LT'; - } - }, - sameElse: 'L', - }, - calendar: function (g7, g8) { - var g6 = this._calendarEl[g7], - g5 = g8 && g8.hours(); - if (bz(g6)) { - g6 = g6.apply(g8); - } - return g6.replace('{}', g5 % 12 === 1 ? 'στη' : 'στις'); - }, - relativeTime: { - future: 'σε %s', - past: '%s πριν', - s: 'λίγα δευτερόλεπτα', - m: 'ένα λεπτό', - mm: '%d λεπτά', - h: 'μία ώρα', - hh: '%d ώρες', - d: 'μία μέρα', - dd: '%d μέρες', - M: 'ένας μήνας', - MM: '%d μήνες', - y: 'ένας χρόνος', - yy: '%d χρόνια', - }, - dayOfMonthOrdinalParse: /\d{1,2}η/, - ordinal: '%dη', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('en-au', { - months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), - longDateFormat: { - LT: 'h:mm A', - LTS: 'h:mm:ss A', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY h:mm A', - LLLL: 'dddd, D MMMM YYYY h:mm A', - }, - calendar: { - sameDay: '[Today at] LT', - nextDay: '[Tomorrow at] LT', - nextWeek: 'dddd [at] LT', - lastDay: '[Yesterday at] LT', - lastWeek: '[Last] dddd [at] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'in %s', - past: '%s ago', - s: 'a few seconds', - m: 'a minute', - mm: '%d minutes', - h: 'an hour', - hh: '%d hours', - d: 'a day', - dd: '%d days', - M: 'a month', - MM: '%d months', - y: 'a year', - yy: '%d years', - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = ~~((g7 % 100) / 10) === 1 ? 'th' : g5 === 1 ? 'st' : g5 === 2 ? 'nd' : g5 === 3 ? 'rd' : 'th'; - return g7 + g6; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('en-ca', { - months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), - longDateFormat: { - LT: 'h:mm A', - LTS: 'h:mm:ss A', - L: 'YYYY-MM-DD', - LL: 'MMMM D, YYYY', - LLL: 'MMMM D, YYYY h:mm A', - LLLL: 'dddd, MMMM D, YYYY h:mm A', - }, - calendar: { - sameDay: '[Today at] LT', - nextDay: '[Tomorrow at] LT', - nextWeek: 'dddd [at] LT', - lastDay: '[Yesterday at] LT', - lastWeek: '[Last] dddd [at] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'in %s', - past: '%s ago', - s: 'a few seconds', - m: 'a minute', - mm: '%d minutes', - h: 'an hour', - hh: '%d hours', - d: 'a day', - dd: '%d days', - M: 'a month', - MM: '%d months', - y: 'a year', - yy: '%d years', - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = ~~((g7 % 100) / 10) === 1 ? 'th' : g5 === 1 ? 'st' : g5 === 2 ? 'nd' : g5 === 3 ? 'rd' : 'th'; - return g7 + g6; - }, - }); - gm.defineLocale('en-gb', { - months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Today at] LT', - nextDay: '[Tomorrow at] LT', - nextWeek: 'dddd [at] LT', - lastDay: '[Yesterday at] LT', - lastWeek: '[Last] dddd [at] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'in %s', - past: '%s ago', - s: 'a few seconds', - m: 'a minute', - mm: '%d minutes', - h: 'an hour', - hh: '%d hours', - d: 'a day', - dd: '%d days', - M: 'a month', - MM: '%d months', - y: 'a year', - yy: '%d years', - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = ~~((g7 % 100) / 10) === 1 ? 'th' : g5 === 1 ? 'st' : g5 === 2 ? 'nd' : g5 === 3 ? 'rd' : 'th'; - return g7 + g6; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('en-ie', { - months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD-MM-YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Today at] LT', - nextDay: '[Tomorrow at] LT', - nextWeek: 'dddd [at] LT', - lastDay: '[Yesterday at] LT', - lastWeek: '[Last] dddd [at] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'in %s', - past: '%s ago', - s: 'a few seconds', - m: 'a minute', - mm: '%d minutes', - h: 'an hour', - hh: '%d hours', - d: 'a day', - dd: '%d days', - M: 'a month', - MM: '%d months', - y: 'a year', - yy: '%d years', - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = ~~((g7 % 100) / 10) === 1 ? 'th' : g5 === 1 ? 'st' : g5 === 2 ? 'nd' : g5 === 3 ? 'rd' : 'th'; - return g7 + g6; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('en-nz', { - months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), - longDateFormat: { - LT: 'h:mm A', - LTS: 'h:mm:ss A', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY h:mm A', - LLLL: 'dddd, D MMMM YYYY h:mm A', - }, - calendar: { - sameDay: '[Today at] LT', - nextDay: '[Tomorrow at] LT', - nextWeek: 'dddd [at] LT', - lastDay: '[Yesterday at] LT', - lastWeek: '[Last] dddd [at] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'in %s', - past: '%s ago', - s: 'a few seconds', - m: 'a minute', - mm: '%d minutes', - h: 'an hour', - hh: '%d hours', - d: 'a day', - dd: '%d days', - M: 'a month', - MM: '%d months', - y: 'a year', - yy: '%d years', - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = ~~((g7 % 100) / 10) === 1 ? 'th' : g5 === 1 ? 'st' : g5 === 2 ? 'nd' : g5 === 3 ? 'rd' : 'th'; - return g7 + g6; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('eo', { - months: 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'), - monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'), - weekdays: 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'), - weekdaysShort: 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'), - weekdaysMin: 'di_lu_ma_me_ĵa_ve_sa'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY-MM-DD', - LL: 'D[-a de] MMMM, YYYY', - LLL: 'D[-a de] MMMM, YYYY HH:mm', - LLLL: 'dddd, [la] D[-a de] MMMM, YYYY HH:mm', - }, - meridiemParse: /[ap]\.t\.m/i, - isPM: function (g5) { - return g5.charAt(0).toLowerCase() === 'p'; - }, - meridiem: function (g5, g6, g7) { - if (g5 > 11) { - return g7 ? 'p.t.m.' : 'P.T.M.'; - } else { - return g7 ? 'a.t.m.' : 'A.T.M.'; - } - }, - calendar: { - sameDay: '[Hodiaŭ je] LT', - nextDay: '[Morgaŭ je] LT', - nextWeek: 'dddd [je] LT', - lastDay: '[Hieraŭ je] LT', - lastWeek: '[pasinta] dddd [je] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'post %s', - past: 'antaŭ %s', - s: 'sekundoj', - m: 'minuto', - mm: '%d minutoj', - h: 'horo', - hh: '%d horoj', - d: 'tago', - dd: '%d tagoj', - M: 'monato', - MM: '%d monatoj', - y: 'jaro', - yy: '%d jaroj', - }, - dayOfMonthOrdinalParse: /\d{1,2}a/, - ordinal: '%da', - week: { dow: 1, doy: 7 }, - }); - var gN = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'); - var df = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); - gm.defineLocale('es-do', { - months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), - monthsShort: function (g5, g6) { - if (!g5) { - return gN; - } else { - if (/-MMM-/.test(g6)) { - return df[g5.month()]; - } else { - return gN[g5.month()]; - } - } - }, - monthsParseExact: true, - weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), - weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), - weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'h:mm A', - LTS: 'h:mm:ss A', - L: 'DD/MM/YYYY', - LL: 'D [de] MMMM [de] YYYY', - LLL: 'D [de] MMMM [de] YYYY h:mm A', - LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A', - }, - calendar: { - sameDay: function () { - return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - nextDay: function () { - return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - nextWeek: function () { - return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - lastDay: function () { - return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - lastWeek: function () { - return '[el] dddd [pasado a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - sameElse: 'L', - }, - relativeTime: { - future: 'en %s', - past: 'hace %s', - s: 'unos segundos', - m: 'un minuto', - mm: '%d minutos', - h: 'una hora', - hh: '%d horas', - d: 'un día', - dd: '%d días', - M: 'un mes', - MM: '%d meses', - y: 'un año', - yy: '%d años', - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal: '%dº', - week: { dow: 1, doy: 4 }, - }); - var eE = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'); - var dd = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); - gm.defineLocale('es', { - months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), - monthsShort: function (g5, g6) { - if (!g5) { - return eE; - } else { - if (/-MMM-/.test(g6)) { - return dd[g5.month()]; - } else { - return eE[g5.month()]; - } - } - }, - monthsParseExact: true, - weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), - weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), - weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D [de] MMMM [de] YYYY', - LLL: 'D [de] MMMM [de] YYYY H:mm', - LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm', - }, - calendar: { - sameDay: function () { - return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - nextDay: function () { - return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - nextWeek: function () { - return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - lastDay: function () { - return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - lastWeek: function () { - return '[el] dddd [pasado a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; - }, - sameElse: 'L', - }, - relativeTime: { - future: 'en %s', - past: 'hace %s', - s: 'unos segundos', - m: 'un minuto', - mm: '%d minutos', - h: 'una hora', - hh: '%d horas', - d: 'un día', - dd: '%d días', - M: 'un mes', - MM: '%d meses', - y: 'un año', - yy: '%d años', - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal: '%dº', - week: { dow: 1, doy: 4 }, - }); - function at(g7, g6, g5, g9) { - var g8 = { - s: ['mõne sekundi', 'mõni sekund', 'paar sekundit'], - m: ['ühe minuti', 'üks minut'], - mm: [g7 + ' minuti', g7 + ' minutit'], - h: ['ühe tunni', 'tund aega', 'üks tund'], - hh: [g7 + ' tunni', g7 + ' tundi'], - d: ['ühe päeva', 'üks päev'], - M: ['kuu aja', 'kuu aega', 'üks kuu'], - MM: [g7 + ' kuu', g7 + ' kuud'], - y: ['ühe aasta', 'aasta', 'üks aasta'], - yy: [g7 + ' aasta', g7 + ' aastat'], - }; - if (g6) { - return g8[g5][2] ? g8[g5][2] : g8[g5][1]; - } - return g9 ? g8[g5][0] : g8[g5][1]; - } - gm.defineLocale('et', { - months: 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'), - monthsShort: 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'), - weekdays: 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'), - weekdaysShort: 'P_E_T_K_N_R_L'.split('_'), - weekdaysMin: 'P_E_T_K_N_R_L'.split('_'), - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[Täna,] LT', - nextDay: '[Homme,] LT', - nextWeek: '[Järgmine] dddd LT', - lastDay: '[Eile,] LT', - lastWeek: '[Eelmine] dddd LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s pärast', - past: '%s tagasi', - s: at, - m: at, - mm: at, - h: at, - hh: at, - d: at, - dd: '%d päeva', - M: at, - MM: at, - y: at, - yy: at, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('eu', { - months: 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split( - '_' - ), - monthsShort: 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'), - monthsParseExact: true, - weekdays: 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'), - weekdaysShort: 'ig._al._ar._az._og._ol._lr.'.split('_'), - weekdaysMin: 'ig_al_ar_az_og_ol_lr'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY-MM-DD', - LL: 'YYYY[ko] MMMM[ren] D[a]', - LLL: 'YYYY[ko] MMMM[ren] D[a] HH:mm', - LLLL: 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm', - l: 'YYYY-M-D', - ll: 'YYYY[ko] MMM D[a]', - lll: 'YYYY[ko] MMM D[a] HH:mm', - llll: 'ddd, YYYY[ko] MMM D[a] HH:mm', - }, - calendar: { - sameDay: '[gaur] LT[etan]', - nextDay: '[bihar] LT[etan]', - nextWeek: 'dddd LT[etan]', - lastDay: '[atzo] LT[etan]', - lastWeek: '[aurreko] dddd LT[etan]', - sameElse: 'L', - }, - relativeTime: { - future: '%s barru', - past: 'duela %s', - s: 'segundo batzuk', - m: 'minutu bat', - mm: '%d minutu', - h: 'ordu bat', - hh: '%d ordu', - d: 'egun bat', - dd: '%d egun', - M: 'hilabete bat', - MM: '%d hilabete', - y: 'urte bat', - yy: '%d urte', - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 7 }, - }); - var c4 = { 1: '۱', 2: '۲', 3: '۳', 4: '۴', 5: '۵', 6: '۶', 7: '۷', 8: '۸', 9: '۹', 0: '۰' }; - var fT = { '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '۰': '0' }; - gm.defineLocale('fa', { - months: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), - monthsShort: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), - weekdays: 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), - weekdaysShort: 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), - weekdaysMin: 'ی_د_س_چ_پ_ج_ش'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - meridiemParse: /قبل از ظهر|بعد از ظهر/, - isPM: function (g5) { - return /بعد از ظهر/.test(g5); - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'قبل از ظهر'; - } else { - return 'بعد از ظهر'; - } - }, - calendar: { - sameDay: '[امروز ساعت] LT', - nextDay: '[فردا ساعت] LT', - nextWeek: 'dddd [ساعت] LT', - lastDay: '[دیروز ساعت] LT', - lastWeek: 'dddd [پیش] [ساعت] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'در %s', - past: '%s پیش', - s: 'چند ثانیه', - m: 'یک دقیقه', - mm: '%d دقیقه', - h: 'یک ساعت', - hh: '%d ساعت', - d: 'یک روز', - dd: '%d روز', - M: 'یک ماه', - MM: '%d ماه', - y: 'یک سال', - yy: '%d سال', - }, - preparse: function (g5) { - return g5 - .replace(/[۰-۹]/g, function (g6) { - return fT[g6]; - }) - .replace(/،/g, ','); - }, - postformat: function (g5) { - return g5 - .replace(/\d/g, function (g6) { - return c4[g6]; - }) - .replace(/,/g, '،'); - }, - dayOfMonthOrdinalParse: /\d{1,2}م/, - ordinal: '%dم', - week: { dow: 6, doy: 12 }, - }); - var u = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '); - var aY = ['nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', u[7], u[8], u[9]]; - function g1(g8, g7, g6, g9) { - var g5 = ''; - switch (g6) { - case 's': - return g9 ? 'muutaman sekunnin' : 'muutama sekunti'; - case 'm': - return g9 ? 'minuutin' : 'minuutti'; - case 'mm': - g5 = g9 ? 'minuutin' : 'minuuttia'; - break; - case 'h': - return g9 ? 'tunnin' : 'tunti'; - case 'hh': - g5 = g9 ? 'tunnin' : 'tuntia'; - break; - case 'd': - return g9 ? 'päivän' : 'päivä'; - case 'dd': - g5 = g9 ? 'päivän' : 'päivää'; - break; - case 'M': - return g9 ? 'kuukauden' : 'kuukausi'; - case 'MM': - g5 = g9 ? 'kuukauden' : 'kuukautta'; - break; - case 'y': - return g9 ? 'vuoden' : 'vuosi'; - case 'yy': - g5 = g9 ? 'vuoden' : 'vuotta'; - break; - } - g5 = ec(g8, g9) + ' ' + g5; - return g5; - } - function ec(g5, g6) { - return g5 < 10 ? (g6 ? aY[g5] : u[g5]) : g5; - } - gm.defineLocale('fi', { - months: 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split( - '_' - ), - monthsShort: 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'), - weekdays: 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'), - weekdaysShort: 'su_ma_ti_ke_to_pe_la'.split('_'), - weekdaysMin: 'su_ma_ti_ke_to_pe_la'.split('_'), - longDateFormat: { - LT: 'HH.mm', - LTS: 'HH.mm.ss', - L: 'DD.MM.YYYY', - LL: 'Do MMMM[ta] YYYY', - LLL: 'Do MMMM[ta] YYYY, [klo] HH.mm', - LLLL: 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm', - l: 'D.M.YYYY', - ll: 'Do MMM YYYY', - lll: 'Do MMM YYYY, [klo] HH.mm', - llll: 'ddd, Do MMM YYYY, [klo] HH.mm', - }, - calendar: { - sameDay: '[tänään] [klo] LT', - nextDay: '[huomenna] [klo] LT', - nextWeek: 'dddd [klo] LT', - lastDay: '[eilen] [klo] LT', - lastWeek: '[viime] dddd[na] [klo] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s päästä', - past: '%s sitten', - s: g1, - m: g1, - mm: g1, - h: g1, - hh: g1, - d: g1, - dd: g1, - M: g1, - MM: g1, - y: g1, - yy: g1, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('fo', { - months: 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'), - monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), - weekdays: 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'), - weekdaysShort: 'sun_mán_týs_mik_hós_frí_ley'.split('_'), - weekdaysMin: 'su_má_tý_mi_hó_fr_le'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D. MMMM, YYYY HH:mm', - }, - calendar: { - sameDay: '[Í dag kl.] LT', - nextDay: '[Í morgin kl.] LT', - nextWeek: 'dddd [kl.] LT', - lastDay: '[Í gjár kl.] LT', - lastWeek: '[síðstu] dddd [kl] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'um %s', - past: '%s síðani', - s: 'fá sekund', - m: 'ein minutt', - mm: '%d minuttir', - h: 'ein tími', - hh: '%d tímar', - d: 'ein dagur', - dd: '%d dagar', - M: 'ein mánaði', - MM: '%d mánaðir', - y: 'eitt ár', - yy: '%d ár', - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('fr-ca', { - months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), - monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), - monthsParseExact: true, - weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), - weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), - weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY-MM-DD', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Aujourd’hui à] LT', - nextDay: '[Demain à] LT', - nextWeek: 'dddd [à] LT', - lastDay: '[Hier à] LT', - lastWeek: 'dddd [dernier à] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'dans %s', - past: 'il y a %s', - s: 'quelques secondes', - m: 'une minute', - mm: '%d minutes', - h: 'une heure', - hh: '%d heures', - d: 'un jour', - dd: '%d jours', - M: 'un mois', - MM: '%d mois', - y: 'un an', - yy: '%d ans', - }, - dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, - ordinal: function (g5, g6) { - switch (g6) { - default: - case 'M': - case 'Q': - case 'D': - case 'DDD': - case 'd': - return g5 + (g5 === 1 ? 'er' : 'e'); - case 'w': - case 'W': - return g5 + (g5 === 1 ? 're' : 'e'); - } - }, - }); - gm.defineLocale('fr-ch', { - months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), - monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), - monthsParseExact: true, - weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), - weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), - weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Aujourd’hui à] LT', - nextDay: '[Demain à] LT', - nextWeek: 'dddd [à] LT', - lastDay: '[Hier à] LT', - lastWeek: 'dddd [dernier à] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'dans %s', - past: 'il y a %s', - s: 'quelques secondes', - m: 'une minute', - mm: '%d minutes', - h: 'une heure', - hh: '%d heures', - d: 'un jour', - dd: '%d jours', - M: 'un mois', - MM: '%d mois', - y: 'un an', - yy: '%d ans', - }, - dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, - ordinal: function (g5, g6) { - switch (g6) { - default: - case 'M': - case 'Q': - case 'D': - case 'DDD': - case 'd': - return g5 + (g5 === 1 ? 'er' : 'e'); - case 'w': - case 'W': - return g5 + (g5 === 1 ? 're' : 'e'); - } - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('fr', { - months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), - monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), - monthsParseExact: true, - weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), - weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), - weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Aujourd’hui à] LT', - nextDay: '[Demain à] LT', - nextWeek: 'dddd [à] LT', - lastDay: '[Hier à] LT', - lastWeek: 'dddd [dernier à] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'dans %s', - past: 'il y a %s', - s: 'quelques secondes', - m: 'une minute', - mm: '%d minutes', - h: 'une heure', - hh: '%d heures', - d: 'un jour', - dd: '%d jours', - M: 'un mois', - MM: '%d mois', - y: 'un an', - yy: '%d ans', - }, - dayOfMonthOrdinalParse: /\d{1,2}(er|)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'D': - return g5 + (g5 === 1 ? 'er' : ''); - default: - case 'M': - case 'Q': - case 'DDD': - case 'd': - return g5 + (g5 === 1 ? 'er' : 'e'); - case 'w': - case 'W': - return g5 + (g5 === 1 ? 're' : 'e'); - } - }, - week: { dow: 1, doy: 4 }, - }); - var f2 = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'); - var gv = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'); - gm.defineLocale('fy', { - months: 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split( - '_' - ), - monthsShort: function (g5, g6) { - if (!g5) { - return f2; - } else { - if (/-MMM-/.test(g6)) { - return gv[g5.month()]; - } else { - return f2[g5.month()]; - } - } - }, - monthsParseExact: true, - weekdays: 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'), - weekdaysShort: 'si._mo._ti._wo._to._fr._so.'.split('_'), - weekdaysMin: 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD-MM-YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[hjoed om] LT', - nextDay: '[moarn om] LT', - nextWeek: 'dddd [om] LT', - lastDay: '[juster om] LT', - lastWeek: '[ôfrûne] dddd [om] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'oer %s', - past: '%s lyn', - s: 'in pear sekonden', - m: 'ien minút', - mm: '%d minuten', - h: 'ien oere', - hh: '%d oeren', - d: 'ien dei', - dd: '%d dagen', - M: 'ien moanne', - MM: '%d moannen', - y: 'ien jier', - yy: '%d jierren', - }, - dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, - ordinal: function (g5) { - return g5 + (g5 === 1 || g5 === 8 || g5 >= 20 ? 'ste' : 'de'); - }, - week: { dow: 1, doy: 4 }, - }); - var ew = [ - 'Am Faoilleach', - 'An Gearran', - 'Am Màrt', - 'An Giblean', - 'An Cèitean', - 'An t-Ògmhios', - 'An t-Iuchar', - 'An Lùnastal', - 'An t-Sultain', - 'An Dàmhair', - 'An t-Samhain', - 'An Dùbhlachd', - ]; - var dc = ['Faoi', 'Gear', 'Màrt', 'Gibl', 'Cèit', 'Ògmh', 'Iuch', 'Lùn', 'Sult', 'Dàmh', 'Samh', 'Dùbh']; - var bN = ['Didòmhnaich', 'Diluain', 'Dimàirt', 'Diciadain', 'Diardaoin', 'Dihaoine', 'Disathairne']; - var fN = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis']; - var G = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa']; - gm.defineLocale('gd', { - months: ew, - monthsShort: dc, - monthsParseExact: true, - weekdays: bN, - weekdaysShort: fN, - weekdaysMin: G, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[An-diugh aig] LT', - nextDay: '[A-màireach aig] LT', - nextWeek: 'dddd [aig] LT', - lastDay: '[An-dè aig] LT', - lastWeek: 'dddd [seo chaidh] [aig] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'ann an %s', - past: 'bho chionn %s', - s: 'beagan diogan', - m: 'mionaid', - mm: '%d mionaidean', - h: 'uair', - hh: '%d uairean', - d: 'latha', - dd: '%d latha', - M: 'mìos', - MM: '%d mìosan', - y: 'bliadhna', - yy: '%d bliadhna', - }, - dayOfMonthOrdinalParse: /\d{1,2}(d|na|mh)/, - ordinal: function (g6) { - var g5 = g6 === 1 ? 'd' : g6 % 10 === 2 ? 'na' : 'mh'; - return g6 + g5; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('gl', { - months: 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'), - monthsShort: 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays: 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'), - weekdaysShort: 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'), - weekdaysMin: 'do_lu_ma_mé_xo_ve_sá'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D [de] MMMM [de] YYYY', - LLL: 'D [de] MMMM [de] YYYY H:mm', - LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm', - }, - calendar: { - sameDay: function () { - return '[hoxe ' + (this.hours() !== 1 ? 'ás' : 'á') + '] LT'; - }, - nextDay: function () { - return '[mañá ' + (this.hours() !== 1 ? 'ás' : 'á') + '] LT'; - }, - nextWeek: function () { - return 'dddd [' + (this.hours() !== 1 ? 'ás' : 'a') + '] LT'; - }, - lastDay: function () { - return '[onte ' + (this.hours() !== 1 ? 'á' : 'a') + '] LT'; - }, - lastWeek: function () { - return '[o] dddd [pasado ' + (this.hours() !== 1 ? 'ás' : 'a') + '] LT'; - }, - sameElse: 'L', - }, - relativeTime: { - future: function (g5) { - if (g5.indexOf('un') === 0) { - return 'n' + g5; - } - return 'en ' + g5; - }, - past: 'hai %s', - s: 'uns segundos', - m: 'un minuto', - mm: '%d minutos', - h: 'unha hora', - hh: '%d horas', - d: 'un día', - dd: '%d días', - M: 'un mes', - MM: '%d meses', - y: 'un ano', - yy: '%d anos', - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal: '%dº', - week: { dow: 1, doy: 4 }, - }); - function ar(g7, g6, g5, g9) { - var g8 = { - s: ['thodde secondanim', 'thodde second'], - m: ['eka mintan', 'ek minute'], - mm: [g7 + ' mintanim', g7 + ' mintam'], - h: ['eka horan', 'ek hor'], - hh: [g7 + ' horanim', g7 + ' hor'], - d: ['eka disan', 'ek dis'], - dd: [g7 + ' disanim', g7 + ' dis'], - M: ['eka mhoinean', 'ek mhoino'], - MM: [g7 + ' mhoineanim', g7 + ' mhoine'], - y: ['eka vorsan', 'ek voros'], - yy: [g7 + ' vorsanim', g7 + ' vorsam'], - }; - return g6 ? g8[g5][0] : g8[g5][1]; - } - gm.defineLocale('gom-latn', { - months: 'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split('_'), - monthsShort: 'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'), - monthsParseExact: true, - weekdays: "Aitar_Somar_Mongllar_Budvar_Brestar_Sukrar_Son'var".split('_'), - weekdaysShort: 'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'), - weekdaysMin: 'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'A h:mm [vazta]', - LTS: 'A h:mm:ss [vazta]', - L: 'DD-MM-YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY A h:mm [vazta]', - LLLL: 'dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]', - llll: 'ddd, D MMM YYYY, A h:mm [vazta]', - }, - calendar: { - sameDay: '[Aiz] LT', - nextDay: '[Faleam] LT', - nextWeek: '[Ieta to] dddd[,] LT', - lastDay: '[Kal] LT', - lastWeek: '[Fatlo] dddd[,] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s', - past: '%s adim', - s: ar, - m: ar, - mm: ar, - h: ar, - hh: ar, - d: ar, - dd: ar, - M: ar, - MM: ar, - y: ar, - yy: ar, - }, - dayOfMonthOrdinalParse: /\d{1,2}(er)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'D': - return g5 + 'er'; - default: - case 'M': - case 'Q': - case 'DDD': - case 'd': - case 'w': - case 'W': - return g5; - } - }, - week: { dow: 1, doy: 4 }, - meridiemParse: /rati|sokalli|donparam|sanje/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'rati') { - return g5 < 4 ? g5 : g5 + 12; - } else { - if (g6 === 'sokalli') { - return g5; - } else { - if (g6 === 'donparam') { - return g5 > 12 ? g5 : g5 + 12; - } else { - if (g6 === 'sanje') { - return g5 + 12; - } - } - } - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'rati'; - } else { - if (g5 < 12) { - return 'sokalli'; - } else { - if (g5 < 16) { - return 'donparam'; - } else { - if (g5 < 20) { - return 'sanje'; - } else { - return 'rati'; - } - } - } - } - }, - }); - gm.defineLocale('he', { - months: 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'), - monthsShort: 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'), - weekdays: 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'), - weekdaysShort: 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'), - weekdaysMin: 'א_ב_ג_ד_ה_ו_ש'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D [ב]MMMM YYYY', - LLL: 'D [ב]MMMM YYYY HH:mm', - LLLL: 'dddd, D [ב]MMMM YYYY HH:mm', - l: 'D/M/YYYY', - ll: 'D MMM YYYY', - lll: 'D MMM YYYY HH:mm', - llll: 'ddd, D MMM YYYY HH:mm', - }, - calendar: { - sameDay: '[היום ב־]LT', - nextDay: '[מחר ב־]LT', - nextWeek: 'dddd [בשעה] LT', - lastDay: '[אתמול ב־]LT', - lastWeek: '[ביום] dddd [האחרון בשעה] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'בעוד %s', - past: 'לפני %s', - s: 'מספר שניות', - m: 'דקה', - mm: '%d דקות', - h: 'שעה', - hh: function (g5) { - if (g5 === 2) { - return 'שעתיים'; - } - return g5 + ' שעות'; - }, - d: 'יום', - dd: function (g5) { - if (g5 === 2) { - return 'יומיים'; - } - return g5 + ' ימים'; - }, - M: 'חודש', - MM: function (g5) { - if (g5 === 2) { - return 'חודשיים'; - } - return g5 + ' חודשים'; - }, - y: 'שנה', - yy: function (g5) { - if (g5 === 2) { - return 'שנתיים'; - } else { - if (g5 % 10 === 0 && g5 !== 10) { - return g5 + ' שנה'; - } - } - return g5 + ' שנים'; - }, - }, - meridiemParse: /אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i, - isPM: function (g5) { - return /^(אחה"צ|אחרי הצהריים|בערב)$/.test(g5); - }, - meridiem: function (g5, g7, g6) { - if (g5 < 5) { - return 'לפנות בוקר'; - } else { - if (g5 < 10) { - return 'בבוקר'; - } else { - if (g5 < 12) { - return g6 ? 'לפנה"צ' : 'לפני הצהריים'; - } else { - if (g5 < 18) { - return g6 ? 'אחה"צ' : 'אחרי הצהריים'; - } else { - return 'בערב'; - } - } - } - } - }, - }); - var c1 = { 1: '१', 2: '२', 3: '३', 4: '४', 5: '५', 6: '६', 7: '७', 8: '८', 9: '९', 0: '०' }; - var fS = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; - gm.defineLocale('hi', { - months: 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'), - monthsShort: 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'), - monthsParseExact: true, - weekdays: 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), - weekdaysShort: 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'), - weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'), - longDateFormat: { - LT: 'A h:mm बजे', - LTS: 'A h:mm:ss बजे', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm बजे', - LLLL: 'dddd, D MMMM YYYY, A h:mm बजे', - }, - calendar: { - sameDay: '[आज] LT', - nextDay: '[कल] LT', - nextWeek: 'dddd, LT', - lastDay: '[कल] LT', - lastWeek: '[पिछले] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s में', - past: '%s पहले', - s: 'कुछ ही क्षण', - m: 'एक मिनट', - mm: '%d मिनट', - h: 'एक घंटा', - hh: '%d घंटे', - d: 'एक दिन', - dd: '%d दिन', - M: 'एक महीने', - MM: '%d महीने', - y: 'एक वर्ष', - yy: '%d वर्ष', - }, - preparse: function (g5) { - return g5.replace(/[१२३४५६७८९०]/g, function (g6) { - return fS[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return c1[g6]; - }); - }, - meridiemParse: /रात|सुबह|दोपहर|शाम/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'रात') { - return g5 < 4 ? g5 : g5 + 12; - } else { - if (g6 === 'सुबह') { - return g5; - } else { - if (g6 === 'दोपहर') { - return g5 >= 10 ? g5 : g5 + 12; - } else { - if (g6 === 'शाम') { - return g5 + 12; - } - } - } - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'रात'; - } else { - if (g5 < 10) { - return 'सुबह'; - } else { - if (g5 < 17) { - return 'दोपहर'; - } else { - if (g5 < 20) { - return 'शाम'; - } else { - return 'रात'; - } - } - } - } - }, - week: { dow: 0, doy: 6 }, - }); - function gZ(g8, g7, g6) { - var g5 = g8 + ' '; - switch (g6) { - case 'm': - return g7 ? 'jedna minuta' : 'jedne minute'; - case 'mm': - if (g8 === 1) { - g5 += 'minuta'; - } else { - if (g8 === 2 || g8 === 3 || g8 === 4) { - g5 += 'minute'; - } else { - g5 += 'minuta'; - } - } - return g5; - case 'h': - return g7 ? 'jedan sat' : 'jednog sata'; - case 'hh': - if (g8 === 1) { - g5 += 'sat'; - } else { - if (g8 === 2 || g8 === 3 || g8 === 4) { - g5 += 'sata'; - } else { - g5 += 'sati'; - } - } - return g5; - case 'dd': - if (g8 === 1) { - g5 += 'dan'; - } else { - g5 += 'dana'; - } - return g5; - case 'MM': - if (g8 === 1) { - g5 += 'mjesec'; - } else { - if (g8 === 2 || g8 === 3 || g8 === 4) { - g5 += 'mjeseca'; - } else { - g5 += 'mjeseci'; - } - } - return g5; - case 'yy': - if (g8 === 1) { - g5 += 'godina'; - } else { - if (g8 === 2 || g8 === 3 || g8 === 4) { - g5 += 'godine'; - } else { - g5 += 'godina'; - } - } - return g5; - } - } - gm.defineLocale('hr', { - months: { - format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split( - '_' - ), - standalone: - 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split( - '_' - ), - }, - monthsShort: 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'), - monthsParseExact: true, - weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), - weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), - weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[danas u] LT', - nextDay: '[sutra u] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[u] [nedjelju] [u] LT'; - case 3: - return '[u] [srijedu] [u] LT'; - case 6: - return '[u] [subotu] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[u] dddd [u] LT'; - } - }, - lastDay: '[jučer u] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - case 3: - return '[prošlu] dddd [u] LT'; - case 6: - return '[prošle] [subote] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[prošli] dddd [u] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'za %s', - past: 'prije %s', - s: 'par sekundi', - m: gZ, - mm: gZ, - h: gZ, - hh: gZ, - d: 'dan', - dd: gZ, - M: 'mjesec', - MM: gZ, - y: 'godinu', - yy: gZ, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 7 }, - }); - var fa = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); - function gY(g8, g7, g6, ha) { - var g5 = g8, - g9; - switch (g6) { - case 's': - return ha || g7 ? 'néhány másodperc' : 'néhány másodperce'; - case 'm': - return 'egy' + (ha || g7 ? ' perc' : ' perce'); - case 'mm': - return g5 + (ha || g7 ? ' perc' : ' perce'); - case 'h': - return 'egy' + (ha || g7 ? ' óra' : ' órája'); - case 'hh': - return g5 + (ha || g7 ? ' óra' : ' órája'); - case 'd': - return 'egy' + (ha || g7 ? ' nap' : ' napja'); - case 'dd': - return g5 + (ha || g7 ? ' nap' : ' napja'); - case 'M': - return 'egy' + (ha || g7 ? ' hónap' : ' hónapja'); - case 'MM': - return g5 + (ha || g7 ? ' hónap' : ' hónapja'); - case 'y': - return 'egy' + (ha || g7 ? ' év' : ' éve'); - case 'yy': - return g5 + (ha || g7 ? ' év' : ' éve'); - } - return ''; - } - function aD(g5) { - return (g5 ? '' : '[múlt] ') + '[' + fa[this.day()] + '] LT[-kor]'; - } - gm.defineLocale('hu', { - months: 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split( - '_' - ), - monthsShort: 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'), - weekdays: 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'), - weekdaysShort: 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'), - weekdaysMin: 'v_h_k_sze_cs_p_szo'.split('_'), - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'YYYY.MM.DD.', - LL: 'YYYY. MMMM D.', - LLL: 'YYYY. MMMM D. H:mm', - LLLL: 'YYYY. MMMM D., dddd H:mm', - }, - meridiemParse: /de|du/i, - isPM: function (g5) { - return g5.charAt(1).toLowerCase() === 'u'; - }, - meridiem: function (g5, g6, g7) { - if (g5 < 12) { - return g7 === true ? 'de' : 'DE'; - } else { - return g7 === true ? 'du' : 'DU'; - } - }, - calendar: { - sameDay: '[ma] LT[-kor]', - nextDay: '[holnap] LT[-kor]', - nextWeek: function () { - return aD.call(this, true); - }, - lastDay: '[tegnap] LT[-kor]', - lastWeek: function () { - return aD.call(this, false); - }, - sameElse: 'L', - }, - relativeTime: { - future: '%s múlva', - past: '%s', - s: gY, - m: gY, - mm: gY, - h: gY, - hh: gY, - d: gY, - dd: gY, - M: gY, - MM: gY, - y: gY, - yy: gY, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('hy-am', { - months: { - format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split( - '_' - ), - standalone: - 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split( - '_' - ), - }, - monthsShort: 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'), - weekdays: 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'), - weekdaysShort: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), - weekdaysMin: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY թ.', - LLL: 'D MMMM YYYY թ., HH:mm', - LLLL: 'dddd, D MMMM YYYY թ., HH:mm', - }, - calendar: { - sameDay: '[այսօր] LT', - nextDay: '[վաղը] LT', - lastDay: '[երեկ] LT', - nextWeek: function () { - return 'dddd [օրը ժամը] LT'; - }, - lastWeek: function () { - return '[անցած] dddd [օրը ժամը] LT'; - }, - sameElse: 'L', - }, - relativeTime: { - future: '%s հետո', - past: '%s առաջ', - s: 'մի քանի վայրկյան', - m: 'րոպե', - mm: '%d րոպե', - h: 'ժամ', - hh: '%d ժամ', - d: 'օր', - dd: '%d օր', - M: 'ամիս', - MM: '%d ամիս', - y: 'տարի', - yy: '%d տարի', - }, - meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/, - isPM: function (g5) { - return /^(ցերեկվա|երեկոյան)$/.test(g5); - }, - meridiem: function (g5) { - if (g5 < 4) { - return 'գիշերվա'; - } else { - if (g5 < 12) { - return 'առավոտվա'; - } else { - if (g5 < 17) { - return 'ցերեկվա'; - } else { - return 'երեկոյան'; - } - } - } - }, - dayOfMonthOrdinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'DDD': - case 'w': - case 'W': - case 'DDDo': - if (g5 === 1) { - return g5 + '-ին'; - } - return g5 + '-րդ'; - default: - return g5; - } - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('id', { - months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'), - monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des'.split('_'), - weekdays: 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'), - weekdaysShort: 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'), - weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'), - longDateFormat: { - LT: 'HH.mm', - LTS: 'HH.mm.ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY [pukul] HH.mm', - LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', - }, - meridiemParse: /pagi|siang|sore|malam/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'pagi') { - return g5; - } else { - if (g6 === 'siang') { - return g5 >= 11 ? g5 : g5 + 12; - } else { - if (g6 === 'sore' || g6 === 'malam') { - return g5 + 12; - } - } - } - }, - meridiem: function (g5, g6, g7) { - if (g5 < 11) { - return 'pagi'; - } else { - if (g5 < 15) { - return 'siang'; - } else { - if (g5 < 19) { - return 'sore'; - } else { - return 'malam'; - } - } - } - }, - calendar: { - sameDay: '[Hari ini pukul] LT', - nextDay: '[Besok pukul] LT', - nextWeek: 'dddd [pukul] LT', - lastDay: '[Kemarin pukul] LT', - lastWeek: 'dddd [lalu pukul] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'dalam %s', - past: '%s yang lalu', - s: 'beberapa detik', - m: 'semenit', - mm: '%d menit', - h: 'sejam', - hh: '%d jam', - d: 'sehari', - dd: '%d hari', - M: 'sebulan', - MM: '%d bulan', - y: 'setahun', - yy: '%d tahun', - }, - week: { dow: 1, doy: 7 }, - }); - function cG(g5) { - if (g5 % 100 === 11) { - return true; - } else { - if (g5 % 10 === 1) { - return false; - } - } - return true; - } - function gX(g8, g7, g6, g9) { - var g5 = g8 + ' '; - switch (g6) { - case 's': - return g7 || g9 ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; - case 'm': - return g7 ? 'mínúta' : 'mínútu'; - case 'mm': - if (cG(g8)) { - return g5 + (g7 || g9 ? 'mínútur' : 'mínútum'); - } else { - if (g7) { - return g5 + 'mínúta'; - } - } - return g5 + 'mínútu'; - case 'hh': - if (cG(g8)) { - return g5 + (g7 || g9 ? 'klukkustundir' : 'klukkustundum'); - } - return g5 + 'klukkustund'; - case 'd': - if (g7) { - return 'dagur'; - } - return g9 ? 'dag' : 'degi'; - case 'dd': - if (cG(g8)) { - if (g7) { - return g5 + 'dagar'; - } - return g5 + (g9 ? 'daga' : 'dögum'); - } else { - if (g7) { - return g5 + 'dagur'; - } - } - return g5 + (g9 ? 'dag' : 'degi'); - case 'M': - if (g7) { - return 'mánuður'; - } - return g9 ? 'mánuð' : 'mánuði'; - case 'MM': - if (cG(g8)) { - if (g7) { - return g5 + 'mánuðir'; - } - return g5 + (g9 ? 'mánuði' : 'mánuðum'); - } else { - if (g7) { - return g5 + 'mánuður'; - } - } - return g5 + (g9 ? 'mánuð' : 'mánuði'); - case 'y': - return g7 || g9 ? 'ár' : 'ári'; - case 'yy': - if (cG(g8)) { - return g5 + (g7 || g9 ? 'ár' : 'árum'); - } - return g5 + (g7 || g9 ? 'ár' : 'ári'); - } - } - gm.defineLocale('is', { - months: 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'), - monthsShort: 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'), - weekdays: 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'), - weekdaysShort: 'sun_mán_þri_mið_fim_fös_lau'.split('_'), - weekdaysMin: 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'), - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY [kl.] H:mm', - LLLL: 'dddd, D. MMMM YYYY [kl.] H:mm', - }, - calendar: { - sameDay: '[í dag kl.] LT', - nextDay: '[á morgun kl.] LT', - nextWeek: 'dddd [kl.] LT', - lastDay: '[í gær kl.] LT', - lastWeek: '[síðasta] dddd [kl.] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'eftir %s', - past: 'fyrir %s síðan', - s: gX, - m: gX, - mm: gX, - h: 'klukkustund', - hh: gX, - d: gX, - dd: gX, - M: gX, - MM: gX, - y: gX, - yy: gX, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('it', { - months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split( - '_' - ), - monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), - weekdays: 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'), - weekdaysShort: 'dom_lun_mar_mer_gio_ven_sab'.split('_'), - weekdaysMin: 'do_lu_ma_me_gi_ve_sa'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Oggi alle] LT', - nextDay: '[Domani alle] LT', - nextWeek: 'dddd [alle] LT', - lastDay: '[Ieri alle] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[la scorsa] dddd [alle] LT'; - default: - return '[lo scorso] dddd [alle] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: function (g5) { - return (/^[0-9].+$/.test(g5) ? 'tra' : 'in') + ' ' + g5; - }, - past: '%s fa', - s: 'alcuni secondi', - m: 'un minuto', - mm: '%d minuti', - h: "un'ora", - hh: '%d ore', - d: 'un giorno', - dd: '%d giorni', - M: 'un mese', - MM: '%d mesi', - y: 'un anno', - yy: '%d anni', - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal: '%dº', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('ja', { - months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), - weekdaysShort: '日_月_火_水_木_金_土'.split('_'), - weekdaysMin: '日_月_火_水_木_金_土'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY/MM/DD', - LL: 'YYYY年M月D日', - LLL: 'YYYY年M月D日 HH:mm', - LLLL: 'YYYY年M月D日 HH:mm dddd', - l: 'YYYY/MM/DD', - ll: 'YYYY年M月D日', - lll: 'YYYY年M月D日 HH:mm', - llll: 'YYYY年M月D日 HH:mm dddd', - }, - meridiemParse: /午前|午後/i, - isPM: function (g5) { - return g5 === '午後'; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return '午前'; - } else { - return '午後'; - } - }, - calendar: { - sameDay: '[今日] LT', - nextDay: '[明日] LT', - nextWeek: '[来週]dddd LT', - lastDay: '[昨日] LT', - lastWeek: '[前週]dddd LT', - sameElse: 'L', - }, - dayOfMonthOrdinalParse: /\d{1,2}日/, - ordinal: function (g5, g6) { - switch (g6) { - case 'd': - case 'D': - case 'DDD': - return g5 + '日'; - default: - return g5; - } - }, - relativeTime: { - future: '%s後', - past: '%s前', - s: '数秒', - m: '1分', - mm: '%d分', - h: '1時間', - hh: '%d時間', - d: '1日', - dd: '%d日', - M: '1ヶ月', - MM: '%dヶ月', - y: '1年', - yy: '%d年', - }, - }); - gm.defineLocale('jv', { - months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'), - monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'), - weekdays: 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'), - weekdaysShort: 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'), - weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'), - longDateFormat: { - LT: 'HH.mm', - LTS: 'HH.mm.ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY [pukul] HH.mm', - LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', - }, - meridiemParse: /enjing|siyang|sonten|ndalu/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'enjing') { - return g5; - } else { - if (g6 === 'siyang') { - return g5 >= 11 ? g5 : g5 + 12; - } else { - if (g6 === 'sonten' || g6 === 'ndalu') { - return g5 + 12; - } - } - } - }, - meridiem: function (g5, g6, g7) { - if (g5 < 11) { - return 'enjing'; - } else { - if (g5 < 15) { - return 'siyang'; - } else { - if (g5 < 19) { - return 'sonten'; - } else { - return 'ndalu'; - } - } - } - }, - calendar: { - sameDay: '[Dinten puniko pukul] LT', - nextDay: '[Mbenjang pukul] LT', - nextWeek: 'dddd [pukul] LT', - lastDay: '[Kala wingi pukul] LT', - lastWeek: 'dddd [kepengker pukul] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'wonten ing %s', - past: '%s ingkang kepengker', - s: 'sawetawis detik', - m: 'setunggal menit', - mm: '%d menit', - h: 'setunggal jam', - hh: '%d jam', - d: 'sedinten', - dd: '%d dinten', - M: 'sewulan', - MM: '%d wulan', - y: 'setaun', - yy: '%d taun', - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('ka', { - months: { - standalone: - 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split( - '_' - ), - format: 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split( - '_' - ), - }, - monthsShort: 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'), - weekdays: { - standalone: 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), - format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'), - isFormat: /(წინა|შემდეგ)/, - }, - weekdaysShort: 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'), - weekdaysMin: 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'), - longDateFormat: { - LT: 'h:mm A', - LTS: 'h:mm:ss A', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY h:mm A', - LLLL: 'dddd, D MMMM YYYY h:mm A', - }, - calendar: { - sameDay: '[დღეს] LT[-ზე]', - nextDay: '[ხვალ] LT[-ზე]', - lastDay: '[გუშინ] LT[-ზე]', - nextWeek: '[შემდეგ] dddd LT[-ზე]', - lastWeek: '[წინა] dddd LT-ზე', - sameElse: 'L', - }, - relativeTime: { - future: function (g5) { - return /(წამი|წუთი|საათი|წელი)/.test(g5) ? g5.replace(/ი$/, 'ში') : g5 + 'ში'; - }, - past: function (g5) { - if (/(წამი|წუთი|საათი|დღე|თვე)/.test(g5)) { - return g5.replace(/(ი|ე)$/, 'ის უკან'); - } - if (/წელი/.test(g5)) { - return g5.replace(/წელი$/, 'წლის უკან'); - } - }, - s: 'რამდენიმე წამი', - m: 'წუთი', - mm: '%d წუთი', - h: 'საათი', - hh: '%d საათი', - d: 'დღე', - dd: '%d დღე', - M: 'თვე', - MM: '%d თვე', - y: 'წელი', - yy: '%d წელი', - }, - dayOfMonthOrdinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/, - ordinal: function (g5) { - if (g5 === 0) { - return g5; - } - if (g5 === 1) { - return g5 + '-ლი'; - } - if (g5 < 20 || (g5 <= 100 && g5 % 20 === 0) || g5 % 100 === 0) { - return 'მე-' + g5; - } - return g5 + '-ე'; - }, - week: { dow: 1, doy: 7 }, - }); - var r = { - 0: '-ші', - 1: '-ші', - 2: '-ші', - 3: '-ші', - 4: '-ші', - 5: '-ші', - 6: '-шы', - 7: '-ші', - 8: '-ші', - 9: '-шы', - 10: '-шы', - 20: '-шы', - 30: '-шы', - 40: '-шы', - 50: '-ші', - 60: '-шы', - 70: '-ші', - 80: '-ші', - 90: '-шы', - 100: '-ші', - }; - gm.defineLocale('kk', { - months: 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'), - monthsShort: 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'), - weekdays: 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'), - weekdaysShort: 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'), - weekdaysMin: 'жк_дй_сй_ср_бй_жм_сн'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Бүгін сағат] LT', - nextDay: '[Ертең сағат] LT', - nextWeek: 'dddd [сағат] LT', - lastDay: '[Кеше сағат] LT', - lastWeek: '[Өткен аптаның] dddd [сағат] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s ішінде', - past: '%s бұрын', - s: 'бірнеше секунд', - m: 'бір минут', - mm: '%d минут', - h: 'бір сағат', - hh: '%d сағат', - d: 'бір күн', - dd: '%d күн', - M: 'бір ай', - MM: '%d ай', - y: 'бір жыл', - yy: '%d жыл', - }, - dayOfMonthOrdinalParse: /\d{1,2}-(ші|шы)/, - ordinal: function (g7) { - var g6 = g7 % 10, - g5 = g7 >= 100 ? 100 : null; - return g7 + (r[g7] || r[g6] || r[g5]); - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('km', { - months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'), - monthsShort: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'), - weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), - weekdaysShort: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), - weekdaysMin: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[ថ្ងៃនេះ ម៉ោង] LT', - nextDay: '[ស្អែក ម៉ោង] LT', - nextWeek: 'dddd [ម៉ោង] LT', - lastDay: '[ម្សិលមិញ ម៉ោង] LT', - lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%sទៀត', - past: '%sមុន', - s: 'ប៉ុន្មានវិនាទី', - m: 'មួយនាទី', - mm: '%d នាទី', - h: 'មួយម៉ោង', - hh: '%d ម៉ោង', - d: 'មួយថ្ងៃ', - dd: '%d ថ្ងៃ', - M: 'មួយខែ', - MM: '%d ខែ', - y: 'មួយឆ្នាំ', - yy: '%d ឆ្នាំ', - }, - week: { dow: 1, doy: 4 }, - }); - var cZ = { 1: '೧', 2: '೨', 3: '೩', 4: '೪', 5: '೫', 6: '೬', 7: '೭', 8: '೮', 9: '೯', 0: '೦' }; - var fR = { '೧': '1', '೨': '2', '೩': '3', '೪': '4', '೫': '5', '೬': '6', '೭': '7', '೮': '8', '೯': '9', '೦': '0' }; - gm.defineLocale('kn', { - months: 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split('_'), - monthsShort: 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬ_ಅಕ್ಟೋಬ_ನವೆಂಬ_ಡಿಸೆಂಬ'.split('_'), - monthsParseExact: true, - weekdays: 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split('_'), - weekdaysShort: 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'), - weekdaysMin: 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'), - longDateFormat: { - LT: 'A h:mm', - LTS: 'A h:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm', - LLLL: 'dddd, D MMMM YYYY, A h:mm', - }, - calendar: { - sameDay: '[ಇಂದು] LT', - nextDay: '[ನಾಳೆ] LT', - nextWeek: 'dddd, LT', - lastDay: '[ನಿನ್ನೆ] LT', - lastWeek: '[ಕೊನೆಯ] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s ನಂತರ', - past: '%s ಹಿಂದೆ', - s: 'ಕೆಲವು ಕ್ಷಣಗಳು', - m: 'ಒಂದು ನಿಮಿಷ', - mm: '%d ನಿಮಿಷ', - h: 'ಒಂದು ಗಂಟೆ', - hh: '%d ಗಂಟೆ', - d: 'ಒಂದು ದಿನ', - dd: '%d ದಿನ', - M: 'ಒಂದು ತಿಂಗಳು', - MM: '%d ತಿಂಗಳು', - y: 'ಒಂದು ವರ್ಷ', - yy: '%d ವರ್ಷ', - }, - preparse: function (g5) { - return g5.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (g6) { - return fR[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return cZ[g6]; - }); - }, - meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'ರಾತ್ರಿ') { - return g5 < 4 ? g5 : g5 + 12; - } else { - if (g6 === 'ಬೆಳಿಗ್ಗೆ') { - return g5; - } else { - if (g6 === 'ಮಧ್ಯಾಹ್ನ') { - return g5 >= 10 ? g5 : g5 + 12; - } else { - if (g6 === 'ಸಂಜೆ') { - return g5 + 12; - } - } - } - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'ರಾತ್ರಿ'; - } else { - if (g5 < 10) { - return 'ಬೆಳಿಗ್ಗೆ'; - } else { - if (g5 < 17) { - return 'ಮಧ್ಯಾಹ್ನ'; - } else { - if (g5 < 20) { - return 'ಸಂಜೆ'; - } else { - return 'ರಾತ್ರಿ'; - } - } - } - } - }, - dayOfMonthOrdinalParse: /\d{1,2}(ನೇ)/, - ordinal: function (g5) { - return g5 + 'ನೇ'; - }, - week: { dow: 0, doy: 6 }, - }); - gm.defineLocale('ko', { - months: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), - monthsShort: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), - weekdays: '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'), - weekdaysShort: '일_월_화_수_목_금_토'.split('_'), - weekdaysMin: '일_월_화_수_목_금_토'.split('_'), - longDateFormat: { - LT: 'A h:mm', - LTS: 'A h:mm:ss', - L: 'YYYY.MM.DD', - LL: 'YYYY년 MMMM D일', - LLL: 'YYYY년 MMMM D일 A h:mm', - LLLL: 'YYYY년 MMMM D일 dddd A h:mm', - l: 'YYYY.MM.DD', - ll: 'YYYY년 MMMM D일', - lll: 'YYYY년 MMMM D일 A h:mm', - llll: 'YYYY년 MMMM D일 dddd A h:mm', - }, - calendar: { - sameDay: '오늘 LT', - nextDay: '내일 LT', - nextWeek: 'dddd LT', - lastDay: '어제 LT', - lastWeek: '지난주 dddd LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s 후', - past: '%s 전', - s: '몇 초', - ss: '%d초', - m: '1분', - mm: '%d분', - h: '한 시간', - hh: '%d시간', - d: '하루', - dd: '%d일', - M: '한 달', - MM: '%d달', - y: '일 년', - yy: '%d년', - }, - dayOfMonthOrdinalParse: /\d{1,2}일/, - ordinal: '%d일', - meridiemParse: /오전|오후/, - isPM: function (g5) { - return g5 === '오후'; - }, - meridiem: function (g5, g7, g6) { - return g5 < 12 ? '오전' : '오후'; - }, - }); - var n = { - 0: '-чү', - 1: '-чи', - 2: '-чи', - 3: '-чү', - 4: '-чү', - 5: '-чи', - 6: '-чы', - 7: '-чи', - 8: '-чи', - 9: '-чу', - 10: '-чу', - 20: '-чы', - 30: '-чу', - 40: '-чы', - 50: '-чү', - 60: '-чы', - 70: '-чи', - 80: '-чи', - 90: '-чу', - 100: '-чү', - }; - gm.defineLocale('ky', { - months: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), - monthsShort: 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), - weekdays: 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'), - weekdaysShort: 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'), - weekdaysMin: 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Бүгүн саат] LT', - nextDay: '[Эртең саат] LT', - nextWeek: 'dddd [саат] LT', - lastDay: '[Кече саат] LT', - lastWeek: '[Өткен аптанын] dddd [күнү] [саат] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s ичинде', - past: '%s мурун', - s: 'бирнече секунд', - m: 'бир мүнөт', - mm: '%d мүнөт', - h: 'бир саат', - hh: '%d саат', - d: 'бир күн', - dd: '%d күн', - M: 'бир ай', - MM: '%d ай', - y: 'бир жыл', - yy: '%d жыл', - }, - dayOfMonthOrdinalParse: /\d{1,2}-(чи|чы|чү|чу)/, - ordinal: function (g7) { - var g6 = g7 % 10, - g5 = g7 >= 100 ? 100 : null; - return g7 + (n[g7] || n[g6] || n[g5]); - }, - week: { dow: 1, doy: 7 }, - }); - function ap(g7, g6, g5, g9) { - var g8 = { - m: ['eng Minutt', 'enger Minutt'], - h: ['eng Stonn', 'enger Stonn'], - d: ['een Dag', 'engem Dag'], - M: ['ee Mount', 'engem Mount'], - y: ['ee Joer', 'engem Joer'], - }; - return g6 ? g8[g5][0] : g8[g5][1]; - } - function gy(g5) { - var g6 = g5.substr(0, g5.indexOf(' ')); - if (dP(g6)) { - return 'a ' + g5; - } - return 'an ' + g5; - } - function gp(g5) { - var g6 = g5.substr(0, g5.indexOf(' ')); - if (dP(g6)) { - return 'viru ' + g5; - } - return 'virun ' + g5; - } - function dP(g6) { - g6 = parseInt(g6, 10); - if (isNaN(g6)) { - return false; - } - if (g6 < 0) { - return true; - } else { - if (g6 < 10) { - if (4 <= g6 && g6 <= 7) { - return true; - } - return false; - } else { - if (g6 < 100) { - var g5 = g6 % 10, - g7 = g6 / 10; - if (g5 === 0) { - return dP(g7); - } - return dP(g5); - } else { - if (g6 < 10000) { - while (g6 >= 10) { - g6 = g6 / 10; - } - return dP(g6); - } else { - g6 = g6 / 1000; - return dP(g6); - } - } - } - } - } - gm.defineLocale('lb', { - months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), - monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), - monthsParseExact: true, - weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'), - weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'), - weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm [Auer]', - LTS: 'H:mm:ss [Auer]', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm [Auer]', - LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]', - }, - calendar: { - sameDay: '[Haut um] LT', - sameElse: 'L', - nextDay: '[Muer um] LT', - nextWeek: 'dddd [um] LT', - lastDay: '[Gëschter um] LT', - lastWeek: function () { - switch (this.day()) { - case 2: - case 4: - return '[Leschten] dddd [um] LT'; - default: - return '[Leschte] dddd [um] LT'; - } - }, - }, - relativeTime: { - future: gy, - past: gp, - s: 'e puer Sekonnen', - m: ap, - mm: '%d Minutten', - h: ap, - hh: '%d Stonnen', - d: ap, - dd: '%d Deeg', - M: ap, - MM: '%d Méint', - y: ap, - yy: '%d Joer', - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('lo', { - months: 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), - monthsShort: 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), - weekdays: 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), - weekdaysShort: 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), - weekdaysMin: 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'ວັນdddd D MMMM YYYY HH:mm', - }, - meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/, - isPM: function (g5) { - return g5 === 'ຕອນແລງ'; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'ຕອນເຊົ້າ'; - } else { - return 'ຕອນແລງ'; - } - }, - calendar: { - sameDay: '[ມື້ນີ້ເວລາ] LT', - nextDay: '[ມື້ອື່ນເວລາ] LT', - nextWeek: '[ວັນ]dddd[ໜ້າເວລາ] LT', - lastDay: '[ມື້ວານນີ້ເວລາ] LT', - lastWeek: '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'ອີກ %s', - past: '%sຜ່ານມາ', - s: 'ບໍ່ເທົ່າໃດວິນາທີ', - m: '1 ນາທີ', - mm: '%d ນາທີ', - h: '1 ຊົ່ວໂມງ', - hh: '%d ຊົ່ວໂມງ', - d: '1 ມື້', - dd: '%d ມື້', - M: '1 ເດືອນ', - MM: '%d ເດືອນ', - y: '1 ປີ', - yy: '%d ປີ', - }, - dayOfMonthOrdinalParse: /(ທີ່)\d{1,2}/, - ordinal: function (g5) { - return 'ທີ່' + g5; - }, - }); - var e = { - m: 'minutė_minutės_minutę', - mm: 'minutės_minučių_minutes', - h: 'valanda_valandos_valandą', - hh: 'valandos_valandų_valandas', - d: 'diena_dienos_dieną', - dd: 'dienos_dienų_dienas', - M: 'mėnuo_mėnesio_mėnesį', - MM: 'mėnesiai_mėnesių_mėnesius', - y: 'metai_metų_metus', - yy: 'metai_metų_metus', - }; - function e4(g7, g6, g5, g8) { - if (g6) { - return 'kelios sekundės'; - } else { - return g8 ? 'kelių sekundžių' : 'kelias sekundes'; - } - } - function gd(g7, g6, g5, g8) { - return g6 ? aX(g5)[0] : g8 ? aX(g5)[1] : aX(g5)[2]; - } - function cq(g5) { - return g5 % 10 === 0 || (g5 > 10 && g5 < 20); - } - function aX(g5) { - return e[g5].split('_'); - } - function gU(g8, g7, g6, g9) { - var g5 = g8 + ' '; - if (g8 === 1) { - return g5 + gd(g8, g7, g6[0], g9); - } else { - if (g7) { - return g5 + (cq(g8) ? aX(g6)[1] : aX(g6)[0]); - } else { - if (g9) { - return g5 + aX(g6)[1]; - } else { - return g5 + (cq(g8) ? aX(g6)[1] : aX(g6)[2]); - } - } - } - } - gm.defineLocale('lt', { - months: { - format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split( - '_' - ), - standalone: - 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split( - '_' - ), - isFormat: /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/, - }, - monthsShort: 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'), - weekdays: { - format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'), - standalone: - 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'), - isFormat: /dddd HH:mm/, - }, - weekdaysShort: 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'), - weekdaysMin: 'S_P_A_T_K_Pn_Š'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY-MM-DD', - LL: 'YYYY [m.] MMMM D [d.]', - LLL: 'YYYY [m.] MMMM D [d.], HH:mm [val.]', - LLLL: 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]', - l: 'YYYY-MM-DD', - ll: 'YYYY [m.] MMMM D [d.]', - lll: 'YYYY [m.] MMMM D [d.], HH:mm [val.]', - llll: 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]', - }, - calendar: { - sameDay: '[Šiandien] LT', - nextDay: '[Rytoj] LT', - nextWeek: 'dddd LT', - lastDay: '[Vakar] LT', - lastWeek: '[Praėjusį] dddd LT', - sameElse: 'L', - }, - relativeTime: { - future: 'po %s', - past: 'prieš %s', - s: e4, - m: gd, - mm: gU, - h: gd, - hh: gU, - d: gd, - dd: gU, - M: gd, - MM: gU, - y: gd, - yy: gU, - }, - dayOfMonthOrdinalParse: /\d{1,2}-oji/, - ordinal: function (g5) { - return g5 + '-oji'; - }, - week: { dow: 1, doy: 4 }, - }); - var bK = { - m: 'minūtes_minūtēm_minūte_minūtes'.split('_'), - mm: 'minūtes_minūtēm_minūte_minūtes'.split('_'), - h: 'stundas_stundām_stunda_stundas'.split('_'), - hh: 'stundas_stundām_stunda_stundas'.split('_'), - d: 'dienas_dienām_diena_dienas'.split('_'), - dd: 'dienas_dienām_diena_dienas'.split('_'), - M: 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), - MM: 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), - y: 'gada_gadiem_gads_gadi'.split('_'), - yy: 'gada_gadiem_gads_gadi'.split('_'), - }; - function bf(g5, g7, g6) { - if (g6) { - return g7 % 10 === 1 && g7 % 100 !== 11 ? g5[2] : g5[3]; - } else { - return g7 % 10 === 1 && g7 % 100 !== 11 ? g5[0] : g5[1]; - } - } - function dJ(g7, g6, g5) { - return g7 + ' ' + bf(bK[g5], g7, g6); - } - function eq(g7, g6, g5) { - return bf(bK[g5], g7, g6); - } - function by(g6, g5) { - return g5 ? 'dažas sekundes' : 'dažām sekundēm'; - } - gm.defineLocale('lv', { - months: 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split( - '_' - ), - monthsShort: 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'), - weekdays: 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'), - weekdaysShort: 'Sv_P_O_T_C_Pk_S'.split('_'), - weekdaysMin: 'Sv_P_O_T_C_Pk_S'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY.', - LL: 'YYYY. [gada] D. MMMM', - LLL: 'YYYY. [gada] D. MMMM, HH:mm', - LLLL: 'YYYY. [gada] D. MMMM, dddd, HH:mm', - }, - calendar: { - sameDay: '[Šodien pulksten] LT', - nextDay: '[Rīt pulksten] LT', - nextWeek: 'dddd [pulksten] LT', - lastDay: '[Vakar pulksten] LT', - lastWeek: '[Pagājušā] dddd [pulksten] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'pēc %s', - past: 'pirms %s', - s: by, - m: eq, - mm: dJ, - h: eq, - hh: dJ, - d: eq, - dd: dJ, - M: eq, - MM: dJ, - y: eq, - yy: dJ, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - var f9 = { - words: { - m: ['jedan minut', 'jednog minuta'], - mm: ['minut', 'minuta', 'minuta'], - h: ['jedan sat', 'jednog sata'], - hh: ['sat', 'sata', 'sati'], - dd: ['dan', 'dana', 'dana'], - MM: ['mjesec', 'mjeseca', 'mjeseci'], - yy: ['godina', 'godine', 'godina'], - }, - correctGrammaticalCase: function (g6, g5) { - return g6 === 1 ? g5[0] : g6 >= 2 && g6 <= 4 ? g5[1] : g5[2]; - }, - translate: function (g8, g6, g5) { - var g7 = f9.words[g5]; - if (g5.length === 1) { - return g6 ? g7[0] : g7[1]; - } else { - return g8 + ' ' + f9.correctGrammaticalCase(g8, g7); - } - }, - }; - gm.defineLocale('me', { - months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), - monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), - weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), - weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[danas u] LT', - nextDay: '[sjutra u] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[u] [nedjelju] [u] LT'; - case 3: - return '[u] [srijedu] [u] LT'; - case 6: - return '[u] [subotu] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[u] dddd [u] LT'; - } - }, - lastDay: '[juče u] LT', - lastWeek: function () { - var g5 = [ - '[prošle] [nedjelje] [u] LT', - '[prošlog] [ponedjeljka] [u] LT', - '[prošlog] [utorka] [u] LT', - '[prošle] [srijede] [u] LT', - '[prošlog] [četvrtka] [u] LT', - '[prošlog] [petka] [u] LT', - '[prošle] [subote] [u] LT', - ]; - return g5[this.day()]; - }, - sameElse: 'L', - }, - relativeTime: { - future: 'za %s', - past: 'prije %s', - s: 'nekoliko sekundi', - m: f9.translate, - mm: f9.translate, - h: f9.translate, - hh: f9.translate, - d: 'dan', - dd: f9.translate, - M: 'mjesec', - MM: f9.translate, - y: 'godinu', - yy: f9.translate, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('mi', { - months: 'Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea'.split( - '_' - ), - monthsShort: 'Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki'.split('_'), - monthsRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, - monthsStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, - monthsShortRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, - monthsShortStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i, - weekdays: 'Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei'.split('_'), - weekdaysShort: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), - weekdaysMin: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY [i] HH:mm', - LLLL: 'dddd, D MMMM YYYY [i] HH:mm', - }, - calendar: { - sameDay: '[i teie mahana, i] LT', - nextDay: '[apopo i] LT', - nextWeek: 'dddd [i] LT', - lastDay: '[inanahi i] LT', - lastWeek: 'dddd [whakamutunga i] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'i roto i %s', - past: '%s i mua', - s: 'te hēkona ruarua', - m: 'he meneti', - mm: '%d meneti', - h: 'te haora', - hh: '%d haora', - d: 'he ra', - dd: '%d ra', - M: 'he marama', - MM: '%d marama', - y: 'he tau', - yy: '%d tau', - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal: '%dº', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('mk', { - months: 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'), - monthsShort: 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'), - weekdays: 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'), - weekdaysShort: 'нед_пон_вто_сре_чет_пет_саб'.split('_'), - weekdaysMin: 'нe_пo_вт_ср_че_пе_сa'.split('_'), - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'D.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY H:mm', - LLLL: 'dddd, D MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[Денес во] LT', - nextDay: '[Утре во] LT', - nextWeek: '[Во] dddd [во] LT', - lastDay: '[Вчера во] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - case 3: - case 6: - return '[Изминатата] dddd [во] LT'; - case 1: - case 2: - case 4: - case 5: - return '[Изминатиот] dddd [во] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'после %s', - past: 'пред %s', - s: 'неколку секунди', - m: 'минута', - mm: '%d минути', - h: 'час', - hh: '%d часа', - d: 'ден', - dd: '%d дена', - M: 'месец', - MM: '%d месеци', - y: 'година', - yy: '%d години', - }, - dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, - ordinal: function (g7) { - var g6 = g7 % 10, - g5 = g7 % 100; - if (g7 === 0) { - return g7 + '-ев'; - } else { - if (g5 === 0) { - return g7 + '-ен'; - } else { - if (g5 > 10 && g5 < 20) { - return g7 + '-ти'; - } else { - if (g6 === 1) { - return g7 + '-ви'; - } else { - if (g6 === 2) { - return g7 + '-ри'; - } else { - if (g6 === 7 || g6 === 8) { - return g7 + '-ми'; - } else { - return g7 + '-ти'; - } - } - } - } - } - } - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('ml', { - months: 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'), - monthsShort: 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'), - monthsParseExact: true, - weekdays: 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'), - weekdaysShort: 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'), - weekdaysMin: 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'), - longDateFormat: { - LT: 'A h:mm -നു', - LTS: 'A h:mm:ss -നു', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm -നു', - LLLL: 'dddd, D MMMM YYYY, A h:mm -നു', - }, - calendar: { - sameDay: '[ഇന്ന്] LT', - nextDay: '[നാളെ] LT', - nextWeek: 'dddd, LT', - lastDay: '[ഇന്നലെ] LT', - lastWeek: '[കഴിഞ്ഞ] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s കഴിഞ്ഞ്', - past: '%s മുൻപ്', - s: 'അൽപ നിമിഷങ്ങൾ', - m: 'ഒരു മിനിറ്റ്', - mm: '%d മിനിറ്റ്', - h: 'ഒരു മണിക്കൂർ', - hh: '%d മണിക്കൂർ', - d: 'ഒരു ദിവസം', - dd: '%d ദിവസം', - M: 'ഒരു മാസം', - MM: '%d മാസം', - y: 'ഒരു വർഷം', - yy: '%d വർഷം', - }, - meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if ((g6 === 'രാത്രി' && g5 >= 4) || g6 === 'ഉച്ച കഴിഞ്ഞ്' || g6 === 'വൈകുന്നേരം') { - return g5 + 12; - } else { - return g5; - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'രാത്രി'; - } else { - if (g5 < 12) { - return 'രാവിലെ'; - } else { - if (g5 < 17) { - return 'ഉച്ച കഴിഞ്ഞ്'; - } else { - if (g5 < 20) { - return 'വൈകുന്നേരം'; - } else { - return 'രാത്രി'; - } - } - } - } - }, - }); - var cY = { 1: '१', 2: '२', 3: '३', 4: '४', 5: '५', 6: '६', 7: '७', 8: '८', 9: '९', 0: '०' }; - var fQ = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; - function g3(g8, g7, g6, g9) { - var g5 = ''; - if (g7) { - switch (g6) { - case 's': - g5 = 'काही सेकंद'; - break; - case 'm': - g5 = 'एक मिनिट'; - break; - case 'mm': - g5 = '%d मिनिटे'; - break; - case 'h': - g5 = 'एक तास'; - break; - case 'hh': - g5 = '%d तास'; - break; - case 'd': - g5 = 'एक दिवस'; - break; - case 'dd': - g5 = '%d दिवस'; - break; - case 'M': - g5 = 'एक महिना'; - break; - case 'MM': - g5 = '%d महिने'; - break; - case 'y': - g5 = 'एक वर्ष'; - break; - case 'yy': - g5 = '%d वर्षे'; - break; - } - } else { - switch (g6) { - case 's': - g5 = 'काही सेकंदां'; - break; - case 'm': - g5 = 'एका मिनिटा'; - break; - case 'mm': - g5 = '%d मिनिटां'; - break; - case 'h': - g5 = 'एका तासा'; - break; - case 'hh': - g5 = '%d तासां'; - break; - case 'd': - g5 = 'एका दिवसा'; - break; - case 'dd': - g5 = '%d दिवसां'; - break; - case 'M': - g5 = 'एका महिन्या'; - break; - case 'MM': - g5 = '%d महिन्यां'; - break; - case 'y': - g5 = 'एका वर्षा'; - break; - case 'yy': - g5 = '%d वर्षां'; - break; - } - } - return g5.replace(/%d/i, g8); - } - gm.defineLocale('mr', { - months: 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'), - monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'), - monthsParseExact: true, - weekdays: 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), - weekdaysShort: 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'), - weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'), - longDateFormat: { - LT: 'A h:mm वाजता', - LTS: 'A h:mm:ss वाजता', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm वाजता', - LLLL: 'dddd, D MMMM YYYY, A h:mm वाजता', - }, - calendar: { - sameDay: '[आज] LT', - nextDay: '[उद्या] LT', - nextWeek: 'dddd, LT', - lastDay: '[काल] LT', - lastWeek: '[मागील] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%sमध्ये', - past: '%sपूर्वी', - s: g3, - m: g3, - mm: g3, - h: g3, - hh: g3, - d: g3, - dd: g3, - M: g3, - MM: g3, - y: g3, - yy: g3, - }, - preparse: function (g5) { - return g5.replace(/[१२३४५६७८९०]/g, function (g6) { - return fQ[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return cY[g6]; - }); - }, - meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'रात्री') { - return g5 < 4 ? g5 : g5 + 12; - } else { - if (g6 === 'सकाळी') { - return g5; - } else { - if (g6 === 'दुपारी') { - return g5 >= 10 ? g5 : g5 + 12; - } else { - if (g6 === 'सायंकाळी') { - return g5 + 12; - } - } - } - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'रात्री'; - } else { - if (g5 < 10) { - return 'सकाळी'; - } else { - if (g5 < 17) { - return 'दुपारी'; - } else { - if (g5 < 20) { - return 'सायंकाळी'; - } else { - return 'रात्री'; - } - } - } - } - }, - week: { dow: 0, doy: 6 }, - }); - gm.defineLocale('ms-my', { - months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), - monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), - weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), - weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), - weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), - longDateFormat: { - LT: 'HH.mm', - LTS: 'HH.mm.ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY [pukul] HH.mm', - LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', - }, - meridiemParse: /pagi|tengahari|petang|malam/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'pagi') { - return g5; - } else { - if (g6 === 'tengahari') { - return g5 >= 11 ? g5 : g5 + 12; - } else { - if (g6 === 'petang' || g6 === 'malam') { - return g5 + 12; - } - } - } - }, - meridiem: function (g5, g6, g7) { - if (g5 < 11) { - return 'pagi'; - } else { - if (g5 < 15) { - return 'tengahari'; - } else { - if (g5 < 19) { - return 'petang'; - } else { - return 'malam'; - } - } - } - }, - calendar: { - sameDay: '[Hari ini pukul] LT', - nextDay: '[Esok pukul] LT', - nextWeek: 'dddd [pukul] LT', - lastDay: '[Kelmarin pukul] LT', - lastWeek: 'dddd [lepas pukul] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'dalam %s', - past: '%s yang lepas', - s: 'beberapa saat', - m: 'seminit', - mm: '%d minit', - h: 'sejam', - hh: '%d jam', - d: 'sehari', - dd: '%d hari', - M: 'sebulan', - MM: '%d bulan', - y: 'setahun', - yy: '%d tahun', - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('ms', { - months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), - monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), - weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), - weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), - weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), - longDateFormat: { - LT: 'HH.mm', - LTS: 'HH.mm.ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY [pukul] HH.mm', - LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', - }, - meridiemParse: /pagi|tengahari|petang|malam/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'pagi') { - return g5; - } else { - if (g6 === 'tengahari') { - return g5 >= 11 ? g5 : g5 + 12; - } else { - if (g6 === 'petang' || g6 === 'malam') { - return g5 + 12; - } - } - } - }, - meridiem: function (g5, g6, g7) { - if (g5 < 11) { - return 'pagi'; - } else { - if (g5 < 15) { - return 'tengahari'; - } else { - if (g5 < 19) { - return 'petang'; - } else { - return 'malam'; - } - } - } - }, - calendar: { - sameDay: '[Hari ini pukul] LT', - nextDay: '[Esok pukul] LT', - nextWeek: 'dddd [pukul] LT', - lastDay: '[Kelmarin pukul] LT', - lastWeek: 'dddd [lepas pukul] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'dalam %s', - past: '%s yang lepas', - s: 'beberapa saat', - m: 'seminit', - mm: '%d minit', - h: 'sejam', - hh: '%d jam', - d: 'sehari', - dd: '%d hari', - M: 'sebulan', - MM: '%d bulan', - y: 'setahun', - yy: '%d tahun', - }, - week: { dow: 1, doy: 7 }, - }); - var cX = { 1: '၁', 2: '၂', 3: '၃', 4: '၄', 5: '၅', 6: '၆', 7: '၇', 8: '၈', 9: '၉', 0: '၀' }; - var fP = { '၁': '1', '၂': '2', '၃': '3', '၄': '4', '၅': '5', '၆': '6', '၇': '7', '၈': '8', '၉': '9', '၀': '0' }; - gm.defineLocale('my', { - months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'), - monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'), - weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'), - weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), - weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[ယနေ.] LT [မှာ]', - nextDay: '[မနက်ဖြန်] LT [မှာ]', - nextWeek: 'dddd LT [မှာ]', - lastDay: '[မနေ.က] LT [မှာ]', - lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]', - sameElse: 'L', - }, - relativeTime: { - future: 'လာမည့် %s မှာ', - past: 'လွန်ခဲ့သော %s က', - s: 'စက္ကန်.အနည်းငယ်', - m: 'တစ်မိနစ်', - mm: '%d မိနစ်', - h: 'တစ်နာရီ', - hh: '%d နာရီ', - d: 'တစ်ရက်', - dd: '%d ရက်', - M: 'တစ်လ', - MM: '%d လ', - y: 'တစ်နှစ်', - yy: '%d နှစ်', - }, - preparse: function (g5) { - return g5.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (g6) { - return fP[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return cX[g6]; - }); - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('nb', { - months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), - monthsShort: 'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'), - monthsParseExact: true, - weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), - weekdaysShort: 'sø._ma._ti._on._to._fr._lø.'.split('_'), - weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY [kl.] HH:mm', - LLLL: 'dddd D. MMMM YYYY [kl.] HH:mm', - }, - calendar: { - sameDay: '[i dag kl.] LT', - nextDay: '[i morgen kl.] LT', - nextWeek: 'dddd [kl.] LT', - lastDay: '[i går kl.] LT', - lastWeek: '[forrige] dddd [kl.] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'om %s', - past: '%s siden', - s: 'noen sekunder', - m: 'ett minutt', - mm: '%d minutter', - h: 'en time', - hh: '%d timer', - d: 'en dag', - dd: '%d dager', - M: 'en måned', - MM: '%d måneder', - y: 'ett år', - yy: '%d år', - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - var gL = { 1: '१', 2: '२', 3: '३', 4: '४', 5: '५', 6: '६', 7: '७', 8: '८', 9: '९', 0: '०' }; - var fO = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; - gm.defineLocale('ne', { - months: 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'), - monthsShort: 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'), - monthsParseExact: true, - weekdays: 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'), - weekdaysShort: 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'), - weekdaysMin: 'आ._सो._मं._बु._बि._शु._श.'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'Aको h:mm बजे', - LTS: 'Aको h:mm:ss बजे', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, Aको h:mm बजे', - LLLL: 'dddd, D MMMM YYYY, Aको h:mm बजे', - }, - preparse: function (g5) { - return g5.replace(/[१२३४५६७८९०]/g, function (g6) { - return fO[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return gL[g6]; - }); - }, - meridiemParse: /राति|बिहान|दिउँसो|साँझ/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'राति') { - return g5 < 4 ? g5 : g5 + 12; - } else { - if (g6 === 'बिहान') { - return g5; - } else { - if (g6 === 'दिउँसो') { - return g5 >= 10 ? g5 : g5 + 12; - } else { - if (g6 === 'साँझ') { - return g5 + 12; - } - } - } - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 3) { - return 'राति'; - } else { - if (g5 < 12) { - return 'बिहान'; - } else { - if (g5 < 16) { - return 'दिउँसो'; - } else { - if (g5 < 20) { - return 'साँझ'; - } else { - return 'राति'; - } - } - } - } - }, - calendar: { - sameDay: '[आज] LT', - nextDay: '[भोलि] LT', - nextWeek: '[आउँदो] dddd[,] LT', - lastDay: '[हिजो] LT', - lastWeek: '[गएको] dddd[,] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%sमा', - past: '%s अगाडि', - s: 'केही क्षण', - m: 'एक मिनेट', - mm: '%d मिनेट', - h: 'एक घण्टा', - hh: '%d घण्टा', - d: 'एक दिन', - dd: '%d दिन', - M: 'एक महिना', - MM: '%d महिना', - y: 'एक बर्ष', - yy: '%d बर्ष', - }, - week: { dow: 0, doy: 6 }, - }); - var dw = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'); - var dz = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); - var fv = [ - /^jan/i, - /^feb/i, - /^maart|mrt.?$/i, - /^apr/i, - /^mei$/i, - /^jun[i.]?$/i, - /^jul[i.]?$/i, - /^aug/i, - /^sep/i, - /^okt/i, - /^nov/i, - /^dec/i, - ]; - var fE = - /^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; - gm.defineLocale('nl-be', { - months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), - monthsShort: function (g5, g6) { - if (!g5) { - return dw; - } else { - if (/-MMM-/.test(g6)) { - return dz[g5.month()]; - } else { - return dw[g5.month()]; - } - } - }, - monthsRegex: fE, - monthsShortRegex: fE, - monthsStrictRegex: /^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i, - monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, - monthsParse: fv, - longMonthsParse: fv, - shortMonthsParse: fv, - weekdays: 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), - weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'), - weekdaysMin: 'Zo_Ma_Di_Wo_Do_Vr_Za'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[vandaag om] LT', - nextDay: '[morgen om] LT', - nextWeek: 'dddd [om] LT', - lastDay: '[gisteren om] LT', - lastWeek: '[afgelopen] dddd [om] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'over %s', - past: '%s geleden', - s: 'een paar seconden', - m: 'één minuut', - mm: '%d minuten', - h: 'één uur', - hh: '%d uur', - d: 'één dag', - dd: '%d dagen', - M: 'één maand', - MM: '%d maanden', - y: 'één jaar', - yy: '%d jaar', - }, - dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, - ordinal: function (g5) { - return g5 + (g5 === 1 || g5 === 8 || g5 >= 20 ? 'ste' : 'de'); - }, - week: { dow: 1, doy: 4 }, - }); - var dr = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'); - var dv = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); - var aC = [ - /^jan/i, - /^feb/i, - /^maart|mrt.?$/i, - /^apr/i, - /^mei$/i, - /^jun[i.]?$/i, - /^jul[i.]?$/i, - /^aug/i, - /^sep/i, - /^okt/i, - /^nov/i, - /^dec/i, - ]; - var fD = - /^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; - gm.defineLocale('nl', { - months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), - monthsShort: function (g5, g6) { - if (!g5) { - return dr; - } else { - if (/-MMM-/.test(g6)) { - return dv[g5.month()]; - } else { - return dr[g5.month()]; - } - } - }, - monthsRegex: fD, - monthsShortRegex: fD, - monthsStrictRegex: /^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i, - monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, - monthsParse: aC, - longMonthsParse: aC, - shortMonthsParse: aC, - weekdays: 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), - weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'), - weekdaysMin: 'Zo_Ma_Di_Wo_Do_Vr_Za'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD-MM-YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[vandaag om] LT', - nextDay: '[morgen om] LT', - nextWeek: 'dddd [om] LT', - lastDay: '[gisteren om] LT', - lastWeek: '[afgelopen] dddd [om] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'over %s', - past: '%s geleden', - s: 'een paar seconden', - m: 'één minuut', - mm: '%d minuten', - h: 'één uur', - hh: '%d uur', - d: 'één dag', - dd: '%d dagen', - M: 'één maand', - MM: '%d maanden', - y: 'één jaar', - yy: '%d jaar', - }, - dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, - ordinal: function (g5) { - return g5 + (g5 === 1 || g5 === 8 || g5 >= 20 ? 'ste' : 'de'); - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('nn', { - months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), - monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), - weekdays: 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'), - weekdaysShort: 'sun_mån_tys_ons_tor_fre_lau'.split('_'), - weekdaysMin: 'su_må_ty_on_to_fr_lø'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY [kl.] H:mm', - LLLL: 'dddd D. MMMM YYYY [kl.] HH:mm', - }, - calendar: { - sameDay: '[I dag klokka] LT', - nextDay: '[I morgon klokka] LT', - nextWeek: 'dddd [klokka] LT', - lastDay: '[I går klokka] LT', - lastWeek: '[Føregåande] dddd [klokka] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'om %s', - past: '%s sidan', - s: 'nokre sekund', - m: 'eit minutt', - mm: '%d minutt', - h: 'ein time', - hh: '%d timar', - d: 'ein dag', - dd: '%d dagar', - M: 'ein månad', - MM: '%d månader', - y: 'eit år', - yy: '%d år', - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - var gK = { 1: '੧', 2: '੨', 3: '੩', 4: '੪', 5: '੫', 6: '੬', 7: '੭', 8: '੮', 9: '੯', 0: '੦' }; - var cb = { '੧': '1', '੨': '2', '੩': '3', '੪': '4', '੫': '5', '੬': '6', '੭': '7', '੮': '8', '੯': '9', '੦': '0' }; - gm.defineLocale('pa-in', { - months: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), - monthsShort: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), - weekdays: 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'), - weekdaysShort: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), - weekdaysMin: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), - longDateFormat: { - LT: 'A h:mm ਵਜੇ', - LTS: 'A h:mm:ss ਵਜੇ', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm ਵਜੇ', - LLLL: 'dddd, D MMMM YYYY, A h:mm ਵਜੇ', - }, - calendar: { - sameDay: '[ਅਜ] LT', - nextDay: '[ਕਲ] LT', - nextWeek: 'dddd, LT', - lastDay: '[ਕਲ] LT', - lastWeek: '[ਪਿਛਲੇ] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s ਵਿੱਚ', - past: '%s ਪਿਛਲੇ', - s: 'ਕੁਝ ਸਕਿੰਟ', - m: 'ਇਕ ਮਿੰਟ', - mm: '%d ਮਿੰਟ', - h: 'ਇੱਕ ਘੰਟਾ', - hh: '%d ਘੰਟੇ', - d: 'ਇੱਕ ਦਿਨ', - dd: '%d ਦਿਨ', - M: 'ਇੱਕ ਮਹੀਨਾ', - MM: '%d ਮਹੀਨੇ', - y: 'ਇੱਕ ਸਾਲ', - yy: '%d ਸਾਲ', - }, - preparse: function (g5) { - return g5.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (g6) { - return cb[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return gK[g6]; - }); - }, - meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'ਰਾਤ') { - return g5 < 4 ? g5 : g5 + 12; - } else { - if (g6 === 'ਸਵੇਰ') { - return g5; - } else { - if (g6 === 'ਦੁਪਹਿਰ') { - return g5 >= 10 ? g5 : g5 + 12; - } else { - if (g6 === 'ਸ਼ਾਮ') { - return g5 + 12; - } - } - } - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'ਰਾਤ'; - } else { - if (g5 < 10) { - return 'ਸਵੇਰ'; - } else { - if (g5 < 17) { - return 'ਦੁਪਹਿਰ'; - } else { - if (g5 < 20) { - return 'ਸ਼ਾਮ'; - } else { - return 'ਰਾਤ'; - } - } - } - } - }, - week: { dow: 0, doy: 6 }, - }); - var cw = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split( - '_' - ); - var ay = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split( - '_' - ); - function cE(g5) { - return g5 % 10 < 5 && g5 % 10 > 1 && ~~(g5 / 10) % 10 !== 1; - } - function gS(g8, g7, g6) { - var g5 = g8 + ' '; - switch (g6) { - case 'm': - return g7 ? 'minuta' : 'minutę'; - case 'mm': - return g5 + (cE(g8) ? 'minuty' : 'minut'); - case 'h': - return g7 ? 'godzina' : 'godzinę'; - case 'hh': - return g5 + (cE(g8) ? 'godziny' : 'godzin'); - case 'MM': - return g5 + (cE(g8) ? 'miesiące' : 'miesięcy'); - case 'yy': - return g5 + (cE(g8) ? 'lata' : 'lat'); - } - } - gm.defineLocale('pl', { - months: function (g6, g5) { - if (!g6) { - return cw; - } else { - if (g5 === '') { - return '(' + ay[g6.month()] + '|' + cw[g6.month()] + ')'; - } else { - if (/D MMMM/.test(g5)) { - return ay[g6.month()]; - } else { - return cw[g6.month()]; - } - } - } - }, - monthsShort: 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'), - weekdays: 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'), - weekdaysShort: 'ndz_pon_wt_śr_czw_pt_sob'.split('_'), - weekdaysMin: 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Dziś o] LT', - nextDay: '[Jutro o] LT', - nextWeek: '[W] dddd [o] LT', - lastDay: '[Wczoraj o] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[W zeszłą niedzielę o] LT'; - case 3: - return '[W zeszłą środę o] LT'; - case 6: - return '[W zeszłą sobotę o] LT'; - default: - return '[W zeszły] dddd [o] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'za %s', - past: '%s temu', - s: 'kilka sekund', - m: gS, - mm: gS, - h: gS, - hh: gS, - d: '1 dzień', - dd: '%d dni', - M: 'miesiąc', - MM: gS, - y: 'rok', - yy: gS, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('pt-br', { - months: 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), - monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), - weekdays: 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'), - weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), - weekdaysMin: 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D [de] MMMM [de] YYYY', - LLL: 'D [de] MMMM [de] YYYY [às] HH:mm', - LLLL: 'dddd, D [de] MMMM [de] YYYY [às] HH:mm', - }, - calendar: { - sameDay: '[Hoje às] LT', - nextDay: '[Amanhã às] LT', - nextWeek: 'dddd [às] LT', - lastDay: '[Ontem às] LT', - lastWeek: function () { - return this.day() === 0 || this.day() === 6 ? '[Último] dddd [às] LT' : '[Última] dddd [às] LT'; - }, - sameElse: 'L', - }, - relativeTime: { - future: 'em %s', - past: '%s atrás', - s: 'poucos segundos', - m: 'um minuto', - mm: '%d minutos', - h: 'uma hora', - hh: '%d horas', - d: 'um dia', - dd: '%d dias', - M: 'um mês', - MM: '%d meses', - y: 'um ano', - yy: '%d anos', - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal: '%dº', - }); - gm.defineLocale('pt', { - months: 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), - monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), - weekdays: 'Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado'.split('_'), - weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), - weekdaysMin: 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D [de] MMMM [de] YYYY', - LLL: 'D [de] MMMM [de] YYYY HH:mm', - LLLL: 'dddd, D [de] MMMM [de] YYYY HH:mm', - }, - calendar: { - sameDay: '[Hoje às] LT', - nextDay: '[Amanhã às] LT', - nextWeek: 'dddd [às] LT', - lastDay: '[Ontem às] LT', - lastWeek: function () { - return this.day() === 0 || this.day() === 6 ? '[Último] dddd [às] LT' : '[Última] dddd [às] LT'; - }, - sameElse: 'L', - }, - relativeTime: { - future: 'em %s', - past: 'há %s', - s: 'segundos', - m: 'um minuto', - mm: '%d minutos', - h: 'uma hora', - hh: '%d horas', - d: 'um dia', - dd: '%d dias', - M: 'um mês', - MM: '%d meses', - y: 'um ano', - yy: '%d anos', - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal: '%dº', - week: { dow: 1, doy: 4 }, - }); - function dI(g7, g6, g5) { - var g9 = { mm: 'minute', hh: 'ore', dd: 'zile', MM: 'luni', yy: 'ani' }, - g8 = ' '; - if (g7 % 100 >= 20 || (g7 >= 100 && g7 % 100 === 0)) { - g8 = ' de '; - } - return g7 + g8 + g9[g5]; - } - gm.defineLocale('ro', { - months: 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split( - '_' - ), - monthsShort: 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays: 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'), - weekdaysShort: 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'), - weekdaysMin: 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'), - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY H:mm', - LLLL: 'dddd, D MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[azi la] LT', - nextDay: '[mâine la] LT', - nextWeek: 'dddd [la] LT', - lastDay: '[ieri la] LT', - lastWeek: '[fosta] dddd [la] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'peste %s', - past: '%s în urmă', - s: 'câteva secunde', - m: 'un minut', - mm: dI, - h: 'o oră', - hh: dI, - d: 'o zi', - dd: dI, - M: 'o lună', - MM: dI, - y: 'un an', - yy: dI, - }, - week: { dow: 1, doy: 7 }, - }); - function cC(g7, g6) { - var g5 = g7.split('_'); - return g6 % 10 === 1 && g6 % 100 !== 11 - ? g5[0] - : g6 % 10 >= 2 && g6 % 10 <= 4 && (g6 % 100 < 10 || g6 % 100 >= 20) - ? g5[1] - : g5[2]; - } - function dG(g7, g6, g5) { - var g8 = { - mm: g6 ? 'минута_минуты_минут' : 'минуту_минуты_минут', - hh: 'час_часа_часов', - dd: 'день_дня_дней', - MM: 'месяц_месяца_месяцев', - yy: 'год_года_лет', - }; - if (g5 === 'm') { - return g6 ? 'минута' : 'минуту'; - } else { - return g7 + ' ' + cC(g8[g5], +g7); - } - } - var aB = [ - /^янв/i, - /^фев/i, - /^мар/i, - /^апр/i, - /^ма[йя]/i, - /^июн/i, - /^июл/i, - /^авг/i, - /^сен/i, - /^окт/i, - /^ноя/i, - /^дек/i, - ]; - gm.defineLocale('ru', { - months: { - format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'), - standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), - }, - monthsShort: { - format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'), - standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_'), - }, - weekdays: { - standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), - format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'), - isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/, - }, - weekdaysShort: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), - weekdaysMin: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), - monthsParse: aB, - longMonthsParse: aB, - shortMonthsParse: aB, - monthsRegex: - /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, - monthsShortRegex: - /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, - monthsStrictRegex: - /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, - monthsShortStrictRegex: - /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY г.', - LLL: 'D MMMM YYYY г., HH:mm', - LLLL: 'dddd, D MMMM YYYY г., HH:mm', - }, - calendar: { - sameDay: '[Сегодня в] LT', - nextDay: '[Завтра в] LT', - lastDay: '[Вчера в] LT', - nextWeek: function (g5) { - if (g5.week() !== this.week()) { - switch (this.day()) { - case 0: - return '[В следующее] dddd [в] LT'; - case 1: - case 2: - case 4: - return '[В следующий] dddd [в] LT'; - case 3: - case 5: - case 6: - return '[В следующую] dddd [в] LT'; - } - } else { - if (this.day() === 2) { - return '[Во] dddd [в] LT'; - } else { - return '[В] dddd [в] LT'; - } - } - }, - lastWeek: function (g5) { - if (g5.week() !== this.week()) { - switch (this.day()) { - case 0: - return '[В прошлое] dddd [в] LT'; - case 1: - case 2: - case 4: - return '[В прошлый] dddd [в] LT'; - case 3: - case 5: - case 6: - return '[В прошлую] dddd [в] LT'; - } - } else { - if (this.day() === 2) { - return '[Во] dddd [в] LT'; - } else { - return '[В] dddd [в] LT'; - } - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'через %s', - past: '%s назад', - s: 'несколько секунд', - m: dG, - mm: dG, - h: 'час', - hh: dG, - d: 'день', - dd: dG, - M: 'месяц', - MM: dG, - y: 'год', - yy: dG, - }, - meridiemParse: /ночи|утра|дня|вечера/i, - isPM: function (g5) { - return /^(дня|вечера)$/.test(g5); - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'ночи'; - } else { - if (g5 < 12) { - return 'утра'; - } else { - if (g5 < 17) { - return 'дня'; - } else { - return 'вечера'; - } - } - } - }, - dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'M': - case 'd': - case 'DDD': - return g5 + '-й'; - case 'D': - return g5 + '-го'; - case 'w': - case 'W': - return g5 + '-я'; - default: - return g5; - } - }, - week: { dow: 1, doy: 7 }, - }); - var ev = [ - 'جنوري', - 'فيبروري', - 'مارچ', - 'اپريل', - 'مئي', - 'جون', - 'جولاءِ', - 'آگسٽ', - 'سيپٽمبر', - 'آڪٽوبر', - 'نومبر', - 'ڊسمبر', - ]; - var q = ['آچر', 'سومر', 'اڱارو', 'اربع', 'خميس', 'جمع', 'ڇنڇر']; - gm.defineLocale('sd', { - months: ev, - monthsShort: ev, - weekdays: q, - weekdaysShort: q, - weekdaysMin: q, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd، D MMMM YYYY HH:mm', - }, - meridiemParse: /صبح|شام/, - isPM: function (g5) { - return 'شام' === g5; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'صبح'; - } - return 'شام'; - }, - calendar: { - sameDay: '[اڄ] LT', - nextDay: '[سڀاڻي] LT', - nextWeek: 'dddd [اڳين هفتي تي] LT', - lastDay: '[ڪالهه] LT', - lastWeek: '[گزريل هفتي] dddd [تي] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s پوء', - past: '%s اڳ', - s: 'چند سيڪنڊ', - m: 'هڪ منٽ', - mm: '%d منٽ', - h: 'هڪ ڪلاڪ', - hh: '%d ڪلاڪ', - d: 'هڪ ڏينهن', - dd: '%d ڏينهن', - M: 'هڪ مهينو', - MM: '%d مهينا', - y: 'هڪ سال', - yy: '%d سال', - }, - preparse: function (g5) { - return g5.replace(/،/g, ','); - }, - postformat: function (g5) { - return g5.replace(/,/g, '،'); - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('se', { - months: 'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split( - '_' - ), - monthsShort: 'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'), - weekdays: 'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split('_'), - weekdaysShort: 'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'), - weekdaysMin: 's_v_m_g_d_b_L'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'MMMM D. [b.] YYYY', - LLL: 'MMMM D. [b.] YYYY [ti.] HH:mm', - LLLL: 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm', - }, - calendar: { - sameDay: '[otne ti] LT', - nextDay: '[ihttin ti] LT', - nextWeek: 'dddd [ti] LT', - lastDay: '[ikte ti] LT', - lastWeek: '[ovddit] dddd [ti] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s geažes', - past: 'maŋit %s', - s: 'moadde sekunddat', - m: 'okta minuhta', - mm: '%d minuhtat', - h: 'okta diimmu', - hh: '%d diimmut', - d: 'okta beaivi', - dd: '%d beaivvit', - M: 'okta mánnu', - MM: '%d mánut', - y: 'okta jahki', - yy: '%d jagit', - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('si', { - months: 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split( - '_' - ), - monthsShort: 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'), - weekdays: 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'), - weekdaysShort: 'ඉරි_සඳු_අඟ_බදා_බ්රහ_සිකු_සෙන'.split('_'), - weekdaysMin: 'ඉ_ස_අ_බ_බ්ර_සි_සෙ'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'a h:mm', - LTS: 'a h:mm:ss', - L: 'YYYY/MM/DD', - LL: 'YYYY MMMM D', - LLL: 'YYYY MMMM D, a h:mm', - LLLL: 'YYYY MMMM D [වැනි] dddd, a h:mm:ss', - }, - calendar: { - sameDay: '[අද] LT[ට]', - nextDay: '[හෙට] LT[ට]', - nextWeek: 'dddd LT[ට]', - lastDay: '[ඊයේ] LT[ට]', - lastWeek: '[පසුගිය] dddd LT[ට]', - sameElse: 'L', - }, - relativeTime: { - future: '%sකින්', - past: '%sකට පෙර', - s: 'තත්පර කිහිපය', - m: 'මිනිත්තුව', - mm: 'මිනිත්තු %d', - h: 'පැය', - hh: 'පැය %d', - d: 'දිනය', - dd: 'දින %d', - M: 'මාසය', - MM: 'මාස %d', - y: 'වසර', - yy: 'වසර %d', - }, - dayOfMonthOrdinalParse: /\d{1,2} වැනි/, - ordinal: function (g5) { - return g5 + ' වැනි'; - }, - meridiemParse: /පෙර වරු|පස් වරු|පෙ.ව|ප.ව./, - isPM: function (g5) { - return g5 === 'ප.ව.' || g5 === 'පස් වරු'; - }, - meridiem: function (g5, g6, g7) { - if (g5 > 11) { - return g7 ? 'ප.ව.' : 'පස් වරු'; - } else { - return g7 ? 'පෙ.ව.' : 'පෙර වරු'; - } - }, - }); - var eu = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'); - var db = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_'); - function cB(g5) { - return g5 > 1 && g5 < 5; - } - function gQ(g8, g7, g6, g9) { - var g5 = g8 + ' '; - switch (g6) { - case 's': - return g7 || g9 ? 'pár sekúnd' : 'pár sekundami'; - case 'm': - return g7 ? 'minúta' : g9 ? 'minútu' : 'minútou'; - case 'mm': - if (g7 || g9) { - return g5 + (cB(g8) ? 'minúty' : 'minút'); - } else { - return g5 + 'minútami'; - } - break; - case 'h': - return g7 ? 'hodina' : g9 ? 'hodinu' : 'hodinou'; - case 'hh': - if (g7 || g9) { - return g5 + (cB(g8) ? 'hodiny' : 'hodín'); - } else { - return g5 + 'hodinami'; - } - break; - case 'd': - return g7 || g9 ? 'deň' : 'dňom'; - case 'dd': - if (g7 || g9) { - return g5 + (cB(g8) ? 'dni' : 'dní'); - } else { - return g5 + 'dňami'; - } - break; - case 'M': - return g7 || g9 ? 'mesiac' : 'mesiacom'; - case 'MM': - if (g7 || g9) { - return g5 + (cB(g8) ? 'mesiace' : 'mesiacov'); - } else { - return g5 + 'mesiacmi'; - } - break; - case 'y': - return g7 || g9 ? 'rok' : 'rokom'; - case 'yy': - if (g7 || g9) { - return g5 + (cB(g8) ? 'roky' : 'rokov'); - } else { - return g5 + 'rokmi'; - } - break; - } - } - gm.defineLocale('sk', { - months: eu, - monthsShort: db, - weekdays: 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'), - weekdaysShort: 'ne_po_ut_st_št_pi_so'.split('_'), - weekdaysMin: 'ne_po_ut_st_št_pi_so'.split('_'), - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd D. MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[dnes o] LT', - nextDay: '[zajtra o] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[v nedeľu o] LT'; - case 1: - case 2: - return '[v] dddd [o] LT'; - case 3: - return '[v stredu o] LT'; - case 4: - return '[vo štvrtok o] LT'; - case 5: - return '[v piatok o] LT'; - case 6: - return '[v sobotu o] LT'; - } - }, - lastDay: '[včera o] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[minulú nedeľu o] LT'; - case 1: - case 2: - return '[minulý] dddd [o] LT'; - case 3: - return '[minulú stredu o] LT'; - case 4: - case 5: - return '[minulý] dddd [o] LT'; - case 6: - return '[minulú sobotu o] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'za %s', - past: 'pred %s', - s: gQ, - m: gQ, - mm: gQ, - h: gQ, - hh: gQ, - d: gQ, - dd: gQ, - M: gQ, - MM: gQ, - y: gQ, - yy: gQ, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - function ao(g8, g7, g6, g9) { - var g5 = g8 + ' '; - switch (g6) { - case 's': - return g7 || g9 ? 'nekaj sekund' : 'nekaj sekundami'; - case 'm': - return g7 ? 'ena minuta' : 'eno minuto'; - case 'mm': - if (g8 === 1) { - g5 += g7 ? 'minuta' : 'minuto'; - } else { - if (g8 === 2) { - g5 += g7 || g9 ? 'minuti' : 'minutama'; - } else { - if (g8 < 5) { - g5 += g7 || g9 ? 'minute' : 'minutami'; - } else { - g5 += g7 || g9 ? 'minut' : 'minutami'; - } - } - } - return g5; - case 'h': - return g7 ? 'ena ura' : 'eno uro'; - case 'hh': - if (g8 === 1) { - g5 += g7 ? 'ura' : 'uro'; - } else { - if (g8 === 2) { - g5 += g7 || g9 ? 'uri' : 'urama'; - } else { - if (g8 < 5) { - g5 += g7 || g9 ? 'ure' : 'urami'; - } else { - g5 += g7 || g9 ? 'ur' : 'urami'; - } - } - } - return g5; - case 'd': - return g7 || g9 ? 'en dan' : 'enim dnem'; - case 'dd': - if (g8 === 1) { - g5 += g7 || g9 ? 'dan' : 'dnem'; - } else { - if (g8 === 2) { - g5 += g7 || g9 ? 'dni' : 'dnevoma'; - } else { - g5 += g7 || g9 ? 'dni' : 'dnevi'; - } - } - return g5; - case 'M': - return g7 || g9 ? 'en mesec' : 'enim mesecem'; - case 'MM': - if (g8 === 1) { - g5 += g7 || g9 ? 'mesec' : 'mesecem'; - } else { - if (g8 === 2) { - g5 += g7 || g9 ? 'meseca' : 'mesecema'; - } else { - if (g8 < 5) { - g5 += g7 || g9 ? 'mesece' : 'meseci'; - } else { - g5 += g7 || g9 ? 'mesecev' : 'meseci'; - } - } - } - return g5; - case 'y': - return g7 || g9 ? 'eno leto' : 'enim letom'; - case 'yy': - if (g8 === 1) { - g5 += g7 || g9 ? 'leto' : 'letom'; - } else { - if (g8 === 2) { - g5 += g7 || g9 ? 'leti' : 'letoma'; - } else { - if (g8 < 5) { - g5 += g7 || g9 ? 'leta' : 'leti'; - } else { - g5 += g7 || g9 ? 'let' : 'leti'; - } - } - } - return g5; - } - } - gm.defineLocale('sl', { - months: 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'), - monthsShort: 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays: 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'), - weekdaysShort: 'ned._pon._tor._sre._čet._pet._sob.'.split('_'), - weekdaysMin: 'ne_po_to_sr_če_pe_so'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[danes ob] LT', - nextDay: '[jutri ob] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[v] [nedeljo] [ob] LT'; - case 3: - return '[v] [sredo] [ob] LT'; - case 6: - return '[v] [soboto] [ob] LT'; - case 1: - case 2: - case 4: - case 5: - return '[v] dddd [ob] LT'; - } - }, - lastDay: '[včeraj ob] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[prejšnjo] [nedeljo] [ob] LT'; - case 3: - return '[prejšnjo] [sredo] [ob] LT'; - case 6: - return '[prejšnjo] [soboto] [ob] LT'; - case 1: - case 2: - case 4: - case 5: - return '[prejšnji] dddd [ob] LT'; - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'čez %s', - past: 'pred %s', - s: ao, - m: ao, - mm: ao, - h: ao, - hh: ao, - d: ao, - dd: ao, - M: ao, - MM: ao, - y: ao, - yy: ao, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('sq', { - months: 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'), - monthsShort: 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'), - weekdays: 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'), - weekdaysShort: 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'), - weekdaysMin: 'D_H_Ma_Më_E_P_Sh'.split('_'), - weekdaysParseExact: true, - meridiemParse: /PD|MD/, - isPM: function (g5) { - return g5.charAt(0) === 'M'; - }, - meridiem: function (g5, g6, g7) { - return g5 < 12 ? 'PD' : 'MD'; - }, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Sot në] LT', - nextDay: '[Nesër në] LT', - nextWeek: 'dddd [në] LT', - lastDay: '[Dje në] LT', - lastWeek: 'dddd [e kaluar në] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'në %s', - past: '%s më parë', - s: 'disa sekonda', - m: 'një minutë', - mm: '%d minuta', - h: 'një orë', - hh: '%d orë', - d: 'një ditë', - dd: '%d ditë', - M: 'një muaj', - MM: '%d muaj', - y: 'një vit', - yy: '%d vite', - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - var cF = { - words: { - m: ['један минут', 'једне минуте'], - mm: ['минут', 'минуте', 'минута'], - h: ['један сат', 'једног сата'], - hh: ['сат', 'сата', 'сати'], - dd: ['дан', 'дана', 'дана'], - MM: ['месец', 'месеца', 'месеци'], - yy: ['година', 'године', 'година'], - }, - correctGrammaticalCase: function (g6, g5) { - return g6 === 1 ? g5[0] : g6 >= 2 && g6 <= 4 ? g5[1] : g5[2]; - }, - translate: function (g8, g6, g5) { - var g7 = cF.words[g5]; - if (g5.length === 1) { - return g6 ? g7[0] : g7[1]; - } else { - return g8 + ' ' + cF.correctGrammaticalCase(g8, g7); - } - }, - }; - gm.defineLocale('sr-cyrl', { - months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'), - monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'), - monthsParseExact: true, - weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'), - weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'), - weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[данас у] LT', - nextDay: '[сутра у] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[у] [недељу] [у] LT'; - case 3: - return '[у] [среду] [у] LT'; - case 6: - return '[у] [суботу] [у] LT'; - case 1: - case 2: - case 4: - case 5: - return '[у] dddd [у] LT'; - } - }, - lastDay: '[јуче у] LT', - lastWeek: function () { - var g5 = [ - '[прошле] [недеље] [у] LT', - '[прошлог] [понедељка] [у] LT', - '[прошлог] [уторка] [у] LT', - '[прошле] [среде] [у] LT', - '[прошлог] [четвртка] [у] LT', - '[прошлог] [петка] [у] LT', - '[прошле] [суботе] [у] LT', - ]; - return g5[this.day()]; - }, - sameElse: 'L', - }, - relativeTime: { - future: 'за %s', - past: 'пре %s', - s: 'неколико секунди', - m: cF.translate, - mm: cF.translate, - h: cF.translate, - hh: cF.translate, - d: 'дан', - dd: cF.translate, - M: 'месец', - MM: cF.translate, - y: 'годину', - yy: cF.translate, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 7 }, - }); - var cD = { - words: { - m: ['jedan minut', 'jedne minute'], - mm: ['minut', 'minute', 'minuta'], - h: ['jedan sat', 'jednog sata'], - hh: ['sat', 'sata', 'sati'], - dd: ['dan', 'dana', 'dana'], - MM: ['mesec', 'meseca', 'meseci'], - yy: ['godina', 'godine', 'godina'], - }, - correctGrammaticalCase: function (g6, g5) { - return g6 === 1 ? g5[0] : g6 >= 2 && g6 <= 4 ? g5[1] : g5[2]; - }, - translate: function (g8, g6, g5) { - var g7 = cD.words[g5]; - if (g5.length === 1) { - return g6 ? g7[0] : g7[1]; - } else { - return g8 + ' ' + cD.correctGrammaticalCase(g8, g7); - } - }, - }; - gm.defineLocale('sr', { - months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), - monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays: 'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split('_'), - weekdaysShort: 'ned._pon._uto._sre._čet._pet._sub.'.split('_'), - weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm', - }, - calendar: { - sameDay: '[danas u] LT', - nextDay: '[sutra u] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[u] [nedelju] [u] LT'; - case 3: - return '[u] [sredu] [u] LT'; - case 6: - return '[u] [subotu] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[u] dddd [u] LT'; - } - }, - lastDay: '[juče u] LT', - lastWeek: function () { - var g5 = [ - '[prošle] [nedelje] [u] LT', - '[prošlog] [ponedeljka] [u] LT', - '[prošlog] [utorka] [u] LT', - '[prošle] [srede] [u] LT', - '[prošlog] [četvrtka] [u] LT', - '[prošlog] [petka] [u] LT', - '[prošle] [subote] [u] LT', - ]; - return g5[this.day()]; - }, - sameElse: 'L', - }, - relativeTime: { - future: 'za %s', - past: 'pre %s', - s: 'nekoliko sekundi', - m: cD.translate, - mm: cD.translate, - h: cD.translate, - hh: cD.translate, - d: 'dan', - dd: cD.translate, - M: 'mesec', - MM: cD.translate, - y: 'godinu', - yy: cD.translate, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('ss', { - months: "Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split( - '_' - ), - monthsShort: 'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'), - weekdays: 'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split('_'), - weekdaysShort: 'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'), - weekdaysMin: 'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'h:mm A', - LTS: 'h:mm:ss A', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY h:mm A', - LLLL: 'dddd, D MMMM YYYY h:mm A', - }, - calendar: { - sameDay: '[Namuhla nga] LT', - nextDay: '[Kusasa nga] LT', - nextWeek: 'dddd [nga] LT', - lastDay: '[Itolo nga] LT', - lastWeek: 'dddd [leliphelile] [nga] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'nga %s', - past: 'wenteka nga %s', - s: 'emizuzwana lomcane', - m: 'umzuzu', - mm: '%d emizuzu', - h: 'lihora', - hh: '%d emahora', - d: 'lilanga', - dd: '%d emalanga', - M: 'inyanga', - MM: '%d tinyanga', - y: 'umnyaka', - yy: '%d iminyaka', - }, - meridiemParse: /ekuseni|emini|entsambama|ebusuku/, - meridiem: function (g5, g6, g7) { - if (g5 < 11) { - return 'ekuseni'; - } else { - if (g5 < 15) { - return 'emini'; - } else { - if (g5 < 19) { - return 'entsambama'; - } else { - return 'ebusuku'; - } - } - } - }, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'ekuseni') { - return g5; - } else { - if (g6 === 'emini') { - return g5 >= 11 ? g5 : g5 + 12; - } else { - if (g6 === 'entsambama' || g6 === 'ebusuku') { - if (g5 === 0) { - return 0; - } - return g5 + 12; - } - } - } - }, - dayOfMonthOrdinalParse: /\d{1,2}/, - ordinal: '%d', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('sv', { - months: 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'), - monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), - weekdays: 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'), - weekdaysShort: 'sön_mån_tis_ons_tor_fre_lör'.split('_'), - weekdaysMin: 'sö_må_ti_on_to_fr_lö'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY-MM-DD', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY [kl.] HH:mm', - LLLL: 'dddd D MMMM YYYY [kl.] HH:mm', - lll: 'D MMM YYYY HH:mm', - llll: 'ddd D MMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Idag] LT', - nextDay: '[Imorgon] LT', - lastDay: '[Igår] LT', - nextWeek: '[På] dddd LT', - lastWeek: '[I] dddd[s] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'om %s', - past: 'för %s sedan', - s: 'några sekunder', - m: 'en minut', - mm: '%d minuter', - h: 'en timme', - hh: '%d timmar', - d: 'en dag', - dd: '%d dagar', - M: 'en månad', - MM: '%d månader', - y: 'ett år', - yy: '%d år', - }, - dayOfMonthOrdinalParse: /\d{1,2}(e|a)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = ~~((g7 % 100) / 10) === 1 ? 'e' : g5 === 1 ? 'a' : g5 === 2 ? 'a' : g5 === 3 ? 'e' : 'e'; - return g7 + g6; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('sw', { - months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'), - monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), - weekdays: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), - weekdaysShort: 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'), - weekdaysMin: 'J2_J3_J4_J5_Al_Ij_J1'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[leo saa] LT', - nextDay: '[kesho saa] LT', - nextWeek: '[wiki ijayo] dddd [saat] LT', - lastDay: '[jana] LT', - lastWeek: '[wiki iliyopita] dddd [saat] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s baadaye', - past: 'tokea %s', - s: 'hivi punde', - m: 'dakika moja', - mm: 'dakika %d', - h: 'saa limoja', - hh: 'masaa %d', - d: 'siku moja', - dd: 'masiku %d', - M: 'mwezi mmoja', - MM: 'miezi %d', - y: 'mwaka mmoja', - yy: 'miaka %d', - }, - week: { dow: 1, doy: 7 }, - }); - var gI = { 1: '௧', 2: '௨', 3: '௩', 4: '௪', 5: '௫', 6: '௬', 7: '௭', 8: '௮', 9: '௯', 0: '௦' }; - var ca = { '௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5', '௬': '6', '௭': '7', '௮': '8', '௯': '9', '௦': '0' }; - gm.defineLocale('ta', { - months: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), - monthsShort: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split( - '_' - ), - weekdays: 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split( - '_' - ), - weekdaysShort: 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'), - weekdaysMin: 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, HH:mm', - LLLL: 'dddd, D MMMM YYYY, HH:mm', - }, - calendar: { - sameDay: '[இன்று] LT', - nextDay: '[நாளை] LT', - nextWeek: 'dddd, LT', - lastDay: '[நேற்று] LT', - lastWeek: '[கடந்த வாரம்] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s இல்', - past: '%s முன்', - s: 'ஒரு சில விநாடிகள்', - m: 'ஒரு நிமிடம்', - mm: '%d நிமிடங்கள்', - h: 'ஒரு மணி நேரம்', - hh: '%d மணி நேரம்', - d: 'ஒரு நாள்', - dd: '%d நாட்கள்', - M: 'ஒரு மாதம்', - MM: '%d மாதங்கள்', - y: 'ஒரு வருடம்', - yy: '%d ஆண்டுகள்', - }, - dayOfMonthOrdinalParse: /\d{1,2}வது/, - ordinal: function (g5) { - return g5 + 'வது'; - }, - preparse: function (g5) { - return g5.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (g6) { - return ca[g6]; - }); - }, - postformat: function (g5) { - return g5.replace(/\d/g, function (g6) { - return gI[g6]; - }); - }, - meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/, - meridiem: function (g5, g7, g6) { - if (g5 < 2) { - return ' யாமம்'; - } else { - if (g5 < 6) { - return ' வைகறை'; - } else { - if (g5 < 10) { - return ' காலை'; - } else { - if (g5 < 14) { - return ' நண்பகல்'; - } else { - if (g5 < 18) { - return ' எற்பாடு'; - } else { - if (g5 < 22) { - return ' மாலை'; - } else { - return ' யாமம்'; - } - } - } - } - } - } - }, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'யாமம்') { - return g5 < 2 ? g5 : g5 + 12; - } else { - if (g6 === 'வைகறை' || g6 === 'காலை') { - return g5; - } else { - if (g6 === 'நண்பகல்') { - return g5 >= 10 ? g5 : g5 + 12; - } else { - return g5 + 12; - } - } - } - }, - week: { dow: 0, doy: 6 }, - }); - gm.defineLocale('te', { - months: 'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జూలై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split('_'), - monthsShort: 'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జూలై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split('_'), - monthsParseExact: true, - weekdays: 'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split('_'), - weekdaysShort: 'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'), - weekdaysMin: 'ఆ_సో_మం_బు_గు_శు_శ'.split('_'), - longDateFormat: { - LT: 'A h:mm', - LTS: 'A h:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm', - LLLL: 'dddd, D MMMM YYYY, A h:mm', - }, - calendar: { - sameDay: '[నేడు] LT', - nextDay: '[రేపు] LT', - nextWeek: 'dddd, LT', - lastDay: '[నిన్న] LT', - lastWeek: '[గత] dddd, LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s లో', - past: '%s క్రితం', - s: 'కొన్ని క్షణాలు', - m: 'ఒక నిమిషం', - mm: '%d నిమిషాలు', - h: 'ఒక గంట', - hh: '%d గంటలు', - d: 'ఒక రోజు', - dd: '%d రోజులు', - M: 'ఒక నెల', - MM: '%d నెలలు', - y: 'ఒక సంవత్సరం', - yy: '%d సంవత్సరాలు', - }, - dayOfMonthOrdinalParse: /\d{1,2}వ/, - ordinal: '%dవ', - meridiemParse: /రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === 'రాత్రి') { - return g5 < 4 ? g5 : g5 + 12; - } else { - if (g6 === 'ఉదయం') { - return g5; - } else { - if (g6 === 'మధ్యాహ్నం') { - return g5 >= 10 ? g5 : g5 + 12; - } else { - if (g6 === 'సాయంత్రం') { - return g5 + 12; - } - } - } - } - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'రాత్రి'; - } else { - if (g5 < 10) { - return 'ఉదయం'; - } else { - if (g5 < 17) { - return 'మధ్యాహ్నం'; - } else { - if (g5 < 20) { - return 'సాయంత్రం'; - } else { - return 'రాత్రి'; - } - } - } - } - }, - week: { dow: 0, doy: 6 }, - }); - gm.defineLocale('tet', { - months: 'Janeiru_Fevereiru_Marsu_Abril_Maiu_Juniu_Juliu_Augustu_Setembru_Outubru_Novembru_Dezembru'.split('_'), - monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Aug_Set_Out_Nov_Dez'.split('_'), - weekdays: 'Domingu_Segunda_Tersa_Kuarta_Kinta_Sexta_Sabadu'.split('_'), - weekdaysShort: 'Dom_Seg_Ters_Kua_Kint_Sext_Sab'.split('_'), - weekdaysMin: 'Do_Seg_Te_Ku_Ki_Sex_Sa'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Ohin iha] LT', - nextDay: '[Aban iha] LT', - nextWeek: 'dddd [iha] LT', - lastDay: '[Horiseik iha] LT', - lastWeek: 'dddd [semana kotuk] [iha] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'iha %s', - past: '%s liuba', - s: 'minutu balun', - m: 'minutu ida', - mm: 'minutus %d', - h: 'horas ida', - hh: 'horas %d', - d: 'loron ida', - dd: 'loron %d', - M: 'fulan ida', - MM: 'fulan %d', - y: 'tinan ida', - yy: 'tinan %d', - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = ~~((g7 % 100) / 10) === 1 ? 'th' : g5 === 1 ? 'st' : g5 === 2 ? 'nd' : g5 === 3 ? 'rd' : 'th'; - return g7 + g6; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('th', { - months: 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split( - '_' - ), - monthsShort: 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'), - monthsParseExact: true, - weekdays: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'), - weekdaysShort: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), - weekdaysMin: 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'H:mm', - LTS: 'H:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY เวลา H:mm', - LLLL: 'วันddddที่ D MMMM YYYY เวลา H:mm', - }, - meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/, - isPM: function (g5) { - return g5 === 'หลังเที่ยง'; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'ก่อนเที่ยง'; - } else { - return 'หลังเที่ยง'; - } - }, - calendar: { - sameDay: '[วันนี้ เวลา] LT', - nextDay: '[พรุ่งนี้ เวลา] LT', - nextWeek: 'dddd[หน้า เวลา] LT', - lastDay: '[เมื่อวานนี้ เวลา] LT', - lastWeek: '[วัน]dddd[ที่แล้ว เวลา] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'อีก %s', - past: '%sที่แล้ว', - s: 'ไม่กี่วินาที', - m: '1 นาที', - mm: '%d นาที', - h: '1 ชั่วโมง', - hh: '%d ชั่วโมง', - d: '1 วัน', - dd: '%d วัน', - M: '1 เดือน', - MM: '%d เดือน', - y: '1 ปี', - yy: '%d ปี', - }, - }); - gm.defineLocale('tl-ph', { - months: 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'), - monthsShort: 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'), - weekdays: 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'), - weekdaysShort: 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'), - weekdaysMin: 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'MM/D/YYYY', - LL: 'MMMM D, YYYY', - LLL: 'MMMM D, YYYY HH:mm', - LLLL: 'dddd, MMMM DD, YYYY HH:mm', - }, - calendar: { - sameDay: 'LT [ngayong araw]', - nextDay: '[Bukas ng] LT', - nextWeek: 'LT [sa susunod na] dddd', - lastDay: 'LT [kahapon]', - lastWeek: 'LT [noong nakaraang] dddd', - sameElse: 'L', - }, - relativeTime: { - future: 'sa loob ng %s', - past: '%s ang nakalipas', - s: 'ilang segundo', - m: 'isang minuto', - mm: '%d minuto', - h: 'isang oras', - hh: '%d oras', - d: 'isang araw', - dd: '%d araw', - M: 'isang buwan', - MM: '%d buwan', - y: 'isang taon', - yy: '%d taon', - }, - dayOfMonthOrdinalParse: /\d{1,2}/, - ordinal: function (g5) { - return g5; - }, - week: { dow: 1, doy: 4 }, - }); - var ab = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_'); - function gk(g5) { - var g6 = g5; - g6 = - g5.indexOf('jaj') !== -1 - ? g6.slice(0, -3) + 'leS' - : g5.indexOf('jar') !== -1 - ? g6.slice(0, -3) + 'waQ' - : g5.indexOf('DIS') !== -1 - ? g6.slice(0, -3) + 'nem' - : g6 + ' pIq'; - return g6; - } - function gW(g5) { - var g6 = g5; - g6 = - g5.indexOf('jaj') !== -1 - ? g6.slice(0, -3) + 'Hu’' - : g5.indexOf('jar') !== -1 - ? g6.slice(0, -3) + 'wen' - : g5.indexOf('DIS') !== -1 - ? g6.slice(0, -3) + 'ben' - : g6 + ' ret'; - return g6; - } - function gP(g8, g7, g6, g9) { - var g5 = ey(g8); - switch (g6) { - case 'mm': - return g5 + ' tup'; - case 'hh': - return g5 + ' rep'; - case 'dd': - return g5 + ' jaj'; - case 'MM': - return g5 + ' jar'; - case 'yy': - return g5 + ' DIS'; - } - } - function ey(g7) { - var g9 = Math.floor((g7 % 1000) / 100), - g5 = Math.floor((g7 % 100) / 10), - g6 = g7 % 10, - g8 = ''; - if (g9 > 0) { - g8 += ab[g9] + 'vatlh'; - } - if (g5 > 0) { - g8 += (g8 !== '' ? ' ' : '') + ab[g5] + 'maH'; - } - if (g6 > 0) { - g8 += (g8 !== '' ? ' ' : '') + ab[g6]; - } - return g8 === '' ? 'pagh' : g8; - } - gm.defineLocale('tlh', { - months: 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split( - '_' - ), - monthsShort: - 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split( - '_' - ), - monthsParseExact: true, - weekdays: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), - weekdaysShort: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), - weekdaysMin: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[DaHjaj] LT', - nextDay: '[wa’leS] LT', - nextWeek: 'LLL', - lastDay: '[wa’Hu’] LT', - lastWeek: 'LLL', - sameElse: 'L', - }, - relativeTime: { - future: gk, - past: gW, - s: 'puS lup', - m: 'wa’ tup', - mm: gP, - h: 'wa’ rep', - hh: gP, - d: 'wa’ jaj', - dd: gP, - M: 'wa’ jar', - MM: gP, - y: 'wa’ DIS', - yy: gP, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - var j = { - 1: "'inci", - 5: "'inci", - 8: "'inci", - 70: "'inci", - 80: "'inci", - 2: "'nci", - 7: "'nci", - 20: "'nci", - 50: "'nci", - 3: "'üncü", - 4: "'üncü", - 100: "'üncü", - 6: "'ncı", - 9: "'uncu", - 10: "'uncu", - 30: "'uncu", - 60: "'ıncı", - 90: "'ıncı", - }; - gm.defineLocale('tr', { - months: 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'), - monthsShort: 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'), - weekdays: 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'), - weekdaysShort: 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'), - weekdaysMin: 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[bugün saat] LT', - nextDay: '[yarın saat] LT', - nextWeek: '[haftaya] dddd [saat] LT', - lastDay: '[dün] LT', - lastWeek: '[geçen hafta] dddd [saat] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s sonra', - past: '%s önce', - s: 'birkaç saniye', - m: 'bir dakika', - mm: '%d dakika', - h: 'bir saat', - hh: '%d saat', - d: 'bir gün', - dd: '%d gün', - M: 'bir ay', - MM: '%d ay', - y: 'bir yıl', - yy: '%d yıl', - }, - dayOfMonthOrdinalParse: /\d{1,2}'(inci|nci|üncü|ncı|uncu|ıncı)/, - ordinal: function (g7) { - if (g7 === 0) { - return g7 + "'ıncı"; - } - var g6 = g7 % 10, - g5 = (g7 % 100) - g6, - g8 = g7 >= 100 ? 100 : null; - return g7 + (j[g6] || j[g5] || j[g8]); - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('tzl', { - months: 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'), - monthsShort: 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'), - weekdays: 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'), - weekdaysShort: 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'), - weekdaysMin: 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'), - longDateFormat: { - LT: 'HH.mm', - LTS: 'HH.mm.ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM [dallas] YYYY', - LLL: 'D. MMMM [dallas] YYYY HH.mm', - LLLL: 'dddd, [li] D. MMMM [dallas] YYYY HH.mm', - }, - meridiemParse: /d\'o|d\'a/i, - isPM: function (g5) { - return "d'o" === g5.toLowerCase(); - }, - meridiem: function (g5, g6, g7) { - if (g5 > 11) { - return g7 ? "d'o" : "D'O"; - } else { - return g7 ? "d'a" : "D'A"; - } - }, - calendar: { - sameDay: '[oxhi à] LT', - nextDay: '[demà à] LT', - nextWeek: 'dddd [à] LT', - lastDay: '[ieiri à] LT', - lastWeek: '[sür el] dddd [lasteu à] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'osprei %s', - past: 'ja%s', - s: am, - m: am, - mm: am, - h: am, - hh: am, - d: am, - dd: am, - M: am, - MM: am, - y: am, - yy: am, - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { dow: 1, doy: 4 }, - }); - function am(g7, g6, g5, g9) { - var g8 = { - s: ['viensas secunds', "'iensas secunds"], - m: ["'n míut", "'iens míut"], - mm: [g7 + ' míuts', '' + g7 + ' míuts'], - h: ["'n þora", "'iensa þora"], - hh: [g7 + ' þoras', '' + g7 + ' þoras'], - d: ["'n ziua", "'iensa ziua"], - dd: [g7 + ' ziuas', '' + g7 + ' ziuas'], - M: ["'n mes", "'iens mes"], - MM: [g7 + ' mesen', '' + g7 + ' mesen'], - y: ["'n ar", "'iens ar"], - yy: [g7 + ' ars', '' + g7 + ' ars'], - }; - return g9 ? g8[g5][0] : g6 ? g8[g5][0] : g8[g5][1]; - } - gm.defineLocale('tzm-latn', { - months: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), - monthsShort: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), - weekdays: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), - weekdaysShort: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), - weekdaysMin: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[asdkh g] LT', - nextDay: '[aska g] LT', - nextWeek: 'dddd [g] LT', - lastDay: '[assant g] LT', - lastWeek: 'dddd [g] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'dadkh s yan %s', - past: 'yan %s', - s: 'imik', - m: 'minuḍ', - mm: '%d minuḍ', - h: 'saɛa', - hh: '%d tassaɛin', - d: 'ass', - dd: '%d ossan', - M: 'ayowr', - MM: '%d iyyirn', - y: 'asgas', - yy: '%d isgasn', - }, - week: { dow: 6, doy: 12 }, - }); - gm.defineLocale('tzm', { - months: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), - monthsShort: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), - weekdays: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), - weekdaysShort: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), - weekdaysMin: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[ⴰⵙⴷⵅ ⴴ] LT', - nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', - nextWeek: 'dddd [ⴴ] LT', - lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', - lastWeek: 'dddd [ⴴ] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s', - past: 'ⵢⴰⵏ %s', - s: 'ⵉⵎⵉⴽ', - m: 'ⵎⵉⵏⵓⴺ', - mm: '%d ⵎⵉⵏⵓⴺ', - h: 'ⵙⴰⵄⴰ', - hh: '%d ⵜⴰⵙⵙⴰⵄⵉⵏ', - d: 'ⴰⵙⵙ', - dd: '%d oⵙⵙⴰⵏ', - M: 'ⴰⵢoⵓⵔ', - MM: '%d ⵉⵢⵢⵉⵔⵏ', - y: 'ⴰⵙⴳⴰⵙ', - yy: '%d ⵉⵙⴳⴰⵙⵏ', - }, - week: { dow: 6, doy: 12 }, - }); - function cA(g7, g6) { - var g5 = g7.split('_'); - return g6 % 10 === 1 && g6 % 100 !== 11 - ? g5[0] - : g6 % 10 >= 2 && g6 % 10 <= 4 && (g6 % 100 < 10 || g6 % 100 >= 20) - ? g5[1] - : g5[2]; - } - function dF(g7, g6, g5) { - var g8 = { - mm: g6 ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин', - hh: g6 ? 'година_години_годин' : 'годину_години_годин', - dd: 'день_дні_днів', - MM: 'місяць_місяці_місяців', - yy: 'рік_роки_років', - }; - if (g5 === 'm') { - return g6 ? 'хвилина' : 'хвилину'; - } else { - if (g5 === 'h') { - return g6 ? 'година' : 'годину'; - } else { - return g7 + ' ' + cA(g8[g5], +g7); - } - } - } - function bS(g5, g8) { - var g6 = { - nominative: 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), - accusative: 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), - genitive: 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_'), - }; - if (!g5) { - return g6.nominative; - } - var g7 = /(\[[ВвУу]\]) ?dddd/.test(g8) - ? 'accusative' - : /\[?(?:минулої|наступної)? ?\] ?dddd/.test(g8) - ? 'genitive' - : 'nominative'; - return g6[g7][g5.day()]; - } - function aW(g5) { - return function () { - return g5 + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; - }; - } - gm.defineLocale('uk', { - months: { - format: 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_'), - standalone: - 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split( - '_' - ), - }, - monthsShort: 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'), - weekdays: bS, - weekdaysShort: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), - weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D MMMM YYYY р.', - LLL: 'D MMMM YYYY р., HH:mm', - LLLL: 'dddd, D MMMM YYYY р., HH:mm', - }, - calendar: { - sameDay: aW('[Сьогодні '), - nextDay: aW('[Завтра '), - lastDay: aW('[Вчора '), - nextWeek: aW('[У] dddd ['), - lastWeek: function () { - switch (this.day()) { - case 0: - case 3: - case 5: - case 6: - return aW('[Минулої] dddd [').call(this); - case 1: - case 2: - case 4: - return aW('[Минулого] dddd [').call(this); - } - }, - sameElse: 'L', - }, - relativeTime: { - future: 'за %s', - past: '%s тому', - s: 'декілька секунд', - m: dF, - mm: dF, - h: 'годину', - hh: dF, - d: 'день', - dd: dF, - M: 'місяць', - MM: dF, - y: 'рік', - yy: dF, - }, - meridiemParse: /ночі|ранку|дня|вечора/, - isPM: function (g5) { - return /^(дня|вечора)$/.test(g5); - }, - meridiem: function (g5, g7, g6) { - if (g5 < 4) { - return 'ночі'; - } else { - if (g5 < 12) { - return 'ранку'; - } else { - if (g5 < 17) { - return 'дня'; - } else { - return 'вечора'; - } - } - } - }, - dayOfMonthOrdinalParse: /\d{1,2}-(й|го)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'M': - case 'd': - case 'DDD': - case 'w': - case 'W': - return g5 + '-й'; - case 'D': - return g5 + '-го'; - default: - return g5; - } - }, - week: { dow: 1, doy: 7 }, - }); - var es = ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر']; - var m = ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ']; - gm.defineLocale('ur', { - months: es, - monthsShort: es, - weekdays: m, - weekdaysShort: m, - weekdaysMin: m, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd، D MMMM YYYY HH:mm', - }, - meridiemParse: /صبح|شام/, - isPM: function (g5) { - return 'شام' === g5; - }, - meridiem: function (g5, g7, g6) { - if (g5 < 12) { - return 'صبح'; - } - return 'شام'; - }, - calendar: { - sameDay: '[آج بوقت] LT', - nextDay: '[کل بوقت] LT', - nextWeek: 'dddd [بوقت] LT', - lastDay: '[گذشتہ روز بوقت] LT', - lastWeek: '[گذشتہ] dddd [بوقت] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s بعد', - past: '%s قبل', - s: 'چند سیکنڈ', - m: 'ایک منٹ', - mm: '%d منٹ', - h: 'ایک گھنٹہ', - hh: '%d گھنٹے', - d: 'ایک دن', - dd: '%d دن', - M: 'ایک ماہ', - MM: '%d ماہ', - y: 'ایک سال', - yy: '%d سال', - }, - preparse: function (g5) { - return g5.replace(/،/g, ','); - }, - postformat: function (g5) { - return g5.replace(/,/g, '،'); - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('uz-latn', { - months: 'Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr'.split('_'), - monthsShort: 'Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek'.split('_'), - weekdays: 'Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba'.split('_'), - weekdaysShort: 'Yak_Dush_Sesh_Chor_Pay_Jum_Shan'.split('_'), - weekdaysMin: 'Ya_Du_Se_Cho_Pa_Ju_Sha'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'D MMMM YYYY, dddd HH:mm', - }, - calendar: { - sameDay: '[Bugun soat] LT [da]', - nextDay: '[Ertaga] LT [da]', - nextWeek: 'dddd [kuni soat] LT [da]', - lastDay: '[Kecha soat] LT [da]', - lastWeek: "[O'tgan] dddd [kuni soat] LT [da]", - sameElse: 'L', - }, - relativeTime: { - future: 'Yaqin %s ichida', - past: 'Bir necha %s oldin', - s: 'soniya', - m: 'bir daqiqa', - mm: '%d daqiqa', - h: 'bir soat', - hh: '%d soat', - d: 'bir kun', - dd: '%d kun', - M: 'bir oy', - MM: '%d oy', - y: 'bir yil', - yy: '%d yil', - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('uz', { - months: 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'), - monthsShort: 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), - weekdays: 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'), - weekdaysShort: 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'), - weekdaysMin: 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'D MMMM YYYY, dddd HH:mm', - }, - calendar: { - sameDay: '[Бугун соат] LT [да]', - nextDay: '[Эртага] LT [да]', - nextWeek: 'dddd [куни соат] LT [да]', - lastDay: '[Кеча соат] LT [да]', - lastWeek: '[Утган] dddd [куни соат] LT [да]', - sameElse: 'L', - }, - relativeTime: { - future: 'Якин %s ичида', - past: 'Бир неча %s олдин', - s: 'фурсат', - m: 'бир дакика', - mm: '%d дакика', - h: 'бир соат', - hh: '%d соат', - d: 'бир кун', - dd: '%d кун', - M: 'бир ой', - MM: '%d ой', - y: 'бир йил', - yy: '%d йил', - }, - week: { dow: 1, doy: 7 }, - }); - gm.defineLocale('vi', { - months: 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split( - '_' - ), - monthsShort: 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'), - monthsParseExact: true, - weekdays: 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'), - weekdaysShort: 'CN_T2_T3_T4_T5_T6_T7'.split('_'), - weekdaysMin: 'CN_T2_T3_T4_T5_T6_T7'.split('_'), - weekdaysParseExact: true, - meridiemParse: /sa|ch/i, - isPM: function (g5) { - return /^ch$/i.test(g5); - }, - meridiem: function (g5, g6, g7) { - if (g5 < 12) { - return g7 ? 'sa' : 'SA'; - } else { - return g7 ? 'ch' : 'CH'; - } - }, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM [năm] YYYY', - LLL: 'D MMMM [năm] YYYY HH:mm', - LLLL: 'dddd, D MMMM [năm] YYYY HH:mm', - l: 'DD/M/YYYY', - ll: 'D MMM YYYY', - lll: 'D MMM YYYY HH:mm', - llll: 'ddd, D MMM YYYY HH:mm', - }, - calendar: { - sameDay: '[Hôm nay lúc] LT', - nextDay: '[Ngày mai lúc] LT', - nextWeek: 'dddd [tuần tới lúc] LT', - lastDay: '[Hôm qua lúc] LT', - lastWeek: 'dddd [tuần rồi lúc] LT', - sameElse: 'L', - }, - relativeTime: { - future: '%s tới', - past: '%s trước', - s: 'vài giây', - m: 'một phút', - mm: '%d phút', - h: 'một giờ', - hh: '%d giờ', - d: 'một ngày', - dd: '%d ngày', - M: 'một tháng', - MM: '%d tháng', - y: 'một năm', - yy: '%d năm', - }, - dayOfMonthOrdinalParse: /\d{1,2}/, - ordinal: function (g5) { - return g5; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('x-pseudo', { - months: 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split( - '_' - ), - monthsShort: 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'), - monthsParseExact: true, - weekdays: 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'), - weekdaysShort: 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'), - weekdaysMin: 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm', - }, - calendar: { - sameDay: '[T~ódá~ý át] LT', - nextDay: '[T~ómó~rró~w át] LT', - nextWeek: 'dddd [át] LT', - lastDay: '[Ý~ést~érdá~ý át] LT', - lastWeek: '[L~ást] dddd [át] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'í~ñ %s', - past: '%s á~gó', - s: 'á ~féw ~sécó~ñds', - m: 'á ~míñ~úté', - mm: '%d m~íñú~tés', - h: 'á~ñ hó~úr', - hh: '%d h~óúrs', - d: 'á ~dáý', - dd: '%d d~áýs', - M: 'á ~móñ~th', - MM: '%d m~óñt~hs', - y: 'á ~ýéár', - yy: '%d ý~éárs', - }, - dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal: function (g7) { - var g5 = g7 % 10, - g6 = ~~((g7 % 100) / 10) === 1 ? 'th' : g5 === 1 ? 'st' : g5 === 2 ? 'nd' : g5 === 3 ? 'rd' : 'th'; - return g7 + g6; - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('yo', { - months: 'Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀'.split('_'), - monthsShort: 'Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀'.split('_'), - weekdays: 'Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta'.split('_'), - weekdaysShort: 'Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá'.split('_'), - weekdaysMin: 'Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb'.split('_'), - longDateFormat: { - LT: 'h:mm A', - LTS: 'h:mm:ss A', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY h:mm A', - LLLL: 'dddd, D MMMM YYYY h:mm A', - }, - calendar: { - sameDay: '[Ònì ni] LT', - nextDay: '[Ọ̀la ni] LT', - nextWeek: "dddd [Ọsẹ̀ tón'bọ] [ni] LT", - lastDay: '[Àna ni] LT', - lastWeek: 'dddd [Ọsẹ̀ tólọ́] [ni] LT', - sameElse: 'L', - }, - relativeTime: { - future: 'ní %s', - past: '%s kọjá', - s: 'ìsẹjú aayá die', - m: 'ìsẹjú kan', - mm: 'ìsẹjú %d', - h: 'wákati kan', - hh: 'wákati %d', - d: 'ọjọ́ kan', - dd: 'ọjọ́ %d', - M: 'osù kan', - MM: 'osù %d', - y: 'ọdún kan', - yy: 'ọdún %d', - }, - dayOfMonthOrdinalParse: /ọjọ́\s\d{1,2}/, - ordinal: 'ọjọ́ %d', - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('zh-cn', { - months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), - monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), - weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'), - weekdaysMin: '日_一_二_三_四_五_六'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY年MMMD日', - LL: 'YYYY年MMMD日', - LLL: 'YYYY年MMMD日Ah点mm分', - LLLL: 'YYYY年MMMD日ddddAh点mm分', - l: 'YYYY年MMMD日', - ll: 'YYYY年MMMD日', - lll: 'YYYY年MMMD日 HH:mm', - llll: 'YYYY年MMMD日dddd HH:mm', - }, - meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === '凌晨' || g6 === '早上' || g6 === '上午') { - return g5; - } else { - if (g6 === '下午' || g6 === '晚上') { - return g5 + 12; - } else { - return g5 >= 11 ? g5 : g5 + 12; - } - } - }, - meridiem: function (g5, g7, g6) { - var g8 = g5 * 100 + g7; - if (g8 < 600) { - return '凌晨'; - } else { - if (g8 < 900) { - return '早上'; - } else { - if (g8 < 1130) { - return '上午'; - } else { - if (g8 < 1230) { - return '中午'; - } else { - if (g8 < 1800) { - return '下午'; - } else { - return '晚上'; - } - } - } - } - } - }, - calendar: { - sameDay: '[今天]LT', - nextDay: '[明天]LT', - nextWeek: '[下]ddddLT', - lastDay: '[昨天]LT', - lastWeek: '[上]ddddLT', - sameElse: 'L', - }, - dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'd': - case 'D': - case 'DDD': - return g5 + '日'; - case 'M': - return g5 + '月'; - case 'w': - case 'W': - return g5 + '周'; - default: - return g5; - } - }, - relativeTime: { - future: '%s内', - past: '%s前', - s: '几秒', - m: '1 分钟', - mm: '%d 分钟', - h: '1 小时', - hh: '%d 小时', - d: '1 天', - dd: '%d 天', - M: '1 个月', - MM: '%d 个月', - y: '1 年', - yy: '%d 年', - }, - week: { dow: 1, doy: 4 }, - }); - gm.defineLocale('zh-hk', { - months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), - monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), - weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'), - weekdaysMin: '日_一_二_三_四_五_六'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY年MMMD日', - LL: 'YYYY年MMMD日', - LLL: 'YYYY年MMMD日 HH:mm', - LLLL: 'YYYY年MMMD日dddd HH:mm', - l: 'YYYY年MMMD日', - ll: 'YYYY年MMMD日', - lll: 'YYYY年MMMD日 HH:mm', - llll: 'YYYY年MMMD日dddd HH:mm', - }, - meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === '凌晨' || g6 === '早上' || g6 === '上午') { - return g5; - } else { - if (g6 === '中午') { - return g5 >= 11 ? g5 : g5 + 12; - } else { - if (g6 === '下午' || g6 === '晚上') { - return g5 + 12; - } - } - } - }, - meridiem: function (g5, g7, g6) { - var g8 = g5 * 100 + g7; - if (g8 < 600) { - return '凌晨'; - } else { - if (g8 < 900) { - return '早上'; - } else { - if (g8 < 1130) { - return '上午'; - } else { - if (g8 < 1230) { - return '中午'; - } else { - if (g8 < 1800) { - return '下午'; - } else { - return '晚上'; - } - } - } - } - } - }, - calendar: { - sameDay: '[今天]LT', - nextDay: '[明天]LT', - nextWeek: '[下]ddddLT', - lastDay: '[昨天]LT', - lastWeek: '[上]ddddLT', - sameElse: 'L', - }, - dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'd': - case 'D': - case 'DDD': - return g5 + '日'; - case 'M': - return g5 + '月'; - case 'w': - case 'W': - return g5 + '週'; - default: - return g5; - } - }, - relativeTime: { - future: '%s內', - past: '%s前', - s: '幾秒', - m: '1 分鐘', - mm: '%d 分鐘', - h: '1 小時', - hh: '%d 小時', - d: '1 天', - dd: '%d 天', - M: '1 個月', - MM: '%d 個月', - y: '1 年', - yy: '%d 年', - }, - }); - gm.defineLocale('zh-tw', { - months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), - monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), - weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'), - weekdaysMin: '日_一_二_三_四_五_六'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY年MMMD日', - LL: 'YYYY年MMMD日', - LLL: 'YYYY年MMMD日 HH:mm', - LLLL: 'YYYY年MMMD日dddd HH:mm', - l: 'YYYY年MMMD日', - ll: 'YYYY年MMMD日', - lll: 'YYYY年MMMD日 HH:mm', - llll: 'YYYY年MMMD日dddd HH:mm', - }, - meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, - meridiemHour: function (g5, g6) { - if (g5 === 12) { - g5 = 0; - } - if (g6 === '凌晨' || g6 === '早上' || g6 === '上午') { - return g5; - } else { - if (g6 === '中午') { - return g5 >= 11 ? g5 : g5 + 12; - } else { - if (g6 === '下午' || g6 === '晚上') { - return g5 + 12; - } - } - } - }, - meridiem: function (g5, g7, g6) { - var g8 = g5 * 100 + g7; - if (g8 < 600) { - return '凌晨'; - } else { - if (g8 < 900) { - return '早上'; - } else { - if (g8 < 1130) { - return '上午'; - } else { - if (g8 < 1230) { - return '中午'; - } else { - if (g8 < 1800) { - return '下午'; - } else { - return '晚上'; - } - } - } - } - } - }, - calendar: { - sameDay: '[今天]LT', - nextDay: '[明天]LT', - nextWeek: '[下]ddddLT', - lastDay: '[昨天]LT', - lastWeek: '[上]ddddLT', - sameElse: 'L', - }, - dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, - ordinal: function (g5, g6) { - switch (g6) { - case 'd': - case 'D': - case 'DDD': - return g5 + '日'; - case 'M': - return g5 + '月'; - case 'w': - case 'W': - return g5 + '週'; - default: - return g5; - } - }, - relativeTime: { - future: '%s內', - past: '%s前', - s: '幾秒', - m: '1 分鐘', - mm: '%d 分鐘', - h: '1 小時', - hh: '%d 小時', - d: '1 天', - dd: '%d 天', - M: '1 個月', - MM: '%d 個月', - y: '1 年', - yy: '%d 年', - }, - }); - gm.locale('en'); - return gm; -}); -var LZString = (function () { - var c = String.fromCharCode; - var g = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - var b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$'; - var e = {}; - function a(j, h) { - if (!e[j]) { - e[j] = {}; - for (var f = 0; f < j.length; f++) { - e[j][j.charAt(f)] = f; - } - } - return e[j][h]; - } - var d = { - compressToBase64: function (f) { - if (f == null) { - return ''; - } - var h = d._compress(f, 6, function (i) { - return g.charAt(i); - }); - switch (h.length % 4) { - default: - case 0: - return h; - case 1: - return h + '==='; - case 2: - return h + '=='; - case 3: - return h + '='; - } - }, - decompressFromBase64: function (f) { - if (f == null) { - return ''; - } - if (f == '') { - return null; - } - return d._decompress(f.length, 32, function (h) { - return a(g, f.charAt(h)); - }); - }, - compressToUTF16: function (f) { - if (f == null) { - return ''; - } - return ( - d._compress(f, 15, function (h) { - return c(h + 32); - }) + ' ' - ); - }, - decompressFromUTF16: function (f) { - if (f == null) { - return ''; - } - if (f == '') { - return null; - } - return d._decompress(f.length, 16384, function (h) { - return f.charCodeAt(h) - 32; - }); - }, - compressToUint8Array: function (n) { - var m = d.compress(n); - var h = new Uint8Array(m.length * 2); - for (var l = 0, j = m.length; l < j; l++) { - var f = m.charCodeAt(l); - h[l * 2] = f >>> 8; - h[l * 2 + 1] = f % 256; - } - return h; - }, - decompressFromUint8Array: function (m) { - if (m === null || m === undefined) { - return d.decompress(m); - } else { - var h = new Array(m.length / 2); - for (var l = 0, j = h.length; l < j; l++) { - h[l] = m[l * 2] * 256 + m[l * 2 + 1]; - } - var f = []; - h.forEach(function (i) { - f.push(c(i)); - }); - return d.decompress(f.join('')); - } - }, - compressToEncodedURIComponent: function (f) { - if (f == null) { - return ''; - } - return d._compress(f, 6, function (h) { - return b.charAt(h); - }); - }, - decompressFromEncodedURIComponent: function (f) { - if (f == null) { - return ''; - } - if (f == '') { - return null; - } - f = f.replace(/ /g, '+'); - return d._decompress(f.length, 32, function (h) { - return a(b, f.charAt(h)); - }); - }, - compress: function (f) { - return d._compress(f, 16, function (h) { - return c(h); - }); - }, - _compress: function (m, x, r) { - if (m == null) { - return ''; - } - var o, - s, - u = {}, - t = {}, - v = '', - j = '', - y = '', - l = 2, - n = 3, - h = 2, - q = [], - f = 0, - p = 0, - w; - for (w = 0; w < m.length; w += 1) { - v = m.charAt(w); - if (!Object.prototype.hasOwnProperty.call(u, v)) { - u[v] = n++; - t[v] = true; - } - j = y + v; - if (Object.prototype.hasOwnProperty.call(u, j)) { - y = j; - } else { - if (Object.prototype.hasOwnProperty.call(t, y)) { - if (y.charCodeAt(0) < 256) { - for (o = 0; o < h; o++) { - f = f << 1; - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - } - s = y.charCodeAt(0); - for (o = 0; o < 8; o++) { - f = (f << 1) | (s & 1); - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = s >> 1; - } - } else { - s = 1; - for (o = 0; o < h; o++) { - f = (f << 1) | s; - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = 0; - } - s = y.charCodeAt(0); - for (o = 0; o < 16; o++) { - f = (f << 1) | (s & 1); - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = s >> 1; - } - } - l--; - if (l == 0) { - l = Math.pow(2, h); - h++; - } - delete t[y]; - } else { - s = u[y]; - for (o = 0; o < h; o++) { - f = (f << 1) | (s & 1); - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = s >> 1; - } - } - l--; - if (l == 0) { - l = Math.pow(2, h); - h++; - } - u[j] = n++; - y = String(v); - } - } - if (y !== '') { - if (Object.prototype.hasOwnProperty.call(t, y)) { - if (y.charCodeAt(0) < 256) { - for (o = 0; o < h; o++) { - f = f << 1; - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - } - s = y.charCodeAt(0); - for (o = 0; o < 8; o++) { - f = (f << 1) | (s & 1); - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = s >> 1; - } - } else { - s = 1; - for (o = 0; o < h; o++) { - f = (f << 1) | s; - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = 0; - } - s = y.charCodeAt(0); - for (o = 0; o < 16; o++) { - f = (f << 1) | (s & 1); - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = s >> 1; - } - } - l--; - if (l == 0) { - l = Math.pow(2, h); - h++; - } - delete t[y]; - } else { - s = u[y]; - for (o = 0; o < h; o++) { - f = (f << 1) | (s & 1); - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = s >> 1; - } - } - l--; - if (l == 0) { - l = Math.pow(2, h); - h++; - } - } - s = 2; - for (o = 0; o < h; o++) { - f = (f << 1) | (s & 1); - if (p == x - 1) { - p = 0; - q.push(r(f)); - f = 0; - } else { - p++; - } - s = s >> 1; - } - while (true) { - f = f << 1; - if (p == x - 1) { - q.push(r(f)); - break; - } else { - p++; - } - } - return q.join(''); - }, - decompress: function (f) { - if (f == null) { - return ''; - } - if (f == '') { - return null; - } - return d._decompress(f.length, 32768, function (h) { - return f.charCodeAt(h); - }); - }, - _decompress: function (j, l, f) { - var r = [], - t, - n = 4, - u = 4, - s = 3, - h = '', - p = [], - x, - q, - v, - z, - m, - o, - y, - A = { val: f(0), position: l, index: 1 }; - for (x = 0; x < 3; x += 1) { - r[x] = x; - } - v = 0; - m = Math.pow(2, 2); - o = 1; - while (o != m) { - z = A.val & A.position; - A.position >>= 1; - if (A.position == 0) { - A.position = l; - A.val = f(A.index++); - } - v |= (z > 0 ? 1 : 0) * o; - o <<= 1; - } - switch ((t = v)) { - case 0: - v = 0; - m = Math.pow(2, 8); - o = 1; - while (o != m) { - z = A.val & A.position; - A.position >>= 1; - if (A.position == 0) { - A.position = l; - A.val = f(A.index++); - } - v |= (z > 0 ? 1 : 0) * o; - o <<= 1; - } - y = c(v); - break; - case 1: - v = 0; - m = Math.pow(2, 16); - o = 1; - while (o != m) { - z = A.val & A.position; - A.position >>= 1; - if (A.position == 0) { - A.position = l; - A.val = f(A.index++); - } - v |= (z > 0 ? 1 : 0) * o; - o <<= 1; - } - y = c(v); - break; - case 2: - return ''; - } - r[3] = y; - q = y; - p.push(y); - while (true) { - if (A.index > j) { - return ''; - } - v = 0; - m = Math.pow(2, s); - o = 1; - while (o != m) { - z = A.val & A.position; - A.position >>= 1; - if (A.position == 0) { - A.position = l; - A.val = f(A.index++); - } - v |= (z > 0 ? 1 : 0) * o; - o <<= 1; - } - switch ((y = v)) { - case 0: - v = 0; - m = Math.pow(2, 8); - o = 1; - while (o != m) { - z = A.val & A.position; - A.position >>= 1; - if (A.position == 0) { - A.position = l; - A.val = f(A.index++); - } - v |= (z > 0 ? 1 : 0) * o; - o <<= 1; - } - r[u++] = c(v); - y = u - 1; - n--; - break; - case 1: - v = 0; - m = Math.pow(2, 16); - o = 1; - while (o != m) { - z = A.val & A.position; - A.position >>= 1; - if (A.position == 0) { - A.position = l; - A.val = f(A.index++); - } - v |= (z > 0 ? 1 : 0) * o; - o <<= 1; - } - r[u++] = c(v); - y = u - 1; - n--; - break; - case 2: - return p.join(''); - } - if (n == 0) { - n = Math.pow(2, s); - s++; - } - if (r[y]) { - h = r[y]; - } else { - if (y === u) { - h = q + q.charAt(0); - } else { - return null; - } - } - p.push(h); - r[u++] = q + h.charAt(0); - n--; - q = h; - if (n == 0) { - n = Math.pow(2, s); - s++; - } - } - }, - }; - return d; -})(); -if (typeof define === 'function' && define.amd) { - define(function () { - return LZString; - }); -} else { - if (typeof module !== 'undefined' && module != null) { - module.exports = LZString; - } -} +__whitespace={" ":true,"\t":true,"\n":true,"\f":true,"\r":true};difflib={defaultJunkFunction:function(a){return a in __whitespace},stripLinebreaks:function(a){return a.replace(/^[\n\r]*|[\n\r]*$/g,"")},stringAsLines:function(f){var a=f.indexOf("\n");var e=f.indexOf("\r");var d=((a>-1&&e>-1)||e<0)?"\n":"\r";var b=f.split(d);for(var c=0;cc[f]){return 1}}return d.length==c.length?0:(d.length=200&&p.length*100>g){j[l]=1;delete h[l]}else{p.push(m)}}else{h[l]=[m]}}for(var l in j){delete h[l]}var f=this.isjunk;var a={};if(f){for(var l in j){if(f(l)){a[l]=1;delete j[l]}}for(var l in h){if(f(l)){a[l]=1;delete h[l]}}}this.isbjunk=difflib.__isindict(a);this.isbpopular=difflib.__isindict(j)};this.find_longest_match=function(g,w,q,n){var y=this.a;var x=this.b;var z=this.b2j;var f=this.isbjunk;var o=g;var m=q;var l=0;var t=null;var s={};var p=[];for(var u=g;u=n){break}h[t]=k=difflib.__dictget(s,t-1,0)+1;if(k>l){o=u-k+1;m=t-k+1;l=k}}s=h}while(o>g&&m>q&&!f(x[m-1])&&y[o-1]==x[m-1]){o--;m--;l++}while(o+lg&&m>q&&f(x[m-1])&&y[o-1]==x[m-1]){o--;m--;l++}while(o+ll){f.push([p,i,Math.min(h,i+g),o,Math.min(m,o+g)]);i=Math.max(i,h-g);o=Math.max(o,m-g)}f.push([p,i,h,o,m])}if(f&&f[f.length-1][0]=="equal"){f.pop()}return f};this.ratio=function(){matches=difflib.__reduce(function(a,b){return a+b[b.length-1]},this.get_matching_blocks(),0);return difflib.__calculate_ratio(matches,this.a.length+this.b.length)};this.quick_ratio=function(){var a,b;if(this.fullbcount==null){this.fullbcount=a={};for(var g=0;g0){h++}}return difflib.__calculate_ratio(h,this.a.length+this.b.length)};this.real_quick_ratio=function(){var b=this.a.length;var a=this.b.length;return _calculate_ratio(Math.min(b,a),b+a)};this.isjunk=d?d:difflib.defaultJunkFunction;this.a=this.b=null;this.set_seqs(e,c)}};diffview={buildView:function(C){var u=C.baseTextLines;var e=C.newTextLines;var o=C.opcodes;var h=C.baseTextName?C.baseTextName:"Base Text";var v=C.newTextName?C.newTextName:"New Text";var q=C.contextSize;var d=(C.viewType==0||C.viewType==1)?C.viewType:0;if(u==null){throw"Cannot build diff view; baseTextLines is not defined."}if(e==null){throw"Cannot build diff view; newTextLines is not defined."}if(!o){throw"Canno build diff view; opcodes is not defined."}function E(i,b){var n=document.createElement(i);n.className=b;return n}function p(b,n){var i=document.createElement(b);i.appendChild(document.createTextNode(n));return i}function r(i,b,H){var n=document.createElement(i);n.className=b;n.innerHTML=H;return n}var s=document.createElement("thead");var y=document.createElement("tr");s.appendChild(y);if(d){y.appendChild(document.createElement("th"));y.appendChild(document.createElement("th"));y.appendChild(r("th","texttitle",h+" vs. "+v))}else{y.appendChild(document.createElement("th"));y.appendChild(r("th","texttitle",h));y.appendChild(document.createElement("th"));y.appendChild(r("th","texttitle",v))}s=[s];var m=[];var a;function c(H,b,n,i,I){if(b1&&((t>0&&z==q)||(t==0&&z==0))&&change=="equal"){var g=G-((t==0?1:2)*q);if(g>1){x.push(y=document.createElement("tr"));D+=g;w+=g;z+=g-1;y.appendChild(p("th","..."));if(!d){y.appendChild(r("td","skip",""))}y.appendChild(p("th","..."));y.appendChild(r("td","skip",""));if(t+1==o.length){break}else{continue}}}x.push(y=document.createElement("tr"));if(d){if(change=="insert"){B(y,null,w++,e,change)}else{if(change=="replace"){A.push(a=document.createElement("tr"));if(D/g,">");b=b.replace(/"/g,""");return b}function diffString(g,h){g=g.replace(/\s+$/,"");h=h.replace(/\s+$/,"");var b=diff(g==""?[]:g.split(/\s+/),h==""?[]:h.split(/\s+/));var f="";var a=g.match(/\s+/g);if(a==null){a=["\n"]}else{a.push("\n")}var d=h.match(/\s+/g);if(d==null){d=["\n"]}else{d.push("\n")}if(b.n.length==0){for(var c=0;c"+escape_jsdiff(b.o[c])+a[c]+""}}else{if(b.n[0].text==null){for(h=0;h"+escape_jsdiff(b.o[h])+a[h]+""}}for(var c=0;c"+escape_jsdiff(b.n[c])+d[c]+""}else{var e="";for(h=b.n[c].row+1;h"+escape_jsdiff(b.o[h])+a[h]+""}f+=" "+b.n[c].text+d[c]+e}}}return f}function randomColor(){return"rgb("+(Math.random()*100)+"%, "+(Math.random()*100)+"%, "+(Math.random()*100)+"%)"}function diffString2(b,c){b=b.replace(/\s+$/,"");c=c.replace(/\s+$/,"");var e=diff(b==""?[]:b.split(/\s+/),c==""?[]:c.split(/\s+/));var j=b.match(/\s+/g);if(j==null){j=["\n"]}else{j.push("\n")}var g=c.match(/\s+/g);if(g==null){g=["\n"]}else{g.push("\n")}var d="";var a=new Array();for(var f=0;f"+escape_jsdiff(e.o[f])+j[f]+""}}var h="";for(var f=0;f"+escape_jsdiff(e.n[f])+g[f]+""}}return{o:d,n:h}}function diff(d,e){var b=new Object();var c=new Object();for(var a=0;a0;a--){if(e[a].text!=null&&e[a-1].text==null&&e[a].row>0&&d[e[a].row-1].text==null&&e[a-1]==d[e[a].row-1]){e[a-1]={text:e[a-1],row:e[a].row-1};d[e[a].row-1]={text:d[e[a].row-1],row:a-1}}}return{o:d,n:e}}(function(b,a){typeof exports==="object"&&typeof module!=="undefined"?module.exports=a():typeof define==="function"&&define.amd?define(a):b.moment=a()}(this,(function(){var cT;function gm(){return cT.apply(null,arguments)}function bi(g5){cT=g5}function ag(g5){return g5 instanceof Array||Object.prototype.toString.call(g5)==="[object Array]"}function E(g5){return g5!=null&&Object.prototype.toString.call(g5)==="[object Object]"}function c6(g6){var g5;for(g5 in g6){return false}return true}function P(g5){return g5===void 0}function z(g5){return typeof g5==="number"||Object.prototype.toString.call(g5)==="[object Number]"}function gc(g5){return g5 instanceof Date||Object.prototype.toString.call(g5)==="[object Date]"}function bT(g5,g8){var g7=[],g6;for(g6=0;g6>>0;for(var g7=0;g70){for(g5=0;g50?"future":"past"];return bz(g6)?g6(g5):g6.replace(/%s/i,g5)}var dT={};function c0(g7,g5){var g6=g7.toLowerCase();dT[g6]=dT[g6+"s"]=dT[g5]=g7}function dY(g5){return typeof g5==="string"?dT[g5]||dT[g5.toLowerCase()]:undefined}function fb(g7){var g6={},g5,g8;for(g8 in g7){if(eJ(g7,g8)){g5=dY(g8);if(g5){g6[g5]=g7[g8]}}}return g6}var bY={};function fo(g6,g5){bY[g6]=g5}function bV(g5){var g6=[];for(var g7 in g5){g6.push({unit:g7,priority:bY[g7]})}g6.sort(function(g9,g8){return g9.priority-g8.priority});return g6}function fH(g5,g6){return function(g7){if(g7!=null){bc(this,g5,g7);gm.updateOffset(this,g6);return this}else{return eY(this,g5)}}}function eY(g6,g5){return g6.isValid()?g6._d["get"+(g6._isUTC?"UTC":"")+g5]():NaN}function bc(g6,g5,g7){if(g6.isValid()){g6._d["set"+(g6._isUTC?"UTC":"")+g5](g7)}}function a0(g5){g5=dY(g5);if(bz(this[g5])){return this[g5]()}return this}function aR(g5,g8){if(typeof g5==="object"){g5=fb(g5);var g7=bV(g5);for(var g6=0;g6=0;return(g5?(g6?"+":""):"-")+Math.pow(10,Math.max(0,g7)).toString().substr(1)+g8}var co=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;var cn=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;var cm={};var bC={};function dy(g6,g7,g5,g9){var g8=g9;if(typeof g9==="string"){g8=function(){return this[g9]()}}if(g6){bC[g6]=g8}if(g7){bC[g7[0]]=function(){return dk(g8.apply(this,arguments),g7[1],g7[2])}}if(g5){bC[g5]=function(){return this.localeData().ordinal(g8.apply(this,arguments),g6)}}}function aT(g5){if(g5.match(/\[[\s\S]/)){return g5.replace(/^\[|\]$/g,"")}return g5.replace(/\\/g,"")}function b2(g7){var g8=g7.match(co),g5,g6;for(g5=0,g6=g8.length;g5=0&&cn.test(g8)){g8=g8.replace(cn,g7);cn.lastIndex=0;g6-=1}return g8}var bb=/\d/;var ba=/\d\d/;var a9=/\d{3}/;var a8=/\d{4}/;var a7=/[+-]?\d{6}/;var aP=/\d\d?/;var dh=/\d\d\d\d?/;var fJ=/\d\d\d\d\d\d?/;var aO=/\d{1,3}/;var aN=/\d{1,4}/;var aL=/[+-]?\d{1,6}/;var A=/\d+/;var L=/[+-]?\d+/;var cf=/Z|[+-]\d\d:?\d\d/gi;var dK=/Z|[+-]\d\d(?::?\d\d)?/gi;var gE=/[+-]?\d+(\.\d{1,3})?/;var bB=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;var bv={};function bG(g5,g6,g7){bv[g5]=bz(g6)?g6:function(g9,g8){return(g9&&g7)?g7:g6}}function b9(g6,g5){if(!eJ(bv,g6)){return new RegExp(eH(g6))}return bv[g6](g5._strict,g5._locale)}function eH(g5){return c3(g5.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(g6,ha,g9,g8,g7){return ha||g9||g8||g7}))}function c3(g5){return g5.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var i={};function cs(g6,g8){var g5,g7=g8;if(typeof g6==="string"){g6=[g6]}if(z(g8)){g7=function(g9,ha){ha[g8]=dZ(g9)}}for(g5=0;g568?1900:2000)};var dM=fH("FullYear",true);function d5(){return fs(this.year())}function fB(hc,g5,ha,g9,hb,g8,g7){var g6=new Date(hc,g5,ha,g9,hb,g8,g7);if(hc<100&&hc>=0&&isFinite(g6.getFullYear())){g6.setFullYear(hc)}return g6}function eS(g6){var g5=new Date(Date.UTC.apply(null,arguments));if(g6<100&&g6>=0&&isFinite(g5.getUTCFullYear())){g5.setUTCFullYear(g6)}return g5}function bM(g6,g9,g8){var g5=7+g9-g8,g7=(7+eS(g6,0,g5).getUTCDay()-g9)%7;return -g7+g5-1}function b5(g8,g6,g7,he,hc){var hd=(7+g7-he)%7,g5=bM(g8,he,hc),ha=1+7*(g6-1)+hd+g5,hb,g9;if(ha<=0){hb=g8-1;g9=e3(hb)+ha}else{if(ha>e3(g8)){hb=g8+1;g9=ha-e3(g8)}else{hb=g8;g9=ha}}return{year:hb,dayOfYear:g9}}function f8(g9,hb,ha){var g7=bM(g9.year(),hb,ha),g8=Math.floor((g9.dayOfYear()-g7-1)/7)+1,g5,g6;if(g8<1){g6=g9.year()-1;g5=g8+O(g6,hb,ha)}else{if(g8>O(g9.year(),hb,ha)){g5=g8-O(g9.year(),hb,ha);g6=g9.year()+1}else{g6=g9.year();g5=g8}}return{week:g5,year:g6}}function O(g6,g9,g7){var g5=bM(g6,g9,g7),g8=bM(g6+1,g9,g7);return(e3(g6)-g5+g8)/7}dy("w",["ww",2],"wo","week");dy("W",["WW",2],"Wo","isoWeek");c0("week","w");c0("isoWeek","W");fo("week",5);fo("isoWeek",5);bG("w",aP);bG("ww",aP,ba);bG("W",aP);bG("WW",aP,ba);aj(["w","ww","W","WW"],function(g5,g8,g6,g7){g8[g7.substr(0,1)]=dZ(g5)});function bU(g5){return f8(g5,this._week.dow,this._week.doy).week}var cK={dow:0,doy:6};function aE(){return this._week.dow}function em(){return this._week.doy}function T(g5){var g6=this.localeData().week(this);return g5==null?g6:this.add((g5-g6)*7,"d")}function H(g5){var g6=f8(this,1,4).week;return g5==null?g6:this.add((g5-g6)*7,"d")}dy("d",0,"do","day");dy("dd",0,0,function(g5){return this.localeData().weekdaysMin(this,g5)});dy("ddd",0,0,function(g5){return this.localeData().weekdaysShort(this,g5)});dy("dddd",0,0,function(g5){return this.localeData().weekdays(this,g5)});dy("e",0,0,"weekday");dy("E",0,0,"isoWeekday");c0("day","d");c0("weekday","e");c0("isoWeekday","E");fo("day",11);fo("weekday",11);fo("isoWeekday",11);bG("d",aP);bG("e",aP);bG("E",aP);bG("dd",function(g6,g5){return g5.weekdaysMinRegex(g6)});bG("ddd",function(g6,g5){return g5.weekdaysShortRegex(g6)});bG("dddd",function(g6,g5){return g5.weekdaysRegex(g6)});aj(["dd","ddd","dddd"],function(g5,g8,g6,g7){var g9=g6._locale.weekdaysParse(g5,g7,g6._strict);if(g9!=null){g8.d=g9}else{bE(g6).invalidWeekday=g5}});aj(["d","e","E"],function(g5,g8,g6,g7){g8[g7]=dZ(g5)});function bL(g6,g5){if(typeof g6!=="string"){return g6}if(!isNaN(g6)){return parseInt(g6,10)}g6=g5.weekdaysParse(g6);if(typeof g6==="number"){return g6}return null}function b8(g6,g5){if(typeof g6==="string"){return g5.weekdaysParse(g6)%7||7}return isNaN(g6)?null:g6}var ad="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");function aU(g5,g6){if(!g5){return ag(this._weekdays)?this._weekdays:this._weekdays.standalone}return ag(this._weekdays)?this._weekdays[g5.day()]:this._weekdays[this._weekdays.isFormat.test(g6)?"format":"standalone"][g5.day()]}var s="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");function W(g5){return(g5)?this._weekdaysShort[g5.day()]:this._weekdaysShort}var bZ="Su_Mo_Tu_We_Th_Fr_Sa".split("_");function gn(g5){return(g5)?this._weekdaysMin[g5.day()]:this._weekdaysMin}function ff(ha,hb,g5){var g7,g8,g9,g6=ha.toLocaleLowerCase();if(!this._weekdaysParse){this._weekdaysParse=[];this._shortWeekdaysParse=[];this._minWeekdaysParse=[];for(g7=0;g7<7;++g7){g9=du([2000,1]).day(g7);this._minWeekdaysParse[g7]=this.weekdaysMin(g9,"").toLocaleLowerCase();this._shortWeekdaysParse[g7]=this.weekdaysShort(g9,"").toLocaleLowerCase();this._weekdaysParse[g7]=this.weekdays(g9,"").toLocaleLowerCase()}}if(g5){if(hb==="dddd"){g8=el.call(this._weekdaysParse,g6);return g8!==-1?g8:null}else{if(hb==="ddd"){g8=el.call(this._shortWeekdaysParse,g6);return g8!==-1?g8:null}else{g8=el.call(this._minWeekdaysParse,g6);return g8!==-1?g8:null}}}else{if(hb==="dddd"){g8=el.call(this._weekdaysParse,g6);if(g8!==-1){return g8}g8=el.call(this._shortWeekdaysParse,g6);if(g8!==-1){return g8}g8=el.call(this._minWeekdaysParse,g6);return g8!==-1?g8:null}else{if(hb==="ddd"){g8=el.call(this._shortWeekdaysParse,g6);if(g8!==-1){return g8}g8=el.call(this._weekdaysParse,g6);if(g8!==-1){return g8}g8=el.call(this._minWeekdaysParse,g6);return g8!==-1?g8:null}else{g8=el.call(this._minWeekdaysParse,g6);if(g8!==-1){return g8}g8=el.call(this._weekdaysParse,g6);if(g8!==-1){return g8}g8=el.call(this._shortWeekdaysParse,g6);return g8!==-1?g8:null}}}}function cj(g9,ha,g5){var g6,g8,g7;if(this._weekdaysParseExact){return ff.call(this,g9,ha,g5)}if(!this._weekdaysParse){this._weekdaysParse=[];this._minWeekdaysParse=[];this._shortWeekdaysParse=[];this._fullWeekdaysParse=[]}for(g6=0;g6<7;g6++){g8=du([2000,1]).day(g6);if(g5&&!this._fullWeekdaysParse[g6]){this._fullWeekdaysParse[g6]=new RegExp("^"+this.weekdays(g8,"").replace(".",".?")+"$","i");this._shortWeekdaysParse[g6]=new RegExp("^"+this.weekdaysShort(g8,"").replace(".",".?")+"$","i");this._minWeekdaysParse[g6]=new RegExp("^"+this.weekdaysMin(g8,"").replace(".",".?")+"$","i")}if(!this._weekdaysParse[g6]){g7="^"+this.weekdays(g8,"")+"|^"+this.weekdaysShort(g8,"")+"|^"+this.weekdaysMin(g8,"");this._weekdaysParse[g6]=new RegExp(g7.replace(".",""),"i")}if(g5&&ha==="dddd"&&this._fullWeekdaysParse[g6].test(g9)){return g6}else{if(g5&&ha==="ddd"&&this._shortWeekdaysParse[g6].test(g9)){return g6}else{if(g5&&ha==="dd"&&this._minWeekdaysParse[g6].test(g9)){return g6}else{if(!g5&&this._weekdaysParse[g6].test(g9)){return g6}}}}}}function fZ(g6){if(!this.isValid()){return g6!=null?this:NaN}var g5=this._isUTC?this._d.getUTCDay():this._d.getDay();if(g6!=null){g6=bL(g6,this.localeData());return this.add(g6-g5,"d")}else{return g5}}function av(g5){if(!this.isValid()){return g5!=null?this:NaN}var g6=(this.day()+7-this.localeData()._week.dow)%7;return g5==null?g6:this.add(g5-g6,"d")}function ds(g5){if(!this.isValid()){return g5!=null?this:NaN}if(g5!=null){var g6=b8(g5,this.localeData());return this.day(this.day()%7?g6:g6-7)}else{return this.day()||7}}var aq=bB;function gH(g5){if(this._weekdaysParseExact){if(!eJ(this,"_weekdaysRegex")){J.call(this)}if(g5){return this._weekdaysStrictRegex}else{return this._weekdaysRegex}}else{if(!eJ(this,"_weekdaysRegex")){this._weekdaysRegex=aq}return this._weekdaysStrictRegex&&g5?this._weekdaysStrictRegex:this._weekdaysRegex}}var F=bB;function a6(g5){if(this._weekdaysParseExact){if(!eJ(this,"_weekdaysRegex")){J.call(this)}if(g5){return this._weekdaysShortStrictRegex}else{return this._weekdaysShortRegex}}else{if(!eJ(this,"_weekdaysShortRegex")){this._weekdaysShortRegex=F}return this._weekdaysShortStrictRegex&&g5?this._weekdaysShortStrictRegex:this._weekdaysShortRegex}}var fm=bB;function N(g5){if(this._weekdaysParseExact){if(!eJ(this,"_weekdaysRegex")){J.call(this)}if(g5){return this._weekdaysMinStrictRegex}else{return this._weekdaysMinRegex}}else{if(!eJ(this,"_weekdaysMinRegex")){this._weekdaysMinRegex=fm}return this._weekdaysMinStrictRegex&&g5?this._weekdaysMinStrictRegex:this._weekdaysMinRegex}}function J(){function g8(hg,hf){return hf.length-hg.length}var ha=[],hb=[],he=[],g5=[],g9,g7,g6,hc,hd;for(g9=0;g9<7;g9++){g7=du([2000,1]).day(g9);g6=this.weekdaysMin(g7,"");hc=this.weekdaysShort(g7,"");hd=this.weekdays(g7,"");ha.push(g6);hb.push(hc);he.push(hd);g5.push(g6);g5.push(hc);g5.push(hd)}ha.sort(g8);hb.sort(g8);he.sort(g8);g5.sort(g8);for(g9=0;g9<7;g9++){hb[g9]=c3(hb[g9]);he[g9]=c3(he[g9]);g5[g9]=c3(g5[g9])}this._weekdaysRegex=new RegExp("^("+g5.join("|")+")","i");this._weekdaysShortRegex=this._weekdaysRegex;this._weekdaysMinRegex=this._weekdaysRegex;this._weekdaysStrictRegex=new RegExp("^("+he.join("|")+")","i");this._weekdaysShortStrictRegex=new RegExp("^("+hb.join("|")+")","i");this._weekdaysMinStrictRegex=new RegExp("^("+ha.join("|")+")","i")}function eW(){return this.hours()%12||12}function Y(){return this.hours()||24}dy("H",["HH",2],0,"hour");dy("h",["hh",2],0,eW);dy("k",["kk",2],0,Y);dy("hmm",0,0,function(){return""+eW.apply(this)+dk(this.minutes(),2)});dy("hmmss",0,0,function(){return""+eW.apply(this)+dk(this.minutes(),2)+dk(this.seconds(),2)});dy("Hmm",0,0,function(){return""+this.hours()+dk(this.minutes(),2)});dy("Hmmss",0,0,function(){return""+this.hours()+dk(this.minutes(),2)+dk(this.seconds(),2)});function f3(g5,g6){dy(g5,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),g6)})}f3("a",true);f3("A",false);c0("hour","h");fo("hour",13);function ac(g6,g5){return g5._meridiemParse}bG("a",ac);bG("A",ac);bG("H",aP);bG("h",aP);bG("k",aP);bG("HH",aP,ba);bG("hh",aP,ba);bG("kk",aP,ba);bG("hmm",dh);bG("hmmss",fJ);bG("Hmm",dh);bG("Hmmss",fJ);cs(["H","HH"],gr);cs(["k","kk"],function(g6,g8,g7){var g5=dZ(g6);g8[gr]=g5===24?0:g5});cs(["a","A"],function(g5,g7,g6){g6._isPm=g6._locale.isPM(g5);g6._meridiem=g5});cs(["h","hh"],function(g5,g7,g6){g7[gr]=dZ(g5);bE(g6).bigHour=true});cs("hmm",function(g5,g8,g6){var g7=g5.length-2;g8[gr]=dZ(g5.substr(0,g7));g8[e6]=dZ(g5.substr(g7));bE(g6).bigHour=true});cs("hmmss",function(g5,g9,g6){var g8=g5.length-4;var g7=g5.length-2;g9[gr]=dZ(g5.substr(0,g8));g9[e6]=dZ(g5.substr(g8,2));g9[aH]=dZ(g5.substr(g7));bE(g6).bigHour=true});cs("Hmm",function(g5,g8,g6){var g7=g5.length-2;g8[gr]=dZ(g5.substr(0,g7));g8[e6]=dZ(g5.substr(g7))});cs("Hmmss",function(g5,g9,g6){var g8=g5.length-4;var g7=g5.length-2;g9[gr]=dZ(g5.substr(0,g8));g9[e6]=dZ(g5.substr(g8,2));g9[aH]=dZ(g5.substr(g7))});function cW(g5){return((g5+"").toLowerCase().charAt(0)==="p")}var cN=/[ap]\.?m?\.?/i;function bk(g5,g6,g7){if(g5>11){return g7?"pm":"PM"}else{return g7?"am":"AM"}}var dl=fH("Hours",true);var cH={calendar:de,longDateFormat:fp,invalidDate:aK,ordinal:cO,dayOfMonthOrdinalParse:g0,relativeTime:gi,months:Z,monthsShort:ft,week:cK,weekdays:ad,weekdaysMin:bZ,weekdaysShort:s,meridiemParse:cN};var b3={};var t={};var d7;function eM(g5){return g5?g5.toLowerCase().replace("_","-"):g5}function d6(ha){var g8=0,g6,g9,g5,g7;while(g80){g5=a2(g7.slice(0,g6).join("-"));if(g5){return g5}if(g9&&g9.length>=g6&&cy(g7,g9,true)>=g6-1){break}g6--}g8++}return null}function a2(g5){var g7=null;if(!b3[g5]&&(typeof module!=="undefined")&&module&&module.exports){try{g7=d7._abbr;require("./locale/"+g5);K(g7)}catch(g6){}}return b3[g5]}function K(g6,g5){var g7;if(g6){if(P(g5)){g7=aa(g6)}else{g7=dC(g6,g5)}if(g7){d7=g7}}return d7._abbr}function dC(g6,g5){if(g5!==null){var g7=cH;g5.abbr=g6;if(b3[g6]!=null){gD("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info.");g7=b3[g6]._config}else{if(g5.parentLocale!=null){if(b3[g5.parentLocale]!=null){g7=b3[g5.parentLocale]._config}else{if(!t[g5.parentLocale]){t[g5.parentLocale]=[]}t[g5.parentLocale].push({name:g6,config:g5});return null}}}b3[g6]=new dE(fA(g7,g5));if(t[g6]){t[g6].forEach(function(g8){dC(g8.name,g8.config)})}K(g6);return b3[g6]}else{delete b3[g6];return null}}function f0(g7,g6){if(g6!=null){var g5,g8=cH;if(b3[g7]!=null){g8=b3[g7]._config}g6=fA(g8,g6);g5=new dE(g6);g5.parentLocale=b3[g7];b3[g7]=g5;K(g7)}else{if(b3[g7]!=null){if(b3[g7].parentLocale!=null){b3[g7]=b3[g7].parentLocale}else{if(b3[g7]!=null){delete b3[g7]}}}}return b3[g7]}function aa(g6){var g5;if(g6&&g6._locale&&g6._locale._abbr){g6=g6._locale._abbr}if(!g6){return d7}if(!ag(g6)){g5=a2(g6);if(g5){return g5}g6=[g6]}return d6(g6)}function cM(){return fe(b3)}function dX(g5){var g7;var g6=g5._a;if(g6&&bE(g5).overflow===-2){g7=g6[o]<0||g6[o]>11?o:g6[ga]<1||g6[ga]>ce(g6[gF],g6[o])?ga:g6[gr]<0||g6[gr]>24||(g6[gr]===24&&(g6[e6]!==0||g6[aH]!==0||g6[ch]!==0))?gr:g6[e6]<0||g6[e6]>59?e6:g6[aH]<0||g6[aH]>59?aH:g6[ch]<0||g6[ch]>999?ch:-1;if(bE(g5)._overflowDayOfYear&&(g7ga)){g7=ga}if(bE(g5)._overflowWeeks&&g7===-1){g7=da}if(bE(g5)._overflowWeekday&&g7===-1){g7=l}bE(g5).overflow=g7}return g5}var p=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;var bj=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;var dL=/Z|[+-]\d\d(?::?\d\d)?/;var d1=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,false],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,false],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,false],["YYYYDDD",/\d{7}/]];var dm=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]];var ct=/^\/?Date\((\-?\d+)/i;function M(g6){var ha,g8,hc=g6._i,hb=p.exec(hc)||bj.exec(hc),hd,g5,g9,g7;if(hb){bE(g6).iso=true;for(ha=0,g8=d1.length;ha10)?"YYYY ":"YY ");hc="HH:mm"+(he[4]?":ss":"");if(he[1]){var ha=new Date(he[2]);var g7=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][ha.getDay()];if(he[1].substr(0,3)!==g7){bE(g8).weekdayMismatch=true;g8._isValid=false;return}}switch(he[5].length){case 2:if(g6===0){hg=" +0000"}else{g6=hb.indexOf(he[5][1].toUpperCase())-12;hg=((g6<0)?" -":" +")+((""+g6).replace(/^-?/,"0")).match(/..$/)[0]+"00"}break;case 4:hg=hh[he[5]];break;default:hg=hh[" GMT"]}he[5]=hg;g8._i=he.splice(1).join("");g9=" ZZ";g8._f=hd+g5+hc+g9;cv(g8);bE(g8).rfc2822=true}else{g8._isValid=false}}function bF(g6){var g5=ct.exec(g6._i);if(g5!==null){g6._d=new Date(+g5[1]);return}M(g6);if(g6._isValid===false){delete g6._isValid}else{return}cr(g6);if(g6._isValid===false){delete g6._isValid}else{return}gm.createFromInputFallback(g6)}gm.createFromInputFallback=fK("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(g5){g5._d=new Date(g5._i+(g5._useUTC?" UTC":""))});function fC(g6,g5,g7){if(g6!=null){return g6}if(g5!=null){return g5}return g7}function bu(g6){var g5=new Date(gm.now());if(g6._useUTC){return[g5.getUTCFullYear(),g5.getUTCMonth(),g5.getUTCDate()]}return[g5.getFullYear(),g5.getMonth(),g5.getDate()]}function g(g9){var ha,g8,g7=[],g6,g5;if(g9._d){return}g6=bu(g9);if(g9._w&&g9._a[ga]==null&&g9._a[o]==null){eb(g9)}if(g9._dayOfYear!=null){g5=fC(g9._a[gF],g6[gF]);if(g9._dayOfYear>e3(g5)||g9._dayOfYear===0){bE(g9)._overflowDayOfYear=true}g8=eS(g5,0,g9._dayOfYear);g9._a[o]=g8.getUTCMonth();g9._a[ga]=g8.getUTCDate()}for(ha=0;ha<3&&g9._a[ha]==null;++ha){g9._a[ha]=g7[ha]=g6[ha]}for(;ha<7;ha++){g9._a[ha]=g7[ha]=(g9._a[ha]==null)?(ha===2?1:0):g9._a[ha]}if(g9._a[gr]===24&&g9._a[e6]===0&&g9._a[aH]===0&&g9._a[ch]===0){g9._nextDay=true;g9._a[gr]=0}g9._d=(g9._useUTC?eS:fB).apply(null,g7);if(g9._tzm!=null){g9._d.setUTCMinutes(g9._d.getUTCMinutes()-g9._tzm)}if(g9._nextDay){g9._a[gr]=24}}function eb(g8){var hb,g5,g6,g9,he,hc,hd,ha;hb=g8._w;if(hb.GG!=null||hb.W!=null||hb.E!=null){he=1;hc=4;g5=fC(hb.GG,g8._a[gF],f8(eZ(),1,4).year);g6=fC(hb.W,1);g9=fC(hb.E,1);if(g9<1||g9>7){ha=true}}else{he=g8._locale._week.dow;hc=g8._locale._week.doy;var g7=f8(eZ(),he,hc);g5=fC(hb.gg,g8._a[gF],g7.year);g6=fC(hb.w,g7.week);if(hb.d!=null){g9=hb.d;if(g9<0||g9>6){ha=true}}else{if(hb.e!=null){g9=hb.e+he;if(hb.e<0||hb.e>6){ha=true}}else{g9=he}}}if(g6<1||g6>O(g5,he,hc)){bE(g8)._overflowWeeks=true}else{if(ha!=null){bE(g8)._overflowWeekday=true}else{hd=b5(g5,g6,g9,he,hc);g8._a[gF]=hd.year;g8._dayOfYear=hd.dayOfYear}}}gm.ISO_8601=function(){};gm.RFC_2822=function(){};function cv(g7){if(g7._f===gm.ISO_8601){M(g7);return}if(g7._f===gm.RFC_2822){cr(g7);return}g7._a=[];bE(g7).empty=true;var ha=""+g7._i,g9,g6,hd,g8,hc,g5=ha.length,hb=0;hd=cc(g7._f,g7._locale).match(co)||[];for(g9=0;g90){bE(g7).unusedInput.push(hc)}ha=ha.slice(ha.indexOf(g6)+g6.length);hb+=g6.length}if(bC[g8]){if(g6){bE(g7).empty=false}else{bE(g7).unusedTokens.push(g8)}D(g8,g6,g7)}else{if(g7._strict&&!g6){bE(g7).unusedTokens.push(g8)}}}bE(g7).charsLeftOver=g5-hb;if(ha.length>0){bE(g7).unusedInput.push(ha)}if(g7._a[gr]<=12&&bE(g7).bigHour===true&&g7._a[gr]>0){bE(g7).bigHour=undefined}bE(g7).parsedDateParts=g7._a.slice(0);bE(g7).meridiem=g7._meridiem;g7._a[gr]=fL(g7._locale,g7._a[gr],g7._meridiem);g(g7);dX(g7)}function fL(g5,g7,g8){var g6;if(g8==null){return g7}if(g5.meridiemHour!=null){return g5.meridiemHour(g7,g8)}else{if(g5.isPM!=null){g6=g5.isPM(g8);if(g6&&g7<12){g7+=12}if(!g6&&g7===12){g7=0}return g7}else{return g7}}}function e1(g5){var g9,g7,g8,g6,ha;if(g5._f.length===0){bE(g5).invalidFormat=true;g5._d=new Date(NaN);return}for(g6=0;g6this?this:g5}else{return X()}});function gR(g7,g8){var g6,g5;if(g8.length===1&&ag(g8[0])){g8=g8[0]}if(!g8.length){return eZ()}g6=g8[0];for(g5=1;g5this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset())}function b(){if(!P(this._isDSTShifted)){return this._isDSTShifted}var g6={};y(g6,this);g6=bX(g6);if(g6._a){var g5=g6._isUTC?du(g6._a):eZ(g6._a);this._isDSTShifted=this.isValid()&&cy(g6._a,g5.toArray())>0}else{this._isDSTShifted=false}return this._isDSTShifted}function eU(){return this.isValid()?!this._isUTC:false}function cp(){return this.isValid()?this._isUTC:false}function e0(){return this.isValid()?this._isUTC&&this._offset===0:false}var al=/^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;var dx=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;function eD(g7,ha){var hb=g7,g9=null,g6,g8,g5;if(az(g7)){hb={ms:g7._milliseconds,d:g7._days,M:g7._months}}else{if(z(g7)){hb={};if(ha){hb[ha]=g7}else{hb.milliseconds=g7}}else{if(!!(g9=al.exec(g7))){g6=(g9[1]==="-")?-1:1;hb={y:0,d:dZ(g9[ga])*g6,h:dZ(g9[gr])*g6,m:dZ(g9[e6])*g6,s:dZ(g9[aH])*g6,ms:dZ(fX(g9[ch]*1000))*g6}}else{if(!!(g9=dx.exec(g7))){g6=(g9[1]==="-")?-1:1;hb={y:gG(g9[2],g6),M:gG(g9[3],g6),w:gG(g9[4],g6),d:gG(g9[5],g6),h:gG(g9[6],g6),m:gG(g9[7],g6),s:gG(g9[8],g6)}}else{if(hb==null){hb={}}else{if(typeof hb==="object"&&("from" in hb||"to" in hb)){g5=cl(eZ(hb.from),eZ(hb.to));hb={};hb.ms=g5.milliseconds;hb.M=g5.months}}}}}}g8=new fg(hb);if(az(g7)&&eJ(g7,"_locale")){g8._locale=g7._locale}return g8}eD.fn=fg.prototype;eD.invalid=bo;function gG(g7,g5){var g6=g7&&parseFloat(g7.replace(",","."));return(isNaN(g6)?0:g6)*g5}function eX(g7,g5){var g6={milliseconds:0,months:0};g6.months=g5.month()-g7.month()+(g5.year()-g7.year())*12;if(g7.clone().add(g6.months,"M").isAfter(g5)){--g6.months}g6.milliseconds=+g5-+(g7.clone().add(g6.months,"M"));return g6}function cl(g7,g5){var g6;if(!(g7.isValid()&&g5.isValid())){return{milliseconds:0,months:0}}g5=a3(g5,g7);if(g7.isBefore(g5)){g6=eX(g7,g5)}else{g6=eX(g5,g7);g6.milliseconds=-g6.milliseconds;g6.months=-g6.months}return g6}function bx(g6,g5){return function(ha,g9){var g8,g7;if(g9!==null&&!isNaN(+g9)){gD(g5,"moment()."+g5+"(period, number) is deprecated. Please use moment()."+g5+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.");g7=ha;ha=g9;g9=g7}ha=typeof ha==="string"?+ha:ha;g8=eD(ha,g9);br(this,g8,g6);return this}}function br(g7,ha,g9,g8){var g6=ha._milliseconds,hb=fX(ha._days),g5=fX(ha._months);if(!g7.isValid()){return}g8=g8==null?true:g8;if(g6){g7._d.setTime(g7._d.valueOf()+g6*g9)}if(hb){bc(g7,"Date",eY(g7,"Date")+hb*g9)}if(g5){bn(g7,eY(g7,"Month")+g5*g9)}if(g8){gm.updateOffset(g7,hb||g5)}}var bq=bx(1,"add");var aV=bx(-1,"subtract");function aS(g7,g5){var g6=g7.diff(g5,"days",true);return g6<-6?"sameElse":g6<-1?"lastWeek":g6<0?"lastDay":g6<1?"sameDay":g6<2?"nextDay":g6<7?"nextWeek":"sameElse"}function c2(ha,g5){var g8=ha||eZ(),g7=a3(g8,this).startOf("day"),g9=gm.calendarFormat(this,g7)||"sameElse";var g6=g5&&(bz(g5[g9])?g5[g9].call(this,g8):g5[g9]);return this.format(g6||this.localeData().calendar(g9,this,eZ(g8)))}function eP(){return new f7(this)}function dH(g6,g5){var g7=cU(g6)?g6:eZ(g6);if(!(this.isValid()&&g7.isValid())){return false}g5=dY(!P(g5)?g5:"millisecond");if(g5==="millisecond"){return this.valueOf()>g7.valueOf()}else{return g7.valueOf()9999){return aA(g5,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}if(bz(Date.prototype.toISOString)){return this.toDate().toISOString()}return aA(g5,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function bh(){if(!this.isValid()){return"moment.invalid(/* "+this._i+" */)"}var g7="moment";var g5="";if(!this.isLocal()){g7=this.utcOffset()===0?"moment.utc":"moment.parseZone";g5="Z"}var g8="["+g7+'("]';var g6=(0<=this.year()&&this.year()<=9999)?"YYYY":"YYYYYY";var ha="-MM-DD[T]HH:mm:ss.SSS";var g9=g5+'[")]';return this.format(g8+g6+ha+g9)}function ei(g6){if(!g6){g6=this.isUtc()?gm.defaultFormatUtc:gm.defaultFormat}var g5=aA(this,g6);return this.localeData().postformat(g5)}function fj(g6,g5){if(this.isValid()&&((cU(g6)&&g6.isValid())||eZ(g6).isValid())){return eD({to:this,from:g6}).locale(this.locale()).humanize(!g5)}else{return this.localeData().invalidDate()}}function fc(g5){return this.from(eZ(),g5)}function aF(g6,g5){if(this.isValid()&&((cU(g6)&&g6.isValid())||eZ(g6).isValid())){return eD({from:this,to:g6}).locale(this.locale()).humanize(!g5)}else{return this.localeData().invalidDate()}}function bg(g5){return this.to(eZ(),g5)}function g4(g6){var g5;if(g6===undefined){return this._locale._abbr}else{g5=aa(g6);if(g5!=null){this._locale=g5}return this}}var I=fK("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(g5){if(g5===undefined){return this.localeData()}else{return this.locale(g5)}});function fk(){return this._locale}function cQ(g5){g5=dY(g5);switch(g5){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}if(g5==="week"){this.weekday(0)}if(g5==="isoWeek"){this.isoWeekday(1)}if(g5==="quarter"){this.month(Math.floor(this.month()/3)*3)}return this}function ge(g5){g5=dY(g5);if(g5===undefined||g5==="millisecond"){return this}if(g5==="date"){g5="day"}return this.startOf(g5).add(1,(g5==="isoWeek"?"week":g5)).subtract(1,"ms")}function fn(){return this._d.valueOf()-((this._offset||0)*60000)}function b4(){return Math.floor(this.valueOf()/1000)}function ea(){return new Date(this.valueOf())}function e9(){var g5=this;return[g5.year(),g5.month(),g5.date(),g5.hour(),g5.minute(),g5.second(),g5.millisecond()]}function fl(){var g5=this;return{years:g5.year(),months:g5.month(),date:g5.date(),hours:g5.hours(),minutes:g5.minutes(),seconds:g5.seconds(),milliseconds:g5.milliseconds()}}function ej(){return this.isValid()?this.toISOString():null}function x(){return aM(this)}function e2(){return gO({},bE(this))}function dB(){return bE(this).overflow}function gC(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}dy(0,["gg",2],0,function(){return this.weekYear()%100});dy(0,["GG",2],0,function(){return this.isoWeekYear()%100});function ai(g6,g5){dy(0,[g6,g6.length],0,g5)}ai("gggg","weekYear");ai("ggggg","weekYear");ai("GGGG","isoWeekYear");ai("GGGGG","isoWeekYear");c0("weekYear","gg");c0("isoWeekYear","GG");fo("weekYear",1);fo("isoWeekYear",1);bG("G",L);bG("g",L);bG("GG",aP,ba);bG("gg",aP,ba);bG("GGGG",aN,a8);bG("gggg",aN,a8);bG("GGGGG",aL,a7);bG("ggggg",aL,a7);aj(["gggg","ggggg","GGGG","GGGGG"],function(g5,g8,g6,g7){g8[g7.substr(0,2)]=dZ(g5)});aj(["gg","GG"],function(g5,g8,g6,g7){g8[g7]=gm.parseTwoDigitYear(g5)});function bW(g5){return dp.call(this,g5,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)}function fr(g5){return dp.call(this,g5,this.isoWeek(),this.isoWeekday(),1,4)}function eo(){return O(this.year(),1,4)}function S(){var g5=this.localeData()._week;return O(this.year(),g5.dow,g5.doy)}function dp(g5,g6,g8,ha,g9){var g7;if(g5==null){return f8(this,ha,g9).year}else{g7=O(g5,ha,g9);if(g6>g7){g6=g7}return bA.call(this,g5,g6,g8,ha,g9)}}function bA(g7,g6,g9,hb,ha){var g8=b5(g7,g6,g9,hb,ha),g5=eS(g8.year,0,g8.dayOfYear);this.year(g5.getUTCFullYear());this.month(g5.getUTCMonth());this.date(g5.getUTCDate());return this}dy("Q",0,"Qo","quarter");c0("quarter","Q");fo("quarter",7);bG("Q",bb);cs("Q",function(g5,g6){g6[o]=(dZ(g5)-1)*3});function cz(g5){return g5==null?Math.ceil((this.month()+1)/3):this.month((g5-1)*3+this.month()%3)}dy("D",["DD",2],"Do","date");c0("date","D");fo("date",9);bG("D",aP);bG("DD",aP,ba);bG("Do",function(g6,g5){return g6?(g5._dayOfMonthOrdinalParse||g5._ordinalParse):g5._dayOfMonthOrdinalParseLenient});cs(["D","DD"],ga);cs("Do",function(g5,g6){g6[ga]=dZ(g5.match(aP)[0],10)});var dj=fH("Date",true);dy("DDD",["DDDD",3],"DDDo","dayOfYear");c0("dayOfYear","DDD");fo("dayOfYear",4);bG("DDD",aO);bG("DDDD",a9);cs(["DDD","DDDD"],function(g5,g7,g6){g6._dayOfYear=dZ(g5)});function bI(g5){var g6=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/86400000)+1;return g5==null?g6:this.add((g5-g6),"d")}dy("m",["mm",2],0,"minute");c0("minute","m");fo("minute",14);bG("m",aP);bG("mm",aP,ba);cs(["m","mm"],e6);var gz=fH("Minutes",false);dy("s",["ss",2],0,"second");c0("second","s");fo("second",15);bG("s",aP);bG("ss",aP,ba);cs(["s","ss"],aH);var b0=fH("Seconds",false);dy("S",0,0,function(){return ~~(this.millisecond()/100)});dy(0,["SS",2],0,function(){return ~~(this.millisecond()/10)});dy(0,["SSS",3],0,"millisecond");dy(0,["SSSS",4],0,function(){return this.millisecond()*10});dy(0,["SSSSS",5],0,function(){return this.millisecond()*100});dy(0,["SSSSSS",6],0,function(){return this.millisecond()*1000});dy(0,["SSSSSSS",7],0,function(){return this.millisecond()*10000});dy(0,["SSSSSSSS",8],0,function(){return this.millisecond()*100000});dy(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1000000});c0("millisecond","ms");fo("millisecond",16);bG("S",aO,bb);bG("SS",aO,ba);bG("SSS",aO,a9);var bP;for(bP="SSSS";bP.length<=9;bP+="S"){bG(bP,A)}function eg(g5,g6){g6[ch]=dZ(("0."+g5)*1000)}for(bP="S";bP.length<=9;bP+="S"){cs(bP,eg)}var cx=fH("Milliseconds",false);dy("z",0,0,"zoneAbbr");dy("zz",0,0,"zoneName");function gu(){return this._isUTC?"UTC":""}function fM(){return this._isUTC?"Coordinated Universal Time":""}var cV=f7.prototype;cV.add=bq;cV.calendar=c2;cV.clone=eP;cV.diff=U;cV.endOf=ge;cV.format=ei;cV.from=fj;cV.fromNow=fc;cV.to=aF;cV.toNow=bg;cV.get=a0;cV.invalidAt=dB;cV.isAfter=dH;cV.isBefore=gA;cV.isBetween=f6;cV.isSame=dO;cV.isSameOrAfter=gt;cV.isSameOrBefore=gx;cV.isValid=x;cV.lang=I;cV.locale=g4;cV.localeData=fk;cV.max=f4;cV.min=dQ;cV.parsingFlags=e2;cV.set=aR;cV.startOf=cQ;cV.subtract=aV;cV.toArray=e9;cV.toObject=fl;cV.toDate=ea;cV.toISOString=ee;cV.inspect=bh;cV.toJSON=ej;cV.toString=fu;cV.unix=b4;cV.valueOf=fn;cV.creationData=gC;cV.year=dM;cV.isLeapYear=d5;cV.weekYear=bW;cV.isoWeekYear=fr;cV.quarter=cV.quarters=cz;cV.month=gq;cV.daysInMonth=ck;cV.week=cV.weeks=T;cV.isoWeek=cV.isoWeeks=H;cV.weeksInYear=S;cV.isoWeeksInYear=eo;cV.date=dj;cV.day=cV.days=fZ;cV.weekday=av;cV.isoWeekday=ds;cV.dayOfYear=bI;cV.hour=cV.hours=dl;cV.minute=cV.minutes=gz;cV.second=cV.seconds=b0;cV.millisecond=cV.milliseconds=cx;cV.utcOffset=eT;cV.utc=bs;cV.local=eQ;cV.parseZone=cR;cV.hasAlignedHourOffset=a1;cV.isDST=bd;cV.isLocal=eU;cV.isUtcOffset=cp;cV.isUtc=e0;cV.isUTC=e0;cV.zoneAbbr=gu;cV.zoneName=fM;cV.dates=fK("dates accessor is deprecated. Use date instead.",dj);cV.months=fK("months accessor is deprecated. Use month instead",gq);cV.years=fK("years accessor is deprecated. Use year instead",dM);cV.zone=fK("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",eO);cV.isDSTShifted=fK("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",b);function er(g5){return eZ(g5*1000)}function dW(){return eZ.apply(null,arguments).parseZone()}function eV(g5){return g5}var fx=dE.prototype;fx.calendar=d;fx.longDateFormat=dR;fx.invalidDate=f5;fx.ordinal=gj;fx.preparse=eV;fx.postformat=eV;fx.relativeTime=ae;fx.pastFuture=fq;fx.set=eL;fx.months=bt;fx.monthsShort=bD;fx.monthsParse=ep;fx.monthsRegex=d8;fx.monthsShortRegex=eI;fx.week=bU;fx.firstDayOfYear=em;fx.firstDayOfWeek=aE;fx.weekdays=aU;fx.weekdaysMin=gn;fx.weekdaysShort=W;fx.weekdaysParse=cj;fx.weekdaysRegex=gH;fx.weekdaysShortRegex=a6;fx.weekdaysMinRegex=N;fx.isPM=cW;fx.meridiem=bk;function R(g9,g6,g8,ha){var g5=aa();var g7=du().set(ha,g6);return g5[g8](g7,g9)}function bp(g9,g6,g8){if(z(g9)){g6=g9;g9=undefined}g9=g9||"";if(g6!=null){return R(g9,g6,g8,"month")}var g7;var g5=[];for(g7=0;g7<12;g7++){g5[g7]=R(g9,g7,g8,"month")}return g5}function gJ(ha,hc,g8,hb){if(typeof ha==="boolean"){if(z(hc)){g8=hc;hc=undefined}hc=hc||""}else{hc=ha;g8=hc;ha=false;if(z(hc)){g8=hc;hc=undefined}hc=hc||""}var g5=aa(),g6=ha?g5._week.dow:0;if(g8!=null){return R(hc,(g8+g6)%7,hb,"day")}var g9;var g7=[];for(g9=0;g9<7;g9++){g7[g9]=R(hc,(g9+g6)%7,hb,"day")}return g7}function d3(g6,g5){return bp(g6,g5,"months")}function dD(g6,g5){return bp(g6,g5,"monthsShort")}function eh(g6,g7,g5){return gJ(g6,g7,g5,"weekdays")}function dV(g6,g7,g5){return gJ(g6,g7,g5,"weekdaysShort")}function ak(g6,g7,g5){return gJ(g6,g7,g5,"weekdaysMin")}K("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(g7){var g5=g7%10,g6=(dZ(g7%100/10)===1)?"th":(g5===1)?"st":(g5===2)?"nd":(g5===3)?"rd":"th";return g7+g6}});gm.lang=fK("moment.lang is deprecated. Use moment.locale instead.",K);gm.langData=fK("moment.langData is deprecated. Use moment.localeData instead.",aa);var gg=Math.abs;function bR(){var g5=this._data;this._milliseconds=gg(this._milliseconds);this._days=gg(this._days);this._months=gg(this._months);g5.milliseconds=gg(g5.milliseconds);g5.seconds=gg(g5.seconds);g5.minutes=gg(g5.minutes);g5.hours=gg(g5.hours);g5.months=gg(g5.months);g5.years=gg(g5.years);return this}function a5(g9,g6,g7,g8){var g5=eD(g6,g7);g9._milliseconds+=g8*g5._milliseconds;g9._days+=g8*g5._days;g9._months+=g8*g5._months;return g9._bubble()}function b6(g5,g6){return a5(this,g5,g6,1)}function fh(g5,g6){return a5(this,g5,g6,-1)}function go(g5){if(g5<0){return Math.floor(g5)}else{return Math.ceil(g5)}}function d4(){var g7=this._milliseconds;var hd=this._days;var g5=this._months;var g9=this._data;var hc,g8,hb,ha,g6;if(!((g7>=0&&hd>=0&&g5>=0)||(g7<=0&&hd<=0&&g5<=0))){g7+=go(gT(g5)+hd)*86400000;hd=0;g5=0}g9.milliseconds=g7%1000;hc=eG(g7/1000);g9.seconds=hc%60;g8=eG(hc/60);g9.minutes=g8%60;hb=eG(g8/60);g9.hours=hb%24;hd+=eG(hb/24);g6=eG(h(hd));g5+=g6;hd-=go(gT(g6));ha=eG(g5/12);g5%=12;g9.days=hd;g9.months=g5;g9.years=ha;return this}function h(g5){return g5*4800/146097}function gT(g5){return g5*146097/4800}function gs(g6){if(!this.isValid()){return NaN}var g8;var g5;var g7=this._milliseconds;g6=dY(g6);if(g6==="month"||g6==="year"){g8=this._days+g7/86400000;g5=this._months+h(g8);return g6==="month"?g5:g5/12}else{g8=this._days+Math.round(gT(this._months));switch(g6){case"week":return g8/7+g7/604800000;case"day":return g8+g7/86400000;case"hour":return g8*24+g7/3600000;case"minute":return g8*1440+g7/60000;case"second":return g8*86400+g7/1000;case"millisecond":return Math.floor(g8*86400000)+g7;default:throw new Error("Unknown unit "+g6)}}}function ed(){if(!this.isValid()){return NaN}return(this._milliseconds+this._days*86400000+(this._months%12)*2592000000+dZ(this._months/12)*31536000000)}function fz(g5){return function(){return this.as(g5)}}var gV=fz("ms");var V=fz("s");var eR=fz("m");var C=fz("h");var fG=fz("d");var fi=fz("w");var fy=fz("M");var bO=fz("y");function Q(g5){g5=dY(g5);return this.isValid()?this[g5+"s"]():NaN}function cS(g5){return function(){return this.isValid()?this._data[g5]:NaN}}var c=cS("milliseconds");var bJ=cS("seconds");var a4=cS("minutes");var af=cS("hours");var bH=cS("days");var gw=cS("months");var ci=cS("years");function fI(){return eG(this.days()/7)}var d9=Math.round;var e5={ss:44,s:45,m:45,h:22,d:26,M:11};function aI(g6,g8,g7,g9,g5){return g5.relativeTime(g8||1,!!g7,g6,g9)}function e8(g9,g6,hd){var g7=eD(g9).abs();var he=d9(g7.as("s"));var g8=d9(g7.as("m"));var hc=d9(g7.as("h"));var hf=d9(g7.as("d"));var g5=d9(g7.as("M"));var ha=d9(g7.as("y"));var hb=he<=e5.ss&&["s",he]||he0;hb[4]=hd;return aI.apply(null,hb)}function gb(g5){if(g5===undefined){return d9}if(typeof(g5)==="function"){d9=g5;return true}return false}function di(g5,g6){if(e5[g5]===undefined){return false}if(g6===undefined){return e5[g5]}e5[g5]=g6;if(g5==="s"){e5.ss=g6-1}return true}function a(g7){if(!this.isValid()){return this.localeData().invalidDate()}var g5=this.localeData();var g6=e8(this,!g7,g5);if(g7){g6=g5.pastFuture(+this,g6)}return g5.postformat(g6)}var bl=Math.abs;function cg(){if(!this.isValid()){return this.localeData().invalidDate()}var hf=bl(this._milliseconds)/1000;var hg=bl(this._days);var g7=bl(this._months);var g9,he,hb;g9=eG(hf/60);he=eG(g9/60);hf%=60;g9%=60;hb=eG(g7/12);g7%=12;var g6=hb;var hc=g7;var g5=hg;var ha=he;var g8=g9;var hh=hf;var hd=this.asSeconds();if(!hd){return"P0D"}return(hd<0?"-":"")+"P"+(g6?g6+"Y":"")+(hc?hc+"M":"")+(g5?g5+"D":"")+((ha||g8||hh)?"T":"")+(ha?ha+"H":"")+(g8?g8+"M":"")+(hh?hh+"S":"")}var fw=fg.prototype;fw.isValid=B;fw.abs=bR;fw.add=b6;fw.subtract=fh;fw.as=gs;fw.asMilliseconds=gV;fw.asSeconds=V;fw.asMinutes=eR;fw.asHours=C;fw.asDays=fG;fw.asWeeks=fi;fw.asMonths=fy;fw.asYears=bO;fw.valueOf=ed;fw._bubble=d4;fw.get=Q;fw.milliseconds=c;fw.seconds=bJ;fw.minutes=a4;fw.hours=af;fw.days=bH;fw.weeks=fI;fw.months=gw;fw.years=ci;fw.humanize=a;fw.toISOString=cg;fw.toString=cg;fw.toJSON=cg;fw.locale=g4;fw.localeData=fk;fw.toIsoString=fK("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",cg);fw.lang=I;dy("X",0,0,"unix");dy("x",0,0,"valueOf");bG("x",L);bG("X",gE);cs("X",function(g5,g7,g6){g6._d=new Date(parseFloat(g5,10)*1000)});cs("x",function(g5,g7,g6){g6._d=new Date(dZ(g5))});gm.version="2.18.1";bi(eZ);gm.fn=cV;gm.min=w;gm.max=bQ;gm.now=dA;gm.utc=du;gm.unix=er;gm.months=d3;gm.isDate=gc;gm.locale=K;gm.invalid=X;gm.duration=eD;gm.isMoment=cU;gm.weekdays=eh;gm.parseZone=dW;gm.localeData=aa;gm.isDuration=az;gm.monthsShort=dD;gm.weekdaysMin=ak;gm.defineLocale=dC;gm.updateLocale=f0;gm.locales=cM;gm.weekdaysShort=dV;gm.normalizeUnits=dY;gm.relativeTimeRounding=gb;gm.relativeTimeThreshold=di;gm.calendarFormat=aS;gm.prototype=cV;gm.defineLocale("af",{months:"Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember".split("_"),monthsShort:"Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des".split("_"),weekdays:"Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag".split("_"),weekdaysShort:"Son_Maa_Din_Woe_Don_Vry_Sat".split("_"),weekdaysMin:"So_Ma_Di_Wo_Do_Vr_Sa".split("_"),meridiemParse:/vm|nm/i,isPM:function(g5){return/^nm$/i.test(g5)},meridiem:function(g5,g6,g7){if(g5<12){return g7?"vm":"VM"}else{return g7?"nm":"NM"}},longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Vandag om] LT",nextDay:"[Môre om] LT",nextWeek:"dddd [om] LT",lastDay:"[Gister om] LT",lastWeek:"[Laas] dddd [om] LT",sameElse:"L"},relativeTime:{future:"oor %s",past:"%s gelede",s:"'n paar sekondes",m:"'n minuut",mm:"%d minute",h:"'n uur",hh:"%d ure",d:"'n dag",dd:"%d dae",M:"'n maand",MM:"%d maande",y:"'n jaar",yy:"%d jaar"},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(g5){return g5+((g5===1||g5===8||g5>=20)?"ste":"de")},week:{dow:1,doy:4}});gm.defineLocale("ar-dz",{months:"جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),monthsShort:"جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"أح_إث_ثلا_أر_خم_جم_سب".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:0,doy:4}});gm.defineLocale("ar-kw",{months:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),weekdays:"الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:0,doy:12}});var dq={"1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","0":"0"};var aZ=function(g5){return g5===0?0:g5===1?1:g5===2?2:g5%100>=3&&g5%100<=10?3:g5%100>=11?4:5};var cJ={s:["أقل من ثانية","ثانية واحدة",["ثانيتان","ثانيتين"],"%d ثوان","%d ثانية","%d ثانية"],m:["أقل من دقيقة","دقيقة واحدة",["دقيقتان","دقيقتين"],"%d دقائق","%d دقيقة","%d دقيقة"],h:["أقل من ساعة","ساعة واحدة",["ساعتان","ساعتين"],"%d ساعات","%d ساعة","%d ساعة"],d:["أقل من يوم","يوم واحد",["يومان","يومين"],"%d أيام","%d يومًا","%d يوم"],M:["أقل من شهر","شهر واحد",["شهران","شهرين"],"%d أشهر","%d شهرا","%d شهر"],y:["أقل من عام","عام واحد",["عامان","عامين"],"%d أعوام","%d عامًا","%d عام"]};var e7=function(g5){return function(g8,g7,g6,ha){var g9=aZ(g8),hb=cJ[g5][aZ(g8)];if(g9===2){hb=hb[g7?0:1]}return hb.replace(/%d/i,g8)}};var eB=["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر"];gm.defineLocale("ar-ly",{months:eB,monthsShort:eB,weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"D/\u200FM/\u200FYYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/ص|م/,isPM:function(g5){return"م"===g5},meridiem:function(g5,g7,g6){if(g5<12){return"ص"}else{return"م"}},calendar:{sameDay:"[اليوم عند الساعة] LT",nextDay:"[غدًا عند الساعة] LT",nextWeek:"dddd [عند الساعة] LT",lastDay:"[أمس عند الساعة] LT",lastWeek:"dddd [عند الساعة] LT",sameElse:"L"},relativeTime:{future:"بعد %s",past:"منذ %s",s:e7("s"),m:e7("m"),mm:e7("m"),h:e7("h"),hh:e7("h"),d:e7("d"),dd:e7("d"),M:e7("M"),MM:e7("M"),y:e7("y"),yy:e7("y")},preparse:function(g5){return g5.replace(/\u200f/g,"").replace(/،/g,",")},postformat:function(g5){return g5.replace(/\d/g,function(g6){return dq[g6]}).replace(/,/g,"،")},week:{dow:6,doy:12}});gm.defineLocale("ar-ma",{months:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),weekdays:"الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:6,doy:12}});var c9={"1":"١","2":"٢","3":"٣","4":"٤","5":"٥","6":"٦","7":"٧","8":"٨","9":"٩","0":"٠"};var ef={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"};gm.defineLocale("ar-sa",{months:"يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/ص|م/,isPM:function(g5){return"م"===g5},meridiem:function(g5,g7,g6){if(g5<12){return"ص"}else{return"م"}},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},preparse:function(g5){return g5.replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(g6){return ef[g6]}).replace(/،/g,",")},postformat:function(g5){return g5.replace(/\d/g,function(g6){return c9[g6]}).replace(/,/g,"،")},week:{dow:0,doy:6}});gm.defineLocale("ar-tn",{months:"جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),monthsShort:"جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:1,doy:4}});var c8={"1":"١","2":"٢","3":"٣","4":"٤","5":"٥","6":"٦","7":"٧","8":"٨","9":"٩","0":"٠"};var fW={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"};var dg=function(g5){return g5===0?0:g5===1?1:g5===2?2:g5%100>=3&&g5%100<=10?3:g5%100>=11?4:5};var fd={s:["أقل من ثانية","ثانية واحدة",["ثانيتان","ثانيتين"],"%d ثوان","%d ثانية","%d ثانية"],m:["أقل من دقيقة","دقيقة واحدة",["دقيقتان","دقيقتين"],"%d دقائق","%d دقيقة","%d دقيقة"],h:["أقل من ساعة","ساعة واحدة",["ساعتان","ساعتين"],"%d ساعات","%d ساعة","%d ساعة"],d:["أقل من يوم","يوم واحد",["يومان","يومين"],"%d أيام","%d يومًا","%d يوم"],M:["أقل من شهر","شهر واحد",["شهران","شهرين"],"%d أشهر","%d شهرا","%d شهر"],y:["أقل من عام","عام واحد",["عامان","عامين"],"%d أعوام","%d عامًا","%d عام"]};var gB=function(g5){return function(g8,g7,g6,ha){var g9=dg(g8),hb=fd[g5][dg(g8)];if(g9===2){hb=hb[g7?0:1]}return hb.replace(/%d/i,g8)}};var eA=["كانون الثاني يناير","شباط فبراير","آذار مارس","نيسان أبريل","أيار مايو","حزيران يونيو","تموز يوليو","آب أغسطس","أيلول سبتمبر","تشرين الأول أكتوبر","تشرين الثاني نوفمبر","كانون الأول ديسمبر"];gm.defineLocale("ar",{months:eA,monthsShort:eA,weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"D/\u200FM/\u200FYYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/ص|م/,isPM:function(g5){return"م"===g5},meridiem:function(g5,g7,g6){if(g5<12){return"ص"}else{return"م"}},calendar:{sameDay:"[اليوم عند الساعة] LT",nextDay:"[غدًا عند الساعة] LT",nextWeek:"dddd [عند الساعة] LT",lastDay:"[أمس عند الساعة] LT",lastWeek:"dddd [عند الساعة] LT",sameElse:"L"},relativeTime:{future:"بعد %s",past:"منذ %s",s:gB("s"),m:gB("m"),mm:gB("m"),h:gB("h"),hh:gB("h"),d:gB("d"),dd:gB("d"),M:gB("M"),MM:gB("M"),y:gB("y"),yy:gB("y")},preparse:function(g5){return g5.replace(/\u200f/g,"").replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(g6){return fW[g6]}).replace(/،/g,",")},postformat:function(g5){return g5.replace(/\d/g,function(g6){return c8[g6]}).replace(/,/g,"،")},week:{dow:6,doy:12}});var bm={1:"-inci",5:"-inci",8:"-inci",70:"-inci",80:"-inci",2:"-nci",7:"-nci",20:"-nci",50:"-nci",3:"-üncü",4:"-üncü",100:"-üncü",6:"-ncı",9:"-uncu",10:"-uncu",30:"-uncu",60:"-ıncı",90:"-ıncı"};gm.defineLocale("az",{months:"yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr".split("_"),monthsShort:"yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek".split("_"),weekdays:"Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə".split("_"),weekdaysShort:"Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən".split("_"),weekdaysMin:"Bz_BE_ÇA_Çə_CA_Cü_Şə".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[sabah saat] LT",nextWeek:"[gələn həftə] dddd [saat] LT",lastDay:"[dünən] LT",lastWeek:"[keçən həftə] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s əvvəl",s:"birneçə saniyyə",m:"bir dəqiqə",mm:"%d dəqiqə",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir il",yy:"%d il"},meridiemParse:/gecə|səhər|gündüz|axşam/,isPM:function(g5){return/^(gündüz|axşam)$/.test(g5)},meridiem:function(g5,g7,g6){if(g5<4){return"gecə"}else{if(g5<12){return"səhər"}else{if(g5<17){return"gündüz"}else{return"axşam"}}}},dayOfMonthOrdinalParse:/\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/,ordinal:function(g7){if(g7===0){return g7+"-ıncı"}var g6=g7%10,g5=g7%100-g6,g8=g7>=100?100:null;return g7+(bm[g6]||bm[g5]||bm[g8])},week:{dow:1,doy:7}});function en(g7,g6){var g5=g7.split("_");return g6%10===1&&g6%100!==11?g5[0]:(g6%10>=2&&g6%10<=4&&(g6%100<10||g6%100>=20)?g5[1]:g5[2])}function ek(g7,g6,g5){var g8={mm:g6?"хвіліна_хвіліны_хвілін":"хвіліну_хвіліны_хвілін",hh:g6?"гадзіна_гадзіны_гадзін":"гадзіну_гадзіны_гадзін",dd:"дзень_дні_дзён",MM:"месяц_месяцы_месяцаў",yy:"год_гады_гадоў"};if(g5==="m"){return g6?"хвіліна":"хвіліну"}else{if(g5==="h"){return g6?"гадзіна":"гадзіну"}else{return g7+" "+en(g8[g5],+g7)}}}gm.defineLocale("be",{months:{format:"студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня".split("_"),standalone:"студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань".split("_")},monthsShort:"студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж".split("_"),weekdays:{format:"нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу".split("_"),standalone:"нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота".split("_"),isFormat:/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/},weekdaysShort:"нд_пн_ат_ср_чц_пт_сб".split("_"),weekdaysMin:"нд_пн_ат_ср_чц_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сёння ў] LT",nextDay:"[Заўтра ў] LT",lastDay:"[Учора ў] LT",nextWeek:function(){return"[У] dddd [ў] LT"},lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return"[У мінулую] dddd [ў] LT";case 1:case 2:case 4:return"[У мінулы] dddd [ў] LT"}},sameElse:"L"},relativeTime:{future:"праз %s",past:"%s таму",s:"некалькі секунд",m:ek,mm:ek,h:ek,hh:ek,d:"дзень",dd:ek,M:"месяц",MM:ek,y:"год",yy:ek},meridiemParse:/ночы|раніцы|дня|вечара/,isPM:function(g5){return/^(дня|вечара)$/.test(g5)},meridiem:function(g5,g7,g6){if(g5<4){return"ночы"}else{if(g5<12){return"раніцы"}else{if(g5<17){return"дня"}else{return"вечара"}}}},dayOfMonthOrdinalParse:/\d{1,2}-(і|ы|га)/,ordinal:function(g5,g6){switch(g6){case"M":case"d":case"DDD":case"w":case"W":return(g5%10===2||g5%10===3)&&(g5%100!==12&&g5%100!==13)?g5+"-і":g5+"-ы";case"D":return g5+"-га";default:return g5}},week:{dow:1,doy:7}});gm.defineLocale("bg",{months:"януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"),monthsShort:"янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"),weekdays:"неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"),weekdaysShort:"нед_пон_вто_сря_чет_пет_съб".split("_"),weekdaysMin:"нд_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"D.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[Днес в] LT",nextDay:"[Утре в] LT",nextWeek:"dddd [в] LT",lastDay:"[Вчера в] LT",lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return"[В изминалата] dddd [в] LT";case 1:case 2:case 4:case 5:return"[В изминалия] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"след %s",past:"преди %s",s:"няколко секунди",m:"минута",mm:"%d минути",h:"час",hh:"%d часа",d:"ден",dd:"%d дни",M:"месец",MM:"%d месеца",y:"година",yy:"%d години"},dayOfMonthOrdinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(g7){var g6=g7%10,g5=g7%100;if(g7===0){return g7+"-ев"}else{if(g5===0){return g7+"-ен"}else{if(g5>10&&g5<20){return g7+"-ти"}else{if(g6===1){return g7+"-ви"}else{if(g6===2){return g7+"-ри"}else{if(g6===7||g6===8){return g7+"-ми"}else{return g7+"-ти"}}}}}}},week:{dow:1,doy:7}});var c7={"1":"১","2":"২","3":"৩","4":"৪","5":"৫","6":"৬","7":"৭","8":"৮","9":"৯","0":"০"};var fV={"১":"1","২":"2","৩":"3","৪":"4","৫":"5","৬":"6","৭":"7","৮":"8","৯":"9","০":"0"};gm.defineLocale("bn",{months:"জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর".split("_"),monthsShort:"জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে".split("_"),weekdays:"রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার".split("_"),weekdaysShort:"রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি".split("_"),weekdaysMin:"রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি".split("_"),longDateFormat:{LT:"A h:mm সময়",LTS:"A h:mm:ss সময়",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm সময়",LLLL:"dddd, D MMMM YYYY, A h:mm সময়"},calendar:{sameDay:"[আজ] LT",nextDay:"[আগামীকাল] LT",nextWeek:"dddd, LT",lastDay:"[গতকাল] LT",lastWeek:"[গত] dddd, LT",sameElse:"L"},relativeTime:{future:"%s পরে",past:"%s আগে",s:"কয়েক সেকেন্ড",m:"এক মিনিট",mm:"%d মিনিট",h:"এক ঘন্টা",hh:"%d ঘন্টা",d:"এক দিন",dd:"%d দিন",M:"এক মাস",MM:"%d মাস",y:"এক বছর",yy:"%d বছর"},preparse:function(g5){return g5.replace(/[১২৩৪৫৬৭৮৯০]/g,function(g6){return fV[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return c7[g6]})},meridiemParse:/রাত|সকাল|দুপুর|বিকাল|রাত/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if((g6==="রাত"&&g5>=4)||(g6==="দুপুর"&&g5<5)||g6==="বিকাল"){return g5+12}else{return g5}},meridiem:function(g5,g7,g6){if(g5<4){return"রাত"}else{if(g5<10){return"সকাল"}else{if(g5<17){return"দুপুর"}else{if(g5<20){return"বিকাল"}else{return"রাত"}}}}},week:{dow:0,doy:6}});var c5={"1":"༡","2":"༢","3":"༣","4":"༤","5":"༥","6":"༦","7":"༧","8":"༨","9":"༩","0":"༠"};var fU={"༡":"1","༢":"2","༣":"3","༤":"4","༥":"5","༦":"6","༧":"7","༨":"8","༩":"9","༠":"0"};gm.defineLocale("bo",{months:"ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ".split("_"),monthsShort:"ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ".split("_"),weekdays:"གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་".split("_"),weekdaysShort:"ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་".split("_"),weekdaysMin:"ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་".split("_"),longDateFormat:{LT:"A h:mm",LTS:"A h:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm",LLLL:"dddd, D MMMM YYYY, A h:mm"},calendar:{sameDay:"[དི་རིང] LT",nextDay:"[སང་ཉིན] LT",nextWeek:"[བདུན་ཕྲག་རྗེས་མ], LT",lastDay:"[ཁ་སང] LT",lastWeek:"[བདུན་ཕྲག་མཐའ་མ] dddd, LT",sameElse:"L"},relativeTime:{future:"%s ལ་",past:"%s སྔན་ལ",s:"ལམ་སང",m:"སྐར་མ་གཅིག",mm:"%d སྐར་མ",h:"ཆུ་ཚོད་གཅིག",hh:"%d ཆུ་ཚོད",d:"ཉིན་གཅིག",dd:"%d ཉིན་",M:"ཟླ་བ་གཅིག",MM:"%d ཟླ་བ",y:"ལོ་གཅིག",yy:"%d ལོ"},preparse:function(g5){return g5.replace(/[༡༢༣༤༥༦༧༨༩༠]/g,function(g6){return fU[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return c5[g6]})},meridiemParse:/མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if((g6==="མཚན་མོ"&&g5>=4)||(g6==="ཉིན་གུང"&&g5<5)||g6==="དགོང་དག"){return g5+12}else{return g5}},meridiem:function(g5,g7,g6){if(g5<4){return"མཚན་མོ"}else{if(g5<10){return"ཞོགས་ཀས"}else{if(g5<17){return"ཉིན་གུང"}else{if(g5<20){return"དགོང་དག"}else{return"མཚན་མོ"}}}}},week:{dow:0,doy:6}});function f(g7,g6,g5){var g8={mm:"munutenn",MM:"miz",dd:"devezh"};return g7+" "+gh(g8[g5],g7)}function aG(g5){switch(dS(g5)){case 1:case 3:case 4:case 5:case 9:return g5+" bloaz";default:return g5+" vloaz"}}function dS(g5){if(g5>9){return dS(g5%10)}return g5}function gh(g6,g5){if(g5===2){return fY(g6)}return g6}function fY(g6){var g5={m:"v",b:"v",d:"z"};if(g5[g6.charAt(0)]===undefined){return g6}return g5[g6.charAt(0)]+g6.substring(1)}gm.defineLocale("br",{months:"Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split("_"),monthsShort:"Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split("_"),weekdays:"Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split("_"),weekdaysShort:"Sul_Lun_Meu_Mer_Yao_Gwe_Sad".split("_"),weekdaysMin:"Su_Lu_Me_Mer_Ya_Gw_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"h[e]mm A",LTS:"h[e]mm:ss A",L:"DD/MM/YYYY",LL:"D [a viz] MMMM YYYY",LLL:"D [a viz] MMMM YYYY h[e]mm A",LLLL:"dddd, D [a viz] MMMM YYYY h[e]mm A"},calendar:{sameDay:"[Hiziv da] LT",nextDay:"[Warc'hoazh da] LT",nextWeek:"dddd [da] LT",lastDay:"[Dec'h da] LT",lastWeek:"dddd [paset da] LT",sameElse:"L"},relativeTime:{future:"a-benn %s",past:"%s 'zo",s:"un nebeud segondennoù",m:"ur vunutenn",mm:f,h:"un eur",hh:"%d eur",d:"un devezh",dd:f,M:"ur miz",MM:f,y:"ur bloaz",yy:aG},dayOfMonthOrdinalParse:/\d{1,2}(añ|vet)/,ordinal:function(g6){var g5=(g6===1)?"añ":"vet";return g6+g5},week:{dow:1,doy:4}});function dU(g8,g7,g6){var g5=g8+" ";switch(g6){case"m":return g7?"jedna minuta":"jedne minute";case"mm":if(g8===1){g5+="minuta"}else{if(g8===2||g8===3||g8===4){g5+="minute"}else{g5+="minuta"}}return g5;case"h":return g7?"jedan sat":"jednog sata";case"hh":if(g8===1){g5+="sat"}else{if(g8===2||g8===3||g8===4){g5+="sata"}else{g5+="sati"}}return g5;case"dd":if(g8===1){g5+="dan"}else{g5+="dana"}return g5;case"MM":if(g8===1){g5+="mjesec"}else{if(g8===2||g8===3||g8===4){g5+="mjeseca"}else{g5+="mjeseci"}}return g5;case"yy":if(g8===1){g5+="godina"}else{if(g8===2||g8===3||g8===4){g5+="godine"}else{g5+="godina"}}return g5}}gm.defineLocale("bs",{months:"januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar".split("_"),monthsShort:"jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.".split("_"),monthsParseExact:true,weekdays:"nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"),weekdaysShort:"ned._pon._uto._sri._čet._pet._sub.".split("_"),weekdaysMin:"ne_po_ut_sr_če_pe_su".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[jučer u] LT",lastWeek:function(){switch(this.day()){case 0:case 3:return"[prošlu] dddd [u] LT";case 6:return"[prošle] [subote] [u] LT";case 1:case 2:case 4:case 5:return"[prošli] dddd [u] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"par sekundi",m:dU,mm:dU,h:dU,hh:dU,d:"dan",dd:dU,M:"mjesec",MM:dU,y:"godinu",yy:dU},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}});gm.defineLocale("ca",{months:{standalone:"gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre".split("_"),format:"de gener_de febrer_de març_d'abril_de maig_de juny_de juliol_d'agost_de setembre_d'octubre_de novembre_de desembre".split("_"),isFormat:/D[oD]?(\s)+MMMM/},monthsShort:"gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.".split("_"),monthsParseExact:true,weekdays:"diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte".split("_"),weekdaysShort:"dg._dl._dt._dc._dj._dv._ds.".split("_"),weekdaysMin:"Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"[el] D MMMM [de] YYYY",ll:"D MMM YYYY",LLL:"[el] D MMMM [de] YYYY [a les] H:mm",lll:"D MMM YYYY, H:mm",LLLL:"[el] dddd D MMMM [de] YYYY [a les] H:mm",llll:"ddd D MMM YYYY, H:mm"},calendar:{sameDay:function(){return"[avui a "+((this.hours()!==1)?"les":"la")+"] LT"},nextDay:function(){return"[demà a "+((this.hours()!==1)?"les":"la")+"] LT"},nextWeek:function(){return"dddd [a "+((this.hours()!==1)?"les":"la")+"] LT"},lastDay:function(){return"[ahir a "+((this.hours()!==1)?"les":"la")+"] LT"},lastWeek:function(){return"[el] dddd [passat a "+((this.hours()!==1)?"les":"la")+"] LT"},sameElse:"L"},relativeTime:{future:"d'aquí %s",past:"fa %s",s:"uns segons",m:"un minut",mm:"%d minuts",h:"una hora",hh:"%d hores",d:"un dia",dd:"%d dies",M:"un mes",MM:"%d mesos",y:"un any",yy:"%d anys"},dayOfMonthOrdinalParse:/\d{1,2}(r|n|t|è|a)/,ordinal:function(g6,g7){var g5=(g6===1)?"r":(g6===2)?"n":(g6===3)?"r":(g6===4)?"t":"è";if(g7==="w"||g7==="W"){g5="a"}return g6+g5},week:{dow:1,doy:4}});var ez="leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec".split("_");var cP="led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro".split("_");function cI(g5){return(g5>1)&&(g5<5)&&(~~(g5/10)!==1)}function g2(g8,g7,g6,g9){var g5=g8+" ";switch(g6){case"s":return(g7||g9)?"pár sekund":"pár sekundami";case"m":return g7?"minuta":(g9?"minutu":"minutou");case"mm":if(g7||g9){return g5+(cI(g8)?"minuty":"minut")}else{return g5+"minutami"}break;case"h":return g7?"hodina":(g9?"hodinu":"hodinou");case"hh":if(g7||g9){return g5+(cI(g8)?"hodiny":"hodin")}else{return g5+"hodinami"}break;case"d":return(g7||g9)?"den":"dnem";case"dd":if(g7||g9){return g5+(cI(g8)?"dny":"dní")}else{return g5+"dny"}break;case"M":return(g7||g9)?"měsíc":"měsícem";case"MM":if(g7||g9){return g5+(cI(g8)?"měsíce":"měsíců")}else{return g5+"měsíci"}break;case"y":return(g7||g9)?"rok":"rokem";case"yy":if(g7||g9){return g5+(cI(g8)?"roky":"let")}else{return g5+"lety"}break}}gm.defineLocale("cs",{months:ez,monthsShort:cP,monthsParse:(function(g5,g7){var g6,g8=[];for(g6=0;g6<12;g6++){g8[g6]=new RegExp("^"+g5[g6]+"$|^"+g7[g6]+"$","i")}return g8}(ez,cP)),shortMonthsParse:(function(g6){var g5,g7=[];for(g5=0;g5<12;g5++){g7[g5]=new RegExp("^"+g6[g5]+"$","i")}return g7}(cP)),longMonthsParse:(function(g5){var g6,g7=[];for(g6=0;g6<12;g6++){g7[g6]=new RegExp("^"+g5[g6]+"$","i")}return g7}(ez)),weekdays:"neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota".split("_"),weekdaysShort:"ne_po_út_st_čt_pá_so".split("_"),weekdaysMin:"ne_po_út_st_čt_pá_so".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd D. MMMM YYYY H:mm",l:"D. M. YYYY"},calendar:{sameDay:"[dnes v] LT",nextDay:"[zítra v] LT",nextWeek:function(){switch(this.day()){case 0:return"[v neděli v] LT";case 1:case 2:return"[v] dddd [v] LT";case 3:return"[ve středu v] LT";case 4:return"[ve čtvrtek v] LT";case 5:return"[v pátek v] LT";case 6:return"[v sobotu v] LT"}},lastDay:"[včera v] LT",lastWeek:function(){switch(this.day()){case 0:return"[minulou neděli v] LT";case 1:case 2:return"[minulé] dddd [v] LT";case 3:return"[minulou středu v] LT";case 4:case 5:return"[minulý] dddd [v] LT";case 6:return"[minulou sobotu v] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"před %s",s:g2,m:g2,mm:g2,h:g2,hh:g2,d:g2,dd:g2,M:g2,MM:g2,y:g2,yy:g2},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("cv",{months:"кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав".split("_"),monthsShort:"кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш".split("_"),weekdays:"вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун".split("_"),weekdaysShort:"выр_тун_ытл_юн_кӗҫ_эрн_шӑм".split("_"),weekdaysMin:"вр_тн_ыт_юн_кҫ_эр_шм".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]",LLL:"YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm",LLLL:"dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm"},calendar:{sameDay:"[Паян] LT [сехетре]",nextDay:"[Ыран] LT [сехетре]",lastDay:"[Ӗнер] LT [сехетре]",nextWeek:"[Ҫитес] dddd LT [сехетре]",lastWeek:"[Иртнӗ] dddd LT [сехетре]",sameElse:"L"},relativeTime:{future:function(g6){var g5=/сехет$/i.exec(g6)?"рен":/ҫул$/i.exec(g6)?"тан":"ран";return g6+g5},past:"%s каялла",s:"пӗр-ик ҫеккунт",m:"пӗр минут",mm:"%d минут",h:"пӗр сехет",hh:"%d сехет",d:"пӗр кун",dd:"%d кун",M:"пӗр уйӑх",MM:"%d уйӑх",y:"пӗр ҫул",yy:"%d ҫул"},dayOfMonthOrdinalParse:/\d{1,2}-мӗш/,ordinal:"%d-мӗш",week:{dow:1,doy:7}});gm.defineLocale("cy",{months:"Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr".split("_"),monthsShort:"Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag".split("_"),weekdays:"Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn".split("_"),weekdaysShort:"Sul_Llun_Maw_Mer_Iau_Gwe_Sad".split("_"),weekdaysMin:"Su_Ll_Ma_Me_Ia_Gw_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Heddiw am] LT",nextDay:"[Yfory am] LT",nextWeek:"dddd [am] LT",lastDay:"[Ddoe am] LT",lastWeek:"dddd [diwethaf am] LT",sameElse:"L"},relativeTime:{future:"mewn %s",past:"%s yn ôl",s:"ychydig eiliadau",m:"munud",mm:"%d munud",h:"awr",hh:"%d awr",d:"diwrnod",dd:"%d diwrnod",M:"mis",MM:"%d mis",y:"blwyddyn",yy:"%d flynedd"},dayOfMonthOrdinalParse:/\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,ordinal:function(g7){var g5=g7,g6="",g8=["","af","il","ydd","ydd","ed","ed","ed","fed","fed","fed","eg","fed","eg","eg","fed","eg","eg","fed","eg","fed"];if(g5>20){if(g5===40||g5===50||g5===60||g5===80||g5===100){g6="fed"}else{g6="ain"}}else{if(g5>0){g6=g8[g5]}}return g7+g6},week:{dow:1,doy:4}});gm.defineLocale("da",{months:"januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tir_ons_tor_fre_lør".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd [d.] D. MMMM YYYY [kl.] HH:mm"},calendar:{sameDay:"[i dag kl.] LT",nextDay:"[i morgen kl.] LT",nextWeek:"på dddd [kl.] LT",lastDay:"[i går kl.] LT",lastWeek:"[i] dddd[s kl.] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"få sekunder",m:"et minut",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dage",M:"en måned",MM:"%d måneder",y:"et år",yy:"%d år"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});function ah(g7,g6,g5,g9){var g8={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[g7+" Tage",g7+" Tagen"],M:["ein Monat","einem Monat"],MM:[g7+" Monate",g7+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[g7+" Jahre",g7+" Jahren"]};return g6?g8[g5][0]:g8[g5][1]}gm.defineLocale("de-at",{months:"Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jän._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),monthsParseExact:true,weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd, D. MMMM YYYY HH:mm"},calendar:{sameDay:"[heute um] LT [Uhr]",sameElse:"L",nextDay:"[morgen um] LT [Uhr]",nextWeek:"dddd [um] LT [Uhr]",lastDay:"[gestern um] LT [Uhr]",lastWeek:"[letzten] dddd [um] LT [Uhr]"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:ah,mm:"%d Minuten",h:ah,hh:"%d Stunden",d:ah,dd:ah,M:ah,MM:ah,y:ah,yy:ah},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});function ax(g7,g6,g5,g9){var g8={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[g7+" Tage",g7+" Tagen"],M:["ein Monat","einem Monat"],MM:[g7+" Monate",g7+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[g7+" Jahre",g7+" Jahren"]};return g6?g8[g5][0]:g8[g5][1]}gm.defineLocale("de-ch",{months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._März_April_Mai_Juni_Juli_Aug._Sept._Okt._Nov._Dez.".split("_"),monthsParseExact:true,weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH.mm",LLLL:"dddd, D. MMMM YYYY HH.mm"},calendar:{sameDay:"[heute um] LT [Uhr]",sameElse:"L",nextDay:"[morgen um] LT [Uhr]",nextWeek:"dddd [um] LT [Uhr]",lastDay:"[gestern um] LT [Uhr]",lastWeek:"[letzten] dddd [um] LT [Uhr]"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:ax,mm:"%d Minuten",h:ax,hh:"%d Stunden",d:ax,dd:ax,M:ax,MM:ax,y:ax,yy:ax},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});function aw(g7,g6,g5,g9){var g8={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[g7+" Tage",g7+" Tagen"],M:["ein Monat","einem Monat"],MM:[g7+" Monate",g7+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[g7+" Jahre",g7+" Jahren"]};return g6?g8[g5][0]:g8[g5][1]}gm.defineLocale("de",{months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),monthsParseExact:true,weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd, D. MMMM YYYY HH:mm"},calendar:{sameDay:"[heute um] LT [Uhr]",sameElse:"L",nextDay:"[morgen um] LT [Uhr]",nextWeek:"dddd [um] LT [Uhr]",lastDay:"[gestern um] LT [Uhr]",lastWeek:"[letzten] dddd [um] LT [Uhr]"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:aw,mm:"%d Minuten",h:aw,hh:"%d Stunden",d:aw,dd:aw,M:aw,MM:aw,y:aw,yy:aw},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});var ex=["ޖެނުއަރީ","ފެބްރުއަރީ","މާރިޗު","އޭޕްރީލު","މޭ","ޖޫން","ޖުލައި","އޯގަސްޓު","ސެޕްޓެމްބަރު","އޮކްޓޯބަރު","ނޮވެމްބަރު","ޑިސެމްބަރު"];var fF=["އާދިއްތަ","ހޯމަ","އަންގާރަ","ބުދަ","ބުރާސްފަތި","ހުކުރު","ހޮނިހިރު"];gm.defineLocale("dv",{months:ex,monthsShort:ex,weekdays:fF,weekdaysShort:fF,weekdaysMin:"އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"D/M/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/މކ|މފ/,isPM:function(g5){return"މފ"===g5},meridiem:function(g5,g7,g6){if(g5<12){return"މކ"}else{return"މފ"}},calendar:{sameDay:"[މިއަދު] LT",nextDay:"[މާދަމާ] LT",nextWeek:"dddd LT",lastDay:"[އިއްޔެ] LT",lastWeek:"[ފާއިތުވި] dddd LT",sameElse:"L"},relativeTime:{future:"ތެރޭގައި %s",past:"ކުރިން %s",s:"ސިކުންތުކޮޅެއް",m:"މިނިޓެއް",mm:"މިނިޓު %d",h:"ގަޑިއިރެއް",hh:"ގަޑިއިރު %d",d:"ދުވަހެއް",dd:"ދުވަސް %d",M:"މަހެއް",MM:"މަސް %d",y:"އަހަރެއް",yy:"އަހަރު %d"},preparse:function(g5){return g5.replace(/،/g,",")},postformat:function(g5){return g5.replace(/,/g,"،")},week:{dow:7,doy:12}});gm.defineLocale("el",{monthsNominativeEl:"Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"),monthsGenitiveEl:"Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου".split("_"),months:function(g6,g5){if(!g6){return this._monthsNominativeEl}else{if(/D/.test(g5.substring(0,g5.indexOf("MMMM")))){return this._monthsGenitiveEl[g6.month()]}else{return this._monthsNominativeEl[g6.month()]}}},monthsShort:"Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"),weekdays:"Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"),weekdaysShort:"Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"),weekdaysMin:"Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"),meridiem:function(g5,g6,g7){if(g5>11){return g7?"μμ":"ΜΜ"}else{return g7?"πμ":"ΠΜ"}},isPM:function(g5){return((g5+"").toLowerCase()[0]==="μ")},meridiemParse:/[ΠΜ]\.?Μ?\.?/i,longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendarEl:{sameDay:"[Σήμερα {}] LT",nextDay:"[Αύριο {}] LT",nextWeek:"dddd [{}] LT",lastDay:"[Χθες {}] LT",lastWeek:function(){switch(this.day()){case 6:return"[το προηγούμενο] dddd [{}] LT";default:return"[την προηγούμενη] dddd [{}] LT"}},sameElse:"L"},calendar:function(g7,g8){var g6=this._calendarEl[g7],g5=g8&&g8.hours();if(bz(g6)){g6=g6.apply(g8)}return g6.replace("{}",(g5%12===1?"στη":"στις"))},relativeTime:{future:"σε %s",past:"%s πριν",s:"λίγα δευτερόλεπτα",m:"ένα λεπτό",mm:"%d λεπτά",h:"μία ώρα",hh:"%d ώρες",d:"μία μέρα",dd:"%d μέρες",M:"ένας μήνας",MM:"%d μήνες",y:"ένας χρόνος",yy:"%d χρόνια"},dayOfMonthOrdinalParse:/\d{1,2}η/,ordinal:"%dη",week:{dow:1,doy:4}});gm.defineLocale("en-au",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(g7){var g5=g7%10,g6=(~~(g7%100/10)===1)?"th":(g5===1)?"st":(g5===2)?"nd":(g5===3)?"rd":"th";return g7+g6},week:{dow:1,doy:4}});gm.defineLocale("en-ca",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"YYYY-MM-DD",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(g7){var g5=g7%10,g6=(~~(g7%100/10)===1)?"th":(g5===1)?"st":(g5===2)?"nd":(g5===3)?"rd":"th";return g7+g6}});gm.defineLocale("en-gb",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(g7){var g5=g7%10,g6=(~~(g7%100/10)===1)?"th":(g5===1)?"st":(g5===2)?"nd":(g5===3)?"rd":"th";return g7+g6},week:{dow:1,doy:4}});gm.defineLocale("en-ie",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(g7){var g5=g7%10,g6=(~~(g7%100/10)===1)?"th":(g5===1)?"st":(g5===2)?"nd":(g5===3)?"rd":"th";return g7+g6},week:{dow:1,doy:4}});gm.defineLocale("en-nz",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(g7){var g5=g7%10,g6=(~~(g7%100/10)===1)?"th":(g5===1)?"st":(g5===2)?"nd":(g5===3)?"rd":"th";return g7+g6},week:{dow:1,doy:4}});gm.defineLocale("eo",{months:"januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec".split("_"),weekdays:"dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato".split("_"),weekdaysShort:"dim_lun_mard_merk_ĵaŭ_ven_sab".split("_"),weekdaysMin:"di_lu_ma_me_ĵa_ve_sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D[-a de] MMMM, YYYY",LLL:"D[-a de] MMMM, YYYY HH:mm",LLLL:"dddd, [la] D[-a de] MMMM, YYYY HH:mm"},meridiemParse:/[ap]\.t\.m/i,isPM:function(g5){return g5.charAt(0).toLowerCase()==="p"},meridiem:function(g5,g6,g7){if(g5>11){return g7?"p.t.m.":"P.T.M."}else{return g7?"a.t.m.":"A.T.M."}},calendar:{sameDay:"[Hodiaŭ je] LT",nextDay:"[Morgaŭ je] LT",nextWeek:"dddd [je] LT",lastDay:"[Hieraŭ je] LT",lastWeek:"[pasinta] dddd [je] LT",sameElse:"L"},relativeTime:{future:"post %s",past:"antaŭ %s",s:"sekundoj",m:"minuto",mm:"%d minutoj",h:"horo",hh:"%d horoj",d:"tago",dd:"%d tagoj",M:"monato",MM:"%d monatoj",y:"jaro",yy:"%d jaroj"},dayOfMonthOrdinalParse:/\d{1,2}a/,ordinal:"%da",week:{dow:1,doy:7}});var gN="ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_");var df="ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic".split("_");gm.defineLocale("es-do",{months:"enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"),monthsShort:function(g5,g6){if(!g5){return gN}else{if(/-MMM-/.test(g6)){return df[g5.month()]}else{return gN[g5.month()]}}},monthsParseExact:true,weekdays:"domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"),weekdaysShort:"dom._lun._mar._mié._jue._vie._sáb.".split("_"),weekdaysMin:"do_lu_ma_mi_ju_vi_sá".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY h:mm A",LLLL:"dddd, D [de] MMMM [de] YYYY h:mm A"},calendar:{sameDay:function(){return"[hoy a la"+((this.hours()!==1)?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+((this.hours()!==1)?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+((this.hours()!==1)?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+((this.hours()!==1)?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+((this.hours()!==1)?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}});var eE="ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_");var dd="ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic".split("_");gm.defineLocale("es",{months:"enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"),monthsShort:function(g5,g6){if(!g5){return eE}else{if(/-MMM-/.test(g6)){return dd[g5.month()]}else{return eE[g5.month()]}}},monthsParseExact:true,weekdays:"domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"),weekdaysShort:"dom._lun._mar._mié._jue._vie._sáb.".split("_"),weekdaysMin:"do_lu_ma_mi_ju_vi_sá".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY H:mm",LLLL:"dddd, D [de] MMMM [de] YYYY H:mm"},calendar:{sameDay:function(){return"[hoy a la"+((this.hours()!==1)?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+((this.hours()!==1)?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+((this.hours()!==1)?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+((this.hours()!==1)?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+((this.hours()!==1)?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}});function at(g7,g6,g5,g9){var g8={s:["mõne sekundi","mõni sekund","paar sekundit"],m:["ühe minuti","üks minut"],mm:[g7+" minuti",g7+" minutit"],h:["ühe tunni","tund aega","üks tund"],hh:[g7+" tunni",g7+" tundi"],d:["ühe päeva","üks päev"],M:["kuu aja","kuu aega","üks kuu"],MM:[g7+" kuu",g7+" kuud"],y:["ühe aasta","aasta","üks aasta"],yy:[g7+" aasta",g7+" aastat"]};if(g6){return g8[g5][2]?g8[g5][2]:g8[g5][1]}return g9?g8[g5][0]:g8[g5][1]}gm.defineLocale("et",{months:"jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember".split("_"),monthsShort:"jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets".split("_"),weekdays:"pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev".split("_"),weekdaysShort:"P_E_T_K_N_R_L".split("_"),weekdaysMin:"P_E_T_K_N_R_L".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[Täna,] LT",nextDay:"[Homme,] LT",nextWeek:"[Järgmine] dddd LT",lastDay:"[Eile,] LT",lastWeek:"[Eelmine] dddd LT",sameElse:"L"},relativeTime:{future:"%s pärast",past:"%s tagasi",s:at,m:at,mm:at,h:at,hh:at,d:at,dd:"%d päeva",M:at,MM:at,y:at,yy:at},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("eu",{months:"urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"),monthsShort:"urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"),monthsParseExact:true,weekdays:"igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"),weekdaysShort:"ig._al._ar._az._og._ol._lr.".split("_"),weekdaysMin:"ig_al_ar_az_og_ol_lr".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"YYYY[ko] MMMM[ren] D[a]",LLL:"YYYY[ko] MMMM[ren] D[a] HH:mm",LLLL:"dddd, YYYY[ko] MMMM[ren] D[a] HH:mm",l:"YYYY-M-D",ll:"YYYY[ko] MMM D[a]",lll:"YYYY[ko] MMM D[a] HH:mm",llll:"ddd, YYYY[ko] MMM D[a] HH:mm"},calendar:{sameDay:"[gaur] LT[etan]",nextDay:"[bihar] LT[etan]",nextWeek:"dddd LT[etan]",lastDay:"[atzo] LT[etan]",lastWeek:"[aurreko] dddd LT[etan]",sameElse:"L"},relativeTime:{future:"%s barru",past:"duela %s",s:"segundo batzuk",m:"minutu bat",mm:"%d minutu",h:"ordu bat",hh:"%d ordu",d:"egun bat",dd:"%d egun",M:"hilabete bat",MM:"%d hilabete",y:"urte bat",yy:"%d urte"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}});var c4={"1":"۱","2":"۲","3":"۳","4":"۴","5":"۵","6":"۶","7":"۷","8":"۸","9":"۹","0":"۰"};var fT={"۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9","۰":"0"};gm.defineLocale("fa",{months:"ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر".split("_"),monthsShort:"ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر".split("_"),weekdays:"یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه".split("_"),weekdaysShort:"یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه".split("_"),weekdaysMin:"ی_د_س_چ_پ_ج_ش".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},meridiemParse:/قبل از ظهر|بعد از ظهر/,isPM:function(g5){return/بعد از ظهر/.test(g5)},meridiem:function(g5,g7,g6){if(g5<12){return"قبل از ظهر"}else{return"بعد از ظهر"}},calendar:{sameDay:"[امروز ساعت] LT",nextDay:"[فردا ساعت] LT",nextWeek:"dddd [ساعت] LT",lastDay:"[دیروز ساعت] LT",lastWeek:"dddd [پیش] [ساعت] LT",sameElse:"L"},relativeTime:{future:"در %s",past:"%s پیش",s:"چند ثانیه",m:"یک دقیقه",mm:"%d دقیقه",h:"یک ساعت",hh:"%d ساعت",d:"یک روز",dd:"%d روز",M:"یک ماه",MM:"%d ماه",y:"یک سال",yy:"%d سال"},preparse:function(g5){return g5.replace(/[۰-۹]/g,function(g6){return fT[g6]}).replace(/،/g,",")},postformat:function(g5){return g5.replace(/\d/g,function(g6){return c4[g6]}).replace(/,/g,"،")},dayOfMonthOrdinalParse:/\d{1,2}م/,ordinal:"%dم",week:{dow:6,doy:12}});var u="nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän".split(" ");var aY=["nolla","yhden","kahden","kolmen","neljän","viiden","kuuden",u[7],u[8],u[9]];function g1(g8,g7,g6,g9){var g5="";switch(g6){case"s":return g9?"muutaman sekunnin":"muutama sekunti";case"m":return g9?"minuutin":"minuutti";case"mm":g5=g9?"minuutin":"minuuttia";break;case"h":return g9?"tunnin":"tunti";case"hh":g5=g9?"tunnin":"tuntia";break;case"d":return g9?"päivän":"päivä";case"dd":g5=g9?"päivän":"päivää";break;case"M":return g9?"kuukauden":"kuukausi";case"MM":g5=g9?"kuukauden":"kuukautta";break;case"y":return g9?"vuoden":"vuosi";case"yy":g5=g9?"vuoden":"vuotta";break}g5=ec(g8,g9)+" "+g5;return g5}function ec(g5,g6){return g5<10?(g6?aY[g5]:u[g5]):g5}gm.defineLocale("fi",{months:"tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"),monthsShort:"tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"),weekdays:"sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"),weekdaysShort:"su_ma_ti_ke_to_pe_la".split("_"),weekdaysMin:"su_ma_ti_ke_to_pe_la".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD.MM.YYYY",LL:"Do MMMM[ta] YYYY",LLL:"Do MMMM[ta] YYYY, [klo] HH.mm",LLLL:"dddd, Do MMMM[ta] YYYY, [klo] HH.mm",l:"D.M.YYYY",ll:"Do MMM YYYY",lll:"Do MMM YYYY, [klo] HH.mm",llll:"ddd, Do MMM YYYY, [klo] HH.mm"},calendar:{sameDay:"[tänään] [klo] LT",nextDay:"[huomenna] [klo] LT",nextWeek:"dddd [klo] LT",lastDay:"[eilen] [klo] LT",lastWeek:"[viime] dddd[na] [klo] LT",sameElse:"L"},relativeTime:{future:"%s päästä",past:"%s sitten",s:g1,m:g1,mm:g1,h:g1,hh:g1,d:g1,dd:g1,M:g1,MM:g1,y:g1,yy:g1},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("fo",{months:"januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"),weekdaysShort:"sun_mán_týs_mik_hós_frí_ley".split("_"),weekdaysMin:"su_má_tý_mi_hó_fr_le".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D. MMMM, YYYY HH:mm"},calendar:{sameDay:"[Í dag kl.] LT",nextDay:"[Í morgin kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[Í gjár kl.] LT",lastWeek:"[síðstu] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"um %s",past:"%s síðani",s:"fá sekund",m:"ein minutt",mm:"%d minuttir",h:"ein tími",hh:"%d tímar",d:"ein dagur",dd:"%d dagar",M:"ein mánaði",MM:"%d mánaðir",y:"eitt ár",yy:"%d ár"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("fr-ca",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),monthsParseExact:true,weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Aujourd’hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"un an",yy:"%d ans"},dayOfMonthOrdinalParse:/\d{1,2}(er|e)/,ordinal:function(g5,g6){switch(g6){default:case"M":case"Q":case"D":case"DDD":case"d":return g5+(g5===1?"er":"e");case"w":case"W":return g5+(g5===1?"re":"e")}}});gm.defineLocale("fr-ch",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),monthsParseExact:true,weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Aujourd’hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"un an",yy:"%d ans"},dayOfMonthOrdinalParse:/\d{1,2}(er|e)/,ordinal:function(g5,g6){switch(g6){default:case"M":case"Q":case"D":case"DDD":case"d":return g5+(g5===1?"er":"e");case"w":case"W":return g5+(g5===1?"re":"e")}},week:{dow:1,doy:4}});gm.defineLocale("fr",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),monthsParseExact:true,weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Aujourd’hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"un an",yy:"%d ans"},dayOfMonthOrdinalParse:/\d{1,2}(er|)/,ordinal:function(g5,g6){switch(g6){case"D":return g5+(g5===1?"er":"");default:case"M":case"Q":case"DDD":case"d":return g5+(g5===1?"er":"e");case"w":case"W":return g5+(g5===1?"re":"e")}},week:{dow:1,doy:4}});var f2="jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.".split("_");var gv="jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_");gm.defineLocale("fy",{months:"jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber".split("_"),monthsShort:function(g5,g6){if(!g5){return f2}else{if(/-MMM-/.test(g6)){return gv[g5.month()]}else{return f2[g5.month()]}}},monthsParseExact:true,weekdays:"snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon".split("_"),weekdaysShort:"si._mo._ti._wo._to._fr._so.".split("_"),weekdaysMin:"Si_Mo_Ti_Wo_To_Fr_So".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[hjoed om] LT",nextDay:"[moarn om] LT",nextWeek:"dddd [om] LT",lastDay:"[juster om] LT",lastWeek:"[ôfrûne] dddd [om] LT",sameElse:"L"},relativeTime:{future:"oer %s",past:"%s lyn",s:"in pear sekonden",m:"ien minút",mm:"%d minuten",h:"ien oere",hh:"%d oeren",d:"ien dei",dd:"%d dagen",M:"ien moanne",MM:"%d moannen",y:"ien jier",yy:"%d jierren"},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(g5){return g5+((g5===1||g5===8||g5>=20)?"ste":"de")},week:{dow:1,doy:4}});var ew=["Am Faoilleach","An Gearran","Am Màrt","An Giblean","An Cèitean","An t-Ògmhios","An t-Iuchar","An Lùnastal","An t-Sultain","An Dàmhair","An t-Samhain","An Dùbhlachd"];var dc=["Faoi","Gear","Màrt","Gibl","Cèit","Ògmh","Iuch","Lùn","Sult","Dàmh","Samh","Dùbh"];var bN=["Didòmhnaich","Diluain","Dimàirt","Diciadain","Diardaoin","Dihaoine","Disathairne"];var fN=["Did","Dil","Dim","Dic","Dia","Dih","Dis"];var G=["Dò","Lu","Mà","Ci","Ar","Ha","Sa"];gm.defineLocale("gd",{months:ew,monthsShort:dc,monthsParseExact:true,weekdays:bN,weekdaysShort:fN,weekdaysMin:G,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[An-diugh aig] LT",nextDay:"[A-màireach aig] LT",nextWeek:"dddd [aig] LT",lastDay:"[An-dè aig] LT",lastWeek:"dddd [seo chaidh] [aig] LT",sameElse:"L"},relativeTime:{future:"ann an %s",past:"bho chionn %s",s:"beagan diogan",m:"mionaid",mm:"%d mionaidean",h:"uair",hh:"%d uairean",d:"latha",dd:"%d latha",M:"mìos",MM:"%d mìosan",y:"bliadhna",yy:"%d bliadhna"},dayOfMonthOrdinalParse:/\d{1,2}(d|na|mh)/,ordinal:function(g6){var g5=g6===1?"d":g6%10===2?"na":"mh";return g6+g5},week:{dow:1,doy:4}});gm.defineLocale("gl",{months:"xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro".split("_"),monthsShort:"xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.".split("_"),monthsParseExact:true,weekdays:"domingo_luns_martes_mércores_xoves_venres_sábado".split("_"),weekdaysShort:"dom._lun._mar._mér._xov._ven._sáb.".split("_"),weekdaysMin:"do_lu_ma_mé_xo_ve_sá".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY H:mm",LLLL:"dddd, D [de] MMMM [de] YYYY H:mm"},calendar:{sameDay:function(){return"[hoxe "+((this.hours()!==1)?"ás":"á")+"] LT"},nextDay:function(){return"[mañá "+((this.hours()!==1)?"ás":"á")+"] LT"},nextWeek:function(){return"dddd ["+((this.hours()!==1)?"ás":"a")+"] LT"},lastDay:function(){return"[onte "+((this.hours()!==1)?"á":"a")+"] LT"},lastWeek:function(){return"[o] dddd [pasado "+((this.hours()!==1)?"ás":"a")+"] LT"},sameElse:"L"},relativeTime:{future:function(g5){if(g5.indexOf("un")===0){return"n"+g5}return"en "+g5},past:"hai %s",s:"uns segundos",m:"un minuto",mm:"%d minutos",h:"unha hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un ano",yy:"%d anos"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}});function ar(g7,g6,g5,g9){var g8={s:["thodde secondanim","thodde second"],m:["eka mintan","ek minute"],mm:[g7+" mintanim",g7+" mintam"],h:["eka horan","ek hor"],hh:[g7+" horanim",g7+" hor"],d:["eka disan","ek dis"],dd:[g7+" disanim",g7+" dis"],M:["eka mhoinean","ek mhoino"],MM:[g7+" mhoineanim",g7+" mhoine"],y:["eka vorsan","ek voros"],yy:[g7+" vorsanim",g7+" vorsam"]};return g6?g8[g5][0]:g8[g5][1]}gm.defineLocale("gom-latn",{months:"Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr".split("_"),monthsShort:"Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.".split("_"),monthsParseExact:true,weekdays:"Aitar_Somar_Mongllar_Budvar_Brestar_Sukrar_Son'var".split("_"),weekdaysShort:"Ait._Som._Mon._Bud._Bre._Suk._Son.".split("_"),weekdaysMin:"Ai_Sm_Mo_Bu_Br_Su_Sn".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"A h:mm [vazta]",LTS:"A h:mm:ss [vazta]",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY A h:mm [vazta]",LLLL:"dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]",llll:"ddd, D MMM YYYY, A h:mm [vazta]"},calendar:{sameDay:"[Aiz] LT",nextDay:"[Faleam] LT",nextWeek:"[Ieta to] dddd[,] LT",lastDay:"[Kal] LT",lastWeek:"[Fatlo] dddd[,] LT",sameElse:"L"},relativeTime:{future:"%s",past:"%s adim",s:ar,m:ar,mm:ar,h:ar,hh:ar,d:ar,dd:ar,M:ar,MM:ar,y:ar,yy:ar},dayOfMonthOrdinalParse:/\d{1,2}(er)/,ordinal:function(g5,g6){switch(g6){case"D":return g5+"er";default:case"M":case"Q":case"DDD":case"d":case"w":case"W":return g5}},week:{dow:1,doy:4},meridiemParse:/rati|sokalli|donparam|sanje/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="rati"){return g5<4?g5:g5+12}else{if(g6==="sokalli"){return g5}else{if(g6==="donparam"){return g5>12?g5:g5+12}else{if(g6==="sanje"){return g5+12}}}}},meridiem:function(g5,g7,g6){if(g5<4){return"rati"}else{if(g5<12){return"sokalli"}else{if(g5<16){return"donparam"}else{if(g5<20){return"sanje"}else{return"rati"}}}}}});gm.defineLocale("he",{months:"ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר".split("_"),monthsShort:"ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳".split("_"),weekdays:"ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת".split("_"),weekdaysShort:"א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"),weekdaysMin:"א_ב_ג_ד_ה_ו_ש".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [ב]MMMM YYYY",LLL:"D [ב]MMMM YYYY HH:mm",LLLL:"dddd, D [ב]MMMM YYYY HH:mm",l:"D/M/YYYY",ll:"D MMM YYYY",lll:"D MMM YYYY HH:mm",llll:"ddd, D MMM YYYY HH:mm"},calendar:{sameDay:"[היום ב־]LT",nextDay:"[מחר ב־]LT",nextWeek:"dddd [בשעה] LT",lastDay:"[אתמול ב־]LT",lastWeek:"[ביום] dddd [האחרון בשעה] LT",sameElse:"L"},relativeTime:{future:"בעוד %s",past:"לפני %s",s:"מספר שניות",m:"דקה",mm:"%d דקות",h:"שעה",hh:function(g5){if(g5===2){return"שעתיים"}return g5+" שעות"},d:"יום",dd:function(g5){if(g5===2){return"יומיים"}return g5+" ימים"},M:"חודש",MM:function(g5){if(g5===2){return"חודשיים"}return g5+" חודשים"},y:"שנה",yy:function(g5){if(g5===2){return"שנתיים"}else{if(g5%10===0&&g5!==10){return g5+" שנה"}}return g5+" שנים"}},meridiemParse:/אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i,isPM:function(g5){return/^(אחה"צ|אחרי הצהריים|בערב)$/.test(g5)},meridiem:function(g5,g7,g6){if(g5<5){return"לפנות בוקר"}else{if(g5<10){return"בבוקר"}else{if(g5<12){return g6?'לפנה"צ':"לפני הצהריים"}else{if(g5<18){return g6?'אחה"צ':"אחרי הצהריים"}else{return"בערב"}}}}}});var c1={"1":"१","2":"२","3":"३","4":"४","5":"५","6":"६","7":"७","8":"८","9":"९","0":"०"};var fS={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"};gm.defineLocale("hi",{months:"जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर".split("_"),monthsShort:"जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.".split("_"),monthsParseExact:true,weekdays:"रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार".split("_"),weekdaysShort:"रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि".split("_"),weekdaysMin:"र_सो_मं_बु_गु_शु_श".split("_"),longDateFormat:{LT:"A h:mm बजे",LTS:"A h:mm:ss बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm बजे",LLLL:"dddd, D MMMM YYYY, A h:mm बजे"},calendar:{sameDay:"[आज] LT",nextDay:"[कल] LT",nextWeek:"dddd, LT",lastDay:"[कल] LT",lastWeek:"[पिछले] dddd, LT",sameElse:"L"},relativeTime:{future:"%s में",past:"%s पहले",s:"कुछ ही क्षण",m:"एक मिनट",mm:"%d मिनट",h:"एक घंटा",hh:"%d घंटे",d:"एक दिन",dd:"%d दिन",M:"एक महीने",MM:"%d महीने",y:"एक वर्ष",yy:"%d वर्ष"},preparse:function(g5){return g5.replace(/[१२३४५६७८९०]/g,function(g6){return fS[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return c1[g6]})},meridiemParse:/रात|सुबह|दोपहर|शाम/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="रात"){return g5<4?g5:g5+12}else{if(g6==="सुबह"){return g5}else{if(g6==="दोपहर"){return g5>=10?g5:g5+12}else{if(g6==="शाम"){return g5+12}}}}},meridiem:function(g5,g7,g6){if(g5<4){return"रात"}else{if(g5<10){return"सुबह"}else{if(g5<17){return"दोपहर"}else{if(g5<20){return"शाम"}else{return"रात"}}}}},week:{dow:0,doy:6}});function gZ(g8,g7,g6){var g5=g8+" ";switch(g6){case"m":return g7?"jedna minuta":"jedne minute";case"mm":if(g8===1){g5+="minuta"}else{if(g8===2||g8===3||g8===4){g5+="minute"}else{g5+="minuta"}}return g5;case"h":return g7?"jedan sat":"jednog sata";case"hh":if(g8===1){g5+="sat"}else{if(g8===2||g8===3||g8===4){g5+="sata"}else{g5+="sati"}}return g5;case"dd":if(g8===1){g5+="dan"}else{g5+="dana"}return g5;case"MM":if(g8===1){g5+="mjesec"}else{if(g8===2||g8===3||g8===4){g5+="mjeseca"}else{g5+="mjeseci"}}return g5;case"yy":if(g8===1){g5+="godina"}else{if(g8===2||g8===3||g8===4){g5+="godine"}else{g5+="godina"}}return g5}}gm.defineLocale("hr",{months:{format:"siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca".split("_"),standalone:"siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac".split("_")},monthsShort:"sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.".split("_"),monthsParseExact:true,weekdays:"nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"),weekdaysShort:"ned._pon._uto._sri._čet._pet._sub.".split("_"),weekdaysMin:"ne_po_ut_sr_če_pe_su".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[jučer u] LT",lastWeek:function(){switch(this.day()){case 0:case 3:return"[prošlu] dddd [u] LT";case 6:return"[prošle] [subote] [u] LT";case 1:case 2:case 4:case 5:return"[prošli] dddd [u] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"par sekundi",m:gZ,mm:gZ,h:gZ,hh:gZ,d:"dan",dd:gZ,M:"mjesec",MM:gZ,y:"godinu",yy:gZ},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}});var fa="vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton".split(" ");function gY(g8,g7,g6,ha){var g5=g8,g9;switch(g6){case"s":return(ha||g7)?"néhány másodperc":"néhány másodperce";case"m":return"egy"+(ha||g7?" perc":" perce");case"mm":return g5+(ha||g7?" perc":" perce");case"h":return"egy"+(ha||g7?" óra":" órája");case"hh":return g5+(ha||g7?" óra":" órája");case"d":return"egy"+(ha||g7?" nap":" napja");case"dd":return g5+(ha||g7?" nap":" napja");case"M":return"egy"+(ha||g7?" hónap":" hónapja");case"MM":return g5+(ha||g7?" hónap":" hónapja");case"y":return"egy"+(ha||g7?" év":" éve");case"yy":return g5+(ha||g7?" év":" éve")}return""}function aD(g5){return(g5?"":"[múlt] ")+"["+fa[this.day()]+"] LT[-kor]"}gm.defineLocale("hu",{months:"január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"),monthsShort:"jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"),weekdays:"vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat".split("_"),weekdaysShort:"vas_hét_kedd_sze_csüt_pén_szo".split("_"),weekdaysMin:"v_h_k_sze_cs_p_szo".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"YYYY.MM.DD.",LL:"YYYY. MMMM D.",LLL:"YYYY. MMMM D. H:mm",LLLL:"YYYY. MMMM D., dddd H:mm"},meridiemParse:/de|du/i,isPM:function(g5){return g5.charAt(1).toLowerCase()==="u"},meridiem:function(g5,g6,g7){if(g5<12){return g7===true?"de":"DE"}else{return g7===true?"du":"DU"}},calendar:{sameDay:"[ma] LT[-kor]",nextDay:"[holnap] LT[-kor]",nextWeek:function(){return aD.call(this,true)},lastDay:"[tegnap] LT[-kor]",lastWeek:function(){return aD.call(this,false)},sameElse:"L"},relativeTime:{future:"%s múlva",past:"%s",s:gY,m:gY,mm:gY,h:gY,hh:gY,d:gY,dd:gY,M:gY,MM:gY,y:gY,yy:gY},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("hy-am",{months:{format:"հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի".split("_"),standalone:"հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր".split("_")},monthsShort:"հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ".split("_"),weekdays:"կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ".split("_"),weekdaysShort:"կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"),weekdaysMin:"կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY թ.",LLL:"D MMMM YYYY թ., HH:mm",LLLL:"dddd, D MMMM YYYY թ., HH:mm"},calendar:{sameDay:"[այսօր] LT",nextDay:"[վաղը] LT",lastDay:"[երեկ] LT",nextWeek:function(){return"dddd [օրը ժամը] LT"},lastWeek:function(){return"[անցած] dddd [օրը ժամը] LT"},sameElse:"L"},relativeTime:{future:"%s հետո",past:"%s առաջ",s:"մի քանի վայրկյան",m:"րոպե",mm:"%d րոպե",h:"ժամ",hh:"%d ժամ",d:"օր",dd:"%d օր",M:"ամիս",MM:"%d ամիս",y:"տարի",yy:"%d տարի"},meridiemParse:/գիշերվա|առավոտվա|ցերեկվա|երեկոյան/,isPM:function(g5){return/^(ցերեկվա|երեկոյան)$/.test(g5)},meridiem:function(g5){if(g5<4){return"գիշերվա"}else{if(g5<12){return"առավոտվա"}else{if(g5<17){return"ցերեկվա"}else{return"երեկոյան"}}}},dayOfMonthOrdinalParse:/\d{1,2}|\d{1,2}-(ին|րդ)/,ordinal:function(g5,g6){switch(g6){case"DDD":case"w":case"W":case"DDDo":if(g5===1){return g5+"-ին"}return g5+"-րդ";default:return g5}},week:{dow:1,doy:7}});gm.defineLocale("id",{months:"Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"),weekdays:"Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"),weekdaysShort:"Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"),weekdaysMin:"Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|siang|sore|malam/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="pagi"){return g5}else{if(g6==="siang"){return g5>=11?g5:g5+12}else{if(g6==="sore"||g6==="malam"){return g5+12}}}},meridiem:function(g5,g6,g7){if(g5<11){return"pagi"}else{if(g5<15){return"siang"}else{if(g5<19){return"sore"}else{return"malam"}}}},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Besok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kemarin pukul] LT",lastWeek:"dddd [lalu pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lalu",s:"beberapa detik",m:"semenit",mm:"%d menit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}});function cG(g5){if(g5%100===11){return true}else{if(g5%10===1){return false}}return true}function gX(g8,g7,g6,g9){var g5=g8+" ";switch(g6){case"s":return g7||g9?"nokkrar sekúndur":"nokkrum sekúndum";case"m":return g7?"mínúta":"mínútu";case"mm":if(cG(g8)){return g5+(g7||g9?"mínútur":"mínútum")}else{if(g7){return g5+"mínúta"}}return g5+"mínútu";case"hh":if(cG(g8)){return g5+(g7||g9?"klukkustundir":"klukkustundum")}return g5+"klukkustund";case"d":if(g7){return"dagur"}return g9?"dag":"degi";case"dd":if(cG(g8)){if(g7){return g5+"dagar"}return g5+(g9?"daga":"dögum")}else{if(g7){return g5+"dagur"}}return g5+(g9?"dag":"degi");case"M":if(g7){return"mánuður"}return g9?"mánuð":"mánuði";case"MM":if(cG(g8)){if(g7){return g5+"mánuðir"}return g5+(g9?"mánuði":"mánuðum")}else{if(g7){return g5+"mánuður"}}return g5+(g9?"mánuð":"mánuði");case"y":return g7||g9?"ár":"ári";case"yy":if(cG(g8)){return g5+(g7||g9?"ár":"árum")}return g5+(g7||g9?"ár":"ári")}}gm.defineLocale("is",{months:"janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"),monthsShort:"jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"),weekdays:"sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"),weekdaysShort:"sun_mán_þri_mið_fim_fös_lau".split("_"),weekdaysMin:"Su_Má_Þr_Mi_Fi_Fö_La".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] H:mm",LLLL:"dddd, D. MMMM YYYY [kl.] H:mm"},calendar:{sameDay:"[í dag kl.] LT",nextDay:"[á morgun kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[í gær kl.] LT",lastWeek:"[síðasta] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"eftir %s",past:"fyrir %s síðan",s:gX,m:gX,mm:gX,h:"klukkustund",hh:gX,d:gX,dd:gX,M:gX,MM:gX,y:gX,yy:gX},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("it",{months:"gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre".split("_"),monthsShort:"gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic".split("_"),weekdays:"domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato".split("_"),weekdaysShort:"dom_lun_mar_mer_gio_ven_sab".split("_"),weekdaysMin:"do_lu_ma_me_gi_ve_sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:function(){switch(this.day()){case 0:return"[la scorsa] dddd [alle] LT";default:return"[lo scorso] dddd [alle] LT"}},sameElse:"L"},relativeTime:{future:function(g5){return((/^[0-9].+$/).test(g5)?"tra":"in")+" "+g5},past:"%s fa",s:"alcuni secondi",m:"un minuto",mm:"%d minuti",h:"un'ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}});gm.defineLocale("ja",{months:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"),weekdaysShort:"日_月_火_水_木_金_土".split("_"),weekdaysMin:"日_月_火_水_木_金_土".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日 HH:mm",LLLL:"YYYY年M月D日 HH:mm dddd",l:"YYYY/MM/DD",ll:"YYYY年M月D日",lll:"YYYY年M月D日 HH:mm",llll:"YYYY年M月D日 HH:mm dddd"},meridiemParse:/午前|午後/i,isPM:function(g5){return g5==="午後"},meridiem:function(g5,g7,g6){if(g5<12){return"午前"}else{return"午後"}},calendar:{sameDay:"[今日] LT",nextDay:"[明日] LT",nextWeek:"[来週]dddd LT",lastDay:"[昨日] LT",lastWeek:"[前週]dddd LT",sameElse:"L"},dayOfMonthOrdinalParse:/\d{1,2}日/,ordinal:function(g5,g6){switch(g6){case"d":case"D":case"DDD":return g5+"日";default:return g5}},relativeTime:{future:"%s後",past:"%s前",s:"数秒",m:"1分",mm:"%d分",h:"1時間",hh:"%d時間",d:"1日",dd:"%d日",M:"1ヶ月",MM:"%dヶ月",y:"1年",yy:"%d年"}});gm.defineLocale("jv",{months:"Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des".split("_"),weekdays:"Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu".split("_"),weekdaysShort:"Min_Sen_Sel_Reb_Kem_Jem_Sep".split("_"),weekdaysMin:"Mg_Sn_Sl_Rb_Km_Jm_Sp".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/enjing|siyang|sonten|ndalu/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="enjing"){return g5}else{if(g6==="siyang"){return g5>=11?g5:g5+12}else{if(g6==="sonten"||g6==="ndalu"){return g5+12}}}},meridiem:function(g5,g6,g7){if(g5<11){return"enjing"}else{if(g5<15){return"siyang"}else{if(g5<19){return"sonten"}else{return"ndalu"}}}},calendar:{sameDay:"[Dinten puniko pukul] LT",nextDay:"[Mbenjang pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kala wingi pukul] LT",lastWeek:"dddd [kepengker pukul] LT",sameElse:"L"},relativeTime:{future:"wonten ing %s",past:"%s ingkang kepengker",s:"sawetawis detik",m:"setunggal menit",mm:"%d menit",h:"setunggal jam",hh:"%d jam",d:"sedinten",dd:"%d dinten",M:"sewulan",MM:"%d wulan",y:"setaun",yy:"%d taun"},week:{dow:1,doy:7}});gm.defineLocale("ka",{months:{standalone:"იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი".split("_"),format:"იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს".split("_")},monthsShort:"იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ".split("_"),weekdays:{standalone:"კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი".split("_"),format:"კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს".split("_"),isFormat:/(წინა|შემდეგ)/},weekdaysShort:"კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ".split("_"),weekdaysMin:"კვ_ორ_სა_ოთ_ხუ_პა_შა".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[დღეს] LT[-ზე]",nextDay:"[ხვალ] LT[-ზე]",lastDay:"[გუშინ] LT[-ზე]",nextWeek:"[შემდეგ] dddd LT[-ზე]",lastWeek:"[წინა] dddd LT-ზე",sameElse:"L"},relativeTime:{future:function(g5){return(/(წამი|წუთი|საათი|წელი)/).test(g5)?g5.replace(/ი$/,"ში"):g5+"ში"},past:function(g5){if((/(წამი|წუთი|საათი|დღე|თვე)/).test(g5)){return g5.replace(/(ი|ე)$/,"ის უკან")}if((/წელი/).test(g5)){return g5.replace(/წელი$/,"წლის უკან")}},s:"რამდენიმე წამი",m:"წუთი",mm:"%d წუთი",h:"საათი",hh:"%d საათი",d:"დღე",dd:"%d დღე",M:"თვე",MM:"%d თვე",y:"წელი",yy:"%d წელი"},dayOfMonthOrdinalParse:/0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/,ordinal:function(g5){if(g5===0){return g5}if(g5===1){return g5+"-ლი"}if((g5<20)||(g5<=100&&(g5%20===0))||(g5%100===0)){return"მე-"+g5}return g5+"-ე"},week:{dow:1,doy:7}});var r={0:"-ші",1:"-ші",2:"-ші",3:"-ші",4:"-ші",5:"-ші",6:"-шы",7:"-ші",8:"-ші",9:"-шы",10:"-шы",20:"-шы",30:"-шы",40:"-шы",50:"-ші",60:"-шы",70:"-ші",80:"-ші",90:"-шы",100:"-ші"};gm.defineLocale("kk",{months:"қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан".split("_"),monthsShort:"қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел".split("_"),weekdays:"жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі".split("_"),weekdaysShort:"жек_дүй_сей_сәр_бей_жұм_сен".split("_"),weekdaysMin:"жк_дй_сй_ср_бй_жм_сн".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Бүгін сағат] LT",nextDay:"[Ертең сағат] LT",nextWeek:"dddd [сағат] LT",lastDay:"[Кеше сағат] LT",lastWeek:"[Өткен аптаның] dddd [сағат] LT",sameElse:"L"},relativeTime:{future:"%s ішінде",past:"%s бұрын",s:"бірнеше секунд",m:"бір минут",mm:"%d минут",h:"бір сағат",hh:"%d сағат",d:"бір күн",dd:"%d күн",M:"бір ай",MM:"%d ай",y:"бір жыл",yy:"%d жыл"},dayOfMonthOrdinalParse:/\d{1,2}-(ші|шы)/,ordinal:function(g7){var g6=g7%10,g5=g7>=100?100:null;return g7+(r[g7]||r[g6]||r[g5])},week:{dow:1,doy:7}});gm.defineLocale("km",{months:"មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ".split("_"),monthsShort:"មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ".split("_"),weekdays:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),weekdaysShort:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),weekdaysMin:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[ថ្ងៃនេះ ម៉ោង] LT",nextDay:"[ស្អែក ម៉ោង] LT",nextWeek:"dddd [ម៉ោង] LT",lastDay:"[ម្សិលមិញ ម៉ោង] LT",lastWeek:"dddd [សប្តាហ៍មុន] [ម៉ោង] LT",sameElse:"L"},relativeTime:{future:"%sទៀត",past:"%sមុន",s:"ប៉ុន្មានវិនាទី",m:"មួយនាទី",mm:"%d នាទី",h:"មួយម៉ោង",hh:"%d ម៉ោង",d:"មួយថ្ងៃ",dd:"%d ថ្ងៃ",M:"មួយខែ",MM:"%d ខែ",y:"មួយឆ្នាំ",yy:"%d ឆ្នាំ"},week:{dow:1,doy:4}});var cZ={"1":"೧","2":"೨","3":"೩","4":"೪","5":"೫","6":"೬","7":"೭","8":"೮","9":"೯","0":"೦"};var fR={"೧":"1","೨":"2","೩":"3","೪":"4","೫":"5","೬":"6","೭":"7","೮":"8","೯":"9","೦":"0"};gm.defineLocale("kn",{months:"ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್".split("_"),monthsShort:"ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬ_ಅಕ್ಟೋಬ_ನವೆಂಬ_ಡಿಸೆಂಬ".split("_"),monthsParseExact:true,weekdays:"ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ".split("_"),weekdaysShort:"ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ".split("_"),weekdaysMin:"ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ".split("_"),longDateFormat:{LT:"A h:mm",LTS:"A h:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm",LLLL:"dddd, D MMMM YYYY, A h:mm"},calendar:{sameDay:"[ಇಂದು] LT",nextDay:"[ನಾಳೆ] LT",nextWeek:"dddd, LT",lastDay:"[ನಿನ್ನೆ] LT",lastWeek:"[ಕೊನೆಯ] dddd, LT",sameElse:"L"},relativeTime:{future:"%s ನಂತರ",past:"%s ಹಿಂದೆ",s:"ಕೆಲವು ಕ್ಷಣಗಳು",m:"ಒಂದು ನಿಮಿಷ",mm:"%d ನಿಮಿಷ",h:"ಒಂದು ಗಂಟೆ",hh:"%d ಗಂಟೆ",d:"ಒಂದು ದಿನ",dd:"%d ದಿನ",M:"ಒಂದು ತಿಂಗಳು",MM:"%d ತಿಂಗಳು",y:"ಒಂದು ವರ್ಷ",yy:"%d ವರ್ಷ"},preparse:function(g5){return g5.replace(/[೧೨೩೪೫೬೭೮೯೦]/g,function(g6){return fR[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return cZ[g6]})},meridiemParse:/ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="ರಾತ್ರಿ"){return g5<4?g5:g5+12}else{if(g6==="ಬೆಳಿಗ್ಗೆ"){return g5}else{if(g6==="ಮಧ್ಯಾಹ್ನ"){return g5>=10?g5:g5+12}else{if(g6==="ಸಂಜೆ"){return g5+12}}}}},meridiem:function(g5,g7,g6){if(g5<4){return"ರಾತ್ರಿ"}else{if(g5<10){return"ಬೆಳಿಗ್ಗೆ"}else{if(g5<17){return"ಮಧ್ಯಾಹ್ನ"}else{if(g5<20){return"ಸಂಜೆ"}else{return"ರಾತ್ರಿ"}}}}},dayOfMonthOrdinalParse:/\d{1,2}(ನೇ)/,ordinal:function(g5){return g5+"ನೇ"},week:{dow:0,doy:6}});gm.defineLocale("ko",{months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),weekdaysMin:"일_월_화_수_목_금_토".split("_"),longDateFormat:{LT:"A h:mm",LTS:"A h:mm:ss",L:"YYYY.MM.DD",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 A h:mm",LLLL:"YYYY년 MMMM D일 dddd A h:mm",l:"YYYY.MM.DD",ll:"YYYY년 MMMM D일",lll:"YYYY년 MMMM D일 A h:mm",llll:"YYYY년 MMMM D일 dddd A h:mm"},calendar:{sameDay:"오늘 LT",nextDay:"내일 LT",nextWeek:"dddd LT",lastDay:"어제 LT",lastWeek:"지난주 dddd LT",sameElse:"L"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇 초",ss:"%d초",m:"1분",mm:"%d분",h:"한 시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한 달",MM:"%d달",y:"일 년",yy:"%d년"},dayOfMonthOrdinalParse:/\d{1,2}일/,ordinal:"%d일",meridiemParse:/오전|오후/,isPM:function(g5){return g5==="오후"},meridiem:function(g5,g7,g6){return g5<12?"오전":"오후"}});var n={0:"-чү",1:"-чи",2:"-чи",3:"-чү",4:"-чү",5:"-чи",6:"-чы",7:"-чи",8:"-чи",9:"-чу",10:"-чу",20:"-чы",30:"-чу",40:"-чы",50:"-чү",60:"-чы",70:"-чи",80:"-чи",90:"-чу",100:"-чү"};gm.defineLocale("ky",{months:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),monthsShort:"янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек".split("_"),weekdays:"Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби".split("_"),weekdaysShort:"Жек_Дүй_Шей_Шар_Бей_Жум_Ише".split("_"),weekdaysMin:"Жк_Дй_Шй_Шр_Бй_Жм_Иш".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Бүгүн саат] LT",nextDay:"[Эртең саат] LT",nextWeek:"dddd [саат] LT",lastDay:"[Кече саат] LT",lastWeek:"[Өткен аптанын] dddd [күнү] [саат] LT",sameElse:"L"},relativeTime:{future:"%s ичинде",past:"%s мурун",s:"бирнече секунд",m:"бир мүнөт",mm:"%d мүнөт",h:"бир саат",hh:"%d саат",d:"бир күн",dd:"%d күн",M:"бир ай",MM:"%d ай",y:"бир жыл",yy:"%d жыл"},dayOfMonthOrdinalParse:/\d{1,2}-(чи|чы|чү|чу)/,ordinal:function(g7){var g6=g7%10,g5=g7>=100?100:null;return g7+(n[g7]||n[g6]||n[g5])},week:{dow:1,doy:7}});function ap(g7,g6,g5,g9){var g8={m:["eng Minutt","enger Minutt"],h:["eng Stonn","enger Stonn"],d:["een Dag","engem Dag"],M:["ee Mount","engem Mount"],y:["ee Joer","engem Joer"]};return g6?g8[g5][0]:g8[g5][1]}function gy(g5){var g6=g5.substr(0,g5.indexOf(" "));if(dP(g6)){return"a "+g5}return"an "+g5}function gp(g5){var g6=g5.substr(0,g5.indexOf(" "));if(dP(g6)){return"viru "+g5}return"virun "+g5}function dP(g6){g6=parseInt(g6,10);if(isNaN(g6)){return false}if(g6<0){return true}else{if(g6<10){if(4<=g6&&g6<=7){return true}return false}else{if(g6<100){var g5=g6%10,g7=g6/10;if(g5===0){return dP(g7)}return dP(g5)}else{if(g6<10000){while(g6>=10){g6=g6/10}return dP(g6)}else{g6=g6/1000;return dP(g6)}}}}}gm.defineLocale("lb",{months:"Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),monthsParseExact:true,weekdays:"Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg".split("_"),weekdaysShort:"So._Mé._Dë._Më._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mé_Dë_Më_Do_Fr_Sa".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm [Auer]",LTS:"H:mm:ss [Auer]",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm [Auer]",LLLL:"dddd, D. MMMM YYYY H:mm [Auer]"},calendar:{sameDay:"[Haut um] LT",sameElse:"L",nextDay:"[Muer um] LT",nextWeek:"dddd [um] LT",lastDay:"[Gëschter um] LT",lastWeek:function(){switch(this.day()){case 2:case 4:return"[Leschten] dddd [um] LT";default:return"[Leschte] dddd [um] LT"}}},relativeTime:{future:gy,past:gp,s:"e puer Sekonnen",m:ap,mm:"%d Minutten",h:ap,hh:"%d Stonnen",d:ap,dd:"%d Deeg",M:ap,MM:"%d Méint",y:ap,yy:"%d Joer"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("lo",{months:"ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ".split("_"),monthsShort:"ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ".split("_"),weekdays:"ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ".split("_"),weekdaysShort:"ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ".split("_"),weekdaysMin:"ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"ວັນdddd D MMMM YYYY HH:mm"},meridiemParse:/ຕອນເຊົ້າ|ຕອນແລງ/,isPM:function(g5){return g5==="ຕອນແລງ"},meridiem:function(g5,g7,g6){if(g5<12){return"ຕອນເຊົ້າ"}else{return"ຕອນແລງ"}},calendar:{sameDay:"[ມື້ນີ້ເວລາ] LT",nextDay:"[ມື້ອື່ນເວລາ] LT",nextWeek:"[ວັນ]dddd[ໜ້າເວລາ] LT",lastDay:"[ມື້ວານນີ້ເວລາ] LT",lastWeek:"[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT",sameElse:"L"},relativeTime:{future:"ອີກ %s",past:"%sຜ່ານມາ",s:"ບໍ່ເທົ່າໃດວິນາທີ",m:"1 ນາທີ",mm:"%d ນາທີ",h:"1 ຊົ່ວໂມງ",hh:"%d ຊົ່ວໂມງ",d:"1 ມື້",dd:"%d ມື້",M:"1 ເດືອນ",MM:"%d ເດືອນ",y:"1 ປີ",yy:"%d ປີ"},dayOfMonthOrdinalParse:/(ທີ່)\d{1,2}/,ordinal:function(g5){return"ທີ່"+g5}});var e={m:"minutė_minutės_minutę",mm:"minutės_minučių_minutes",h:"valanda_valandos_valandą",hh:"valandos_valandų_valandas",d:"diena_dienos_dieną",dd:"dienos_dienų_dienas",M:"mėnuo_mėnesio_mėnesį",MM:"mėnesiai_mėnesių_mėnesius",y:"metai_metų_metus",yy:"metai_metų_metus"};function e4(g7,g6,g5,g8){if(g6){return"kelios sekundės"}else{return g8?"kelių sekundžių":"kelias sekundes"}}function gd(g7,g6,g5,g8){return g6?aX(g5)[0]:(g8?aX(g5)[1]:aX(g5)[2])}function cq(g5){return g5%10===0||(g5>10&&g5<20)}function aX(g5){return e[g5].split("_")}function gU(g8,g7,g6,g9){var g5=g8+" ";if(g8===1){return g5+gd(g8,g7,g6[0],g9)}else{if(g7){return g5+(cq(g8)?aX(g6)[1]:aX(g6)[0])}else{if(g9){return g5+aX(g6)[1]}else{return g5+(cq(g8)?aX(g6)[1]:aX(g6)[2])}}}}gm.defineLocale("lt",{months:{format:"sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio".split("_"),standalone:"sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis".split("_"),isFormat:/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/},monthsShort:"sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"),weekdays:{format:"sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį".split("_"),standalone:"sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis".split("_"),isFormat:/dddd HH:mm/},weekdaysShort:"Sek_Pir_Ant_Tre_Ket_Pen_Šeš".split("_"),weekdaysMin:"S_P_A_T_K_Pn_Š".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"YYYY [m.] MMMM D [d.]",LLL:"YYYY [m.] MMMM D [d.], HH:mm [val.]",LLLL:"YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]",l:"YYYY-MM-DD",ll:"YYYY [m.] MMMM D [d.]",lll:"YYYY [m.] MMMM D [d.], HH:mm [val.]",llll:"YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]"},calendar:{sameDay:"[Šiandien] LT",nextDay:"[Rytoj] LT",nextWeek:"dddd LT",lastDay:"[Vakar] LT",lastWeek:"[Praėjusį] dddd LT",sameElse:"L"},relativeTime:{future:"po %s",past:"prieš %s",s:e4,m:gd,mm:gU,h:gd,hh:gU,d:gd,dd:gU,M:gd,MM:gU,y:gd,yy:gU},dayOfMonthOrdinalParse:/\d{1,2}-oji/,ordinal:function(g5){return g5+"-oji"},week:{dow:1,doy:4}});var bK={m:"minūtes_minūtēm_minūte_minūtes".split("_"),mm:"minūtes_minūtēm_minūte_minūtes".split("_"),h:"stundas_stundām_stunda_stundas".split("_"),hh:"stundas_stundām_stunda_stundas".split("_"),d:"dienas_dienām_diena_dienas".split("_"),dd:"dienas_dienām_diena_dienas".split("_"),M:"mēneša_mēnešiem_mēnesis_mēneši".split("_"),MM:"mēneša_mēnešiem_mēnesis_mēneši".split("_"),y:"gada_gadiem_gads_gadi".split("_"),yy:"gada_gadiem_gads_gadi".split("_")};function bf(g5,g7,g6){if(g6){return g7%10===1&&g7%100!==11?g5[2]:g5[3]}else{return g7%10===1&&g7%100!==11?g5[0]:g5[1]}}function dJ(g7,g6,g5){return g7+" "+bf(bK[g5],g7,g6)}function eq(g7,g6,g5){return bf(bK[g5],g7,g6)}function by(g6,g5){return g5?"dažas sekundes":"dažām sekundēm"}gm.defineLocale("lv",{months:"janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris".split("_"),monthsShort:"jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec".split("_"),weekdays:"svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena".split("_"),weekdaysShort:"Sv_P_O_T_C_Pk_S".split("_"),weekdaysMin:"Sv_P_O_T_C_Pk_S".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY.",LL:"YYYY. [gada] D. MMMM",LLL:"YYYY. [gada] D. MMMM, HH:mm",LLLL:"YYYY. [gada] D. MMMM, dddd, HH:mm"},calendar:{sameDay:"[Šodien pulksten] LT",nextDay:"[Rīt pulksten] LT",nextWeek:"dddd [pulksten] LT",lastDay:"[Vakar pulksten] LT",lastWeek:"[Pagājušā] dddd [pulksten] LT",sameElse:"L"},relativeTime:{future:"pēc %s",past:"pirms %s",s:by,m:eq,mm:dJ,h:eq,hh:dJ,d:eq,dd:dJ,M:eq,MM:dJ,y:eq,yy:dJ},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});var f9={words:{m:["jedan minut","jednog minuta"],mm:["minut","minuta","minuta"],h:["jedan sat","jednog sata"],hh:["sat","sata","sati"],dd:["dan","dana","dana"],MM:["mjesec","mjeseca","mjeseci"],yy:["godina","godine","godina"]},correctGrammaticalCase:function(g6,g5){return g6===1?g5[0]:(g6>=2&&g6<=4?g5[1]:g5[2])},translate:function(g8,g6,g5){var g7=f9.words[g5];if(g5.length===1){return g6?g7[0]:g7[1]}else{return g8+" "+f9.correctGrammaticalCase(g8,g7)}}};gm.defineLocale("me",{months:"januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar".split("_"),monthsShort:"jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.".split("_"),monthsParseExact:true,weekdays:"nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"),weekdaysShort:"ned._pon._uto._sri._čet._pet._sub.".split("_"),weekdaysMin:"ne_po_ut_sr_če_pe_su".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sjutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[juče u] LT",lastWeek:function(){var g5=["[prošle] [nedjelje] [u] LT","[prošlog] [ponedjeljka] [u] LT","[prošlog] [utorka] [u] LT","[prošle] [srijede] [u] LT","[prošlog] [četvrtka] [u] LT","[prošlog] [petka] [u] LT","[prošle] [subote] [u] LT"];return g5[this.day()]},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"nekoliko sekundi",m:f9.translate,mm:f9.translate,h:f9.translate,hh:f9.translate,d:"dan",dd:f9.translate,M:"mjesec",MM:f9.translate,y:"godinu",yy:f9.translate},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}});gm.defineLocale("mi",{months:"Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea".split("_"),monthsShort:"Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki".split("_"),monthsRegex:/(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,monthsStrictRegex:/(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,monthsShortRegex:/(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,monthsShortStrictRegex:/(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i,weekdays:"Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei".split("_"),weekdaysShort:"Ta_Ma_Tū_We_Tāi_Pa_Hā".split("_"),weekdaysMin:"Ta_Ma_Tū_We_Tāi_Pa_Hā".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [i] HH:mm",LLLL:"dddd, D MMMM YYYY [i] HH:mm"},calendar:{sameDay:"[i teie mahana, i] LT",nextDay:"[apopo i] LT",nextWeek:"dddd [i] LT",lastDay:"[inanahi i] LT",lastWeek:"dddd [whakamutunga i] LT",sameElse:"L"},relativeTime:{future:"i roto i %s",past:"%s i mua",s:"te hēkona ruarua",m:"he meneti",mm:"%d meneti",h:"te haora",hh:"%d haora",d:"he ra",dd:"%d ra",M:"he marama",MM:"%d marama",y:"he tau",yy:"%d tau"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}});gm.defineLocale("mk",{months:"јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември".split("_"),monthsShort:"јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек".split("_"),weekdays:"недела_понеделник_вторник_среда_четврток_петок_сабота".split("_"),weekdaysShort:"нед_пон_вто_сре_чет_пет_саб".split("_"),weekdaysMin:"нe_пo_вт_ср_че_пе_сa".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"D.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[Денес во] LT",nextDay:"[Утре во] LT",nextWeek:"[Во] dddd [во] LT",lastDay:"[Вчера во] LT",lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return"[Изминатата] dddd [во] LT";case 1:case 2:case 4:case 5:return"[Изминатиот] dddd [во] LT"}},sameElse:"L"},relativeTime:{future:"после %s",past:"пред %s",s:"неколку секунди",m:"минута",mm:"%d минути",h:"час",hh:"%d часа",d:"ден",dd:"%d дена",M:"месец",MM:"%d месеци",y:"година",yy:"%d години"},dayOfMonthOrdinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(g7){var g6=g7%10,g5=g7%100;if(g7===0){return g7+"-ев"}else{if(g5===0){return g7+"-ен"}else{if(g5>10&&g5<20){return g7+"-ти"}else{if(g6===1){return g7+"-ви"}else{if(g6===2){return g7+"-ри"}else{if(g6===7||g6===8){return g7+"-ми"}else{return g7+"-ти"}}}}}}},week:{dow:1,doy:7}});gm.defineLocale("ml",{months:"ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ".split("_"),monthsShort:"ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.".split("_"),monthsParseExact:true,weekdays:"ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച".split("_"),weekdaysShort:"ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി".split("_"),weekdaysMin:"ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ".split("_"),longDateFormat:{LT:"A h:mm -നു",LTS:"A h:mm:ss -നു",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm -നു",LLLL:"dddd, D MMMM YYYY, A h:mm -നു"},calendar:{sameDay:"[ഇന്ന്] LT",nextDay:"[നാളെ] LT",nextWeek:"dddd, LT",lastDay:"[ഇന്നലെ] LT",lastWeek:"[കഴിഞ്ഞ] dddd, LT",sameElse:"L"},relativeTime:{future:"%s കഴിഞ്ഞ്",past:"%s മുൻപ്",s:"അൽപ നിമിഷങ്ങൾ",m:"ഒരു മിനിറ്റ്",mm:"%d മിനിറ്റ്",h:"ഒരു മണിക്കൂർ",hh:"%d മണിക്കൂർ",d:"ഒരു ദിവസം",dd:"%d ദിവസം",M:"ഒരു മാസം",MM:"%d മാസം",y:"ഒരു വർഷം",yy:"%d വർഷം"},meridiemParse:/രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i,meridiemHour:function(g5,g6){if(g5===12){g5=0}if((g6==="രാത്രി"&&g5>=4)||g6==="ഉച്ച കഴിഞ്ഞ്"||g6==="വൈകുന്നേരം"){return g5+12}else{return g5}},meridiem:function(g5,g7,g6){if(g5<4){return"രാത്രി"}else{if(g5<12){return"രാവിലെ"}else{if(g5<17){return"ഉച്ച കഴിഞ്ഞ്"}else{if(g5<20){return"വൈകുന്നേരം"}else{return"രാത്രി"}}}}}});var cY={"1":"१","2":"२","3":"३","4":"४","5":"५","6":"६","7":"७","8":"८","9":"९","0":"०"};var fQ={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"};function g3(g8,g7,g6,g9){var g5="";if(g7){switch(g6){case"s":g5="काही सेकंद";break;case"m":g5="एक मिनिट";break;case"mm":g5="%d मिनिटे";break;case"h":g5="एक तास";break;case"hh":g5="%d तास";break;case"d":g5="एक दिवस";break;case"dd":g5="%d दिवस";break;case"M":g5="एक महिना";break;case"MM":g5="%d महिने";break;case"y":g5="एक वर्ष";break;case"yy":g5="%d वर्षे";break}}else{switch(g6){case"s":g5="काही सेकंदां";break;case"m":g5="एका मिनिटा";break;case"mm":g5="%d मिनिटां";break;case"h":g5="एका तासा";break;case"hh":g5="%d तासां";break;case"d":g5="एका दिवसा";break;case"dd":g5="%d दिवसां";break;case"M":g5="एका महिन्या";break;case"MM":g5="%d महिन्यां";break;case"y":g5="एका वर्षा";break;case"yy":g5="%d वर्षां";break}}return g5.replace(/%d/i,g8)}gm.defineLocale("mr",{months:"जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर".split("_"),monthsShort:"जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.".split("_"),monthsParseExact:true,weekdays:"रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार".split("_"),weekdaysShort:"रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि".split("_"),weekdaysMin:"र_सो_मं_बु_गु_शु_श".split("_"),longDateFormat:{LT:"A h:mm वाजता",LTS:"A h:mm:ss वाजता",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm वाजता",LLLL:"dddd, D MMMM YYYY, A h:mm वाजता"},calendar:{sameDay:"[आज] LT",nextDay:"[उद्या] LT",nextWeek:"dddd, LT",lastDay:"[काल] LT",lastWeek:"[मागील] dddd, LT",sameElse:"L"},relativeTime:{future:"%sमध्ये",past:"%sपूर्वी",s:g3,m:g3,mm:g3,h:g3,hh:g3,d:g3,dd:g3,M:g3,MM:g3,y:g3,yy:g3},preparse:function(g5){return g5.replace(/[१२३४५६७८९०]/g,function(g6){return fQ[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return cY[g6]})},meridiemParse:/रात्री|सकाळी|दुपारी|सायंकाळी/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="रात्री"){return g5<4?g5:g5+12}else{if(g6==="सकाळी"){return g5}else{if(g6==="दुपारी"){return g5>=10?g5:g5+12}else{if(g6==="सायंकाळी"){return g5+12}}}}},meridiem:function(g5,g7,g6){if(g5<4){return"रात्री"}else{if(g5<10){return"सकाळी"}else{if(g5<17){return"दुपारी"}else{if(g5<20){return"सायंकाळी"}else{return"रात्री"}}}}},week:{dow:0,doy:6}});gm.defineLocale("ms-my",{months:"Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"),monthsShort:"Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"),weekdays:"Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"),weekdaysShort:"Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"),weekdaysMin:"Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|tengahari|petang|malam/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="pagi"){return g5}else{if(g6==="tengahari"){return g5>=11?g5:g5+12}else{if(g6==="petang"||g6==="malam"){return g5+12}}}},meridiem:function(g5,g6,g7){if(g5<11){return"pagi"}else{if(g5<15){return"tengahari"}else{if(g5<19){return"petang"}else{return"malam"}}}},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Esok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kelmarin pukul] LT",lastWeek:"dddd [lepas pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lepas",s:"beberapa saat",m:"seminit",mm:"%d minit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}});gm.defineLocale("ms",{months:"Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"),monthsShort:"Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"),weekdays:"Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"),weekdaysShort:"Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"),weekdaysMin:"Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|tengahari|petang|malam/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="pagi"){return g5}else{if(g6==="tengahari"){return g5>=11?g5:g5+12}else{if(g6==="petang"||g6==="malam"){return g5+12}}}},meridiem:function(g5,g6,g7){if(g5<11){return"pagi"}else{if(g5<15){return"tengahari"}else{if(g5<19){return"petang"}else{return"malam"}}}},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Esok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kelmarin pukul] LT",lastWeek:"dddd [lepas pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lepas",s:"beberapa saat",m:"seminit",mm:"%d minit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}});var cX={"1":"၁","2":"၂","3":"၃","4":"၄","5":"၅","6":"၆","7":"၇","8":"၈","9":"၉","0":"၀"};var fP={"၁":"1","၂":"2","၃":"3","၄":"4","၅":"5","၆":"6","၇":"7","၈":"8","၉":"9","၀":"0"};gm.defineLocale("my",{months:"ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ".split("_"),monthsShort:"ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ".split("_"),weekdays:"တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ".split("_"),weekdaysShort:"နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ".split("_"),weekdaysMin:"နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[ယနေ.] LT [မှာ]",nextDay:"[မနက်ဖြန်] LT [မှာ]",nextWeek:"dddd LT [မှာ]",lastDay:"[မနေ.က] LT [မှာ]",lastWeek:"[ပြီးခဲ့သော] dddd LT [မှာ]",sameElse:"L"},relativeTime:{future:"လာမည့် %s မှာ",past:"လွန်ခဲ့သော %s က",s:"စက္ကန်.အနည်းငယ်",m:"တစ်မိနစ်",mm:"%d မိနစ်",h:"တစ်နာရီ",hh:"%d နာရီ",d:"တစ်ရက်",dd:"%d ရက်",M:"တစ်လ",MM:"%d လ",y:"တစ်နှစ်",yy:"%d နှစ်"},preparse:function(g5){return g5.replace(/[၁၂၃၄၅၆၇၈၉၀]/g,function(g6){return fP[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return cX[g6]})},week:{dow:1,doy:4}});gm.defineLocale("nb",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.".split("_"),monthsParseExact:true,weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"sø._ma._ti._on._to._fr._lø.".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] HH:mm",LLLL:"dddd D. MMMM YYYY [kl.] HH:mm"},calendar:{sameDay:"[i dag kl.] LT",nextDay:"[i morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[i går kl.] LT",lastWeek:"[forrige] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});var gL={"1":"१","2":"२","3":"३","4":"४","5":"५","6":"६","7":"७","8":"८","9":"९","0":"०"};var fO={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"};gm.defineLocale("ne",{months:"जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर".split("_"),monthsShort:"जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.".split("_"),monthsParseExact:true,weekdays:"आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार".split("_"),weekdaysShort:"आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.".split("_"),weekdaysMin:"आ._सो._मं._बु._बि._शु._श.".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"Aको h:mm बजे",LTS:"Aको h:mm:ss बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, Aको h:mm बजे",LLLL:"dddd, D MMMM YYYY, Aको h:mm बजे"},preparse:function(g5){return g5.replace(/[१२३४५६७८९०]/g,function(g6){return fO[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return gL[g6]})},meridiemParse:/राति|बिहान|दिउँसो|साँझ/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="राति"){return g5<4?g5:g5+12}else{if(g6==="बिहान"){return g5}else{if(g6==="दिउँसो"){return g5>=10?g5:g5+12}else{if(g6==="साँझ"){return g5+12}}}}},meridiem:function(g5,g7,g6){if(g5<3){return"राति"}else{if(g5<12){return"बिहान"}else{if(g5<16){return"दिउँसो"}else{if(g5<20){return"साँझ"}else{return"राति"}}}}},calendar:{sameDay:"[आज] LT",nextDay:"[भोलि] LT",nextWeek:"[आउँदो] dddd[,] LT",lastDay:"[हिजो] LT",lastWeek:"[गएको] dddd[,] LT",sameElse:"L"},relativeTime:{future:"%sमा",past:"%s अगाडि",s:"केही क्षण",m:"एक मिनेट",mm:"%d मिनेट",h:"एक घण्टा",hh:"%d घण्टा",d:"एक दिन",dd:"%d दिन",M:"एक महिना",MM:"%d महिना",y:"एक बर्ष",yy:"%d बर्ष"},week:{dow:0,doy:6}});var dw="jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_");var dz="jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_");var fv=[/^jan/i,/^feb/i,/^maart|mrt.?$/i,/^apr/i,/^mei$/i,/^jun[i.]?$/i,/^jul[i.]?$/i,/^aug/i,/^sep/i,/^okt/i,/^nov/i,/^dec/i];var fE=/^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;gm.defineLocale("nl-be",{months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:function(g5,g6){if(!g5){return dw}else{if(/-MMM-/.test(g6)){return dz[g5.month()]}else{return dw[g5.month()]}}},monthsRegex:fE,monthsShortRegex:fE,monthsStrictRegex:/^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i,monthsShortStrictRegex:/^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,monthsParse:fv,longMonthsParse:fv,shortMonthsParse:fv,weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[vandaag om] LT",nextDay:"[morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(g5){return g5+((g5===1||g5===8||g5>=20)?"ste":"de")},week:{dow:1,doy:4}});var dr="jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_");var dv="jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_");var aC=[/^jan/i,/^feb/i,/^maart|mrt.?$/i,/^apr/i,/^mei$/i,/^jun[i.]?$/i,/^jul[i.]?$/i,/^aug/i,/^sep/i,/^okt/i,/^nov/i,/^dec/i];var fD=/^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;gm.defineLocale("nl",{months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:function(g5,g6){if(!g5){return dr}else{if(/-MMM-/.test(g6)){return dv[g5.month()]}else{return dr[g5.month()]}}},monthsRegex:fD,monthsShortRegex:fD,monthsStrictRegex:/^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i,monthsShortStrictRegex:/^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,monthsParse:aC,longMonthsParse:aC,shortMonthsParse:aC,weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[vandaag om] LT",nextDay:"[morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(g5){return g5+((g5===1||g5===8||g5>=20)?"ste":"de")},week:{dow:1,doy:4}});gm.defineLocale("nn",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"),weekdaysShort:"sun_mån_tys_ons_tor_fre_lau".split("_"),weekdaysMin:"su_må_ty_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] H:mm",LLLL:"dddd D. MMMM YYYY [kl.] HH:mm"},calendar:{sameDay:"[I dag klokka] LT",nextDay:"[I morgon klokka] LT",nextWeek:"dddd [klokka] LT",lastDay:"[I går klokka] LT",lastWeek:"[Føregåande] dddd [klokka] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s sidan",s:"nokre sekund",m:"eit minutt",mm:"%d minutt",h:"ein time",hh:"%d timar",d:"ein dag",dd:"%d dagar",M:"ein månad",MM:"%d månader",y:"eit år",yy:"%d år"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});var gK={"1":"੧","2":"੨","3":"੩","4":"੪","5":"੫","6":"੬","7":"੭","8":"੮","9":"੯","0":"੦"};var cb={"੧":"1","੨":"2","੩":"3","੪":"4","੫":"5","੬":"6","੭":"7","੮":"8","੯":"9","੦":"0"};gm.defineLocale("pa-in",{months:"ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ".split("_"),monthsShort:"ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ".split("_"),weekdays:"ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ".split("_"),weekdaysShort:"ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ".split("_"),weekdaysMin:"ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ".split("_"),longDateFormat:{LT:"A h:mm ਵਜੇ",LTS:"A h:mm:ss ਵਜੇ",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm ਵਜੇ",LLLL:"dddd, D MMMM YYYY, A h:mm ਵਜੇ"},calendar:{sameDay:"[ਅਜ] LT",nextDay:"[ਕਲ] LT",nextWeek:"dddd, LT",lastDay:"[ਕਲ] LT",lastWeek:"[ਪਿਛਲੇ] dddd, LT",sameElse:"L"},relativeTime:{future:"%s ਵਿੱਚ",past:"%s ਪਿਛਲੇ",s:"ਕੁਝ ਸਕਿੰਟ",m:"ਇਕ ਮਿੰਟ",mm:"%d ਮਿੰਟ",h:"ਇੱਕ ਘੰਟਾ",hh:"%d ਘੰਟੇ",d:"ਇੱਕ ਦਿਨ",dd:"%d ਦਿਨ",M:"ਇੱਕ ਮਹੀਨਾ",MM:"%d ਮਹੀਨੇ",y:"ਇੱਕ ਸਾਲ",yy:"%d ਸਾਲ"},preparse:function(g5){return g5.replace(/[੧੨੩੪੫੬੭੮੯੦]/g,function(g6){return cb[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return gK[g6]})},meridiemParse:/ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="ਰਾਤ"){return g5<4?g5:g5+12}else{if(g6==="ਸਵੇਰ"){return g5}else{if(g6==="ਦੁਪਹਿਰ"){return g5>=10?g5:g5+12}else{if(g6==="ਸ਼ਾਮ"){return g5+12}}}}},meridiem:function(g5,g7,g6){if(g5<4){return"ਰਾਤ"}else{if(g5<10){return"ਸਵੇਰ"}else{if(g5<17){return"ਦੁਪਹਿਰ"}else{if(g5<20){return"ਸ਼ਾਮ"}else{return"ਰਾਤ"}}}}},week:{dow:0,doy:6}});var cw="styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_");var ay="stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia".split("_");function cE(g5){return(g5%10<5)&&(g5%10>1)&&((~~(g5/10)%10)!==1)}function gS(g8,g7,g6){var g5=g8+" ";switch(g6){case"m":return g7?"minuta":"minutę";case"mm":return g5+(cE(g8)?"minuty":"minut");case"h":return g7?"godzina":"godzinę";case"hh":return g5+(cE(g8)?"godziny":"godzin");case"MM":return g5+(cE(g8)?"miesiące":"miesięcy");case"yy":return g5+(cE(g8)?"lata":"lat")}}gm.defineLocale("pl",{months:function(g6,g5){if(!g6){return cw}else{if(g5===""){return"("+ay[g6.month()]+"|"+cw[g6.month()]+")"}else{if(/D MMMM/.test(g5)){return ay[g6.month()]}else{return cw[g6.month()]}}}},monthsShort:"sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"),weekdays:"niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"),weekdaysShort:"ndz_pon_wt_śr_czw_pt_sob".split("_"),weekdaysMin:"Nd_Pn_Wt_Śr_Cz_Pt_So".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Dziś o] LT",nextDay:"[Jutro o] LT",nextWeek:"[W] dddd [o] LT",lastDay:"[Wczoraj o] LT",lastWeek:function(){switch(this.day()){case 0:return"[W zeszłą niedzielę o] LT";case 3:return"[W zeszłą środę o] LT";case 6:return"[W zeszłą sobotę o] LT";default:return"[W zeszły] dddd [o] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"%s temu",s:"kilka sekund",m:gS,mm:gS,h:gS,hh:gS,d:"1 dzień",dd:"%d dni",M:"miesiąc",MM:gS,y:"rok",yy:gS},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("pt-br",{months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Do_2ª_3ª_4ª_5ª_6ª_Sá".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY [às] HH:mm",LLLL:"dddd, D [de] MMMM [de] YYYY [às] HH:mm"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return(this.day()===0||this.day()===6)?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"poucos segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº"});gm.defineLocale("pt",{months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Do_2ª_3ª_4ª_5ª_6ª_Sá".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY HH:mm",LLLL:"dddd, D [de] MMMM [de] YYYY HH:mm"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return(this.day()===0||this.day()===6)?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"há %s",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}});function dI(g7,g6,g5){var g9={mm:"minute",hh:"ore",dd:"zile",MM:"luni",yy:"ani"},g8=" ";if(g7%100>=20||(g7>=100&&g7%100===0)){g8=" de "}return g7+g8+g9[g5]}gm.defineLocale("ro",{months:"ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie".split("_"),monthsShort:"ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.".split("_"),monthsParseExact:true,weekdays:"duminică_luni_marți_miercuri_joi_vineri_sâmbătă".split("_"),weekdaysShort:"Dum_Lun_Mar_Mie_Joi_Vin_Sâm".split("_"),weekdaysMin:"Du_Lu_Ma_Mi_Jo_Vi_Sâ".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[azi la] LT",nextDay:"[mâine la] LT",nextWeek:"dddd [la] LT",lastDay:"[ieri la] LT",lastWeek:"[fosta] dddd [la] LT",sameElse:"L"},relativeTime:{future:"peste %s",past:"%s în urmă",s:"câteva secunde",m:"un minut",mm:dI,h:"o oră",hh:dI,d:"o zi",dd:dI,M:"o lună",MM:dI,y:"un an",yy:dI},week:{dow:1,doy:7}});function cC(g7,g6){var g5=g7.split("_");return g6%10===1&&g6%100!==11?g5[0]:(g6%10>=2&&g6%10<=4&&(g6%100<10||g6%100>=20)?g5[1]:g5[2])}function dG(g7,g6,g5){var g8={mm:g6?"минута_минуты_минут":"минуту_минуты_минут",hh:"час_часа_часов",dd:"день_дня_дней",MM:"месяц_месяца_месяцев",yy:"год_года_лет"};if(g5==="m"){return g6?"минута":"минуту"}else{return g7+" "+cC(g8[g5],+g7)}}var aB=[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[йя]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i];gm.defineLocale("ru",{months:{format:"января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_"),standalone:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_")},monthsShort:{format:"янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.".split("_"),standalone:"янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.".split("_")},weekdays:{standalone:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),format:"воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу".split("_"),isFormat:/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/},weekdaysShort:"вс_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),monthsParse:aB,longMonthsParse:aB,shortMonthsParse:aB,monthsRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsShortRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsStrictRegex:/^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,monthsShortStrictRegex:/^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(g5){if(g5.week()!==this.week()){switch(this.day()){case 0:return"[В следующее] dddd [в] LT";case 1:case 2:case 4:return"[В следующий] dddd [в] LT";case 3:case 5:case 6:return"[В следующую] dddd [в] LT"}}else{if(this.day()===2){return"[Во] dddd [в] LT"}else{return"[В] dddd [в] LT"}}},lastWeek:function(g5){if(g5.week()!==this.week()){switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}}else{if(this.day()===2){return"[Во] dddd [в] LT"}else{return"[В] dddd [в] LT"}}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:dG,mm:dG,h:"час",hh:dG,d:"день",dd:dG,M:"месяц",MM:dG,y:"год",yy:dG},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(g5){return/^(дня|вечера)$/.test(g5)},meridiem:function(g5,g7,g6){if(g5<4){return"ночи"}else{if(g5<12){return"утра"}else{if(g5<17){return"дня"}else{return"вечера"}}}},dayOfMonthOrdinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(g5,g6){switch(g6){case"M":case"d":case"DDD":return g5+"-й";case"D":return g5+"-го";case"w":case"W":return g5+"-я";default:return g5}},week:{dow:1,doy:7}});var ev=["جنوري","فيبروري","مارچ","اپريل","مئي","جون","جولاءِ","آگسٽ","سيپٽمبر","آڪٽوبر","نومبر","ڊسمبر"];var q=["آچر","سومر","اڱارو","اربع","خميس","جمع","ڇنڇر"];gm.defineLocale("sd",{months:ev,monthsShort:ev,weekdays:q,weekdaysShort:q,weekdaysMin:q,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd، D MMMM YYYY HH:mm"},meridiemParse:/صبح|شام/,isPM:function(g5){return"شام"===g5},meridiem:function(g5,g7,g6){if(g5<12){return"صبح"}return"شام"},calendar:{sameDay:"[اڄ] LT",nextDay:"[سڀاڻي] LT",nextWeek:"dddd [اڳين هفتي تي] LT",lastDay:"[ڪالهه] LT",lastWeek:"[گزريل هفتي] dddd [تي] LT",sameElse:"L"},relativeTime:{future:"%s پوء",past:"%s اڳ",s:"چند سيڪنڊ",m:"هڪ منٽ",mm:"%d منٽ",h:"هڪ ڪلاڪ",hh:"%d ڪلاڪ",d:"هڪ ڏينهن",dd:"%d ڏينهن",M:"هڪ مهينو",MM:"%d مهينا",y:"هڪ سال",yy:"%d سال"},preparse:function(g5){return g5.replace(/،/g,",")},postformat:function(g5){return g5.replace(/,/g,"،")},week:{dow:1,doy:4}});gm.defineLocale("se",{months:"ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu".split("_"),monthsShort:"ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov".split("_"),weekdays:"sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat".split("_"),weekdaysShort:"sotn_vuos_maŋ_gask_duor_bear_láv".split("_"),weekdaysMin:"s_v_m_g_d_b_L".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"MMMM D. [b.] YYYY",LLL:"MMMM D. [b.] YYYY [ti.] HH:mm",LLLL:"dddd, MMMM D. [b.] YYYY [ti.] HH:mm"},calendar:{sameDay:"[otne ti] LT",nextDay:"[ihttin ti] LT",nextWeek:"dddd [ti] LT",lastDay:"[ikte ti] LT",lastWeek:"[ovddit] dddd [ti] LT",sameElse:"L"},relativeTime:{future:"%s geažes",past:"maŋit %s",s:"moadde sekunddat",m:"okta minuhta",mm:"%d minuhtat",h:"okta diimmu",hh:"%d diimmut",d:"okta beaivi",dd:"%d beaivvit",M:"okta mánnu",MM:"%d mánut",y:"okta jahki",yy:"%d jagit"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});gm.defineLocale("si",{months:"ජනවාරි_පෙබරවාරි_මාර්තු_අප්රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්".split("_"),monthsShort:"ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ".split("_"),weekdays:"ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා".split("_"),weekdaysShort:"ඉරි_සඳු_අඟ_බදා_බ්රහ_සිකු_සෙන".split("_"),weekdaysMin:"ඉ_ස_අ_බ_බ්ර_සි_සෙ".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"a h:mm",LTS:"a h:mm:ss",L:"YYYY/MM/DD",LL:"YYYY MMMM D",LLL:"YYYY MMMM D, a h:mm",LLLL:"YYYY MMMM D [වැනි] dddd, a h:mm:ss"},calendar:{sameDay:"[අද] LT[ට]",nextDay:"[හෙට] LT[ට]",nextWeek:"dddd LT[ට]",lastDay:"[ඊයේ] LT[ට]",lastWeek:"[පසුගිය] dddd LT[ට]",sameElse:"L"},relativeTime:{future:"%sකින්",past:"%sකට පෙර",s:"තත්පර කිහිපය",m:"මිනිත්තුව",mm:"මිනිත්තු %d",h:"පැය",hh:"පැය %d",d:"දිනය",dd:"දින %d",M:"මාසය",MM:"මාස %d",y:"වසර",yy:"වසර %d"},dayOfMonthOrdinalParse:/\d{1,2} වැනි/,ordinal:function(g5){return g5+" වැනි"},meridiemParse:/පෙර වරු|පස් වරු|පෙ.ව|ප.ව./,isPM:function(g5){return g5==="ප.ව."||g5==="පස් වරු"},meridiem:function(g5,g6,g7){if(g5>11){return g7?"ප.ව.":"පස් වරු"}else{return g7?"පෙ.ව.":"පෙර වරු"}}});var eu="január_február_marec_apríl_máj_jún_júl_august_september_október_november_december".split("_");var db="jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec".split("_");function cB(g5){return(g5>1)&&(g5<5)}function gQ(g8,g7,g6,g9){var g5=g8+" ";switch(g6){case"s":return(g7||g9)?"pár sekúnd":"pár sekundami";case"m":return g7?"minúta":(g9?"minútu":"minútou");case"mm":if(g7||g9){return g5+(cB(g8)?"minúty":"minút")}else{return g5+"minútami"}break;case"h":return g7?"hodina":(g9?"hodinu":"hodinou");case"hh":if(g7||g9){return g5+(cB(g8)?"hodiny":"hodín")}else{return g5+"hodinami"}break;case"d":return(g7||g9)?"deň":"dňom";case"dd":if(g7||g9){return g5+(cB(g8)?"dni":"dní")}else{return g5+"dňami"}break;case"M":return(g7||g9)?"mesiac":"mesiacom";case"MM":if(g7||g9){return g5+(cB(g8)?"mesiace":"mesiacov")}else{return g5+"mesiacmi"}break;case"y":return(g7||g9)?"rok":"rokom";case"yy":if(g7||g9){return g5+(cB(g8)?"roky":"rokov")}else{return g5+"rokmi"}break}}gm.defineLocale("sk",{months:eu,monthsShort:db,weekdays:"nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota".split("_"),weekdaysShort:"ne_po_ut_st_št_pi_so".split("_"),weekdaysMin:"ne_po_ut_st_št_pi_so".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd D. MMMM YYYY H:mm"},calendar:{sameDay:"[dnes o] LT",nextDay:"[zajtra o] LT",nextWeek:function(){switch(this.day()){case 0:return"[v nedeľu o] LT";case 1:case 2:return"[v] dddd [o] LT";case 3:return"[v stredu o] LT";case 4:return"[vo štvrtok o] LT";case 5:return"[v piatok o] LT";case 6:return"[v sobotu o] LT"}},lastDay:"[včera o] LT",lastWeek:function(){switch(this.day()){case 0:return"[minulú nedeľu o] LT";case 1:case 2:return"[minulý] dddd [o] LT";case 3:return"[minulú stredu o] LT";case 4:case 5:return"[minulý] dddd [o] LT";case 6:return"[minulú sobotu o] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"pred %s",s:gQ,m:gQ,mm:gQ,h:gQ,hh:gQ,d:gQ,dd:gQ,M:gQ,MM:gQ,y:gQ,yy:gQ},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});function ao(g8,g7,g6,g9){var g5=g8+" ";switch(g6){case"s":return g7||g9?"nekaj sekund":"nekaj sekundami";case"m":return g7?"ena minuta":"eno minuto";case"mm":if(g8===1){g5+=g7?"minuta":"minuto"}else{if(g8===2){g5+=g7||g9?"minuti":"minutama"}else{if(g8<5){g5+=g7||g9?"minute":"minutami"}else{g5+=g7||g9?"minut":"minutami"}}}return g5;case"h":return g7?"ena ura":"eno uro";case"hh":if(g8===1){g5+=g7?"ura":"uro"}else{if(g8===2){g5+=g7||g9?"uri":"urama"}else{if(g8<5){g5+=g7||g9?"ure":"urami"}else{g5+=g7||g9?"ur":"urami"}}}return g5;case"d":return g7||g9?"en dan":"enim dnem";case"dd":if(g8===1){g5+=g7||g9?"dan":"dnem"}else{if(g8===2){g5+=g7||g9?"dni":"dnevoma"}else{g5+=g7||g9?"dni":"dnevi"}}return g5;case"M":return g7||g9?"en mesec":"enim mesecem";case"MM":if(g8===1){g5+=g7||g9?"mesec":"mesecem"}else{if(g8===2){g5+=g7||g9?"meseca":"mesecema"}else{if(g8<5){g5+=g7||g9?"mesece":"meseci"}else{g5+=g7||g9?"mesecev":"meseci"}}}return g5;case"y":return g7||g9?"eno leto":"enim letom";case"yy":if(g8===1){g5+=g7||g9?"leto":"letom"}else{if(g8===2){g5+=g7||g9?"leti":"letoma"}else{if(g8<5){g5+=g7||g9?"leta":"leti"}else{g5+=g7||g9?"let":"leti"}}}return g5}}gm.defineLocale("sl",{months:"januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december".split("_"),monthsShort:"jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"),monthsParseExact:true,weekdays:"nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota".split("_"),weekdaysShort:"ned._pon._tor._sre._čet._pet._sob.".split("_"),weekdaysMin:"ne_po_to_sr_če_pe_so".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danes ob] LT",nextDay:"[jutri ob] LT",nextWeek:function(){switch(this.day()){case 0:return"[v] [nedeljo] [ob] LT";case 3:return"[v] [sredo] [ob] LT";case 6:return"[v] [soboto] [ob] LT";case 1:case 2:case 4:case 5:return"[v] dddd [ob] LT"}},lastDay:"[včeraj ob] LT",lastWeek:function(){switch(this.day()){case 0:return"[prejšnjo] [nedeljo] [ob] LT";case 3:return"[prejšnjo] [sredo] [ob] LT";case 6:return"[prejšnjo] [soboto] [ob] LT";case 1:case 2:case 4:case 5:return"[prejšnji] dddd [ob] LT"}},sameElse:"L"},relativeTime:{future:"čez %s",past:"pred %s",s:ao,m:ao,mm:ao,h:ao,hh:ao,d:ao,dd:ao,M:ao,MM:ao,y:ao,yy:ao},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}});gm.defineLocale("sq",{months:"Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor".split("_"),monthsShort:"Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj".split("_"),weekdays:"E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë".split("_"),weekdaysShort:"Die_Hën_Mar_Mër_Enj_Pre_Sht".split("_"),weekdaysMin:"D_H_Ma_Më_E_P_Sh".split("_"),weekdaysParseExact:true,meridiemParse:/PD|MD/,isPM:function(g5){return g5.charAt(0)==="M"},meridiem:function(g5,g6,g7){return g5<12?"PD":"MD"},longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Sot në] LT",nextDay:"[Nesër në] LT",nextWeek:"dddd [në] LT",lastDay:"[Dje në] LT",lastWeek:"dddd [e kaluar në] LT",sameElse:"L"},relativeTime:{future:"në %s",past:"%s më parë",s:"disa sekonda",m:"një minutë",mm:"%d minuta",h:"një orë",hh:"%d orë",d:"një ditë",dd:"%d ditë",M:"një muaj",MM:"%d muaj",y:"një vit",yy:"%d vite"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});var cF={words:{m:["један минут","једне минуте"],mm:["минут","минуте","минута"],h:["један сат","једног сата"],hh:["сат","сата","сати"],dd:["дан","дана","дана"],MM:["месец","месеца","месеци"],yy:["година","године","година"]},correctGrammaticalCase:function(g6,g5){return g6===1?g5[0]:(g6>=2&&g6<=4?g5[1]:g5[2])},translate:function(g8,g6,g5){var g7=cF.words[g5];if(g5.length===1){return g6?g7[0]:g7[1]}else{return g8+" "+cF.correctGrammaticalCase(g8,g7)}}};gm.defineLocale("sr-cyrl",{months:"јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар".split("_"),monthsShort:"јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.".split("_"),monthsParseExact:true,weekdays:"недеља_понедељак_уторак_среда_четвртак_петак_субота".split("_"),weekdaysShort:"нед._пон._уто._сре._чет._пет._суб.".split("_"),weekdaysMin:"не_по_ут_ср_че_пе_су".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[данас у] LT",nextDay:"[сутра у] LT",nextWeek:function(){switch(this.day()){case 0:return"[у] [недељу] [у] LT";case 3:return"[у] [среду] [у] LT";case 6:return"[у] [суботу] [у] LT";case 1:case 2:case 4:case 5:return"[у] dddd [у] LT"}},lastDay:"[јуче у] LT",lastWeek:function(){var g5=["[прошле] [недеље] [у] LT","[прошлог] [понедељка] [у] LT","[прошлог] [уторка] [у] LT","[прошле] [среде] [у] LT","[прошлог] [четвртка] [у] LT","[прошлог] [петка] [у] LT","[прошле] [суботе] [у] LT"];return g5[this.day()]},sameElse:"L"},relativeTime:{future:"за %s",past:"пре %s",s:"неколико секунди",m:cF.translate,mm:cF.translate,h:cF.translate,hh:cF.translate,d:"дан",dd:cF.translate,M:"месец",MM:cF.translate,y:"годину",yy:cF.translate},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}});var cD={words:{m:["jedan minut","jedne minute"],mm:["minut","minute","minuta"],h:["jedan sat","jednog sata"],hh:["sat","sata","sati"],dd:["dan","dana","dana"],MM:["mesec","meseca","meseci"],yy:["godina","godine","godina"]},correctGrammaticalCase:function(g6,g5){return g6===1?g5[0]:(g6>=2&&g6<=4?g5[1]:g5[2])},translate:function(g8,g6,g5){var g7=cD.words[g5];if(g5.length===1){return g6?g7[0]:g7[1]}else{return g8+" "+cD.correctGrammaticalCase(g8,g7)}}};gm.defineLocale("sr",{months:"januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar".split("_"),monthsShort:"jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.".split("_"),monthsParseExact:true,weekdays:"nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota".split("_"),weekdaysShort:"ned._pon._uto._sre._čet._pet._sub.".split("_"),weekdaysMin:"ne_po_ut_sr_če_pe_su".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedelju] [u] LT";case 3:return"[u] [sredu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[juče u] LT",lastWeek:function(){var g5=["[prošle] [nedelje] [u] LT","[prošlog] [ponedeljka] [u] LT","[prošlog] [utorka] [u] LT","[prošle] [srede] [u] LT","[prošlog] [četvrtka] [u] LT","[prošlog] [petka] [u] LT","[prošle] [subote] [u] LT"];return g5[this.day()]},sameElse:"L"},relativeTime:{future:"za %s",past:"pre %s",s:"nekoliko sekundi",m:cD.translate,mm:cD.translate,h:cD.translate,hh:cD.translate,d:"dan",dd:cD.translate,M:"mesec",MM:cD.translate,y:"godinu",yy:cD.translate},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}});gm.defineLocale("ss",{months:"Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split("_"),monthsShort:"Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo".split("_"),weekdays:"Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo".split("_"),weekdaysShort:"Lis_Umb_Lsb_Les_Lsi_Lsh_Umg".split("_"),weekdaysMin:"Li_Us_Lb_Lt_Ls_Lh_Ug".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[Namuhla nga] LT",nextDay:"[Kusasa nga] LT",nextWeek:"dddd [nga] LT",lastDay:"[Itolo nga] LT",lastWeek:"dddd [leliphelile] [nga] LT",sameElse:"L"},relativeTime:{future:"nga %s",past:"wenteka nga %s",s:"emizuzwana lomcane",m:"umzuzu",mm:"%d emizuzu",h:"lihora",hh:"%d emahora",d:"lilanga",dd:"%d emalanga",M:"inyanga",MM:"%d tinyanga",y:"umnyaka",yy:"%d iminyaka"},meridiemParse:/ekuseni|emini|entsambama|ebusuku/,meridiem:function(g5,g6,g7){if(g5<11){return"ekuseni"}else{if(g5<15){return"emini"}else{if(g5<19){return"entsambama"}else{return"ebusuku"}}}},meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="ekuseni"){return g5}else{if(g6==="emini"){return g5>=11?g5:g5+12}else{if(g6==="entsambama"||g6==="ebusuku"){if(g5===0){return 0}return g5+12}}}},dayOfMonthOrdinalParse:/\d{1,2}/,ordinal:"%d",week:{dow:1,doy:4}});gm.defineLocale("sv",{months:"januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"),weekdaysShort:"sön_mån_tis_ons_tor_fre_lör".split("_"),weekdaysMin:"sö_må_ti_on_to_fr_lö".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [kl.] HH:mm",LLLL:"dddd D MMMM YYYY [kl.] HH:mm",lll:"D MMM YYYY HH:mm",llll:"ddd D MMM YYYY HH:mm"},calendar:{sameDay:"[Idag] LT",nextDay:"[Imorgon] LT",lastDay:"[Igår] LT",nextWeek:"[På] dddd LT",lastWeek:"[I] dddd[s] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"för %s sedan",s:"några sekunder",m:"en minut",mm:"%d minuter",h:"en timme",hh:"%d timmar",d:"en dag",dd:"%d dagar",M:"en månad",MM:"%d månader",y:"ett år",yy:"%d år"},dayOfMonthOrdinalParse:/\d{1,2}(e|a)/,ordinal:function(g7){var g5=g7%10,g6=(~~(g7%100/10)===1)?"e":(g5===1)?"a":(g5===2)?"a":(g5===3)?"e":"e";return g7+g6},week:{dow:1,doy:4}});gm.defineLocale("sw",{months:"Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba".split("_"),monthsShort:"Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des".split("_"),weekdays:"Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi".split("_"),weekdaysShort:"Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos".split("_"),weekdaysMin:"J2_J3_J4_J5_Al_Ij_J1".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[leo saa] LT",nextDay:"[kesho saa] LT",nextWeek:"[wiki ijayo] dddd [saat] LT",lastDay:"[jana] LT",lastWeek:"[wiki iliyopita] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s baadaye",past:"tokea %s",s:"hivi punde",m:"dakika moja",mm:"dakika %d",h:"saa limoja",hh:"masaa %d",d:"siku moja",dd:"masiku %d",M:"mwezi mmoja",MM:"miezi %d",y:"mwaka mmoja",yy:"miaka %d"},week:{dow:1,doy:7}});var gI={"1":"௧","2":"௨","3":"௩","4":"௪","5":"௫","6":"௬","7":"௭","8":"௮","9":"௯","0":"௦"};var ca={"௧":"1","௨":"2","௩":"3","௪":"4","௫":"5","௬":"6","௭":"7","௮":"8","௯":"9","௦":"0"};gm.defineLocale("ta",{months:"ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்".split("_"),monthsShort:"ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்".split("_"),weekdays:"ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை".split("_"),weekdaysShort:"ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி".split("_"),weekdaysMin:"ஞா_தி_செ_பு_வி_வெ_ச".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, HH:mm",LLLL:"dddd, D MMMM YYYY, HH:mm"},calendar:{sameDay:"[இன்று] LT",nextDay:"[நாளை] LT",nextWeek:"dddd, LT",lastDay:"[நேற்று] LT",lastWeek:"[கடந்த வாரம்] dddd, LT",sameElse:"L"},relativeTime:{future:"%s இல்",past:"%s முன்",s:"ஒரு சில விநாடிகள்",m:"ஒரு நிமிடம்",mm:"%d நிமிடங்கள்",h:"ஒரு மணி நேரம்",hh:"%d மணி நேரம்",d:"ஒரு நாள்",dd:"%d நாட்கள்",M:"ஒரு மாதம்",MM:"%d மாதங்கள்",y:"ஒரு வருடம்",yy:"%d ஆண்டுகள்"},dayOfMonthOrdinalParse:/\d{1,2}வது/,ordinal:function(g5){return g5+"வது"},preparse:function(g5){return g5.replace(/[௧௨௩௪௫௬௭௮௯௦]/g,function(g6){return ca[g6]})},postformat:function(g5){return g5.replace(/\d/g,function(g6){return gI[g6]})},meridiemParse:/யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/,meridiem:function(g5,g7,g6){if(g5<2){return" யாமம்"}else{if(g5<6){return" வைகறை"}else{if(g5<10){return" காலை"}else{if(g5<14){return" நண்பகல்"}else{if(g5<18){return" எற்பாடு"}else{if(g5<22){return" மாலை"}else{return" யாமம்"}}}}}}},meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="யாமம்"){return g5<2?g5:g5+12}else{if(g6==="வைகறை"||g6==="காலை"){return g5}else{if(g6==="நண்பகல்"){return g5>=10?g5:g5+12}else{return g5+12}}}},week:{dow:0,doy:6}});gm.defineLocale("te",{months:"జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జూలై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్".split("_"),monthsShort:"జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జూలై_ఆగ._సెప్._అక్టో._నవ._డిసె.".split("_"),monthsParseExact:true,weekdays:"ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం".split("_"),weekdaysShort:"ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని".split("_"),weekdaysMin:"ఆ_సో_మం_బు_గు_శు_శ".split("_"),longDateFormat:{LT:"A h:mm",LTS:"A h:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm",LLLL:"dddd, D MMMM YYYY, A h:mm"},calendar:{sameDay:"[నేడు] LT",nextDay:"[రేపు] LT",nextWeek:"dddd, LT",lastDay:"[నిన్న] LT",lastWeek:"[గత] dddd, LT",sameElse:"L"},relativeTime:{future:"%s లో",past:"%s క్రితం",s:"కొన్ని క్షణాలు",m:"ఒక నిమిషం",mm:"%d నిమిషాలు",h:"ఒక గంట",hh:"%d గంటలు",d:"ఒక రోజు",dd:"%d రోజులు",M:"ఒక నెల",MM:"%d నెలలు",y:"ఒక సంవత్సరం",yy:"%d సంవత్సరాలు"},dayOfMonthOrdinalParse:/\d{1,2}వ/,ordinal:"%dవ",meridiemParse:/రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="రాత్రి"){return g5<4?g5:g5+12}else{if(g6==="ఉదయం"){return g5}else{if(g6==="మధ్యాహ్నం"){return g5>=10?g5:g5+12}else{if(g6==="సాయంత్రం"){return g5+12}}}}},meridiem:function(g5,g7,g6){if(g5<4){return"రాత్రి"}else{if(g5<10){return"ఉదయం"}else{if(g5<17){return"మధ్యాహ్నం"}else{if(g5<20){return"సాయంత్రం"}else{return"రాత్రి"}}}}},week:{dow:0,doy:6}});gm.defineLocale("tet",{months:"Janeiru_Fevereiru_Marsu_Abril_Maiu_Juniu_Juliu_Augustu_Setembru_Outubru_Novembru_Dezembru".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Aug_Set_Out_Nov_Dez".split("_"),weekdays:"Domingu_Segunda_Tersa_Kuarta_Kinta_Sexta_Sabadu".split("_"),weekdaysShort:"Dom_Seg_Ters_Kua_Kint_Sext_Sab".split("_"),weekdaysMin:"Do_Seg_Te_Ku_Ki_Sex_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Ohin iha] LT",nextDay:"[Aban iha] LT",nextWeek:"dddd [iha] LT",lastDay:"[Horiseik iha] LT",lastWeek:"dddd [semana kotuk] [iha] LT",sameElse:"L"},relativeTime:{future:"iha %s",past:"%s liuba",s:"minutu balun",m:"minutu ida",mm:"minutus %d",h:"horas ida",hh:"horas %d",d:"loron ida",dd:"loron %d",M:"fulan ida",MM:"fulan %d",y:"tinan ida",yy:"tinan %d"},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(g7){var g5=g7%10,g6=(~~(g7%100/10)===1)?"th":(g5===1)?"st":(g5===2)?"nd":(g5===3)?"rd":"th";return g7+g6},week:{dow:1,doy:4}});gm.defineLocale("th",{months:"มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม".split("_"),monthsShort:"ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.".split("_"),monthsParseExact:true,weekdays:"อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์".split("_"),weekdaysShort:"อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์".split("_"),weekdaysMin:"อา._จ._อ._พ._พฤ._ศ._ส.".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY เวลา H:mm",LLLL:"วันddddที่ D MMMM YYYY เวลา H:mm"},meridiemParse:/ก่อนเที่ยง|หลังเที่ยง/,isPM:function(g5){return g5==="หลังเที่ยง"},meridiem:function(g5,g7,g6){if(g5<12){return"ก่อนเที่ยง"}else{return"หลังเที่ยง"}},calendar:{sameDay:"[วันนี้ เวลา] LT",nextDay:"[พรุ่งนี้ เวลา] LT",nextWeek:"dddd[หน้า เวลา] LT",lastDay:"[เมื่อวานนี้ เวลา] LT",lastWeek:"[วัน]dddd[ที่แล้ว เวลา] LT",sameElse:"L"},relativeTime:{future:"อีก %s",past:"%sที่แล้ว",s:"ไม่กี่วินาที",m:"1 นาที",mm:"%d นาที",h:"1 ชั่วโมง",hh:"%d ชั่วโมง",d:"1 วัน",dd:"%d วัน",M:"1 เดือน",MM:"%d เดือน",y:"1 ปี",yy:"%d ปี"}});gm.defineLocale("tl-ph",{months:"Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"),monthsShort:"Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"),weekdays:"Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"),weekdaysShort:"Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"),weekdaysMin:"Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"MM/D/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY HH:mm",LLLL:"dddd, MMMM DD, YYYY HH:mm"},calendar:{sameDay:"LT [ngayong araw]",nextDay:"[Bukas ng] LT",nextWeek:"LT [sa susunod na] dddd",lastDay:"LT [kahapon]",lastWeek:"LT [noong nakaraang] dddd",sameElse:"L"},relativeTime:{future:"sa loob ng %s",past:"%s ang nakalipas",s:"ilang segundo",m:"isang minuto",mm:"%d minuto",h:"isang oras",hh:"%d oras",d:"isang araw",dd:"%d araw",M:"isang buwan",MM:"%d buwan",y:"isang taon",yy:"%d taon"},dayOfMonthOrdinalParse:/\d{1,2}/,ordinal:function(g5){return g5},week:{dow:1,doy:4}});var ab="pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut".split("_");function gk(g5){var g6=g5;g6=(g5.indexOf("jaj")!==-1)?g6.slice(0,-3)+"leS":(g5.indexOf("jar")!==-1)?g6.slice(0,-3)+"waQ":(g5.indexOf("DIS")!==-1)?g6.slice(0,-3)+"nem":g6+" pIq";return g6}function gW(g5){var g6=g5;g6=(g5.indexOf("jaj")!==-1)?g6.slice(0,-3)+"Hu’":(g5.indexOf("jar")!==-1)?g6.slice(0,-3)+"wen":(g5.indexOf("DIS")!==-1)?g6.slice(0,-3)+"ben":g6+" ret";return g6}function gP(g8,g7,g6,g9){var g5=ey(g8);switch(g6){case"mm":return g5+" tup";case"hh":return g5+" rep";case"dd":return g5+" jaj";case"MM":return g5+" jar";case"yy":return g5+" DIS"}}function ey(g7){var g9=Math.floor((g7%1000)/100),g5=Math.floor((g7%100)/10),g6=g7%10,g8="";if(g9>0){g8+=ab[g9]+"vatlh"}if(g5>0){g8+=((g8!=="")?" ":"")+ab[g5]+"maH"}if(g6>0){g8+=((g8!=="")?" ":"")+ab[g6]}return(g8==="")?"pagh":g8}gm.defineLocale("tlh",{months:"tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’".split("_"),monthsShort:"jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’".split("_"),monthsParseExact:true,weekdays:"lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj".split("_"),weekdaysShort:"lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj".split("_"),weekdaysMin:"lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[DaHjaj] LT",nextDay:"[wa’leS] LT",nextWeek:"LLL",lastDay:"[wa’Hu’] LT",lastWeek:"LLL",sameElse:"L"},relativeTime:{future:gk,past:gW,s:"puS lup",m:"wa’ tup",mm:gP,h:"wa’ rep",hh:gP,d:"wa’ jaj",dd:gP,M:"wa’ jar",MM:gP,y:"wa’ DIS",yy:gP},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});var j={1:"'inci",5:"'inci",8:"'inci",70:"'inci",80:"'inci",2:"'nci",7:"'nci",20:"'nci",50:"'nci",3:"'üncü",4:"'üncü",100:"'üncü",6:"'ncı",9:"'uncu",10:"'uncu",30:"'uncu",60:"'ıncı",90:"'ıncı"};gm.defineLocale("tr",{months:"Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),monthsShort:"Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),weekdays:"Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),weekdaysShort:"Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),weekdaysMin:"Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[yarın saat] LT",nextWeek:"[haftaya] dddd [saat] LT",lastDay:"[dün] LT",lastWeek:"[geçen hafta] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s önce",s:"birkaç saniye",m:"bir dakika",mm:"%d dakika",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir yıl",yy:"%d yıl"},dayOfMonthOrdinalParse:/\d{1,2}'(inci|nci|üncü|ncı|uncu|ıncı)/,ordinal:function(g7){if(g7===0){return g7+"'ıncı"}var g6=g7%10,g5=g7%100-g6,g8=g7>=100?100:null;return g7+(j[g6]||j[g5]||j[g8])},week:{dow:1,doy:7}});gm.defineLocale("tzl",{months:"Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar".split("_"),monthsShort:"Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec".split("_"),weekdays:"Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi".split("_"),weekdaysShort:"Súl_Lún_Mai_Már_Xhú_Vié_Sát".split("_"),weekdaysMin:"Sú_Lú_Ma_Má_Xh_Vi_Sá".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD.MM.YYYY",LL:"D. MMMM [dallas] YYYY",LLL:"D. MMMM [dallas] YYYY HH.mm",LLLL:"dddd, [li] D. MMMM [dallas] YYYY HH.mm"},meridiemParse:/d\'o|d\'a/i,isPM:function(g5){return"d'o"===g5.toLowerCase()},meridiem:function(g5,g6,g7){if(g5>11){return g7?"d'o":"D'O"}else{return g7?"d'a":"D'A"}},calendar:{sameDay:"[oxhi à] LT",nextDay:"[demà à] LT",nextWeek:"dddd [à] LT",lastDay:"[ieiri à] LT",lastWeek:"[sür el] dddd [lasteu à] LT",sameElse:"L"},relativeTime:{future:"osprei %s",past:"ja%s",s:am,m:am,mm:am,h:am,hh:am,d:am,dd:am,M:am,MM:am,y:am,yy:am},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}});function am(g7,g6,g5,g9){var g8={s:["viensas secunds","'iensas secunds"],m:["'n míut","'iens míut"],mm:[g7+" míuts",""+g7+" míuts"],h:["'n þora","'iensa þora"],hh:[g7+" þoras",""+g7+" þoras"],d:["'n ziua","'iensa ziua"],dd:[g7+" ziuas",""+g7+" ziuas"],M:["'n mes","'iens mes"],MM:[g7+" mesen",""+g7+" mesen"],y:["'n ar","'iens ar"],yy:[g7+" ars",""+g7+" ars"]};return g9?g8[g5][0]:(g6?g8[g5][0]:g8[g5][1])}gm.defineLocale("tzm-latn",{months:"innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"),monthsShort:"innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"),weekdays:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),weekdaysShort:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),weekdaysMin:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[asdkh g] LT",nextDay:"[aska g] LT",nextWeek:"dddd [g] LT",lastDay:"[assant g] LT",lastWeek:"dddd [g] LT",sameElse:"L"},relativeTime:{future:"dadkh s yan %s",past:"yan %s",s:"imik",m:"minuḍ",mm:"%d minuḍ",h:"saɛa",hh:"%d tassaɛin",d:"ass",dd:"%d ossan",M:"ayowr",MM:"%d iyyirn",y:"asgas",yy:"%d isgasn"},week:{dow:6,doy:12}});gm.defineLocale("tzm",{months:"ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"),monthsShort:"ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"),weekdays:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),weekdaysShort:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),weekdaysMin:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[ⴰⵙⴷⵅ ⴴ] LT",nextDay:"[ⴰⵙⴽⴰ ⴴ] LT",nextWeek:"dddd [ⴴ] LT",lastDay:"[ⴰⵚⴰⵏⵜ ⴴ] LT",lastWeek:"dddd [ⴴ] LT",sameElse:"L"},relativeTime:{future:"ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s",past:"ⵢⴰⵏ %s",s:"ⵉⵎⵉⴽ",m:"ⵎⵉⵏⵓⴺ",mm:"%d ⵎⵉⵏⵓⴺ",h:"ⵙⴰⵄⴰ",hh:"%d ⵜⴰⵙⵙⴰⵄⵉⵏ",d:"ⴰⵙⵙ",dd:"%d oⵙⵙⴰⵏ",M:"ⴰⵢoⵓⵔ",MM:"%d ⵉⵢⵢⵉⵔⵏ",y:"ⴰⵙⴳⴰⵙ",yy:"%d ⵉⵙⴳⴰⵙⵏ"},week:{dow:6,doy:12}});function cA(g7,g6){var g5=g7.split("_");return g6%10===1&&g6%100!==11?g5[0]:(g6%10>=2&&g6%10<=4&&(g6%100<10||g6%100>=20)?g5[1]:g5[2])}function dF(g7,g6,g5){var g8={mm:g6?"хвилина_хвилини_хвилин":"хвилину_хвилини_хвилин",hh:g6?"година_години_годин":"годину_години_годин",dd:"день_дні_днів",MM:"місяць_місяці_місяців",yy:"рік_роки_років"};if(g5==="m"){return g6?"хвилина":"хвилину"}else{if(g5==="h"){return g6?"година":"годину"}else{return g7+" "+cA(g8[g5],+g7)}}}function bS(g5,g8){var g6={nominative:"неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота".split("_"),accusative:"неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу".split("_"),genitive:"неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи".split("_")};if(!g5){return g6.nominative}var g7=(/(\[[ВвУу]\]) ?dddd/).test(g8)?"accusative":((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(g8)?"genitive":"nominative");return g6[g7][g5.day()]}function aW(g5){return function(){return g5+"о"+(this.hours()===11?"б":"")+"] LT"}}gm.defineLocale("uk",{months:{format:"січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня".split("_"),standalone:"січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень".split("_")},monthsShort:"січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"),weekdays:bS,weekdaysShort:"нд_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"нд_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY р.",LLL:"D MMMM YYYY р., HH:mm",LLLL:"dddd, D MMMM YYYY р., HH:mm"},calendar:{sameDay:aW("[Сьогодні "),nextDay:aW("[Завтра "),lastDay:aW("[Вчора "),nextWeek:aW("[У] dddd ["),lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return aW("[Минулої] dddd [").call(this);case 1:case 2:case 4:return aW("[Минулого] dddd [").call(this)}},sameElse:"L"},relativeTime:{future:"за %s",past:"%s тому",s:"декілька секунд",m:dF,mm:dF,h:"годину",hh:dF,d:"день",dd:dF,M:"місяць",MM:dF,y:"рік",yy:dF},meridiemParse:/ночі|ранку|дня|вечора/,isPM:function(g5){return/^(дня|вечора)$/.test(g5)},meridiem:function(g5,g7,g6){if(g5<4){return"ночі"}else{if(g5<12){return"ранку"}else{if(g5<17){return"дня"}else{return"вечора"}}}},dayOfMonthOrdinalParse:/\d{1,2}-(й|го)/,ordinal:function(g5,g6){switch(g6){case"M":case"d":case"DDD":case"w":case"W":return g5+"-й";case"D":return g5+"-го";default:return g5}},week:{dow:1,doy:7}});var es=["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"];var m=["اتوار","پیر","منگل","بدھ","جمعرات","جمعہ","ہفتہ"];gm.defineLocale("ur",{months:es,monthsShort:es,weekdays:m,weekdaysShort:m,weekdaysMin:m,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd، D MMMM YYYY HH:mm"},meridiemParse:/صبح|شام/,isPM:function(g5){return"شام"===g5},meridiem:function(g5,g7,g6){if(g5<12){return"صبح"}return"شام"},calendar:{sameDay:"[آج بوقت] LT",nextDay:"[کل بوقت] LT",nextWeek:"dddd [بوقت] LT",lastDay:"[گذشتہ روز بوقت] LT",lastWeek:"[گذشتہ] dddd [بوقت] LT",sameElse:"L"},relativeTime:{future:"%s بعد",past:"%s قبل",s:"چند سیکنڈ",m:"ایک منٹ",mm:"%d منٹ",h:"ایک گھنٹہ",hh:"%d گھنٹے",d:"ایک دن",dd:"%d دن",M:"ایک ماہ",MM:"%d ماہ",y:"ایک سال",yy:"%d سال"},preparse:function(g5){return g5.replace(/،/g,",")},postformat:function(g5){return g5.replace(/,/g,"،")},week:{dow:1,doy:4}});gm.defineLocale("uz-latn",{months:"Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr".split("_"),monthsShort:"Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek".split("_"),weekdays:"Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba".split("_"),weekdaysShort:"Yak_Dush_Sesh_Chor_Pay_Jum_Shan".split("_"),weekdaysMin:"Ya_Du_Se_Cho_Pa_Ju_Sha".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"D MMMM YYYY, dddd HH:mm"},calendar:{sameDay:"[Bugun soat] LT [da]",nextDay:"[Ertaga] LT [da]",nextWeek:"dddd [kuni soat] LT [da]",lastDay:"[Kecha soat] LT [da]",lastWeek:"[O'tgan] dddd [kuni soat] LT [da]",sameElse:"L"},relativeTime:{future:"Yaqin %s ichida",past:"Bir necha %s oldin",s:"soniya",m:"bir daqiqa",mm:"%d daqiqa",h:"bir soat",hh:"%d soat",d:"bir kun",dd:"%d kun",M:"bir oy",MM:"%d oy",y:"bir yil",yy:"%d yil"},week:{dow:1,doy:7}});gm.defineLocale("uz",{months:"январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр".split("_"),monthsShort:"янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),weekdays:"Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"),weekdaysShort:"Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"),weekdaysMin:"Як_Ду_Се_Чо_Па_Жу_Ша".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"D MMMM YYYY, dddd HH:mm"},calendar:{sameDay:"[Бугун соат] LT [да]",nextDay:"[Эртага] LT [да]",nextWeek:"dddd [куни соат] LT [да]",lastDay:"[Кеча соат] LT [да]",lastWeek:"[Утган] dddd [куни соат] LT [да]",sameElse:"L"},relativeTime:{future:"Якин %s ичида",past:"Бир неча %s олдин",s:"фурсат",m:"бир дакика",mm:"%d дакика",h:"бир соат",hh:"%d соат",d:"бир кун",dd:"%d кун",M:"бир ой",MM:"%d ой",y:"бир йил",yy:"%d йил"},week:{dow:1,doy:7}});gm.defineLocale("vi",{months:"tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12".split("_"),monthsShort:"Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12".split("_"),monthsParseExact:true,weekdays:"chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy".split("_"),weekdaysShort:"CN_T2_T3_T4_T5_T6_T7".split("_"),weekdaysMin:"CN_T2_T3_T4_T5_T6_T7".split("_"),weekdaysParseExact:true,meridiemParse:/sa|ch/i,isPM:function(g5){return/^ch$/i.test(g5)},meridiem:function(g5,g6,g7){if(g5<12){return g7?"sa":"SA"}else{return g7?"ch":"CH"}},longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM [năm] YYYY",LLL:"D MMMM [năm] YYYY HH:mm",LLLL:"dddd, D MMMM [năm] YYYY HH:mm",l:"DD/M/YYYY",ll:"D MMM YYYY",lll:"D MMM YYYY HH:mm",llll:"ddd, D MMM YYYY HH:mm"},calendar:{sameDay:"[Hôm nay lúc] LT",nextDay:"[Ngày mai lúc] LT",nextWeek:"dddd [tuần tới lúc] LT",lastDay:"[Hôm qua lúc] LT",lastWeek:"dddd [tuần rồi lúc] LT",sameElse:"L"},relativeTime:{future:"%s tới",past:"%s trước",s:"vài giây",m:"một phút",mm:"%d phút",h:"một giờ",hh:"%d giờ",d:"một ngày",dd:"%d ngày",M:"một tháng",MM:"%d tháng",y:"một năm",yy:"%d năm"},dayOfMonthOrdinalParse:/\d{1,2}/,ordinal:function(g5){return g5},week:{dow:1,doy:4}});gm.defineLocale("x-pseudo",{months:"J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér".split("_"),monthsShort:"J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc".split("_"),monthsParseExact:true,weekdays:"S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý".split("_"),weekdaysShort:"S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát".split("_"),weekdaysMin:"S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá".split("_"),weekdaysParseExact:true,longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[T~ódá~ý át] LT",nextDay:"[T~ómó~rró~w át] LT",nextWeek:"dddd [át] LT",lastDay:"[Ý~ést~érdá~ý át] LT",lastWeek:"[L~ást] dddd [át] LT",sameElse:"L"},relativeTime:{future:"í~ñ %s",past:"%s á~gó",s:"á ~féw ~sécó~ñds",m:"á ~míñ~úté",mm:"%d m~íñú~tés",h:"á~ñ hó~úr",hh:"%d h~óúrs",d:"á ~dáý",dd:"%d d~áýs",M:"á ~móñ~th",MM:"%d m~óñt~hs",y:"á ~ýéár",yy:"%d ý~éárs"},dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(g7){var g5=g7%10,g6=(~~(g7%100/10)===1)?"th":(g5===1)?"st":(g5===2)?"nd":(g5===3)?"rd":"th";return g7+g6},week:{dow:1,doy:4}});gm.defineLocale("yo",{months:"Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀".split("_"),monthsShort:"Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀".split("_"),weekdays:"Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta".split("_"),weekdaysShort:"Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá".split("_"),weekdaysMin:"Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[Ònì ni] LT",nextDay:"[Ọ̀la ni] LT",nextWeek:"dddd [Ọsẹ̀ tón'bọ] [ni] LT",lastDay:"[Àna ni] LT",lastWeek:"dddd [Ọsẹ̀ tólọ́] [ni] LT",sameElse:"L"},relativeTime:{future:"ní %s",past:"%s kọjá",s:"ìsẹjú aayá die",m:"ìsẹjú kan",mm:"ìsẹjú %d",h:"wákati kan",hh:"wákati %d",d:"ọjọ́ kan",dd:"ọjọ́ %d",M:"osù kan",MM:"osù %d",y:"ọdún kan",yy:"ọdún %d"},dayOfMonthOrdinalParse:/ọjọ́\s\d{1,2}/,ordinal:"ọjọ́ %d",week:{dow:1,doy:4}});gm.defineLocale("zh-cn",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日Ah点mm分",LLLL:"YYYY年MMMD日ddddAh点mm分",l:"YYYY年MMMD日",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日 HH:mm",llll:"YYYY年MMMD日dddd HH:mm"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="凌晨"||g6==="早上"||g6==="上午"){return g5}else{if(g6==="下午"||g6==="晚上"){return g5+12}else{return g5>=11?g5:g5+12}}},meridiem:function(g5,g7,g6){var g8=g5*100+g7;if(g8<600){return"凌晨"}else{if(g8<900){return"早上"}else{if(g8<1130){return"上午"}else{if(g8<1230){return"中午"}else{if(g8<1800){return"下午"}else{return"晚上"}}}}}},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},dayOfMonthOrdinalParse:/\d{1,2}(日|月|周)/,ordinal:function(g5,g6){switch(g6){case"d":case"D":case"DDD":return g5+"日";case"M":return g5+"月";case"w":case"W":return g5+"周";default:return g5}},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},week:{dow:1,doy:4}});gm.defineLocale("zh-hk",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日 HH:mm",LLLL:"YYYY年MMMD日dddd HH:mm",l:"YYYY年MMMD日",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日 HH:mm",llll:"YYYY年MMMD日dddd HH:mm"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="凌晨"||g6==="早上"||g6==="上午"){return g5}else{if(g6==="中午"){return g5>=11?g5:g5+12}else{if(g6==="下午"||g6==="晚上"){return g5+12}}}},meridiem:function(g5,g7,g6){var g8=g5*100+g7;if(g8<600){return"凌晨"}else{if(g8<900){return"早上"}else{if(g8<1130){return"上午"}else{if(g8<1230){return"中午"}else{if(g8<1800){return"下午"}else{return"晚上"}}}}}},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},dayOfMonthOrdinalParse:/\d{1,2}(日|月|週)/,ordinal:function(g5,g6){switch(g6){case"d":case"D":case"DDD":return g5+"日";case"M":return g5+"月";case"w":case"W":return g5+"週";default:return g5}},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"1 分鐘",mm:"%d 分鐘",h:"1 小時",hh:"%d 小時",d:"1 天",dd:"%d 天",M:"1 個月",MM:"%d 個月",y:"1 年",yy:"%d 年"}});gm.defineLocale("zh-tw",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日 HH:mm",LLLL:"YYYY年MMMD日dddd HH:mm",l:"YYYY年MMMD日",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日 HH:mm",llll:"YYYY年MMMD日dddd HH:mm"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(g5,g6){if(g5===12){g5=0}if(g6==="凌晨"||g6==="早上"||g6==="上午"){return g5}else{if(g6==="中午"){return g5>=11?g5:g5+12}else{if(g6==="下午"||g6==="晚上"){return g5+12}}}},meridiem:function(g5,g7,g6){var g8=g5*100+g7;if(g8<600){return"凌晨"}else{if(g8<900){return"早上"}else{if(g8<1130){return"上午"}else{if(g8<1230){return"中午"}else{if(g8<1800){return"下午"}else{return"晚上"}}}}}},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},dayOfMonthOrdinalParse:/\d{1,2}(日|月|週)/,ordinal:function(g5,g6){switch(g6){case"d":case"D":case"DDD":return g5+"日";case"M":return g5+"月";case"w":case"W":return g5+"週";default:return g5}},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"1 分鐘",mm:"%d 分鐘",h:"1 小時",hh:"%d 小時",d:"1 天",dd:"%d 天",M:"1 個月",MM:"%d 個月",y:"1 年",yy:"%d 年"}});gm.locale("en");return gm})));var LZString=(function(){var c=String.fromCharCode;var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";var e={};function a(j,h){if(!e[j]){e[j]={};for(var f=0;f>>8;h[l*2+1]=f%256}return h},decompressFromUint8Array:function(m){if(m===null||m===undefined){return d.decompress(m)}else{var h=new Array(m.length/2);for(var l=0,j=h.length;l>1}}else{s=1;for(o=0;o>1}}l--;if(l==0){l=Math.pow(2,h);h++}delete t[y]}else{s=u[y];for(o=0;o>1}}l--;if(l==0){l=Math.pow(2,h);h++}u[j]=n++;y=String(v)}}if(y!==""){if(Object.prototype.hasOwnProperty.call(t,y)){if(y.charCodeAt(0)<256){for(o=0;o>1}}else{s=1;for(o=0;o>1}}l--;if(l==0){l=Math.pow(2,h);h++}delete t[y]}else{s=u[y];for(o=0;o>1}}l--;if(l==0){l=Math.pow(2,h);h++}}s=2;for(o=0;o>1}while(true){f=(f<<1);if(p==x-1){q.push(r(f));break}else{p++}}return q.join("")},decompress:function(f){if(f==null){return""}if(f==""){return null}return d._decompress(f.length,32768,function(h){return f.charCodeAt(h)})},_decompress:function(j,l,f){var r=[],t,n=4,u=4,s=3,h="",p=[],x,q,v,z,m,o,y,A={val:f(0),position:l,index:1};for(x=0;x<3;x+=1){r[x]=x}v=0;m=Math.pow(2,2);o=1;while(o!=m){z=A.val&A.position;A.position>>=1;if(A.position==0){A.position=l;A.val=f(A.index++)}v|=(z>0?1:0)*o;o<<=1}switch(t=v){case 0:v=0;m=Math.pow(2,8);o=1;while(o!=m){z=A.val&A.position;A.position>>=1;if(A.position==0){A.position=l;A.val=f(A.index++)}v|=(z>0?1:0)*o;o<<=1}y=c(v);break;case 1:v=0;m=Math.pow(2,16);o=1;while(o!=m){z=A.val&A.position;A.position>>=1;if(A.position==0){A.position=l;A.val=f(A.index++)}v|=(z>0?1:0)*o;o<<=1}y=c(v);break;case 2:return""}r[3]=y;q=y;p.push(y);while(true){if(A.index>j){return""}v=0;m=Math.pow(2,s);o=1;while(o!=m){z=A.val&A.position;A.position>>=1;if(A.position==0){A.position=l;A.val=f(A.index++)}v|=(z>0?1:0)*o;o<<=1}switch(y=v){case 0:v=0;m=Math.pow(2,8);o=1;while(o!=m){z=A.val&A.position;A.position>>=1;if(A.position==0){A.position=l;A.val=f(A.index++)}v|=(z>0?1:0)*o;o<<=1}r[u++]=c(v);y=u-1;n--;break;case 1:v=0;m=Math.pow(2,16);o=1;while(o!=m){z=A.val&A.position;A.position>>=1;if(A.position==0){A.position=l;A.val=f(A.index++)}v|=(z>0?1:0)*o;o<<=1}r[u++]=c(v);y=u-1;n--;break;case 2:return p.join("")}if(n==0){n=Math.pow(2,s);s++}if(r[y]){h=r[y]}else{if(y===u){h=q+q.charAt(0)}else{return null}}p.push(h);r[u++]=q+h.charAt(0);n--;q=h;if(n==0){n=Math.pow(2,s);s++}}}};return d})();if(typeof define==="function"&&define.amd){define(function(){return LZString})}else{if(typeof module!=="undefined"&&module!=null){module.exports=LZString}}; \ No newline at end of file diff --git a/src/lib/ckeditor-plugins/autosave/lang/en.js b/src/lib/ckeditor-plugins/autosave/lang/en.js index b7c002e3c..958039e5f 100644 --- a/src/lib/ckeditor-plugins/autosave/lang/en.js +++ b/src/lib/ckeditor-plugins/autosave/lang/en.js @@ -4,16 +4,14 @@ For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('autosave', 'en', { dateFormat: 'LLL', - autoSaveMessage: - 'Saved Locally ', - loadSavedContent: - 'A recovered version from {0} has been found.

    Would you like to review and optionally load or discard this version?

    ', + autoSaveMessage: 'Saved Locally ', + loadSavedContent: 'A recovered version from {0} has been found.

    Would you like to review and optionally load or discard this version?

    ', title: 'Load Recovered Version?', - loadedContent: 'Last Saved', + loadedContent: 'Last Saved', localStorageFull: 'Browser localStorage is full, clear your storage or Increase database size', - autoSavedContent: "Recovered from: '", - ok: 'Load Recovered Version', - no: 'Discard Recovered Version', - sideBySide: 'Side by side (HTML)', - inline: 'Inline', + autoSavedContent: 'Recovered from: \'', + ok: 'Load Recovered Version', + no: 'Discard Recovered Version', + sideBySide: 'Side by side (HTML)', + inline: 'Inline' }); diff --git a/src/lib/ckeditor-plugins/autosave/plugin.js b/src/lib/ckeditor-plugins/autosave/plugin.js index a84d11d78..d613ec795 100644 --- a/src/lib/ckeditor-plugins/autosave/plugin.js +++ b/src/lib/ckeditor-plugins/autosave/plugin.js @@ -8,8 +8,8 @@ */ CKEDITOR.MmsAutosavePlugin = (function () { if (!supportsLocalStorage()) { - CKEDITOR.plugins.add('autosave', {}); //register a dummy plugin to pass CKEditor plugin initialization process - return; + CKEDITOR.plugins.add('autosave', {}) //register a dummy plugin to pass CKEditor plugin initialization process + return } CKEDITOR.plugins.add('autosave', { @@ -18,11 +18,11 @@ CKEDITOR.MmsAutosavePlugin = (function () { version: '0.18.0', init: (editor) => { if (!editor.config.autosave.enableAutosave) { - return; + return } // Look for autosave from config.js - this is a bit redundant but necessary - editor.config.autosave = 'autosave' in editor.config ? editor.config.autosave : {}; + editor.config.autosave = 'autosave' in editor.config ? editor.config.autosave : {} // Prepare temp vars for constructing local storage SaveKey name var _saveKeyPrefix = @@ -37,12 +37,12 @@ CKEDITOR.MmsAutosavePlugin = (function () { _saveKeyDelimiter = 'saveKeyDelimiter' in editor.config.autosave ? editor.config.autosave.saveKeyDelimiter : '_', _saveKeyAttribute = - 'saveKeyAttribute' in editor.config.autosave ? editor.config.autosave.saveKeyAttribute : 'name'; + 'saveKeyAttribute' in editor.config.autosave ? editor.config.autosave.saveKeyAttribute : 'name' if ('saveKeyIgnoreParams' in editor.config.autosave) { $(editor.config.autosave.saveKeyIgnoreParams).each(function () { - _saveKeyUrl = autosaveRemoveUrlParam(this, null, _saveKeyUrl); - }); + _saveKeyUrl = autosaveRemoveUrlParam(this, null, _saveKeyUrl) + }) } // Construct default configuration @@ -60,18 +60,18 @@ CKEDITOR.MmsAutosavePlugin = (function () { $(document.getElementById('#' + editor.name)).attr(_saveKeyAttribute), diffType: 'sideBySide', autoLoad: false, - }; + } // Extend CKEDITOR config and lang - config also available at loadPlugin() - var config = CKEDITOR.tools.extend(defaultConfig, editor.config.autosave || {}, true); + var config = CKEDITOR.tools.extend(defaultConfig, editor.config.autosave || {}, true) if (editor.plugins.wordcount && config.messageType == 'statusbar') { - config.messageType = 'notification'; + config.messageType = 'notification' } CKEDITOR.document.appendStyleSheet( CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'css/autosave.min.css') - ); + ) editor.on( 'uiSpace', @@ -86,13 +86,13 @@ CKEDITOR.MmsAutosavePlugin = (function () { autoSaveMessageId(event.editor) + '"class="hidden">' + event.editor.lang.autosave.autoSaveMessage + - ''; + '' } }, editor, null, 100 - ); + ) editor.on( 'instanceReady', @@ -101,64 +101,64 @@ CKEDITOR.MmsAutosavePlugin = (function () { CKEDITOR.scriptLoader.load( '//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', function () { - jQuery.noConflict(); + jQuery.noConflict() - loadPlugin(editor, config); + loadPlugin(editor, config) } - ); + ) } else { CKEDITOR.scriptLoader.load( CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'js/extensions.min.js'), function () { - loadPlugin(editor, config); + loadPlugin(editor, config) } - ); + ) } }, editor, null, 100 - ); + ) }, - }); + }) function loadPlugin(editorInstance, config) { CKEDITOR.scriptLoader.load( CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'js/extensions.min.js'), function () { - GenerateAutoSaveDialog(editorInstance, config, config.SaveKey); + GenerateAutoSaveDialog(editorInstance, config, config.SaveKey) - CheckForAutoSavedContent(editorInstance, config, config.SaveKey, config.NotOlderThen); + CheckForAutoSavedContent(editorInstance, config, config.SaveKey, config.NotOlderThen) } - ); + ) jQuery(config.saveDetectionSelectors).click(function () { - RemoveStorage(config.SaveKey, editorInstance); - }); + RemoveStorage(config.SaveKey, editorInstance) + }) editorInstance.on('change', function () { - startTimer(config, editorInstance); - }); + startTimer(config, editorInstance) + }) editorInstance.on('destroy', function () { if (config.saveOnDestroy) { - SaveData(config.SaveKey, editorInstance, config); + SaveData(config.SaveKey, editorInstance, config) } - }); + }) } function autoSaveMessageId(editorInstance) { - return 'cke_autoSaveMessage_' + editorInstance.name; + return 'cke_autoSaveMessage_' + editorInstance.name } const startTimer = (configAutosave, editorInstance) => { if (editorInstance.config.autosave_timeOutId == null) { - var delay = configAutosave.delay != null ? configAutosave.delay : 10; + var delay = configAutosave.delay != null ? configAutosave.delay : 10 editorInstance.config.autosave_timeOutId = setTimeout(function () { - onTimer(configAutosave, editorInstance); - }, delay * 1000); + onTimer(configAutosave, editorInstance) + }, delay * 1000) } - }; + } const onTimer = (configAutosave, editorInstance) => { if (editorInstance.checkDirty() || editorInstance.plugins.bbcode) { var editor = editorInstance, @@ -168,27 +168,27 @@ CKEDITOR.MmsAutosavePlugin = (function () { : 'autosave_' + window.location + '_' + - $(document.getElementById('#' + editor.name)).attr('name'); + $(document.getElementById('#' + editor.name)).attr('name') - SaveData(autoSaveKey, editor, configAutosave); + SaveData(autoSaveKey, editor, configAutosave) - clearTimeout(editorInstance.config.autosave_timeOutId); + clearTimeout(editorInstance.config.autosave_timeOutId) - editorInstance.config.autosave_timeOutId = null; + editorInstance.config.autosave_timeOutId = null } - }; + } // localStorage detection function supportsLocalStorage() { if (typeof Storage === 'undefined') { - return false; + return false } try { - localStorage.getItem('___test_key'); - return true; + localStorage.getItem('___test_key') + return true } catch (e) { - return false; + return false } } @@ -200,18 +200,18 @@ CKEDITOR.MmsAutosavePlugin = (function () { height: 300, width: 800, onShow: function () { - RenderDiff(this, editorInstance, autoSaveKey); + RenderDiff(this, editorInstance, autoSaveKey) }, onOk: function () { if (localStorage.getItem(autoSaveKey)) { - var jsonSavedContent = LoadData(autoSaveKey); - editorInstance.setData(jsonSavedContent.data); + var jsonSavedContent = LoadData(autoSaveKey) + editorInstance.setData(jsonSavedContent.data) - RemoveStorage(autoSaveKey, editorInstance); + RemoveStorage(autoSaveKey, editorInstance) } }, onCancel: function () { - RemoveStorage(autoSaveKey, editorInstance); + RemoveStorage(autoSaveKey, editorInstance) }, contents: [ { @@ -228,7 +228,7 @@ CKEDITOR.MmsAutosavePlugin = (function () { ], default: config.diffType, onClick: function () { - RenderDiff(this._.dialog, editorInstance, autoSaveKey); + RenderDiff(this._.dialog, editorInstance, autoSaveKey) }, }, { @@ -246,8 +246,8 @@ CKEDITOR.MmsAutosavePlugin = (function () { label: editorInstance.lang.autosave.ok, class: 'cke_dialog_ui_button_ok cke_dialog_autosave_ok', onClick: function (evt) { - var dialog = evt.data.dialog; - if (dialog.fire('ok', { hide: true }).hide !== false) dialog.hide(); + var dialog = evt.data.dialog + if (dialog.fire('ok', { hide: true }).hide !== false) dialog.hide() }, }, { @@ -256,42 +256,42 @@ CKEDITOR.MmsAutosavePlugin = (function () { label: editorInstance.lang.autosave.no, class: 'cke_dialog_ui_button_cancel', onClick: function (evt) { - var dialog = evt.data.dialog; - if (dialog.fire('cancel', { hide: true }).hide !== false) dialog.hide(); + var dialog = evt.data.dialog + if (dialog.fire('cancel', { hide: true }).hide !== false) dialog.hide() }, }, ], - }; - }); + } + }) } function CheckForAutoSavedContent(editorInstance, config, autoSaveKey, notOlderThen) { // Checks If there is data available and load it if (localStorage.getItem(autoSaveKey)) { - var jsonSavedContent = LoadData(autoSaveKey); + var jsonSavedContent = LoadData(autoSaveKey) - var autoSavedContent = jsonSavedContent.data; - var autoSavedContentDate = jsonSavedContent.saveTime; + var autoSavedContent = jsonSavedContent.data + var autoSavedContentDate = jsonSavedContent.saveTime - var editorLoadedContent = editorInstance.getData(); + var editorLoadedContent = editorInstance.getData() // check if the loaded editor content is the same as the autosaved content if (editorLoadedContent === autoSavedContent) { - localStorage.removeItem(autoSaveKey); - return; + localStorage.removeItem(autoSaveKey) + return } // Ignore if autosaved content is older then x minutes if (moment(new Date()).diff(new Date(autoSavedContentDate), 'minutes') > notOlderThen) { - RemoveStorage(autoSaveKey, editorInstance); + RemoveStorage(autoSaveKey, editorInstance) - return; + return } if (config.autoLoad) { if (localStorage.getItem(autoSaveKey)) { - editorInstance.setData(autoSavedContent); - RemoveStorage(autoSaveKey, editorInstance); + editorInstance.setData(autoSavedContent) + RemoveStorage(autoSaveKey, editorInstance) } } else { var confirmMessage = editorInstance.lang.autosave.loadSavedContent.replace( @@ -299,41 +299,41 @@ CKEDITOR.MmsAutosavePlugin = (function () { moment(autoSavedContentDate) .locale(editorInstance.config.language) .format(editorInstance.lang.autosave.dateFormat) - ); + ) - _handleAutosaveConfirmationDialog(confirmMessage, editorInstance, autoSaveKey); + _handleAutosaveConfirmationDialog(confirmMessage, editorInstance, autoSaveKey) } } } function _handleAutosaveConfirmationDialog(confirmMessage, editorInstance, autoSaveKey) { - var autosaveModalId = 'autosaveModal'; - var autosaveMessageId = 'autosaveMessage'; - var autosaveModal = $('#' + autosaveModalId); + var autosaveModalId = 'autosaveModal' + var autosaveMessageId = 'autosaveMessage' + var autosaveModal = $('#' + autosaveModalId) if (autosaveModal.length) { - autosaveModal.find('#' + autosaveMessageId).html(confirmMessage); + autosaveModal.find('#' + autosaveMessageId).html(confirmMessage) } else { - var dialogDom = _createDialogDom(confirmMessage, autosaveModalId, autosaveMessageId); - dialogDom.appendTo('body'); - autosaveModal = $('#' + autosaveModalId); + var dialogDom = _createDialogDom(confirmMessage, autosaveModalId, autosaveMessageId) + dialogDom.appendTo('body') + autosaveModal = $('#' + autosaveModalId) } $('#autosave-confirm') .unbind('click') .click(function () { - autosaveModal.css('display', 'none'); - var dialog = editorInstance.openDialog('autosaveDialog'); - var dialogDom = dialog.getElement()['$']; - var contentDom = $(dialogDom).children(':first'); - contentDom.addClass('autosave'); - }); + autosaveModal.css('display', 'none') + var dialog = editorInstance.openDialog('autosaveDialog') + var dialogDom = dialog.getElement()['$'] + var contentDom = $(dialogDom).children(':first') + contentDom.addClass('autosave') + }) $('#autosave-cancel') .unbind('click') .click(function () { - RemoveStorage(autoSaveKey, editorInstance); - autosaveModal.css('display', 'none'); - }); - autosaveModal.css('display', 'block'); + RemoveStorage(autoSaveKey, editorInstance) + autosaveModal.css('display', 'none') + }) + autosaveModal.css('display', 'block') } function _createDialogDom(message, autosaveModalId, autosaveMessageId) { @@ -355,15 +355,15 @@ CKEDITOR.MmsAutosavePlugin = (function () { ' \n' + ' \n' + ' \n' + - ''; - var dialogDom = $(dialogHtml); - dialogDom.find('#' + autosaveMessageId).html(message); - return dialogDom; + '' + var dialogDom = $(dialogHtml) + dialogDom.find('#' + autosaveMessageId).html(message) + return dialogDom } function LoadData(autoSaveKey) { - var compressedJSON = LZString.decompressFromUTF16(localStorage.getItem(autoSaveKey)); - return JSON.parse(compressedJSON); + var compressedJSON = LZString.decompressFromUTF16(localStorage.getItem(autoSaveKey)) + return JSON.parse(compressedJSON) } function SaveData(autoSaveKey, editorInstance, config) { @@ -373,7 +373,7 @@ CKEDITOR.MmsAutosavePlugin = (function () { saveTime: new Date(), isAutosaveContent: true, }) - ); + ) var quotaExceeded = _trySavingContentToLocalStorage( localStorage, @@ -382,7 +382,7 @@ CKEDITOR.MmsAutosavePlugin = (function () { config.NotOlderThen, autoSaveKey, compressedJSON - ); + ) /* if (quotaExceeded) { console.log(editorInstance.lang.autosave.localStorageFull); @@ -417,34 +417,34 @@ CKEDITOR.MmsAutosavePlugin = (function () { function _changeAutosavePopupStyle(editorInstance, notification) { // Allow changing style for "autosave" popup - var editorElement = $(editorInstance.container['$']); - editorElement.css('position', 'relative'); - var autosavePopupElement = $('#' + notification.id); - autosavePopupElement.appendTo(editorElement); + var editorElement = $(editorInstance.container['$']) + editorElement.css('position', 'relative') + var autosavePopupElement = $('#' + notification.id) + autosavePopupElement.appendTo(editorElement) autosavePopupElement.css({ position: 'absolute', - }); + }) autosavePopupElement.css({ left: editorElement.outerWidth(true) - autosavePopupElement.outerWidth(true), top: editorElement.outerHeight(true) - autosavePopupElement.outerHeight(true), - }); + }) } function RemoveStorage(autoSaveKey, editor) { if (editor.config.autosave_timeOutId) { - clearTimeout(editor.config.autosave_timeOutId); + clearTimeout(editor.config.autosave_timeOutId) } - localStorage.removeItem(autoSaveKey); + localStorage.removeItem(autoSaveKey) } function RenderDiff(dialog, editorInstance, autoSaveKey) { - var jsonSavedContent = LoadData(autoSaveKey); + var jsonSavedContent = LoadData(autoSaveKey) - var base = difflib.stringAsLines(editorInstance.getData()); - var newtxt = difflib.stringAsLines(jsonSavedContent.data); - var sm = new difflib.SequenceMatcher(base, newtxt); - var opcodes = sm.get_opcodes(); + var base = difflib.stringAsLines(editorInstance.getData()) + var newtxt = difflib.stringAsLines(jsonSavedContent.data) + var sm = new difflib.SequenceMatcher(base, newtxt) + var opcodes = sm.get_opcodes() dialog .getContentElement('general', 'diffContent') @@ -466,85 +466,85 @@ CKEDITOR.MmsAutosavePlugin = (function () { viewType: dialog.getContentElement('general', 'diffType').getValue() == 'inline' ? 1 : 0, }).outerHTML + '' - ); + ) } function isQuotaExceeded(e) { - var quotaExceeded = false; + var quotaExceeded = false if (e) { if (e.code) { switch (e.code) { case 22: - quotaExceeded = true; - break; + quotaExceeded = true + break case 1014: // Firefox if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { - quotaExceeded = true; + quotaExceeded = true } - break; + break } } else if (e.number === -2147024882) { // Internet Explorer 8 - quotaExceeded = true; + quotaExceeded = true } } - return quotaExceeded; + return quotaExceeded } // Querystring mitigator - Quick and dirty paste. // I don't know who original author is for creds. // https://stackoverflow.com/a/11654436/2418655 function autosaveRemoveUrlParam(key, value, url) { - if (!url) url = window.location.href; + if (!url) url = window.location.href var re = new RegExp('([?&])' + key + '=.*?(&|#|$)(.*)', 'gi'), - hash; + hash if (re.test(url)) { if (typeof value !== 'undefined' && value !== null) { - return url.replace(re, '$1' + key + '=' + value + '$2$3'); + return url.replace(re, '$1' + key + '=' + value + '$2$3') } else { - hash = url.split('#'); - url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, ''); + hash = url.split('#') + url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '') if (typeof hash[1] !== 'undefined' && hash[1] !== null) { - url += '#' + hash[1]; + url += '#' + hash[1] } - return url; + return url } } else { if (typeof value !== 'undefined' && value !== null) { - var separator = url.indexOf('?') !== -1 ? '&' : '?'; - hash = url.split('#'); - url = hash[0] + separator + key + '=' + value; + var separator = url.indexOf('?') !== -1 ? '&' : '?' + hash = url.split('#') + url = hash[0] + separator + key + '=' + value if (typeof hash[1] !== 'undefined' && hash[1] !== null) { - url += '#' + hash[1]; + url += '#' + hash[1] } - return url; + return url } else { - return url; + return url } } } function _jsonParse(contentToParse) { try { - var parseValue = JSON.parse(contentToParse.value); + var parseValue = JSON.parse(contentToParse.value) if (typeof parseValue === 'object' && parseValue !== null) { - return { key: contentToParse.key, value: parseValue }; + return { key: contentToParse.key, value: parseValue } } } catch (e) {} - return {}; + return {} } function _removeAllExpiredAutosave(localStorage, listOfExpiredAutosave) { listOfExpiredAutosave.forEach(function (expiredAutosave) { - localStorage.removeItem(expiredAutosave.key); - }); + localStorage.removeItem(expiredAutosave.key) + }) } function _getAllExpiredAutosave(listOfAutosave, minutesTillExpired, currentDate, moment) { return listOfAutosave.filter(function (autosave) { - return moment(currentDate).diff(new Date(autosave.value.saveTime), 'minutes') > minutesTillExpired; - }); + return moment(currentDate).diff(new Date(autosave.value.saveTime), 'minutes') > minutesTillExpired + }) } function _getAllAutosave(localStorage, LZString) { @@ -553,18 +553,18 @@ CKEDITOR.MmsAutosavePlugin = (function () { return { key: autosaveKey, value: LZString.decompressFromUTF16(localStorage.getItem(autosaveKey)), - }; + } }) .map(_jsonParse) .filter(function (jsonObj) { - return jsonObj.value && jsonObj.value.isAutosaveContent; - }); + return jsonObj.value && jsonObj.value.isAutosaveContent + }) } function _clearExpiredLocalStorageContents(localStorage, moment, LZString, minutesTillExpired) { - var listOfAutosave = _getAllAutosave(localStorage, LZString); - var listOfExpiredAutosave = _getAllExpiredAutosave(listOfAutosave, minutesTillExpired, new Date(), moment); - _removeAllExpiredAutosave(localStorage, listOfExpiredAutosave); + var listOfAutosave = _getAllAutosave(localStorage, LZString) + var listOfExpiredAutosave = _getAllExpiredAutosave(listOfAutosave, minutesTillExpired, new Date(), moment) + _removeAllExpiredAutosave(localStorage, listOfExpiredAutosave) } function _trySavingContentToLocalStorage( @@ -575,23 +575,23 @@ CKEDITOR.MmsAutosavePlugin = (function () { autosaveKey, compressedJSON ) { - var quotaExceeded = false; + var quotaExceeded = false try { - localStorage.setItem(autosaveKey, compressedJSON); + localStorage.setItem(autosaveKey, compressedJSON) } catch (e) { if (isQuotaExceeded(e)) { // need to use "customHelpers" at the front. If not, jasmine's spy wont work on this function // since it will be "_clearExpiredLocalStorageContents" in this local scope and not "_clearExpiredLocalStorageContents" // on "customHelpers" object where the spy is set - customHelpers._clearExpiredLocalStorageContents(localStorage, moment, LZString, minutesTillExpired); + customHelpers._clearExpiredLocalStorageContents(localStorage, moment, LZString, minutesTillExpired) try { - localStorage.setItem(autosaveKey, compressedJSON); + localStorage.setItem(autosaveKey, compressedJSON) } catch (e) { - quotaExceeded = true; + quotaExceeded = true } } } - return quotaExceeded; + return quotaExceeded } var customHelpers = { @@ -601,6 +601,6 @@ CKEDITOR.MmsAutosavePlugin = (function () { _getAllAutosave: _getAllAutosave, _clearExpiredLocalStorageContents: _clearExpiredLocalStorageContents, _trySavingContentToLocalStorage: _trySavingContentToLocalStorage, - }; - return customHelpers; -})(); + } + return customHelpers +})() diff --git a/src/lib/ckeditor-plugins/mathjax/dialogs/mathjax.js b/src/lib/ckeditor-plugins/mathjax/dialogs/mathjax.js index f004b18b8..4a4072ae1 100644 --- a/src/lib/ckeditor-plugins/mathjax/dialogs/mathjax.js +++ b/src/lib/ckeditor-plugins/mathjax/dialogs/mathjax.js @@ -2,62 +2,6 @@ Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ -CKEDITOR.dialog.add('mathjax', function (d) { - var c, - b = d.lang.mathjax; - return { - title: b.title, - minWidth: 350, - minHeight: 100, - contents: [ - { - id: 'info', - elements: [ - { - id: 'equation', - type: 'textarea', - label: b.dialogInput, - onLoad: function () { - var a = this; - if (!CKEDITOR.env.ie || 8 != CKEDITOR.env.version) - this.getInputElement().on('keyup', function () { - c.setValue('\\(' + a.getInputElement().getValue() + '\\)'); - }); - }, - setup: function (a) { - this.setValue(CKEDITOR.plugins.mathjax.trim(a.data.math)); - }, - commit: function (a) { - a.setData('math', '\\(' + this.getValue() + '\\)'); - }, - }, - { - id: 'documentation', - type: 'html', - html: - '\x3cdiv style\x3d"width:100%;text-align:right;margin:-8px 0 10px"\x3e\x3ca class\x3d"cke_mathjax_doc" href\x3d"' + - b.docUrl + - '" target\x3d"_black" style\x3d"cursor:pointer;color:#00B2CE;text-decoration:underline"\x3e' + - b.docLabel + - '\x3c/a\x3e\x3c/div\x3e', - }, - !(CKEDITOR.env.ie && 8 == CKEDITOR.env.version) && { - id: 'preview', - type: 'html', - html: - '\x3cdiv style\x3d"width:100%;text-align:center;"\x3e\x3ciframe style\x3d"border:0;width:0;height:0;font-size:20px" scrolling\x3d"no" frameborder\x3d"0" allowTransparency\x3d"true" src\x3d"' + - CKEDITOR.plugins.mathjax.fixSrc + - '"\x3e\x3c/iframe\x3e\x3c/div\x3e', - onLoad: function () { - var a = CKEDITOR.document.getById(this.domId).getChild(0); - c = new CKEDITOR.plugins.mathjax.frameWrapper(a, d); - }, - setup: function (a) { - c.setValue(a.data.math); - }, - }, - ], - }, - ], - }; -}); +CKEDITOR.dialog.add("mathjax",function(d){var c,b=d.lang.mathjax;return{title:b.title,minWidth:350,minHeight:100,contents:[{id:"info",elements:[{id:"equation",type:"textarea",label:b.dialogInput,onLoad:function(){var a=this;if(!CKEDITOR.env.ie||8!=CKEDITOR.env.version)this.getInputElement().on("keyup",function(){c.setValue("\\("+a.getInputElement().getValue()+"\\)")})},setup:function(a){this.setValue(CKEDITOR.plugins.mathjax.trim(a.data.math))},commit:function(a){a.setData("math","\\("+this.getValue()+ +"\\)")}},{id:"documentation",type:"html",html:'\x3cdiv style\x3d"width:100%;text-align:right;margin:-8px 0 10px"\x3e\x3ca class\x3d"cke_mathjax_doc" href\x3d"'+b.docUrl+'" target\x3d"_black" style\x3d"cursor:pointer;color:#00B2CE;text-decoration:underline"\x3e'+b.docLabel+"\x3c/a\x3e\x3c/div\x3e"},!(CKEDITOR.env.ie&&8==CKEDITOR.env.version)&&{id:"preview",type:"html",html:'\x3cdiv style\x3d"width:100%;text-align:center;"\x3e\x3ciframe style\x3d"border:0;width:0;height:0;font-size:20px" scrolling\x3d"no" frameborder\x3d"0" allowTransparency\x3d"true" src\x3d"'+ +CKEDITOR.plugins.mathjax.fixSrc+'"\x3e\x3c/iframe\x3e\x3c/div\x3e',onLoad:function(){var a=CKEDITOR.document.getById(this.domId).getChild(0);c=new CKEDITOR.plugins.mathjax.frameWrapper(a,d)},setup:function(a){c.setValue(a.data.math)}}]}]}}); \ No newline at end of file diff --git a/src/lib/ckeditor-plugins/mathjax/plugin.js b/src/lib/ckeditor-plugins/mathjax/plugin.js index 23d302f53..09d596b3c 100644 --- a/src/lib/ckeditor-plugins/mathjax/plugin.js +++ b/src/lib/ckeditor-plugins/mathjax/plugin.js @@ -7,8 +7,8 @@ * @fileOverview The [Mathematical Formulas](https://ckeditor.com/cke4/addon/mathjax) plugin that allows you to create and modify mathematical equations written in TeX directly in CKEditor.. */ -'use strict'; -(function () { +'use strict' +;(function () { CKEDITOR.plugins.add('mathjax', { // jscs:disable maximumLineLength lang: 'af,ar,az,bg,ca,cs,cy,da,de,de-ch,el,en,en-au,en-gb,eo,es,es-mx,et,eu,fa,fi,fr,gl,he,hr,hu,id,it,ja,km,ko,ku,lt,lv,nb,nl,no,oc,pl,pt,pt-br,ro,ru,sk,sl,sq,sr,sr-latn,sv,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE% @@ -18,14 +18,14 @@ hidpi: true, // %REMOVE_LINE_CORE% isSupportedEnvironment: function () { - return !CKEDITOR.env.ie || CKEDITOR.env.version > 8; + return !CKEDITOR.env.ie || CKEDITOR.env.version > 8 }, init: function (editor) { - var cls = editor.config.mathJaxClass || 'math-tex'; + var cls = editor.config.mathJaxClass || 'math-tex' if (!editor.config.mathJaxLib) { - CKEDITOR.error('mathjax-no-config'); + CKEDITOR.error('mathjax-no-config') } editor.widgets.add('mathjax', { @@ -36,11 +36,11 @@ allowedContent: 'span(!' + cls + ')', // Allow style classes only on spans having mathjax class. styleToAllowedContentRules: function (style) { - var classes = style.getClassesArray(); - if (!classes) return null; - classes.push('!' + cls); + var classes = style.getClassesArray() + if (!classes) return null + classes.push('!' + cls) - return 'span(' + classes.join(',') + ')'; + return 'span(' + classes.join(',') + ')' }, pathName: editor.lang.mathjax.pathName, @@ -55,19 +55,19 @@ }, init: function () { - var iframe = this.parts.span.getChild(0); + var iframe = this.parts.span.getChild(0) // Check if span contains iframe and create it otherwise. if (!iframe || iframe.type != CKEDITOR.NODE_ELEMENT || !iframe.is('iframe')) { - iframe = new CKEDITOR.dom.element('iframe'); + iframe = new CKEDITOR.dom.element('iframe') iframe.setAttributes({ style: 'border:0;width:0;height:0', scrolling: 'no', frameborder: 0, allowTransparency: true, src: CKEDITOR.plugins.mathjax.fixSrc, - }); - this.parts.span.append(iframe); + }) + this.parts.span.append(iframe) } // Wait for ready because on some browsers iFrame will not @@ -76,78 +76,78 @@ this.once('ready', function () { // Src attribute must be recreated to fix custom domain error after undo // (see iFrame.removeAttribute( 'src' ) in frameWrapper.load). - if (CKEDITOR.env.ie) iframe.setAttribute('src', CKEDITOR.plugins.mathjax.fixSrc); + if (CKEDITOR.env.ie) iframe.setAttribute('src', CKEDITOR.plugins.mathjax.fixSrc) - this.frameWrapper = new CKEDITOR.plugins.mathjax.frameWrapper(iframe, editor); - this.frameWrapper.setValue(this.data.math); - }); + this.frameWrapper = new CKEDITOR.plugins.mathjax.frameWrapper(iframe, editor) + this.frameWrapper.setValue(this.data.math) + }) }, data: function () { - if (this.frameWrapper) this.frameWrapper.setValue(this.data.math); + if (this.frameWrapper) this.frameWrapper.setValue(this.data.math) }, upcast: function (el, data) { - if (!(el.name == 'span' && el.hasClass(cls))) return; + if (!(el.name == 'span' && el.hasClass(cls))) return - if (el.children.length > 1 || el.children[0].type != CKEDITOR.NODE_TEXT) return; + if (el.children.length > 1 || el.children[0].type != CKEDITOR.NODE_TEXT) return - data.math = CKEDITOR.tools.htmlDecode(el.children[0].value); + data.math = CKEDITOR.tools.htmlDecode(el.children[0].value) // Add style display:inline-block to have proper height of widget wrapper and mask. - var attrs = el.attributes; + var attrs = el.attributes - if (attrs.style) attrs.style += ';display:inline-block'; - else attrs.style = 'display:inline-block'; + if (attrs.style) attrs.style += ';display:inline-block' + else attrs.style = 'display:inline-block' // Add attribute to prevent deleting empty span in data processing. - attrs['data-cke-survive'] = 1; + attrs['data-cke-survive'] = 1 - el.children[0].remove(); + el.children[0].remove() - return el; + return el }, downcast: function (el) { - el.children[0].replaceWith(new CKEDITOR.htmlParser.text(CKEDITOR.tools.htmlEncode(this.data.math))); + el.children[0].replaceWith(new CKEDITOR.htmlParser.text(CKEDITOR.tools.htmlEncode(this.data.math))) // Remove style display:inline-block. - var attrs = el.attributes; - attrs.style = attrs.style.replace(/display:\s?inline-block;?\s?/, ''); - if (attrs.style === '') delete attrs.style; + var attrs = el.attributes + attrs.style = attrs.style.replace(/display:\s?inline-block;?\s?/, '') + if (attrs.style === '') delete attrs.style - return el; + return el }, - }); + }) // Add dialog. - CKEDITOR.dialog.add('mathjax', this.path + 'dialogs/mathjax.js'); + CKEDITOR.dialog.add('mathjax', this.path + 'dialogs/mathjax.js') // Add MathJax script to page preview. editor.on('contentPreview', function (evt) { evt.data.dataValue = evt.data.dataValue.replace( /<\/head>/, '' - ); - }); + ) + }) editor.on('paste', function (evt) { // Firefox does remove iFrame elements from pasted content so this event do the same on other browsers. // Also iFrame in paste content is reason of "Unspecified error" in IE9 (https://dev.ckeditor.com/ticket/10857). - var regex = new RegExp(']*?' + cls + '.*?', 'ig'); + var regex = new RegExp(']*?' + cls + '.*?', 'ig') evt.data.dataValue = evt.data.dataValue.replace(regex, function (match) { - return match.replace(/()/i, ''); - }); - }); + return match.replace(/()/i, '') + }) + }) }, - }); + }) /** * @private * @singleton * @class CKEDITOR.plugins.mathjax */ - CKEDITOR.plugins.mathjax = {}; + CKEDITOR.plugins.mathjax = {} /** * A variable to fix problems with `iframe`. This variable is global @@ -167,7 +167,7 @@ encodeURIComponent('document.open();' + '(' + CKEDITOR.tools.fixDomain + ')();' + 'document.close();') + '})())' : // In Chrome src must be undefined to emit load event. - 'javascript:void(0)'; // jshint ignore:line + 'javascript:void(0)' // jshint ignore:line /** * Loading indicator image generated by http://preloaders.net. @@ -175,7 +175,7 @@ * @private * @property {String} loadingIcon */ - CKEDITOR.plugins.mathjax.loadingIcon = CKEDITOR.plugins.get('mathjax').path + 'images/loader.gif'; + CKEDITOR.plugins.mathjax.loadingIcon = CKEDITOR.plugins.get('mathjax').path + 'images/loader.gif' /** * Computes predefined styles and copies them to another element. @@ -185,14 +185,14 @@ * @param {CKEDITOR.dom.element} to Copy target. */ CKEDITOR.plugins.mathjax.copyStyles = function (from, to) { - var stylesToCopy = ['color', 'font-family', 'font-style', 'font-weight', 'font-variant', 'font-size']; + var stylesToCopy = ['color', 'font-family', 'font-style', 'font-weight', 'font-variant', 'font-size'] for (var i = 0; i < stylesToCopy.length; i++) { var key = stylesToCopy[i], - val = from.getComputedStyle(key); - if (val) to.setStyle(key, val); + val = from.getComputedStyle(key) + if (val) to.setStyle(key, val) } - }; + } /** * Trims MathJax value from '\(1+1=2\)' to '1+1=2'. @@ -203,10 +203,10 @@ */ CKEDITOR.plugins.mathjax.trim = function (value) { var begin = value.indexOf('\\(') + 2, - end = value.lastIndexOf('\\)'); + end = value.lastIndexOf('\\)') - return value.substring(begin, end); - }; + return value.substring(begin, end) + } /** * FrameWrapper is responsible for communication between the MathJax library @@ -234,61 +234,61 @@ isRunning = false, // Function called when MathJax is loaded. loadedHandler = CKEDITOR.tools.addFunction(function () { - preview = doc.getById('preview'); - buffer = doc.getById('buffer'); - isInit = true; + preview = doc.getById('preview') + buffer = doc.getById('buffer') + isInit = true - if (newValue) update(); + if (newValue) update() // Private! For test usage only. - CKEDITOR.fire('mathJaxLoaded', iFrame); + CKEDITOR.fire('mathJaxLoaded', iFrame) }), // Function called when MathJax finish his job. updateDoneHandler = CKEDITOR.tools.addFunction(function () { - CKEDITOR.plugins.mathjax.copyStyles(iFrame, preview); + CKEDITOR.plugins.mathjax.copyStyles(iFrame, preview) - preview.setHtml(buffer.getHtml()); + preview.setHtml(buffer.getHtml()) - editor.fire('lockSnapshot'); + editor.fire('lockSnapshot') iFrame.setStyles({ height: 0, width: 0, - }); + }) // Set iFrame dimensions. var height = Math.max(doc.$.body.offsetHeight, doc.$.documentElement.offsetHeight), - width = Math.max(preview.$.offsetWidth, doc.$.body.scrollWidth); + width = Math.max(preview.$.offsetWidth, doc.$.body.scrollWidth) iFrame.setStyles({ height: height + 'px', width: width + 'px', - }); + }) - editor.fire('unlockSnapshot'); + editor.fire('unlockSnapshot') // Private! For test usage only. - CKEDITOR.fire('mathJaxUpdateDone', iFrame); + CKEDITOR.fire('mathJaxUpdateDone', iFrame) // If value changed in the meantime update it again. - if (value != newValue) update(); - else isRunning = false; - }); + if (value != newValue) update() + else isRunning = false + }) // Function called to run MathJax on update and star - iFrame.on('load', load); + iFrame.on('load', load) - load(); + load() function load() { - doc = iFrame.getFrameDocument(); + doc = iFrame.getFrameDocument() - if (doc.getById('preview')) return; + if (doc.getById('preview')) return // Because of IE9 bug in a src attribute can not be javascript // when you undo (https://dev.ckeditor.com/ticket/10930). If you have iFrame with javascript in src // and call insertBefore on such element then IE9 will see crash. - if (CKEDITOR.env.ie) iFrame.removeAttribute('src'); + if (CKEDITOR.env.ie) iFrame.removeAttribute('src') doc.write( ` @@ -368,35 +368,35 @@ ` - ); + ) } // Run MathJax parsing Tex. function update() { - isRunning = true; + isRunning = true - value = newValue; + value = newValue - editor.fire('lockSnapshot'); + editor.fire('lockSnapshot') - buffer.setHtml(value); + buffer.setHtml(value) // Set loading indicator. preview.setHtml( ' + editor.lang.mathjax.loading + ' - ); + ) iFrame.setStyles({ height: '16px', width: '16px', display: 'inline', 'vertical-align': 'middle', - }); + }) - editor.fire('unlockSnapshot'); + editor.fire('unlockSnapshot') // Run MathJax. - doc.getWindow().$.update(value); + doc.getWindow().$.update(value) } return { @@ -409,12 +409,12 @@ * @param {String} value TeX string. */ setValue: function (value) { - newValue = CKEDITOR.tools.htmlEncode(value); + newValue = CKEDITOR.tools.htmlEncode(value) - if (isInit && !isRunning) update(); + if (isInit && !isRunning) update() }, - }; - }; + } + } } else { // In IE8 MathJax does not work stable so instead of using standard // frame wrapper it is replaced by placeholder to show pure TeX in iframe. @@ -431,32 +431,32 @@ '' + '' + '' - ); + ) return { setValue: function (value) { var doc = iFrame.getFrameDocument(), - tex = doc.getById('tex'); + tex = doc.getById('tex') - tex.setHtml(CKEDITOR.plugins.mathjax.trim(CKEDITOR.tools.htmlEncode(value))); + tex.setHtml(CKEDITOR.plugins.mathjax.trim(CKEDITOR.tools.htmlEncode(value))) - CKEDITOR.plugins.mathjax.copyStyles(iFrame, tex); + CKEDITOR.plugins.mathjax.copyStyles(iFrame, tex) - editor.fire('lockSnapshot'); + editor.fire('lockSnapshot') iFrame.setStyles({ width: Math.min(250, tex.$.offsetWidth) + 'px', height: doc.$.body.offsetHeight + 'px', display: 'inline', 'vertical-align': 'middle', - }); + }) - editor.fire('unlockSnapshot'); + editor.fire('unlockSnapshot') }, - }; - }; + } + } } -})(); +})() /** * Sets the path to the MathJax library. It can be both a local resource and a location different than the default CDN. diff --git a/src/lib/ckeditor-plugins/mmscf/plugin.js b/src/lib/ckeditor-plugins/mmscf/plugin.js index 6819d05af..5bdc07577 100644 --- a/src/lib/ckeditor-plugins/mmscf/plugin.js +++ b/src/lib/ckeditor-plugins/mmscf/plugin.js @@ -18,18 +18,18 @@ CKEDITOR.plugins.add('mmscf', { insert: () => { var defaultConfig = { callbackModalFnc: () => { - console.log('There is no callback function defined'); + console.log('There is no callback function defined') }, - }; - var config = CKEDITOR.tools.extend(defaultConfig, editor.config.mmscf || {}, true); - var tag = config.callbackModalFnc(editor, false); + } + var config = CKEDITOR.tools.extend(defaultConfig, editor.config.mmscf || {}, true) + var tag = config.callbackModalFnc(editor, false) }, // Check the elements that need to be converted to widgets. upcast: (element) => { // Return "true" (that element needs to converted to a mmscf widget) // for all elements. - return element.name === 'mms-cf' && element.attributes['mms-cf-type'] !== 'com'; + return element.name === 'mms-cf' && element.attributes['mms-cf-type'] !== 'com' }, - }); + }) }, -}); +}) diff --git a/src/lib/ckeditor-plugins/mmscomment/plugin.js b/src/lib/ckeditor-plugins/mmscomment/plugin.js index da44fd297..253e8cac3 100644 --- a/src/lib/ckeditor-plugins/mmscomment/plugin.js +++ b/src/lib/ckeditor-plugins/mmscomment/plugin.js @@ -17,11 +17,11 @@ CKEDITOR.plugins.add('mmscomment', { insert: () => { var defaultConfig = { callbackModalFnc: () => { - console.log('There is no callback function defined'); + console.log('There is no callback function defined') }, - }; - var config = CKEDITOR.tools.extend(defaultConfig, editor.config.mmscomment || {}, true); - var tag = config.callbackModalFnc(editor); + } + var config = CKEDITOR.tools.extend(defaultConfig, editor.config.mmscomment || {}, true) + var tag = config.callbackModalFnc(editor) }, // Check the elements that need to be converted to widgets. upcast: (element) => { @@ -31,8 +31,8 @@ CKEDITOR.plugins.add('mmscomment', { element.name === 'transclude-com' || element.name === 'mms-transclude-com' || (element.name === 'mms-cf' && element.attributes['mms-cf-type'] === 'com') - ); + ) }, - }); + }) }, -}); +}) diff --git a/src/lib/ckeditor-plugins/mmsdropdown/plugin.js b/src/lib/ckeditor-plugins/mmsdropdown/plugin.js index 1bdb1a6b6..b4e3291df 100644 --- a/src/lib/ckeditor-plugins/mmsdropdown/plugin.js +++ b/src/lib/ckeditor-plugins/mmsdropdown/plugin.js @@ -2,7 +2,7 @@ CKEDITOR.plugins.add('mmsdropdown', { requires: ['richcombo'], init: (editor) => { var config = editor.config, - lang = editor.lang.format; + lang = editor.lang.format function createItem(options) { return options.isMmsCustomPlugin ? ' ' + options.label + - ' '; + ' ' } editor.ui.addRichCombo('mmsExtraFeature', { title: 'Insert more content', className: 'mmsExtraFeature', multiSelect: false, panel: { - css: [CKEDITOR.skin.getPath('editor')].concat(config.contentsCss), + css: [CKEDITOR.skin.getPath('editor')].concat( + config.contentsCss + ), }, init: () => { @@ -29,21 +31,25 @@ CKEDITOR.plugins.add('mmsdropdown', { 'mmscf', createItem({ isMmsCustomPlugin: true, - imgSrc: window.CKEDITOR_BASEPATH + 'plugins/mmscf/icons/mmscf.png', + imgSrc: + window.CKEDITOR_BASEPATH + + 'plugins/mmscf/icons/mmscf.png', label: 'Cross Reference', }), 'Insert Cross Reference' - ); + ) this.add( 'mmsvlink', createItem({ isMmsCustomPlugin: true, - imgSrc: window.CKEDITOR_BASEPATH + 'plugins/mmsvlink/icons/mmsvlink.png', + imgSrc: + window.CKEDITOR_BASEPATH + + 'plugins/mmsvlink/icons/mmsvlink.png', label: 'Cross Reference as link', }), 'Insert Cross Reference as link (View Link)' - ); - this.add('', '
    ', 'mms-br'); + ) + this.add('', '
    ', 'mms-br') this.add( 'link', @@ -53,7 +59,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Link', }), 'Insert link' - ); + ) this.add( 'table', createItem({ @@ -62,7 +68,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Table', }), 'Insert table' - ); + ) this.add( 'image', createItem({ @@ -71,7 +77,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Image', }), 'Insert image' - ); + ) this.add( 'iframe', createItem({ @@ -80,7 +86,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Iframe', }), 'Insert iframe' - ); + ) this.add( 'mathjax', createItem({ @@ -89,7 +95,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Math', }), 'Insert math' - ); + ) this.add( 'specialchar', createItem({ @@ -98,19 +104,21 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Special Character', }), 'Insert symbol' - ); - this.add('', '
    ', 'mms-br'); + ) + this.add('', '
    ', 'mms-br') this.add( 'mmscomment', createItem({ isMmsCustomPlugin: true, - imgSrc: window.CKEDITOR_BASEPATH + 'plugins/mmscomment/icons/mmscomment.png', + imgSrc: + window.CKEDITOR_BASEPATH + + 'plugins/mmscomment/icons/mmscomment.png', label: 'Comment', }), 'Insert comment' - ); - this.add('', '
    ', 'mms-br'); + ) + this.add('', '
    ', 'mms-br') this.add( 'codeSnippet', @@ -120,7 +128,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Code Snippet', }), 'Insert code snippet' - ); + ) this.add( 'blockquote', createItem({ @@ -129,8 +137,8 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Quote', }), 'Insert quote' - ); - this.add('', '
    ', 'mms-br'); + ) + this.add('', '
    ', 'mms-br') this.add( 'pagebreak', @@ -140,7 +148,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Page break for printing', }), 'Insert page break' - ); + ) this.add( 'horizontalrule', createItem({ @@ -149,32 +157,36 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Horizontal Rule', }), 'Insert horizontal rule' - ); - this.add('', '
    ', 'mms-br'); + ) + this.add('', '
    ', 'mms-br') this.add( 'mmssignature', createItem({ isMmsCustomPlugin: true, - imgSrc: window.CKEDITOR_BASEPATH + 'plugins/mmssignature/icons/mmssignature.png', + imgSrc: + window.CKEDITOR_BASEPATH + + 'plugins/mmssignature/icons/mmssignature.png', label: 'Signature template', }), 'Insert signature template' - ); + ) }, onClick: (command) => { if (command !== '') { - editor.execCommand(command); + editor.execCommand(command) } }, - }); + }) editor.ui.addRichCombo('mmsExtraFormat', { title: 'Extra formatting', className: 'mmsExtraFormat', multiSelect: false, panel: { - css: [CKEDITOR.skin.getPath('editor')].concat(config.contentsCss), + css: [CKEDITOR.skin.getPath('editor')].concat( + config.contentsCss + ), }, init: () => { this.add( @@ -185,7 +197,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Strikethrough', }), 'Strikethrough' - ); + ) this.add( 'superscript', createItem({ @@ -194,7 +206,7 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Superscript', }), 'Superscript' - ); + ) this.add( 'subscript', createItem({ @@ -203,8 +215,8 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Subscript', }), 'Subscript' - ); - this.add('', '
    ', 'mms-br'); + ) + this.add('', '
    ', 'mms-br') this.add( 'removeFormat', @@ -214,14 +226,14 @@ CKEDITOR.plugins.add('mmsdropdown', { label: 'Clear Formatting', }), 'Clear Formatting' - ); + ) }, onClick: (command) => { if (command !== '') { - editor.execCommand(command); + editor.execCommand(command) } }, - }); + }) }, -}); +}) diff --git a/src/lib/ckeditor-plugins/mmsreset/plugin.js b/src/lib/ckeditor-plugins/mmsreset/plugin.js index 04ca50bd4..f6e4ad433 100644 --- a/src/lib/ckeditor-plugins/mmsreset/plugin.js +++ b/src/lib/ckeditor-plugins/mmsreset/plugin.js @@ -11,17 +11,21 @@ CKEDITOR.plugins.add('mmsreset', { exec: (editor) => { var defaultConfig = { callbackModalFnc: () => { - console.log('There is no callback function defined'); + console.log('There is no callback function defined') }, - }; - var config = CKEDITOR.tools.extend(defaultConfig, editor.config.mmsreset || {}, true); - config.callback(editor); + } + var config = CKEDITOR.tools.extend( + defaultConfig, + editor.config.mmsreset || {}, + true + ) + config.callback(editor) }, - }); + }) editor.ui.addButton('mmsreset', { label: 'Update Cross Ref', command: 'mmsreset', - }); + }) }, -}); +}) diff --git a/src/lib/ckeditor-plugins/mmssignature/plugin.js b/src/lib/ckeditor-plugins/mmssignature/plugin.js index 2e09601ef..4aa4eb540 100644 --- a/src/lib/ckeditor-plugins/mmssignature/plugin.js +++ b/src/lib/ckeditor-plugins/mmssignature/plugin.js @@ -42,8 +42,10 @@ CKEDITOR.plugins.add('mmssignature', { }, upcast: (element) => { - return element.name == 'div' && element.hasClass('signature-box'); + return ( + element.name == 'div' && element.hasClass('signature-box') + ) }, - }); + }) }, -}); +}) diff --git a/src/lib/ckeditor-plugins/mmsvlink/plugin.js b/src/lib/ckeditor-plugins/mmsvlink/plugin.js index bc7a3c7a3..8fa36c9da 100644 --- a/src/lib/ckeditor-plugins/mmsvlink/plugin.js +++ b/src/lib/ckeditor-plugins/mmsvlink/plugin.js @@ -18,18 +18,18 @@ CKEDITOR.plugins.add('mmsvlink', { insert: () => { var defaultConfig = { callbackModalFnc: () => { - console.log('There is no callback function defined'); + console.log('There is no callback function defined') }, - }; - var config = CKEDITOR.tools.extend(defaultConfig, editor.config.mmsvlink || {}, true); - var tag = config.callbackModalFnc(editor, false); + } + var config = CKEDITOR.tools.extend(defaultConfig, editor.config.mmsvlink || {}, true) + var tag = config.callbackModalFnc(editor, false) }, // Check the elements that need to be converted to widgets. upcast: (element) => { // Return "true" (that element needs to converted to a mmsvlink widget) // for all elements. - return element.name === 'mms-view-link'; + return element.name === 'mms-view-link' }, - }); + }) }, -}); +}) diff --git a/src/lib/ckeditor-plugins/ve-ckeditor-plugins.d.ts b/src/lib/ckeditor-plugins/ve-ckeditor-plugins.d.ts index ed0a51c69..f001593b9 100644 --- a/src/lib/ckeditor-plugins/ve-ckeditor-plugins.d.ts +++ b/src/lib/ckeditor-plugins/ve-ckeditor-plugins.d.ts @@ -1,24 +1,24 @@ declare namespace CKEDITOR { namespace plugins { interface autoSaveConfig { - delay?: number; - messageType?: string; - saveOnDestroy?: boolean; - saveDetectionSelectors?: string; - diffType?: string; - autoLoad?: boolean; - NotOlderThen?: number; - enableAutosave?: boolean; - SaveKey?; + delay?: number + messageType?: string + saveOnDestroy?: boolean + saveDetectionSelectors?: string + diffType?: string + autoLoad?: boolean + NotOlderThen?: number + enableAutosave?: boolean + SaveKey? } } interface config { //MMS Specific - autosave?: plugins.autoSaveConfig; - mmscf?: { callbackModalFnc: (ed: editor) => void }; - mmscomment?: { callbackModalFnc: (ed: editor) => void }; - mmsvlink?: { callbackModalFnc: (ed: editor) => void }; - mmsreset?: { callback: (ed: editor) => void }; + autosave?: plugins.autoSaveConfig + mmscf?: { callbackModalFnc: (ed: editor) => void } + mmscomment?: { callbackModalFnc: (ed: editor) => void } + mmsvlink?: { callbackModalFnc: (ed: editor) => void } + mmsreset?: { callback: (ed: editor) => void } } } diff --git a/src/lib/ckeditor/CHANGES.md b/src/lib/ckeditor/CHANGES.md index a26d60274..4f20ea8c8 100644 --- a/src/lib/ckeditor/CHANGES.md +++ b/src/lib/ckeditor/CHANGES.md @@ -1,2237 +1,2237 @@ -# CKEditor 4 Changelog - -## CKEditor 4.19.1 - -Fixed Issues: - -- [#5125](https://github.com/ckeditor/ckeditor4/issues/5125): Fixed: Deleting a widget with disabled [autoParagraph](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-autoParagraph) by the keyboard `backspace` key removes the editor editable area and crashes the editor. -- [#5135](https://github.com/ckeditor/ckeditor4/issues/5135): Fixed: The [`checkbox.setValue`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_ui_dialog_checkbox.html#method-setValue) and [`radio.setValue`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_ui_dialog_radio.html#method-setValue) methods are not chainable as stated in the documentation. Thanks to [Jordan Bradford](https://github.com/LordPachelbel)! -- [#5085](https://github.com/ckeditor/ckeditor4/issues/5085): Fixed: The [Language](https://ckeditor.com/cke4/addon/language) plugin removes the element marking the text in foreign language if said element does not have an information about the text direction. -- [#4284](https://github.com/ckeditor/ckeditor4/issues/4284): Fixed: [Tableselection](https://ckeditor.com/cke4/addon/tableselection) Merging cells with a rowspan throws an unexpected error and does not create an undo step. -- [#5184](https://github.com/ckeditor/ckeditor4/issues/5184): Fixed: The [Editor Placeholder](https://ckeditor.com/cke4/addon/wysiwygarea) plugin degrades typing performance. -- [#5158](https://github.com/ckeditor/ckeditor4/issues/5158): Fixed: [`CKEDITOR.tools#convertToPx()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools.html#method-convertToPx) gives invalid results if the helper calculator element was deleted from the DOM. -- [#5234](https://github.com/ckeditor/ckeditor4/issues/5234): Fixed: [Easy Image](https://ckeditor.com/cke4/addon/easyimage) doesn't allow to upload images files using toolbar button. -- [#438](https://github.com/ckeditor/ckeditor4/issues/438): Fixed: It is impossible to navigate to the [elementspath](https://ckeditor.com/cke4/addon/elementspath) from the [toolbar](https://ckeditor.com/cke4/addon/toolbar) by keyboard and vice versa. -- [#4449](https://github.com/ckeditor/ckeditor4/issues/4449): Fixed: [`dialog.validate#functions`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-functions) incorrectly composes functions that return an optional error message, like e.g. [`dialog.validate.number`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-number) due to unnecessary return type coercion. -- [#4473](https://github.com/ckeditor/ckeditor4/issues/4473): Fixed: The [dialog.validate](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html) method does not accept parameter value. The issue originated in [dialog.validate.functions](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-functions) method that did not properly propagate parameter value to validator. Affected validators: - - [`functions`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-functions) - - [`equals`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-equals) - - [`notEqual`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-notEqual) - - [`cssLength`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-cssLength) - - [`htmlLength`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-htmlLength) - - [`inlineStyle`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog_validate.html#method-inlineStyle) -- [#5147](https://github.com/ckeditor/ckeditor4/issues/5147): Fixed: The [Accessibility Help](https://ckeditor.com/cke4/addon/a11yhelp) dialog does not contain info about focus being moved back to the editing area upon leaving dialogs. -- [#5144](https://github.com/ckeditor/ckeditor4/issues/5144): Fixed: [Menu buttons](https://ckeditor.com/cke4/addon/menubutton) and [panel buttons](https://ckeditor.com/cke4/addon/panelbutton) incorrectly indicate the open status of their associated pop-up menus in the browser's accessibility tree. -- [#5022](https://github.com/ckeditor/ckeditor4/issues/5022): Fixed: [Find and Replace](https://ckeditor.com/cke4/addon/find) does not respond to the `Enter` key. - -API changes: - -- [#5184](https://github.com/ckeditor/ckeditor4/issues/5184): Added the [`config.editorplaceholder_delay`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-editorplaceholder_delay) configuration option allowing to delay placeholder before it is toggled when changing editor content. -- [#5184](https://github.com/ckeditor/ckeditor4/issues/5184): Added the [`CKEDITOR.tools#debounce()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools.html#method-debounce) function allowing to postpone a passed function execution until the given milliseconds have elapsed since the last time it was invoked. - -## CKEditor 4.19.0 - -New features: - -- [#2444](https://github.com/ckeditor/ckeditor4/issues/2444): Togglable toolbar buttons are now exposed as toggle buttons in the browser's accessibility tree. -- [#4641](https://github.com/ckeditor/ckeditor4/issues/4641): Added an option allowing to cancel the [Delayed Editor Creation](https://ckeditor.com/docs/ckeditor4/latest/features/delayed_creation.html) feature as a function handle for editor creators ([`CKEDITOR.replace`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-replace), [`CKEDITOR.inline`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-inline), [`CKEDITOR.appendTo`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-appendTo)). -- [#4986](https://github.com/ckeditor/ckeditor4/issues/4986): Added [`config.shiftLineBreaks`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-shiftLineBreaks) allowing to preserve inline elements formatting when the `shift`+`enter` keystroke is used. -- [#2445](https://github.com/ckeditor/ckeditor4/issues/2445): Added [`config.applicationTitle`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-applicationTitle) configuration option allowing to customize or disable the editor's application region label. This option, combined with [`config.title`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-title), gives much better control over the editor's labels read by screen readers. - -Fixed Issues: - -- [#4543](https://github.com/ckeditor/ckeditor4/issues/4543): Fixed: Toolbar buttons toggle state is not correctly announced by screen readers lacking the information whether the feature is on or off. -- [#4052](https://github.com/ckeditor/ckeditor4/issues/4052): Fixed: Editor labels are read incorrectly by screen readers due to invalid editor control type for the [Iframe Editing Area](https://ckeditor.com/cke4/addon/wysiwygarea) editors. -- [#1904](https://github.com/ckeditor/ckeditor4/issues/1904): Fixed: Screen readers are not announcing the read-only editor state. -- [#4904](https://github.com/ckeditor/ckeditor4/issues/4904): Fixed: Table cell selection and navigation with the `tab` key behavior is inconsistent after adding a new row. -- [#3394](https://github.com/ckeditor/ckeditor4/issues/3394): Fixed: [Enhanced image](https://ckeditor.com/cke4/addon/image2) plugin dialog is not supporting URL with query string parameters. Thanks to [Simon Urli](https://github.com/surli)! -- [#5049](https://github.com/ckeditor/ckeditor4/issues/5049): Fixed: The editor fails in strict mode due to not following the `use strict` directives in a core editor module. -- [#5095](https://github.com/ckeditor/ckeditor4/issues/5095): Fixed: The [clipboard](https://ckeditor.com/cke4/addon/clipboard) plugin shows notification about unsupported file format when the file type is different than `jpg`, `gif`, `png`, not respecting [supported types](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_fileTools_uploadWidgetDefinition.html#property-supportedTypes) by the [Upload Widget](https://ckeditor.com/cke4/addon/uploadwidget) plugin. -- [#4855](https://github.com/ckeditor/ckeditor4/issues/4855): [iOS] Fixed: Focusing toolbar buttons with an enabled VoiceOver screen reader moves the browser focus into an editable area and interrupts button functionality. - -API changes: - -- [#4641](https://github.com/ckeditor/ckeditor4/issues/4641): The [`CKEDITOR.replace`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-replace), [`CKEDITOR.inline`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-inline), [`CKEDITOR.appendTo`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-appendTo) functions are now returning a handle function allowing to cancel the [Delayed Editor Creation](https://ckeditor.com/docs/ckeditor4/latest/features/delayed_creation.html) feature. -- [#5095](https://github.com/ckeditor/ckeditor4/issues/5095): Added the [CKEDITOR.plugins.clipboard.addFileMatcher](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_clipboard.html#method-addFileMatcher) function allowing to define file formats supported by the [clipboard](https://ckeditor.com/cke4/addon/clipboard) plugin. Trying to paste unsupported files will result in a notification that a file cannot be dropped or pasted into the editor. -- [#2445](https://github.com/ckeditor/ckeditor4/issues/2445): Added [`config.applicationTitle`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-applicationTitle) alongside [`CKEDITOR.editor#applicationTitle`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#property-applicationTitle) to allow customizing editor's application region label. - -## CKEditor 4.18.0 - -**Security Updates:** - -- Fixed an XSS vulnerability in the core module reported by GitHub Security Lab team member [Kevin Backhouse](https://github.com/kevinbackhouse). - - Issue summary: The vulnerability allowed to inject malformed HTML bypassing content sanitization, which could result in executing a JavaScript code. See [CVE-2022-24728](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-4fc4-4p5g-6w89) for more details. - -- Fixed a Regular expression Denial of Service (ReDoS) vulnerability in dialog plugin discovered by the CKEditor 4 team during our regular security audit. - - Issue summary: The vulnerability allowed to abuse a dialog input validator regular expression, which could cause a significant performance drop resulting in a browser tab freeze. See [CVE-2022-24729](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-f6rf-9m92-x2hh) for more details. - -You can read more details in the relevant security advisory and [contact us](security@cksource.com) if you have more questions. - -**An upgrade is highly recommended!** - -**Highlights:** - -[Web Spell Checker](https://webspellchecker.com/) ended support for WebSpellChecker Dialog on December 31st, 2021. This means the plugin is not supported any longer. Therefore, we decided to deprecate and remove the WebSpellChecker Dialog plugin from CKEditor 4 presets. - -We strongly encourage everyone to choose one of the other available spellchecking solutions - [Spell Check As You Type (SCAYT)](https://ckeditor.com/cke4/addon/scayt) or [WProofreader](https://ckeditor.com/cke4/addon/wproofreader). - -Fixed issues: - -- [#5097](https://github.com/ckeditor/ckeditor4/issues/5097): [Chrome] Fixed: Incorrect conversion of points to pixels while using [`CKEDITOR.tools.convertToPx()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools.html#method-convertToPx). -- [#5044](https://github.com/ckeditor/ckeditor4/issues/5044): Fixed: `select` elements with `multiple` attribute had incorrect styling. Thanks to [John R. D'Orazio](https://github.com/JohnRDOrazio)! - -Other changes: - -- [#5093](https://github.com/ckeditor/ckeditor4/issues/5093): Deprecated and removed WebSpellChecker Dialog from presets. -- [#5127](https://github.com/ckeditor/ckeditor4/issues/5127): Deprecated the [`CKEDITOR.rnd`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#property-rnd) property to discourage using it in a security-sensitive context. -- [#5087](https://github.com/ckeditor/ckeditor4/issues/5087): Improved the jQuery adapter by replacing a deprecated jQuery API with existing counterparts. Thanks to [Fran Boon](https://github.com/flavour)! -- [#5128](https://github.com/ckeditor/ckeditor4/issues/5128): Improved the [Emoji](https://ckeditor.com/cke4/addon/emoji) definitions encoding set by the [`config.emoji_emojiListUrl`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-emoji_emojiListUrl) configuration option. - -## CKEditor 4.17.2 - -Fixed issues: - -- [#4934](https://github.com/ckeditor/ckeditor4/issues/4934): Fixed: Active focus in dialog tabs is not visible in the High Contrast mode. -- [#547](https://github.com/ckeditor/ckeditor4/issues/547): Fixed: Dragging and dropping elements like images within a table is no longer available. -- [#4875](https://github.com/ckeditor/ckeditor4/issues/4875): Fixed: It is not possible to delete multiple selected lists. -- [#4873](https://github.com/ckeditor/ckeditor4/issues/4873): Fixed: Pasting content from MS Word and Outlook with horizontal lines prevents images from being uploaded. -- [#4952](https://github.com/ckeditor/ckeditor4/issues/4952): Fixed: Dragging and dropping images within a table cell appends additional elements. -- [#4761](https://github.com/ckeditor/ckeditor4/issues/4761): Fixed: Some CSS files are missing unique timestamp used to prevent browser to cache static resources between editor releases. -- [#4987](https://github.com/ckeditor/ckeditor4/issues/4987): Fixed: [Find/Replace](https://ckeditor.com/cke4/addon/find) is not recognizing more than one space character. -- [#5061](https://github.com/ckeditor/ckeditor4/issues/5061): Fixed: [Find/Replace](https://ckeditor.com/cke4/addon/find) plugin incorrectly handles multiple whitespace during replacing text. -- [#5004](https://github.com/ckeditor/ckeditor4/issues/5004): Fixed: `MutationObserver` used in [IFrame Editing Area](https://ckeditor.com/cke4/addon/wysiwygarea) plugin causes memory leaks. -- [#4994](https://github.com/ckeditor/ckeditor4/issues/4994): Fixed: [Easy Image](https://ckeditor.com/cke4/addon/easyimage) plugin caused content pasted from Word to turn into an image. - -API changes: - -- [#4918](https://github.com/ckeditor/ckeditor4/issues/4918): Explicitly set the [`config.useComputedState`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-useComputedState) default value to `true`. Thanks to [Shabab Karim](https://github.com/shabab477)! -- [#4761](https://github.com/ckeditor/ckeditor4/issues/4761): The [`CKEDITOR.appendTimestamp()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-appendTimestamp) function was added. -- [#4761](https://github.com/ckeditor/ckeditor4/issues/4761): [`CKEDITOR.dom.document#appendStyleSheet()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dom_document.html#method-appendStyleSheet) and [`CKEDITOR.tools.buildStyleHtml()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools.html#method-buildStyleHtml) now use the newly added [`CKEDITOR.appendTimestamp()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-appendTimestamp) function to correctly handle caching of CSS files. - -Other changes: - -- [#5014](https://github.com/ckeditor/ckeditor4/issues/5014): Fixed: Toolbar configurator fails when plugin does not define a toolbar group. Thanks to [SuperPat](https://github.com/SuperPat45)! - -## CKEditor 4.17.1 - -**Highlights:** - -Due to a regression in CKEeditor 4.17.0 version that was only revealed after the release and affected a limited area of operation, CSS assets loaded via relative links started to point into invalid location when loaded from external resources. - -We have therefore decided to immediately release CKEditor 4.17.1 that fixed this problem. If you have already upgraded to v4.17.0, make sure to upgrade to v4.17.1 to avoid this regression. - -Fixed issues: - -- [#4979](https://github.com/ckeditor/ckeditor4/issues/3757): Fixed: Added cache key in [#4761](https://github.com/ckeditor/ckeditor4/issues/4761) started to breaking relative links for external CSS resources. The fix has been reverted and will be corrected in the next editor version. - -## CKEditor 4.17 - -**Security Updates:** - -- Fixed XSS vulnerability in the core module reported by [William Bowling](https://github.com/wbowling). - - Issue summary: The vulnerability allowed to inject malformed comments HTML bypassing content sanitization, which could result in executing JavaScript code. See [CVE-2021-41165](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-7h26-63m7-qhf2) for more details. - -- Fixed XSS vulnerability in the core module reported by [Maurice Dauer](https://twitter.com/laytonctf). - - Issue summary: The vulnerability allowed to inject malformed HTML bypassing content sanitization, which could result in executing JavaScript code. See [CVE-2021-41164](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-pvmx-g8h5-cprj) for more details. - -You can read more details in the relevant security advisory and [contact us](security@cksource.com) if you have more questions. - -**An upgrade is highly recommended!** - -**Highlights:** - -Adobe [ended support of Flash Player](https://www.adobe.com/products/flashplayer/end-of-life.html) on December 31, 2020 and blocked Flash content from running in Flash Player beginning January 12, 2021. -We have decided to deprecate and remove the [Flash](https://ckeditor.com/cke4/addon/flash) plugin from CKEditor 4 to help protect users' systems and discourage using insecure software. - -New Features: - -- [#3433](https://github.com/ckeditor/ckeditor4/issues/3433): Marked required fields in dialogs with asterisk (`*`) symbol. -- [#4374](https://github.com/ckeditor/ckeditor4/issues/4374): Integrated the [Maximize](https://ckeditor.com/cke4/addon/maximize) plugin with browser's History API. -- [#4461](https://github.com/ckeditor/ckeditor4/issues/4461): Introduced the possibility to delay editor initialization while it is in a detached DOM element. -- [#4462](https://github.com/ckeditor/ckeditor4/issues/4462): Introduced support for reattaching editor container element to DOM. -- [#4612](https://github.com/ckeditor/ckeditor4/issues/4612): Allow pasting images as Base64 from [clipboard](https://ckeditor.com/cke4/addon/clipboard) in all browsers except IE. -- [#4681](https://github.com/ckeditor/ckeditor4/issues/4681): Allow drag and drop images as Base64. -- [#4750](https://github.com/ckeditor/ckeditor4/issues/4750): Added notification for pasting and dropping unsupported file types into the editor. -- [#4807](https://github.com/ckeditor/ckeditor4/issues/4807): [Chrome] Improved the performance of pasting large images. Thanks to [FlowIT-JIT](https://github.com/FlowIT-JIT)! -- [#4850](https://github.com/ckeditor/ckeditor4/issues/4850): Added support for loading [content templates](https://ckeditor.com/cke4/addon/templates) from HTML files. Thanks to [Fynn96](https://github.com/Fynn96)! -- [#4874](https://github.com/ckeditor/ckeditor4/issues/4874): Added the [`config.clipboard_handleImages`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-clipboard_handleImages) configuration option for enabling and disabling built-in support for pasting and dropping images in the [Clipboard](https://ckeditor.com/cke4/addon/clipboard) plugin. Thanks to [FlowIT-JIT](https://github.com/FlowIT-JIT)! -- [#4026](https://github.com/ckeditor/ckeditor4/issues/4026): [Preview](https://ckeditor.com/cke4/addon/preview) plugin now uses the [`editor#title`](http://localhost/ckeditor4-docs/build/docs/ckeditor4/latest/api/CKEDITOR_editor.html#property-title) property for the title of the preview window. Thanks to [Ely](https://github.com/Elyasin)! -- [#4467](https://github.com/ckeditor/ckeditor4/issues/4467): Added support for inserting content next to a block [widgets](https://ckeditor.com/cke4/addon/widget) using keyboard navigation. Thanks to [bunglegrind](https://github.com/bunglegrind)! - -Fixed Issues: - -- [#3757](https://github.com/ckeditor/ckeditor4/issues/3757): [Firefox] Fixed: images pasted from [clipboard](https://ckeditor.com/cke4/addon/clipboard) are not inserted as Base64-encoded images. -- [#3876](https://github.com/ckeditor/ckeditor4/issues/3876): Fixed: The [Print](https://ckeditor.com/cke4/addon/print) plugin incorrectly prints links and images. -- [#4444](https://github.com/ckeditor/ckeditor4/issues/4444): [Firefox] Fixed: Print preview is incorrectly loaded from CDN. -- [#4596](https://github.com/ckeditor/ckeditor4/issues/4596): Fixed: Incorrect handling of HSL/HSLA values in [`CKEDITOR.tools.color`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools_color.html). -- [#4597](https://github.com/ckeditor/ckeditor4/issues/4597): Fixed: Incorrect color conversion for HSL/HSLA values in [`CKEDITOR.tools.color`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools_color.html). -- [#4604](https://github.com/ckeditor/ckeditor4/issues/4604): Fixed: [`CKEDITOR.plugins.clipboard.dataTransfer#getTypes()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_clipboard_dataTransfer.html#method-getTypes) returns no types. -- [#4761](https://github.com/ckeditor/ckeditor4/issues/4761): Fixed: Not all resources loaded by the editor respect the cache key. -- [#4783](https://github.com/ckeditor/ckeditor4/issues/4783): Fixed: The [Accessibility Help](https://ckeditor.com/cke4/addon/a11yhelp) dialog does not contain info about focus being moved back to the editing area upon activating a toolbar button. -- [#4790](https://github.com/ckeditor/ckeditor4/issues/4790): Fixed: Printing page is invoked before the printed page is fully loaded. -- [#4874](https://github.com/ckeditor/ckeditor4/issues/4874): Fixed: Built-in support for pasting and dropping images in the [Clipboard](https://ckeditor.com/cke4/addon/clipboard) plugin restricts third party plugins from handling image pasting. Thanks to [FlowIT-JIT](https://github.com/FlowIT-JIT)! -- [#4888](https://github.com/ckeditor/ckeditor4/issues/4888): Fixed: The [`CKEDITOR.dialog#setState()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog.html#method-setState) method throws error when there is no "OK" button in the dialog. -- [#4858](https://github.com/ckeditor/ckeditor4/issues/4858): Fixed: The [Autolink](https://ckeditor.com/cke4/addon/autolink) plugin incorrectly escapes the `&` characters when pasting links into the editor. -- [#4892](https://github.com/ckeditor/ckeditor4/issues/4892): Fixed: Focus of buttons in dialogs is not visible enough in High Contrast mode. -- [#3858](https://github.com/ckeditor/ckeditor4/issues/3858): Fixed: Pasting content in `ENTER_BR` [enter mode](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-enterMode) crashes the editor. -- [#4891](https://github.com/ckeditor/ckeditor4/issues/4891): Fixed: The [Autogrow](https://ckeditor.com/cke4/addon/autogrow) plugin applies fixed width to the editor. - -API Changes: - -- [#4462](https://github.com/ckeditor/ckeditor4/issues/4462): [`CKEDITOR.editor#getSelection()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-getSelection) now returns `null` if the editor is in recreating state. -- [#4583](https://github.com/ckeditor/ckeditor4/issues/4583): Added support for new, comma-less color syntax to [`CKEDITOR.tools.color`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools_color.html). -- [#4604](https://github.com/ckeditor/ckeditor4/issues/4604): Added the [`CKEDITOR.plugins.clipboard.dataTransfer#isFileTransfer()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_clipboard_dataTransfer.html#method-isFileTransfer) method. -- [#4790](https://github.com/ckeditor/ckeditor4/issues/4790): Added `callback` parameter to [`CKEDITOR.plugins.preview#createPreview()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_preview.html#method-createPreview) method. - -Other Changes: - -- [#4866](https://github.com/ckeditor/ckeditor4/issues/#4866): The [Flash](https://ckeditor.com/cke4/addon/flash) plugin is now deprecated and has been removed from CKEditor 4. -- [#4901](https://github.com/ckeditor/ckeditor4/issues/4901): Redesigned buttons placement in the [Content templates](https://ckeditor.com/cke4/addon/templates) dialog to make it more UX friendly. Thanks to [Fynn96](https://github.com/Fynn96)! - -## CKEditor 4.16.2 - -**Security Updates:** - -- Fixed XSS vulnerability in the [Clipboard](https://ckeditor.com/cke4/addon/clipboard) plugin reported by [Anton Subbotin](https://github.com/skavans). - - Issue summary: The vulnerability allowed to abuse paste functionality using malformed HTML, which could result in injecting arbitrary HTML into the editor. See [CVE-2021-32809](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-7889-rm5j-hpgg) for more details. - -- Fixed XSS vulnerability in the [Widget](https://ckeditor.com/cke4/addon/widget) plugin reported by [Anton Subbotin](https://github.com/skavans). - - Issue summary: The vulnerability allowed to abuse undo functionality using malformed [Widget](https://ckeditor.com/cke4/addon/widget) HTML, which could result in executing JavaScript code. See [CVE-2021-32808](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-6226-h7ff-ch6c) for more details. - -- Fixed XSS vulnerability in the [Fake Objects](https://ckeditor.com/cke4/addon/fakeobjects) plugin reported by [Mika Kulmala](https://github.com/kulmik). - - Issue summary: The vulnerability allowed to inject malformed [Fake Objects](https://ckeditor.com/cke4/addon/fakeobjects) HTML, which could result in executing JavaScript code. See [CVE-2021-37695](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-m94c-37g6-cjhc) for more details. - -You can read more details in the relevant security advisory and [contact us](security@cksource.com) if you have more questions. - -**An upgrade is highly recommended!** - -Fixed Issues: - -- [#4777](https://github.com/ckeditor/ckeditor4/issues/4777): Fixed: HTML comments in widgets not processed correctly. -- [#4733](https://github.com/ckeditor/ckeditor4/pull/4733): Fixed: [Link](https://ckeditor.com/cke4/addon/link) prevent duplicate anchors in text with styles. - - [#4728](https://github.com/ckeditor/ckeditor4/issues/4728): Fixed: Multiple anchors in one line and multi-line with text style. - - [#3863](https://github.com/ckeditor/ckeditor4/issues/3863): Fixed: Multiple anchors in single word with text style. -- [#3819](https://github.com/ckeditor/ckeditor4/issues/3819): [Chrome] Fixed: After removing one of the two consecutive spaces, the ` ` character appears in the editor instead of a space. -- [#4666](https://github.com/ckeditor/ckeditor4/pull/4666): [IE] Introduce CSS.escape polyfill. Thanks to [limingli0707](https://github.com/limingli0707)! - - [#681](https://github.com/ckeditor/ckeditor4/issues/681): Fixed: Table elements (td, tr, th, ..) with an id that starts with dot (.) causes javascript runtime err. - - [#641](https://github.com/ckeditor/ckeditor4/issues/641): Fixed: UploadImage Plugin Widgets not working in IE, Opera, Safari, PhantomJS. -- [#3638](https://github.com/ckeditor/ckeditor4/issues/3638): Fixed: Opening the same dialog twice causes it to become hidden under the dialog's page cover. -- [#4247](https://github.com/ckeditor/ckeditor4/issues/4247): Fixed: [Color Button](https://ckeditor.com/cke4/addon/colorbutton)'s incorrect rendering on the first opening. -- [#4555](https://github.com/ckeditor/ckeditor4/issues/4555): Fixed: [Font](https://ckeditor.com/cke4/addon/font) styles with attributes are not applied correctly when used multiple times over the same selection. -- [#4782](https://github.com/ckeditor/ckeditor4/issues/4782): [Firefox] Fixed: `TypeError` is thrown when switching to Source View and back while [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) plugin is enabled. - -## CKEditor 4.16.1 - -Fixed Issues: - -- [#4617](https://github.com/ckeditor/ckeditor4/issues/4617): Fixed: [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) is not accessible in inline editors. -- [#4493](https://github.com/ckeditor/ckeditor4/issues/4493): Fixed: The [drop-down](https://ckeditor.com/cke4/addon/richcombo) label does not reflect the current value of the drop-down. -- [#1572](https://github.com/ckeditor/ckeditor4/issues/1572): Fixed: A paragraph before or after a [widget](https://ckeditor.com/cke4/addon/widget) cannot be removed. Thanks to [bunglegrind](https://github.com/bunglegrind)! -- [#4301](https://github.com/ckeditor/ckeditor4/issues/4301): Fixed: Pasted content is overwritten when pasted in an initially empty editor with the [`div` Enter mode](https://ckeditor.com/docs/ckeditor4/latest/features/enterkey.html). -- [#4351](https://github.com/ckeditor/ckeditor4/issues/4351): Fixed: Incorrect values for RGBA/HSLA colors in [Color Dialog](https://ckeditor.com/cke4/addon/colordialog). -- [#4509](https://github.com/ckeditor/ckeditor4/issues/4509): Fixed: Incorrect handling of drag & drop inside [widgets](https://ckeditor.com/cke4/addon/widget) and nested editables. -- [#4611](https://github.com/ckeditor/ckeditor4/issues/4611): [Android, iOS] Fixed: Incorrect hover styles for buttons in the toolbar on mobile devices. -- [#4652](https://github.com/ckeditor/ckeditor4/issues/4652): Fixed: [Event data](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_eventInfo.html) set to `false` is treated as an event cancellation. -- [#4659](https://github.com/ckeditor/ckeditor4/issues/4659): Fixed: [`CKEDITOR.htmlParser`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_htmlParser.html) does not treat `--!>` as a comment end tag correctly. - -## CKEditor 4.16 - -**Security Updates:** - -- Fixed ReDoS vulnerability in the [Autolink](https://ckeditor.com/cke4/addon/autolink) plugin. - - Issue summary: It was possible to execute a ReDoS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted URL-like text into the editor and press Enter or Space. - -- Fixed ReDoS vulnerability in the [Advanced Tab for Dialogs](https://ckeditor.com/cke4/addon/dialogadvtab) plugin. - - Issue summary: It was possible to execute a ReDoS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted text into the Styles dialog. - -**An upgrade is highly recommended!** - -New Features: - -- [#2800](https://github.com/ckeditor/ckeditor4/issues/2800): Unsupported image formats are now gracefully handled by the [Paste from Word](https://ckeditor.com/cke4/addon/pastefromword) plugin on paste, additionally showing descriptive error messages. -- [#2800](https://github.com/ckeditor/ckeditor4/issues/2800): Unsupported image formats are now gracefully handled by the [Paste from LibreOffice](https://ckeditor.com/cke4/addon/pastefromlibreoffice) plugin on paste, additionally showing descriptive error messages. -- [#3582](https://github.com/ckeditor/ckeditor4/issues/3582): Introduced smart positioning of the [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) panel used by the [Mentions](https://ckeditor.com/cke4/addon/mentions) and [Emoji](https://ckeditor.com/cke4/addon/emoji) plugins. The panel will now be additionally positioned related to the browser viewport to be always fully visible. -- [#4388](https://github.com/ckeditor/ckeditor4/issues/4388): Added the option to remove an iframe created with the [IFrame Dialog](https://ckeditor.com/cke4/addon/iframe) plugin from the sequential keyboard navigation using the `tabindex` attribute. Thanks to [Timo Kirkkala](https://github.com/kirkkala)! - -Fixed Issues: - -- [#1134](https://github.com/ckeditor/ckeditor4/issues/1134): [Safari] Fixed: [Paste from Word](https://ckeditor.com/cke4/addon/pastefromword) does not embed images. -- [#2800](https://github.com/ckeditor/ckeditor4/issues/2800): Fixed: No images are imported from Microsoft Word when the content is pasted via the [Paste from Word](https://ckeditor.com/cke4/addon/pastefromword) plugin if there is at least one image of unsupported format. -- [#4379](https://github.com/ckeditor/ckeditor4/issues/4379): [Edge] Fixed: Incorrect detection of the [high contrast mode](https://ckeditor.com/docs/ckeditor4/latest/guide/dev_a11y.html#high-contrast-mode). -- [#4422](https://github.com/ckeditor/ckeditor4/issues/4422): Fixed: Missing space between the button name and the keyboard shortcut inside the button label in the [high contrast mode](https://ckeditor.com/docs/ckeditor4/latest/guide/dev_a11y.html#high-contrast-mode). -- [#2208](https://github.com/ckeditor/ckeditor4/issues/2208): [IE] Fixed: The [Autolink](https://ckeditor.com/cke4/addon/autolink) plugin duplicates the native browser implementation. -- [#1824](https://github.com/ckeditor/ckeditor4/issues/1824): Fixed: The [Autolink](https://ckeditor.com/cke4/addon/autolink) plugin should require the [Link](https://ckeditor.com/cke4/addon/link) plugin. -- [#4253](https://github.com/ckeditor/ckeditor4/issues/4253): Fixed: The [Editor Placeholder](https://ckeditor.com/cke4/addon/editorplaceholder) plugin throws an error during the editor initialization with [`config.fullPage`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-fullPage) enabled when there is no `` tag in the editor content. -- [#4372](https://github.com/ckeditor/ckeditor4/issues/4372): Fixed: The [Autogrow](https://ckeditor.com/cke4/addon/autogrow) plugin changes the editor's width when used with an absolute [`config.width`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-width) value. - -API Changes: - -- [#4358](https://github.com/ckeditor/ckeditor4/issues/4358): Introduced the [`CKEDITOR.tools.color`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools_color.html) class which adds colors validation and methods for converting colors between various formats: named colors, HEX, RGB, RGBA, HSL and HSLA. -- [#3782](https://github.com/ckeditor/ckeditor4/issues/3782): Moved the [`CKEDITOR.plugins.pastetools.filters.word.images`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_pastetools_filters_word_images.html) filters to the [`CKEDITOR.plugins.pastetools.filters.image`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_pastetools_filters_image.html) namespace. -- [#4297](https://github.com/ckeditor/ckeditor4/issues/4297): All [`CKEDITOR.plugins.pastetools.filters`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_pastetools_filters.html) are now available under the [`CKEDITOR.pasteTools`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#property-pasteTools) alias. -- [#4394](https://github.com/ckeditor/ckeditor4/issues/4394): Introduced [`CKEDITOR.ajax`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_ajax.html) specialized loading methods for loading binary ([`CKEDITOR.ajax.loadBinary()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_ajax.html#method-loadBinary)) and text ([`CKEDITOR.ajax.loadText()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_ajax.html#method-loadText)) data. - -Other Changes: - -- The [WebSpellChecker](https://ckeditor.com/cke4/addon/wsc) (WSC) plugin is now disabled by default in [Standard and Full presets](https://ckeditor.com/cke4/presets). It can be enabled via [`extraPlugins`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-extraPlugins) configuration option. - -## CKEditor 4.15.1 - -**Security Updates:** - -- Fixed XSS vulnerability in the [Color History feature](https://ckeditor.com/docs/ckeditor4/latest/features/colorbutton.html#color-history) reported by [Mark Wade](https://github.com/mark-wade). - - Issue summary: It was possible to execute an XSS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted HTML code into the [Color Button](https://ckeditor.com/cke4/addon/colorbutton) dialog. - -**An upgrade is highly recommended!** - -Fixed Issues: - -- [#4293](https://github.com/ckeditor/ckeditor4/issues/4293): Fixed: The [`CKEDITOR.inlineAll()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-inlineAll) method tries to initialize inline editor also on elements with an editor already attached to them. -- [#3961](https://github.com/ckeditor/ckeditor4/issues/3961): Fixed: The [Table Resize](https://ckeditor.com/cke4/addon/tableresize) plugin prevents editing of merged cells. -- [#3649](https://github.com/ckeditor/ckeditor4/issues/3649): Fixed: Applying a [block format](https://ckeditor.com/docs/ckeditor4/latest/features/format.html) should remove existing block styles. -- [#4282](https://github.com/ckeditor/ckeditor4/issues/4282): Fixed: The [script loader](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_scriptLoader.html) does not execute callback for scripts already loaded when called for the second time. Thanks to [Alexander Korotkevich](https://github.com/aldoom)! -- [#4273](https://github.com/ckeditor/ckeditor4/issues/4273): Fixed: A memory leak in the [`CKEDITOR.domReady()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-domReady) method connected with not removing `load` event listeners. Thanks to [rohit1](https://github.com/rohit1)! -- [#1330](https://github.com/ckeditor/ckeditor4/issues/1330): Fixed: Incomplete CSS margin parsing if an `auto` or `0` value is used. -- [#4286](https://github.com/ckeditor/ckeditor4/issues/4286): Fixed: The [Auto Grow](https://ckeditor.com/cke4/addon/autogrow) plugin causes the editor width to be set to `0` on editor resize. -- [#848](https://github.com/ckeditor/ckeditor4/issues/848): Fixed: Arabic text not being "bound" correctly when pasting. Thanks to [Thomas Hunkapiller](https://github.com/devoidfury) and [J. Ivan Duarte Rodríguez](https://github.com/jidrone-mbm)! - -API Changes: - -- [#3649](https://github.com/ckeditor/ckeditor4/issues/3649): Added a new [`stylesRemove`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#event-stylesRemove) editor event. - -Other Changes: - -- [#4262](https://github.com/ckeditor/ckeditor4/issues/4262): Removed the global reference to the `stylesLoaded` variable. Thanks to [Levi Carter](https://github.com/swiftMessenger)! -- Updated the [Export to PDF](https://ckeditor.com/cke4/addon/exportpdf) plugin to `1.0.1` version: - - Improved external CSS support for [classic editor](https://ckeditor.com/docs/ckeditor4/latest/examples/classic.html) by handling exceptions and displaying convenient [error messages](https://ckeditor.com/docs/ckeditor4/latest/guide/dev_errors.html#exportpdf-stylesheets-incaccessible). - -## CKEditor 4.15 - -New features: - -- [#3940](https://github.com/ckeditor/ckeditor4/issues/3940): Introduced the `colorName` property for customizing foreground and background styles in the [Color Button](https://ckeditor.com/cke4/addon/colorbutton) plugin via the [`config.colorButton_foreStyle`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-colorButton_foreStyle) and [`config.colorButton_backStyle`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-colorButton_backStyle) configuration options. -- [#3793](https://github.com/ckeditor/ckeditor4/issues/3793): Introduced the [Editor Placeholder](https://ckeditor.com/cke4/addon/editorplaceholder) plugin. -- [#1795](https://github.com/ckeditor/ckeditor4/issues/1795): The colors picked from the [Color Dialog](https://ckeditor.com/cke4/addon/colordialog) are now stored in the [Color Button](https://ckeditor.com/cke4/addon/colorbutton) palette and can be reused easily. -- [#3783](https://github.com/ckeditor/ckeditor4/issues/3783): The colors used in the document are now displayed as a part of the [Color Button](https://ckeditor.com/cke4/addon/colorbutton) palette. - -Fixed Issues: - -- [#4060](https://github.com/ckeditor/ckeditor4/issues/4060): Fixed: The content inside a [widget](https://ckeditor.com/cke4/addon/widget) nested editable is escaped twice. -- [#4183](https://github.com/ckeditor/ckeditor4/issues/4183): [Safari] Fixed: Incorrect image dimensions when using the [Easy Image](https://ckeditor.com/cke4/addon/easyimage) plugin alongside the [IFrame Editing Area](https://ckeditor.com/cke4/addon/wysiwygarea) plugin. -- [#3693](https://github.com/ckeditor/ckeditor4/issues/3693): Fixed: Incorrect default values for several [Color Button](https://ckeditor.com/cke4/addon/colorbutton) configuration variables in the API documentation. -- [#3795](https://github.com/ckeditor/ckeditor4/issues/3795): Fixed: Setting the [`config.dataIndentationChars`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-dataIndentationChars) configuration option to an empty string is ignored and replaced by a tab (`\t`) character. Thanks to [Thomas Grinderslev](https://github.com/Znegl)! -- [#4107](https://github.com/ckeditor/ckeditor4/issues/4107): Fixed: Multiple [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) instances cause keyboard navigation issues. -- [#4041](https://github.com/ckeditor/ckeditor4/issues/4041): Fixed: The[`selection.scrollIntoView`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dom_selection.html#method-scrollIntoView) method throws an error when the editor selection is not set. -- [#3361](https://github.com/ckeditor/ckeditor4/issues/3361): Fixed: Loading multiple [custom editor configurations](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-customConfig) is prone to a race condition between these. -- [#4007](https://github.com/ckeditor/ckeditor4/issues/4007): Fixed: Screen readers do not announce the [Rich Combo](https://ckeditor.com/cke4/addon/richcombo) plugin is collapsed or expanded. -- [#4141](https://github.com/ckeditor/ckeditor4/issues/4141): Fixed: The styles are incorrectly applied when there is a `` DOM element. - -Other Changes: - -- [#13859](https://dev.ckeditor.com/ticket/13859): Test cases created with `bender.tools.createTestsForEditors` will also receive editor bot as a second parameter. - -## CKEditor 4.5.4 - -New Features: - -- [#13632](https://dev.ckeditor.com/ticket/13632): Introduce error logging mechanism. -- [#13730](https://dev.ckeditor.com/ticket/13730): Switch to the new error logging mechanism. - -Fixed Issues: - -- [#9856](https://dev.ckeditor.com/ticket/9856): Fixed: Cannot use the native context menu together with the [Div Editing Area](https://ckeditor.com/cke4/addon/divarea) plugin. Thanks to [Mark Wade](https://github.com/mark-wade)! -- [#12733](https://dev.ckeditor.com/ticket/12733): [IE9+] Fixed: Radio button `onChange` does not work. Thanks to [Iliya Kostadinov](https://github.com/iliyakostadinov)! -- [#13142](https://dev.ckeditor.com/ticket/13142): [Edge] Fixed: _Ctrl+A_ and then _Backspace_ result in an empty `
    ` element. -- [#13599](https://dev.ckeditor.com/ticket/13599): Fixed: Cross-editor drag and drop of an inline widget results in error/artifacts. -- [#13640](https://dev.ckeditor.com/ticket/13640): [IE] Fixed: Dropping a widget outside the `` element is not handled correctly. -- [#13533](https://dev.ckeditor.com/ticket/13533): Fixed: No progress during upload. -- [#13680](https://dev.ckeditor.com/ticket/13680): Fixed: The parser should allow the `` element to be a child of the `` element. -- [#11724](https://dev.ckeditor.com/ticket/11724): [Touch devices] Fixed: Drop-downs often hide right after opening them. -- [#13690](https://dev.ckeditor.com/ticket/13690): Fixed: Copying content from IE to Chrome adds an extra paragraph. -- [#13284](https://dev.ckeditor.com/ticket/13284): Fixed: Cannot drag and drop a widget if the text caret is placed just after the widget instance. -- [#13516](https://dev.ckeditor.com/ticket/13516): Fixed: CKEditor removes empty HTML5 anchors without the `name` attribute. -- [#13765](https://dev.ckeditor.com/ticket/13765): [Safari 9] Fixed: Problems with rendering samples. - -Other Changes: - -- [#11725](https://dev.ckeditor.com/ticket/11725): Marked [`CKEDITOR.env.mobile`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_env.html#property-mobile) as deprecated. The reason is that it is no longer clear what "mobile" means. -- [#13737](https://dev.ckeditor.com/ticket/13737): Upgraded [Bender.js](https://github.com/benderjs/benderjs) to 0.4.1. - -## CKEditor 4.5.3 - -New Features: - -- [#13501](https://dev.ckeditor.com/ticket/13501): Added the [`config.fileTools_defaultFileName`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-fileTools_defaultFileName) option to allow setting a default file name for paste uploads. -- [#13603](https://dev.ckeditor.com/ticket/13603): Added support for uploading dropped BMP images. - -Fixed Issues: - -- [#13590](https://dev.ckeditor.com/ticket/13590): Fixed: Various issues related to the [Paste from Word](https://ckeditor.com/cke4/addon/pastefromword) feature. Fixes also: - - [#11215](https://dev.ckeditor.com/ticket/11215), - - [#8780](https://dev.ckeditor.com/ticket/8780), - - [#12762](https://dev.ckeditor.com/ticket/12762). -- [#13386](https://dev.ckeditor.com/ticket/13386): [Edge] Fixed: Issues with selecting and editing images. -- [#13568](https://dev.ckeditor.com/ticket/13568): Fixed: The [`editor.getSelectedHtml()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-getSelectedHtml) method returns invalid results for entire content selection. -- [#13453](https://dev.ckeditor.com/ticket/13453): Fixed: Drag&drop of entire editor content throws an error. -- [#13465](https://dev.ckeditor.com/ticket/13465): Fixed: Error is thrown and the widget is lost on drag&drop if it is the only content of the editor. -- [#13414](https://dev.ckeditor.com/ticket/13414): Fixed: Content auto paragraphing in a nested editable despite editor configuration. -- [#13429](https://dev.ckeditor.com/ticket/13429): Fixed: Incorrect selection after content insertion by the [Auto Embed](https://ckeditor.com/cke4/addon/autoembed) plugin. -- [#13388](https://dev.ckeditor.com/ticket/13388): Fixed: [Table Resize](https://ckeditor.com/cke4/addon/tableresize) integration with [Undo](https://ckeditor.com/cke4/addon/undo) is broken. - -Other Changes: - -- [#13637](https://dev.ckeditor.com/ticket/13637): Several icons were refactored. -- Updated [Bender.js](https://github.com/benderjs/benderjs) to 0.3.0 and introduced the ability to run tests via HTTPs ([#13265](https://dev.ckeditor.com/ticket/13265)). - -## CKEditor 4.5.2 - -Fixed Issues: - -- [#13609](https://dev.ckeditor.com/ticket/13609): [Edge] Fixed: The browser crashes when switching to the source mode. Thanks to [Andrew Williams and Mark Smeed](http://webxsolution.com/)! -- [PR#201](https://github.com/ckeditor/ckeditor4/pull/201): Fixed: Buttons in the toolbar configurator cause form submission. Thanks to [colemanw](https://github.com/colemanw)! -- [#13422](https://dev.ckeditor.com/ticket/13422): Fixed: A monospaced font should be used in the ` -`; - num++; - }); - exportPopup(genTextArea); +` + num++ + }) + exportPopup(genTextArea) } - }); - }; + }) + } /** * @name veApp.AppUtilsService#printModal @@ -167,30 +167,30 @@ Save CSV
    isDoc: boolean, mode: number ): VePromise { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() const settings: VeModalSettings = { component: 'printConfirmModal', resolve: { print: () => { - return printElement; + return printElement }, refOb: () => { - return refOb; + return refOb }, viewOrDocOb: () => { - return viewOrDocOb; + return viewOrDocOb }, isDoc: () => { - return isDoc; + return isDoc }, mode: () => { - return mode; + return mode }, }, backdrop: 'static', keyboard: false, - }; - const modalInstance = this.$uibModal.open(settings); + } + const modalInstance = this.$uibModal.open(settings) /* choice: ['ok', $scope.model.genTotf, $scope.model.htmlTotf, $scope.model.landscape, $scope.meta] [0] 'ok' - modal button to confirm print/export @@ -209,20 +209,20 @@ Save CSV isDoc, choice.model.genTotf, choice.model.htmlTotf - ); + ) const css = choice.customization ? choice.customCSS - : this.utilsSvc.getPrintCss(choice.model.htmlTotf, choice.model.landscape, choice.meta); - result.toe = choice[2] ? '' : result.toe; + : this.utilsSvc.getPrintCss(choice.model.htmlTotf, choice.model.landscape, choice.meta) + result.toe = choice[2] ? '' : result.toe if (mode === 1) { const popupWin = this.$window.open( 'about:blank', '_blank', 'width=800,height=600,scrollbars=1,status=1,toolbar=1,menubar=1' - ); + ) if (popupWin) { - const popup: Window = popupWin; - popup.document.open(); + const popup: Window = popupWin + popup.document.open() popup.document.write(` @@ -238,33 +238,33 @@ Save CSV ${result.contents} -`); - popup.document.close(); +`) + popup.document.close() void this.$timeout( () => { - popup.print(); + popup.print() }, 1000, false - ); + ) } else { - this.growl.error('Popup Window Failed to open. Allow popups and try again'); + this.growl.error('Popup Window Failed to open. Allow popups and try again') } } else { - result.tof = choice[1] ? result.tof + result.toe : ''; - result.tot = choice[1] ? result.tot : ''; + result.tof = choice[1] ? result.tof + result.toe : '' + result.tot = choice[1] ? result.tot : '' const htmlArr = [ '' + viewOrDocOb.name + '', result.cover, - ]; - if (result.toc != '') htmlArr.push(result.toc); - if (result.tot != '') htmlArr.push(result.tot); - if (result.tof != '') htmlArr.push(result.tof); - htmlArr.push(result.contents, ''); - const htmlString = htmlArr.join(''); - this.growl.info('Generating, please wait...', { ttl: -1 }); + ] + if (result.toc != '') htmlArr.push(result.toc) + if (result.tot != '') htmlArr.push(result.tot) + if (result.tof != '') htmlArr.push(result.tof) + htmlArr.push(result.contents, '') + const htmlString = htmlArr.join('') + this.growl.info('Generating, please wait...', { ttl: -1 }) this.utilsSvc .exportHtmlAs(mode, { htmlString: htmlString, @@ -275,24 +275,24 @@ Save CSV }) .then( () => { - this.growl.success('File Downloaded', { ttl: -1 }); - deferred.resolve(); + this.growl.success('File Downloaded', { ttl: -1 }) + deferred.resolve() }, (reason) => { - this.growl.error('Generation Failed'); - deferred.reject(reason); + this.growl.error('Generation Failed') + deferred.reject(reason) } - ); + ) } } else { void this.$state.go('main.project.ref.view.present.document', { display: 'document', keywords: undefined, - }); - deferred.reject({ message: 'User Cancelled' }); + }) + deferred.reject({ message: 'User Cancelled' }) } - }); - return deferred.promise; + }) + return deferred.promise } /** @@ -325,25 +325,25 @@ Save CSV genTotf: boolean, htmlTotf: boolean ): DocumentStructure => { - let printContents = ''; - let printElementCopy = angular.element('#print-div'); + let printContents = '' + let printElementCopy = angular.element('#print-div') // Conversion of canvas to its dataUrl must be done before "clone", because "clone" doesn't preserve // canvas' content - const mapping = this._storeTomsawyerDiagramAsImg(printElementCopy); - printElementCopy = printElementCopy.clone(); - this._replaceMmsTsDiagramWithImg(printElementCopy, mapping); + const mapping = this._storeTomsawyerDiagramAsImg(printElementCopy) + printElementCopy = printElementCopy.clone() + this._replaceMmsTsDiagramWithImg(printElementCopy, mapping) - const hostname = this.$location.host(); - const port = this.$location.port(); - const protocol = this.$location.protocol(); - const absurl = this.$location.absUrl(); - const prefix = protocol + ':// hostname' + (port == 80 || port == 443 ? '' : `:${port}`); - const mmsIndex = absurl.indexOf('index.html'); - let toc = this.utilsSvc.makeHtmlTOC(this.treeSvc.getTreeData()[0]); + const hostname = this.$location.host() + const port = this.$location.port() + const protocol = this.$location.protocol() + const absurl = this.$location.absUrl() + const prefix = protocol + ':// hostname' + (port == 80 || port == 443 ? '' : `:${port}`) + const mmsIndex = absurl.indexOf('index.html') + let toc = this.utilsSvc.makeHtmlTOC(this.treeSvc.getTreeData()[0]) // Conver to proper links for word/pdf - this.utilsSvc.convertViewLinks(printElementCopy); + this.utilsSvc.convertViewLinks(printElementCopy) // Get correct table/image numbering based on doc hierarchy const tableAndFigTOC = this.utilsSvc.makeTablesAndFiguresTOC( @@ -351,79 +351,79 @@ Save CSV printElementCopy, false, htmlTotf - ); - let tof = tableAndFigTOC.figures; - let tot = tableAndFigTOC.tables; - let toe = tableAndFigTOC.equations; + ) + let tof = tableAndFigTOC.figures + let tot = tableAndFigTOC.tables + let toe = tableAndFigTOC.equations // Customize TOC based on user choice if (!isDoc) { - toc = tof = tot = toe = ''; + toc = tof = tot = toe = '' } if (!genTotf) { - tof = tot = toe = ''; + tof = tot = toe = '' } angular .element(printElementCopy) .find('a') .attr('href', (index, old) => { - if (!old) return old; - if (old.indexOf('/') === 0) return prefix + old; - if (old.indexOf('../../') === 0) return prefix + old.substring(5); - if (old.indexOf('../') === 0) return prefix + '/alfresco' + old.substring(2); - if (old.indexOf('mms.html') === 0) return absurl.substring(0, mmsIndex) + old; - return old; - }); + if (!old) return old + if (old.indexOf('/') === 0) return prefix + old + if (old.indexOf('../../') === 0) return prefix + old.substring(5) + if (old.indexOf('../') === 0) return prefix + '/alfresco' + old.substring(2) + if (old.indexOf('mms.html') === 0) return absurl.substring(0, mmsIndex) + old + return old + }) // Remove comments, table features, and all elements with classes: ve-error, no-print, ng-hide - printElementCopy.find('transclude-com').remove(); - printElementCopy.find('style').remove(); //prevent user inserted styles from interfering - printElementCopy.find('div.tableSearch').remove(); + printElementCopy.find('transclude-com').remove() + printElementCopy.find('style').remove() //prevent user inserted styles from interfering + printElementCopy.find('div.tableSearch').remove() //printElementCopy.find('.ve-error').html('error'); - printElementCopy.find('.no-print').remove(); - printElementCopy.find('.ng-hide').remove(); + printElementCopy.find('.no-print').remove() + printElementCopy.find('.ng-hide').remove() // word doesn't support svg only png. if (mode === 2) { - printElementCopy.find('.mms-svg').remove(); + printElementCopy.find('.mms-svg').remove() } else { - printElementCopy.find('.mms-png').remove(); + printElementCopy.find('.mms-png').remove() } // Remove all empty paragraphs - printElementCopy.find('p:empty').remove(); + printElementCopy.find('p:empty').remove() printElementCopy.find('p').each((index, element) => { - const $this = $(element); + const $this = $(element) if ($this.html().replace(/\s| /g, '').length === 0) { - $this.remove(); + $this.remove() } - }); - printElementCopy.find('[width]').not('img').not('.ve-fixed-width').removeAttr('width'); + }) + printElementCopy.find('[width]').not('img').not('.ve-fixed-width').removeAttr('width') printElementCopy .find('[style]') .not('hr') .each((index, element) => { - element.style.removeProperty('font-size'); - element.style.removeProperty('width'); - element.style.removeProperty('min-width'); - element.style.removeProperty('height'); + element.style.removeProperty('font-size') + element.style.removeProperty('width') + element.style.removeProperty('min-width') + element.style.removeProperty('height') //remove frozen headers and column - element.style.removeProperty('transform'); - element.style.removeProperty('will-change'); - }); - printElementCopy.find('.math').remove(); //this won't work in chrome for popups since chrome can't display mathml - printElementCopy.find('script').remove(); + element.style.removeProperty('transform') + element.style.removeProperty('will-change') + }) + printElementCopy.find('.math').remove() //this won't work in chrome for popups since chrome can't display mathml + printElementCopy.find('script').remove() //printElementCopy.find('.MJX_Assistive_MathML').remove(); //pdf generation need mathml version // Get doc cover page by doc ID - let coverHtml = ''; + let coverHtml = '' if (isDoc) { - const cover = printElementCopy.find("view[mms-element-id='" + viewOrDocOb.id + "']"); - cover.remove(); + const cover = printElementCopy.find("view[mms-element-id='" + viewOrDocOb.id + "']") + cover.remove() // Add class to style cover page - cover.addClass('ve-cover-page'); - coverHtml = cover[0].outerHTML; + cover.addClass('ve-cover-page') + coverHtml = cover[0].outerHTML } - printContents = printElementCopy[0].outerHTML; + printContents = printElementCopy[0].outerHTML return { cover: coverHtml, @@ -432,31 +432,31 @@ Save CSV tof: tof, tot: tot, toe: toe, - }; - }; + } + } /** Store all tomsawyer diagram(canvas) as an img element **/ private _storeTomsawyerDiagramAsImg(originalDom: JQuery): JQuery[] { - const mapping: JQuery[] = []; + const mapping: JQuery[] = [] originalDom.find('mms-ts-diagram').each((index, element) => { - const tsDom = $(element); - const canvas = tsDom.find('canvas')[0]; + const tsDom = $(element) + const canvas = tsDom.find('canvas')[0] if (canvas) { - const imgElement = $(''); - imgElement.attr({ src: canvas.toDataURL(), width: '100%' }); - mapping[index] = imgElement; + const imgElement = $('') + imgElement.attr({ src: canvas.toDataURL(), width: '100%' }) + mapping[index] = imgElement } - }); - return mapping; + }) + return mapping } /** Replace all mms-ts-diagram elements with their corresponding img elements **/ private _replaceMmsTsDiagramWithImg(element: JQuery, mapping: JQuery[]): void { element.find('mms-ts-diagram').each((index) => { - const imgDom = mapping[index]; - $(this).replaceWith(imgDom); - }); + const imgDom = mapping[index] + $(this).replaceWith(imgDom) + }) } } -veApp.service('AppUtilsService', AppUtilsService); +veApp.service('AppUtilsService', AppUtilsService) diff --git a/src/ve-app/main/services/FullDocument.service.ts b/src/ve-app/main/services/FullDocument.service.ts index d1fbdecc7..b247b0f1a 100644 --- a/src/ve-app/main/services/FullDocument.service.ts +++ b/src/ve-app/main/services/FullDocument.service.ts @@ -1,19 +1,19 @@ -import angular from 'angular'; -import _ from 'lodash'; +import angular from 'angular' +import _ from 'lodash' -import { ViewData } from '@ve-utils/mms-api-client'; +import { ViewData } from '@ve-utils/mms-api-client' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { TreeBranch } from '@ve-types/tree'; +import { TreeBranch } from '@ve-types/tree' export class FullDocumentApi { - public viewsBuffer: ViewData[] = []; - public views: ViewData[] = []; + public viewsBuffer: ViewData[] = [] + public views: ViewData[] = [] - private _isLoadingRemaingViews: boolean = false; - _isFullDocFullyLoaded: boolean = false; - _loadingRemainingViewsMessage: angular.growl.IGrowlMessage; + private _isLoadingRemaingViews: boolean = false + _isFullDocFullyLoaded: boolean = false + _loadingRemainingViewsMessage: angular.growl.IGrowlMessage constructor( private $timeout: angular.ITimeoutService, @@ -23,177 +23,177 @@ export class FullDocumentApi { ) {} public handleClickOnBranch = (viewId: string, callback: () => void): boolean => { - const isViewLoadedBefore = this._loadViewsUntilViewWith(viewId); // load some views if necessary + const isViewLoadedBefore = this._loadViewsUntilViewWith(viewId) // load some views if necessary if (isViewLoadedBefore) { - callback(); + callback() } else { - const message = this.growl.info('Loading more views!', { ttl: -1 }); + const message = this.growl.info('Loading more views!', { ttl: -1 }) this._waitTillAfterDigestCycle(() => { // wait for digest to finish and for content to finish rendering - message.destroy(); - callback(); - }); + message.destroy() + callback() + }) } - return isViewLoadedBefore; - }; + return isViewLoadedBefore + } public loadRemainingViews = (callback?: () => void): void => { if (this._isFullDocFullyLoaded && callback) { - callback(); + callback() } else { - let handler: angular.IPromise; + let handler: angular.IPromise if (!this._loadingRemainingViewsMessage) { this._loadingRemainingViewsMessage = this.growl.info('Loading more views!', { ttl: -1, onclose: () => { - delete this._loadingRemainingViewsMessage; + delete this._loadingRemainingViewsMessage }, - }); + }) } if (!this._isLoadingRemaingViews) { - this._isLoadingRemaingViews = true; + this._isLoadingRemaingViews = true handler = this.$interval(() => { - let nextIndex = this.viewsBuffer.length + 9; + let nextIndex = this.viewsBuffer.length + 9 if (nextIndex >= this.views.length) { - nextIndex = this.views.length - 1; + nextIndex = this.views.length - 1 } - this._pushNewViewsToBuffer(this.viewsBuffer.length, nextIndex); + this._pushNewViewsToBuffer(this.viewsBuffer.length, nextIndex) if (nextIndex === this.views.length - 1) { - this.$interval.cancel(handler); + this.$interval.cancel(handler) this._waitTillAfterDigestCycle(() => { - callback(); - this._isLoadingRemaingViews = false; + callback() + this._isLoadingRemaingViews = false if (this._loadingRemainingViewsMessage) { - this._loadingRemainingViewsMessage.destroy(); - delete this._loadingRemainingViewsMessage; + this._loadingRemainingViewsMessage.destroy() + delete this._loadingRemainingViewsMessage } - }); + }) } - }, 1000); + }, 1000) } } - }; + } public handleDocumentScrolling = (): boolean => { - return this._pushNewViewsToBuffer(this.viewsBuffer.length, this.viewsBuffer.length); - }; + return this._pushNewViewsToBuffer(this.viewsBuffer.length, this.viewsBuffer.length) + } public addInitialViews = (isScrollbarVisible: () => boolean): void => { - const message = this.growl.info('Loading initial view!', { ttl: -1 }); + const message = this.growl.info('Loading initial view!', { ttl: -1 }) const destroyMessage = (): void => { - message.destroy(); - }; - this._incrementallyAddViewTillScroll(destroyMessage, isScrollbarVisible); - }; + message.destroy() + } + this._incrementallyAddViewTillScroll(destroyMessage, isScrollbarVisible) + } public handleViewAdd = (view: ViewData, prevSiblingViewId: string): void => { // load the new view into the original views right after its sibling - const siblingIndex = this._findViewFromOriginalViews(prevSiblingViewId); - this.views.splice(siblingIndex + 1, 0, view); + const siblingIndex = this._findViewFromOriginalViews(prevSiblingViewId) + this.views.splice(siblingIndex + 1, 0, view) // load the new view into the viewsBuffer - const siblingIndexFromLoadedViews = this._findViewFromLoadedViews(prevSiblingViewId); + const siblingIndexFromLoadedViews = this._findViewFromLoadedViews(prevSiblingViewId) if (siblingIndexFromLoadedViews === -1) { // load all views up until the sibling view plus the new view - this._pushNewViewsToBuffer(this.viewsBuffer.length, siblingIndex + 1); + this._pushNewViewsToBuffer(this.viewsBuffer.length, siblingIndex + 1) } else { // load the new view right after its sibling - this._addNewViewToBufferAt(siblingIndexFromLoadedViews + 1); + this._addNewViewToBufferAt(siblingIndexFromLoadedViews + 1) } - }; + } public handleViewDelete = (deletedBranch: TreeBranch): void => { - const viewIdsToDelete: string[] = []; - this._getAllViewsStartingAt(deletedBranch, viewIdsToDelete); - this._deleteViewsFrom(this.views, viewIdsToDelete); - this._deleteViewsFrom(this.viewsBuffer, viewIdsToDelete); - }; + const viewIdsToDelete: string[] = [] + this._getAllViewsStartingAt(deletedBranch, viewIdsToDelete) + this._deleteViewsFrom(this.views, viewIdsToDelete) + this._deleteViewsFrom(this.viewsBuffer, viewIdsToDelete) + } private _addNewViewToBufferAt = (index: number): void => { - this.viewsBuffer.splice(index, 0, this.viewsBuffer[index]); - }; + this.viewsBuffer.splice(index, 0, this.viewsBuffer[index]) + } private _pushNewViewsToBuffer = (startIndex: number, endIndex: number): boolean => { - let isLoadedBefore = true; + let isLoadedBefore = true if (startIndex < this.views.length && endIndex < this.views.length) { - Array.prototype.push.apply(this.viewsBuffer, this.views.slice(startIndex, endIndex + 1)); - isLoadedBefore = false; + Array.prototype.push.apply(this.viewsBuffer, this.views.slice(startIndex, endIndex + 1)) + isLoadedBefore = false if (endIndex === this.views.length - 1) { this._waitTillAfterDigestCycle(() => { - this._isFullDocFullyLoaded = true; - }); + this._isFullDocFullyLoaded = true + }) } } - return isLoadedBefore; - }; + return isLoadedBefore + } private _loadViewsUntilViewWith = (viewId: string): boolean => { - let isViewLoadedBefore = true; + let isViewLoadedBefore = true // if not, find the index of that view and load starting from lastLoadedViewIndex till that view + 1 if (this._findViewFromLoadedViews(viewId) === -1) { - const index = this._findViewFromOriginalViews(viewId); + const index = this._findViewFromOriginalViews(viewId) if (index !== -1) { - this._pushNewViewsToBuffer(this.viewsBuffer.length, index); + this._pushNewViewsToBuffer(this.viewsBuffer.length, index) } - isViewLoadedBefore = false; + isViewLoadedBefore = false } - return isViewLoadedBefore; - }; + return isViewLoadedBefore + } private _incrementallyAddViewTillScroll = (callback: () => void, isScrollbarVisible: () => boolean): void => { - const isNoMoreToLoad = this._pushNewViewsToBuffer(this.viewsBuffer.length, this.viewsBuffer.length); + const isNoMoreToLoad = this._pushNewViewsToBuffer(this.viewsBuffer.length, this.viewsBuffer.length) this._waitTillAfterDigestCycle(() => { //const isScrollBarVisible = isScrollbarVisible() // the scrollbar logic no longer work, error in pane, just load a view and stop - const isScrollBarVisible = true; + const isScrollBarVisible = true if (isScrollBarVisible || isNoMoreToLoad) { - callback(); + callback() } else { - this._incrementallyAddViewTillScroll(callback, isScrollbarVisible); + this._incrementallyAddViewTillScroll(callback, isScrollbarVisible) } - }); - }; + }) + } private _getAllViewsStartingAt(branch: TreeBranch, results: string[]): void { if (branch.type === 'view') { - results.push(branch.data.id); + results.push(branch.data.id) branch.children.forEach((childBranch) => { - this._getAllViewsStartingAt(childBranch, results); - }); + this._getAllViewsStartingAt(childBranch, results) + }) } } private _deleteViewsFrom(viewListToDeleteFrom: ViewData[], viewIdsToDelete: string[]): void { _.remove(viewListToDeleteFrom, (view: ViewData) => { - return viewIdsToDelete.indexOf(view.id) !== -1; - }); + return viewIdsToDelete.indexOf(view.id) !== -1 + }) } private _findViewFromLoadedViews = (viewId: string): number => { - return _.findIndex(this.viewsBuffer, { id: viewId }); - }; + return _.findIndex(this.viewsBuffer, { id: viewId }) + } private _findViewFromOriginalViews = (viewId: string): number => { - return _.findIndex(this.views, { id: viewId }); - }; + return _.findIndex(this.views, { id: viewId }) + } private _waitTillAfterDigestCycle = (callback: () => void): void => { void this.$timeout(() => { if (this._isViewsFullyLoaded()) { - callback(); + callback() } else { - this._waitTillAfterDigestCycle(callback); + this._waitTillAfterDigestCycle(callback) } - }, 500); - }; + }, 500) + } private _isViewsFullyLoaded = (): boolean => { - return this.$http.pendingRequests.length === 0; - }; + return this.$http.pendingRequests.length === 0 + } } export class FullDocumentService { - static $inject = ['$timeout', '$interval', '$http', 'growl']; + static $inject = ['$timeout', '$interval', '$http', 'growl'] constructor( private $timeout: angular.ITimeoutService, @@ -203,8 +203,8 @@ export class FullDocumentService { ) {} get(): FullDocumentApi { - return new FullDocumentApi(this.$timeout, this.$interval, this.$http, this.growl); + return new FullDocumentApi(this.$timeout, this.$interval, this.$http, this.growl) } } -veUtils.service('FullDocumentService', FullDocumentService); +veUtils.service('FullDocumentService', FullDocumentService) diff --git a/src/ve-app/main/services/Resolve.service.ts b/src/ve-app/main/services/Resolve.service.ts index f2ab571f6..eb3f42f8f 100644 --- a/src/ve-app/main/services/Resolve.service.ts +++ b/src/ve-app/main/services/Resolve.service.ts @@ -1,7 +1,7 @@ -import { UIRouter } from '@uirouter/angularjs'; +import { UIRouter } from '@uirouter/angularjs' -import { BrandingService, BrandingStyle, ShortUrlService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { BrandingService, BrandingStyle, ShortUrlService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' import { AuthService, ElementService, @@ -10,11 +10,11 @@ import { ProjectService, URLService, ViewService, -} from '@ve-utils/mms-api-client'; +} from '@ve-utils/mms-api-client' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' -import { VePromise, VeQService } from '@ve-types/angular'; +import { VePromise, VeQService } from '@ve-types/angular' import { CheckAuthResponse, DocumentObject, @@ -32,8 +32,8 @@ import { RefObject, RefsResponse, ViewObject, -} from '@ve-types/mms'; -import { VeStorageService } from '@ve-types/view-editor'; +} from '@ve-types/mms' +import { VeStorageService } from '@ve-types/view-editor' export class ResolveService { static $inject = [ @@ -51,7 +51,7 @@ export class ResolveService { 'ElementService', 'PermissionsService', 'EventService', - ]; + ] constructor( private $localStorage: VeStorageService, @@ -71,150 +71,150 @@ export class ResolveService { ) {} public getBanner(params?: ParamsObject): VePromise { - return this.brandingSvc.getBanner(params); + return this.brandingSvc.getBanner(params) } public getLoginBanner(): VePromise { - return this.brandingSvc.getLoginBanner(); + return this.brandingSvc.getLoginBanner() } public getFooter(params?: ParamsObject): VePromise { - return this.brandingSvc.getFooter(params); + return this.brandingSvc.getFooter(params) } public getToken(): VePromise { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() this.authSvc.checkLogin().then( (data) => { - this.uRLSvc.setToken(this.$localStorage.token); - deferred.resolve(this.$localStorage.token); - this.$cookies.put('com.tomsawyer.web.license.user', data.username, { path: '/' }); + this.uRLSvc.setToken(this.$localStorage.token) + deferred.resolve(this.$localStorage.token) + this.$cookies.put('com.tomsawyer.web.license.user', data.username, { path: '/' }) }, (rejection) => { - deferred.reject(rejection); + deferred.reject(rejection) } - ); - return deferred.promise; + ) + return deferred.promise } public getOrg(projectOb: ProjectObject): VePromise { - const promise = this.projectSvc.getOrg(projectOb.orgId); + const promise = this.projectSvc.getOrg(projectOb.orgId) promise.then( (result) => { - this.eventSvc.resolve('mmsOrg', result); + this.eventSvc.resolve('mmsOrg', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getOrgs(): VePromise { - const promise = this.projectSvc.getOrgs(); + const promise = this.projectSvc.getOrgs() promise.then( (result) => { - this.eventSvc.resolve('mmsOrgs', result); + this.eventSvc.resolve('mmsOrgs', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getProject(params: ParamsObject): VePromise { - const promise = this.projectSvc.getProject(params.projectId); + const promise = this.projectSvc.getProject(params.projectId) promise.then( (result) => { - this.eventSvc.resolve('mmsProject', result); + this.eventSvc.resolve('mmsProject', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getProjects(projectOb: ProjectObject, refresh?: boolean): VePromise { - const promise = this.projectSvc.getProjects(projectOb.orgId, refresh); + const promise = this.projectSvc.getProjects(projectOb.orgId, refresh) promise.then( (result) => { - this.eventSvc.resolve('mmsProjects', result); + this.eventSvc.resolve('mmsProjects', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getProjectMounts(params: ParamsObject, refresh?: boolean): VePromise { - const promise = this.projectSvc.getProjectMounts(params.projectId, params.refId, refresh); + const promise = this.projectSvc.getProjectMounts(params.projectId, params.refId, refresh) promise.then( (result) => { - this.eventSvc.resolve('mmsProject', result); + this.eventSvc.resolve('mmsProject', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getRef(params: ParamsObject): VePromise { - const promise = this.projectSvc.getRef(params.refId, params.projectId); + const promise = this.projectSvc.getRef(params.refId, params.projectId) promise.then( (result) => { - this.eventSvc.resolve('mmsRef', result); + this.eventSvc.resolve('mmsRef', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getRefs(params: ParamsObject): VePromise { - const promise = this.projectSvc.getRefs(params.projectId); + const promise = this.projectSvc.getRefs(params.projectId) promise.then( (result) => { - this.eventSvc.resolve('mmsRefs', result); + this.eventSvc.resolve('mmsRefs', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getGroups(params: ParamsObject, refresh?: boolean): VePromise { return this.$q((resolve, reject) => { this.projectSvc.getGroups(params.projectId, params.refId, refresh).then( (result) => { - resolve(result); - this.eventSvc.resolve('mmsGroups', result); + resolve(result) + this.eventSvc.resolve('mmsGroups', result) }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } public getGroup(groupObs: GroupObject[], documentOb: DocumentObject): GroupObject { - let group: GroupObject = null; + let group: GroupObject = null if (documentOb) { for (let i = 0; i < groupObs.length; i++) { if (groupObs[i].id == documentOb._groupId) { - group = groupObs[i]; - break; + group = groupObs[i] + break } } } - this.eventSvc.resolve('mmsGroup', group); - return group; + this.eventSvc.resolve('mmsGroup', group) + return group } public getProjectRoot(params: ParamsObject): VePromise { @@ -222,7 +222,7 @@ export class ResolveService { projectId: params.projectId, refId: params.refId, elementId: params.projectId + '_pm', - }); + }) } public getCoverDocument( @@ -231,8 +231,8 @@ export class ResolveService { projectOb: ProjectObject, refresh?: boolean ): VePromise { - const deferred = this.$q.defer(); - const eid = params.projectId + '_cover'; + const deferred = this.$q.defer() + const eid = params.projectId + '_cover' this.elementSvc .getElement( { @@ -245,14 +245,14 @@ export class ResolveService { ) .then( (data) => { - this.eventSvc.resolve('mmsDocument', data); - if (!data._groupId) data._groupId = params.projectId + '_pm'; - deferred.resolve(data); + this.eventSvc.resolve('mmsDocument', data) + if (!data._groupId) data._groupId = params.projectId + '_pm' + deferred.resolve(data) }, (reason) => { if (reason.status === 404) { if (refOb.type === 'Tag') { - deferred.resolve(null); + deferred.resolve(null) } else { this.viewSvc .createView( @@ -272,19 +272,19 @@ export class ResolveService { ) .then( (data) => { - this.eventSvc.resolve('mmsDocument', data); - deferred.resolve(data); + this.eventSvc.resolve('mmsDocument', data) + deferred.resolve(data) }, (reason2) => { - deferred.resolve(null); + deferred.resolve(null) } - ); + ) } } else if (reason.status === 410) { //resurrect - let name = projectOb.name + ' Cover Page '; + let name = projectOb.name + ' Cover Page ' try { - name = `${reason.data.deleted[0].name} `; + name = `${reason.data.deleted[0].name} ` } catch (e) {} this.elementSvc .updateElements([ @@ -306,37 +306,37 @@ export class ResolveService { ]) .then( (data) => { - let resolved = false; + let resolved = false if (data.length > 0) { data.forEach((e) => { if (e.id == eid) { - deferred.resolve(e); - resolved = true; + deferred.resolve(e) + resolved = true } - }); + }) } if (!resolved) { - deferred.resolve(null); + deferred.resolve(null) } }, () => { - deferred.resolve(null); + deferred.resolve(null) } - ); + ) } else { - deferred.resolve(null); //let user get into project + deferred.resolve(null) //let user get into project } } - ); - return deferred.promise; + ) + return deferred.promise } public getPreviewDocument(params: ParamsObject, refOb: RefObject, refresh?: boolean): VePromise { - const deferred = this.$q.defer(); - const eid: string = params.preview; - const coverIndex = eid.indexOf('_cover'); + const deferred = this.$q.defer() + const eid: string = params.preview + const coverIndex = eid.indexOf('_cover') if (coverIndex > 0) { - const groupId = eid.substring(5, coverIndex); + const groupId = eid.substring(5, coverIndex) this.elementSvc .getElement( { @@ -350,18 +350,18 @@ export class ResolveService { ) .then( (data) => { - this.eventSvc.resolve('mmsDocument', data); - deferred.resolve(data); + this.eventSvc.resolve('mmsDocument', data) + deferred.resolve(data) }, (reason) => { if (reason.status === 404) { if (refOb.type === 'Tag') { - deferred.resolve(null); + deferred.resolve(null) } else { const viewDoc = '[cf:group docs]'; + '">[cf:group docs]' this.elementSvc .getElement( { @@ -392,35 +392,35 @@ export class ResolveService { ) .then( (data) => { - this.eventSvc.resolve('mmsDocument', data); - deferred.resolve(data); + this.eventSvc.resolve('mmsDocument', data) + deferred.resolve(data) }, (reason3) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) }, (reason2) => { - deferred.reject(reason2); + deferred.reject(reason2) } - ); + ) } } else { - deferred.reject(reason); + deferred.reject(reason) } } - ); + ) } else { this.getProjectDocument(params, refresh).then( (data) => { - deferred.resolve(data); + deferred.resolve(data) }, (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } - return deferred.promise; + return deferred.promise } public getProjectDocument(params: ParamsObject, refresh?: boolean): VePromise { @@ -432,17 +432,17 @@ export class ResolveService { }, 2, refresh - ); + ) promise.then( (result) => { - this.eventSvc.resolve('mmsDocument', result); + this.eventSvc.resolve('mmsDocument', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getProjectDocuments( @@ -461,14 +461,14 @@ export class ResolveService { ) .then( (result) => { - resolve(result); - this.eventSvc.resolve('mmsDocuments', result); + resolve(result) + this.eventSvc.resolve('mmsDocuments', result) }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } public getView(params: ParamsObject, refresh?: boolean): VePromise { @@ -480,39 +480,39 @@ export class ResolveService { }, 2, refresh - ); + ) promise.then( (result) => { - this.eventSvc.resolve('mmsView', result); + this.eventSvc.resolve('mmsView', result) }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message); + this.growl.error('Resolve Error: ' + reason.message) } - ); - return promise; + ) + return promise } public getSearch = (params: ParamsObject): string => { if (params.search === undefined) { - return null; + return null } - return params.search; - }; + return params.search + } public getField = (params: ParamsObject): string => { if (params.field === undefined) { - return 'all'; + return 'all' } - return params.field; - }; + return params.field + } public initializePermissions( projectOb: ProjectObject, refOb: RefObject ): VePromise { - return this.permissionsSvc.initializePermissions(projectOb, refOb); + return this.permissionsSvc.initializePermissions(projectOb, refOb) } } -veApp.service('ResolveService', ResolveService); +veApp.service('ResolveService', ResolveService) diff --git a/src/ve-app/main/services/index.ts b/src/ve-app/main/services/index.ts index d8eab8020..7ac8a2135 100644 --- a/src/ve-app/main/services/index.ts +++ b/src/ve-app/main/services/index.ts @@ -1,7 +1,7 @@ -import './AppUtils.service'; -import './Resolve.service'; -import './FullDocument.service'; +import './AppUtils.service' +import './Resolve.service' +import './FullDocument.service' -export * from './AppUtils.service'; -export * from './Resolve.service'; -export * from './FullDocument.service'; +export * from './AppUtils.service' +export * from './Resolve.service' +export * from './FullDocument.service' diff --git a/src/ve-app/pane-center/document.component.ts b/src/ve-app/pane-center/document.component.ts index c53f832af..3be4d1154 100644 --- a/src/ve-app/pane-center/document.component.ts +++ b/src/ve-app/pane-center/document.component.ts @@ -1,60 +1,60 @@ -import { IPaneScrollApi } from '@openmbee/pane-layout/lib/components/ng-pane'; -import { HookResult, Ng1Controller, StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs'; -import { Transition } from '@uirouter/core'; -import angular, { IComponentController } from 'angular'; -import Rx from 'rx-lite'; - -import { veAppEvents } from '@ve-app/events'; -import { AppUtilsService, FullDocumentApi, FullDocumentService } from '@ve-app/main/services'; -import { pane_center_buttons } from '@ve-app/pane-center/pane-center-buttons.config'; -import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service'; -import { TreeService } from '@ve-components/trees'; -import { IButtonBarButton, ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; -import { veCoreEvents } from '@ve-core/events'; -import { RootScopeService, ShortUrlService, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { PermissionsService, ViewData, ViewService, URLService } from '@ve-utils/mms-api-client'; - -import { veApp } from '@ve-app'; - -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { DocumentObject, ElementObject, ParamsObject, ProjectObject, RefObject, ViewObject } from '@ve-types/mms'; -import { TreeBranch, View2NodeMap } from '@ve-types/tree'; +import { IPaneScrollApi } from '@openmbee/pane-layout/lib/components/ng-pane' +import { HookResult, Ng1Controller, StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs' +import { Transition } from '@uirouter/core' +import angular, { IComponentController } from 'angular' +import Rx from 'rx-lite' + +import { veAppEvents } from '@ve-app/events' +import { AppUtilsService, FullDocumentApi, FullDocumentService } from '@ve-app/main/services' +import { pane_center_buttons } from '@ve-app/pane-center/pane-center-buttons.config' +import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service' +import { TreeService } from '@ve-components/trees' +import { IButtonBarButton, ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' +import { veCoreEvents } from '@ve-core/events' +import { RootScopeService, ShortUrlService, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { PermissionsService, ViewData, ViewService, URLService } from '@ve-utils/mms-api-client' + +import { veApp } from '@ve-app' + +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { DocumentObject, ElementObject, ParamsObject, ProjectObject, RefObject, ViewObject } from '@ve-types/mms' +import { TreeBranch, View2NodeMap } from '@ve-types/tree' class FullDocumentController implements IComponentController, Ng1Controller { //Bindings - public mmsView: ViewObject; - public mmsDocument: DocumentObject; - public mmsProject: ProjectObject; - public mmsRef: RefObject; + public mmsView: ViewObject + public mmsDocument: DocumentObject + public mmsProject: ProjectObject + public mmsRef: RefObject // // //Locals // public document: DocumentObject // public project: ProjectObject // public ref: RefObject - public subs: Rx.IDisposable[]; - bars: string[]; - bbApi: ButtonBarApi; - bbId = 'full-doc'; - fullDocumentApi: FullDocumentApi; - viewContentLoading: boolean; - buttons: IButtonBarButton[] = []; - latestElement: string = ''; - scrollApi: IPaneScrollApi; - views: ViewData[] = []; - viewsBuffer: ViewData[] = []; - view2Children: { [key: string]: string[] } = {}; - view2Node: View2NodeMap = {}; - num = 1; - seenViewIds = {}; - shortUrl: string = ''; - processed: string; + public subs: Rx.IDisposable[] + bars: string[] + bbApi: ButtonBarApi + bbId = 'full-doc' + fullDocumentApi: FullDocumentApi + viewContentLoading: boolean + buttons: IButtonBarButton[] = [] + latestElement: string = '' + scrollApi: IPaneScrollApi + views: ViewData[] = [] + viewsBuffer: ViewData[] = [] + view2Children: { [key: string]: string[] } = {} + view2Node: View2NodeMap = {} + num = 1 + seenViewIds = {} + shortUrl: string = '' + processed: string private dynamicPopover: { - templateUrl: string; - title: string; - }; + templateUrl: string + title: string + } static $inject = [ '$q', @@ -81,7 +81,7 @@ class FullDocumentController implements IComponentController, Ng1Controller { 'TreeService', 'EventService', 'ButtonBarService', - ]; + ] constructor( private $q: VeQService, private $scope: angular.IScope, @@ -110,71 +110,71 @@ class FullDocumentController implements IComponentController, Ng1Controller { ) {} $onInit(): void { - this.rootScopeSvc.veFullDocMode(true); - this.rootScopeSvc.veHideLeft(false); - this.rootScopeSvc.veHideRight(false); - this.rootScopeSvc.veNumberingOn(true); - this.eventSvc.$init(this); + this.rootScopeSvc.veFullDocMode(true) + this.rootScopeSvc.veHideLeft(false) + this.rootScopeSvc.veHideRight(false) + this.rootScopeSvc.veNumberingOn(true) + this.eventSvc.$init(this) //Init/Reset Tree Updated Subject - this.eventSvc.resolve(TreeService.events.UPDATED, false); + this.eventSvc.resolve(TreeService.events.UPDATED, false) - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, pane_center_buttons); + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, pane_center_buttons) this.view2Node[this.mmsDocument.id] = { label: this.mmsDocument.name, data: this.mmsDocument, type: 'view', children: [], - }; - this.view2Children[this.mmsDocument.id] = []; + } + this.view2Children[this.mmsDocument.id] = [] // Share URL button settings - this.dynamicPopover = this.shortUrlSvc.dynamicPopover; + this.dynamicPopover = this.shortUrlSvc.dynamicPopover this.shortUrl = this.shortUrlSvc.getShortUrl({ orgId: this.mmsProject.orgId, projectId: this.mmsProject.id, refId: this.mmsRef.id, documentId: this.mmsDocument.id, - }); + }) - this.viewContentLoading = this.rootScopeSvc.veViewContentLoading(false); + this.viewContentLoading = this.rootScopeSvc.veViewContentLoading(false) this.$transitions.onSuccess({}, (transition) => { - this._scroll(transition.params().viewId as string); - }); + this._scroll(transition.params().viewId as string) + }) this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEVIEWCONTENTLOADING, (data) => { - this.viewContentLoading = data; + this.viewContentLoading = data }) - ); + ) // api to communicate with borderlayout library, no longer works this.scrollApi = { notifyOnScroll: this.notifyOnScroll, isScrollVisible: (): boolean => { - return false; + return false }, // pane's directive (in borderlayout) resets this to the right function throttleRate: 500, // how often should the wheel event triggered threshold: 3000, // how far from the bottom of the page before adding more views frequency: 100, // how fast to add more views - }; + } this.subs.push( this.eventSvc.$on('view.deleted', (deletedBranch: TreeBranch) => { - this.fullDocumentApi.handleViewDelete(deletedBranch); + this.fullDocumentApi.handleViewDelete(deletedBranch) }) - ); + ) this.subs.push( this.eventSvc.$on('view.added', (data: veAppEvents.viewAddedData) => { - this.fullDocumentApi.handleViewAdd(this._buildViewData(data.vId, data.curSec), data.prevSibId); - this._scroll(data.vId); - this.eventSvc.$broadcast('view.selected'); + this.fullDocumentApi.handleViewAdd(this._buildViewData(data.vId, data.curSec), data.prevSibId) + this._scroll(data.vId) + this.eventSvc.$broadcast('view.selected') }) - ); + ) this.subs.push( // this.eventSvc.$on('view.scroll', (viewId) => { @@ -186,36 +186,36 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.bbApi.toggleButton( 'show-comments', this.rootScopeSvc.veCommentsOn(!this.rootScopeSvc.veCommentsOn()) - ); - break; + ) + break case 'show-elements': this.bbApi.toggleButton( 'show-elements', this.rootScopeSvc.veElementsOn(!this.rootScopeSvc.veElementsOn()) - ); + ) if (!this.rootScopeSvc.veElementsOn() && this.rootScopeSvc.veEditMode()) { - this.bbApi.toggleButton('show-edits', false); - this.rootScopeSvc.veEditMode(false); + this.bbApi.toggleButton('show-edits', false) + this.rootScopeSvc.veEditMode(false) } - break; + break case 'show-edits': this.bbApi.toggleButton( 'show-edits', this.rootScopeSvc.veEditMode(!this.rootScopeSvc.veEditMode()) - ); + ) if (this.rootScopeSvc.veElementsOn() !== this.rootScopeSvc.veEditMode()) { - this.bbApi.toggleButton('show-elements', this.rootScopeSvc.veEditMode()); - this.rootScopeSvc.veElementsOn(this.rootScopeSvc.veEditMode()); + this.bbApi.toggleButton('show-elements', this.rootScopeSvc.veEditMode()) + this.rootScopeSvc.veElementsOn(this.rootScopeSvc.veEditMode()) } - break; + break case 'show-numbering': this.bbApi.toggleButton( 'show-numbering', this.rootScopeSvc.veNumberingOn(!this.rootScopeSvc.veNumberingOn()) - ); - break; + ) + break case 'convert-pdf': this.fullDocumentApi.loadRemainingViews(() => { void this.appUtilsSvc.printModal( @@ -224,9 +224,9 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.mmsRef, true, 3 - ); - }); - break; + ) + }) + break case 'print': this.fullDocumentApi.loadRemainingViews(() => { void this.appUtilsSvc.printModal( @@ -235,9 +235,9 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.mmsRef, true, 1 - ); - }); - break; + ) + }) + break case 'word': this.fullDocumentApi.loadRemainingViews(() => { void this.appUtilsSvc.printModal( @@ -246,28 +246,28 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.mmsRef, true, 2 - ); - }); - break; + ) + }) + break case 'tabletocsv': this.fullDocumentApi.loadRemainingViews(() => { - this.appUtilsSvc.tableToCsv(angular.element('#print-div'), true); - }); - break; + this.appUtilsSvc.tableToCsv(angular.element('#print-div'), true) + }) + break case 'refresh-numbering': //TODO - break; + break } }) - ); - this.initViews(); + ) + this.initViews() } $onDestroy(): void { - this.eventSvc.$destroy(this.subs); - this.buttonBarSvc.destroy(this.bbId); + this.eventSvc.$destroy(this.subs) + this.buttonBarSvc.destroy(this.bbId) } initViews(): void { @@ -280,35 +280,35 @@ class FullDocumentController implements IComponentController, Ng1Controller { refId: this.mmsRef.id, refType: this.mmsRef.type, refresh: this.$uiRouterGlobals.transition.$from().name === '', - }; + } - this.eventSvc.$broadcast('view.selected', data); - this.fullDocumentApi = this.fullDocumentSvc.get(); - this.views = this.fullDocumentApi.views; - this.viewsBuffer = this.fullDocumentApi.viewsBuffer; + this.eventSvc.$broadcast('view.selected', data) + this.fullDocumentApi = this.fullDocumentSvc.get() + this.views = this.fullDocumentApi.views + this.viewsBuffer = this.fullDocumentApi.viewsBuffer this._createViews().then( () => { - this.fullDocumentApi.addInitialViews(scrollVisible); + this.fullDocumentApi.addInitialViews(scrollVisible) if (this.mmsView && this.mmsView.id !== this.mmsDocument.id) { this.fullDocumentApi.handleClickOnBranch(this.mmsView.id, () => { - this._scroll(this.mmsView.id); - this.fullDocumentApi.loadRemainingViews(); //remove if scroll works - }); + this._scroll(this.mmsView.id) + this.fullDocumentApi.loadRemainingViews() //remove if scroll works + }) } else { - this.fullDocumentApi.loadRemainingViews(); //remove if scroll works + this.fullDocumentApi.loadRemainingViews() //remove if scroll works } }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) const scrollVisible = (): boolean => { - return this.scrollApi.isScrollVisible(); - }; + return this.scrollApi.isScrollVisible() + } } uiOnParamsChanged(newValues: ParamsObject, $transition$: Transition): void { - if (newValues.viewId !== this.processed) this._scroll(newValues.viewId); + if (newValues.viewId !== this.processed) this._scroll(newValues.viewId) } uiCanExit(transition: Transition): HookResult { //Do nothing @@ -319,8 +319,8 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.mmsRef.type === 'Branch' && this.permissionsSvc.hasBranchEditPermission(this.mmsProject.id, this.mmsRef.id) ) { - api.addButton(this.buttonBarSvc.getButtonBarButton('show-edits')); - api.toggleButton('show-edits', this.rootScopeSvc.veEditMode()); + api.addButton(this.buttonBarSvc.getButtonBarButton('show-edits')) + api.toggleButton('show-edits', this.rootScopeSvc.veEditMode()) this.hotkeys.bindTo(this.$scope).add({ combo: 'alt+d', @@ -328,20 +328,20 @@ class FullDocumentController implements IComponentController, Ng1Controller { callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-edits', - }); + }) }, - }); + }) } - api.addButton(this.buttonBarSvc.getButtonBarButton('show-elements')); - api.toggleButton('show-elements', this.rootScopeSvc.veElementsOn()); - api.addButton(this.buttonBarSvc.getButtonBarButton('show-comments')); - api.toggleButton('show-comments', this.rootScopeSvc.veCommentsOn()); - api.addButton(this.buttonBarSvc.getButtonBarButton('show-numbering')); - api.toggleButton('show-numbering', this.rootScopeSvc.veNumberingOn()); - api.addButton(this.buttonBarSvc.getButtonBarButton('refresh-numbering')); - api.addButton(this.buttonBarSvc.getButtonBarButton('print')); - api.addButton(this.buttonBarSvc.getButtonBarButton('export')); + api.addButton(this.buttonBarSvc.getButtonBarButton('show-elements')) + api.toggleButton('show-elements', this.rootScopeSvc.veElementsOn()) + api.addButton(this.buttonBarSvc.getButtonBarButton('show-comments')) + api.toggleButton('show-comments', this.rootScopeSvc.veCommentsOn()) + api.addButton(this.buttonBarSvc.getButtonBarButton('show-numbering')) + api.toggleButton('show-numbering', this.rootScopeSvc.veNumberingOn()) + api.addButton(this.buttonBarSvc.getButtonBarButton('refresh-numbering')) + api.addButton(this.buttonBarSvc.getButtonBarButton('print')) + api.addButton(this.buttonBarSvc.getButtonBarButton('export')) this.hotkeys .bindTo(this.$scope) @@ -351,7 +351,7 @@ class FullDocumentController implements IComponentController, Ng1Controller { callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-comments', - }); + }) }, }) .add({ @@ -360,10 +360,10 @@ class FullDocumentController implements IComponentController, Ng1Controller { callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-elements', - }); + }) }, - }); - }; + }) + } private _scroll = (viewId: string): void => { if (this.view2Children[viewId]) { @@ -374,19 +374,19 @@ class FullDocumentController implements IComponentController, Ng1Controller { projectId: this.mmsProject.id, refId: this.mmsRef.id, refType: this.mmsRef.type, - }; + } - this.eventSvc.$broadcast('element.selected', data); - if (viewId === this.processed) return; - this.processed = viewId; + this.eventSvc.$broadcast('element.selected', data) + if (viewId === this.processed) return + this.processed = viewId this.fullDocumentApi.handleClickOnBranch(viewId, () => { - document.getElementById(viewId).scrollIntoView(true); - }); + document.getElementById(viewId).scrollIntoView(true) + }) } - }; + } private _createViews = (): VePromise => { - const message = this._loadingViewsFromServer(); + const message = this._loadingViewsFromServer() return new this.$q((resolve, reject) => { this.views.push({ id: this.mmsDocument.id, @@ -394,9 +394,9 @@ class FullDocumentController implements IComponentController, Ng1Controller { elementTranscluded: this._elementTranscluded, elementClicked: this._elementClicked, }, - }); + }) if (!this.mmsDocument._childViews) { - this.mmsDocument._childViews = []; + this.mmsDocument._childViews = [] } this.viewSvc .handleChildViews( @@ -410,27 +410,27 @@ class FullDocumentController implements IComponentController, Ng1Controller { ) .then((childIds: string[]) => { for (let i = 0; i < childIds.length; i++) { - this._constructViews(childIds[i], this.num.toString(10)); - this.num = this.num + 1; + this._constructViews(childIds[i], this.num.toString(10)) + this.num = this.num + 1 } - resolve(); + resolve() }, reject) .finally(() => { - message.destroy(); - }); - }); - }; + message.destroy() + }) + }) + } private _loadingViewsFromServer = (): angular.growl.IGrowlMessage => { - return this.growl.info('Loading data from server!', { ttl: -1 }); - }; + return this.growl.info('Loading data from server!', { ttl: -1 }) + } private _elementTranscluded = (elementOb: ElementObject, type: string): void => { if (elementOb && type !== 'Comment') { if (elementOb._modified && elementOb._modified > this.latestElement) - this.latestElement = elementOb._modified; + this.latestElement = elementOb._modified } - }; + } private _elementClicked = (elementOb: ElementObject): void => { const data = { @@ -439,9 +439,9 @@ class FullDocumentController implements IComponentController, Ng1Controller { projectId: elementOb._projectId, refId: elementOb._refId, commitId: 'latest', - }; - this.eventSvc.$broadcast('element.selected', data); - }; + } + this.eventSvc.$broadcast('element.selected', data) + } private _buildViewData = (vId: string, curSec: string): ViewData => { return { @@ -453,55 +453,55 @@ class FullDocumentController implements IComponentController, Ng1Controller { number: curSec, topLevel: curSec ? curSec.toString().indexOf('.') === -1 : false, first: curSec == '1', - }; - }; + } + } private _constructViews = (viewId: string, curSection: string): void => { - this.views.push(this._buildViewData(viewId, curSection)); + this.views.push(this._buildViewData(viewId, curSection)) if (this.view2Children[viewId] && Array.isArray(this.view2Children[viewId])) { - let num = 1; - const childIds = this.view2Children[viewId]; + let num = 1 + const childIds = this.view2Children[viewId] for (let i = 0; i < childIds.length; i++) { - this._constructViews(this.view2Children[viewId][i], `${curSection}.${num}`); - num = num + 1; + this._constructViews(this.view2Children[viewId][i], `${curSection}.${num}`) + num = num + 1 } } - }; + } private _handleSingleView = (v: ViewObject, aggr: string): string[] => { - let childIds = this.view2Children[v.id]; + let childIds = this.view2Children[v.id] if (!childIds) { - childIds = []; + childIds = [] } - this.view2Children[v.id] = childIds; + this.view2Children[v.id] = childIds if (!v._childViews || v._childViews.length === 0 || aggr === 'none') { - return childIds; + return childIds } for (let i = 0; i < v._childViews.length; i++) { if (this.seenViewIds[v._childViews[i].id]) { - continue; + continue } - this.seenViewIds[v._childViews[i].id] = true; - childIds.push(v._childViews[i].id); + this.seenViewIds[v._childViews[i].id] = true + childIds.push(v._childViews[i].id) } - return childIds; - }; + return childIds + } public notifyOnScroll = (): boolean => { - return this.fullDocumentApi.handleDocumentScrolling(); - }; + return this.fullDocumentApi.handleDocumentScrolling() + } public copyToClipboard = ($event: JQuery.ClickEvent): void => { this.shortUrlSvc.copyToClipboard(this.$element, $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }); + this.growl.info('Copied to clipboard!', { ttl: 2000 }) }, (err) => { - this.growl.error('Unable to copy: ' + err.message); + this.growl.error('Unable to copy: ' + err.message) } - ); - }; + ) + } } /* Controller */ @@ -549,6 +549,6 @@ const DocumentComponent: VeComponentOptions = { mmsDocument: '<', }, controller: FullDocumentController, -}; +} -veApp.component(DocumentComponent.selector, DocumentComponent); +veApp.component(DocumentComponent.selector, DocumentComponent) diff --git a/src/ve-app/pane-center/index.ts b/src/ve-app/pane-center/index.ts index cddc45cdc..159a896b7 100644 --- a/src/ve-app/pane-center/index.ts +++ b/src/ve-app/pane-center/index.ts @@ -1,8 +1,8 @@ -import './services/ContentWindow.service'; +import './services/ContentWindow.service' -import './document.component'; -import './slideshow.component'; -import './search.component'; -import './refs.component'; -import './reorder.component'; -import './reorder-group.component'; +import './document.component' +import './slideshow.component' +import './search.component' +import './refs.component' +import './reorder.component' +import './reorder-group.component' diff --git a/src/ve-app/pane-center/pane-center-buttons.config.ts b/src/ve-app/pane-center/pane-center-buttons.config.ts index ca370ccb8..41448a545 100644 --- a/src/ve-app/pane-center/pane-center-buttons.config.ts +++ b/src/ve-app/pane-center/pane-center-buttons.config.ts @@ -1,4 +1,4 @@ -import { IButtonBarButton } from '@ve-core/button-bar'; +import { IButtonBarButton } from '@ve-core/button-bar' export const pane_center_buttons: IButtonBarButton[] = [ { @@ -98,4 +98,4 @@ export const pane_center_buttons: IButtonBarButton[] = [ selectable: false, tooltip: 'Table to CSV', }, -]; +] diff --git a/src/ve-app/pane-center/refs.component.ts b/src/ve-app/pane-center/refs.component.ts index 39cf1eb22..f63b38645 100644 --- a/src/ve-app/pane-center/refs.component.ts +++ b/src/ve-app/pane-center/refs.component.ts @@ -1,22 +1,22 @@ -import { StateService } from '@uirouter/angularjs'; -import angular, { IWindowService } from 'angular'; -import _ from 'lodash'; -import Rx from 'rx-lite'; +import { StateService } from '@uirouter/angularjs' +import angular, { IWindowService } from 'angular' +import _ from 'lodash' +import Rx from 'rx-lite' -import { AppUtilsService } from '@ve-app/main/services'; -import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service'; -import { InsertRefData } from '@ve-components/insertions/components/insert-ref.component'; -import { ConfirmDeleteModalResolveFn } from '@ve-core/modals'; -import { ApplicationService, RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { ProjectService, ElementService } from '@ve-utils/mms-api-client'; +import { AppUtilsService } from '@ve-app/main/services' +import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service' +import { InsertRefData } from '@ve-components/insertions/components/insert-ref.component' +import { ConfirmDeleteModalResolveFn } from '@ve-core/modals' +import { ApplicationService, RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { ProjectService, ElementService } from '@ve-utils/mms-api-client' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' -import { VeComponentOptions, VeQService } from '@ve-types/angular'; -import { InsertResolveFn } from '@ve-types/components'; -import { ProjectObject, RefObject } from '@ve-types/mms'; -import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; +import { VeComponentOptions, VeQService } from '@ve-types/angular' +import { InsertResolveFn } from '@ve-types/components' +import { ProjectObject, RefObject } from '@ve-types/mms' +import { VeModalService, VeModalSettings } from '@ve-types/view-editor' class RefsController { static $inject = [ @@ -36,29 +36,29 @@ class RefsController { 'ApplicationService', 'RootScopeService', 'EventService', - ]; + ] - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] //Bindings - mmsRefs: RefObject[]; - mmsProject: ProjectObject; - mmsRef: RefObject; + mmsRefs: RefObject[] + mmsProject: ProjectObject + mmsRef: RefObject //Local - public refManageView: boolean; - isLoading: boolean; - refData; - bbApi; - buttons; - project: ProjectObject; - refs: RefObject[]; - branches: RefObject[]; - tags: RefObject[]; - refSelected: RefObject; - search; - view; - htmlTooltip: string; + public refManageView: boolean + isLoading: boolean + refData + bbApi + buttons + project: ProjectObject + refs: RefObject[] + branches: RefObject[] + tags: RefObject[] + refSelected: RefObject + search + view + htmlTooltip: string constructor( private $sce: angular.ISCEService, @@ -80,65 +80,65 @@ class RefsController { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) - this.contentWindowSvc.toggleLeftPane(true); - this.rootScopeSvc.veHideLeft(true); - this.rootScopeSvc.veHideRight(true); - this.refManageView = true; - this.refData = []; - this.bbApi = {}; - this.buttons = []; - this.refSelected = this.mmsRef; - this.search = null; - this.view = null; + this.contentWindowSvc.toggleLeftPane(true) + this.rootScopeSvc.veHideLeft(true) + this.rootScopeSvc.veHideRight(true) + this.refManageView = true + this.refData = [] + this.bbApi = {} + this.buttons = [] + this.refSelected = this.mmsRef + this.search = null + this.view = null - this.refs = this.mmsRefs; + this.refs = this.mmsRefs this.branches = this.refs.filter((ref) => { - return ref.type === 'Branch'; - }); + return ref.type === 'Branch' + }) this.tags = this.refs.filter((ref) => { - return ref.type === 'Tag'; - }); + return ref.type === 'Tag' + }) - this.project = this.mmsProject; + this.project = this.mmsProject - this.htmlTooltip = this.$sce.trustAsHtml('Branch temporarily unavailable during duplication.') as string; + this.htmlTooltip = this.$sce.trustAsHtml('Branch temporarily unavailable during duplication.') as string } selectMasterDefault = (): void => { - const masterIndex = _.findIndex(this.refs, { name: 'master' }); + const masterIndex = _.findIndex(this.refs, { name: 'master' }) if (masterIndex > -1) { - this.refSelected = this.refs[masterIndex]; + this.refSelected = this.refs[masterIndex] } - }; + } addBranch = (e: JQuery.ClickEvent): void => { - e.stopPropagation(); - this.insert('Branch'); - }; + e.stopPropagation() + this.insert('Branch') + } addTag = (e: JQuery.ClickEvent): void => { - e.stopPropagation(); - this.insert('Tag'); - }; + e.stopPropagation() + this.insert('Tag') + } deleteRef = (e: JQuery.ClickEvent): void => { - e.stopPropagation(); - this.deleteItem(); - }; + e.stopPropagation() + this.deleteItem() + } refClickHandler = (ref: RefObject): void => { this.projectSvc.getRef(ref.id, this.project.id).then( (data) => { - this.refSelected = data; + this.refSelected = data }, (error) => { - this.growl.error('Ref click handler error: ' + error.message); - return; + this.growl.error('Ref click handler error: ' + error.message) + return } - ); - }; + ) + } insert = (itemType: string): void => { const insertData: InsertRefData = { @@ -147,126 +147,126 @@ class RefsController { parentTitle: '', insertType: 'ref', lastCommit: true, - }; - const branch = this.refSelected; + } + const branch = this.refSelected // Item specific setup: if (itemType === 'Branch') { if (!branch) { - this.growl.warning('Add Branch Error: Select a branch or tag first'); - return; + this.growl.warning('Add Branch Error: Select a branch or tag first') + return } if (branch.type === 'Tag') { - insertData.parentTitle = 'Tag ' + branch.name; + insertData.parentTitle = 'Tag ' + branch.name } else { - insertData.parentTitle = 'Branch ' + branch.name; + insertData.parentTitle = 'Branch ' + branch.name } - insertData.parentRefId = branch.id; + insertData.parentRefId = branch.id } else if (itemType === 'Tag') { if (!branch) { - this.growl.warning('Add Tag Error: Select a branch or tag first'); - return; + this.growl.warning('Add Tag Error: Select a branch or tag first') + return } - insertData.parentRefId = branch.id; + insertData.parentRefId = branch.id } else { - this.growl.error('Add Item of Type ' + itemType + ' is not supported'); - return; + this.growl.error('Add Item of Type ' + itemType + ' is not supported') + return } const instance = this.$uibModal.open, RefObject>({ component: 'insertElementModal', resolve: { getInsertData: () => { - return insertData; + return insertData }, getFilter: () => { - return this.$filter; + return this.$filter }, getProjectId: () => { - return this.project.id; + return this.project.id }, getRefId: () => { - return null; + return null }, getOrgId: () => { - return this.project.orgId; + return this.project.orgId }, getSeenViewIds: () => { - return null; + return null }, }, - }); + }) instance.result.then( (data) => { if (data.type === 'Branch') { - this.branches.push(data); - this.refSelected = data; + this.branches.push(data) + this.refSelected = data } else { - this.tags.push(data); - this.refSelected = data; + this.tags.push(data) + this.refSelected = data } }, (reason?) => { if (reason && reason.status !== 444) { - this.growl.error('Ref Creation Error:' + reason.message); + this.growl.error('Ref Creation Error:' + reason.message) } else { this.growl.info('Ref Creation Cancelled', { ttl: 1000, - }); + }) } } - ); - }; + ) + } deleteItem = (): void => { - const branch = this.refSelected; + const branch = this.refSelected if (!branch) { - this.growl.warning('Select item to delete.'); - return; + this.growl.warning('Select item to delete.') + return } const settings: VeModalSettings = { component: 'confirmDeleteModal', resolve: { getName: () => { - return branch.name; + return branch.name }, getType: () => { if (branch.type === 'Tag') { - return 'Tag'; + return 'Tag' } else if (branch.type === 'Branch') { - return 'Branch'; + return 'Branch' } }, finalize: () => { return () => { - return this.projectSvc.deleteRef(branch.id, this.project.id); - }; + return this.projectSvc.deleteRef(branch.id, this.project.id) + } }, }, - }; - const instance = this.$uibModal.open(settings); + } + const instance = this.$uibModal.open(settings) instance.result.then( () => { //TODO $state project with no selected ref - let index: number; + let index: number if (this.refSelected.type === 'Branch') { - index = this.branches.indexOf(this.refSelected); - this.branches.splice(index, 1); + index = this.branches.indexOf(this.refSelected) + this.branches.splice(index, 1) } else if (this.refSelected.type === 'Tag') { - index = this.tags.indexOf(this.refSelected); - this.tags.splice(index, 1); + index = this.tags.indexOf(this.refSelected) + this.tags.splice(index, 1) } - this.refSelected = null; + this.refSelected = null }, (reason?) => { if (reason) { - this.growl.error('Ref Deletion Error:' + reason.message); + this.growl.error('Ref Deletion Error:' + reason.message) } else { this.growl.info('Ref Deletion Cancelled', { ttl: 1000, - }); + }) } } - ); - }; + ) + } } const RefsComponent: VeComponentOptions = { @@ -353,6 +353,6 @@ const RefsComponent: VeComponentOptions = { mmsRefs: '<', }, controller: RefsController, -}; +} -veApp.component(RefsComponent.selector, RefsComponent); +veApp.component(RefsComponent.selector, RefsComponent) diff --git a/src/ve-app/pane-center/reorder-group.component.ts b/src/ve-app/pane-center/reorder-group.component.ts index a5b27d810..2a2880af8 100644 --- a/src/ve-app/pane-center/reorder-group.component.ts +++ b/src/ve-app/pane-center/reorder-group.component.ts @@ -1,48 +1,48 @@ -import { StateService } from '@uirouter/angularjs'; -import { IComponentController } from 'angular'; -import _ from 'lodash'; +import { StateService } from '@uirouter/angularjs' +import { IComponentController } from 'angular' +import _ from 'lodash' -import { TreeService } from '@ve-components/trees'; -import { CacheService } from '@ve-utils/core'; -import { ElementService } from '@ve-utils/mms-api-client'; +import { TreeService } from '@ve-components/trees' +import { CacheService } from '@ve-utils/core' +import { ElementService } from '@ve-utils/mms-api-client' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' -import { VeComponentOptions, VeQService } from '@ve-types/angular'; -import { DocumentObject, ElementObject, GroupObject, ParamsObject, ProjectObject, RefObject } from '@ve-types/mms'; -import { AngularUITree, VeTreeNodeScope } from '@ve-types/tree'; +import { VeComponentOptions, VeQService } from '@ve-types/angular' +import { DocumentObject, ElementObject, GroupObject, ParamsObject, ProjectObject, RefObject } from '@ve-types/mms' +import { AngularUITree, VeTreeNodeScope } from '@ve-types/tree' interface ReorderGroupNode { - data: GroupObject | DocumentObject; - children: ReorderGroupNode[]; - name: string; - id: string; - type: string; - isChild?: boolean; + data: GroupObject | DocumentObject + children: ReorderGroupNode[] + name: string + id: string + type: string + isChild?: boolean } interface ReorderGroupResult { - node: ReorderGroupNode; - newOwnerId: string; + node: ReorderGroupNode + newOwnerId: string } class ReorderGroupController implements IComponentController { - params: ParamsObject; - mmsProject: ProjectObject; - mmsRef: RefObject; - mmsGroups: GroupObject[]; - mmsDocuments: DocumentObject[]; + params: ParamsObject + mmsProject: ProjectObject + mmsRef: RefObject + mmsGroups: GroupObject[] + mmsDocuments: DocumentObject[] //Locals - groups: GroupObject[]; - documents: DocumentObject[]; - isSaving = false; - targetId = ''; + groups: GroupObject[] + documents: DocumentObject[] + isSaving = false + targetId = '' - treeOptions: AngularUITree.ICallbacks; + treeOptions: AngularUITree.ICallbacks - static $inject = ['$q', '$scope', '$state', 'growl', 'ElementService', 'CacheService', 'TreeService']; - private tree: ReorderGroupNode[]; + static $inject = ['$q', '$scope', '$state', 'growl', 'ElementService', 'CacheService', 'TreeService'] + private tree: ReorderGroupNode[] constructor( private $q: VeQService, @@ -55,102 +55,102 @@ class ReorderGroupController implements IComponentController { ) {} $onInit(): void { - this.groups = this.mmsGroups; - this.documents = this.mmsDocuments; + this.groups = this.mmsGroups + this.documents = this.mmsDocuments - const children = this.generateTree(); - this.sortRecursively(children); + const children = this.generateTree() + this.sortRecursively(children) const root = this.createNode('Top Level', 'root', children, { id: 'root', _projectId: this.params.projectId, _refId: this.params.refId, - }); - this.tree = [root]; + }) + this.tree = [root] this.treeOptions = { dropped: (change): void => { - this.sortRecursively(children); - this.targetId = ''; + this.sortRecursively(children) + this.targetId = '' }, accept: (sourceNodeScope: VeTreeNodeScope, destNodeScope: VeTreeNodeScope, destIndex): boolean => { // allow moving to the root or to a group const accept = - destNodeScope.node && (destNodeScope.node.type === 'group' || destNodeScope.node.type === 'root'); + destNodeScope.node && (destNodeScope.node.type === 'group' || destNodeScope.node.type === 'root') if (accept) { if ( destNodeScope.$nodeScope && destNodeScope.$nodeScope.$modelValue && ( destNodeScope.$nodeScope.$modelValue as { - id: string; + id: string } ).id ) { this.targetId = ( destNodeScope.$nodeScope.$modelValue as { - id: string; + id: string } - ).id; + ).id } } - return accept; + return accept }, dragStart: (data): void => { this.targetId = ( data.dest.nodesScope.$nodeScope.$modelValue as { - id: string; + id: string } - ).id; + ).id }, - }; + } } public generateTree(): ReorderGroupNode[] { // create a node for each groupOb let tree = this.groups.map((groupOb) => { - return this.createNode(groupOb.name, 'group', [], groupOb); - }); + return this.createNode(groupOb.name, 'group', [], groupOb) + }) // add document to its group this.documents .filter((documentOb) => { - return documentOb._groupId; + return documentOb._groupId }) .forEach((documentOb) => { const parent = _.find(tree, (node) => { - return node.data.id === documentOb._groupId; - }); + return node.data.id === documentOb._groupId + }) if (parent) { - parent.children.push(this.createNode(documentOb.name, 'view', [], documentOb)); + parent.children.push(this.createNode(documentOb.name, 'view', [], documentOb)) } - }); + }) // for any group that has a parent group, establish that connection tree.forEach((groupNode) => { const foundParent = _.find(tree, (node) => { - return node.data.id === groupNode.data._parentId; - }); + return node.data.id === groupNode.data._parentId + }) if (foundParent) { - groupNode.isChild = true; - foundParent.children.push(groupNode); + groupNode.isChild = true + foundParent.children.push(groupNode) } - return groupNode; - }); + return groupNode + }) // only groups that don't have parents show up at root level tree = tree.filter((groupNode) => { - return !groupNode.isChild; - }); + return !groupNode.isChild + }) // add all the documents that don't belong to any group this.documents .filter((documentOb) => { - return !documentOb._groupId; + return !documentOb._groupId }) .forEach((documentOb) => { - this.tree.push(this.createNode(documentOb.name, 'view', [], documentOb)); - }); - return tree; + this.tree.push(this.createNode(documentOb.name, 'view', [], documentOb)) + }) + return tree } public createNode( @@ -165,18 +165,18 @@ class ReorderGroupController implements IComponentController { children: children, data: data, id: data.id, - }; + } } public cancelReorder = (): void => { - this.navigateAway(false); - }; + this.navigateAway(false) + } public saveReorder = (): void => { if (!this.isSaving) { - this.isSaving = true; - const results: ReorderGroupResult[] = []; - this.findNodesToUpdate(results); + this.isSaving = true + const results: ReorderGroupResult[] = [] + this.findNodesToUpdate(results) const elementsToUpdate: ElementObject[] = results.map((result) => { return { id: result.node.data.id, @@ -184,40 +184,40 @@ class ReorderGroupController implements IComponentController { _projectId: this.params.projectId, _refId: this.params.refId, type: result.node.data.type, - }; - }); + } + }) this.elementSvc .updateElements(elementsToUpdate, false) .then(() => { - this.cleanupCache(results); - this.navigateAway(true); + this.cleanupCache(results) + this.navigateAway(true) }) .catch(() => { - this.growl.error('Failed to save the grouping!'); + this.growl.error('Failed to save the grouping!') }) .finally(() => { - this.isSaving = false; - }); + this.isSaving = false + }) } else { - this.growl.info('please wait'); + this.growl.info('please wait') } - }; + } public findNodesToUpdate = (result: ReorderGroupResult[]): void => { // ignore root - const root = this.tree[0]; + const root = this.tree[0] root.children.forEach((node) => { // handle node change at the root level if ((node.type === 'group' && node.data._parentId) || (node.type === 'view' && node.data._groupId)) { result.push({ node: node, newOwnerId: 'holding_bin_' + this.params.projectId, - }); + }) } // handle change at lower level - helper(node, result); - }); + helper(node, result) + }) const helper = (node: ReorderGroupNode, result: ReorderGroupResult[]): void => { node.children.forEach((childNode) => { @@ -228,12 +228,12 @@ class ReorderGroupController implements IComponentController { result.push({ node: childNode, newOwnerId: node.data.id, - }); + }) } - helper(childNode, result); - }); - }; - }; + helper(childNode, result) + }) + } + } public cleanupCache = (results: ReorderGroupResult[]): void => { // update cache for documents list and groups list @@ -241,62 +241,62 @@ class ReorderGroupController implements IComponentController { 'documents', this.params.projectId, this.params.refId, - ]); + ]) const listOfGroupInCache = this.cacheSvc.get([ 'groups', this.params.projectId, this.params.refId, - ]); + ]) results.forEach((result) => { // for group or document that is moved to the root, _parentId for "group" and _groupId for "document" need to be set to undefined - const newOwnerId = result.newOwnerId.indexOf(this.params.projectId) !== -1 ? undefined : result.newOwnerId; + const newOwnerId = result.newOwnerId.indexOf(this.params.projectId) !== -1 ? undefined : result.newOwnerId if (result.node.type === 'group') { const cacheGroupOb = _.find(listOfGroupInCache, (groupOb) => { - return groupOb.id === result.node.data.id; - }); + return groupOb.id === result.node.data.id + }) if (cacheGroupOb) { - cacheGroupOb._parentId = newOwnerId; + cacheGroupOb._parentId = newOwnerId } } else if (result.node.type === 'view') { const cacheDocument = _.find(listOfDocInCache, (documentOb) => { - return documentOb.id === result.node.data.id; - }); + return documentOb.id === result.node.data.id + }) if (cacheDocument) { - cacheDocument._groupId = newOwnerId; + cacheDocument._groupId = newOwnerId } } - }); - }; + }) + } public comparator = (a: ReorderGroupNode, b: ReorderGroupNode): number => { if (a.type === b.type) { - return a.name.localeCompare(b.name); + return a.name.localeCompare(b.name) } else { if (a.type === 'group') { - return -1; + return -1 } else { - return 1; + return 1 } } - }; + } public sortRecursively = (nodes: ReorderGroupNode[]): void => { - nodes.sort(this.comparator); + nodes.sort(this.comparator) nodes.forEach((node) => { - this.sortRecursively(node.children); - }); - }; + this.sortRecursively(node.children) + }) + } public navigateAway = (reload: boolean): void => { - const curBranch = this.treeSvc.getSelectedBranch(); + const curBranch = this.treeSvc.getSelectedBranch() if (curBranch) { - const documentId = curBranch.type === 'group' ? 'site_' + curBranch.data.id + '_cover' : curBranch.data.id; - void this.$state.go('main.project.ref.portal.preview', { preview: documentId }, { reload: reload }); + const documentId = curBranch.type === 'group' ? 'site_' + curBranch.data.id + '_cover' : curBranch.data.id + void this.$state.go('main.project.ref.portal.preview', { preview: documentId }, { reload: reload }) } else { - void this.$state.go('main.project.ref.portal', {}, { reload: reload }); + void this.$state.go('main.project.ref.portal', {}, { reload: reload }) } - }; + } } const ReorderGroupComponent: VeComponentOptions = { @@ -333,6 +333,6 @@ const ReorderGroupComponent: VeComponentOptions = { mmsDocuments: '<', }, controller: ReorderGroupController, -}; +} -veApp.component(ReorderGroupComponent.selector, ReorderGroupComponent); +veApp.component(ReorderGroupComponent.selector, ReorderGroupComponent) diff --git a/src/ve-app/pane-center/reorder.component.ts b/src/ve-app/pane-center/reorder.component.ts index 1a1129372..990115b32 100644 --- a/src/ve-app/pane-center/reorder.component.ts +++ b/src/ve-app/pane-center/reorder.component.ts @@ -1,17 +1,17 @@ -import { StateService } from '@uirouter/angularjs'; -import angular, { IComponentController } from 'angular'; -import _ from 'lodash'; +import { StateService } from '@uirouter/angularjs' +import angular, { IComponentController } from 'angular' +import _ from 'lodash' -import { AppUtilsService } from '@ve-app/main/services'; -import { TreeService } from '@ve-components/trees'; -import { EventService } from '@ve-utils/core'; -import { ViewService, ElementService } from '@ve-utils/mms-api-client'; +import { AppUtilsService } from '@ve-app/main/services' +import { TreeService } from '@ve-components/trees' +import { EventService } from '@ve-utils/core' +import { ViewService, ElementService } from '@ve-utils/mms-api-client' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' -import { VeComponentOptions, VePromise } from '@ve-types/angular'; -import { DocumentObject, ViewObject } from '@ve-types/mms'; -import { AngularUITree, TreeBranch, VeTreeNodeScope, View2NodeMap } from '@ve-types/tree'; +import { VeComponentOptions, VePromise } from '@ve-types/angular' +import { DocumentObject, ViewObject } from '@ve-types/mms' +import { AngularUITree, TreeBranch, VeTreeNodeScope, View2NodeMap } from '@ve-types/tree' /* Controllers */ /** @@ -28,20 +28,20 @@ import { AngularUITree, TreeBranch, VeTreeNodeScope, View2NodeMap } from '@ve-ty */ class ReorderController implements IComponentController { //bindings - private mmsDocument: VePromise; + private mmsDocument: VePromise //local - protected doc: ViewObject; - private viewIds2node: View2NodeMap = {}; - private origViews: { [key: string]: ViewObject } = {}; - public tree: TreeBranch[]; - public treeOptions: AngularUITree.ICallbacks; - private seenViewIds: View2NodeMap = {}; - public saveClass: string = ''; - private saving: boolean = false; + protected doc: ViewObject + private viewIds2node: View2NodeMap = {} + private origViews: { [key: string]: ViewObject } = {} + public tree: TreeBranch[] + public treeOptions: AngularUITree.ICallbacks + private seenViewIds: View2NodeMap = {} + public saveClass: string = '' + private saving: boolean = false //injectables - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] static $inject = [ '$state', @@ -53,7 +53,7 @@ class ReorderController implements IComponentController { 'AppUtilsService', 'TreeService', 'EventService', - ]; + ] constructor( private $state: StateService, @@ -68,12 +68,12 @@ class ReorderController implements IComponentController { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) this.mmsDocument.then( (doc) => { - this.doc = doc; - const name = this.doc.name ? this.doc.name : this.doc.id; + this.doc = doc + const name = this.doc.name ? this.doc.name : this.doc.id this.viewIds2node[this.doc.id] = { label: name, @@ -81,7 +81,7 @@ class ReorderController implements IComponentController { data: this.doc, aggr: 'composite', children: [], - }; + } this.viewSvc .handleChildViews( @@ -96,43 +96,43 @@ class ReorderController implements IComponentController { ) .then( (docNode: TreeBranch) => { - let num = 1; + let num = 1 docNode.children.forEach((node) => { - this.updateNumber(node, `${num}`, 'old'); - this.updateNumber(node, `${num}`, 'new'); - num++; - }); - this.tree = [docNode]; + this.updateNumber(node, `${num}`, 'old') + this.updateNumber(node, `${num}`, 'new') + num++ + }) + this.tree = [docNode] }, (reason) => { - this.growl.error('Error Getting Child Views: ' + reason.message); + this.growl.error('Error Getting Child Views: ' + reason.message) } - ); + ) }, (reason) => { - this.growl.error('Error Getting Child Views: ' + reason.message); + this.growl.error('Error Getting Child Views: ' + reason.message) } - ); + ) this.subs.push( this.eventSvc.$on('foobar', () => { - const root = this.tree; - console.log(root); + const root = this.tree + console.log(root) }) - ); + ) this.treeOptions = { dropped: (e): void => { void this.$timeout(() => { for (let i = 0; i < this.tree.length; i++) { - const root = this.tree[i]; - root.new = ''; - let num = 1; + const root = this.tree[i] + root.new = '' + let num = 1 for (let j = 0; j < root.children.length; j++) { - this.updateNumber(root.children[j], `${num}`, 'new'); - num++; + this.updateNumber(root.children[j], `${num}`, 'new') + num++ } } - }, 1); + }, 1) }, // dragStop: (e) => { // for (let i = 0; i < this.tree.length; i++) { @@ -149,23 +149,23 @@ class ReorderController implements IComponentController { //Do Nothing }, accept: (sourceNodeScope: VeTreeNodeScope, destNodeScope: VeTreeNodeScope, destIndex): boolean => { - if (destNodeScope.$element.hasClass('root')) return false; //don't allow moving to outside doc - return destNodeScope.node.aggr != 'none'; + if (destNodeScope.$element.hasClass('root')) return false //don't allow moving to outside doc + return destNodeScope.node.aggr != 'none' }, - }; + } } public updateNumber = (node: TreeBranch, curSection: string, key: string): void => { - node[key] = curSection; - let num = 1; + node[key] = curSection + let num = 1 for (let i = 0; i < node.children.length; i++) { - this.updateNumber(node.children[i], `${curSection}.${num}`, key); - num++; + this.updateNumber(node.children[i], `${curSection}.${num}`, key) + num++ } - }; + } public handleSingleView = (v: ViewObject, aggr: string, propId: string): TreeBranch => { - let curNode: TreeBranch = this.viewIds2node[v.id]; + let curNode: TreeBranch = this.viewIds2node[v.id] if (!curNode) { curNode = { label: v.name ? v.name : v.id, @@ -174,44 +174,44 @@ class ReorderController implements IComponentController { propertyId: propId, type: v.type, children: [], - }; - this.viewIds2node[v.id] = curNode; + } + this.viewIds2node[v.id] = curNode } - this.origViews[v.id] = v; - return curNode; - }; + this.origViews[v.id] = v + return curNode + } public handleChildren = (curNode: TreeBranch, childNodes: TreeBranch[]): void => { - const newChildNodes: TreeBranch[] = []; + const newChildNodes: TreeBranch[] = [] for (let i = 0; i < childNodes.length; i++) { - const node: TreeBranch = childNodes[i]; + const node: TreeBranch = childNodes[i] if (this.seenViewIds[node.data.id]) { - return; + return } - this.seenViewIds[node.data.id] = node; - newChildNodes.push(node); + this.seenViewIds[node.data.id] = node + newChildNodes.push(node) } - curNode.children.push(...newChildNodes); - }; + curNode.children.push(...newChildNodes) + } public save = (): void => { if (this.saving) { - this.growl.info('please wait'); - return; + this.growl.info('please wait') + return } if (this.tree.length > 1 || this.tree[0].data.id !== this.doc.id) { - this.growl.error('Views cannot be re-ordered outside the context of the current document.'); - return; + this.growl.error('Views cannot be re-ordered outside the context of the current document.') + return } - this.saving = true; - this.saveClass = 'fa fa-spin fa-spinner'; - const toSave: ViewObject[] = []; + this.saving = true + this.saveClass = 'fa fa-spin fa-spinner' + const toSave: ViewObject[] = [] for (const [id, node] of Object.entries(this.viewIds2node)) { if (node.aggr == 'none') { //cannot process views whose aggr is none since their children are not shown - return; + return } - const childViews: ViewObject[] = []; + const childViews: ViewObject[] = [] for (let i = 0; i < node.children.length; i++) { childViews.push({ id: node.children[i].data.id, @@ -220,9 +220,9 @@ class ReorderController implements IComponentController { _projectId: node.data._projectId, _refId: node.data._refId, type: node.data.type, - }); + }) } - const orig = this.origViews[id]; + const orig = this.origViews[id] if ( ((!orig._childViews || orig._childViews.length === 0) && childViews.length > 0) || (orig._childViews && !_.isEqual(orig._childViews, childViews)) @@ -234,55 +234,55 @@ class ReorderController implements IComponentController { _projectId: orig._projectId, _refId: orig._refId, type: orig.type, - }); + }) } } if (toSave.length === 0) { - this.growl.info('No changes to save!'); - this.saving = false; - this.saveClass = ''; - return; + this.growl.info('No changes to save!') + this.saving = false + this.saveClass = '' + return } this.elementSvc .updateElements(toSave, true) .then( () => { - this.growl.success('Reorder Successful'); - this.navigate(true); + this.growl.success('Reorder Successful') + this.navigate(true) }, (response) => { - const reason = response.data.failedRequests[0]; - const errorMessage = reason.message; + const reason = response.data.failedRequests[0] + const errorMessage = reason.message if (reason.status === 409) { - this.growl.error("There's a conflict in the views you're trying to change!"); + this.growl.error("There's a conflict in the views you're trying to change!") } else { - this.growl.error(errorMessage); + this.growl.error(errorMessage) } } ) .finally(() => { - this.saveClass = ''; - this.saving = false; - }); - }; + this.saveClass = '' + this.saving = false + }) + } public cancel = (): void => { - this.navigate(false); - }; + this.navigate(false) + } public navigate = (reload: boolean): void => { - const curBranch = this.treeSvc.getSelectedBranch(); + const curBranch = this.treeSvc.getSelectedBranch() if (!curBranch) { - void this.$state.go('main.project.ref.view.present', {}, { reload: true }); + void this.$state.go('main.project.ref.view.present', {}, { reload: true }) } else { - let goToId: string = curBranch.data.id; + let goToId: string = curBranch.data.id if (curBranch.type !== 'section' && curBranch.type !== 'view') { - goToId = curBranch.viewId ? curBranch.viewId : ''; + goToId = curBranch.viewId ? curBranch.viewId : '' } - void this.$state.go('main.project.ref.view.present', { viewId: goToId }, { reload: reload }); + void this.$state.go('main.project.ref.view.present', { viewId: goToId }, { reload: reload }) } - }; + } } const ReorderComponent: VeComponentOptions = { @@ -315,6 +315,6 @@ const ReorderComponent: VeComponentOptions = { mmsDocument: '<', }, controller: ReorderController, -}; +} -veApp.component(ReorderComponent.selector, ReorderComponent); +veApp.component(ReorderComponent.selector, ReorderComponent) diff --git a/src/ve-app/pane-center/search.component.ts b/src/ve-app/pane-center/search.component.ts index c59025b28..ebe59ffa5 100644 --- a/src/ve-app/pane-center/search.component.ts +++ b/src/ve-app/pane-center/search.component.ts @@ -1,23 +1,23 @@ -import { StateService } from '@uirouter/angularjs'; +import { StateService } from '@uirouter/angularjs' -import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service'; -import { veCoreEvents } from '@ve-core/events'; -import { RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service' +import { veCoreEvents } from '@ve-core/events' +import { RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' -import { VeComponentOptions } from '@ve-types/angular'; -import { ElementObject, ParamsObject } from '@ve-types/mms'; -import { VeSearchOptions } from '@ve-types/view-editor'; +import { VeComponentOptions } from '@ve-types/angular' +import { ElementObject, ParamsObject } from '@ve-types/mms' +import { VeSearchOptions } from '@ve-types/view-editor' class SearchController { - params: ParamsObject; + params: ParamsObject - searchContentLoading: boolean = true; - searchOptions: VeSearchOptions; + searchContentLoading: boolean = true + searchOptions: VeSearchOptions - static $inject = ['$state', 'ContentWindowService', 'RootScopeService', 'EventService']; + static $inject = ['$state', 'ContentWindowService', 'RootScopeService', 'EventService'] constructor( private $state: StateService, @@ -27,10 +27,10 @@ class SearchController { ) {} $onInit(): void { - this.searchContentLoading = false; + this.searchContentLoading = false - this.contentWindowSvc.toggleLeftPane(true); - this.rootScopeSvc.veHideLeft(true); + this.contentWindowSvc.toggleLeftPane(true) + this.rootScopeSvc.veHideLeft(true) this.searchOptions = { emptyDocTxt: 'This field is empty.', @@ -44,10 +44,10 @@ class SearchController { projectId: elementOb._projectId, refId: elementOb._refId, commitId: 'latest', - }; - this.eventSvc.$broadcast('element.selected', data); + } + this.eventSvc.$broadcast('element.selected', data) if (typeof this.rootScopeSvc.rightPaneClosed() === 'boolean' && this.rootScopeSvc.rightPaneClosed()) - this.eventSvc.$broadcast('right-pane.toggle', false); + this.eventSvc.$broadcast('right-pane.toggle', false) }, relatedCallback: (doc, view, elem): void => { //siteId, documentId, viewId) { @@ -57,9 +57,9 @@ class SearchController { viewId: view.id, refId: doc._refId, keywords: undefined, - }); + }) }, - }; + } } } @@ -81,6 +81,6 @@ const SearchComponent: VeComponentOptions = { field: '<', }, controller: SearchController, -}; +} -veApp.component(SearchComponent.selector, SearchComponent); +veApp.component(SearchComponent.selector, SearchComponent) diff --git a/src/ve-app/pane-center/services/ContentWindow.service.ts b/src/ve-app/pane-center/services/ContentWindow.service.ts index 37febfe3f..df302e876 100644 --- a/src/ve-app/pane-center/services/ContentWindow.service.ts +++ b/src/ve-app/pane-center/services/ContentWindow.service.ts @@ -1,21 +1,21 @@ -import { RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' export class ContentWindowService { - static $inject = ['RootScopeService', 'EventService']; + static $inject = ['RootScopeService', 'EventService'] constructor(private rootScopeSvc: RootScopeService, private eventSvc: EventService) {} public toggleLeftPane = (closed): void => { if (closed && !this.rootScopeSvc.leftPaneClosed()) { - this.eventSvc.$broadcast('left-pane.toggle', true); + this.eventSvc.$broadcast('left-pane.toggle', true) } if (!closed && this.rootScopeSvc.leftPaneClosed()) { - this.eventSvc.$broadcast('left-pane.toggle', false); + this.eventSvc.$broadcast('left-pane.toggle', false) } - }; + } } -veApp.service('ContentWindowService', ContentWindowService); +veApp.service('ContentWindowService', ContentWindowService) diff --git a/src/ve-app/pane-center/slideshow.component.ts b/src/ve-app/pane-center/slideshow.component.ts index 182e11318..bded4d1b1 100644 --- a/src/ve-app/pane-center/slideshow.component.ts +++ b/src/ve-app/pane-center/slideshow.component.ts @@ -1,19 +1,19 @@ -import { HookResult, Ng1Controller, StateService, UIRouterGlobals } from '@uirouter/angularjs'; -import { Transition } from '@uirouter/core'; - -import { AppUtilsService, ResolveService } from '@ve-app/main/services'; -import { pane_center_buttons } from '@ve-app/pane-center/pane-center-buttons.config'; -import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service'; -import { TreeService } from '@ve-components/trees'; -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; -import { veCoreEvents } from '@ve-core/events'; -import { RootScopeService, ShortUrlService, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { PermissionsService, URLService, ViewApi } from '@ve-utils/mms-api-client'; - -import { veApp } from '@ve-app'; - -import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { HookResult, Ng1Controller, StateService, UIRouterGlobals } from '@uirouter/angularjs' +import { Transition } from '@uirouter/core' + +import { AppUtilsService, ResolveService } from '@ve-app/main/services' +import { pane_center_buttons } from '@ve-app/pane-center/pane-center-buttons.config' +import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service' +import { TreeService } from '@ve-components/trees' +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' +import { veCoreEvents } from '@ve-core/events' +import { RootScopeService, ShortUrlService, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { PermissionsService, URLService, ViewApi } from '@ve-utils/mms-api-client' + +import { veApp } from '@ve-app' + +import { VeComponentOptions, VeQService } from '@ve-types/angular' import { DocumentObject, ElementObject, @@ -22,7 +22,7 @@ import { ProjectObject, RefObject, ViewObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' /** * Note: This controller is intended for navigating between 'views' and 'sections' only. If you wish to navigate between @@ -30,38 +30,38 @@ import { */ class SlideshowController implements angular.IComponentController, Ng1Controller { //Bindings - mmsParams: ParamsObject; - mmsProject: ProjectObject; - mmsRef: RefObject; - mmsGroup: GroupObject; - mmsDocument: DocumentObject; - mmsView: ViewObject; - - subs: Rx.IDisposable[]; - vidLink: boolean; - viewContentLoading: boolean; - init: boolean = false; - - public bbApi: ButtonBarApi; - bbId = 'view-ctrl'; - bars: string[] = []; + mmsParams: ParamsObject + mmsProject: ProjectObject + mmsRef: RefObject + mmsGroup: GroupObject + mmsDocument: DocumentObject + mmsView: ViewObject + + subs: Rx.IDisposable[] + vidLink: boolean + viewContentLoading: boolean + init: boolean = false + + public bbApi: ButtonBarApi + bbId = 'view-ctrl' + bars: string[] = [] comments: { - count: number; - lastCommented: string; - lastCommentedBy: string; - map: object; + count: number + lastCommented: string + lastCommentedBy: string + map: object } = { count: 0, lastCommented: null, lastCommentedBy: '', map: {}, - }; - dynamicPopover: { templateUrl: string; title: string }; - shortUrl: string; - viewApi: ViewApi; - number: string; - private viewId: string; - private params: ParamsObject; + } + dynamicPopover: { templateUrl: string; title: string } + shortUrl: string + viewApi: ViewApi + number: string + private viewId: string + private params: ParamsObject static $inject = [ '$q', @@ -86,7 +86,7 @@ class SlideshowController implements angular.IComponentController, Ng1Controller 'TreeService', 'EventService', 'ButtonBarService', - ]; + ] constructor( public $q: VeQService, @@ -114,24 +114,24 @@ class SlideshowController implements angular.IComponentController, Ng1Controller ) {} $onInit(): void { - this.params = this.mmsParams; - this.rootScopeSvc.veFullDocMode(false); - this.rootScopeSvc.veHideLeft(false); - this.rootScopeSvc.veHideRight(false); - this.eventSvc.$init(this); + this.params = this.mmsParams + this.rootScopeSvc.veFullDocMode(false) + this.rootScopeSvc.veHideLeft(false) + this.rootScopeSvc.veHideRight(false) + this.eventSvc.$init(this) - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, pane_center_buttons); + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, pane_center_buttons) //Init/Reset Tree Updated Subject - this.eventSvc.resolve(TreeService.events.UPDATED, false); + this.eventSvc.resolve(TreeService.events.UPDATED, false) this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEVIEWCONTENTLOADING, (newValue) => { - this.viewContentLoading = newValue; + this.viewContentLoading = newValue }) - ); + ) - this.initView(); + this.initView() this.subs.push( this.eventSvc.$on(this.bbId, (data) => { @@ -139,135 +139,114 @@ class SlideshowController implements angular.IComponentController, Ng1Controller this.bbApi.toggleButton( 'show-comments', this.rootScopeSvc.veCommentsOn(!this.rootScopeSvc.veCommentsOn()) - ); - return; + ) + return } else if (data.clicked === 'show-numbering') { this.bbApi.toggleButton( 'show-numbering', this.rootScopeSvc.veNumberingOn(!this.rootScopeSvc.veNumberingOn()) - ); - return; + ) + return } else if (data.clicked === 'show-elements') { this.bbApi.toggleButton( 'show-elements', this.rootScopeSvc.veElementsOn(!this.rootScopeSvc.veElementsOn()) - ); + ) if (!this.rootScopeSvc.veElementsOn() && this.rootScopeSvc.veEditMode()) { - this.bbApi.toggleButton('show-edits', false); - this.rootScopeSvc.veEditMode(false); + this.bbApi.toggleButton('show-edits', false) + this.rootScopeSvc.veEditMode(false) } - return; + return } else if (data.clicked === 'show-edits') { - this.bbApi.toggleButton( - 'show-edits', - this.rootScopeSvc.veEditMode(!this.rootScopeSvc.veEditMode()) - ); + this.bbApi.toggleButton('show-edits', this.rootScopeSvc.veEditMode(!this.rootScopeSvc.veEditMode())) if (this.rootScopeSvc.veElementsOn() !== this.rootScopeSvc.veEditMode()) { - this.bbApi.toggleButton('show-elements', this.rootScopeSvc.veEditMode()); - this.rootScopeSvc.veElementsOn(this.rootScopeSvc.veEditMode()); + this.bbApi.toggleButton('show-elements', this.rootScopeSvc.veEditMode()) + this.rootScopeSvc.veElementsOn(this.rootScopeSvc.veEditMode()) } - return; + return } else if (data.clicked === 'center-previous') { this.treeSvc.getPrevBranch(this.treeSvc.getSelectedBranch(), ['view', 'section']).then( (prev) => { - this.bbApi.toggleButtonSpinner('center-previous'); + this.bbApi.toggleButtonSpinner('center-previous') this.treeSvc.selectBranch(prev).catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); - this.bbApi.toggleButtonSpinner('center-previous'); + this.growl.error(TreeService.treeError(reason)) + }) + this.bbApi.toggleButtonSpinner('center-previous') }, (reason) => { - if (reason.status === 200) this.growl.info(reason.message); - else this.growl.error(reason.message); + if (reason.status === 200) this.growl.info(reason.message) + else this.growl.error(reason.message) } - ); - return; + ) + return } else if (data.clicked === 'center-next') { this.treeSvc.getNextBranch(this.treeSvc.getSelectedBranch(), ['view', 'section']).then( (next) => { - this.bbApi.toggleButtonSpinner('center-next'); + this.bbApi.toggleButtonSpinner('center-next') this.treeSvc.selectBranch(next).catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); - this.bbApi.toggleButtonSpinner('center-next'); + this.growl.error(TreeService.treeError(reason)) + }) + this.bbApi.toggleButtonSpinner('center-next') }, (reason) => { - if (reason.status === 200) this.growl.info(reason.message); - else this.growl.error(reason.message); + if (reason.status === 200) this.growl.info(reason.message) + else this.growl.error(reason.message) } - ); - return; + ) + return } else if (data.clicked === 'convert-pdf') { - if (this.isPageLoading()) return; - void this.appUtilsSvc.printModal( - angular.element('#print-div'), - this.mmsView, - this.mmsRef, - false, - 3 - ); - return; + if (this.isPageLoading()) return + void this.appUtilsSvc.printModal(angular.element('#print-div'), this.mmsView, this.mmsRef, false, 3) + return } else if (data.clicked === 'print') { - if (this.isPageLoading()) return; - void this.appUtilsSvc.printModal( - angular.element('#print-div'), - this.mmsView, - this.mmsRef, - false, - 1 - ); - return; + if (this.isPageLoading()) return + void this.appUtilsSvc.printModal(angular.element('#print-div'), this.mmsView, this.mmsRef, false, 1) + return } else if (data.clicked === 'word') { - if (this.isPageLoading()) return; - void this.appUtilsSvc.printModal( - angular.element('#print-div'), - this.mmsView, - this.mmsRef, - false, - 2 - ); - return; + if (this.isPageLoading()) return + void this.appUtilsSvc.printModal(angular.element('#print-div'), this.mmsView, this.mmsRef, false, 2) + return } else if (data.clicked === 'tabletocsv') { - if (this.isPageLoading()) return; - this.appUtilsSvc.tableToCsv(angular.element('#print-div'), false); - return; + if (this.isPageLoading()) return + this.appUtilsSvc.tableToCsv(angular.element('#print-div'), false) + return } else if (data.clicked === 'refresh-numbering') { // TODO - return; + return } }) - ); + ) } uiOnParamsChanged(newValues: ParamsObject, $transition$: Transition): void { if (newValues.viewId && newValues.viewId !== this.params.viewId) - this.initView($transition$.params() as ParamsObject); + this.initView($transition$.params() as ParamsObject) } uiCanExit(transition: Transition): HookResult { //Do nothing } initView = (params?: ParamsObject): void => { - this.rootScopeSvc.veViewContentLoading(true); + this.rootScopeSvc.veViewContentLoading(true) if (params) { - this.params = params; - this.viewId = params.viewId; + this.params = params + this.viewId = params.viewId } else if (this.mmsDocument || this.mmsView) { - this.viewId = this.mmsView ? this.mmsView.id : this.mmsDocument.id; + this.viewId = this.mmsView ? this.mmsView.id : this.mmsDocument.id } else { - return; + return } - this.rootScopeSvc.veViewContentLoading(false); + this.rootScopeSvc.veViewContentLoading(false) - this.vidLink = false; //whether to have go to document link + this.vidLink = false //whether to have go to document link if ( this.$state.includes('main.project.ref.portal.preview') && this.mmsDocument && this.mmsDocument.id.indexOf('_cover') < 0 ) { - this.vidLink = true; + this.vidLink = true } this.shortUrl = this.shortUrlSvc.getShortUrl({ @@ -276,7 +255,7 @@ class SlideshowController implements angular.IComponentController, Ng1Controller viewId: this.params.viewId && !this.params.documentId.endsWith('_cover') ? this.params.viewId : '', projectId: this.params.projectId, refId: this.params.refId, - }); + }) if (this.$state.includes('main.project.ref')) { const data = { @@ -287,52 +266,52 @@ class SlideshowController implements angular.IComponentController, Ng1Controller refId: this.mmsRef.id, refType: this.mmsRef.type, refresh: this.$uiRouterGlobals.transition.from().name === '', - }; - this.eventSvc.$broadcast('view.selected', data); + } + this.eventSvc.$broadcast('view.selected', data) } - this.contentWindowSvc.toggleLeftPane(false); + this.contentWindowSvc.toggleLeftPane(false) - this.rootScopeSvc.veNumberingOn(true); + this.rootScopeSvc.veNumberingOn(true) // Share URL button settings - this.dynamicPopover = this.shortUrlSvc.dynamicPopover; + this.dynamicPopover = this.shortUrlSvc.dynamicPopover this.viewApi = { elementClicked: this.elementClicked, elementTranscluded: this.elementTranscluded, - }; - }; + } + } $onDestroy(): void { - this.eventSvc.$destroy(this.subs); - this.buttonBarSvc.destroy(this.bbId); + this.eventSvc.$destroy(this.subs) + this.buttonBarSvc.destroy(this.bbId) } public bbInit = (api: ButtonBarApi): void => { if (this.mmsRef.type === 'Branch') { - api.addButton(this.buttonBarSvc.getButtonBarButton('show-edits')); + api.addButton(this.buttonBarSvc.getButtonBarButton('show-edits')) api.setPermission( 'show-edits', this.permissionsSvc.hasBranchEditPermission(this.mmsProject.id, this.mmsRef.id) - ); - api.toggleButton('show-edits', this.rootScopeSvc.veEditMode()); + ) + api.toggleButton('show-edits', this.rootScopeSvc.veEditMode()) this.hotkeys.bindTo(this.$scope).add({ combo: 'alt+d', description: 'toggle edit mode', callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-edits', - }); + }) }, - }); + }) } - api.addButton(this.buttonBarSvc.getButtonBarButton('show-elements')); - api.toggleButton('show-elements', this.rootScopeSvc.veElementsOn()); - api.addButton(this.buttonBarSvc.getButtonBarButton('show-comments')); - api.toggleButton('show-comments', this.rootScopeSvc.veCommentsOn()); - api.addButton(this.buttonBarSvc.getButtonBarButton('show-numbering')); - api.toggleButton('show-numbering', this.rootScopeSvc.veNumberingOn()); + api.addButton(this.buttonBarSvc.getButtonBarButton('show-elements')) + api.toggleButton('show-elements', this.rootScopeSvc.veElementsOn()) + api.addButton(this.buttonBarSvc.getButtonBarButton('show-comments')) + api.toggleButton('show-comments', this.rootScopeSvc.veCommentsOn()) + api.addButton(this.buttonBarSvc.getButtonBarButton('show-numbering')) + api.toggleButton('show-numbering', this.rootScopeSvc.veNumberingOn()) // Set hotkeys for toolbar this.hotkeys @@ -343,7 +322,7 @@ class SlideshowController implements angular.IComponentController, Ng1Controller callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-comments', - }); + }) }, }) .add({ @@ -352,16 +331,16 @@ class SlideshowController implements angular.IComponentController, Ng1Controller callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-elements', - }); + }) }, - }); + }) if (this.$state.includes('**.present.**')) { - api.addButton(this.buttonBarSvc.getButtonBarButton('refresh-numbering')); - api.addButton(this.buttonBarSvc.getButtonBarButton('print')); - api.addButton(this.buttonBarSvc.getButtonBarButton('export')); - api.addButton(this.buttonBarSvc.getButtonBarButton('center-previous')); - api.addButton(this.buttonBarSvc.getButtonBarButton('center-next')); + api.addButton(this.buttonBarSvc.getButtonBarButton('refresh-numbering')) + api.addButton(this.buttonBarSvc.getButtonBarButton('print')) + api.addButton(this.buttonBarSvc.getButtonBarButton('export')) + api.addButton(this.buttonBarSvc.getButtonBarButton('center-previous')) + api.addButton(this.buttonBarSvc.getButtonBarButton('center-next')) // Set hotkeys for toolbar this.hotkeys .bindTo(this.$scope) @@ -371,7 +350,7 @@ class SlideshowController implements angular.IComponentController, Ng1Controller callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'center-next', - }); + }) }, }) .add({ @@ -380,35 +359,35 @@ class SlideshowController implements angular.IComponentController, Ng1Controller callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'center-previous', - }); + }) }, - }); + }) } else { - api.addButton(this.buttonBarSvc.getButtonBarButton('export')); + api.addButton(this.buttonBarSvc.getButtonBarButton('export')) } - }; + } public copyToClipboard = ($event: JQuery.ClickEvent): void => { this.shortUrlSvc.copyToClipboard(this.$element, $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }); + this.growl.info('Copied to clipboard!', { ttl: 2000 }) }, (err) => { - this.growl.error('Unable to copy: ' + err.message); + this.growl.error('Unable to copy: ' + err.message) } - ); - }; + ) + } public elementTranscluded = (elementOb: ElementObject, type): void => { if (type === 'Comment' && !this.comments.map.hasOwnProperty(elementOb.id)) { - this.comments.map[elementOb.id] = elementOb; - this.comments.count++; + this.comments.map[elementOb.id] = elementOb + this.comments.count++ if (elementOb._modified > this.comments.lastCommented) { - this.comments.lastCommented = elementOb._modified; - this.comments.lastCommentedBy = elementOb._modifier; + this.comments.lastCommented = elementOb._modified + this.comments.lastCommentedBy = elementOb._modifier } } - }; + } public elementClicked = (elementOb: ElementObject): void => { const data = { @@ -417,17 +396,17 @@ class SlideshowController implements angular.IComponentController, Ng1Controller projectId: elementOb._projectId, refId: elementOb._refId, commitId: 'latest', - }; - this.eventSvc.$broadcast('element.selected', data); - }; + } + this.eventSvc.$broadcast('element.selected', data) + } public isPageLoading = (): boolean => { if (this.$element.find('.isLoading').length > 0) { - this.growl.warning('Still loading!'); - return true; + this.growl.warning('Still loading!') + return true } - return false; - }; + return false + } } /* Controllers */ @@ -485,6 +464,6 @@ const SlideshowComponent: VeComponentOptions = { mmsView: '<', }, controller: SlideshowController, -}; +} -veApp.component(SlideshowComponent.selector, SlideshowComponent); +veApp.component(SlideshowComponent.selector, SlideshowComponent) diff --git a/src/ve-app/pane-left/index.ts b/src/ve-app/pane-left/index.ts index 054a9a58a..cd20e6f1d 100644 --- a/src/ve-app/pane-left/index.ts +++ b/src/ve-app/pane-left/index.ts @@ -1,2 +1,2 @@ -import './left-pane.component'; -import './left-toolbar.component'; +import './left-pane.component' +import './left-toolbar.component' diff --git a/src/ve-app/pane-left/left-buttons.config.ts b/src/ve-app/pane-left/left-buttons.config.ts index 3339eb147..828562d07 100644 --- a/src/ve-app/pane-left/left-buttons.config.ts +++ b/src/ve-app/pane-left/left-buttons.config.ts @@ -1,5 +1,5 @@ -import { IButtonBarButton } from '@ve-core/button-bar'; -import { IToolBarButton } from '@ve-core/toolbar'; +import { IButtonBarButton } from '@ve-core/button-bar' +import { IToolBarButton } from '@ve-core/toolbar' export const left_default_toolbar: IToolBarButton[] = [ { @@ -63,9 +63,9 @@ export const left_default_toolbar: IToolBarButton[] = [ spinner: false, enabledFor: ['**.present.**'], }, -]; +] -export const left_dynamic_toolbar: IToolBarButton[] = []; +export const left_dynamic_toolbar: IToolBarButton[] = [] export const left_default_buttons: IButtonBarButton[] = [ { @@ -187,4 +187,4 @@ export const left_default_buttons: IButtonBarButton[] = [ }, enabledFor: ['**.present.**'], }, -]; +] diff --git a/src/ve-app/pane-left/left-pane.component.ts b/src/ve-app/pane-left/left-pane.component.ts index 3a8e83966..2ac2d8aea 100644 --- a/src/ve-app/pane-left/left-pane.component.ts +++ b/src/ve-app/pane-left/left-pane.component.ts @@ -1,23 +1,23 @@ -import { IPane } from '@openmbee/pane-layout'; -import { IPaneManagerService } from '@openmbee/pane-layout/lib/PaneManagerService'; -import { StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs'; - -import { veAppEvents } from '@ve-app/events'; -import { AppUtilsService } from '@ve-app/main/services'; -import { TreeService } from '@ve-components/trees'; -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; -import { veCoreEvents } from '@ve-core/events'; -import { ConfirmDeleteModalResolveFn } from '@ve-core/modals'; -import { RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { ApiService, ElementService, PermissionsService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; - -import { veApp } from '@ve-app'; - -import { left_default_buttons } from './left-buttons.config'; - -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { IPane } from '@openmbee/pane-layout' +import { IPaneManagerService } from '@openmbee/pane-layout/lib/PaneManagerService' +import { StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs' + +import { veAppEvents } from '@ve-app/events' +import { AppUtilsService } from '@ve-app/main/services' +import { TreeService } from '@ve-components/trees' +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' +import { veCoreEvents } from '@ve-core/events' +import { ConfirmDeleteModalResolveFn } from '@ve-core/modals' +import { RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { ApiService, ElementService, PermissionsService, ProjectService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' + +import { veApp } from '@ve-app' + +import { left_default_buttons } from './left-buttons.config' + +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' import { ElementObject, ElementsRequest, @@ -28,37 +28,37 @@ import { RefObject, RefsResponse, ViewObject, -} from '@ve-types/mms'; -import { TreeApi, TreeBranch } from '@ve-types/tree'; -import { VeModalService } from '@ve-types/view-editor'; +} from '@ve-types/mms' +import { TreeApi, TreeBranch } from '@ve-types/tree' +import { VeModalService } from '@ve-types/view-editor' class LeftPaneController implements angular.IComponentController { //Scope - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] - private $pane: IPane; + private $pane: IPane - public bbApi: ButtonBarApi; - public bbSize: string; - public bars: string[]; - private headerSize: string = '83px'; - protected squishSize: number = 250; + public bbApi: ButtonBarApi + public bbSize: string + public bars: string[] + private headerSize: string = '83px' + protected squishSize: number = 250 //Bindings - private mmsProject: ProjectObject; - private mmsRef: RefObject; - private mmsRoot: ElementObject; + private mmsProject: ProjectObject + private mmsRef: RefObject + private mmsRoot: ElementObject //Tree Api - private treeApi: TreeApi; + private treeApi: TreeApi //Local Variables - toolbarId: string = 'left-toolbar'; - buttonId: string = 'tree-button-bar'; + toolbarId: string = 'left-toolbar' + buttonId: string = 'tree-button-bar' - schema = 'cameo'; - filterInputPlaceholder = 'Filter'; - treeFilter = ''; + schema = 'cameo' + filterInputPlaceholder = 'Filter' + treeFilter = '' static $inject = [ '$q', @@ -86,7 +86,7 @@ class LeftPaneController implements angular.IComponentController { 'RootScopeService', 'EventService', 'ButtonBarService', - ]; + ] constructor( private $q: VeQService, @@ -118,75 +118,75 @@ class LeftPaneController implements angular.IComponentController { $onInit(): void { //Init/Reset Tree Updated Subject - this.eventSvc.resolve(TreeService.events.UPDATED, false); + this.eventSvc.resolve(TreeService.events.UPDATED, false) - this.transitionCallback(); + this.transitionCallback() - this.eventSvc.$init(this); + this.eventSvc.$init(this) - this.bbSize = '83px'; + this.bbSize = '83px' this.$transitions.onSuccess({}, () => { - this.transitionCallback(); - }); + this.transitionCallback() + }) //Init Pane Toggle Controls - this.rootScopeSvc.leftPaneClosed(this.$pane.closed); + this.rootScopeSvc.leftPaneClosed(this.$pane.closed) this.subs.push( this.$pane.$toggled.subscribe(() => { - this.rootScopeSvc.leftPaneClosed(this.$pane.closed); + this.rootScopeSvc.leftPaneClosed(this.$pane.closed) }) - ); + ) this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.LEFTPANECLOSED, (paneClosed) => { if (paneClosed !== this.$pane.closed) { - this.$pane.toggle(); + this.$pane.toggle() } }) - ); + ) // Start listening to change events this.subs.push( this.eventSvc.$on('view.selected', this.changeData), this.eventSvc.$on('view.deleted', (data) => { - let goto = '^.currentState'; - let documentId = this.treeApi.rootId; - let viewId: string; + let goto = '^.currentState' + let documentId = this.treeApi.rootId + let viewId: string if (this.$state.includes('**.portal.**')) { if (data.parentBranch) { - documentId = data.parentBranch.data.id; + documentId = data.parentBranch.data.id } else { - goto = 'main.project.ref.portal'; - documentId = null; + goto = 'main.project.ref.portal' + documentId = null } } else if (this.$state.includes('**.present.**')) { if (data.prevBranch) { - viewId = data.prevBranch.viewId ? data.prevBranch.viewId : data.prevBranch.data.id; + viewId = data.prevBranch.viewId ? data.prevBranch.viewId : data.prevBranch.data.id } else if (data.parentBranch) { - viewId = data.parentBranch.viewId ? data.parentBranch.viewId : data.parentBranch.data.id; + viewId = data.parentBranch.viewId ? data.parentBranch.viewId : data.parentBranch.data.id } } void this.$state.go(goto, { documentId, viewId, search: undefined, - }); + }) }), this.eventSvc.$on('presentation.deleted', (data) => { this.treeSvc.getBranch(data).then( (branch) => { this.treeSvc.removeBranch(branch).catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) }, () => { - this.growl.error('Deleted branch not found'); + this.growl.error('Deleted branch not found') } - ); + ) }) - ); + ) /* this.subs.push( this.eventSvc.$on('tree.ready', () => { @@ -207,58 +207,58 @@ class LeftPaneController implements angular.IComponentController { }) ) */ - this.bbApi = this.buttonBarSvc.initApi(this.buttonId, this.bbInit, left_default_buttons); + this.bbApi = this.buttonBarSvc.initApi(this.buttonId, this.bbInit, left_default_buttons) this.buttonBarSvc.waitForApi(this.buttonId).then( (api) => { - this.bbApi = api; + this.bbApi = api this.subs.push( this.eventSvc.$on(this.buttonId, (data) => { switch (data.clicked) { case 'tree-reorder-view': { - this.bbApi.toggleButton('tree-full-document', false); + this.bbApi.toggleButton('tree-full-document', false) void this.$state.go('main.project.ref.view.reorder', { search: undefined, - }); - break; + }) + break } case 'tree-reorder-group': { - void this.$state.go('main.project.ref.groupReorder'); - break; + void this.$state.go('main.project.ref.groupReorder') + break } case 'tree-full-document': { - this.fullDocMode(); - break; + this.fullDocMode() + break } case 'tree-refresh': { - this.reloadData(); - break; + this.reloadData() + break } case 'tree-delete': { - this.deleteItem(); - break; + this.deleteItem() + break } case 'tree-show-pe': { - this.bbApi.toggleButton('tree-show-pe'); + this.bbApi.toggleButton('tree-show-pe') } } }) - ); + ) }, (reason) => { - console.log(reason.message); + console.log(reason.message) } - ); + ) } $onDestroy(): void { - this.eventSvc.$destroy(this.subs); - this.buttonBarSvc.destroy(this.buttonId); + this.eventSvc.$destroy(this.subs) + this.buttonBarSvc.destroy(this.buttonId) } bbInit = (api: ButtonBarApi): void => { - api.buttons.length = 0; - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-expand')); - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-collapse')); + api.buttons.length = 0 + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-expand')) + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-collapse')) /*api.addButton(this.buttonBarSvc.getButtonBarButton('tree-add')) api.setPermission('tree-add', this.treeSvc.treeApi.refType !== 'Tag' && this.treeSvc.treeEditable) api.addButton(this.buttonBarSvc.getButtonBarButton('tree-delete')) @@ -277,26 +277,26 @@ class LeftPaneController implements angular.IComponentController { api.setPermission('tree-add.view', this.treeSvc.treeApi.refType !== 'Tag' && this.treeSvc.treeEditable) api.addButton(this.buttonBarSvc.getButtonBarButton('tree-reorder-view'))*/ - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-full-document')); - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-show-pe')); + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-full-document')) + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-show-pe')) //api.setPermission('tree-reorder-view', this.treeSvc.treeEditable) if (this.rootScopeSvc.veFullDocMode()) { - api.toggleButton('tree-full-document', true); + api.toggleButton('tree-full-document', true) } - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-refresh')); + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-refresh')) api.checkActive((state: string) => { - return this.$state.includes(state); - }); - }; + return this.$state.includes(state) + }) + } changeData = (data: veCoreEvents.elementSelectedData): void => { //If the transitioning state detects a refresh, it will let us know to regenerate the tree - if (data.refresh) this.treeSvc.processedRoot = ''; - const rootId = !data.rootId && data.elementId.endsWith('_cover') ? data.projectId + '_pm' : data.rootId; - const elementId = data.elementId; - const refId = data.refId; - const projectId = data.projectId; - const commitId = data.commitId ? data.commitId : null; + if (data.refresh) this.treeSvc.processedRoot = '' + const rootId = !data.rootId && data.elementId.endsWith('_cover') ? data.projectId + '_pm' : data.rootId + const elementId = data.elementId + const refId = data.refId + const projectId = data.projectId + const commitId = data.commitId ? data.commitId : null if ((rootId && this.treeSvc.processedRoot !== rootId && rootId != '') || !this.treeApi) { new this.$q((resolve, reject) => { if ( @@ -306,10 +306,10 @@ class LeftPaneController implements angular.IComponentController { projectId != this.treeApi.projectId ) { this.projectSvc.getRef(refId, projectId).then((ref) => { - resolve(ref.type); - }, reject); + resolve(ref.type) + }, reject) } else { - resolve(this.treeApi.refType); + resolve(this.treeApi.refType) } }).then( (refType) => { @@ -320,24 +320,24 @@ class LeftPaneController implements angular.IComponentController { refType, refId, commitId, - }; + } - this.treeApi.onSelect = this.treeClickCallback; - this.treeApi.onDblClick = this.treeDblClickCallback; + this.treeApi.onSelect = this.treeClickCallback + this.treeApi.onDblClick = this.treeDblClickCallback - this.treeSvc.treeApi = this.treeApi; + this.treeSvc.treeApi = this.treeApi this.treeSvc.treeEditable = this.permissionsSvc.hasBranchEditPermission( this.mmsProject.id, this.mmsRef.id - ); + ) - this.treeApi.sectionNumbering = this.$state.includes('**.present.**'); + this.treeApi.sectionNumbering = this.$state.includes('**.present.**') this.treeApi.expandLevel = this.$state.includes('**.present.**') ? 3 : this.$state.includes('**.portal.**') ? 0 - : 1; - this.treeApi.sort = !this.$state.includes('**.present.**'); + : 1 + this.treeApi.sort = !this.$state.includes('**.present.**') new this.$q>((resolve, reject) => { if (this.$state.includes('**.present.**')) { @@ -345,7 +345,7 @@ class LeftPaneController implements angular.IComponentController { elementId: this.treeApi.rootId, refId: this.treeApi.refId, projectId: this.treeApi.projectId, - }; + } this.elementSvc.getElement(reqOb).then((root) => { // TODO this call is taking a long time that keeps the tree from being visible, need // to see if it can be moved to a resolve or faster @@ -368,49 +368,49 @@ class LeftPaneController implements angular.IComponentController { resolve(root) }, reject) } else {*/ - this.treeApi.numberingDepth = 0; - this.treeApi.numberingSeparator = '.'; - this.treeApi.startChapter = 1; - resolve(root); + this.treeApi.numberingDepth = 0 + this.treeApi.numberingSeparator = '.' + this.treeApi.startChapter = 1 + resolve(root) //} - }, reject); + }, reject) } else { - resolve(null); + resolve(null) } }).then( (root) => { - this.treeApi.elementId = elementId; + this.treeApi.elementId = elementId this.treeSvc.changeRoots(root).catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) } else { - this.treeApi.elementId = elementId; + this.treeApi.elementId = elementId this.treeSvc.changeElement().catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) } - }; + } transitionCallback = (): void => { this.buttonBarSvc.waitForApi(this.buttonId).then( (api) => { - this.bbApi = api; + this.bbApi = api }, (reason) => { - console.log(reason.message); + console.log(reason.message) } - ); - }; + ) + } treeClickCallback = (branch: TreeBranch): void => { if (this.$state.includes('**.portal.**')) { @@ -418,15 +418,15 @@ class LeftPaneController implements angular.IComponentController { void this.$state.go('main.project.ref.portal.preview', { preview: 'site_' + branch.data.id + '_cover', search: undefined, - }); + }) } else if (branch.type === 'view' || branch.type === 'snapshot') { void this.$state.go('main.project.ref.portal.preview', { preview: branch.data.id, search: undefined, - }); + }) } } else if (this.$state.includes('**.present.**')) { - const viewId = branch.type !== 'view' ? branch.viewId : branch.data.id; + const viewId = branch.type !== 'view' ? branch.viewId : branch.data.id // If clicked on a PE send the element.selected event for Tool Pane if (!(branch.type === 'view' || branch.type === 'section')) { @@ -435,8 +435,8 @@ class LeftPaneController implements angular.IComponentController { projectId: branch.data._projectId, refId: branch.data._refId, commitId: 'latest', - }; - this.eventSvc.$broadcast('element.selected', data); + } + this.eventSvc.$broadcast('element.selected', data) } void this.$state.go( @@ -445,9 +445,9 @@ class LeftPaneController implements angular.IComponentController { viewId, search: undefined, } - ); + ) } - }; + } treeDblClickCallback = (branch: TreeBranch): void => { if (this.$state.includes('**.portal.**')) { @@ -458,39 +458,39 @@ class LeftPaneController implements angular.IComponentController { documentId: branch.data.id, search: undefined, } - ); + ) } } else if (this.$state.includes('**.present.**')) { this.treeSvc.expandBranch(branch).catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) } - }; + } filterInputChangeHandler = (): void => { - this.eventSvc.$broadcast(TreeService.events.FILTER, this.treeFilter); - }; + this.eventSvc.$broadcast(TreeService.events.FILTER, this.treeFilter) + } public fullDocMode = (): void => { - let display = ''; + let display = '' this.bbApi.toggleButton( 'tree-full-document', this.rootScopeSvc.veFullDocMode(!this.rootScopeSvc.veFullDocMode()) - ); + ) if (this.rootScopeSvc.veFullDocMode()) { - display = 'document'; + display = 'document' } else { - display = 'slideshow'; + display = 'slideshow' } void this.$state.go('main.project.ref.view.present.' + display, { search: undefined, display, - }); - }; + }) + } reloadData = (): void => { - this.bbApi.toggleButtonSpinner('tree-refresh'); - this.treeSvc.processedRoot = ''; + this.bbApi.toggleButtonSpinner('tree-refresh') + this.treeSvc.processedRoot = '' const data: veCoreEvents.elementSelectedData = { rootId: this.treeApi.rootId, elementId: this.treeApi.elementId, @@ -498,35 +498,35 @@ class LeftPaneController implements angular.IComponentController { refId: this.treeApi.refId, refType: this.treeApi.refType, commitId: 'latest', - }; - this.eventSvc.$broadcast('view.selected', data); + } + this.eventSvc.$broadcast('view.selected', data) const finished = this.eventSvc.$on('tree.ready', () => { - this.bbApi.toggleButtonSpinner('tree-refresh'); - finished.dispose(); - }); - }; + this.bbApi.toggleButtonSpinner('tree-refresh') + finished.dispose() + }) + } deleteItem = (): void => { - const branch = this.treeSvc.getSelectedBranch(); + const branch = this.treeSvc.getSelectedBranch() if (!branch) { - this.growl.warning('Select item to remove.'); - return; + this.growl.warning('Select item to remove.') + return } this.treeSvc.getPrevBranch(branch).then( (prevBranch) => { - const type = this.viewSvc.getElementType(branch.data); + const type = this.viewSvc.getElementType(branch.data) if (this.$state.includes('**.present.**')) { if (type == 'Document') { this.growl.warning( 'Cannot remove a document from this view. To remove this item, go to project home.' - ); - return; + ) + return } if (branch.type !== 'view' || !this.apiSvc.isView(branch.data)) { this.growl.warning( 'Cannot remove non-view item. To remove this item, open it in the center pane.' - ); - return; + ) + return } } else { if ( @@ -534,22 +534,22 @@ class LeftPaneController implements angular.IComponentController { !this.apiSvc.isDocument(branch.data) && (branch.type !== 'group' || branch.children.length > 0) ) { - this.growl.warning('Cannot remove group with contents. Empty contents and try again.'); - return; + this.growl.warning('Cannot remove group with contents. Empty contents and try again.') + return } } const instance = this.$uibModal.open({ component: 'confirmDeleteModal', resolve: { getType: () => { - let type = branch.type; + let type = branch.type if (this.apiSvc.isDocument(branch.data)) { - type = 'Document'; + type = 'Document' } - return type; + return type }, getName: () => { - return branch.data.name; + return branch.data.name }, finalize: () => { return (): VePromise => { @@ -557,7 +557,7 @@ class LeftPaneController implements angular.IComponentController { if (branch.type === 'view') { this.treeSvc.getParent(branch).then((parentBranch) => { if (!this.$state.includes('**.present.**')) { - this.viewSvc.downgradeDocument(branch.data).then(resolve, reject); + this.viewSvc.downgradeDocument(branch.data).then(resolve, reject) } else { this.viewSvc .removeViewFromParentView({ @@ -566,19 +566,19 @@ class LeftPaneController implements angular.IComponentController { parentViewId: parentBranch.data.id, viewId: branch.data.id, }) - .then(resolve, reject); + .then(resolve, reject) } - }, reject); + }, reject) } else if (branch.type === 'group') { - this.viewSvc.removeGroup(branch.data).then(resolve, reject); + this.viewSvc.removeGroup(branch.data).then(resolve, reject) } else { - resolve(); + resolve() } - }); - }; + }) + } }, }, - }); + }) instance.result.then( () => { this.treeSvc.removeBranch(branch).then( @@ -589,47 +589,47 @@ class LeftPaneController implements angular.IComponentController { parentBranch, prevBranch, branch, - }; - this.eventSvc.$broadcast('view.deleted', data); + } + this.eventSvc.$broadcast('view.deleted', data) if (this.$state.includes('**.present.**') && branch.type === 'view') { - this.treeSvc.processDeletedViewBranch(branch); + this.treeSvc.processDeletedViewBranch(branch) } - let selectBranch: TreeBranch = null; + let selectBranch: TreeBranch = null if (prevBranch) { - selectBranch = prevBranch; + selectBranch = prevBranch } else if (parentBranch) { - selectBranch = parentBranch; + selectBranch = parentBranch } this.treeSvc.selectBranch(selectBranch).then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD); + this.eventSvc.$broadcast(TreeService.events.RELOAD) }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); + ) }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); + ) }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); + ) }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); - }; + ) + } } /* Controllers */ @@ -666,6 +666,6 @@ const LeftPaneComponent: VeComponentOptions = { $pane: '^ngPane', }, controller: LeftPaneController, -}; +} -veApp.component(LeftPaneComponent.selector, LeftPaneComponent); +veApp.component(LeftPaneComponent.selector, LeftPaneComponent) diff --git a/src/ve-app/pane-left/left-toolbar.component.ts b/src/ve-app/pane-left/left-toolbar.component.ts index 92641505a..40fee51c7 100644 --- a/src/ve-app/pane-left/left-toolbar.component.ts +++ b/src/ve-app/pane-left/left-toolbar.component.ts @@ -1,19 +1,19 @@ -import { StateService } from '@uirouter/angularjs'; -import { IComponentController } from 'angular'; -import Rx from 'rx-lite'; +import { StateService } from '@uirouter/angularjs' +import { IComponentController } from 'angular' +import Rx from 'rx-lite' -import { ExtensionService } from '@ve-components/services'; -import { IToolBarButton, ToolbarApi, ToolbarService } from '@ve-core/toolbar'; -import { RootScopeService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { PermissionsService } from '@ve-utils/mms-api-client'; +import { ExtensionService } from '@ve-components/services' +import { IToolBarButton, ToolbarApi, ToolbarService } from '@ve-core/toolbar' +import { RootScopeService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { PermissionsService } from '@ve-utils/mms-api-client' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' -import { left_default_toolbar, left_dynamic_toolbar } from './left-buttons.config'; +import { left_default_toolbar, left_dynamic_toolbar } from './left-buttons.config' -import { VeComponentOptions } from '@ve-types/angular'; -import { ElementObject, RefObject } from '@ve-types/mms'; +import { VeComponentOptions } from '@ve-types/angular' +import { ElementObject, RefObject } from '@ve-types/mms' /* Classes */ const LeftToolbarComponent: VeComponentOptions = { @@ -33,20 +33,20 @@ const LeftToolbarComponent: VeComponentOptions = { 'EventService', 'ToolbarService', 'RootScopeService', - ]; + ] //Injected Deps - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] //Bindings - private mmsRef: RefObject; + private mmsRef: RefObject // Though we don't explicitly use it right now, we do need it to trigger updates when // entering/exiting certain states - private mmsRoot: ElementObject; + private mmsRoot: ElementObject //Local - public toolbarId: string; + public toolbarId: string constructor( public growl: angular.growl.IGrowlService, @@ -58,14 +58,14 @@ const LeftToolbarComponent: VeComponentOptions = { private toolbarSvc: ToolbarService, private rootScopeSvc: RootScopeService ) { - this.toolbarId = 'left-toolbar'; + this.toolbarId = 'left-toolbar' } $onInit(): void { - this.eventSvc.$init(this); - let initialState: string; + this.eventSvc.$init(this) + let initialState: string if (this.mmsRoot) { - initialState = this.$state.includes('**.portal.**') ? 'tree-of-documents' : 'tree-of-contents'; + initialState = this.$state.includes('**.portal.**') ? 'tree-of-documents' : 'tree-of-contents' } this.toolbarSvc.initApi( this.toolbarId, @@ -74,58 +74,58 @@ const LeftToolbarComponent: VeComponentOptions = { left_default_toolbar, left_dynamic_toolbar, initialState - ); + ) } $onDestroy(): void { - this.eventSvc.$destroy(this.subs); - this.toolbarSvc.destroyApi(this.toolbarId); + this.eventSvc.$destroy(this.subs) + this.toolbarSvc.destroyApi(this.toolbarId) } tbInit = (tbApi: ToolbarApi): void => { if (this.mmsRoot) { - const trees = this.extensionSvc.getExtensions('treeOf'); + const trees = this.extensionSvc.getExtensions('treeOf') for (const tree of trees) { - const button = this.toolbarSvc.getToolbarButton(tree); - tbApi.addButton(button); + const button = this.toolbarSvc.getToolbarButton(tree) + tbApi.addButton(button) if (button.enabledFor) { - button.active = false; + button.active = false for (const enableState of button.enabledFor) { if (this.$state.includes(enableState)) { - button.active = true; - break; + button.active = true + break } } } if (button.disabledFor) { for (const disableState of button.disabledFor) { if (this.$state.includes(disableState)) { - button.active = false; - break; + button.active = false + break } } } } } - }; + } paneToggle = (button: IToolBarButton): void => { - let toggleDeactivateFlag = false; + let toggleDeactivateFlag = false if (this.rootScopeSvc.leftPaneClosed()) { if (button.selected || this.rootScopeSvc.leftPaneClosed()) { - if (button.selected && !this.rootScopeSvc.leftPaneClosed()) toggleDeactivateFlag = true; - this.eventSvc.$broadcast('left-pane.toggle'); + if (button.selected && !this.rootScopeSvc.leftPaneClosed()) toggleDeactivateFlag = true + this.eventSvc.$broadcast('left-pane.toggle') } } if (toggleDeactivateFlag) { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.deactivate(button.id), (reason) => this.growl.error(ToolbarService.error(reason)) - ); + ) } - }; + } }, -}; +} /* Controllers */ -veApp.component(LeftToolbarComponent.selector, LeftToolbarComponent); +veApp.component(LeftToolbarComponent.selector, LeftToolbarComponent) diff --git a/src/ve-app/pane-right/index.ts b/src/ve-app/pane-right/index.ts index d51766dfb..5710afba7 100644 --- a/src/ve-app/pane-right/index.ts +++ b/src/ve-app/pane-right/index.ts @@ -1,2 +1,2 @@ -import './right-pane.component'; -import './right-toolbar.component'; +import './right-pane.component' +import './right-toolbar.component' diff --git a/src/ve-app/pane-right/right-buttons.config.ts b/src/ve-app/pane-right/right-buttons.config.ts index 8f4c7d623..15c80e0fd 100644 --- a/src/ve-app/pane-right/right-buttons.config.ts +++ b/src/ve-app/pane-right/right-buttons.config.ts @@ -1,4 +1,4 @@ -import { IToolBarButton } from '@ve-core/toolbar'; +import { IToolBarButton } from '@ve-core/toolbar' export const right_default_toolbar: IToolBarButton[] = [ { @@ -57,7 +57,7 @@ export const right_default_toolbar: IToolBarButton[] = [ spinner: false, enabledFor: ['main.project.ref'], }, -]; +] export const right_dynamic_toolbar: IToolBarButton[] = [ { @@ -120,4 +120,4 @@ export const right_dynamic_toolbar: IToolBarButton[] = [ tooltip: 'Cancel', spinner: false, }, -]; +] diff --git a/src/ve-app/pane-right/right-pane.component.ts b/src/ve-app/pane-right/right-pane.component.ts index f8803171a..1ab62756c 100644 --- a/src/ve-app/pane-right/right-pane.component.ts +++ b/src/ve-app/pane-right/right-pane.component.ts @@ -1,43 +1,43 @@ -import { IPane } from '@openmbee/pane-layout'; -import { StateService } from '@uirouter/angularjs'; -import angular, { IComponentController } from 'angular'; -import _ from 'lodash'; -import Rx from 'rx-lite'; +import { IPane } from '@openmbee/pane-layout' +import { StateService } from '@uirouter/angularjs' +import angular, { IComponentController } from 'angular' +import _ from 'lodash' +import Rx from 'rx-lite' -import { SpecService } from '@ve-components/spec-tools'; -import { veCoreEvents } from '@ve-core/events'; -import { ToolbarService } from '@ve-core/toolbar'; -import { RootScopeService } from '@ve-utils/application'; -import { EditObject, EditService, EventService } from '@ve-utils/core'; -import { ElementService, PermissionsService, ProjectService } from '@ve-utils/mms-api-client'; +import { SpecService } from '@ve-components/spec-tools' +import { veCoreEvents } from '@ve-core/events' +import { ToolbarService } from '@ve-core/toolbar' +import { RootScopeService } from '@ve-utils/application' +import { EditObject, EditService, EventService } from '@ve-utils/core' +import { ElementService, PermissionsService, ProjectService } from '@ve-utils/mms-api-client' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { ElementObject, RefObject, RefsResponse } from '@ve-types/mms'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { ElementObject, RefObject, RefsResponse } from '@ve-types/mms' +import { VeModalService } from '@ve-types/view-editor' -import elementSelectedData = veCoreEvents.elementSelectedData; +import elementSelectedData = veCoreEvents.elementSelectedData class RightPaneController implements IComponentController { //Bindings - private mmsRef: RefObject; + private mmsRef: RefObject // Though we don't explicitly use it right now, we do need it to trigger updates when // entering/exiting certain states - private mmsRoot: ElementObject; + private mmsRoot: ElementObject //Local Values - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] - private openEdits: number; - private edits: { [id: string]: EditObject }; + private openEdits: number + private edits: { [id: string]: EditObject } - private $pane: IPane; - private $tools: JQuery; + private $pane: IPane + private $tools: JQuery - private toolbarId: string = 'right-toolbar'; + private toolbarId: string = 'right-toolbar' static $inject = [ '$scope', @@ -57,7 +57,7 @@ class RightPaneController implements IComponentController { 'EditService', 'ToolbarService', 'SpecService', - ]; + ] constructor( private $scope: angular.IScope, @@ -80,38 +80,38 @@ class RightPaneController implements IComponentController { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) //Init Pane Toggle Controls - this.rootScopeSvc.rightPaneClosed(this.$pane.closed); + this.rootScopeSvc.rightPaneClosed(this.$pane.closed) //Init spec ready binding - this.eventSvc.resolve('spec.ready', true); + this.eventSvc.resolve('spec.ready', true) this.subs.push( this.$pane.$toggled.subscribe(() => { - this.rootScopeSvc.rightPaneClosed(this.$pane.closed); + this.rootScopeSvc.rightPaneClosed(this.$pane.closed) }) - ); + ) this.subs.push( this.eventSvc.$on('right-pane.toggle', (paneClosed) => { if (paneClosed === undefined) { - this.$pane.toggle(); + this.$pane.toggle() } else if (paneClosed && !this.$pane.closed) { - this.$pane.toggle(); + this.$pane.toggle() } else if (!paneClosed && this.$pane.closed) { - this.$pane.toggle(); + this.$pane.toggle() } - this.rootScopeSvc.rightPaneClosed(this.$pane.closed); + this.rootScopeSvc.rightPaneClosed(this.$pane.closed) }) - ); + ) this.subs.push( this.eventSvc.$on('element.selected', (data) => { - this.changeAction(data); + this.changeAction(data) }) - ); + ) this.subs.push( this.eventSvc.$on('element.updated', (data) => { @@ -121,37 +121,37 @@ class RightPaneController implements IComponentController { data.element._refId === this.specSvc.specApi.refId && !data.continueEdit ) { - this.eventSvc.resolve('spec.ready', false); - this.specSvc.setElement(); + this.eventSvc.resolve('spec.ready', false) + this.specSvc.setElement() } }) - ); + ) this.subs.push( this.eventSvc.$on('view.selected', (data) => { - this.changeAction(data); + this.changeAction(data) }) - ); + ) this.subs.push( this.eventSvc.$on(this.autosaveSvc.EVENT, () => { - this.openEdits = this.autosaveSvc.openEdits(); + this.openEdits = this.autosaveSvc.openEdits() }) - ); + ) - this.edits = this.autosaveSvc.getAll(); + this.edits = this.autosaveSvc.getAll() } $onDestroy(): void { - this.eventSvc.$destroy(this.subs); + this.eventSvc.$destroy(this.subs) } changeAction = (data: veCoreEvents.elementSelectedData): void => { - const elementId = data.elementId; - const refId = data.refId; - const projectId = data.projectId; - const commitId = data.commitId ? data.commitId : null; - const displayOldSpec = data.displayOldSpec ? data.displayOldSpec : null; + const elementId = data.elementId + const refId = data.refId + const projectId = data.projectId + const commitId = data.commitId ? data.commitId : null + const displayOldSpec = data.displayOldSpec ? data.displayOldSpec : null const promise: VePromise = new this.$q((resolve, reject) => { if ( !this.specSvc.specApi.refType || @@ -159,12 +159,12 @@ class RightPaneController implements IComponentController { projectId != this.specSvc.specApi.projectId ) { this.projectSvc.getRef(refId, projectId).then((ref) => { - resolve(ref.type); - }, reject); + resolve(ref.type) + }, reject) } else { - resolve(this.specSvc.specApi.refType); + resolve(this.specSvc.specApi.refType) } - }); + }) promise.then( (refType) => { @@ -175,7 +175,7 @@ class RightPaneController implements IComponentController { refId, commitId, displayOldSpec, - }; + } if (this.specSvc.specApi) { const current = { elementId: this.specSvc.specApi.elementId, @@ -184,52 +184,52 @@ class RightPaneController implements IComponentController { refType: this.specSvc.specApi.refType, commitId: this.specSvc.specApi.commitId, displayOldSpec: this.specSvc.specApi.displayOldSpec, - }; + } if (_.isEqual(specApi, current)) { - return; //don't do unnecessary updates + return //don't do unnecessary updates } } - this.eventSvc.resolve('spec.ready', false); - Object.assign(this.specSvc.specApi, specApi); + this.eventSvc.resolve('spec.ready', false) + Object.assign(this.specSvc.specApi, specApi) // if (this.specSvc.setEditing) { // this.specSvc.setEditing(false) // } - this.specSvc.specApi.rootId = data.rootId ? data.rootId : ''; + this.specSvc.specApi.rootId = data.rootId ? data.rootId : '' this.specSvc.editable = data.rootId && this.mmsRef.type === 'Branch' && refType === 'Branch' && - this.permissionsSvc.hasBranchEditPermission(projectId, refId); + this.permissionsSvc.hasBranchEditPermission(projectId, refId) this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.setIcon('spec-editor', 'fa-edit'), (reason) => this.growl.error(ToolbarService.error(reason)) - ); - this.specSvc.setElement(); + ) + this.specSvc.setElement() }, (reason) => { - this.growl.error('Unable to get ref: ' + reason.message); + this.growl.error('Unable to get ref: ' + reason.message) } - ); - }; + ) + } public etrackerChange = (): void => { - this.specSvc.keepMode(); - const id = this.specSvc.tracker.etrackerSelected; - if (!id) return; - const info = id.split('|'); + this.specSvc.keepMode() + const id = this.specSvc.tracker.etrackerSelected + if (!id) return + const info = id.split('|') const data: veCoreEvents.elementSelectedData = { elementId: info[2], projectId: info[0], refId: info[1], commitId: 'latest', - }; + } - this.eventSvc.$broadcast('element.selected', data); - }; + this.eventSvc.$broadcast('element.selected', data) + } } const RightPaneComponent: VeComponentOptions = { @@ -261,6 +261,6 @@ const RightPaneComponent: VeComponentOptions = { mmsRoot: '<', }, controller: RightPaneController, -}; +} -veApp.component(RightPaneComponent.selector, RightPaneComponent); +veApp.component(RightPaneComponent.selector, RightPaneComponent) diff --git a/src/ve-app/pane-right/right-toolbar.component.ts b/src/ve-app/pane-right/right-toolbar.component.ts index b1b6a6068..dc97a4344 100644 --- a/src/ve-app/pane-right/right-toolbar.component.ts +++ b/src/ve-app/pane-right/right-toolbar.component.ts @@ -1,18 +1,18 @@ -import { StateService } from '@uirouter/angularjs'; -import { IComponentController } from 'angular'; -import Rx from 'rx-lite'; +import { StateService } from '@uirouter/angularjs' +import { IComponentController } from 'angular' +import Rx from 'rx-lite' -import { right_default_toolbar, right_dynamic_toolbar } from '@ve-app/pane-right/right-buttons.config'; -import { ExtensionService } from '@ve-components/services'; -import { IToolBarButton, ToolbarApi, ToolbarService } from '@ve-core/toolbar'; -import { RootScopeService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { PermissionsService } from '@ve-utils/mms-api-client'; +import { right_default_toolbar, right_dynamic_toolbar } from '@ve-app/pane-right/right-buttons.config' +import { ExtensionService } from '@ve-components/services' +import { IToolBarButton, ToolbarApi, ToolbarService } from '@ve-core/toolbar' +import { RootScopeService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { PermissionsService } from '@ve-utils/mms-api-client' -import { veApp } from '@ve-app'; +import { veApp } from '@ve-app' -import { VeComponentOptions } from '@ve-types/angular'; -import { ElementObject, RefObject } from '@ve-types/mms'; +import { VeComponentOptions } from '@ve-types/angular' +import { ElementObject, RefObject } from '@ve-types/mms' class RightToolbarController implements IComponentController { static $inject = [ @@ -24,20 +24,20 @@ class RightToolbarController implements IComponentController { 'EventService', 'ToolbarService', 'RootScopeService', - ]; + ] //Injected Deps - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] //Bindings - private mmsRef: RefObject; + private mmsRef: RefObject // Though we don't explicitly use it right now, we do need it to trigger updates when // entering/exiting certain states - private mmsRoot: ElementObject; + private mmsRoot: ElementObject //Local - public toolbarId: string; + public toolbarId: string constructor( public growl: angular.growl.IGrowlService, @@ -49,11 +49,11 @@ class RightToolbarController implements IComponentController { private toolbarSvc: ToolbarService, private rootScopeSvc: RootScopeService ) { - this.toolbarId = 'right-toolbar'; + this.toolbarId = 'right-toolbar' } $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) this.toolbarSvc.initApi( this.toolbarId, @@ -62,32 +62,32 @@ class RightToolbarController implements IComponentController { right_default_toolbar, right_dynamic_toolbar, 'spec-inspector' - ); + ) } $onDestroy(): void { - this.eventSvc.$destroy(this.subs); - this.toolbarSvc.destroyApi(this.toolbarId); + this.eventSvc.$destroy(this.subs) + this.toolbarSvc.destroyApi(this.toolbarId) } tbInit = (tbApi: ToolbarApi): void => { for (const tool of this.extensionSvc.getExtensions('spec')) { - const button = this.toolbarSvc.getToolbarButton(tool); - tbApi.addButton(button); + const button = this.toolbarSvc.getToolbarButton(tool) + tbApi.addButton(button) if (button.enabledFor) { - button.active = false; + button.active = false for (const enableState of button.enabledFor) { if (this.$state.includes(enableState)) { - button.active = true; - break; + button.active = true + break } } } if (button.disabledFor) { for (const disableState of button.disabledFor) { if (this.$state.includes(disableState)) { - button.active = false; - break; + button.active = false + break } } } @@ -95,26 +95,26 @@ class RightToolbarController implements IComponentController { button.permission = this.mmsRef && this.mmsRef.type === 'Branch' && - this.permissionsSvc.hasBranchEditPermission(this.mmsRef._projectId, this.mmsRef.id); + this.permissionsSvc.hasBranchEditPermission(this.mmsRef._projectId, this.mmsRef.id) } } - }; + } public paneToggle = (button: IToolBarButton): void => { - let toggleDeactivateFlag = false; + let toggleDeactivateFlag = false if (this.rootScopeSvc.rightPaneClosed() && this.rootScopeSvc.rightPaneToggleable()) { if (button.selected || this.rootScopeSvc.rightPaneClosed()) { - if (button.selected && !this.rootScopeSvc.rightPaneClosed()) toggleDeactivateFlag = true; - this.eventSvc.$broadcast('right-pane.toggle'); + if (button.selected && !this.rootScopeSvc.rightPaneClosed()) toggleDeactivateFlag = true + this.eventSvc.$broadcast('right-pane.toggle') } } if (toggleDeactivateFlag) { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.deactivate(button.id), (reason) => this.growl.error(ToolbarService.error(reason)) - ); + ) } - }; + } } /* Classes */ @@ -126,7 +126,7 @@ const RightToolbarComponent: VeComponentOptions = { mmsRoot: '<', }, controller: RightToolbarController, -}; +} /* Controllers */ -veApp.component(RightToolbarComponent.selector, RightToolbarComponent); +veApp.component(RightToolbarComponent.selector, RightToolbarComponent) diff --git a/src/ve-app/ve-app.module.ts b/src/ve-app/ve-app.module.ts index 68d463091..f3b6837fa 100644 --- a/src/ve-app/ve-app.module.ts +++ b/src/ve-app/ve-app.module.ts @@ -1,6 +1,6 @@ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -import ngPane from '@openmbee/pane-layout'; +import ngPane from '@openmbee/pane-layout' import uiRouter, { StateProvider, StateService, @@ -10,7 +10,7 @@ import uiRouter, { UIRouterGlobals, UrlParts, UrlService, -} from '@uirouter/angularjs'; +} from '@uirouter/angularjs' import angular, { IHttpInterceptor, IHttpResponse, @@ -21,15 +21,15 @@ import angular, { IPromise, IQService, IRequestConfig, -} from 'angular'; +} from 'angular' -import { LoginModalResolveFn } from '@ve-app/main/modals/login-modal.component'; -import { ResolveService } from '@ve-app/main/services'; -import { ApplicationService, BrandingStyle, RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { AuthService, URLService, PermissionCache, ViewService, DocumentMetadata } from '@ve-utils/mms-api-client'; +import { LoginModalResolveFn } from '@ve-app/main/modals/login-modal.component' +import { ResolveService } from '@ve-app/main/services' +import { ApplicationService, BrandingStyle, RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { AuthService, URLService, PermissionCache, ViewService, DocumentMetadata } from '@ve-utils/mms-api-client' -import { VePromise } from '@ve-types/angular'; +import { VePromise } from '@ve-types/angular' import { CheckAuthResponse, DocumentObject, @@ -47,8 +47,8 @@ import { RefObject, RefsResponse, ViewObject, -} from '@ve-types/mms'; -import { VeModalService } from '@ve-types/view-editor'; +} from '@ve-types/mms' +import { VeModalService } from '@ve-types/view-editor' export const veApp = angular.module('ve-app', [ 've-utils', @@ -68,7 +68,7 @@ export const veApp = angular.module('ve-app', [ 'ngPromiseExtras', 'ngSanitize', 'ngStorage', -]); +]) veApp.config([ '$stateProvider', @@ -90,41 +90,41 @@ veApp.config([ '$delegate', function ( $delegate: ({ - link?(scope: angular.IScope, element: JQLite, attr: angular.IAttributes): void; + link?(scope: angular.IScope, element: JQLite, attr: angular.IAttributes): void } & angular.IDirective)[] ): { - link?(scope: angular.IScope, element: JQLite, attr: angular.IAttributes): void; + link?(scope: angular.IScope, element: JQLite, attr: angular.IAttributes): void } & angular.IDirective[] { - const originalLinkFn = $delegate[0].link; + const originalLinkFn = $delegate[0].link $delegate[0].compile = (): angular.IDirectiveLinkFn => { return function newLinkFn( scope: { - selectActive(matchId: string): void; - active: string; + selectActive(matchId: string): void + active: string } & angular.IScope, elem, attr ) { // fire the originalLinkFn // eslint-disable-next-line prefer-rest-params - originalLinkFn.apply($delegate[0], [scope, elem, attr]); + originalLinkFn.apply($delegate[0], [scope, elem, attr]) scope.selectActive = (matchIdx): void => { // added behavior - elem.children().removeClass('active'); + elem.children().removeClass('active') // default behavior - scope.active = matchIdx; - }; - }; - }; + scope.active = matchIdx + } + } + } // get rid of the old link function since we return a link function in compile - delete $delegate[0].link; - return $delegate; + delete $delegate[0].link + return $delegate }, - ]); + ]) - $locationProvider.hashPrefix(''); + $locationProvider.hashPrefix('') - $httpProvider.defaults.withCredentials = true; + $httpProvider.defaults.withCredentials = true $stateProvider .state('main', { @@ -145,19 +145,19 @@ veApp.config([ bannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getBanner(); + return resolveSvc.getBanner() }, ], loginBannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getLoginBanner(); + return resolveSvc.getLoginBanner() }, ], paramsOb: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params(); + return $transition$.params() }, ], }, @@ -184,7 +184,7 @@ veApp.config([ token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken(); + return resolveSvc.getToken() }, ], }, @@ -206,25 +206,25 @@ veApp.config([ token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken(); + return resolveSvc.getToken() }, ], bannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getBanner(); + return resolveSvc.getBanner() }, ], loginBannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getLoginBanner(); + return resolveSvc.getLoginBanner() }, ], orgObs: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getOrgs(); + return resolveSvc.getOrgs() }, ], }, @@ -259,26 +259,26 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params(); + return $transition$.params() }, ], token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken(); + return resolveSvc.getToken() }, ], refresh: [ '$transition$', ($transition$: Transition): boolean => { - const options = $transition$.options(); - return options.reload === true || options.reload === 'true'; + const options = $transition$.options() + return options.reload === true || options.reload === 'true' }, ], bannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getBanner(); + return resolveSvc.getBanner() }, ], projectOb: [ @@ -288,7 +288,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getProject(params); + return resolveSvc.getProject(params) }, ], projectObs: [ @@ -300,27 +300,27 @@ veApp.config([ resolveSvc: ResolveService, projectOb: ProjectObject ): VePromise => { - return resolveSvc.getProjects(projectOb, refresh); + return resolveSvc.getProjects(projectOb, refresh) }, ], orgOb: [ 'ResolveService', 'projectOb', (resolveSvc: ResolveService, projectOb: ProjectObject): VePromise => { - return resolveSvc.getOrg(projectOb); + return resolveSvc.getOrg(projectOb) }, ], orgObs: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getOrgs(); + return resolveSvc.getOrgs() }, ], refObs: [ 'ResolveService', 'params', (resolveSvc: ResolveService, params: ParamsObject): VePromise => { - return resolveSvc.getRefs(params); + return resolveSvc.getRefs(params) }, ], }, @@ -367,14 +367,14 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params(); + return $transition$.params() }, ], refresh: [ '$transition$', ($transition$: Transition): boolean => { - const options = $transition$.options(); - return options.reload === true || options.reload === 'true'; + const options = $transition$.options() + return options.reload === true || options.reload === 'true' }, ], projectOb: [ @@ -384,14 +384,14 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getProjectMounts(params); + return resolveSvc.getProjectMounts(params) }, ], refOb: [ 'ResolveService', 'params', (resolveSvc: ResolveService, params: ParamsObject): VePromise => { - return resolveSvc.getRef(params); + return resolveSvc.getRef(params) }, ], groupObs: [ @@ -403,7 +403,7 @@ veApp.config([ params: ParamsObject, refresh: boolean ): VePromise => { - return resolveSvc.getGroups(params, refresh); + return resolveSvc.getGroups(params, refresh) }, ], documentObs: [ @@ -415,7 +415,7 @@ veApp.config([ params: ParamsObject, refresh: boolean ): VePromise> => { - return resolveSvc.getProjectDocuments(params, refresh); + return resolveSvc.getProjectDocuments(params, refresh) }, ], bannerOb: [ @@ -425,7 +425,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getBanner(params); + return resolveSvc.getBanner(params) }, ], footerOb: [ @@ -435,7 +435,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getFooter(params); + return resolveSvc.getFooter(params) }, ], permissions: [ @@ -447,7 +447,7 @@ veApp.config([ projectOb: ProjectObject, resolveSvc: ResolveService ): VePromise => { - return resolveSvc.initializePermissions(projectOb, refOb); + return resolveSvc.initializePermissions(projectOb, refOb) }, ], }, @@ -495,7 +495,7 @@ veApp.config([ refresh: boolean, resolveSvc: ResolveService ): VePromise => { - return resolveSvc.getCoverDocument(params, refOb, projectOb, refresh); + return resolveSvc.getCoverDocument(params, refOb, projectOb, refresh) }, ], groupOb: [ @@ -507,14 +507,14 @@ veApp.config([ documentOb: DocumentObject, resolveSvc: ResolveService ): GroupObject => { - return resolveSvc.getGroup(groupObs, documentOb); + return resolveSvc.getGroup(groupObs, documentOb) }, ], rootOb: [ 'params', 'ResolveService', (params: ParamsObject, resolveSvc: ResolveService): VePromise => { - return resolveSvc.getProjectRoot(params); + return resolveSvc.getProjectRoot(params) }, ], }, @@ -605,7 +605,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params(); + return $transition$.params() }, ], documentOb: [ @@ -619,7 +619,7 @@ veApp.config([ refOb: RefObject, refresh: boolean ): VePromise => { - return resolveSvc.getPreviewDocument(params, refOb, refresh); + return resolveSvc.getPreviewDocument(params, refOb, refresh) }, ], groupOb: [ @@ -631,7 +631,7 @@ veApp.config([ documentOb: DocumentObject, resolveSvc: ResolveService ): GroupObject => { - return resolveSvc.getGroup(groupObs, documentOb); + return resolveSvc.getGroup(groupObs, documentOb) }, ], }, @@ -658,7 +658,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise> => { - return resolveSvc.getProjectDocuments(params); + return resolveSvc.getProjectDocuments(params) }, ], }, @@ -689,7 +689,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params(); + return $transition$.params() }, ], documentOb: [ @@ -701,7 +701,7 @@ veApp.config([ refresh: boolean, resolveSvc: ResolveService ): VePromise => { - return resolveSvc.getProjectDocument(params, refresh); + return resolveSvc.getProjectDocument(params, refresh) }, ], docMeta: [ @@ -712,7 +712,7 @@ veApp.config([ projectId: documentOb._projectId, refId: documentOb._refId, elementId: documentOb.id, - }); + }) }, ], }, @@ -806,7 +806,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params(); + return $transition$.params() }, ], viewOb: [ @@ -815,9 +815,9 @@ veApp.config([ 'refresh', (resolveSvc: ResolveService, params: ParamsObject, refresh: boolean): VePromise => { if (params.viewId) { - return resolveSvc.getView(params, refresh); + return resolveSvc.getView(params, refresh) } else { - return null; + return null } }, ], @@ -861,7 +861,7 @@ veApp.config([ 'params', 'ResolveService', (params: ParamsObject, resolveSvc: ResolveService): VePromise => { - return resolveSvc.getProjectDocument(params, true); + return resolveSvc.getProjectDocument(params, true) }, ], }, @@ -889,7 +889,7 @@ veApp.config([ paramsOb: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params(); + return $transition$.params() }, ], }, @@ -938,13 +938,13 @@ veApp.config([ token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken(); + return resolveSvc.getToken() }, ], paramsOb: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params(); + return $transition$.params() }, ], }, @@ -953,7 +953,7 @@ veApp.config([ component: 'shortUrl', }, }, - }); + }) // anonymous factory intercepts requests $httpProvider.interceptors.push([ @@ -969,51 +969,51 @@ veApp.config([ ): IHttpInterceptor { return { request: (config: IRequestConfig): IRequestConfig => { - config.headers = uRLSvc.getAuthorizationHeader(config.headers); + config.headers = uRLSvc.getAuthorizationHeader(config.headers) if (!config.timeout) { - config.cancel = $q.defer(); - config.timeout = config.cancel.promise; + config.cancel = $q.defer() + config.timeout = config.cancel.promise } else { - console.log(config.url); + console.log(config.url) } - return config; + return config }, responseError: ( rejection: IHttpResponse ): IPromise> | IHttpResponse => { - const timeout: IPromise = rejection.config.timeout as IPromise; + const timeout: IPromise = rejection.config.timeout as IPromise if (timeout.state && timeout.state === 'cancelled') { - rejection.data = 'cancelled'; - return $q.when(rejection); + rejection.data = 'cancelled' + return $q.when(rejection) } if (rejection.status == 401) { - console.log(rejection.config.url); + console.log(rejection.config.url) if (rejection.config.url === uRLSvc.getCheckTokenURL()) { - return $q.reject(rejection); + return $q.reject(rejection) } else { - eventSvc.$broadcast('mms.unauthorized'); + eventSvc.$broadcast('mms.unauthorized') } } - return $q.reject(rejection); + return $q.reject(rejection) }, response: (response): IHttpResponse => { if (response.status === 202) { - eventSvc.$broadcast('mms.working', response); + eventSvc.$broadcast('mms.working', response) } - response.status = 501; - return response; + response.status = 501 + return response }, - }; + } }, - ]); + ]) - $httpProvider.useApplyAsync(true); + $httpProvider.useApplyAsync(true) // $uiRouterProvider.urlService.rules.otherwise((match, url: UrlParts | undefined) => { // console.log(url); // }) }, -]); +]) veApp.run([ '$q', @@ -1044,59 +1044,59 @@ veApp.run([ eventSvc: EventService, applicationSvc: ApplicationService ): void { - rootScopeSvc.loginModalOpen(false); + rootScopeSvc.loginModalOpen(false) $transitions.onBefore({}, (transition: Transition) => { - const to = transition.$to().name; - const params: ParamsObject = transition.params(); + const to = transition.$to().name + const params: ParamsObject = transition.params() if (to === 'main.login' || rootScopeSvc.loginModalOpen()) { if (params.next) { - $urlService.url(params.next, true); + $urlService.url(params.next, true) } - return; + return } return new Promise((resolve) => { authSvc.checkLogin().then( (data) => { - applicationSvc.getState().user = data.username; + applicationSvc.getState().user = data.username if (to === 'main') { - resolve($state.target('main.login.select')); + resolve($state.target('main.login.select')) } else if (to === 'main.project.ref') { - resolve($state.target('main.project.ref.portal')); + resolve($state.target('main.project.ref.portal')) } else if (to === 'main.project.ref.view.present') { if (!params.display || params.display === '') { - params.display = 'slideshow'; + params.display = 'slideshow' } - resolve($state.target('main.project.ref.view.present.' + params.display, params)); + resolve($state.target('main.project.ref.view.present.' + params.display, params)) } else if ($state.includes('*.present.**') && !(transition.params() as ParamsObject).display) { - const display = transition.$to().name.split('.')[transition.$to().name.split('.').length]; + const display = transition.$to().name.split('.')[transition.$to().name.split('.').length] resolve( $state.target(transition.$to().name, { display, }) - ); + ) } else { - resolve(); + resolve() } }, () => { $http.pendingRequests.forEach((pendingReq) => { if (pendingReq.cancel) { - pendingReq.cancel.resolve('cancelled'); + pendingReq.cancel.resolve('cancelled') } - }); + }) resolve( $state.target('main.login', { next: $urlService.url(), }) - ); + ) } - ); - }); - }); + ) + }) + }) $transitions.onError({}, (reason) => { - console.log(reason); + console.log(reason) //console.log(reason.error()); - }); + }) eventSvc.$on('mms.unauthorized', (response) => { // add a boolean to the 'or' statement to check for modal window if ( @@ -1109,9 +1109,9 @@ veApp.run([ $uiRouterGlobals.current.name === 'main.login.select' || ($uiRouterGlobals.transition && $uiRouterGlobals.transition.$to.name === 'main.login.select') ) { - void $state.go('main.login'); + void $state.go('main.login') } - return; + return } authSvc.checkLogin().then( @@ -1119,54 +1119,54 @@ veApp.run([ /* do nothing if success */ }, () => { - rootScopeSvc.loginModalOpen(true); + rootScopeSvc.loginModalOpen(true) $uibModal .open({ component: 'loginModal', resolve: { continue: () => { - return true; + return true }, }, backdrop: 'static', size: 'md', }) .result.finally(() => { - rootScopeSvc.loginModalOpen(false); - }); + rootScopeSvc.loginModalOpen(false) + }) } - ); - }); + ) + }) // broadcast mms.unauthorized every 10 minutes with interval service void $interval( () => { - eventSvc.$broadcast('mms.unauthorized'); + eventSvc.$broadcast('mms.unauthorized') }, window.__env.loginTimeout ? window.__env.loginTimeout : 60000, 0, false - ); + ) // Check if user is logged in, if so redirect to select page otherwise go to login if the url isn't mapped $urlService.rules.otherwise((match, url: UrlParts | undefined) => { void authSvc.checkLogin().then((checkLogin) => { if (checkLogin) { if ($location.url().includes('workspace')) { - rootScopeSvc.veRedirectFromOld(true); - rootScopeSvc.veCrushUrl($location.path()); - void $state.go('main.login.redirect'); + rootScopeSvc.veRedirectFromOld(true) + rootScopeSvc.veCrushUrl($location.path()) + void $state.go('main.login.redirect') } else { - rootScopeSvc.veRedirectFromOld(false); - void $state.go('main.login.select'); + rootScopeSvc.veRedirectFromOld(false) + void $state.go('main.login.select') } } else { - void $state.go('main.login'); + void $state.go('main.login') } - }); - }); + }) + }) }, -]); +]) /* veApp.run([ diff --git a/src/ve-components/components/annotation.component.ts b/src/ve-components/components/annotation.component.ts index bbee61d9b..744bfa330 100644 --- a/src/ve-components/components/annotation.component.ts +++ b/src/ve-components/components/annotation.component.ts @@ -1,20 +1,20 @@ -import { ExtensionService } from '@ve-components/services'; -import { veCoreEvents } from '@ve-core/events'; -import { ApplicationService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { ValueService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService } from '@ve-components/services' +import { veCoreEvents } from '@ve-core/events' +import { ApplicationService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { ValueService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VeComponentOptions } from '@ve-types/angular'; -import { ElementObject, InstanceSpecObject, LiteralObject } from '@ve-types/mms'; +import { VeComponentOptions } from '@ve-types/angular' +import { ElementObject, InstanceSpecObject, LiteralObject } from '@ve-types/mms' export interface AnnotationObject { - toolTipTitle: string; - toolTipContent: string; - inlineContent: string; - id: string; + toolTipTitle: string + toolTipContent: string + inlineContent: string + id: string } class AnnotationController implements angular.IComponentController { @@ -26,17 +26,17 @@ class AnnotationController implements angular.IComponentController { 'ApplicationService', 'EventService', 'ValueService', - ]; + ] //Bindings - private mmsElementId: string; - mmsRecentElement: ElementObject; - mmsType: 'presentation' | 'transclusion' | 'link'; - mmsField: 'name' | 'documentation' | 'value'; + private mmsElementId: string + mmsRecentElement: ElementObject + mmsType: 'presentation' | 'transclusion' | 'link' + mmsField: 'name' | 'documentation' | 'value' //Local - public displayContent; - private schema: string = 'cameo'; + public displayContent + private schema: string = 'cameo' constructor( private $element: JQuery, @@ -57,50 +57,50 @@ class AnnotationController implements angular.IComponentController { refId: this.mmsRecentElement._refId, commitId: this.mmsRecentElement._commitId, displayOldSpec: true, - }; - this.eventSvc.$broadcast('element.selected', data); + } + this.eventSvc.$broadcast('element.selected', data) } - }); + }) - let displayContent: AnnotationObject; + let displayContent: AnnotationObject if (this.mmsRecentElement) { - displayContent = this._getContentIfElementFound(); + displayContent = this._getContentIfElementFound() } else { - displayContent = this._getContentIfElementNotFound(); + displayContent = this._getContentIfElementNotFound() } - this.displayContent = displayContent; + this.displayContent = displayContent } public copyToClipboard($event: JQuery.ClickEvent): void { this.applicationSvc.copyToClipboard($('#tooltipElementId'), $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }); + this.growl.info('Copied to clipboard!', { ttl: 2000 }) }, (err) => { - this.growl.error('Unable to copy: ' + err.message); + this.growl.error('Unable to copy: ' + err.message) } - ); + ) } private _getContentIfElementFound(): AnnotationObject { - let inlineContent = ''; - let toolTipTitle: string; - let toolTipContent: string; + let inlineContent = '' + let toolTipTitle: string + let toolTipContent: string if (this.mmsType === 'transclusion') { if (this.mmsField !== 'value') { - inlineContent = this.mmsRecentElement[this.mmsField] || '(no text)'; - toolTipTitle = 'Referenced element not found'; - toolTipContent = `Displaying last found ${this.mmsField} as placeholder.`; + inlineContent = this.mmsRecentElement[this.mmsField] || '(no text)' + toolTipTitle = 'Referenced element not found' + toolTipContent = `Displaying last found ${this.mmsField} as placeholder.` } else { if (!this.valueSvc.isValue(this.mmsRecentElement)) { - inlineContent = '(no text)'; - toolTipTitle = 'Referenced element is not a value'; - toolTipContent = `Cannot display value of non-value type element`; + inlineContent = '(no text)' + toolTipTitle = 'Referenced element is not a value' + toolTipContent = `Cannot display value of non-value type element` } else { - inlineContent = this._getValueForTranscludeVal(this.mmsRecentElement); - toolTipTitle = 'Referenced element not found'; - toolTipContent = `Displaying last found ${this.mmsField} as placeholder.`; + inlineContent = this._getValueForTranscludeVal(this.mmsRecentElement) + toolTipTitle = 'Referenced element not found' + toolTipContent = `Displaying last found ${this.mmsField} as placeholder.` } } } else if (this.mmsType === 'presentation') { @@ -108,18 +108,18 @@ class AnnotationController implements angular.IComponentController { 'TYPE_TO_CLASSIFIER_ID', (this.mmsRecentElement as InstanceSpecObject).classifierIds[0], this.schema - ); + ) if (classifierType.endsWith('T')) { - classifierType = classifierType.substring(0, classifierType.length - 1); + classifierType = classifierType.substring(0, classifierType.length - 1) } - inlineContent = this.mmsRecentElement.documentation || '(no text)'; - toolTipTitle = 'Referenced ' + classifierType + ' not found.'; - toolTipContent = 'Displaying last found content as placeholder.'; + inlineContent = this.mmsRecentElement.documentation || '(no text)' + toolTipTitle = 'Referenced ' + classifierType + ' not found.' + toolTipContent = 'Displaying last found content as placeholder.' } else if (this.mmsType === 'link') { - inlineContent = this.mmsRecentElement.name; - toolTipTitle = 'Referenced view link not found'; - toolTipContent = 'Displaying last found view link as placeholder.'; + inlineContent = this.mmsRecentElement.name + toolTipTitle = 'Referenced view link not found' + toolTipContent = 'Displaying last found view link as placeholder.' } return { @@ -127,19 +127,19 @@ class AnnotationController implements angular.IComponentController { toolTipTitle: toolTipTitle, toolTipContent: toolTipContent, id: this.mmsElementId, - }; + } } private _getContentIfElementNotFound(): AnnotationObject { - const AT = this.extensionSvc.AnnotationType; - let inlineContent = ''; - const label = this.mmsElementId ? `(${this.mmsElementId})` : ''; + const AT = this.extensionSvc.AnnotationType + let inlineContent = '' + const label = this.mmsElementId ? `(${this.mmsElementId})` : '' if (this.mmsType === 'transclusion') { - inlineContent = 'cf element ' + label + ' does not exist'; + inlineContent = 'cf element ' + label + ' does not exist' } else if (this.mmsType === 'link') { - inlineContent = 'view link does not exist'; + inlineContent = 'view link does not exist' } else if (this.mmsType === 'presentation') { - inlineContent = 'presentation element does not exist'; + inlineContent = 'presentation element does not exist' } return { @@ -147,24 +147,24 @@ class AnnotationController implements angular.IComponentController { toolTipTitle: 'Element not found', toolTipContent: '', id: this.mmsElementId, - }; + } } private _getValueForTranscludeVal = (element: ElementObject): string => { - let value: unknown; + let value: unknown if (element.type === 'Property' || element.type === 'Port' || element.type === 'Slot') { if (element.defaultValue) { - value = (element.defaultValue as LiteralObject).value; + value = (element.defaultValue as LiteralObject).value } else if ((element as LiteralObject).value) { - value = (element as LiteralObject[]>).value[0].value; + value = (element as LiteralObject[]>).value[0].value } } if (element.type === 'Constraint' && element.specification) { - value = ((element as InstanceSpecObject).specification as LiteralObject).value; + value = ((element as InstanceSpecObject).specification as LiteralObject).value } - return value.toString(); - }; + return value.toString() + } } /** Used for annotating an element that doesn't have any commit history at all or for an element that is deleted but has commit history **/ @@ -189,5 +189,5 @@ const AnnotationComponent: VeComponentOptions = { mmsField: '<', }, controller: AnnotationController, -}; -veUtils.component(AnnotationComponent.selector, AnnotationComponent); +} +veUtils.component(AnnotationComponent.selector, AnnotationComponent) diff --git a/src/ve-components/components/error.component.ts b/src/ve-components/components/error.component.ts index c5a8ca329..ffa030418 100644 --- a/src/ve-components/components/error.component.ts +++ b/src/ve-components/components/error.component.ts @@ -1,51 +1,51 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { ApplicationService } from '@ve-utils/application'; +import { ApplicationService } from '@ve-utils/application' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VeComponentOptions } from '@ve-types/angular'; +import { VeComponentOptions } from '@ve-types/angular' class ExtensionErrorController implements angular.IComponentController { //Bindings - extType: string; - extKind: string; - errorMsg: string; - mmsElementId: string; + extType: string + extKind: string + errorMsg: string + mmsElementId: string //Local Structure - protected content: string; - protected title: string; - protected id: string; + protected content: string + protected title: string + protected id: string - static $inject = ['growl', 'ApplicationService']; + static $inject = ['growl', 'ApplicationService'] constructor(private growl: angular.growl.IGrowlService, private applicationSvc: ApplicationService) {} $onInit(): void { - this.id = this.mmsElementId; + this.id = this.mmsElementId if (!this.extKind && !this.extType) { - this.title = 'Error'; - this.content = this.errorMsg ? this.errorMsg : 'There was a problem displaying your content.'; - return; + this.title = 'Error' + this.content = this.errorMsg ? this.errorMsg : 'There was a problem displaying your content.' + return } - const localKind = this.extKind ? _.capitalize(this.extKind) : 'Element'; - const localExtType = _.capitalize(this.extType); + const localKind = this.extKind ? _.capitalize(this.extKind) : 'Element' + const localExtType = _.capitalize(this.extType) - this.title = 'Unsupported ' + localKind + ' Type: ' + localExtType; + this.title = 'Unsupported ' + localKind + ' Type: ' + localExtType this.content = - 'This ' + localKind + ' has a rendering type: ' + localExtType + ' that is not supported by View Editor'; + 'This ' + localKind + ' has a rendering type: ' + localExtType + ' that is not supported by View Editor' } public copyToClipboard($event: JQuery.ClickEvent): void { this.applicationSvc.copyToClipboard($('#tooltipElementId'), $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }); + this.growl.info('Copied to clipboard!', { ttl: 2000 }) }, (err) => { - this.growl.error('Unable to copy: ' + err.message); + this.growl.error('Unable to copy: ' + err.message) } - ); + ) } } @@ -71,6 +71,6 @@ const ExtensionErrorComponent: VeComponentOptions = { mmsElementId: '<', }, controller: ExtensionErrorController, -}; +} -veUtils.component(ExtensionErrorComponent.selector, ExtensionErrorComponent); +veUtils.component(ExtensionErrorComponent.selector, ExtensionErrorComponent) diff --git a/src/ve-components/components/index.ts b/src/ve-components/components/index.ts index 663d34710..8ecae0fb7 100644 --- a/src/ve-components/components/index.ts +++ b/src/ve-components/components/index.ts @@ -1,3 +1,3 @@ //Services -import './annotation.component'; -import './error.component'; +import './annotation.component' +import './error.component' diff --git a/src/ve-components/diffs/components/diff-attr.component.ts b/src/ve-components/diffs/components/diff-attr.component.ts index f0d920bde..06f5b9cc4 100644 --- a/src/ve-components/diffs/components/diff-attr.component.ts +++ b/src/ve-components/diffs/components/diff-attr.component.ts @@ -1,14 +1,14 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { ViewController } from '@ve-components/presentations'; -import { ExtensionService } from '@ve-components/services'; -import { ElementService } from '@ve-utils/mms-api-client'; -import { handleChange } from '@ve-utils/utils'; +import { ViewController } from '@ve-components/presentations' +import { ExtensionService } from '@ve-components/services' +import { ElementService } from '@ve-utils/mms-api-client' +import { handleChange } from '@ve-utils/utils' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { ElementObject, ElementsRequest, RequestObject } from '@ve-types/mms'; +import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { ElementObject, ElementsRequest, RequestObject } from '@ve-types/mms' /** * @ngdoc directive @@ -36,31 +36,31 @@ import { ElementObject, ElementsRequest, RequestObject } from '@ve-types/mms'; class DiffAttrController { //Bindings - attr: string; - elementId: string; - compareElementId: string; - projectId: string; - compareProjectId: string; + attr: string + elementId: string + compareElementId: string + projectId: string + compareProjectId: string - refId: string; - compareRefId: string; + refId: string + compareRefId: string - commitId: string; - compareCommitId: string; + commitId: string + compareCommitId: string //Controllers - mmsViewCtrl: ViewController; + mmsViewCtrl: ViewController //Local - diffLoading: boolean = false; - baseNotFound: boolean = false; - compNotFound: boolean = false; - baseDeleted: boolean = false; - compDeleted: boolean = false; - private viewOrigin: RequestObject; - baseElementHtml: string; - comparedElementHtml: string; - message: string; + diffLoading: boolean = false + baseNotFound: boolean = false + compNotFound: boolean = false + baseDeleted: boolean = false + compDeleted: boolean = false + private viewOrigin: RequestObject + baseElementHtml: string + comparedElementHtml: string + message: string static $inject = [ '$scope', @@ -71,7 +71,7 @@ class DiffAttrController { '$compile', '$q', '$interval', - ]; + ] constructor( private $scope: angular.IScope, @@ -85,42 +85,42 @@ class DiffAttrController { ) {} $onInit(): void { - this.viewOrigin = this.mmsViewCtrl ? this.mmsViewCtrl.getElementOrigin() : null; + this.viewOrigin = this.mmsViewCtrl ? this.mmsViewCtrl.getElementOrigin() : null } $postLink(): void { - this.performDiff(); + this.performDiff() } $onChanges(onChangesObj: angular.IOnChangesObject): void { - handleChange(onChangesObj, 'commitId', this.changeAction); - handleChange(onChangesObj, 'compareCommitId', this.changeAction); + handleChange(onChangesObj, 'commitId', this.changeAction) + handleChange(onChangesObj, 'compareCommitId', this.changeAction) } public diffFinish = (): void => { - this.diffLoading = false; - }; + this.diffLoading = false + } protected changeAction = (newVal, oldVal, firstChange): void => { if (!newVal || firstChange) { - return; + return } - if (oldVal !== newVal) this.performDiff(); - }; + if (oldVal !== newVal) this.performDiff() + } protected performDiff = (): void => { if (this.attr && this.extensionSvc.getTagByType('transclude', this.attr) !== 'extension-error') { this.getDiff().then( (responses: angular.PromiseValue[]) => { - const respForBaseElement = responses[0]; + const respForBaseElement = responses[0] if (respForBaseElement.state === 'fulfilled') { this._fullyRender(respForBaseElement.value).then( (baseElementHtml) => { - this.baseElementHtml = $(baseElementHtml).children().html(); + this.baseElementHtml = $(baseElementHtml).children().html() }, (reason) => { - this.growl.error(`Error getting Diff: ${reason.message}`); + this.growl.error(`Error getting Diff: ${reason.message}`) } - ); + ) } else { if ( respForBaseElement.reason && @@ -129,23 +129,23 @@ class DiffAttrController { .toLowerCase() .includes('deleted') ) { - this.baseDeleted = true; + this.baseDeleted = true } else { - this.baseNotFound = true; + this.baseNotFound = true } - this.baseElementHtml = ''; + this.baseElementHtml = '' } - const respForComparedElement = responses[1]; + const respForComparedElement = responses[1] if (respForComparedElement.state === 'fulfilled') { this._fullyRender(respForComparedElement.value).then( (comparedElementHtml) => { - this.comparedElementHtml = $(comparedElementHtml).children().html(); + this.comparedElementHtml = $(comparedElementHtml).children().html() }, () => { - this.growl.error('Problem Rendering Diff'); + this.growl.error('Problem Rendering Diff') } - ); + ) } else { if ( respForComparedElement.reason && @@ -154,65 +154,65 @@ class DiffAttrController { .toLowerCase() .includes('deleted') ) { - this.compDeleted = true; + this.compDeleted = true } else { - this.compNotFound = true; + this.compNotFound = true } - this.comparedElementHtml = ''; + this.comparedElementHtml = '' } - this.message = this._checkElementExistence(); + this.message = this._checkElementExistence() }, (reason) => { - this.growl.error(`Error getting Diff: ${reason.message}`); + this.growl.error(`Error getting Diff: ${reason.message}`) } - ); + ) } else { - this.growl.error('Unsupported Attribute for diff'); + this.growl.error('Unsupported Attribute for diff') } - }; + } public getDiff = (): VePromise[]> => { - this.diffLoading = true; + this.diffLoading = true - const baseProjectId = this.projectId || (this.viewOrigin ? this.viewOrigin.projectId : null); - const compareProjectId = this.compareProjectId || baseProjectId; + const baseProjectId = this.projectId || (this.viewOrigin ? this.viewOrigin.projectId : null) + const compareProjectId = this.compareProjectId || baseProjectId - const baseRefId = this.refId || (this.viewOrigin ? this.viewOrigin.refId : 'master'); - const compareRefId = this.compareRefId || baseRefId; + const baseRefId = this.refId || (this.viewOrigin ? this.viewOrigin.refId : 'master') + const compareRefId = this.compareRefId || baseRefId - const baseCommitId = this.commitId || 'latest'; - const compareCommitId = this.compareCommitId || 'latest'; + const baseCommitId = this.commitId || 'latest' + const compareCommitId = this.compareCommitId || 'latest' - const baseElementId = this.elementId; - const compareElementId = this.compareElementId || baseElementId; + const baseElementId = this.elementId + const compareElementId = this.compareElementId || baseElementId const baseReqOb: ElementsRequest = { elementId: baseElementId, projectId: baseProjectId, refId: baseRefId, commitId: baseCommitId, - }; + } const compareReqOb: ElementsRequest = { elementId: compareElementId, projectId: compareProjectId, refId: compareRefId, commitId: compareCommitId, - }; - const isSame = _.isEqual(baseReqOb, compareReqOb); + } + const isSame = _.isEqual(baseReqOb, compareReqOb) if (isSame) { - return; + return } - const baseElementPromise = this.elementSvc.getElement(baseReqOb); - const comparedElementPromise = this.elementSvc.getElement(compareReqOb); - return this.$q.allSettled([baseElementPromise, comparedElementPromise]); - }; + const baseElementPromise = this.elementSvc.getElement(baseReqOb) + const comparedElementPromise = this.elementSvc.getElement(compareReqOb) + return this.$q.allSettled([baseElementPromise, comparedElementPromise]) + } protected _createElement = (type: string, reqOb: ElementsRequest): JQuery => { - const ignoreMathjaxAutoFormatting = type === 'doc' || type === 'val' || type === 'com'; + const ignoreMathjaxAutoFormatting = type === 'doc' || type === 'val' || type === 'com' const html = ''; + 'mms-cf-type="{{type}}" mms-element-id="{{mmsElementId}}" mms-project-id="{{mmsProjectId}}" mms-ref-id="{{mmsRefId}}" mms-commit-id="{{commitId}}">' const newScope = Object.assign(this.$scope.$new(), { type: type, mmsElementId: reqOb.elementId, @@ -220,47 +220,47 @@ class DiffAttrController { mmsRefId: reqOb.refId, commitId: reqOb.commitId, mmsGenerateForDiff: true, - }); - return this.$compile(html)(newScope); - }; + }) + return this.$compile(html)(newScope) + } protected _fullyRender = (data: ElementObject): VePromise => { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() const element = this._createElement(this.attr, { elementId: data.id, projectId: data._projectId, refId: data._refId, commitId: data._commitId, - }); + }) const handler = this.$interval(() => { - const baseHtml = element.html(); + const baseHtml = element.html() if (!baseHtml.includes('(loading...)')) { - this.$interval.cancel(handler); - deferred.resolve(baseHtml); + this.$interval.cancel(handler) + deferred.resolve(baseHtml) } - }, 10); + }, 10) - return deferred.promise; - }; + return deferred.promise + } protected _checkElementExistence = (): string => { - let message = ''; + let message = '' if (this.baseNotFound && this.compNotFound) { - message = ' Both base and compare elements do not exist.'; + message = ' Both base and compare elements do not exist.' } else if (this.baseNotFound) { - message = ' This is a new element.'; + message = ' This is a new element.' } else if (this.compNotFound) { - message = ' Comparison element does not exist.'; + message = ' Comparison element does not exist.' } if (this.baseDeleted && this.compDeleted) { - message = ' This element has been deleted.'; + message = ' This element has been deleted.' } else if (this.baseDeleted) { - message = ' Base element has been deleted.'; + message = ' Base element has been deleted.' } else if (this.compDeleted) { - message = ' Comparison element has been deleted.'; + message = ' Comparison element has been deleted.' } - return message; - }; + return message + } } const DiffAttrComponent: VeComponentOptions = { @@ -289,6 +289,6 @@ const DiffAttrComponent: VeComponentOptions = { require: { mmsViewCtrl: '?^^view', }, -}; -veComponents.component('mmsDiffAttr', DiffAttrComponent); -veComponents.component(DiffAttrComponent.selector, DiffAttrComponent); +} +veComponents.component('mmsDiffAttr', DiffAttrComponent) +veComponents.component(DiffAttrComponent.selector, DiffAttrComponent) diff --git a/src/ve-components/diffs/components/diff-html.component.ts b/src/ve-components/diffs/components/diff-html.component.ts index 162a59aad..706503f2a 100644 --- a/src/ve-components/diffs/components/diff-html.component.ts +++ b/src/ve-components/diffs/components/diff-html.component.ts @@ -1,95 +1,95 @@ -import { handleChange } from '@ve-utils/utils'; +import { handleChange } from '@ve-utils/utils' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { HtmlRenderedDiff } from '../../../lib/html-rendered-diff'; +import { HtmlRenderedDiff } from '../../../lib/html-rendered-diff' -import { VeComponentOptions } from '@ve-types/angular'; +import { VeComponentOptions } from '@ve-types/angular' class DiffHtmlController { //bindings - private base: string; - private compare: string; - private diffCallback: () => void; + private base: string + private compare: string + private diffCallback: () => void //local - private htmlRenderedDiff: HtmlRenderedDiff; - htmlDiffIdPrefix: string = 'html-diff-'; - htmlDiffId: string; - diffResult: string; + private htmlRenderedDiff: HtmlRenderedDiff + htmlDiffIdPrefix: string = 'html-diff-' + htmlDiffId: string + diffResult: string - static $inject = ['$scope', '$timeout', 'growl']; + static $inject = ['$scope', '$timeout', 'growl'] constructor( private $scope: angular.IScope, private $timeout: angular.ITimeoutService, private growl: angular.growl.IGrowlService ) { - this.htmlRenderedDiff = window.HtmlRenderedDiff; + this.htmlRenderedDiff = window.HtmlRenderedDiff } $onInit(): void { - this.htmlDiffId = `${this.htmlDiffIdPrefix}${this.$scope.$id}`; - this.performDiff(); + this.htmlDiffId = `${this.htmlDiffIdPrefix}${this.$scope.$id}` + this.performDiff() } $onChanges(onChangesObj: angular.IOnChangesObject): void { - handleChange(onChangesObj, 'base', this.performDiff); - handleChange(onChangesObj, 'compare', this.performDiff); + handleChange(onChangesObj, 'base', this.performDiff) + handleChange(onChangesObj, 'compare', this.performDiff) } protected performDiff = (): void => { this.diffResult = this.htmlRenderedDiff.generateDiff( DiffHtmlController._preformatHtml(this.base), DiffHtmlController._preformatHtml(this.compare) - ); + ) this.$timeout(() => { - const diffContainer = $('#' + this.htmlDiffId); - this._formatImgDiff(diffContainer); - this._formatRowDiff(diffContainer); + const diffContainer = $('#' + this.htmlDiffId) + this._formatImgDiff(diffContainer) + this._formatRowDiff(diffContainer) }).then( () => { - if (this.diffCallback) this.diffCallback(); + if (this.diffCallback) this.diffCallback() }, () => { - this.growl.error('Problem performing diff.'); + this.growl.error('Problem performing diff.') } - ); - }; + ) + } static _preformatHtml(html: string): string { - return html.replace(/\r?\n|\r|\t/g, '').replace('

     

    ', ''); + return html.replace(/\r?\n|\r|\t/g, '').replace('

     

    ', '') } private _formatImgDiff = (diffContainer: JQuery): void => { diffContainer.find('img').each((index, element) => { - const img$ = $(element); + const img$ = $(element) const imgPatcherClass = img$.hasClass('patcher-insert') ? 'patcher-insert' : img$.hasClass('patcher-delete') ? 'patcher-delete' - : null; + : null if (imgPatcherClass) { - img$.wrap(''); + img$.wrap('') } - }); - }; + }) + } private _formatRowDiff = (diffContainer: JQuery): void => { diffContainer.find('tr').each((index, element) => { - const tr$: JQuery = $(element); + const tr$: JQuery = $(element) const trPatcherClass: string = tr$.hasClass('patcher-insert') ? 'patcher-insert' : tr$.hasClass('patcher-delete') ? 'patcher-delete' - : ''; + : '' if (trPatcherClass !== '') { - tr$.removeClass(trPatcherClass); + tr$.removeClass(trPatcherClass) tr$.children().each((index, el) => { - $(el).addClass(trPatcherClass); - }); + $(el).addClass(trPatcherClass) + }) } - }); - }; + }) + } } const DiffHtmlComponent: VeComponentOptions = { @@ -104,6 +104,6 @@ const DiffHtmlComponent: VeComponentOptions = { diffCallback: '&', }, controller: DiffHtmlController, -}; +} -veComponents.component(DiffHtmlComponent.selector, DiffHtmlComponent); +veComponents.component(DiffHtmlComponent.selector, DiffHtmlComponent) diff --git a/src/ve-components/diffs/components/index.ts b/src/ve-components/diffs/components/index.ts index 7d8b67fee..f11f1b958 100644 --- a/src/ve-components/diffs/components/index.ts +++ b/src/ve-components/diffs/components/index.ts @@ -1,2 +1,2 @@ -import './diff-html.component'; -import './diff-attr.component'; +import './diff-html.component' +import './diff-attr.component' diff --git a/src/ve-components/diffs/index.ts b/src/ve-components/diffs/index.ts index 06c4704a8..07116e14d 100644 --- a/src/ve-components/diffs/index.ts +++ b/src/ve-components/diffs/index.ts @@ -1,10 +1,10 @@ // Services -import './services/DiffMerge.service'; +import './services/DiffMerge.service' -export * from './services/DiffMerge.service'; +export * from './services/DiffMerge.service' //Components -import './components'; +import './components' //Modals -import './modals'; +import './modals' -export * from './modals'; +export * from './modals' diff --git a/src/ve-components/diffs/modals/index.ts b/src/ve-components/diffs/modals/index.ts index 46408f6ae..3b6483468 100644 --- a/src/ve-components/diffs/modals/index.ts +++ b/src/ve-components/diffs/modals/index.ts @@ -1,7 +1,7 @@ -import './revert-confirm.component'; -import './save-conflict.component'; -import './merge-confirm-modal.component'; +import './revert-confirm.component' +import './save-conflict.component' +import './merge-confirm-modal.component' -export * from './merge-confirm-modal.component'; -export * from './revert-confirm.component'; -export * from './save-conflict.component'; +export * from './merge-confirm-modal.component' +export * from './revert-confirm.component' +export * from './save-conflict.component' diff --git a/src/ve-components/diffs/modals/merge-confirm-modal.component.ts b/src/ve-components/diffs/modals/merge-confirm-modal.component.ts index 8b7e05cba..fc4cfb238 100644 --- a/src/ve-components/diffs/modals/merge-confirm-modal.component.ts +++ b/src/ve-components/diffs/modals/merge-confirm-modal.component.ts @@ -1,54 +1,54 @@ -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { RefObject } from '@ve-types/mms'; -import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; +import { RefObject } from '@ve-types/mms' +import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' export interface MergeConfirmResolve extends VeModalResolve { - getSrcRefOb: RefObject; - getDocName: string; + getSrcRefOb: RefObject + getDocName: string } export interface MergeConfirmResolveFn extends VeModalResolveFn { - getSrcRefOb(): RefObject; - getDocName(): string; + getSrcRefOb(): RefObject + getDocName(): string } class MergeConfirmModalController extends VeModalControllerImpl implements VeModalController { //Bindings - protected resolve: MergeConfirmResolve; + protected resolve: MergeConfirmResolve - oking: boolean; - commitMessage: string; - createForm: boolean; - srcRefOb: RefObject; - docName: string; + oking: boolean + commitMessage: string + createForm: boolean + srcRefOb: RefObject + docName: string - static $inject = ['growl']; + static $inject = ['growl'] constructor(private growl: angular.growl.IGrowlService) { - super(); + super() } $onInit(): void { - this.srcRefOb = this.resolve.getSrcRefOb; - this.docName = this.resolve.getDocName; - this.oking = false; - this.commitMessage = ''; - this.createForm = true; + this.srcRefOb = this.resolve.getSrcRefOb + this.docName = this.resolve.getDocName + this.oking = false + this.commitMessage = '' + this.createForm = true } public ok = (): void => { if (this.oking) { - this.growl.info('Please wait...'); - return; + this.growl.info('Please wait...') + return } - this.oking = false; - }; + this.oking = false + } public cancel = (): void => { - this.modalInstance.dismiss(); - }; + this.modalInstance.dismiss() + } } const MergeConfirmModalComponent: VeModalComponent = { @@ -88,6 +88,6 @@ const MergeConfirmModalComponent: VeModalComponent = { resolve: '<', }, controller: MergeConfirmModalController, -}; +} -veComponents.component(MergeConfirmModalComponent.selector, MergeConfirmModalComponent); +veComponents.component(MergeConfirmModalComponent.selector, MergeConfirmModalComponent) diff --git a/src/ve-components/diffs/modals/revert-confirm.component.ts b/src/ve-components/diffs/modals/revert-confirm.component.ts index c1fce2b39..17101c660 100644 --- a/src/ve-components/diffs/modals/revert-confirm.component.ts +++ b/src/ve-components/diffs/modals/revert-confirm.component.ts @@ -1,40 +1,40 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { Commit, CompareData } from '@ve-components/diffs'; -import { EventService } from '@ve-utils/core'; -import { ElementService } from '@ve-utils/mms-api-client'; +import { Commit, CompareData } from '@ve-components/diffs' +import { EventService } from '@ve-utils/core' +import { ElementService } from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions } from '@ve-types/angular'; -import { ConstraintObject, ElementObject, ElementsRequest, ElementTaggedValueObject, SlotObject } from '@ve-types/mms'; -import { VeModalController, VeModalInstanceService } from '@ve-types/view-editor'; +import { VeComponentOptions } from '@ve-types/angular' +import { ConstraintObject, ElementObject, ElementsRequest, ElementTaggedValueObject, SlotObject } from '@ve-types/mms' +import { VeModalController, VeModalInstanceService } from '@ve-types/view-editor' export interface RevertConfirmResolve { - reqOb: ElementsRequest; - revertData: CompareData; + reqOb: ElementsRequest + revertData: CompareData } export interface RevertConfirmResolveFn { - reqOb(): ElementsRequest; + reqOb(): ElementsRequest revertData(): { - baseCommit: Commit; - compareCommit: Commit; - element: ElementObject; - }; + baseCommit: Commit + compareCommit: Commit + element: ElementObject + } } class RevertConfirmController implements VeModalController { //bindings - public modalInstance: VeModalInstanceService; - public resolve: RevertConfirmResolve; + public modalInstance: VeModalInstanceService + public resolve: RevertConfirmResolve - public oking; - revertData: CompareData; - reqOb: ElementsRequest; - element: ElementObject; + public oking + revertData: CompareData + reqOb: ElementsRequest + element: ElementObject - static $inject = ['growl', 'ElementService', 'EventService']; + static $inject = ['growl', 'ElementService', 'EventService'] constructor( private growl: angular.growl.IGrowlService, @@ -43,26 +43,26 @@ class RevertConfirmController implements VeModalController { ) {} $onInit(): void { - this.revertData = this.resolve.revertData; - this.reqOb = this.resolve.reqOb; + this.revertData = this.resolve.revertData + this.reqOb = this.resolve.reqOb this.elementSvc.getElement(this.reqOb).then((el) => { - this.element = el; - }); + this.element = el + }) } ok(): void { if (this.oking) { - this.growl.info('Please wait...'); - return; + this.growl.info('Please wait...') + return } - this.oking = true; + this.oking = true - const reqOb = _.cloneDeep(this.reqOb); - reqOb.refId = this.revertData.baseCommit.ref.id; + const reqOb = _.cloneDeep(this.reqOb) + reqOb.refId = this.revertData.baseCommit.ref.id reqOb.commitId = typeof this.revertData.baseCommit.commitSelected === 'string' ? this.revertData.baseCommit.commitSelected - : this.revertData.baseCommit.commitSelected.id; + : this.revertData.baseCommit.commitSelected.id this.elementSvc .getElement(reqOb, 2, false) .then( @@ -74,19 +74,19 @@ class RevertConfirmController implements VeModalController { documentation: targetOb.documentation, _projectId: this.reqOb.projectId, _refId: this.reqOb.refId, - }; + } if (revertOb.type === 'Property' || revertOb.type === 'Port') { - revertOb.defaultValue = _.cloneDeep(targetOb.defaultValue); + revertOb.defaultValue = _.cloneDeep(targetOb.defaultValue) } else if (revertOb.type === 'ElementTaggedValue') { - (revertOb as ElementTaggedValueObject).valueIds = _.cloneDeep( + ;(revertOb as ElementTaggedValueObject).valueIds = _.cloneDeep( (targetOb as ElementTaggedValueObject).valueIds - ); + ) } else if (revertOb.type === 'Slot' || revertOb.type.endsWith('TaggedValue')) { - (revertOb as SlotObject).value = _.cloneDeep((targetOb as SlotObject).value); + ;(revertOb as SlotObject).value = _.cloneDeep((targetOb as SlotObject).value) } else if (revertOb.type === 'Constraint' && revertOb.specification) { - (revertOb as ConstraintObject).specification = _.cloneDeep( + ;(revertOb as ConstraintObject).specification = _.cloneDeep( (targetOb as ConstraintObject).specification - ); + ) } this.elementSvc.updateElement(revertOb).then( @@ -94,25 +94,25 @@ class RevertConfirmController implements VeModalController { const data = { element: element, continueEdit: false, - }; - this.eventSvc.$broadcast('element.updated', data); - this.modalInstance.close(); + } + this.eventSvc.$broadcast('element.updated', data) + this.modalInstance.close() }, (reason) => { - this.growl.error('Revert not completed - Update Error: ' + reason.message); + this.growl.error('Revert not completed - Update Error: ' + reason.message) } - ); + ) }, (reason) => { - this.growl.error('Revert not completed - Error: Target Version not found'); + this.growl.error('Revert not completed - Error: Target Version not found') } ) .finally(() => { - this.oking = false; - }); + this.oking = false + }) } cancel(): void { - this.modalInstance.dismiss(); + this.modalInstance.dismiss() } } @@ -160,6 +160,6 @@ const RevertConfirmComponent: VeComponentOptions = { resolve: '<', }, controller: RevertConfirmController, -}; +} -veComponents.component(RevertConfirmComponent.selector, RevertConfirmComponent); +veComponents.component(RevertConfirmComponent.selector, RevertConfirmComponent) diff --git a/src/ve-components/diffs/modals/save-conflict.component.ts b/src/ve-components/diffs/modals/save-conflict.component.ts index a4aa95bb5..0ae49b4d3 100644 --- a/src/ve-components/diffs/modals/save-conflict.component.ts +++ b/src/ve-components/diffs/modals/save-conflict.component.ts @@ -1,44 +1,44 @@ -import { IComponentController } from 'angular'; +import { IComponentController } from 'angular' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions } from '@ve-types/angular'; -import { ElementObject } from '@ve-types/mms'; -import { VeModalInstanceService, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; +import { VeComponentOptions } from '@ve-types/angular' +import { ElementObject } from '@ve-types/mms' +import { VeModalInstanceService, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' export interface SaveConflictResolve extends VeModalResolve { - latest: T; + latest: T } export interface SaveConflictResolveFn extends VeModalResolveFn { - latest(): T; + latest(): T } class SaveConflictController implements IComponentController { //bindings - private modalInstance: VeModalInstanceService; - resolve: SaveConflictResolve; + private modalInstance: VeModalInstanceService + resolve: SaveConflictResolve //local - public latest: ElementObject; + public latest: ElementObject $onInit(): void { - this.latest = this.resolve.latest; + this.latest = this.resolve.latest } ok(): void { - this.modalInstance.close('ok'); + this.modalInstance.close('ok') } cancel(): void { - this.modalInstance.close('cancel'); + this.modalInstance.close('cancel') } force(): void { - this.modalInstance.close('force'); + this.modalInstance.close('force') } merge(): void { - this.modalInstance.close('merge'); + this.modalInstance.close('merge') } } @@ -67,6 +67,6 @@ const SaveConflictComponent: VeComponentOptions = { modalInstance: '<', }, controller: SaveConflictController, -}; +} -veComponents.component(SaveConflictComponent.selector, SaveConflictComponent); +veComponents.component(SaveConflictComponent.selector, SaveConflictComponent) diff --git a/src/ve-components/diffs/services/DiffMerge.service.ts b/src/ve-components/diffs/services/DiffMerge.service.ts index 9db0c311b..4f088fe43 100644 --- a/src/ve-components/diffs/services/DiffMerge.service.ts +++ b/src/ve-components/diffs/services/DiffMerge.service.ts @@ -1,42 +1,42 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { RevertConfirmResolveFn } from '@ve-components/diffs'; -import { ApiService, ElementService } from '@ve-utils/mms-api-client'; +import { RevertConfirmResolveFn } from '@ve-components/diffs' +import { ApiService, ElementService } from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; -import { CommitObject, ElementObject, ElementsRequest, RefObject } from '@ve-types/mms'; -import { VeModalService } from '@ve-types/view-editor'; +import { VePromise, VeQService } from '@ve-types/angular' +import { CommitObject, ElementObject, ElementsRequest, RefObject } from '@ve-types/mms' +import { VeModalService } from '@ve-types/view-editor' export interface Commit { - ref: RefObject; - isOpen: boolean; - refIsOpen?: boolean; - history: CommitObject[]; - commitSelected: CommitObject | string; + ref: RefObject + isOpen: boolean + refIsOpen?: boolean + history: CommitObject[] + commitSelected: CommitObject | string } export interface CompareData { - baseCommit: Commit; - compareCommit: Commit; - element: ElementObject; + baseCommit: Commit + compareCommit: Commit + element: ElementObject } export interface DiffResponse { - status?: 'new' | 'deleted' | 'changed'; - diff?: DiffDetail; + status?: 'new' | 'deleted' | 'changed' + diff?: DiffDetail } export interface DiffDetail { - name: boolean; - documentation: boolean; - value: boolean; - [key: string]: boolean; + name: boolean + documentation: boolean + value: boolean + [key: string]: boolean } export class DiffMergeService { - static $inject = ['$q', 'growl', '$uibModal', 'ApiService', 'ElementService']; + static $inject = ['$q', 'growl', '$uibModal', 'ApiService', 'ElementService'] constructor( private $q: VeQService, private growl: angular.growl.IGrowlService, @@ -66,80 +66,80 @@ export class DiffMergeService { component: 'revertConfirm', resolve: { reqOb: () => { - return reqOb; + return reqOb }, revertData: () => { - return revertData; + return revertData }, }, - }); + }) instance.result.then( () => { - this.growl.success('Element reverted'); + this.growl.success('Element reverted') }, () => { - this.growl.error('Revert Cancelled'); + this.growl.error('Revert Cancelled') } - ); + ) } public checkDiff(sourceOb: ElementObject): VePromise { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() const diff: DiffDetail = { name: false, documentation: false, value: false, - }; - let response: DiffResponse; + } + let response: DiffResponse this.elementSvc.getElement(this.apiSvc.makeElementRequestObject(sourceOb), 1, true, true).then( (targetOb) => { if (!targetOb) { - response.status = 'new'; - deferred.resolve(response); + response.status = 'new' + deferred.resolve(response) } if (sourceOb.name !== targetOb.name) { - diff.name = true; + diff.name = true } if (sourceOb.documentation !== targetOb.documentation) { - diff.documentation = true; + diff.documentation = true } if ( (sourceOb.type === 'Property' || sourceOb.type === 'Port') && !_.isEqual(sourceOb.defaultValue, targetOb.defaultValue) ) { - diff.value = true; + diff.value = true } else if (sourceOb.type === 'Slot' && !_.isEqual(sourceOb.value, targetOb.value)) { - diff.value = true; + diff.value = true } else if ( sourceOb.type === 'Constraint' && !_.isEqual(sourceOb.specification, targetOb.specification) ) { - diff.value = true; + diff.value = true } - let changed = false; + let changed = false Object.keys(diff).forEach((value) => { - changed = changed || diff[value]; - }); + changed = changed || diff[value] + }) if (changed) { response = { status: 'changed', diff, - }; + } } - deferred.resolve(response); + deferred.resolve(response) }, (reason) => { if (reason.status === 410) { - response.status = 'deleted'; - deferred.resolve(response); + response.status = 'deleted' + deferred.resolve(response) } else { - this.growl.error(`Diff Check not completed - ${reason.message}`); - deferred.reject(null); + this.growl.error(`Diff Check not completed - ${reason.message}`) + deferred.reject(null) } } - ); - return deferred.promise; + ) + return deferred.promise } } -veComponents.service('DiffMergeService', DiffMergeService); +veComponents.service('DiffMergeService', DiffMergeService) diff --git a/src/ve-components/index.ts b/src/ve-components/index.ts index 42e0d382b..1e06f68b1 100644 --- a/src/ve-components/index.ts +++ b/src/ve-components/index.ts @@ -9,30 +9,30 @@ // import '@ve-core' //Module Main -import './ve-components.module'; +import './ve-components.module' -import './services'; +import './services' -import './components'; +import './components' // Extensions -import './trees'; -import './diffs'; -import './presentations'; -import './transclusions'; -import './spec-tools'; -import './insertions'; +import './trees' +import './diffs' +import './presentations' +import './transclusions' +import './spec-tools' +import './insertions' -export * from './ve-components.module'; +export * from './ve-components.module' -import '../ve-extensions'; -import { ElementObject } from '@ve-types/mms'; +import '../ve-extensions' +import { ElementObject } from '@ve-types/mms' -export default 've-components'; +export default 've-components' export interface PropertySpec { - options?: ElementObject[]; - isEnumeration?: boolean; - isSlot?: boolean; - isTaggedValue?: boolean; + options?: ElementObject[] + isEnumeration?: boolean + isSlot?: boolean + isTaggedValue?: boolean } diff --git a/src/ve-components/insertions/components/index.ts b/src/ve-components/insertions/components/index.ts index 7fb74bce5..04e141fb4 100644 --- a/src/ve-components/insertions/components/index.ts +++ b/src/ve-components/insertions/components/index.ts @@ -1,5 +1,5 @@ -import './insert-comment.component'; -import './insert-pe.component'; -import './insert-view.component'; -import './insert-ref.component'; -import './insert-element.component'; +import './insert-comment.component' +import './insert-pe.component' +import './insert-view.component' +import './insert-ref.component' +import './insert-element.component' diff --git a/src/ve-components/insertions/components/insert-comment.component.ts b/src/ve-components/insertions/components/insert-comment.component.ts index 051404f7d..aca5c2d2f 100644 --- a/src/ve-components/insertions/components/insert-comment.component.ts +++ b/src/ve-components/insertions/components/insert-comment.component.ts @@ -1,20 +1,20 @@ -import { Insertion, InsertionService } from '@ve-components/insertions'; -import { EditorService } from '@ve-core/editor'; -import { ApplicationService, UtilsService } from '@ve-utils/application'; -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; -import { Class } from '@ve-utils/utils'; +import { Insertion, InsertionService } from '@ve-components/insertions' +import { EditorService } from '@ve-core/editor' +import { ApplicationService, UtilsService } from '@ve-utils/application' +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' +import { Class } from '@ve-utils/utils' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { InsertData } from '@ve-types/components'; -import { ElementCreationRequest, ElementObject } from '@ve-types/mms'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { InsertData } from '@ve-types/components' +import { ElementCreationRequest, ElementObject } from '@ve-types/mms' +import { VeModalService } from '@ve-types/view-editor' class InsertCommentController extends Insertion { - protected comment: ElementObject; - static $inject = Insertion.$inject; + protected comment: ElementObject + static $inject = Insertion.$inject constructor( $scope: angular.IScope, @@ -49,12 +49,12 @@ class InsertCommentController extends Insertion { apiSvc, utils, editorSvc - ); + ) } public $onInit(): void { - super.$onInit(); - const id = this.apiSvc.createUniqueId(); + super.$onInit() + const id = this.apiSvc.createUniqueId() this.comment = new Class({ id: id, _projectId: this.mmsProjectId, @@ -64,24 +64,24 @@ class InsertCommentController extends Insertion { type: 'Class', ownerId: 'holding_bin_' + this.mmsProjectId, appliedStereotypeIds: [], - }); - this.oking = false; + }) + this.oking = false } public create = (): VePromise => { if (this.oking) { - this.growl.info('Please wait...'); - return; + this.growl.info('Please wait...') + return } - this.oking = true; + this.oking = true const reqOb: ElementCreationRequest = { elements: [this.comment], elementId: this.comment.id, projectId: this.mmsProjectId, refId: this.mmsRefId, - }; - return this.elementSvc.createElement(reqOb); - }; + } + return this.elementSvc.createElement(reqOb) + } } const InsertCommentComponent: VeComponentOptions = { @@ -115,6 +115,6 @@ const InsertCommentComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertCommentController, -}; +} -veComponents.component(InsertCommentComponent.selector, InsertCommentComponent); +veComponents.component(InsertCommentComponent.selector, InsertCommentComponent) diff --git a/src/ve-components/insertions/components/insert-element.component.ts b/src/ve-components/insertions/components/insert-element.component.ts index 3847913c4..b70077d7c 100644 --- a/src/ve-components/insertions/components/insert-element.component.ts +++ b/src/ve-components/insertions/components/insert-element.component.ts @@ -1,29 +1,29 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { Insertion, InsertionService } from '@ve-components/insertions'; -import { InsertTransclusionData } from '@ve-components/transclusions'; -import { EditorService } from '@ve-core/editor'; -import { ApplicationService, UtilsService } from '@ve-utils/application'; -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { Insertion, InsertionService } from '@ve-components/insertions' +import { InsertTransclusionData } from '@ve-components/transclusions' +import { EditorService } from '@ve-core/editor' +import { ApplicationService, UtilsService } from '@ve-utils/application' +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { ElementObject, MmsObject } from '@ve-types/mms'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { ElementObject, MmsObject } from '@ve-types/mms' +import { VeModalService } from '@ve-types/view-editor' class InsertElementController extends Insertion { //Bindings - protected parentAction: string; + protected parentAction: string //Locals //protected createType: number = 1 - protected description: string; - protected searchExisting: boolean = true; - protected disableCreateNew: boolean = false; + protected description: string + protected searchExisting: boolean = true + protected disableCreateNew: boolean = false - static $inject = Insertion.$inject; + static $inject = Insertion.$inject constructor( $scope: angular.IScope, @@ -58,15 +58,15 @@ class InsertElementController extends Insertion { apiSvc, insertionSvc, editorSvc - ); + ) } public $onInit(): void { - super.$onInit(); + super.$onInit() if (this.insertData.selected && this.insertData.isNew) { - this.createItem = this.insertData.selected; - this.searchExisting = false; + this.createItem = this.insertData.selected + this.searchExisting = false } else { this.createItem = { id: `${this.apiSvc.createUniqueId()}`, @@ -77,32 +77,32 @@ class InsertElementController extends Insertion { documentation: '', type: 'Class', appliedStereotypeIds: [], - }; + } } - this.disableCreateNew = this.insertData.viewLink; + this.disableCreateNew = this.insertData.viewLink if (!this.disableCreateNew) { - this.editItem = this.elementSvc.openEdit(this.createItem, false); + this.editItem = this.elementSvc.openEdit(this.createItem, false) } - this.description = 'Search for an existing element before you ' + this.parentAction; + this.description = 'Search for an existing element before you ' + this.parentAction - this.searchOptions.getProperties = true; - this.searchOptions.emptyDocTxt = 'This field is empty, but you can still click here to mms-cf a placeholder.'; + this.searchOptions.getProperties = true + this.searchOptions.emptyDocTxt = 'This field is empty, but you can still click here to mms-cf a placeholder.' } public create = (): VePromise => { - this.insertData.isNew = true; - return this.insertionSvc.createAction(this.createItem, this.insertData.noPublish); - }; + this.insertData.isNew = true + return this.insertionSvc.createAction(this.createItem, this.insertData.noPublish) + } public fail = >(reason: V): void => { if (reason.status === 401) { - this.reLogin(); + this.reLogin() } else if (reason.status === 422) { - this.continue = true; + this.continue = true } else { - this.growl.error(`Create ${_.upperCase(this.insertData.type)} Error: ${reason.message}`); + this.growl.error(`Create ${_.upperCase(this.insertData.type)} Error: ${reason.message}`) } - }; + } } // Component for inserting cross-reference @@ -176,6 +176,6 @@ const InsertComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertElementController, -}; +} -veComponents.component(InsertComponent.selector, InsertComponent); +veComponents.component(InsertComponent.selector, InsertComponent) diff --git a/src/ve-components/insertions/components/insert-pe.component.ts b/src/ve-components/insertions/components/insert-pe.component.ts index 6889cdcfd..380d267b6 100644 --- a/src/ve-components/insertions/components/insert-pe.component.ts +++ b/src/ve-components/insertions/components/insert-pe.component.ts @@ -1,28 +1,28 @@ -import { Insertion, InsertionService } from '@ve-components/insertions'; -import { EditorService } from '@ve-core/editor'; -import { SearchFilter } from '@ve-core/search/mms-search.component'; -import { ApplicationService, UtilsService } from '@ve-utils/application'; -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { Insertion, InsertionService } from '@ve-components/insertions' +import { EditorService } from '@ve-core/editor' +import { SearchFilter } from '@ve-core/search/mms-search.component' +import { ApplicationService, UtilsService } from '@ve-utils/application' +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { InsertData } from '@ve-types/components'; -import { InstanceValueObject, ViewCreationRequest, ViewInstanceSpec } from '@ve-types/mms'; -import { TreeBranch } from '@ve-types/tree'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { InsertData } from '@ve-types/components' +import { InstanceValueObject, ViewCreationRequest, ViewInstanceSpec } from '@ve-types/mms' +import { TreeBranch } from '@ve-types/tree' +import { VeModalService } from '@ve-types/view-editor' export interface InsertPresentationData extends InsertData { - parentBranch: TreeBranch; - viewOrSectionOb?: ViewInstanceSpec; - addPeIndex: number; + parentBranch: TreeBranch + viewOrSectionOb?: ViewInstanceSpec + addPeIndex: number } class InsertPeController extends Insertion { - protected aggr: 'composite' | 'shared'; + protected aggr: 'composite' | 'shared' - static $inject = Insertion.$inject; + static $inject = Insertion.$inject constructor( $scope: angular.IScope, @@ -57,54 +57,54 @@ class InsertPeController extends Insertion { apiSvc, utils, editorSvc - ); + ) } $onInit(): void { - super.$onInit(); + super.$onInit() } public queryFilter = (): SearchFilter => { const filters: { - appliedStereotypeIds?: string[]; - classifierIds?: string[]; - } = {}; + appliedStereotypeIds?: string[] + classifierIds?: string[] + } = {} if (this.type === 'Table') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'TableT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Table', this.schema), - ]; + ] } else if (this.type === 'List') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'ListT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'List', this.schema), - ]; + ] } else if (this.type === 'Image') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'ImageT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Image', this.schema), - ]; + ] } else if (this.type === 'Paragraph') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'ParagraphT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Paragraph', this.schema), - ]; + ] } else if (this.type === 'Section') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'SectionT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Section', this.schema), - ]; + ] } else { - filters.classifierIds = [this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', this.type, this.schema)]; + filters.classifierIds = [this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', this.type, this.schema)] } - return filters; - }; + return filters + } public success = (): void => { - const elemType = this.type; - this.insertionSvc.successUpdates(elemType, this.insertData.viewOrSectionOb.id); - this.growl.success(this.type + ' is being created'); - }; + const elemType = this.type + this.insertionSvc.successUpdates(elemType, this.insertData.viewOrSectionOb.id) + this.growl.success(this.type + ' is being created') + } public insert = (elementOb: ViewInstanceSpec): VePromise => { const instanceVal: InstanceValueObject = { @@ -113,14 +113,14 @@ class InsertPeController extends Insertion { type: 'InstanceValue', _projectId: this.projectId, _refId: this.refId, - }; + } const viewReqOb: ViewCreationRequest = { viewId: this.insertData.viewOrSectionOb.id, projectId: this.projectId, refId: this.refId, - }; - return this.viewSvc.insertToViewOrSection(viewReqOb, instanceVal, this.insertData.addPeIndex); - }; + } + return this.viewSvc.insertToViewOrSection(viewReqOb, instanceVal, this.insertData.addPeIndex) + } public create = (): VePromise => { return this.viewSvc.createInstanceSpecification( @@ -128,8 +128,8 @@ class InsertPeController extends Insertion { this.type, this.name, this.insertData.addPeIndex - ); - }; + ) + } } const InsertPeComponent: VeComponentOptions = { @@ -179,6 +179,6 @@ const InsertPeComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertPeController, -}; +} -veComponents.component(InsertPeComponent.selector, InsertPeComponent); +veComponents.component(InsertPeComponent.selector, InsertPeComponent) diff --git a/src/ve-components/insertions/components/insert-ref.component.ts b/src/ve-components/insertions/components/insert-ref.component.ts index 69790680e..181cb5ae6 100644 --- a/src/ve-components/insertions/components/insert-ref.component.ts +++ b/src/ve-components/insertions/components/insert-ref.component.ts @@ -1,31 +1,31 @@ -import flatpickr from 'flatpickr'; +import flatpickr from 'flatpickr' -import { Insertion, InsertionService } from '@ve-components/insertions'; -import { EditorService } from '@ve-core/editor'; -import { ApplicationService, UtilsService } from '@ve-utils/application'; -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { Insertion, InsertionService } from '@ve-components/insertions' +import { EditorService } from '@ve-core/editor' +import { ApplicationService, UtilsService } from '@ve-utils/application' +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { InsertData } from '@ve-types/components'; -import { CommitObject, RefObject, RefsResponse } from '@ve-types/mms'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { InsertData } from '@ve-types/components' +import { CommitObject, RefObject, RefsResponse } from '@ve-types/mms' +import { VeModalService } from '@ve-types/view-editor' export interface InsertRefData extends InsertData { - parentRefId: string; - lastCommit: boolean; + parentRefId: string + lastCommit: boolean } class InsertRefController extends Insertion { - static $inject = [...Insertion.$inject, '$filter']; + static $inject = [...Insertion.$inject, '$filter'] - protected parentCommit: CommitObject; - protected lastCommit: boolean; - protected now: Date; - protected dateTimeOpts: flatpickr.Options.Options; - protected timestamp: Date; + protected parentCommit: CommitObject + protected lastCommit: boolean + protected now: Date + protected dateTimeOpts: flatpickr.Options.Options + protected timestamp: Date constructor( $scope: angular.IScope, @@ -60,22 +60,22 @@ class InsertRefController extends Insertion { apiSvc, utils, editorSvc - ); + ) } public $onInit(): void { - super.$onInit(); + super.$onInit() - this.lastCommit = this.insertData.lastCommit; - this.now = new Date(); - this.timestamp = this.now; + this.lastCommit = this.insertData.lastCommit + this.now = new Date() + this.timestamp = this.now this.createItem = { id: this.apiSvc.createUniqueId(), _projectId: this.projectId, type: this.type, description: '', permission: 'read', - }; + } this.dateTimeOpts = { enableTime: true, enableSeconds: true, @@ -84,11 +84,11 @@ class InsertRefController extends Insertion { time_24hr: true, maxDate: new Date(), onClose: (selectedDates): void => { - this.lastCommit = false; - this.timestamp = selectedDates[0]; + this.lastCommit = false + this.timestamp = selectedDates[0] }, inline: false, - }; + } } public create = (): VePromise => { @@ -99,8 +99,8 @@ class InsertRefController extends Insertion { description: this.createItem.description, id: this.apiSvc.createUniqueId(), //parentCommitId: null - }; - if (this.insertData.parentRefId) refObj.parentRefId = this.insertData.parentRefId; + } + if (this.insertData.parentRefId) refObj.parentRefId = this.insertData.parentRefId /* if (!this.lastCommit || this.type === 'Tag') { // Make call to history?maxTimestamp to get closest commit id to branch off @@ -112,17 +112,17 @@ class InsertRefController extends Insertion { }, this.insertReject) } else { */ - return this.projectSvc.createRef(refObj, this.projectId); + return this.projectSvc.createRef(refObj, this.projectId) //} - }; + } public resolve = (data: RefObject): void => { - this.growl.success(this.type + ' is being created'); + this.growl.success(this.type + ' is being created') if (this.type === 'Tag') { - this.growl.info('Please wait for a completion email prior to viewing of the tag.'); + this.growl.info('Please wait for a completion email prior to viewing of the tag.') } - this.insertApi.resolve(data); - }; + this.insertApi.resolve(data) + } } const InsertRefComponent: VeComponentOptions = { @@ -203,6 +203,6 @@ const InsertRefComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertRefController, -}; +} -veComponents.component(InsertRefComponent.selector, InsertRefComponent); +veComponents.component(InsertRefComponent.selector, InsertRefComponent) diff --git a/src/ve-components/insertions/components/insert-view.component.ts b/src/ve-components/insertions/components/insert-view.component.ts index aa8d74e30..3453aa9e0 100644 --- a/src/ve-components/insertions/components/insert-view.component.ts +++ b/src/ve-components/insertions/components/insert-view.component.ts @@ -1,28 +1,28 @@ -import { Insertion, InsertionService } from '@ve-components/insertions'; -import { EditorService } from '@ve-core/editor'; -import { SearchFilter } from '@ve-core/search/mms-search.component'; -import { ApplicationService, UtilsService } from '@ve-utils/application'; -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { Insertion, InsertionService } from '@ve-components/insertions' +import { EditorService } from '@ve-core/editor' +import { SearchFilter } from '@ve-core/search/mms-search.component' +import { ApplicationService, UtilsService } from '@ve-utils/application' +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { InsertData } from '@ve-types/components'; -import { ViewObject } from '@ve-types/mms'; -import { TreeBranch } from '@ve-types/tree'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { InsertData } from '@ve-types/components' +import { ViewObject } from '@ve-types/mms' +import { TreeBranch } from '@ve-types/tree' +import { VeModalService } from '@ve-types/view-editor' export interface InsertViewData extends InsertData { - parentBranch: TreeBranch; - seenViewIds: { [viewId: string]: TreeBranch }; - newViewAggr?: 'composite' | 'shared'; + parentBranch: TreeBranch + seenViewIds: { [viewId: string]: TreeBranch } + newViewAggr?: 'composite' | 'shared' } class InsertViewController extends Insertion { - private aggr: 'composite' | 'shared' = 'composite'; + private aggr: 'composite' | 'shared' = 'composite' - static $inject = Insertion.$inject; + static $inject = Insertion.$inject constructor( $scope: angular.IScope, @@ -57,32 +57,32 @@ class InsertViewController extends Insertion { apiSvc, utils, editorSvc - ); + ) } public $onInit(): void { - super.$onInit(); + super.$onInit() if (this.insertData.newViewAggr) { - this.aggr = this.insertData.newViewAggr; + this.aggr = this.insertData.newViewAggr } if (this.insertData.parentBranch) { - this.parentData = this.insertData.parentBranch.data; + this.parentData = this.insertData.parentBranch.data } } public insert = (data: ViewObject): VePromise => { - const deferred = this.$q.defer(); - const view = data; - const viewId = view.id; + const deferred = this.$q.defer() + const view = data + const viewId = view.id if (this.insertData.seenViewIds[viewId]) { - this.growl.error('Error: View ' + view.name + ' is already in this document.'); - return; + this.growl.error('Error: View ' + view.name + ' is already in this document.') + return } if (this.oking) { - this.growl.info('Please wait...'); - return; + this.growl.info('Please wait...') + return } - this.oking = true; + this.oking = true this.viewSvc .addViewToParentView({ parentViewId: this.parentData.id, @@ -106,34 +106,34 @@ class InsertViewController extends Insertion { ) .then( (realView) => { - deferred.resolve(realView); + deferred.resolve(realView) }, (reason) => { - reason.data.elements = [view]; - deferred.reject(reason); + reason.data.elements = [view] + deferred.reject(reason) } - ); + ) }, (reason) => { - this.growl.error(`View Add Error: ${reason.message}`); + this.growl.error(`View Add Error: ${reason.message}`) } - ); - return deferred.promise; - }; + ) + return deferred.promise + } public last = (): void => { - this.growl.success('View Added'); - }; + this.growl.success('View Added') + } public queryFilter = (): SearchFilter => { - const filters: SearchFilter = {}; + const filters: SearchFilter = {} filters.appliedStereotypeIds = [ this.schemaSvc.getSchema('VIEW_SID', this.schema), this.schemaSvc.getSchema('DOCUMENT_SID', this.schema), ...this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema), - ]; - return filters; - }; + ] + return filters + } public create = (): VePromise => { if (this.type === 'Document') { @@ -151,7 +151,7 @@ class InsertViewController extends Insertion { _refId: this.refId, type: 'Class', } - ); + ) } else if (this.type === 'View') { return this.viewSvc.createView(this.parentData, { id: this.apiSvc.createUniqueId(), @@ -159,20 +159,20 @@ class InsertViewController extends Insertion { _projectId: this.projectId, _refId: this.refId, type: 'Class', - }); + }) } else if (this.type === 'Group') { return this.viewSvc.createGroup(this.createItem.name, { _projectId: this.projectId, _refId: this.refId, id: this.ownerId, - }); + }) } else { return this.$q.reject({ status: 666, message: 'Unsupported View Type', - }); + }) } - }; + } } const InsertViewComponent: VeComponentOptions = { @@ -232,8 +232,8 @@ const InsertViewComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertViewController, -}; +} -veComponents.component(InsertViewComponent.selector, InsertViewComponent); -veComponents.component('addGroup', InsertViewComponent); -veComponents.component('addDocument', InsertViewComponent); +veComponents.component(InsertViewComponent.selector, InsertViewComponent) +veComponents.component('addGroup', InsertViewComponent) +veComponents.component('addDocument', InsertViewComponent) diff --git a/src/ve-components/insertions/index.ts b/src/ve-components/insertions/index.ts index 0bdb1f101..7d7171262 100644 --- a/src/ve-components/insertions/index.ts +++ b/src/ve-components/insertions/index.ts @@ -1,8 +1,8 @@ -export * from './insertion.controller'; +export * from './insertion.controller' -import './services'; +import './services' -export * from './services'; -import './insert-element-modal.component'; +export * from './services' +import './insert-element-modal.component' -import './components'; +import './components' diff --git a/src/ve-components/insertions/insert-element-modal.component.ts b/src/ve-components/insertions/insert-element-modal.component.ts index d7bb836c9..a9d2a9ba4 100644 --- a/src/ve-components/insertions/insert-element-modal.component.ts +++ b/src/ve-components/insertions/insert-element-modal.component.ts @@ -1,29 +1,29 @@ -import { ExtensionService } from '@ve-components/services'; -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; +import { ExtensionService } from '@ve-components/services' +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { InsertApi, InsertData, InsertResolve } from '@ve-types/components'; -import { ElementObject, MmsObject } from '@ve-types/mms'; -import { VeModalComponent, VeModalController, VeModalService } from '@ve-types/view-editor'; +import { InsertApi, InsertData, InsertResolve } from '@ve-types/components' +import { ElementObject, MmsObject } from '@ve-types/mms' +import { VeModalComponent, VeModalController, VeModalService } from '@ve-types/view-editor' class InsertController extends VeModalControllerImpl implements VeModalController { - static $inject = ['$scope', '$compile', '$element', '$timeout', '$uibModal', 'growl', 'ExtensionService']; + static $inject = ['$scope', '$compile', '$element', '$timeout', '$uibModal', 'growl', 'ExtensionService'] - private schema = 'cameo'; + private schema = 'cameo' - protected resolve: InsertResolve; + protected resolve: InsertResolve //local - private insertData: InsertData; - private insertApi: InsertApi; - private projectId: string; - private refId: string; - private orgId: string; - private insertType: string; - private type: string; + private insertData: InsertData + private insertApi: InsertApi + private projectId: string + private refId: string + private orgId: string + private insertType: string + private type: string - private $componentEl: JQuery; + private $componentEl: JQuery constructor( private $scope: angular.IScope, @@ -34,53 +34,53 @@ class InsertController extends VeModalControllerImpl implements VeMod private growl: angular.growl.IGrowlService, private extensionSvc: ExtensionService ) { - super(); + super() } - public parentData: ElementObject = {} as ElementObject; + public parentData: ElementObject = {} as ElementObject $onInit(): void { - this.insertData = this.resolve.getInsertData; + this.insertData = this.resolve.getInsertData - this.insertType = this.insertData.insertType; - this.projectId = this.resolve.getProjectId; - this.refId = this.resolve.getRefId ? this.resolve.getRefId : 'master'; - this.orgId = this.resolve.getOrgId ? this.resolve.getOrgId : null; + this.insertType = this.insertData.insertType + this.projectId = this.resolve.getProjectId + this.refId = this.resolve.getRefId ? this.resolve.getRefId : 'master' + this.orgId = this.resolve.getOrgId ? this.resolve.getOrgId : null - this.type = this.insertData.type; + this.type = this.insertData.type this.insertApi = { resolve: (data): void => { - this.modalInstance.close(data); + this.modalInstance.close(data) }, reject: (reason): void => { - this.modalInstance.dismiss(reason); + this.modalInstance.dismiss(reason) }, - }; + } } $postLink(): void { - this.recompile(); + this.recompile() } public recompile = (): void => { - let tag = this.extensionSvc.getTagByType('insert', this.insertType); + let tag = this.extensionSvc.getTagByType('insert', this.insertType) if (tag === 'extension-error') { - tag = 'insert-element'; + tag = 'insert-element' } - const newPe = $('
    '); + const newPe = $('
    ') $(newPe).append( `<${tag} insert-data="$ctrl.insertData" insert-api="$ctrl.insertApi" mms-project-id="{{$ctrl.projectId}}" ${this.refId ? `mms-ref-id="{{$ctrl.refId}}" ` : ''}${ this.orgId ? 'mms-org-id="{{$ctrl.orgId}}" ' : '' }>` - ); - $(this.$element).append(newPe); - this.$compile(newPe)(this.$scope); - }; + ) + $(this.$element).append(newPe) + this.$compile(newPe)(this.$scope) + } public cancel = (): void => { - this.modalInstance.dismiss(); - }; + this.modalInstance.dismiss() + } } const InsertElementModalComponent: VeModalComponent = { @@ -98,6 +98,6 @@ const InsertElementModalComponent: VeModalComponent = { resolve: '<', }, controller: InsertController, -}; +} -veComponents.component(InsertElementModalComponent.selector, InsertElementModalComponent); +veComponents.component(InsertElementModalComponent.selector, InsertElementModalComponent) diff --git a/src/ve-components/insertions/insertion.controller.ts b/src/ve-components/insertions/insertion.controller.ts index d506d1c3b..112e2a78f 100644 --- a/src/ve-components/insertions/insertion.controller.ts +++ b/src/ve-components/insertions/insertion.controller.ts @@ -1,17 +1,17 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { LoginModalResolveFn } from '@ve-app/main/modals/login-modal.component'; -import { InsertionService } from '@ve-components/insertions'; -import { EditorService } from '@ve-core/editor'; -import { ApplicationService, UtilsService } from '@ve-utils/application'; -import { EditObject } from '@ve-utils/core'; -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { LoginModalResolveFn } from '@ve-app/main/modals/login-modal.component' +import { InsertionService } from '@ve-components/insertions' +import { EditorService } from '@ve-core/editor' +import { ApplicationService, UtilsService } from '@ve-utils/application' +import { EditObject } from '@ve-utils/core' +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { InsertApi, InsertData } from '@ve-types/components'; -import { BasicResponse, ElementObject, MmsObject } from '@ve-types/mms'; -import { VeModalService, VeModalSettings, veSearchCallback, VeSearchOptions } from '@ve-types/view-editor'; +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { InsertApi, InsertData } from '@ve-types/components' +import { BasicResponse, ElementObject, MmsObject } from '@ve-types/mms' +import { VeModalService, VeModalSettings, veSearchCallback, VeSearchOptions } from '@ve-types/view-editor' /** * @name veComponents/Insertion @@ -30,26 +30,26 @@ export class Insertion< U extends MmsObject = ElementObject > { //Bindings - public insertData: T; - public insertApi: InsertApi>>; - public mmsProjectId: string; - public mmsRefId: string; - public mmsOrgId: string; + public insertData: T + public insertApi: InsertApi>> + public mmsProjectId: string + public mmsRefId: string + public mmsOrgId: string //Locals - public name: string; - public ownerId: string; - public searchOptions: VeSearchOptions = null; - type: string; - createForm: boolean = true; - oking: boolean = false; - continue: boolean = false; - projectId: string; - refId: string; - orgId: string; - insertType: string; - createItem: U; - editItem: EditObject; + public name: string + public ownerId: string + public searchOptions: VeSearchOptions = null + type: string + createForm: boolean = true + oking: boolean = false + continue: boolean = false + projectId: string + refId: string + orgId: string + insertType: string + createItem: U + editItem: EditObject static $inject = [ '$scope', @@ -67,13 +67,13 @@ export class Insertion< 'ApiService', 'InsertionService', 'EditorService', - ]; + ] - protected schema = 'cameo'; + protected schema = 'cameo' //local - private $componentEl: JQuery; + private $componentEl: JQuery constructor( protected $scope: angular.IScope, @@ -93,14 +93,14 @@ export class Insertion< protected editorSvc: EditorService ) {} - public parentData: ElementObject = {} as ElementObject; + public parentData: ElementObject = {} as ElementObject $onInit(): void { - this.insertType = this.insertData.insertType; - this.projectId = this.mmsProjectId; - this.refId = this.mmsRefId ? this.mmsRefId : ''; - this.orgId = this.mmsOrgId; - this.type = this.insertData.type; + this.insertType = this.insertData.insertType + this.projectId = this.mmsProjectId + this.refId = this.mmsRefId ? this.mmsRefId : '' + this.orgId = this.mmsOrgId + this.type = this.insertData.type this.searchOptions = { callback: this.callback, @@ -110,98 +110,98 @@ export class Insertion< hideFilterOptions: true, closeable: false, closeCallback: this.cancel, - }; + } } public ok = (): void => { if (this.oking) { - this.growl.info('Please wait...'); - return; + this.growl.info('Please wait...') + return } - this.oking = true; + this.oking = true - this.ownerId = this.parentData && this.parentData.id ? this.parentData.id : 'holding_bin_' + this.projectId; - let ready = this.$q.resolve(null); + this.ownerId = this.parentData && this.parentData.id ? this.parentData.id : 'holding_bin_' + this.projectId + let ready = this.$q.resolve(null) if (this.editItem) { - ready = this.editorSvc.updateAllData(this.editItem.key, true, true); + ready = this.editorSvc.updateAllData(this.editItem.key, true, true) } ready.then( () => { this.create() .then((data) => { - this.insertResolve(data, 'created'); + this.insertResolve(data, 'created') }, this.insertReject) - .finally(this.insertFinally); + .finally(this.insertFinally) }, (reason) => this.insertReject(reason) - ); - }; + ) + } public loginCb = (result?: boolean): void => { if (result) { - this.ok(); + this.ok() } else { this.insertReject({ status: 666, message: 'User not Authenticated', - }); + }) } - }; + } public reLogin = (): void => { - this.$componentEl = this.$element.children(); - this.$element.empty(); + this.$componentEl = this.$element.children() + this.$element.empty() const settings: VeModalSettings = { component: 'loginModal', resolve: { continue: () => { - return true; + return true }, }, - }; - const instance = this.$uibModal.open(settings); + } + const instance = this.$uibModal.open(settings) instance.result.then(this.loginCb, () => { this.insertReject({ status: 666, message: 'User Cancelled Authentication', - }); - }); - }; + }) + }) + } public insertResolve = (data: U, type: string): void => { - this.growl.success(this.type + ' is being ' + type); - this.success(data); - this.insertApi.resolve(data); - }; + this.growl.success(this.type + ' is being ' + type) + this.success(data) + this.insertApi.resolve(data) + } protected insertReject = >>(reason: V): void => { - this.fail(reason); + this.fail(reason) if (!this.continue) { - this.insertApi.reject(reason); + this.insertApi.reject(reason) } - this.continue = false; - }; + this.continue = false + } public success = (data?: U): void => { /* Put custom success logic here*/ - }; + } public fail = >(reason: V): void => { if (reason.status === 401) { - this.reLogin(); + this.reLogin() } else { - this.growl.error(`Create ${_.upperCase(this.insertData.type)} Error: ${reason.message}`); + this.growl.error(`Create ${_.upperCase(this.insertData.type)} Error: ${reason.message}`) } - }; + } public last = (): void => { /* Put custom finally logic here*/ - }; + } public insertFinally = (): void => { - this.last(); - this.oking = false; - }; + this.last() + this.oking = false + } /** * @name Insertion/callback @@ -210,51 +210,51 @@ export class Insertion< */ public callback: veSearchCallback = (data: U, property?: string): void => { if (this.oking) { - this.growl.info('Please wait...'); - return; + this.growl.info('Please wait...') + return } - this.oking = true; + this.oking = true this.addExisting(data, property) .then((finalData) => { if (this.editItem) { - this.editorSvc.cleanUpEdit(this.editItem.key); + this.editorSvc.cleanUpEdit(this.editItem.key) } - this.insertData.isNew = false; - this.insertResolve(finalData, 'added'); + this.insertData.isNew = false + this.insertResolve(finalData, 'added') }, this.insertReject) - .finally(this.insertFinally); - }; + .finally(this.insertFinally) + } public cancel = (): void => { if (this.insertData.selected) { - this.insertionSvc.cancelAction(this.insertData.selected); + this.insertionSvc.cancelAction(this.insertData.selected) } if (this.insertApi.reject) { - this.insertApi.reject({ status: 444, message: 'User cancelled request' }); + this.insertApi.reject({ status: 444, message: 'User cancelled request' }) } - }; + } /** * */ public queryFilter = (): { - appliedStereotypeIds?: string[]; - classifierIds?: string[]; + appliedStereotypeIds?: string[] + classifierIds?: string[] } => { /* Implement and Search Filtering Logic Here */ return { appliedStereotypeIds: [], classifierIds: [], - }; - }; + } + } /** * * @return {VePromise>} */ public create = (): VePromise> => { - this.growl.error(`Add Item of Type ${this.type} is not supported`); - return this.$q.reject(); - }; + this.growl.error(`Add Item of Type ${this.type} is not supported`) + return this.$q.reject() + } /** * @name Insertion/addExisting @@ -263,6 +263,6 @@ export class Insertion< * @return {VePromise} */ public addExisting = (existingOb: U, property?: string): VePromise => { - return this.$q.resolve(existingOb); - }; + return this.$q.resolve(existingOb) + } } diff --git a/src/ve-components/insertions/services/Insertion.service.ts b/src/ve-components/insertions/services/Insertion.service.ts index 9bc6b0683..633522ffb 100644 --- a/src/ve-components/insertions/services/Insertion.service.ts +++ b/src/ve-components/insertions/services/Insertion.service.ts @@ -1,18 +1,18 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { EditorService } from '@ve-core/editor'; -import { RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { ElementService } from '@ve-utils/mms-api-client'; -import { Class } from '@ve-utils/utils'; +import { EditorService } from '@ve-core/editor' +import { RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { ElementService } from '@ve-utils/mms-api-client' +import { Class } from '@ve-utils/utils' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; -import { ElementObject } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { ElementObject } from '@ve-types/mms' export class InsertionService { - static $inject = ['$q', '$timeout', 'growl', 'ElementService', 'EditorService', 'RootScopeService', 'EventService']; + static $inject = ['$q', '$timeout', 'growl', 'ElementService', 'EditorService', 'RootScopeService', 'EventService'] constructor( private $q: VeQService, @@ -25,37 +25,37 @@ export class InsertionService { ) {} public successUpdates = (elemType: string, id: string): void => { - this.eventSvc.$broadcast('content-reorder.refresh'); - this.eventSvc.$broadcast('content-reorder-saved', { id: id }); - this.growl.success('Adding ' + elemType + ' Successful'); + this.eventSvc.$broadcast('content-reorder.refresh') + this.eventSvc.$broadcast('content-reorder-saved', { id: id }) + this.growl.success('Adding ' + elemType + ' Successful') // Show comments when creating a comment PE if (elemType === 'Comment' && !this.rootScopeSvc.veCommentsOn()) { void this.$timeout( () => { - $('.show-comments').trigger('click'); + $('.show-comments').trigger('click') }, 0, false - ); + ) } - }; + } public createAction = (createItem: ElementObject, noPublish: boolean): VePromise => { if (!createItem.name) { - this.growl.error('Error: A name for your new element is required.'); - return this.$q.reject({ status: 422 }); + this.growl.error('Error: A name for your new element is required.') + return this.$q.reject({ status: 422 }) } - const editKey = this.elementSvc.getEditElementKey(createItem); + const editKey = this.elementSvc.getEditElementKey(createItem) - const toCreate: ElementObject = new Class(createItem); + const toCreate: ElementObject = new Class(createItem) - let promise: VePromise; + let promise: VePromise if (!noPublish) { promise = this.elementSvc.createElement({ elements: [toCreate], refId: toCreate._refId, projectId: toCreate._projectId, - }); + }) } else { promise = this.$q.resolve( this.elementSvc.cacheElement( @@ -65,19 +65,19 @@ export class InsertionService { }, _.cloneDeep(toCreate) ) - ); + ) } promise.finally(() => { - this.editorSvc.cleanUpEdit(editKey); - }); + this.editorSvc.cleanUpEdit(editKey) + }) - return promise; - }; + return promise + } public cancelAction = (cancelledItem: ElementObject): void => { - this.editorSvc.cleanUpEdit(this.elementSvc.getEditElementKey(cancelledItem)); - }; + this.editorSvc.cleanUpEdit(this.elementSvc.getEditElementKey(cancelledItem)) + } } -veComponents.service('InsertionService', InsertionService); +veComponents.service('InsertionService', InsertionService) diff --git a/src/ve-components/insertions/services/index.ts b/src/ve-components/insertions/services/index.ts index 83a1f3fba..602eb6176 100644 --- a/src/ve-components/insertions/services/index.ts +++ b/src/ve-components/insertions/services/index.ts @@ -1,3 +1,3 @@ -import './Insertion.service'; +import './Insertion.service' -export * from './Insertion.service'; +export * from './Insertion.service' diff --git a/src/ve-components/presentations/add-pe-menu.component.ts b/src/ve-components/presentations/add-pe-menu.component.ts index ccdb20482..4c8cd170f 100644 --- a/src/ve-components/presentations/add-pe-menu.component.ts +++ b/src/ve-components/presentations/add-pe-menu.component.ts @@ -1,20 +1,20 @@ -import { IComponentController } from 'angular'; +import { IComponentController } from 'angular' -import { PresentationService } from '@ve-components/presentations/services/Presentation.service'; -import { RootScopeService } from '@ve-utils/application'; +import { PresentationService } from '@ve-components/presentations/services/Presentation.service' +import { RootScopeService } from '@ve-utils/application' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions } from '@ve-types/angular'; -import { ViewObject } from '@ve-types/mms'; +import { VeComponentOptions } from '@ve-types/angular' +import { ViewObject } from '@ve-types/mms' class AddPeMenuController implements IComponentController { // Bindings - private mmsView: ViewObject; + private mmsView: ViewObject - public addPeIndex: number; + public addPeIndex: number - static $inject = ['PresentationService', 'RootScopeService']; + static $inject = ['PresentationService', 'RootScopeService'] constructor(private presentationSvc: PresentationService, private rootScopeSvc: RootScopeService) {} /** @@ -23,22 +23,22 @@ class AddPeMenuController implements IComponentController { */ public addEltAction = (index: number, type: string): void => { if (!this.rootScopeSvc.veEditMode()) { - return; + return } - this.addPeIndex = index; - this.presentationSvc.addPresentationElement(this, type, this.mmsView); - }; + this.addPeIndex = index + this.presentationSvc.addPresentationElement(this, type, this.mmsView) + } public setPeLineVisibility = ($event: JQuery.ClickEvent): void => { window.setTimeout(() => { - const peContainer = $($event.currentTarget).closest('.add-pe-button-container'); + const peContainer = $($event.currentTarget).closest('.add-pe-button-container') if (peContainer.find('.dropdown-menu').css('display') == 'none') { - peContainer.find('hr').css('visibility', 'hidden'); + peContainer.find('hr').css('visibility', 'hidden') } else { - peContainer.find('hr').css('visibility', 'visible'); + peContainer.find('hr').css('visibility', 'visible') } - }); - }; + }) + } } const InsertPeMenuComponent: VeComponentOptions = { @@ -90,6 +90,6 @@ const InsertPeMenuComponent: VeComponentOptions = { index: '<', }, controller: AddPeMenuController, -}; +} -veComponents.component(InsertPeMenuComponent.selector, InsertPeMenuComponent); +veComponents.component(InsertPeMenuComponent.selector, InsertPeMenuComponent) diff --git a/src/ve-components/presentations/components/present-comment.component.ts b/src/ve-components/presentations/components/present-comment.component.ts index 7d823d333..395594d19 100644 --- a/src/ve-components/presentations/components/present-comment.component.ts +++ b/src/ve-components/presentations/components/present-comment.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations'; +import { PresentationLite } from '@ve-components/presentations' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation' const PresentCommentComponent: IPresentationComponentOptions = { selector: 'presentComment', @@ -13,6 +13,6 @@ const PresentCommentComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -}; +} -veComponents.component(PresentCommentComponent.selector, PresentCommentComponent); +veComponents.component(PresentCommentComponent.selector, PresentCommentComponent) diff --git a/src/ve-components/presentations/components/present-equation.component.ts b/src/ve-components/presentations/components/present-equation.component.ts index f9c791809..5bf5fec2d 100644 --- a/src/ve-components/presentations/components/present-equation.component.ts +++ b/src/ve-components/presentations/components/present-equation.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations'; +import { PresentationLite } from '@ve-components/presentations' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation' const PresentEquationComponent: IPresentationComponentOptions = { selector: 'presentEquation', @@ -14,6 +14,6 @@ const PresentEquationComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -}; +} -veComponents.component(PresentEquationComponent.selector, PresentEquationComponent); +veComponents.component(PresentEquationComponent.selector, PresentEquationComponent) diff --git a/src/ve-components/presentations/components/present-figure.component.ts b/src/ve-components/presentations/components/present-figure.component.ts index 8d5e425cb..cef0367dd 100644 --- a/src/ve-components/presentations/components/present-figure.component.ts +++ b/src/ve-components/presentations/components/present-figure.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations'; +import { PresentationLite } from '@ve-components/presentations' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation' const PresentFigureComponent: IPresentationComponentOptions = { selector: 'presentFigure', @@ -14,6 +14,6 @@ const PresentFigureComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -}; +} -veComponents.component(PresentFigureComponent.selector, PresentFigureComponent); +veComponents.component(PresentFigureComponent.selector, PresentFigureComponent) diff --git a/src/ve-components/presentations/components/present-image.component.ts b/src/ve-components/presentations/components/present-image.component.ts index eaee3656f..fa59b8e0a 100644 --- a/src/ve-components/presentations/components/present-image.component.ts +++ b/src/ve-components/presentations/components/present-image.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations'; +import { PresentationLite } from '@ve-components/presentations' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation' const PresentImageComponent: IPresentationComponentOptions = { selector: 'presentImage', @@ -21,6 +21,6 @@ const PresentImageComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -}; +} -veComponents.component(PresentImageComponent.selector, PresentImageComponent); +veComponents.component(PresentImageComponent.selector, PresentImageComponent) diff --git a/src/ve-components/presentations/components/present-list-t.component.ts b/src/ve-components/presentations/components/present-list-t.component.ts index 5a4c7773c..9c1ab1116 100644 --- a/src/ve-components/presentations/components/present-list-t.component.ts +++ b/src/ve-components/presentations/components/present-list-t.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations'; +import { PresentationLite } from '@ve-components/presentations' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation' const PresentListTComponent: IPresentationComponentOptions = { selector: 'presentListt', @@ -14,6 +14,6 @@ const PresentListTComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -}; +} -veComponents.component(PresentListTComponent.selector, PresentListTComponent); +veComponents.component(PresentListTComponent.selector, PresentListTComponent) diff --git a/src/ve-components/presentations/components/present-list.component.ts b/src/ve-components/presentations/components/present-list.component.ts index 2c780d76d..26ede1313 100644 --- a/src/ve-components/presentations/components/present-list.component.ts +++ b/src/ve-components/presentations/components/present-list.component.ts @@ -1,18 +1,18 @@ -import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations'; -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { ImageService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { SchemaService } from '@ve-utils/model-schema'; +import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations' +import { ComponentService, ExtensionService } from '@ve-components/services' +import { ButtonBarService } from '@ve-core/button-bar' +import { ImageService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; -import { PresentListObject } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { PresentListObject } from '@ve-types/mms' class PresentListController extends Presentation { - static $inject = Presentation.$inject; + static $inject = Presentation.$inject constructor( $q: VeQService, $element: JQuery, @@ -42,12 +42,12 @@ class PresentListController extends Presentation { imageSvc, buttonBarSvc, extensionSvc - ); + ) } protected getContent = (): VePromise => { - return this.$q.resolve(this.viewHtmlSvc.makeHtmlList(this.peObject as PresentListObject)); - }; + return this.$q.resolve(this.viewHtmlSvc.makeHtmlList(this.peObject as PresentListObject)) + } } const PresentListComponent: IPresentationComponentOptions = { @@ -59,6 +59,6 @@ const PresentListComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentListController, -}; +} -veComponents.component(PresentListComponent.selector, PresentListComponent); +veComponents.component(PresentListComponent.selector, PresentListComponent) diff --git a/src/ve-components/presentations/components/present-paragraph.component.ts b/src/ve-components/presentations/components/present-paragraph.component.ts index 3448e0edc..749b32d38 100644 --- a/src/ve-components/presentations/components/present-paragraph.component.ts +++ b/src/ve-components/presentations/components/present-paragraph.component.ts @@ -1,18 +1,18 @@ -import { ViewHtmlService, Presentation, PresentationService } from '@ve-components/presentations'; -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { ImageService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ViewHtmlService, Presentation, PresentationService } from '@ve-components/presentations' +import { ComponentService, ExtensionService } from '@ve-components/services' +import { ButtonBarService } from '@ve-core/button-bar' +import { ImageService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; -import { PresentTextObject } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { PresentTextObject } from '@ve-types/mms' class PresentParagraph extends Presentation implements angular.IComponentController { - static $inject = Presentation.$inject; + static $inject = Presentation.$inject constructor( $q: VeQService, $element: JQuery, @@ -42,12 +42,12 @@ class PresentParagraph extends Presentation implements angular.IComponentControl imageSvc, buttonBarSvc, extensionSvc - ); + ) } protected getContent = (): VePromise => { - return this.$q.resolve(this.viewHtmlSvc.makeHtmlPara(this.peObject as PresentTextObject)); - }; + return this.$q.resolve(this.viewHtmlSvc.makeHtmlPara(this.peObject as PresentTextObject)) + } } const PresentParagraphComponent: IPresentationComponentOptions = { @@ -59,6 +59,6 @@ const PresentParagraphComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentParagraph, -}; +} -veComponents.component(PresentParagraphComponent.selector, PresentParagraphComponent); +veComponents.component(PresentParagraphComponent.selector, PresentParagraphComponent) diff --git a/src/ve-components/presentations/components/present-section.component.ts b/src/ve-components/presentations/components/present-section.component.ts index b4ee350d6..edfcc838e 100644 --- a/src/ve-components/presentations/components/present-section.component.ts +++ b/src/ve-components/presentations/components/present-section.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations'; +import { PresentationLite } from '@ve-components/presentations' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation' const PresentSectionComponent: IPresentationComponentOptions = { selector: 'presentSection', @@ -20,6 +20,6 @@ const PresentSectionComponent: IPresentationComponentOptions = { mmsViewCtrl: '?^^view', mmsViewPresentationElemCtrl: '?^^viewPe', }, -}; +} -veComponents.component(PresentSectionComponent.selector, PresentSectionComponent); +veComponents.component(PresentSectionComponent.selector, PresentSectionComponent) diff --git a/src/ve-components/presentations/components/present-table-t.component.ts b/src/ve-components/presentations/components/present-table-t.component.ts index 2ec52b363..e124e1d36 100644 --- a/src/ve-components/presentations/components/present-table-t.component.ts +++ b/src/ve-components/presentations/components/present-table-t.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations'; +import { PresentationLite } from '@ve-components/presentations' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation' const PresentTableTComponent: IPresentationComponentOptions = { selector: 'presentTablet', @@ -14,6 +14,6 @@ const PresentTableTComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -}; +} -veComponents.component(PresentTableTComponent.selector, PresentTableTComponent); +veComponents.component(PresentTableTComponent.selector, PresentTableTComponent) diff --git a/src/ve-components/presentations/components/present-table.component.ts b/src/ve-components/presentations/components/present-table.component.ts index 8dd04e8f5..29864443a 100644 --- a/src/ve-components/presentations/components/present-table.component.ts +++ b/src/ve-components/presentations/components/present-table.component.ts @@ -1,49 +1,49 @@ -import $ from 'jquery'; +import $ from 'jquery' -import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations'; -import { Table2CSVService } from '@ve-components/presentations/services/Table2CSV.service'; -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { ImageService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { SchemaService } from '@ve-utils/model-schema'; +import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations' +import { Table2CSVService } from '@ve-components/presentations/services/Table2CSV.service' +import { ComponentService, ExtensionService } from '@ve-components/services' +import { ButtonBarService } from '@ve-core/button-bar' +import { ImageService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; -import { IPresentationComponentOptions, ITableConfig } from '@ve-types/components/presentation'; -import { PresentTableObject, TableEntryObject } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { IPresentationComponentOptions, ITableConfig } from '@ve-types/components/presentation' +import { PresentTableObject, TableEntryObject } from '@ve-types/mms' class PresentTableController extends Presentation { - public $searchEl: JQuery; - public $tHeadEl: JQuery; - public $captionEl: JQuery; - - public table: PresentTableObject; - public tableConfig: ITableConfig; - private trs: JQuery; - public ngModelOptions: angular.INgModelOptions; - public showFilter: boolean = false; - public fixedHeaders: boolean = false; - public fixedColumns: boolean = false; - private _fixedHeadersElem: JQuery = null; - private _fixedColumnsElem: JQuery = null; - public numFixedColumns: number = 2; - private nextIndex: number; - private tbody: JQuery; - private lastIndex: number; - private numTotal: number; - private sortColumnNum: number; + public $searchEl: JQuery + public $tHeadEl: JQuery + public $captionEl: JQuery + + public table: PresentTableObject + public tableConfig: ITableConfig + private trs: JQuery + public ngModelOptions: angular.INgModelOptions + public showFilter: boolean = false + public fixedHeaders: boolean = false + public fixedColumns: boolean = false + private _fixedHeadersElem: JQuery = null + private _fixedColumnsElem: JQuery = null + public numFixedColumns: number = 2 + private nextIndex: number + private tbody: JQuery + private lastIndex: number + private numTotal: number + private sortColumnNum: number /** Full Table Filter **/ - private searchTerm: string = ''; - private numFiltered: number; + private searchTerm: string = '' + private numFiltered: number /** Column Filter **/ private _columnsInputSubs: { - [columnId: string]: { sub: Rx.IDisposable; cell: TableEntryObject }; - } = {}; + [columnId: string]: { sub: Rx.IDisposable; cell: TableEntryObject } + } = {} /** * _filterTermForColumns is used to keep track of filter terms on each header's column for multi-columns @@ -51,16 +51,16 @@ class PresentTableController extends Presentation { * keeps track, of all the children columns number that it is a parent of. ie: * {filterTermForColumn01: {filterTerm: 'A', columns: [0,1]}, filterTermForColumn11: {filterTerm: 'B', columns: [1]}} **/ private _filterTermForColumns: { - [filterTermForColumn: string]: { filterTerm: string; columns: number[] }; - } = {}; - private filterTermForColumn: { [cols: string]: string } = {}; + [filterTermForColumn: string]: { filterTerm: string; columns: number[] } + } = {} + private filterTermForColumn: { [cols: string]: string } = {} /** Variables for Sorting Functions **/ - private _rowSortOrderAttrName = 'data-original-row-num'; - public isAscending: boolean = false; - private showSortReset: boolean = false; + private _rowSortOrderAttrName = 'data-original-row-num' + public isAscending: boolean = false + private showSortReset: boolean = false - static $inject = [...Presentation.$inject, '$timeout']; + static $inject = [...Presentation.$inject, '$timeout'] constructor( $q: VeQService, @@ -92,44 +92,44 @@ class PresentTableController extends Presentation { imageSvc, buttonBarSvc, extensionSvc - ); + ) } recompile = (): void => { this.$element.on('click', (e) => { - const tag = (e.target as unknown as Element).tagName; + const tag = (e.target as unknown as Element).tagName if (tag === 'INPUT' || tag === 'LABEL' || tag === 'BUTTON') { - e.stopPropagation(); + e.stopPropagation() } - }); - this.setNumber(); + }) + this.setNumber() this.getContent().then( (result) => { - this.$transcludeEl = $(result); + this.$transcludeEl = $(result) this.$transcludeEl.find('img').each((index, element) => { - this.imageSvc.fixImgSrc($(element)); - }); - - this.$element.append(this.$transcludeEl); - this.nextIndex = 0; - this.$tHeadEl = this.$element.find('thead'); - this.$compile(this.$tHeadEl)(this.$scope); - this.$searchEl = this.$element.children('div').eq(0); + this.imageSvc.fixImgSrc($(element)) + }) + + this.$element.append(this.$transcludeEl) + this.nextIndex = 0 + this.$tHeadEl = this.$element.find('thead') + this.$compile(this.$tHeadEl)(this.$scope) + this.$searchEl = this.$element.children('div').eq(0) //this.$compile(this.$searchEl)(this.$scope) //already compiled due to template - this.$captionEl = this.$element.find('caption'); - this.$compile(this.$captionEl)(this.$scope); + this.$captionEl = this.$element.find('caption') + this.$compile(this.$captionEl)(this.$scope) //Add the search input here (before the TRS, aka the columns/rows) - this.tbody = this.$element.find('.table-wrapper').children('table').children('tbody'); - this.trs = this.tbody.children('tr'); + this.tbody = this.$element.find('.table-wrapper').children('table').children('tbody') + this.trs = this.tbody.children('tr') - this.lastIndex = this.trs.length; - this.numFiltered = this.lastIndex; - this.numTotal = this.lastIndex; + this.lastIndex = this.trs.length + this.numFiltered = this.lastIndex + this.numTotal = this.lastIndex //this.addColumnsWiseFilter(this.tableConfig, this.trs) - this.addSorting(this.trs, this.tbody); + this.addSorting(this.trs, this.tbody) - this.compileTable(); + this.compileTable() }, (reason) => { const reqOb = { @@ -138,85 +138,85 @@ class PresentTableController extends Presentation { refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - }; - this.$element.empty(); + } + this.$element.empty() //TODO: Add reason/errorMessage handling here. this.$transcludeEl = $( '' - ); - this.$element.append(this.$transcludeEl); + ) + this.$element.append(this.$transcludeEl) this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: reqOb.elementId, recentElement: reason.recentVersionOfElement, type: 'presentation', }) - ); + ) } - ); - }; + ) + } config = (): void => { if ( !(this.peObject as PresentTableObject).showIfEmpty && (this.peObject as PresentTableObject).body.length === 0 ) { - return; + return } - this.table = this.peObject as PresentTableObject; - this.sortColumnNum = -1; + this.table = this.peObject as PresentTableObject + this.sortColumnNum = -1 this.ngModelOptions = { debounce: 300, getterSetter: true, - }; - }; + } + } getContent = (): VePromise => { - const html = this.viewHtmlSvc.makeHtmlTable(this.table, true, true, this.instanceSpec); - return this.$q.resolve(`
    ${html}
    `); - }; + const html = this.viewHtmlSvc.makeHtmlTable(this.table, true, true, this.instanceSpec) + return this.$q.resolve(`
    ${html}
    `) + } /** Filter rows by search term **/ private fullTableFilter = (): void => { - this._resetColumnWiseFilterInputs(); + this._resetColumnWiseFilterInputs() if (this.searchTerm === '') { - this.numFiltered = this.trs.length; - this.trs.show(); + this.numFiltered = this.trs.length + this.trs.show() } else { - this.numFiltered = 0; + this.numFiltered = 0 this._displaySomeRows(this.trs, () => { - this.numFiltered++; - }); + this.numFiltered++ + }) } - }; + } /** Display rows that match the filter term **/ private _displaySomeRows = (trs: JQuery, increaseNumOfRowToShow: () => void): void => { - const regExp = new RegExp(this.searchTerm, 'i'); + const regExp = new RegExp(this.searchTerm, 'i') for (let i = 0, numRows = trs.length; i < numRows; i++) { - const string = $(trs[i]).text(); + const string = $(trs[i]).text() if (regExp.test(string)) { - $(trs[i]).show(); - increaseNumOfRowToShow(); + $(trs[i]).show() + increaseNumOfRowToShow() } else { - $(trs[i]).hide(); + $(trs[i]).hide() } } - }; + } /** End of Full Table Filter **/ /** Add column(s)-wise filter ability **/ private filterByColumn = (startColNum: number, endColNum: number): void => { - this.searchTerm = ''; - const filterTerm = this.filterTermForColumn[`filter${startColNum}${endColNum}`]; - const filterInputBinding = `columnFilter${startColNum}${endColNum}`; - this._storeColumnWiseFilterTerm(filterInputBinding, startColNum, endColNum, filterTerm); - this.numFiltered = 0; + this.searchTerm = '' + const filterTerm = this.filterTermForColumn[`filter${startColNum}${endColNum}`] + const filterInputBinding = `columnFilter${startColNum}${endColNum}` + this._storeColumnWiseFilterTerm(filterInputBinding, startColNum, endColNum, filterTerm) + this.numFiltered = 0 this._displayRowsMatchingAllColumnsFilterTerms(this.trs, () => { - this.numFiltered++; - }); - }; + this.numFiltered++ + }) + } /** Only show the rows that has contents matching all currently outstanding filter terms **/ private _displayRowsMatchingAllColumnsFilterTerms = ( @@ -225,19 +225,19 @@ class PresentTableController extends Presentation { ): void => { trs.toArray().forEach((row) => { const shouldKeepRow = Object.keys(this._filterTermForColumns).every((k) => { - const regExp = new RegExp(this._filterTermForColumns[k].filterTerm, 'i'); + const regExp = new RegExp(this._filterTermForColumns[k].filterTerm, 'i') return this._filterTermForColumns[k].columns.some((colNum) => { - return regExp.test(this._getCellValueForFiltering(row, colNum)); - }); - }); + return regExp.test(this._getCellValueForFiltering(row, colNum)) + }) + }) if (shouldKeepRow) { - $(row).show(); - increaseNumOfRowToShow(); + $(row).show() + increaseNumOfRowToShow() } else { - $(row).hide(); + $(row).hide() } - }); - }; + }) + } /** Update or add a new filter term for a header column with the given filterInputBinding **/ private _storeColumnWiseFilterTerm = ( @@ -247,11 +247,11 @@ class PresentTableController extends Presentation { filterTerm: string ): void => { if (this._filterTermForColumns[filterInputBinding]) { - this._updateExistingColumnWiseFilterTerm(filterInputBinding, filterTerm); + this._updateExistingColumnWiseFilterTerm(filterInputBinding, filterTerm) } else { - this._addNewColumnWiseFilterTerm(filterInputBinding, startColNum, endColNum, filterTerm); + this._addNewColumnWiseFilterTerm(filterInputBinding, startColNum, endColNum, filterTerm) } - }; + } /** Add a new filter term to a header column with the given filterInputBinding **/ private _addNewColumnWiseFilterTerm = ( @@ -263,345 +263,345 @@ class PresentTableController extends Presentation { this._filterTermForColumns[filterInputBinding] = { filterTerm: filterTerm, columns: startColNum === endColNum ? [startColNum] : [startColNum, endColNum], - }; - }; + } + } /** Update a filter term for a header column with the given filterInputBinding **/ private _updateExistingColumnWiseFilterTerm = (filterInputBinding: string, filterTerm: string): void => { - this._filterTermForColumns[filterInputBinding].filterTerm = filterTerm; - }; + this._filterTermForColumns[filterInputBinding].filterTerm = filterTerm + } /** Return the content of a cell given a row & columnIndex **/ private _getCellValueForFiltering = (row: HTMLElement, columnIndex: number): string => { - const cell = $(row).children('td').eq(columnIndex); - return cell.text().trim(); - }; + const cell = $(row).children('td').eq(columnIndex) + return cell.text().trim() + } /** Clear out filter term(s) for all header's columns that used to be filtered by before **/ private _resetColumnWiseFilterInputs = (): void => { - const listOfFilterInputBindings = Object.keys(this._filterTermForColumns); + const listOfFilterInputBindings = Object.keys(this._filterTermForColumns) if (listOfFilterInputBindings.length > 0) { listOfFilterInputBindings.forEach((filterInputBinding) => { - delete this._filterTermForColumns[filterInputBinding]; - }); + delete this._filterTermForColumns[filterInputBinding] + }) } Object.keys(this.filterTermForColumn).forEach((key) => { - this.filterTermForColumn[key] = ''; - }); - }; + this.filterTermForColumn[key] = '' + }) + } /** End of Column(s)-Wise Filter **/ /** Sorting feature **/ /** Add sorting ability **/ public addSorting = (trs: JQuery, tbody: JQuery): void => { - this._addDefaultSortOrder(trs); - }; + this._addDefaultSortOrder(trs) + } /** Remember the original row number for each row. Used to restore sort order **/ private _addDefaultSortOrder = (trs: JQuery): void => { trs.each((rowNumber, tr) => { - $(tr).attr(this._rowSortOrderAttrName, rowNumber); - }); - }; + $(tr).attr(this._rowSortOrderAttrName, rowNumber) + }) + } /** Used to sort columns(s). Add sort binding to each header columns of the outermost table **/ private sortByColumnFn = (event: Event, sortColumnNum: number): void => { - this.sortColumnNum = sortColumnNum; - event.stopPropagation(); - const rows = this.trs.toArray(); + this.sortColumnNum = sortColumnNum + event.stopPropagation() + const rows = this.trs.toArray() let sortedRows = this._areAllCellValidNumber(rows, sortColumnNum) ? rows.sort(this._numericalComparator(sortColumnNum)) - : rows.sort(this._generalComparator(sortColumnNum)); + : rows.sort(this._generalComparator(sortColumnNum)) - this.isAscending = !this.isAscending; + this.isAscending = !this.isAscending if (!this.isAscending) { - sortedRows = sortedRows.reverse(); + sortedRows = sortedRows.reverse() } - this._displaySortedRows(sortedRows, this.tbody); - this.showSortReset = true; - }; + this._displaySortedRows(sortedRows, this.tbody) + this.showSortReset = true + } /** Used to restore the sort order of table's rows **/ private resetSort = (): void => { - const sortedRows = this.trs.toArray().sort(this._comparatorForSortReset()); - this._displaySortedRows(sortedRows, this.tbody); - this.showSortReset = false; - this.sortColumnNum = -1; - }; + const sortedRows = this.trs.toArray().sort(this._comparatorForSortReset()) + this._displaySortedRows(sortedRows, this.tbody) + this.showSortReset = false + this.sortColumnNum = -1 + } /** A comparator for sorting table's rows. When one of them is null ( null is reserved for non-sortable content * such as image, list, table ), that content is pushed to the end of the final sorted list regardless of * whether sorting asc or dsc **/ private _generalComparator = (columnIndex: number): ((rowA: HTMLElement, rowB: HTMLElement) => number) => { return (rowA: HTMLElement, rowB: HTMLElement): number => { - let cellValueA = this._getCellValueForSorting(rowA, columnIndex); - let cellValueB = this._getCellValueForSorting(rowB, columnIndex); + let cellValueA = this._getCellValueForSorting(rowA, columnIndex) + let cellValueB = this._getCellValueForSorting(rowB, columnIndex) if (cellValueA === null && cellValueB === null) { - return 0; + return 0 } if (cellValueA === null && cellValueB !== null) { - return this.isAscending ? 1 : -1; + return this.isAscending ? 1 : -1 } if (cellValueA !== null && cellValueB === null) { - return this.isAscending ? -1 : 1; + return this.isAscending ? -1 : 1 } if (cellValueA !== null && cellValueB !== null) { - cellValueA = cellValueA.toLowerCase(); - cellValueB = cellValueB.toLowerCase(); - return cellValueA < cellValueB ? -1 : cellValueA > cellValueB ? 1 : 0; + cellValueA = cellValueA.toLowerCase() + cellValueB = cellValueB.toLowerCase() + return cellValueA < cellValueB ? -1 : cellValueA > cellValueB ? 1 : 0 } - }; - }; + } + } /** Return true if and only if all cells' value can be converted to a valid number **/ private _areAllCellValidNumber = (rows: HTMLElement[], columnIndex: number): boolean => { return rows.every((row): boolean => { - return this._isValidNumber(this._getCellValueForSorting(row, columnIndex)); - }); - }; + return this._isValidNumber(this._getCellValueForSorting(row, columnIndex)) + }) + } private _numericalComparator = (columnIndex: number): ((rowA: HTMLElement, rowB: HTMLElement) => number) => { return (rowA: HTMLElement, rowB: HTMLElement) => { - const cellValueA = Number(this._getCellValueForSorting(rowA, columnIndex)); - const cellValueB = Number(this._getCellValueForSorting(rowB, columnIndex)); - return cellValueA - cellValueB; - }; - }; + const cellValueA = Number(this._getCellValueForSorting(rowA, columnIndex)) + const cellValueB = Number(this._getCellValueForSorting(rowB, columnIndex)) + return cellValueA - cellValueB + } + } private _isValidNumber = (val): boolean => { - return val !== null && !isNaN(Number(val)); - }; + return val !== null && !isNaN(Number(val)) + } /** Get content of a cell given its row and its columnIndex. Return null for a cell that contains non-sortable * content such as image, table, list **/ private _getCellValueForSorting = (row: HTMLElement, columnIndex: number): string => { - const cell = $(row).children('td').eq(columnIndex); - const containerDivContent = cell.children('div').contents(); + const cell = $(row).children('td').eq(columnIndex) + const containerDivContent = cell.children('div').contents() // if there is no content, think of it as empty string if (containerDivContent.length === 0) { - return ''; + return '' } else if (!containerDivContent.prop('tagName')) { - return cell.text().trim(); + return cell.text().trim() } else { - const cf = 'mms-cf'; - const contentTag: string = (containerDivContent.prop('tagName') as object).toString().toLowerCase(); - const contentTagAttr = containerDivContent.attr('mms-cf-type'); + const cf = 'mms-cf' + const contentTag: string = (containerDivContent.prop('tagName') as object).toString().toLowerCase() + const contentTagAttr = containerDivContent.attr('mms-cf-type') if ( contentTag === 'img' || contentTag === 'table' || (contentTag === cf && (contentTagAttr === 'img' || contentTagAttr === 'table')) ) { - return null; + return null } else { - return cell.text().trim(); + return cell.text().trim() } } - }; + } /** Display newly sorted rows **/ private _displaySortedRows = (sortedRows: HTMLElement[], tbody: JQuery): void => { - $(sortedRows).detach().appendTo(tbody); - }; + $(sortedRows).detach().appendTo(tbody) + } /** This special comparator is used to turn the table's rows into its original sort order **/ private _comparatorForSortReset = () => { return (rowA, rowB): number => { - const rowARowNumber = Number($(rowA).attr(this._rowSortOrderAttrName)); - const rowBRowNumber = Number($(rowB).attr(this._rowSortOrderAttrName)); - return rowARowNumber < rowBRowNumber ? -1 : rowARowNumber > rowBRowNumber ? 1 : 0; - }; - }; + const rowARowNumber = Number($(rowA).attr(this._rowSortOrderAttrName)) + const rowBRowNumber = Number($(rowB).attr(this._rowSortOrderAttrName)) + return rowARowNumber < rowBRowNumber ? -1 : rowARowNumber > rowBRowNumber ? 1 : 0 + } + } /** End of Sorting feature **/ /** Begin Linking Functions **/ public getSortIconClass = (cellColumn): string[] => { - const sortingColumnNumber = this.sortColumnNum; + const sortingColumnNumber = this.sortColumnNum if (sortingColumnNumber !== cellColumn) { - return ['fa', 'fa-sort', 'sort-default']; + return ['fa', 'fa-sort', 'sort-default'] } else { if (this.isAscending) { - return ['fa', 'fa-caret-down', 'sort-activated']; + return ['fa', 'fa-caret-down', 'sort-activated'] } else { - return ['fa', 'fa-caret-up', 'sort-activated']; + return ['fa', 'fa-caret-up', 'sort-activated'] } } - }; + } makeCsv = (): void => { - const el = this.$element.find('.table-wrapper').children('table'); - const csvString: string | boolean = Table2CSVService.export(el, { delivery: 'value' }); + const el = this.$element.find('.table-wrapper').children('table') + const csvString: string | boolean = Table2CSVService.export(el, { delivery: 'value' }) // var bom = "\xEF\xBB\xBF"; //just for excel if (typeof csvString === 'string') { - const bom2 = '\uFEFF'; //just for excel + const bom2 = '\uFEFF' //just for excel const blob = new Blob([bom2 + csvString], { type: 'text/csv;charset=utf-8;', - }); + }) - const downloadContainer = angular.element('
    '); - const downloadLink = angular.element(downloadContainer.children()[0]); - downloadLink.attr('href', window.URL.createObjectURL(blob)); - downloadLink.attr('download', 'TableData.csv'); - downloadLink.attr('target', '_blank'); + const downloadContainer = angular.element('
    ') + const downloadLink = angular.element(downloadContainer.children()[0]) + downloadLink.attr('href', window.URL.createObjectURL(blob)) + downloadLink.attr('download', 'TableData.csv') + downloadLink.attr('target', '_blank') - $(document).find('body').append(downloadContainer); + $(document).find('body').append(downloadContainer) void this.$timeout(() => { - downloadLink[0].click(); - downloadLink.remove(); - }, null); + downloadLink[0].click() + downloadLink.remove() + }, null) } else { - this.growl.error('Error generating CSV; Please Try Again'); + this.growl.error('Error generating CSV; Please Try Again') } - }; + } public scroll = (): void => { if (this._fixedColumnsElem) { - const scroll = this.$element.find('.table-fix-column').scrollLeft(); - this._fixedColumnsElem.css('transform', `translateX(${scroll}px)`); + const scroll = this.$element.find('.table-fix-column').scrollLeft() + this._fixedColumnsElem.css('transform', `translateX(${scroll}px)`) } if (this._fixedHeadersElem) { - const scroll = this.$element.find('.table-fix-head').scrollTop(); - this._fixedHeadersElem.css('transform', `translateY(${scroll}px)`); + const scroll = this.$element.find('.table-fix-head').scrollTop() + this._fixedHeadersElem.css('transform', `translateY(${scroll}px)`) } if (this._fixedHeadersElem && this._fixedColumnsElem) { - const scrollX = this.$element.find('.table-fix-column').scrollLeft(); - const scrollY = this.$element.find('.table-fix-head').scrollTop(); - this.$captionEl.css('transform', `translate(${scrollX}px, ${scrollY}px)`); + const scrollX = this.$element.find('.table-fix-column').scrollLeft() + const scrollY = this.$element.find('.table-fix-head').scrollTop() + this.$captionEl.css('transform', `translate(${scrollX}px, ${scrollY}px)`) } - }; + } public makeFixedHeader = (): void => { if (!this.fixedHeaders) { - this.$element.find('.table-wrapper').removeClass('table-fix-head').css('height', ''); - this._fixedHeadersElem.css('transform', '').css('will-change', ''); - this._fixedHeadersElem = null; - window.localStorage.setItem('ve-table-header-' + this.instanceSpec.id, 'false'); - return; + this.$element.find('.table-wrapper').removeClass('table-fix-head').css('height', '') + this._fixedHeadersElem.css('transform', '').css('will-change', '') + this._fixedHeadersElem = null + window.localStorage.setItem('ve-table-header-' + this.instanceSpec.id, 'false') + return } this.$element .find('.table-wrapper') .addClass('table-fix-head') - .css('height', window.innerHeight - 36 * 3); + .css('height', window.innerHeight - 36 * 3) //heights for navbar, menu, toolbar - this._fixedHeadersElem = this.$element.find('thead, caption'); - this._fixedHeadersElem.css('will-change', 'transform'); //browser optimization - this.$element.find('.table-fix-head').on('scroll', this.scroll); - window.localStorage.setItem('ve-table-header-' + this.instanceSpec.id, 'true'); - }; + this._fixedHeadersElem = this.$element.find('thead, caption') + this._fixedHeadersElem.css('will-change', 'transform') //browser optimization + this.$element.find('.table-fix-head').on('scroll', this.scroll) + window.localStorage.setItem('ve-table-header-' + this.instanceSpec.id, 'true') + } public makeFixedColumn = (): void => { if (!this.fixedColumns) { - this.$element.find('.table-wrapper').removeClass('table-fix-column').css('width', ''); - this._fixedColumnsElem.css('transform', '').css('will-change', '').removeClass('table-fixed-cell'); - this._fixedColumnsElem = null; - window.localStorage.setItem('ve-table-column-' + this.instanceSpec.id, 'false'); - return; + this.$element.find('.table-wrapper').removeClass('table-fix-column').css('width', '') + this._fixedColumnsElem.css('transform', '').css('will-change', '').removeClass('table-fixed-cell') + this._fixedColumnsElem = null + window.localStorage.setItem('ve-table-column-' + this.instanceSpec.id, 'false') + return } this.$element .find('.table-wrapper') .addClass('table-fix-column') - .css('width', window.innerWidth - 400); - this._fixedColumnsElem = this._findColumnCells('thead', 'th', this.numFixedColumns); - this._fixedColumnsElem = this._fixedColumnsElem.add(this._findColumnCells('tbody', 'td', this.numFixedColumns)); - this._fixedColumnsElem = this._fixedColumnsElem.add(this.$element.find('.table-fix-column caption')); - this._fixedColumnsElem.css('will-change', 'transform'); //browser optimization - this._fixedColumnsElem.addClass('table-fixed-cell'); - this.$element.find('.table-fix-column').on('scroll', this.scroll); - window.localStorage.setItem('ve-table-column-' + this.instanceSpec.id, this.numFixedColumns.toString()); - }; + .css('width', window.innerWidth - 400) + this._fixedColumnsElem = this._findColumnCells('thead', 'th', this.numFixedColumns) + this._fixedColumnsElem = this._fixedColumnsElem.add(this._findColumnCells('tbody', 'td', this.numFixedColumns)) + this._fixedColumnsElem = this._fixedColumnsElem.add(this.$element.find('.table-fix-column caption')) + this._fixedColumnsElem.css('will-change', 'transform') //browser optimization + this._fixedColumnsElem.addClass('table-fixed-cell') + this.$element.find('.table-fix-column').on('scroll', this.scroll) + window.localStorage.setItem('ve-table-column-' + this.instanceSpec.id, this.numFixedColumns.toString()) + } public updateFixedColumns = (): void => { - this.fixedColumns = false; - this.makeFixedColumn(); - this.fixedColumns = true; - this.makeFixedColumn(); - }; + this.fixedColumns = false + this.makeFixedColumn() + this.fixedColumns = true + this.makeFixedColumn() + } private _findColumnCells = (bodyTag: string, cellTag: string, n: number): JQuery => { - const spanData: boolean[][] = []; //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell - let curRow = 0; - let data = $(); + const spanData: boolean[][] = [] //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell + let curRow = 0 + let data = $() $(this.$element) .find('.table-fix-column table') .children(bodyTag) .children('tr') .each((index, element) => { - let curCol = 0; + let curCol = 0 $(element) .children(cellTag) .each((index, element) => { while (spanData[curRow] && spanData[curRow][curCol]) { - curCol++; + curCol++ } if (curCol >= n) { - return; + return } - data = data.add($(element)); - const rowstring = $(element).attr('rowspan'); - let rowspan = 0; + data = data.add($(element)) + const rowstring = $(element).attr('rowspan') + let rowspan = 0 if (rowstring) { - rowspan = parseInt(rowstring); + rowspan = parseInt(rowstring) if (rowspan > 1) { for (let i = 1; i < rowspan; i++) { if (!spanData[curRow + i]) { - spanData[curRow + i] = []; + spanData[curRow + i] = [] } - spanData[curRow + i][curCol] = true; + spanData[curRow + i][curCol] = true } } } - const colstring = $(element).attr('colspan'); + const colstring = $(element).attr('colspan') if (!colstring) { - curCol++; - return; + curCol++ + return } - let colspan = parseInt(colstring); + let colspan = parseInt(colstring) while (colspan > 1) { - curCol++; - colspan--; + curCol++ + colspan-- if (rowspan > 1) { for (let j = 1; j < rowspan; j++) { - spanData[curRow + j][curCol] = true; + spanData[curRow + j][curCol] = true } } } - curCol++; - }); - curRow++; - }); - return data; - }; + curCol++ + }) + curRow++ + }) + return data + } private compileTable(): void { void this.$timeout( () => { - const first = this.nextIndex; - if (first > this.lastIndex) return; - const now = this.trs.slice(first, first + 300); - this.$compile(now)(this.$scope); - this.nextIndex = first + 300; - if (this.nextIndex < this.lastIndex) this.compileTable(); + const first = this.nextIndex + if (first > this.lastIndex) return + const now = this.trs.slice(first, first + 300) + this.$compile(now)(this.$scope) + this.nextIndex = first + 300 + if (this.nextIndex < this.lastIndex) this.compileTable() else { if (window.localStorage.getItem('ve-table-header-' + this.instanceSpec.id) == 'true') { - this.fixedHeaders = true; - this.makeFixedHeader(); + this.fixedHeaders = true + this.makeFixedHeader() } - const columnFix = window.localStorage.getItem('ve-table-column-' + this.instanceSpec.id); + const columnFix = window.localStorage.getItem('ve-table-column-' + this.instanceSpec.id) if (columnFix != 'false' && columnFix != null && columnFix != 'null') { - this.fixedColumns = true; - this.numFixedColumns = Number.parseInt(columnFix); - this.makeFixedColumn(); + this.fixedColumns = true + this.numFixedColumns = Number.parseInt(columnFix) + this.makeFixedColumn() } } }, 100, false - ); + ) } } @@ -628,6 +628,6 @@ const PresentTableComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentTableController, -}; +} -veComponents.component(PresentTableComponent.selector, PresentTableComponent); +veComponents.component(PresentTableComponent.selector, PresentTableComponent) diff --git a/src/ve-components/presentations/index.ts b/src/ve-components/presentations/index.ts index d636c87c8..910d92e61 100644 --- a/src/ve-components/presentations/index.ts +++ b/src/ve-components/presentations/index.ts @@ -1,30 +1,30 @@ -export * from './presentation-element.controller'; +export * from './presentation-element.controller' //Services -import './services/ViewHtml.service'; -import './services/Presentation.service'; +import './services/ViewHtml.service' +import './services/Presentation.service' -export * from './services/ViewHtml.service'; -export * from './services/Presentation.service'; +export * from './services/ViewHtml.service' +export * from './services/Presentation.service' //Components -import './add-pe-menu.component'; -import './view.component'; +import './add-pe-menu.component' +import './view.component' -export * from './view.component'; -import './view-pe.component'; +export * from './view.component' +import './view-pe.component' -export * from './view-pe.component'; -import './mms-view-link.component'; +export * from './view-pe.component' +import './mms-view-link.component' //Presentations -import './components/present-equation.component'; -import './components/present-figure.component'; -import './components/present-image.component'; -import './components/present-list.component'; -import './components/present-list-t.component'; -import './components/present-paragraph.component'; -import './components/present-table.component'; -import './components/present-table-t.component'; -import './components/present-section.component'; -import './components/present-comment.component'; +import './components/present-equation.component' +import './components/present-figure.component' +import './components/present-image.component' +import './components/present-list.component' +import './components/present-list-t.component' +import './components/present-paragraph.component' +import './components/present-table.component' +import './components/present-table-t.component' +import './components/present-section.component' +import './components/present-comment.component' diff --git a/src/ve-components/presentations/mms-view-link.component.ts b/src/ve-components/presentations/mms-view-link.component.ts index 556d29cdf..f40b12072 100644 --- a/src/ve-components/presentations/mms-view-link.component.ts +++ b/src/ve-components/presentations/mms-view-link.component.ts @@ -1,16 +1,16 @@ -import $ from 'jquery'; +import $ from 'jquery' -import { ViewController } from '@ve-components/presentations/view.component'; -import { ExtensionService } from '@ve-components/services'; -import { CrossReferenceController } from '@ve-components/transclusions/mms-cf.component'; -import { ApplicationService } from '@ve-utils/application'; -import { ApiService, ElementService, ViewService } from '@ve-utils/mms-api-client'; -import { handleChange, onChangesCallback } from '@ve-utils/utils'; +import { ViewController } from '@ve-components/presentations/view.component' +import { ExtensionService } from '@ve-components/services' +import { CrossReferenceController } from '@ve-components/transclusions/mms-cf.component' +import { ApplicationService } from '@ve-utils/application' +import { ApiService, ElementService, ViewService } from '@ve-utils/mms-api-client' +import { handleChange, onChangesCallback } from '@ve-utils/utils' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions } from '@ve-types/angular'; -import { ElementObject, ElementsRequest } from '@ve-types/mms'; +import { VeComponentOptions } from '@ve-types/angular' +import { ElementObject, ElementsRequest } from '@ve-types/mms' /** * @ngdoc directive @@ -30,35 +30,35 @@ import { ElementObject, ElementsRequest } from '@ve-types/mms'; */ class ViewLinkController implements angular.IComponentController { //Bindings - public mmsElementId: string; - mmsProjectId: string; - mmsRefId: string; - mmsCommitId: string; - mmsDocId: string; - mmsPeId: string; - linkText: string; - linkClass: string; - linkIconClass: string; - linkTarget: string; - mmsExternalLink: boolean; - suppressNumbering: boolean; - showName: boolean; + public mmsElementId: string + mmsProjectId: string + mmsRefId: string + mmsCommitId: string + mmsDocId: string + mmsPeId: string + linkText: string + linkClass: string + linkIconClass: string + linkTarget: string + mmsExternalLink: boolean + suppressNumbering: boolean + showName: boolean // Controllers - private mmsCfCtrl: CrossReferenceController; - private mmsViewCtrl: ViewController; + private mmsCfCtrl: CrossReferenceController + private mmsViewCtrl: ViewController // Locals - loading: boolean = true; - target: string; - private processed: boolean = false; - projectId: string; - refId: string; - commitId: string; - element: ElementObject; - elementName: string; - type: string; - $transcludeEl: JQuery; + loading: boolean = true + target: string + private processed: boolean = false + projectId: string + refId: string + commitId: string + element: ElementObject + elementName: string + type: string + $transcludeEl: JQuery static $inject = [ '$scope', @@ -70,13 +70,13 @@ class ViewLinkController implements angular.IComponentController { 'ViewService', 'ApplicationService', 'ExtensionService', - ]; - suffix: string; - hash: string; - href: string; - private docid: string; - showNum: boolean; - vid: string; + ] + suffix: string + hash: string + href: string + private docid: string + showNum: boolean + vid: string constructor( private $scope: angular.IScope, @@ -91,47 +91,47 @@ class ViewLinkController implements angular.IComponentController { ) {} $onInit(): void { - this.target = this.linkTarget ? this.linkTarget : '_self'; + this.target = this.linkTarget ? this.linkTarget : '_self' } $onChanges(onChangesObj: angular.IOnChangesObject): void { - handleChange(onChangesObj, 'mmsElementId', this.changeAction); + handleChange(onChangesObj, 'mmsElementId', this.changeAction) } $postLink(): void { - this.changeAction(this.mmsElementId, '', false); + this.changeAction(this.mmsElementId, '', false) } protected changeAction: onChangesCallback = (newVal, oldVal, firstChange) => { - if (!newVal || (newVal === oldVal && this.processed)) return; + if (!newVal || (newVal === oldVal && this.processed)) return - this.processed = true; + this.processed = true - let projectId = this.mmsProjectId; - let refId = this.mmsRefId; - let commitId = this.mmsCommitId; - let docid = this.mmsDocId; + let projectId = this.mmsProjectId + let refId = this.mmsRefId + let commitId = this.mmsCommitId + let docid = this.mmsDocId if (this.mmsCfCtrl) { - const cfVersion = this.mmsCfCtrl.getElementOrigin(); - if (!projectId) projectId = cfVersion.projectId; - if (!refId) refId = cfVersion.refId; - if (!commitId) commitId = cfVersion.commitId; + const cfVersion = this.mmsCfCtrl.getElementOrigin() + if (!projectId) projectId = cfVersion.projectId + if (!refId) refId = cfVersion.refId + if (!commitId) commitId = cfVersion.commitId } if (this.mmsViewCtrl) { - const viewVersion = this.mmsViewCtrl.getElementOrigin(); - if (!projectId) projectId = viewVersion.projectId; - if (!refId) refId = viewVersion.refId; - if (!commitId) commitId = viewVersion.commitId; + const viewVersion = this.mmsViewCtrl.getElementOrigin() + if (!projectId) projectId = viewVersion.projectId + if (!refId) refId = viewVersion.refId + if (!commitId) commitId = viewVersion.commitId } if (!projectId) { - return; + return } - this.projectId = projectId; - this.refId = refId ? refId : 'master'; - this.commitId = commitId ? commitId : 'latest'; - let elementId = this.mmsElementId; + this.projectId = projectId + this.refId = refId ? refId : 'master' + this.commitId = commitId ? commitId : 'latest' + let elementId = this.mmsElementId if (!elementId && this.mmsPeId && !this.mmsDocId) { - elementId = this.applicationSvc.getState().currentDoc; + elementId = this.applicationSvc.getState().currentDoc } const reqOb: ElementsRequest = { @@ -139,89 +139,89 @@ class ViewLinkController implements angular.IComponentController { projectId, refId, commitId, - }; + } this.elementSvc .getElement(reqOb, 1) .then( (data: ElementObject) => { - this.element = data; - this.elementName = data.name; - this.type = 'Section '; - this.suffix = ''; - this.hash = '#' + data.id; + this.element = data + this.elementName = data.name + this.type = 'Section ' + this.suffix = '' + this.hash = '#' + data.id if (this.mmsPeId && this.mmsPeId !== '') { const reqPEOb: ElementsRequest = { elementId: this.mmsPeId, projectId, refId, commitId, - }; + } this.elementSvc.getElement(reqPEOb).then( (pe) => { - this.vid = pe.id; - this.element = pe; - this.elementName = pe.name; + this.vid = pe.id + this.element = pe + this.elementName = pe.name if (this.viewSvc.isTable(pe)) { - this.type = 'Table '; + this.type = 'Table ' } else if (this.viewSvc.isFigure(pe)) { - this.type = 'Fig. '; + this.type = 'Fig. ' } else if (this.viewSvc.isEquation(pe)) { - this.type = 'Eq. ('; - this.suffix = ')'; + this.type = 'Eq. (' + this.suffix = ')' } if (this.applicationSvc.getState().fullDoc) { - this.href = `main.project.ref.view.present.document({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })`; + this.href = `main.project.ref.view.present.document({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })` } else { - this.href = `main.project.ref.view.present.slideshow({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })`; + this.href = `main.project.ref.view.present.slideshow({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })` } }, (reason) => { - this.growl.warning(`Unable to retrieve element: ${reason.message}`); + this.growl.warning(`Unable to retrieve element: ${reason.message}`) } - ); + ) } if (this.apiSvc.isDocument(data)) { - docid = data.id; - this.docid = docid; - this.vid = data.id; + docid = data.id + this.docid = docid + this.vid = data.id } else if (this.apiSvc.isView(data) || data.type === 'InstanceSpecification') { if (!docid || docid === '') { - docid = this.applicationSvc.getState().currentDoc; + docid = this.applicationSvc.getState().currentDoc } - this.docid = docid; - this.vid = data.id; + this.docid = docid + this.vid = data.id } else { - this.$element.html('view link doesn\'t refer to a view'); + this.$element.html('view link doesn\'t refer to a view') } if (this.applicationSvc.getState().fullDoc) { - this.href = `main.project.ref.view.present.document({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })`; + this.href = `main.project.ref.view.present.document({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })` } else { - this.href = `main.project.ref.view.present.slideshow({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })`; + this.href = `main.project.ref.view.present.slideshow({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })` } this.showNum = this.applicationSvc.getState().inDoc && this.applicationSvc.getState().currentDoc === this.docid && - !this.suppressNumbering; + !this.suppressNumbering }, (reason) => { - this.$element.empty(); + this.$element.empty() this.$transcludeEl = $( '' - ); - this.$element.append(this.$transcludeEl); + ) + this.$element.append(this.$transcludeEl) this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: reqOb.elementId, recentElement: reason.recentVersionOfElement, type: 'link', }) - ); + ) } ) .finally(() => { - this.loading = false; - }); - }; + this.loading = false + }) + } } export const MmsViewLinkComponent: VeComponentOptions = { @@ -260,6 +260,6 @@ export const MmsViewLinkComponent: VeComponentOptions = { showName: '<', }, controller: ViewLinkController, -}; +} -veComponents.component(MmsViewLinkComponent.selector, MmsViewLinkComponent); +veComponents.component(MmsViewLinkComponent.selector, MmsViewLinkComponent) diff --git a/src/ve-components/presentations/mmsMaturityBar.directive.ts b/src/ve-components/presentations/mmsMaturityBar.directive.ts index 871d97827..8c5de38e7 100644 --- a/src/ve-components/presentations/mmsMaturityBar.directive.ts +++ b/src/ve-components/presentations/mmsMaturityBar.directive.ts @@ -1,6 +1,6 @@ -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -veComponents.directive('mmsMaturityBar', ['$window', mmsMaturityBar]); +veComponents.directive('mmsMaturityBar', ['$window', mmsMaturityBar]) /** * @ngdoc directive @@ -12,23 +12,23 @@ veComponents.directive('mmsMaturityBar', ['$window', mmsMaturityBar]); */ function mmsMaturityBar($window) { const mmsMaturityBarLink = (scope, element, attrs) => { - const d3 = $window.d3; + const d3 = $window.d3 - const svgContainer = d3.select(element[0]).append('svg').attr('width', 520).attr('height', 70); - let colorRect; + const svgContainer = d3.select(element[0]).append('svg').attr('width', 520).attr('height', 70) + let colorRect if (scope.state == 'Identified') { - colorRect = ['brown', '#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0']; + colorRect = ['brown', '#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0'] } else if (scope.state == 'Draft') { - colorRect = ['#FF7519', '#FF7519', '#B0B0B0', '#B0B0B0', '#B0B0B0']; + colorRect = ['#FF7519', '#FF7519', '#B0B0B0', '#B0B0B0', '#B0B0B0'] } else if (scope.state == 'Prelim') { - colorRect = ['#FFAA00', '#FFAA00', '#FFAA00', '#B0B0B0', '#B0B0B0']; + colorRect = ['#FFAA00', '#FFAA00', '#FFAA00', '#B0B0B0', '#B0B0B0'] } else if (scope.state == 'Baseline') { - colorRect = ['#04859E', '#04859E', '#04859E', '#04859E', '#B0B0B0']; + colorRect = ['#04859E', '#04859E', '#04859E', '#04859E', '#B0B0B0'] } else if (scope.state == 'Final') { - colorRect = ['#00BD39', '#00BD39', '#00BD39', '#00BD39', '#00BD39']; + colorRect = ['#00BD39', '#00BD39', '#00BD39', '#00BD39', '#00BD39'] } else { - colorRect = ['#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0']; + colorRect = ['#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0'] } svgContainer @@ -39,7 +39,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[0]) .style('stroke', '#fff') - .style('stroke-width', 3); + .style('stroke-width', 3) svgContainer .append('text') .text('Identified') @@ -48,7 +48,7 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle'); + .style('text-anchor', 'middle') svgContainer .append('rect') .attr('x', 110) @@ -57,7 +57,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[1]) .style('stroke', '#fff') - .style('stroke-width', 3); + .style('stroke-width', 3) svgContainer .append('text') .text('Draft') @@ -66,7 +66,7 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle'); + .style('text-anchor', 'middle') svgContainer .append('rect') .attr('x', 210) @@ -75,7 +75,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[2]) .style('stroke', '#fff') - .style('stroke-width', 3); + .style('stroke-width', 3) svgContainer .append('text') .text('Prelim') @@ -84,7 +84,7 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle'); + .style('text-anchor', 'middle') svgContainer .append('rect') .attr('x', 310) @@ -93,7 +93,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[3]) .style('stroke', '#fff') - .style('stroke-width', 3); + .style('stroke-width', 3) svgContainer .append('text') .text('Baseline') @@ -102,7 +102,7 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle'); + .style('text-anchor', 'middle') svgContainer .append('rect') .attr('x', 410) @@ -111,7 +111,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[4]) .style('stroke', '#fff') - .style('stroke-width', 3); + .style('stroke-width', 3) svgContainer .append('text') .text('Final') @@ -120,8 +120,8 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle'); - }; + .style('text-anchor', 'middle') + } return { restrict: 'E', @@ -130,5 +130,5 @@ function mmsMaturityBar($window) { state: '@', }, link: mmsMaturityBarLink, - }; + } } diff --git a/src/ve-components/presentations/presentation-element.controller.ts b/src/ve-components/presentations/presentation-element.controller.ts index f0aa45e5d..7c00141e1 100644 --- a/src/ve-components/presentations/presentation-element.controller.ts +++ b/src/ve-components/presentations/presentation-element.controller.ts @@ -1,56 +1,56 @@ -import $ from 'jquery'; +import $ from 'jquery' -import { ViewHtmlService, ViewPresentationElemController, PresentationService } from '@ve-components/presentations'; -import { ViewController } from '@ve-components/presentations/view.component'; -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { ImageService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ViewHtmlService, ViewPresentationElemController, PresentationService } from '@ve-components/presentations' +import { ViewController } from '@ve-components/presentations/view.component' +import { ComponentService, ExtensionService } from '@ve-components/services' +import { ButtonBarService } from '@ve-core/button-bar' +import { ImageService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { SchemaService } from '@ve-utils/model-schema' -import { VePromise, VeQService } from '@ve-types/angular'; +import { VePromise, VeQService } from '@ve-types/angular' import { ElementObject, InstanceSpecObject, InstanceValueObject, PresentationInstanceObject, ViewObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' export class PresentationLite { //Bindings - public peObject: PresentationInstanceObject; - public instanceSpec: InstanceSpecObject; - public peNumber: string; + public peObject: PresentationInstanceObject + public instanceSpec: InstanceSpecObject + public peNumber: string } export class Presentation extends PresentationLite { //Bindings - protected mmsProjectId: string; - protected mmsRefId: string; - protected mmsCommitId: string; + protected mmsProjectId: string + protected mmsRefId: string + protected mmsCommitId: string //Deps - protected mmsViewPresentationElemCtrl: ViewPresentationElemController; - protected mmsViewCtrl: ViewController; + protected mmsViewPresentationElemCtrl: ViewPresentationElemController + protected mmsViewCtrl: ViewController - subs: Rx.IDisposable[]; + subs: Rx.IDisposable[] //Common //public element: ElementObject; - protected $transcludeEl: JQuery; - public view: ViewObject; - public projectId: string; - public refId: string; - public commitId: string; - public instanceVal: InstanceValueObject; - protected presentationElem: PresentationInstanceObject | ElementObject; - protected isDirectChildOfPresentationElement: boolean; + protected $transcludeEl: JQuery + public view: ViewObject + public projectId: string + public refId: string + public commitId: string + public instanceVal: InstanceValueObject + protected presentationElem: PresentationInstanceObject | ElementObject + protected isDirectChildOfPresentationElement: boolean - public number: string; - public level: number; + public number: string + public level: number - private schema = 'cameo'; + private schema = 'cameo' static $inject = [ '$q', @@ -66,7 +66,7 @@ export class Presentation extends PresentationLite { 'ImageService', 'ButtonBarService', 'ExtensionService', - ]; + ] constructor( protected $q: VeQService, protected $element: JQuery, @@ -82,36 +82,36 @@ export class Presentation extends PresentationLite { protected buttonBarSvc: ButtonBarService, protected extensionSvc: ExtensionService ) { - super(); + super() } /** * @listens element.updated */ $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) - this.setNumber(); + this.setNumber() - let projectId = this.mmsProjectId; - let refId = this.mmsRefId; - let commitId = this.mmsCommitId; + let projectId = this.mmsProjectId + let refId = this.mmsRefId + let commitId = this.mmsCommitId if (this.mmsViewCtrl) { - const viewVersion = this.mmsViewCtrl.getElementOrigin(); - if (!projectId) projectId = viewVersion.projectId; - if (!refId) refId = viewVersion.refId; - if (!commitId) commitId = viewVersion.commitId; + const viewVersion = this.mmsViewCtrl.getElementOrigin() + if (!projectId) projectId = viewVersion.projectId + if (!refId) refId = viewVersion.refId + if (!commitId) commitId = viewVersion.commitId } - this.projectId = projectId; - this.refId = refId ? refId : 'master'; - this.commitId = commitId ? commitId : 'latest'; + this.projectId = projectId + this.refId = refId ? refId : 'master' + this.commitId = commitId ? commitId : 'latest' - this.config(); + this.config() } $postLink(): void { - this.recompile(); + this.recompile() } // Presentation Api @@ -124,7 +124,7 @@ export class Presentation extends PresentationLite { */ protected config = (): void => { /* Implement any initialization Logic Here */ - }; + } /** * @name Presentation/getContent @@ -132,8 +132,8 @@ export class Presentation extends PresentationLite { * @description Extension API method in which presentation components should return the content they wish to display. */ protected getContent = (): VePromise => { - return this.$q.reject('Not Yet Implemented'); - }; + return this.$q.reject('Not Yet Implemented') + } /** * @name Presentation/recompile @@ -143,16 +143,16 @@ export class Presentation extends PresentationLite { * This function is automatically triggered by the "element.updated" event. */ protected recompile = (): void => { - this.setNumber(); + this.setNumber() this.getContent().then( (result) => { - this.$element.empty(); - this.$transcludeEl = $(result); + this.$element.empty() + this.$transcludeEl = $(result) this.$transcludeEl.find('img').each((index, element) => { - this.imageSvc.fixImgSrc($(element)); - }); - this.$element.append(this.$transcludeEl); - this.$compile(this.$transcludeEl)(this.$scope); + this.imageSvc.fixImgSrc($(element)) + }) + this.$element.append(this.$transcludeEl) + this.$compile(this.$transcludeEl)(this.$scope) }, (reason) => { const reqOb = { @@ -161,23 +161,23 @@ export class Presentation extends PresentationLite { refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - }; - this.$element.empty(); + } + this.$element.empty() //TODO: Add reason/errorMessage handling here. this.$transcludeEl = $( '' - ); - this.$element.append(this.$transcludeEl); + ) + this.$element.append(this.$transcludeEl) this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: reqOb.elementId, recentElement: reason.recentVersionOfElement, type: 'presentation', }) - ); + ) } - ); - }; + ) + } // Static Helper Functions /** @@ -189,9 +189,9 @@ export class Presentation extends PresentationLite { */ public setNumber = (): void => { if (this.peNumber) { - if (Number.isInteger(this.peNumber)) this.level = 1; - else this.level = this.peNumber.split('.').length; - this.number = this.peNumber; + if (Number.isInteger(this.peNumber)) this.level = 1 + else this.level = this.peNumber.split('.').length + this.number = this.peNumber } - }; + } } diff --git a/src/ve-components/presentations/services/Presentation.service.ts b/src/ve-components/presentations/services/Presentation.service.ts index 4e27e887a..6c35f228f 100644 --- a/src/ve-components/presentations/services/Presentation.service.ts +++ b/src/ve-components/presentations/services/Presentation.service.ts @@ -1,23 +1,23 @@ -import { InsertPresentationData } from '@ve-components/insertions/components/insert-pe.component'; -import { ViewService } from '@ve-utils/mms-api-client'; +import { InsertPresentationData } from '@ve-components/insertions/components/insert-pe.component' +import { ViewService } from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { InsertResolveFn } from '@ve-types/components'; -import { ElementObject, InstanceSpecObject, InstanceValueObject } from '@ve-types/mms'; -import { VeModalService } from '@ve-types/view-editor'; +import { InsertResolveFn } from '@ve-types/components' +import { ElementObject, InstanceSpecObject, InstanceValueObject } from '@ve-types/mms' +import { VeModalService } from '@ve-types/view-editor' export class PresentationService { private revertData: { - elementId: string; - baseCommit: object; - refId: string; - compareCommit: object; - projectId: string; - element: object; - }; + elementId: string + baseCommit: object + refId: string + compareCommit: object + projectId: string + element: object + } - static $inject = ['$timeout', '$uibModal', 'growl', 'ViewService']; + static $inject = ['$timeout', '$uibModal', 'growl', 'ViewService'] constructor( private $timeout: angular.ITimeoutService, @@ -29,23 +29,23 @@ export class PresentationService { public checkForDuplicateInstances(operand: InstanceValueObject[]): InstanceValueObject[] { const seen: { [id: string]: boolean } = {}, dups: InstanceValueObject[] = [], - cleared: InstanceValueObject[] = []; - let curr: string; + cleared: InstanceValueObject[] = [] + let curr: string operand.forEach((value, index) => { - curr = value.instanceId; + curr = value.instanceId if (curr) { if (seen[curr]) { - dups.push(value); - operand.splice(index, 1); - return; + dups.push(value) + operand.splice(index, 1) + return } - cleared.push(value); - seen[curr] = true; + cleared.push(value) + seen[curr] = true } - }); - operand.length = 0; - operand.push(...cleared); - return dups; + }) + operand.length = 0 + operand.push(...cleared) + return dups } /** @@ -69,46 +69,46 @@ export class PresentationService { viewOrSectionOb, addPeIndex: $ctrl.addPeIndex, parentBranch: null, - }; + } }, getProjectId: () => { - return viewOrSectionOb._projectId; + return viewOrSectionOb._projectId }, getRefId: () => { - return viewOrSectionOb._refId; + return viewOrSectionOb._refId }, getOrgId: () => { - return ''; + return '' }, }, - }); + }) instance.result.then( (data) => { if (data.type !== 'InstanceSpecification' || this.viewSvc.isSection(data)) { - return; //do not open editor for existing pes added or if pe/owner is a section + return //do not open editor for existing pes added or if pe/owner is a section } void this.$timeout( () => { //auto open editor for newly added pe $('#' + data.id) .find('transclude-doc,transclude-com') - .trigger('click'); + .trigger('click') }, 0, false - ); + ) }, (reason) => { if (reason && reason.status !== 444) { - this.growl.warning(`Error adding PE: ${reason.message}`); + this.growl.warning(`Error adding PE: ${reason.message}`) } else { this.growl.info('PE Insert Cancelled', { ttl: 1000, - }); + }) } } - ); + ) } } -veComponents.service('PresentationService', PresentationService); +veComponents.service('PresentationService', PresentationService) diff --git a/src/ve-components/presentations/services/Table2CSV.service.ts b/src/ve-components/presentations/services/Table2CSV.service.ts index 04bb4ec81..64650a96f 100644 --- a/src/ve-components/presentations/services/Table2CSV.service.ts +++ b/src/ve-components/presentations/services/Table2CSV.service.ts @@ -1,4 +1,4 @@ -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' export class Table2CSVService { public static export(el: JQuery, inputOptions: JQuery.table2CSV.inputOptions): string { @@ -9,113 +9,113 @@ export class Table2CSVService { delivery: 'popup', // popup, value }, inputOptions - ); + ) - const csvData: string[] = []; + const csvData: string[] = [] // const el = this const row2CSV = (tmpRow: string[]): void => { - const tmp = tmpRow.join(''); // to remove any blank rows + const tmp = tmpRow.join('') // to remove any blank rows if (tmpRow.length > 0 && tmp != '') { - csvData[csvData.length] = tmpRow.join(options.separator); + csvData[csvData.length] = tmpRow.join(options.separator) } - }; + } const formatData = (input: string): string => { // replace " with “ - const regexp = new RegExp(/["]/g); - let output = input.replace(regexp, '“'); + const regexp = new RegExp(/["]/g) + let output = input.replace(regexp, '“') //HTML // var regexp = new RegExp(/\<[^\<]+\>/g); // var output = output.replace(regexp, ""); - const i = output.search(/\S/); //index of first non whitespace char + const i = output.search(/\S/) //index of first non whitespace char if (i > 0) { - output = '_'.repeat(i) + $.trim(output); + output = '_'.repeat(i) + $.trim(output) } - output = $.trim(output); - if (output == '') return ''; + output = $.trim(output) + if (output == '') return '' if (output[0] == '+' || output[0] == '=' || output[0] == '-') { - output = ' ' + output; + output = ' ' + output } - return `"${output}"`; - }; + return `"${output}"` + } const popup = (data: string): string => { - const generator = window.open('', 'csv', 'height=400,width=600'); - generator.document.write('CSV'); - generator.document.write(''); - generator.document.write(''); - generator.document.write(''); - generator.document.close(); - return 'ok'; - }; + const generator = window.open('', 'csv', 'height=400,width=600') + generator.document.write('CSV') + generator.document.write('') + generator.document.write('') + generator.document.write('') + generator.document.close() + return 'ok' + } const handleMatrix = (bodyTag: string, cellTag: string): void => { - const spanData: { [row: number]: { [column: number]: unknown } } = {}; //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell - let curRow = 0; + const spanData: { [row: number]: { [column: number]: unknown } } = {} //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell + let curRow = 0 $(el) .children(bodyTag) .children('tr') .each((index, element) => { - tmpRow = []; - let curCol = 0; + tmpRow = [] + let curCol = 0 $(element) .children(cellTag) .each((index, element) => { while (spanData[curRow] && spanData[curRow][curCol]) { - tmpRow.push('""'); - curCol++; + tmpRow.push('""') + curCol++ } - tmpRow.push(formatData($(element).text())); - const rowstring = $(element).attr('rowspan'); - const rowspan = parseInt(rowstring); + tmpRow.push(formatData($(element).text())) + const rowstring = $(element).attr('rowspan') + const rowspan = parseInt(rowstring) if (rowspan && rowspan > 1) { for (let i = 1; i < rowspan; i++) { if (!spanData[curRow + i]) { - spanData[curRow + i] = {}; + spanData[curRow + i] = {} } - spanData[curRow + i][curCol] = true; + spanData[curRow + i][curCol] = true } } - const colstring = $(element).attr('colspan'); + const colstring = $(element).attr('colspan') if (!colstring) { - curCol++; - return; + curCol++ + return } - let colspan = parseInt(colstring); + let colspan = parseInt(colstring) while (colspan > 1) { - curCol++; - tmpRow.push('""'); - colspan--; + curCol++ + tmpRow.push('""') + colspan-- if (rowspan > 1) { for (let i = 1; i < rowspan; i++) { - spanData[curRow + i][curCol] = true; + spanData[curRow + i][curCol] = true } } } - curCol++; - }); - row2CSV(tmpRow); - curRow++; - }); - }; + curCol++ + }) + row2CSV(tmpRow) + curRow++ + }) + } //header - const numCols = options.header.length; - let tmpRow: string[] = []; + const numCols = options.header.length + let tmpRow: string[] = [] if (numCols > 0) { for (let i = 0; i < numCols; i++) { - tmpRow[tmpRow.length] = formatData(options.header[i]); + tmpRow[tmpRow.length] = formatData(options.header[i]) } } else { - handleMatrix('thead', 'th'); + handleMatrix('thead', 'th') } // actual data - handleMatrix('tbody', 'td'); - const mydata = csvData.join('\n'); + handleMatrix('tbody', 'td') + const mydata = csvData.join('\n') if (options.delivery == 'popup') { - return popup(mydata); + return popup(mydata) } else { - return mydata; + return mydata } } } -veComponents.service('Table2CSVService', Table2CSVService); +veComponents.service('Table2CSVService', Table2CSVService) diff --git a/src/ve-components/presentations/services/ViewHtml.service.ts b/src/ve-components/presentations/services/ViewHtml.service.ts index 3dc9d009d..daa144561 100644 --- a/src/ve-components/presentations/services/ViewHtml.service.ts +++ b/src/ve-components/presentations/services/ViewHtml.service.ts @@ -1,8 +1,8 @@ -import { ApplicationService } from '@ve-utils/application'; +import { ApplicationService } from '@ve-utils/application' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { ITableConfig } from '@ve-types/components/presentation'; +import { ITableConfig } from '@ve-types/components/presentation' import { PresentationInstanceObject, PresentImageObject, @@ -10,7 +10,7 @@ import { PresentTableObject, PresentTextObject, TableEntryObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' export class ViewHtmlService { public tableConfig: ITableConfig = { @@ -20,9 +20,9 @@ export class ViewHtmlService { showBindingForSortIcon: -1, filterDebounceRate: 200, filterTermColumnPrefixBinding: 'filterTermForColumn', - }; + } - static $inject = ['ApplicationService']; + static $inject = ['ApplicationService'] constructor(private applicationSvc: ApplicationService) {} @@ -36,65 +36,65 @@ export class ViewHtmlService { * @returns {string} generated html string */ public makeHtmlTable = (table: PresentTableObject, isFilterable?: boolean, isSortable?: boolean, pe?): string => { - const result = ['']; + const result = ['
    '] if (table.colwidths && table.colwidths.length > 0) { - result.push(''); + result.push('') for (let i = 0; i < table.colwidths.length; i++) { if (table.colwidths[i]) { - result.push(''); + result.push('') } else { - result.push(''); + result.push('') } } - result.push(''); + result.push('') } - result.push(''); //put tbody before thead to control stacking context so if freeze header/columns are both used headers cover cells (?) + result.push('') //put tbody before thead to control stacking context so if freeze header/columns are both used headers cover cells (?) //https://stackoverflow.com/questions/45676848/stacking-context-on-table-elementhead-and-body - result.push(this.makeTableBody(table.body, false)); - result.push(''); + result.push(this.makeTableBody(table.body, false)) + result.push('') if (table.header && table.header.length) { // only add styling to the filterable or sortable header if (isFilterable || isSortable) { - result.push(''); + result.push('') } else { - result.push(''); + result.push('') } - result.push(this.makeTableBody(table.header, true, isFilterable, isSortable)); - result.push(''); + result.push(this.makeTableBody(table.header, true, isFilterable, isSortable)) + result.push('') } if (this.applicationSvc.getState().inDoc && !table.excludeFromList) { result.push( '' - ); + ) } else if (table.title) { - result.push(''); + result.push('') } //same for caption to control stacking context - result.push('
    Table {{$ctrl.instanceSpec._veNumber}}. {{$ctrl.table.title || $ctrl.instanceSpec.name}}' + table.title + '' + table.title + '
    '); - return result.join(''); - }; + result.push('') + return result.join('') + } /** Include row and column number for table's header data object **/ public generateRowColNumber(header: TableEntryObject[][]): void { header.forEach((row, rowIndex) => { - let startCol = 0; - let colCounter = 0; + let startCol = 0 + let colCounter = 0 row.forEach((cell, cellIndex) => { // startCol is always 0 except when row > 0th and on cell === 0th && rowSpan of the previous row's first element is larger than 1 // This is the only time when we need to offset the starting colNumber for cells under merged this.column(s) if (rowIndex !== 0 && cellIndex === 0 && Number(header[rowIndex - 1][0].rowspan) > 1) { - startCol = Number(header[rowIndex - 1][0].colspan); + startCol = Number(header[rowIndex - 1][0].colspan) } - const colSpan = Number(cell.colspan); - cell.startRow = rowIndex; - cell.endRow = cell.startRow + Number(cell.rowspan) - 1; - cell.startCol = startCol + colCounter; - cell.endCol = cell.startCol + colSpan - 1; - colCounter += colSpan; - }); - startCol = 0; - colCounter = 0; - }); + const colSpan = Number(cell.colspan) + cell.startRow = rowIndex + cell.endRow = cell.startRow + Number(cell.rowspan) - 1 + cell.startCol = startCol + colCounter + cell.endCol = cell.startCol + colSpan - 1 + colCounter += colSpan + }) + startCol = 0 + colCounter = 0 + }) } /** @@ -114,46 +114,46 @@ export class ViewHtmlService { isSortable?: boolean ): string { if (isHeader && (isFilterable || isSortable)) { - this.generateRowColNumber(body); + this.generateRowColNumber(body) } - const result = []; - const dtag: string = isHeader ? 'th' : 'td'; + const result = [] + const dtag: string = isHeader ? 'th' : 'td' body.forEach((row) => { - result.push(''); + result.push('') row.forEach((cell) => { - result.push(`<${dtag} colspan="${cell.colspan}" rowspan="${cell.rowspan}">`); + result.push(`<${dtag} colspan="${cell.colspan}" rowspan="${cell.rowspan}">`) cell.content.forEach((thing) => { if (isFilterable || isSortable) { - result.push('
    '); + result.push('
    ') } else { - result.push('
    '); + result.push('
    ') } - let thingString = this.makeHtml(thing); + let thingString = this.makeHtml(thing) if (thing.type === 'Paragraph') { if ((isFilterable || isSortable) && thing.sourceType === 'text' && dtag === 'th') { - thingString = thingString.replace('

    ', '

    '); + thingString = thingString.replace('

    ', '

    ') } } - result.push(thingString); - result.push('

    '); + result.push(thingString) + result.push('
    ') if (isHeader) { if (isSortable && Number(cell.colspan) === 1) { result.push( `` - ); + ) } if (isFilterable) { result.push( `` - ); + ) } } - }); - result.push(''); - }); - result.push(''); - }); - return result.join(''); + }) + result.push('') + }) + result.push('') + }) + return result.join('') } /** @@ -164,22 +164,22 @@ export class ViewHtmlService { * @returns {string} generated html string */ public makeHtmlList = (list: PresentListObject): string => { - const result: string[] = []; - if (list.ordered) result.push('
      '); - else result.push('
        '); + const result: string[] = [] + if (list.ordered) result.push('
          ') + else result.push('
            ') list.list.forEach((item) => { - result.push('
          • '); + result.push('
          • ') item.forEach((thing) => { - result.push('
            '); - result.push(this.makeHtml(thing)); - result.push('
            '); - }); - result.push('
          • '); - }); - if (list.ordered) result.push('
        '); - else result.push('
      '); - return result.join(''); - }; + result.push('
      ') + result.push(this.makeHtml(thing)) + result.push('
      ') + }) + result.push('') + }) + if (list.ordered) result.push('
    ') + else result.push('') + return result.join('') + } /** * @name veUtils/UtilsService#makeHtmlPara @@ -189,32 +189,32 @@ export class ViewHtmlService { * @returns {string} generated html string */ public makeHtmlPara = (para: PresentTextObject): string => { - if (para.sourceType === 'text') return para.text; - let t = 'doc'; - let attr = ''; + if (para.sourceType === 'text') return para.text + let t = 'doc' + let attr = '' if (para.sourceProperty === 'name') { - t = 'name'; + t = 'name' } if (para.sourceProperty === 'value') { - t = 'val'; + t = 'val' } if (para.nonEditable) { - attr = ` non-editable="${para.nonEditable.toString()}"`; + attr = ` non-editable="${para.nonEditable.toString()}"` } - return ''; - }; + return '' + } public makeHtml = (thing: PresentationInstanceObject): string => { if (thing.type === 'Paragraph') { - return this.makeHtmlPara(thing as PresentTextObject); + return this.makeHtmlPara(thing as PresentTextObject) } else if (thing.type === 'Table') { - return this.makeHtmlTable(thing as PresentTableObject); + return this.makeHtmlTable(thing as PresentTableObject) } else if (thing.type === 'List') { - return this.makeHtmlList(thing as PresentListObject); + return this.makeHtmlList(thing as PresentListObject) } else if (thing.type === 'Image') { - return ``; + return `` } - }; + } } -veComponents.service('ViewHtmlService', ViewHtmlService); +veComponents.service('ViewHtmlService', ViewHtmlService) diff --git a/src/ve-components/presentations/view-pe.component.ts b/src/ve-components/presentations/view-pe.component.ts index 35f0f0864..eae202dff 100644 --- a/src/ve-components/presentations/view-pe.component.ts +++ b/src/ve-components/presentations/view-pe.component.ts @@ -1,21 +1,21 @@ -import $ from 'jquery'; +import $ from 'jquery' -import { ViewController } from '@ve-components/presentations/view.component'; -import { ExtensionService } from '@ve-components/services'; -import { TreeService } from '@ve-components/trees'; -import { EventService } from '@ve-utils/core'; -import { ElementService, ViewService } from '@ve-utils/mms-api-client'; +import { ViewController } from '@ve-components/presentations/view.component' +import { ExtensionService } from '@ve-components/services' +import { TreeService } from '@ve-components/trees' +import { EventService } from '@ve-utils/core' +import { ElementService, ViewService } from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromiseReason } from '@ve-types/angular'; +import { VeComponentOptions, VePromiseReason } from '@ve-types/angular' import { ElementObject, ElementsRequest, InstanceSpecObject, InstanceValueObject, PresentationInstanceObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' /** * @ngdoc component @@ -38,17 +38,17 @@ import { * @param {Object} mmsParentSection the parent section if available */ export class ViewPresentationElemController implements angular.IComponentController { - private mmsInstanceVal: InstanceValueObject; - private mmsParentSection: InstanceSpecObject; + private mmsInstanceVal: InstanceValueObject + private mmsParentSection: InstanceSpecObject - private viewCtrl: ViewController; + private viewCtrl: ViewController - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] - public presentationElemLoading: boolean; - public instanceSpec: InstanceSpecObject; - public presentationElem: PresentationInstanceObject | ElementObject; - public peNumber: string; + public presentationElemLoading: boolean + public instanceSpec: InstanceSpecObject + public presentationElem: PresentationInstanceObject | ElementObject + public peNumber: string static $inject = [ '$scope', @@ -63,7 +63,7 @@ export class ViewPresentationElemController implements angular.IComponentControl 'TreeService', 'ExtensionService', 'EventService', - ]; + ] constructor( private $scope: angular.IScope, private $element: JQuery, @@ -80,51 +80,51 @@ export class ViewPresentationElemController implements angular.IComponentControl ) {} $onInit(): void { - this.presentationElemLoading = true; - this.eventSvc.$init(this); + this.presentationElemLoading = true + this.eventSvc.$init(this) if (!this.mmsInstanceVal || !this.mmsInstanceVal.instanceId) { - this.$element.html('Reference is null'); - return; + this.$element.html('Reference is null') + return } - let projectId: string = null; - let refId: string = null; - let commitId: string = null; + let projectId: string = null + let refId: string = null + let commitId: string = null if (this.viewCtrl) { - const viewVersion = this.viewCtrl.getElementOrigin(); - projectId = viewVersion.projectId; - refId = viewVersion.refId; - commitId = viewVersion.commitId; + const viewVersion = this.viewCtrl.getElementOrigin() + projectId = viewVersion.projectId + refId = viewVersion.refId + commitId = viewVersion.commitId } // Parse the element reference tree for the presentation element: - this.$element.addClass('isLoading'); + this.$element.addClass('isLoading') const reqOb = { elementId: this.mmsInstanceVal.instanceId, projectId: projectId, refId: refId, commitId: commitId, //includeRecentVersionElement: true, - }; + } this.elementSvc .getElement(reqOb, 1) .then( (instanceSpec) => { this.viewSvc.getViewElements(reqOb, 1).finally(() => { - this.instanceSpec = instanceSpec; - this.presentationElem = this.viewSvc.getPresentationInstanceObject(instanceSpec); - this.presentationElemLoading = false; + this.instanceSpec = instanceSpec + this.presentationElem = this.viewSvc.getPresentationInstanceObject(instanceSpec) + this.presentationElemLoading = false if (this.viewCtrl) { - this.viewCtrl.elementTranscluded(instanceSpec, this.presentationElem.type); + this.viewCtrl.elementTranscluded(instanceSpec, this.presentationElem.type) } this.$element.on('click', (e) => { - if (this.viewCtrl) this.viewCtrl.transcludeClicked(instanceSpec); - e.stopPropagation(); - }); - const tag = this.extensionSvc.getTagByType('present', this.presentationElem.type); + if (this.viewCtrl) this.viewCtrl.transcludeClicked(instanceSpec) + e.stopPropagation() + }) + const tag = this.extensionSvc.getTagByType('present', this.presentationElem.type) const newPe = $( '
    ' - ); + ) $(newPe).append( '<' + tag + @@ -132,35 +132,35 @@ export class ViewPresentationElemController implements angular.IComponentControl '' - ); - $(this.$element).append(newPe); - this.$compile(newPe)(this.$scope); - }); + ) + $(this.$element).append(newPe) + this.$compile(newPe)(this.$scope) + }) }, (reason) => { - this._error(reqOb, reason); + this._error(reqOb, reason) } ) .finally(() => { - this.$element.removeClass('isLoading'); - }); + this.$element.removeClass('isLoading') + }) } public getInstanceSpec = (): InstanceSpecObject => { - return this.instanceSpec; - }; + return this.instanceSpec + } public getInstanceVal = (): InstanceValueObject => { - return this.mmsInstanceVal; - }; + return this.mmsInstanceVal + } public getPresentationElement = (): ElementObject | PresentationInstanceObject => { - return this.presentationElem; - }; + return this.presentationElem + } public getParentSection = (): InstanceSpecObject => { - return this.mmsParentSection; - }; + return this.mmsParentSection + } private _error = (reqOb: ElementsRequest, reason: VePromiseReason): void => { if (reason.status === 500) { @@ -168,23 +168,23 @@ export class ViewPresentationElemController implements angular.IComponentControl 'View element reference error: ' + this.mmsInstanceVal.instanceId + ' invalid specification' - ); + ) } else { - this.$element.empty(); + this.$element.empty() const annotation = $( '' - ); - this.$element.append(annotation); + ) + this.$element.append(annotation) this.$compile(annotation)( Object.assign(this.$scope.$new(), { elementId: reqOb.elementId, recentElement: reason.recentVersionOfElement, type: 'presentation', }) - ); + ) } - }; + } } const ViewPeComponent: VeComponentOptions = { @@ -200,6 +200,6 @@ const ViewPeComponent: VeComponentOptions = { mmsParentSection: '<', }, controller: ViewPresentationElemController, -}; +} -veComponents.component(ViewPeComponent.selector, ViewPeComponent); +veComponents.component(ViewPeComponent.selector, ViewPeComponent) diff --git a/src/ve-components/presentations/view.component.ts b/src/ve-components/presentations/view.component.ts index 8bf880d12..ec72fdf56 100644 --- a/src/ve-components/presentations/view.component.ts +++ b/src/ve-components/presentations/view.component.ts @@ -1,13 +1,13 @@ -import { PresentationService } from '@ve-components/presentations/services/Presentation.service'; -import { TreeService } from '@ve-components/trees'; -import { RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { ElementService, UserService, ViewApi, ViewService } from '@ve-utils/mms-api-client'; -import { handleChange, onChangesCallback } from '@ve-utils/utils'; +import { PresentationService } from '@ve-components/presentations/services/Presentation.service' +import { TreeService } from '@ve-components/trees' +import { RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { ElementService, UserService, ViewApi, ViewService } from '@ve-utils/mms-api-client' +import { handleChange, onChangesCallback } from '@ve-utils/utils' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions } from '@ve-types/angular'; +import { VeComponentOptions } from '@ve-types/angular' import { ElementObject, ElementsRequest, @@ -18,7 +18,7 @@ import { ValueObject, ViewInstanceSpec, ViewObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' /** * @ngdoc directive @@ -68,15 +68,15 @@ import { export class ViewController implements angular.IComponentController { // private presentationElemCleanUpFncs: {(): any}[] = []; - private mmsElementId: string; - private mmsProjectId: string; - private mmsRefId: string; - private mmsCommitId: string; - private mmsLink: boolean; - public mmsViewApi: ViewApi; - private mmsNumber: number; - public noTitle: boolean; - public buttonId: string; + private mmsElementId: string + private mmsProjectId: string + private mmsRefId: string + private mmsCommitId: string + private mmsLink: boolean + public mmsViewApi: ViewApi + private mmsNumber: number + public noTitle: boolean + public buttonId: string static $inject = [ '$element', @@ -88,26 +88,26 @@ export class ViewController implements angular.IComponentController { 'EventService', 'TreeService', 'RootScopeService', - ]; - private showEdits: boolean; - private modified: string; - private modifier: UserObject; - private view: ViewObject; + ] + private showEdits: boolean + private modified: string + private modifier: UserObject + private view: ViewObject private reqOb: ElementsRequest = { elementId: '', projectId: '', refId: '', commitId: '', - }; - private processed: boolean; - private isHover: boolean; - private isSection: boolean; - private level: number; - private number: string = ''; - private showComments: boolean; - private showElements: boolean; - private showNumbering: boolean; - public subs: Rx.IDisposable[]; + } + private processed: boolean + private isHover: boolean + private isSection: boolean + private level: number + private number: string = '' + private showComments: boolean + private showElements: boolean + private showNumbering: boolean + public subs: Rx.IDisposable[] constructor( private $element: JQuery, @@ -122,59 +122,59 @@ export class ViewController implements angular.IComponentController { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) this.reqOb = { elementId: this.mmsElementId, projectId: this.mmsProjectId, refId: this.mmsRefId, commitId: this.mmsCommitId, - }; - this.processed = false; + } + this.processed = false if (this.mmsNumber) { - this.number = this.mmsNumber.toString(10); + this.number = this.mmsNumber.toString(10) } else if (this.treeSvc.branch2viewNumber[this.mmsElementId]) { - this.number = this.treeSvc.branch2viewNumber[this.mmsElementId]; + this.number = this.treeSvc.branch2viewNumber[this.mmsElementId] } - this.showNumbering = this.rootScopeSvc.veNumberingOn(); + this.showNumbering = this.rootScopeSvc.veNumberingOn() - this.isSection = false; - this.showElements = false; - this.showComments = false; - this.showEdits = false; + this.isSection = false + this.showElements = false + this.showComments = false + this.showEdits = false this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEELEMENTSON, (data) => { - this.toggleShowElements(data); + this.toggleShowElements(data) }), this.eventSvc.binding(this.rootScopeSvc.constants.VECOMMENTSON, (data) => { - this.toggleShowComments(data); + this.toggleShowComments(data) }), this.eventSvc.binding(this.rootScopeSvc.constants.VENUMBERINGON, (data) => { - this.showNumbering = data; + this.showNumbering = data }), this.eventSvc.binding(this.rootScopeSvc.constants.VEEDITMODE, (data) => { - this.toggleShowEdits(data); + this.toggleShowEdits(data) }) - ); + ) this.subs.push( this.eventSvc.binding(TreeService.events.UPDATED, (data) => { - if (!data) return; + if (!data) return if (this.treeSvc.branch2viewNumber[this.mmsElementId]) { - this.level = this.treeSvc.branch2viewNumber[this.mmsElementId].split('.').length; + this.level = this.treeSvc.branch2viewNumber[this.mmsElementId].split('.').length } }) - ); + ) - this._changeView(this.mmsElementId, ''); + this._changeView(this.mmsElementId, '') } $onChanges(onChangesObj: angular.IOnChangesObject): void { handleChange(onChangesObj, 'mmsNumber', (newVal: string) => { - this.number = newVal; - }); - handleChange(onChangesObj, 'mmsElementId', this._changeView, true); + this.number = newVal + }) + handleChange(onChangesObj, 'mmsElementId', this._changeView, true) } public isTranscludedElement = (elementName): boolean => { @@ -185,35 +185,35 @@ export class ViewController implements angular.IComponentController { elementName === 'MMS-TRANSCLUDE-IMG' || elementName === 'MMS-TRANSCLUDE-NAME' || elementName === 'MMS-TRANSCLUDE-VAL' - ); - }; + ) + } public isEditable = (): boolean => { - return this.showEdits; - }; + return this.showEdits + } public transcludeClicked = (elementOb: ElementObject): void => { - if (this.mmsViewApi && this.mmsViewApi.elementClicked && elementOb) this.mmsViewApi.elementClicked(elementOb); - }; + if (this.mmsViewApi && this.mmsViewApi.elementClicked && elementOb) this.mmsViewApi.elementClicked(elementOb) + } public elementTranscluded = (elem: ElementObject, type: string): void => { if (elem) { if (elem._modified > this.modified && type !== 'Comment') { - this.modified = elem._modified; + this.modified = elem._modified if (elem._modifier) { this.userSvc.getUserData(elem._modifier).then( (result) => { - this.modifier = result; + this.modifier = result }, () => { - this.modifier = { username: elem._modifier }; + this.modifier = { username: elem._modifier } } - ); + ) } } - if (this.mmsViewApi && this.mmsViewApi.elementTranscluded) this.mmsViewApi.elementTranscluded(elem, type); + if (this.mmsViewApi && this.mmsViewApi.elementTranscluded) this.mmsViewApi.elementTranscluded(elem, type) } - }; + } //INFO this was getWsAndVersion public getElementOrigin = (): RequestObject => { @@ -221,20 +221,20 @@ export class ViewController implements angular.IComponentController { projectId: this.mmsProjectId, refId: this.mmsRefId, commitId: this.mmsCommitId, - }; - }; + } + } public getView = (): ViewObject => { // this view gets set in the viewlink fnc - return this.view; - }; + return this.view + } public hoverIn = (): void => { - this.isHover = true; - }; + this.isHover = true + } public hoverOut = (): void => { - this.isHover = false; - }; + this.isHover = false + } // public setPeLineVisibility($event) { // window.setTimeout(() => { @@ -248,37 +248,37 @@ export class ViewController implements angular.IComponentController { // }; private _changeView: onChangesCallback = (newVal, oldVal) => { - if (!newVal || (newVal === oldVal && this.processed)) return; + if (!newVal || (newVal === oldVal && this.processed)) return - this.processed = true; - this.$element.addClass('isLoading'); + this.processed = true + this.$element.addClass('isLoading') this.reqOb = { elementId: this.mmsElementId, projectId: this.mmsProjectId, refId: this.mmsRefId, commitId: this.mmsCommitId, - }; + } this.elementSvc .getElement(this.reqOb, 1) .then( (data) => { //view accepts a section element if (data.type === 'InstanceSpecification') { - this.isSection = true; + this.isSection = true } - let operand: ValueObject[] = []; + let operand: ValueObject[] = [] if (data._contents && (data as ViewObject)._contents.operand) { - operand = (data as ViewObject)._contents.operand; + operand = (data as ViewObject)._contents.operand } if (data.specification && (data as ViewInstanceSpec).specification.operand) { - operand = (data.specification as ExpressionObject).operand; + operand = (data.specification as ExpressionObject).operand } - const dups = this.presentationSvc.checkForDuplicateInstances(operand); + const dups = this.presentationSvc.checkForDuplicateInstances(operand) if (dups.length > 0) { - this.growl.warning('There are duplicates in this view, duplicates ignored!'); + this.growl.warning('There are duplicates in this view, duplicates ignored!') } if (data._veNumber) { - this.level = data._veNumber.split('.').length; + this.level = data._veNumber.split('.').length } if ( //data._numElements && data._numElements > 5000 && @@ -287,40 +287,40 @@ export class ViewController implements angular.IComponentController { ) { //threshold where getting view elements in bulk takes too long and it's not latest //getting cached individual elements should be faster - this.view = data; - this.modified = data._modified; + this.view = data + this.modified = data._modified this.userSvc.getUserData(data._modifier).then( (result) => { - this.modifier = result; + this.modifier = result }, () => { - this.modifier = { username: data._modifier }; + this.modifier = { username: data._modifier } } - ); - return; + ) + return } this.viewSvc.getViewElements(this.reqOb, 1).finally(() => { - this.view = data; - this.modified = data._modified; + this.view = data + this.modified = data._modified this.userSvc.getUserData(data._modifier).then( (result) => { - this.modifier = result; + this.modifier = result }, () => { - this.modifier = { username: data._modifier }; + this.modifier = { username: data._modifier } } - ); - this.$element.removeClass('isLoading'); - }); + ) + this.$element.removeClass('isLoading') + }) }, (reason) => { - this.growl.error(`Getting View Error: ${reason.message}: ${this.mmsElementId}`); + this.growl.error(`Getting View Error: ${reason.message}: ${this.mmsElementId}`) } ) .finally(() => { - if (this.view) this.$element.removeClass('isLoading'); - }); - }; + if (this.view) this.$element.removeClass('isLoading') + }) + } /** * @name veComponents.component:mmsView#toggleShowElements @@ -328,16 +328,16 @@ export class ViewController implements angular.IComponentController { */ public toggleShowElements = (value?: boolean): void => { if (typeof value !== 'undefined') { - this.showElements = value; + this.showElements = value } else { - this.showElements = !this.showElements; + this.showElements = !this.showElements } if (this.showElements) { - this.$element.addClass('outline'); + this.$element.addClass('outline') } else if (this.$element.hasClass('outline')) { - this.$element.removeClass('outline'); + this.$element.removeClass('outline') } - }; + } /** * @name veComponents.component:mmsView#toggleShowComments @@ -345,16 +345,16 @@ export class ViewController implements angular.IComponentController { */ public toggleShowComments = (value?: boolean): void => { if (typeof value !== 'undefined') { - this.showComments = value; + this.showComments = value } else { - this.showComments = !this.showComments; + this.showComments = !this.showComments } if (this.showComments) { - this.$element.addClass('reviewing'); + this.$element.addClass('reviewing') } else if (this.$element.hasClass('reviewing')) { - this.$element.removeClass('reviewing'); + this.$element.removeClass('reviewing') } - }; + } /** * @name veComponents.component:mmsView#toggleShowEdits @@ -362,21 +362,21 @@ export class ViewController implements angular.IComponentController { */ public toggleShowEdits = (value?: boolean): void => { if (typeof value !== 'undefined') { - this.showEdits = value; + this.showEdits = value } else { - this.showEdits = !this.showEdits; + this.showEdits = !this.showEdits } if (this.showEdits) { - this.$element.addClass('editing'); + this.$element.addClass('editing') } else if (this.$element.hasClass('editing')) { - this.$element.removeClass('editing'); + this.$element.removeClass('editing') } // Call the callback functions to clean up frames, show edits, and // re-open frames when needed: // for (let i = 0; i < this.presentationElemCleanUpFncs.length; i++) { // this.presentationElemCleanUpFncs[i](); // } - }; + } } export const ViewComponent: VeComponentOptions = { @@ -431,6 +431,6 @@ export const ViewComponent: VeComponentOptions = { buttonId: '<', }, controller: ViewController, -}; +} -veComponents.component(ViewComponent.selector, ViewComponent); +veComponents.component(ViewComponent.selector, ViewComponent) diff --git a/src/ve-components/services/Component.service.ts b/src/ve-components/services/Component.service.ts index 2a28c5dc5..f821cfb0d 100644 --- a/src/ve-components/services/Component.service.ts +++ b/src/ve-components/services/Component.service.ts @@ -1,10 +1,10 @@ -import { ViewController } from '@ve-components/presentations'; -import { ITransclusion } from '@ve-components/transclusions'; +import { ViewController } from '@ve-components/presentations' +import { ITransclusion } from '@ve-components/transclusions' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeQService } from '@ve-types/angular'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeQService } from '@ve-types/angular' +import { VeModalService } from '@ve-types/view-editor' /** * @internal @@ -18,7 +18,7 @@ import { VeModalService } from '@ve-types/view-editor'; * */ export class ComponentService { - static $inject = ['$q', '$timeout', '$compile', '$uibModal']; + static $inject = ['$q', '$timeout', '$compile', '$uibModal'] constructor( private $q: VeQService, @@ -28,40 +28,40 @@ export class ComponentService { ) {} public hasCircularReference = (ctrl: ITransclusion, curId: string, curType: string): boolean => { - let curscope = ctrl.$scope; + let curscope = ctrl.$scope while (curscope.$parent) { - const parent = curscope.$parent; + const parent = curscope.$parent if (curscope.$parent.$ctrl) { - if (parent.$ctrl.mmsElementId === curId && parent.$ctrl.cfType === curType) return true; + if (parent.$ctrl.mmsElementId === curId && parent.$ctrl.cfType === curType) return true } - curscope = parent; + curscope = parent } - return false; - }; + return false + } // var ENUM_ID = '_9_0_62a020a_1105704885400_895774_7947'; // var ENUM_LITERAL = '_9_0_62a020a_1105704885423_380971_7955'; public isDirectChildOfPresentationElementFunc(element: JQuery, mmsViewCtrl: ViewController): boolean { - let parent = element[0].parentElement; + let parent = element[0].parentElement while (parent && parent.nodeName !== 'MMS-VIEW-PRESENTATION-ELEM' && parent.nodeName !== 'MMS-VIEW') { if (mmsViewCtrl.isTranscludedElement(parent.nodeName)) { - return false; + return false } if ( parent.nodeName === 'MMS-VIEW-TABLE' || parent.nodeName === 'MMS-VIEW-LIST' || parent.nodeName === 'MMS-VIEW-SECTION' ) - return false; - parent = parent.parentElement; + return false + parent = parent.parentElement } - return parent && parent.nodeName !== 'MMS-VIEW'; + return parent && parent.nodeName !== 'MMS-VIEW' } public hasHtml = (s: string): boolean => { - return s.indexOf('

    ') !== -1; - }; + return s.indexOf('

    ') !== -1 + } } -veComponents.service('ComponentService', ComponentService); +veComponents.service('ComponentService', ComponentService) diff --git a/src/ve-components/services/Extension.service.ts b/src/ve-components/services/Extension.service.ts index 02601eb23..b276a2cdc 100644 --- a/src/ve-components/services/Extension.service.ts +++ b/src/ve-components/services/Extension.service.ts @@ -1,29 +1,29 @@ -import angular from 'angular'; -import _ from 'lodash'; +import angular from 'angular' +import _ from 'lodash' -import { IButtonBarButton } from '@ve-core/button-bar'; -import { IToolBarButton } from '@ve-core/toolbar'; +import { IButtonBarButton } from '@ve-core/button-bar' +import { IToolBarButton } from '@ve-core/toolbar' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' export interface VeExperimentDescriptor { - id: string; - path?: string; - config?: string; - name?: string; - toolButton?: IToolBarButton; - toolDynamicButton?: IToolBarButton[]; - barButtons?: IButtonBarButton[]; + id: string + path?: string + config?: string + name?: string + toolButton?: IToolBarButton + toolDynamicButton?: IToolBarButton[] + barButtons?: IButtonBarButton[] } export interface VeExperimentConfig { - [extensionType: string]: VeExperimentDescriptor[]; + [extensionType: string]: VeExperimentDescriptor[] } export class ExtensionService { - extensionTags: string[] = []; - extensionData: unknown[] = []; - allowedExtensions: string[] = ['present', 'transclude', 'spec', 'insert', 'tree-of']; + extensionTags: string[] = [] + extensionData: unknown[] = [] + allowedExtensions: string[] = ['present', 'transclude', 'spec', 'insert', 'tree-of'] public AnnotationType = { transcludeName: 1, @@ -33,21 +33,21 @@ export class ExtensionService { mmsViewLink: 5, presentationElement: 6, transcludeView: 7, - }; + } - static $inject = []; + static $inject = [] constructor() { - ( + ;( angular.module('ve-components')['_invokeQueue'] as { - 1: string; - 2: string[]; + 1: string + 2: string[] }[] ).forEach((value) => { if (value[1] === 'component') { - this.extensionTags.push(_.kebabCase(value[2][0])); - this.extensionData.push(value[2]); + this.extensionTags.push(_.kebabCase(value[2][0])) + this.extensionData.push(value[2]) } - }); + }) // for (const tag of this.extensionTags) { // @@ -55,26 +55,26 @@ export class ExtensionService { } public getTagByType = (extPrefix: string, type: string): string => { - extPrefix = _.kebabCase(extPrefix); + extPrefix = _.kebabCase(extPrefix) if (!this.allowedExtensions.includes(extPrefix)) { // this.growl.error('Unknown Extension Prefix: ' + extPrefix) - return 'extension-error'; + return 'extension-error' } - if (type == 'InstanceSpecification') type = 'section'; - if (type == 'ImageT') type = 'figure'; - const tag = _.kebabCase(type.startsWith(extPrefix) ? type : extPrefix + _.capitalize(type)); + if (type == 'InstanceSpecification') type = 'section' + if (type == 'ImageT') type = 'figure' + const tag = _.kebabCase(type.startsWith(extPrefix) ? type : extPrefix + _.capitalize(type)) if (!this.extensionTags.includes(tag)) { // this.growl.error('Unknown Extension type: ' + type) - return 'extension-error'; + return 'extension-error' } - return tag; - }; + return tag + } public getExtensions(extPrefix: string, exclude?: string[]): string[] { return this.extensionTags.filter((value) => { - return value.startsWith(_.kebabCase(extPrefix)) && (exclude ? !exclude.includes(value) : true); - }); + return value.startsWith(_.kebabCase(extPrefix)) && (exclude ? !exclude.includes(value) : true) + }) } } -veComponents.service('ExtensionService', ExtensionService); +veComponents.service('ExtensionService', ExtensionService) diff --git a/src/ve-components/services/index.ts b/src/ve-components/services/index.ts index 9433c7d95..d7e4d2d87 100644 --- a/src/ve-components/services/index.ts +++ b/src/ve-components/services/index.ts @@ -1,5 +1,5 @@ -import './Component.service'; -import './Extension.service'; +import './Component.service' +import './Extension.service' -export * from './Extension.service'; -export * from './Component.service'; +export * from './Extension.service' +export * from './Component.service' diff --git a/src/ve-components/spec-tools/components/spec-editor.component.ts b/src/ve-components/spec-tools/components/spec-editor.component.ts index ccf72ae3b..f5df95f14 100644 --- a/src/ve-components/spec-tools/components/spec-editor.component.ts +++ b/src/ve-components/spec-tools/components/spec-editor.component.ts @@ -1,11 +1,11 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { ComponentService } from '@ve-components/services'; -import { SpecService, SpecTool, ISpecTool } from '@ve-components/spec-tools'; -import { EditorService } from '@ve-core/editor'; -import { ToolbarApi, ToolbarService } from '@ve-core/toolbar'; -import { ApplicationService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; +import { ComponentService } from '@ve-components/services' +import { SpecService, SpecTool, ISpecTool } from '@ve-components/spec-tools' +import { EditorService } from '@ve-core/editor' +import { ToolbarApi, ToolbarService } from '@ve-core/toolbar' +import { ApplicationService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' import { URLService, ElementService, @@ -14,12 +14,12 @@ import { ProjectService, ApiService, ValueService, -} from '@ve-utils/mms-api-client'; +} from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromiseReason, VeQService } from '@ve-types/angular'; -import { ElementObject, ElementsResponse } from '@ve-types/mms'; +import { VeComponentOptions, VePromiseReason, VeQService } from '@ve-types/angular' +import { ElementObject, ElementsResponse } from '@ve-types/mms' /** * @ngdoc directive @@ -89,9 +89,9 @@ import { ElementObject, ElementsResponse } from '@ve-types/mms'; */ class SpecEditorController extends SpecTool implements ISpecTool { - static $inject = [...SpecTool.$inject, 'EditService', 'ValueService', 'EditorService']; + static $inject = [...SpecTool.$inject, 'EditService', 'ValueService', 'EditorService'] - private isValue: boolean; + private isValue: boolean constructor( $q: VeQService, @@ -129,48 +129,48 @@ class SpecEditorController extends SpecTool implements ISpecTool { eventSvc, specSvc, toolbarSvc - ); - this.specType = _.kebabCase(SpecEditorComponent.selector); - this.specTitle = 'Edit Element'; + ) + this.specType = _.kebabCase(SpecEditorComponent.selector) + this.specTitle = 'Edit Element' } configToolbar = (api: ToolbarApi): void => { if (this.autosaveSvc.openEdits() > 0) { //Tell toolbar to show an open edit if there are open edits - api.setIcon('spec-editor', 'fa-edit-asterisk'); - api.setPermission('spec-editor.saveall', true); + api.setIcon('spec-editor', 'fa-edit-asterisk') + api.setPermission('spec-editor.saveall', true) } - }; + } initCallback = (): void => { - this.specSvc.setEditing(true); - const e = this.specSvc.getElement(); + this.specSvc.setEditing(true) + const e = this.specSvc.getElement() this.editorSvc.openEdit(e).then( (editOb) => { - this.specSvc.tracker.etrackerSelected = editOb.key; - this.specSvc.toggleSave(this.toolbarId); + this.specSvc.tracker.etrackerSelected = editOb.key + this.specSvc.toggleSave(this.toolbarId) this.elementSvc.isCacheOutdated(editOb.element).then( (data) => { - const server = data.server ? data.server._modified : new Date(); - const cache = data.cache ? data.cache._modified : new Date(); + const server = data.server ? data.server._modified : new Date() + const cache = data.cache ? data.cache._modified : new Date() if (data.status && server > cache) this.growl.error( 'This element has been updated on the server. Please refresh the page to get the latest version.' - ); + ) }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); - this.edit = editOb; - this.specSvc.setEdits(editOb); - this.isValue = this.valueSvc.isValue(editOb.element); + ) + this.edit = editOb + this.specSvc.setEdits(editOb) + this.isValue = this.valueSvc.isValue(editOb.element) }, (reason: VePromiseReason>) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); - }; + ) + } } const SpecEditorComponent: VeComponentOptions = { selector: 'specEditor', @@ -220,6 +220,6 @@ const SpecEditorComponent: VeComponentOptions = { mmsDisplayOldSpec: ' { - if (!this.projectId || !this.refId) return; + if (!this.projectId || !this.refId) return const reqOb: ElementsRequest = { elementId: this.element.id, projectId: this.projectId, refId: this.refId, - }; + } if (this.keepCommitSelected) { - this.keepCommitSelected = false; - return; + this.keepCommitSelected = false + return } - this.gettingHistory = true; + this.gettingHistory = true this.elementSvc .getElementHistory(reqOb, 2, true) .then( (data) => { - this.historyVer = 'latest'; - this.compareCommit.history = data; - this.compareCommit.commitSelected = this.compareCommit.history[0]; - this.baseCommit.history = data; + this.historyVer = 'latest' + this.compareCommit.history = data + this.compareCommit.commitSelected = this.compareCommit.history[0] + this.baseCommit.history = data if (data.length > 1) { - this.baseCommit.commitSelected = this.compareCommit.history[1]; + this.baseCommit.commitSelected = this.compareCommit.history[1] } else if (data.length > 0) { - this.baseCommit.commitSelected = this.compareCommit.history[0]; + this.baseCommit.commitSelected = this.compareCommit.history[0] } else { - this.baseCommit.commitSelected = '--- none ---'; + this.baseCommit.commitSelected = '--- none ---' } - void this.getRefs(); + void this.getRefs() }, (reason) => { - this.growl.error(`Unable to get Element History - ${reason.message}`); + this.growl.error(`Unable to get Element History - ${reason.message}`) } ) .finally(() => { - this.gettingHistory = false; - this.disableRevert = this._isSame(); - }); - }; + this.gettingHistory = false + this.disableRevert = this._isSame() + }) + } // Get ref list for project and details on getRefs = (): VePromise => { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() this.projectSvc.getRefs(this.projectId).then( (data) => { - this.refList = data; + this.refList = data this.compareCommit.ref = this.refList.filter((ref) => { - return ref.id === this.refId; - })[0]; - this.baseCommit.ref = this.compareCommit.ref; - deferred.resolve(); + return ref.id === this.refId + })[0] + this.baseCommit.ref = this.compareCommit.ref + deferred.resolve() }, (reason) => { - this.growl.error(`Unable to get Refs - ${reason.message}`); - deferred.reject(); + this.growl.error(`Unable to get Refs - ${reason.message}`) + deferred.reject() } - ); - return deferred.promise; - }; + ) + return deferred.promise + } commitClicked = (version: CommitObject): void => { - this.compareCommit.commitSelected = version; - this.historyVer = this.compareCommit.commitSelected.id; - this.compareCommit.isOpen = !this.compareCommit.isOpen; + this.compareCommit.commitSelected = version + this.historyVer = this.compareCommit.commitSelected.id + this.compareCommit.isOpen = !this.compareCommit.isOpen const data = { elementId: this.element.id, projectId: this.element._projectId, refId: this.element._refId, commitId: this.historyVer, - }; - this.keepCommitSelected = true; - this.eventSvc.$broadcast('element.selected', data); - }; + } + this.keepCommitSelected = true + this.eventSvc.$broadcast('element.selected', data) + } getElementHistoryByRef = (ref?: RefObject): void => { if (ref) { - this.disableRevert = false; + this.disableRevert = false // scope.gettingCompareHistory = true; - this.baseCommit.ref = ref; + this.baseCommit.ref = ref const reqOb = { elementId: this.element.id, projectId: this.projectId, refId: ref.id, - }; + } this.elementSvc .getElementHistory(reqOb, 2) .then( (data) => { - this.baseCommit.history = data; + this.baseCommit.history = data if (data.length > 0) { - this.baseCommit.commitSelected = this.baseCommit.history[0]; + this.baseCommit.commitSelected = this.baseCommit.history[0] } - this.disableRevert = this._isSame(); + this.disableRevert = this._isSame() }, (error) => { - this.baseCommit.history = []; - this.baseCommit.commitSelected = ''; - this.disableRevert = true; + this.baseCommit.history = [] + this.baseCommit.commitSelected = '' + this.disableRevert = true } ) .finally(() => { // scope.gettingCompareHistory = false; - this.baseCommit.refIsOpen = !this.baseCommit.refIsOpen; - }); + this.baseCommit.refIsOpen = !this.baseCommit.refIsOpen + }) } - }; + } baseCommitClicked = (version: CommitObject): void => { - this.baseCommit.commitSelected = version; - this.baseCommit.isOpen = !this.baseCommit.isOpen; - }; + this.baseCommit.commitSelected = version + this.baseCommit.isOpen = !this.baseCommit.isOpen + } //TODO // check if commit ids are the same - display to user that they are comparing same or disable the commit that matches @@ -225,27 +225,27 @@ class SpecHistoryController extends SpecTool implements ISpecTool { elementId: this.element.id, projectId: this.projectId, refId: this.refId, - }; + } const compareData: CompareData = { compareCommit: this.compareCommit, baseCommit: this.baseCommit, element: this.element, - }; - this.diffMergeSvc.revertAction(reqOb, compareData, this.$element); - } else this.growl.warning('Nothing to revert!'); - }; + } + this.diffMergeSvc.revertAction(reqOb, compareData, this.$element) + } else this.growl.warning('Nothing to revert!') + } private _isSame = (): boolean => { const compareId = typeof this.compareCommit.commitSelected === 'string' ? this.compareCommit.commitSelected - : this.compareCommit.commitSelected.id; + : this.compareCommit.commitSelected.id const baseId = typeof this.baseCommit.commitSelected === 'string' ? this.baseCommit.commitSelected - : this.baseCommit.commitSelected.id; - return baseId == compareId; - }; + : this.baseCommit.commitSelected.id + return baseId == compareId + } } const SpecHistoryComponent: VeComponentOptions = { @@ -392,6 +392,6 @@ const SpecHistoryComponent: VeComponentOptions = { `, controller: SpecHistoryController, -}; +} -veComponents.component(SpecHistoryComponent.selector, SpecHistoryComponent); +veComponents.component(SpecHistoryComponent.selector, SpecHistoryComponent) diff --git a/src/ve-components/spec-tools/components/spec-inspector.component.ts b/src/ve-components/spec-tools/components/spec-inspector.component.ts index 35e464867..1714007e5 100644 --- a/src/ve-components/spec-tools/components/spec-inspector.component.ts +++ b/src/ve-components/spec-tools/components/spec-inspector.component.ts @@ -1,10 +1,10 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { ComponentService } from '@ve-components/services'; -import { SpecService, ISpecTool, SpecTool } from '@ve-components/spec-tools'; -import { ToolbarService } from '@ve-core/toolbar'; -import { ApplicationService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { ComponentService } from '@ve-components/services' +import { SpecService, ISpecTool, SpecTool } from '@ve-components/spec-tools' +import { ToolbarService } from '@ve-core/toolbar' +import { ApplicationService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' import { ProjectService, URLService, @@ -12,11 +12,11 @@ import { PermissionsService, ElementService, ApiService, -} from '@ve-utils/mms-api-client'; +} from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VeQService } from '@ve-types/angular' /** * @ngdoc directive @@ -87,7 +87,7 @@ import { VeComponentOptions, VeQService } from '@ve-types/angular'; */ class SpecInspectorController extends SpecTool implements ISpecTool { - static $inject = SpecTool.$inject; + static $inject = SpecTool.$inject constructor( $q: VeQService, @@ -122,16 +122,16 @@ class SpecInspectorController extends SpecTool implements ISpecTool { eventSvc, specSvc, toolbarSvc - ); + ) - this.specType = _.kebabCase(SpecInspectorComponent.selector); - this.specTitle = 'Preview Element'; + this.specType = _.kebabCase(SpecInspectorComponent.selector) + this.specTitle = 'Preview Element' } protected initCallback = (): void => { - this.specSvc.setEditing(false); - this.specSvc.toggleSave(this.toolbarId); - }; + this.specSvc.setEditing(false) + this.specSvc.toggleSave(this.toolbarId) + } } const SpecInspectorComponent: VeComponentOptions = { @@ -262,6 +262,6 @@ const SpecInspectorComponent: VeComponentOptions = { mmsDisplayOldSpec: ' { - this.refs = refs; + this.refs = refs }, (reason) => { - this.growl.error('Error getting refs: ' + reason.message); + this.growl.error('Error getting refs: ' + reason.message) } ) .finally(() => { - this.isLoading = false; - }); + this.isLoading = false + }) } //Callback function for document change public initCallback = (): void => { - if (this.document) this.docName = this.document.name; + if (this.document) this.docName = this.document.name if (!this.apiSvc.isDocument(this.element)) { - this.isDoc = false; - return; + this.isDoc = false + return } else { - this.isDoc = true; + this.isDoc = true } this.docEditable = this.specApi.refType != 'Tag' && - this.permissionsSvc.hasBranchEditPermission(this.specApi.projectId, this.specApi.refId); - }; + this.permissionsSvc.hasBranchEditPermission(this.specApi.projectId, this.specApi.refId) + } public docMergeAction = (srcRef: RefObject): void => { - this.srcRefOb = srcRef; + this.srcRefOb = srcRef const instance = this.$uibModal.open({ resolve: { getDocName: (): string => { - if (this.document) return this.document.name; - return '(Not Found)'; + if (this.document) return this.document.name + return '(Not Found)' }, getSrcRefOb: (): RefObject => { - return this.srcRefOb; + return this.srcRefOb }, }, component: 'mergeConfirmModal', - }); + }) instance.result.then( () => { // TODO: do anything here? }, () => { - this.growl.error('Unable to Merge'); + this.growl.error('Unable to Merge') } - ); - }; + ) + } } const SpecRefListComponent: VeComponentOptions = { @@ -239,6 +239,6 @@ const SpecRefListComponent: VeComponentOptions = { mmsRefs: '<', }, controller: SpecRefListController, -}; +} -veComponents.component(SpecRefListComponent.selector, SpecRefListComponent); +veComponents.component(SpecRefListComponent.selector, SpecRefListComponent) diff --git a/src/ve-components/spec-tools/components/spec-reorder.component.ts b/src/ve-components/spec-tools/components/spec-reorder.component.ts index 3b9c32df5..3599c82c8 100644 --- a/src/ve-components/spec-tools/components/spec-reorder.component.ts +++ b/src/ve-components/spec-tools/components/spec-reorder.component.ts @@ -1,11 +1,11 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { ComponentService } from '@ve-components/services'; -import { SpecService, SpecTool, ISpecTool } from '@ve-components/spec-tools'; -import { veCoreEvents } from '@ve-core/events'; -import { ToolbarService } from '@ve-core/toolbar'; -import { ApplicationService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { ComponentService } from '@ve-components/services' +import { SpecService, SpecTool, ISpecTool } from '@ve-components/spec-tools' +import { veCoreEvents } from '@ve-core/events' +import { ToolbarService } from '@ve-core/toolbar' +import { ApplicationService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' import { PermissionsService, URLService, @@ -13,11 +13,11 @@ import { ViewService, ProjectService, ApiService, -} from '@ve-utils/mms-api-client'; +} from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VePromisesResponse, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VePromise, VePromisesResponse, VeQService } from '@ve-types/angular' import { ElementObject, ElementsRequest, @@ -26,7 +26,7 @@ import { PresentationReference, ViewInstanceSpec, ViewObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' /** * @ngdoc directive @@ -43,14 +43,14 @@ import { * @param {string=latest} mmsCommitId Commit ID, default is latest */ class SpecReorderController extends SpecTool implements ISpecTool { - private treeOptions: object; + private treeOptions: object - private elementReferenceTree: PresentationReference[] = []; - private originalElementReferenceTree: PresentationReference[] = []; - public view: ViewObject | ViewInstanceSpec; - reorderable: boolean; + private elementReferenceTree: PresentationReference[] = [] + private originalElementReferenceTree: PresentationReference[] = [] + public view: ViewObject | ViewInstanceSpec + reorderable: boolean - viewSaving: boolean; + viewSaving: boolean constructor( $q: VeQService, @@ -85,92 +85,92 @@ class SpecReorderController extends SpecTool implements ISpecTool { eventSvc, specSvc, toolbarSvc - ); - this.specType = _.kebabCase(SpecReorderComponent.selector); - this.specTitle = 'Reorder Spec'; + ) + this.specType = _.kebabCase(SpecReorderComponent.selector) + this.specTitle = 'Reorder Spec' } $onInit(): void { - super.$onInit(); + super.$onInit() this.treeOptions = { accept: (sourceNodeScope: SpecTool, destNodeScope: SpecTool, destIndex: number): boolean => { - if (sourceNodeScope.element.isOpaque) return false; - if (destNodeScope.$element.hasClass('root')) return true; - return !!this.viewSvc.isSection(destNodeScope.element as ViewInstanceSpec); + if (sourceNodeScope.element.isOpaque) return false + if (destNodeScope.$element.hasClass('root')) return true + return !!this.viewSvc.isSection(destNodeScope.element as ViewInstanceSpec) }, - }; + } this.subs.push( this.eventSvc.$on('spec-reorder.save', () => { if (this.viewSaving) { - this.growl.info('Please Wait...'); - return; + this.growl.info('Please Wait...') + return } - this.viewSaving = true; + this.viewSaving = true this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-reorder.save'); + api.toggleButtonSpinner('spec-reorder.save') }, (reason) => { - this.growl.error(ToolbarService.error(reason)); + this.growl.error(ToolbarService.error(reason)) } - ); + ) this.treeSave().then( (elements) => { - this.viewSaving = false; + this.viewSaving = false //this.refresh() //TODO reset orig - this.growl.success('Save Successful'); + this.growl.success('Save Successful') this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-reorder.save'); + api.toggleButtonSpinner('spec-reorder.save') }, (reason) => { - this.growl.error(ToolbarService.error(reason)); + this.growl.error(ToolbarService.error(reason)) } - ); - const saved = elements.filter((val) => val.id === this.view.id); + ) + const saved = elements.filter((val) => val.id === this.view.id) if (saved.length > 0) { - this.eventSvc.$broadcast('element.updated', { element: saved[0] }); + this.eventSvc.$broadcast('element.updated', { element: saved[0] }) } - this.eventSvc.$broadcast('spec-reorder.saved', this.view.id); + this.eventSvc.$broadcast('spec-reorder.saved', this.view.id) this.eventSvc.resolve(this.toolbarId, { id: 'spec-inspector', - }); + }) }, (response) => { - this.refresh(); - this.viewSaving = false; - const reason = response.data.failedRequests[0]; - this.growl.error(reason.message); + this.refresh() + this.viewSaving = false + const reason = response.data.failedRequests[0] + this.growl.error(reason.message) this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-reorder.save'); + api.toggleButtonSpinner('spec-reorder.save') }, (reason) => { - this.growl.error(ToolbarService.error(reason)); + this.growl.error(ToolbarService.error(reason)) } - ); + ) } - ); + ) }) - ); + ) this.subs.push( this.eventSvc.$on('spec-reorder.cancel', () => { - this.revert(); + this.revert() }) - ); + ) } initCallback = (): void => { if (this.apiSvc.isView(this.specSvc.getView()) || this.viewSvc.isSection(this.specSvc.getView())) { - this.view = this.specSvc.getView(); - this.reorderable = true; - this.refresh(); + this.view = this.specSvc.getView() + this.reorderable = true + this.refresh() } - }; + } treeSave(): VePromise> { - const elementObsToUpdate: ElementObject[] = []; + const elementObsToUpdate: ElementObject[] = [] const updateSectionElementOrder = (elementReference: PresentationReference): void => { const sectionEdit: ViewInstanceSpec = { id: elementReference.instanceId, @@ -179,33 +179,33 @@ class SpecReorderController extends SpecTool implements ISpecTool { _refId: elementReference.instanceSpecification._refId, type: elementReference.instanceSpecification.type, specification: _.cloneDeep(elementReference.instanceSpecification.specification), - }; + } //sectionEdit.specialization = _.cloneDeep(elementReference.instanceSpecification.specialization); - const operand: InstanceValueObject[] = (sectionEdit.specification.operand = []); + const operand: InstanceValueObject[] = (sectionEdit.specification.operand = []) if (!elementReference.instanceSpecification.specification) { - this.growl.error('Malformed Reference Tree; Aborting'); + this.growl.error('Malformed Reference Tree; Aborting') } const origOperand = ( elementReference.instanceSpecification.specification as ExpressionObject - ).operand; + ).operand elementReference.sectionElements.forEach((sectionElement, index) => { - operand.push(sectionElement.instanceVal); - if (sectionElement.sectionElements.length > 0) updateSectionElementOrder(sectionElement); - }); + operand.push(sectionElement.instanceVal) + if (sectionElement.sectionElements.length > 0) updateSectionElementOrder(sectionElement) + }) if (!_.isEqual(operand, origOperand)) { - elementObsToUpdate.push(sectionEdit); + elementObsToUpdate.push(sectionEdit) } - }; + } - const deferred = this.$q.defer(); + const deferred = this.$q.defer() if (this.elementReferenceTree.length === 0) { deferred.reject({ type: 'error', message: 'View specs were not initialized properly or is empty.', - }); - return deferred.promise; + }) + return deferred.promise } const viewEdit: ViewInstanceSpec | ViewObject = { id: this.view.id, @@ -213,33 +213,33 @@ class SpecReorderController extends SpecTool implements ISpecTool { _projectId: this.view._projectId, _refId: this.view._refId, type: this.view.type, - }; + } if (this.view._contents) { - viewEdit._contents = _.cloneDeep(this.view._contents); + viewEdit._contents = _.cloneDeep(this.view._contents) } if (this.view.specification) { - viewEdit.specification = _.cloneDeep((this.view as ViewInstanceSpec).specification); + viewEdit.specification = _.cloneDeep((this.view as ViewInstanceSpec).specification) } - const specs: ExpressionObject = viewEdit._contents || viewEdit.specification; - const origSpecs: ExpressionObject = this.view._contents || this.view.specification; + const specs: ExpressionObject = viewEdit._contents || viewEdit.specification + const origSpecs: ExpressionObject = this.view._contents || this.view.specification // Update the View edit object on Save if (specs.operand) { - specs.operand = []; + specs.operand = [] this.elementReferenceTree.forEach((elementRef) => { - specs.operand.push(elementRef.instanceVal); - }); + specs.operand.push(elementRef.instanceVal) + }) if (specs && !_.isEqual(specs.operand, origSpecs.operand)) { - elementObsToUpdate.push(viewEdit); + elementObsToUpdate.push(viewEdit) } } // Recurse this.elementReferenceTree.forEach((elementReference) => { if (elementReference.sectionElements && elementReference.sectionElements.length > 0) { - updateSectionElementOrder(elementReference); + updateSectionElementOrder(elementReference) } - }); + }) - return this.elementSvc.updateElements(elementObsToUpdate, false); + return this.elementSvc.updateElements(elementObsToUpdate, false) } revert = (): void => { @@ -250,29 +250,29 @@ class SpecReorderController extends SpecTool implements ISpecTool { key === 'presentationElement' || key === 'instanceVal' ) - return value; - return undefined; - }) as PresentationReference[]; - }; + return value + return undefined + }) as PresentationReference[] + } refresh = () => { - let contents: ExpressionObject = null; + let contents: ExpressionObject = null if (this.view._contents) { - contents = (this.view as ViewObject)._contents; + contents = (this.view as ViewObject)._contents } if (this.view.specification) { - contents = (this.view as ViewInstanceSpec).specification; + contents = (this.view as ViewInstanceSpec).specification } const reqOb: ElementsRequest = { elementId: this.specSvc.specApi.elementId, projectId: this.specSvc.specApi.projectId, refId: this.specSvc.specApi.refId, commitId: this.specSvc.specApi.commitId, - }; + } if (contents) { this.viewSvc.getElementReferenceTree(reqOb, contents).then( (elementReferenceTree) => { - this.elementReferenceTree = elementReferenceTree; + this.elementReferenceTree = elementReferenceTree this.originalElementReferenceTree = _.cloneDeepWith(elementReferenceTree, (value: unknown, key) => { if ( key === 'instanceId' || @@ -280,20 +280,20 @@ class SpecReorderController extends SpecTool implements ISpecTool { key === 'presentationElement' || key === 'instanceVal' ) - return value; - return undefined; - }) as PresentationReference[]; + return value + return undefined + }) as PresentationReference[] }, (reason) => { - this.elementReferenceTree = []; - this.originalElementReferenceTree = []; + this.elementReferenceTree = [] + this.originalElementReferenceTree = [] } - ); + ) } else { - this.elementReferenceTree = []; - this.originalElementReferenceTree = []; + this.elementReferenceTree = [] + this.originalElementReferenceTree = [] } - }; + } } const SpecReorderComponent: VeComponentOptions = { @@ -331,6 +331,6 @@ const SpecReorderComponent: VeComponentOptions = { mmsCommitId: '@', }, controller: SpecReorderController, -}; +} -veComponents.component(SpecReorderComponent.selector, SpecReorderComponent); +veComponents.component(SpecReorderComponent.selector, SpecReorderComponent) diff --git a/src/ve-components/spec-tools/index.ts b/src/ve-components/spec-tools/index.ts index 2f3cd216e..d763d1d28 100644 --- a/src/ve-components/spec-tools/index.ts +++ b/src/ve-components/spec-tools/index.ts @@ -1,15 +1,15 @@ //Exports -export * from './services/Spec.service'; +export * from './services/Spec.service' -export * from './spec-tool.controller'; +export * from './spec-tool.controller' //Services -import './services/Spec.service'; +import './services/Spec.service' //Core Components -import './mms-tools.component'; +import './mms-tools.component' //Default Extensions -import './components/spec-inspector.component'; -import './components/spec-editor.component'; -import './components/spec-reorder.component'; -import './components/spec-history.component'; -import './components/spec-ref-list.component'; +import './components/spec-inspector.component' +import './components/spec-editor.component' +import './components/spec-reorder.component' +import './components/spec-history.component' +import './components/spec-ref-list.component' diff --git a/src/ve-components/spec-tools/mms-tools.component.ts b/src/ve-components/spec-tools/mms-tools.component.ts index fd3bed5f2..b02438098 100644 --- a/src/ve-components/spec-tools/mms-tools.component.ts +++ b/src/ve-components/spec-tools/mms-tools.component.ts @@ -1,21 +1,21 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { EditorService } from '@ve-core/editor'; -import { EditDialogService } from '@ve-core/editor/services/EditDialog.service'; -import { veCoreEvents } from '@ve-core/events'; -import { IToolBarButton, ToolbarService } from '@ve-core/toolbar'; -import { RootScopeService } from '@ve-utils/application'; -import { EditObject, EditService, EventService } from '@ve-utils/core'; -import { ElementService, ProjectService, PermissionsService } from '@ve-utils/mms-api-client'; +import { ComponentService, ExtensionService } from '@ve-components/services' +import { EditorService } from '@ve-core/editor' +import { EditDialogService } from '@ve-core/editor/services/EditDialog.service' +import { veCoreEvents } from '@ve-core/events' +import { IToolBarButton, ToolbarService } from '@ve-core/toolbar' +import { RootScopeService } from '@ve-utils/application' +import { EditObject, EditService, EventService } from '@ve-utils/core' +import { ElementService, ProjectService, PermissionsService } from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { SpecApi, SpecService } from './services/Spec.service'; +import { SpecApi, SpecService } from './services/Spec.service' -import { VeComponentOptions, VeQService } from '@ve-types/angular'; -import { ElementObject } from '@ve-types/mms'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeComponentOptions, VeQService } from '@ve-types/angular' +import { ElementObject } from '@ve-types/mms' +import { VeModalService } from '@ve-types/view-editor' /** * @ngdoc directive @@ -87,37 +87,37 @@ import { VeModalService } from '@ve-types/view-editor'; class ToolsController { //Bindings - toolsCategory: string; + toolsCategory: string //Local - elementId: string; - projectId: string; - refId: string; - commitId: string; - edit: EditObject; - element: ElementObject; - inPreviewMode: boolean; - isEditing: boolean; - skipBroadcast: boolean; - - subs: Rx.IDisposable[]; - currentTool: string; - currentTitle: string; - specApi: SpecApi; + elementId: string + projectId: string + refId: string + commitId: string + edit: EditObject + element: ElementObject + inPreviewMode: boolean + isEditing: boolean + skipBroadcast: boolean + + subs: Rx.IDisposable[] + currentTool: string + currentTitle: string + specApi: SpecApi show: { - [key: string]: boolean; - } = {}; + [key: string]: boolean + } = {} - editable: boolean; - viewId: string; - elementSaving: boolean; - elementLoading: boolean; + editable: boolean + viewId: string + elementSaving: boolean + elementLoading: boolean - protected errorType: string; + protected errorType: string - toolbarId: string; + toolbarId: string - protected $tools: JQuery; + protected $tools: JQuery static $inject = [ '$q', '$timeout', @@ -139,7 +139,7 @@ class ToolsController { 'ToolbarService', 'SpecService', 'ExtensionService', - ]; + ] constructor( private $q: VeQService, @@ -165,197 +165,197 @@ class ToolsController { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) - this.$tools = $('#tools'); + this.$tools = $('#tools') - this.specApi = this.specSvc.specApi; - this.elementSaving = false; + this.specApi = this.specSvc.specApi + this.elementSaving = false //Listen for Toolbar Clicked Subject - this.subs.push(this.eventSvc.binding(this.toolbarId, this.changeTool)); + this.subs.push(this.eventSvc.binding(this.toolbarId, this.changeTool)) this.subs.push( this.eventSvc.$on('editor.open', (editOb: ElementObject) => { - this.openEdit(); + this.openEdit() }) - ); + ) this.subs.push( this.eventSvc.$on('editor.close', (editOb: ElementObject) => { - this.closeEdit(); + this.closeEdit() }) - ); + ) this.subs.push( this.eventSvc.$on('spec-editor.save', () => { - this.save(false); + this.save(false) }) - ); + ) this.subs.push( this.eventSvc.$on('spec-editor.save-continue', () => { - this.save(true); + this.save(true) }) - ); + ) this.subs.push( this.eventSvc.$on('element-saving', (data: boolean) => { - this.elementSaving = data; + this.elementSaving = data }) - ); + ) this.subs.push( this.eventSvc.binding('spec.ready', (data) => { - this.elementLoading = !data; + this.elementLoading = !data }) - ); + ) this.hotkeys.bindTo(this.$scope).add({ combo: 'alt+a', description: 'save all', callback: () => { - this.eventSvc.$broadcast('spec-editor.saveall'); + this.eventSvc.$broadcast('spec-editor.saveall') }, - }); - const savingAll = false; + }) + const savingAll = false this.subs.push( this.eventSvc.$on('spec-editor.saveall', () => { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-editor.saveall'); + api.toggleButtonSpinner('spec-editor.saveall') this.editorSvc .saveAll() .catch(() => { // reset the last edit elementOb to one of the existing element - const firstEdit = Object.values(this.autosaveSvc.getAll())[0]; - this.specSvc.tracker.etrackerSelected = firstEdit.key; - this.specSvc.keepMode(); - this.specApi.elementId = firstEdit.element.id; - this.specApi.projectId = firstEdit.element._projectId; - this.specApi.refId = firstEdit.element._refId; - this.specApi.commitId = 'latest'; - this.growl.error('Some elements failed to save, resolve individually in edit pane'); + const firstEdit = Object.values(this.autosaveSvc.getAll())[0] + this.specSvc.tracker.etrackerSelected = firstEdit.key + this.specSvc.keepMode() + this.specApi.elementId = firstEdit.element.id + this.specApi.projectId = firstEdit.element._projectId + this.specApi.refId = firstEdit.element._refId + this.specApi.commitId = 'latest' + this.growl.error('Some elements failed to save, resolve individually in edit pane') }) .finally(() => { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-editor.saveall'); - this.specSvc.toggleSave(this.toolbarId); + api.toggleButtonSpinner('spec-editor.saveall') + this.specSvc.toggleSave(this.toolbarId) }, (reason) => { - this.growl.error(ToolbarService.error(reason)); + this.growl.error(ToolbarService.error(reason)) } - ); - }); + ) + }) - this.specSvc.setEditing(false); + this.specSvc.setEditing(false) }, (reason) => { - this.growl.error(ToolbarService.error(reason)); + this.growl.error(ToolbarService.error(reason)) } - ); + ) }) - ); + ) this.subs.push( this.eventSvc.$on('spec-editor.cancel', () => { const go = (): void => { - this.editorSvc.cleanUpEdit(this.specSvc.getEdits().key); + this.editorSvc.cleanUpEdit(this.specSvc.getEdits().key) if (this.autosaveSvc.openEdits() > 0) { - const id = Object.keys(this.autosaveSvc.getAll())[0]; - const info = id.split('|'); + const id = Object.keys(this.autosaveSvc.getAll())[0] + const info = id.split('|') const data: veCoreEvents.elementSelectedData = { elementId: info[2], projectId: info[0], refId: info[1], commitId: 'latest', - }; - this.eventSvc.$broadcast('element.selected', data); + } + this.eventSvc.$broadcast('element.selected', data) } else { - this.specSvc.setEditing(false); + this.specSvc.setEditing(false) this.eventSvc.resolve(this.toolbarId, { id: 'spec-inspector', - }); + }) this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.setIcon('spec-editor', 'fa-edit'), (reason) => { - this.growl.error(ToolbarService.error(reason)); + this.growl.error(ToolbarService.error(reason)) } - ); - this.specSvc.toggleSave(this.toolbarId); + ) + this.specSvc.toggleSave(this.toolbarId) } - }; + } this.editorSvc.hasEdits(this.specSvc.getEdits()).then( (hasEdits) => { if (hasEdits) { this.editorSvc.deleteEditModal(this.specSvc.getEdits()).result.then( () => { - go(); + go() }, () => { /* Do Nothing */ } - ); - } else go(); + ) + } else go() }, () => { - go(); + go() } - ); + ) }) - ); + ) } private changeTool = (data: veCoreEvents.toolbarClicked): void => { if (!this.currentTool) { - this.currentTool = ''; + this.currentTool = '' } if (this.currentTool !== data.id) { - if (this.currentTool !== '') this.show[_.camelCase(this.currentTool)] = false; + if (this.currentTool !== '') this.show[_.camelCase(this.currentTool)] = false - this.currentTool = data.id; + this.currentTool = data.id - const inspect: IToolBarButton = this.toolbarSvc.getToolbarButton(data.id); + const inspect: IToolBarButton = this.toolbarSvc.getToolbarButton(data.id) if (!data.title) { - data.title = inspect.tooltip; + data.title = inspect.tooltip } if (!data.category) { - data.category = inspect.category; + data.category = inspect.category } - this.currentTitle = data.title ? data.title : inspect.tooltip; + this.currentTitle = data.title ? data.title : inspect.tooltip if (!this.show.hasOwnProperty(_.camelCase(data.id))) { - this.startTool(data.id); - this.show[_.camelCase(data.id)] = true; + this.startTool(data.id) + this.show[_.camelCase(data.id)] = true } else { - this.show[_.camelCase(data.id)] = true; + this.show[_.camelCase(data.id)] = true } } - }; + } private startTool = (id: string): void => { - const tag = this.extensionSvc.getTagByType('spec', id); - const toolId: string = _.camelCase(id); + const tag = this.extensionSvc.getTagByType('spec', id) + const toolId: string = _.camelCase(id) const newTool: JQuery = $( '

    ' - ); + ) if (tag === 'extensionError') { - this.errorType = this.currentTool.replace('spec-', ''); + this.errorType = this.currentTool.replace('spec-', '') newTool.append( '' - ); + ) } else { - newTool.append('<' + tag + ' toolbar-id="{{$ctrl.toolbarId}}">'); + newTool.append('<' + tag + ' toolbar-id="{{$ctrl.toolbarId}}">') } - this.$tools.append(newTool); + this.$tools.append(newTool) - this.$compile(newTool)(this.$scope); - }; + this.$compile(newTool)(this.$scope) + } // private changeElement= (newVal, oldVal) => { // if (newVal === oldVal) { @@ -368,66 +368,66 @@ class ToolsController { // } public closeEdit = (): void => { - this.specSvc.toggleSave(this.toolbarId); - }; + this.specSvc.toggleSave(this.toolbarId) + } public openEdit = (): void => { - this.specSvc.toggleSave(this.toolbarId); - }; + this.specSvc.toggleSave(this.toolbarId) + } public save = (continueEdit: boolean): void => { if (this.elementSaving) { - this.growl.info('Please Wait...'); - return; + this.growl.info('Please Wait...') + return } this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { if (!continueEdit) { - api.toggleButtonSpinner('spec-editor.save'); + api.toggleButtonSpinner('spec-editor.save') } else { - api.toggleButtonSpinner('spec-editor.save-continue'); + api.toggleButtonSpinner('spec-editor.save-continue') } this.editorSvc .save(this.specSvc.getEdits().key, continueEdit) .then( () => { if (this.autosaveSvc.openEdits() > 0) { - const next = Object.keys(this.autosaveSvc.getAll())[0]; - const info = next.split('|'); + const next = Object.keys(this.autosaveSvc.getAll())[0] + const info = next.split('|') const data: veCoreEvents.elementSelectedData = { elementId: info[2], projectId: info[0], refId: info[1], commitId: 'latest', - }; - this.eventSvc.$broadcast('element.selected', data); + } + this.eventSvc.$broadcast('element.selected', data) } else { - this.specSvc.setEditing(false); - this.specSvc.toggleSave(this.toolbarId); + this.specSvc.setEditing(false) + this.specSvc.toggleSave(this.toolbarId) this.eventSvc.resolve(this.toolbarId, { id: 'spec-inspector', - }); + }) } }, (reason) => { - if (reason.type === 'info') this.growl.info(reason.message); - else if (reason.type === 'warning') this.growl.warning(reason.message); - else if (reason.type === 'error') this.growl.error(reason.message); + if (reason.type === 'info') this.growl.info(reason.message) + else if (reason.type === 'warning') this.growl.warning(reason.message) + else if (reason.type === 'error') this.growl.error(reason.message) } ) .finally(() => { if (!continueEdit) { - api.toggleButtonSpinner('spec-editor.save'); + api.toggleButtonSpinner('spec-editor.save') } else { - api.toggleButtonSpinner('spec-editor.save-continue'); + api.toggleButtonSpinner('spec-editor.save-continue') } - }); + }) }, (reason) => { - this.growl.error(ToolbarService.error(reason)); + this.growl.error(ToolbarService.error(reason)) } - ); - }; + ) + } } const MmsToolsComponent: VeComponentOptions = { @@ -447,6 +447,6 @@ const MmsToolsComponent: VeComponentOptions = { toolsCategory: '<', }, controller: ToolsController, -}; +} -veComponents.component(MmsToolsComponent.selector, MmsToolsComponent); +veComponents.component(MmsToolsComponent.selector, MmsToolsComponent) diff --git a/src/ve-components/spec-tools/services/Spec.service.ts b/src/ve-components/spec-tools/services/Spec.service.ts index 1fe499aff..f7a2ad848 100644 --- a/src/ve-components/spec-tools/services/Spec.service.ts +++ b/src/ve-components/spec-tools/services/Spec.service.ts @@ -1,8 +1,8 @@ -import { ComponentService } from '@ve-components/services'; -import { EditorService } from '@ve-core/editor'; -import { ToolbarService } from '@ve-core/toolbar'; -import { UtilsService } from '@ve-utils/application'; -import { EditObject, EditService, EventService } from '@ve-utils/core'; +import { ComponentService } from '@ve-components/services' +import { EditorService } from '@ve-core/editor' +import { ToolbarService } from '@ve-core/toolbar' +import { UtilsService } from '@ve-utils/application' +import { EditObject, EditService, EventService } from '@ve-utils/core' import { ApiService, AuthService, @@ -13,11 +13,11 @@ import { UserService, ViewService, ValueService, -} from '@ve-utils/mms-api-client'; +} from '@ve-utils/mms-api-client' -import { PropertySpec, veComponents } from '@ve-components'; +import { PropertySpec, veComponents } from '@ve-components' -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' import { DocumentObject, ElementObject, @@ -27,37 +27,37 @@ import { ValueObject, ViewInstanceSpec, ViewObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' export interface SpecApi extends ElementsRequest { - rootId?: string; - refType: string; - displayOldSpec?: boolean | null; - relatedDocuments?: ViewObject[]; - propSpec?: PropertySpec; - typeClass?: string; - dataLink?: string; - qualifiedName?: string; + rootId?: string + refType: string + displayOldSpec?: boolean | null + relatedDocuments?: ViewObject[] + propSpec?: PropertySpec + typeClass?: string + dataLink?: string + qualifiedName?: string } export class SpecService implements angular.Injectable { - private element: ElementObject; - private view: ViewObject | ViewInstanceSpec; - private document: DocumentObject; - private modifier: UserObject; - private ref: RefObject; - private values: ValueObject[]; - private edit: EditObject; - private editing: boolean = false; - public editable: boolean; - private keeping: boolean = false; + private element: ElementObject + private view: ViewObject | ViewInstanceSpec + private document: DocumentObject + private modifier: UserObject + private ref: RefObject + private values: ValueObject[] + private edit: EditObject + private editing: boolean = false + public editable: boolean + private keeping: boolean = false - public specApi: SpecApi = { refType: '', refId: '', elementId: '', projectId: '' }; + public specApi: SpecApi = { refType: '', refId: '', elementId: '', projectId: '' } public tracker: { - etrackerSelected?: string; - } = {}; + etrackerSelected?: string + } = {} - public editValues: ValueObject[] = []; + public editValues: ValueObject[] = [] static $inject = [ '$q', @@ -78,10 +78,10 @@ export class SpecService implements angular.Injectable { 'ApiService', 'ValueService', 'EditorService', - ]; - private ran: boolean; - private lastid: string; - private gettingSpec: boolean; + ] + private ran: boolean + private lastid: string + private gettingSpec: boolean constructor( private $q: VeQService, private $timeout: angular.ITimeoutService, @@ -111,13 +111,13 @@ export class SpecService implements angular.Injectable { */ public toggleEditing = (): boolean => { if (!this.editing) { - if (this.editable) this.editing = true; - else return false; + if (this.editable) this.editing = true + else return false } else { - this.editing = false; + this.editing = false } - return true; - }; + return true + } /** * @name veComponents.component:mmsSpec#setEditing * sets editor state @@ -127,11 +127,11 @@ export class SpecService implements angular.Injectable { */ public setEditing = (mode): boolean => { if (mode) { - if (this.editable) this.editing = true; - else return false; - } else this.editing = false; - return true; - }; + if (this.editable) this.editing = true + else return false + } else this.editing = false + return true + } /** * @name veComponents.component:mmsSpec#getEditing * get editor state @@ -139,8 +139,8 @@ export class SpecService implements angular.Injectable { * @return {boolean} editor or not */ public getEditing = (): boolean => { - return this.editing; - }; + return this.editing + } /** * @name veComponents.component:mmsSpec#getEdits * get current edit object @@ -149,98 +149,98 @@ export class SpecService implements angular.Injectable { * current element object that can be edited (may include changes) */ public getEdits = (): EditObject => { - return this.edit; - }; + return this.edit + } public setEdits = (editOb: EditObject): void => { if (this.valueSvc.isValue(editOb.element)) { - editOb.values = this.valueSvc.getValues(editOb.element); + editOb.values = this.valueSvc.getValues(editOb.element) } - this.edit = editOb; - }; + this.edit = editOb + } public getElement = (): ElementObject => { - return this.element; - }; + return this.element + } public getDocument = (): DocumentObject => { - return this.document; - }; + return this.document + } public getView = (): ElementObject => { - return this.view; - }; + return this.view + } public getModifier = (): UserObject => { - return this.modifier; - }; + return this.modifier + } public getValues(): ValueObject[] { - return this.values; + return this.values } public getRef = (): RefObject => { - return this.ref; - }; + return this.ref + } public getTypeClass = (element: ElementObject): void => { // Get Type - this.specApi.typeClass = this.utilsSvc.getElementTypeClass(element, this.viewSvc.getElementType(element)); - }; + this.specApi.typeClass = this.utilsSvc.getElementTypeClass(element, this.viewSvc.getElementType(element)) + } public getQualifiedName(element: ElementObject): VePromise { - const deferred = this.$q.defer(); - if (this.edit) element = this.edit.element; + const deferred = this.$q.defer() + if (this.edit) element = this.edit.element const reqOb: ElementsRequest = { commitId: element._commitId ? element._commitId : 'latest', projectId: element._projectId, refId: element._refId, elementId: element.id, - }; + } this.elementSvc.getElementQualifiedName(reqOb).then( (result) => { - this.specApi.qualifiedName = result; - deferred.resolve(true); + this.specApi.qualifiedName = result + deferred.resolve(true) }, (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); - return deferred.promise; + ) + return deferred.promise } public setElement = (): void => { - this.specApi.relatedDocuments = null; - this.specApi.propSpec = {}; + this.specApi.relatedDocuments = null + this.specApi.propSpec = {} - this.ran = true; - this.lastid = this.specApi.elementId; + this.ran = true + this.lastid = this.specApi.elementId - this.specApi.extended = !(this.specApi.commitId && this.specApi.commitId !== 'latest'); + this.specApi.extended = !(this.specApi.commitId && this.specApi.commitId !== 'latest') - this._updateElement(); - }; + this._updateElement() + } private _updateElement = (): void => { - const reqOb = Object.assign({}, this.specApi); + const reqOb = Object.assign({}, this.specApi) this.elementSvc .getElement(reqOb, 2, false) .then( (data) => { - const promises: angular.IPromise[] = []; + const promises: angular.IPromise[] = [] if (data.id !== this.lastid) { - return; + return } - this.element = data; + this.element = data if (this.apiSvc.isView(data) || this.viewSvc.isSection(data)) { - this.view = data; + this.view = data } - this.values = this.valueSvc.getValues(data); + this.values = this.valueSvc.getValues(data) promises.push( this.userSvc.getUserData(data._modifier).then((result) => { - this.modifier = result; + this.modifier = result }) - ); + ) /* no more related docs search supported if (!this.specApi.commitId || this.specApi.commitId === 'latest') { promises.push( @@ -276,32 +276,32 @@ export class SpecService implements angular.Injectable { projectId: this.specApi.projectId, refId: this.specApi.refId, commitId: this.specApi.commitId ? this.specApi.commitId : 'latest', - }; + } promises.push( this.viewSvc.getProjectDocument(docReq, 1).then((result) => { - this.document = result; + this.document = result }) - ); + ) } if ( (this.specApi.commitId && this.specApi.commitId !== 'latest') || !this.permissionsSvc.hasBranchEditPermission(data._projectId, data._refId) || this.specApi.refType === 'Tag' ) { - this.editable = false; - this.edit = null; - this.setEditing(false); + this.editable = false + this.edit = null + this.setEditing(false) } else { - this.editable = true; + this.editable = true // only get edit object if in spec edit } promises.push( this.projectSvc.getRef(this.specApi.refId, this.specApi.projectId).then((result) => { - this.ref = result; + this.ref = result }) - ); - this.getTypeClass(this.element); - promises.push(this.getQualifiedName(this.element)); + ) + this.getTypeClass(this.element) + promises.push(this.getQualifiedName(this.element)) this.specApi.dataLink = this.uRLSvc.getRoot() + '/projects/' + @@ -313,56 +313,56 @@ export class SpecService implements angular.Injectable { '?commitId=' + this.element._commitId + '&token=' + - this.authSvc.getToken(); + this.authSvc.getToken() this.$q.allSettled(promises).then( () => this.eventSvc.resolve('spec.ready', true), (reason: VePromiseReason) => { - this.growl.error('Getting Element Error: ' + reason.message); + this.growl.error('Getting Element Error: ' + reason.message) } - ); + ) }, (reason) => { - this.growl.error('Getting Element Error: ' + reason.message); + this.growl.error('Getting Element Error: ' + reason.message) } ) .finally(() => { - this.gettingSpec = false; - }); - }; + this.gettingSpec = false + }) + } public setKeepMode = (value?: boolean): void => { if (value === undefined) { - this.keepMode(); + this.keepMode() } - this.keeping = value; - }; + this.keeping = value + } public getKeepMode = (): boolean => { - return this.keeping; - }; + return this.keeping + } public keepMode = (): void => { - this.keeping = true; - }; + this.keeping = true + } // Check edit count and toggle appropriate save all and edit/edit-asterisk buttons public toggleSave = (toolbarId: string): void => { this.toolbarSvc.waitForApi(toolbarId).then( (api) => { if (this.autosaveSvc.openEdits() > 0) { - api.setPermission('spec-editor.saveall', true); - api.setIcon('spec-editor', 'fa-edit-asterisk'); + api.setPermission('spec-editor.saveall', true) + api.setIcon('spec-editor', 'fa-edit-asterisk') } else { - api.setPermission('spec-editor.saveall', false); - api.setIcon('spec-editor', 'fa-edit'); + api.setPermission('spec-editor.saveall', false) + api.setIcon('spec-editor', 'fa-edit') } }, (reason) => { - this.growl.error(ToolbarService.error(reason)); + this.growl.error(ToolbarService.error(reason)) } - ); - }; + ) + } // // Check edit count and toggle appropriate save all and edit/edit-asterisk buttons @@ -384,4 +384,4 @@ export class SpecService implements angular.Injectable { // } } -veComponents.service('SpecService', SpecService); +veComponents.service('SpecService', SpecService) diff --git a/src/ve-components/spec-tools/spec-tool.controller.ts b/src/ve-components/spec-tools/spec-tool.controller.ts index d27768d66..2bd9720a6 100644 --- a/src/ve-components/spec-tools/spec-tool.controller.ts +++ b/src/ve-components/spec-tools/spec-tool.controller.ts @@ -1,10 +1,10 @@ -import { IPaneScope } from '@openmbee/pane-layout'; +import { IPaneScope } from '@openmbee/pane-layout' -import { ComponentService } from '@ve-components/services'; -import { veCoreEvents } from '@ve-core/events'; -import { ToolbarService, ToolbarApi } from '@ve-core/toolbar'; -import { ApplicationService } from '@ve-utils/application'; -import { EditObject, EventService } from '@ve-utils/core'; +import { ComponentService } from '@ve-components/services' +import { veCoreEvents } from '@ve-core/events' +import { ToolbarService, ToolbarApi } from '@ve-core/toolbar' +import { ApplicationService } from '@ve-utils/application' +import { EditObject, EventService } from '@ve-utils/core' import { ApiService, ElementService, @@ -12,32 +12,32 @@ import { ProjectService, URLService, ViewService, -} from '@ve-utils/mms-api-client'; +} from '@ve-utils/mms-api-client' -import { SpecApi, SpecService } from './services/Spec.service'; +import { SpecApi, SpecService } from './services/Spec.service' -import { VeQService } from '@ve-types/angular'; -import { ElementObject, RefObject, ValueObject, ViewObject } from '@ve-types/mms'; +import { VeQService } from '@ve-types/angular' +import { ElementObject, RefObject, ValueObject, ViewObject } from '@ve-types/mms' export interface ISpecTool extends angular.IComponentController { - $scope: ISpecToolScope; - commitId: string; - specType: string; - edit: EditObject; - element: ElementObject; - isEditing: boolean; - inPreviewMode: boolean; - skipBroadcast: boolean; - editValues?: ValueObject[]; - values?: ValueObject[]; + $scope: ISpecToolScope + commitId: string + specType: string + edit: EditObject + element: ElementObject + isEditing: boolean + inPreviewMode: boolean + skipBroadcast: boolean + editValues?: ValueObject[] + values?: ValueObject[] //Functions - addValue?(type: string): void; - removeVal?(i: number): void; + addValue?(type: string): void + removeVal?(i: number): void } export interface ISpecToolScope extends IPaneScope { - $ctrl?: ISpecTool; - $parent: ISpecToolScope; + $ctrl?: ISpecTool + $parent: ISpecToolScope } /** @@ -76,40 +76,40 @@ export interface ISpecToolScope extends IPaneScope { */ export class SpecTool implements ISpecTool { //Bindings - protected toolbarId: string; + protected toolbarId: string - public specApi: SpecApi; + public specApi: SpecApi //Customizers - public specType: string; - public specTitle: string; + public specType: string + public specTitle: string - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] - public commitId: string; - protected projectId: string; - protected refId: string; + public commitId: string + protected projectId: string + protected refId: string - public isEditing: boolean; - public isEnumeration: boolean; - public inPreviewMode: boolean; - public elementSaving: boolean; - public skipBroadcast: boolean; + public isEditing: boolean + public isEnumeration: boolean + public inPreviewMode: boolean + public elementSaving: boolean + public skipBroadcast: boolean - protected gettingSpec = true; - public element: ElementObject; - public document: ViewObject; - public ref: RefObject; - public values: any[]; - public edit: EditObject; - protected modifier; - protected options: any; - protected elementDataLink: string; - protected qualifiedName: string; + protected gettingSpec = true + public element: ElementObject + public document: ViewObject + public ref: RefObject + public values: any[] + public edit: EditObject + protected modifier + protected options: any + protected elementDataLink: string + protected qualifiedName: string - public editValues: any[]; + public editValues: any[] - protected template: string | angular.Injectable<(...args: any[]) => string>; + protected template: string | angular.Injectable<(...args: any[]) => string> static $inject = [ '$q', @@ -127,7 +127,7 @@ export class SpecTool implements ISpecTool { 'EventService', 'SpecService', 'ToolbarService', - ]; + ] constructor( protected $q: VeQService, @@ -148,9 +148,9 @@ export class SpecTool implements ISpecTool { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) - this.editValues = this.specSvc.editValues; + this.editValues = this.specSvc.editValues this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { if ( @@ -158,24 +158,24 @@ export class SpecTool implements ISpecTool { window.__env && window.__env.enableDebug ) { - console.log('Spec View: ' + this.specType + 'is missing a button definition'); + console.log('Spec View: ' + this.specType + 'is missing a button definition') } - this.configToolbar(api); + this.configToolbar(api) }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) - this.changeElement(); + this.changeElement() - this.subs.push(this.eventSvc.binding('spec.ready', this.changeElement)); + this.subs.push(this.eventSvc.binding('spec.ready', this.changeElement)) //this.subs.push(this.eventSvc.$on(this.specType, this.initCallback)) } $onDestroy(): void { - this.eventSvc.destroy(this.subs); - this.destroy(); + this.eventSvc.destroy(this.subs) + this.destroy() } /** @@ -187,7 +187,7 @@ export class SpecTool implements ISpecTool { */ protected configToolbar = (api: ToolbarApi): void => { /* Implement any toolbar initialization Logic Here */ - }; + } /** * @name veComponents/SpecTool#initCallback @@ -198,7 +198,7 @@ export class SpecTool implements ISpecTool { */ protected initCallback: () => void = () => { /* Implement any post initialization steps here */ - }; + } /** * @name veComponents/SpecTool#destroy @@ -209,41 +209,41 @@ export class SpecTool implements ISpecTool { */ protected destroy: () => void = () => { /* Implement any custom on destroy logic to unregister listeners etc */ - }; + } public changeElement = (ready?: boolean): void => { - if (!ready) return; - this.gettingSpec = true; - this.specApi = this.specSvc.specApi; - this.refId = this.specApi.refId; - this.projectId = this.specApi.projectId; - this.commitId = this.specApi.commitId; - this.modifier = this.specSvc.getModifier(); - this.qualifiedName = this.specApi.qualifiedName; - this.element = this.specSvc.getElement(); - this.document = this.specSvc.getDocument(); - this.values = this.specSvc.getValues(); - this.ref = this.specSvc.getRef(); - this.elementDataLink = this.specApi.dataLink; - this.initCallback(); - this.gettingSpec = false; - }; + if (!ready) return + this.gettingSpec = true + this.specApi = this.specSvc.specApi + this.refId = this.specApi.refId + this.projectId = this.specApi.projectId + this.commitId = this.specApi.commitId + this.modifier = this.specSvc.getModifier() + this.qualifiedName = this.specApi.qualifiedName + this.element = this.specSvc.getElement() + this.document = this.specSvc.getDocument() + this.values = this.specSvc.getValues() + this.ref = this.specSvc.getRef() + this.elementDataLink = this.specApi.dataLink + this.initCallback() + this.gettingSpec = false + } //Spec Tool Common API public copyToClipboard($event: JQuery.ClickEvent, selector: string): void { this.applicationSvc.copyToClipboard(this.$element.find(selector), $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }); + this.growl.info('Copied to clipboard!', { ttl: 2000 }) }, (err) => { - this.growl.error('Unable to copy: ' + err.message); + this.growl.error('Unable to copy: ' + err.message) } - ); + ) } public cleanupVal(obj: { value: unknown }): void { - obj.value = parseInt(obj.value as string); + obj.value = parseInt(obj.value as string) } public propertyTypeClicked = (id: string): void => { @@ -252,12 +252,12 @@ export class SpecTool implements ISpecTool { projectId: this.element._projectId, refId: this.element._refId, commitId: 'latest', - }; - this.eventSvc.$broadcast('element.selected', data); - }; + } + this.eventSvc.$broadcast('element.selected', data) + } public addHtml(value: { value: string }): void { - value.value = '

    ' + value.value + '

    '; + value.value = '

    ' + value.value + '

    ' } /** @@ -275,6 +275,6 @@ export class SpecTool implements ISpecTool { // } public hasHtml = (s: string): boolean => { - return this.componentSvc.hasHtml(s); - }; + return this.componentSvc.hasHtml(s) + } } diff --git a/src/ve-components/transclusions/components/index.ts b/src/ve-components/transclusions/components/index.ts index 1d7d11a1a..182bc59e5 100644 --- a/src/ve-components/transclusions/components/index.ts +++ b/src/ve-components/transclusions/components/index.ts @@ -1,12 +1,12 @@ -import './transclude-art.component'; -import './transclude-attr.component'; -import './transclude-com.component'; -import './transclude-doc.component'; -import './transclude-enum.component'; -import './transclude-group-docs.component'; -import './transclude-img.component'; -import './transclude-name.component'; -import './transclude-val.component'; -import './transclude-value-link.component'; -import './transclude-view.component'; -import './transclude-section.component'; +import './transclude-art.component' +import './transclude-attr.component' +import './transclude-com.component' +import './transclude-doc.component' +import './transclude-enum.component' +import './transclude-group-docs.component' +import './transclude-img.component' +import './transclude-name.component' +import './transclude-val.component' +import './transclude-value-link.component' +import './transclude-view.component' +import './transclude-section.component' diff --git a/src/ve-components/transclusions/components/transclude-art.component.ts b/src/ve-components/transclusions/components/transclude-art.component.ts index c8f826ffb..a3da55ae2 100644 --- a/src/ve-components/transclusions/components/transclude-art.component.ts +++ b/src/ve-components/transclusions/components/transclude-art.component.ts @@ -1,15 +1,15 @@ -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { Transclusion, ITransclusion, ITransclusionComponentOptions } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { UtilsService, MathService, ImageService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, URLService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { Transclusion, ITransclusion, ITransclusionComponentOptions } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { UtilsService, MathService, ImageService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, URLService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; +import { VePromise, VeQService } from '@ve-types/angular' /** * @ngdoc component @@ -47,13 +47,13 @@ import { VePromise, VeQService } from '@ve-types/angular'; */ export class TranscludeArtController extends Transclusion implements ITransclusion { //Custom Bindings - mmsArtExt: string; + mmsArtExt: string //Locals - artExt: string; - artifacts: any[]; + artExt: string + artifacts: any[] - static $inject: string[] = [...Transclusion.$inject, 'URLService']; + static $inject: string[] = [...Transclusion.$inject, 'URLService'] constructor( $q: VeQService, @@ -91,32 +91,32 @@ export class TranscludeArtController extends Transclusion implements ITransclusi extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'doc'; - this.cfTitle = 'Documentation'; - this.cfKind = 'Text'; - this.checkCircular = true; + ) + this.cfType = 'doc' + this.cfTitle = 'Documentation' + this.cfKind = 'Text' + this.checkCircular = true } $onInit(): void { - super.$onInit(); + super.$onInit() - this.artExt = this.mmsArtExt; + this.artExt = this.mmsArtExt this.$element.on('click', (e) => { - if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element); + if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element) - e.stopPropagation(); - }); + e.stopPropagation() + }) } public getContent = (preview?: boolean): VePromise => { - const artifacts = this.element._artifacts; + const artifacts = this.element._artifacts if (artifacts !== undefined) { - const allExt = artifacts.map((a) => a.extension); - let includeExt = allExt; + const allExt = artifacts.map((a) => a.extension) + let includeExt = allExt if (this.artExt !== '' || this.artExt !== undefined) { - includeExt = this.artExt.split(',').filter((a) => allExt.includes(a)); + includeExt = this.artExt.split(',').filter((a) => allExt.includes(a)) } const reqOb = { elementId: this.mmsElementId, @@ -124,7 +124,7 @@ export class TranscludeArtController extends Transclusion implements ITransclusi refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - }; + } this.artifacts = artifacts .filter((a) => includeExt.includes(a.extension)) .map((a) => { @@ -132,13 +132,13 @@ export class TranscludeArtController extends Transclusion implements ITransclusi url: this.urlSvc.getArtifactURL(reqOb, a.extension), image: a.mimetype.indexOf('image') > -1, ext: a.extension, - }; - }); + } + }) } const result = - ''; - return this.$q.resolve(result); - }; + '' + return this.$q.resolve(result) + } } export const TranscludeArtComponent: ITransclusionComponentOptions = { @@ -161,6 +161,6 @@ export const TranscludeArtComponent: ITransclusionComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeArtController, -}; +} -veComponents.component(TranscludeArtComponent.selector, TranscludeArtComponent); +veComponents.component(TranscludeArtComponent.selector, TranscludeArtComponent) diff --git a/src/ve-components/transclusions/components/transclude-attr.component.ts b/src/ve-components/transclusions/components/transclude-attr.component.ts index 930eba2f1..3c855d44e 100644 --- a/src/ve-components/transclusions/components/transclude-attr.component.ts +++ b/src/ve-components/transclusions/components/transclude-attr.component.ts @@ -4,31 +4,31 @@ //

    Target

    // //
    -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { ITransclusion, Transclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { veCoreEvents } from '@ve-core/events'; -import { MathService, UtilsService, ImageService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { ITransclusion, Transclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { veCoreEvents } from '@ve-core/events' +import { MathService, UtilsService, ImageService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' export class TranscludeAttrController extends Transclusion implements ITransclusion { protected template: string = ` -`; +` //Custom Binding - mmsAttr: string; + mmsAttr: string //Locals - attrValues: string[] = []; + attrValues: string[] = [] - static $inject = Transclusion.$inject; + static $inject = Transclusion.$inject constructor( $q: VeQService, @@ -65,61 +65,61 @@ export class TranscludeAttrController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'name'; - this.cfTitle = ''; - this.cfKind = 'Text'; - this.checkCircular = false; + ) + this.cfType = 'name' + this.cfTitle = '' + this.cfKind = 'Text' + this.checkCircular = false } $onInit(): void { - super.$onInit(); + super.$onInit() this.$element.on('click', (e) => { - e.stopPropagation(); - if (this.noClick) return; + e.stopPropagation() + if (this.noClick) return const data = { elementId: this.element.id, projectId: this.element._projectId, refId: this.element._refId, commitId: 'latest', - }; - this.eventSvc.$broadcast('element.selected', data); - }); + } + this.eventSvc.$broadcast('element.selected', data) + }) } public getContent = (preview?): VePromise => { - const deferred = this.$q.defer(); - let contentTemplate: string; - const ids: string[] = []; + const deferred = this.$q.defer() + let contentTemplate: string + const ids: string[] = [] if ( this.element[this.mmsAttr] || (Array.isArray(this.element[this.mmsAttr]) && (this.element[this.mmsAttr] as Array).length > 0) ) { //Grab id reference to an array for CF if (this.mmsAttr.endsWith('Id')) { - ids.push(this.element[this.mmsAttr] as string); + ids.push(this.element[this.mmsAttr] as string) } // Grab id array for a CF list else if (this.mmsAttr.endsWith('Ids')) { - ids.push(...(this.element[this.mmsAttr] as Array)); + ids.push(...(this.element[this.mmsAttr] as Array)) } // Convert List of elements to strings else if (Array.isArray(this.element[this.mmsAttr])) { - (this.element[this.mmsAttr] as Array).forEach((value) => { + ;(this.element[this.mmsAttr] as Array).forEach((value) => { if (typeof this.element[this.mmsAttr] === 'object') { - value = JSON.stringify(value); + value = JSON.stringify(value) } - this.attrValues.push(`${value.toString()}`); - }); + this.attrValues.push(`${value.toString()}`) + }) } else { - let value: string; + let value: string if (typeof this.element[this.mmsAttr] === 'object') { - value = JSON.stringify(this.element[this.mmsAttr]); + value = JSON.stringify(this.element[this.mmsAttr]) } else { - value = (this.element[this.mmsAttr] as unknown).toString(); + value = (this.element[this.mmsAttr] as unknown).toString() } - this.attrValues.push(`${value}`); + this.attrValues.push(`${value}`) } // Convert referenced ids array to CF list if (ids.length > 0) { @@ -128,24 +128,24 @@ export class TranscludeAttrController extends Transclusion implements ITransclus `` - ); - }); + ) + }) } } else { - this.attrValues.push(`(empty)`); + this.attrValues.push(`(empty)`) } if (this.mmsCfLabel) { - contentTemplate = `

    {{$ctrl.mmsAttr}}

    `; + contentTemplate = `

    {{$ctrl.mmsAttr}}

    ` } this.attrValues.forEach((value, index) => { - const sep = index == this.attrValues.length - 1 ? '' : ', '; - contentTemplate += `${value}${this.mmsCfLabel ? '
    ' : sep}`; - }); - deferred.resolve(contentTemplate); + const sep = index == this.attrValues.length - 1 ? '' : ', ' + contentTemplate += `${value}${this.mmsCfLabel ? '
    ' : sep}` + }) + deferred.resolve(contentTemplate) - return deferred.promise; - }; + return deferred.promise + } } export const TranscludeNameComponent: VeComponentOptions = { @@ -167,6 +167,6 @@ export const TranscludeNameComponent: VeComponentOptions = { mmsSpecEditor: '?^^specEditor', }, controller: TranscludeAttrController, -}; +} -veComponents.component(TranscludeNameComponent.selector, TranscludeNameComponent); +veComponents.component(TranscludeNameComponent.selector, TranscludeNameComponent) diff --git a/src/ve-components/transclusions/components/transclude-com.component.ts b/src/ve-components/transclusions/components/transclude-com.component.ts index fd6fe3d71..be86fda4c 100644 --- a/src/ve-components/transclusions/components/transclude-com.component.ts +++ b/src/ve-components/transclusions/components/transclude-com.component.ts @@ -1,17 +1,17 @@ -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { ITransclusion, ITransclusionComponentOptions } from '@ve-components/transclusions'; -import { TranscludeDocController } from '@ve-components/transclusions/components/transclude-doc.component'; -import { DeletableTransclusion } from '@ve-components/transclusions/deletable-transclusion.controller'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { ImageService, MathService, UtilsService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { ITransclusion, ITransclusionComponentOptions } from '@ve-components/transclusions' +import { TranscludeDocController } from '@ve-components/transclusions/components/transclude-doc.component' +import { DeletableTransclusion } from '@ve-components/transclusions/deletable-transclusion.controller' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { ImageService, MathService, UtilsService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; +import { VePromise, VeQService } from '@ve-types/angular' /** * @ngdoc directive @@ -38,7 +38,7 @@ import { VePromise, VeQService } from '@ve-types/angular'; * @param {string=latest} mmsCommitId Commit ID, default is latest */ export class TranscludeComController extends TranscludeDocController implements ITransclusion { - static $inject = DeletableTransclusion.$inject; + static $inject = DeletableTransclusion.$inject constructor( $q: VeQService, @@ -77,49 +77,49 @@ export class TranscludeComController extends TranscludeDocController implements buttonBarSvc, imageSvc, viewSvc - ); - this.cfType = 'doc'; - this.cfTitle = 'comment'; - this.cfKind = 'Comment'; - this.checkCircular = true; + ) + this.cfType = 'doc' + this.cfTitle = 'comment' + this.cfKind = 'Comment' + this.checkCircular = true } $onInit(): void { - super.$onInit(); + super.$onInit() if (this.mmsViewPresentationElemCtrl) { if (this.isDeletable) { - const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec(); - this.panelTitle = instanceSpec ? instanceSpec.name : 'Comment'; + const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec() + this.panelTitle = instanceSpec ? instanceSpec.name : 'Comment' } - this.panelType = 'Comment'; + this.panelType = 'Comment' } } public getContent = (preview?: boolean): VePromise => { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() - let doc = (preview ? this.edit.element.documentation : this.element.documentation) || '(No comment)'; - doc += ' - Comment by ' + this.element._creator + ''; + let doc = (preview ? this.edit.element.documentation : this.element.documentation) || '(No comment)' + doc += ' - Comment by ' + this.element._creator + '' - let result = ''; + let result = '' if (preview) { - result = '
    ' + doc + '
    '; + result = '
    ' + doc + '
    ' } else { - result = doc; + result = doc } if (!this.mmsGenerateForDiff) { - const resultHtml = $('

    ').html(result).toArray(); + const resultHtml = $('

    ').html(result).toArray() this.mathSvc.typeset(resultHtml).then( () => deferred.resolve(resultHtml), (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } else { - deferred.resolve(result); + deferred.resolve(result) } - return deferred.promise; - }; + return deferred.promise + } } export const TranscludeComComponent: ITransclusionComponentOptions = { @@ -141,6 +141,6 @@ export const TranscludeComComponent: ITransclusionComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeComController, -}; +} -veComponents.component(TranscludeComComponent.selector, TranscludeComComponent); +veComponents.component(TranscludeComComponent.selector, TranscludeComComponent) diff --git a/src/ve-components/transclusions/components/transclude-doc.component.ts b/src/ve-components/transclusions/components/transclude-doc.component.ts index b33af456a..55916ee05 100644 --- a/src/ve-components/transclusions/components/transclude-doc.component.ts +++ b/src/ve-components/transclusions/components/transclude-doc.component.ts @@ -1,15 +1,15 @@ -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { ITransclusion, DeletableTransclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService, editor_buttons } from '@ve-core/editor'; -import { UtilsService, MathService, ImageService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { ITransclusion, DeletableTransclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService, editor_buttons } from '@ve-core/editor' +import { UtilsService, MathService, ImageService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' /** * @ngdoc component @@ -65,9 +65,9 @@ export class TranscludeDocController extends DeletableTransclusion implements IT
    -`; +` - static $inject = DeletableTransclusion.$inject; + static $inject = DeletableTransclusion.$inject constructor( $q: VeQService, @@ -106,72 +106,72 @@ export class TranscludeDocController extends DeletableTransclusion implements IT buttonBarSvc, imageSvc, viewSvc - ); - this.cfType = 'doc'; - this.cfTitle = 'Documentation'; - this.cfKind = 'Text'; - this.checkCircular = true; + ) + this.cfType = 'doc' + this.cfTitle = 'Documentation' + this.cfKind = 'Text' + this.checkCircular = true } $onInit(): void { - super.$onInit(); + super.$onInit() - this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_${this.cfType}`); - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons); + this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_${this.cfType}`) + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons) this.$element.on('click', (e) => { - if (this.startEdit && !this.nonEditable) this.startEdit(); + if (this.startEdit && !this.nonEditable) this.startEdit() - if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element); + if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element) if (this.nonEditable && this.mmsViewCtrl && this.mmsViewCtrl.isEditable()) { - this.growl.warning('Cross Reference is not editable.'); + this.growl.warning('Cross Reference is not editable.') } - e.stopPropagation(); - }); + e.stopPropagation() + }) if (this.mmsViewPresentationElemCtrl) { - const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec(); - const presentationElem = this.mmsViewPresentationElemCtrl.getPresentationElement(); + const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec() + const presentationElem = this.mmsViewPresentationElemCtrl.getPresentationElement() if (this.isDeletable) { - this.panelTitle = instanceSpec ? instanceSpec.name : ''; - this.panelType = presentationElem ? presentationElem.type : ''; //this is hack for fake table/list/equation until we get actual editors + this.panelTitle = instanceSpec ? instanceSpec.name : '' + this.panelType = presentationElem ? presentationElem.type : '' //this is hack for fake table/list/equation until we get actual editors if (this.panelType.charAt(this.panelType.length - 1) === 'T') - this.panelType = this.panelType.substring(0, this.panelType.length - 1); - if (this.panelType === 'Paragraph') this.panelType = 'Text'; - if (this.panelType === 'Figure' || this.panelType === 'ImageT') this.panelType = 'Image'; + this.panelType = this.panelType.substring(0, this.panelType.length - 1) + if (this.panelType === 'Paragraph') this.panelType = 'Text' + if (this.panelType === 'Figure' || this.panelType === 'ImageT') this.panelType = 'Image' } if (presentationElem) { - this.editorType = presentationElem.type; + this.editorType = presentationElem.type } } } $onDestroy(): void { - super.$onDestroy(); - this.buttonBarSvc.destroy(this.bbId); + super.$onDestroy() + this.buttonBarSvc.destroy(this.bbId) } public getContent = (preview?: boolean): VePromise => { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() - let doc = preview ? this.edit.element.documentation : this.element.documentation; + let doc = preview ? this.edit.element.documentation : this.element.documentation if (!doc || this.emptyRegex.test(doc)) { - doc = '

    (no ' + this.panelType + ')

    '; + doc = '

    (no ' + this.panelType + ')

    ' } - doc = doc.replace(this.fixPreSpanRegex, ''); - doc = doc.replace(this.spacePeriod, '>.'); - doc = doc.replace(this.spaceSpace, '> '); - doc = doc.replace(this.spaceComma, '>,'); - let result: string; + doc = doc.replace(this.fixPreSpanRegex, '') + doc = doc.replace(this.spacePeriod, '>.') + doc = doc.replace(this.spaceSpace, '> ') + doc = doc.replace(this.spaceComma, '>,') + let result: string if (preview) { - result = '
    ' + doc + '
    '; + result = '
    ' + doc + '
    ' } else { - result = doc; + result = doc } if (this.mmsViewPresentationElemCtrl) { - const element = this.mmsViewPresentationElemCtrl.getPresentationElement(); - const pe = this.mmsViewPresentationElemCtrl.getInstanceSpec(); + const element = this.mmsViewPresentationElemCtrl.getPresentationElement() + const pe = this.mmsViewPresentationElemCtrl.getInstanceSpec() if ( pe && pe._veNumber && @@ -181,26 +181,26 @@ export class TranscludeDocController extends DeletableTransclusion implements IT element.type === 'Equation' || element.type === 'ImageT') ) { - this.type = element.type === 'TableT' ? 'table' : element.type.toLowerCase(); + this.type = element.type === 'TableT' ? 'table' : element.type.toLowerCase() if (this.type === 'imaget') { - this.type = 'figure'; + this.type = 'figure' } - this.utilsSvc.addLiveNumbering(pe, $('#' + pe.id), this.type); + this.utilsSvc.addLiveNumbering(pe, $('#' + pe.id), this.type) } } if (!this.mmsGenerateForDiff) { - const resultHtml = $('

    ').html(result).toArray(); + const resultHtml = $('

    ').html(result).toArray() this.mathSvc.typeset(resultHtml).then( () => deferred.resolve(resultHtml), (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } else { - deferred.resolve(result); + deferred.resolve(result) } - return deferred.promise; - }; + return deferred.promise + } } export const TranscludeDocComponent: VeComponentOptions = { @@ -222,6 +222,6 @@ export const TranscludeDocComponent: VeComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeDocController, -}; +} -veComponents.component(TranscludeDocComponent.selector, TranscludeDocComponent); +veComponents.component(TranscludeDocComponent.selector, TranscludeDocComponent) diff --git a/src/ve-components/transclusions/components/transclude-enum.component.ts b/src/ve-components/transclusions/components/transclude-enum.component.ts index ca3df96dc..c69942f8d 100644 --- a/src/ve-components/transclusions/components/transclude-enum.component.ts +++ b/src/ve-components/transclusions/components/transclude-enum.component.ts @@ -5,18 +5,18 @@ * responsible person for that particular item which gets saved as the Type/Value? of the property You could additionally add a * binding which specifies the template for the creation of new objects as types to be placed in the holding bin. */ -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { ITransclusion, Transclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { MathService, UtilsService, ImageService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ComponentService, ExtensionService } from '@ve-components/services' +import { ITransclusion, Transclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { MathService, UtilsService, ImageService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' /** * @ngdoc component @@ -50,10 +50,10 @@ import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; */ export class TranscludeEnumController extends Transclusion implements ITransclusion { //Locals - noClick: boolean | undefined; - clickHandler: () => void; + noClick: boolean | undefined + clickHandler: () => void - static $inject = Transclusion.$inject; + static $inject = Transclusion.$inject constructor( $q: VeQService, @@ -90,50 +90,50 @@ export class TranscludeEnumController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'name'; - this.cfTitle = ''; - this.cfKind = 'Text'; - this.checkCircular = false; + ) + this.cfType = 'name' + this.cfTitle = '' + this.cfKind = 'Text' + this.checkCircular = false } $onInit(): void { - super.$onInit(); + super.$onInit() // Need a way to put in a query for allowed options. // Value to save the resulting pointer // Transclusion for new options this.$element.on('click', (e) => { - if (this.noClick) return; + if (this.noClick) return if (this.clickHandler) { - this.clickHandler(); - return; + this.clickHandler() + return } - if (this.startEdit && !this.nonEditable) this.startEdit(); + if (this.startEdit && !this.nonEditable) this.startEdit() - if (!this.mmsViewCtrl) return false; + if (!this.mmsViewCtrl) return false if (this.nonEditable && this.mmsViewCtrl && this.mmsViewCtrl.isEditable()) { - this.growl.warning('Cross Reference is not editable.'); + this.growl.warning('Cross Reference is not editable.') } - this.mmsViewCtrl.transcludeClicked(this.element); - e.stopPropagation(); - }); + this.mmsViewCtrl.transcludeClicked(this.element) + e.stopPropagation() + }) } public getContent = (preview?: boolean): VePromise => { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() const defaultTemplate = - '{{$ctrl.element.name}}(no name)'; + '{{$ctrl.element.name}}(no name)' const editTemplate = - '{{$ctrl.edit.name}}(no name)'; + '{{$ctrl.edit.name}}(no name)' if (preview) { - deferred.resolve('
    ' + editTemplate + '
    '); + deferred.resolve('
    ' + editTemplate + '
    ') } else { - deferred.resolve(defaultTemplate); + deferred.resolve(defaultTemplate) } - return deferred.promise; - }; + return deferred.promise + } // private _startEdit( // ctrl: ComponentController, @@ -262,6 +262,6 @@ export const TranscludeEnumComponent: VeComponentOptions = { mmsSpecEditor: '?^^specEditor', }, controller: TranscludeEnumController, -}; +} -veComponents.component(TranscludeEnumComponent.selector, TranscludeEnumComponent); +veComponents.component(TranscludeEnumComponent.selector, TranscludeEnumComponent) diff --git a/src/ve-components/transclusions/components/transclude-group-docs.component.ts b/src/ve-components/transclusions/components/transclude-group-docs.component.ts index 27e55e3e5..5e0fdb8cc 100644 --- a/src/ve-components/transclusions/components/transclude-group-docs.component.ts +++ b/src/ve-components/transclusions/components/transclude-group-docs.component.ts @@ -1,17 +1,17 @@ -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { ITransclusion, Transclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { ImageService, MathService, UtilsService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; -import { handleChange } from '@ve-utils/utils'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { ITransclusion, Transclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { ImageService, MathService, UtilsService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' +import { handleChange } from '@ve-utils/utils' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { ViewObject } from '@ve-types/mms'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { ViewObject } from '@ve-types/mms' /** * @ngdoc directive @@ -31,14 +31,14 @@ class TranscludeGroupDocsController extends Transclusion implements ITransclusio -`; +` - mmsGroupId: string; + mmsGroupId: string - documents: ViewObject[]; - docs: ViewObject[]; + documents: ViewObject[] + docs: ViewObject[] - static $inject = [...Transclusion.$inject, 'ViewService']; + static $inject = [...Transclusion.$inject, 'ViewService'] constructor( $q: VeQService, @@ -76,32 +76,32 @@ class TranscludeGroupDocsController extends Transclusion implements ITransclusio extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'groupDocs'; - this.cfTitle = ''; - this.cfKind = 'Table'; - this.checkCircular = false; + ) + this.cfType = 'groupDocs' + this.cfTitle = '' + this.cfKind = 'Table' + this.checkCircular = false } $postLink(): void { - this.changeAction(this.mmsGroupId, '', false); + this.changeAction(this.mmsGroupId, '', false) } $onInit(): void { - super.$onInit(); - this.mmsGroupId = this.mmsElementId; + super.$onInit() + this.mmsGroupId = this.mmsElementId } protected watch = (onChangesObj: angular.IOnChangesObject): void => { if (onChangesObj.mmsGroupId) { - this.mmsElementId = this.mmsGroupId; + this.mmsElementId = this.mmsGroupId } - handleChange(onChangesObj, 'mmsGroupId', this.changeAction); - }; + handleChange(onChangesObj, 'mmsGroupId', this.changeAction) + } public getContent = (): VePromise => { - const deferred = this.$q.defer(); - this.mmsGroupId = this.mmsElementId; + const deferred = this.$q.defer() + this.mmsGroupId = this.mmsElementId this.viewSvc .getProjectDocuments( { @@ -112,29 +112,29 @@ class TranscludeGroupDocsController extends Transclusion implements ITransclusio ) .then( (documents) => { - this.documents = documents; - this.update(); - deferred.resolve(this.template); + this.documents = documents + this.update() + deferred.resolve(this.template) }, (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); - return deferred.promise; - }; + ) + return deferred.promise + } public update = (): void => { - const docs: ViewObject[] = []; - const groupId = this.mmsGroupId === '' ? undefined : this.mmsGroupId; + const docs: ViewObject[] = [] + const groupId = this.mmsGroupId === '' ? undefined : this.mmsGroupId for (let i = 0; i < this.documents.length; i++) { if ((groupId === undefined || groupId === this.projectId) && !this.documents[i]._groupId) { - docs.push(this.documents[i]); + docs.push(this.documents[i]) } else if (this.documents[i]._groupId == this.mmsGroupId) { - docs.push(this.documents[i]); + docs.push(this.documents[i]) } } - this.docs = docs; - }; + this.docs = docs + } } export const TranscludeGroupDocsComponent: VeComponentOptions = { @@ -156,6 +156,6 @@ export const TranscludeGroupDocsComponent: VeComponentOptions = { mmsViewCtrl: '?^^view', }, controller: TranscludeGroupDocsController, -}; +} -veComponents.component(TranscludeGroupDocsComponent.selector, TranscludeGroupDocsComponent); +veComponents.component(TranscludeGroupDocsComponent.selector, TranscludeGroupDocsComponent) diff --git a/src/ve-components/transclusions/components/transclude-img.component.ts b/src/ve-components/transclusions/components/transclude-img.component.ts index 693455c88..e4cf8cd57 100644 --- a/src/ve-components/transclusions/components/transclude-img.component.ts +++ b/src/ve-components/transclusions/components/transclude-img.component.ts @@ -1,15 +1,15 @@ -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { Transclusion, ITransclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { UtilsService, MathService, ImageService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, URLService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { Transclusion, ITransclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { UtilsService, MathService, ImageService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, URLService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' /** * @ngdoc component @@ -47,12 +47,12 @@ import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; */ export class TranscludeImgController extends Transclusion implements ITransclusion { //Locals - includeExt = ['svg', 'png']; - svg: { url: string; image: boolean; ext: string }[]; - png: { url: string; image: boolean; ext: string }[]; - artifacts: { url: string; image: boolean; ext: string }[]; + includeExt = ['svg', 'png'] + svg: { url: string; image: boolean; ext: string }[] + png: { url: string; image: boolean; ext: string }[] + artifacts: { url: string; image: boolean; ext: string }[] - static $inject: string[] = [...Transclusion.$inject, 'URLService']; + static $inject: string[] = [...Transclusion.$inject, 'URLService'] constructor( $q: VeQService, @@ -90,24 +90,24 @@ export class TranscludeImgController extends Transclusion implements ITransclusi extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'doc'; - this.cfTitle = 'Documentation'; - this.cfKind = 'Text'; - this.checkCircular = true; + ) + this.cfType = 'doc' + this.cfTitle = 'Documentation' + this.cfKind = 'Text' + this.checkCircular = true } $onInit(): void { - super.$onInit(); + super.$onInit() this.$element.on('click', (e) => { - if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element); + if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element) - e.stopPropagation(); - }); + e.stopPropagation() + }) } public getContent = (preview?): VePromise => { - const artifacts = this.element._artifacts; + const artifacts = this.element._artifacts if (artifacts !== undefined) { const reqOb = { elementId: this.mmsElementId, @@ -115,7 +115,7 @@ export class TranscludeImgController extends Transclusion implements ITransclusi refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - }; + } this.artifacts = artifacts .filter((a) => this.includeExt.includes(a.extension)) .map((a) => { @@ -123,16 +123,16 @@ export class TranscludeImgController extends Transclusion implements ITransclusi url: this.urlSvc.getArtifactURL(reqOb, a.extension), image: a.mimetype.indexOf('image') > -1, ext: a.extension, - }; - }); - this.svg = this.artifacts.filter((a) => a.ext === 'svg'); + } + }) + this.svg = this.artifacts.filter((a) => a.ext === 'svg') //this.png = this.artifacts.filter((a) => a.ext === 'png') } const result = '{{$ctrl.element.name}}' + - ''; - return this.$q.resolve(result); - }; + '' + return this.$q.resolve(result) + } } export const TranscludeImgComponent: VeComponentOptions = { @@ -154,6 +154,6 @@ export const TranscludeImgComponent: VeComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeImgController, -}; +} -veComponents.component(TranscludeImgComponent.selector, TranscludeImgComponent); +veComponents.component(TranscludeImgComponent.selector, TranscludeImgComponent) diff --git a/src/ve-components/transclusions/components/transclude-name.component.ts b/src/ve-components/transclusions/components/transclude-name.component.ts index 3c078af3b..87338cafe 100644 --- a/src/ve-components/transclusions/components/transclude-name.component.ts +++ b/src/ve-components/transclusions/components/transclude-name.component.ts @@ -1,16 +1,16 @@ -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { SpecTool } from '@ve-components/spec-tools'; -import { ITransclusion, Transclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { MathService, UtilsService, ImageService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { SpecTool } from '@ve-components/spec-tools' +import { ITransclusion, Transclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { MathService, UtilsService, ImageService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' /** * @ngdoc component @@ -54,13 +54,13 @@ export class TranscludeNameController extends Transclusion implements ITransclus -`; +` //Locals - clickHandler: () => void; - mmsSpecEditorCtrl: SpecTool; + clickHandler: () => void + mmsSpecEditorCtrl: SpecTool - static $inject = Transclusion.$inject; + static $inject = Transclusion.$inject constructor( $q: VeQService, @@ -97,47 +97,47 @@ export class TranscludeNameController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'name'; - this.cfTitle = ''; - this.cfKind = 'Text'; - this.checkCircular = false; + ) + this.cfType = 'name' + this.cfTitle = '' + this.cfKind = 'Text' + this.checkCircular = false } $onInit(): void { - super.$onInit(); + super.$onInit() this.$element.on('click', (e) => { - if (this.noClick) return; + if (this.noClick) return if (this.clickHandler) { - this.clickHandler(); - return; + this.clickHandler() + return } - if (this.startEdit && !this.nonEditable) this.startEdit(); + if (this.startEdit && !this.nonEditable) this.startEdit() - if (!this.mmsViewCtrl) return false; + if (!this.mmsViewCtrl) return false if (this.nonEditable && this.mmsViewCtrl && this.mmsViewCtrl.isEditable()) { - this.growl.warning('Cross Reference is not editable.'); + this.growl.warning('Cross Reference is not editable.') } - this.mmsViewCtrl.transcludeClicked(this.element); - e.stopPropagation(); - }); + this.mmsViewCtrl.transcludeClicked(this.element) + e.stopPropagation() + }) } public getContent = (preview?): VePromise => { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() const defaultTemplate = - '{{$ctrl.element.name}}({{ $ctrl.element.type }})'; + '{{$ctrl.element.name}}({{ $ctrl.element.type }})' const editTemplate = - '{{$ctrl.edit.element.name}}({{ $ctrl.element.type }})'; + '{{$ctrl.edit.element.name}}({{ $ctrl.element.type }})' if (preview) { - deferred.resolve('
    ' + editTemplate + '
    '); + deferred.resolve('
    ' + editTemplate + '
    ') } else { - deferred.resolve(defaultTemplate); + deferred.resolve(defaultTemplate) } - return deferred.promise; - }; + return deferred.promise + } } export const TranscludeNameComponent: VeComponentOptions = { @@ -160,6 +160,6 @@ export const TranscludeNameComponent: VeComponentOptions = { mmsSpecEditor: '?^^specEditor', }, controller: TranscludeNameController, -}; +} -veComponents.component(TranscludeNameComponent.selector, TranscludeNameComponent); +veComponents.component(TranscludeNameComponent.selector, TranscludeNameComponent) diff --git a/src/ve-components/transclusions/components/transclude-section.component.ts b/src/ve-components/transclusions/components/transclude-section.component.ts index aa29c2f6f..3ccb591f7 100644 --- a/src/ve-components/transclusions/components/transclude-section.component.ts +++ b/src/ve-components/transclusions/components/transclude-section.component.ts @@ -1,17 +1,17 @@ -import { PresentationService } from '@ve-components/presentations'; -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { DeletableTransclusion, ITransclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { editor_buttons, EditorService } from '@ve-core/editor'; -import { MathService, UtilsService, ImageService, RootScopeService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { PresentationService } from '@ve-components/presentations' +import { ExtensionService, ComponentService } from '@ve-components/services' +import { DeletableTransclusion, ITransclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { editor_buttons, EditorService } from '@ve-core/editor' +import { MathService, UtilsService, ImageService, RootScopeService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { InstanceValueObject } from '@ve-types/mms'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { InstanceValueObject } from '@ve-types/mms' /** * @ngdoc component @@ -43,11 +43,11 @@ import { InstanceValueObject } from '@ve-types/mms'; * @param {boolean=false} nonEditable can edit inline or not */ export class TranscludeSectionController extends DeletableTransclusion implements ITransclusion { - showNumbering: boolean; - noCompile: boolean = true; + showNumbering: boolean + noCompile: boolean = true //Locals - static $inject = [...DeletableTransclusion.$inject, 'PresentationService', 'RootScopeService']; + static $inject = [...DeletableTransclusion.$inject, 'PresentationService', 'RootScopeService'] constructor( $q: VeQService, @@ -88,51 +88,51 @@ export class TranscludeSectionController extends DeletableTransclusion implement buttonBarSvc, imageSvc, viewSvc - ); - this.cfType = 'name'; - this.cfTitle = ''; - this.cfKind = 'Text'; - this.checkCircular = false; + ) + this.cfType = 'name' + this.cfTitle = '' + this.cfKind = 'Text' + this.checkCircular = false } $onInit(): void { - super.$onInit(); - this.showNumbering = this.rootScopeSvc.veNumberingOn(); - this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_section`); - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons); - this.bbApi.setPermission('editor-preview', false); - this.bbApi.setPermission('editor-save-continue', false); - this.bbApi.setPermission('editor-reset', false); + super.$onInit() + this.showNumbering = this.rootScopeSvc.veNumberingOn() + this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_section`) + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons) + this.bbApi.setPermission('editor-preview', false) + this.bbApi.setPermission('editor-save-continue', false) + this.bbApi.setPermission('editor-reset', false) this.$element.on('click', (e) => { - if (this.startEdit) this.startEdit(); - if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element); - e.stopPropagation(); - }); + if (this.startEdit) this.startEdit() + if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element) + e.stopPropagation() + }) this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VENUMBERINGON, (data) => { - this.showNumbering = data; + this.showNumbering = data }) - ); + ) } $onDestroy(): void { - super.$onDestroy(); - this.buttonBarSvc.destroy(this.bbId); + super.$onDestroy() + this.buttonBarSvc.destroy(this.bbId) } public getContent = (preview?): VePromise => { if (this.element.specification && this.element.specification.operand) { const dups = this.presentationSvc.checkForDuplicateInstances( this.element.specification.operand as InstanceValueObject[] - ); + ) if (dups.length > 0) { - this.growl.warning('There are duplicates in this section, duplicates ignored!'); + this.growl.warning('There are duplicates in this section, duplicates ignored!') } } - const deferred = this.$q.defer(); - deferred.reject({ status: 200 }); //don't recompile - return deferred.promise; - }; + const deferred = this.$q.defer() + deferred.reject({ status: 200 }) //don't recompile + return deferred.promise + } } export const TranscludeSectionComponent: VeComponentOptions = { @@ -174,6 +174,6 @@ export const TranscludeSectionComponent: VeComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeSectionController, -}; +} -veComponents.component(TranscludeSectionComponent.selector, TranscludeSectionComponent); +veComponents.component(TranscludeSectionComponent.selector, TranscludeSectionComponent) diff --git a/src/ve-components/transclusions/components/transclude-val.component.ts b/src/ve-components/transclusions/components/transclude-val.component.ts index d73308d6b..e977b4da3 100644 --- a/src/ve-components/transclusions/components/transclude-val.component.ts +++ b/src/ve-components/transclusions/components/transclude-val.component.ts @@ -1,19 +1,19 @@ -import $ from 'jquery'; +import $ from 'jquery' -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { SpecTool } from '@ve-components/spec-tools'; -import { ITransclusion, ITransclusionComponentOptions, Transclusion } from '@ve-components/transclusions'; -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; -import { EditorService, editor_buttons } from '@ve-core/editor'; -import { MathService, UtilsService, ImageService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, ValueService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { SpecTool } from '@ve-components/spec-tools' +import { ITransclusion, ITransclusionComponentOptions, Transclusion } from '@ve-components/transclusions' +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' +import { EditorService, editor_buttons } from '@ve-core/editor' +import { MathService, UtilsService, ImageService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, ValueService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { PropertySpec, veComponents } from '@ve-components'; +import { PropertySpec, veComponents } from '@ve-components' -import { VeQService } from '@ve-types/angular'; -import { ValueObject } from '@ve-types/mms'; +import { VeQService } from '@ve-types/angular' +import { ValueObject } from '@ve-types/mms' /** * @ngdoc component @@ -46,18 +46,18 @@ import { ValueObject } from '@ve-types/mms'; */ export class TranscludeValController extends Transclusion implements ITransclusion { //Custom Bindings - first: boolean; + first: boolean //Custom Require - mmsSpecEditorCtrl: SpecTool; + mmsSpecEditorCtrl: SpecTool //Locals - addValueType: string = 'LiteralString'; - values: ValueObject[] = []; - editValues: ValueObject[] = []; - propertySpec: PropertySpec; - public bbApi: ButtonBarApi; - public bars: string[]; + addValueType: string = 'LiteralString' + values: ValueObject[] = [] + editValues: ValueObject[] = [] + propertySpec: PropertySpec + public bbApi: ButtonBarApi + public bars: string[] //Templates template = ` @@ -71,7 +71,7 @@ export class TranscludeValController extends Transclusion implements ITransclusi {{::value.body[0]}} {{$ctrl.first ? $ctrl.values : value}}
    -`; +` previewTemplate = `
    @@ -85,7 +85,7 @@ export class TranscludeValController extends Transclusion implements ITransclusi {{value}}
    -`; +` editTemplate = `
    @@ -170,9 +170,9 @@ export class TranscludeValController extends Transclusion implements ITransclusi
    -`; +` - static $inject = [...Transclusion.$inject, 'ValueService']; + static $inject = [...Transclusion.$inject, 'ValueService'] constructor( $q: VeQService, @@ -210,108 +210,108 @@ export class TranscludeValController extends Transclusion implements ITransclusi extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'val'; - this.cfTitle = 'Value'; - this.cfKind = 'Value'; - this.cfField = 'value'; - this.checkCircular = false; + ) + this.cfType = 'val' + this.cfTitle = 'Value' + this.cfKind = 'Value' + this.cfField = 'value' + this.checkCircular = false } $onInit(): void { - super.$onInit(); - this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_${this.cfType}`); - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons); + super.$onInit() + this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_${this.cfType}`) + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons) this.$element.on('click', (e) => { - e.stopPropagation(); - if (this.noClick) return; + e.stopPropagation() + if (this.noClick) return if (!this.nonEditable && !this.isEditing) { - this.startEdit(); + this.startEdit() } if (this.mmsViewCtrl) { - this.mmsViewCtrl.transcludeClicked(this.element); + this.mmsViewCtrl.transcludeClicked(this.element) } if (this.nonEditable && this.mmsViewCtrl && this.mmsViewCtrl.isEditable()) { - this.growl.warning('Cross Reference is not editable.'); + this.growl.warning('Cross Reference is not editable.') } - }); + }) } public getContent = (preview?): angular.IPromise => { - const deferred = this.$q.defer(); - const toCompileList: any[] = []; - let areStrings = false; - this.values = this.valueSvc.getValues(this.element); - let values = this.values; - let result = ''; + const deferred = this.$q.defer() + const toCompileList: any[] = [] + let areStrings = false + this.values = this.valueSvc.getValues(this.element) + let values = this.values + let result = '' if (preview) { - values = this.editValues; + values = this.editValues } for (let i = 0; i < values.length; i++) { if (values[i].type === 'LiteralString') { - areStrings = true; - let s = values[i].value as string; + areStrings = true + let s = values[i].value as string if (s.indexOf('

    ') === -1) { - s = s.replace('<', '<'); + s = s.replace('<', '<') } - toCompileList.push(s); + toCompileList.push(s) } else { - break; + break } } if (values.length === 0 || Object.keys(values[0]).length < 2) { - result = '(no value)'; - deferred.resolve(result); + result = '(no value)' + deferred.resolve(result) } else if (areStrings) { - let toCompile = toCompileList.join(' '); + let toCompile = toCompileList.join(' ') if (toCompile === '' || this.emptyRegex.test(toCompile)) { - result = '(no value)'; - deferred.resolve(result); + result = '(no value)' + deferred.resolve(result) } - toCompile = toCompile.replace(this.spacePeriod, '>.'); - toCompile = toCompile.replace(this.spaceSpace, '> '); - toCompile = toCompile.replace(this.spaceComma, '>,'); + toCompile = toCompile.replace(this.spacePeriod, '>.') + toCompile = toCompile.replace(this.spaceSpace, '> ') + toCompile = toCompile.replace(this.spaceComma, '>,') if (preview) { - result = '

    ' + toCompile + '
    '; + result = '
    ' + toCompile + '
    ' } else { - result = toCompile; + result = toCompile } if (!this.mmsGenerateForDiff) { - const resultHtml = $('

    ').html(result).toArray(); + const resultHtml = $('

    ').html(result).toArray() this.mathSvc.typeset(resultHtml).then( () => deferred.resolve(resultHtml), (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } else { - deferred.resolve(result); + deferred.resolve(result) } } else { if (preview) { - deferred.resolve(this.previewTemplate); + deferred.resolve(this.previewTemplate) } else { if (this.first) { - this.values = [this.values[0]]; + this.values = [this.values[0]] } - deferred.resolve(this.template); + deferred.resolve(this.template) } } - return deferred.promise; - }; + return deferred.promise + } protected recompile = (preview?: boolean): void => { if (!this.valueSvc.isValue(this.element)) { - this.$element.empty(); + this.$element.empty() //TODO: Add reason/errorMessage handling here. this.$transcludeEl = $( '' - ); - this.$element.append(this.$transcludeEl); + ) + this.$element.append(this.$transcludeEl) this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: this.element.id, @@ -319,72 +319,72 @@ export class TranscludeValController extends Transclusion implements ITransclusi type: 'transclusion', field: this.cfField, }) - ); - return; + ) + return } if (!this.nonEditable && this.mmsSpecEditorCtrl && !this.edit) { - this.startEdit(); + this.startEdit() } else { - this.defaultRecompile(preview); + this.defaultRecompile(preview) } - }; + } protected startEdit(): void { if (this.propertySpec) { super.startEdit(() => { - this.editValues = this.valueSvc.getValues(this.edit.element); - }); - return; + this.editValues = this.valueSvc.getValues(this.edit.element) + }) + return } this.valueSvc.getPropertySpec(this.element).then( (value) => { - this.propertySpec = value; + this.propertySpec = value super.startEdit(() => { - this.editValues = this.valueSvc.getValues(this.edit.element); - }); + this.editValues = this.valueSvc.getValues(this.edit.element) + }) }, (reason) => { - this.growl.error('Failed to get property spec: ' + reason.message); + this.growl.error('Failed to get property spec: ' + reason.message) } - ); + ) } public save = (e: JQuery.ClickEvent): void => { - e.stopPropagation(); - this.saveAction(false); - }; + e.stopPropagation() + this.saveAction(false) + } public saveC = (e: JQuery.ClickEvent): void => { - e.stopPropagation(); - this.saveAction(true); - }; + e.stopPropagation() + this.saveAction(true) + } public cancel = (e: JQuery.ClickEvent): void => { - e.stopPropagation(); - this.cancelAction(); - }; + e.stopPropagation() + this.cancelAction() + } public addValue(e: JQueryEventObject): void { - e.stopPropagation(); - const newVal = this.valueSvc.addValue(this.edit, this.addValueType); + e.stopPropagation() + const newVal = this.valueSvc.addValue(this.edit, this.addValueType) if (this.editValues.length == 0) { - this.editValues.push(newVal); + this.editValues.push(newVal) } } public addEnumerationValue(e: JQueryEventObject): void { - e.stopPropagation(); - const enumValue = this.valueSvc.addEnumerationValue(this.propertySpec, this.edit); - this.editValues.push(enumValue); + e.stopPropagation() + const enumValue = this.valueSvc.addEnumerationValue(this.propertySpec, this.edit) + this.editValues.push(enumValue) if (this.element.type == 'Property' || this.element.type == 'Port') { - this.edit.element.defaultValue = enumValue; + this.edit.element.defaultValue = enumValue } } public removeVal = (e: JQueryEventObject, i: number): void => { - e.stopPropagation(); - this.editValues.splice(i, 1); - }; + e.stopPropagation() + this.editValues.splice(i, 1) + } } export const TranscludeValComponent: ITransclusionComponentOptions = { @@ -410,6 +410,6 @@ export const TranscludeValComponent: ITransclusionComponentOptions = { mmsSpecEditorCtrl: '?^specEditor', }, controller: TranscludeValController, -}; +} -veComponents.component(TranscludeValComponent.selector, TranscludeValComponent); +veComponents.component(TranscludeValComponent.selector, TranscludeValComponent) diff --git a/src/ve-components/transclusions/components/transclude-value-link.component.ts b/src/ve-components/transclusions/components/transclude-value-link.component.ts index c93d890f0..82e920476 100644 --- a/src/ve-components/transclusions/components/transclude-value-link.component.ts +++ b/src/ve-components/transclusions/components/transclude-value-link.component.ts @@ -1,16 +1,16 @@ -import { ExtensionService, ComponentService } from '@ve-components/services'; -import { ITransclusion, ITransclusionComponentOptions, Transclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { MathService, UtilsService, ImageService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ExtensionService, ComponentService } from '@ve-components/services' +import { ITransclusion, ITransclusionComponentOptions, Transclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { MathService, UtilsService, ImageService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; -import { ElementObject, LiteralObject, SlotObject } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { ElementObject, LiteralObject, SlotObject } from '@ve-types/mms' /** * @ngdoc component @@ -43,9 +43,9 @@ import { ElementObject, LiteralObject, SlotObject } from '@ve-types/mms'; */ export class TranscludeNameController extends Transclusion implements ITransclusion { //Custom Bindings - mmsLinkText: string; + mmsLinkText: string - static $inject = Transclusion.$inject; + static $inject = Transclusion.$inject constructor( $q: VeQService, @@ -82,25 +82,25 @@ export class TranscludeNameController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'name'; - this.cfTitle = ''; - this.cfKind = 'Text'; - this.checkCircular = false; - this.nonEditable = true; + ) + this.cfType = 'name' + this.cfTitle = '' + this.cfKind = 'Text' + this.checkCircular = false + this.nonEditable = true } $onInit(): void { - super.$onInit(); - if (typeof this.mmsLinkText === 'undefined') this.mmsLinkText = 'Link'; + super.$onInit() + if (typeof this.mmsLinkText === 'undefined') this.mmsLinkText = 'Link' } public getContent = (): VePromise => { - let url = ''; + let url = '' if (this.element.type === 'Property') { - const value = this.element.defaultValue; + const value = this.element.defaultValue if (value && value.type === 'LiteralString') { - url = value.value as string; + url = value.value as string } } else if (this.element.type === 'Slot') { if ( @@ -108,16 +108,16 @@ export class TranscludeNameController extends Transclusion implements ITransclus this.element.value.length > 0 && (this.element.value[0] as ElementObject).type === 'LiteralString' ) { - url = ((this.element as SlotObject).value[0] as LiteralObject).value; + url = ((this.element as SlotObject).value[0] as LiteralObject).value } } if (url !== '') { - return this.$q.resolve('' + this.mmsLinkText + ''); + return this.$q.resolve('' + this.mmsLinkText + '') } else { - return this.$q.reject('Element does not provide link value.'); + return this.$q.reject('Element does not provide link value.') } - }; + } } export const TranscludeValueLinkComponent: ITransclusionComponentOptions = { @@ -140,6 +140,6 @@ export const TranscludeValueLinkComponent: ITransclusionComponentOptions = { mmsViewCtrl: '?^^view', }, controller: TranscludeNameController, -}; +} -veComponents.component(TranscludeValueLinkComponent.selector, TranscludeValueLinkComponent); +veComponents.component(TranscludeValueLinkComponent.selector, TranscludeValueLinkComponent) diff --git a/src/ve-components/transclusions/components/transclude-view.component.ts b/src/ve-components/transclusions/components/transclude-view.component.ts index c52fae9f6..0d3d86aef 100644 --- a/src/ve-components/transclusions/components/transclude-view.component.ts +++ b/src/ve-components/transclusions/components/transclude-view.component.ts @@ -1,15 +1,15 @@ -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { ITransclusion, Transclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { ImageService, MathService, UtilsService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, ViewApi } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ComponentService, ExtensionService } from '@ve-components/services' +import { ITransclusion, Transclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { ImageService, MathService, UtilsService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, ViewApi } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' /** * @ngdoc component @@ -47,11 +47,11 @@ import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; */ export class TranscludeViewController extends Transclusion implements ITransclusion { //Custom Bindings - public noTitle: boolean; + public noTitle: boolean - public viewApi: ViewApi; + public viewApi: ViewApi - static $inject = Transclusion.$inject; + static $inject = Transclusion.$inject constructor( $q: VeQService, @@ -88,29 +88,29 @@ export class TranscludeViewController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ); - this.cfType = 'view'; - this.cfTitle = 'View'; - this.cfKind = 'contents'; - this.checkCircular = true; + ) + this.cfType = 'view' + this.cfTitle = 'View' + this.cfKind = 'contents' + this.checkCircular = true } $onInit(): void { - super.$onInit(); + super.$onInit() if (typeof this.noTitle === 'undefined') { - this.noTitle = true; + this.noTitle = true } if (this.mmsViewCtrl) { - this.viewApi = this.mmsViewCtrl.mmsViewApi; + this.viewApi = this.mmsViewCtrl.mmsViewApi } } public getContent = (): VePromise => { return this.$q.resolve( '' - ); - }; + ) + } } const TranscludeViewComponent: VeComponentOptions = { @@ -132,6 +132,6 @@ const TranscludeViewComponent: VeComponentOptions = { mmsViewPresentationElemCtrl: '?^^mmsViewPresentationElem', }, controller: TranscludeViewController, -}; +} -veComponents.component(TranscludeViewComponent.selector, TranscludeViewComponent); +veComponents.component(TranscludeViewComponent.selector, TranscludeViewComponent) diff --git a/src/ve-components/transclusions/deletable-transclusion.controller.ts b/src/ve-components/transclusions/deletable-transclusion.controller.ts index 8bc86ec35..7cef9a3bc 100644 --- a/src/ve-components/transclusions/deletable-transclusion.controller.ts +++ b/src/ve-components/transclusions/deletable-transclusion.controller.ts @@ -1,17 +1,17 @@ -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { Transclusion } from '@ve-components/transclusions'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { ImageService, MathService, UtilsService } from '@ve-utils/application'; -import { EditService, EventService } from '@ve-utils/core'; -import { ElementService, ViewService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ComponentService, ExtensionService } from '@ve-components/services' +import { Transclusion } from '@ve-components/transclusions' +import { ButtonBarService } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { ImageService, MathService, UtilsService } from '@ve-utils/application' +import { EditService, EventService } from '@ve-utils/core' +import { ElementService, ViewService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { VeQService } from '@ve-types/angular'; -import { PresentTextObject } from '@ve-types/mms'; +import { VeQService } from '@ve-types/angular' +import { PresentTextObject } from '@ve-types/mms' export class DeletableTransclusion extends Transclusion { - static $inject = [...Transclusion.$inject, 'ViewService']; + static $inject = [...Transclusion.$inject, 'ViewService'] constructor( $q: VeQService, $scope: angular.IScope, @@ -48,74 +48,74 @@ export class DeletableTransclusion extends Transclusion { extensionSvc, buttonBarSvc, imageSvc - ); + ) } $onInit(): void { - super.$onInit(); + super.$onInit() if (this.mmsViewPresentationElemCtrl) { // delete is used for transclude doc, com, or section this.delete = (): void => { - this.deleteAction(); - }; - const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec(); - const presentationElem = this.mmsViewPresentationElemCtrl.getPresentationElement(); + this.deleteAction() + } + const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec() + const presentationElem = this.mmsViewPresentationElemCtrl.getPresentationElement() const isOpaque = instanceSpec.classifierIds && instanceSpec.classifierIds.length > 0 && this.schemaSvc .getMap('OPAQUE_CLASSIFIERS', this.schema) - .indexOf(instanceSpec.classifierIds[0]) >= 0; + .indexOf(instanceSpec.classifierIds[0]) >= 0 if ( !isOpaque && this.mmsElementId === (presentationElem as PresentTextObject).source && this.mmsElementId === instanceSpec.id ) { - this.isDeletable = true; + this.isDeletable = true } if (!isOpaque && this.viewSvc.isSection(instanceSpec) && this.mmsElementId === instanceSpec.id) { - this.isDeletable = true; + this.isDeletable = true } } } protected deleteAction = (): void => { if (this.elementSaving) { - this.growl.info('Please Wait...'); - return; + this.growl.info('Please Wait...') + return } - this.bbApi.toggleButtonSpinner('editor-delete'); + this.bbApi.toggleButtonSpinner('editor-delete') this.editorSvc .deleteConfirmModal(this.edit) .result.then(() => { - const section = this.mmsViewPresentationElemCtrl.getParentSection(); - const instanceVal = this.mmsViewPresentationElemCtrl.getInstanceVal(); - const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec(); - const viewOrSec = section ? section : this.view; + const section = this.mmsViewPresentationElemCtrl.getParentSection() + const instanceVal = this.mmsViewPresentationElemCtrl.getInstanceVal() + const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec() + const viewOrSec = section ? section : this.view const reqOb = { elementId: viewOrSec.id, projectId: viewOrSec._projectId, refId: viewOrSec._refId, commitId: 'latest', - }; + } this.viewSvc.removeElementFromViewOrSection(reqOb, instanceVal).then( () => { // Broadcast message to TreeCtrl: - this.eventSvc.$broadcast('presentation.deleted', instanceSpec); + this.eventSvc.$broadcast('presentation.deleted', instanceSpec) - this.eventSvc.$broadcast('content-reorder.refresh'); + this.eventSvc.$broadcast('content-reorder.refresh') - this.cleanUpAction(); + this.cleanUpAction() - this.growl.success('Remove Successful'); + this.growl.success('Remove Successful') }, (reason) => this.editorSvc.handleError(reason) - ); + ) }) .finally(() => { - this.bbApi.toggleButtonSpinner('editor-delete'); - }); - }; + this.bbApi.toggleButtonSpinner('editor-delete') + }) + } } diff --git a/src/ve-components/transclusions/index.ts b/src/ve-components/transclusions/index.ts index 073d3e937..737e64d28 100644 --- a/src/ve-components/transclusions/index.ts +++ b/src/ve-components/transclusions/index.ts @@ -1,17 +1,17 @@ // import "./transclusion.controller" -export * from './transclusion.controller'; -export * from './deletable-transclusion.controller'; -import './services/Transclusion.service'; +export * from './transclusion.controller' +export * from './deletable-transclusion.controller' +import './services/Transclusion.service' -export * from './services/Transclusion.service'; +export * from './services/Transclusion.service' -import './mms-cf.component'; +import './mms-cf.component' -import './components'; -import './mms-transclude-compatibility.component'; +import './components' +import './mms-transclude-compatibility.component' -import './modals/create-transclusion.modal'; +import './modals/create-transclusion.modal' -export * from './modals/create-transclusion.modal'; +export * from './modals/create-transclusion.modal' // import "./mmsTsDiagram.directive"; diff --git a/src/ve-components/transclusions/mms-cf.component.ts b/src/ve-components/transclusions/mms-cf.component.ts index 5ad134bf0..79638bf0d 100644 --- a/src/ve-components/transclusions/mms-cf.component.ts +++ b/src/ve-components/transclusions/mms-cf.component.ts @@ -1,12 +1,12 @@ -import angular, { IComponentController } from 'angular'; +import angular, { IComponentController } from 'angular' -import { ViewController } from '@ve-components/presentations/view.component'; -import { ExtensionService } from '@ve-components/services'; +import { ViewController } from '@ve-components/presentations/view.component' +import { ExtensionService } from '@ve-components/services' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions } from '@ve-types/angular'; -import { RequestObject } from '@ve-types/mms'; +import { VeComponentOptions } from '@ve-types/angular' +import { RequestObject } from '@ve-types/mms' /** * @ngdoc component @@ -28,31 +28,31 @@ import { RequestObject } from '@ve-types/mms'; export class CrossReferenceController implements IComponentController { //Bindings - mmsElementId: string; - mmsProjectId: string; - mmsRefId: string; - mmsCommitId: string; - mmsCfType: string; - mmsWatchId: string; - nonEditable: boolean; - mmsGenerateForDiff: boolean; - mmsAttr: string; - mmsCfLabel: boolean; + mmsElementId: string + mmsProjectId: string + mmsRefId: string + mmsCommitId: string + mmsCfType: string + mmsWatchId: string + nonEditable: boolean + mmsGenerateForDiff: boolean + mmsAttr: string + mmsCfLabel: boolean //Deps - transclusionCtrl: CrossReferenceController; - mmsViewCtrl: ViewController; + transclusionCtrl: CrossReferenceController + mmsViewCtrl: ViewController //Local - projectId: string; - refId: string; - commitId: string; - clearWatch: boolean = false; - extType: string = 'transclusion'; + projectId: string + refId: string + commitId: string + clearWatch: boolean = false + extType: string = 'transclusion' - static $inject = ['$compile', '$scope', '$element', 'ExtensionService']; + static $inject = ['$compile', '$scope', '$element', 'ExtensionService'] - protected $transcludeEl: JQuery; + protected $transcludeEl: JQuery constructor( private $compile: angular.ICompileService, @@ -62,7 +62,7 @@ export class CrossReferenceController implements IComponentController { ) {} $onInit(): void { - this.changeAction(); + this.changeAction() } //INFO this was this.getWsAndVersion @@ -71,39 +71,39 @@ export class CrossReferenceController implements IComponentController { projectId: this.projectId, refId: this.refId, commitId: this.commitId, - }; - }; + } + } private changeAction = (): void => { - let projectId = this.mmsProjectId; - let refId = this.mmsRefId; - let commitId = this.mmsCommitId; + let projectId = this.mmsProjectId + let refId = this.mmsRefId + let commitId = this.mmsCommitId if (this.transclusionCtrl) { - const cfVersion = this.transclusionCtrl.getElementOrigin(); - if (!projectId) projectId = cfVersion.projectId; - if (!refId) refId = cfVersion.refId; - if (!commitId) commitId = cfVersion.commitId; + const cfVersion = this.transclusionCtrl.getElementOrigin() + if (!projectId) projectId = cfVersion.projectId + if (!refId) refId = cfVersion.refId + if (!commitId) commitId = cfVersion.commitId } if (this.mmsViewCtrl) { - const viewVersion = this.mmsViewCtrl.getElementOrigin(); - if (!projectId) projectId = viewVersion.projectId; - if (!refId) refId = viewVersion.refId; - if (!commitId) commitId = viewVersion.commitId; + const viewVersion = this.mmsViewCtrl.getElementOrigin() + if (!projectId) projectId = viewVersion.projectId + if (!refId) refId = viewVersion.refId + if (!commitId) commitId = viewVersion.commitId } if (!projectId) { - return; + return } - this.projectId = projectId; - this.refId = refId ? refId : 'master'; - this.commitId = commitId ? commitId : 'latest'; + this.projectId = projectId + this.refId = refId ? refId : 'master' + this.commitId = commitId ? commitId : 'latest' //this.templateElementHtml = this.$element[0].innerHTML; if (this.mmsCfType) { - this.$element.empty(); - const tag = this.extensionSvc.getTagByType('transclude', this.mmsCfType); + this.$element.empty() + const tag = this.extensionSvc.getTagByType('transclude', this.mmsCfType) if (tag === 'extension-error') { this.$transcludeEl = $( '' - ); + ) } else { this.$transcludeEl = $( '<' + @@ -114,12 +114,12 @@ export class CrossReferenceController implements IComponentController { ' mms-element-id="{{$ctrl.mmsElementId}}" mms-project-id="{{$ctrl.projectId}}" mms-ref-id="{{$ctrl.refId}}" mms-commit-id="{{$ctrl.commitId}}" non-editable="$ctrl.nonEditable">' - ); + ) } - this.$element.append(this.$transcludeEl); - this.$compile(this.$transcludeEl)(this.$scope); + this.$element.append(this.$transcludeEl) + this.$compile(this.$transcludeEl)(this.$scope) } - }; + } } const MmsCfComponent: VeComponentOptions = { @@ -143,5 +143,5 @@ const MmsCfComponent: VeComponentOptions = { mmsViewCtrl: '?^^view', }, controller: CrossReferenceController, -}; -veComponents.component(MmsCfComponent.selector, MmsCfComponent); +} +veComponents.component(MmsCfComponent.selector, MmsCfComponent) diff --git a/src/ve-components/transclusions/mms-transclude-compatibility.component.ts b/src/ve-components/transclusions/mms-transclude-compatibility.component.ts index 8017f6bd0..e4ee6badc 100644 --- a/src/ve-components/transclusions/mms-transclude-compatibility.component.ts +++ b/src/ve-components/transclusions/mms-transclude-compatibility.component.ts @@ -1,13 +1,13 @@ -import { TranscludeArtComponent } from '@ve-components/transclusions/components/transclude-art.component'; -import { TranscludeComComponent } from '@ve-components/transclusions/components/transclude-com.component'; -import { TranscludeGroupDocsComponent } from '@ve-components/transclusions/components/transclude-group-docs.component'; -import { TranscludeImgComponent } from '@ve-components/transclusions/components/transclude-img.component'; -import { TranscludeValComponent } from '@ve-components/transclusions/components/transclude-val.component'; +import { TranscludeArtComponent } from '@ve-components/transclusions/components/transclude-art.component' +import { TranscludeComComponent } from '@ve-components/transclusions/components/transclude-com.component' +import { TranscludeGroupDocsComponent } from '@ve-components/transclusions/components/transclude-group-docs.component' +import { TranscludeImgComponent } from '@ve-components/transclusions/components/transclude-img.component' +import { TranscludeValComponent } from '@ve-components/transclusions/components/transclude-val.component' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { TranscludeDocComponent } from './components/transclude-doc.component'; -import { TranscludeNameComponent } from './components/transclude-name.component'; +import { TranscludeDocComponent } from './components/transclude-doc.component' +import { TranscludeNameComponent } from './components/transclude-name.component' veComponents .component('mmsTranscludeDoc', TranscludeDocComponent) @@ -16,4 +16,4 @@ veComponents .component('mmsTranscludeArt', TranscludeArtComponent) .component('mmsTranscludeCom', TranscludeComComponent) .component('mmsTranscludeGroupDocs', TranscludeGroupDocsComponent) - .component('mmsTranscludeVal', TranscludeValComponent); + .component('mmsTranscludeVal', TranscludeValComponent) diff --git a/src/ve-components/transclusions/modals/create-transclusion.modal.ts b/src/ve-components/transclusions/modals/create-transclusion.modal.ts index aaa9b6fe1..5434f3332 100644 --- a/src/ve-components/transclusions/modals/create-transclusion.modal.ts +++ b/src/ve-components/transclusions/modals/create-transclusion.modal.ts @@ -1,18 +1,18 @@ -import angular from 'angular'; +import angular from 'angular' -import { InsertionService } from '@ve-components/insertions'; -import { TransclusionService } from '@ve-components/transclusions'; -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; +import { InsertionService } from '@ve-components/insertions' +import { TransclusionService } from '@ve-components/transclusions' +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { InsertApi, InsertData, InsertResolve } from '@ve-types/components'; -import { ElementObject, ElementsResponse, TransclusionObject } from '@ve-types/mms'; -import { VeModalComponent, VeModalController } from '@ve-types/view-editor'; +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { InsertApi, InsertData, InsertResolve } from '@ve-types/components' +import { ElementObject, ElementsResponse, TransclusionObject } from '@ve-types/mms' +import { VeModalComponent, VeModalController } from '@ve-types/view-editor' export interface InsertTransclusionData extends InsertData { - viewLink: boolean; + viewLink: boolean } class CreateTransclusionModalController @@ -33,7 +33,7 @@ class CreateTransclusionModalController -`; +` protected transclusionTemplate: string = `

    @@ -48,7 +48,7 @@ class CreateTransclusionModalController  Restrict editing
    -`; +` protected targetTemplate: string = `
    @@ -63,44 +63,44 @@ class CreateTransclusionModalController
    -`; +` protected previewTemplate: string = `
    -`; +` - protected title: string = 'Insert Cross Reference'; - protected description: string; - protected searchExisting: boolean = true; - protected cf: TransclusionObject; - protected element: ElementObject; - protected requestName: boolean = false; - protected requestDocumentation: boolean = false; - protected viewLink: boolean; - protected nonEditableCheckbox: boolean = false; - protected showEditableOp: boolean = true; - protected oking: boolean; - protected cfType: string; - protected linkType: number; - protected linkText: string; + protected title: string = 'Insert Cross Reference' + protected description: string + protected searchExisting: boolean = true + protected cf: TransclusionObject + protected element: ElementObject + protected requestName: boolean = false + protected requestDocumentation: boolean = false + protected viewLink: boolean + protected nonEditableCheckbox: boolean = false + protected showEditableOp: boolean = true + protected oking: boolean + protected cfType: string + protected linkType: number + protected linkText: string - protected insertApi: InsertApi>>; - protected insertData: InsertTransclusionData; - protected inserting: boolean = false; - protected insertNew: boolean; + protected insertApi: InsertApi>> + protected insertData: InsertTransclusionData + protected inserting: boolean = false + protected insertNew: boolean - protected projectId: string; - protected refId: string; - protected orgId: string; + protected projectId: string + protected refId: string + protected orgId: string - protected $modalBody: JQuery; - protected $previewEl: JQuery = $('
    '); - private $insert: JQuery; - private $target: JQuery; - private $transclusion: JQuery; - private $link: JQuery; + protected $modalBody: JQuery + protected $previewEl: JQuery = $('
    ') + private $insert: JQuery + private $target: JQuery + private $transclusion: JQuery + private $link: JQuery - static $inject = ['$q', '$scope', '$compile', '$element', 'growl', 'TransclusionService', 'InsertionService']; + static $inject = ['$q', '$scope', '$compile', '$element', 'growl', 'TransclusionService', 'InsertionService'] constructor( private $q: VeQService, @@ -111,116 +111,116 @@ class CreateTransclusionModalController private transclusionSvc: TransclusionService, private insertionSvc: InsertionService ) { - super(); + super() } $onInit(): void { - this.projectId = this.resolve.getProjectId; - this.refId = this.resolve.getRefId ? this.resolve.getRefId : 'master'; - this.orgId = this.resolve.getOrgId ? this.resolve.getOrgId : null; + this.projectId = this.resolve.getProjectId + this.refId = this.resolve.getRefId ? this.resolve.getRefId : 'master' + this.orgId = this.resolve.getOrgId ? this.resolve.getOrgId : null - this.$modalBody = this.$element.find('.modal-body'); - this.$target = $(this.targetTemplate); - this.viewLink = this.resolve.getInsertData.viewLink; + this.$modalBody = this.$element.find('.modal-body') + this.$target = $(this.targetTemplate) + this.viewLink = this.resolve.getInsertData.viewLink this.insertApi = { resolve: (result): void => { - this.element = result; - this.insertData.selected = result; - this.selectOptions(); + this.element = result + this.insertData.selected = result + this.selectOptions() }, reject: (reason): void => { if (reason.status !== 444) { - this.growl.error(reason.message); + this.growl.error(reason.message) } - this.element = null; - this.cancel(); + this.element = null + this.cancel() }, - }; - this.insertData = this.resolve.getInsertData; - this.description = 'Begin by searching for or creating an element, then click on a result.'; + } + this.insertData = this.resolve.getInsertData + this.description = 'Begin by searching for or creating an element, then click on a result.' if (this.insertData.viewLink) { - this.description = 'Begin by searching for a view or presentation, then click on a result.'; + this.description = 'Begin by searching for a view or presentation, then click on a result.' } //Unless Explicitly overridden, don't save a new element until transclusion is created - if (typeof this.insertData.noPublish === 'undefined') this.insertData.noPublish = true; + if (typeof this.insertData.noPublish === 'undefined') this.insertData.noPublish = true this.cf = { tag: '', - }; + } } $postLink(): void { - this.insert(); + this.insert() } public choose = (): void => { - this.oking = true; + this.oking = true - let promise: VePromise; - if (this.insertData.isNew) promise = this.insertionSvc.createAction(this.element, false); - else promise = this.$q.resolve(this.element); + let promise: VePromise + if (this.insertData.isNew) promise = this.insertionSvc.createAction(this.element, false) + else promise = this.$q.resolve(this.element) promise .then( (result) => { - this.cf.element = result; + this.cf.element = result if (!this.viewLink) { this.cf.tag = this.transclusionSvc.createTransclusion( result, this.cfType, this.nonEditableCheckbox - ); + ) } else { - this.cf.tag = this.transclusionSvc.createViewLink(result, this.linkType, this.linkText); + this.cf.tag = this.transclusionSvc.createViewLink(result, this.linkType, this.linkText) } - this.modalInstance.close(this.cf); + this.modalInstance.close(this.cf) }, (reason) => { - this.growl.error('Error: ' + reason.message); + this.growl.error('Error: ' + reason.message) } ) .finally(() => { - this.oking = false; - }); - }; + this.oking = false + }) + } public cancel = (): void => { - this.modalInstance.dismiss(); - }; + this.modalInstance.dismiss() + } public insert = (): void => { - this.inserting = true; - this.$modalBody.empty(); - this.$modalBody.append(this.$target); + this.inserting = true + this.$modalBody.empty() + this.$modalBody.append(this.$target) this.$insert = $(``); - this.$modalBody.append(this.$insert); - this.$compile(this.$modalBody)(this.$scope.$new()); - }; + `) + this.$modalBody.append(this.$insert) + this.$compile(this.$modalBody)(this.$scope.$new()) + } public selectOptions = (): void => { - this.inserting = false; - this.$modalBody.empty(); - this.$modalBody.append(this.$target); + this.inserting = false + this.$modalBody.empty() + this.$modalBody.append(this.$target) if (this.viewLink) { - this.$link = $(this.linkTemplate); - this.$modalBody.append(this.$link); + this.$link = $(this.linkTemplate) + this.$modalBody.append(this.$link) } else { - this.$transclusion = $(this.transclusionTemplate); - this.$modalBody.append(this.transclusionTemplate); + this.$transclusion = $(this.transclusionTemplate) + this.$modalBody.append(this.transclusionTemplate) } - this.$compile(this.$modalBody)(this.$scope.$new()); - }; + this.$compile(this.$modalBody)(this.$scope.$new()) + } public toggleRadio = (field: string): void => { - this.cfType = field; - this.$previewEl.empty(); - this.$previewEl.append($(this.previewTemplate)); + this.cfType = field + this.$previewEl.empty() + this.$previewEl.append($(this.previewTemplate)) this.$previewEl.append( $( `
    ${this.transclusionSvc.createTransclusion( @@ -230,10 +230,10 @@ class CreateTransclusionModalController true )}
    ` ) - ); - this.$compile(this.$previewEl)(this.$scope.$new()); - this.$modalBody.append(this.$previewEl); - }; + ) + this.$compile(this.$previewEl)(this.$scope.$new()) + this.$modalBody.append(this.$previewEl) + } } // Component for inserting cross-reference @@ -266,6 +266,6 @@ const CreateTransclusionModal: VeModalComponent = { resolve: '<', }, controller: CreateTransclusionModalController, -}; +} -veComponents.component(CreateTransclusionModal.selector, CreateTransclusionModal); +veComponents.component(CreateTransclusionModal.selector, CreateTransclusionModal) diff --git a/src/ve-components/transclusions/services/Transclusion.service.ts b/src/ve-components/transclusions/services/Transclusion.service.ts index ace70693b..3abfb1ecd 100644 --- a/src/ve-components/transclusions/services/Transclusion.service.ts +++ b/src/ve-components/transclusions/services/Transclusion.service.ts @@ -1,14 +1,14 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { ApplicationService } from '@ve-utils/application'; -import { ViewService } from '@ve-utils/mms-api-client'; +import { ApplicationService } from '@ve-utils/application' +import { ViewService } from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { ElementObject, ViewObject } from '@ve-types/mms'; +import { ElementObject, ViewObject } from '@ve-types/mms' export class TransclusionService { - static $inject = ['ApplicationService', 'ViewService']; + static $inject = ['ApplicationService', 'ViewService'] constructor(private applicationSvc: ApplicationService, private viewSvc: ViewService) {} @@ -22,41 +22,41 @@ export class TransclusionService { ${addProjectandRef ? ` mms-project-id="${element._projectId}"` : ''} ${addProjectandRef ? ` mms-ref-id="${element._refId}"` : ''} ${addProjectandRef && element._commitId ? ` mms-commit-id="${element._commitId}"` : ''} - ${nonEditable ? ' non-editable="true"' : ''}>[cf:${element.name}.${cfType}]`; - }; + ${nonEditable ? ' non-editable="true"' : ''}>[cf:${element.name}.${cfType}]` + } public createViewLink = (elem: ViewObject, linkType: number, linkText?: string): string => { - let did: string; - let vid: string; - let peid: string; - const currentDoc = this.applicationSvc.getState().currentDoc; + let did: string + let vid: string + let peid: string + const currentDoc = this.applicationSvc.getState().currentDoc if (elem._relatedDocuments && elem._relatedDocuments.length > 0) { const cur = _.find(elem._relatedDocuments, { id: currentDoc, - }); + }) if (cur) { - did = currentDoc; + did = currentDoc if (cur._parentViews.length > 0) { - vid = cur._parentViews[0].id; + vid = cur._parentViews[0].id } } else { - did = elem._relatedDocuments[0].id; + did = elem._relatedDocuments[0].id if (elem._relatedDocuments[0]._parentViews.length > 0) { - vid = elem._relatedDocuments[0]._parentViews[0].id; + vid = elem._relatedDocuments[0]._parentViews[0].id } } } if (elem.type === 'InstanceSpecification') { if (this.viewSvc.isSection(elem)) { - vid = elem.id; + vid = elem.id } else { - peid = elem.id; + peid = elem.id } } else { - vid = elem.id; + vid = elem.id } - return this.getLink(elem, did, vid, peid, linkType, linkText); - }; + return this.getLink(elem, did, vid, peid, linkType, linkText) + } public getLink = ( elem: ElementObject, @@ -66,34 +66,34 @@ export class TransclusionService { linkType: number, linkText?: string ): string => { - let tag = ''; - return tag; - }; + tag += '>[cf:' + elem.name + '.vlink]
    ' + return tag + } } -veComponents.service('TransclusionService', TransclusionService); +veComponents.service('TransclusionService', TransclusionService) diff --git a/src/ve-components/transclusions/transclusion.controller.ts b/src/ve-components/transclusions/transclusion.controller.ts index 24438e341..9c30d3b98 100644 --- a/src/ve-components/transclusions/transclusion.controller.ts +++ b/src/ve-components/transclusions/transclusion.controller.ts @@ -1,58 +1,58 @@ -import { IPaneScope } from '@openmbee/pane-layout'; -import $ from 'jquery'; - -import { ViewPresentationElemController } from '@ve-components/presentations'; -import { ViewController } from '@ve-components/presentations/view.component'; -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { SpecTool } from '@ve-components/spec-tools'; -import { ButtonBarApi, ButtonBarService, IButtonBarButton } from '@ve-core/button-bar'; -import { EditorService } from '@ve-core/editor'; -import { veCoreEvents } from '@ve-core/events'; -import { ImageService, MathService, UtilsService } from '@ve-utils/application'; -import { EditObject, EditService, EventService } from '@ve-utils/core'; -import { ElementService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; -import { handleChange, onChangesCallback } from '@ve-utils/utils'; - -import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { EditorActions } from '@ve-types/core/editor'; -import { ElementObject, ElementsResponse, ViewObject } from '@ve-types/mms'; +import { IPaneScope } from '@openmbee/pane-layout' +import $ from 'jquery' + +import { ViewPresentationElemController } from '@ve-components/presentations' +import { ViewController } from '@ve-components/presentations/view.component' +import { ComponentService, ExtensionService } from '@ve-components/services' +import { SpecTool } from '@ve-components/spec-tools' +import { ButtonBarApi, ButtonBarService, IButtonBarButton } from '@ve-core/button-bar' +import { EditorService } from '@ve-core/editor' +import { veCoreEvents } from '@ve-core/events' +import { ImageService, MathService, UtilsService } from '@ve-utils/application' +import { EditObject, EditService, EventService } from '@ve-utils/core' +import { ElementService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' +import { handleChange, onChangesCallback } from '@ve-utils/utils' + +import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { EditorActions } from '@ve-types/core/editor' +import { ElementObject, ElementsResponse, ViewObject } from '@ve-types/mms' export interface ITransclusion extends angular.IComponentController { - $scope: TranscludeScope; - mmsElementId: string; - mmsProjectId: string; - mmsRefId: string; - commitId: string; - cfType: string; - edit: EditObject; - element: ElementObject; - isEditing: boolean; - inPreviewMode: boolean; - skipBroadcast: boolean; - recompileScope?: TranscludeScope; + $scope: TranscludeScope + mmsElementId: string + mmsProjectId: string + mmsRefId: string + commitId: string + cfType: string + edit: EditObject + element: ElementObject + isEditing: boolean + inPreviewMode: boolean + skipBroadcast: boolean + recompileScope?: TranscludeScope } export interface ITransclusionComponentOptions extends VeComponentOptions { - bindings: TranscludeDefaultBindings; + bindings: TranscludeDefaultBindings } interface TranscludeDefaultBindings { - mmsElementId: '@'; - mmsProjectId: '@'; - mmsRefId: '@'; - mmsCommitId: '@'; - mmsWatchId: '<'; - mmsCfLabel: '@'; - mmsGenerateForDiff?: '<'; - noClick?: '<'; - nonEditable?: '<'; - [key: string]: string; + mmsElementId: '@' + mmsProjectId: '@' + mmsRefId: '@' + mmsCommitId: '@' + mmsWatchId: '<' + mmsCfLabel: '@' + mmsGenerateForDiff?: '<' + noClick?: '<' + nonEditable?: '<' + [key: string]: string } export interface TranscludeScope extends IPaneScope { - $ctrl?: ITransclusion; - $parent: TranscludeScope; + $ctrl?: ITransclusion + $parent: TranscludeScope } /** @@ -91,81 +91,81 @@ export interface TranscludeScope extends IPaneScope { */ export class Transclusion implements ITransclusion, EditorActions { //Regex - fixPreSpanRegex: RegExp = /<\/span>\s*\s*]*>/g; - emptyRegex: RegExp = /^\s*$/; - spacePeriod: RegExp = />(?:\s| )\./g; - spaceSpace: RegExp = />(?:\s| )(?:\s| )/g; - spaceComma: RegExp = />(?:\s| ),/g; + fixPreSpanRegex: RegExp = /<\/span>\s*\s*]*>/g + emptyRegex: RegExp = /^\s*$/ + spacePeriod: RegExp = />(?:\s| )\./g + spaceSpace: RegExp = />(?:\s| )(?:\s| )/g + spaceComma: RegExp = />(?:\s| ),/g //Required Controllers - protected mmsViewCtrl: ViewController; - protected mmsViewPresentationElemCtrl: ViewPresentationElemController; - protected mmsSpecEditorCtrl: SpecTool; + protected mmsViewCtrl: ViewController + protected mmsViewPresentationElemCtrl: ViewPresentationElemController + protected mmsSpecEditorCtrl: SpecTool //Bindings - mmsElementId: string; - mmsProjectId: string; - mmsRefId: string; - mmsCommitId: string; - mmsWatchId: string; - nonEditable: boolean; - noClick: boolean; - mmsCfLabel: boolean; - mmsGenerateForDiff: boolean; - mmsCallback: () => void; + mmsElementId: string + mmsProjectId: string + mmsRefId: string + mmsCommitId: string + mmsWatchId: string + nonEditable: boolean + noClick: boolean + mmsCfLabel: boolean + mmsGenerateForDiff: boolean + mmsCallback: () => void //Customizers - public cfType: string; - protected cfTitle: string; - protected cfField: 'name' | 'value' | 'documentation'; - protected cfKind: string; - protected checkCircular: boolean; - protected noCompile: boolean = false; + public cfType: string + protected cfTitle: string + protected cfField: 'name' | 'value' | 'documentation' + protected cfKind: string + protected checkCircular: boolean + protected noCompile: boolean = false //Locals - protected isDeletable: boolean; - protected editable: () => boolean = () => false; + protected isDeletable: boolean + protected editable: () => boolean = () => false - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] - public commitId: string; - protected projectId: string; - protected refId: string; + public commitId: string + protected projectId: string + protected refId: string - public isEditing: boolean = false; - public inPreviewMode: boolean = false; - public elementSaving: boolean = false; - public editLoading: boolean = false; - public skipBroadcast: boolean; + public isEditing: boolean = false + public inPreviewMode: boolean = false + public elementSaving: boolean = false + public editLoading: boolean = false + public skipBroadcast: boolean - public editKey: string | string[]; - public edit: EditObject; - public element: ElementObject; - protected type: string = ''; - protected editorType: string; + public editKey: string | string[] + public edit: EditObject + public element: ElementObject + protected type: string = '' + protected editorType: string - public view: ViewObject; + public view: ViewObject // public instanceSpec: InstanceSpecObject // public instanceVal: InstanceValueObject // protected presentationElem: PresentationInstanceObject | ElementObject - protected panelTitle: string; - protected panelType: string; + protected panelTitle: string + protected panelType: string - protected $transcludeEl: JQuery; + protected $transcludeEl: JQuery // Possible templates to manage api functions - protected template: string; - protected editTemplate: string; - protected previewTemplate: string; + protected template: string + protected editTemplate: string + protected previewTemplate: string - public bbApi: ButtonBarApi; - public bbId: string; - public bars: string[]; - protected buttons: IButtonBarButton[] = []; + public bbApi: ButtonBarApi + public bbId: string + public bars: string[] + protected buttons: IButtonBarButton[] = [] - public schema = 'cameo'; + public schema = 'cameo' //Default Toolbar Api /* eslint-disable @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars */ @@ -194,7 +194,7 @@ export class Transclusion implements ITransclusion, EditorActions { 'ExtensionService', 'ButtonBarService', 'ImageService', - ]; + ] constructor( public $q: VeQService, @@ -216,60 +216,60 @@ export class Transclusion implements ITransclusion, EditorActions { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) if ((this.$element.prop('tagName') as string).includes('mms')) { this.growl.warning( 'mmsTransclude(*) Syntax is deprecated and will be removed in a future version' + 'please see the release documentation for further details' - ); + ) } if (this.mmsViewCtrl) { - this.view = this.mmsViewCtrl.getView(); - this.editable = this.mmsViewCtrl.isEditable; + this.view = this.mmsViewCtrl.getView() + this.editable = this.mmsViewCtrl.isEditable } if (this.mmsSpecEditorCtrl && this.mmsSpecEditorCtrl.specApi.elementId === this.mmsElementId) { - this.editable = (): boolean => this.mmsSpecEditorCtrl.specSvc.editable; + this.editable = (): boolean => this.mmsSpecEditorCtrl.specSvc.editable } //if (this.editTemplate) { this.save = (e: JQuery.ClickEvent): void => { - if (e) e.stopPropagation(); - this.saveAction(false); - }; + if (e) e.stopPropagation() + this.saveAction(false) + } this.saveC = (): void => { - this.saveAction(true); - }; + this.saveAction(true) + } this.cancel = (e?: JQuery.ClickEvent): void => { - if (e) e.stopPropagation(); - this.cancelAction(); - }; + if (e) e.stopPropagation() + this.cancelAction() + } this.reset = (e?: JQuery.ClickEvent): void => { - if (e) e.stopPropagation(); - this.cleanUpAction(true); - }; + if (e) e.stopPropagation() + this.cleanUpAction(true) + } this.preview = (): void => { - this.previewAction(); - }; + this.previewAction() + } //} } $onDestroy(): void { - this.eventSvc.destroy(this.subs); + this.eventSvc.destroy(this.subs) } $onChanges(onChangesObj: angular.IOnChangesObject): void { - this.watch(onChangesObj); - handleChange(onChangesObj, 'mmsElementId', this.changeAction); - handleChange(onChangesObj, 'mmsRefId', this.changeAction); - handleChange(onChangesObj, 'mmsCommitId', this.changeAction); + this.watch(onChangesObj) + handleChange(onChangesObj, 'mmsElementId', this.changeAction) + handleChange(onChangesObj, 'mmsRefId', this.changeAction) + handleChange(onChangesObj, 'mmsCommitId', this.changeAction) } $postLink(): void { - this.changeAction(this.mmsElementId, '', false); + this.changeAction(this.mmsElementId, '', false) } /** @@ -282,7 +282,7 @@ export class Transclusion implements ITransclusion, EditorActions { */ protected watch: (onChangesObj: angular.IOnChangesObject) => void = () => { /* Implement custom watch logic here */ - }; + } /** * @name veComponents/Transclusion#config @@ -291,113 +291,113 @@ export class Transclusion implements ITransclusion, EditorActions { */ protected destroy: () => void = () => { /* Implement Custom Destroy Logic Here */ - }; + } public getContent = (preview?: boolean): VePromise => { - return this.$q.resolve('Not Yet Implemented'); - }; + return this.$q.resolve('Not Yet Implemented') + } protected recompile = (preview?: boolean): void => { - this.defaultRecompile(preview); - }; + this.defaultRecompile(preview) + } public defaultRecompile = (preview?: boolean): void => { this.getContent(preview).then( (result) => { - this.$element.empty(); - this.$transcludeEl = $(result); - this.$element.append(this.$transcludeEl); - this.$compile(this.$transcludeEl)(this.$scope.$new()); + this.$element.empty() + this.$transcludeEl = $(result) + this.$element.append(this.$transcludeEl) + this.$compile(this.$transcludeEl)(this.$scope.$new()) if (this.mmsViewCtrl) { - this.mmsViewCtrl.elementTranscluded(this.element, this.type); + this.mmsViewCtrl.elementTranscluded(this.element, this.type) } $(this.$element) .find('img') .each((index, element) => { - this.imageSvc.fixImgSrc($(element)); - }); + this.imageSvc.fixImgSrc($(element)) + }) }, (reason) => { if (reason.status !== 200) { - this.growl.error(`Transclusion Error: ${reason.message}`); + this.growl.error(`Transclusion Error: ${reason.message}`) } } - ); - }; + ) + } protected changeAction: onChangesCallback = (newVal, oldVal, firstChange) => { if (!newVal || !this.mmsProjectId || firstChange || newVal === oldVal) { - return; + return } if (this.checkCircular) { if (this.componentSvc.hasCircularReference(this, this.mmsElementId, 'doc')) { - this.$element.html('Circular Reference!'); - return; + this.$element.html('Circular Reference!') + return } } - this.projectId = this.mmsProjectId; - this.refId = this.mmsRefId ? this.mmsRefId : 'master'; - this.commitId = this.mmsCommitId ? this.mmsCommitId : 'latest'; + this.projectId = this.mmsProjectId + this.refId = this.mmsRefId ? this.mmsRefId : 'master' + this.commitId = this.mmsCommitId ? this.mmsCommitId : 'latest' if (!this.noCompile) { - this.$element.html('(loading...)'); + this.$element.html('(loading...)') } - this.$element.addClass('isLoading'); + this.$element.addClass('isLoading') const reqOb = { elementId: this.mmsElementId, projectId: this.projectId, refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - }; + } this.elementSvc .getElement(reqOb, 1, false) .then( (data) => { - this.element = data; + this.element = data if (!this.panelTitle) { - this.panelTitle = this.element.name + ' ' + this.cfTitle; - this.panelType = this.cfKind; + this.panelTitle = this.element.name + ' ' + this.cfTitle + this.panelType = this.cfKind } if (this.commitId === 'latest') { this.subs.push( this.eventSvc.$on( 'element.updated', (data: { element: ElementObject; continueEdit: boolean }) => { - const elementOb = data.element; - const continueEdit = data.continueEdit; + const elementOb = data.element + const continueEdit = data.continueEdit if ( elementOb.id === this.element.id && elementOb._projectId === this.element._projectId && elementOb._refId === this.element._refId ) { - this.element = elementOb; - this.cleanUpAction(continueEdit); + this.element = elementOb + this.cleanUpAction(continueEdit) } } ) - ); + ) } if (this.editTemplate) { this._reopenUnsaved().then( (data) => { - if (data) this.startEdit(); - else this.recompile(); + if (data) this.startEdit() + else this.recompile() }, () => { - this.recompile(); + this.recompile() } - ); + ) } else { - this.recompile(); + this.recompile() } }, (reason) => { - this.$element.empty(); + this.$element.empty() //TODO: Add reason/errorMessage handling here. this.$transcludeEl = $( '' - ); - this.$element.append(this.$transcludeEl); + ) + this.$element.append(this.$transcludeEl) this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: reqOb, @@ -405,24 +405,24 @@ export class Transclusion implements ITransclusion, EditorActions { type: 'transclusion', field: this.cfField, }) - ); + ) } ) .finally(() => { - this.$element.removeClass('isLoading'); - if (this.mmsCallback) this.mmsCallback(); - }); - }; + this.$element.removeClass('isLoading') + if (this.mmsCallback) this.mmsCallback() + }) + } protected bbInit = (api: ButtonBarApi): void => { - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-preview', this)); - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-save', this)); - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-save-continue', this)); - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-cancel', this)); - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-reset', this)); - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-delete', this)); - api.setPermission('editor-delete', this.isDeletable); - }; + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-preview', this)) + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-save', this)) + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-save-continue', this)) + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-cancel', this)) + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-reset', this)) + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-delete', this)) + api.setPermission('editor-delete', this.isDeletable) + } /** * @name Utils#reopenUnsavedElts * called by transcludes when users have unsaved edits, leaves that view, and comes back to that view. @@ -437,15 +437,15 @@ export class Transclusion implements ITransclusion, EditorActions { */ private _reopenUnsaved = (): VePromise => { return new this.$q((resolve, reject) => { - const key = this.elementSvc.getEditElementKey(this.element); - const editOb = this.editSvc.get(key); + const key = this.elementSvc.getEditElementKey(this.element) + const editOb = this.editSvc.get(key) if (!editOb || this.commitId !== 'latest') { - resolve(false); + resolve(false) } else { - this.editorSvc.hasEdits(editOb, this.cfField).then(resolve, reject); + this.editorSvc.hasEdits(editOb, this.cfField).then(resolve, reject) } - }); - }; + }) + } /** * @name Transclusion#startEdit * called by transcludes to add the editor frame @@ -469,105 +469,105 @@ export class Transclusion implements ITransclusion, EditorActions { .openEdit(this.element) .then( (data) => { - this.isEditing = true; + this.isEditing = true if (this.inPreviewMode) { - this.editorSvc.clearAutosave(this.editKey, this.cfField); - this.inPreviewMode = false; + this.editorSvc.clearAutosave(this.editKey, this.cfField) + this.inPreviewMode = false } - this.edit = data; - this.editKey = data.key; + this.edit = data + this.editKey = data.key if (cb) { - cb(); + cb() } if (this.editTemplate) { - this.$element.empty(); - this.$transcludeEl = $(this.editTemplate); + this.$element.empty() + this.$transcludeEl = $(this.editTemplate) - this.$element.append(this.$transcludeEl); - this.$compile(this.$transcludeEl)(this.$scope.$new()); + this.$element.append(this.$transcludeEl) + this.$compile(this.$transcludeEl)(this.$scope.$new()) } if (!this.skipBroadcast) { // Broadcast message for the toolCtrl: - this.eventSvc.$broadcast('editor.open', this.edit); + this.eventSvc.$broadcast('editor.open', this.edit) } else { - this.skipBroadcast = false; + this.skipBroadcast = false } - this.editorSvc.scrollToElement(this.$element); + this.editorSvc.scrollToElement(this.$element) }, (reason: VePromiseReason>) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } ) .finally(() => { - this.editLoading = false; - }); + this.editLoading = false + }) this.elementSvc.isCacheOutdated(this.element).then( (data) => { if (data.status && data.server._modified > data.cache._modified) { - this.growl.warning('This element has been updated on the server'); + this.growl.warning('This element has been updated on the server') } }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) } } protected saveAction(continueEdit?: boolean): void { if (this.elementSaving) { - this.growl.info('Please Wait...'); - return; + this.growl.info('Please Wait...') + return } // this.editSvc.clearAutosave(ctrl.element._projectId + ctrl.element._refId + ctrl.element.id, ctrl.edit.type) if (this.bbApi) { if (!continueEdit) { - this.bbApi.toggleButtonSpinner('editor-save'); + this.bbApi.toggleButtonSpinner('editor-save') } else { - this.bbApi.toggleButtonSpinner('editor-save-continue'); + this.bbApi.toggleButtonSpinner('editor-save-continue') } } - this.elementSaving = true; + this.elementSaving = true this.editorSvc .save(this.editKey, continueEdit) .then( (data) => { - this.inPreviewMode = false; - this.element = data; + this.inPreviewMode = false + this.element = data // do not call here since it's called by element.updated event listener //this.cleanUpAction(continueEdit) //scrollToElement(domElement); }, (reason) => { - this.editorSvc.handleError(reason); + this.editorSvc.handleError(reason) } ) .finally(() => { - this.elementSaving = false; + this.elementSaving = false if (this.bbApi) { if (!continueEdit) { - this.bbApi.toggleButtonSpinner('editor-save'); + this.bbApi.toggleButtonSpinner('editor-save') } else { - this.bbApi.toggleButtonSpinner('editor-save-continue'); + this.bbApi.toggleButtonSpinner('editor-save-continue') } } - }); + }) } protected cancelAction(): void { if (this.elementSaving) { - this.growl.info('Please Wait...'); - return; + this.growl.info('Please Wait...') + return } if (this.bbApi) { - this.bbApi.toggleButtonSpinner('editor-cancel'); + this.bbApi.toggleButtonSpinner('editor-cancel') } // const cancelFn: () => VePromise = (): VePromise => { // if (ctrl.editorApi && ctrl.editorApi.cancel) { @@ -585,7 +585,7 @@ export class Transclusion implements ITransclusion, EditorActions { this.editorSvc.handleError({ message: 'Problem Saving from Editor', type: 'warning', - }); + }) } this.editorSvc.hasEdits(this.edit, this.cfField).then( (hasEdits) => { @@ -593,86 +593,86 @@ export class Transclusion implements ITransclusion, EditorActions { this.editorSvc.deleteEditModal(this.edit).result.then( (result) => { if (result) { - this.cleanUpAction(); + this.cleanUpAction() } }, () => { //Do Nothing if user wants to keep working } - ); + ) } else { - this.cleanUpAction(); + this.cleanUpAction() } }, () => { - this.cleanUpAction(); + this.cleanUpAction() } - ); + ) }, () => { this.editorSvc.handleError({ message: 'Error Saving from Editor; Please Retry', type: 'error', - }); + }) } ) .finally(() => { if (this.bbApi) { - this.bbApi.toggleButtonSpinner('editor-cancel'); + this.bbApi.toggleButtonSpinner('editor-cancel') } - }); + }) } public previewAction(): void { if (this.elementSaving) { - this.growl.info('Please Wait...'); - return; + this.growl.info('Please Wait...') + return } if (this.edit && this.isEditing) { this.editorSvc .hasEdits(this.edit) .then((hasEdits) => { if (hasEdits && !this.inPreviewMode) { - this.skipBroadcast = true; //preview next click to go into edit mode from broadcasting - this.inPreviewMode = true; - this.recompile(true); + this.skipBroadcast = true //preview next click to go into edit mode from broadcasting + this.inPreviewMode = true + this.recompile(true) } else { //nothing has changed, cancel instead of preview - this.growl.info('No edits found! Preview cancelled'); - this.cleanUpAction(); + this.growl.info('No edits found! Preview cancelled') + this.cleanUpAction() } }) .finally(() => { - this.isEditing = false; - this.editorSvc.scrollToElement(this.$element); - }); + this.isEditing = false + this.editorSvc.scrollToElement(this.$element) + }) } } public cleanUpAction = (continueEdit?: boolean): void => { - this.editorSvc.cleanUpEdit(this.editKey); - this.isEditing = false; + this.editorSvc.cleanUpEdit(this.editKey) + this.isEditing = false if (!continueEdit) { - this.eventSvc.$broadcast('editor.close', this.edit); - this.recompile(); + this.eventSvc.$broadcast('editor.close', this.edit) + this.recompile() } else { - this.startEdit(); + this.startEdit() } // scrollToElement(domElement); - }; + } //Transclusion API protected hasHtml = (s: string): boolean => { - return this.componentSvc.hasHtml(s); - }; + return this.componentSvc.hasHtml(s) + } protected cleanupVal(obj: { value: string | number }): void { - obj.value = parseInt(obj.value as string); + obj.value = parseInt(obj.value as string) } protected addHtml(e: JQueryEventObject, value: { value: string | number }): void { - e.stopPropagation(); - value.value = `

    ${value.value}

    `; + e.stopPropagation() + value.value = `

    ${value.value}

    ` } } diff --git a/src/ve-components/trees/components/index.ts b/src/ve-components/trees/components/index.ts index 60e4d42b8..5986fae2c 100644 --- a/src/ve-components/trees/components/index.ts +++ b/src/ve-components/trees/components/index.ts @@ -1,6 +1,6 @@ -import './tree-of-contents.component'; -import './tree-of-equations.component'; -import './tree-of-figures.component'; -import './tree-of-tables.component'; -import './tree-of-documents.component'; -import './tree-of-favorites.component'; +import './tree-of-contents.component' +import './tree-of-equations.component' +import './tree-of-figures.component' +import './tree-of-tables.component' +import './tree-of-documents.component' +import './tree-of-favorites.component' diff --git a/src/ve-components/trees/components/tree-of-contents.component.ts b/src/ve-components/trees/components/tree-of-contents.component.ts index 41825415d..1a2f71d35 100644 --- a/src/ve-components/trees/components/tree-of-contents.component.ts +++ b/src/ve-components/trees/components/tree-of-contents.component.ts @@ -1,12 +1,12 @@ -import angular from 'angular'; +import angular from 'angular' -import { TreeService, TreeController } from '@ve-components/trees'; -import { RootScopeService, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { TreeService, TreeController } from '@ve-components/trees' +import { RootScopeService, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VeQService } from '@ve-types/angular' export class TreeOfContentsController extends TreeController { constructor( @@ -20,20 +20,20 @@ export class TreeOfContentsController extends TreeController { rootScopeSvc: RootScopeService, eventSvc: EventService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) - this.types = ['view', 'section']; - this.id = 'tree-of-contents'; + this.types = ['view', 'section'] + this.id = 'tree-of-contents' } protected setPeVisibility = (): void => { - this.types.length = 0; + this.types.length = 0 if (this.showPe) { - this.types.push('all'); + this.types.push('all') } else { - this.types = ['view', 'section']; + this.types = ['view', 'section'] } - }; + } } const TreeOfContentsComponent: VeComponentOptions = { @@ -70,6 +70,6 @@ const TreeOfContentsComponent: VeComponentOptions = { showPe: '<', }, controller: TreeOfContentsController, -}; +} -veComponents.component(TreeOfContentsComponent.selector, TreeOfContentsComponent); +veComponents.component(TreeOfContentsComponent.selector, TreeOfContentsComponent) diff --git a/src/ve-components/trees/components/tree-of-documents.component.ts b/src/ve-components/trees/components/tree-of-documents.component.ts index dab4808ad..32c14c958 100644 --- a/src/ve-components/trees/components/tree-of-documents.component.ts +++ b/src/ve-components/trees/components/tree-of-documents.component.ts @@ -1,14 +1,14 @@ -import { TreeService, TreeController } from '@ve-components/trees'; -import { ApplicationService, RootScopeService, UserSettingsObject, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { TreeService, TreeController } from '@ve-components/trees' +import { ApplicationService, RootScopeService, UserSettingsObject, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { TreeBranch } from '@ve-types/tree'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { TreeBranch } from '@ve-types/tree' class TreeOfDocumentsController extends TreeController { - static $inject = [...TreeController.$inject, 'ApplicationService']; + static $inject = [...TreeController.$inject, 'ApplicationService'] constructor( $q: VeQService, $scope: angular.IScope, @@ -21,48 +21,48 @@ class TreeOfDocumentsController extends TreeController { eventSvc: EventService, private applicationSvc: ApplicationService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); - this.id = 'tree-of-documents'; - this.types = ['group']; + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) + this.id = 'tree-of-documents' + this.types = ['group'] } protected preConfig = (): void => { - this.types = ['group']; + this.types = ['group'] if (this.treeSvc.treeApi.refType === 'Branch') { - this.types.push('view'); + this.types.push('view') } else { - this.types.push('snapshot'); + this.types.push('snapshot') } - }; + } toggleFavorite($event: JQuery.ClickEvent, branch: TreeBranch): void { - $event.stopPropagation(); - let promise: VePromise; + $event.stopPropagation() + let promise: VePromise if (!branch.favorite) { promise = this.applicationSvc.addPins( this.applicationSvc.getState().user, this.treeSvc.treeApi.projectId, this.treeSvc.treeApi.refId, [branch.data.id] - ); + ) } else { promise = this.applicationSvc.removePins( this.applicationSvc.getState().user, this.treeSvc.treeApi.projectId, this.treeSvc.treeApi.refId, [branch.data.id] - ); + ) } promise.then( () => { - branch.favorite = !branch.favorite; - this.eventSvc.$broadcast(TreeService.events.RELOAD, 'table-of-favorites'); + branch.favorite = !branch.favorite + this.eventSvc.$broadcast(TreeService.events.RELOAD, 'table-of-favorites') }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) } } @@ -101,6 +101,6 @@ const TreeOfDocumentsComponent: VeComponentOptions = { buttonId: '@', }, controller: TreeOfDocumentsController, -}; +} -veComponents.component(TreeOfDocumentsComponent.selector, TreeOfDocumentsComponent); +veComponents.component(TreeOfDocumentsComponent.selector, TreeOfDocumentsComponent) diff --git a/src/ve-components/trees/components/tree-of-equations.component.ts b/src/ve-components/trees/components/tree-of-equations.component.ts index ff952cad4..b6051aecb 100644 --- a/src/ve-components/trees/components/tree-of-equations.component.ts +++ b/src/ve-components/trees/components/tree-of-equations.component.ts @@ -1,12 +1,12 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees'; -import { RootScopeService, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees' +import { RootScopeService, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeQService } from '@ve-types/angular'; +import { VeQService } from '@ve-types/angular' class TreeOfEquationsController extends TreeController { constructor( @@ -20,15 +20,15 @@ class TreeOfEquationsController extends TreeController { rootScopeSvc: RootScopeService, eventSvc: EventService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); - this.id = 'table-of-equations'; - this.types = ['equation']; - this.title = 'Table of Equations'; + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) + this.id = 'table-of-equations' + this.types = ['equation'] + this.title = 'Table of Equations' } } -const TreeOfEquationsComponent = _.cloneDeep(TreeOfAnyComponent); -TreeOfEquationsComponent.selector = 'treeOfEquations'; -TreeOfEquationsComponent.controller = TreeOfEquationsController; +const TreeOfEquationsComponent = _.cloneDeep(TreeOfAnyComponent) +TreeOfEquationsComponent.selector = 'treeOfEquations' +TreeOfEquationsComponent.controller = TreeOfEquationsController -veComponents.component(TreeOfEquationsComponent.selector, TreeOfEquationsComponent); +veComponents.component(TreeOfEquationsComponent.selector, TreeOfEquationsComponent) diff --git a/src/ve-components/trees/components/tree-of-favorites.component.ts b/src/ve-components/trees/components/tree-of-favorites.component.ts index c2286cd73..0e022f204 100644 --- a/src/ve-components/trees/components/tree-of-favorites.component.ts +++ b/src/ve-components/trees/components/tree-of-favorites.component.ts @@ -1,19 +1,19 @@ -import { TreeService, TreeController } from '@ve-components/trees'; -import { ApplicationService, RootScopeService, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { TreeService, TreeController } from '@ve-components/trees' +import { ApplicationService, RootScopeService, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VeQService } from '@ve-types/angular' class TreeOfFavoritesController extends TreeController { public icons = { iconExpand: 'fa-solid fa-caret-down fa-lg fa-fw', iconCollapse: 'fa-solid fa-caret-right fa-lg fa-fw', iconDefault: 'fa-solid fa-star fa-fw', - }; + } - static $inject = [...TreeController.$inject, 'ApplicationService']; + static $inject = [...TreeController.$inject, 'ApplicationService'] constructor( $q: VeQService, @@ -27,10 +27,10 @@ class TreeOfFavoritesController extends TreeController { eventSvc: EventService, private applicationSvc: ApplicationService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); - this.id = 'table-of-favorites'; - this.types = ['favorite']; - this.title = 'Table of Favorites'; + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) + this.id = 'table-of-favorites' + this.types = ['favorite'] + this.title = 'Table of Favorites' } } @@ -64,6 +64,6 @@ const TreeOfFavoritesComponent: VeComponentOptions = { showPe: '<', }, controller: TreeOfFavoritesController, -}; +} -veComponents.component(TreeOfFavoritesComponent.selector, TreeOfFavoritesComponent); +veComponents.component(TreeOfFavoritesComponent.selector, TreeOfFavoritesComponent) diff --git a/src/ve-components/trees/components/tree-of-figures.component.ts b/src/ve-components/trees/components/tree-of-figures.component.ts index 62dfae2f2..d2eb45dcc 100644 --- a/src/ve-components/trees/components/tree-of-figures.component.ts +++ b/src/ve-components/trees/components/tree-of-figures.component.ts @@ -1,12 +1,12 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees'; -import { RootScopeService, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees' +import { RootScopeService, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeQService } from '@ve-types/angular'; +import { VeQService } from '@ve-types/angular' class TreeOfFiguresController extends TreeController { constructor( @@ -20,15 +20,15 @@ class TreeOfFiguresController extends TreeController { rootScopeSvc: RootScopeService, eventSvc: EventService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); - this.id = 'table-of-figures'; - this.types = ['figure']; - this.title = 'Table of Figures'; + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) + this.id = 'table-of-figures' + this.types = ['figure'] + this.title = 'Table of Figures' } } -const TreeOfFiguresComponent = _.cloneDeep(TreeOfAnyComponent); -TreeOfFiguresComponent.selector = 'treeOfFigures'; -TreeOfFiguresComponent.controller = TreeOfFiguresController; +const TreeOfFiguresComponent = _.cloneDeep(TreeOfAnyComponent) +TreeOfFiguresComponent.selector = 'treeOfFigures' +TreeOfFiguresComponent.controller = TreeOfFiguresController -veComponents.component(TreeOfFiguresComponent.selector, TreeOfFiguresComponent); +veComponents.component(TreeOfFiguresComponent.selector, TreeOfFiguresComponent) diff --git a/src/ve-components/trees/components/tree-of-tables.component.ts b/src/ve-components/trees/components/tree-of-tables.component.ts index 9c6882df8..e80636054 100644 --- a/src/ve-components/trees/components/tree-of-tables.component.ts +++ b/src/ve-components/trees/components/tree-of-tables.component.ts @@ -1,12 +1,12 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees'; -import { RootScopeService, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees' +import { RootScopeService, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeQService } from '@ve-types/angular'; +import { VeQService } from '@ve-types/angular' class TreeOfTablesController extends TreeController { constructor( @@ -20,15 +20,15 @@ class TreeOfTablesController extends TreeController { rootScopeSvc: RootScopeService, eventSvc: EventService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); - this.id = 'table-of-tables'; - this.types = ['table']; - this.title = 'Table of Tables'; + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) + this.id = 'table-of-tables' + this.types = ['table'] + this.title = 'Table of Tables' } } -const TreeOfTablesComponent = _.cloneDeep(TreeOfAnyComponent); -TreeOfTablesComponent.selector = 'treeOfTables'; -TreeOfTablesComponent.controller = TreeOfTablesController; +const TreeOfTablesComponent = _.cloneDeep(TreeOfAnyComponent) +TreeOfTablesComponent.selector = 'treeOfTables' +TreeOfTablesComponent.controller = TreeOfTablesController -veComponents.component(TreeOfTablesComponent.selector, TreeOfTablesComponent); +veComponents.component(TreeOfTablesComponent.selector, TreeOfTablesComponent) diff --git a/src/ve-components/trees/index.ts b/src/ve-components/trees/index.ts index 7d143f562..9a9576cd1 100644 --- a/src/ve-components/trees/index.ts +++ b/src/ve-components/trees/index.ts @@ -1,8 +1,8 @@ -import './services/Tree.service'; +import './services/Tree.service' -export * from './services/Tree.service'; +export * from './services/Tree.service' -export * from './tree.controller'; +export * from './tree.controller' //Components -import './mms-trees.component'; -import './components'; +import './mms-trees.component' +import './components' diff --git a/src/ve-components/trees/mms-trees.component.ts b/src/ve-components/trees/mms-trees.component.ts index 9f2899ec1..978300896 100644 --- a/src/ve-components/trees/mms-trees.component.ts +++ b/src/ve-components/trees/mms-trees.component.ts @@ -1,25 +1,25 @@ -import angular, { IComponentController } from 'angular'; -import _ from 'lodash'; -import Rx from 'rx-lite'; - -import { veAppEvents } from '@ve-app/events'; -import { InsertViewData } from '@ve-components/insertions/components/insert-view.component'; -import { ExtensionService } from '@ve-components/services'; -import { TreeService } from '@ve-components/trees/services/Tree.service'; -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; -import { veCoreEvents } from '@ve-core/events'; -import { IToolBarButton, ToolbarService } from '@ve-core/toolbar'; -import { RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { ApiService, PermissionsService, ViewService } from '@ve-utils/mms-api-client'; - -import { veComponents } from '@ve-components'; - -import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { InsertResolveFn } from '@ve-types/components'; -import { ElementObject, InstanceSpecObject, ViewObject } from '@ve-types/mms'; -import { TreeBranch } from '@ve-types/tree'; -import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; +import angular, { IComponentController } from 'angular' +import _ from 'lodash' +import Rx from 'rx-lite' + +import { veAppEvents } from '@ve-app/events' +import { InsertViewData } from '@ve-components/insertions/components/insert-view.component' +import { ExtensionService } from '@ve-components/services' +import { TreeService } from '@ve-components/trees/services/Tree.service' +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' +import { veCoreEvents } from '@ve-core/events' +import { IToolBarButton, ToolbarService } from '@ve-core/toolbar' +import { RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { ApiService, PermissionsService, ViewService } from '@ve-utils/mms-api-client' + +import { veComponents } from '@ve-components' + +import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { InsertResolveFn } from '@ve-types/components' +import { ElementObject, InstanceSpecObject, ViewObject } from '@ve-types/mms' +import { TreeBranch } from '@ve-types/tree' +import { VeModalService, VeModalSettings } from '@ve-types/view-editor' /** * @ngdoc directive @@ -90,35 +90,35 @@ import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; class TreesController implements IComponentController { //Bindings - toolbarId: string = 'toolbar'; - buttonId: string; + toolbarId: string = 'toolbar' + buttonId: string //Local - documentId: string; - viewId: string; - projectId: string; - refId: string; - commitId: string; + documentId: string + viewId: string + projectId: string + refId: string + commitId: string - subs: Rx.IDisposable[]; + subs: Rx.IDisposable[] - currentTree: string; - currentTitle: string; + currentTree: string + currentTitle: string show: { - [key: string]: { tree: boolean; pe: boolean }; - } = {}; + [key: string]: { tree: boolean; pe: boolean } + } = {} - protected errorType: string; + protected errorType: string - private insertData: InsertViewData; + private insertData: InsertViewData - public filterInputPlaceholder: string; - public treeSearch: string; - private spin: boolean = true; + public filterInputPlaceholder: string + public treeSearch: string + private spin: boolean = true - protected $trees: JQuery; + protected $trees: JQuery - bbApi: ButtonBarApi; + bbApi: ButtonBarApi static $inject = [ '$compile', @@ -138,7 +138,7 @@ class TreesController implements IComponentController { 'TreeService', 'ExtensionService', 'ButtonBarService', - ]; + ] constructor( private $compile: angular.ICompileService, @@ -161,10 +161,10 @@ class TreesController implements IComponentController { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) - this.buttonId = this.buttonId ? this.buttonId : 'tree-button-bar'; - this.toolbarId = this.toolbarId ? this.toolbarId : 'toolbar'; + this.buttonId = this.buttonId ? this.buttonId : 'tree-button-bar' + this.toolbarId = this.toolbarId ? this.toolbarId : 'toolbar' // Initialize button-bar event listeners this.subs.push( @@ -174,124 +174,124 @@ class TreesController implements IComponentController { case 'tree-expand': { this.treeSvc.expandAll().then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree); + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree) }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); - break; + ) + break } case 'tree-collapse': { this.treeSvc.collapseAll().then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree); + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree) }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); - break; + ) + break } case 'tree-add-document': { this.insert('Document').catch((reason) => { - this.growl.error(reason.message); - }); - break; + this.growl.error(reason.message) + }) + break } case 'tree-add-view': { this.insert('View').catch((reason) => { - this.growl.error(reason.message); - }); - break; + this.growl.error(reason.message) + }) + break } case 'tree-add-group': { this.insert('Group').catch((reason) => { - this.growl.error(reason.message); - }); - break; + this.growl.error(reason.message) + }) + break } case 'tree-show-pe': { - this.show[_.camelCase(this.currentTree)].pe = !this.show[_.camelCase(this.currentTree)].pe; - break; + this.show[_.camelCase(this.currentTree)].pe = !this.show[_.camelCase(this.currentTree)].pe + break } } } - data.$event.stopPropagation(); + data.$event.stopPropagation() }), this.eventSvc.$on('presentation.deleted', (data) => { this.treeSvc.getBranch(data).then( (branch) => { if (branch) { this.treeSvc.removeBranch(branch).catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) } }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); + ) }) - ); + ) } $onDestroy(): void { - this.eventSvc.$destroy(this.subs); + this.eventSvc.$destroy(this.subs) } $postLink(): void { - this.$trees = $('#trees'); + this.$trees = $('#trees') //Listen for Toolbar Clicked Subject - this.subs.push(this.eventSvc.binding(this.toolbarId, this.changeTree)); + this.subs.push(this.eventSvc.binding(this.toolbarId, this.changeTree)) } insert(itemType: string): VePromise { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() this.insertData = { insertType: 'view', type: itemType, newViewAggr: 'shared', parentBranch: null, seenViewIds: this.treeSvc.seenViewIds, - }; - const branch = this.treeSvc.getSelectedBranch(); + } + const branch = this.treeSvc.getSelectedBranch() if (itemType === 'Document') { this.addDocument(branch).then( (result) => { - this.insertModal(result); - deferred.resolve(); + this.insertModal(result) + deferred.resolve() }, (reason: VePromiseReason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } else if (itemType === 'Group') { this.addGroup(branch).then( (result) => { - this.insertModal(result); - deferred.resolve(); + this.insertModal(result) + deferred.resolve() }, (reason: VePromiseReason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } else if (itemType === 'View') { this.addView(branch).then( (result) => { - this.insertModal(result); - deferred.resolve(); + this.insertModal(result) + deferred.resolve() }, (reason: VePromiseReason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } else { - deferred.reject('Add Item of Type ' + itemType + ' is not supported'); + deferred.reject('Add Item of Type ' + itemType + ' is not supported') } - return deferred.promise; + return deferred.promise } insertModal = (branchType: string): void => { @@ -299,24 +299,24 @@ class TreesController implements IComponentController { component: 'insertElementModal', resolve: { getInsertData: () => { - return this.insertData; + return this.insertData }, getProjectId: () => { - return this.treeSvc.treeApi.projectId; + return this.treeSvc.treeApi.projectId }, getRefId: () => { - return this.treeSvc.treeApi.refId; + return this.treeSvc.treeApi.refId }, getOrgId: () => { - return this.treeSvc.treeApi.orgId; + return this.treeSvc.treeApi.orgId }, }, - }; - const instance = this.$uibModal.open, ElementObject>(settings); + } + const instance = this.$uibModal.open, ElementObject>(settings) instance.result.then( (result) => { if (!this.rootScopeSvc.veEditMode()) { - this.eventSvc.$broadcast('show-edits', true); + this.eventSvc.$broadcast('show-edits', true) } const newbranch: TreeBranch = { label: result.name, @@ -324,35 +324,35 @@ class TreesController implements IComponentController { data: result, children: [], aggr: '', - }; - const top = this.insertData.type === 'Group'; + } + const top = this.insertData.type === 'Group' const addToFullDocView = (node: TreeBranch, curSection: string, prevSysml: string): string => { - let lastChild = prevSysml; + let lastChild = prevSysml if (node.children) { - let num = 1; + let num = 1 for (let i = 0; i < node.children.length; i++) { - const cNode = node.children[i]; + const cNode = node.children[i] const data: veAppEvents.viewAddedData = { vId: cNode.data.id, curSec: `${curSection}.${num}`, prevSibId: lastChild, - }; - this.eventSvc.$broadcast('view.added', data); - lastChild = addToFullDocView(cNode, `${curSection}.${num}`, cNode.data.id); - num = num + 1; + } + this.eventSvc.$broadcast('view.added', data) + lastChild = addToFullDocView(cNode, `${curSection}.${num}`, cNode.data.id) + num = num + 1 } } - return lastChild; - }; + return lastChild + } this.treeSvc.addBranch(this.insertData.parentBranch, newbranch, top).then( () => { if (this.insertData.type === 'View') { - this.treeSvc.viewId2node[result.id] = newbranch; - this.treeSvc.seenViewIds[result.id] = newbranch; - newbranch.aggr = this.insertData.newViewAggr; + this.treeSvc.viewId2node[result.id] = newbranch + this.treeSvc.seenViewIds[result.id] = newbranch + newbranch.aggr = this.insertData.newViewAggr const curNum = this.insertData.parentBranch.children[this.insertData.parentBranch.children.length - 1] - .data._veNumber; + .data._veNumber this.treeSvc .getPrevBranch(newbranch, ['view']) .then( @@ -372,28 +372,28 @@ class TreesController implements IComponentController { (node) => { // handle full doc mode if (this.rootScopeSvc.veFullDocMode()) { - addToFullDocView(node as TreeBranch, curNum, newbranch.data.id); + addToFullDocView(node as TreeBranch, curNum, newbranch.data.id) } - this.addViewSectionsRecursivelyForNode(node as TreeBranch); + this.addViewSectionsRecursivelyForNode(node as TreeBranch) }, (reason) => { this.growl.error( 'Error processing new child views: ' + reason.message - ); + ) } - ); + ) if (!this.rootScopeSvc.veFullDocMode()) { this.eventSvc.$broadcast('view.added', { vId: result.id, curSec: curNum, prevSibId: prevBranch.data.id, - }); + }) } else { this.eventSvc.$broadcast('view.added', { vId: result.id, curSec: curNum, prevSibId: prevBranch.data.id, - }); + }) } }, (reason) => { @@ -402,151 +402,151 @@ class TreesController implements IComponentController { vId: result.id, curSec: curNum, prevSibId: this.insertData.parentBranch.data.id, - }); + }) } else { - this.growl.error('Error adding item to tree: ' + reason.message); + this.growl.error('Error adding item to tree: ' + reason.message) } } ) .finally(() => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree); - }); + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree) + }) } else { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree); + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree) } }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); + ) }, (reason) => { if (reason && reason.status !== 444) { - this.growl.warning(`Error adding View: ${reason.message}`); + this.growl.warning(`Error adding View: ${reason.message}`) } else { this.growl.info('View Insert Cancelled', { ttl: 1000, - }); + }) } } - ); - }; + ) + } addDocument(branch: TreeBranch): VePromise { if (!branch) { - this.insertData.parentBranch = null; - branch = null; + this.insertData.parentBranch = null + branch = null } else if (branch.type !== 'group') { return this.$q.reject({ message: 'Select a group to add document under', - }); + }) } else { - this.insertData.parentBranch = branch; + this.insertData.parentBranch = branch } - return this.$q.resolve('view'); + return this.$q.resolve('view') } addGroup(branch: TreeBranch): VePromise { if (branch && branch.type === 'group') { - this.insertData.parentBranch = branch; + this.insertData.parentBranch = branch } else if (branch && branch.type !== 'group') { return this.$q.reject({ message: 'Select a group to add group under', - }); + }) } else { - this.insertData.parentBranch = null; + this.insertData.parentBranch = null // Always create group at root level if the selected branch is not a group branch - branch = null; + branch = null } - return this.$q.resolve('group'); + return this.$q.resolve('group') } addView(branch: TreeBranch): VePromise { if (!branch) { return this.$q.reject({ message: 'Add View Error: Select parent view first', - }); + }) } else if (branch.type === 'section') { return this.$q.reject({ message: 'Add View Error: Cannot add a child view to a section', - }); + }) } else if (branch.aggr === 'none') { return this.$q.reject({ message: 'Add View Error: Cannot add a child view to a non-owned and non-shared view.', - }); + }) } - this.insertData.parentBranch = branch; - return this.$q.resolve('view'); + this.insertData.parentBranch = branch + return this.$q.resolve('view') } addViewSections = (view: ViewObject): void => { - const node = this.treeSvc.viewId2node[view.id]; + const node = this.treeSvc.viewId2node[view.id] this.treeSvc.addSectionElements(view, node, node).catch((reason) => { - this.growl.error('Error adding view sections:' + reason.message); - }); - }; + this.growl.error('Error adding view sections:' + reason.message) + }) + } addViewSectionsRecursivelyForNode = (node: TreeBranch): void => { - this.addViewSections(node.data); + this.addViewSections(node.data) for (let i = 0; i < node.children.length; i++) { if (node.children[i].type === 'view') { - this.addViewSectionsRecursivelyForNode(node.children[i]); + this.addViewSectionsRecursivelyForNode(node.children[i]) } } - }; + } userClicksPane = (): void => { this.treeSvc.selectBranch().catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); - }; + this.growl.error(TreeService.treeError(reason)) + }) + } private changeTree = (data: { id: string; category?: string; title?: string }): void => { if (!this.currentTree) { - this.currentTree = ''; + this.currentTree = '' } if (this.currentTree !== data.id) { if (this.currentTree !== '') { - this.show[_.camelCase(this.currentTree)].tree = false; + this.show[_.camelCase(this.currentTree)].tree = false } - this.currentTree = data.id; - const inspect: IToolBarButton = this.toolbarSvc.getToolbarButton(data.id); + this.currentTree = data.id + const inspect: IToolBarButton = this.toolbarSvc.getToolbarButton(data.id) if (!data.category) { - data.category = inspect.category; + data.category = inspect.category } - this.currentTitle = data.title ? data.title : inspect.tooltip; + this.currentTitle = data.title ? data.title : inspect.tooltip if (!this.show.hasOwnProperty(_.camelCase(data.id))) { - this.startTree(data.id); - this.show[_.camelCase(data.id)] = { tree: true, pe: false }; + this.startTree(data.id) + this.show[_.camelCase(data.id)] = { tree: true, pe: false } } else { - this.eventSvc.$broadcast(TreeService.events.RELOAD, data.id); - this.show[_.camelCase(data.id)].tree = true; + this.eventSvc.$broadcast(TreeService.events.RELOAD, data.id) + this.show[_.camelCase(data.id)].tree = true } } - }; + } private startTree = (id: string): void => { - const tag = this.extensionSvc.getTagByType('treeOf', id); - const treeId: string = _.camelCase(id); - const newTree: JQuery = $(`
    `); + const tag = this.extensionSvc.getTagByType('treeOf', id) + const treeId: string = _.camelCase(id) + const newTree: JQuery = $(`
    `) if (tag === 'extensionError') { - this.errorType = this.currentTree.replace('tree-of-', ''); + this.errorType = this.currentTree.replace('tree-of-', '') newTree.append( '' - ); + ) } else { newTree.append( `<${tag} show-pe="$ctrl.show.${treeId}.pe" toolbar-id="${this.toolbarId}" button-id="${this.buttonId}"}>` - ); + ) } - this.$trees.append(newTree); + this.$trees.append(newTree) - this.$compile(newTree)(this.$scope); - }; + this.$compile(newTree)(this.$scope) + } } const TreesComponent: VeComponentOptions = { @@ -570,6 +570,6 @@ const TreesComponent: VeComponentOptions = { buttonId: '@', }, controller: TreesController, -}; +} -veComponents.component(TreesComponent.selector, TreesComponent); +veComponents.component(TreesComponent.selector, TreesComponent) diff --git a/src/ve-components/trees/services/Tree.service.ts b/src/ve-components/trees/services/Tree.service.ts index 4e291449f..2c9f5a99c 100644 --- a/src/ve-components/trees/services/Tree.service.ts +++ b/src/ve-components/trees/services/Tree.service.ts @@ -1,12 +1,12 @@ -import { IQResolveReject } from 'angular'; +import { IQResolveReject } from 'angular' -import { ApplicationService, RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; +import { ApplicationService, RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' import { ElementObject, ElementsRequest, @@ -15,42 +15,42 @@ import { ValueObject, ViewInstanceSpec, ViewObject, -} from '@ve-types/mms'; -import { TreeApi, TreeBranch, TreeRow } from '@ve-types/tree'; +} from '@ve-types/mms' +import { TreeApi, TreeBranch, TreeRow } from '@ve-types/tree' export class TreeService { - public selectedBranch: TreeBranch = null; - public branch2viewNumber: { [key: string]: string } = {}; - public defaultIcon: string = 'fa-solid fa-file fa-fw'; + public selectedBranch: TreeBranch = null + public branch2viewNumber: { [key: string]: string } = {} + public defaultIcon: string = 'fa-solid fa-file fa-fw' public defaultIcons = { iconExpand: 'fa-solid fa-caret-down fa-lg fa-fw', iconCollapse: 'fa-solid fa-caret-right fa-lg fa-fw', iconDefault: 'fa-solid fa-file fa-fw', - }; + } - public defaultSectionTypes = ['group', 'view', 'section']; + public defaultSectionTypes = ['group', 'view', 'section'] - public loading: boolean; + public loading: boolean - private inProgress: VePromise = null; - private treeData: TreeBranch[] = []; + private inProgress: VePromise = null + private treeData: TreeBranch[] = [] - public viewId2node: { [key: string]: TreeBranch } = {}; - public seenViewIds: { [key: string]: TreeBranch } = {}; + public viewId2node: { [key: string]: TreeBranch } = {} + public seenViewIds: { [key: string]: TreeBranch } = {} - public processedRoot: string = ''; - public processedFocus: string = ''; + public processedRoot: string = '' + public processedFocus: string = '' - public treeApi: TreeApi; - private rows: { [id: string]: TreeRow[] } = {}; + public treeApi: TreeApi + private rows: { [id: string]: TreeRow[] } = {} - treeEditable: boolean; + treeEditable: boolean static events = { UPDATED: 'tree.updated', RELOAD: 'tree.reload', FILTER: 'tree.filter', - }; + } static MetaTypes = [ 'tag', @@ -72,7 +72,7 @@ export class TreeService { 'view-composite', 'view-shared', 'view-none', - ]; + ] static $inject = [ '$q', @@ -85,7 +85,7 @@ export class TreeService { 'ApplicationService', 'RootScopeService', 'EventService', - ]; + ] constructor( private $q: VeQService, @@ -101,12 +101,12 @@ export class TreeService { ) {} public isTreeReady = (): boolean => { - return this.treeData.length > 0; - }; + return this.treeData.length > 0 + } public getTreeData = (): TreeBranch[] => { - return this.treeData; - }; + return this.treeData + } // // public setTreeApi = (treeOptions: TreeOptions): void => { // this.treeOptions = treeOptions @@ -131,118 +131,118 @@ export class TreeService { level2_Func: (elementOb: ElementObject, node: TreeBranch) => VePromise ): VePromise => { return new this.$q((resolve, reject) => { - const rootNodes: TreeBranch[] = []; - const data2Node: { [key: string]: TreeBranch } = {}; + const rootNodes: TreeBranch[] = [] + const data2Node: { [key: string]: TreeBranch } = {} // create flat map for each element elementObs.forEach((elementOb) => { - const elementId: string = elementOb[idKey] as string; + const elementId: string = elementOb[idKey] as string data2Node[elementId] = { label: elementOb.name, type: type, data: elementOb, children: [], loading: true, - }; - }); + } + }) // make second pass to associate data to parent nodes elementObs.forEach((elementOb) => { - const parentId: string = elementOb[parentKey] as string; - const elementId: string = elementOb[idKey] as string; + const parentId: string = elementOb[parentKey] as string + const elementId: string = elementOb[idKey] as string // If there's an element in data2Node whose key matches the 'parent' value in the array element // add the array element to the children array of the matched data2Node element if (parentId && data2Node[parentId]) { - data2Node[parentId].children.push(data2Node[elementId]); + data2Node[parentId].children.push(data2Node[elementId]) } else { // If there's not an element in data2Node whose key matches the 'parent' value in the array element // it's a "root node" and so it should be pushed to the root nodes array along with its children - rootNodes.push(data2Node[elementId]); + rootNodes.push(data2Node[elementId]) } - }); + }) //apply level2 function if available if (level2_Func) { elementObs.forEach((elementOb) => { - const elementId: string = elementOb[idKey] as string; - const level1_parentNode = data2Node[elementId]; - level2_Func(elementOb, level1_parentNode).catch(reject); - }); + const elementId: string = elementOb[idKey] as string + const level1_parentNode = data2Node[elementId] + level2_Func(elementOb, level1_parentNode).catch(reject) + }) } const sortFunction = (a: TreeBranch, b: TreeBranch): number => { if (a.children.length > 1) { - a.children.sort(sortFunction); + a.children.sort(sortFunction) } if (b.children.length > 1) { - b.children.sort(sortFunction); + b.children.sort(sortFunction) } if (a.label.toLowerCase() < b.label.toLowerCase()) { - return -1; + return -1 } if (a.label.toLowerCase() > b.label.toLowerCase()) { - return 1; + return 1 } - return 0; - }; - rootNodes.sort(sortFunction); - resolve(rootNodes); - }); - }; + return 0 + } + rootNodes.sort(sortFunction) + resolve(rootNodes) + }) + } private getTypeIcon = (type: string): string => { - let t = type; - if (!t) t = 'unknown'; - t = t.toLowerCase(); + let t = type + if (!t) t = 'unknown' + t = t.toLowerCase() switch (t) { case 'tag': - return 'fa-solid fa-tag'; + return 'fa-solid fa-tag' case 'connector': - return 'fa-solid fa-expand'; + return 'fa-solid fa-expand' case 'dependency': - return 'fa-solid fa-long-arrow-right'; + return 'fa-solid fa-long-arrow-right' case 'directedrelationship': - return 'fa-solid fa-arrow-right-long'; + return 'fa-solid fa-arrow-right-long' case 'element': - return 'fa-solid fa-border-top-left'; + return 'fa-solid fa-border-top-left' case 'property': - return 'fa-solid fa-circle'; + return 'fa-solid fa-circle' case 'generalization': - return 'fa-solid fa-arrow-up-long'; + return 'fa-solid fa-arrow-up-long' case 'package': - return 'fa-regular fa-folder'; + return 'fa-regular fa-folder' case 'section': - return 'section-icon'; //"fa-file-o"; + return 'section-icon' //"fa-file-o"; case 'group': - return 'fa-solid fa-folder'; + return 'fa-solid fa-folder' case 'snapshot': - return 'fa-solid fa-camera'; + return 'fa-solid fa-camera' case 'view': - return 'fa-solid fa-file'; + return 'fa-solid fa-file' case 'view-composite': - return 'fa-solid fa-file'; + return 'fa-solid fa-file' case 'view-shared': - return 'fa-regular fa-file'; + return 'fa-regular fa-file' case 'view-none': - return 'fa-regular fa-file'; + return 'fa-regular fa-file' case 'branch': - return 'fa-solid fa-code-branch'; + return 'fa-solid fa-code-branch' case 'table': - return 'fa-solid fa-table'; + return 'fa-solid fa-table' case 'figure': - return 'fa-regular fa-image'; + return 'fa-regular fa-image' case 'diagram': - return 'fa-solid fa-diagram-project'; + return 'fa-solid fa-diagram-project' case 'equation': - return 'fa-solid fa-superscript'; + return 'fa-solid fa-superscript' default: - return 'fa-solid fa-file-circle-question'; + return 'fa-solid fa-file-circle-question' } - }; + } static treeError(reason: VePromiseReason): string { - return 'Error refreshing tree: ' + reason.message; + return 'Error refreshing tree: ' + reason.message } /** @@ -252,9 +252,9 @@ export class TreeService { public expandAll = (): VePromise => { return this.forEachBranch((b) => { //scope.expandCallback({ branch: b }); - b.expanded = true; - }, false); - }; + b.expanded = true + }, false) + } /** * @name TreeApi#collapseAll * self-explanatory @@ -262,28 +262,28 @@ export class TreeService { public collapseAll = (excludeBranch?: TreeBranch): VePromise => { return this.forEachBranch( (b, level) => { - b.expanded = false; + b.expanded = false }, false, excludeBranch - ); - }; + ) + } /** * Gets the first branch in the tree * @returns {TreeBranch} */ public getFirstBranch = (): TreeBranch => { - if (this.treeData.length > 0) return this.treeData[0]; - }; + if (this.treeData.length > 0) return this.treeData[0] + } /** * Selects the first branch in the tree */ public selectFirstBranch = (): VePromise => { - const b = this.getFirstBranch(); - return this.selectBranch(b); - }; + const b = this.getFirstBranch() + return this.selectBranch(b) + } /** * @name TreeApi#getSelectedBranch @@ -292,25 +292,25 @@ export class TreeService { * @return {Object} current selected branch */ public getSelectedBranch = (): TreeBranch => { - return this.selectedBranch; - }; + return this.selectedBranch + } public clearSelectedBranch = (): void => { - if (this.selectedBranch) this.selectedBranch.selected = false; - this.selectedBranch = null; - }; + if (this.selectedBranch) this.selectedBranch.selected = false + this.selectedBranch = null + } public getChildren = (b: TreeBranch): TreeBranch[] => { - return b.children; - }; + return b.children + } public selectParentBranch = (branch: TreeBranch): VePromise => { return this.$q((resolve, reject) => { this.getParent(branch).then((p) => { - this.selectBranch(p).then(resolve, reject); - }, reject); - }); - }; + this.selectBranch(p).then(resolve, reject) + }, reject) + }) + } /** * @ngdoc function @@ -323,20 +323,20 @@ export class TreeService { */ public addBranch = (parent: TreeBranch, new_branch: TreeBranch, top: boolean): VePromise => { if (parent) { - if (top) parent.children.unshift(new_branch); - else parent.children.push(new_branch); - parent.expanded = true; + if (top) parent.children.unshift(new_branch) + else parent.children.push(new_branch) + parent.expanded = true } else { - if (top) this.treeData.unshift(new_branch); - else this.treeData.push(new_branch); + if (top) this.treeData.unshift(new_branch) + else this.treeData.push(new_branch) } - return this.$q.resolve(); - }; + return this.$q.resolve() + } public removeBranch = (branch: TreeBranch): VePromise => { - this._removeBranch(branch, false); - return this.$q.resolve(); - }; + this._removeBranch(branch, false) + return this.$q.resolve() + } /** * @name TreeApi#expandBranch @@ -345,13 +345,13 @@ export class TreeService { * @param {TreeBranch} branch branch to expand */ public expandBranch = (branch: TreeBranch): VePromise => { - if (!branch) branch = this.getSelectedBranch(); + if (!branch) branch = this.getSelectedBranch() if (branch) { //scope.expandCallback({ branch: b }); - branch.expanded = true; + branch.expanded = true } - return this.$q.resolve(); - }; + return this.$q.resolve() + } /** * @name TreeApi#closeBranch @@ -360,13 +360,13 @@ export class TreeService { * @param {TreeBranch} branch branch to close */ public closeBranch = (branch: TreeBranch): VePromise => { - if (!branch) branch = this.getSelectedBranch(); + if (!branch) branch = this.getSelectedBranch() if (branch) { //scope.expandCallback({ branch: b }); - branch.expanded = false; + branch.expanded = false } - return this.$q.resolve(); - }; + return this.$q.resolve() + } /** * Gets siblings of specified branch @@ -377,14 +377,14 @@ export class TreeService { return this.$q((resolve) => { this.getParent(branch).then( (p) => { - resolve(p.children); + resolve(p.children) }, () => { - resolve(this.treeData); + resolve(this.treeData) } - ); - }); - }; + ) + }) + } /** * Gets numerically next sibling (if exists) of specified branch @@ -395,13 +395,13 @@ export class TreeService { return this.$q((resolve, reject) => { this.getSiblings(branch).then((siblings) => { if (Array.isArray(siblings)) { - const i = siblings.indexOf(branch); - if (i < siblings.length - 1) resolve(siblings[i + 1]); - else reject(); + const i = siblings.indexOf(branch) + if (i < siblings.length - 1) resolve(siblings[i + 1]) + else reject() } - }, reject); - }); - }; + }, reject) + }) + } /** * Gets numerically previous sibling (if exists) of specified branch @@ -412,13 +412,13 @@ export class TreeService { return this.$q((resolve, reject) => { this.getSiblings(branch).then((siblings) => { if (Array.isArray(siblings)) { - const i = siblings.indexOf(branch); - if (i > 0) resolve(siblings[i - 1]); - else reject(); + const i = siblings.indexOf(branch) + if (i > 0) resolve(siblings[i - 1]) + else reject() } - }, reject); - }); - }; + }, reject) + }) + } /** * Gets the first child of the specified branch (if exists) @@ -426,9 +426,9 @@ export class TreeService { * @returns {TreeBranch} */ public getFirstChild = (branch: TreeBranch): TreeBranch => { - if (!branch) branch = this.selectedBranch; - if (branch && branch.children && branch.children.length > 0) return branch.children[0]; - }; + if (!branch) branch = this.selectedBranch + if (branch && branch.children && branch.children.length > 0) return branch.children[0] + } /** * Traverse up/down the tree to find the next closest sibling to the specified branch @@ -439,16 +439,16 @@ export class TreeService { return this.$q((resolve, reject) => { this.getNextSibling(branch).then( (b) => { - resolve(b); + resolve(b) }, () => { this.getParent(branch).then((next) => { - this.getClosestAncestorNextSibling(next).then(resolve, reject); - }, reject); + this.getClosestAncestorNextSibling(next).then(resolve, reject) + }, reject) } - ); - }); - }; + ) + }) + } /** * Gets the next branch in the tree @@ -459,24 +459,24 @@ export class TreeService { */ public getNextBranch = (branch: TreeBranch, types?: string[]): VePromise => { return this.$q((resolve, reject) => { - if (!branch) branch = this.selectedBranch; + if (!branch) branch = this.selectedBranch if (branch) { - const next = this.getFirstChild(branch); + const next = this.getFirstChild(branch) if (next) { - if (types && types.includes(next.type)) resolve(next); - else this.getNextBranch(next, types).then(resolve, reject); + if (types && types.includes(next.type)) resolve(next) + else this.getNextBranch(next, types).then(resolve, reject) } else { this.getClosestAncestorNextSibling(branch).then((nextSib) => { if (types && !types.includes(nextSib.type)) { - this.getNextBranch(nextSib, types).then(resolve, reject); + this.getNextBranch(nextSib, types).then(resolve, reject) } else { - resolve(nextSib); + resolve(nextSib) } - }, reject); + }, reject) } - } else reject({ message: 'No More branches!', status: 200 }); - }); - }; + } else reject({ message: 'No More branches!', status: 200 }) + }) + } /** * Returns the last descendant branch of the specified branch @@ -486,14 +486,14 @@ export class TreeService { public lastDescendant = (branch: TreeBranch): VePromise => { return new this.$q((resolve, reject) => { if (branch) { - if (branch.children.length === 0) resolve(branch); - const last = branch.children[branch.children.length - 1]; - return this.lastDescendant(last).then(resolve, reject); + if (branch.children.length === 0) resolve(branch) + const last = branch.children[branch.children.length - 1] + return this.lastDescendant(last).then(resolve, reject) } else { - reject({ message: 'No branch Specified', status: 401 }); + reject({ message: 'No branch Specified', status: 401 }) } - }); - }; + }) + } /** * Get's the branch previous to the branch specified @@ -508,18 +508,18 @@ export class TreeService { (prevSibling) => { this.lastDescendant(prevSibling).then((last) => { if (types && !types.includes(last.type)) { - this.getPrevBranch(last, types).then(resolve, reject); + this.getPrevBranch(last, types).then(resolve, reject) } else { - resolve(last); + resolve(last) } - }, reject); + }, reject) }, () => { - this.getParent(branch).then(resolve, reject); + this.getParent(branch).then(resolve, reject) } - ); - }); - }; + ) + }) + } /** * @name TreeApi#refresh @@ -527,12 +527,12 @@ export class TreeService { */ public refresh = (treeData: TreeBranch[]): VePromise => { if (this.inProgress == null) { - this.inProgress = this.$q.resolve(); + this.inProgress = this.$q.resolve() } - this.treeData.length = 0; - this.treeData.push(...treeData); - return this._onTreeDataChange(); - }; + this.treeData.length = 0 + this.treeData.push(...treeData) + return this._onTreeDataChange() + } /** * @name TreeApi#getBranch @@ -542,11 +542,11 @@ export class TreeService { return new this.$q((resolve, reject) => { this.forEachBranch((b) => { if (b.data.id === data.id) { - resolve(b); + resolve(b) } - }).catch(reject); - }); - }; + }).catch(reject) + }) + } /** * Runs the specified callback function on each branch in the tree as specified by treeData @@ -559,37 +559,37 @@ export class TreeService { excludeBranch?: TreeBranch ): VePromise => { return new this.$q((resolve, reject) => { - const flag = false; + const flag = false const run = (branch: TreeBranch, level: number, flag: boolean): void => { - if (flag && !useFlag) resolve(); - func(branch, flag); + if (flag && !useFlag) resolve() + func(branch, flag) if (branch.children) { for (let i = 0; i < branch.children.length; i++) { - run(branch.children[i], level + 1, flag); + run(branch.children[i], level + 1, flag) } } - }; + } const rootLevelBranches = excludeBranch ? this.treeData.filter((branch) => { - return branch !== excludeBranch; + return branch !== excludeBranch }) - : this.treeData; + : this.treeData rootLevelBranches.forEach((branch) => { - run(branch, 1, flag); - }); - if (!useFlag) resolve(); - else reject({ message: 'No valid Branches found', status: 401 }); - }); - }; + run(branch, 1, flag) + }) + if (!useFlag) resolve() + else reject({ message: 'No valid Branches found', status: 401 }) + }) + } private _removeBranch = (branch: TreeBranch, singleBranch: boolean): void => { this.getParent(branch).then( (parentBranch) => { for (let i = 0; i < parentBranch.children.length; i++) { if (parentBranch.children[i].uid === branch.uid) { - parentBranch.children.splice(i, 1); + parentBranch.children.splice(i, 1) if (singleBranch) { - break; + break } } } @@ -597,13 +597,13 @@ export class TreeService { () => { for (let j = 0; j < this.treeData.length; j++) { if (this.treeData[j].uid === branch.uid) { - this.treeData.splice(j, 1); - break; + this.treeData.splice(j, 1) + break } } } - ); - }; + ) + } /** * Gets branch parent @@ -612,26 +612,26 @@ export class TreeService { */ public getParent = (child: TreeBranch): VePromise => { return new this.$q((resolve, reject) => { - if (child === null) reject({ message: 'No child specified!', status: 404 }); + if (child === null) reject({ message: 'No child specified!', status: 404 }) if (child.parent_uid) { this.forEachBranch((b) => { if (b.uid === child.parent_uid) { - resolve(b); + resolve(b) } - }).catch(reject); + }).catch(reject) } else { - reject({ message: 'Already at root!', status: 200 }); + reject({ message: 'Already at root!', status: 200 }) } - }); - }; + }) + } public expandPathToSelectedBranch = (): VePromise => { if (this.selectedBranch) { - return this.expandAllParents(this.selectedBranch); + return this.expandAllParents(this.selectedBranch) } - return this.$q.resolve(); - }; + return this.$q.resolve() + } public forAllAncestors = ( child: TreeBranch, @@ -641,24 +641,24 @@ export class TreeService { this.getParent(child).then( (parent) => { fn(parent).then(() => { - this.forAllAncestors(parent, fn).then(resolve, reject); - }, reject); + this.forAllAncestors(parent, fn).then(resolve, reject) + }, reject) }, () => { - resolve(); + resolve() } - ); - }); - }; + ) + }) + } public expandAllParents = (child: TreeBranch): VePromise => { return this.forAllAncestors(child, (b) => { if (b.expandable && !b.expanded) { - return this.expandBranch(b); + return this.expandBranch(b) } - return this.$q.resolve(); - }); - }; + return this.$q.resolve() + }) + } /** * Select a branch @@ -666,37 +666,37 @@ export class TreeService { * @param noClick */ public selectBranch = (branch?: TreeBranch, noClick?): VePromise => { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() if (!branch) { - if (this.selectedBranch) this.selectedBranch.selected = false; - this.clearSelectedBranch(); - return this.$q.resolve(); + if (this.selectedBranch) this.selectedBranch.selected = false + this.clearSelectedBranch() + return this.$q.resolve() } if (branch !== this.selectedBranch) { - if (this.selectedBranch) this.selectedBranch.selected = false; - branch.selected = true; - this.selectedBranch = branch; + if (this.selectedBranch) this.selectedBranch.selected = false + branch.selected = true + this.selectedBranch = branch } this.expandAllParents(branch).then( () => { if (!noClick) { if (branch.onSelect != null) { - branch.onSelect(branch); + branch.onSelect(branch) } else if (this.treeApi.onSelect) { - this.treeApi.onSelect(branch); + this.treeApi.onSelect(branch) } } if (branch.data.id) { this.eventSvc.$broadcast('tree-get-branch-element', { id: branch.data.id, - }); + }) } - deferred.resolve(); + deferred.resolve() }, (reason) => deferred.reject(reason) - ); - return deferred.promise; - }; + ) + return deferred.promise + } private _onTreeDataChange = (): VePromise => { return new this.$q((resolve, reject) => { @@ -704,18 +704,18 @@ export class TreeService { reject({ message: '[warn] treeData is not an array!', status: 401, - }); + }) } this.treeData.forEach((branch) => { - this._addBranchData(1, [], branch, true, {}); - }); + this._addBranchData(1, [], branch, true, {}) + }) - this.eventSvc.resolve(TreeService.events.UPDATED, true); - this.eventSvc.$broadcast('tree.ready'); - resolve(); - }); - }; + this.eventSvc.resolve(TreeService.events.UPDATED, true) + this.eventSvc.$broadcast('tree.ready') + resolve() + }) + } private _addBranchData = ( level: number, @@ -724,103 +724,103 @@ export class TreeService { visible: boolean, peNums: { [type: string]: number } ): void => { - if (!branch.uid) branch.uid = `${Math.random()}`; - if (typeof branch.expanded === 'undefined') branch.expanded = level <= this.treeApi.expandLevel; - branch.expandable = branch.children && branch.children.length > 0; - branch.favorite = false; + if (!branch.uid) branch.uid = `${Math.random()}` + if (typeof branch.expanded === 'undefined') branch.expanded = level <= this.treeApi.expandLevel + branch.expandable = branch.children && branch.children.length > 0 + branch.favorite = false - let number = ''; - if (section) number = section.join('.'); + let number = '' + if (section) number = section.join('.') // Handle numbering of non-section types if (!this.defaultSectionTypes.includes(branch.type)) { - if (!peNums[branch.type]) peNums[branch.type] = 0; - peNums[branch.type]++; + if (!peNums[branch.type]) peNums[branch.type] = 0 + peNums[branch.type]++ if (this.treeApi.numberingDepth === 0 && !this.defaultSectionTypes.includes(branch.type)) { - number = peNums[branch.type].toString(10); + number = peNums[branch.type].toString(10) } else if (section.length >= this.treeApi.numberingDepth) { number = `${section.slice(0, this.treeApi.numberingDepth).join('.')}${this.treeApi.numberingSeparator}${ peNums[branch.type] - }`; + }` } else { - const sectionCopy = [...section]; + const sectionCopy = [...section] while (sectionCopy.length < this.treeApi.numberingDepth) { - sectionCopy.push('0'); + sectionCopy.push('0') } - number = `${sectionCopy.join('.')}${this.treeApi.numberingSeparator}${peNums[branch.type]}`; + number = `${sectionCopy.join('.')}${this.treeApi.numberingSeparator}${peNums[branch.type]}` } } if (branch.data && branch.data.id && this.treeApi.sectionNumbering) { - this.branch2viewNumber[branch.data.id] = number; - branch.data._veNumber = number; + this.branch2viewNumber[branch.data.id] = number + branch.data._veNumber = number } if (branch.children) { - let alpha = false; + let alpha = false if (this.treeApi.sort) { - branch.children.sort(this._treeSortFunction); + branch.children.sort(this._treeSortFunction) } - let j = this.treeApi.startChapter; + let j = this.treeApi.startChapter if (j === null || j === undefined || level != 1) { - j = 1; + j = 1 } branch.children.forEach((child) => { - child.parent_uid = branch.uid; - const child_visible = visible && branch.expanded; + child.parent_uid = branch.uid + const child_visible = visible && branch.expanded if (!this.defaultSectionTypes.includes(child.type)) { - this._addBranchData(level + 1, section, child, child_visible, peNums); + this._addBranchData(level + 1, section, child, child_visible, peNums) } else { if (this.treeApi.sectionNumbering) { if (child.data._isAppendix) { - alpha = true; - j = 0; + alpha = true + j = 0 } - const nextSection = [...section, alpha ? String.fromCharCode(j + 65) : j.toString(10)]; + const nextSection = [...section, alpha ? String.fromCharCode(j + 65) : j.toString(10)] if (nextSection.length <= this.treeApi.numberingDepth) { - peNums = {}; + peNums = {} } - this._addBranchData(level + 1, nextSection, child, child_visible, peNums); + this._addBranchData(level + 1, nextSection, child, child_visible, peNums) } else { - this._addBranchData(level + 1, [], child, child_visible, peNums); + this._addBranchData(level + 1, [], child, child_visible, peNums) } - j++; + j++ } - }); + }) if (this.treeApi.sort) { - this.treeData.sort(this._treeSortFunction); + this.treeData.sort(this._treeSortFunction) } - if (!this.treeApi.expandLevel && this.treeApi.expandLevel !== 0) this.treeApi.expandLevel = 1; + if (!this.treeApi.expandLevel && this.treeApi.expandLevel !== 0) this.treeApi.expandLevel = 1 } - branch.loading = false; - this.eventSvc.resolve(TreeService.events.UPDATED, false); - }; + branch.loading = false + this.eventSvc.resolve(TreeService.events.UPDATED, false) + } public updateRows = (id: string, types: string[], treeRows: TreeRow[]): VePromise => { - treeRows.length = 0; + treeRows.length = 0 return new this.$q((resolve, reject) => { const addBranchToList = (level: number, branch: TreeBranch, visible: boolean): void => { - let typeIcon = this.defaultIcon; - let visibleChild = false; - let aggr = branch.aggr; - if (!aggr) aggr = ''; - else aggr = '-' + aggr.toLowerCase(); + let typeIcon = this.defaultIcon + let visibleChild = false + let aggr = branch.aggr + if (!aggr) aggr = '' + else aggr = '-' + aggr.toLowerCase() for (let i = 0; i < branch.children.length; i++) { if (types.includes('all') || types.includes(branch.children[i].type)) { - visibleChild = true; - break; + visibleChild = true + break } } if (this.getTypeIcon(branch.type.toLowerCase() + aggr)) { - typeIcon = this.getTypeIcon(branch.type.toLowerCase() + aggr); + typeIcon = this.getTypeIcon(branch.type.toLowerCase() + aggr) } else if (this.getTypeIcon('default')) { - typeIcon = this.getTypeIcon('default'); + typeIcon = this.getTypeIcon('default') } - let number = ''; + let number = '' if (this.treeApi.sectionNumbering) { if (branch.data && branch.data._veNumber) { - number = branch.data._veNumber; + number = branch.data._veNumber } } @@ -838,71 +838,71 @@ export class TreeService { visible, typeIcon, children: branch.children, - }; - treeRows.push(treeRow); + } + treeRows.push(treeRow) } //Work on children if (branch.children) { branch.children.forEach((child) => { - const child_visible = visible && branch.expanded; - addBranchToList(level + 1, child, child_visible); - }); + const child_visible = visible && branch.expanded + addBranchToList(level + 1, child, child_visible) + }) //This branch is done, stop loading } - }; + } if (types && types.length > 0) { - this.branch2viewNumber = {}; + this.branch2viewNumber = {} this.treeData.forEach((branch) => { - addBranchToList(1, branch, true); - }); + addBranchToList(1, branch, true) + }) } else { reject({ status: 500, message: 'Tree component has no types', - }); + }) } - this.rows[id] = treeRows; - resolve(treeRows); - }); - }; + this.rows[id] = treeRows + resolve(treeRows) + }) + } // TODO: Update sort function to handle all cases private _treeSortFunction = (a: TreeBranch, b: TreeBranch): number => { - a.priority = 100; + a.priority = 100 if (a.type === 'tag') { - a.priority = 0; + a.priority = 0 } else if (a.type === 'group') { - a.priority = 1; + a.priority = 1 } else if (a.type === 'view') { - a.priority = 2; + a.priority = 2 } - b.priority = 100; + b.priority = 100 if (b.type === 'tag') { - b.priority = 0; + b.priority = 0 } else if (b.type === 'group') { - b.priority = 1; + b.priority = 1 } else if (b.type === 'view') { - b.priority = 2; + b.priority = 2 } - if (a.priority < b.priority) return -1; - if (a.priority > b.priority) return 1; + if (a.priority < b.priority) return -1 + if (a.priority > b.priority) return 1 if (!a.label) { - a.label = ''; + a.label = '' } if (!b.label) { - b.label = ''; + b.label = '' } - if (a.label.toLowerCase() < b.label.toLowerCase()) return -1; - if (a.label.toLowerCase() > b.label.toLowerCase()) return 1; - return 0; - }; + if (a.label.toLowerCase() < b.label.toLowerCase()) return -1 + if (a.label.toLowerCase() > b.label.toLowerCase()) return 1 + return 0 + } changeRoots = (root?: ElementObject): VePromise => { - this.processedRoot = this.treeApi.rootId; + this.processedRoot = this.treeApi.rootId - const treeData: TreeBranch[] = []; + const treeData: TreeBranch[] = [] return new this.$q((resolve, reject) => { if (!root) { // if (this.mmsRef.type === 'Branch') { @@ -926,7 +926,7 @@ export class TreeService { '_parentId', this.groupLevel2Func ).then((treeHierarchy) => { - treeData.push(...treeHierarchy); + treeData.push(...treeHierarchy) documents.forEach((document) => { if (!document._groupId || document._groupId == this.treeApi.projectId) { treeData.push({ @@ -934,42 +934,42 @@ export class TreeService { type: 'view', data: document, children: [], - }); + }) } - }); - this.processedFocus = ''; + }) + this.processedFocus = '' if (treeData.length > 0) { - this.treeData.length = 0; - this.treeData.push(...treeData); + this.treeData.length = 0 + this.treeData.push(...treeData) } - this.changeElement().then(resolve, reject); - }, reject); + this.changeElement().then(resolve, reject) + }, reject) }, (reason) => { - reason.message = 'Error getting Documents: ' + reason.message; - reject(reason); + reason.message = 'Error getting Documents: ' + reason.message + reject(reason) } - ); + ) }, (reason) => { - reason.message = 'Error getting Groups: ' + reason.message; - reject(reason); + reason.message = 'Error getting Groups: ' + reason.message + reject(reason) } - ); + ) } else { - this.seenViewIds = {}; - this.viewId2node = {}; + this.seenViewIds = {} + this.viewId2node = {} const reqOb: ElementsRequest = { elementId: this.treeApi.rootId, refId: this.treeApi.refId, projectId: this.treeApi.projectId, - }; + } this.elementSvc.getElement(reqOb).then((root) => { if (this.apiSvc.isView(root)) { - const rootBranch = this.handleSingleView(root, 'composite'); - this.treeData.length = 0; - this.treeData.push(rootBranch); - this._onTreeDataChange().catch(reject); + const rootBranch = this.handleSingleView(root, 'composite') + this.treeData.length = 0 + this.treeData.push(rootBranch) + this._onTreeDataChange().catch(reject) this.viewSvc .handleChildViews( root, @@ -982,12 +982,12 @@ export class TreeService { this.handleChildren ) .then(() => { - const bulkGet: string[] = []; + const bulkGet: string[] = [] for (const i in this.viewId2node) { - const view: ViewObject = this.viewId2node[i].data; + const view: ViewObject = this.viewId2node[i].data if (view._contents && view._contents.operand) { for (let j = 0; j < view._contents.operand.length; j++) { - bulkGet.push(view._contents.operand[j].instanceId); + bulkGet.push(view._contents.operand[j].instanceId) } } } @@ -1007,55 +1007,55 @@ export class TreeService { this.viewId2node[i], this.viewId2node[i], true - ).catch(reject); + ).catch(reject) } - this.processedFocus = ''; - this.changeElement().then(resolve, reject); - }); - }, reject); + this.processedFocus = '' + this.changeElement().then(resolve, reject) + }) + }, reject) } else { //TODO: Implement Collect Owned Elements Logic } - }, reject); + }, reject) } - }); - }; + }) + } changeElement = (): VePromise => { if (this.treeApi.elementId === this.processedFocus) return new this.$q((resolve, reject) => { - resolve(); - }); + resolve() + }) - this.processedFocus = this.treeApi.elementId; + this.processedFocus = this.treeApi.elementId return new this.$q((resolve, reject) => { //As of right now the project portal page is 'hidden' so it won't appear in the tree if (this.treeApi.elementId === this.treeApi.projectId + '_cover') - this._onTreeDataChange().then(resolve, reject); + this._onTreeDataChange().then(resolve, reject) else { this.forEachBranch((b): void => { if (b.data.id === this.treeApi.elementId || this.treeApi.elementId === `site_${b.data.id}_cover`) { this.selectBranch(b, true).then( () => { - this._onTreeDataChange().then(resolve, reject); + this._onTreeDataChange().then(resolve, reject) }, (reason) => { - reject(reason); + reject(reason) } - ); + ) } }).catch((reason) => { reject({ message: 'Invalid tree selection:' + reason.message, status: 401, - }); - }); + }) + }) } - }); - }; + }) + } groupLevel2Func = (groupOb: ElementObject, groupNode: TreeBranch): VePromise => { - groupNode.loading = true; + groupNode.loading = true return new this.$q((resolve, reject) => { this.viewSvc .getProjectDocuments( @@ -1067,37 +1067,37 @@ export class TreeService { ) .then( (documentObs: ViewObject[]) => { - const docs: ViewObject[] = []; - let docOb: ViewObject, i; + const docs: ViewObject[] = [] + let docOb: ViewObject, i for (let i = 0; i < documentObs.length; i++) { - docOb = documentObs[i]; + docOb = documentObs[i] if (docOb._groupId === groupOb.id) { - docs.push(docOb); + docs.push(docOb) } } for (let i = 0; i < docs.length; i++) { - docOb = docs[i]; + docOb = docs[i] groupNode.children.unshift({ label: docOb.name, type: this.treeApi.refType === 'Branch' ? 'view' : 'snapshot', data: docOb, group: groupOb, children: [], - }); + }) } - this._onTreeDataChange().catch(reject); - resolve(); + this._onTreeDataChange().catch(reject) + resolve() }, (reason) => { - reason.message = 'Error getting project Documents: ' + reason.message; - reject(reason); + reason.message = 'Error getting project Documents: ' + reason.message + reject(reason) } - ); - }); - }; + ) + }) + } handleSingleView = (v: ViewObject, aggr: string): TreeBranch => { - let curNode = this.viewId2node[v.id]; + let curNode = this.viewId2node[v.id] if (!curNode) { curNode = { label: v.name, @@ -1106,45 +1106,45 @@ export class TreeService { children: [], loading: true, aggr: aggr, - }; - this.viewId2node[v.id] = curNode; + } + this.viewId2node[v.id] = curNode } - return curNode; - }; + return curNode + } public handleChildren = ( curNode: TreeBranch, childNodes: TreeBranch[], reject: IQResolveReject> ): void => { - const newChildNodes: TreeBranch[] = []; - let node: TreeBranch; + const newChildNodes: TreeBranch[] = [] + let node: TreeBranch for (let i = 0; i < childNodes.length; i++) { - node = childNodes[i]; + node = childNodes[i] if (this.seenViewIds[node.data.id]) { - this.growl.error('Warning: View ' + node.data.name + ' have multiple parents! Duplicates not shown.'); - continue; + this.growl.error('Warning: View ' + node.data.name + ' have multiple parents! Duplicates not shown.') + continue } - this.seenViewIds[node.data.id] = node; - newChildNodes.push(node); + this.seenViewIds[node.data.id] = node + newChildNodes.push(node) } - curNode.children.push(...newChildNodes); - this._onTreeDataChange().catch(reject); + curNode.children.push(...newChildNodes) + this._onTreeDataChange().catch(reject) //this.eventSvc.$broadcast(TreeService.events.RELOAD) - }; + } processDeletedViewBranch = (branch: TreeBranch): void => { - const id = branch.data.id; + const id = branch.data.id if (this.seenViewIds[id]) { - delete this.seenViewIds[id]; + delete this.seenViewIds[id] } if (this.viewId2node[id]) { - delete this.viewId2node[id]; + delete this.viewId2node[id] } for (let i = 0; i < branch.children.length; i++) { - this.processDeletedViewBranch(branch.children[i]); + this.processDeletedViewBranch(branch.children[i]) } - }; + } addSectionElements = ( element: ElementObject, @@ -1153,14 +1153,14 @@ export class TreeService { initial?: boolean ): VePromise => { return new this.$q((resolve, reject) => { - let contents: ValueObject | null = null; + let contents: ValueObject | null = null const addContentsSectionTreeNode = (operand: InstanceValueObject[]): void => { - const bulkGet: string[] = []; - const i = 0; + const bulkGet: string[] = [] + const i = 0 operand.forEach((operator) => { - bulkGet.push(operator.instanceId); - }); + bulkGet.push(operator.instanceId) + }) this.elementSvc .getElements( { @@ -1172,7 +1172,7 @@ export class TreeService { ) .then( (ignore) => { - const instances: VePromise[] = []; + const instances: VePromise[] = [] for (let i = 0; i < operand.length; i++) { instances.push( this.elementSvc.getElement( @@ -1183,12 +1183,12 @@ export class TreeService { }, 0 ) - ); + ) } this.$q.allSettled(instances).then((results) => { - let k = results.length - 1; + let k = results.length - 1 for (; k >= 0; k--) { - const instance: ViewInstanceSpec = results[k].value; + const instance: ViewInstanceSpec = results[k].value if (this.viewSvc.isSection(instance)) { const sectionTreeNode = { label: instance.name ? instance.name : viewNode.data.id, @@ -1196,51 +1196,51 @@ export class TreeService { viewId: viewNode.data.id, data: instance, children: [], - }; - this.viewId2node[instance.id] = sectionTreeNode; - parentNode.children.unshift(sectionTreeNode); + } + this.viewId2node[instance.id] = sectionTreeNode + parentNode.children.unshift(sectionTreeNode) this.addSectionElements(instance, viewNode, sectionTreeNode, initial).catch( reject - ); + ) } else if (this.viewSvc.getTreeType(instance) !== 'none') { const otherTreeNode: TreeBranch = { label: instance.name, type: this.viewSvc.getTreeType(instance), data: instance, children: [], - }; + } if (otherTreeNode.type !== 'view') { - otherTreeNode.viewId = viewNode.data.id; + otherTreeNode.viewId = viewNode.data.id } - parentNode.children.unshift(otherTreeNode); + parentNode.children.unshift(otherTreeNode) } - this._onTreeDataChange().catch(reject); + this._onTreeDataChange().catch(reject) } if (initial) { - this.changeElement().catch(reject); + this.changeElement().catch(reject) } - }, reject); + }, reject) }, (reason) => { - reason.message = 'Error retrieving contained elements: ' + reason.message; - reject(reason); + reason.message = 'Error retrieving contained elements: ' + reason.message + reject(reason) } - ); - }; + ) + } if (element._contents) { - contents = (element as ViewObject)._contents; + contents = (element as ViewObject)._contents } else if (this.viewSvc.isSection(element) && element.specification) { - contents = (element as ViewInstanceSpec).specification; // For Sections, the contents expression is the specification + contents = (element as ViewInstanceSpec).specification // For Sections, the contents expression is the specification } else { //bad? } if (contents && contents.operand) { - addContentsSectionTreeNode((contents as ExpressionObject).operand); + addContentsSectionTreeNode((contents as ExpressionObject).operand) } - resolve(); - }); - }; + resolve() + }) + } } -veCore.service('TreeService', TreeService); +veCore.service('TreeService', TreeService) diff --git a/src/ve-components/trees/tree.controller.ts b/src/ve-components/trees/tree.controller.ts index fb31f359b..7d2e77a9e 100644 --- a/src/ve-components/trees/tree.controller.ts +++ b/src/ve-components/trees/tree.controller.ts @@ -1,10 +1,10 @@ -import { TreeService } from '@ve-components/trees'; -import { RootScopeService, UtilsService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { handleChange } from '@ve-utils/utils'; +import { TreeService } from '@ve-components/trees' +import { RootScopeService, UtilsService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { handleChange } from '@ve-utils/utils' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; -import { TreeBranch, TreeIcons, TreeRow } from '@ve-types/tree'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { TreeBranch, TreeIcons, TreeRow } from '@ve-types/tree' /** * @ngdoc directive @@ -96,26 +96,26 @@ import { TreeBranch, TreeIcons, TreeRow } from '@ve-types/tree'; */ export class TreeController implements angular.IComponentController { //Bindings - toolbarId: string; - buttonId: string; - showPe: boolean; + toolbarId: string + buttonId: string + showPe: boolean - public init: boolean = false; + public init: boolean = false - public treeRows: TreeRow[] = []; - public title; - private selectedBranch: any; - public treeSpin: boolean = true; + public treeRows: TreeRow[] = [] + public title + private selectedBranch: any + public treeSpin: boolean = true - public subs: Rx.IDisposable[]; - private treeFilter: angular.uiTreeFilter.IFilterUiTree; + public subs: Rx.IDisposable[] + private treeFilter: angular.uiTreeFilter.IFilterUiTree //Locals - public icons: TreeIcons; - types: string[]; - id: string; - filter: string; + public icons: TreeIcons + types: string[] + id: string + filter: string static $inject = [ '$q', @@ -127,7 +127,7 @@ export class TreeController implements angular.IComponentController { 'TreeService', 'RootScopeService', 'EventService', - ]; + ] constructor( protected $q: VeQService, @@ -140,27 +140,27 @@ export class TreeController implements angular.IComponentController { protected rootScopeSvc: RootScopeService, protected eventSvc: EventService ) { - this.types = ['']; + this.types = [''] } $onInit(): void { - this.treeFilter = this.$filter('uiTreeFilter'); + this.treeFilter = this.$filter('uiTreeFilter') - this.eventSvc.$init(this); + this.eventSvc.$init(this) this.subs.push( this.eventSvc.binding(TreeService.events.UPDATED, (data) => { if (data) { this.update().catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) } }), this.eventSvc.$on(TreeService.events.RELOAD, (data) => { if ((data && this.id === data) || !data) { - this.treeSpin = true; + this.treeSpin = true this.update().catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) } }), this.eventSvc.$on(TreeService.events.FILTER, (data) => { @@ -169,37 +169,37 @@ export class TreeController implements angular.IComponentController { () => { this.treeSvc.expandPathToSelectedBranch().then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.id); - this.filter = data; + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.id) + this.filter = data }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); + ) }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); + ) } else { // expand all branches so that the filter works correctly this.treeSvc.expandAll().then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.id); - this.filter = data; + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.id) + this.filter = data }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); + ) } }) - ); + ) if (this.treeSvc.isTreeReady()) { this.update().catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) } // this.subs.push( @@ -227,108 +227,108 @@ export class TreeController implements angular.IComponentController { 'showPe', () => { this.update().catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); + this.growl.error(TreeService.treeError(reason)) + }) }, true - ); + ) } $onDestroy(): void { - this.eventSvc.destroy(this.subs); + this.eventSvc.destroy(this.subs) } update(): VePromise { - this.treeRows = []; - this.setPeVisibility(); - this.preConfig(); - this.selectedBranch = this.treeSvc.getSelectedBranch(); + this.treeRows = [] + this.setPeVisibility() + this.preConfig() + this.selectedBranch = this.treeSvc.getSelectedBranch() - this.icons = this.icons ? this.icons : this.treeSvc.defaultIcons; + this.icons = this.icons ? this.icons : this.treeSvc.defaultIcons - this.treeSvc.defaultIcon = this.icons.iconDefault; + this.treeSvc.defaultIcon = this.icons.iconDefault return new this.$q((resolve, reject) => { this.treeSvc.updateRows(this.id, this.types, this.treeRows).then(() => { - this.treeSpin = false; - resolve(); - }, reject); - }); + this.treeSpin = false + resolve() + }, reject) + }) } public expandCallback = (branch: TreeBranch, e: JQuery.ClickEvent): void => { - branch.loading = true; + branch.loading = true if (!branch.expanded && this.treeSvc.treeApi.expandCallback) { - this.treeSvc.treeApi.expandCallback(branch.data.id, branch, false); + this.treeSvc.treeApi.expandCallback(branch.data.id, branch, false) } if (e) { - e.stopPropagation(); + e.stopPropagation() } - const promise = branch.expanded ? this.treeSvc.closeBranch(branch) : this.treeSvc.expandBranch(branch); + const promise = branch.expanded ? this.treeSvc.closeBranch(branch) : this.treeSvc.expandBranch(branch) promise.then( () => { this.update() .catch((reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) }) .finally(() => { - branch.loading = false; - }); + branch.loading = false + }) }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } - ); - }; + ) + } public userClicksBranch = (branch: TreeBranch): void => { - branch.loading = true; + branch.loading = true this.treeSvc .selectBranch(branch, true) .then( () => { if (branch.onSelect) { - branch.onSelect(branch); + branch.onSelect(branch) } else if (this.treeSvc.treeApi.onSelect) { - this.treeSvc.treeApi.onSelect(branch); + this.treeSvc.treeApi.onSelect(branch) } }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } ) .finally(() => { - branch.loading = false; - }); - }; + branch.loading = false + }) + } public userDblClicksBranch = (branch: TreeBranch): void => { - branch.loading = true; + branch.loading = true this.treeSvc .selectBranch(branch, true) .then( () => { if (branch.onDblClick) { - branch.onDblClick(branch); + branch.onDblClick(branch) } else if (this.treeSvc.treeApi.onDblClick) { - this.treeSvc.treeApi.onDblClick(branch); + this.treeSvc.treeApi.onDblClick(branch) } }, (reason) => { - this.growl.error(TreeService.treeError(reason)); + this.growl.error(TreeService.treeError(reason)) } ) .finally(() => { - branch.loading = false; - }); - }; + branch.loading = false + }) + } protected setPeVisibility = (): void => { //Implement any custom logic for showing PE's here - }; + } protected preConfig = (): void => { //Implement any custom logic that should happen before row generation - }; + } // public getHref = (row: TreeRow): string => { // //var data = row.branch.data; @@ -370,4 +370,4 @@ export const TreeOfAnyComponent: VeComponentOptions = { buttonId: '@', showPe: '<', }, -}; +} diff --git a/src/ve-components/ve-components.module.ts b/src/ve-components/ve-components.module.ts index 944839c74..0b51bcfbc 100644 --- a/src/ve-components/ve-components.module.ts +++ b/src/ve-components/ve-components.module.ts @@ -1,4 +1,4 @@ -import angular from 'angular'; +import angular from 'angular' /** * @@ -10,7 +10,7 @@ export const veComponents = angular.module('ve-components', [ 'ui.bootstrap', 'angular-growl', // 'ngSanitize', -]); +]) // veComponents.config(['$sanitizeProvider', function($sanitizeProvider: angular.sanitize.ISanitizeProvider) { // $sanitizeProvider.addValidElements({ @@ -24,10 +24,10 @@ veComponents .filter('veRealNum', () => { return (n: string | number): string => { if (Number.isInteger(n)) { - return `${n}.0`; + return `${n}.0` } - return n as string; - }; + return n as string + } }) .constant('CKEDITOR', window.CKEDITOR) - .constant('veConfig', window.__env); + .constant('veConfig', window.__env) diff --git a/src/ve-core/button-bar/button-bar.component.ts b/src/ve-core/button-bar/button-bar.component.ts index 7d9f1d069..13fda9b54 100644 --- a/src/ve-core/button-bar/button-bar.component.ts +++ b/src/ve-core/button-bar/button-bar.component.ts @@ -1,10 +1,10 @@ -import { BarButton, ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; -import { veCoreEvents } from '@ve-core/events'; -import { EventService } from '@ve-utils/core'; +import { BarButton, ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' +import { veCoreEvents } from '@ve-core/events' +import { EventService } from '@ve-utils/core' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VeComponentOptions } from '@ve-types/angular'; +import { VeComponentOptions } from '@ve-types/angular' const ButtonBarComponent: VeComponentOptions = { selector: 'buttonBar', @@ -50,17 +50,17 @@ const ButtonBarComponent: VeComponentOptions = { }, controller: class ButtonBarController implements angular.IComponentController { // Bindings - private buttonId: string; - private minSize: number = 100; + private buttonId: string + private minSize: number = 100 - private bbApi: ButtonBarApi; - public init: boolean = false; - public buttons: BarButton[]; - public dropdownIcon: { [id: string]: string }; - private squished: boolean = false; - private squishButton: BarButton; - private currentHeight: number; - static $inject = ['$element', 'growl', 'EventService', 'ButtonBarService']; + private bbApi: ButtonBarApi + public init: boolean = false + public buttons: BarButton[] + public dropdownIcon: { [id: string]: string } + private squished: boolean = false + private squishButton: BarButton + private currentHeight: number + static $inject = ['$element', 'growl', 'EventService', 'ButtonBarService'] constructor( private $element: JQuery, @@ -72,56 +72,56 @@ const ButtonBarComponent: VeComponentOptions = { $onInit(): void { this.buttonBarSvc.waitForApi(this.buttonId).then( (api) => { - this.bbApi = api; - this.buttons = this.bbApi.buttons; - this.configure(); + this.bbApi = api + this.buttons = this.bbApi.buttons + this.configure() }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) } configure = (): void => { //Setup Squish - this.squishButton = this.buttonBarSvc.getButtonBarButton('button-bar-menu'); - this.squishButton.dropdown_buttons = this.buttons; - const observed = this.$element.children().get(0); + this.squishButton = this.buttonBarSvc.getButtonBarButton('button-bar-menu') + this.squishButton.dropdown_buttons = this.buttons + const observed = this.$element.children().get(0) const observer = new ResizeObserver((mutations) => mutations.forEach((mutationRecord) => { - const size = mutationRecord.borderBoxSize; - const oldHeight = this.currentHeight; + const size = mutationRecord.borderBoxSize + const oldHeight = this.currentHeight this.eventSvc.$broadcast(this.bbApi.WRAP_EVENT, { oldSize: oldHeight, newSize: size[0].blockSize, - }); - this.currentHeight = size[0].blockSize; + }) + this.currentHeight = size[0].blockSize if (size[0].inlineSize <= this.minSize && !this.squished) { - this.squished = true; - this.buttons = [this.squishButton]; + this.squished = true + this.buttons = [this.squishButton] } else if (size[0].inlineSize > this.minSize && this.squished) { - this.squished = false; - this.buttons = this.squishButton.dropdown_buttons; + this.squished = false + this.buttons = this.squishButton.dropdown_buttons } }) - ); + ) - observer.observe(observed); - }; + observer.observe(observed) + } buttonClicked(e: JQuery.ClickEvent, button: BarButton): void { if (button.action) { - button.action(e); + button.action(e) } else { const data: veCoreEvents.buttonClicked = { $event: e, clicked: button.id, - }; + } //Setup fire button-bar click event - this.eventSvc.$broadcast(this.bbApi.id, data); + this.eventSvc.$broadcast(this.bbApi.id, data) } } }, -}; +} -veUtils.component(ButtonBarComponent.selector, ButtonBarComponent); +veUtils.component(ButtonBarComponent.selector, ButtonBarComponent) diff --git a/src/ve-core/button-bar/index.ts b/src/ve-core/button-bar/index.ts index 9dd47e925..f8e2c1c4a 100644 --- a/src/ve-core/button-bar/index.ts +++ b/src/ve-core/button-bar/index.ts @@ -1,10 +1,10 @@ -export * from './services/BarButton.api'; -export * from './services/ButtonBar.api'; +export * from './services/BarButton.api' +export * from './services/ButtonBar.api' //Service -import './services/ButtonBar.service'; +import './services/ButtonBar.service' -export * from './services/ButtonBar.service'; +export * from './services/ButtonBar.service' //Components -import './button-bar.component'; +import './button-bar.component' diff --git a/src/ve-core/button-bar/services/BarButton.api.ts b/src/ve-core/button-bar/services/BarButton.api.ts index 34bbf534e..bf8f274ec 100644 --- a/src/ve-core/button-bar/services/BarButton.api.ts +++ b/src/ve-core/button-bar/services/BarButton.api.ts @@ -1,123 +1,123 @@ export interface IButtonBarButton { - id: string; - icon: string; - tooltip: string; - placement?: string; - button_content?: string; - selectable: boolean; + id: string + icon: string + tooltip: string + placement?: string + button_content?: string + selectable: boolean //Toggle Config toggle?: | { - icon?: string; - tooltip?: string; + icon?: string + tooltip?: string } - | boolean; + | boolean //Dropdown Config dropdown?: { - icon: string; - toggle_icon: string; - ids: string[]; - }; - api?: string; - enabledFor?: string[]; - disabledFor?: string[]; - type?: string; + icon: string + toggle_icon: string + ids: string[] + } + api?: string + enabledFor?: string[] + disabledFor?: string[] + type?: string } export interface buttonActionFn { - (event?: JQuery.ClickEvent): void; + (event?: JQuery.ClickEvent): void } export class BarButton { //configs - id: string; - icon: string = 'fa-gears'; - tooltip: string = 'Generic Button'; - dropdown_icon: string = ''; - button_content: string = ''; - placement?: string; + id: string + icon: string = 'fa-gears' + tooltip: string = 'Generic Button' + dropdown_icon: string = '' + button_content: string = '' + placement?: string //State - active: boolean = true; - selected: boolean = false; - permission: boolean = true; - toggled: boolean = false; - dropdown_toggled: boolean = false; - spinner: boolean = false; - locked: boolean = false; + active: boolean = true + selected: boolean = false + permission: boolean = true + toggled: boolean = false + dropdown_toggled: boolean = false + spinner: boolean = false + locked: boolean = false //Toggle Configuration //Set Custom Click actions - action?: buttonActionFn; + action?: buttonActionFn - dropdown_buttons: BarButton[] = []; + dropdown_buttons: BarButton[] = [] //Internal - readonly dropdown_icon_original: string; - readonly tooltip_original: string; - readonly icon_original: string; + readonly dropdown_icon_original: string + readonly tooltip_original: string + readonly icon_original: string constructor(id: string, readonly config?: IButtonBarButton) { - this.id = id; + this.id = id if (this.config) { - if (this.config.icon) this.icon = this.icon_original = this.config.icon; + if (this.config.icon) this.icon = this.icon_original = this.config.icon if (this.config.tooltip) { - this.tooltip = this.tooltip_original = this.config.tooltip; + this.tooltip = this.tooltip_original = this.config.tooltip } if (this.config.button_content) { - this.button_content = this.config.button_content; + this.button_content = this.config.button_content } if (this.config.dropdown && this.config.dropdown.icon && this.config.dropdown.icon !== '') { - this.dropdown_icon = this.dropdown_icon_original = this.config.dropdown.icon; + this.dropdown_icon = this.dropdown_icon_original = this.config.dropdown.icon } } } public setAction = (action: buttonActionFn): void => { - this.action = action; - }; + this.action = action + } public toggle = (state?: boolean): void => { if (this.config.toggle) { - this.toggled = state != null ? state : !this.toggled; + this.toggled = state != null ? state : !this.toggled if (this.toggled) { if ((this.config.toggle as { tooltip: string; icon: string }).tooltip) { - this.tooltip = (this.config.toggle as { tooltip: string; icon: string }).tooltip; + this.tooltip = (this.config.toggle as { tooltip: string; icon: string }).tooltip } if ((this.config.toggle as { tooltip: string; icon: string }).icon) { - this.icon = (this.config.toggle as { tooltip: string; icon: string }).icon; + this.icon = (this.config.toggle as { tooltip: string; icon: string }).icon } } else { - this.icon = this.icon_original; + this.icon = this.icon_original if (this.tooltip_original) { - this.tooltip = this.tooltip_original; + this.tooltip = this.tooltip_original } } } if (this.config.dropdown && this.config.dropdown.icon) { - this.dropdown_toggled = state != null ? state : !this.dropdown_toggled; + this.dropdown_toggled = state != null ? state : !this.dropdown_toggled if (this.dropdown_toggled && this.config.dropdown.toggle_icon) { - this.dropdown_icon = this.config.dropdown.toggle_icon; + this.dropdown_icon = this.config.dropdown.toggle_icon } else { - this.dropdown_icon = this.dropdown_icon_original; + this.dropdown_icon = this.dropdown_icon_original } } - }; + } public toggleSpin = (): void => { if (this.spinner) { if (this.toggled && this.config.toggle) { - this.icon = (this.config.toggle as { tooltip: string; icon: string }).icon; + this.icon = (this.config.toggle as { tooltip: string; icon: string }).icon } else { - this.icon = this.icon_original; + this.icon = this.icon_original } } else { - this.icon = 'fa fa-spinner fa-spin'; + this.icon = 'fa fa-spinner fa-spin' } - this.spinner = !this.spinner; - }; + this.spinner = !this.spinner + } public toggleLock = (): void => { - this.locked = !this.locked; - }; + this.locked = !this.locked + } } diff --git a/src/ve-core/button-bar/services/ButtonBar.api.ts b/src/ve-core/button-bar/services/ButtonBar.api.ts index 953750a72..9352322b1 100644 --- a/src/ve-core/button-bar/services/ButtonBar.api.ts +++ b/src/ve-core/button-bar/services/ButtonBar.api.ts @@ -1,117 +1,117 @@ -import { BarButton } from '@ve-core/button-bar'; +import { BarButton } from '@ve-core/button-bar' export interface ButtonWrapEvent { - oldSize: number; - newSize: number; + oldSize: number + newSize: number } export class ButtonBarApi { - public buttons: BarButton[] = []; - public WRAP_EVENT: string; + public buttons: BarButton[] = [] + public WRAP_EVENT: string constructor(public id: string) { if (this.id === '') { - this.id = 'unknown'; + this.id = 'unknown' } - this.WRAP_EVENT = `${id}-wrap`; + this.WRAP_EVENT = `${id}-wrap` } public getId = (): string => { - return this.id; - }; + return this.id + } public select = (parentButton: BarButton, childButton: BarButton): void => { if (parentButton && childButton && childButton.config.selectable) { parentButton.dropdown_buttons.forEach((dropdownButton) => { if (parentButton.config.dropdown) { if (dropdownButton.id === childButton.id) { - dropdownButton.selected = dropdownButton.selected ? !dropdownButton.selected : true; + dropdownButton.selected = dropdownButton.selected ? !dropdownButton.selected : true } } else { - dropdownButton.selected = dropdownButton.id === childButton.id; + dropdownButton.selected = dropdownButton.id === childButton.id } - }); + }) } - }; + } public deselect = (parentButton: BarButton, childButton: BarButton): void => { if (parentButton && childButton) { parentButton.dropdown_buttons.forEach((dropdownButton) => { if (parentButton.config.dropdown) { if (dropdownButton.id === childButton.id) { - dropdownButton.selected = false; + dropdownButton.selected = false } } - }); + }) } - }; + } public setPermission = (id: string, permission: boolean): void => { this.buttons.forEach((button) => { - if (button.id === id) button.permission = permission; - }); - }; + if (button.id === id) button.permission = permission + }) + } public setActive = (id: string, state: boolean, parent?: string): void => { this.buttons.forEach((button) => { if (parent && button.id === parent && button.dropdown_buttons) { button.dropdown_buttons.forEach((child) => { - if (child.id === id) child.active = state; - }); + if (child.id === id) child.active = state + }) } - if (button.id === id) button.active = state; - }); - }; + if (button.id === id) button.active = state + }) + } public addButton = (button: BarButton): void => { if (this.buttons.length === 0) { - button.placement = 'bottom-left'; + button.placement = 'bottom-left' } else if (!button.placement) { // else { - button.placement = 'bottom'; + button.placement = 'bottom' } - this.buttons.push(button); - }; + this.buttons.push(button) + } public toggleButtonSpinner = (id: string): void => { this.buttons.forEach((button) => { - if (button.id === id) button.toggleSpin(); - else button.toggleLock(); - }); - }; + if (button.id === id) button.toggleSpin() + else button.toggleLock() + }) + } public toggleButton = (id: string, state?: boolean): void => { this.buttons.forEach((button) => { - if (button.id === id) button.toggle(state); - }); - }; + if (button.id === id) button.toggle(state) + }) + } public checkActive = (cb: (enableState: string) => boolean, parent?: BarButton): void => { - const buttons = parent ? parent.dropdown_buttons : this.buttons; + const buttons = parent ? parent.dropdown_buttons : this.buttons buttons.forEach((button) => { - const config = button.config; + const config = button.config if (config) { if (config.enabledFor) { - this.setActive(button.id, false, parent ? parent.id : null); + this.setActive(button.id, false, parent ? parent.id : null) for (const enableState of config.enabledFor) { if (cb(enableState)) { - this.setActive(button.id, true, parent ? parent.id : null); - break; + this.setActive(button.id, true, parent ? parent.id : null) + break } } } if (config.disabledFor) { for (const disableState of config.disabledFor) { if (cb(disableState)) { - this.setActive(button.id, false, parent ? parent.id : null); - break; + this.setActive(button.id, false, parent ? parent.id : null) + break } } } } if (button.dropdown_buttons.length > 0) { - this.checkActive(cb, button); + this.checkActive(cb, button) } - }); - }; + }) + } } diff --git a/src/ve-core/button-bar/services/ButtonBar.service.ts b/src/ve-core/button-bar/services/ButtonBar.service.ts index eb5bebe0f..ede0f0605 100644 --- a/src/ve-core/button-bar/services/ButtonBar.service.ts +++ b/src/ve-core/button-bar/services/ButtonBar.service.ts @@ -1,12 +1,12 @@ -import { BarButton, ButtonBarApi, IButtonBarButton } from '@ve-core/button-bar'; -import { EventService } from '@ve-utils/core'; +import { BarButton, ButtonBarApi, IButtonBarButton } from '@ve-core/button-bar' +import { EventService } from '@ve-utils/core' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; -import { VeConfig } from '@ve-types/config'; -import { EditorActions } from '@ve-types/core/editor'; -import { VeApiObject } from '@ve-types/view-editor'; +import { VePromise, VeQService } from '@ve-types/angular' +import { VeConfig } from '@ve-types/config' +import { EditorActions } from '@ve-types/core/editor' +import { VeApiObject } from '@ve-types/view-editor' const default_buttons: IButtonBarButton[] = [ { @@ -21,31 +21,31 @@ const default_buttons: IButtonBarButton[] = [ ids: [], }, }, -]; +] export interface buttonInitFn { - (api: ButtonBarApi): void; + (api: ButtonBarApi): void } export class ButtonBarService { - static $inject = ['$q', 'EventService']; + static $inject = ['$q', 'EventService'] - private barCounter: { [id: string]: number } = {}; - private buttons: { [key: string]: IButtonBarButton } = {}; - private buttonBars: VeApiObject = {}; - private veConfig: VeConfig; + private barCounter: { [id: string]: number } = {} + private buttons: { [key: string]: IButtonBarButton } = {} + private buttonBars: VeApiObject = {} + private veConfig: VeConfig constructor(private $q: VeQService, private eventSvc: EventService) { for (const button of default_buttons) { - this.buttons[button.id] = button; + this.buttons[button.id] = button } - this.veConfig = window.__env; + this.veConfig = window.__env if (this.veConfig.expConfig) { for (const ext of Object.keys(this.veConfig.expConfig)) { if (this.veConfig.expConfig[ext] && this.veConfig.expConfig[ext].length > 0) { for (const tool of this.veConfig.expConfig[ext]) { if (tool.barButtons) { - this.registerButtons(tool.barButtons); + this.registerButtons(tool.barButtons) } } } @@ -55,104 +55,104 @@ export class ButtonBarService { public waitForApi = (id: string): VePromise => { if (!this.buttonBars.hasOwnProperty(id)) { - this.buttonBars[id] = {}; + this.buttonBars[id] = {} this.buttonBars[id].promise = new this.$q((resolve, reject) => { - this.buttonBars[id].resolve = resolve; - this.buttonBars[id].reject = reject; - }); + this.buttonBars[id].resolve = resolve + this.buttonBars[id].reject = reject + }) } - return this.buttonBars[id].promise; - }; + return this.buttonBars[id].promise + } public generateBarId = (root?: string): string => { if (!root) { - root = 'button_bar'; + root = 'button_bar' } - if (!this.barCounter[root]) this.barCounter[root] = 1; - else this.barCounter[root]++; - return `${root}_${this.barCounter[root]}`; - }; + if (!this.barCounter[root]) this.barCounter[root] = 1 + else this.barCounter[root]++ + return `${root}_${this.barCounter[root]}` + } public initApi(id: string, init: buttonInitFn, buttons?: IButtonBarButton[]): ButtonBarApi { if (!init) { - return null; + return null } - const api = new ButtonBarApi(id); + const api = new ButtonBarApi(id) if (buttons && buttons.length > 0) { - this.registerButtons(buttons); + this.registerButtons(buttons) } - init(api); + init(api) if (!this.buttonBars[id]) { this.buttonBars[id] = { api, - }; + } } else { - this.buttonBars[id].api = api; + this.buttonBars[id].api = api } if (!this.buttonBars[id].resolve) { this.buttonBars[id].promise = new this.$q((resolve, reject) => { - this.buttonBars[id].resolve = resolve; - this.buttonBars[id].reject = reject; - }); + this.buttonBars[id].resolve = resolve + this.buttonBars[id].reject = reject + }) } - this.buttonBars[id].resolve(api); - return api; + this.buttonBars[id].resolve(api) + return api } destroy(id: string): void { if (this.buttonBars.hasOwnProperty(id)) { - delete this.buttonBars[id]; + delete this.buttonBars[id] } } destroyAll(ids: string[]): void { ids.forEach((bbId) => { - this.destroy(bbId); - }); + this.destroy(bbId) + }) } getButtonBarButton = (buttonId: string, ctrl?: EditorActions): BarButton => { if (this.buttons.hasOwnProperty(buttonId)) { - const newButton = new BarButton(buttonId, this.buttons[buttonId]); + const newButton = new BarButton(buttonId, this.buttons[buttonId]) if (this.buttons[buttonId].dropdown) { - newButton.dropdown_buttons = []; + newButton.dropdown_buttons = [] for (const id of this.buttons[buttonId].dropdown.ids) { - newButton.dropdown_buttons.push(this.getButtonBarButton(id, ctrl)); + newButton.dropdown_buttons.push(this.getButtonBarButton(id, ctrl)) } } if (this.buttons[buttonId].api && ctrl && ctrl[this.buttons[buttonId].api]) { newButton.setAction((event): void => { - if (event) event.stopPropagation(); - (ctrl[this.buttons[buttonId].api] as () => void)(); - }); + if (event) event.stopPropagation() + ;(ctrl[this.buttons[buttonId].api] as () => void)() + }) } - return newButton; + return newButton } else { - return new BarButton(buttonId); + return new BarButton(buttonId) } - }; + } getButtonDefinition = (buttonId: string): IButtonBarButton => { if (this.buttons.hasOwnProperty(buttonId)) { - return this.buttons[buttonId]; + return this.buttons[buttonId] } - return null; - }; + return null + } public registerButtons = (buttons: IButtonBarButton | IButtonBarButton[]): void => { if (!Array.isArray(buttons)) { - buttons = [buttons]; + buttons = [buttons] } if (buttons.length > 0) { for (const button of buttons) { if (!this.buttons[button.id]) { - this.buttons[button.id] = button; + this.buttons[button.id] = button } } } - }; + } } -veUtils.service('ButtonBarService', ButtonBarService); +veUtils.service('ButtonBarService', ButtonBarService) diff --git a/src/ve-core/editor/components/mention-intercept.component.ts b/src/ve-core/editor/components/mention-intercept.component.ts index dca4f8fc8..076a0efd3 100644 --- a/src/ve-core/editor/components/mention-intercept.component.ts +++ b/src/ve-core/editor/components/mention-intercept.component.ts @@ -1,25 +1,25 @@ -import { MMSMentionController } from '@ve-core/editor/components/mention.component'; +import { MMSMentionController } from '@ve-core/editor/components/mention.component' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { ElementObject } from '@ve-types/mms'; +import { ElementObject } from '@ve-types/mms' class MMSMentionInterceptController implements angular.IComponentController { - public mmsMentionInterceptValue: string; - mmsFastCf: ElementObject[]; + public mmsMentionInterceptValue: string + mmsFastCf: ElementObject[] - private ngModel: angular.INgModelController; - mentionCtrl: MMSMentionController; + private ngModel: angular.INgModelController + mentionCtrl: MMSMentionController $onChanges(changes: angular.IOnChangesObject): void { if (changes.mmsMentionInterceptValue) { - this.ngModel.$setViewValue(changes.mmsMentionInterceptValue.currentValue); - this.ngModel.$render(); + this.ngModel.$setViewValue(changes.mmsMentionInterceptValue.currentValue) + this.ngModel.$render() } } public selectMentionItem($item: ElementObject): void { - this.mentionCtrl.selectMentionItem($item); + this.mentionCtrl.selectMentionItem($item) } } @@ -45,6 +45,6 @@ const MMSMentionIntercept = { mmsMentionId: '<', }, controller: MMSMentionInterceptController, -}; +} -veCore.component(MMSMentionIntercept.selector, MMSMentionIntercept); +veCore.component(MMSMentionIntercept.selector, MMSMentionIntercept) diff --git a/src/ve-core/editor/components/mention.component.ts b/src/ve-core/editor/components/mention.component.ts index 273cb4ed3..2baf429a4 100644 --- a/src/ve-core/editor/components/mention.component.ts +++ b/src/ve-core/editor/components/mention.component.ts @@ -1,32 +1,32 @@ -import { EditorService, MentionService } from '@ve-core/editor'; +import { EditorService, MentionService } from '@ve-core/editor' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { ElementObject } from '@ve-types/mms'; +import { ElementObject } from '@ve-types/mms' export class MMSMentionController implements angular.IComponentController { //Bindings - public mmsEditor: CKEDITOR.editor; - mmsMentionValue: string; - mmsMentionId: string; - mmsProjectId: string; - mmsRefId: string; + public mmsEditor: CKEDITOR.editor + mmsMentionValue: string + mmsMentionId: string + mmsProjectId: string + mmsRefId: string //Local - public fastCfListing: ElementObject[]; + public fastCfListing: ElementObject[] - static $inject = ['MentionService', 'EditorService']; + static $inject = ['MentionService', 'EditorService'] constructor(private mentionSvc: MentionService, private editorSvc: EditorService) {} $onInit(): void { - this.fastCfListing = this.mentionSvc.getFastCfListing(this.mmsProjectId, this.mmsRefId); + this.fastCfListing = this.mentionSvc.getFastCfListing(this.mmsProjectId, this.mmsRefId) // expose this api on the controller itself so that it can be accessed by codes that use $compile service to construct this directive. } public selectMentionItem($item: ElementObject): void { - this._createCf($item); - this.mentionSvc.handleMentionSelection(this.mmsEditor, this.mmsMentionId); + this._createCf($item) + this.mentionSvc.handleMentionSelection(this.mmsEditor, this.mmsMentionId) } private _createCf($item: ElementObject): void { @@ -39,9 +39,9 @@ export class MMSMentionController implements angular.IComponentController { $item.name + '.' + $item.type + - ']
    '; - this.mmsEditor.insertHtml(tag); - this.editorSvc.focusOnEditorAfterAddingWidgetTag(this.mmsEditor); + ']
    ' + this.mmsEditor.insertHtml(tag) + this.editorSvc.focusOnEditorAfterAddingWidgetTag(this.mmsEditor) } } @@ -85,6 +85,6 @@ const MMSMention = { mmsRefId: '<', }, controller: MMSMentionController, -}; +} -veCore.component(MMSMention.selector, MMSMention); +veCore.component(MMSMention.selector, MMSMention) diff --git a/src/ve-core/editor/editor-buttons.config.ts b/src/ve-core/editor/editor-buttons.config.ts index 1c760c53f..6c14fa59d 100644 --- a/src/ve-core/editor/editor-buttons.config.ts +++ b/src/ve-core/editor/editor-buttons.config.ts @@ -1,4 +1,4 @@ -import { IButtonBarButton } from '@ve-core/button-bar'; +import { IButtonBarButton } from '@ve-core/button-bar' export const editor_buttons: IButtonBarButton[] = [ { @@ -43,4 +43,4 @@ export const editor_buttons: IButtonBarButton[] = [ tooltip: 'Preview Changes', api: 'preview', }, -]; +] diff --git a/src/ve-core/editor/editor.component.ts b/src/ve-core/editor/editor.component.ts index ff423a414..82c23ac31 100644 --- a/src/ve-core/editor/editor.component.ts +++ b/src/ve-core/editor/editor.component.ts @@ -1,22 +1,22 @@ -import angular, { IComponentController } from 'angular'; -import $ from 'jquery'; -import _, { DebouncedFunc } from 'lodash'; +import angular, { IComponentController } from 'angular' +import $ from 'jquery' +import _, { DebouncedFunc } from 'lodash' -import { InsertTransclusionData } from '@ve-components/transclusions'; -import { MentionService } from '@ve-core/editor'; -import { EditorService } from '@ve-core/editor/services/Editor.service'; -import { ImageService } from '@ve-utils/application'; -import { ApiService, ElementService, URLService, ViewService } from '@ve-utils/mms-api-client'; +import { InsertTransclusionData } from '@ve-components/transclusions' +import { MentionService } from '@ve-core/editor' +import { EditorService } from '@ve-core/editor/services/Editor.service' +import { ImageService } from '@ve-utils/application' +import { ApiService, ElementService, URLService, ViewService } from '@ve-utils/mms-api-client' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import eventDataTypes = CKEDITOR.eventDataTypes; +import eventDataTypes = CKEDITOR.eventDataTypes -import { VeComponentOptions, VeNgModelController, VePromise, VeQService } from '@ve-types/angular'; -import { InsertData, InsertResolveFn } from '@ve-types/components'; -import { VeConfig } from '@ve-types/config'; -import { ElementObject, ElementsResponse, TransclusionObject } from '@ve-types/mms'; -import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; +import { VeComponentOptions, VeNgModelController, VePromise, VeQService } from '@ve-types/angular' +import { InsertData, InsertResolveFn } from '@ve-types/components' +import { VeConfig } from '@ve-types/config' +import { ElementObject, ElementsResponse, TransclusionObject } from '@ve-types/mms' +import { VeModalService, VeModalSettings } from '@ve-types/view-editor' /** * @ngdoc directive @@ -44,49 +44,49 @@ import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; */ export class EditorController implements IComponentController { - private veConfig: VeConfig = window.__env; - private ckEditor = window.CKEDITOR; + private veConfig: VeConfig = window.__env + private ckEditor = window.CKEDITOR - private ngModelCtrl: VeNgModelController; - private ngModel: string; + private ngModelCtrl: VeNgModelController + private ngModel: string - mmsElementId: string; - mmsProjectId: string; - mmsRefId: string; - private editorType: string; - private editField: 'name' | 'value' | 'documentation' = 'documentation'; - private editKey: string | string[]; - private editIndex: string = ''; + mmsElementId: string + mmsProjectId: string + mmsRefId: string + private editorType: string + private editField: 'name' | 'value' | 'documentation' = 'documentation' + private editKey: string | string[] + private editIndex: string = '' private stylesToolbar = { name: 'styles', items: ['Styles', /*'Format',*/ 'FontSize', 'TextColor', 'BGColor'], - }; + } private basicStylesToolbar = { name: 'basicstyles', //items: ['Bold', 'Italic', 'Underline', 'mmsExtraFormat'], items: ['Bold', 'Italic', 'Underline'], - }; - private clipboardToolbar = { name: 'clipboard', items: ['Undo', 'Redo'] }; + } + private clipboardToolbar = { name: 'clipboard', items: ['Undo', 'Redo'] } private justifyToolbar = { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight'], - }; - private editingToolbar = { name: 'editing', items: ['Find', 'Replace'] }; - private linksToolbar = { name: 'links', items: ['Link', 'Unlink', '-'] }; - private imageToolbar = { name: 'image', items: ['Image', 'Iframe'] }; + } + private editingToolbar = { name: 'editing', items: ['Find', 'Replace'] } + private linksToolbar = { name: 'links', items: ['Link', 'Unlink', '-'] } + private imageToolbar = { name: 'image', items: ['Image', 'Iframe'] } private listToolbar = { name: 'list', items: ['NumberedList', 'BulletedList', 'Outdent', 'Indent'], - }; + } private equationToolbar = { name: 'equation', items: ['Mathjax', 'SpecialChar'], - }; + } private sourceToolbar = { name: 'source', items: ['Maximize', 'Sourcedialog'], - }; + } private combinedToolbar = { name: 'combined', items: [ @@ -100,19 +100,19 @@ export class EditorController implements IComponentController { 'Mmscomment', //'mmsExtraFeature', ], - }; - private tableEquationToolbar = { name: 'tableEquation', items: ['Table', 'Mathjax', 'SpecialChar', '-'] }; + } + private tableEquationToolbar = { name: 'tableEquation', items: ['Table', 'Mathjax', 'SpecialChar', '-'] } - private extrasToolbar = { name: 'extras', items: ['mmsExtraFeature'] }; + private extrasToolbar = { name: 'extras', items: ['mmsExtraFeature'] } - protected $transcludeEl: JQuery; - public id: string; - protected init: boolean = false; + protected $transcludeEl: JQuery + public id: string + protected init: boolean = false - private instance: CKEDITOR.editor = null; - private deb: DebouncedFunc<(e) => void>; + private instance: CKEDITOR.editor = null + private deb: DebouncedFunc<(e) => void> - private tokenStr: RegExp = new RegExp('([?&]token=[a-zA-Z0-9.]*)'); + private tokenStr: RegExp = new RegExp('([?&]token=[a-zA-Z0-9.]*)') static $inject = [ '$compile', @@ -130,7 +130,7 @@ export class EditorController implements IComponentController { 'MentionService', 'EditorService', 'ImageService', - ]; + ] /** * @@ -169,51 +169,51 @@ export class EditorController implements IComponentController { ) { this.deb = _.debounce((e) => { this.update().catch(() => { - this.growl.error('Error saving editor content'); - }); - }, 1000); + this.growl.error('Error saving editor content') + }) + }, 1000) } $onChanges(onChangesObj: angular.IOnChangesObject): void { if (onChangesObj.ngModel && !this.init) { - this.init = true; + this.init = true - this.id = this.editorSvc.createId(); + this.id = this.editorSvc.createId() this.editKey = this.elementSvc.getEditKey({ refId: this.mmsRefId, projectId: this.mmsProjectId, elementId: this.mmsElementId, - }); + }) if (this.editKey) { this.editorSvc.add( this.editKey, `${this.editField}${this.editIndex ? this.editIndex : ''}`, this.update - ); + ) } - this.startEditor(); + this.startEditor() } } $onDestroy(): void { - this.destroy(); + this.destroy() } public destroy(): void { - this.instance.config.autosave = { enableAutosave: false }; - this.editorSvc.remove(this.editKey, `${this.editField}${this.editIndex ? this.editIndex : ''}`); - if (this.ckEditor.instances[this.id]) this.ckEditor.instances[this.id].destroy(true); + this.instance.config.autosave = { enableAutosave: false } + this.editorSvc.remove(this.editKey, `${this.editField}${this.editIndex ? this.editIndex : ''}`) + if (this.ckEditor.instances[this.id]) this.ckEditor.instances[this.id].destroy(true) } public startEditor(): void { // Initialize ckeditor and set event handlers - if (this.ckEditor.instances[this.id]) return; - this.$element.empty(); - this.$transcludeEl = $(``); - this.$transcludeEl.val(this.ngModel); + if (this.ckEditor.instances[this.id]) return + this.$element.empty() + this.$transcludeEl = $(``) + this.$transcludeEl.val(this.ngModel) - this.$element.append(this.$transcludeEl); - this.$compile(this.$transcludeEl)(this.$scope); + this.$element.append(this.$transcludeEl) + this.$compile(this.$transcludeEl)(this.$scope) this.instance = this.ckEditor.replace(this.id, { mmscf: { callbackModalFnc: this.transcludeCallback }, @@ -222,7 +222,7 @@ export class EditorController implements IComponentController { mmsreset: { callback: this.mmsResetCallback }, contentsCss: `${this.ckEditor.basePath}contents.css`, toolbar: this.getToolbar(), - }); + }) // Enable Autosave plugin only when provided with unique identifier (editKey) if (this.editKey) { @@ -234,44 +234,44 @@ export class EditorController implements IComponentController { delay: 5, NotOlderThen: 7200, // 5 days in minutes enableAutosave: true, - }; + } } else { - this.instance.config.autosave = { enableAutosave: false }; + this.instance.config.autosave = { enableAutosave: false } } this.instance.on('instanceReady', () => { - this.addCkeditorHtmlFilterRule(this.instance); - this._addContextMenuItems(this.instance); - this.highlightActiveEditor(this.instance); - }); + this.addCkeditorHtmlFilterRule(this.instance) + this._addContextMenuItems(this.instance) + this.highlightActiveEditor(this.instance) + }) - this._addInlineMention(); + this._addInlineMention() this.instance.on( 'toHtml', () => { - this.addCkeditorDataFilterRules(this.instance); + this.addCkeditorDataFilterRules(this.instance) }, null, null, 9 - ); + ) this.instance.on('init', () => { this._waitForEditor(() => { - this.ngModelCtrl.$setPristine(); - }); - }); - - this.instance.on('change', (e) => this._waitForEditor(this.deb, e)); - this.instance.on('afterCommandExec', (e) => this._waitForEditor(this.deb, e)); - this.instance.on('resize', (e) => this._waitForEditor(this.deb, e)); - this.instance.on('beforeDestroy', (e) => this._waitForEditor(this.deb, e)); + this.ngModelCtrl.$setPristine() + }) + }) + + this.instance.on('change', (e) => this._waitForEditor(this.deb, e)) + this.instance.on('afterCommandExec', (e) => this._waitForEditor(this.deb, e)) + this.instance.on('resize', (e) => this._waitForEditor(this.deb, e)) + this.instance.on('beforeDestroy', (e) => this._waitForEditor(this.deb, e)) this.instance.on('blur', () => this._waitForEditor(() => { - this.instance.focusManager.blur(); + this.instance.focusManager.blur() }) - ); + ) this.instance.on( 'key', (e: CKEDITOR.eventInfo) => @@ -279,13 +279,13 @@ export class EditorController implements IComponentController { null, null, 31 - ); //priority is after indent list plugin's event handler + ) //priority is after indent list plugin's event handler this.instance.on('fileUploadRequest', (e: CKEDITOR.eventInfo) => { //this._waitForEditor((evt) => { - const fileLoader = e.data.fileLoader; - const formData = new FormData(); - const xhr = fileLoader.xhr; + const fileLoader = e.data.fileLoader + const formData = new FormData() + const xhr = fileLoader.xhr xhr.open( 'POST', @@ -295,31 +295,31 @@ export class EditorController implements IComponentController { elementId: this.apiSvc.createUniqueId().replace('MMS', '_hidden_image'), }), true - ); + ) //xhr.withCredentials = true; - xhr.setRequestHeader('Authorization', this.uRLSvc.getAuthorizationHeaderValue()); - formData.append('file', fileLoader.file, fileLoader.fileName); + xhr.setRequestHeader('Authorization', this.uRLSvc.getAuthorizationHeaderValue()) + formData.append('file', fileLoader.file, fileLoader.fileName) if (fileLoader.fileName) { - formData.append('name', fileLoader.fileName); + formData.append('name', fileLoader.fileName) } - fileLoader.xhr.send(formData); + fileLoader.xhr.send(formData) // Prevented the default behavior. - e.stop(); + e.stop() //}, e) - }); + }) this.instance.on('fileUploadResponse', (e: CKEDITOR.eventInfo) => { //this._waitForEditor((evt) => { // Prevent the default response handler. - e.stop(); + e.stop() // Get XHR and response. - const data = e.data; - const xhr = data.fileLoader.xhr; + const data = e.data + const xhr = data.fileLoader.xhr const response: ElementsResponse = JSON.parse( xhr.response as string - ) as ElementsResponse; + ) as ElementsResponse if ( !response.elements || @@ -329,54 +329,54 @@ export class EditorController implements IComponentController { ) { // An error occurred during upload. //data.message = response[ 1 ]; - e.cancel(); + e.cancel() } else { //TODO does this need to be smarter? - const element = response.elements[0]; + const element = response.elements[0] data.url = this.uRLSvc.getArtifactURL({ projectId: element._projectId, refId: element._refId, elementId: element.id, artifactExtension: element._artifacts[0].extension, - }); + }) } //}, e) - }); + }) } public highlightActiveEditor = (instance: CKEDITOR.editor): void => { - const activeEditorClass = 'activeditor'; - $('transclude-doc').children('div').removeClass(activeEditorClass); - $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass); + const activeEditorClass = 'activeditor' + $('transclude-doc').children('div').removeClass(activeEditorClass) + $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass) instance.on('focus', () => { - $('transclude-doc').children('div').removeClass(activeEditorClass); - $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass); - }); - }; + $('transclude-doc').children('div').removeClass(activeEditorClass) + $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass) + }) + } public addCkeditorDataFilterRules = (instance: CKEDITOR.editor): void => { instance.dataProcessor.dataFilter.addRules({ elements: { $: (element: CKEDITOR.htmlParser.element) => { if (element.name === 'script') { - element.remove(); - return; + element.remove() + return } if (element.name.startsWith('transclude-') || element.name.startsWith('present-')) { - element.replaceWithChildren(); - return; + element.replaceWithChildren() + return } const attributesToDelete = Object.keys(element.attributes).filter((attrKey) => { - return attrKey.startsWith('ng-'); - }); + return attrKey.startsWith('ng-') + }) attributesToDelete.forEach((attrToDelete) => { - delete element.attributes[attrToDelete]; - }); + delete element.attributes[attrToDelete] + }) }, }, - }); + }) instance.dataProcessor.dataFilter.addRules({ elements: { // Adds the token to img's in the editor environment to allow images to be displayed while editor @@ -388,39 +388,39 @@ export class EditorController implements IComponentController { el.attributes['data-cke-saved-src'] && (el.attributes['data-cke-saved-src'].indexOf(this.veConfig.apiUrl) > -1 || el.attributes['data-cke-saved-src'].indexOf('http') < 0) - ); + ) }, true) .forEach((el: CKEDITOR.htmlParser.element) => { - el.attributes['src'] = this.imageSvc.fixImgUrl(el.attributes['data-cke-saved-src'], true); + el.attributes['src'] = this.imageSvc.fixImgUrl(el.attributes['data-cke-saved-src'], true) // el.attributes['src'] = el.attributes['data-cke-saved-src']; - }); + }) }, }, - }); - }; + }) + } public addCkeditorHtmlFilterRule = (instance: CKEDITOR.editor): void => { instance.dataProcessor.htmlFilter.addRules({ elements: { $: (element: CKEDITOR.htmlParser.element) => { if (element.name === 'script') { - element.remove(); - return; + element.remove() + return } if (element.name.startsWith('transclude-') || element.name.startsWith('present-')) { - element.replaceWithChildren(); - return; + element.replaceWithChildren() + return } const attributesToDelete = Object.keys(element.attributes).filter((attrKey) => { - return attrKey.startsWith('ng-'); - }); + return attrKey.startsWith('ng-') + }) attributesToDelete.forEach((attrToDelete) => { - delete element.attributes[attrToDelete]; - }); + delete element.attributes[attrToDelete] + }) }, }, - }); + }) instance.dataProcessor.htmlFilter.addRules({ elements: { // Removes the token from the export src to prevent saving of token to server @@ -431,36 +431,36 @@ export class EditorController implements IComponentController { el.name == 'img' && el.attributes['data-cke-saved-src'] && el.attributes['data-cke-saved-src'].indexOf(this.veConfig.apiUrl) > -1 - ); + ) }, true) .forEach((el: CKEDITOR.htmlParser.element) => { el.attributes['data-cke-saved-src'] = this.imageSvc.fixImgUrl( el.attributes['data-cke-saved-src'], false - ); + ) // el.attributes['src'] = el.attributes['data-cke-saved-src']; - }); + }) }, }, - }); - }; + }) + } public getToolbar(): Array< | string | string[] | { - name: string; - items?: string[] | undefined; - groups?: string[] | undefined; + name: string + items?: string[] | undefined + groups?: string[] | undefined } > { let thisToolbar: Array< | string | string[] | { - name: string; - items?: string[] | undefined; - groups?: string[] | undefined; + name: string + items?: string[] | undefined + groups?: string[] | undefined } > = [ this.stylesToolbar, @@ -472,7 +472,7 @@ export class EditorController implements IComponentController { this.clipboardToolbar, this.editingToolbar, this.sourceToolbar, - ]; + ] switch (this.editorType) { // case 'TableT': // thisToolbar = [ @@ -499,17 +499,17 @@ export class EditorController implements IComponentController { this.clipboardToolbar, this.editingToolbar, this.sourceToolbar, - ]; - break; + ] + break case 'Equation': - thisToolbar = [this.justifyToolbar, this.equationToolbar, this.sourceToolbar]; - break; + thisToolbar = [this.justifyToolbar, this.equationToolbar, this.sourceToolbar] + break case 'Figure': case 'ImageT': - thisToolbar = [this.justifyToolbar, this.imageToolbar, this.sourceToolbar]; - break; + thisToolbar = [this.justifyToolbar, this.imageToolbar, this.sourceToolbar] + break } - return thisToolbar; + return thisToolbar } public transcludeCallback = (editor: CKEDITOR.editor): void => { @@ -521,30 +521,30 @@ export class EditorController implements IComponentController { type: 'Transclusion', viewLink: false, insertType: 'transclusion', - }; + } }, getProjectId: () => { - return this.mmsProjectId; + return this.mmsProjectId }, getRefId: () => { - return this.mmsRefId; + return this.mmsRefId }, getOrgId: () => { - return ''; + return '' }, }, size: 'lg', - }; - const tInstance = this.$uibModal.open, TransclusionObject>(tSettings); + } + const tInstance = this.$uibModal.open, TransclusionObject>(tSettings) tInstance.result.then( (result) => { - this._addWidgetTag(result.tag, editor); + this._addWidgetTag(result.tag, editor) }, () => { - editor.focus(); + editor.focus() } - ); - }; + ) + } // Controller for inserting view link // Defines scope variables for html template and how to handle user click @@ -560,30 +560,30 @@ export class EditorController implements IComponentController { type: 'ViewLink', viewLink: true, insertType: 'transclusion', - }; + } }, getProjectId: () => { - return this.mmsProjectId; + return this.mmsProjectId }, getRefId: () => { - return this.mmsRefId; + return this.mmsRefId }, getOrgId: () => { - return ''; + return '' }, }, size: 'lg', - }; - const tInstance = this.$uibModal.open, TransclusionObject>(tSettings); + } + const tInstance = this.$uibModal.open, TransclusionObject>(tSettings) tInstance.result.then( (result) => { - this._addWidgetTag(result.tag, editor); + this._addWidgetTag(result.tag, editor) }, () => { - editor.focus(); + editor.focus() } - ); - }; + ) + } public commentCallback = (editor: CKEDITOR.editor): void => { const cSettings: VeModalSettings> = { @@ -593,111 +593,111 @@ export class EditorController implements IComponentController { return { type: 'Comment', insertType: 'comment', - }; + } }, getProjectId: () => { - return this.mmsProjectId; + return this.mmsProjectId }, getRefId: () => { - return this.mmsRefId; + return this.mmsRefId }, getOrgId: () => { - return ''; + return '' }, }, - }; - const cInstance = this.$uibModal.open, ElementObject>(cSettings); + } + const cInstance = this.$uibModal.open, ElementObject>(cSettings) cInstance.result.then( (data) => { const tag = - 'comment:' + data._creator + ''; - this._addWidgetTag(tag, editor); + 'comment:' + data._creator + '' + this._addWidgetTag(tag, editor) }, (reason) => { if (reason && reason.status !== 444) { - this.growl.warning(`Error adding Comment: ${reason.message}`); + this.growl.warning(`Error adding Comment: ${reason.message}`) } else { this.growl.info('Commenting Cancelled', { ttl: 1000, - }); + }) } } - ); - }; + ) + } public resetCrossRef = (type: CKEDITOR.dom.node[], typeString: string): void => { type.forEach((node, key) => { - const value = node.$; - const transclusionObject = angular.element(value); - const transclusionId = transclusionObject.attr('mms-element-id'); + const value = node.$ + const transclusionObject = angular.element(value) + const transclusionId = transclusionObject.attr('mms-element-id') //TODO create Utils function to handle request objects const reqOb = { elementId: transclusionId, projectId: this.mmsProjectId, refId: this.mmsRefId, - }; + } this.elementSvc.getElement(reqOb, 2).then( (data) => { - transclusionObject.html('[cf:' + data.name + typeString); + transclusionObject.html('[cf:' + data.name + typeString) }, (reason) => { - let error: string; - if (reason.status === 410) error = 'deleted'; - if (reason.status === 404) error = 'not found'; - transclusionObject.html('[cf:' + error + typeString); + let error: string + if (reason.status === 410) error = 'deleted' + if (reason.status === 404) error = 'not found' + transclusionObject.html('[cf:' + error + typeString) } - ); - }); - }; + ) + }) + } public mmsResetCallback = (ed: CKEDITOR.editor): void => { - const body: CKEDITOR.dom.element = ed.document.getBody(); - this.resetCrossRef(body.find("mms-cf[mms-cf-type='name']").toArray(), '.name]'); - this.resetCrossRef(body.find("mms-cf[mms-cf-type='doc']").toArray(), '.doc]'); - this.resetCrossRef(body.find("mms-cf[mms-cf-type='val']").toArray(), '.val]'); - this.resetCrossRef(body.find('mms-view-link').toArray(), '.vlink]'); + const body: CKEDITOR.dom.element = ed.document.getBody() + this.resetCrossRef(body.find("mms-cf[mms-cf-type='name']").toArray(), '.name]') + this.resetCrossRef(body.find("mms-cf[mms-cf-type='doc']").toArray(), '.doc]') + this.resetCrossRef(body.find("mms-cf[mms-cf-type='val']").toArray(), '.val]') + this.resetCrossRef(body.find('mms-view-link').toArray(), '.vlink]') this.update().then( () => { /**/ }, () => { - this.growl.error('Error saving editor content'); + this.growl.error('Error saving editor content') } - ); - }; + ) + } public update = (destroy?: boolean): VePromise => { // getData() returns CKEditor's processed/clean HTML content. return new this.$q((resolve, reject) => { if (this.instance) { try { - this.ngModelCtrl.$setViewValue(this.instance.getData()); + this.ngModelCtrl.$setViewValue(this.instance.getData()) } catch (e) { reject({ status: 500, message: 'Error updating editor data', data: this.id, - }); + }) } } - if (destroy) this.destroy(); - resolve(true); - }); - }; + if (destroy) this.destroy() + resolve(true) + }) + } private _addWidgetTag = (tag: string, editor: CKEDITOR.editor): void => { - editor.insertHtml(tag); - this.editorSvc.focusOnEditorAfterAddingWidgetTag(editor); - }; + editor.insertHtml(tag) + this.editorSvc.focusOnEditorAfterAddingWidgetTag(editor) + } private _addInlineMention = (): void => { - let keyupHandler: CKEDITOR.listenerRegistration; + let keyupHandler: CKEDITOR.listenerRegistration this.ckEditor.instances[this.id].on('contentDom', () => { keyupHandler = this.ckEditor.instances[this.instance.name].document.on('keyup', (e) => { if (this._isMentionKey((e.data as CKEDITOR.dom.node).$)) { - this.mentionSvc.createMention(this.instance, this.$scope.$new(), this.mmsProjectId, this.mmsRefId); + this.mentionSvc.createMention(this.instance, this.$scope.$new(), this.mmsProjectId, this.mmsRefId) } else { this.mentionSvc.handleInput( e as CKEDITOR.eventInfo>, @@ -705,98 +705,98 @@ export class EditorController implements IComponentController { this.instance, this.mmsProjectId, this.mmsRefId - ); + ) } - }); - }); + }) + }) this.ckEditor.instances[this.id].on('contentDomUnload', () => { if (keyupHandler) { - keyupHandler.removeListener(); + keyupHandler.removeListener() } - }); - }; + }) + } private _keyHandler = (e: CKEDITOR.eventInfo): boolean => { if (this._isMentionKey(e.data.domEvent.$)) { - return false; // to prevent "@" from getting written to the editor + return false // to prevent "@" from getting written to the editor } // when tab is pressed or any of these special keys is pressed while the mention results show up, ignore default ckeditor's behaviour const ignoreDefaultBehaviour = - this._isTabKey(e) || (this._isSpecialKey(e) && this.mentionSvc.hasMentionResults(this.instance)); + this._isTabKey(e) || (this._isSpecialKey(e) && this.mentionSvc.hasMentionResults(this.instance)) if (ignoreDefaultBehaviour) { - e.cancel(); - e.stop(); + e.cancel() + e.stop() } if (this._isTabKey(e) && !this._isShiftKeyOn(e.data.domEvent.$)) { - this.instance.insertHtml('    '); + this.instance.insertHtml('    ') } if (!ignoreDefaultBehaviour) { - this.deb(e); + this.deb(e) } - return true; - }; + return true + } // 13 = enter, 38 = up arrow, 40 = down arrow private _isSpecialKey = (event: CKEDITOR.eventInfo): boolean => { - const key = event.data.domEvent.$.which; - return key === 13 || key === 38 || key === 40; - }; + const key = event.data.domEvent.$.which + return key === 13 || key === 38 || key === 40 + } private _isTabKey = (event: CKEDITOR.eventInfo): boolean => { - return event.data.domEvent.$.which === 9; - }; + return event.data.domEvent.$.which === 9 + } private _isMentionKey = (keyboardEvent: KeyboardEvent): boolean => { - return this._isShiftKeyOn(keyboardEvent) && keyboardEvent.key === '@'; - }; + return this._isShiftKeyOn(keyboardEvent) && keyboardEvent.key === '@' + } private _isShiftKeyOn = (keyboardEvent: KeyboardEvent): boolean => { - return keyboardEvent.shiftKey; - }; + return keyboardEvent.shiftKey + } private _addContextMenuItems = (editor: CKEDITOR.editor): void => { - this._addFormatAsCodeMenuItem(editor); - }; + this._addFormatAsCodeMenuItem(editor) + } private _addFormatAsCodeMenuItem = (editor: CKEDITOR.editor): void => { editor.addCommand('formatAsCode', { exec: (editor: CKEDITOR.editor) => { - const selected_text = editor.getSelection().getSelectedText(); - const newElement = new this.ckEditor.dom.element('code'); - newElement.addClass('inlineCode'); - newElement.setText(selected_text); - editor.insertElement(newElement); - return true; + const selected_text = editor.getSelection().getSelectedText() + const newElement = new this.ckEditor.dom.element('code') + newElement.addClass('inlineCode') + newElement.setText(selected_text) + editor.insertElement(newElement) + return true }, - }); - editor.addMenuGroup('veGroup'); + }) + editor.addMenuGroup('veGroup') editor.addMenuItem('formatAsCode', { label: 'Format as inline code', command: 'formatAsCode', group: 'group', icon: 'codeSnippet', - }); + }) editor.contextMenu.addListener((element) => { - return { formatAsCode: this.ckEditor.TRISTATE_OFF }; - }); - editor.setKeystroke(this.ckEditor.CTRL + 75, 'formatAsCode'); - }; + return { formatAsCode: this.ckEditor.TRISTATE_OFF } + }) + editor.setKeystroke(this.ckEditor.CTRL + 75, 'formatAsCode') + } private _waitForEditor>(fn: (e?: T) => void, evt?: T): void { - if (this.instance.status === 'loaded') fn(); + if (this.instance.status === 'loaded') fn() else { new this.$q((resolve) => { this.instance.on('loaded', () => { - fn(evt); - resolve(); - }); + fn(evt) + resolve() + }) }).catch((reason) => { - this.growl.error('CKEditor Error: ' + reason.message); - }); + this.growl.error('CKEditor Error: ' + reason.message) + }) } } } @@ -817,6 +817,6 @@ const EditorComponent: VeComponentOptions = { editIndex: '<', }, controller: EditorController, -}; +} -veCore.component(EditorComponent.selector, EditorComponent); +veCore.component(EditorComponent.selector, EditorComponent) diff --git a/src/ve-core/editor/index.ts b/src/ve-core/editor/index.ts index e4886f56b..803880c70 100644 --- a/src/ve-core/editor/index.ts +++ b/src/ve-core/editor/index.ts @@ -1,10 +1,10 @@ //Services -import './services'; +import './services' -export * from './services'; -export * from './editor-buttons.config'; +export * from './services' +export * from './editor-buttons.config' //Components -import './components/mention.component'; -import './components/mention-intercept.component'; -import './editor.component'; +import './components/mention.component' +import './components/mention-intercept.component' +import './editor.component' diff --git a/src/ve-core/editor/services/EditDialog.service.ts b/src/ve-core/editor/services/EditDialog.service.ts index 77d57ce8d..7f2093e55 100644 --- a/src/ve-core/editor/services/EditDialog.service.ts +++ b/src/ve-core/editor/services/EditDialog.service.ts @@ -1,13 +1,13 @@ -import { EditService } from '@ve-utils/core'; +import { EditService } from '@ve-utils/core' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { VeQService } from '@ve-types/angular'; -import { VeModalService } from '@ve-types/view-editor'; +import { VeQService } from '@ve-types/angular' +import { VeModalService } from '@ve-types/view-editor' export class EditDialogService { - static $inject = ['$q', '$uibModal', 'EditService']; + static $inject = ['$q', '$uibModal', 'EditService'] constructor(private $q: VeQService, private $uibModal: VeModalService, private autosaveSvc: EditService) {} } -veCore.service('EditDialogService', EditDialogService); +veCore.service('EditDialogService', EditDialogService) diff --git a/src/ve-core/editor/services/Editor.service.ts b/src/ve-core/editor/services/Editor.service.ts index 0dab2c763..6a84b4455 100644 --- a/src/ve-core/editor/services/Editor.service.ts +++ b/src/ve-core/editor/services/Editor.service.ts @@ -1,24 +1,24 @@ -import angular from 'angular'; -import $ from 'jquery'; +import angular from 'angular' +import $ from 'jquery' -import { SaveConflictResolveFn } from '@ve-components/diffs'; -import { EditDialogService } from '@ve-core/editor'; -import { ConfirmDeleteModalResolveFn } from '@ve-core/modals'; -import { ToolbarService } from '@ve-core/toolbar'; -import { CacheService, EditObject, EditService, EventService } from '@ve-utils/core'; -import { ApiService, ElementService, PermissionsService, ViewService, ValueService } from '@ve-utils/mms-api-client'; +import { SaveConflictResolveFn } from '@ve-components/diffs' +import { EditDialogService } from '@ve-core/editor' +import { ConfirmDeleteModalResolveFn } from '@ve-core/modals' +import { ToolbarService } from '@ve-core/toolbar' +import { CacheService, EditObject, EditService, EventService } from '@ve-utils/core' +import { ApiService, ElementService, PermissionsService, ViewService, ValueService } from '@ve-utils/mms-api-client' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { BasicResponse, ElementObject, ElementsResponse, MmsObject } from '@ve-types/mms'; -import { VeModalInstanceService, VeModalService, VeModalSettings } from '@ve-types/view-editor'; +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { BasicResponse, ElementObject, ElementsResponse, MmsObject } from '@ve-types/mms' +import { VeModalInstanceService, VeModalService, VeModalSettings } from '@ve-types/view-editor' export class EditorService { - public generatedIds: number = 0; + public generatedIds: number = 0 private edit2editor: { [editKey: string]: { [field: string]: (destroy?: boolean) => VePromise } } = - {}; - public savingAll: boolean = false; + {} + public savingAll: boolean = false static $inject = [ '$q', @@ -35,7 +35,7 @@ export class EditorService { 'EditDialogService', 'EventService', 'EditService', - ]; + ] constructor( private $q: VeQService, @@ -55,7 +55,7 @@ export class EditorService { ) {} public get(editKey: string): { [field: string]: () => VePromise } { - return this.edit2editor[editKey]; + return this.edit2editor[editKey] } public updateAllData( @@ -63,20 +63,20 @@ export class EditorService { allowNone?: boolean, destroy?: boolean ): VePromise> { - const key: string = this.editSvc.makeKey(editKey); + const key: string = this.editSvc.makeKey(editKey) return new this.$q>((resolve, reject) => { if (this.edit2editor[key]) { - const promises: VePromise[] = []; + const promises: VePromise[] = [] for (const id of Object.keys(this.edit2editor[key])) { - promises.push(this.edit2editor[key][id](destroy)); + promises.push(this.edit2editor[key][id](destroy)) } - this.$q.all(promises).then(resolve, reject); + this.$q.all(promises).then(resolve, reject) } else if (allowNone) { - resolve(); + resolve() } else { - reject({ status: 500, message: 'No editors present to update from' }); + reject({ status: 500, message: 'No editors present to update from' }) } - }); + }) } public add( @@ -84,87 +84,87 @@ export class EditorService { field: string, updateFn: (destroy?: boolean) => VePromise ): void { - editKey = this.editSvc.makeKey(editKey); - if (!this.edit2editor[editKey]) this.edit2editor[editKey] = {}; - this.edit2editor[editKey][field] = updateFn; + editKey = this.editSvc.makeKey(editKey) + if (!this.edit2editor[editKey]) this.edit2editor[editKey] = {} + this.edit2editor[editKey][field] = updateFn } public remove(editKey: string | string[], field: string): void { - editKey = Array.isArray(editKey) ? editKey.join('|') : editKey; + editKey = Array.isArray(editKey) ? editKey.join('|') : editKey if (this.edit2editor[editKey] && this.edit2editor[editKey][field]) { this.edit2editor[editKey][field]().finally(() => { - delete this.edit2editor[editKey as string][field]; + delete this.edit2editor[editKey as string][field] if (Object.keys(this.edit2editor[editKey as string]).length === 0) { - delete this.edit2editor[editKey as string]; + delete this.edit2editor[editKey as string] } - }); + }) } } public createId(): string { - return `mmsCKEditor${this.generatedIds++}`; + return `mmsCKEditor${this.generatedIds++}` } public focusOnEditorAfterAddingWidgetTag(editor: CKEDITOR.editor): void { - const element = editor.widgets.focused.element.getParent(); - editor.focusManager.focus(element); + const element = editor.widgets.focused.element.getParent() + editor.focusManager.focus(element) } public save = (editKey: string | string[], continueEdit: boolean): VePromise => { - this.eventSvc.$broadcast('element-saving', true); + this.eventSvc.$broadcast('element-saving', true) return new this.$q((resolve, reject) => { this._save(editKey, continueEdit).then( (data) => { - this.eventSvc.$broadcast('element-saving', false); + this.eventSvc.$broadcast('element-saving', false) if (!data) { - this.growl.info('Save Skipped (No Changes)'); + this.growl.info('Save Skipped (No Changes)') } else { - this.growl.success('Save Successful'); + this.growl.success('Save Successful') } - resolve(data); + resolve(data) }, (reason) => { - this.eventSvc.$broadcast('element-saving', false); - reject(reason); + this.eventSvc.$broadcast('element-saving', false) + reject(reason) } - ); - }); - }; + ) + }) + } public saveAll = (): VePromise => { if (this.savingAll) { - this.growl.info('Please wait...'); - return this.$q.resolve(); + this.growl.info('Please wait...') + return this.$q.resolve() } if (this.editSvc.openEdits() === 0) { - this.growl.info('Nothing to save'); - return this.$q.resolve(); + this.growl.info('Nothing to save') + return this.$q.resolve() } - this.savingAll = true; + this.savingAll = true return new this.$q((resolve, reject) => { this.elementSvc .updateElements( Object.values(this.editSvc.getAll()).map((editOb) => { - return editOb.element; + return editOb.element }) ) .then((responses) => { responses.forEach((elementOb) => { - const edit = this.editSvc.get(this.elementSvc.getEditElementKey(elementOb)); - this.cleanUpEdit(edit.key); + const edit = this.editSvc.get(this.elementSvc.getEditElementKey(elementOb)) + this.cleanUpEdit(edit.key) const data = { element: elementOb, continueEdit: false, - }; - this.eventSvc.$broadcast('element.updated', data); - }); - this.growl.success('Save All Successful'); - resolve(); - }, reject); - }); - }; + } + this.eventSvc.$broadcast('element.updated', data) + }) + this.growl.success('Save All Successful') + resolve() + }, reject) + }) + } /** * @name Utils#save @@ -182,44 +182,44 @@ export class EditorService { return new this.$q((resolve, reject) => { this.updateAllData(editKey, true, true).then( () => { - const edit = this.editSvc.get(editKey).element; + const edit = this.editSvc.get(editKey).element this.elementSvc.updateElement(edit, false, true).then( (element: T) => { const data = { element: element, continueEdit: continueEdit ? continueEdit : false, - }; - this.eventSvc.$broadcast('element.updated', data); - this.cleanUpEdit(editKey); - resolve(element); + } + this.eventSvc.$broadcast('element.updated', data) + this.cleanUpEdit(editKey) + resolve(element) }, (reason: VePromiseReason>) => { if (reason.status === 409) { - const latest = reason.data.elements[0]; + const latest = reason.data.elements[0] this.saveConflictDialog(latest).result.then( (data) => { - const choice = data; + const choice = data if (choice === 'ok') { const reqOb = { elementId: latest.id, projectId: latest._projectId, refId: latest._refId, commitId: 'latest', - }; - this.cleanUpEdit(editKey); - resolve(this.elementSvc.cacheElement(reqOb, latest)); + } + this.cleanUpEdit(editKey) + resolve(this.elementSvc.cacheElement(reqOb, latest)) } else if (choice === 'force') { - edit._modified = latest._modified; + edit._modified = latest._modified this._save(editKey, continueEdit).then( (resolved) => { - resolve(resolved); + resolve(resolved) }, (error) => { - reject(error); + reject(error) } - ); + ) } else { - reject({ status: 444, type: 'info', message: 'Save cancelled!' }); + reject({ status: 444, type: 'info', message: 'Save cancelled!' }) } }, () => { @@ -227,25 +227,25 @@ export class EditorService { status: 500, message: 'An error occurred. Please try your request again', type: 'error', - }); + }) } - ); + ) } else { - reason.type = 'error'; - reject(reason); + reason.type = 'error' + reject(reason) } } - ); + ) }, () => { reject({ status: 500, message: 'Error Saving from Editor; Please Retry', type: 'error', - }); + }) } - ); - }); + ) + }) } /** @@ -262,8 +262,8 @@ export class EditorService { editOb: EditObject, field?: 'name' | 'value' | 'documentation' ): VePromise> => { - const edit = editOb.element; - edit._commitId = 'latest'; + const edit = editOb.element + edit._commitId = 'latest' return new this.$q>((resolve) => { this.updateAllData(editOb.key, true, false).then( () => { @@ -271,42 +271,42 @@ export class EditorService { (elementOb) => { if (elementOb) { if ((!field || field === 'name') && edit.name !== elementOb.name) { - resolve(true); + resolve(true) } if ( (!field || field === 'documentation') && edit.documentation !== elementOb.documentation ) { - resolve(true); + resolve(true) } if ( this.valueSvc.isValue(edit) && (!field || field === 'value') && !this.valueSvc.isEqual(edit, elementOb) ) { - resolve(true); + resolve(true) } - resolve(false); + resolve(false) } else if ( edit.id.endsWith('_temp') && (edit.name || edit.documentation || this.valueSvc.hasValue(edit)) ) { - resolve(true); + resolve(true) } else { - resolve(false); + resolve(false) } }, () => { - resolve(false); + resolve(false) } - ); + ) }, () => { - resolve(false); + resolve(false) } - ); - }); - }; + ) + }) + } /** * @name Utils#openEdit @@ -332,62 +332,62 @@ export class EditorService { elementId: elementOb.id, projectId: elementOb._projectId, refId: elementOb._refId, - }; + } if (!this.permissionsSvc.hasBranchEditPermission(elementOb._projectId, elementOb._refId)) { - reject({ message: 'No edit permission on branch', status: 403 }); - return; + reject({ message: 'No edit permission on branch', status: 403 }) + return } this.elementSvc.getElementForEdit(reqOb).then( (edit) => { if (this.valueSvc.isValue(edit.element)) { - edit.values = this.valueSvc.getValues(edit.element); + edit.values = this.valueSvc.getValues(edit.element) } - resolve(edit); + resolve(edit) }, (reason) => { - reject(reason); + reject(reason) } - ); - }); - }); + ) + }) + }) } public cleanUpEdit(editKey: string | string[]): void { - this.clearAutosave(editKey); - this.editSvc.remove(editKey); + this.clearAutosave(editKey) + this.editSvc.remove(editKey) // Broadcast message for the ToolCtrl: - this.eventSvc.$broadcast('editor.close'); + this.eventSvc.$broadcast('editor.close') } public clearAutosave = (key: string | string[], field?: string): void => { - key = this.editSvc.makeKey(key); - if (field) key = key + '|' + field; + key = this.editSvc.makeKey(key) + if (field) key = key + '|' + field Object.keys(window.localStorage).forEach((akey) => { if (akey.indexOf(key as string) !== -1) { - window.localStorage.removeItem(akey); + window.localStorage.removeItem(akey) } - }); - }; + }) + } private _makeKey(key: string | string[]): string { - return Array.isArray(key) ? key.join('|') : key; + return Array.isArray(key) ? key.join('|') : key } public handleError(reason: { message: string; type: 'error' | 'warning' | 'info' } | VePromiseReason): void { - if (reason.type === 'info') this.growl.info(reason.message); - else if (reason.type === 'warning') this.growl.warning(reason.message); - else if (reason.type === 'error') this.growl.error(reason.message); + if (reason.type === 'info') this.growl.info(reason.message) + else if (reason.type === 'warning') this.growl.warning(reason.message) + else if (reason.type === 'error') this.growl.error(reason.message) } public updateEditor(editKey: string | string[], field: string): VePromise { return new this.$q((resolve, reject) => { - editKey = this.editSvc.makeKey(editKey); + editKey = this.editSvc.makeKey(editKey) if (this.edit2editor[editKey] && this.edit2editor[editKey][field]) { - this.edit2editor[editKey][field]().then(resolve, reject); + this.edit2editor[editKey][field]().then(resolve, reject) } else { - resolve(true); // continue for non ckeditor transcludes + resolve(true) // continue for non ckeditor transcludes } - }); + }) } /** @@ -413,9 +413,9 @@ export class EditorService { public scrollToElement = (domElement: JQuery): void => { this.$timeout( () => { - const el = domElement[0]; - if ($(domElement).isOnScreen()) return; - el.scrollIntoView(); + const el = domElement[0] + if ($(domElement).isOnScreen()) return + el.scrollIntoView() }, 500, false @@ -426,8 +426,8 @@ export class EditorService { () => { /**/ } - ); - }; + ) + } saveConflictDialog(latest: T): VeModalInstanceService { return this.$uibModal.open, string>({ @@ -435,10 +435,10 @@ export class EditorService { size: 'lg', resolve: { latest: () => { - return latest; + return latest }, }, - }); + }) } public deleteEditModal(editOb: EditObject): VeModalInstanceService { @@ -446,19 +446,19 @@ export class EditorService { component: 'confirmDeleteModal', resolve: { getName: () => { - return `${editOb.element.type} ${editOb.element.id}`; + return `${editOb.element.type} ${editOb.element.id}` }, getType: () => { - return 'edit'; + return 'edit' }, finalize: () => { return () => { - return this.$q.resolve(); - }; + return this.$q.resolve() + } }, }, - }; - return this.$uibModal.open(settings); + } + return this.$uibModal.open(settings) } public deleteConfirmModal(edit: EditObject): VeModalInstanceService { @@ -466,21 +466,21 @@ export class EditorService { component: 'confirmDeleteModal', resolve: { getType: () => { - return edit.element.type ? edit.element.type : 'element'; + return edit.element.type ? edit.element.type : 'element' }, getName: () => { - return edit.element.name ? edit.element.name : 'Element'; + return edit.element.name ? edit.element.name : 'Element' }, finalize: () => { return () => { - this.cleanUpEdit(edit.key); - return this.$q.resolve(); - }; + this.cleanUpEdit(edit.key) + return this.$q.resolve() + } }, }, - }; - return this.$uibModal.open(settings); + } + return this.$uibModal.open(settings) } } -veCore.service('EditorService', EditorService); +veCore.service('EditorService', EditorService) diff --git a/src/ve-core/editor/services/Mention.service.ts b/src/ve-core/editor/services/Mention.service.ts index 4e350466d..61483e979 100644 --- a/src/ve-core/editor/services/Mention.service.ts +++ b/src/ve-core/editor/services/Mention.service.ts @@ -1,36 +1,36 @@ -import $ from 'jquery'; -import moment from 'moment'; +import $ from 'jquery' +import moment from 'moment' -import { MMSMentionController } from '@ve-core/editor/components/mention.component'; -import { UtilsService } from '@ve-utils/application'; -import { CacheService } from '@ve-utils/core'; -import { ApiService, ViewService } from '@ve-utils/mms-api-client'; +import { MMSMentionController } from '@ve-core/editor/components/mention.component' +import { UtilsService } from '@ve-utils/application' +import { CacheService } from '@ve-utils/core' +import { ApiService, ViewService } from '@ve-utils/mms-api-client' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { ElementObject } from '@ve-types/mms'; +import { ElementObject } from '@ve-types/mms' export interface MentionScope extends angular.IScope { - mmsEditor?: CKEDITOR.editor; - mmsMentionValue?: string; - mmsMentionId?: string; - mmsProjectId?: string; - mmsRefId?: string; + mmsEditor?: CKEDITOR.editor + mmsMentionValue?: string + mmsMentionId?: string + mmsProjectId?: string + mmsRefId?: string } export interface MentionState { - mentionScope: MentionScope; - mentionController: MMSMentionController; - mentionElement: JQLite; - mentionId: string; - mentionPlaceHolderId: string; + mentionScope: MentionScope + mentionController: MMSMentionController + mentionElement: JQLite + mentionId: string + mentionPlaceHolderId: string } export class MentionService { - mentions: { [id: string]: MentionState } = {}; - mentionPlacerHolderPrefix = 'mentionPlaceHolder'; + mentions: { [id: string]: MentionState } = {} + mentionPlacerHolderPrefix = 'mentionPlaceHolder' - static $inject = ['$compile', '$timeout', 'growl', 'CacheService', 'ViewService', 'UtilsService', 'ApiService']; + static $inject = ['$compile', '$timeout', 'growl', 'CacheService', 'ViewService', 'UtilsService', 'ApiService'] constructor( private $compile: angular.ICompileService, @@ -44,26 +44,26 @@ export class MentionService { /** Used to maintain all mention in all ckeditors **/ public getFastCfListing(projectId: string, refId: string): ElementObject[] { - const latestElements: ElementObject[] = this.cacheSvc.getLatestElements(projectId, refId); + const latestElements: ElementObject[] = this.cacheSvc.getLatestElements(projectId, refId) latestElements.reduce( ( result: { - id: string; - name: string; - type: string; - iconClass: string; - documentation?: string; - editor: string; - editTime: string; - elementType: string; - value?: string; + id: string + name: string + type: string + iconClass: string + documentation?: string + editor: string + editTime: string + elementType: string + value?: string }[], cacheElement ) => { - const elementType = this.viewSvc.getElementType(cacheElement); - const elementName = cacheElement.name ? cacheElement.name : cacheElement.id; - const iconClass = this.utilsSvc.getElementTypeClass(cacheElement, elementType); + const elementType = this.viewSvc.getElementType(cacheElement) + const elementName = cacheElement.name ? cacheElement.name : cacheElement.id + const iconClass = this.utilsSvc.getElementTypeClass(cacheElement, elementType) result.push({ id: cacheElement.id, name: elementName, @@ -73,7 +73,7 @@ export class MentionService { editor: cacheElement._modifier, editTime: moment(cacheElement._modified).fromNow(), elementType: elementType ? elementType : cacheElement.type, - }); + }) if (cacheElement.documentation != undefined) { result.push({ id: cacheElement.id, @@ -84,13 +84,13 @@ export class MentionService { editor: cacheElement._modifier, editTime: moment(cacheElement._modified).fromNow(), elementType: elementType || cacheElement.type, - }); + }) } if (cacheElement.type === 'Property' && cacheElement.defaultValue) { - let value = String(cacheElement.defaultValue.value); + let value = String(cacheElement.defaultValue.value) if (!value || value === 'undefined') { - value = 'this field is empty'; + value = 'this field is empty' } result.push({ id: cacheElement.id, @@ -101,13 +101,13 @@ export class MentionService { editor: cacheElement._modifier, editTime: moment(cacheElement._modified).fromNow(), elementType: cacheElement.type, - }); + }) } - return result; + return result }, [] - ); - return latestElements; + ) + return latestElements } public createMention( @@ -116,17 +116,17 @@ export class MentionService { projectId: string, refId: string, existingMentionPlaceHolder?: { - mentionId: string; - mentionPlaceHolderId: string; + mentionId: string + mentionPlaceHolderId: string } ): void { - const mentionId = existingMentionPlaceHolder ? existingMentionPlaceHolder.mentionId : this.apiSvc.createUUID(); + const mentionId = existingMentionPlaceHolder ? existingMentionPlaceHolder.mentionId : this.apiSvc.createUUID() const mentionPlaceHolderId = existingMentionPlaceHolder ? existingMentionPlaceHolder.mentionPlaceHolderId - : this._createMentionPlaceHolder(editor, mentionId); - const mention = this._createMentionDirective(editor, mentionScope, mentionId, projectId, refId); - this._createNewMentionState(editor, mention, mentionPlaceHolderId, mentionId); - MentionService._positionMentionElement(editor, mention, mentionPlaceHolderId); + : this._createMentionPlaceHolder(editor, mentionId) + const mention = this._createMentionDirective(editor, mentionScope, mentionId, projectId, refId) + this._createNewMentionState(editor, mention, mentionPlaceHolderId, mentionId) + MentionService._positionMentionElement(editor, mention, mentionPlaceHolderId) } public handleInput( @@ -137,57 +137,57 @@ export class MentionService { refId: string ): void { if (editor._ && editor._.elementsPath) { - const elementsPath = editor._.elementsPath; - const currentEditingElement = elementsPath.list[0].$; - const currentEditingElementId = currentEditingElement.getAttribute('id'); - const mentionId = this._getMentionIdFromMentionPlaceHolder(currentEditingElementId); + const elementsPath = editor._.elementsPath + const currentEditingElement = elementsPath.list[0].$ + const currentEditingElementId = currentEditingElement.getAttribute('id') + const mentionId = this._getMentionIdFromMentionPlaceHolder(currentEditingElementId) if (mentionId) { - let mentionState = this._retrieveMentionState(editor.id, mentionId); + let mentionState = this._retrieveMentionState(editor.id, mentionId) // logic to reactivate existing "@" when reloading ckeditor if (!mentionState) { this.createMention(editor, newScope, projectId, refId, { mentionId: mentionId, mentionPlaceHolderId: currentEditingElementId, - }); - mentionState = this._retrieveMentionState(editor.id, mentionId); + }) + mentionState = this._retrieveMentionState(editor.id, mentionId) } - const mentionScope = mentionState.mentionScope; + const mentionScope = mentionState.mentionScope mentionScope.$apply(() => { - let text = currentEditingElement.innerText; - text = text.substring(1); // ignore @ - mentionScope.mmsMentionValue = text; - this._repositionDropdownIfOffScreen(editor, mentionState); - }); + let text = currentEditingElement.innerText + text = text.substring(1) // ignore @ + mentionScope.mmsMentionValue = text + this._repositionDropdownIfOffScreen(editor, mentionState) + }) - this._handleSpecialKeys(event, mentionId, editor, projectId, refId); + this._handleSpecialKeys(event, mentionId, editor, projectId, refId) } } } public handleMentionSelection(editor: CKEDITOR.editor, mentionId: string): void { - this._cleanup(editor, mentionId); + this._cleanup(editor, mentionId) } public removeAllMentionForEditor(editor: CKEDITOR.editor): void { Object.keys(this.mentions) .filter((key) => { - const splits = key.split('-'); - return splits[0] === editor.id; + const splits = key.split('-') + return splits[0] === editor.id }) .forEach((key) => { - this._cleanup(editor, key.split('-')[1]); - }); + this._cleanup(editor, key.split('-')[1]) + }) } public hasMentionResults(editor: CKEDITOR.editor): boolean { - const currentEditingElement = editor._.elementsPath.list[0].$; - const currentEditingElementId = currentEditingElement.getAttribute('id'); - const mentionId = this._getMentionIdFromMentionPlaceHolder(currentEditingElementId); + const currentEditingElement = editor._.elementsPath.list[0].$ + const currentEditingElementId = currentEditingElement.getAttribute('id') + const mentionId = this._getMentionIdFromMentionPlaceHolder(currentEditingElementId) if (mentionId) { - return MentionService._hasMentionResults(mentionId); + return MentionService._hasMentionResults(mentionId) } - return false; + return false } private static _hasMentionResults(mentionId: string): boolean { @@ -195,7 +195,7 @@ export class MentionService { $('#' + mentionId) .find('ul') .children().length > 0 - ); + ) } private _createMentionDirective( @@ -205,18 +205,18 @@ export class MentionService { projectId: string, refId: string ): JQLite { - mentionScope.mmsEditor = editor; - mentionScope.mmsMentionValue = ''; - mentionScope.mmsMentionId = mentionId; - mentionScope.mmsProjectId = projectId; - mentionScope.mmsRefId = refId; + mentionScope.mmsEditor = editor + mentionScope.mmsMentionValue = '' + mentionScope.mmsMentionId = mentionId + mentionScope.mmsProjectId = projectId + mentionScope.mmsRefId = refId return this.$compile( '' - )(mentionScope); + )(mentionScope) } private static _getCkeditorFrame(editor: CKEDITOR.editor): HTMLIFrameElement { - return editor.container.$.getElementsByTagName('iframe')[0]; + return editor.container.$.getElementsByTagName('iframe')[0] } private static _positionMentionElement( @@ -224,16 +224,16 @@ export class MentionService { mentionElement: JQLite, mentionPlaceHolderId: string ): void { - const ckeditorFrame = MentionService._getCkeditorFrame(editor); - const ckeditorBox = ckeditorFrame.getBoundingClientRect(); - const mentionPlaceHolder = ckeditorFrame.contentDocument.getElementById(mentionPlaceHolderId); - const mentionPlaceHolderBox = $(mentionPlaceHolder)[0].getBoundingClientRect(); + const ckeditorFrame = MentionService._getCkeditorFrame(editor) + const ckeditorBox = ckeditorFrame.getBoundingClientRect() + const mentionPlaceHolder = ckeditorFrame.contentDocument.getElementById(mentionPlaceHolderId) + const mentionPlaceHolderBox = $(mentionPlaceHolder)[0].getBoundingClientRect() mentionElement.css({ position: 'absolute', top: ckeditorBox.top + mentionPlaceHolderBox.top + 30, left: ckeditorBox.left + mentionPlaceHolderBox.left, - }); - $('body').append(mentionElement); + }) + $('body').append(mentionElement) } private _createNewMentionState( @@ -242,64 +242,64 @@ export class MentionService { mentionPlaceHolderId: string, mentionId: string ): MentionState { - const key = MentionService._getMentionStateId(editor.id, mentionId); + const key = MentionService._getMentionStateId(editor.id, mentionId) const value: MentionState = { mentionScope: mention.scope(), mentionController: mention.controller() as MMSMentionController, mentionElement: mention, mentionId: mentionId, mentionPlaceHolderId: mentionPlaceHolderId, - }; - this.mentions[key] = value; - return value; + } + this.mentions[key] = value + return value } private _retrieveMentionState = (editorId: string, mentionId: string): MentionState => { - return this.mentions[MentionService._getMentionStateId(editorId, mentionId)]; - }; + return this.mentions[MentionService._getMentionStateId(editorId, mentionId)] + } private static _getMentionStateId(editorId: string, mentionId: string): string { - return editorId + '-' + mentionId; + return editorId + '-' + mentionId } private _createMentionPlaceHolder(editor: CKEDITOR.editor, mentionId: string): string { - const id = this.mentionPlacerHolderPrefix + '-' + editor.id + '-' + mentionId; - const mentionPlaceHolder = '@'; - editor.insertHtml(mentionPlaceHolder); - return id; + const id = this.mentionPlacerHolderPrefix + '-' + editor.id + '-' + mentionId + const mentionPlaceHolder = '@' + editor.insertHtml(mentionPlaceHolder) + return id } private _getMentionIdFromMentionPlaceHolder = (currentEditingElementId: string): string => { if (currentEditingElementId && currentEditingElementId.indexOf(this.mentionPlacerHolderPrefix) > -1) { - const splits = currentEditingElementId.split('-'); - return splits[2]; + const splits = currentEditingElementId.split('-') + return splits[2] } - return null; - }; + return null + } private _cleanup(editor: CKEDITOR.editor, mentionId: string, unwrapOnly?): void { - const mentionState = this._retrieveMentionState(editor.id, mentionId); - const mentionPlaceHolderId = mentionState.mentionPlaceHolderId; - const mentionPlaceHolderDom = editor.document.getById(mentionPlaceHolderId); + const mentionState = this._retrieveMentionState(editor.id, mentionId) + const mentionPlaceHolderId = mentionState.mentionPlaceHolderId + const mentionPlaceHolderDom = editor.document.getById(mentionPlaceHolderId) if (unwrapOnly) { - const range = editor.createRange(); + const range = editor.createRange() if (range && mentionPlaceHolderDom) { - range.moveToClosestEditablePosition(mentionPlaceHolderDom, true); - $(mentionPlaceHolderDom.$).contents().unwrap(); - range.select(); + range.moveToClosestEditablePosition(mentionPlaceHolderDom, true) + $(mentionPlaceHolderDom.$).contents().unwrap() + range.select() } } else { // remove the mentionPlaceHolder - mentionPlaceHolderDom.remove(); + mentionPlaceHolderDom.remove() } // cleanup the mention directive - const mentionScope = mentionState.mentionScope; - mentionScope.$destroy(); + const mentionScope = mentionState.mentionScope + mentionScope.$destroy() // remove the mention dom - const mentionElement = mentionState.mentionElement; - mentionElement.remove(); + const mentionElement = mentionState.mentionElement + mentionElement.remove() // remove the mention state - delete this.mentions[MentionService._getMentionStateId(editor.id, mentionId)]; + delete this.mentions[MentionService._getMentionStateId(editor.id, mentionId)] } private _handleSpecialKeys( @@ -311,81 +311,81 @@ export class MentionService { ): void { switch (evt.data.$.which) { case 38: // up arrow - this._handleArrowKey(mentionId, false); - break; + this._handleArrowKey(mentionId, false) + break case 40: // down arrow - this._handleArrowKey(mentionId, true); - break; + this._handleArrowKey(mentionId, true) + break case 13: // enter - this._handleEnterKey(editor.id, mentionId, projectId, refId); - break; + this._handleEnterKey(editor.id, mentionId, projectId, refId) + break case 27: // esc - this._handleEscKey(editor, mentionId); + this._handleEscKey(editor, mentionId) } } private _getMentionItem = (key: string, projectId: string, refId: string): ElementObject => { - const cfListing = this.getFastCfListing(projectId, refId); + const cfListing = this.getFastCfListing(projectId, refId) return cfListing.find((cf) => { - return cf.id + cf.type === key; - }); - }; + return cf.id + cf.type === key + }) + } private _handleEnterKey = (editorId: string, mentionId: string, projectId: string, refId: string): void => { - const matchDom = $('#' + mentionId + ' .active .mentionMatch'); + const matchDom = $('#' + mentionId + ' .active .mentionMatch') if (matchDom.length > 0) { - const key = matchDom.attr('id'); - const mentionItem = this._getMentionItem(key, projectId, refId); - const mentionState = this._retrieveMentionState(editorId, mentionId); - mentionState.mentionController.selectMentionItem(mentionItem); + const key = matchDom.attr('id') + const mentionItem = this._getMentionItem(key, projectId, refId) + const mentionState = this._retrieveMentionState(editorId, mentionId) + mentionState.mentionController.selectMentionItem(mentionItem) } - }; + } private _handleEscKey(editor: CKEDITOR.editor, mentionId: string): void { - this._cleanup(editor, mentionId, true); + this._cleanup(editor, mentionId, true) } private _handleArrowKey = (mentionId: string, isDownArrow: boolean): void => { - const popUpEl = $('#' + mentionId); - const allOptions = popUpEl.find('li'); - const len = allOptions.length; - let activeIndex = -1; + const popUpEl = $('#' + mentionId) + const allOptions = popUpEl.find('li') + const len = allOptions.length + let activeIndex = -1 allOptions.each((index) => { if ($(this).hasClass('active')) { - activeIndex = index; + activeIndex = index } - }); + }) if (activeIndex !== -1) { - let nextIndex: number; + let nextIndex: number if (isDownArrow) { - nextIndex = (activeIndex + 1) % len; + nextIndex = (activeIndex + 1) % len } else { if (activeIndex === 0) { - nextIndex = len - 1; + nextIndex = len - 1 } else { - nextIndex = (activeIndex - 1) % len; + nextIndex = (activeIndex - 1) % len } } - const target = $(allOptions[nextIndex]); - target.addClass('active'); - $(allOptions[activeIndex]).removeClass('active'); + const target = $(allOptions[nextIndex]) + target.addClass('active') + $(allOptions[activeIndex]).removeClass('active') // scroll if necessary - (target[0].parentNode).scrollTop = target[0].offsetTop; + ;(target[0].parentNode).scrollTop = target[0].offsetTop } - }; + } private _repositionDropdownIfOffScreen(editor: CKEDITOR.editor, mentionState: MentionState): void { // wait for dropdown result to render so that we can determine whether it is on/off-screen this.$timeout( () => { - const mentionElement = mentionState.mentionElement; - const dropdownResultElement = mentionElement.find('ul.dropdown-menu'); + const mentionElement = mentionState.mentionElement + const dropdownResultElement = mentionElement.find('ul.dropdown-menu') if (dropdownResultElement.children().length > 0 && !dropdownResultElement.isOnScreen()) { - const ckeditorBox = MentionService._getCkeditorFrame(editor).getBoundingClientRect(); + const ckeditorBox = MentionService._getCkeditorFrame(editor).getBoundingClientRect() mentionElement.css({ top: ckeditorBox.top, left: ckeditorBox.left, - }); + }) } }, 0, @@ -397,8 +397,8 @@ export class MentionService { () => { /*Do Nothing*/ } - ); + ) } } -veCore.service('MentionService', MentionService); +veCore.service('MentionService', MentionService) diff --git a/src/ve-core/editor/services/index.ts b/src/ve-core/editor/services/index.ts index bc9551bf3..401541c1a 100644 --- a/src/ve-core/editor/services/index.ts +++ b/src/ve-core/editor/services/index.ts @@ -1,8 +1,8 @@ //Services -import './Editor.service'; -import './Mention.service'; -import './EditDialog.service'; +import './Editor.service' +import './Mention.service' +import './EditDialog.service' -export * from './Editor.service'; -export * from './Mention.service'; -export * from './EditDialog.service'; +export * from './Editor.service' +export * from './Mention.service' +export * from './EditDialog.service' diff --git a/src/ve-core/events.d.ts b/src/ve-core/events.d.ts index 550a0d5d2..4b6e0f8f7 100644 --- a/src/ve-core/events.d.ts +++ b/src/ve-core/events.d.ts @@ -1,35 +1,35 @@ -import { ElementObject, ElementsRequest } from '@ve-types/mms'; +import { ElementObject, ElementsRequest } from '@ve-types/mms' export namespace veCoreEvents { interface elementSelectedData extends ElementsRequest { - rootId?: string; - refType?: string; - displayOldSpec?: boolean; - refresh?: boolean; + rootId?: string + refType?: string + displayOldSpec?: boolean + refresh?: boolean } interface elementUpdatedData { - element: ElementObject; - continueEdit?: boolean; + element: ElementObject + continueEdit?: boolean } interface buttonClicked { - $event?: JQuery.ClickEvent; - clicked: string; + $event?: JQuery.ClickEvent + clicked: string } interface toolbarClicked { - id: string; - category?: string; - title?: string; + id: string + category?: string + title?: string } abstract interface setToolbarData { - tbId: string; - id: string; - value: T; + tbId: string + id: string + value: T } - type setPermissionData = setToolbarData; - type setIconData = setToolbarData; - type setToggleData = setToolbarData; + type setPermissionData = setToolbarData + type setIconData = setToolbarData + type setToggleData = setToolbarData } diff --git a/src/ve-core/index.ts b/src/ve-core/index.ts index bc5ad6acf..4d4823a0b 100644 --- a/src/ve-core/index.ts +++ b/src/ve-core/index.ts @@ -2,13 +2,13 @@ // import '@ve-utils' //Module Main -import './ve-core.module'; +import './ve-core.module' // Core Component Libraries -import './modals'; -import './button-bar'; -import './toolbar'; -import './editor'; -import './search'; +import './modals' +import './button-bar' +import './toolbar' +import './editor' +import './search' -export * from './ve-core.module'; +export * from './ve-core.module' diff --git a/src/ve-core/modals/confirm-delete-modal.component.ts b/src/ve-core/modals/confirm-delete-modal.component.ts index bfaf7ee63..6ee323b57 100644 --- a/src/ve-core/modals/confirm-delete-modal.component.ts +++ b/src/ve-core/modals/confirm-delete-modal.component.ts @@ -1,24 +1,24 @@ -import angular from 'angular'; -import _ from 'lodash'; +import angular from 'angular' +import _ from 'lodash' -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { VeComponentOptions, VePromise } from '@ve-types/angular'; -import { RefsResponse } from '@ve-types/mms'; -import { VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; +import { VeComponentOptions, VePromise } from '@ve-types/angular' +import { RefsResponse } from '@ve-types/mms' +import { VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' export interface ConfirmDeleteModalResolve extends VeModalResolve { - getType: string; - getName: string; - finalize(): VePromise; + getType: string + getName: string + finalize(): VePromise } export interface ConfirmDeleteModalResolveFn extends VeModalResolveFn { - getType(): string; - getName(): string; - finalize(): () => VePromise; + getType(): string + getName(): string + finalize(): () => VePromise } const ConfirmDeleteModalComponent: VeComponentOptions = { @@ -48,53 +48,53 @@ const ConfirmDeleteModalComponent: VeComponentOptions = { resolve: '<', }, controller: class ConfirmDeleteModalController extends VeModalControllerImpl implements VeModalController { - static $inject = ['growl']; + static $inject = ['growl'] - protected resolve: ConfirmDeleteModalResolve; + protected resolve: ConfirmDeleteModalResolve //local - public oking: boolean; - public type: string; - public name: string; + public oking: boolean + public type: string + public name: string constructor(private growl: angular.growl.IGrowlService) { - super(); + super() } $onInit(): void { - this.oking = false; - this.type = this.resolve.getType; - this.name = this.resolve.getName; + this.oking = false + this.type = this.resolve.getType + this.name = this.resolve.getName } ok = (): void => { if (this.oking) { - this.growl.info('Please wait...'); - return; + this.growl.info('Please wait...') + return } - this.oking = true; + this.oking = true if (this.resolve.finalize) { this.resolve.finalize().then( () => { - this.growl.success(_.upperFirst(this.type) + ' Removed'); - this.oking = false; - this.modalInstance.close('ok'); + this.growl.success(_.upperFirst(this.type) + ' Removed') + this.oking = false + this.modalInstance.close('ok') }, (reason) => { if (reason.message) { - this.growl.error(this.type + ' Removal Error: ' + reason.message); + this.growl.error(this.type + ' Removal Error: ' + reason.message) } - this.oking = false; - this.modalInstance.dismiss(); + this.oking = false + this.modalInstance.dismiss() } - ); + ) } - }; + } cancel(): void { - this.modalInstance.dismiss(); + this.modalInstance.dismiss() } }, -}; +} -veCore.component(ConfirmDeleteModalComponent.selector, ConfirmDeleteModalComponent); +veCore.component(ConfirmDeleteModalComponent.selector, ConfirmDeleteModalComponent) diff --git a/src/ve-core/modals/index.ts b/src/ve-core/modals/index.ts index 801fffdda..e0fe11de4 100644 --- a/src/ve-core/modals/index.ts +++ b/src/ve-core/modals/index.ts @@ -1,3 +1,3 @@ -import './confirm-delete-modal.component'; +import './confirm-delete-modal.component' -export * from './confirm-delete-modal.component'; +export * from './confirm-delete-modal.component' diff --git a/src/ve-core/search/index.ts b/src/ve-core/search/index.ts index c9ed03d72..315791d2d 100644 --- a/src/ve-core/search/index.ts +++ b/src/ve-core/search/index.ts @@ -1,5 +1,5 @@ -import './mms-search.component'; +import './mms-search.component' -export * from './mms-search.component'; +export * from './mms-search.component' -import './mms-search-results.component'; +import './mms-search-results.component' diff --git a/src/ve-core/search/mms-search-buttons.config.ts b/src/ve-core/search/mms-search-buttons.config.ts index 6ece9040d..6272636bf 100644 --- a/src/ve-core/search/mms-search-buttons.config.ts +++ b/src/ve-core/search/mms-search-buttons.config.ts @@ -1,4 +1,4 @@ -import { IButtonBarButton } from '@ve-core/button-bar'; +import { IButtonBarButton } from '@ve-core/button-bar' export const search_default_buttons: IButtonBarButton[] = [ { @@ -74,4 +74,4 @@ export const search_default_buttons: IButtonBarButton[] = [ icon: 'pe-type-req', type: 'Requirement', }, -]; +] diff --git a/src/ve-core/search/mms-search-results.component.ts b/src/ve-core/search/mms-search-results.component.ts index 40e0028a8..5604360f3 100644 --- a/src/ve-core/search/mms-search-results.component.ts +++ b/src/ve-core/search/mms-search-results.component.ts @@ -1,20 +1,20 @@ -import { IComponentController } from 'angular'; +import { IComponentController } from 'angular' -import { SearchController } from '@ve-core/search'; +import { SearchController } from '@ve-core/search' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { VeComponentOptions } from '@ve-types/angular'; -import { ElementObject } from '@ve-types/mms'; +import { VeComponentOptions } from '@ve-types/angular' +import { ElementObject } from '@ve-types/mms' export class MmsSearchResultsController implements IComponentController { //Parent Controllers - private $search: SearchController; + private $search: SearchController //Bindings - private elem: ElementObject; + private elem: ElementObject - $onChanges; + $onChanges } const MmsSearchResultsComponent: VeComponentOptions = { selector: 'mmsSearchResults', @@ -148,6 +148,6 @@ const MmsSearchResultsComponent: VeComponentOptions = { `, controller: MmsSearchResultsController, -}; +} -veCore.component(MmsSearchResultsComponent.selector, MmsSearchResultsComponent); +veCore.component(MmsSearchResultsComponent.selector, MmsSearchResultsComponent) diff --git a/src/ve-core/search/mms-search.component.ts b/src/ve-core/search/mms-search.component.ts index ca2a6d6b7..0b06b1309 100644 --- a/src/ve-core/search/mms-search.component.ts +++ b/src/ve-core/search/mms-search.component.ts @@ -1,17 +1,17 @@ -import { StateService } from '@uirouter/angularjs'; -import _ from 'lodash'; +import { StateService } from '@uirouter/angularjs' +import _ from 'lodash' -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; -import { veCoreEvents } from '@ve-core/events'; -import { search_default_buttons } from '@ve-core/search/mms-search-buttons.config'; -import { UtilsService } from '@ve-utils/application'; -import { CacheService, EventService } from '@ve-utils/core'; -import { ElementService, ProjectService, ViewService, ValueService } from '@ve-utils/mms-api-client'; -import { SchemaService } from '@ve-utils/model-schema'; +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' +import { veCoreEvents } from '@ve-core/events' +import { search_default_buttons } from '@ve-core/search/mms-search-buttons.config' +import { UtilsService } from '@ve-utils/application' +import { CacheService, EventService } from '@ve-utils/core' +import { ElementService, ProjectService, ViewService, ValueService } from '@ve-utils/mms-api-client' +import { SchemaService } from '@ve-utils/model-schema' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' import { DocumentObject, ElementObject, @@ -21,34 +21,34 @@ import { RequestObject, SearchResponse, ViewObject, -} from '@ve-types/mms'; -import { VeSearchOptions } from '@ve-types/view-editor'; +} from '@ve-types/mms' +import { VeSearchOptions } from '@ve-types/view-editor' export interface SearchQuery { - searchText: string; - selectedSearchMetatypes: any[]; - searchField: SearchField; - from?: number; - size?: number; + searchText: string + selectedSearchMetatypes: any[] + searchField: SearchField + from?: number + size?: number } export interface AdvancedSearchQuery extends SearchQuery { - operator: string; + operator: string } export interface SearchField { - id: string; - label: string; + id: string + label: string } export interface SearchFilter { - appliedStereotypeIds?: string[]; - classifierIds?: string[]; + appliedStereotypeIds?: string[] + classifierIds?: string[] } export interface SearchObject extends ViewObject { - allRelatedDocuments?: ViewObject[]; - remainingRelatedDocuments?: ViewObject[]; + allRelatedDocuments?: ViewObject[] + remainingRelatedDocuments?: ViewObject[] } /** @@ -61,19 +61,19 @@ export interface SearchObject extends ViewObject { * */ export class SearchController implements angular.IComponentController { - private mmsOptions: VeSearchOptions; - private mmsProjectId: string; - private mmsRefId: string; - private embedded: boolean; + private mmsOptions: VeSearchOptions + private mmsProjectId: string + private mmsRefId: string + private embedded: boolean //Search Results - private metatypeSearch: string; - protected searchResults: ElementObject[] = []; - protected baseSearchResults: ElementObject[] = []; - protected filteredSearchResults: ElementObject[] = []; - protected showFilterOptions: boolean; - protected searchLoading: boolean = false; - protected firstSearch: boolean = true; + private metatypeSearch: string + protected searchResults: ElementObject[] = [] + protected baseSearchResults: ElementObject[] = [] + protected filteredSearchResults: ElementObject[] = [] + protected showFilterOptions: boolean + protected searchLoading: boolean = false + protected firstSearch: boolean = true protected mainSearch: SearchQuery = { searchText: '', searchField: { @@ -81,31 +81,31 @@ export class SearchController implements angular.IComponentController { label: 'All Fields', }, selectedSearchMetatypes: [], - }; + } protected docsviews: { selected: boolean } = { selected: false, - }; - private emptyDocTxt: string; - protected refId: string; + } + private emptyDocTxt: string + protected refId: string // Search result settings - protected activeFilter: any[] = []; + protected activeFilter: any[] = [] // Pagination settings - protected totalResults: number = 0; - protected paginationCache: { [key: number]: ElementObject[] } = {}; - private maxPages: number; - protected currentPage: number = 0; - protected itemsPerPage: number = 10; + protected totalResults: number = 0 + protected paginationCache: { [key: number]: ElementObject[] } = {} + private maxPages: number + protected currentPage: number = 0 + protected itemsPerPage: number = 10 // Advanced search settings - protected advanceSearch: boolean = false; - protected advancedSearchResults: boolean; - protected advanceSearchRows: AdvancedSearchQuery[] = []; - protected stringQuery = this.mainSearch.searchText; + protected advanceSearch: boolean = false + protected advancedSearchResults: boolean + protected advanceSearchRows: AdvancedSearchQuery[] = [] + protected stringQuery = this.mainSearch.searchText // View property settings - protected showSearchResultProps = false; - protected switchText = 'More'; - protected limitForProps = 6; + protected showSearchResultProps = false + protected switchText = 'More' + protected limitForProps = 6 // Set search options public fieldTypeList: SearchField[] = [ @@ -133,9 +133,9 @@ export class SearchController implements angular.IComponentController { id: 'type', label: 'Metatype', }, - ]; + ] - public operatorList = ['And', 'Or', 'And Not']; + public operatorList = ['And', 'Or', 'And Not'] // settings for multiselect metatype dropdown public metatypeSettings = { @@ -146,20 +146,20 @@ export class SearchController implements angular.IComponentController { showCheckAll: false, smartButtonMaxItems: 10, buttonClasses: '', - }; + } // event handler for multiselect metatype dropdown public multiselectEvent: { - onItemSelect(ob): void; - onItemDeselect(ob): void; - onDeselectAll(ob): void; - }; + onItemSelect(ob): void + onItemDeselect(ob): void + onDeselectAll(ob): void + } - bbId: string; - bbApi: ButtonBarApi; - private filterList: QueryObject[] = []; + bbId: string + bbApi: ButtonBarApi + private filterList: QueryObject[] = [] - private schema = 'cameo'; + private schema = 'cameo' static $inject = [ '$q', @@ -176,7 +176,7 @@ export class SearchController implements angular.IComponentController { 'ValueService', 'SchemaService', 'ButtonBarService', - ]; + ] constructor( private $q: VeQService, @@ -196,78 +196,78 @@ export class SearchController implements angular.IComponentController { ) {} $onInit(): void { - this.showFilterOptions = !this.mmsOptions.hideFilterOptions; + this.showFilterOptions = !this.mmsOptions.hideFilterOptions if (this.showFilterOptions) { - this.bbId = this.buttonBarSvc.generateBarId('mms-search'); - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, search_default_buttons); + this.bbId = this.buttonBarSvc.generateBarId('mms-search') + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, search_default_buttons) this.eventSvc.$on(this.bbId, (data) => { - this.bbApi.toggleButton(data.clicked); - this.filterSearchResults(this.buttonBarSvc.getButtonDefinition(data.clicked).type); - }); + this.bbApi.toggleButton(data.clicked) + this.filterSearchResults(this.buttonBarSvc.getButtonDefinition(data.clicked).type) + }) } - this.refId = this.mmsRefId ? this.mmsRefId : 'master'; + this.refId = this.mmsRefId ? this.mmsRefId : 'master' // Set functions - void this.projectSvc.getProjectMounts(this.mmsProjectId, this.refId); + void this.projectSvc.getProjectMounts(this.mmsProjectId, this.refId) //ensure project mounts object is cached // Function used to get string value of metatype names for advanced search - this.getMetaTypes(); + this.getMetaTypes() this.multiselectEvent = { onItemSelect: (ob): void => { void this.$timeout(() => { - this.stringQueryUpdate(); - }, 500); + this.stringQueryUpdate() + }, 500) }, onItemDeselect: (ob): void => { void this.$timeout(() => { - this.stringQueryUpdate(); - }, 500); + this.stringQueryUpdate() + }, 500) }, onDeselectAll: (ob): void => { void this.$timeout(() => { - this.stringQueryUpdate(); - }, 500); + this.stringQueryUpdate() + }, 500) }, - }; + } - this.addAdvanceSearchRow(); // Second row created by default + this.addAdvanceSearchRow() // Second row created by default // Set options if (this.mmsOptions.searchResult) { - const data1 = this.mmsOptions.searchResult; - this.searchResults = data1; - this.paginationCache[0] = data1; + const data1 = this.mmsOptions.searchResult + this.searchResults = data1 + this.paginationCache[0] = data1 } if (this.mmsOptions.searchField) { for (const field of this.fieldTypeList) { if (this.mmsOptions.searchField === field.label || this.mmsOptions.searchField === field.id) { - this.mainSearch.searchField = field; - break; + this.mainSearch.searchField = field + break } } } if (this.mmsOptions.searchInput) { - this.mainSearch.searchText = this.mmsOptions.searchInput; - this.newSearch(this.mainSearch); + this.mainSearch.searchText = this.mmsOptions.searchInput + this.newSearch(this.mainSearch) } if (this.mmsOptions.itemsPerPage) { - this.itemsPerPage = this.mmsOptions.itemsPerPage; + this.itemsPerPage = this.mmsOptions.itemsPerPage } if (this.mmsOptions.emptyDocTxt) { - this.emptyDocTxt = this.mmsOptions.emptyDocTxt; + this.emptyDocTxt = this.mmsOptions.emptyDocTxt } } handleChange = (newVal: ElementObject[]): void => { - if (!newVal) return; + if (!newVal) return if (!this.mmsOptions.getProperties) { - return; + return } newVal.forEach((elem) => { if (elem._properties) { - return; + return } // mms does not return properties will need to make a call for the results whose type is Class // Call this.elementSvc.getOwnedElements with depth of 2 @@ -279,15 +279,15 @@ export class SearchController implements angular.IComponentController { projectId: elem._projectId, refId: elem._refId, depth: 2, - }; + } this.elementSvc.getOwnedElements(reqOb, 2).then( (data: ElementObject[]) => { - const properties: ElementObject[] = []; + const properties: ElementObject[] = [] //TODO might not be elements data.forEach((elt) => { - if (this.valueSvc.isValue(elt)) properties.push(elt); - }); - elem._properties = properties; + if (this.valueSvc.isValue(elt)) properties.push(elt) + }) + elem._properties = properties // OLD CODE - splits into 3cols // if (elem._properties && elem._properties[0]) { // var properties2 = []; @@ -301,55 +301,55 @@ export class SearchController implements angular.IComponentController { // } }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) } - }); - }; + }) + } bbInit = (api: ButtonBarApi): void => { - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-document')); - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-paragraph')); - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-table')); - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-image')); - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-equation')); - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-comment')); - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-section')); - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-view')); - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-req')); - }; + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-document')) + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-paragraph')) + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-table')) + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-image')) + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-equation')) + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-comment')) + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-section')) + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-view')) + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-req')) + } public qualifiedNameFormatter = (qualifiedName: string): string => { if (qualifiedName) { - const parts = qualifiedName.split('/'); - let result = qualifiedName; + const parts = qualifiedName.split('/') + let result = qualifiedName if (parts.length > 7) { - result = parts.slice(0, 4).join('/') + '/.../' + parts.slice(parts.length - 3, parts.length).join('/'); + result = parts.slice(0, 4).join('/') + '/.../' + parts.slice(parts.length - 3, parts.length).join('/') } - return result; + return result } - }; + } public expandQualifiedName = ($event: JQuery.ClickEvent, qualifiedName: string): void => { - ($event.currentTarget as HTMLElement).innerHTML = qualifiedName; - }; + ;($event.currentTarget as HTMLElement).innerHTML = qualifiedName + } public showMoreRelatedViews = (element: SearchObject): void => { - element.remainingRelatedDocuments = element.allRelatedDocuments.slice(3, element.allRelatedDocuments.length); - }; + element.remainingRelatedDocuments = element.allRelatedDocuments.slice(3, element.allRelatedDocuments.length) + } public closeSearch = (): void => { if (this.mmsOptions.closeCallback) { - this.mmsOptions.closeCallback(); + this.mmsOptions.closeCallback() } else { - void this.$state.go('main.project.ref.portal', { search: null, field: null }, { reload: true }); + void this.$state.go('main.project.ref.portal', { search: null, field: null }, { reload: true }) } - }; + } public advancedSearchHandler = (): void => { /* TODO: Reimplement Advanced Search */ - }; + } // Get metatypes for dropdown options public getMetaTypes = (): void => { @@ -363,50 +363,50 @@ export class SearchController implements angular.IComponentController { // }).finally(() => { // scope.metatypeSearch = ""; // }); - this.advancedSearchHandler(); - }; + this.advancedSearchHandler() + } public getMetatypeSelection = (id: string): string => { - const mainElement = angular.element(id); - return mainElement.find('div').attr('value'); - }; + const mainElement = angular.element(id) + return mainElement.find('div').attr('value') + } public getTypeClass = (element: ElementObject): string => { // Get Type - return this.utilsSvc.getElementTypeClass(element, this.viewSvc.getElementType(element)); - }; + return this.utilsSvc.getElementTypeClass(element, this.viewSvc.getElementType(element)) + } // Filter options public getActiveFilterClass = (item: unknown[]): boolean => { if (!this.activeFilter.length) { - return false; + return false } - return _.includes(this.activeFilter, item); - }; + return _.includes(this.activeFilter, item) + } public filterSearchResults = (type: string): void => { - const tempArr = _.clone(this.activeFilter); + const tempArr = _.clone(this.activeFilter) if (_.includes(this.activeFilter, type)) { - _.pull(this.activeFilter, type); + _.pull(this.activeFilter, type) } else { - this.activeFilter.push(type); + this.activeFilter.push(type) } - this._applyFiltersAndPaginate(); - }; + this._applyFiltersAndPaginate() + } private _applyFiltersAndPaginate = (): void => { if (!this.activeFilter.length) { - this.filteredSearchResults = this.searchResults; + this.filteredSearchResults = this.searchResults } else { this.filteredSearchResults = _.filter(this.baseSearchResults, (item) => { - return _.includes(this.activeFilter, this.viewSvc.getElementType(item)); - }); + return _.includes(this.activeFilter, this.viewSvc.getElementType(item)) + }) } - this.maxPages = Math.ceil(this.filteredSearchResults.length / this.itemsPerPage); + this.maxPages = Math.ceil(this.filteredSearchResults.length / this.itemsPerPage) for (const pg of [...Array(this.maxPages).keys()]) { - this.paginationCache[pg] = this.searchResults.slice(pg * this.itemsPerPage, (pg + 1) * this.itemsPerPage); + this.paginationCache[pg] = this.searchResults.slice(pg * this.itemsPerPage, (pg + 1) * this.itemsPerPage) } - }; + } // var findRefineOptions = (results) => { // var presentationElements = _.map(results, this.viewSvc.getElementType); @@ -419,13 +419,13 @@ export class SearchController implements angular.IComponentController { * Updates advanced search main query input */ public stringQueryUpdate = (): void => { - const rowLength = this.advanceSearchRows.length; - this.stringQuery = Array(rowLength + 1).join('('); - this.stringQuery += this.mainSearch.searchField.label + ':'; + const rowLength = this.advanceSearchRows.length + this.stringQuery = Array(rowLength + 1).join('(') + this.stringQuery += this.mainSearch.searchField.label + ':' if (this.mainSearch.searchField.id === 'metatype') { - this.stringQuery += this.getMetatypeSelection('#searchMetatypeSelectAdvance'); + this.stringQuery += this.getMetatypeSelection('#searchMetatypeSelectAdvance') } else { - this.stringQuery += this.mainSearch.searchText; + this.stringQuery += this.mainSearch.searchText } for (let i = 0; i < rowLength; i++) { this.stringQuery += @@ -433,14 +433,14 @@ export class SearchController implements angular.IComponentController { this.advanceSearchRows[i].operator.toUpperCase() + ' ' + this.advanceSearchRows[i].searchField.label + - ':'; + ':' if (this.advanceSearchRows[i].searchField.id === 'metatype') { - this.stringQuery += this.getMetatypeSelection('#searchMetatypeSelect-' + i.toString()) + ')'; + this.stringQuery += this.getMetatypeSelection('#searchMetatypeSelect-' + i.toString()) + ')' } else { - this.stringQuery += this.advanceSearchRows[i].searchText + ')'; + this.stringQuery += this.advanceSearchRows[i].searchText + ')' } } - }; + } /** * @name veCore.directive:mmsSearch#addAdvanceSearchRow @@ -455,9 +455,9 @@ export class SearchController implements angular.IComponentController { }, searchText: '', selectedSearchMetatypes: [], - }); - this.stringQueryUpdate(); - }; + }) + this.stringQueryUpdate() + } /** * @name veCore.directive:mmsSearch#removeRowAdvanceSearch * Removes selected row and updates advanced search main query input @@ -465,22 +465,22 @@ export class SearchController implements angular.IComponentController { * @param {object} row advanced search row */ public removeRowAdvanceSearch = (row: AdvancedSearchQuery): void => { - this.advanceSearchRows = _.without(this.advanceSearchRows, row); - this.stringQueryUpdate(); - }; + this.advanceSearchRows = _.without(this.advanceSearchRows, row) + this.stringQueryUpdate() + } public modifyAdvanceSearch = (): void => { - this.advanceSearch = !this.advanceSearch; - this.advancedSearchResults = !this.advancedSearchResults; - }; + this.advanceSearch = !this.advanceSearch + this.advancedSearchResults = !this.advancedSearchResults + } public pageChanged = (): void => { if (this.paginationCache[this.currentPage]) { - this.baseSearchResults = this.paginationCache[this.currentPage]; + this.baseSearchResults = this.paginationCache[this.currentPage] } else { - this.search(this.mainSearch, this.currentPage, this.itemsPerPage); + this.search(this.mainSearch, this.currentPage, this.itemsPerPage) } - }; + } /** * @name veCore.directive:mmsSearch#search @@ -492,14 +492,14 @@ export class SearchController implements angular.IComponentController { * @param {number} numItems number of items to return per page */ public search = (query: SearchQuery, page: number, numItems: number): void => { - this.searchLoading = true; + this.searchLoading = true if (!this.embedded) { void this.$state.go('.', { search: query.searchText, field: query.searchField.id, - }); + }) } - const queryObs: QueryObject[] = this.buildQuery(query); + const queryObs: QueryObject[] = this.buildQuery(query) // for (const queryOb of queryObs) { // queryOb.from = page * numItems + page // queryOb.size = numItems @@ -507,67 +507,67 @@ export class SearchController implements angular.IComponentController { const reqOb: RequestObject = { projectId: this.mmsProjectId, refId: this.refId, - }; - const promises: VePromise, SearchResponse>[] = []; + } + const promises: VePromise, SearchResponse>[] = [] for (const queryOb of queryObs) { - promises.push(this._performSearch(reqOb, queryOb)); + promises.push(this._performSearch(reqOb, queryOb)) } this.$q .allSettled>(promises) .then( (data) => { - const elements: ElementObject[] = []; - this.searchResults = []; - this.totalResults = 0; + const elements: ElementObject[] = [] + this.searchResults = [] + this.totalResults = 0 for (const d of data) { - elements.push(...d.value.elements); - this.totalResults = this.totalResults + d.value.total; + elements.push(...d.value.elements) + this.totalResults = this.totalResults + d.value.total } if (this.mmsOptions.filterCallback) { - const results = this.mmsOptions.filterCallback(elements); + const results = this.mmsOptions.filterCallback(elements) if (results) { - this.searchResults = results; + this.searchResults = results } else { - this.searchResults = []; + this.searchResults = [] } } else if (elements.length > 0) { - this.searchResults = elements; + this.searchResults = elements } - this.combineRelatedViews(); - this.currentPage = page; - this._applyFiltersAndPaginate(); - this.baseSearchResults = this.paginationCache[page]; + this.combineRelatedViews() + this.currentPage = page + this._applyFiltersAndPaginate() + this.baseSearchResults = this.paginationCache[page] if (this.advanceSearch) { // scope.advanceSearch = !scope.advanceSearch; - this.advancedSearchResults = true; + this.advancedSearchResults = true } // scope.refineOptions = findRefineOptions(baseSearchResults); }, (reason) => { - this.growl.error('Search Error: ' + reason.message); + this.growl.error('Search Error: ' + reason.message) } ) .finally(() => { - this.searchLoading = false; - this.firstSearch = false; - }); - }; + this.searchLoading = false + this.firstSearch = false + }) + } private _performSearch( reqOb: RequestObject, queryOb: QueryObject ): VePromise, SearchResponse> { - return this.elementSvc.search(reqOb, queryOb); + return this.elementSvc.search(reqOb, queryOb) } public newSearch = (query: SearchQuery): void => { - this.searchResults.length = 0; - this.searchLoading = true; - this.paginationCache = {}; - this.search(query, 0, this.itemsPerPage); - }; + this.searchResults.length = 0 + this.searchLoading = true + this.paginationCache = {} + this.search(query, 0, this.itemsPerPage) + } /** * @name veCore.directive:mmsSearch#getProjectMountsQuery @@ -579,29 +579,29 @@ export class SearchController implements angular.IComponentController { * @return {object} Elastic query JSON object with list of project mounts */ getProjectMountsQuery = (): VePromise => { - const deferred: angular.IDeferred = this.$q.defer(); - const projList: MountObject[] = []; + const deferred: angular.IDeferred = this.$q.defer() + const projList: MountObject[] = [] - const mountCacheKey = ['project-mounts', this.mmsProjectId, this.refId]; + const mountCacheKey = ['project-mounts', this.mmsProjectId, this.refId] if (this.cacheSvc.exists(mountCacheKey)) { - const project = this.cacheSvc.get(mountCacheKey); - this.getAllMountsAsArray(project, projList); - deferred.resolve(projList); + const project = this.cacheSvc.get(mountCacheKey) + this.getAllMountsAsArray(project, projList) + deferred.resolve(projList) } else { // Get project element data to gather mounted project list this.projectSvc.getProjectMounts(this.mmsProjectId, this.refId).then( (project) => { - this.getAllMountsAsArray(project, projList); - deferred.resolve(projList); + this.getAllMountsAsArray(project, projList) + deferred.resolve(projList) }, (reason) => { - this.growl.error('Problem getting Project Mounts:' + reason.message); - deferred.resolve(projList); + this.growl.error('Problem getting Project Mounts:' + reason.message) + deferred.resolve(projList) } - ); + ) } - return deferred.promise; - }; + return deferred.promise + } /** * @name veCore.directive:mmsSearch#getAllMountsAsArray @@ -610,20 +610,20 @@ export class SearchController implements angular.IComponentController { * */ public getAllMountsAsArray = (project: ProjectObject, projectsList: ProjectObject[]): void => { - projectsList.push(project); - const mounts = (project as MountObject)._mounts; + projectsList.push(project) + const mounts = (project as MountObject)._mounts if (Array.isArray(mounts) && mounts.length !== 0) { for (let i = 0; i < mounts.length; i++) { if (mounts[i]._mounts) { - this.getAllMountsAsArray(mounts[i], projectsList); + this.getAllMountsAsArray(mounts[i], projectsList) } } } - }; + } public buildSearchClause = (query): void => { /*TODO*/ - }; + } /** * @name veCore.directive:mmsSearch#buildQuery @@ -635,37 +635,37 @@ export class SearchController implements angular.IComponentController { public buildQuery = (query: SearchQuery): QueryObject[] => { // Set project and mounted projects filter //var projectList = this.getProjectMountsQuery() - const filterTerms: { [key: string]: string[] } = {}; - const filterQueries: QueryObject[] = []; - const queryObs: QueryObject[] = []; - this.filterList = []; + const filterTerms: { [key: string]: string[] } = {} + const filterQueries: QueryObject[] = [] + const queryObs: QueryObject[] = [] + this.filterList = [] if (query.searchField.id === 'all') { for (const type of this.fieldTypeList) { if (type.id !== 'all') { - const queryOb: QueryObject = { params: {} }; - queryOb.params[type.id] = query.searchText; - queryObs.push(queryOb); + const queryOb: QueryObject = { params: {} } + queryOb.params[type.id] = query.searchText + queryObs.push(queryOb) } } } else { - const queryOb: QueryObject = { params: {} }; - queryOb.params[query.searchField.id] = query.searchText; - queryObs.push(queryOb); + const queryOb: QueryObject = { params: {} } + queryOb.params[query.searchField.id] = query.searchText + queryObs.push(queryOb) } if (this.mmsOptions.filterQueryList) { for (const filterQuery of this.mmsOptions.filterQueryList) { for (const [term, list] of Object.entries(filterQuery())) { if (!filterTerms[term]) { - filterTerms[term] = []; + filterTerms[term] = [] } filterTerms[term].push( ...list.filter((value) => { - return filterTerms[term].includes(value); + return filterTerms[term].includes(value) }) - ); + ) } } } @@ -674,17 +674,17 @@ export class SearchController implements angular.IComponentController { this.schemaSvc.getSchema('VIEW_SID', this.schema), this.schemaSvc.getSchema('DOCUMENT_SID', this.schema), ...this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema), - ]; + ] /*If the filter list already contain the view id's do not add them a second time since filtering is done client side */ if (!filterTerms.appliedStereotypeIds) { - filterTerms.appliedStereotypeIds = []; + filterTerms.appliedStereotypeIds = [] } filterTerms.appliedStereotypeIds.push( ...stereoIds.filter((value) => { - return !filterTerms.appliedStereotypeIds.includes(value); + return !filterTerms.appliedStereotypeIds.includes(value) }) - ); + ) } if (Object.entries(filterTerms).length > 0) { @@ -692,24 +692,24 @@ export class SearchController implements angular.IComponentController { for (const [term, list] of Object.entries(filterTerms)) { if (list.length > 0) { for (const sid of list) { - const newOb = _.cloneDeep(queryOb); - newOb.params[term] = sid; - filterQueries.push(newOb); + const newOb = _.cloneDeep(queryOb) + newOb.params[term] = sid + filterQueries.push(newOb) } } } } } - if (filterQueries.length > 0) return filterQueries; - else return queryObs; - }; + if (filterQueries.length > 0) return filterQueries + else return queryObs + } private combineRelatedViews = (): void => { this.searchResults.forEach((element: ViewObject) => { const allRelatedDocuments: { - relatedDocument: ViewObject; - relatedView: ViewObject; - }[] = []; + relatedDocument: ViewObject + relatedView: ViewObject + }[] = [] if (element._relatedDocuments) { element._relatedDocuments.forEach((relatedDoc: ViewObject) => { if (relatedDoc._parentViews) { @@ -717,21 +717,21 @@ export class SearchController implements angular.IComponentController { allRelatedDocuments.push({ relatedDocument: relatedDoc, relatedView: parentView, - }); - }); + }) + }) } - }); + }) } - element.allRelatedDocuments = allRelatedDocuments; - element.someRelatedDocuments = allRelatedDocuments.slice(0, 3); - }); - }; + element.allRelatedDocuments = allRelatedDocuments + element.someRelatedDocuments = allRelatedDocuments.slice(0, 3) + }) + } public userResultClick = (elem: ElementObject, property: string): void => { if (this.mmsOptions.callback) { - this.mmsOptions.callback(elem, property); + this.mmsOptions.callback(elem, property) } - }; + } public userRelatedClick = ( event: JQuery.ClickEvent, @@ -739,13 +739,13 @@ export class SearchController implements angular.IComponentController { view: ViewObject, elem: ElementObject ): void => { - event.preventDefault(); - event.stopPropagation(); - if (this.mmsOptions.relatedCallback) this.mmsOptions.relatedCallback(doc, view, elem); - }; + event.preventDefault() + event.stopPropagation() + if (this.mmsOptions.relatedCallback) this.mmsOptions.relatedCallback(doc, view, elem) + } private toggleDocs(): void { - this.docsviews.selected = !this.docsviews.selected; + this.docsviews.selected = !this.docsviews.selected } } const SearchComponent: VeComponentOptions = { @@ -962,6 +962,6 @@ const SearchComponent: VeComponentOptions = { embedded: '<', }, controller: SearchController, -}; +} -veCore.component(SearchComponent.selector, SearchComponent); +veCore.component(SearchComponent.selector, SearchComponent) diff --git a/src/ve-core/toolbar/index.ts b/src/ve-core/toolbar/index.ts index fad0112f2..a491346a7 100644 --- a/src/ve-core/toolbar/index.ts +++ b/src/ve-core/toolbar/index.ts @@ -1,9 +1,9 @@ //Exports -export * from './services/Toolbar.service'; -export * from './services/Toolbar.api'; +export * from './services/Toolbar.service' +export * from './services/Toolbar.api' //Services -import './services/Toolbar.service'; +import './services/Toolbar.service' //Core Components -import './tool-bar.component'; +import './tool-bar.component' diff --git a/src/ve-core/toolbar/services/Toolbar.api.ts b/src/ve-core/toolbar/services/Toolbar.api.ts index c77d107b1..5bbca57d1 100644 --- a/src/ve-core/toolbar/services/Toolbar.api.ts +++ b/src/ve-core/toolbar/services/Toolbar.api.ts @@ -1,7 +1,7 @@ -import { ToolButton } from '@ve-core/toolbar'; +import { ToolButton } from '@ve-core/toolbar' export class ToolbarApi { - public buttons: ToolButton[] = []; + public buttons: ToolButton[] = [] constructor(public id: string) {} @@ -12,27 +12,27 @@ export class ToolbarApi { // $scope.clicked(button); if (!button.dynamic) { this.buttons.forEach((b) => { - b.selected = b.id === button.id; - }); + b.selected = b.id === button.id + }) // de-activate all dynamic this.buttons this.buttons.forEach((b) => { if (b.dynamic) { - b.active = false; + b.active = false } - }); + }) if (button.dynamicButtons) { button.dynamicButtons.forEach((b) => { - b.active = true; - }); + b.active = true + }) } } } //else // button.selected = false; - }); - }; + }) + } public deactivate = (id: string): void => { this.buttons.forEach((button) => { @@ -40,66 +40,66 @@ export class ToolbarApi { if (button.dynamicButtons) { // de-activate all dynamic buttons button.dynamicButtons.forEach((b) => { - b.active = false; - }); + b.active = false + }) } } - }); - }; + }) + } public setPermission = (id: string, permission: boolean): void => { this.buttons.forEach((button) => { if (button.id === id) { - button.permission = permission; + button.permission = permission } - }); - }; + }) + } public setSelected = (id: string, selected: boolean): void => { this.buttons.forEach((button) => { if (button.id === id) { - button.selected = selected; + button.selected = selected } - }); - }; + }) + } public setIcon = (id: string, icon: string): void => { this.buttons.forEach((button) => { if (button.id === id) { - button.icon = icon; + button.icon = icon } - }); - }; + }) + } public addButton = (button: ToolButton): void => { - button.priority = this.buttons.length; - this.buttons.push(button); + button.priority = this.buttons.length + this.buttons.push(button) if (button.dynamicButtons) { - let firstButton = true; + let firstButton = true button.dynamicButtons.forEach((buttonLoop) => { if (!this.buttons.map((button) => button.id).includes(buttonLoop.id)) { if (firstButton) { - buttonLoop.pullDown = true; - firstButton = false; + buttonLoop.pullDown = true + firstButton = false } - buttonLoop.priority = this.buttons.length + 1000; - this.buttons.push(buttonLoop); + buttonLoop.priority = this.buttons.length + 1000 + this.buttons.push(buttonLoop) } - }); + }) } - }; + } public toggleButtonSpinner = (id: string): void => { this.buttons.forEach((button) => { if (button.id === id) { if (button.spinner) { - button.icon = button.icon_original; + button.icon = button.icon_original } else { - button.icon_original = button.icon; - button.icon = 'fa fa-spinner fa-spin'; + button.icon_original = button.icon + button.icon = 'fa fa-spinner fa-spin' } - button.spinner = !button.spinner; + button.spinner = !button.spinner } - }); - }; + }) + } } diff --git a/src/ve-core/toolbar/services/Toolbar.service.ts b/src/ve-core/toolbar/services/Toolbar.service.ts index ebb658dfe..4d6dd4b97 100644 --- a/src/ve-core/toolbar/services/Toolbar.service.ts +++ b/src/ve-core/toolbar/services/Toolbar.service.ts @@ -1,87 +1,87 @@ -import { veCoreEvents } from '@ve-core/events'; -import { EventService } from '@ve-utils/core'; +import { veCoreEvents } from '@ve-core/events' +import { EventService } from '@ve-utils/core' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { ToolbarApi } from './Toolbar.api'; +import { ToolbarApi } from './Toolbar.api' -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { VeConfig } from '@ve-types/config'; -import { VeApiObject } from '@ve-types/view-editor'; +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { VeConfig } from '@ve-types/config' +import { VeApiObject } from '@ve-types/view-editor' export interface IToolBarButton { - id: string; - icon: string; - tooltip: string; - category?: string; - icon_original?: string; - selected?: boolean; - active?: boolean; - permission?: boolean; - spinner?: boolean; - dynamic?: boolean; - priority?: number; - pullDown?: boolean; - onClick?: buttonOnClickFn; - dynamic_ids?: string[]; - disabledFor?: string[]; - enabledFor?: string[]; + id: string + icon: string + tooltip: string + category?: string + icon_original?: string + selected?: boolean + active?: boolean + permission?: boolean + spinner?: boolean + dynamic?: boolean + priority?: number + pullDown?: boolean + onClick?: buttonOnClickFn + dynamic_ids?: string[] + disabledFor?: string[] + enabledFor?: string[] } export interface buttonOnClickFn { - (button?: IToolBarButton): void; + (button?: IToolBarButton): void } export interface toolbarInitFn { - (api: ToolbarApi): void; + (api: ToolbarApi): void } export class ToolButton implements IToolBarButton { - id: string; - category: string = 'global'; - icon: string = 'fa-gears'; - tooltip: string = 'Generic Button'; - icon_original: string = 'fa-gears'; - selected: boolean = false; - active: boolean = true; - permission: boolean; - spinner: boolean = false; - dynamic: boolean = false; - pullDown: boolean = false; - dynamicButtons: ToolButton[] = []; - disabledFor: string[] = []; - enabledFor: string[] = []; - priority: number = 0; + id: string + category: string = 'global' + icon: string = 'fa-gears' + tooltip: string = 'Generic Button' + icon_original: string = 'fa-gears' + selected: boolean = false + active: boolean = true + permission: boolean + spinner: boolean = false + dynamic: boolean = false + pullDown: boolean = false + dynamicButtons: ToolButton[] = [] + disabledFor: string[] = [] + enabledFor: string[] = [] + priority: number = 0 constructor(id: string, tbutton?: IToolBarButton) { - this.id = id; + this.id = id if (tbutton) { - Object.assign(this, tbutton); + Object.assign(this, tbutton) } } - onClick: buttonOnClickFn; + onClick: buttonOnClickFn } export class ToolbarService { - private toolbars: VeApiObject = {}; - private buttons: { [key: string]: IToolBarButton } = {}; - private dynamicButtons: { [key: string]: IToolBarButton } = {}; - private veConfig: VeConfig; + private toolbars: VeApiObject = {} + private buttons: { [key: string]: IToolBarButton } = {} + private dynamicButtons: { [key: string]: IToolBarButton } = {} + private veConfig: VeConfig - static $inject = ['$q', 'EventService']; + static $inject = ['$q', 'EventService'] constructor(private $q: VeQService, private eventSvc: EventService) { - this.veConfig = window.__env; + this.veConfig = window.__env if (this.veConfig.expConfig) { for (const ext of Object.keys(this.veConfig.expConfig)) { if (this.veConfig.expConfig[ext] && this.veConfig.expConfig[ext].length > 0) { for (const tool of this.veConfig.expConfig[ext]) { if (tool.toolButton) { - this.registerToolbarButtons(tool.toolButton); + this.registerToolbarButtons(tool.toolButton) } if (tool.toolDynamicButton && tool.toolDynamicButton.length > 0) { - this.registerDynamicButtons(tool.toolDynamicButton); + this.registerDynamicButtons(tool.toolDynamicButton) } } } @@ -91,14 +91,14 @@ export class ToolbarService { public waitForApi = (id: string): VePromise => { if (!this.toolbars.hasOwnProperty(id)) { - this.toolbars[id] = {}; + this.toolbars[id] = {} this.toolbars[id].promise = new this.$q((resolve, reject) => { - this.toolbars[id].resolve = resolve; - this.toolbars[id].reject = reject; - }); + this.toolbars[id].resolve = resolve + this.toolbars[id].reject = reject + }) } - return this.toolbars[id].promise; - }; + return this.toolbars[id].promise + } public initApi( id: string, @@ -109,16 +109,16 @@ export class ToolbarService { initialSelection?: string ): ToolbarApi { if (!id) { - throw new Error('Unable to create Toolbar, missing id'); + throw new Error('Unable to create Toolbar, missing id') } if (!this.toolbars[id]) { - this.toolbars[id] = {}; + this.toolbars[id] = {} } if (!this.toolbars[id].resolve) { this.toolbars[id].promise = new this.$q((resolve, reject) => { - this.toolbars[id].resolve = resolve; - this.toolbars[id].reject = reject; - }); + this.toolbars[id].resolve = resolve + this.toolbars[id].reject = reject + }) } // if (!ctrl.$onDestroy) { @@ -127,68 +127,68 @@ export class ToolbarService { // } // } - const api = new ToolbarApi(id); + const api = new ToolbarApi(id) if (buttons && buttons.length > 0) { - this.registerToolbarButtons(buttons); + this.registerToolbarButtons(buttons) } if (dynamicButtons && dynamicButtons.length > 0) { - this.registerDynamicButtons(dynamicButtons); + this.registerDynamicButtons(dynamicButtons) } - init(api); - this.toolbars[id].api = api; + init(api) + this.toolbars[id].api = api if (api.buttons.length > 0) { - let inspect: IToolBarButton; + let inspect: IToolBarButton if (initialSelection) { - inspect = this.getToolbarButton(initialSelection); + inspect = this.getToolbarButton(initialSelection) } else { - inspect = api.buttons[0]; + inspect = api.buttons[0] } //Initialize Toolbar Clicked Subject this.eventSvc.resolve(id, { id: inspect.id, title: inspect.tooltip, - }); + }) } - this.toolbars[id].resolve(api); - return api; + this.toolbars[id].resolve(api) + return api } public destroyApi = (id: string): void => { if (this.toolbars.hasOwnProperty(id)) { - delete this.toolbars[id]; + delete this.toolbars[id] } - }; + } public registerToolbarButtons = (buttons: IToolBarButton | IToolBarButton[]): void => { if (!Array.isArray(buttons)) { - buttons = [buttons]; + buttons = [buttons] } if (buttons.length > 0) { for (const button of buttons) { if (!this.buttons[button.id]) { - this.buttons[button.id] = button; + this.buttons[button.id] = button } } } - }; + } public registerDynamicButtons = (dynamicButtons: IToolBarButton | IToolBarButton[]): void => { if (!Array.isArray(dynamicButtons)) { - dynamicButtons = [dynamicButtons]; + dynamicButtons = [dynamicButtons] } if (dynamicButtons.length > 0) { for (const button of dynamicButtons) { if (!this.dynamicButtons[button.id]) { - this.dynamicButtons[button.id] = button; + this.dynamicButtons[button.id] = button } } } - }; + } - public attachDynamicButtons; + public attachDynamicButtons /** * @name veUtils/ToolbarService#this.getToolbarButton @@ -200,29 +200,29 @@ export class ToolbarService { */ public getToolbarButton = (buttonId: string): ToolButton => { if (this.buttons.hasOwnProperty(buttonId)) { - const newButton = new ToolButton(buttonId, this.buttons[buttonId]); + const newButton = new ToolButton(buttonId, this.buttons[buttonId]) if (this.buttons[buttonId].dynamic_ids) { - newButton.dynamicButtons = []; + newButton.dynamicButtons = [] for (const id of this.buttons[buttonId].dynamic_ids) { - newButton.dynamicButtons.push(new ToolButton(id, this.getDynamicButton(id))); + newButton.dynamicButtons.push(new ToolButton(id, this.getDynamicButton(id))) } } - return newButton; + return newButton } else { - return (this.buttons[buttonId] = new ToolButton(buttonId)); + return (this.buttons[buttonId] = new ToolButton(buttonId)) } - }; + } public getDynamicButton = (button: string): IToolBarButton => { if (this.dynamicButtons.hasOwnProperty(button)) { - return this.dynamicButtons[button]; + return this.dynamicButtons[button] } - }; + } static error(reason?: VePromiseReason): string { - if (reason && reason.message) return 'Toolbar error: ' + reason.message; - else return 'Toolbar Error!'; + if (reason && reason.message) return 'Toolbar error: ' + reason.message + else return 'Toolbar Error!' } } -veCore.service('ToolbarService', ToolbarService); +veCore.service('ToolbarService', ToolbarService) diff --git a/src/ve-core/toolbar/tool-bar.component.ts b/src/ve-core/toolbar/tool-bar.component.ts index 76b8b9e62..b58312d80 100644 --- a/src/ve-core/toolbar/tool-bar.component.ts +++ b/src/ve-core/toolbar/tool-bar.component.ts @@ -1,13 +1,13 @@ -import { veCoreEvents } from '@ve-core/events'; -import { buttonOnClickFn, IToolBarButton } from '@ve-core/toolbar'; -import { RootScopeService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { veCoreEvents } from '@ve-core/events' +import { buttonOnClickFn, IToolBarButton } from '@ve-core/toolbar' +import { RootScopeService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' -import { veCore } from '@ve-core'; +import { veCore } from '@ve-core' -import { ToolbarService } from './services/Toolbar.service'; +import { ToolbarService } from './services/Toolbar.service' -import { VeComponentOptions } from '@ve-types/angular'; +import { VeComponentOptions } from '@ve-types/angular' const ToolBarComponent: VeComponentOptions = { selector: 'toolBar', @@ -30,17 +30,17 @@ const ToolBarComponent: VeComponentOptions = { paneToggle: '&', }, controller: class VeToolbarController implements angular.IComponentController { - public subs: Rx.IDisposable[]; + public subs: Rx.IDisposable[] - private anchor: string; - private toolbarId: string; - private paneToggle?(): void; + private anchor: string + private toolbarId: string + private paneToggle?(): void - public buttons: IToolBarButton[]; + public buttons: IToolBarButton[] - tooltipAnchor; + tooltipAnchor - static $inject = ['growl', 'RootScopeService', 'EventService', 'ToolbarService']; + static $inject = ['growl', 'RootScopeService', 'EventService', 'ToolbarService'] constructor( private growl: angular.growl.IGrowlService, @@ -50,65 +50,65 @@ const ToolBarComponent: VeComponentOptions = { ) {} $onInit(): void { - this.eventSvc.$init(this); + this.eventSvc.$init(this) if (this.anchor) { switch (this.anchor) { case 'left': - this.tooltipAnchor = 'right'; - break; + this.tooltipAnchor = 'right' + break case 'right': - this.tooltipAnchor = 'left'; - break; + this.tooltipAnchor = 'left' + break case 'top': - this.tooltipAnchor = 'bottom'; - break; + this.tooltipAnchor = 'bottom' + break case 'bottom': - this.tooltipAnchor = 'top'; - break; + this.tooltipAnchor = 'top' + break } } else { - this.tooltipAnchor = 'left'; + this.tooltipAnchor = 'left' } this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - this.buttons = api.buttons; + this.buttons = api.buttons if (this.buttons.length > 0) { //Binding to catch all "clicks" on tb and execute select function this.eventSvc.binding(this.toolbarId, (data) => { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.select(data.id), (reason) => this.growl.error(ToolbarService.error(reason)) - ); - }); + ) + }) } }, (reason) => { - this.growl.error(reason.message); + this.growl.error(reason.message) } - ); + ) } public clicked = (button: IToolBarButton): void => { if (!button.permission) { - return; + return } if (!button.active) { - return; + return } if (this.paneToggle) { - this.paneToggle(); + this.paneToggle() } if (button.onClick) { - button.onClick(); + button.onClick() } else if (this.onClick) { - this.onClick(button); + this.onClick(button) } else { - this.growl.error('Button' + button.id + 'has no click function'); + this.growl.error('Button' + button.id + 'has no click function') } - }; + } protected onClick: buttonOnClickFn = (button) => { if (!button.dynamic) { @@ -116,12 +116,12 @@ const ToolBarComponent: VeComponentOptions = { id: button.id, category: button.category, title: button.tooltip, - }); + }) } else { - this.eventSvc.$broadcast(button.id); + this.eventSvc.$broadcast(button.id) } - }; + } }, -}; +} -veCore.component(ToolBarComponent.selector, ToolBarComponent); +veCore.component(ToolBarComponent.selector, ToolBarComponent) diff --git a/src/ve-core/ve-core.module.ts b/src/ve-core/ve-core.module.ts index 28334ca8a..999f39349 100644 --- a/src/ve-core/ve-core.module.ts +++ b/src/ve-core/ve-core.module.ts @@ -1,4 +1,4 @@ -import angular from 'angular'; +import angular from 'angular' /** * @ngdoc overview @@ -76,7 +76,7 @@ export const veCore = angular.module('ve-core', [ 'angular-growl', 'angularjs-dropdown-multiselect', 'ui.tree-filter', -]); +]) veCore .config([ @@ -88,17 +88,17 @@ veCore growlProvider: angular.growl.IGrowlProvider, uiTreeFilterSettingsProvider ): void => { - $sceProvider.enabled(false); - growlProvider.onlyUniqueMessages(false); + $sceProvider.enabled(false) + growlProvider.onlyUniqueMessages(false) growlProvider.globalTimeToLive({ success: 5000, error: -1, warning: 5000, info: 5000, - }); - growlProvider.globalPosition('bottom-right'); - uiTreeFilterSettingsProvider.addresses = ['label']; - uiTreeFilterSettingsProvider.descendantCollection = 'children'; + }) + growlProvider.globalPosition('bottom-right') + uiTreeFilterSettingsProvider.addresses = ['label'] + uiTreeFilterSettingsProvider.descendantCollection = 'children' }, ]) - .constant('CKEDITOR', window.CKEDITOR); + .constant('CKEDITOR', window.CKEDITOR) diff --git a/src/ve-extensions/experimental-magic/index.ts b/src/ve-extensions/experimental-magic/index.ts index 2a93ca922..7a73778bc 100644 --- a/src/ve-extensions/experimental-magic/index.ts +++ b/src/ve-extensions/experimental-magic/index.ts @@ -1 +1 @@ -import './spec-tools/spec-magic.component'; +import './spec-tools/spec-magic.component' diff --git a/src/ve-extensions/experimental-magic/spec-tools/spec-magic.component.ts b/src/ve-extensions/experimental-magic/spec-tools/spec-magic.component.ts index 39f397226..a35a288c5 100644 --- a/src/ve-extensions/experimental-magic/spec-tools/spec-magic.component.ts +++ b/src/ve-extensions/experimental-magic/spec-tools/spec-magic.component.ts @@ -1,11 +1,11 @@ -import angular from 'angular'; -import _ from 'lodash'; +import angular from 'angular' +import _ from 'lodash' -import { ComponentService } from '@ve-components/services'; -import { SpecTool, ISpecTool, SpecService } from '@ve-components/spec-tools'; -import { ToolbarService } from '@ve-core/toolbar'; -import { ApplicationService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; +import { ComponentService } from '@ve-components/services' +import { SpecTool, ISpecTool, SpecService } from '@ve-components/spec-tools' +import { ToolbarService } from '@ve-core/toolbar' +import { ApplicationService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' import { ApiService, ElementService, @@ -13,14 +13,14 @@ import { ProjectService, URLService, ViewService, -} from '@ve-utils/mms-api-client'; +} from '@ve-utils/mms-api-client' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { VeComponentOptions, VeQService } from '@ve-types/angular' class SpecMagicController extends SpecTool implements ISpecTool { - static $inject = [...SpecTool.$inject]; + static $inject = [...SpecTool.$inject] constructor( $q: VeQService, @@ -55,9 +55,9 @@ class SpecMagicController extends SpecTool implements ISpecTool { eventSvc, specSvc, toolbarSvc - ); - this.specType = _.kebabCase(SpecMagicComponent.selector); - this.specTitle = 'Magic Element'; + ) + this.specType = _.kebabCase(SpecMagicComponent.selector) + this.specTitle = 'Magic Element' } } @@ -67,6 +67,6 @@ const SpecMagicComponent: VeComponentOptions = {

    Hello World!!

    `, controller: SpecMagicController, -}; +} -veComponents.component(SpecMagicComponent.selector, SpecMagicComponent); +veComponents.component(SpecMagicComponent.selector, SpecMagicComponent) diff --git a/src/ve-extensions/index.ts b/src/ve-extensions/index.ts index d383e35a3..3e118298f 100644 --- a/src/ve-extensions/index.ts +++ b/src/ve-extensions/index.ts @@ -1,2 +1,2 @@ //** Automatically Generated by Webpack do not edit **// -import './experimental-magic'; +import './experimental-magic' \ No newline at end of file diff --git a/src/ve-extensions/present-plots/Plot.service.ts b/src/ve-extensions/present-plots/Plot.service.ts index d6ef86c36..d89e1f6a8 100644 --- a/src/ve-extensions/present-plots/Plot.service.ts +++ b/src/ve-extensions/present-plots/Plot.service.ts @@ -1,8 +1,8 @@ -import { UtilsService } from '@ve-utils/application/Utils.service'; -import { CacheService } from '@ve-utils/core'; -import { ElementService, URLService } from '@ve-utils/mms-api-client'; +import { UtilsService } from '@ve-utils/application/Utils.service' +import { CacheService } from '@ve-utils/core' +import { ElementService, URLService } from '@ve-utils/mms-api-client' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' export class PlotService { constructor( @@ -16,162 +16,162 @@ export class PlotService { //make only a-zA-Z0-9_ because id or class does not support special characters(ie., ()) public toValidId = (original) => { - return original.replace(/[^a-zA-Z0-9_]/gi, ''); - }; + return original.replace(/[^a-zA-Z0-9_]/gi, '') + } /** * @param {Object} clientConfig The size width, height and margin info from magicDraw * @param {Object} defaultPlotConfig The size width, height and margin from the plot directive */ public plotConfig = (clientConfig, defaultPlotConfig) => { - const plotConfig = defaultPlotConfig; + const plotConfig = defaultPlotConfig if (clientConfig !== undefined) { if (clientConfig.size !== undefined) { if (clientConfig.size.width != undefined && !isNaN(clientConfig.size.width)) - plotConfig.width = Number(clientConfig.size.width); + plotConfig.width = Number(clientConfig.size.width) if (clientConfig.size.height != undefined && !isNaN(clientConfig.size.height)) - plotConfig.height = Number(clientConfig.size.height); + plotConfig.height = Number(clientConfig.size.height) } if (clientConfig.padding !== undefined) { if (clientConfig.padding.top != undefined && !isNaN(clientConfig.padding.top)) - plotConfig.marginTop = Number(clientConfig.padding.top); + plotConfig.marginTop = Number(clientConfig.padding.top) if (clientConfig.padding.right != undefined && !isNaN(clientConfig.padding.right)) - plotConfig.marginRight = Number(clientConfig.padding.right); + plotConfig.marginRight = Number(clientConfig.padding.right) if (clientConfig.padding.left != undefined && !isNaN(clientConfig.padding.left)) - plotConfig.marginLeft = Number(clientConfig.padding.left); + plotConfig.marginLeft = Number(clientConfig.padding.left) if (clientConfig.padding.bottom != undefined && !isNaN(clientConfig.padding.bottom)) - plotConfig.marginBottom = Number(clientConfig.padding.bottom); + plotConfig.marginBottom = Number(clientConfig.padding.bottom) } } - return plotConfig; - }; + return plotConfig + } public readValues2(plot, projectId, refId, commitId) { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() const aMmsEid = { projectId: projectId, refId: refId, commitId: commitId, - }; - const isHeader = plot.table.header !== undefined && plot.table.header.length > 0; + } + const isHeader = plot.table.header !== undefined && plot.table.header.length > 0 if (isHeader) { - const aheader = this._asyncReadTableHeader(aMmsEid, plot.table.header[0]); + const aheader = this._asyncReadTableHeader(aMmsEid, plot.table.header[0]) aheader.then((tableheader) => { - const abody = this._asyncReadTableBody2(aMmsEid, plot.table.body, tableheader); + const abody = this._asyncReadTableBody2(aMmsEid, plot.table.body, tableheader) abody.then((tablebody) => { const r = { tableheader: tableheader, tablebody: tablebody, isHeader: isHeader, - }; - deferred.resolve(r); - }); - }); + } + deferred.resolve(r) + }) + }) } else { - const abody = this._asyncReadTableBody(aMmsEid, plot.table.body); + const abody = this._asyncReadTableBody(aMmsEid, plot.table.body) abody.then((tablebody) => { - const r = { tablebody: tablebody, isHeader: isHeader }; - deferred.resolve(r); - }); + const r = { tablebody: tablebody, isHeader: isHeader } + deferred.resolve(r) + }) } - return deferred.promise; + return deferred.promise } //end of readValues public readValues = (plot, projectId, refId, commitId) => { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() const aMmsEid = { projectId: projectId, refId: refId, commitId: commitId, - }; - const isHeader = plot.table.header !== undefined && plot.table.header.length > 0; + } + const isHeader = plot.table.header !== undefined && plot.table.header.length > 0 if (isHeader) { - const aheader = this._asyncReadTableHeader(aMmsEid, plot.table.header[0]); + const aheader = this._asyncReadTableHeader(aMmsEid, plot.table.header[0]) aheader.then((tableheader) => { - const abody = this._asyncReadTableBody(aMmsEid, plot.table.body); + const abody = this._asyncReadTableBody(aMmsEid, plot.table.body) abody.then((tablebody) => { const r = { tableheader: tableheader, tablebody: tablebody, isHeader: isHeader, - }; - deferred.resolve(r); - }); - }); + } + deferred.resolve(r) + }) + }) } else { - const abody = this._asyncReadTableBody(aMmsEid, plot.table.body); + const abody = this._asyncReadTableBody(aMmsEid, plot.table.body) abody.then((tablebody) => { - const r = { tablebody: tablebody, isHeader: isHeader }; - deferred.resolve(r); - }); + const r = { tablebody: tablebody, isHeader: isHeader } + deferred.resolve(r) + }) } - return deferred.promise; - }; //end of readValues + return deferred.promise + } //end of readValues private _asyncReadTableHeader = (aMmsEid, header) => { return this.$q((resolve) => { this._readRowValues(header, aMmsEid).then((tableheader) => { - tableheader.values.shift(); //remove 1st element - resolve(tableheader.values); - }); - }); - }; + tableheader.values.shift() //remove 1st element + resolve(tableheader.values) + }) + }) + } private _asyncReadTableBody = (aMmsEid, tablebody) => { return this.$q((resolve) => { - const c3_data = []; - const valuesO = []; + const c3_data = [] + const valuesO = [] tablebody.forEach((row) => { this._readRowValues(row, aMmsEid).then((yyvalue) => { - c3_data.push(yyvalue.values); - valuesO.push(yyvalue.valuesO); + c3_data.push(yyvalue.values) + valuesO.push(yyvalue.valuesO) if (c3_data.length === tablebody.length) { const r = { c3_data: c3_data, valuesO: valuesO, - }; - resolve(r); + } + resolve(r) } - }); - }); - }); - }; + }) + }) + }) + } private _asyncReadTableBody2(aMmsEid, tablebody, tableheader) { return this.$q((resolve) => { - const c3_data = []; - const valuesO = []; + const c3_data = [] + const valuesO = [] //adding "rowheader" so length of header and rowvalues will be the same. - const mtableheader = tableheader.slice(0); - mtableheader.splice(0, 0, 'rowheader'); + const mtableheader = tableheader.slice(0) + mtableheader.splice(0, 0, 'rowheader') tablebody.forEach((row) => { this._readRowValues2(row, aMmsEid, mtableheader).then((yyvalue) => { - c3_data.push(yyvalue.valuesx); - valuesO.push(yyvalue.valuesO); + c3_data.push(yyvalue.valuesx) + valuesO.push(yyvalue.valuesO) if (valuesO.length === tablebody.length) { const r = { c3_data: c3_data, valuesO: valuesO, - }; - resolve(r); + } + resolve(r) } - }); - }); - }); + }) + }) + }) } private static _getValue(datavalue) { if (datavalue && datavalue.type === 'LiteralString') { - if (isNaN(datavalue.value)) return datavalue.value; - else return Number(datavalue.value); + if (isNaN(datavalue.value)) return datavalue.value + else return Number(datavalue.value) } else if (datavalue && (datavalue.type === 'LiteralReal' || datavalue.type === 'LiteralInteger')) { - return datavalue.value; + return datavalue.value } } @@ -179,60 +179,60 @@ export class PlotService { return this.$q((resolve) => { if (e.content[0].sourceType == 'text') { //console.log("text"); - let tv = e.content[0].text.replace('

    ', '').replace('

    ', '').trim(); - if (!isNaN(tv)) tv = Number(tv); - resolve({ index: index, value: tv, valueO: e }); + let tv = e.content[0].text.replace('

    ', '').replace('

    ', '').trim() + if (!isNaN(tv)) tv = Number(tv) + resolve({ index: index, value: tv, valueO: e }) } else if (e.content[0].sourceType === 'reference') { - aMmsEid.elementId = e.content[0].source; + aMmsEid.elementId = e.content[0].source if (e.content[0].sourceProperty === 'name') { //console.log("name"); this.elementSvc.getElement(aMmsEid, 1, false).then((refe) => { //value = refe.name; //valueO= refe; - let nameModified: number | string = refe.name; + let nameModified: number | string = refe.name if (!isNaN(Number(refe.name))) //means its a number - nameModified = Number(refe.name); + nameModified = Number(refe.name) resolve({ index: index, value: nameModified, valueO: refe, - }); - }); + }) + }) } else if (e.content[0].sourceProperty === 'documentation') { //console.log("doc"); this.elementSvc.getElement(aMmsEid, 1, false).then((refe) => { let docModified: number | string = refe.documentation .replace('

    ', '') .replace('

    ', '') - .trim(); + .trim() //seems adding \n at the end when modified at vieweditor so if number goahead to conver to number //i.e., "5\n" will be a number. if (!isNaN(Number(docModified))) //means it is a number - docModified = Number(docModified); + docModified = Number(docModified) resolve({ index: index, value: docModified, valueO: refe, - }); - }); + }) + }) } else { //sourceProperty === 'value' //console.log('value'); this.elementSvc.getElement(aMmsEid, 1, false).then((refe) => { - const valueO = refe; - let value = ''; + const valueO = refe + let value = '' if (refe.type === 'Property' || refe.type === 'Port') { if (refe.defaultValue) { - value = PlotService._getValue(refe.defaultValue); //default value + value = PlotService._getValue(refe.defaultValue) //default value } else { - value = ''; + value = '' } } if (refe.type === 'Slot') { - value = PlotService._getValue(refe.value[0]); //scope.element.value + value = PlotService._getValue(refe.value[0]) //scope.element.value } /* not sure what to do if (refe.type === 'Constraint' && refe.specification) { @@ -246,71 +246,71 @@ export class PlotService { index: index, value: value, valueO: valueO, - }); - }); + }) + }) } //end of else } //reference - }); - }; + }) + } private _readRowValues = (row, aMmsEid) => { return this.$q((resolve) => { - const values = []; - const valuesO = []; - let index = 0; + const values = [] + const valuesO = [] + let index = 0 row.forEach((e) => { if (e.content.length === 0) { - values[index] = null; - valuesO[index] = null; - index++; + values[index] = null + valuesO[index] = null + index++ } else { if (e.content[0].type == 'Paragraph') { this._readParagraphValue(e, aMmsEid, index++).then((r) => { - values[r.index] = r.value; - valuesO[r.index] = r.valueO; + values[r.index] = r.value + valuesO[r.index] = r.valueO if (values.length === row.length) { const result = { values: values, valuesO: valuesO, - }; - resolve(result); + } + resolve(result) } - }); + }) } // Paragraph } //end of else - }); //for each row - }); - }; //end of function + }) //for each row + }) + } //end of function private _readRowValues2(row, aMmsEid, mtableheader) { return this.$q((resolve) => { - const valuesx = []; //named index instead of number index - const valuesO = []; - let index = 0; + const valuesx = [] //named index instead of number index + const valuesO = [] + let index = 0 row.forEach((e) => { if (e.content.length === 0) { - valuesx[mtableheader[index]] = null; - valuesO[index] = null; - index++; + valuesx[mtableheader[index]] = null + valuesO[index] = null + index++ } else { if (e.content[0].type == 'Paragraph') { this._readParagraphValue(e, aMmsEid, index++).then((r) => { - valuesx[mtableheader[r.index]] = r.value; - valuesO[r.index] = r.valueO; + valuesx[mtableheader[r.index]] = r.value + valuesO[r.index] = r.valueO if (valuesO.length === row.length) { const result = { valuesx: valuesx, valuesO: valuesO, - }; - resolve(result); + } + resolve(result) } - }); + }) } // Paragraph } //end of else - }); //for each row - }); + }) //for each row + }) } //end of function } -PlotService.$inject = ['$q', '$http', 'URLService', 'UtilsService', 'CacheService', 'ElementService']; +PlotService.$inject = ['$q', '$http', 'URLService', 'UtilsService', 'CacheService', 'ElementService'] -veUtils.service('PlotService', PlotService); +veUtils.service('PlotService', PlotService) diff --git a/src/ve-extensions/present-plots/config.json b/src/ve-extensions/present-plots/config.json index 081bf39d3..cf3aff4a7 100644 --- a/src/ve-extensions/present-plots/config.json +++ b/src/ve-extensions/present-plots/config.json @@ -1,8 +1,8 @@ { - "presentations": [ - { - "name": "C3/D3 Plots Extension", - "path": "present-plots" - } - ] -} + "presentations": [ + { + "name": "C3/D3 Plots Extension", + "path": "present-plots" + } + ] +} \ No newline at end of file diff --git a/src/ve-extensions/present-plots/presentations/components/index.ts b/src/ve-extensions/present-plots/presentations/components/index.ts index 4d62d5b3b..354dd2402 100644 --- a/src/ve-extensions/present-plots/presentations/components/index.ts +++ b/src/ve-extensions/present-plots/presentations/components/index.ts @@ -1,7 +1,7 @@ -import './mmsC3Plot.directive'; -import './mmsD3GroupedHorizontalBarPlot.directive'; -import './mmsD3LineGraph.directive'; -import './mmsD3NormalizedStackedBarPlot.directive'; -import './mmsD3ObservationProfileChartIo.directive'; -import './mmsD3ParallelAxisPlot.directive'; -import './mmsD3RadarPlot.directive'; +import './mmsC3Plot.directive' +import './mmsD3GroupedHorizontalBarPlot.directive' +import './mmsD3LineGraph.directive' +import './mmsD3NormalizedStackedBarPlot.directive' +import './mmsD3ObservationProfileChartIo.directive' +import './mmsD3ParallelAxisPlot.directive' +import './mmsD3RadarPlot.directive' diff --git a/src/ve-extensions/present-plots/presentations/components/mmsC3Plot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsC3Plot.directive.ts index e8b8fbc55..e7453df3c 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsC3Plot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsC3Plot.directive.ts @@ -1,21 +1,21 @@ -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -veComponents.directive('mmsC3Plot', ['PlotService', '$window', mmsC3Plot]); +veComponents.directive('mmsC3Plot', ['PlotService', '$window', mmsC3Plot]) function mmsC3Plot(PlotService, $window, _) { const mmsChartLink = function (scope, element, attrs, mmsViewCtrl) { - const c3 = $window.c3; - const d3 = $window.d3; - const divchart = d3.select(element[0]).append('div'); + const c3 = $window.c3 + const d3 = $window.d3 + const divchart = d3.select(element[0]).append('div') - let projectId; - let refId; - let commitId; + let projectId + let refId + let commitId if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin(); - projectId = viewVersion.projectId; - refId = viewVersion.refId; - commitId = viewVersion.commitId; + const viewVersion = mmsViewCtrl.getElementOrigin() + projectId = viewVersion.projectId + refId = viewVersion.refId + commitId = viewVersion.commitId } /** @@ -26,66 +26,66 @@ function mmsC3Plot(PlotService, $window, _) { function simplifyFunctions(object) { _.forOwn(object, function (value, key, ob) { if (_.isPlainObject(value)) { - simplifyFunctions(value); + simplifyFunctions(value) } else { - ob[key] = eval('(' + value + ')'); + ob[key] = eval('(' + value + ')') } - }); + }) } function vf_pplot(c3json, c3jfunc) { if (c3jfunc && _.isPlainObject(c3jfunc)) { - simplifyFunctions(c3jfunc); - _.merge(c3json, c3jfunc); + simplifyFunctions(c3jfunc) + _.merge(c3json, c3jfunc) } - c3.generate(c3json); + c3.generate(c3json) } scope.render = function () { PlotService.readValues(scope.plot, projectId, refId, commitId).then(function (value) { - scope.valuesO = value.tablebody.valuesO; //value objects used in watch - let c3options; + scope.valuesO = value.tablebody.valuesO //value objects used in watch + let c3options if (value.tablebody.c3_data.length === 0) { //no data - return; + return } if (scope.plot.config.options === undefined || scope.plot.config.options.length === 0) { if (value.isHeader) c3options = { data: { x: 'x', type: 'line' }, axis: { x: { type: 'category', tick: { centered: true } } }, - }; - else c3options = { data: {} }; - } else c3options = scope.plot.config.options; + } + else c3options = { data: {} } + } else c3options = scope.plot.config.options if ( value.tablebody.c3_data.length === scope.plot.table.body.length && c3options.data.xs === undefined && value.isHeader ) { - value.tablebody.c3_data.unshift(['x'].concat(value.tableheader)); + value.tablebody.c3_data.unshift(['x'].concat(value.tableheader)) } - c3options.data.columns = value.tablebody.c3_data; + c3options.data.columns = value.tablebody.c3_data - let c3jfunc; + let c3jfunc if (scope.plot.config.functions) { - c3jfunc = scope.plot.config.functions; + c3jfunc = scope.plot.config.functions } - divchart.selectAll('*').remove(); - divchart.attr('id', 'c3chart' + scope.$id); - c3options.bindto = '#c3chart' + scope.$id; + divchart.selectAll('*').remove() + divchart.attr('id', 'c3chart' + scope.$id) + c3options.bindto = '#c3chart' + scope.$id - vf_pplot(c3options, c3jfunc); - }); - }; //end of render + vf_pplot(c3options, c3jfunc) + }) + } //end of render scope.$watch( 'valuesO', function (newVals, oldVals) { - return scope.render(); + return scope.render() }, true - ); - }; //end of link + ) + } //end of link return { restrict: 'EA', @@ -94,5 +94,5 @@ function mmsC3Plot(PlotService, $window, _) { plot: '<', }, link: mmsChartLink, - }; //return + } //return } diff --git a/src/ve-extensions/present-plots/presentations/components/mmsD3GroupedHorizontalBarPlot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsD3GroupedHorizontalBarPlot.directive.ts index 58c3b2163..745c792e3 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsD3GroupedHorizontalBarPlot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsD3GroupedHorizontalBarPlot.directive.ts @@ -1,62 +1,62 @@ -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' //d3js grouped horizontal bar chart is created by referencing //http://bl.ocks.org/erikvullings/51cc5332439939f1f292 -veComponents.directive('mmsD3GroupedHorizontalBarPlot', ['PlotService', '$window', mmsD3GroupedHorizontalBarPlot]); +veComponents.directive('mmsD3GroupedHorizontalBarPlot', ['PlotService', '$window', mmsD3GroupedHorizontalBarPlot]) function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { const mmsChartLink = function (scope, element, attrs, mmsViewCtrl) { - const d3 = $window.d3; - const divchart = d3.select(element[0]).append('div'); + const d3 = $window.d3 + const divchart = d3.select(element[0]).append('div') const defaultPlotConfig = { width: 960, marginTop: 20, marginRight: 40, marginBottom: 30, marginLeft: 40, - }; - const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig); - let achartdata; + } + const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig) + let achartdata element.click(function (e) { //stop Propogating event to parent(transclude-doc) element. - e.stopPropagation(); - }); + e.stopPropagation() + }) - const d3colorR = d3.scaleOrdinal(d3.schemeCategory10).range(); + const d3colorR = d3.scaleOrdinal(d3.schemeCategory10).range() function getColor(data, i) { - return data.colors !== undefined ? d3colorR[data.colors[i]] : d3colorR[i]; + return data.colors !== undefined ? d3colorR[data.colors[i]] : d3colorR[i] } - let projectId; - let refId; - let commitId; + let projectId + let refId + let commitId if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin(); - projectId = viewVersion.projectId; - refId = viewVersion.refId; - commitId = viewVersion.commitId; + const viewVersion = mmsViewCtrl.getElementOrigin() + projectId = viewVersion.projectId + refId = viewVersion.refId + commitId = viewVersion.commitId } const opacitydefault = 1, //0.7, opacityselected = 1.0, - opacitynotselected = 0.3; + opacitynotselected = 0.3 function mouseout() { - d3.selectAll('.ghbbar').transition(200).style('fill-opacity', opacitydefault); + d3.selectAll('.ghbbar').transition(200).style('fill-opacity', opacitydefault) - d3.selectAll('.legendRect').transition(200).style('fill-opacity', opacitydefault); + d3.selectAll('.legendRect').transition(200).style('fill-opacity', opacitydefault) - d3.selectAll('.legentFilter').transition(200).style('opacity', opacitydefault); + d3.selectAll('.legentFilter').transition(200).style('opacity', opacitydefault) } //end of function mouseout function mouseover(mouseoverClassId) { - d3.selectAll('.ghbbar').transition(200).style('fill-opacity', opacitynotselected); + d3.selectAll('.ghbbar').transition(200).style('fill-opacity', opacitynotselected) - d3.selectAll('.legendRect').transition(200).style('fill-opacity', opacitynotselected); + d3.selectAll('.legendRect').transition(200).style('fill-opacity', opacitynotselected) - d3.selectAll('.legentFilter').transition(200).style('opacity', opacitynotselected); + d3.selectAll('.legentFilter').transition(200).style('opacity', opacitynotselected) - d3.selectAll(mouseoverClassId).transition(200).style('fill-opacity', opacityselected); + d3.selectAll(mouseoverClassId).transition(200).style('fill-opacity', opacityselected) - d3.selectAll(mouseoverClassId).transition(200).style('opacity', opacityselected); + d3.selectAll(mouseoverClassId).transition(200).style('opacity', opacityselected) } //end of function mouseover function createFilters(data) { @@ -64,28 +64,28 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { const graphFilter = divchart .append('div') .attr('class', 'graphFilter ' + data.id) - .style('margin-left', plotConfig.marginLeft + 'px'); + .style('margin-left', plotConfig.marginLeft + 'px') const filterLegendsDiv = graphFilter .append('div') .append('label') .style('border', '1px solid #ddd') - .text('Filter by Legends'); + .text('Filter by Legends') filterLegendsDiv .selectAll('div') .data(data.legends) .enter() .append('div') .attr('class', function (d, i) { - return 'legentFilter ' + data.id + ' ' + PlotService.toValidId(d); + return 'legentFilter ' + data.id + ' ' + PlotService.toValidId(d) }) .attr('style', function (d, i) { - return 'opacity: ' + opacitydefault + ';background-color:' + getColor(data, i) + ';'; + return 'opacity: ' + opacitydefault + ';background-color:' + getColor(data, i) + ';' }) .on('mouseover', (d, i) => { - mouseover('.' + data.id + '.' + PlotService.toValidId(d)); + mouseover('.' + data.id + '.' + PlotService.toValidId(d)) }) .on('mouseout', (d, i) => { - mouseout(); + mouseout() }) .append('label') .each((d, i) => { @@ -94,43 +94,43 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { .append('input') .attr('type', 'checkbox') .attr('checked', function (d, i) { - if (data.legendsFilter[PlotService.toValidId(d)] === true) return true; - else return null; + if (data.legendsFilter[PlotService.toValidId(d)] === true) return true + else return null }) .attr('style', function (d, i) { - const color = getColor(data, i); - return 'color: ' + color + ';background-color:' + color + ';'; + const color = getColor(data, i) + return 'color: ' + color + ';background-color:' + color + ';' }) .on('click', (d) => { // filter by legends - data.legendsFilter[PlotService.toValidId(d)] = this.checked; - createGroupedHorizontalBarChart(achartdata); - createFilters(achartdata); - }); + data.legendsFilter[PlotService.toValidId(d)] = this.checked + createGroupedHorizontalBarChart(achartdata) + createFilters(achartdata) + }) d3.select(this) .append('span') .text((d) => { - return d; - }); - }); + return d + }) + }) const filterColoumnsDiv = graphFilter .append('div') .append('label') .style('border', '1px solid #ddd') - .text('Filter by Columns'); + .text('Filter by Columns') filterColoumnsDiv .selectAll('div') .data(data.labels) .enter() .append('div') .attr('class', function (d, i) { - return 'columnfilter ' + data.id + ' ' + PlotService.toValidId(d); + return 'columnfilter ' + data.id + ' ' + PlotService.toValidId(d) }) .on('mouseover', function (d, i) { - mouseover('.' + data.id + '.' + PlotService.toValidId(d)); + mouseover('.' + data.id + '.' + PlotService.toValidId(d)) }) .on('mouseout', function (d, i) { - mouseout(); + mouseout() }) .append('label') .each((d, i) => { @@ -139,54 +139,54 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { .append('input') .attr('type', 'checkbox') .attr('checked', function (d, i) { - if (data.labelsFilter[PlotService.toValidId(d)] === true) return true; - else return null; + if (data.labelsFilter[PlotService.toValidId(d)] === true) return true + else return null }) .on('click', (d) => { //filter by columns(labels) - data.labelsFilter[PlotService.toValidId(d)] = this.checked; - createGroupedHorizontalBarChart(achartdata); //2nd argument is not used - createFilters(achartdata); - }); + data.labelsFilter[PlotService.toValidId(d)] = this.checked + createGroupedHorizontalBarChart(achartdata) //2nd argument is not used + createFilters(achartdata) + }) d3.select(this) .append('span') .text((d) => { - return d; - }); - }); + return d + }) + }) } //end of function createFilter function createGroupedHorizontalBarChart(data) { - divchart.selectAll('*').remove(); - divchart.attr('class', achartdata.id).attr('style', 'border:1px solid #ddd'); + divchart.selectAll('*').remove() + divchart.attr('class', achartdata.id).attr('style', 'border:1px solid #ddd') - const svg = divchart.append('svg:svg').attr('class', 'ghbchart ' + data.id); + const svg = divchart.append('svg:svg').attr('class', 'ghbchart ' + data.id) - const filteredDataValues: any[] = []; - const filteredDataSysmlids: any[] = []; - const filteredDataColors: any[] = []; - const filteredDataLegends: any[] = []; //table row headers - const filteredDataLabels: any[] = []; //table column headers - const datalegendsfilter: any[] = data.legendsFilter; - const datalabelsfilter: any[] = data.labelsFilter; - let counter = -1; + const filteredDataValues: any[] = [] + const filteredDataSysmlids: any[] = [] + const filteredDataColors: any[] = [] + const filteredDataLegends: any[] = [] //table row headers + const filteredDataLabels: any[] = [] //table column headers + const datalegendsfilter: any[] = data.legendsFilter + const datalabelsfilter: any[] = data.labelsFilter + let counter = -1 for (let i = 0; i < data.labels.length; i++) { if (datalabelsfilter[PlotService.toValidId(data.labels[i])]) { - filteredDataLabels.push(data.labels[i]); + filteredDataLabels.push(data.labels[i]) for (let j = 0; j < data.values.length; j++) { //data.values.length == data.legends.length - counter++; + counter++ if (datalegendsfilter[PlotService.toValidId(data.legends[j])]) { - filteredDataValues.push(Number(data.values[j][i])); - filteredDataSysmlids.push(data.valueIds[j][i]); - filteredDataColors.push(getColor(data, counter % data.legends.length)); - filteredDataLegends.push(PlotService.toValidId(data.legends[j])); + filteredDataValues.push(Number(data.values[j][i])) + filteredDataSysmlids.push(data.valueIds[j][i]) + filteredDataColors.push(getColor(data, counter % data.legends.length)) + filteredDataLegends.push(PlotService.toValidId(data.legends[j])) } } } } - const filteredLegendsLength = filteredDataLegends.length / filteredDataLabels.length; + const filteredLegendsLength = filteredDataLegends.length / filteredDataLabels.length const chartWidth = plotConfig.width - 260, barHeight = 20, @@ -194,25 +194,25 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { gapBetweenGroups = 10, spaceForLabels = plotConfig.marginLeft, spaceForLegend = 200, - marginbottom = 50; - const chartHeight = barHeight * filteredDataValues.length + gapBetweenGroups * filteredDataLabels.length; + marginbottom = 50 + const chartHeight = barHeight * filteredDataValues.length + gapBetweenGroups * filteredDataLabels.length const x = d3 .scaleLinear() //d3.scale.linear() .domain([0, d3.max(filteredDataValues)]) - .range([0, chartWidth]); + .range([0, chartWidth]) const y = d3 .scaleLinear() //d3.scale.linear() - .range([chartHeight + gapBetweenGroups, 0]); + .range([chartHeight + gapBetweenGroups, 0]) const yAxis = d3 .axisLeft(y) //d3.svg.axis() .tickFormat('') - .tickSize(0); + .tickSize(0) // Specify the chart area and dimensions - const chart = svg.attr('width', plotConfig.width).attr('height', chartHeight + marginbottom); + const chart = svg.attr('width', plotConfig.width).attr('height', chartHeight + marginbottom) // Create bars const bar = chart @@ -227,16 +227,16 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { ',' + (i * barHeight + gapBetweenGroups * (0.5 + Math.floor(i / filteredLegendsLength))) + ')' - ); - }); - const numRows = filteredDataLegends.length / filteredDataLabels.length; + ) + }) + const numRows = filteredDataLegends.length / filteredDataLabels.length // Create rectangles of the correct width bar.append('rect') .attr('id', function (d, i) { - return filteredDataSysmlids[i]; + return filteredDataSysmlids[i] }) .attr('fill', function (d, i) { - return filteredDataColors[i]; + return filteredDataColors[i] }) .style('fill-opacity', opacitydefault) .attr('class', function (d, i) { @@ -247,32 +247,32 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { filteredDataLegends[i] + ' ' + PlotService.toValidId(filteredDataLabels[Math.floor(i / numRows)]) - ); + ) }) .attr('width', x) .attr('height', barHeight - 1) .on('click', function (d, i) { - if (mmsViewCtrl) mmsViewCtrl.transcludeClicked(this.id); + if (mmsViewCtrl) mmsViewCtrl.transcludeClicked(this.id) }) .on('mouseover', function (d, i) { - mouseover('.' + data.id + '.' + filteredDataLegends[i]); + mouseover('.' + data.id + '.' + filteredDataLegends[i]) }) .on('mouseout', function (d, i) { - mouseout(); - }); + mouseout() + }) // Add text label in bar bar.append('text') .attr('class', function (d, i) { - return 'ghbbar ' + data.id + ' ' + filteredDataLegends[i]; + return 'ghbbar ' + data.id + ' ' + filteredDataLegends[i] }) .attr('x', function (d) { - return x(d) - 3; + return x(d) - 3 }) .attr('y', barHeight / 2) .attr('dy', '.35em') .text(function (d) { - return d; - }); + return d + }) //left side label bar.each(function (d, i) { @@ -281,57 +281,57 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { .append('text') .attr('class', 'label') .attr('x', function (d) { - return -10; + return -10 }) .attr('y', groupHeight / 2) .attr('dy', '.35em') - .text(filteredDataLabels[Math.floor(i / filteredLegendsLength)]); + .text(filteredDataLabels[Math.floor(i / filteredLegendsLength)]) } - }); + }) chart .append('g') .attr('class', 'y axis') .attr('id', 'ghbaxis') .attr('transform', 'translate(' + spaceForLabels + ', ' + -gapBetweenGroups / 2 + ')') - .call(yAxis); + .call(yAxis) // Draw legend const legendRectSize = 18, - legendSpacing = 4; - let mouseoverId; + legendSpacing = 4 + let mouseoverId const legend = chart .selectAll('.legend') .data(data.legends) .enter() .append('g') .attr('transform', (d, i) => { - const height = legendRectSize + legendSpacing; - const offset = -gapBetweenGroups / 2; - const horz = spaceForLabels + chartWidth + 60 + legendRectSize; - const vert = i * height - offset; - return 'translate(' + horz + ',' + vert + ')'; + const height = legendRectSize + legendSpacing + const offset = -gapBetweenGroups / 2 + const horz = spaceForLabels + chartWidth + 60 + legendRectSize + const vert = i * height - offset + return 'translate(' + horz + ',' + vert + ')' }) .on('mouseover', function (d, i) { - mouseover('.' + data.id + '.' + PlotService.toValidId(d)); + mouseover('.' + data.id + '.' + PlotService.toValidId(d)) }) .on('mouseout', function (d, i) { - mouseout(); - }); + mouseout() + }) legend .append('rect') .attr('class', function (d, i) { - return 'legendRect ' + data.id + ' ' + PlotService.toValidId(d); + return 'legendRect ' + data.id + ' ' + PlotService.toValidId(d) }) .attr('width', legendRectSize) .attr('height', legendRectSize) .style('fill-opacity', opacitydefault) .style('fill', (d, i) => { - return getColor(data, i); /*return color(i);*/ + return getColor(data, i) /*return color(i);*/ }) .style('stroke', (d, i) => { - return getColor(data, i); /*return color(i);*/ - }); + return getColor(data, i) /*return color(i);*/ + }) legend .append('text') @@ -339,46 +339,46 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { .attr('x', legendRectSize + legendSpacing) .attr('y', legendRectSize - legendSpacing) .text((d, i) => { - return d; - }); + return d + }) } scope.render = function () { PlotService.readValues(scope.plot, projectId, refId, commitId).then(function (value) { - const tablebody = value.tablebody; - const tableheader = value.tableheader; + const tablebody = value.tablebody + const tableheader = value.tableheader //scope.isHeader = value.isHeader; - scope.valuesO = value.tablebody.valuesO; //value objects used in watch + scope.valuesO = value.tablebody.valuesO //value objects used in watch if (tablebody.c3_data.length === 0) { //no data - return; + return } - let udcolors; + let udcolors if (scope.plot.config.colors !== undefined) { - udcolors = scope.plot.config.colors; + udcolors = scope.plot.config.colors } - const rowvalues: number[] = []; - const cellIds: number[] = []; //0, 1, 2, 3 - const legends: any[] = []; - const legendsFilter: boolean[] = []; - let rowvalue: number[]; - let cellId: number[]; - let cid = 0; + const rowvalues: number[] = [] + const cellIds: number[] = [] //0, 1, 2, 3 + const legends: any[] = [] + const legendsFilter: boolean[] = [] + let rowvalue: number[] + let cellId: number[] + let cid = 0 tablebody.c3_data.forEach(function (row) { - legends.push(row[0]); - legendsFilter[row[0]] = true; - rowvalue = []; //reset - cellId = []; //reset + legends.push(row[0]) + legendsFilter[row[0]] = true + rowvalue = [] //reset + cellId = [] //reset for (let i = 1; i < row.length; i++) { - rowvalue.push(row[i]); - cellId.push(cid++); + rowvalue.push(row[i]) + cellId.push(cid++) } - cellIds.push(...cellId); - rowvalues.push(...rowvalue); - }); - const labelsFilter: { [key: string]: boolean } = {}; + cellIds.push(...cellId) + rowvalues.push(...rowvalue) + }) + const labelsFilter: { [key: string]: boolean } = {} tableheader.forEach(function (item) { - labelsFilter[item] = true; - }); + labelsFilter[item] = true + }) achartdata = { id: '_' + scope.$id, labels: tableheader, @@ -388,24 +388,24 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { valueIds: cellIds, legendsFilter: legendsFilter, labelsFilter: labelsFilter, - }; - createGroupedHorizontalBarChart(achartdata); - createFilters(achartdata); - }); - }; //end of render + } + createGroupedHorizontalBarChart(achartdata) + createFilters(achartdata) + }) + } //end of render scope.$watch( 'valuesO', function (newValue, oldValue) { - return scope.render(); + return scope.render() }, true - ); + ) //rect bar is clicked or table cell (Except rowHeaders) is clicked // eventSvc.$on('element.selected', function(data) { // d3.selectAll("rect").transition(200).style("fill-opacity", opacitynotselected); // }); - }; //end of link + } //end of link return { restrict: 'EA', @@ -414,5 +414,5 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { plot: '<', }, link: mmsChartLink, - }; //return + } //return } diff --git a/src/ve-extensions/present-plots/presentations/components/mmsD3NormalizedStackedBarPlot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsD3NormalizedStackedBarPlot.directive.ts index 6cd30dbdb..7b5f1bddd 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsD3NormalizedStackedBarPlot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsD3NormalizedStackedBarPlot.directive.ts @@ -1,15 +1,15 @@ -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -veComponents.directive('mmsD3NormalizedStackedBarPlot', ['PlotService', '$window', mmsD3NormalizedStackedBarPlot]); +veComponents.directive('mmsD3NormalizedStackedBarPlot', ['PlotService', '$window', mmsD3NormalizedStackedBarPlot]) /** /* reference https://bl.ocks.org/mbostock/3886394 */ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { const mmsChartLink = function (scope, element, attrs, mmsViewCtrl) { - const d3 = $window.d3; + const d3 = $window.d3 - const divchart = d3.select(element[0]).append('div'); + const divchart = d3.select(element[0]).append('div') //default const defaultPlotConfig = { width: 960 /*parseInt(divchart.style("width"))*0.95*/, @@ -18,25 +18,25 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { marginRight: 60, marginBottom: 30, marginLeft: 40, - }; - const plotId = 'd3nbplot' + scope.$id; + } + const plotId = 'd3nbplot' + scope.$id - let projectId, refId, commitId; + let projectId, refId, commitId if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin(); - projectId = viewVersion.projectId; - refId = viewVersion.refId; - commitId = viewVersion.commitId; + const viewVersion = mmsViewCtrl.getElementOrigin() + projectId = viewVersion.projectId + refId = viewVersion.refId + commitId = viewVersion.commitId } function vf_pplot() { - divchart.selectAll('*').remove(); - divchart.attr('id', plotId); - const svg = divchart.append('svg:svg'); + divchart.selectAll('*').remove() + divchart.attr('id', plotId) + const svg = divchart.append('svg:svg') - const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig); - svg.attr('width', plotConfig.width); - svg.attr('height', plotConfig.height); + const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig) + svg.attr('width', plotConfig.width) + svg.attr('height', plotConfig.height) const margin = { top: plotConfig.marginTop, right: plotConfig.marginRight, @@ -45,28 +45,28 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { }, width = +svg.attr('width') - margin.left - margin.right, height = +svg.attr('height') - margin.top - margin.bottom, - g = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); + g = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') - const x = d3.scaleBand().rangeRound([0, width]).padding(0.1).align(0.1); + const x = d3.scaleBand().rangeRound([0, width]).padding(0.1).align(0.1) - const y = d3.scaleLinear().rangeRound([height, 0]); + const y = d3.scaleLinear().rangeRound([height, 0]) - const z = d3.scaleOrdinal(d3.schemeCategory10); + const z = d3.scaleOrdinal(d3.schemeCategory10) - const stack = d3.stack().offset(d3.stackOffsetExpand); + const stack = d3.stack().offset(d3.stackOffsetExpand) - let data = scope.tablebody.c3_data; - data = total(data); + let data = scope.tablebody.c3_data + data = total(data) data.sort(function (a, b) { - return b[scope.tablecolumnheader[0]] / b.total - a[scope.tablecolumnheader[0]] / a.total; - }); + return b[scope.tablecolumnheader[0]] / b.total - a[scope.tablecolumnheader[0]] / a.total + }) x.domain( data.map(function (d) { - return d.rowheader; + return d.rowheader }) - ); - z.domain(scope.tablecolumnheader); + ) + z.domain(scope.tablecolumnheader) const serie = g .selectAll('.serie') @@ -75,43 +75,43 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { .append('g') .attr('class', 'serie') .attr('fill', function (d) { - return z(d.key); - }); + return z(d.key) + }) serie .selectAll('rect') .data(function (d) { - return d; + return d }) .enter() .append('rect') .attr('x', function (d) { - return x(d.data.rowheader); + return x(d.data.rowheader) }) .attr('y', function (d) { - return y(d[1]); + return y(d[1]) }) .attr('height', function (d) { - return y(d[0]) - y(d[1]); + return y(d[0]) - y(d[1]) }) - .attr('width', x.bandwidth()); + .attr('width', x.bandwidth()) g.append('g') .attr('class', 'axis axis--x') .attr('transform', 'translate(0,' + height + ')') - .call(d3.axisBottom(x)); + .call(d3.axisBottom(x)) - g.append('g').attr('class', 'axis axis--y').call(d3.axisLeft(y).ticks(10, '%')); + g.append('g').attr('class', 'axis axis--y').call(d3.axisLeft(y).ticks(10, '%')) const legend = serie .append('g') .attr('class', 'legend') .attr('transform', function (d) { - d = d[d.length - 1]; - return 'translate(' + (x(d.data.rowheader) + x.bandwidth()) + ',' + (y(d[0]) + y(d[1])) / 2 + ')'; - }); + d = d[d.length - 1] + return 'translate(' + (x(d.data.rowheader) + x.bandwidth()) + ',' + (y(d[0]) + y(d[1])) / 2 + ')' + }) - legend.append('line').attr('x1', -6).attr('x2', 6).attr('stroke', '#000'); + legend.append('line').attr('x1', -6).attr('x2', 6).attr('stroke', '#000') legend .append('text') @@ -120,42 +120,42 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { .attr('fill', '#000') .style('font', '10px sans-serif') .text(function (d) { - return d.key; - }); + return d.key + }) } //add total in original row array. function total(all) { all.forEach(function (a) { - a.total = 0; + a.total = 0 for (let i = 0; i < scope.tablecolumnheader.length; i++) { - a.total += Number(a[scope.tablecolumnheader[i]]); + a.total += Number(a[scope.tablecolumnheader[i]]) } - }); - return all; + }) + return all } scope.render = function () { PlotService.readValues2(scope.plot, projectId, refId, commitId).then(function (value) { - scope.tablebody = value.tablebody; - scope.tablecolumnheader = value.tableheader; - scope.valuesO = value.tablebody.valuesO; //value objects used in watch + scope.tablebody = value.tablebody + scope.tablecolumnheader = value.tableheader + scope.valuesO = value.tablebody.valuesO //value objects used in watch if (scope.tablebody.c3_data.length === 0) { //no data - return; + return } - vf_pplot(); - }); //end of PlotService - }; //end of render + vf_pplot() + }) //end of PlotService + } //end of render scope.$watch( 'valuesO', function (newVals, oldVals) { - return scope.render(); + return scope.render() }, true - ); - }; //end of link + ) + } //end of link return { restrict: 'EA', @@ -164,5 +164,5 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { plot: '<', }, link: mmsChartLink, - }; //return + } //return } diff --git a/src/ve-extensions/present-plots/presentations/components/mmsD3ParallelAxisPlot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsD3ParallelAxisPlot.directive.ts index f752b3546..718edfa69 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsD3ParallelAxisPlot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsD3ParallelAxisPlot.directive.ts @@ -1,11 +1,11 @@ -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -veComponents.directive('mmsD3ParallelAxisPlot', ['PlotService', '$window', mmsD3ParallelAxisPlot]); +veComponents.directive('mmsD3ParallelAxisPlot', ['PlotService', '$window', mmsD3ParallelAxisPlot]) function mmsD3ParallelAxisPlot(PlotService, $window) { const mmsChartLink = function (scope, element, attrs, mmsViewCtrl) { - scope.rowHeaders = []; //not null when render is called 1st time. - const d3 = $window.d3; - const divchart = d3.select(element[0]).append('div'); + scope.rowHeaders = [] //not null when render is called 1st time. + const d3 = $window.d3 + const divchart = d3.select(element[0]).append('div') const defaultPlotConfig = { width: 900, @@ -13,52 +13,52 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { marginRight: 0, marginBottom: 25, marginLeft: 60, - }; + } - let projectId; - let refId; - let commitId; + let projectId + let refId + let commitId if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin(); - projectId = viewVersion.projectId; - refId = viewVersion.refId; - commitId = viewVersion.commitId; + const viewVersion = mmsViewCtrl.getElementOrigin() + projectId = viewVersion.projectId + refId = viewVersion.refId + commitId = viewVersion.commitId } function vf_pplot(_out) { - const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig); + const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig) - const outputs = _out; - const width = plotConfig.width; - const height = plotConfig.width * 0.37; - const m = [plotConfig.marginTop, plotConfig.marginRight, plotConfig.marginBottom, plotConfig.marginLeft]; //top, right, bottom, left + const outputs = _out + const width = plotConfig.width + const height = plotConfig.width * 0.37 + const m = [plotConfig.marginTop, plotConfig.marginRight, plotConfig.marginBottom, plotConfig.marginLeft] //top, right, bottom, left - let maxSize = 0; - let size = 0; + let maxSize = 0 + let size = 0 //redefine top and right margin based on TB string length - maxSize = 0; - size = 0; + maxSize = 0 + size = 0 for (let i = 0; i < outputs.variables.length; i++) { - size = outputs.variables[i].length; //length of the string - if (maxSize < size) maxSize = size; + size = outputs.variables[i].length //length of the string + if (maxSize < size) maxSize = size } - m[0] = maxSize * 4.5 * 0.707 + 50; //to make label - m[1] = maxSize * 4.5 * 0.707 + 10; + m[0] = maxSize * 4.5 * 0.707 + 50 //to make label + m[1] = maxSize * 4.5 * 0.707 + 10 //define width and height const w = width - m[1] - m[3], - h = height - m[0] - m[2]; + h = height - m[0] - m[2] - const colorscale = d3.scaleOrdinal(d3.schemeCategory10); + const colorscale = d3.scaleOrdinal(d3.schemeCategory10) const x = d3.scalePoint(d3.schemeCategory10).domain(outputs.variables).range([0, w]), - y = {}; + y = {} let line = d3.line(), - foreground; + foreground - divchart.selectAll('*').remove(); + divchart.selectAll('*').remove() const svg = divchart .append('svg:svg') .attr('class', 'papchart' + scope.$id + ' papchart') @@ -66,73 +66,73 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .attr('width', w + m[1] + m[3]) .attr('height', h + m[0] + m[2]) .append('svg:g') - .attr('transform', 'translate(' + m[3] + ',' + m[0] + ')'); + .attr('transform', 'translate(' + m[3] + ',' + m[0] + ')') //Need to create a temporary object with the data, objectives, and threshold values //to scale the axes properly - const minMax = {}; + const minMax = {} outputs.variables.forEach(function (d, i) { - minMax[d] = {}; + minMax[d] = {} //initialize minTest and maxTest variables - let minTest = outputs.table[0].values[d]; - let maxTest = outputs.table[0].values[d]; + let minTest = outputs.table[0].values[d] + let maxTest = outputs.table[0].values[d] for (let j = 0; j < outputs.table.length; j++) { //test to see if minTest is still the minimum - if (minTest > outputs.table[j].values[d]) minTest = outputs.table[j].values[d]; + if (minTest > outputs.table[j].values[d]) minTest = outputs.table[j].values[d] //tests to see if maxTest is still the maximum - if (maxTest < outputs.table[j].values[d]) maxTest = outputs.table[j].values[d]; + if (maxTest < outputs.table[j].values[d]) maxTest = outputs.table[j].values[d] } - minMax[d].min = minTest; - minMax[d].max = maxTest; - }); + minMax[d].min = minTest + minMax[d].max = maxTest + }) - const range = {}; - const minimum = {}; - const maximum = {}; + const range = {} + const minimum = {} + const maximum = {} - const percentScaling = 0.07; + const percentScaling = 0.07 //make each minMax a bit bigger or smaller to better plot the data set outputs.variables.forEach(function (d, i) { - range[d] = Math.abs(minMax[d].max - minMax[d].min); + range[d] = Math.abs(minMax[d].max - minMax[d].min) - minimum[d] = minMax[d].min - range[d] * percentScaling; - maximum[d] = minMax[d].max + range[d] * percentScaling; + minimum[d] = minMax[d].min - range[d] * percentScaling + maximum[d] = minMax[d].max + range[d] * percentScaling //what if both the min and the max were equal? Give it some "range" about the point if (minMax[d].max == minMax[d].min) { - maximum[d] = minMax[d].max * (percentScaling + 1); - minimum[d] = minMax[d].max * (1 - percentScaling); + maximum[d] = minMax[d].max * (percentScaling + 1) + minimum[d] = minMax[d].max * (1 - percentScaling) } //what if the only value for a variable is zero? Give it some "range" about zero if (minMax[d].max === 0 && minMax[d].min === 0) { - maximum[d] = percentScaling; - minimum[d] = -percentScaling; + maximum[d] = percentScaling + minimum[d] = -percentScaling } - }); + }) //Create a scale and brush for each variables. outputs.variables.forEach((d) => { - y[d] = d3.scaleLinear().domain([minimum[d], maximum[d]]).range([h, 0]); - }); + y[d] = d3.scaleLinear().domain([minimum[d], maximum[d]]).range([h, 0]) + }) const tooltip = svg .append('text') .style('opacity', 0) .style('font-family', 'sans-serif') - .style('font-size', '13px'); + .style('font-size', '13px') - const axisData: any[] = []; - const tickData: any[] = []; + const axisData: any[] = [] + const tickData: any[] = [] outputs.table.forEach(function (d) { - if (d.tickColor === undefined) axisData.push(d); - else tickData.push(d); - }); + if (d.tickColor === undefined) axisData.push(d) + else tickData.push(d) + }) // Add foreground lines. background brush foreground = svg .append('svg:g') @@ -148,33 +148,33 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .attr('y', d3.mouse(this)[1]) .text(d.row) .transition(200) - .style('opacity', 1); + .style('opacity', 1) }) .on('mouseout', function () { //remove the text element added on the mouseover event when the mouseout event is triggered - tooltip.transition(200).style('opacity', 0); + tooltip.transition(200).style('opacity', 0) }) .attr('stroke', function (d, i) { - return colorscale(i); + return colorscale(i) }) .attr('fill', 'none') .style('stroke-width', '1px') .attr('cid', function (d, i) { - return d.cid; + return d.cid }) .attr('config', function (d, i) { - return d.design; + return d.design }) //.attr("title", "TEST") .attr('class', (d, i) => { - const string = 'design ' + d.cid + ' selected'; - return string; + const string = 'design ' + d.cid + ' selected' + return string }) //add title to the path. mouseover shows it in bubble looking .append('svg:title') .text(function (d) { - return d.row; - }); + return d.row + }) // Add a group element for each variables. const g = svg @@ -184,15 +184,15 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .append('svg:g') .attr('class', 'variables') .attr('transform', function (d, i) { - return 'translate(' + x(d) + ')'; - }); + return 'translate(' + x(d) + ')' + }) // Add an axis and title. g.append('svg:g') .attr('class', 'axis') .each(function (d) { //d3.select(this).call(axis.scale(y[d])); - d3.select(this).call(d3.axisLeft(y[d]).ticks(5)); + d3.select(this).call(d3.axisLeft(y[d]).ticks(5)) }) .append('svg:text') .data(outputs.variables) @@ -202,16 +202,16 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .attr('class', 'axislabel') .attr('fill', 'black') .text(function (d) { - return d; - }); + return d + }) - let axisTick; + let axisTick tickData.forEach(function (td) { //Adding axisTick g.select('g.axis') .append('g') .attr('transform', (d) => { - return 'translate(0,' + y[d](td.values[d]) + ')'; + return 'translate(0,' + y[d](td.values[d]) + ')' }) .attr('class', 'objectivetick') .append('line') @@ -227,77 +227,77 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .attr('y', d3.mouse(this)[1] + y[d](td.values[d])) .text(td.row) .transition(200) - .style('opacity', 1); + .style('opacity', 1) }) .on('mouseout', function (d) { //remove the text element added on the mouseover event when the mouseout event is triggered - tooltip.transition(200).style('opacity', 0); - }); - }); + tooltip.transition(200).style('opacity', 0) + }) + }) // Returns the path for a given data point. function path(d) { - d = d.values; + d = d.values return line( outputs.variables.map((p) => { - return [x(p), y[p](d[p])]; + return [x(p), y[p](d[p])] }) - ); + ) } } //end of vf_pplot() function getTickColor(rowHeaderName) { if (scope.plot.config.ticks !== undefined) { for (let kk = 0; kk < scope.plot.config.ticks.length; kk++) { - if (scope.plot.config.ticks[kk].name === rowHeaderName) return scope.plot.config.ticks[kk].color; + if (scope.plot.config.ticks[kk].name === rowHeaderName) return scope.plot.config.ticks[kk].color } } - return undefined; + return undefined } scope.render = function () { PlotService.readValues(scope.plot, projectId, refId, commitId).then(function (value) { - scope.tablebody = value.tablebody; - scope.tableheader = value.tableheader; - scope.isHeader = value.isHeader; - scope.valuesO = value.tablebody.valuesO; //value objects used in watch + scope.tablebody = value.tablebody + scope.tableheader = value.tableheader + scope.isHeader = value.isHeader + scope.valuesO = value.tablebody.valuesO //value objects used in watch if (scope.tablebody.c3_data.length === 0) { //no data - return; + return } const dataseries: { - row: any; - tickColor: any; - values: any; - }[] = []; - let tickColor; + row: any + tickColor: any + values: any + }[] = [] + let tickColor scope.tablebody.c3_data.forEach(function (row) { - const values: { [key: string]: any } = {}; + const values: { [key: string]: any } = {} for (let i = 1; i < row.length; i++) { - values[scope.tableheader[i - 1]] = row[i]; - tickColor = getTickColor(row[0]); + values[scope.tableheader[i - 1]] = row[i] + tickColor = getTickColor(row[0]) } dataseries.push({ row: row[0], tickColor: tickColor, values: values, - }); - }); + }) + }) const modelData = { variables: scope.tableheader, table: dataseries, //columnHeader and values - }; - vf_pplot(modelData); - }); //end of PlotService - }; //end of render + } + vf_pplot(modelData) + }) //end of PlotService + } //end of render scope.$watch( 'valuesO', function (newVals, oldVals) { - return scope.render(); + return scope.render() }, true - ); - }; //end of link + ) + } //end of link return { restrict: 'EA', @@ -306,5 +306,5 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { plot: '<', }, link: mmsChartLink, - }; //return + } //return } diff --git a/src/ve-extensions/present-plots/presentations/components/mmsD3RadarPlot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsD3RadarPlot.directive.ts index 468b15fa7..7a861b19c 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsD3RadarPlot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsD3RadarPlot.directive.ts @@ -1,13 +1,13 @@ -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -veComponents.directive('mmsD3RadarPlot', ['PlotService', '$window', mmsD3RadarPlot]); +veComponents.directive('mmsD3RadarPlot', ['PlotService', '$window', mmsD3RadarPlot]) function mmsD3RadarPlot(PlotService, $window) { const mmsRadarChartLink = function (scope, element, attrs, mmsViewCtrl) { - const d3 = $window.d3; - const colorscale = d3.scaleOrdinal(d3.schemeCategory10); + const d3 = $window.d3 + const colorscale = d3.scaleOrdinal(d3.schemeCategory10) - const scopetableColumnHeadersLabel = []; - const divchart = d3.select(element[0]).append('div'); + const scopetableColumnHeadersLabel = [] + const divchart = d3.select(element[0]).append('div') const defaultPlotConfig = { width: 700 /*parseInt(divchart.style("width"))*0.95*/, @@ -16,67 +16,67 @@ function mmsD3RadarPlot(PlotService, $window) { marginRight: 0, marginBottom: 0, marginLeft: 0, - }; + } - let projectId; - let refId; - let commitId; + let projectId + let refId + let commitId if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin(); - projectId = viewVersion.projectId; - refId = viewVersion.refId; - commitId = viewVersion.commitId; + const viewVersion = mmsViewCtrl.getElementOrigin() + projectId = viewVersion.projectId + refId = viewVersion.refId + commitId = viewVersion.commitId } //if ( scope.plot.config.length !== 0){ //scope.plot.config = JSON.parse(scope.plot.config.replace(/'/g, '"')); //{"colors: [5,6,7,8,9]"} //} scope.render = function () { PlotService.readValues(scope.plot, projectId, refId, commitId).then(function (value) { - scope.tablebody = value.tablebody; - scope.tableheader = value.tableheader; - scope.isHeader = value.isHeader; - scope.valuesO = value.tablebody.valuesO; //value objects used in watch + scope.tablebody = value.tablebody + scope.tableheader = value.tableheader + scope.isHeader = value.isHeader + scope.valuesO = value.tablebody.valuesO //value objects used in watch if (scope.tablebody.c3_data.length === 0) { //no data - return; + return } - const rowvalues: { axis: string; value: number }[][] = []; //[][] {{axis: p2, value: 15}, {axis: p3: value: 1}}... + const rowvalues: { axis: string; value: number }[][] = [] //[][] {{axis: p2, value: 15}, {axis: p3: value: 1}}... scope.tablebody.c3_data.forEach(function (row) { - const rowvalue: { axis: string; value: number }[] = []; + const rowvalue: { axis: string; value: number }[] = [] for ( let i = 1; i < row.length; i++ //ignore row header ) - rowvalue.push({ axis: scope.tableheader[i - 1], value: row[i] }); - rowvalues.push(rowvalue); - }); + rowvalue.push({ axis: scope.tableheader[i - 1], value: row[i] }) + rowvalues.push(rowvalue) + }) - divchart.selectAll('*').remove(); - divchart.attr('class', 'radar' + scope.$id).attr('style', 'border:1px solid #ddd'); + divchart.selectAll('*').remove() + divchart.attr('class', 'radar' + scope.$id).attr('style', 'border:1px solid #ddd') - RadarChart.draw('radar' + scope.$id, rowvalues); + RadarChart.draw('radar' + scope.$id, rowvalues) //add legends from tableheader - const legends: any[] = []; + const legends: any[] = [] scope.tablebody.c3_data.forEach(function (item) { - legends.push(item[0]); - }); - initiateLegend(legends, 'radar' + scope.$id); - }); //Plot - }; //end of scope.render + legends.push(item[0]) + }) + initiateLegend(legends, 'radar' + scope.$id) + }) //Plot + } //end of scope.render scope.$watch( 'valuesO', function (newVals, oldVals) { - return scope.render(); + return scope.render() }, true - ); + ) - const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig); + const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig) - let cfg; + let cfg var RadarChart = { draw: function (id, d) { cfg = { @@ -95,33 +95,33 @@ function mmsD3RadarPlot(PlotService, $window) { ExtraWidthX: 100, ExtraWidthY: 0 /*100 original */, color: colorscale, - }; + } cfg.maxValue = Math.max( cfg.maxValue, d3.max(d, function (i) { return d3.max( i.map(function (o) { - return Number(o.value); + return Number(o.value) }) - ); + ) }) - ); + ) const allAxis = d[0].map(function (i, j) { - return i.axis; - }); - const total = allAxis.length; - const radius = cfg.factor * Math.min(cfg.w / 2, cfg.h / 2); + return i.axis + }) + const total = allAxis.length + const radius = cfg.factor * Math.min(cfg.w / 2, cfg.h / 2) - const svg = divchart.append('svg:svg').attr('class', 'rdchart ' + scope.$id); - svg.attr('width', plotConfig.width); - svg.attr('height', plotConfig.height); + const svg = divchart.append('svg:svg').attr('class', 'rdchart ' + scope.$id) + svg.attr('width', plotConfig.width) + svg.attr('height', plotConfig.height) - const g = svg.append('g').attr('transform', 'translate(' + cfg.TranslateX + ',' + cfg.TranslateY + ')'); - let tooltip; + const g = svg.append('g').attr('transform', 'translate(' + cfg.TranslateX + ',' + cfg.TranslateY + ')') + let tooltip //Text indicating at what % each level is for (let j = 0; j < cfg.levels; j++) { - const levelFactor2 = cfg.factor * radius * ((j + 1) / cfg.levels); + const levelFactor2 = cfg.factor * radius * ((j + 1) / cfg.levels) g.selectAll('.levels') .data([1]) //dummy data .enter() @@ -140,97 +140,97 @@ function mmsD3RadarPlot(PlotService, $window) { ')' ) .attr('fill', '#737373') - .text(d3.format('.3g')(((j + 1) * cfg.maxValue) / cfg.levels)); + .text(d3.format('.3g')(((j + 1) * cfg.maxValue) / cfg.levels)) } function getPosition(i, range, factor, func) { - factor = typeof factor !== 'undefined' ? factor : 1; - return range * (1 - factor * func((i * cfg.radians) / total)); + factor = typeof factor !== 'undefined' ? factor : 1 + return range * (1 - factor * func((i * cfg.radians) / total)) } function getHorizontalPosition(i, range, factor?) { - return getPosition(i, range, factor, Math.sin); + return getPosition(i, range, factor, Math.sin) } function getVerticalPosition(i, range, factor?) { - return getPosition(i, range, factor, Math.cos); + return getPosition(i, range, factor, Math.cos) } // //levels && axises const levelFactors = d3.range(0, cfg.levels).map(function (level) { - return radius * ((level + 1) / cfg.levels); - }); - const levelGroups = g.selectAll('.levels').data(levelFactors); - levelGroups.enter().append('g'); - levelGroups.exit().remove(); + return radius * ((level + 1) / cfg.levels) + }) + const levelGroups = g.selectAll('.levels').data(levelFactors) + levelGroups.enter().append('g') + levelGroups.exit().remove() levelGroups.attr('class', function (d, i) { - return 'level-group level-group-' + i; - }); + return 'level-group level-group-' + i + }) const levelLine = levelGroups.selectAll('.level').data(function (levelFactor) { return d3.range(0, total).map(function () { - return levelFactor; - }); - }); - levelLine.enter().append('line'); - levelLine.exit().remove(); + return levelFactor + }) + }) + levelLine.enter().append('line') + levelLine.exit().remove() levelLine .attr('class', 'level') .attr('x1', function (levelFactor, i) { - return getHorizontalPosition(i, levelFactor); + return getHorizontalPosition(i, levelFactor) }) .attr('y1', function (levelFactor, i) { - return getVerticalPosition(i, levelFactor); + return getVerticalPosition(i, levelFactor) }) .attr('x2', function (levelFactor, i) { - return getHorizontalPosition(i + 1, levelFactor); + return getHorizontalPosition(i + 1, levelFactor) }) .attr('y2', function (levelFactor, i) { - return getVerticalPosition(i + 1, levelFactor); + return getVerticalPosition(i + 1, levelFactor) }) .style('stroke', 'grey') .style('stroke-opacity', '0.75') .style('stroke-width', '0.3px') .attr('transform', function (levelFactor) { - return 'translate(' + (cfg.w / 2 - levelFactor) + ', ' + (cfg.h / 2 - levelFactor) + ')'; - }); - let series = 0; - const axis = g.selectAll('.axis').data(allAxis).enter().append('g').attr('class', 'axis'); + return 'translate(' + (cfg.w / 2 - levelFactor) + ', ' + (cfg.h / 2 - levelFactor) + ')' + }) + let series = 0 + const axis = g.selectAll('.axis').data(allAxis).enter().append('g').attr('class', 'axis') axis.append('line') .attr('x1', cfg.w / 2) .attr('y1', cfg.h / 2) .attr('x2', function (d, i) { - return (cfg.w / 2) * (1 - cfg.factor * Math.sin((i * cfg.radians) / total)); + return (cfg.w / 2) * (1 - cfg.factor * Math.sin((i * cfg.radians) / total)) }) .attr('y2', function (d, i) { - return (cfg.h / 2) * (1 - cfg.factor * Math.cos((i * cfg.radians) / total)); + return (cfg.h / 2) * (1 - cfg.factor * Math.cos((i * cfg.radians) / total)) }) .attr('class', 'line') .style('stroke', 'grey') - .style('stroke-width', '1px'); + .style('stroke-width', '1px') axis.append('text') .attr('class', 'legend') .text(function (d) { - return d; + return d }) .style('font-family', 'sans-serif') .style('font-size', '12px') .attr('text-anchor', 'middle') .attr('dy', '1.5em') .attr('transform', function (d, i) { - return 'translate(0, -8)'; + return 'translate(0, -8)' }) .attr('x', function (d, i) { return ( (cfg.w / 2) * (1 - cfg.factorLegend * Math.sin((i * cfg.radians) / total)) - 60 * Math.sin((i * cfg.radians) / total) - ); + ) }) .attr('y', function (d, i) { return ( (cfg.h / 2) * (1 - Math.cos((i * cfg.radians) / total)) - 20 * Math.cos((i * cfg.radians) / total) - ); - }); + ) + }) - let dataValues: number[][] = []; + let dataValues: number[][] = [] d.forEach(function (y, x) { - dataValues = []; + dataValues = [] g.selectAll('.nodes').data(y, function (j, i) { dataValues.push([ (cfg.w / 2) * @@ -243,13 +243,13 @@ function mmsD3RadarPlot(PlotService, $window) { (Math.max(j.value, 0) / cfg.maxValue) * cfg.factor * Math.cos((i * cfg.radians) / total)), - ]); + ]) // dataValues.push([ // cfg.w/2*(1-(parseFloat(Math.max(j.value, 0))/cfg.maxValue)*cfg.factor*Math.sin(i*cfg.radians/total)), // cfg.h/2*(1-(parseFloat(Math.max(j.value, 0))/cfg.maxValue)*cfg.factor*Math.cos(i*cfg.radians/total)) // ]); - }); - dataValues.push(dataValues[0]); + }) + dataValues.push(dataValues[0]) g.selectAll('.area') .data([dataValues]) .enter() @@ -258,25 +258,25 @@ function mmsD3RadarPlot(PlotService, $window) { .style('stroke-width', '2px') .style('stroke', cfg.color(series)) .attr('points', function (d) { - let str = ''; + let str = '' for (let pti = 0; pti < d.length; pti++) { - str = str + d[pti][0] + ',' + d[pti][1] + ' '; + str = str + d[pti][0] + ',' + d[pti][1] + ' ' } - return str; + return str }) .style('fill', function (j, i) { - return cfg.color(series); + return cfg.color(series) }) .style('fill-opacity', 0.1) .on('mouseover', function (d, i) { - d3.select(this).transition(200).style('fill-opacity', 0.7); + d3.select(this).transition(200).style('fill-opacity', 0.7) }) .on('mouseout', function (d, i) { - d3.select(this).transition(200).style('fill-opacity', 0.1); - }); - series++; - }); - series = 0; + d3.select(this).transition(200).style('fill-opacity', 0.1) + }) + series++ + }) + series = 0 d.forEach(function (y, x) { g.selectAll('.nodes') .data(y) @@ -285,7 +285,7 @@ function mmsD3RadarPlot(PlotService, $window) { .attr('class', 'radar-chart-serie' + series + ' ' + id) .attr('r', cfg.radius) .attr('alt', function (j) { - return Math.max(j.value, 0); + return Math.max(j.value, 0) }) .attr('cx', function (j, i) { dataValues.push([ @@ -299,7 +299,7 @@ function mmsD3RadarPlot(PlotService, $window) { (Math.max(j.value, 0) / cfg.maxValue) * cfg.factor * Math.cos((i * cfg.radians) / total)), - ]); + ]) // dataValues.push([ // cfg.w/2*(1-(parseFloat(Math.max(j.value, 0))/cfg.maxValue)*cfg.factor*Math.sin(i*cfg.radians/total)), // cfg.h/2*(1-(parseFloat(Math.max(j.value, 0))/cfg.maxValue)*cfg.factor*Math.cos(i*cfg.radians/total)) @@ -310,7 +310,7 @@ function mmsD3RadarPlot(PlotService, $window) { (Math.max(j.value, 0) / cfg.maxValue) * cfg.factor * Math.sin((i * cfg.radians) / total)) - ); + ) }) .attr('cy', function (j, i) { return ( @@ -319,41 +319,41 @@ function mmsD3RadarPlot(PlotService, $window) { (Math.max(j.value, 0) / cfg.maxValue) * cfg.factor * Math.cos((i * cfg.radians) / total)) - ); + ) }) .attr('data-id', function (j) { - return j.axis; + return j.axis }) .style('fill', cfg.color(series)) .style('fill-opacity', 0.9) .on('mouseover', function (d) { - const newX = parseFloat(d3.select(this).attr('cx')) - 10; - const newY = parseFloat(d3.select(this).attr('cy')) - 5; + const newX = parseFloat(d3.select(this).attr('cx')) - 10 + const newY = parseFloat(d3.select(this).attr('cy')) - 5 tooltip .attr('x', newX) .attr('y', newY) .text(d.value.toString()) .transition(200) - .style('opacity', 1); + .style('opacity', 1) }) .on('mouseout', function () { - tooltip.transition(200).style('opacity', 0); + tooltip.transition(200).style('opacity', 0) }) .append('svg:title') .text(function (j) { - return Math.max(j.value, 0); - }); - series++; - }); + return Math.max(j.value, 0) + }) + series++ + }) //Tooltip tooltip = g .append('text') .style('opacity', 0) .style('font-family', 'sans-serif') - .style('font-size', '13px'); + .style('font-size', '13px') }, - }; //end of RadarChart + } //end of RadarChart function initiateLegend(LegendOptions, id) { const svg = d3 @@ -361,14 +361,14 @@ function mmsD3RadarPlot(PlotService, $window) { .selectAll('svg') .append('svg') .attr('width', cfg.w + 300) - .attr('height', cfg.h); + .attr('height', cfg.h) //Initiate Legend const legend = svg .append('g') .attr('class', 'legend') .attr('height', 100) .attr('width', 200) - .attr('transform', 'translate(50,50)'); + .attr('transform', 'translate(50,50)') //Create colour squares legend @@ -378,34 +378,34 @@ function mmsD3RadarPlot(PlotService, $window) { .append('rect') .attr('x', cfg.w - 65) .attr('y', function (d, i) { - return i * 20; + return i * 20 }) .attr('width', 10) .attr('height', 10) .style('fill', function (d, i) { - return colorscale(i); + return colorscale(i) }) .attr('fill-opacity', 1) .attr('rid', function (d) { - return d; + return d }) .on('mouseover', function (d, i) { d3.select('.' + id) .selectAll('svg') .selectAll('polygon') .transition(200) - .style('fill-opacity', 0.1); + .style('fill-opacity', 0.1) d3.select('.radar-chart-serie' + i + '.' + id) .transition(200) - .style('fill-opacity', 0.7); + .style('fill-opacity', 0.7) }) .on('mouseout', function (d, i) { d3.select('.' + id) .selectAll('svg') .selectAll('polygon') .transition(200) - .style('fill-opacity', cfg.opacityArea); - }); + .style('fill-opacity', cfg.opacityArea) + }) //Create text next to squares legend .selectAll('text') @@ -414,32 +414,32 @@ function mmsD3RadarPlot(PlotService, $window) { .append('text') .attr('x', cfg.w - 52) .attr('y', function (d, i) { - return i * 20 + 9; + return i * 20 + 9 }) .attr('font-size', '11px') .attr('fill', '#737373') .text(function (d) { - return d; + return d }) .on('mouseover', function (d, i) { d3.select('.' + id) .selectAll('svg') .selectAll('polygon') .transition(200) - .style('fill-opacity', 0.1); + .style('fill-opacity', 0.1) d3.select('.radar-chart-serie' + i + '.' + id) .transition(200) - .style('fill-opacity', 0.7); + .style('fill-opacity', 0.7) }) .on('mouseout', function (d, i) { d3.select('.' + id) .selectAll('svg') .selectAll('polygon') .transition(200) - .style('fill-opacity', 0.1); - }); + .style('fill-opacity', 0.1) + }) } //end of initiateLegend - }; //end of link + } //end of link return { restrict: 'EA', @@ -448,5 +448,5 @@ function mmsD3RadarPlot(PlotService, $window) { plot: '<', }, link: mmsRadarChartLink, - }; //return + } //return } diff --git a/src/ve-extensions/present-plots/presentations/present-plot.component.ts b/src/ve-extensions/present-plots/presentations/present-plot.component.ts index e68708849..21c60d339 100644 --- a/src/ve-extensions/present-plots/presentations/present-plot.component.ts +++ b/src/ve-extensions/present-plots/presentations/present-plot.component.ts @@ -1,22 +1,22 @@ -import angular from 'angular'; +import angular from 'angular' -import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations'; -import { ComponentService, ExtensionService } from '@ve-components/services'; -import { ButtonBarService } from '@ve-core/button-bar'; -import { ImageService } from '@ve-utils/application'; -import { EventService } from '@ve-utils/core'; -import { SchemaService } from '@ve-utils/model-schema'; +import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations' +import { ComponentService, ExtensionService } from '@ve-components/services' +import { ButtonBarService } from '@ve-core/button-bar' +import { ImageService } from '@ve-utils/application' +import { EventService } from '@ve-utils/core' +import { SchemaService } from '@ve-utils/model-schema' -import { veComponents } from '@ve-components'; +import { veComponents } from '@ve-components' -import { VePromise, VeQService } from '@ve-types/angular'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation'; -import { PresentContentObject } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { PresentContentObject } from '@ve-types/mms' export interface PresentPlotObject extends PresentContentObject { - ptype?: string; - config?: string; - [key: string]: unknown; + ptype?: string + config?: string + [key: string]: unknown } const ViewPlotComponent: IPresentationComponentOptions = { @@ -28,10 +28,10 @@ const ViewPlotComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: class ViewPlotController extends Presentation { - public plot: PresentPlotObject; - public plotConfig: PresentPlotObject; + public plot: PresentPlotObject + public plotConfig: PresentPlotObject - static $inject = Presentation.$inject; + static $inject = Presentation.$inject constructor( $q: VeQService, $element: JQuery, @@ -61,31 +61,31 @@ const ViewPlotComponent: IPresentationComponentOptions = { imageSvc, buttonBarSvc, extensionSvc - ); + ) } config = (): void => { - this.plot = this.peObject as PresentPlotObject; - }; + this.plot = this.peObject as PresentPlotObject + } getContent = (): VePromise => { if (this.plot.type === 'Plot') { if (this.plot.config !== undefined && this.plot.config.trim().length !== 0) { try { - this.plotConfig = JSON.parse(this.plot.config.replace(/'/g, '"')) as PresentPlotObject; + this.plotConfig = JSON.parse(this.plot.config.replace(/'/g, '"')) as PresentPlotObject if (this.plotConfig.ptype !== undefined) { - this.plot.ptype = this.plotConfig.ptype; + this.plot.ptype = this.plotConfig.ptype } } catch (err) { - console.log('error ignored'); + console.log('error ignored') } } return this.$q.resolve( `
    {{$ctrl.plot.title}}
    ` - ); + ) } - }; + } }, -}; +} -veComponents.component(ViewPlotComponent.selector, ViewPlotComponent); +veComponents.component(ViewPlotComponent.selector, ViewPlotComponent) diff --git a/src/ve-extensions/ts-diagram/mmsTsDiagram.directive.ts b/src/ve-extensions/ts-diagram/mmsTsDiagram.directive.ts index 1541d1711..9571d7561 100644 --- a/src/ve-extensions/ts-diagram/mmsTsDiagram.directive.ts +++ b/src/ve-extensions/ts-diagram/mmsTsDiagram.directive.ts @@ -1,6 +1,6 @@ -import angular from 'angular'; +import angular from 'angular' -const veDirectives = angular.module('veDirectives'); +const veDirectives = angular.module('veDirectives') veDirectives.directive('mmsTsDiagram', [ 'ElementService', @@ -12,7 +12,7 @@ veDirectives.directive('mmsTsDiagram', [ 'AuthService', 'URLService', mmsTsDiagram, -]); +]) /** * @ngdoc directive @@ -39,13 +39,13 @@ function mmsTsDiagram( AuthService, URLService ) { - let importedTsJs = false; - const template = 'partials/mms-directives/mmsTsDiagram.html'; - const mapping = {}; + let importedTsJs = false + const template = 'partials/mms-directives/mmsTsDiagram.html' + const mapping = {} // var deferreds = {}; - const projectId2PeId = {}; - const peId2projectId = {}; - const projectIdLoaded = {}; + const projectId2PeId = {} + const peId2projectId = {} + const projectIdLoaded = {} const viewNameMapping = { IBD: 'Internal Block Diagram', BDD: 'Block Definition Diagram', @@ -56,7 +56,7 @@ function mmsTsDiagram( PAR: 'Parametric Diagram', REQ: 'Requirement Diagram', UC: 'Use Case Diagram', - }; + } const controlMapping = { IBD: 'IBD Controls', BDD: 'BDD Controls', @@ -67,7 +67,7 @@ function mmsTsDiagram( PAR: 'PAR Controls', REQ: 'REQ Controls', UC: 'UC Controls', - }; + } const elementTableMapping = { IBD: 'IBD Elements', BDD: 'BDD Elements', @@ -78,7 +78,7 @@ function mmsTsDiagram( PAR: 'PAR Elements', REQ: 'REQ Elements', UC: 'UC Elements', - }; + } const relTableMapping = { IBD: 'IBD Relationships', BDD: 'BDD Relationships', @@ -89,54 +89,54 @@ function mmsTsDiagram( PAR: 'PAR Relationships', REQ: 'REQ Relationships', UC: 'UC Relationships', - }; + } $window.onPerspectivesCommandSuccess = (successfulCommand) => { - console.log('Perspectives command: ' + successfulCommand.command + ' completed successfully'); - $window.hidePerspectivesProgressIndicator(); - }; + console.log('Perspectives command: ' + successfulCommand.command + ' completed successfully') + $window.hidePerspectivesProgressIndicator() + } $window.onPerspectivesCommandFailure = function (failedCommand, message, callstack) { - console.log('Perspectives command ' + failedCommand.commmand + ' failed. Reason is: ' + message); - $window.hidePerspectivesProgressIndicator(); - console.log(callstack); - }; + console.log('Perspectives command ' + failedCommand.commmand + ' failed. Reason is: ' + message) + $window.hidePerspectivesProgressIndicator() + console.log(callstack) + } $window.onPerspectivesProjectLoad = (projectID) => { - console.log('All project UI elements should now be on the DOM for ' + projectID); - }; + console.log('All project UI elements should now be on the DOM for ' + projectID) + } $window.onPerspectivesProjectReady = (projectID) => { console.log( 'All project RPC calls are complete and you can now access all project resources via the DOM. ' + projectID - ); + ) if (!projectIdLoaded[projectID]) { - $window.showPerspectivesProgressIndicator(); - $window.invokePerspectivesCommand(mapping[projectID]); - projectIdLoaded[projectID] = true; + $window.showPerspectivesProgressIndicator() + $window.invokePerspectivesCommand(mapping[projectID]) + projectIdLoaded[projectID] = true } - }; + } $window.onPerspectivesViewLoaded = function (projectID, moduleName, modelID, viewID, viewName) { - console.log('The Perspectives view ' + viewID + ' is now on the DOM.'); - }; + console.log('The Perspectives view ' + viewID + ' is now on the DOM.') + } $window.onPerspectivesViewUpdated = function (projectID, moduleName, modelID, viewID, viewNamem, peObject) { - console.log('The Perspectives view' + viewID + ' was udpdated with data ' + peObject); - }; + console.log('The Perspectives view' + viewID + ' was udpdated with data ' + peObject) + } $window.onPerspectivesViewCanvasRendered = function (projectID, moduleName, modelID, viewID, viewName) { - console.log('The Perspectives canvas for view' + viewID + ' was rendered'); - }; + console.log('The Perspectives canvas for view' + viewID + ' was rendered') + } $window.onPerspectivesMouseClickOnObject = (data) => { if (data) { - console.log('JavaScript Callback = Mouse clicked on object with ID = ' + data.objectID); + console.log('JavaScript Callback = Mouse clicked on object with ID = ' + data.objectID) } - }; + } $window.onPerspectivesMouseDoubleClickOnObject = (data) => { if (data) { - console.log('JavaScript Callback = Mouse double clicked on object with ID = ' + data.objectID); + console.log('JavaScript Callback = Mouse double clicked on object with ID = ' + data.objectID) } - }; + } $window.PerspectivesErrorDialogHandler = function (message, callStackString) { //prevent ts error dialog from appearing for any js exception - console.log(message); - console.log(callStackString); - }; + console.log(message) + console.log(callStackString) + } //store global mapping of project name to hash, on*** functions can lookup the hash const mmsTsDiagramLink = (scope, element, attrs) => { if (!$window.invokePerspectivesCommand && !importedTsJs) { @@ -145,25 +145,25 @@ function mmsTsDiagram( '\n' + '\n' + '' - ); + ) - importedTsJs = true; + importedTsJs = true } - let id = ApplicationService.createUniqueId(); + let id = ApplicationService.createUniqueId() if (peId2projectId[scope.mmsPeId]) { - id = peId2projectId[scope.mmsPeId]; + id = peId2projectId[scope.mmsPeId] } else { - peId2projectId[scope.mmsPeId] = id; + peId2projectId[scope.mmsPeId] = id } - projectId2PeId[id] = scope.mmsPeId; + projectId2PeId[id] = scope.mmsPeId - scope.containerId = 'tabContainer-' + id; - scope.viewId = 'view-' + id; - scope.tableId = 'table-' + id; - scope.edgeTableId = 'edgeTable-' + id; - scope.inspectorId = 'inspector-' + id; - scope.controlsId = 'controls-' + id; - scope.initElements = []; + scope.containerId = 'tabContainer-' + id + scope.viewId = 'view-' + id + scope.tableId = 'table-' + id + scope.edgeTableId = 'edgeTable-' + id + scope.inspectorId = 'inspector-' + id + scope.controlsId = 'controls-' + id + scope.initElements = [] const params = { viewName: viewNameMapping[scope.mmsTspSpec.diagramType], @@ -172,26 +172,26 @@ function mmsTsDiagram( edgeTableName: relTableMapping[scope.mmsTspSpec.diagramType], inspectorName: 'Details', controlsName: controlMapping[scope.mmsTspSpec.diagramType], - }; + } - if (scope.mmsTspSpec && scope.mmsTspSpec.elements) scope.initElements = scope.mmsTspSpec.elements; - if (scope.mmsTspSpec && scope.mmsTspSpec.context) scope.context = scope.mmsTspSpec.context; + if (scope.mmsTspSpec && scope.mmsTspSpec.elements) scope.initElements = scope.mmsTspSpec.elements + if (scope.mmsTspSpec && scope.mmsTspSpec.context) scope.context = scope.mmsTspSpec.context - const webProjectCommand = _createWebProjectCommand(scope, params, id); - mapping[id] = _createUpdateCommand(scope, params.viewName, id); + const webProjectCommand = _createWebProjectCommand(scope, params, id) + mapping[id] = _createUpdateCommand(scope, params.viewName, id) function tryInvokeCommand() { if (!$window.invokePerspectivesCommand) { - $timeout(tryInvokeCommand, 1000, false); + $timeout(tryInvokeCommand, 1000, false) } else { - $window.invokePerspectivesCommand(webProjectCommand); + $window.invokePerspectivesCommand(webProjectCommand) } } - tryInvokeCommand(); - }; + tryInvokeCommand() + } function _getElementsArrayString(elements) { - return '[{"id": "' + elements.join('"}, {"id": "') + '"}]'; + return '[{"id": "' + elements.join('"}, {"id": "') + '"}]' } function _createWebProjectCommand(scope, params, id) { @@ -325,20 +325,20 @@ function mmsTsDiagram( }, }, ], - }; - return webProjectCommand; + } + return webProjectCommand } function _createUpdateCommand(scope, viewName, id) { const updateCommand: { - data: object[]; - command: string; - onsuccess: string; + data: object[] + command: string + onsuccess: string } = { command: 'Group', onsuccess: 'onPerspectivesCommandSuccess', data: [] as object[], - }; + } updateCommand.data.push( { command: 'Custom', @@ -391,9 +391,9 @@ function mmsTsDiagram( }, onfailure: 'onPerspectivesCommandFailure', } - ); + ) if (scope.context || scope.initElements.length > 0) { - const initialIntegratorIds: string[] = []; + const initialIntegratorIds: string[] = [] if (scope.initElements.length > 0) { updateCommand.data.push({ command: 'SetModelAttribute', @@ -407,10 +407,10 @@ function mmsTsDiagram( viewName: viewName, }, onfailure: 'onPerspectivesCommandFailure', - }); - initialIntegratorIds.push('int-add-' + id); + }) + initialIntegratorIds.push('int-add-' + id) } - initialIntegratorIds.push('int-fcd-' + id); + initialIntegratorIds.push('int-fcd-' + id) updateCommand.data.push({ command: 'Update', onsuccess: 'onPerspectivesCommandSuccess', @@ -420,7 +420,7 @@ function mmsTsDiagram( module: 'SysML', integratorIDs: initialIntegratorIds, }, - }); + }) if (scope.context) { updateCommand.data.push({ command: 'Custom', @@ -434,10 +434,10 @@ function mmsTsDiagram( args: ['' + scope.context], }, onfailure: 'onPerspectivesCommandFailure', - }); + }) } } - return updateCommand; + return updateCommand } return { @@ -450,5 +450,5 @@ function mmsTsDiagram( mmsPeId: '@', }, link: mmsTsDiagramLink, - }; + } } diff --git a/src/ve-types/angular.d.ts b/src/ve-types/angular.d.ts index 3a4041f57..7d7b67978 100644 --- a/src/ve-types/angular.d.ts +++ b/src/ve-types/angular.d.ts @@ -7,22 +7,19 @@ import angular, { IQResolveReject, IQService, IRequestConfig, -} from 'angular'; +} from 'angular' -import { ElementObject, ElementsResponse } from '@ve-types/mms'; +import { ElementObject, ElementsResponse } from '@ve-types/mms' export interface VeComponentOptions extends IComponentOptions { - selector: string; + selector: string } export interface VeQService extends IQService { new >( resolver: (resolve: IQResolveReject, reject: IQResolveReject>) => any - ): VePromise; - (resolver: (resolve: IQResolveReject, reject: IQResolveReject>) => any): VePromise< - T, - U - >; + ): VePromise + (resolver: (resolve: IQResolveReject, reject: IQResolveReject>) => any): VePromise } export interface VePromise> extends IPromise { @@ -30,40 +27,40 @@ export interface VePromise> extends IPromise { successCallback?: ((value: T) => PromiseLike | PromiseLike | TResult1) | null, errorCallback?: ((reason: VePromiseReason) => PromiseLike | PromiseLike | TResult2) | null, notifyCallback?: (state: unknown) => unknown - ): VePromise; + ): VePromise then( successCallback?: ((value: T) => PromiseLike | PromiseLike | TResult1) | null, errorCallback?: ((reason: VePromiseReason) => PromiseLike | PromiseLike | TResult2) | null, notifyCallback?: (state: unknown) => unknown - ): VePromise; + ): VePromise catch( onRejected?: ((reason: VePromiseReason) => PromiseLike | PromiseLike | TResult) | null - ): VePromise; + ): VePromise catch( onRejected?: ((reason: VePromiseReason) => VePromise | IPromise | TResult) | null - ): VePromise; + ): VePromise } export interface VePromisesResponse> { - failedRequests?: VePromiseReason[]; - successfulRequests?: T[]; + failedRequests?: VePromiseReason[] + successfulRequests?: T[] } export interface VeNgModelController extends INgModelController { - $modelValue: T; + $modelValue: T } export interface VePromiseReason { - type?: 'error' | 'info' | 'warning'; - state?: angular.PromiseState; - message?: string; - recentVersionOfElement?: ElementObject; - data?: T; - status: number; - headers?: IHttpHeadersGetter; - config?: IRequestConfig; - statusText?: string; + type?: 'error' | 'info' | 'warning' + state?: angular.PromiseState + message?: string + recentVersionOfElement?: ElementObject + data?: T + status: number + headers?: IHttpHeadersGetter + config?: IRequestConfig + statusText?: string /** Added in AngularJS 1.6.6 */ - xhrStatus?: 'complete' | 'error' | 'timeout' | 'abort'; + xhrStatus?: 'complete' | 'error' | 'timeout' | 'abort' } diff --git a/src/ve-types/components/index.d.ts b/src/ve-types/components/index.d.ts index 36c2b43c0..cf04e6324 100644 --- a/src/ve-types/components/index.d.ts +++ b/src/ve-types/components/index.d.ts @@ -1,32 +1,32 @@ -import angular from 'angular'; +import angular from 'angular' -import { SpecApi } from '@ve-components/spec-tools'; -import { ButtonBarApi } from '@ve-core/button-bar'; +import { SpecApi } from '@ve-components/spec-tools' +import { ButtonBarApi } from '@ve-core/button-bar' -import { VePromise } from '@ve-types/angular'; -import { ElementObject, InstanceValueObject, ValueObject, ViewObject } from '@ve-types/mms'; +import { VePromise } from '@ve-types/angular' +import { ElementObject, InstanceValueObject, ValueObject, ViewObject } from '@ve-types/mms' export interface ComponentController { - element: T; - commitId: string; - edit: T; - view?: ViewObject; - instanceSpec?: ElementObject; - instanceVal?: InstanceValueObject; - elementSaving: boolean; - editLoading?: boolean; - bbApi?: ButtonBarApi; - editorOptions?: { callback?(e?: JQuery.ClickEvent): VePromise }; - specApi?: SpecApi; + element: T + commitId: string + edit: T + view?: ViewObject + instanceSpec?: ElementObject + instanceVal?: InstanceValueObject + elementSaving: boolean + editLoading?: boolean + bbApi?: ButtonBarApi + editorOptions?: { callback?(e?: JQuery.ClickEvent): VePromise } + specApi?: SpecApi // isEnumeration: boolean, - skipBroadcast: boolean; - isEditing: boolean; - inPreviewMode: boolean; - values?: ValueObject[]; - editValues?: ValueObject[]; - $scope: angular.IScope; + skipBroadcast: boolean + isEditing: boolean + inPreviewMode: boolean + values?: ValueObject[] + editValues?: ValueObject[] + $scope: angular.IScope } -export { InsertApi } from '@ve-types/components/insertions'; -export { InsertData } from '@ve-types/components/insertions'; -export { InsertResolve } from '@ve-types/components/insertions'; -export { InsertResolveFn } from '@ve-types/components/insertions'; +export { InsertApi } from '@ve-types/components/insertions' +export { InsertData } from '@ve-types/components/insertions' +export { InsertResolve } from '@ve-types/components/insertions' +export { InsertResolveFn } from '@ve-types/components/insertions' diff --git a/src/ve-types/components/insertions.d.ts b/src/ve-types/components/insertions.d.ts index 10a27359e..3ab92ed7a 100644 --- a/src/ve-types/components/insertions.d.ts +++ b/src/ve-types/components/insertions.d.ts @@ -1,34 +1,34 @@ -import { ElementObject } from '@ve-types/mms'; -import { VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; +import { ElementObject } from '@ve-types/mms' +import { VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' export interface InsertResolveFn extends VeModalResolveFn { - getInsertData(): T; + getInsertData(): T - getProjectId(): string; + getProjectId(): string - getRefId(): string; + getRefId(): string - getOrgId(): string; + getOrgId(): string } export interface InsertResolve extends VeModalResolve { - getInsertData: T; - getProjectId: string; - getRefId: string; - getOrgId: string; + getInsertData: T + getProjectId: string + getRefId: string + getOrgId: string } export interface InsertData { - type: string; - insertType: string; - noPublish?: boolean; - isNew?: boolean; - parentTitle?: string; - selected?: ElementObject; + type: string + insertType: string + noPublish?: boolean + isNew?: boolean + parentTitle?: string + selected?: ElementObject } export interface InsertApi { - resolve(data: T): void; + resolve(data: T): void - reject(reason: U): void; + reject(reason: U): void } diff --git a/src/ve-types/components/presentation.d.ts b/src/ve-types/components/presentation.d.ts index 83727ef4c..7892049c5 100644 --- a/src/ve-types/components/presentation.d.ts +++ b/src/ve-types/components/presentation.d.ts @@ -1,28 +1,28 @@ -import { VeComponentOptions } from '@ve-types/angular'; +import { VeComponentOptions } from '@ve-types/angular' export interface IPresentationComponentOptions extends VeComponentOptions { - selector: string; - style?: string[]; + selector: string + style?: string[] bindings: { - peObject: string; - instanceSpec: string; - peNumber: string; - mmsProjectId?: '@'; - mmsRefId?: '@'; - mmsCommitId?: '@'; - [key: string]: string; - }; + peObject: string + instanceSpec: string + peNumber: string + mmsProjectId?: '@' + mmsRefId?: '@' + mmsCommitId?: '@' + [key: string]: string + } required?: { - mmsViewPresentationElemCtrl: string; - mmsViewCtrl: string; - [key: string]: string; - }; + mmsViewPresentationElemCtrl: string + mmsViewCtrl: string + [key: string]: string + } } export interface ITableConfig { - sortByColumnFn(sortCol?: number): void; + sortByColumnFn(sortCol?: number): void - showBindingForSortIcon: number; - filterDebounceRate: number; - filterTermColumnPrefixBinding: string; + showBindingForSortIcon: number + filterDebounceRate: number + filterTermColumnPrefixBinding: string } diff --git a/src/ve-types/config.d.ts b/src/ve-types/config.d.ts index d9baacb4a..91d23f4b7 100644 --- a/src/ve-types/config.d.ts +++ b/src/ve-types/config.d.ts @@ -1,18 +1,18 @@ -import { VeExperimentConfig, VeExperimentDescriptor } from '@ve-components/services'; -import { BrandingStyle } from '@ve-utils/application'; +import { VeExperimentConfig, VeExperimentDescriptor } from '@ve-components/services' +import { BrandingStyle } from '@ve-utils/application' export interface VeConfig { - version?: string; - apiUrl: string; - printUrl: string; - basePath: string; - enableDebug?: boolean; - customLabels?: { [key: string]: string }; - loginBanner?: BrandingStyle; - loginWarning?: BrandingStyle; - banner?: BrandingStyle; - footer?: BrandingStyle; - loginTimeout?: number; - experimental?: VeExperimentDescriptor[]; - expConfig?: VeExperimentConfig; + version?: string + apiUrl: string + printUrl: string + basePath: string + enableDebug?: boolean + customLabels?: { [key: string]: string } + loginBanner?: BrandingStyle + loginWarning?: BrandingStyle + banner?: BrandingStyle + footer?: BrandingStyle + loginTimeout?: number + experimental?: VeExperimentDescriptor[] + expConfig?: VeExperimentConfig } diff --git a/src/ve-types/core/editor.d.ts b/src/ve-types/core/editor.d.ts index 078887b38..6e3337ca0 100644 --- a/src/ve-types/core/editor.d.ts +++ b/src/ve-types/core/editor.d.ts @@ -1,13 +1,13 @@ export interface EditorActions { - cancel(e?): void; + cancel(e?): void - reset(e?): void; + reset(e?): void - delete(e?): void; + delete(e?): void - preview(e?): void; + preview(e?): void - save(e?): void; + save(e?): void - saveC(e?): void; + saveC(e?): void } diff --git a/src/ve-types/mms/index.d.ts b/src/ve-types/mms/index.d.ts index a344f7aa4..56830c838 100644 --- a/src/ve-types/mms/index.d.ts +++ b/src/ve-types/mms/index.d.ts @@ -1,36 +1,36 @@ -import { ArtifactObject } from '@ve-types/mms/mms'; -import { ValueObject } from '@ve-types/mms/valuesAndInstances'; +import { ArtifactObject } from '@ve-types/mms/mms' +import { ValueObject } from '@ve-types/mms/valuesAndInstances' -export * from './valuesAndInstances.d'; -export * from './views.d'; -export * from './orgsAndProjects.d'; -export * from './mms.d'; +export * from './valuesAndInstances.d' +export * from './views.d' +export * from './orgsAndProjects.d' +export * from './mms.d' // eslint-disable-next-line @typescript-eslint/no-explicit-any -export type MmsObject = Record; +export type MmsObject = Record export interface TransclusionObject extends MmsObject { - element?: ElementObject; - tag: string; + element?: ElementObject + tag: string } export interface ElementObject extends MmsObject { - id: string; - _projectId: string; - _refId: string; - _commitId?: string; - _modified?: string; - _modifier?: string; - _creator?: string; - _created?: string; - _inRefIds?: string[]; - _artifacts?: ArtifactObject[]; - appliedStereotypeIds?: string[]; - _appliedStereotypeIds?: string[]; // mdk < 6 - type?: string; - typeId?: string; - defaultValue?: ValueObject; - documentation?: string; - name?: string; - ownerId?: string; + id: string + _projectId: string + _refId: string + _commitId?: string + _modified?: string + _modifier?: string + _creator?: string + _created?: string + _inRefIds?: string[] + _artifacts?: ArtifactObject[] + appliedStereotypeIds?: string[] + _appliedStereotypeIds?: string[] // mdk < 6 + type?: string + typeId?: string + defaultValue?: ValueObject + documentation?: string + name?: string + ownerId?: string } diff --git a/src/ve-types/mms/mms.d.ts b/src/ve-types/mms/mms.d.ts index 2b8afd391..5342da01d 100644 --- a/src/ve-types/mms/mms.d.ts +++ b/src/ve-types/mms/mms.d.ts @@ -7,205 +7,205 @@ import { ProjectObject, RefObject, UserObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' export interface UserObject extends MmsObject { - username: string; - id?: string; - created?: Date; - modified?: Date; - email?: string; - firstName?: string; - lastName?: string; - admin?: boolean; - enabled?: boolean; - fullName?: string; + username: string + id?: string + created?: Date + modified?: Date + email?: string + firstName?: string + lastName?: string + admin?: boolean + enabled?: boolean + fullName?: string } export interface CommitObject extends MmsObject { - deleted?: CommitChangeElement[]; - _creator?: string; - added?: CommitChangeElement[]; - _docId?: string; - _created?: string; - comment?: null; - source?: null; - id: string; - updated?: CommitChangeElement[]; - _refId: string; - _projectId: string; + deleted?: CommitChangeElement[] + _creator?: string + added?: CommitChangeElement[] + _docId?: string + _created?: string + comment?: null + source?: null + id: string + updated?: CommitChangeElement[] + _refId: string + _projectId: string } export interface CommitChangeElement extends MmsObject { - _previousDocId: string; - _docId: string; - id: string; - type: string; + _previousDocId: string + _docId: string + id: string + type: string } export interface RequestObject extends MmsObject { - projectId: string; - refId: string; - orgId?: string; - commitId?: string; - depth?: number; + projectId: string + refId: string + orgId?: string + commitId?: string + depth?: number } export interface ShortUrlRequest extends RequestObject { - orgId: string; - viewId?: string; - documentId: string; + orgId: string + viewId?: string + documentId: string } export interface ElementsRequest extends RequestObject { - elementId: T; + elementId: T } export interface UsersRequest extends RequestObject { - username: string; + username: string } export interface CreationRequest { - elements: T[]; + elements: T[] } export interface ElementCreationRequest extends RequestObject { - elements: T[]; + elements: T[] } export interface ViewsRequest extends RequestObject { - returnChildViews?: boolean; - parentViewId?: string; - aggr?: string; + returnChildViews?: boolean + parentViewId?: string + aggr?: string } export interface ViewCreationRequest extends ViewsRequest { - viewId: string; - viewDoc?: string; - viewName?: string; + viewId: string + viewDoc?: string + viewName?: string } export interface ArtifactsRequest extends ElementsRequest { - artifactExtension: string; + artifactExtension: string } export interface AuthRequest { - username: string; - password: string; + username: string + password: string } export interface ArtifactObject { - extension: string; - checksum: string; - locationType: string; - location: string; - mimetype: string; + extension: string + checksum: string + locationType: string + location: string + mimetype: string } export interface ParamsObject { - projectId?: string; - refId?: string; - viewId?: string; - documentId?: string; - shortUrl?: string; - keywords?: string; - field?: string; - fromLogin?: boolean; - '#'?: string; - display?: string; - preview?: string; - next?: string; - [param: string]: string; + projectId?: string + refId?: string + viewId?: string + documentId?: string + shortUrl?: string + keywords?: string + field?: string + fromLogin?: boolean + '#'?: string + display?: string + preview?: string + next?: string + [param: string]: string } export interface QueryObject extends MmsObject { params?: { - [key: string]: string | object; - }; + [key: string]: string | object + } recurse?: { - [key: string]: string | object; - }; - from?: number; - size?: number; + [key: string]: string | object + } + from?: number + size?: number } export interface QueryParams extends MmsObject { - showDeleted?: boolean; - [key: string]: string | boolean | number; + showDeleted?: boolean + [key: string]: string | boolean | number } export interface AuthResponse { - token: string; + token: string } export interface VersionResponse { - mmsVersion: string; + mmsVersion: string } export interface CheckAuthResponse { - username: string; + username: string } interface BasicResponse { - messages: string[]; - rejected: RejectedObject[]; + messages: string[] + rejected: RejectedObject[] } interface GenericResponse extends BasicResponse { - [p: string]: T[]; + [p: string]: T[] } interface RejectedObject { - code: number; - message: string; - object: T; + code: number + message: string + object: T } export interface ElementsResponse extends BasicResponse { - elements: T[]; - deleted?: T[]; + elements: T[] + deleted?: T[] } export interface PermissionsResponse extends BasicResponse { - lookups: PermissionsObject[]; - allPassed: boolean; + lookups: PermissionsObject[] + allPassed: boolean } export interface PermissionsObject { - type: string; - orgId?: string; - projectId?: string; - refId?: string; - groupName?: string; - privilege: string; - allowAnonIfPublic: boolean; - hasPrivilege: boolean; + type: string + orgId?: string + projectId?: string + refId?: string + groupName?: string + privilege: string + allowAnonIfPublic: boolean + hasPrivilege: boolean } export interface SearchResponse extends ElementsResponse { - total: number; - rejectedTotal: number; + total: number + rejectedTotal: number } export interface OrgsResponse extends BasicResponse { - orgs: OrgObject[]; + orgs: OrgObject[] } export interface ProjectsResponse extends BasicResponse { - projects: ProjectObject[]; + projects: ProjectObject[] } export interface RefsResponse extends BasicResponse { - refs: RefObject[]; + refs: RefObject[] } export interface CommitResponse extends BasicResponse { - commits: CommitObject[]; + commits: CommitObject[] } export interface GroupsResponse extends BasicResponse { - groups: GroupObject[]; + groups: GroupObject[] } export interface UsersResponse extends BasicResponse { - users: UserObject[]; + users: UserObject[] } diff --git a/src/ve-types/mms/orgsAndProjects.d.ts b/src/ve-types/mms/orgsAndProjects.d.ts index 64a7dd2d6..4ff33b739 100644 --- a/src/ve-types/mms/orgsAndProjects.d.ts +++ b/src/ve-types/mms/orgsAndProjects.d.ts @@ -1,42 +1,42 @@ -import { MmsObject } from '@ve-types/mms'; +import { MmsObject } from '@ve-types/mms' export interface OrgObject extends MmsObject { - public: boolean; - created: string; - name: string; - modified: string; - id: string; + public: boolean + created: string + name: string + modified: string + id: string } export interface ProjectObject extends MmsObject { - _refId?: string; - schema?: string; - _creator?: string; - _docId?: string; - _created?: string; - name?: string; - id: string; - orgId?: string; + _refId?: string + schema?: string + _creator?: string + _docId?: string + _created?: string + name?: string + id: string + orgId?: string } export interface MountObject extends ProjectObject { - _mounts: MountObject[]; - _refId: string; - _projectId: string; + _mounts: MountObject[] + _refId: string + _projectId: string } export interface RefObject extends MmsObject { - parentRefId?: string; - deleted?: boolean; - _docId?: string; - _creator?: string; - _created?: string; - description?: string; - name?: string; - id: string; - type: string; - _projectId: string; - permission?: string; - parentCommitId?: string; - timestamp?: Date; + parentRefId?: string + deleted?: boolean + _docId?: string + _creator?: string + _created?: string + description?: string + name?: string + id: string + type: string + _projectId: string + permission?: string + parentCommitId?: string + timestamp?: Date } diff --git a/src/ve-types/mms/valuesAndInstances.d.ts b/src/ve-types/mms/valuesAndInstances.d.ts index 34a7275b9..8592773da 100644 --- a/src/ve-types/mms/valuesAndInstances.d.ts +++ b/src/ve-types/mms/valuesAndInstances.d.ts @@ -1,42 +1,42 @@ -import { ElementObject } from '@ve-types/mms'; +import { ElementObject } from '@ve-types/mms' //Value Specs export interface ValueObject extends ElementObject { - expression?: ExpressionObject; + expression?: ExpressionObject } export interface LiteralObject extends ValueObject { - value?: T; + value?: T } export interface InstanceValueObject extends ValueObject { - instanceId?: string; + instanceId?: string } export interface ElementValueObject extends ValueObject { - elementId?: string; + elementId?: string } export interface ExpressionObject extends ValueObject { - operand?: T[]; + operand?: T[] } //Constraint export interface ConstraintObject extends ElementObject { - specification?: ValueObject; + specification?: ValueObject } //Instances export interface InstanceSpecObject extends ElementObject { - classifierIds?: string[]; - specification?: ValueObject; + classifierIds?: string[] + specification?: ValueObject } export interface SlotObject extends LiteralObject[]> { - definingFeatureId: string; + definingFeatureId: string } export interface TaggedValueObject extends LiteralObject[]> { - tagDefinitionId: string; + tagDefinitionId: string } export interface ElementTaggedValueObject extends TaggedValueObject { - valueIds: string[]; + valueIds: string[] } diff --git a/src/ve-types/mms/views.d.ts b/src/ve-types/mms/views.d.ts index 08b0bba9c..b1fb1d32e 100644 --- a/src/ve-types/mms/views.d.ts +++ b/src/ve-types/mms/views.d.ts @@ -5,96 +5,96 @@ import { InstanceSpecObject, InstanceValueObject, LiteralObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' /* View Objects */ export interface ViewObject extends ElementObject { - isDoc?: boolean; - aggregation?: string; - propertyId?: string; - _relatedDocuments?: ViewObject[]; - _parentViews?: ViewObject[]; - _contents?: ExpressionObject; - _childViews?: ViewObject[]; - _displayedElementIds?: string[]; - _veNumber?: string; - _printCss?: string; + isDoc?: boolean + aggregation?: string + propertyId?: string + _relatedDocuments?: ViewObject[] + _parentViews?: ViewObject[] + _contents?: ExpressionObject + _childViews?: ViewObject[] + _displayedElementIds?: string[] + _veNumber?: string + _printCss?: string } export interface DocumentObject extends ViewObject { - _groupId?: string; - _startChapter?: number; + _groupId?: string + _startChapter?: number } export interface PackageObject extends ElementObject { - elementImportIds?: string[]; - packageImportIds?: string[]; - URI?: string; - packageMergeIds?: string[]; - profileApplicationIds?: string[]; + elementImportIds?: string[] + packageImportIds?: string[] + URI?: string + packageMergeIds?: string[] + profileApplicationIds?: string[] } export interface GroupObject extends PackageObject { - _isGroup?: boolean; - _parentId?: string; + _isGroup?: boolean + _parentId?: string } /* View and Presentation Instances */ export interface ViewInstanceSpec extends InstanceSpecObject { - specification?: ExpressionObject | LiteralObject; - _veNumber?: string; + specification?: ExpressionObject | LiteralObject + _veNumber?: string } export interface PresentationReference extends MmsObject { - instanceId: string; - instanceVal?: InstanceValueObject; - sectionElements: PresentationReference[]; - instanceSpecification?: ViewInstanceSpec; - presentationElement?: PresentationInstanceObject | ViewInstanceSpec; - isOpaque: boolean; + instanceId: string + instanceVal?: InstanceValueObject + sectionElements: PresentationReference[] + instanceSpecification?: ViewInstanceSpec + presentationElement?: PresentationInstanceObject | ViewInstanceSpec + isOpaque: boolean } export interface PresentationInstanceObject extends MmsObject { - type: string; - isOpaque?: boolean; + type: string + isOpaque?: boolean } export interface PresentContentObject extends PresentationInstanceObject { - excludeFromList: boolean; - showIfEmpty: boolean; - title: string; + excludeFromList: boolean + showIfEmpty: boolean + title: string } export interface PresentImageObject extends PresentContentObject { - id: string; + id: string } export interface PresentListObject extends PresentContentObject { - list: PresentationInstanceObject[][]; - ordered?: boolean; + list: PresentationInstanceObject[][] + ordered?: boolean } export interface PresentTableObject extends PresentContentObject { - body: TableEntryObject[][]; - header?: TableEntryObject[][]; - colwidths?: string; - style: string; + body: TableEntryObject[][] + header?: TableEntryObject[][] + colwidths?: string + style: string } export interface TableEntryObject { - colspan: number; - rowspan: number; - content: PresentationInstanceObject[]; - startCol?: number; - endCol?: number; - startRow?: number; - endRow?: number; + colspan: number + rowspan: number + content: PresentationInstanceObject[] + startCol?: number + endCol?: number + startRow?: number + endRow?: number } export interface PresentTextObject extends PresentationInstanceObject { - source: string; - sourceProperty?: string; - sourceType: string; - nonEditable?: boolean; - text?: string; + source: string + sourceProperty?: string + sourceType: string + nonEditable?: boolean + text?: string } diff --git a/src/ve-types/third-party/angular.d.ts b/src/ve-types/third-party/angular.d.ts index a07055cb5..186ec05ca 100644 --- a/src/ve-types/third-party/angular.d.ts +++ b/src/ve-types/third-party/angular.d.ts @@ -1,14 +1,14 @@ /* eslint-disable unused-imports/no-unused-imports */ -import angular from 'angular'; +import angular from 'angular' declare module 'angular' { interface IRequestConfig { - cancel: IDeferred; + cancel: IDeferred } interface IPromise { - state: string; + state: string } interface IDeferred { - state: string; + state: string } } diff --git a/src/ve-types/third-party/jquery.d.ts b/src/ve-types/third-party/jquery.d.ts index 05758937c..fa5282a6f 100644 --- a/src/ve-types/third-party/jquery.d.ts +++ b/src/ve-types/third-party/jquery.d.ts @@ -1,18 +1,18 @@ -export {}; +export {} declare global { interface JQuery { - isOnScreen(x?: number, y?: number): boolean; + isOnScreen(x?: number, y?: number): boolean - table2CSV(inputOptions: table2CSV.inputOptions): string; + table2CSV(inputOptions: table2CSV.inputOptions): string } namespace JQuery { namespace table2CSV { interface inputOptions { - delivery: string; - separator?: string; - header?: string[]; + delivery: string + separator?: string + header?: string[] } } } diff --git a/src/ve-types/third-party/mathjax.d.ts b/src/ve-types/third-party/mathjax.d.ts index 5b99e02f3..95cfa3051 100644 --- a/src/ve-types/third-party/mathjax.d.ts +++ b/src/ve-types/third-party/mathjax.d.ts @@ -1,3 +1,3 @@ export interface MathJaxObject { - typesetPromise(elements: any[]): Promise; + typesetPromise(elements: any[]): Promise } diff --git a/src/ve-types/tree.d.ts b/src/ve-types/tree.d.ts index ba7e7e355..869f7b364 100644 --- a/src/ve-types/tree.d.ts +++ b/src/ve-types/tree.d.ts @@ -1,159 +1,159 @@ -import angular from 'angular'; +import angular from 'angular' -import ITreeNode = AngularUITree.ITreeNode; +import ITreeNode = AngularUITree.ITreeNode -import { ElementObject, ElementsRequest, ViewObject } from '@ve-types/mms'; +import { ElementObject, ElementsRequest, ViewObject } from '@ve-types/mms' /** * @typedef TreeBranch */ export interface TreeBranch extends ITreeNode { - label: string; - type: string; - priority?: number; - group?: ElementObject; - data: ViewObject; - children: TreeBranch[]; - hide?: boolean; - level?: number; - new?: string; - loading?: boolean; - aggr?: string; - propertyId?: string; - parent_uid?: string; - uid?: string; - viewId?: string; - selected?: boolean; - expanded?: boolean; - expandable?: boolean; - favorite?: boolean; - onSelect?(branch: TreeBranch): void; - onDblClick?(branch: TreeBranch): void; + label: string + type: string + priority?: number + group?: ElementObject + data: ViewObject + children: TreeBranch[] + hide?: boolean + level?: number + new?: string + loading?: boolean + aggr?: string + propertyId?: string + parent_uid?: string + uid?: string + viewId?: string + selected?: boolean + expanded?: boolean + expandable?: boolean + favorite?: boolean + onSelect?(branch: TreeBranch): void + onDblClick?(branch: TreeBranch): void } export interface TreeRow { - branch: TreeBranch; - children: TreeBranch[]; - visibleChild: boolean; - label: string; - level: number; - section: string; - typeIcon: string; - visible: boolean; + branch: TreeBranch + children: TreeBranch[] + visibleChild: boolean + label: string + level: number + section: string + typeIcon: string + visible: boolean } export interface TreeApi extends ElementsRequest { - rootId?: string; - refType: string; - sectionNumbering?: boolean; - numberingDepth?: number; - numberingSeparator?: string; - expandLevel?: number; - search?: string; - sort?: boolean; - startChapter?: number; - treeContentLoading?: boolean; - treeCategory?: string; - expandCallback?(elementId: string, branch: TreeBranch, recurse: boolean); - onSelect?(branch: TreeBranch): void; - onDblClick?(branch: TreeBranch): void; + rootId?: string + refType: string + sectionNumbering?: boolean + numberingDepth?: number + numberingSeparator?: string + expandLevel?: number + search?: string + sort?: boolean + startChapter?: number + treeContentLoading?: boolean + treeCategory?: string + expandCallback?(elementId: string, branch: TreeBranch, recurse: boolean) + onSelect?(branch: TreeBranch): void + onDblClick?(branch: TreeBranch): void } export interface TreeConfig { - id: string; - title?: string; - icon?: string; - types?: string[]; - treeData?: TreeBranch[]; - treeRows?: TreeRow[]; + id: string + title?: string + icon?: string + types?: string[] + treeData?: TreeBranch[] + treeRows?: TreeRow[] } export interface TreeIcons { - iconExpand: string; - iconCollapse: string; - iconDefault: string; + iconExpand: string + iconCollapse: string + iconDefault: string } export interface VeTreeNodeScope extends AngularUITree.ITreeNodeScope { - node: TreeBranch; + node: TreeBranch } export interface View2NodeMap { - [key: string]: TreeBranch; + [key: string]: TreeBranch } declare namespace AngularUITree { interface IEventSourceInfo { - cloneModel: any; - index: number; - nodeScope: ITreeNodeScope; - nodesScope: ITreeNodeScope; + cloneModel: any + index: number + nodeScope: ITreeNodeScope + nodesScope: ITreeNodeScope } interface IPosition { - dirAx: number; - dirX: number; - dirY: number; - distAxX: number; - distAxY: number; - distX: number; - distY: number; - lastDirX: number; - lastDirY: number; - lastX: number; - lastY: number; - moving: boolean; - nowX: number; - nowY: number; - offsetX: number; - offsetY: number; - startX: number; - startY: number; + dirAx: number + dirX: number + dirY: number + distAxX: number + distAxY: number + distX: number + distY: number + lastDirX: number + lastDirY: number + lastX: number + lastY: number + moving: boolean + nowX: number + nowY: number + offsetX: number + offsetY: number + startX: number + startY: number } interface IEventInfo { dest: { - index: number; - nodesScope: IParentTreeNodeScope; - }; - elements: any; - pos: IPosition; - source: IEventSourceInfo; + index: number + nodesScope: IParentTreeNodeScope + } + elements: any + pos: IPosition + source: IEventSourceInfo } interface IAcceptCallback { - (source: ITreeNodeScope, destination: ITreeNodeScope, destinationIndex: number): boolean; + (source: ITreeNodeScope, destination: ITreeNodeScope, destinationIndex: number): boolean } interface IDragCallback { - (eventInfo: IEventInfo): void; + (eventInfo: IEventInfo): void } interface ICallbacks { - accept?: IAcceptCallback; - dragStart?: IDragCallback; - dropped?: IDragCallback; - dragStop?: IDragCallback; + accept?: IAcceptCallback + dragStart?: IDragCallback + dropped?: IDragCallback + dragStop?: IDragCallback } /** * Internal representation of node in the UI */ interface ITreeNodeScope extends angular.IScope { - $element: JQuery; - $modelValue: any; // Model value for node; - $nodeScope: ITreeNodeScope; // uiTreeNode Scope of this node - $parentNodeScope: IParentTreeNodeScope[]; // uiTreeNode Scope of parent node; - $childNodesScope: ITreeNodeScope[]; // uiTreeNodes Scope of child nodes. - $parentNodesScope: angular.IScope; // uiTreeNodes Scope of parent nodes. - $treeScope: angular.IScope; // uiTree scope - $handleScope: angular.IScope; // it's handle scope - $type: 'uiTreeNode'; - node: ITreeNode; + $element: JQuery + $modelValue: any // Model value for node; + $nodeScope: ITreeNodeScope // uiTreeNode Scope of this node + $parentNodeScope: IParentTreeNodeScope[] // uiTreeNode Scope of parent node; + $childNodesScope: ITreeNodeScope[] // uiTreeNodes Scope of child nodes. + $parentNodesScope: angular.IScope // uiTreeNodes Scope of parent nodes. + $treeScope: angular.IScope // uiTree scope + $handleScope: angular.IScope // it's handle scope + $type: 'uiTreeNode' + node: ITreeNode } interface IParentTreeNodeScope extends ITreeNodeScope { - isParent(nodeScope: ITreeNodeScope): boolean; + isParent(nodeScope: ITreeNodeScope): boolean } // /** diff --git a/src/ve-types/view-editor.d.ts b/src/ve-types/view-editor.d.ts index a6241006a..4915f9887 100644 --- a/src/ve-types/view-editor.d.ts +++ b/src/ve-types/view-editor.d.ts @@ -1,37 +1,37 @@ -import { ngStorage } from 'ngstorage'; +import { ngStorage } from 'ngstorage' -import IModalService = angular.ui.bootstrap.IModalService; -import IModalSettings = angular.ui.bootstrap.IModalSettings; -import IModalInstanceService = angular.ui.bootstrap.IModalInstanceService; +import IModalService = angular.ui.bootstrap.IModalService +import IModalSettings = angular.ui.bootstrap.IModalSettings +import IModalInstanceService = angular.ui.bootstrap.IModalInstanceService -import { VeComponentOptions, VePromise, VePromiseReason } from '@ve-types/angular'; -import { MmsObject, OrgObject, ProjectObject, ViewObject } from '@ve-types/mms'; +import { VeComponentOptions, VePromise, VePromiseReason } from '@ve-types/angular' +import { MmsObject, OrgObject, ProjectObject, ViewObject } from '@ve-types/mms' -export type veSearchCallback = (elem: T, property: string) => void; +export type veSearchCallback = (elem: T, property: string) => void export interface VeSearchOptions { - getProperties?: boolean; - searchResult?: T[]; - searchField?: string; - closeable: boolean; - closeCallback?(): void; - searchInput?: string; - hideFilterOptions?: boolean; - callback?: veSearchCallback; - relatedCallback?(doc: ViewObject, view: ViewObject, elem: T): void; - filterCallback?(elements: T[]): T[]; - filterQueryList?: [(...any) => { [key: string]: string[] }]; - emptyDocTxt?: string; - itemsPerPage?: number; + getProperties?: boolean + searchResult?: T[] + searchField?: string + closeable: boolean + closeCallback?(): void + searchInput?: string + hideFilterOptions?: boolean + callback?: veSearchCallback + relatedCallback?(doc: ViewObject, view: ViewObject, elem: T): void + filterCallback?(elements: T[]): T[] + filterQueryList?: [(...any) => { [key: string]: string[] }] + emptyDocTxt?: string + itemsPerPage?: number } export interface VeModalService extends IModalService { - open?(settings: VeModalSettings): VeModalInstanceService; + open?(settings: VeModalSettings): VeModalInstanceService } export interface VeModalSettings extends IModalSettings { - component: string; - resolve?: U; + component: string + resolve?: U // bindings?: { // modalInstance: VeModalInstanceService // resolve?: U @@ -40,48 +40,48 @@ export interface VeModalSettings extends IModalSetti export interface VeModalComponent extends VeComponentOptions { bindings?: { - modalInstance: string; - resolve?: string; - }; + modalInstance: string + resolve?: string + } } export interface VeModalInstanceService extends IModalInstanceService { - close(result?: T): void; - dismiss(reason?: T): void; - result: VePromise; + close(result?: T): void + dismiss(reason?: T): void + result: VePromise } export interface VeModalController extends IComponentController { // close: ($value?: any) => void, // dismiss: ($value?: any) => void, - modalInstance: IModalInstanceService; + modalInstance: IModalInstanceService } export interface VeModalResolve { - [key: string]: unknown; + [key: string]: unknown } export interface VeModalResolveFn { - [key: string]: () => unknown; + [key: string]: () => unknown } export interface VeStorageService extends ngStorage.StorageService { - token: string; - org: OrgObject; - project: ProjectObject; + token: string + org: OrgObject + project: ProjectObject } export interface VeApiObject { - [key: string]: VeApiWait; + [key: string]: VeApiWait } export interface VeApiWait { - resolve?(result: T): void; - reject?(reason: VePromiseReason): void; - promise?: VePromise; - api?: T; - refId?: string; - projectId?: string; + resolve?(result: T): void + reject?(reason: VePromiseReason): void + promise?: VePromise + api?: T + refId?: string + projectId?: string } // { // getProperties: any diff --git a/src/ve-types/window.d.ts b/src/ve-types/window.d.ts index 88f8342c9..3591fe735 100644 --- a/src/ve-types/window.d.ts +++ b/src/ve-types/window.d.ts @@ -1,18 +1,18 @@ //https://stackoverflow.com/questions/57132428/augmentations-for-the-global-scope-can-only-be-directly-nested-in-external-modul -import { MathJaxObject } from 'mathjax-full/js/components/startup'; +import { MathJaxObject } from 'mathjax-full/js/components/startup' -import { HtmlRenderedDiff } from '../lib/html-rendered-diff'; +import { HtmlRenderedDiff } from '../lib/html-rendered-diff' -import { VeConfig } from '@ve-types/config'; +import { VeConfig } from '@ve-types/config' -export {}; +export {} declare global { interface Window { - $: JQuery; - MathJax: MathJaxObject; - __env: VeConfig; - HtmlRenderedDiff: HtmlRenderedDiff; - Promise: Promise; + $: JQuery + MathJax: MathJaxObject + __env: VeConfig + HtmlRenderedDiff: HtmlRenderedDiff + Promise: Promise } } diff --git a/src/ve-utils/application/Application.service.ts b/src/ve-utils/application/Application.service.ts index 97a83e657..a78c5ba05 100644 --- a/src/ve-utils/application/Application.service.ts +++ b/src/ve-utils/application/Application.service.ts @@ -1,12 +1,12 @@ -import { CacheService } from '@ve-utils/core'; -import { ApiService, ElementService, ProjectService } from '@ve-utils/mms-api-client'; +import { CacheService } from '@ve-utils/core' +import { ApiService, ElementService, ProjectService } from '@ve-utils/mms-api-client' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { BrandingStyle } from './Branding.service'; +import { BrandingStyle } from './Branding.service' -import { VePromise, VeQService } from '@ve-types/angular'; -import { ElementObject, UsersRequest } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { ElementObject, UsersRequest } from '@ve-types/mms' /** * @ngdoc service * @name veUtils/ApplicationService @@ -18,19 +18,19 @@ import { ElementObject, UsersRequest } from '@ve-types/mms'; */ export interface ProjectSettingsObject extends ElementObject { - banner?: BrandingStyle; - footer?: BrandingStyle; + banner?: BrandingStyle + footer?: BrandingStyle } export interface UserSettingsObject extends ElementObject { - pinned?: string[]; + pinned?: string[] } export interface VeApplicationState { - inDoc: boolean; - fullDoc: boolean; - currentDoc: string; - user: string; + inDoc: boolean + fullDoc: boolean + currentDoc: string + user: string } export class ApplicationService { @@ -39,11 +39,11 @@ export class ApplicationService { fullDoc: false, currentDoc: null, user: null, - }; + } - public PROJECT_URL_PREFIX = '#/projects/'; + public PROJECT_URL_PREFIX = '#/projects/' - static $inject = ['$q', 'ProjectService', 'ElementService', 'ApiService', 'CacheService']; + static $inject = ['$q', 'ProjectService', 'ElementService', 'ApiService', 'CacheService'] constructor( private $q: VeQService, @@ -54,22 +54,22 @@ export class ApplicationService { ) {} public getState(): VeApplicationState { - return this.state; + return this.state } public copyToClipboard(target: JQuery, $event: JQuery.ClickEvent): VePromise { - const deferred = this.$q.defer(); - $event.stopPropagation(); + const deferred = this.$q.defer() + $event.stopPropagation() navigator.clipboard.writeText(target[0].childNodes[0].textContent).then( () => { - deferred.resolve(); + deferred.resolve() }, (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); - return deferred.promise; + ) + return deferred.promise } public getUserSettings = ( @@ -77,10 +77,10 @@ export class ApplicationService { refresh?: boolean, weight?: number ): VePromise => { - const cacheKey = this.apiSvc.makeCacheKey(reqOb, '_hidden_' + reqOb.username + '_ve_settings', false); - const cached = this.cacheSvc.get(cacheKey); + const cacheKey = this.apiSvc.makeCacheKey(reqOb, '_hidden_' + reqOb.username + '_ve_settings', false) + const cached = this.cacheSvc.get(cacheKey) if (cached && !refresh) { - return this.$q.resolve(cached); + return this.$q.resolve(cached) } return new this.$q((resolve, reject) => { this.elementSvc @@ -110,18 +110,18 @@ export class ApplicationService { }, ], }) - .then(resolve, reject); - } else resolve(result); - }, reject); - }); - }; + .then(resolve, reject) + } else resolve(result) + }, reject) + }) + } public updateUserSettings = ( reqOb: UsersRequest, settingsOb: UserSettingsObject ): VePromise => { - return this.elementSvc.updateElement(settingsOb); - }; + return this.elementSvc.updateElement(settingsOb) + } public getSettings = ( projectId: string, @@ -129,11 +129,11 @@ export class ApplicationService { refresh?: boolean, weight?: number ): VePromise => { - if (!refId) refId = 'master'; - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '_hidden_' + projectId + '_settings', false); - const cached = this.cacheSvc.get(cacheKey); + if (!refId) refId = 'master' + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '_hidden_' + projectId + '_settings', false) + const cached = this.cacheSvc.get(cacheKey) if (cached && !refresh) { - return this.$q.resolve(cached); + return this.$q.resolve(cached) } return new this.$q((resolve, reject) => { this.elementSvc @@ -149,11 +149,11 @@ export class ApplicationService { ) .then((result) => { if (result === null) { - this.createSettings(projectId, refId, null).then(resolve, reject); - } else resolve(result); - }, reject); - }); - }; + this.createSettings(projectId, refId, null).then(resolve, reject) + } else resolve(result) + }, reject) + }) + } public createSettings = ( projectId: string, @@ -167,21 +167,21 @@ export class ApplicationService { _projectId: projectId, _refId: refId, type: 'Class', - }; + } } return this.elementSvc.createElement({ elementId: '_hidden_' + projectId + '_settings', projectId, refId, elements: [settingsOb], - }); - }; + }) + } addPins(username: string, projectId: string, refId: string, pinned: string[]): VePromise { return new this.$q((resolve, reject) => { this.getUserSettings({ username, projectId, refId }).then((result) => { if (result.pinned) { - pinned = [...new Set([...result.pinned, ...pinned])]; + pinned = [...new Set([...result.pinned, ...pinned])] } this.elementSvc .updateElement({ @@ -190,9 +190,9 @@ export class ApplicationService { _projectId: result._projectId, pinned, }) - .then(resolve, reject); - }, reject); - }); + .then(resolve, reject) + }, reject) + }) } removePins(username: string, projectId: string, refId: string, unpinned: string[]): VePromise { @@ -200,8 +200,8 @@ export class ApplicationService { this.getUserSettings({ username, projectId, refId }).then((response) => { if (response.pinned) { const pinned = response.pinned.filter((pin) => { - return unpinned.includes(pin); - }); + return unpinned.includes(pin) + }) this.elementSvc .updateElement({ id: response.id, @@ -209,11 +209,11 @@ export class ApplicationService { _projectId: response._projectId, pinned, }) - .then(resolve, reject); - } else resolve(response); - }, reject); - }); + .then(resolve, reject) + } else resolve(response) + }, reject) + }) } } -veUtils.service('ApplicationService', ApplicationService); +veUtils.service('ApplicationService', ApplicationService) diff --git a/src/ve-utils/application/Branding.service.ts b/src/ve-utils/application/Branding.service.ts index 4efb954c7..c03c0985a 100644 --- a/src/ve-utils/application/Branding.service.ts +++ b/src/ve-utils/application/Branding.service.ts @@ -1,16 +1,16 @@ -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; -import { VeConfig } from '@ve-types/config'; -import { ParamsObject, ProjectsResponse } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { VeConfig } from '@ve-types/config' +import { ParamsObject, ProjectsResponse } from '@ve-types/mms' export interface BrandingStyle { - labels?: string[] | string[][]; - message?: string | string[]; - separator?: string; - background?: string; - color?: string; - disabled: boolean; + labels?: string[] | string[][] + message?: string | string[] + separator?: string + background?: string + color?: string + disabled: boolean } // export interface BannerStyle extends BrandingStyle { @@ -24,30 +24,30 @@ export interface BrandingStyle { * * Branding Service */ export class BrandingService { - public labels: { [key: string]: string }; - private defaultSeparator: string = ' - '; + public labels: { [key: string]: string } + private defaultSeparator: string = ' - ' private defaultLabels: { [key: string]: string } = { pi: 'PROPRIETARY: Proprietary Information', export_ctrl: 'EXPORT WARNING: No export controlled documents allowed on this server', no_public_release: 'Not for Public Release or Redistribution', unclassified: 'CLASSIFICATION: This system is UNCLASSIFIED', opensource: 'OpenMBEE View Editor | Licensed under Apache 2.0', - }; + } loginBanner: BrandingStyle = { labels: ['opensource', 'unclassified'], disabled: false, - }; - config: VeConfig = window.__env; + } + config: VeConfig = window.__env banner: BrandingStyle = { labels: ['pi'], background: '#0D47A1', color: '#e8e8e8', disabled: false, - }; + } footer: BrandingStyle = { labels: ['pi', 'no_public_release'], disabled: false, - }; + } loginWarning: BrandingStyle = { disabled: false, message: [ @@ -58,81 +58,81 @@ export class BrandingService { 'If you are not authorized to access this system, disconnect now. Users of this system have no expectation', 'of privacy. By continuing, you consent to your keystrokes and data content being monitored.', ], - }; - static $inject = ['$q']; + } + static $inject = ['$q'] constructor(private $q: VeQService) { if (this.config.customLabels) { - this.labels = Object.assign(this.defaultLabels, this.config.customLabels); + this.labels = Object.assign(this.defaultLabels, this.config.customLabels) } if (this.config.banner) { - this.banner = Object.assign(this.banner, this.config.banner); + this.banner = Object.assign(this.banner, this.config.banner) } - this.createMessage(this.banner); + this.createMessage(this.banner) if (this.config.loginBanner) { - this.loginBanner = Object.assign(this.loginBanner, this.config.loginBanner); + this.loginBanner = Object.assign(this.loginBanner, this.config.loginBanner) } - this.createMessage(this.loginBanner); + this.createMessage(this.loginBanner) if (this.config.footer) { - this.footer = Object.assign(this.footer, this.config.footer); + this.footer = Object.assign(this.footer, this.config.footer) } - this.createMessage(this.footer); + this.createMessage(this.footer) if (this.config.loginWarning) { - this.loginWarning = Object.assign(this.loginWarning, this.config.loginWarning); + this.loginWarning = Object.assign(this.loginWarning, this.config.loginWarning) } - this.createMessage(this.loginWarning); + this.createMessage(this.loginWarning) } public createMessage = (brandingStyle: BrandingStyle): void => { if (brandingStyle.labels) { - const separator: string = brandingStyle.separator ? brandingStyle.separator : this.defaultSeparator; - brandingStyle.message = []; + const separator: string = brandingStyle.separator ? brandingStyle.separator : this.defaultSeparator + brandingStyle.message = [] if (Array.isArray(brandingStyle.labels[0])) { for (const line of brandingStyle.labels) { if (Array.isArray(line)) { - brandingStyle.message.push(this._getMessage(line, separator)); + brandingStyle.message.push(this._getMessage(line, separator)) } } } else { - brandingStyle.message.push(this._getMessage(brandingStyle.labels as string[], separator)); + brandingStyle.message.push(this._getMessage(brandingStyle.labels as string[], separator)) } } - }; + } private _getMessage = (labels: string[], separator?: string): string => { - let msg = ''; + let msg = '' for (const [labelNum, label] of labels.entries()) { - msg += this._getLabel(label); + msg += this._getLabel(label) if (labelNum < labels.length - 1) { - msg += separator; + msg += separator } } - return msg; - }; + return msg + } private _getLabel = (labelName: string): string => { - let msg = ''; + let msg = '' if (this.labels.hasOwnProperty(labelName)) { - msg = this.labels[labelName]; + msg = this.labels[labelName] } else { - msg = 'Missing Label'; + msg = 'Missing Label' } - return msg; - }; + return msg + } getBanner(params?: ParamsObject): VePromise { - return this.$q.resolve(this.banner); + return this.$q.resolve(this.banner) } getLoginBanner(): VePromise { - return this.$q.resolve(this.loginBanner); + return this.$q.resolve(this.loginBanner) } getFooter(params?: ParamsObject): VePromise { - return this.$q.resolve(this.footer); + return this.$q.resolve(this.footer) } } -veUtils.service('BrandingService', BrandingService); +veUtils.service('BrandingService', BrandingService) diff --git a/src/ve-utils/application/Image.service.ts b/src/ve-utils/application/Image.service.ts index 9d7830738..fdd369270 100644 --- a/src/ve-utils/application/Image.service.ts +++ b/src/ve-utils/application/Image.service.ts @@ -1,51 +1,51 @@ -import { AuthService } from '@ve-utils/mms-api-client'; +import { AuthService } from '@ve-utils/mms-api-client' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VeConfig } from '@ve-types/config'; +import { VeConfig } from '@ve-types/config' export class ImageService { - public veConfig: VeConfig = window.__env; + public veConfig: VeConfig = window.__env - static $inject = ['AuthService']; + static $inject = ['AuthService'] constructor(private authSvc: AuthService) {} public fixImgSrc(imgDom: JQuery): void { - let src = imgDom.attr('src'); + let src = imgDom.attr('src') if (src) { if (src) { if (src.indexOf('http') < 0) { - src = this.veConfig.apiUrl + src; + src = this.veConfig.apiUrl + src } - imgDom.attr('src', src + '?token=' + this.authSvc.getToken()); + imgDom.attr('src', src + '?token=' + this.authSvc.getToken()) } if (imgDom.width() < 860) { //keep image relative centered with text if less than 9 in - return; + return } - const parent = imgDom.parent('p'); + const parent = imgDom.parent('p') if (parent.length > 0) { if (parent.css('text-align') == 'center' || parent.hasClass('image-center')) { - imgDom.addClass('image-center'); + imgDom.addClass('image-center') } - imgDom.unwrap(); //note this removes parent p and puts img and any of its siblings in its place + imgDom.unwrap() //note this removes parent p and puts img and any of its siblings in its place } } } public fixImgUrl = (src: string, addToken?: boolean): string => { - const url = new window.URL(src); - const params = new window.URLSearchParams(url.search); + const url = new window.URL(src) + const params = new window.URLSearchParams(url.search) if (params.has('token')) { - params.delete('token'); + params.delete('token') } if (addToken) { - params.append('token', this.authSvc.getToken()); + params.append('token', this.authSvc.getToken()) } - url.search = params.toString(); - return url.toString(); - }; + url.search = params.toString() + return url.toString() + } } -veUtils.service('ImageService', ImageService); +veUtils.service('ImageService', ImageService) diff --git a/src/ve-utils/application/Math.service.ts b/src/ve-utils/application/Math.service.ts index b22815d27..c6687e68b 100644 --- a/src/ve-utils/application/Math.service.ts +++ b/src/ve-utils/application/Math.service.ts @@ -1,26 +1,26 @@ -import { MathJaxObject } from 'mathjax-full/js/components/startup'; +import { MathJaxObject } from 'mathjax-full/js/components/startup' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' export class MathService { - private promise = Promise.resolve(); // Used to hold chain of typesetting calls - private mathJax: MathJaxObject = window.MathJax; + private promise = Promise.resolve() // Used to hold chain of typesetting calls + private mathJax: MathJaxObject = window.MathJax - static $inject = []; + static $inject = [] typeset(element: HTMLElement | HTMLElement[]): Promise { this.promise = this.promise .then(() => { if (!Array.isArray(element)) { - element = [element]; + element = [element] } - (this.mathJax.typesetPromise as (elements: HTMLElement[]) => Promise)(element).catch( + ;(this.mathJax.typesetPromise as (elements: HTMLElement[]) => Promise)(element).catch( (err: { message: string }) => console.log(`Typeset failed: ${err.message}`) - ); + ) }) - .catch((err: { message: string }) => console.log(`Typeset failed: ${err.message}`)); - return this.promise; + .catch((err: { message: string }) => console.log(`Typeset failed: ${err.message}`)) + return this.promise } } -veUtils.service('MathService', MathService); +veUtils.service('MathService', MathService) diff --git a/src/ve-utils/application/RootScope.service.ts b/src/ve-utils/application/RootScope.service.ts index f3aaef00f..19506758a 100644 --- a/src/ve-utils/application/RootScope.service.ts +++ b/src/ve-utils/application/RootScope.service.ts @@ -1,10 +1,10 @@ -import { StateDeclaration } from '@uirouter/core/lib/state/interface'; +import { StateDeclaration } from '@uirouter/core/lib/state/interface' -import { SessionService } from '@ve-utils/core'; +import { SessionService } from '@ve-utils/core' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { ParamsObject } from '@ve-types/mms'; +import { ParamsObject } from '@ve-types/mms' export class RootScopeService { public constants = { @@ -32,115 +32,115 @@ export class RootScopeService { TREEINITIALSELECTION: 'tree-initialSelection', TREEICONS: 'tree-icons', LEFTPANECLOSED: 'tree-pane-closed', - }; + } - static $inject = ['SessionService']; + static $inject = ['SessionService'] constructor(private sessionSvc: SessionService) {} init(): void { - this.loginModalOpen(); - this.rightPaneToggleable(); - this.rightPaneClosed(); - this.veTitle(); - this.veShowLogin(); - this.veStateChanging(); - this.veViewContentLoading(); - this.veRedirect(); - this.veRedirectFromOld(); - this.veCrushUrl(); - this.veFullDocMode(); - this.veCommentsOn(); - - this.veNumberingOn(); - this.veElementsOn(); - this.veEditMode(); - this.veHidePanes(); - this.veHideLeft(); - this.veHideRight(); + this.loginModalOpen() + this.rightPaneToggleable() + this.rightPaneClosed() + this.veTitle() + this.veShowLogin() + this.veStateChanging() + this.veViewContentLoading() + this.veRedirect() + this.veRedirectFromOld() + this.veCrushUrl() + this.veFullDocMode() + this.veCommentsOn() + + this.veNumberingOn() + this.veElementsOn() + this.veEditMode() + this.veHidePanes() + this.veHideLeft() + this.veHideRight() } loginModalOpen(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.LOGINMODALOPEN, value, false); + return this.sessionSvc.accessor(this.constants.LOGINMODALOPEN, value, false) } rightPaneToggleable(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.RIGHTPANETOGGLEABLE, value, true); + return this.sessionSvc.accessor(this.constants.RIGHTPANETOGGLEABLE, value, true) } rightPaneClosed(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.RIGHTPANECLOSED, value, false); + return this.sessionSvc.accessor(this.constants.RIGHTPANECLOSED, value, false) } veWarningOk(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEWARNINGOK, value, false); + return this.sessionSvc.accessor(this.constants.VEWARNINGOK, value, false) } veTitle(value?: string | undefined): string { - return this.sessionSvc.accessor(this.constants.VETITLE, value, 'View Editor'); + return this.sessionSvc.accessor(this.constants.VETITLE, value, 'View Editor') } veStateChanging(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VESTATECHANGING, value, false); + return this.sessionSvc.accessor(this.constants.VESTATECHANGING, value, false) } veViewContentLoading(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEVIEWCONTENTLOADING, value, false); + return this.sessionSvc.accessor(this.constants.VEVIEWCONTENTLOADING, value, false) } veRedirect( value?: { toState: StateDeclaration; toParams: ParamsObject } | undefined ): { toState: StateDeclaration; toParams: ParamsObject } | undefined { - return this.sessionSvc.accessor(this.constants.VEREDIRECT, value, null); + return this.sessionSvc.accessor(this.constants.VEREDIRECT, value, null) } veRedirectFromOld(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEREDIRECTFROMOLD, value, false); + return this.sessionSvc.accessor(this.constants.VEREDIRECTFROMOLD, value, false) } veCrushUrl(value?: string | undefined): string { - return this.sessionSvc.accessor(this.constants.VECRUSHURL, value, null); + return this.sessionSvc.accessor(this.constants.VECRUSHURL, value, null) } veFullDocMode(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEFULLDOCMODE, value, false); + return this.sessionSvc.accessor(this.constants.VEFULLDOCMODE, value, false) } veCommentsOn(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VECOMMENTSON, value, false); + return this.sessionSvc.accessor(this.constants.VECOMMENTSON, value, false) } veNumberingOn(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VENUMBERINGON, value, true); + return this.sessionSvc.accessor(this.constants.VENUMBERINGON, value, true) } veElementsOn(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEELEMENTSON, value, false); + return this.sessionSvc.accessor(this.constants.VEELEMENTSON, value, false) } veEditMode(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEEDITMODE, value, false); + return this.sessionSvc.accessor(this.constants.VEEDITMODE, value, false) } veHidePanes(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEHIDEPANES, value, false); + return this.sessionSvc.accessor(this.constants.VEHIDEPANES, value, false) } veHideLeft(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEHIDELEFT, value, false); + return this.sessionSvc.accessor(this.constants.VEHIDELEFT, value, false) } veHideRight(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEHIDERIGHT, value, false); + return this.sessionSvc.accessor(this.constants.VEHIDERIGHT, value, false) } veShowLogin(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VESHOWLOGIN, value, false); + return this.sessionSvc.accessor(this.constants.VESHOWLOGIN, value, false) } leftPaneClosed(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.LEFTPANECLOSED, value, false); + return this.sessionSvc.accessor(this.constants.LEFTPANECLOSED, value, false) } } -veUtils.service('RootScopeService', RootScopeService); +veUtils.service('RootScopeService', RootScopeService) diff --git a/src/ve-utils/application/ShortUrl.service.ts b/src/ve-utils/application/ShortUrl.service.ts index 1a627ef9a..cf4054aec 100644 --- a/src/ve-utils/application/ShortUrl.service.ts +++ b/src/ve-utils/application/ShortUrl.service.ts @@ -1,19 +1,19 @@ -import { ApplicationService } from '@ve-utils/application/Application.service'; -import { ElementService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client'; +import { ApplicationService } from '@ve-utils/application/Application.service' +import { ElementService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; -import { ParamsObject, ShortUrlRequest } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { ParamsObject, ShortUrlRequest } from '@ve-types/mms' export class ShortUrlService { public dynamicPopover: { - templateUrl: string; - title: string; + templateUrl: string + title: string } = { templateUrl: 'shareUrlTemplate.html', title: 'Link', - }; + } static $inject = [ '$q', @@ -24,7 +24,7 @@ export class ShortUrlService { 'ViewService', 'ElementService', 'ApplicationService', - ]; + ] constructor( private $q: VeQService, @@ -38,100 +38,100 @@ export class ShortUrlService { ) {} decodeShortUrl(urlFragment: string): VePromise { - const deferred = this.$q.defer(); - const urlParts: string[] = urlFragment.split('-'); + const deferred = this.$q.defer() + const urlParts: string[] = urlFragment.split('-') const _urlError = (defer?: angular.IDeferred): void => { - if (defer) defer.reject(); - else deferred.reject('Error Decoding URL'); - }; + if (defer) defer.reject() + else deferred.reject('Error Decoding URL') + } const result: ParamsObject = { projectId: urlParts[1], refId: urlParts[2], documentId: urlParts[3] && urlParts[3] === 'cover' ? null : urlParts[3], viewId: urlParts[4], - }; - let orgId: string = urlParts[0]; - const promises: VePromise[] = []; + } + let orgId: string = urlParts[0] + const promises: VePromise[] = [] // eslint-disable-next-line prefer-const if (orgId) { - const deferOrg = this.$q.defer(); - promises.push(deferOrg.promise); + const deferOrg = this.$q.defer() + promises.push(deferOrg.promise) this.projectSvc.getOrgs().then( (data) => { const org = data.filter((o) => { - return o.id.endsWith(orgId); - }); + return o.id.endsWith(orgId) + }) if (org.length > 0) { - orgId = org[0].id; - deferOrg.resolve(); + orgId = org[0].id + deferOrg.resolve() } else { - _urlError(deferOrg); + _urlError(deferOrg) } }, () => { - _urlError(deferOrg); + _urlError(deferOrg) } - ); + ) if (result.projectId) { - const deferProj = this.$q.defer(); - promises.push(deferProj.promise); + const deferProj = this.$q.defer() + promises.push(deferProj.promise) deferOrg.promise.then( () => { this.projectSvc.getProjects(orgId).then( (data) => { const proj = data.filter((p) => { - return p.id.endsWith(result.projectId); - }); + return p.id.endsWith(result.projectId) + }) if (proj.length > 0) { - result.projectId = proj[0].id; - deferProj.resolve(); + result.projectId = proj[0].id + deferProj.resolve() } else { - _urlError(deferProj); + _urlError(deferProj) } }, () => { - _urlError(deferProj); + _urlError(deferProj) } - ); + ) }, () => { - _urlError(deferProj); + _urlError(deferProj) } - ); + ) if (result.refId) { - const deferRef = this.$q.defer(); - promises.push(deferRef.promise); + const deferRef = this.$q.defer() + promises.push(deferRef.promise) deferProj.promise.then( () => { this.projectSvc.getRefs(result.projectId).then( (data) => { const refOb = data.filter((r) => { - return result.refId === 'm' ? r.id === 'master' : r.id.endsWith(result.refId); - }); + return result.refId === 'm' ? r.id === 'master' : r.id.endsWith(result.refId) + }) if (refOb.length > 0) { - result.refId = refOb[0].id; - deferRef.resolve(); + result.refId = refOb[0].id + deferRef.resolve() } else { - _urlError(deferRef); + _urlError(deferRef) } }, () => { - _urlError(deferRef); + _urlError(deferRef) } - ); + ) }, () => { - _urlError(deferRef); + _urlError(deferRef) } - ); + ) if (result.documentId) { if (result.viewId && result.viewId === 'cover') { - result.documentId = result.documentId + '_cover'; + result.documentId = result.documentId + '_cover' } - const deferDoc = this.$q.defer(); - promises.push(deferDoc.promise); + const deferDoc = this.$q.defer() + promises.push(deferDoc.promise) deferRef.promise.then( () => { this.viewSvc @@ -142,27 +142,27 @@ export class ShortUrlService { .then( (data) => { const doc = data.filter((d) => { - return d.id.endsWith(result.documentId); - }); + return d.id.endsWith(result.documentId) + }) if (doc.length > 0) { - result.documentId = doc[0].id; - deferDoc.resolve(); + result.documentId = doc[0].id + deferDoc.resolve() } else { - _urlError(deferDoc); + _urlError(deferDoc) } }, () => { - _urlError(deferDoc); + _urlError(deferDoc) } - ); + ) }, () => { - _urlError(deferDoc); + _urlError(deferDoc) } - ); + ) if (result.viewId && result.viewId !== 'cover') { - const deferView = this.$q.defer(); - promises.push(deferView.promise); + const deferView = this.$q.defer() + promises.push(deferView.promise) deferDoc.promise.then( () => { this.viewSvc @@ -173,24 +173,24 @@ export class ShortUrlService { .then( (data) => { const view = data.filter((v) => { - return v.id.endsWith(result.viewId); - }); + return v.id.endsWith(result.viewId) + }) if (view.length > 0) { - result.viewId = view[0].id; - deferView.resolve(); + result.viewId = view[0].id + deferView.resolve() } else { - _urlError(deferView); + _urlError(deferView) } }, () => { - _urlError(deferView); + _urlError(deferView) } - ); + ) }, () => { - _urlError(deferView); + _urlError(deferView) } - ); + ) } } } @@ -198,57 +198,57 @@ export class ShortUrlService { this.$q.all(promises).then( () => deferred.resolve(result), () => { - _urlError(); + _urlError() } - ); + ) } else { - _urlError(); + _urlError() } - return deferred.promise; + return deferred.promise } public getShortUrl = (paramOb: ShortUrlRequest): string => { - const ids: string[] = []; - const sOId = paramOb.orgId.split(/[-_]+/); - ids.push(sOId[sOId.length - 1]); + const ids: string[] = [] + const sOId = paramOb.orgId.split(/[-_]+/) + ids.push(sOId[sOId.length - 1]) if (paramOb.projectId && paramOb.projectId !== '') { - const sPId = paramOb.projectId.split(/[-_]+/); - ids.push(sPId[sPId.length - 1]); + const sPId = paramOb.projectId.split(/[-_]+/) + ids.push(sPId[sPId.length - 1]) if (paramOb.refId && paramOb.refId !== '') { if (paramOb.refId === 'master') { - ids.push('m'); + ids.push('m') } else { - const sRId = paramOb.refId.split(/[-_]+/); - ids.push(sRId[sRId.length - 1]); + const sRId = paramOb.refId.split(/[-_]+/) + ids.push(sRId[sRId.length - 1]) } if (paramOb.documentId && paramOb.documentId !== '') { - const sDId = paramOb.documentId.split(/[-_]+/); + const sDId = paramOb.documentId.split(/[-_]+/) if (paramOb.documentId.endsWith('_cover')) { if (paramOb.documentId.startsWith('site_')) { - ids.push(sDId[sDId.length - 2]); + ids.push(sDId[sDId.length - 2]) } - ids.push('cover'); + ids.push('cover') } else { - ids.push(sDId[sDId.length - 1]); + ids.push(sDId[sDId.length - 1]) } if (paramOb.viewId && paramOb.documentId !== '') { - const sVId = paramOb.viewId.split(/[-_]+/); - ids.push(sVId[sVId.length - 1]); + const sVId = paramOb.viewId.split(/[-_]+/) + ids.push(sVId[sVId.length - 1]) } } } } - const rootUrl = this.$location.absUrl().split('#')[0]; - let fragment = ids.join('-'); - fragment = fragment.endsWith('-') ? fragment.substring(0, fragment.length - 1) : fragment; - return `${rootUrl}#/s/${fragment}`; - }; + const rootUrl = this.$location.absUrl().split('#')[0] + let fragment = ids.join('-') + fragment = fragment.endsWith('-') ? fragment.substring(0, fragment.length - 1) : fragment + return `${rootUrl}#/s/${fragment}` + } public copyToClipboard(target: JQuery, $event: JQuery.ClickEvent): VePromise { - const shortUrlEl = target.find('#ve-short-url'); - return this.applicationSvc.copyToClipboard(shortUrlEl, $event); + const shortUrlEl = target.find('#ve-short-url') + return this.applicationSvc.copyToClipboard(shortUrlEl, $event) } } -veUtils.service('ShortUrlService', ShortUrlService); +veUtils.service('ShortUrlService', ShortUrlService) diff --git a/src/ve-utils/application/Utils.service.ts b/src/ve-utils/application/Utils.service.ts index 503145755..3675f14e0 100644 --- a/src/ve-utils/application/Utils.service.ts +++ b/src/ve-utils/application/Utils.service.ts @@ -1,20 +1,20 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { ApiService, DocumentMetadata, URLService } from '@ve-utils/mms-api-client'; +import { ApiService, DocumentMetadata, URLService } from '@ve-utils/mms-api-client' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; -import { ElementObject, ViewObject } from '@ve-types/mms'; -import { TreeBranch } from '@ve-types/tree'; +import { VePromise, VeQService } from '@ve-types/angular' +import { ElementObject, ViewObject } from '@ve-types/mms' +import { TreeBranch } from '@ve-types/tree' export interface TOCHtmlObject { - equations: string; - tables: string; - figures: string; - tableCount: number; - equationCount: number; - figureCount: number; + equations: string + tables: string + figures: string + tableCount: number + equationCount: number + figureCount: number } /** @@ -27,7 +27,7 @@ export interface TOCHtmlObject { * * Utilities */ export class UtilsService { - static $inject = ['$q', '$http', 'URLService', 'ApiService']; + static $inject = ['$q', '$http', 'URLService', 'ApiService'] constructor( private $q: VeQService, @@ -44,11 +44,11 @@ export class UtilsService { * @returns {string} toc string */ public makeHtmlTOC = (rootBranch: TreeBranch): string => { - let result = '

    Table of Contents

    '; - result += this.makeHtmlTOCChild(rootBranch, true); - result += '
    '; - return result; - }; + let result = '

    Table of Contents

    ' + result += this.makeHtmlTOCChild(rootBranch, true) + result += '
    ' + return result + } /** * @name veUtils/UtilsService#makeHtmlTOCChild @@ -58,30 +58,30 @@ export class UtilsService { * @return {string} */ public makeHtmlTOCChild = (branch: TreeBranch, skip?): string => { - let result = ''; + let result = '' if (!skip) { - const anchor: string = ''; - result += `
  • ${anchor}${branch.data._veNumber} ${branch.data.name}`; + const anchor: string = '' + result += `
  • ${anchor}${branch.data._veNumber} ${branch.data.name}` } - let ulAdded = false; + let ulAdded = false for (const child of branch.children) { if (child.type !== 'view' && child.type !== 'section') { - continue; + continue } if (!ulAdded) { - result += '
      '; - ulAdded = true; + result += '
        ' + ulAdded = true } - result += this.makeHtmlTOCChild(child); + result += this.makeHtmlTOCChild(child) } if (ulAdded) { - result += '
      '; + result += '
    ' } if (!skip) { - result += '
  • '; + result += '' } - return result; - }; + return result + } /** * @name veUtils/UtilsService#makeTablesAndFiguresTOC @@ -108,27 +108,27 @@ export class UtilsService { tableCount: 0, figureCount: 0, equationCount: 0, - }; + } // If both "Generate List of Tables and Figures" && "Use HTML for List of Tables and Figures " options are checked... if (html) { - ob = this.generateTOCHtmlOption(ob, rootBranch, printElement); + ob = this.generateTOCHtmlOption(ob, rootBranch, printElement) // return obHTML; } else { for (let i = 0; i < rootBranch.children.length; i++) { - this.makeTablesAndFiguresTOCChild(rootBranch.children[i], printElement, ob, live, false); + this.makeTablesAndFiguresTOCChild(rootBranch.children[i], printElement, ob, live, false) } } ob.tables = ob.tables.length ? '

    List of Tables

      ' + ob.tables + '
    ' - : ''; + : '' ob.figures = ob.figures.length ? '

    List of Figures

      ' + ob.figures + '
    ' - : ''; + : '' ob.equations = ob.equations.length ? '

    List of Equations

      ' + ob.equations + '
    ' - : ''; - return ob; + : '' + return ob } /** @@ -149,153 +149,153 @@ export class UtilsService { live: boolean, showRefName: boolean ): void { - const pe = child.data; - const sysmlId = pe.id; - const veNumber = pe._veNumber; - let prefix = ''; - const el = printElement.find('#' + sysmlId); + const pe = child.data + const sysmlId = pe.id + const veNumber = pe._veNumber + let prefix = '' + const el = printElement.find('#' + sysmlId) const refs = printElement.find( 'mms-view-link[mms-pe-id="' + sysmlId + '"], mms-view-link[data-mms-pe-id="' + sysmlId + '"]' - ); - let cap = ''; - let name = ''; + ) + let cap = '' + let name = '' if (child.type === 'table') { - ob.tableCount++; - prefix = 'Table ' + veNumber + '. '; - const capTbl = el.find('table > caption'); - name = capTbl.text(); + ob.tableCount++ + prefix = 'Table ' + veNumber + '. ' + const capTbl = el.find('table > caption') + name = capTbl.text() if (name !== '' && name.indexOf('Table') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length); + name = name.substring(name.indexOf(prefix) + prefix.length) } else if (name === '') { - name = pe.name; + name = pe.name } - cap = veNumber + '. ' + name; - ob.tables += '
  • ' + cap + '
  • '; - capTbl.html('Table ' + cap); + cap = veNumber + '. ' + name + ob.tables += '
  • ' + cap + '
  • ' + capTbl.html('Table ' + cap) // If caption does not exist, add to html if (capTbl.length === 0) { - el.find('table').prepend('Table ' + cap + ''); + el.find('table').prepend('Table ' + cap + '') } // Change cap value based on showRefName true/false if (!showRefName) { - cap = veNumber; + cap = veNumber } if (!live) { - refs.find('a').attr('href', '#' + sysmlId); + refs.find('a').attr('href', '#' + sysmlId) } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Table ' + cap); + .html('Table ' + cap) } if (child.type === 'figure') { - ob.figureCount++; - prefix = 'Figure ' + veNumber + '. '; - const capFig = el.find('figure > figcaption'); - name = capFig.text(); + ob.figureCount++ + prefix = 'Figure ' + veNumber + '. ' + const capFig = el.find('figure > figcaption') + name = capFig.text() if (name !== '' && name.indexOf('Figure') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length); + name = name.substring(name.indexOf(prefix) + prefix.length) } else if (name === '') { - name = pe.name; + name = pe.name } - cap = veNumber + '. ' + name; - ob.figures += '
  • ' + cap + '
  • '; - capFig.html('Figure ' + cap); + cap = veNumber + '. ' + name + ob.figures += '
  • ' + cap + '
  • ' + capFig.html('Figure ' + cap) // If caption does not exist, add to html if (capFig.length === 0) { el.find('img') .wrap('
    ') - .after('
    Figure ' + cap + '
    '); + .after('
    Figure ' + cap + '
    ') } // Change cap value based on showRefName true/false if (!showRefName) { - cap = veNumber; + cap = veNumber } if (!live) { - refs.find('a').attr('href', '#' + sysmlId); + refs.find('a').attr('href', '#' + sysmlId) } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Fig. ' + cap); + .html('Fig. ' + cap) } if (child.type === 'equation') { - ob.equationCount++; - cap = veNumber + '. ' + pe.name; - ob.equations += '
  • ' + cap + '
  • '; - const equationCap = '(' + veNumber + ')'; - const capEq = el.find('.caption-type-equation'); - capEq.html(equationCap); + ob.equationCount++ + cap = veNumber + '. ' + pe.name + ob.equations += '
  • ' + cap + '
  • ' + const equationCap = '(' + veNumber + ')' + const capEq = el.find('.caption-type-equation') + capEq.html(equationCap) // If caption does not exist, add to html if (capEq.length === 0) { el.find('present-equation > transclude > transclude-doc > p') .last() - .append('' + equationCap + ''); + .append('' + equationCap + '') } if (!live) { - refs.find('a').attr('href', '#' + sysmlId); + refs.find('a').attr('href', '#' + sysmlId) } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Eq. ' + equationCap); + .html('Eq. ' + equationCap) } for (let i = 0; i < child.children.length; i++) { - this.makeTablesAndFiguresTOCChild(child.children[i], printElement, ob, live, showRefName); + this.makeTablesAndFiguresTOCChild(child.children[i], printElement, ob, live, showRefName) } } public addLiveNumbering(pe: ViewObject, el: JQuery, type: string): void { - const veNumber = pe._veNumber; + const veNumber = pe._veNumber if (!veNumber) { - return; + return } - let prefix = ''; - let name = ''; - let cap = ''; + let prefix = '' + let name = '' + let cap = '' if (type === 'table') { - prefix = 'Table ' + veNumber + '. '; - const capTbl = el.find('table > caption'); - name = capTbl.text(); + prefix = 'Table ' + veNumber + '. ' + const capTbl = el.find('table > caption') + name = capTbl.text() if (name !== '' && name.indexOf('Table') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length); + name = name.substring(name.indexOf(prefix) + prefix.length) } else if (name === '') { - name = pe.name; + name = pe.name } - cap = veNumber + '. ' + name; - capTbl.html('Table ' + cap); + cap = veNumber + '. ' + name + capTbl.html('Table ' + cap) // If caption does not exist, add to html if (capTbl.length === 0) { - el.find('table').prepend('Table ' + cap + ''); + el.find('table').prepend('Table ' + cap + '') } } if (type === 'figure') { - prefix = 'Figure ' + veNumber + '. '; - const capFig = el.find('figure > figcaption'); - name = capFig.text(); + prefix = 'Figure ' + veNumber + '. ' + const capFig = el.find('figure > figcaption') + name = capFig.text() if (name !== '' && name.indexOf('Figure') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length); + name = name.substring(name.indexOf(prefix) + prefix.length) } else if (name === '') { - name = pe.name; + name = pe.name } - cap = veNumber + '. ' + name; - capFig.html('Figure ' + cap); + cap = veNumber + '. ' + name + capFig.html('Figure ' + cap) // If caption does not exist, add to html if (capFig.length === 0) { el.find('img') .wrap('
    ') - .after('
    Figure ' + cap + '
    '); + .after('
    Figure ' + cap + '
    ') } } if (type === 'equation') { - const equationCap = '(' + veNumber + ')'; - const capEq = el.find('.caption-type-equation'); - capEq.html(equationCap); + const equationCap = '(' + veNumber + ')' + const capEq = el.find('.caption-type-equation') + capEq.html(equationCap) // If caption does not exist, add to html if (capEq.length === 0) { el.find('present-equation > mms-cf > transclude-doc > p') .last() - .append('' + equationCap + ''); + .append('' + equationCap + '') } } } @@ -308,8 +308,8 @@ export class UtilsService { * @returns {string} unique ID wit prefix, tbl_ or fig_ */ public generateAnchorId = (prefix: string): string => { - return `${prefix}${this.apiSvc.createUniqueId()}`; - }; + return `${prefix}${this.apiSvc.createUniqueId()}` + } /** * @name veUtils/UtilsService#generateTOCHtmlOption @@ -327,52 +327,52 @@ export class UtilsService { ): TOCHtmlObject { // Grab all existing tables and figures inside the center pane, and assign them to tables and figures const tables = printElement.find('table'), - figures = printElement.find('figure'); + figures = printElement.find('figure') // equations = printElement.find('.math-tex'); let anchorId = '', thisCap = '', tblCap: JQuery, tbl: JQuery, - fig: JQuery; + fig: JQuery - ob.tableCount = tables.length; - ob.figureCount = figures.length; + ob.tableCount = tables.length + ob.figureCount = figures.length // Tables for (let j = 0; j < tables.length; j++) { - tbl = $(tables[j]); - tblCap = $('caption', tbl); + tbl = $(tables[j]) + tblCap = $('caption', tbl) // Set the link from the List of Tables to the actual tables - anchorId = this.generateAnchorId('tbl_'); - tbl.attr('id', anchorId); + anchorId = this.generateAnchorId('tbl_') + tbl.attr('id', anchorId) // Append li to the List of Tables - thisCap = tblCap && tblCap.text() !== '' ? `${j + 1}. ${tblCap.text()}` : `${j + 1}. `; - ob.tables += '
  • ' + thisCap + '
  • '; + thisCap = tblCap && tblCap.text() !== '' ? `${j + 1}. ${tblCap.text()}` : `${j + 1}. ` + ob.tables += '
  • ' + thisCap + '
  • ' // If no caption exists, add empty caption for numbering if (tblCap.length === 0) { - tbl.prepend(' '); + tbl.prepend(' ') } } // Figures for (let j = 0; j < figures.length; j++) { - fig = $(figures[j]); - const figcap = $('figcaption', fig); + fig = $(figures[j]) + const figcap = $('figcaption', fig) // Set the link from the List of Tables to the actual tables - anchorId = this.generateAnchorId('fig_'); - fig.attr('id', anchorId); + anchorId = this.generateAnchorId('fig_') + fig.attr('id', anchorId) // Append li to the List of Figures - thisCap = figcap && figcap.text() !== '' ? `${j + 1}. ${figcap.text()}` : `${j + 1}`; - ob.figures += '
  • ' + thisCap + '
  • '; + thisCap = figcap && figcap.text() !== '' ? `${j + 1}. ${figcap.text()}` : `${j + 1}` + ob.figures += '
  • ' + thisCap + '
  • ' // If no caption exists, add empty caption for numbering if (figcap.length === 0) { - fig.append('
     
    '); + fig.append('
     
    ') } } @@ -391,7 +391,7 @@ export class UtilsService { // eq.append(' '); // } // } - return ob; + return ob } /** @@ -403,17 +403,17 @@ export class UtilsService { */ public convertViewLinks(printElement: JQuery): void { printElement.find('mms-view-link').each((index) => { - const $this = $(this); - let elementId = $this.attr('mms-element-id') || $this.attr('data-mms-element-id'); + const $this = $(this) + let elementId = $this.attr('mms-element-id') || $this.attr('data-mms-element-id') if (!elementId) { - return; + return } - elementId = elementId.replace(/[^\w\-]/gi, ''); - const isElementInDoc = printElement.find('#' + elementId); + elementId = elementId.replace(/[^\w\-]/gi, '') + const isElementInDoc = printElement.find('#' + elementId) if (isElementInDoc.length) { - $this.find('a').attr('href', '#' + elementId); + $this.find('a').attr('href', '#' + elementId) } - }); + }) } /** @@ -531,10 +531,10 @@ p, div {widows: 2; orphans: 2;} /*------------------------------------------------------------------ 8. Signature Box -`; +` for (let i = 1; i < 10; i++) { ret += `.h${i} {bookmark-level: ${i};} -`; +` } if (htmlFlag) { ret += ` @@ -543,27 +543,27 @@ figure { counter-increment: figure-counter; } figcaption::before {content: "Figure " counter(figure-counter) ". "; } table { counter-increment: table-counter; } caption::before {content: "Table " counter(table-counter) ". "; } -`; +` } if (meta) { Object.keys(meta).forEach((key) => { if (meta[key]) { - let content: string; + let content: string if (meta[key] === 'counter(page)') { - content = meta[key] as string; + content = meta[key] as string } else { - content = `"${(meta[key] as string | number).toString()}"`; + content = `"${(meta[key] as string | number).toString()}"` } ret += `@page {@${key} {font-size: 9px; content: ${content};}} -`; +` } - }); + }) } if (landscape) { - ret += '@page {size: 11in 8.5in;}'; + ret += '@page {size: 11in 8.5in;}' } - return ret; - }; + return ret + } /** * @name veUtils/UtilsService#exportHtmlAs @@ -576,25 +576,25 @@ caption::before {content: "Table " counter(table-counter) ". "; } public exportHtmlAs( exportType: number, data: { - htmlString: string; - name: string; - projectId: string; - refId: string; - css: string; + htmlString: string + name: string + projectId: string + refId: string + css: string } ): VePromise { - let accept: string; + let accept: string switch (exportType) { case 2: - accept = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; - break; + accept = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + break case 3: - accept = 'application/pdf'; - break; + accept = 'application/pdf' + break default: - accept = 'application/pdf'; + accept = 'application/pdf' } - const deferred = this.$q.defer(); + const deferred = this.$q.defer() this.$http .post( this.uRLSvc.getExportHtmlUrl(), @@ -609,31 +609,31 @@ caption::before {content: "Table " counter(table-counter) ". "; } ) .then( (data2) => { - const blob = new Blob([data2.data as BlobPart], { type: accept }); - const a = window.document.createElement('a'); - const url = window.URL.createObjectURL(blob); - a.href = url; - a.download = data.name + (exportType == 2 ? '.docx' : '.pdf'); - a.click(); - window.URL.revokeObjectURL(url); - deferred.resolve('ok'); + const blob = new Blob([data2.data as BlobPart], { type: accept }) + const a = window.document.createElement('a') + const url = window.URL.createObjectURL(blob) + a.href = url + a.download = data.name + (exportType == 2 ? '.docx' : '.pdf') + a.click() + window.URL.revokeObjectURL(url) + deferred.resolve('ok') }, (error: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(error)); + deferred.reject(this.uRLSvc.handleHttpStatus(error)) } - ); - return deferred.promise; + ) + return deferred.promise } public getElementTypeClass = (element: ElementObject, elementType: string): string => { - let elementTypeClass = ''; + let elementTypeClass = '' if (element.type === 'InstanceSpecification') { - elementTypeClass = 'pe-type-' + _.kebabCase(elementType); + elementTypeClass = 'pe-type-' + _.kebabCase(elementType) } else { - elementTypeClass = 'item-type-' + _.kebabCase(elementType); + elementTypeClass = 'item-type-' + _.kebabCase(elementType) } - return elementTypeClass; - }; + return elementTypeClass + } } -veUtils.service('UtilsService', UtilsService); +veUtils.service('UtilsService', UtilsService) diff --git a/src/ve-utils/application/index.ts b/src/ve-utils/application/index.ts index b31dfe142..e19d6419d 100644 --- a/src/ve-utils/application/index.ts +++ b/src/ve-utils/application/index.ts @@ -1,15 +1,15 @@ -import './RootScope.service'; -import './Application.service'; -import './Branding.service'; -import './Math.service'; -import './ShortUrl.service'; -import './Utils.service'; -import './Image.service'; +import './RootScope.service' +import './Application.service' +import './Branding.service' +import './Math.service' +import './ShortUrl.service' +import './Utils.service' +import './Image.service' -export * from './RootScope.service'; -export * from './Application.service'; -export * from './Branding.service'; -export * from './Math.service'; -export * from './ShortUrl.service'; -export * from './Utils.service'; -export * from './Image.service'; +export * from './RootScope.service' +export * from './Application.service' +export * from './Branding.service' +export * from './Math.service' +export * from './ShortUrl.service' +export * from './Utils.service' +export * from './Image.service' diff --git a/src/ve-utils/core/Cache.service.ts b/src/ve-utils/core/Cache.service.ts index 9bd9d5fbc..9333b8a99 100644 --- a/src/ve-utils/core/Cache.service.ts +++ b/src/ve-utils/core/Cache.service.ts @@ -1,40 +1,40 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { ElementObject, MmsObject } from '@ve-types/mms'; +import { ElementObject, MmsObject } from '@ve-types/mms' export class CacheService { - public cache: { [key: string]: string | unknown | unknown[] } = {}; + public cache: { [key: string]: string | unknown | unknown[] } = {} - static $inject = []; + static $inject = [] get(key: string | string[], noCopy?: boolean): T | undefined { - const realKey: string = this._makeKey(key); - const result: T = this._get(realKey); + const realKey: string = this._makeKey(key) + const result: T = this._get(realKey) - return result; + return result //else return _.cloneDeep(result) } private _get = (realKey: string): T => { const recurse = (key: string): string | T => { if (typeof this.cache[key] === 'string') { - return recurse(this.cache[key] as string); + return recurse(this.cache[key] as string) } - return this.cache[key] as T; - }; + return this.cache[key] as T + } if (this.cache.hasOwnProperty(realKey)) { - let result: T; + let result: T if (typeof this.cache[realKey] === 'string') { - result = recurse(this.cache[realKey] as string) as T; + result = recurse(this.cache[realKey] as string) as T } else { - result = this.cache[realKey] as T; + result = this.cache[realKey] as T } - return result; + return result } - return; - }; + return + } /** * @name CacheService#getElements @@ -45,10 +45,10 @@ export class CacheService { * @returns {Object} Value if found, empty array if not found */ getLatestElements(projectId: string, refId: string): T[] { - const latestElements: T[] = []; + const latestElements: T[] = [] for (const key in this.cache) { if (!this.cache.hasOwnProperty(key)) { - continue; + continue } if ( key.indexOf('|latest') >= 0 && @@ -58,13 +58,13 @@ export class CacheService { key.indexOf(refId) >= 0 && key.indexOf(projectId) >= 0 ) { - const val: T | T[] = this._get(key); + const val: T | T[] = this._get(key) if (val) { - Array.isArray(val) ? latestElements.push(...val) : latestElements.push(val); + Array.isArray(val) ? latestElements.push(...val) : latestElements.push(val) } } } - return latestElements; + return latestElements } /** @@ -77,29 +77,29 @@ export class CacheService { * @returns {Object} the original value */ put(key: string | string[], value: T, merge?: boolean): T { - const m = typeof merge === 'undefined' ? false : merge; - const realKey = this._makeKey(key); - let currentValue: T = this.get(realKey, true); + const m = typeof merge === 'undefined' ? false : merge + const realKey = this._makeKey(key) + let currentValue: T = this.get(realKey, true) if (currentValue && m) { _.mergeWith(currentValue, value, (a: unknown, b: unknown, id: string) => { if ((id === '_contents' || id === 'specification') && b && (b as ElementObject).type === 'Expression') { - return b; + return b } if (Array.isArray(a) && Array.isArray(b) && b.length < a.length) { - a.length = 0; - a.push(...(b as unknown[])); - return a as unknown[]; + a.length = 0 + a.push(...(b as unknown[])) + return a as unknown[] } if (id === '_displayedElementIds' && b) { - return b; + return b } - return undefined; - }); + return undefined + }) } else { - this.cache[realKey] = value; - currentValue = value; + this.cache[realKey] = value + currentValue = value } - return currentValue; + return currentValue } /** @@ -110,12 +110,12 @@ export class CacheService { * @param {string | string[]} targetKey */ public link(sourceKey: string | string[], targetKey: string | string[]): void { - const realSourceKey: string = this._makeKey(sourceKey); + const realSourceKey: string = this._makeKey(sourceKey) if (this.cache.hasOwnProperty(realSourceKey) && typeof this.cache[realSourceKey] !== 'string') { - delete this.cache[realSourceKey]; + delete this.cache[realSourceKey] } - this.cache[realSourceKey] = this._makeKey(targetKey); + this.cache[realSourceKey] = this._makeKey(targetKey) } /** @@ -126,21 +126,21 @@ export class CacheService { * @returns {Object} value that was removed or undefined */ remove(key: string | string[]): T { - let realKey: string; + let realKey: string if (Array.isArray(key)) { - realKey = this._makeKey(key); + realKey = this._makeKey(key) } else { - realKey = key; + realKey = key } if (!this.cache.hasOwnProperty(realKey)) { - return null; + return null } - const removed = this.cache[realKey]; - delete this.cache[realKey]; + const removed = this.cache[realKey] + delete this.cache[realKey] if (typeof removed === 'string') { - return this.remove(removed); + return this.remove(removed) } - return removed as T; + return removed as T } /** @@ -151,39 +151,39 @@ export class CacheService { * @returns {boolean} whether value exists for key */ exists(key: string | string[]): boolean { - let realKey = ''; + let realKey = '' if (Array.isArray(key)) { - realKey = this._makeKey(key); + realKey = this._makeKey(key) } else { - realKey = key; + realKey = key } if (!this.cache.hasOwnProperty(realKey)) { - return false; + return false } - const val = this.cache[realKey]; + const val = this.cache[realKey] if (typeof val === 'object') { - return true; + return true } if (typeof val === 'string') { - return this.exists(val); + return this.exists(val) } - return false; + return false } private _makeKey(keys: string | string[]): string { if (Array.isArray(keys)) { - return keys.join('|'); + return keys.join('|') } else { - return keys; + return keys } } reset = (): void => { - const keys = Object.keys(this.cache); + const keys = Object.keys(this.cache) for (let i = 0; i < keys.length; i++) { - delete this.cache[keys[i]]; + delete this.cache[keys[i]] } - }; + } } -veUtils.service('CacheService', CacheService); +veUtils.service('CacheService', CacheService) diff --git a/src/ve-utils/core/Edit.service.ts b/src/ve-utils/core/Edit.service.ts index fc6adc076..b686862c3 100644 --- a/src/ve-utils/core/Edit.service.ts +++ b/src/ve-utils/core/Edit.service.ts @@ -1,75 +1,75 @@ -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { EventService } from './Event.service'; +import { EventService } from './Event.service' -import { ElementObject, ValueObject } from '@ve-types/mms'; +import { ElementObject, ValueObject } from '@ve-types/mms' export interface EditObject { - element: T; - values?: ValueObject[]; - key: string; + element: T + values?: ValueObject[] + key: string } export class EditService { - private edits: { [editKey: string]: EditObject } = {}; + private edits: { [editKey: string]: EditObject } = {} - public EVENT = 've-edits'; + public EVENT = 've-edits' - static $inject = ['EventService']; + static $inject = ['EventService'] constructor(private eventSvc: EventService) {} trigger = (): void => { - this.eventSvc.$broadcast(this.EVENT); - }; + this.eventSvc.$broadcast(this.EVENT) + } get(key: string | string[]): EditObject { - key = this.makeKey(key); - return this.edits[key] as EditObject; + key = this.makeKey(key) + return this.edits[key] as EditObject } getAll(): { [key: string]: EditObject } { - return this.edits; + return this.edits } openEdits = (): number => { - return Object.keys(this.edits).length; - }; + return Object.keys(this.edits).length + } addOrUpdate = (key: string | string[], data: ElementObject, overwrite?: boolean): EditObject => { - key = this.makeKey(key); + key = this.makeKey(key) if (overwrite) { - delete this.edits[key]; + delete this.edits[key] } - this.edits[key] = { key, element: data }; + this.edits[key] = { key, element: data } - this.trigger(); - return this.edits[key]; - }; + this.trigger() + return this.edits[key] + } remove = (key: string | string[]): void => { - key = this.makeKey(key); + key = this.makeKey(key) if (this.edits[key]) { - delete this.edits[key]; - this.trigger(); + delete this.edits[key] + this.trigger() } - }; + } // getKey(): string {} reset = (): void => { - const keys = Object.keys(this.edits); + const keys = Object.keys(this.edits) for (let i = 0; i < keys.length; i++) { - delete this.edits[keys[i]]; + delete this.edits[keys[i]] } - }; + } public makeKey(keys: string | string[]): string { if (Array.isArray(keys)) { - return keys.join('|'); + return keys.join('|') } else { - return keys; + return keys } } } -veUtils.service('EditService', EditService); +veUtils.service('EditService', EditService) diff --git a/src/ve-utils/core/Event.service.ts b/src/ve-utils/core/Event.service.ts index 8a9230be0..bbc257ade 100644 --- a/src/ve-utils/core/Event.service.ts +++ b/src/ve-utils/core/Event.service.ts @@ -1,62 +1,62 @@ -import Rx from 'rx-lite'; +import Rx from 'rx-lite' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -export type eventHandlerFn = (data: T) => void; +export type eventHandlerFn = (data: T) => void export class EventService { - private subjects: { [key: string]: Rx.ISubject } = {}; - private bindings: { [key: string]: Rx.ISubject } = {}; + private subjects: { [key: string]: Rx.ISubject } = {} + private bindings: { [key: string]: Rx.ISubject } = {} //API - public $broadcast = (name: string, data?: T): void => this.emit(name, data); - public $on = (name: string, handler: eventHandlerFn): Rx.IDisposable => this.listen(name, handler); - public $destroy = (subs: Rx.IDisposable[]): void => this.destroy(subs); - public $init = (ctrl: { subs: Rx.IDisposable[] } & angular.IComponentController): void => this.initEventSvc(ctrl); + public $broadcast = (name: string, data?: T): void => this.emit(name, data) + public $on = (name: string, handler: eventHandlerFn): Rx.IDisposable => this.listen(name, handler) + public $destroy = (subs: Rx.IDisposable[]): void => this.destroy(subs) + public $init = (ctrl: { subs: Rx.IDisposable[] } & angular.IComponentController): void => this.initEventSvc(ctrl) createName = (name: string): string => { - return `$ ${name}`; - }; + return `$ ${name}` + } resolve(name: string, data?: T): void { - const fnName = this.createName(name); + const fnName = this.createName(name) //$rootScope.$broadcast(name,data); if (!this.bindings[fnName]) { - this.bindings[fnName] = new Rx.BehaviorSubject(data); + this.bindings[fnName] = new Rx.BehaviorSubject(data) } else { - this.bindings[fnName].onNext(data); + this.bindings[fnName].onNext(data) } } binding(name: string, handler: eventHandlerFn): Rx.IDisposable { - const fnName = this.createName(name); + const fnName = this.createName(name) if (!this.bindings[fnName]) { - throw Error('Binding ' + name + ' subscribed before initialization!'); + throw Error('Binding ' + name + ' subscribed before initialization!') } - return this.bindings[fnName].subscribe(handler); + return this.bindings[fnName].subscribe(handler) } emit(name: string, data?: T): void { - const fnName = this.createName(name); + const fnName = this.createName(name) //$rootScope.$broadcast(name,data); if (!this.subjects[fnName]) { - this.subjects[fnName] = new Rx.Subject(); + this.subjects[fnName] = new Rx.Subject() } - this.subjects[fnName].onNext(data); + this.subjects[fnName].onNext(data) } listen(name: string, handler: eventHandlerFn): Rx.IDisposable { - const fnName = this.createName(name); + const fnName = this.createName(name) if (!this.subjects[fnName]) { - this.subjects[fnName] = new Rx.Subject(); + this.subjects[fnName] = new Rx.Subject() } - return this.subjects[fnName].subscribe(handler); + return this.subjects[fnName].subscribe(handler) } destroy(subs: Rx.IDisposable[]): void { if (subs.length > 0) { for (let i = 0; i < subs.length; i++) { if (typeof subs[i].dispose === 'function') { - subs[i].dispose(); + subs[i].dispose() } } } @@ -64,21 +64,21 @@ export class EventService { initEventSvc( componentOrScope: { - subs: Rx.IDisposable[]; + subs: Rx.IDisposable[] } & angular.IComponentController ): void { - componentOrScope.subs = []; + componentOrScope.subs = [] if (!componentOrScope.$onDestroy) { componentOrScope.$onDestroy = (): void => { - this.destroy(componentOrScope.subs); - }; + this.destroy(componentOrScope.subs) + } } } exists(eventOrBinding: string): boolean { - const name = this.createName(eventOrBinding); - return this.subjects.hasOwnProperty(name) || this.bindings.hasOwnProperty(name); + const name = this.createName(eventOrBinding) + return this.subjects.hasOwnProperty(name) || this.bindings.hasOwnProperty(name) } } -veUtils.service('EventService', EventService); +veUtils.service('EventService', EventService) diff --git a/src/ve-utils/core/Session.service.ts b/src/ve-utils/core/Session.service.ts index a4f4dd36a..81c584050 100644 --- a/src/ve-utils/core/Session.service.ts +++ b/src/ve-utils/core/Session.service.ts @@ -1,50 +1,50 @@ -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { EventService } from './Event.service'; +import { EventService } from './Event.service' export class SessionService { - static $inject = ['EventService']; + static $inject = ['EventService'] constructor(private eventSvc: EventService) {} private static _setStorage(key: string, realValue: T): void { - const value = realValue == null ? null : JSON.stringify(realValue); - sessionStorage.setItem(key, value); + const value = realValue == null ? null : JSON.stringify(realValue) + sessionStorage.setItem(key, value) } private static _getStorage(key: string): T { - const sessionValue = sessionStorage.getItem(key); + const sessionValue = sessionStorage.getItem(key) if (sessionValue === null) { - return null; + return null } else { - return JSON.parse(sessionValue) as T; + return JSON.parse(sessionValue) as T } } private static _removeStorage(key: string): void { - sessionStorage.removeItem(key); + sessionStorage.removeItem(key) } public clear = (): void => { - sessionStorage.clear(); - }; + sessionStorage.clear() + } public accessor = (name: string, value: T, defaultValue: T = null): T => { if (value === undefined) { - let val = SessionService._getStorage(name); + let val = SessionService._getStorage(name) if (val == null) { - val = defaultValue; - SessionService._setStorage(name, val); + val = defaultValue + SessionService._setStorage(name, val) } if (!this.eventSvc.exists(name)) { - this.eventSvc.resolve(name, val); + this.eventSvc.resolve(name, val) } - return val; + return val } - this.eventSvc.resolve(name, value); - SessionService._setStorage(name, value); - return value; - }; + this.eventSvc.resolve(name, value) + SessionService._setStorage(name, value) + return value + } } -veUtils.service('SessionService', SessionService); +veUtils.service('SessionService', SessionService) diff --git a/src/ve-utils/core/index.ts b/src/ve-utils/core/index.ts index 15fc54501..44d28a73e 100644 --- a/src/ve-utils/core/index.ts +++ b/src/ve-utils/core/index.ts @@ -1,9 +1,9 @@ -import './Cache.service'; -import './Edit.service'; -import './Event.service'; -import './Session.service'; +import './Cache.service' +import './Edit.service' +import './Event.service' +import './Session.service' -export * from './Cache.service'; -export * from './Edit.service'; -export * from './Event.service'; -export * from './Session.service'; +export * from './Cache.service' +export * from './Edit.service' +export * from './Event.service' +export * from './Session.service' diff --git a/src/ve-utils/index.ts b/src/ve-utils/index.ts index 7298c68d2..7ded81b91 100644 --- a/src/ve-utils/index.ts +++ b/src/ve-utils/index.ts @@ -1,15 +1,15 @@ //Libraries //import 'angular' -import './ve-utils.module'; +import './ve-utils.module' -import './third-party'; +import './third-party' -import './core'; -import './model-schema'; -import './application'; -import './mms-api-client'; +import './core' +import './model-schema' +import './application' +import './mms-api-client' -export * from './ve-utils.module'; +export * from './ve-utils.module' -export default 've-utils'; +export default 've-utils' diff --git a/src/ve-utils/mms-api-client/Api.service.ts b/src/ve-utils/mms-api-client/Api.service.ts index 28f621c3d..53ebf0c4a 100644 --- a/src/ve-utils/mms-api-client/Api.service.ts +++ b/src/ve-utils/mms-api-client/Api.service.ts @@ -1,13 +1,13 @@ -import _ from 'lodash'; -import * as uuid from 'uuid'; +import _ from 'lodash' +import * as uuid from 'uuid' -import { URLService } from '@ve-utils/mms-api-client/URL.service'; -import { SchemaService } from '@ve-utils/model-schema'; +import { URLService } from '@ve-utils/mms-api-client/URL.service' +import { SchemaService } from '@ve-utils/model-schema' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; -import { VeConfig } from '@ve-types/config'; +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { VeConfig } from '@ve-types/config' import { BasicResponse, ElementObject, @@ -20,7 +20,7 @@ import { ValueObject, VersionResponse, ViewObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' export class ApiService { private editKeys = [ @@ -34,13 +34,13 @@ export class ApiService { '_projectId', '_refId', 'type', - ]; + ] - schema: string = 'cameo'; + schema: string = 'cameo' - public veConfig: VeConfig = window.__env; + public veConfig: VeConfig = window.__env - static $inject = ['$q', '$http', 'URLService', 'SchemaService']; + static $inject = ['$q', '$http', 'URLService', 'SchemaService'] constructor( private $q: VeQService, @@ -50,21 +50,21 @@ export class ApiService { ) {} public getMmsVersion(): VePromise { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() this.$http.get(this.uRLSvc.getMmsVersionURL()).then( (response) => { - deferred.resolve(response.data.mmsVersion); + deferred.resolve(response.data.mmsVersion) }, (response: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(response)); + deferred.reject(this.uRLSvc.handleHttpStatus(response)) } - ); - return deferred.promise; + ) + return deferred.promise } public getVeVersion = (): string => { - return this.veConfig.version; - }; + return this.veConfig.version + } /** * @name veUtils/ApiService#handleErrorCallback @@ -78,14 +78,14 @@ export class ApiService { deferredOrReject: angular.IDeferred | angular.IQResolveReject>, type?: 'error' | 'warning' | 'info' ): void { - const res = this.uRLSvc.handleHttpStatus(response); + const res = this.uRLSvc.handleHttpStatus(response) if (type) { - res.type = type; + res.type = type } if ((deferredOrReject as angular.IDeferred).reject) { - (deferredOrReject as angular.IDeferred).reject(res); + ;(deferredOrReject as angular.IDeferred).reject(res) } else { - (deferredOrReject as angular.IQResolveReject>)(res); + ;(deferredOrReject as angular.IQResolveReject>)(res) } } @@ -98,13 +98,13 @@ export class ApiService { */ private _cleanValueSpec = (vs: ValueObject): void => { - if (vs.hasOwnProperty('valueExpression')) delete vs.valueExpression; + if (vs.hasOwnProperty('valueExpression')) delete vs.valueExpression if (vs.operand && Array.isArray(vs.operand)) { for (let i = 0; i < vs.operand.length; i++) { - this._cleanValueSpec(vs.operand[i] as ValueObject); + this._cleanValueSpec(vs.operand[i] as ValueObject) } } - }; + } /** * @name veUtils/UtilsService#cleanElement @@ -117,50 +117,50 @@ export class ApiService { public cleanElement(elem: T, forEdit?: boolean): T { if (elem.type === 'Property' || elem.type === 'Port') { if (!elem.defaultValue) { - elem.defaultValue = null; + elem.defaultValue = null } } if (elem.type === 'Slot') { - if (!Array.isArray(elem.value)) (elem as LiteralObject).value = []; + if (!Array.isArray(elem.value)) (elem as LiteralObject).value = [] } if (elem.value && Array.isArray(elem.value)) { - (elem as LiteralObject).value.forEach((value: unknown) => { + ;(elem as LiteralObject).value.forEach((value: unknown) => { if (typeof value === 'object' && value !== null) - this._cleanValueSpec(value as ExpressionObject); - }); + this._cleanValueSpec(value as ExpressionObject) + }) } if (elem._contents) { - this._cleanValueSpec((elem as ViewObject)._contents); + this._cleanValueSpec((elem as ViewObject)._contents) } if (elem.specification) { - this._cleanValueSpec((elem as InstanceSpecObject).specification); + this._cleanValueSpec((elem as InstanceSpecObject).specification) } if (elem.type === 'Class') { if (elem._contents && elem.contains) { - delete elem.contains; + delete elem.contains } if (elem._allowedElementIds) { - delete elem._allowedElementIds; + delete elem._allowedElementIds } } if (elem.hasOwnProperty('specialization')) { - delete elem.specialization; + delete elem.specialization } if (!elem.hasOwnProperty('appliedStereotypeIds') && elem._appliedStereotypeIds) { - elem.appliedStereotypeIds = elem._appliedStereotypeIds; + elem.appliedStereotypeIds = elem._appliedStereotypeIds } if (forEdit) { //only keep editable or needed keys in edit object instead of everything - const keys = Object.keys(elem); + const keys = Object.keys(elem) keys.forEach((key) => { if (this.editKeys.indexOf(key) >= 0) { - return; + return } - delete elem[key]; - }); + delete elem[key] + }) } - return elem; + return elem } /** @@ -171,10 +171,10 @@ export class ApiService { * @returns {RequestObject} with default values for ref and commit */ public normalize = (reqOb: RequestObject): RequestObject => { - reqOb.refId = !reqOb.refId ? 'master' : reqOb.refId; - reqOb.commitId = !reqOb.commitId ? 'latest' : reqOb.commitId; - return reqOb; - }; + reqOb.refId = !reqOb.refId ? 'master' : reqOb.refId + reqOb.commitId = !reqOb.commitId ? 'latest' : reqOb.commitId + return reqOb + } /** * @name veUtils/UtilsService#makeRequestObject @@ -188,8 +188,8 @@ export class ApiService { projectId: elementOb._projectId, refId: elementOb._refId, commitId: elementOb._commitId, - }; - }; + } + } /** * @name veUtils/UtilsService#makeElementRequestObject @@ -204,7 +204,7 @@ export class ApiService { projectId: elementOb._projectId, refId: elementOb._refId, commitId: elementOb._commitId, - }; + } } /** @@ -218,18 +218,18 @@ export class ApiService { * @returns {Array} key to be used in CacheService */ public makeCacheKey(reqOb: RequestObject | null, elementId: string, edit?: boolean, type?: string): string[] { - const key: string[] = []; - const keyType: string = type ? type : 'element'; - key.push(keyType); + const key: string[] = [] + const keyType: string = type ? type : 'element' + key.push(keyType) if (reqOb !== null) { - if (reqOb.projectId) key.push(reqOb.projectId); - if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId); + if (reqOb.projectId) key.push(reqOb.projectId) + if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId) if (!keyType.includes('history') && reqOb.commitId !== null) - key.push(!reqOb.commitId ? 'latest' : reqOb.commitId); + key.push(!reqOb.commitId ? 'latest' : reqOb.commitId) } - if (elementId !== '') key.push(elementId); - if (edit) key.push('edit'); - return key; + if (elementId !== '') key.push(elementId) + if (edit) key.push('edit') + return key } /** @@ -277,16 +277,16 @@ export class ApiService { i === '_created' || i === '_commitId' ) { - continue; + continue } if (edit.hasOwnProperty(i) && orig.hasOwnProperty(i) && server.hasOwnProperty(i)) { if (!_.isEqual(orig[i], server[i])) { - return true; + return true } } } - return false; - }; + return false + } /** * @name veUtils/UtilsService#isRestrictedValue @@ -320,8 +320,8 @@ export class ApiService { * */ public createUUID = (): string => { - return uuid.v4(); - }; + return uuid.v4() + } /** * @name veUtils/UtilsService#createUniqueId @@ -330,8 +330,8 @@ export class ApiService { * @returns {string} unique SysML element ID */ public createUniqueId = (): string => { - return `ve-${this.getVeVersion().replace(/\./g, '-')}-${this.createUUID()}`; - }; + return `ve-${this.getVeVersion().replace(/\./g, '-')}-${this.createUUID()}` + } /** * @name veUtils/UtilsService#isView @@ -346,17 +346,17 @@ export class ApiService { e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('VIEW_SID', this.schema)) >= 0 || e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('DOCUMENT_SID', this.schema)) >= 0 ) { - return true; + return true } - const otherViewSids: string[] = this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema); + const otherViewSids: string[] = this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema) for (const otherViewSid of otherViewSids) { if (e.appliedStereotypeIds.indexOf(otherViewSid) >= 0) { - return true; + return true } } } - return false; - }; + return false + } /** * @name veUtils/UtilsService#isDocument @@ -369,8 +369,8 @@ export class ApiService { return ( e.appliedStereotypeIds && e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('DOCUMENT_SID', this.schema)) >= 0 - ); - }; + ) + } /** * @name veUtils/UtilsService#isRequirement @@ -381,15 +381,15 @@ export class ApiService { */ public isRequirement = (e: ElementObject): boolean => { if (e.appliedStereotypeIds) { - const reqSids = this.schemaSvc.getSchema('REQUIREMENT_SID', this.schema); + const reqSids = this.schemaSvc.getSchema('REQUIREMENT_SID', this.schema) for (const reqSid of reqSids) { if (e.appliedStereotypeIds.indexOf(reqSid) >= 0) { - return true; + return true } } } - return false; - }; + return false + } } -veUtils.service('ApiService', ApiService); +veUtils.service('ApiService', ApiService) diff --git a/src/ve-utils/mms-api-client/Authorization.service.ts b/src/ve-utils/mms-api-client/Authorization.service.ts index da0b5ec12..85bb4a34b 100644 --- a/src/ve-utils/mms-api-client/Authorization.service.ts +++ b/src/ve-utils/mms-api-client/Authorization.service.ts @@ -1,10 +1,10 @@ -import { CacheService, EditService, SessionService } from '@ve-utils/core'; -import { ElementService, HttpService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client'; +import { CacheService, EditService, SessionService } from '@ve-utils/core' +import { ElementService, HttpService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; -import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms' /** * @ngdoc service @@ -19,7 +19,7 @@ import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms'; * * Provide general authorization functions. I.e. login, logout, etc... */ export class AuthService { - private token: string | null; + private token: string | null static $inject = [ '$q', '$http', @@ -31,7 +31,7 @@ export class AuthService { 'ProjectService', 'SessionService', 'EditService', - ]; + ] constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -44,64 +44,64 @@ export class AuthService { private sessionSvc: SessionService, private autosaveSvc: EditService ) { - this.token = localStorage.getItem('token'); + this.token = localStorage.getItem('token') } getAuthorized(credentialsJSON: AuthRequest): VePromise { - const deferred = this.$q.defer(); - const loginURL = this.uRLSvc.getAuthenticationUrl(); + const deferred = this.$q.defer() + const loginURL = this.uRLSvc.getAuthenticationUrl() this.$http.post(loginURL, credentialsJSON).then( (success) => { - this.uRLSvc.setToken(success.data.token); - this.token = success.data.token; - localStorage.setItem('token', this.token); - deferred.resolve(this.token); + this.uRLSvc.setToken(success.data.token) + this.token = success.data.token + localStorage.setItem('token', this.token) + deferred.resolve(this.token) }, (fail: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(fail)); + deferred.reject(this.uRLSvc.handleHttpStatus(fail)) } - ); - return deferred.promise; + ) + return deferred.promise } removeToken = (): void => { - localStorage.removeItem('token'); - this.token = undefined; - this.uRLSvc.setToken(null); - this.httpSvc.dropAll(); - this.elementSvc.reset(); - this.projectSvc.reset(); - this.viewSvc.reset(); - this.cacheSvc.reset(); - this.autosaveSvc.reset(); - this.sessionSvc.clear(); - }; + localStorage.removeItem('token') + this.token = undefined + this.uRLSvc.setToken(null) + this.httpSvc.dropAll() + this.elementSvc.reset() + this.projectSvc.reset() + this.viewSvc.reset() + this.cacheSvc.reset() + this.autosaveSvc.reset() + this.sessionSvc.clear() + } getToken = (): string => { - return this.token; - }; + return this.token + } checkLogin(): VePromise { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() if (!this.token) { - deferred.reject(false); - return deferred.promise; + deferred.reject(false) + return deferred.promise } - this.uRLSvc.setToken(this.token); + this.uRLSvc.setToken(this.token) this.$http.get(this.uRLSvc.getCheckTokenURL()).then( (response: angular.IHttpResponse) => { if (response.status === 401) { - deferred.reject(response); + deferred.reject(response) } else { - deferred.resolve(response.data); + deferred.resolve(response.data) } }, (fail) => { - deferred.reject(fail); - this.removeToken(); + deferred.reject(fail) + this.removeToken() } - ); - return deferred.promise; + ) + return deferred.promise } // async isAuthenticated(): Promise { @@ -125,22 +125,22 @@ export class AuthService { // } logout(): VePromise { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() this.checkLogin() .then( () => { - this.removeToken(); + this.removeToken() //$cookies.remove('com.tomsawyer.web.license.user'); }, () => { - this.removeToken(); + this.removeToken() } ) .finally(() => { - deferred.resolve(true); - }); - return deferred.promise; + deferred.resolve(true) + }) + return deferred.promise } } -veUtils.service('AuthService', AuthService); +veUtils.service('AuthService', AuthService) diff --git a/src/ve-utils/mms-api-client/Base.service.ts b/src/ve-utils/mms-api-client/Base.service.ts index f42ead346..fd017847a 100644 --- a/src/ve-utils/mms-api-client/Base.service.ts +++ b/src/ve-utils/mms-api-client/Base.service.ts @@ -1,32 +1,32 @@ -import { VePromise } from '@ve-types/angular'; -import { BasicResponse, MmsObject } from '@ve-types/mms'; +import { VePromise } from '@ve-types/angular' +import { BasicResponse, MmsObject } from '@ve-types/mms' export class BaseApiService { protected inProgress: { - [key: string]: VePromise>; - } = {}; + [key: string]: VePromise> + } = {} protected _isInProgress = (key: string): boolean => { - return this.inProgress.hasOwnProperty(key); - }; + return this.inProgress.hasOwnProperty(key) + } protected _getInProgress>(key: string): VePromise { - if (this._isInProgress(key)) return this.inProgress[key] as unknown as VePromise; - else return; + if (this._isInProgress(key)) return this.inProgress[key] as unknown as VePromise + else return } protected _addInProgress>( key: string, promise: VePromise ): void { - this.inProgress[key] = promise as unknown as VePromise>; + this.inProgress[key] = promise as unknown as VePromise> } protected _removeInProgress = (key: string): void => { - delete this.inProgress[key]; - }; + delete this.inProgress[key] + } public reset = (): void => { - this.inProgress = {}; - }; + this.inProgress = {} + } } diff --git a/src/ve-utils/mms-api-client/Element.service.ts b/src/ve-utils/mms-api-client/Element.service.ts index f0c83d5cb..b97b1ea90 100644 --- a/src/ve-utils/mms-api-client/Element.service.ts +++ b/src/ve-utils/mms-api-client/Element.service.ts @@ -1,12 +1,12 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { CacheService, EditObject, EditService } from '@ve-utils/core'; -import { ApiService, httpCallback, HttpService, URLService } from '@ve-utils/mms-api-client'; -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; +import { CacheService, EditObject, EditService } from '@ve-utils/core' +import { ApiService, httpCallback, HttpService, URLService } from '@ve-utils/mms-api-client' +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular'; +import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular' import { CommitObject, CommitResponse, @@ -21,7 +21,7 @@ import { RequestObject, SearchResponse, TaggedValueObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' /** * @ngdoc service @@ -35,7 +35,7 @@ import { * * An element CRUD service with additional convenience methods for managing edits. */ export class ElementService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'EditService', 'URLService', 'ApiService', 'HttpService']; + static $inject = ['$q', '$http', 'CacheService', 'EditService', 'URLService', 'ApiService', 'HttpService'] constructor( private $q: VeQService, @@ -46,7 +46,7 @@ export class ElementService extends BaseApiService { private apiSvc: ApiService, private httpSvc: HttpService ) { - super(); + super() } /** @@ -105,71 +105,71 @@ export class ElementService extends BaseApiService { refresh?: boolean, allowEmpty?: boolean ): VePromise { - this.apiSvc.normalize(reqOb); - const requestCacheKey = this.getRequestKey(reqOb, reqOb.elementId); + this.apiSvc.normalize(reqOb) + const requestCacheKey = this.getRequestKey(reqOb, reqOb.elementId) if (!reqOb.projectId) { - console.log('foo'); + console.log('foo') } - const url = this.uRLSvc.getElementURL(reqOb); - const cached: T = this.cacheSvc.get(requestCacheKey); + const url = this.uRLSvc.getElementURL(reqOb) + const cached: T = this.cacheSvc.get(requestCacheKey) // if it's in the this.inProgress queue get it immediately if (this._isInProgress(url)) { //change to change priority if it's already in the queue - this.httpSvc.ping(url, weight); - return this._getInProgress(url) as VePromise; + this.httpSvc.ping(url, weight) + return this._getInProgress(url) as VePromise } - const deletedRequestCacheKey = this.getRequestKey(reqOb, reqOb.elementId); - deletedRequestCacheKey.push('deleted'); - const deleted = this.cacheSvc.get(deletedRequestCacheKey); + const deletedRequestCacheKey = this.getRequestKey(reqOb, reqOb.elementId) + deletedRequestCacheKey.push('deleted') + const deleted = this.cacheSvc.get(deletedRequestCacheKey) if (deleted && !refresh) { return new this.$q((resolve, reject) => { return reject({ status: 410, recentVersionOfElement: deleted, message: 'Deleted', - }); - }); + }) + }) } if (cached && !refresh) { return new this.$q((resolve, reject) => { - return resolve(cached); - }); + return resolve(cached) + }) } this._addInProgress( url, new this.$q((resolve, reject) => { const successCallback: httpCallback> = (response) => { - const data = response.data; - this._removeInProgress(url); + const data = response.data + this._removeInProgress(url) if (Array.isArray(data.elements) && data.elements.length > 0) { - resolve(this.cacheElement(reqOb, data.elements[0])); + resolve(this.cacheElement(reqOb, data.elements[0])) } else if (allowEmpty) { - resolve(null); + resolve(null) } else { reject({ status: 500, message: 'Server Error: empty response', - }); //TODO + }) //TODO } - }; + } const errorCallback: httpCallback> = (response) => { - const data = response.data; - const reason = this.uRLSvc.handleHttpStatus(response); - this._removeInProgress(url); + const data = response.data + const reason = this.uRLSvc.handleHttpStatus(response) + this._removeInProgress(url) if (data && data.deleted && data.deleted.length > 0 && data.deleted[0].id === reqOb.elementId) { - reason.recentVersionOfElement = data.deleted[0]; - this.cacheDeletedElement(reqOb, data.deleted[0]); + reason.recentVersionOfElement = data.deleted[0] + this.cacheDeletedElement(reqOb, data.deleted[0]) } if (allowEmpty && response.status == 404) { - resolve(null); + resolve(null) } else { - reject(reason); + reject(reason) } - }; - this.httpSvc.get>(url, successCallback, errorCallback, weight); + } + this.httpSvc.get>(url, successCallback, errorCallback, weight) }) - ); - return this._getInProgress(url) as VePromise; + ) + return this._getInProgress(url) as VePromise } /** @@ -190,44 +190,44 @@ export class ElementService extends BaseApiService { refresh?: boolean ): VePromise> { return new this.$q>((resolve, reject) => { - const request: { elements: { id: string }[] } = { elements: [] }; - const existing: T[] = []; - this.apiSvc.normalize(reqOb); + const request: { elements: { id: string }[] } = { elements: [] } + const existing: T[] = [] + this.apiSvc.normalize(reqOb) for (let i = 0; i < reqOb.elementId.length; i++) { - const id = reqOb.elementId[i]; - const requestCacheKey = this.getRequestKey(reqOb, id); - const exist = this.cacheSvc.get(requestCacheKey); + const id = reqOb.elementId[i] + const requestCacheKey = this.getRequestKey(reqOb, id) + const exist = this.cacheSvc.get(requestCacheKey) if (exist && !refresh) { - existing.push(exist); - continue; + existing.push(exist) + continue } - request.elements.push({ id: id }); + request.elements.push({ id: id }) } if (request.elements.length === 0) { - resolve(existing); - return; + resolve(existing) + return } this.$http.put>(this.uRLSvc.getPutElementsURL(reqOb), request).then( (response) => { - const data = response.data.elements; - let i; + const data = response.data.elements + let i if (data && data.length > 0) { for (let i = 0; i < data.length; i++) { - existing.push(this.cacheElement(reqOb, data[i])); + existing.push(this.cacheElement(reqOb, data[i])) } } - const deleted = response.data.deleted; + const deleted = response.data.deleted if (deleted && deleted.length > 0) { for (let i = 0; i < deleted.length; i++) { - this.cacheDeletedElement(reqOb, deleted[i]); + this.cacheDeletedElement(reqOb, deleted[i]) } } - resolve(existing); + resolve(existing) }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ); - }); + ) + }) } /** @@ -242,45 +242,45 @@ export class ElementService extends BaseApiService { * @returns {object} cached object */ cacheElement(reqOb: RequestObject, elementOb: T): T { - let result: T = this.apiSvc.cleanElement(elementOb); - const requestCacheKey = this.getRequestKey(reqOb, result.id); - const origResultCommit = result._commitId; + let result: T = this.apiSvc.cleanElement(elementOb) + const requestCacheKey = this.getRequestKey(reqOb, result.id) + const origResultCommit = result._commitId if (reqOb.commitId === 'latest') { - const resultCommitCopy: T = _.cloneDeep(result); - result._commitId = 'latest'; //so realCacheKey is right later - const commitCacheKey = this.apiSvc.makeCacheKey(this.apiSvc.makeRequestObject(resultCommitCopy), result.id); //save historic element - this.cacheSvc.put(commitCacheKey, resultCommitCopy, true); + const resultCommitCopy: T = _.cloneDeep(result) + result._commitId = 'latest' //so realCacheKey is right later + const commitCacheKey = this.apiSvc.makeCacheKey(this.apiSvc.makeRequestObject(resultCommitCopy), result.id) //save historic element + this.cacheSvc.put(commitCacheKey, resultCommitCopy, true) } - const realCacheKey = this.getElementKey(result); - result._commitId = origResultCommit; //restore actual commitId + const realCacheKey = this.getElementKey(result) + result._commitId = origResultCommit //restore actual commitId if (!_.isEqual(realCacheKey, requestCacheKey)) { - this.cacheSvc.link(requestCacheKey, realCacheKey); + this.cacheSvc.link(requestCacheKey, realCacheKey) } - result = this.cacheSvc.put(realCacheKey, result, true); - return result; + result = this.cacheSvc.put(realCacheKey, result, true) + return result } openEdit(elementOb: T, clean: boolean): EditObject { - const result: T = clean ? this.apiSvc.cleanElement(elementOb, true) : elementOb; - result._commitId = 'latest'; - const editKey = this.getEditElementKey(elementOb); + const result: T = clean ? this.apiSvc.cleanElement(elementOb, true) : elementOb + result._commitId = 'latest' + const editKey = this.getEditElementKey(elementOb) - return this.editSvc.addOrUpdate(editKey, result) as EditObject; + return this.editSvc.addOrUpdate(editKey, result) as EditObject } cacheDeletedElement = (reqOb: RequestObject, deletedOb: ElementObject): void => { - const requestCacheKey = this.getRequestKey(reqOb, deletedOb.id); - requestCacheKey.push('deleted'); + const requestCacheKey = this.getRequestKey(reqOb, deletedOb.id) + requestCacheKey.push('deleted') const deletedReqOb: RequestObject = { projectId: deletedOb._projectId, refId: deletedOb._refId, commitId: deletedOb._commitId, - }; - const commitCacheKey = this.apiSvc.makeCacheKey(deletedReqOb, deletedOb.id); - this.cacheSvc.link(requestCacheKey, commitCacheKey); - this.cacheSvc.put(commitCacheKey, deletedOb, true); - }; + } + const commitCacheKey = this.apiSvc.makeCacheKey(deletedReqOb, deletedOb.id) + this.cacheSvc.link(requestCacheKey, commitCacheKey) + this.cacheSvc.put(commitCacheKey, deletedOb, true) + } /** * @name veUtils/ElementService#getElementForEdit @@ -322,15 +322,15 @@ export class ElementService extends BaseApiService { weight?: number, overwrite?: boolean ): VePromise, ElementsResponse> { - this.apiSvc.normalize(reqOb); - const requestCacheKey = this.getEditKey(reqOb); - const url = this.uRLSvc.getElementURL(reqOb) + 'edit'; + this.apiSvc.normalize(reqOb) + const requestCacheKey = this.getEditKey(reqOb) + const url = this.uRLSvc.getElementURL(reqOb) + 'edit' if (!this._isInProgress(url)) { - const openEdit = this.editSvc.get(requestCacheKey); + const openEdit = this.editSvc.get(requestCacheKey) if (openEdit && !overwrite) { return new this.$q, ElementsResponse>((resolve, reject) => { - return resolve(openEdit); - }); + return resolve(openEdit) + }) } this._addInProgress( url, @@ -338,20 +338,20 @@ export class ElementService extends BaseApiService { this.getElement(reqOb, weight) .then( (result) => { - const copy = this.apiSvc.cleanElement(_.cloneDeep(result), true); - resolve(this.editSvc.addOrUpdate(requestCacheKey, copy, overwrite) as EditObject); + const copy = this.apiSvc.cleanElement(_.cloneDeep(result), true) + resolve(this.editSvc.addOrUpdate(requestCacheKey, copy, overwrite) as EditObject) }, (reason) => { - reject(reason); + reject(reason) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) }) - ); + ) } - return this._getInProgress(url) as VePromise, ElementsResponse>; + return this._getInProgress(url) as VePromise, ElementsResponse> } /** @@ -370,11 +370,11 @@ export class ElementService extends BaseApiService { weight?: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb); + this.apiSvc.normalize(reqOb) if (!reqOb.depth) { - reqOb.depth = -1; + reqOb.depth = -1 } - return this.getGenericElements(this.uRLSvc.getOwnedElementURL(reqOb), reqOb, 'elements', weight, refresh); + return this.getGenericElements(this.uRLSvc.getOwnedElementURL(reqOb), reqOb, 'elements', weight, refresh) } /** @@ -395,17 +395,17 @@ export class ElementService extends BaseApiService { weight: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb); - const requestCacheKey = this.getRequestKey(reqOb, jsonKey); + this.apiSvc.normalize(reqOb) + const requestCacheKey = this.getRequestKey(reqOb, jsonKey) if (this._isInProgress(url)) { - this.httpSvc.ping(url, weight); - return this._getInProgress(url) as VePromise>; + this.httpSvc.ping(url, weight) + return this._getInProgress(url) as VePromise> } - const cached = this.cacheSvc.get(requestCacheKey); + const cached = this.cacheSvc.get(requestCacheKey) if (cached && !refresh) { return new this.$q>((resolve, reject) => { - return resolve(cached); - }); + return resolve(cached) + }) } this._addInProgress( url, @@ -413,29 +413,29 @@ export class ElementService extends BaseApiService { this.httpSvc.get>( url, (response) => { - const results: T[] = []; - const elements: T[] = response.data[jsonKey]; + const results: T[] = [] + const elements: T[] = response.data[jsonKey] for (let i = 0; i < elements.length; i++) { - const element = elements[i]; + const element = elements[i] if (!element) { //check for possible null - continue; + continue } - results.push(this.cacheElement(reqOb, element)); + results.push(this.cacheElement(reqOb, element)) } - this._removeInProgress(url); - resolve(results); - return; + this._removeInProgress(url) + resolve(results) + return }, (response: angular.IHttpResponse>) => { - this._removeInProgress(url); - reject(this.uRLSvc.handleHttpStatus(response)); + this._removeInProgress(url) + reject(this.uRLSvc.handleHttpStatus(response)) }, weight - ); + ) }) - ); - return this._getInProgress>(url) as VePromise>; + ) + return this._getInProgress>(url) as VePromise> } //called by updateElement, fills in all keys for element to be updated @@ -451,45 +451,45 @@ export class ElementService extends BaseApiService { }, 2) .then((data) => { */ - const ob = _.cloneDeep(elementOb); //make a copy - ob._commitId = 'latest'; - const editOb = this.editSvc.get(this.getEditElementKey(elementOb)); + const ob = _.cloneDeep(elementOb) //make a copy + ob._commitId = 'latest' + const editOb = this.editSvc.get(this.getEditElementKey(elementOb)) if (editOb && editOb.element) { Object.keys(editOb.element).forEach((key) => { if (!elementOb.hasOwnProperty(key)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - ob[key] = editOb.element[key]; + ob[key] = editOb.element[key] } - }); + }) } if (ob._displayedElementIds) { - delete ob._displayedElementIds; + delete ob._displayedElementIds } if (ob._allowedElementIds) { - delete ob._allowedElementIds; + delete ob._allowedElementIds } if (ob._childViews && !elementOb._childViews) { - delete ob._childViews; + delete ob._childViews } if (ob.type && ob.type.endsWith('TaggedValue') && ob.value && (ob as TaggedValueObject).value.length > 0) { // make sure value array only has the value - const newvalues = []; + const newvalues = [] for (const val of (ob as TaggedValueObject).value) { if (ob.type === 'ElementTaggedValue') { - newvalues.push(val.elementId); + newvalues.push(val.elementId) } else { - newvalues.push({ value: val.value }); + newvalues.push({ value: val.value }) } } if (ob.type === 'ElementTaggedValue') { - ob.valueIds = newvalues; - delete ob.value; + ob.valueIds = newvalues + delete ob.value } else { - ob.value = newvalues; + ob.value = newvalues } } - delete ob._commitId; - return ob; + delete ob._commitId + return ob /* resolve(ob); }, () => { @@ -497,7 +497,7 @@ export class ElementService extends BaseApiService { }); }); */ - }; + } /** * @name veUtils/ElementService#updateElement @@ -521,12 +521,12 @@ export class ElementService extends BaseApiService { return new this.$q((resolve, reject) => { const handleSuccess = (data: ElementsResponse): void => { - let e: T = data.elements[0]; + let e: T = data.elements[0] if (data.elements.length > 1 && elementOb.id) { for (let i = 0; i < data.elements.length; i++) { if (data.elements[i].id === elementOb.id) { - e = data.elements[i]; + e = data.elements[i] } } } @@ -535,33 +535,33 @@ export class ElementService extends BaseApiService { refId: e._refId, commitId: 'latest', elementId: e.id, - }; - const resp: T = this.cacheElement(metaOb, e); + } + const resp: T = this.cacheElement(metaOb, e) // const editCopy = _.cloneDeep(e) // this.cacheElement(metaOb, editCopy, true) const history = this.cacheSvc.get( this.apiSvc.makeCacheKey(metaOb, metaOb.elementId, false, 'history') - ); + ) if (history) { - const id = e._commitId ? e._commitId : 'latest'; + const id = e._commitId ? e._commitId : 'latest' history.unshift({ _creator: e._modifier, _created: e._modified, id: id, _refId: e._refId, _projectId: e._projectId, - }); + }) } - resolve(resp); - }; + resolve(resp) + } if (!elementOb.hasOwnProperty('id')) { reject({ status: 400, message: 'Element id not found, create element first!', - }); + }) } - const postElem = this.fillInElement(elementOb); + const postElem = this.fillInElement(elementOb) //.then((postElem) => { this.$http .post>( @@ -578,32 +578,32 @@ export class ElementService extends BaseApiService { ) .then( (response) => { - const rejected = response.data.rejected; + const rejected = response.data.rejected if (rejected && rejected.length > 0 && rejected[0].code === 304 && rejected[0].object) { //elem will be rejected if server detects no changes - resolve(rejected[0].object); - return; + resolve(rejected[0].object) + return } if (!Array.isArray(response.data.elements) || response.data.elements.length === 0) { if (allowEmpty) { - resolve(null); + resolve(null) } else { reject({ status: 500, message: 'Server Error: empty response', - }); + }) } - return; + return } - handleSuccess(response.data); + handleSuccess(response.data) }, (response: angular.IHttpResponse>) => { if (response.status === 409) { - const serverOb = response.data.elements[0]; - this.apiSvc.cleanElement(serverOb); - const origCommit = elementOb._commitId; - elementOb._commitId = 'latest'; + const serverOb = response.data.elements[0] + this.apiSvc.cleanElement(serverOb) + const origCommit = elementOb._commitId + elementOb._commitId = 'latest' const origOb = this.cacheSvc.get( this.apiSvc.makeCacheKey( { @@ -613,29 +613,29 @@ export class ElementService extends BaseApiService { }, elementOb.id ) - ); - elementOb._commitId = origCommit; + ) + elementOb._commitId = origCommit if (!origOb) { - reject(this.uRLSvc.handleHttpStatus(response)); - return; + reject(this.uRLSvc.handleHttpStatus(response)) + return } if (!this.apiSvc.hasConflict(postElem, origOb, serverOb)) { - elementOb._modified = serverOb._modified; + elementOb._modified = serverOb._modified this.updateElement(elementOb, returnChildViews).then( (good) => { - resolve(good); + resolve(good) }, (reason) => { - reject(reason); + reject(reason) } - ); + ) } else { - reject(this.uRLSvc.handleHttpStatus(response)); + reject(this.uRLSvc.handleHttpStatus(response)) } - } else reject(this.uRLSvc.handleHttpStatus(response)); + } else reject(this.uRLSvc.handleHttpStatus(response)) } - ); - }); + ) + }) } /** @@ -655,15 +655,15 @@ export class ElementService extends BaseApiService { return new this.$q>((resolve, reject) => { if (this._validate(elementObs)) { const postElements = elementObs.map((elementOb) => { - return this.fillInElement(elementOb) as T; - }); + return this.fillInElement(elementOb) as T + }) - const groupOfElements = this._groupElementsByProjectIdAndRefId(postElements); - const promises: VePromise>[] = []; + const groupOfElements = this._groupElementsByProjectIdAndRefId(postElements) + const promises: VePromise>[] = [] Object.keys(groupOfElements).forEach((key) => { - promises.push(this._bulkUpdate(groupOfElements[key], returnChildViews)); - }); + promises.push(this._bulkUpdate(groupOfElements[key], returnChildViews)) + }) // responses is an array of response corresponding to both successful and failed requests with the following format // [ { state: 'fulfilled', value: the value returned by the server }, @@ -672,27 +672,27 @@ export class ElementService extends BaseApiService { this.$q.allSettled(promises).then((responses) => { // get all the successful requests const successfulRequests = responses.filter((response) => { - return response.state === 'fulfilled'; - }); + return response.state === 'fulfilled' + }) const successValues = _.flatten( successfulRequests.map((response) => { - return response.value; + return response.value }) - ); + ) if (successfulRequests.length === promises.length) { // All requests succeeded - resolve(successValues); + resolve(successValues) } else { // some requests failed const rejectionReasons: VePromiseReason>[] = responses .filter((response) => { - return response.state === 'rejected'; + return response.state === 'rejected' }) .map((response): unknown => { - return response.reason as VePromiseReason>; - }) as VePromiseReason>[]; + return response.reason as VePromiseReason> + }) as VePromiseReason>[] // since we could have multiple failed requests when having some successful requests, // reject with the following format so that the client can deal with them at a granular level if @@ -704,18 +704,18 @@ export class ElementService extends BaseApiService { failedRequests: rejectionReasons, successfulRequests: successValues, }, - }); + }) } - }, reject); + }, reject) } else { const response: VePromiseReason> = { status: 400, message: 'Some of the elements do not have id, _projectId, _refId', data: {}, - }; - reject(response); + } + reject(response) } - }); + }) } /** @@ -728,9 +728,9 @@ export class ElementService extends BaseApiService { * create is successful. */ createElement(reqOb: ElementCreationRequest): VePromise { - this.apiSvc.normalize(reqOb); + this.apiSvc.normalize(reqOb) return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getPostElementsURL(reqOb); + const url = this.uRLSvc.getPostElementsURL(reqOb) this.$http .post>(url, { elements: reqOb.elements, @@ -743,23 +743,23 @@ export class ElementService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }); - return; + }) + return } - let resp: T = response.data.elements[0]; + let resp: T = response.data.elements[0] if (response.data.elements.length > 1 && reqOb.elements[0].id) { for (let i = 0; i < response.data.elements.length; i++) { if (response.data.elements[i].id === reqOb.elements[0].id) { - resp = response.data.elements[i]; + resp = response.data.elements[i] } } } - resolve(this.cacheElement(reqOb, resp)); + resolve(this.cacheElement(reqOb, resp)) }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ); - }); + ) + }) } /** @@ -772,9 +772,9 @@ export class ElementService extends BaseApiService { * create is successful. */ createElements(reqOb: ElementCreationRequest): VePromise> { - this.apiSvc.normalize(reqOb); + this.apiSvc.normalize(reqOb) return new this.$q>((resolve, reject) => { - const url = this.uRLSvc.getPostElementsURL(reqOb); + const url = this.uRLSvc.getPostElementsURL(reqOb) this.$http .post>(url, { elements: reqOb.elements, @@ -787,22 +787,22 @@ export class ElementService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }); - return; + }) + return } - const results: T[] = []; + const results: T[] = [] for (let i = 0; i < response.data.elements.length; i++) { - results.push(this.cacheElement(reqOb, response.data.elements[i])); + results.push(this.cacheElement(reqOb, response.data.elements[i])) // const editCopy = _.cloneDeep(response.data.elements[i]) // this.cacheElement(reqOb, editCopy, true) } - resolve(results); + resolve(results) }, (response: angular.IHttpResponse>) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } - ); - }); + ) + }) } /** @@ -818,9 +818,9 @@ export class ElementService extends BaseApiService { elementOb: T ): VePromise< { - status?: boolean; - server?: T; - cache?: T; + status?: boolean + server?: T + cache?: T }, ElementsResponse > { @@ -828,46 +828,46 @@ export class ElementService extends BaseApiService { projectId: elementOb._projectId, refId: elementOb._refId, elementId: elementOb.id, - }; + } return new this.$q< { - status?: boolean; - server?: T; - cache?: T; + status?: boolean + server?: T + cache?: T }, ElementsResponse >((resolve, reject) => { - const orig = this.cacheSvc.get(this.apiSvc.makeCacheKey(reqOb, elementOb.id, false)); + const orig = this.cacheSvc.get(this.apiSvc.makeCacheKey(reqOb, elementOb.id, false)) if (!orig) { - return resolve({ status: false }); + return resolve({ status: false }) } this.$http.get>(this.uRLSvc.getElementURL(reqOb)).then( (response) => { - let server = _.cloneDeep(response.data.elements[0]); - delete server._modified; - delete server._read; - delete server._creator; - server = this.apiSvc.cleanElement(server); - let current: ElementObject = _.cloneDeep(orig); - delete current._modified; - delete current._read; - delete current._creator; - current = this.apiSvc.cleanElement(current); + let server = _.cloneDeep(response.data.elements[0]) + delete server._modified + delete server._read + delete server._creator + server = this.apiSvc.cleanElement(server) + let current: ElementObject = _.cloneDeep(orig) + delete current._modified + delete current._read + delete current._creator + current = this.apiSvc.cleanElement(current) if (_.isEqual(server, current)) { - resolve({ status: false }); + resolve({ status: false }) } else { resolve({ status: true, server: response.data.elements[0], cache: orig, - }); + }) } }, (response: angular.IHttpResponse>) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } - ); - }); + ) + }) } /** @@ -887,8 +887,8 @@ export class ElementService extends BaseApiService { queryParams?: QueryParams, weight? ): VePromise, SearchResponse> { - this.apiSvc.normalize(reqOb); - const url = this.uRLSvc.getElementSearchURL(reqOb, queryParams); + this.apiSvc.normalize(reqOb) + const url = this.uRLSvc.getElementSearchURL(reqOb, queryParams) return new this.$q, SearchResponse>((resolve, reject) => { this.$http.post(url, query).then( (response: angular.IHttpResponse>) => { @@ -901,12 +901,12 @@ export class ElementService extends BaseApiService { // result.push(toAdd); //} //resolve(result); - resolve(response.data); + resolve(response.data) }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ); - }); + ) + }) } /** @@ -923,62 +923,62 @@ export class ElementService extends BaseApiService { weight: number, update?: boolean ): VePromise { - this.apiSvc.normalize(reqOb); - const url = this.uRLSvc.getElementHistoryURL(reqOb); + this.apiSvc.normalize(reqOb) + const url = this.uRLSvc.getElementHistoryURL(reqOb) if (this._isInProgress(url)) { - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } - const requestCacheKey: string[] = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'history'); + const requestCacheKey: string[] = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'history') if (this.cacheSvc.exists(requestCacheKey) && !update) { return new this.$q((resolve, reject) => { - return resolve(this.cacheSvc.get(requestCacheKey)); - }); + return resolve(this.cacheSvc.get(requestCacheKey)) + }) } this._addInProgress( url, new this.$q((resolve, reject) => { this.$http.get(this.uRLSvc.getElementHistoryURL(reqOb)).then( (response: angular.IHttpResponse) => { - this.cacheSvc.put(requestCacheKey, response.data.commits, true); - this._removeInProgress(url); - resolve(this.cacheSvc.get(requestCacheKey)); + this.cacheSvc.put(requestCacheKey, response.data.commits, true) + this._removeInProgress(url) + resolve(this.cacheSvc.get(requestCacheKey)) }, (response: angular.IHttpResponse) => { - this._removeInProgress(url); - this.apiSvc.handleErrorCallback(response, reject); + this._removeInProgress(url) + this.apiSvc.handleErrorCallback(response, reject) } - ); + ) }) - ); - return this._getInProgress(url) as VePromise; + ) + return this._getInProgress(url) as VePromise } public getRequestKey(reqOb: RequestObject, id: string, edit?: boolean): string[] { - return this.apiSvc.makeCacheKey(reqOb, id, edit); + return this.apiSvc.makeCacheKey(reqOb, id, edit) } public getElementRequest(elementOb: ElementObject): ElementsRequest { - const req = this.apiSvc.makeRequestObject(elementOb); - (req as ElementsRequest).elementId = elementOb.id; - return req as ElementsRequest; + const req = this.apiSvc.makeRequestObject(elementOb) + ;(req as ElementsRequest).elementId = elementOb.id + return req as ElementsRequest } public getElementKey(elementOb: ElementObject, edit?: boolean): string[] { - return this.getRequestKey(this.getElementRequest(elementOb), elementOb.id, edit); + return this.getRequestKey(this.getElementRequest(elementOb), elementOb.id, edit) } public getEditKey(reqOb: ElementsRequest): string[] { - const key: string[] = []; + const key: string[] = [] if (reqOb !== null) { - if (reqOb.projectId) key.push(reqOb.projectId); - if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId); + if (reqOb.projectId) key.push(reqOb.projectId) + if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId) } - key.push(reqOb.elementId); - return key; + key.push(reqOb.elementId) + return key } public getEditElementKey(e: ElementObject): string[] { - return [e._projectId, e._refId, e.id]; + return [e._projectId, e._refId, e.id] } public getElementQualifiedName(reqOb: ElementsRequest): VePromise> { @@ -991,33 +991,33 @@ export class ElementService extends BaseApiService { recurse: { ownerId: 'id', }, - }; + } this.search(reqOb, queryOb).then( (data) => { - let qualifiedName = ''; - const elements = data.elements.reverse(); - const entries = elements.entries(); + let qualifiedName = '' + const elements = data.elements.reverse() + const entries = elements.entries() for (const [i, element] of entries) { if (element.hasOwnProperty('name')) { - qualifiedName += element.name; + qualifiedName += element.name } if (i != elements.length - 1) { - qualifiedName += '/'; + qualifiedName += '/' } } - return resolve(qualifiedName); + return resolve(qualifiedName) }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } private _groupElementsByProjectIdAndRefId(elementObs: T[]): _.Dictionary { return _.groupBy(elementObs, (element) => { - return element._projectId + '|' + element._refId; - }); + return element._projectId + '|' + element._refId + }) } private _createMetaOb(element: ElementObject): ElementsRequest { @@ -1026,7 +1026,7 @@ export class ElementService extends BaseApiService { refId: element._refId, commitId: 'latest', elementId: element.id, - }; + } } private _validate(elementObs: ElementObject[]): boolean { @@ -1035,8 +1035,8 @@ export class ElementService extends BaseApiService { elementOb.hasOwnProperty('id') && elementOb.hasOwnProperty('_projectId') && elementOb.hasOwnProperty('_refId') - ); - }); + ) + }) } private _bulkUpdate>( @@ -1053,7 +1053,7 @@ export class ElementService extends BaseApiService { : this.uRLSvc.getPostElementsURL({ projectId: elements[0]._projectId, refId: elements[0]._refId, - }); + }) this.$http .post>( url, @@ -1065,32 +1065,32 @@ export class ElementService extends BaseApiService { ) .then( (response) => { - this._bulkUpdateSuccessHandler(response, resolve); + this._bulkUpdateSuccessHandler(response, resolve) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } - ); - }); + ) + }) } private _bulkUpdateSuccessHandler( serverResponse: angular.IHttpResponse>, resolve: angular.IQResolveReject ): void { - const results: T[] = []; - const elements = serverResponse.data.elements; + const results: T[] = [] + const elements = serverResponse.data.elements if (elements && elements.length > 0) { elements.forEach((e) => { - const metaOb = this._createMetaOb(e); + const metaOb = this._createMetaOb(e) //const editCopy = _.cloneDeep(e) - results.push(this.cacheElement(metaOb, e)); + results.push(this.cacheElement(metaOb, e)) //this.cacheElement(metaOb, editCopy, true) const history = this.cacheSvc.get( this.apiSvc.makeCacheKey(metaOb, metaOb.elementId, false, 'history') - ); + ) if (history) { history.unshift({ _creator: e._modifier, @@ -1098,22 +1098,22 @@ export class ElementService extends BaseApiService { id: e._commitId, _refId: e._refId, _projectId: e._projectId, - }); + }) } - }); + }) } - const rejected: RejectedObject[] = serverResponse.data.rejected; + const rejected: RejectedObject[] = serverResponse.data.rejected if (rejected && rejected.length > 0) { rejected.forEach((e) => { if (e.code === 304 && e.object) { - results.push(e.object); //add any server rejected elements because they haven't changed - console.log(`[BULK UPDATE ELEMENT REJECTED]: ${e.code}: ${e.message}`); - console.log(e.object.id); + results.push(e.object) //add any server rejected elements because they haven't changed + console.log(`[BULK UPDATE ELEMENT REJECTED]: ${e.code}: ${e.message}`) + console.log(e.object.id) } - }); + }) } - resolve(results); + resolve(results) } } -veUtils.service('ElementService', ElementService); +veUtils.service('ElementService', ElementService) diff --git a/src/ve-utils/mms-api-client/Http.service.ts b/src/ve-utils/mms-api-client/Http.service.ts index 601eff2ba..aa84d7b37 100644 --- a/src/ve-utils/mms-api-client/Http.service.ts +++ b/src/ve-utils/mms-api-client/Http.service.ts @@ -1,12 +1,12 @@ -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -export type httpCallback = (response: angular.IHttpResponse) => void; +export type httpCallback = (response: angular.IHttpResponse) => void export interface HttpServiceRequest { - url: string; - successCallback: httpCallback; - errorCallback: httpCallback; - weight: number; + url: string + successCallback: httpCallback + errorCallback: httpCallback + weight: number } /** @@ -15,24 +15,24 @@ export interface HttpServiceRequest { * * Provides prioritization and caching for $http service calls */ export class HttpService { - private queue: HttpServiceRequest[][] = []; - cache: { [key: string]: HttpServiceRequest } = {}; - inProgress = 0; - getLimit = 20; + private queue: HttpServiceRequest[][] = [] + cache: { [key: string]: HttpServiceRequest } = {} + inProgress = 0 + getLimit = 20 - static $inject = ['$http']; + static $inject = ['$http'] constructor(private $http: angular.IHttpService) { - this.queue[0] = []; //high proirity - this.queue[1] = []; //low prority + this.queue[0] = [] //high proirity + this.queue[1] = [] //low prority } setOutboundLimit = (limit: number): void => { - this.getLimit = limit; - }; + this.getLimit = limit + } getQueue(): HttpServiceRequest[][] { - return this.queue; + return this.queue } /** @@ -47,68 +47,68 @@ export class HttpService { */ get(url: string, successCallback: httpCallback, errorCallback: httpCallback, weight: number): void { if (weight === undefined) { - weight = 1; + weight = 1 } const request: HttpServiceRequest = { url: url, successCallback: successCallback, errorCallback: errorCallback, weight: weight, - }; + } if (this.inProgress >= this.getLimit) { if (request.weight === 2) { this.$http .get(url) .then( (response: angular.IHttpResponse) => { - successCallback(response); + successCallback(response) }, (response: angular.IHttpResponse) => { - errorCallback(response); + errorCallback(response) } ) .finally(() => { if (this.cache.hasOwnProperty(url)) { - delete this.cache[url]; + delete this.cache[url] } - }); + }) } else if (request.weight === 0) { - this.queue[0].push(request); + this.queue[0].push(request) } else { - this.queue[1].push(request); + this.queue[1].push(request) } if (this.cache.hasOwnProperty(url)) { - if (this.cache[url].weight < request.weight) this.cache[url].weight = request.weight; + if (this.cache[url].weight < request.weight) this.cache[url].weight = request.weight } else { - this.cache[url] = request; + this.cache[url] = request } } else { - this.inProgress++; - this.cache[url] = request; + this.inProgress++ + this.cache[url] = request this.$http .get(url) .then( (response: angular.IHttpResponse) => { - successCallback(response); + successCallback(response) }, (response: angular.IHttpResponse) => { - errorCallback(response); + errorCallback(response) } ) .finally(() => { - this.inProgress--; - let next: HttpServiceRequest; + this.inProgress-- + let next: HttpServiceRequest if (this.cache.hasOwnProperty(url)) { - delete this.cache[url]; + delete this.cache[url] } if (this.queue[1].length > 0) { - next = this.queue[1].shift(); - this.get(next.url, next.successCallback, next.errorCallback, next.weight); + next = this.queue[1].shift() + this.get(next.url, next.successCallback, next.errorCallback, next.weight) } else if (this.queue[0].length > 0) { - next = this.queue[0].shift(); - this.get(next.url, next.successCallback, next.errorCallback, next.weight); + next = this.queue[0].shift() + this.get(next.url, next.successCallback, next.errorCallback, next.weight) } - }); + }) } } @@ -122,29 +122,29 @@ export class HttpService { ping = (url: string, weight?: number): void => { // ping should simply change the weight if (weight === undefined) { - weight = 1; + weight = 1 } if (this.cache.hasOwnProperty(url)) { if (weight > this.cache[url].weight) { - const request = this.cache[url]; - let index: number; - if (request.weight === 0) index = this.queue[0].indexOf(request); - else index = this.queue[1].indexOf(request); + const request = this.cache[url] + let index: number + if (request.weight === 0) index = this.queue[0].indexOf(request) + else index = this.queue[1].indexOf(request) if (weight === 1 && index !== -1) { - request.weight = 1; - this.queue[1].push(request); - this.queue[0].splice(index, 1); + request.weight = 1 + this.queue[1].push(request) + this.queue[0].splice(index, 1) } else if (weight === 2 && index !== -1) { if (request.weight === 0) { - this.queue[0].splice(index, 1); + this.queue[0].splice(index, 1) } else { - this.queue[1].splice(index, 1); + this.queue[1].splice(index, 1) } - this.get(request.url, request.successCallback, request.errorCallback, weight); + this.get(request.url, request.successCallback, request.errorCallback, weight) } } } - }; + } /** * @name veUtils/HttpService#ping @@ -155,23 +155,23 @@ export class HttpService { if (this.queue[1].length > 0) { //will the queue ever be defined? for (let i = 0; i < this.queue[1].length; i++) { - this.queue[1][i].weight = 0; + this.queue[1][i].weight = 0 // if(cache.hasOwnProperty(queue[1][i].request.url)) // cache[queue[1][i].request.url].weight = 0; - this.queue[0].push(this.queue[1][i]); + this.queue[0].push(this.queue[1][i]) //queue[1][i].shift(); } //queue[0] = queue[0].concat(queue[1]); - this.queue[1] = []; + this.queue[1] = [] } - }; + } dropAll = (): void => { - this.queue[1].length = 0; - this.queue[0].length = 0; - this.cache = {}; - this.inProgress = 0; - }; + this.queue[1].length = 0 + this.queue[0].length = 0 + this.cache = {} + this.inProgress = 0 + } } -veUtils.service('HttpService', HttpService); +veUtils.service('HttpService', HttpService) diff --git a/src/ve-utils/mms-api-client/Permissions.service.ts b/src/ve-utils/mms-api-client/Permissions.service.ts index 6ffa7d5bc..e49f41a54 100644 --- a/src/ve-utils/mms-api-client/Permissions.service.ts +++ b/src/ve-utils/mms-api-client/Permissions.service.ts @@ -1,13 +1,13 @@ -import { URLService } from '@ve-utils/mms-api-client'; +import { URLService } from '@ve-utils/mms-api-client' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; -import { PermissionsObject, PermissionsResponse, ProjectObject, RefObject } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { PermissionsObject, PermissionsResponse, ProjectObject, RefObject } from '@ve-types/mms' export interface PermissionCache { - project: { [id: string]: boolean }; - ref: { [id: string]: boolean }; + project: { [id: string]: boolean } + ref: { [id: string]: boolean } } /** @@ -20,9 +20,9 @@ export interface PermissionCache { * * This utility service handles permissions inquiries */ export class PermissionsService { - private permissions: PermissionCache = { project: {}, ref: {} }; + private permissions: PermissionCache = { project: {}, ref: {} } - static $inject = ['$q', '$http', 'URLService']; + static $inject = ['$q', '$http', 'URLService'] constructor(private $q: VeQService, private $http: angular.IHttpService, private uRLSvc: URLService) {} @@ -30,15 +30,15 @@ export class PermissionsService { projectOb: ProjectObject, refOb: RefObject ): VePromise { - const url = this.uRLSvc.getPermissionsLookupURL(); + const url = this.uRLSvc.getPermissionsLookupURL() - const deferred = this.$q.defer(); + const deferred = this.$q.defer() if ( this.permissions.project[projectOb.id] !== undefined && this.permissions.ref[projectOb.id + '/' + refOb.id] !== undefined ) { - deferred.resolve(this.permissions); - return deferred.promise; + deferred.resolve(this.permissions) + return deferred.promise } this.$http .put(url, { @@ -58,39 +58,39 @@ export class PermissionsService { }) .then( (response) => { - const data: PermissionsObject[] = response.data.lookups; + const data: PermissionsObject[] = response.data.lookups if (Array.isArray(data) && data.length > 0) { data.forEach((d) => { if (d.type == 'PROJECT') { - this.permissions.project[d.projectId] = d.hasPrivilege; + this.permissions.project[d.projectId] = d.hasPrivilege } else { - this.permissions.ref[d.projectId + '/' + d.refId] = d.hasPrivilege; + this.permissions.ref[d.projectId + '/' + d.refId] = d.hasPrivilege } - }); - deferred.resolve(this.permissions); + }) + deferred.resolve(this.permissions) } else { deferred.reject({ status: 500, data: '', message: 'Server Error: empty response', - }); + }) } }, (response: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(response)); + deferred.reject(this.uRLSvc.handleHttpStatus(response)) } - ); + ) - return deferred.promise; + return deferred.promise } public hasProjectEditPermission = (projectId: string): boolean => { - return this.permissions.project[projectId]; - }; + return this.permissions.project[projectId] + } public hasBranchEditPermission = (projectId: string, refId: string): boolean => { - return this.permissions.ref[projectId + '/' + refId]; - }; + return this.permissions.ref[projectId + '/' + refId] + } } -veUtils.service('PermissionsService', PermissionsService); +veUtils.service('PermissionsService', PermissionsService) diff --git a/src/ve-utils/mms-api-client/Project.service.ts b/src/ve-utils/mms-api-client/Project.service.ts index 568bc96e5..479fb6334 100644 --- a/src/ve-utils/mms-api-client/Project.service.ts +++ b/src/ve-utils/mms-api-client/Project.service.ts @@ -1,10 +1,10 @@ -import { CacheService } from '@ve-utils/core'; -import { ApiService, ElementService, URLService } from '@ve-utils/mms-api-client'; -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; +import { CacheService } from '@ve-utils/core' +import { ApiService, ElementService, URLService } from '@ve-utils/mms-api-client' +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; +import { VePromise, VeQService } from '@ve-types/angular' import { CommitObject, CommitResponse, @@ -18,7 +18,7 @@ import { ProjectsResponse, RefObject, RefsResponse, -} from '@ve-types/mms'; +} from '@ve-types/mms' /** * @ngdoc service @@ -33,7 +33,7 @@ import { * * This is a utility service for getting project, ref, commit information */ export class ProjectService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'ElementService', 'URLService', 'ApiService']; + static $inject = ['$q', '$http', 'CacheService', 'ElementService', 'URLService', 'ApiService'] constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -42,7 +42,7 @@ export class ProjectService extends BaseApiService { private uRLSvc: URLService, private apiSvc: ApiService ) { - super(); + super() } /** @@ -53,16 +53,16 @@ export class ProjectService extends BaseApiService { * @returns {Promise} Resolves to the org object. */ public getOrg(orgId: string): VePromise { - const key = ['org', orgId]; - const url = this.uRLSvc.getOrgURL(orgId); + const key = ['org', orgId] + const url = this.uRLSvc.getOrgURL(orgId) if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(key)) { - resolve(this.cacheSvc.get(key)); - this._removeInProgress(url); - return; + resolve(this.cacheSvc.get(key)) + this._removeInProgress(url) + return } else { this.$http .get(url) @@ -73,23 +73,23 @@ export class ProjectService extends BaseApiService { status: 404, message: 'Org not found', type: 'error', - }); + }) } else { - this.cacheSvc.put(key, response.data.orgs[0], true); - resolve(this.cacheSvc.get(key)); + this.cacheSvc.put(key, response.data.orgs[0], true) + resolve(this.cacheSvc.get(key)) } }, (response: angular.IHttpResponse) => this.apiSvc.handleErrorCallback(response, reject) ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) } }) - ); + ) } - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } /** @@ -99,46 +99,46 @@ export class ProjectService extends BaseApiService { * @returns {Promise} Resolves into array of org objects. */ public getOrgs(updateCache?: boolean): VePromise { - const key = 'orgs'; + const key = 'orgs' if (!this._isInProgress(key)) { this._addInProgress( key, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(key) && !updateCache) { - resolve(this.cacheSvc.get(key)); - this._removeInProgress(key); - return; + resolve(this.cacheSvc.get(key)) + this._removeInProgress(key) + return } else { this.$http .get(this.uRLSvc.getOrgsURL()) .then( (response) => { - const orgs: OrgObject[] = []; + const orgs: OrgObject[] = [] for (let i = 0; i < response.data.orgs.length; i++) { - const org = response.data.orgs[i]; - this.cacheSvc.put(['org', org.id], org, true); - orgs.push(this.cacheSvc.get(['org', org.id])); + const org = response.data.orgs[i] + this.cacheSvc.put(['org', org.id], org, true) + orgs.push(this.cacheSvc.get(['org', org.id])) } - this.cacheSvc.put(key, orgs, false); - resolve(this.cacheSvc.get(key)); + this.cacheSvc.put(key, orgs, false) + resolve(this.cacheSvc.get(key)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(key); - }); + this._removeInProgress(key) + }) } }) - ); + ) } - return this._getInProgress(key) as VePromise; + return this._getInProgress(key) as VePromise } public createOrg(name: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getOrgsURL(); + const url = this.uRLSvc.getOrgsURL() this.$http .post(url, { orgs: { name: name }, @@ -146,29 +146,29 @@ export class ProjectService extends BaseApiService { }) .then( (response) => { - const org = response.data.orgs[0]; - const key = ['org', org.id]; - this.cacheSvc.put(key, response.data.orgs[0], true); - resolve(this.cacheSvc.get(key)); + const org = response.data.orgs[0] + const key = ['org', org.id] + this.cacheSvc.put(key, response.data.orgs[0], true) + resolve(this.cacheSvc.get(key)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } - ); - }); + ) + }) } public getProjects(orgId?: string, updateCache?: boolean): VePromise { - const url = this.uRLSvc.getProjectsURL(orgId); + const url = this.uRLSvc.getProjectsURL(orgId) if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = !orgId ? 'projects' : ['projects', orgId]; + const cacheKey = !orgId ? 'projects' : ['projects', orgId] if (this.cacheSvc.exists(cacheKey) && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)); - this._removeInProgress(url); - return; + resolve(this.cacheSvc.get(cacheKey)) + this._removeInProgress(url) + return } else { this.$http .get(url) @@ -179,62 +179,62 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }); - return; + }) + return } if (!orgId) { const orgProjects: { - [orgId: string]: ProjectObject[]; - } = {}; + [orgId: string]: ProjectObject[] + } = {} response.data.projects.forEach((project) => { - const porg = project.orgId; + const porg = project.orgId const pCacheKey = this.apiSvc.makeCacheKey( null, project.id, false, 'project' - ); + ) if (orgProjects[porg] === undefined) { - orgProjects[porg] = []; + orgProjects[porg] = [] } - orgProjects[porg].push(this.cacheSvc.put(pCacheKey, project, true)); + orgProjects[porg].push(this.cacheSvc.put(pCacheKey, project, true)) Object.keys(orgProjects).forEach((orgId) => { this.cacheSvc.put( this.apiSvc.makeCacheKey(null, orgId, false, 'projects'), orgProjects[orgId], false - ); - }); - }); + ) + }) + }) } - resolve(this.cacheSvc.put(cacheKey, response.data.projects)); + resolve(this.cacheSvc.put(cacheKey, response.data.projects)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) } }) - ); + ) } - return this._getInProgress(url) as angular.IPromise; + return this._getInProgress(url) as angular.IPromise } public getProject(projectId: string, updateCache?: string): VePromise { - const url = this.uRLSvc.getProjectURL(projectId); + const url = this.uRLSvc.getProjectURL(projectId) if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = ['project', projectId]; - const cached = this.cacheSvc.get(cacheKey); + const cacheKey = ['project', projectId] + const cached = this.cacheSvc.get(cacheKey) if (cached && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)); - this._removeInProgress(url); + resolve(this.cacheSvc.get(cacheKey)) + this._removeInProgress(url) } else { this.$http .get(url) @@ -245,24 +245,24 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }); - return; + }) + return } - this.cacheSvc.put(cacheKey, response.data.projects[0], true); - resolve(this.cacheSvc.get(cacheKey)); + this.cacheSvc.put(cacheKey, response.data.projects[0], true) + resolve(this.cacheSvc.get(cacheKey)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) } }) - ); + ) } - return this._getInProgress(url) as angular.IPromise; + return this._getInProgress(url) as angular.IPromise } public getProjectMounts( @@ -270,12 +270,12 @@ export class ProjectService extends BaseApiService { refId: string, updateCache?: boolean ): VePromise { - const url = this.uRLSvc.getProjectMountsURL(projectId, refId); + const url = this.uRLSvc.getProjectMountsURL(projectId, refId) if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'project-mounts'); + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'project-mounts') this.getProject(projectId).then( (response: ProjectObject) => { @@ -284,14 +284,14 @@ export class ProjectService extends BaseApiService { _mounts: [], _projectId: response.id, _refId: refId, - }; - const result: MountObject = Object.assign(mountOb, response); - const cached: MountObject = this.cacheSvc.get(cacheKey); + } + const result: MountObject = Object.assign(mountOb, response) + const cached: MountObject = this.cacheSvc.get(cacheKey) if (this.cacheSvc.exists(cacheKey) && !updateCache) { - result._mounts.push(...cached._mounts); - resolve(result); - this._removeInProgress(url); - return; + result._mounts.push(...cached._mounts) + resolve(result) + this._removeInProgress(url) + return } else { this.$http .get(url) @@ -305,62 +305,62 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }); - return; + }) + return } if (response.data.projects[0]._mounts) { - result._mounts = (response.data.projects[0] as MountObject)._mounts; + result._mounts = (response.data.projects[0] as MountObject)._mounts } - resolve(this.cacheSvc.put(cacheKey, result, false)); + resolve(this.cacheSvc.put(cacheKey, result, false)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) } }, (response) => { - reject(response); - this._removeInProgress(url); + reject(response) + this._removeInProgress(url) } - ); + ) }) - ); + ) } - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } public getAllMountsAsArray = (project: MountObject): MountObject[] => { - const projectsList: MountObject[] = [project]; - const mounts = project._mounts; + const projectsList: MountObject[] = [project] + const mounts = project._mounts const getMountsArray = (mounts: MountObject[], projectsList: MountObject[]): void => { if (Array.isArray(mounts) && mounts.length !== 0) { for (let i = 0; i < mounts.length; i++) { - projectsList.push(mounts[i]); + projectsList.push(mounts[i]) if (mounts[i]._mounts) { - getMountsArray(mounts[i]._mounts, projectsList); + getMountsArray(mounts[i]._mounts, projectsList) } } } - }; - getMountsArray(mounts, projectsList); - return projectsList; - }; + } + getMountsArray(mounts, projectsList) + return projectsList + } public getRefs(projectId: string): VePromise { - const cacheKey = this.apiSvc.makeCacheKey(null, projectId, false, 'refs'); - const url = this.uRLSvc.getRefsURL(projectId); + const cacheKey = this.apiSvc.makeCacheKey(null, projectId, false, 'refs') + const url = this.uRLSvc.getRefsURL(projectId) if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(cacheKey)) { - resolve(this.cacheSvc.get(cacheKey)); - this._removeInProgress(url); - return; + resolve(this.cacheSvc.get(cacheKey)) + this._removeInProgress(url) + return } else { this.$http .get(url) @@ -371,73 +371,73 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }); - return; + }) + return } - const refs: RefObject[] = []; + const refs: RefObject[] = [] for (let index = 0; index < response.data.refs.length; index++) { - const ref: RefObject = response.data.refs[index]; + const ref: RefObject = response.data.refs[index] if (ref.id === 'master') { - ref.type = 'Branch'; + ref.type = 'Branch' } const refCacheKey: string[] = this.apiSvc.makeCacheKey( { projectId: projectId, refId: ref.id }, '', false, 'ref' - ); - this.cacheSvc.put(refCacheKey, ref, true); - refs.push(this.cacheSvc.get(refCacheKey)); + ) + this.cacheSvc.put(refCacheKey, ref, true) + refs.push(this.cacheSvc.get(refCacheKey)) } - this.cacheSvc.put(cacheKey, refs, false); - resolve(this.cacheSvc.get(cacheKey)); + this.cacheSvc.put(cacheKey, refs, false) + resolve(this.cacheSvc.get(cacheKey)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) } }) - ); + ) } - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } public getRef(refId: string, projectId: string, updateCache?: boolean): VePromise { - const url = this.uRLSvc.getRefURL(projectId, refId); + const url = this.uRLSvc.getRefURL(projectId, refId) if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'ref'); - const cached = this.cacheSvc.get(cacheKey); + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'ref') + const cached = this.cacheSvc.get(cacheKey) if (cached && !updateCache) { - this._removeInProgress(url); - resolve(cached); + this._removeInProgress(url) + resolve(cached) } else { this.$http .get(url) .then( (response) => { - this.cacheSvc.put(cacheKey, response.data.refs[0]); - resolve(this.cacheSvc.get(cacheKey)); + this.cacheSvc.put(cacheKey, response.data.refs[0]) + resolve(this.cacheSvc.get(cacheKey)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) } }) - ); + ) } - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } public getCommits( @@ -446,11 +446,11 @@ export class ProjectService extends BaseApiService { timestamp?: string, limit?: number ): VePromise { - let url: string; + let url: string if (timestamp !== null) { - url = this.uRLSvc.getCommitsURL(projectId, refId, timestamp, limit); + url = this.uRLSvc.getCommitsURL(projectId, refId, timestamp, limit) } else { - url = this.uRLSvc.getCommitsURL(projectId, refId, null, limit); + url = this.uRLSvc.getCommitsURL(projectId, refId, null, limit) } if (!this._isInProgress(url)) { this._addInProgress( @@ -466,63 +466,63 @@ export class ProjectService extends BaseApiService { message: 'Project does not exist at specified time.', type: 'error', - }); - return; + }) + return } - resolve(response.data.commits); + resolve(response.data.commits) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) }) - ); + ) } - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } public getCommit(projectId: string, refId: string, commitId: string): VePromise { - const url = this.uRLSvc.getCommitUrl(projectId, refId, commitId); + const url = this.uRLSvc.getCommitUrl(projectId, refId, commitId) if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId, commitId }, '', false, 'commit'); + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId, commitId }, '', false, 'commit') if (this.cacheSvc.exists(cacheKey)) { - resolve(this.cacheSvc.get(cacheKey)); + resolve(this.cacheSvc.get(cacheKey)) } else { this.$http .get(url) .then( (response) => { - resolve(this.cacheSvc.put(cacheKey, response.data.commits[0])); + resolve(this.cacheSvc.put(cacheKey, response.data.commits[0])) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) } }) - ); + ) } - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } public createRef(refOb: RefObject, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefsURL(projectId); + const url = this.uRLSvc.getRefsURL(projectId) const cacheKey = this.apiSvc.makeCacheKey( { projectId: refOb._projectId, refId: refOb.id }, '', false, 'ref' - ); + ) this.$http .post(url, { refs: [refOb], @@ -536,30 +536,30 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }); - return; + }) + return } - const createdRef = response.data.refs[0]; + const createdRef = response.data.refs[0] const list = this.cacheSvc.get( this.apiSvc.makeCacheKey(null, projectId, false, 'refs'), true - ); + ) if (list) { - list.push(createdRef); + list.push(createdRef) } - this.cacheSvc.put(cacheKey, createdRef); - resolve(this.cacheSvc.get(cacheKey)); + this.cacheSvc.put(cacheKey, createdRef) + resolve(this.cacheSvc.get(cacheKey)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } - ); - }); + ) + }) } public updateRef(refOb: RefObject, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefsURL(projectId); + const url = this.uRLSvc.getRefsURL(projectId) this.$http .post(url, { refs: [refOb], @@ -573,49 +573,49 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }); - return; + }) + return } - const resp = response.data.refs[0]; - this.cacheSvc.put(['ref', projectId, resp.id], resp, true); - resolve(this.cacheSvc.get(['ref', projectId, resp.id])); + const resp = response.data.refs[0] + this.cacheSvc.put(['ref', projectId, resp.id], resp, true) + resolve(this.cacheSvc.get(['ref', projectId, resp.id])) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } - ); - }); + ) + }) } public deleteRef(refId: string, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefURL(projectId, refId); + const url = this.uRLSvc.getRefURL(projectId, refId) this.$http.delete(url).then( (response) => { - const key = this.apiSvc.makeCacheKey({ refId, projectId }, '', false, 'ref'); - const refOb = this.cacheSvc.get(key); + const key = this.apiSvc.makeCacheKey({ refId, projectId }, '', false, 'ref') + const refOb = this.cacheSvc.get(key) if (refOb) { - this.cacheSvc.remove(key); + this.cacheSvc.remove(key) const list = this.cacheSvc.get( this.apiSvc.makeCacheKey(null, projectId, false, 'refs'), true - ); + ) if (list) { for (let i = 0; i < list.length; i++) { if (list[i].id === refOb.id) { - list.splice(i, 1); - break; + list.splice(i, 1) + break } } } } - resolve(); + resolve() }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } - ); - }); + ) + }) } public getGroups( @@ -623,14 +623,14 @@ export class ProjectService extends BaseApiService { refId: string, updateCache?: boolean ): VePromise { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'groups'); - const url = this.uRLSvc.getGroupsURL(projectId, refId); + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'groups') + const url = this.uRLSvc.getGroupsURL(projectId, refId) if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(cacheKey) && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)); + resolve(this.cacheSvc.get(cacheKey)) } else { this.$http .get(url) @@ -642,64 +642,64 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }); - return; + }) + return } - const groups: GroupObject[] = []; + const groups: GroupObject[] = [] const reqOb = { projectId: projectId, refId: refId, commitId: 'latest', elementId: '', - }; + } for (let i = 0; i < response.data.groups.length; i++) { - let group: GroupObject = response.data.groups[i]; - reqOb.elementId = group.id; - group = this.elementSvc.cacheElement(reqOb, group); - this.cacheSvc.put(['group', projectId, refId, group.id], group, true); + let group: GroupObject = response.data.groups[i] + reqOb.elementId = group.id + group = this.elementSvc.cacheElement(reqOb, group) + this.cacheSvc.put(['group', projectId, refId, group.id], group, true) groups.push( this.cacheSvc.get(['group', projectId, refId, group.id]) - ); + ) } - this.cacheSvc.put(cacheKey, groups, false); - resolve(this.cacheSvc.get(cacheKey)); + this.cacheSvc.put(cacheKey, groups, false) + resolve(this.cacheSvc.get(cacheKey)) }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject); + this.apiSvc.handleErrorCallback(response, reject) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) } }) - ); + ) } - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } public getGroup(id: string, projectId: string, refId: string): VePromise { return new this.$q((resolve, reject) => { this.getGroups(projectId, refId).then( (data) => { - const result = this.cacheSvc.get(['group', projectId, refId, id]); + const result = this.cacheSvc.get(['group', projectId, refId, id]) if (result) { - resolve(result); + resolve(result) } else { reject({ status: 404, message: 'Group not found', type: 'error', - }); + }) } }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } } -veUtils.service('ProjectService', ProjectService); +veUtils.service('ProjectService', ProjectService) diff --git a/src/ve-utils/mms-api-client/URL.service.ts b/src/ve-utils/mms-api-client/URL.service.ts index a024dbeaf..11e0a3684 100644 --- a/src/ve-utils/mms-api-client/URL.service.ts +++ b/src/ve-utils/mms-api-client/URL.service.ts @@ -1,7 +1,7 @@ -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromiseReason } from '@ve-types/angular'; -import { VeConfig } from '@ve-types/config'; +import { VePromiseReason } from '@ve-types/angular' +import { VeConfig } from '@ve-types/config' import { ArtifactsRequest, BasicResponse, @@ -10,7 +10,7 @@ import { QueryParams, RequestObject, ViewsRequest, -} from '@ve-types/mms'; +} from '@ve-types/mms' /** * @ngdoc service @@ -33,63 +33,63 @@ import { * actually getting the resources from a different server, solution TBD) */ export class URLService { - readonly root: string; - readonly url: URL; - private token: string; - private veConfig: VeConfig = window.__env; + readonly root: string + readonly url: URL + private token: string + private veConfig: VeConfig = window.__env - static $inject = []; + static $inject = [] constructor(readonly basePath?: string, readonly apiUrl?: string) { if (!this.apiUrl) { - this.apiUrl = this.veConfig.apiUrl; + this.apiUrl = this.veConfig.apiUrl } if (!this.apiUrl) { - throw new Error('Unable to find "apiUrl" configuration for MMS. Please check your configuration file.'); + throw new Error('Unable to find "apiUrl" configuration for MMS. Please check your configuration file.') } - this.url = new URL(this.apiUrl); - this.url.pathname = this.veConfig.basePath ? this.veConfig.basePath : '/'; + this.url = new URL(this.apiUrl) + this.url.pathname = this.veConfig.basePath ? this.veConfig.basePath : '/' - this.root = `${this.apiUrl}${this.basePath ? this.basePath : ''}`; - const token = localStorage.getItem('token'); - this.token = `${token}`; + this.root = `${this.apiUrl}${this.basePath ? this.basePath : ''}` + const token = localStorage.getItem('token') + this.token = `${token}` } getRoot = (): string => { - return this.root; - }; + return this.root + } getUrl = (): URL => { - return Object.assign({}, this.url); - }; + return Object.assign({}, this.url) + } setToken = (t: string): void => { - this.token = t; - }; + this.token = t + } getAuthorizationHeaderValue = (): string => { - return 'Bearer ' + this.token; - }; + return 'Bearer ' + this.token + } getAuthorizationHeader = (headers: angular.HttpHeaderType): angular.HttpHeaderType => { if (!this.token) { - const token = localStorage.getItem('token'); + const token = localStorage.getItem('token') if (!token) { - return headers; + return headers } else { - this.setToken(token); + this.setToken(token) } } if (!headers) { - headers = this.getHeaders(); + headers = this.getHeaders() } - headers.Authorization = this.getAuthorizationHeaderValue(); - return headers; - }; + headers.Authorization = this.getAuthorizationHeaderValue() + return headers + } getMmsServer = (): string => { - return this.apiUrl; - }; + return this.apiUrl + } /** * @name veUtils/URLService#setHeader @@ -101,7 +101,7 @@ export class URLService { return { 'Content-Type': 'application/json', Authorization: 'Bearer ' + this.token, - }; + } } /** @@ -112,10 +112,10 @@ export class URLService { * @returns {boolean} Returns true if the string has '-' in it */ isTimestamp = (version?: string): boolean => { - if (!version) return false; - else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}[+]?-\d{4}$/.test(version.trim())) return true; - return false; - }; + if (!version) return false + else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}[+]?-\d{4}$/.test(version.trim())) return true + return false + } /** * @name veUtils/URLService#getMmsVersionURL @@ -124,8 +124,8 @@ export class URLService { * @returns {object} Returns object with mmsversion */ getMmsVersionURL = (): string => { - return `${this.root}/mmsversion`; - }; + return `${this.root}/mmsversion` + } /** * @name veUtils/URLService#getSiteDashboardURL @@ -135,8 +135,8 @@ export class URLService { * @returns {string} The path for site dashboard. */ getSiteDashboardURL = (site: string): string => { - return `${this.root}/orgs/${site}/projects/${site}/branches/master/elements`; - }; + return `${this.root}/orgs/${site}/projects/${site}/branches/master/elements` + } /** * @name veUtils/URLService#getExportHtmlUrl @@ -146,67 +146,67 @@ export class URLService { * @returns {string} The url */ getExportHtmlUrl = (): string => { - return this.veConfig.printUrl; - }; + return this.veConfig.printUrl + } getAuthenticationUrl = (): string => { - return `${this.root}/authentication`; - }; + return `${this.root}/authentication` + } getPermissionsLookupURL = (): string => { - return `${this.root}/permissions`; - }; + return `${this.root}/permissions` + } getOrgURL = (orgId: string): string => { - return `${this.root}/orgs/${orgId}`; - }; + return `${this.root}/orgs/${orgId}` + } getOrgsURL = (): string => { - return `${this.root}/orgs`; - }; + return `${this.root}/orgs` + } getProjectsURL = (orgId?: string): string => { - if (orgId) return `${this.root}/projects?orgId=${orgId}`; - return `${this.root}/projects`; - }; + if (orgId) return `${this.root}/projects?orgId=${orgId}` + return `${this.root}/projects` + } getProjectURL = (projectId: string): string => { - return `${this.root}/projects/${projectId}`; - }; + return `${this.root}/projects/${projectId}` + } getProjectMountsURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/mounts`; - }; + return `${this.root}/projects/${projectId}/refs/${refId}/mounts` + } getRefsURL = (projectId: string): string => { - return `${this.root}/projects/${projectId}/refs`; - }; + return `${this.root}/projects/${projectId}/refs` + } getRefURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}`; - }; + return `${this.root}/projects/${projectId}/refs/${refId}` + } getCommitsURL = (projectId: string, refId: string, timestamp?: string, limit?: number): string => { - let r = `${this.root}/projects/${projectId}/refs/${refId}/commits`; + let r = `${this.root}/projects/${projectId}/refs/${refId}/commits` if (timestamp && this.isTimestamp(timestamp)) { - r = this._addUrlParam({ maxTimestamp: timestamp }, r); + r = this._addUrlParam({ maxTimestamp: timestamp }, r) if (!limit) { - limit = 1; + limit = 1 } } if (limit) { - r = this._addUrlParam({ limit: limit }, r); + r = this._addUrlParam({ limit: limit }, r) } - return r; - }; + return r + } getCommitUrl = (projectId: string, refId: string, commitId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/commits/${commitId}`; - }; + return `${this.root}/projects/${projectId}/refs/${refId}/commits/${commitId}` + } getGroupsURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/groups`; - }; + return `${this.root}/projects/${projectId}/refs/${refId}/groups` + } /** * @name veUtils/URLService#getProjectDocumentsURL @@ -216,9 +216,9 @@ export class URLService { * @returns {string} The url */ getProjectDocumentsURL = (reqOb: RequestObject): string => { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/documents`; - return this.addVersion(r, reqOb.commitId); - }; + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/documents` + return this.addVersion(r, reqOb.commitId) + } /** * @name veUtils/URLService#getImageURL @@ -228,8 +228,8 @@ export class URLService { * @returns {string} The path for image url queries. */ getImageURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; - return this.addVersion(r, reqOb.commitId); + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` + return this.addVersion(r, reqOb.commitId) } /** @@ -240,8 +240,8 @@ export class URLService { * @returns {string} The url. */ getElementURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views/${reqOb.elementId}`; - return this.addVersion(r, reqOb.commitId); + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views/${reqOb.elementId}` + return this.addVersion(r, reqOb.commitId) } // getViewDataIdsURL (reqOb: RequestObject): string { @@ -270,16 +270,16 @@ export class URLService { // } getOwnedElementURL(reqOb: ElementsRequest): string { - let recurseString = 'recurse=true'; - if (reqOb.depth) recurseString = `depth=${reqOb.depth}`; - let r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; - r = this.addVersion(r, reqOb.commitId); + let recurseString = 'recurse=true' + if (reqOb.depth) recurseString = `depth=${reqOb.depth}` + let r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` + r = this.addVersion(r, reqOb.commitId) if (r.indexOf('?') > 0) { - r += '&' + recurseString; + r += '&' + recurseString } else { - r += '?' + recurseString; + r += '?' + recurseString } - return r; + return r } /** @@ -290,7 +290,7 @@ export class URLService { * @returns {string} The url. */ getElementHistoryURL(reqOb: ElementsRequest): string { - return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/commits`; + return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/commits` } /** @@ -303,8 +303,8 @@ export class URLService { return this.addChildViews( `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views`, reqOb.returnChildViews - ); - }; + ) + } /** * @name veUtils/URLService#getPostElementsURL @@ -314,8 +314,8 @@ export class URLService { * @returns {string} The post elements url. */ getPostElementsURL = (reqOb: RequestObject): string => { - return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements`; - }; + return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements` + } /** * @name veUtils/URLService#getPutElementsURL @@ -325,9 +325,9 @@ export class URLService { * @returns {string} The post elements url. */ getPutElementsURL = (reqOb: RequestObject): string => { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views`; - return this.addVersion(r, reqOb.commitId); - }; + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views` + return this.addVersion(r, reqOb.commitId) + } /** * @name veUtils/URLService#getElementSearchURL @@ -338,18 +338,18 @@ export class URLService { * @returns {string} The post elements url. */ getElementSearchURL = (reqOb: RequestObject, queryParams?: QueryParams): string => { - let r: string; - let urlParams = ''; + let r: string + let urlParams = '' if (queryParams) { - urlParams = this._addUrlParam(queryParams); + urlParams = this._addUrlParam(queryParams) } if (urlParams !== '') { - r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search${urlParams}`; + r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search${urlParams}` } else { - r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search`; + r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search` } - return r; - }; + return r + } /** * @ngdocs method @@ -362,9 +362,9 @@ export class URLService { */ getArtifactURL(reqOb: ElementsRequest | ArtifactsRequest, artifactExtension?: string): string { const ext = - artifactExtension !== undefined ? artifactExtension : (reqOb as ArtifactsRequest).artifactExtension; - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}`; - return this.addToken(this.addVersion(r, reqOb.commitId)); + artifactExtension !== undefined ? artifactExtension : (reqOb as ArtifactsRequest).artifactExtension + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}` + return this.addToken(this.addVersion(r, reqOb.commitId)) } /** @@ -377,9 +377,9 @@ export class URLService { * @returns {string} url */ getArtifactEmbedURL(reqOb: ArtifactsRequest, artifactExtension: string): string { - const ext = artifactExtension !== undefined ? artifactExtension : 'undefined'; - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}`; - return this.addVersion(r, reqOb.commitId); + const ext = artifactExtension !== undefined ? artifactExtension : 'undefined' + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}` + return this.addVersion(r, reqOb.commitId) } /** @@ -391,8 +391,8 @@ export class URLService { * @returns {string} url */ getPutArtifactsURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; - return this.addVersion(r, reqOb.commitId); + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` + return this.addVersion(r, reqOb.commitId) } /** @@ -404,16 +404,16 @@ export class URLService { * @returns {string} url */ getArtifactHistoryURL(reqOb: ElementsRequest): string { - return this.getElementHistoryURL(reqOb); + return this.getElementHistoryURL(reqOb) } getCheckTokenURL = (): string => { - return `${this.root}/checkAuth`; //TODO remove when server returns 404 - }; + return `${this.root}/checkAuth` //TODO remove when server returns 404 + } getPersonURL = (username: string): string => { - return `${this.root}/users?user=${username}`; - }; + return `${this.root}/users?user=${username}` + } /** * @name veUtils/URLService#handleHttpStatus @@ -435,22 +435,22 @@ export class URLService { handleHttpStatus>( response: angular.IHttpResponse ): VePromiseReason { - const result: VePromiseReason = response; - const data: U = result.data; - if (result.status === 404) result.message = 'Not Found'; + const result: VePromiseReason = response + const data: U = result.data + if (result.status === 404) result.message = 'Not Found' else if (result.status === 500) { if (typeof data === 'string' && data.indexOf('ENOTFOUND') >= 0) - result.message = 'Network Error (Please check network)'; - else result.message = 'Server Error'; - } else if (result.status === 401 || result.status === 403) result.message = 'Permission Error'; - else if (result.status === 409) result.message = 'Conflict'; - else if (result.status === 400) result.message = 'BadRequestObject'; - else if (result.status === 410) result.message = 'Deleted'; - else if (result.status === 408) result.message = 'Timed Out'; + result.message = 'Network Error (Please check network)' + else result.message = 'Server Error' + } else if (result.status === 401 || result.status === 403) result.message = 'Permission Error' + else if (result.status === 409) result.message = 'Conflict' + else if (result.status === 400) result.message = 'BadRequestObject' + else if (result.status === 410) result.message = 'Deleted' + else if (result.status === 408) result.message = 'Timed Out' else if (result.status === 501) { - result.message = 'Caching'; - } else result.message = 'Timed Out (Please check network)'; - return result; + result.message = 'Caching' + } else result.message = 'Timed Out (Please check network)' + return result } /** @@ -462,18 +462,18 @@ export class URLService { * @returns {string} The url with commitId parameter added. */ private addVersion = (url: string, version: string): string => { - const r = url; + const r = url if (version && version !== 'latest') { - return this._addUrlParam({ commitId: version }, url); + return this._addUrlParam({ commitId: version }, url) } - return r; - }; + return r + } private addChildViews = (url: string, add: boolean): string => { - const r = url; - if (!add) return r; - return this._addUrlParam({ childviews: true }, r); - }; + const r = url + if (!add) return r + return this._addUrlParam({ childviews: true }, r) + } /** * @name veUtils/URLService#addToken @@ -483,31 +483,31 @@ export class URLService { * @returns {string} The url with commitId parameter added. */ private addToken = (url: string): string => { - return this._addUrlParam({ token: this.token }, url); - }; + return this._addUrlParam({ token: this.token }, url) + } private _addUrlParam( paramOb: { - [key: string]: string | boolean | number; + [key: string]: string | boolean | number }, url?: string ): string { - let urlParams = ''; + let urlParams = '' if (url) { - urlParams = url; + urlParams = url } for (const [key, value] of Object.entries(paramOb)) { - let v: string; - if (typeof value === 'string') v = value; - else v = value.toString(); + let v: string + if (typeof value === 'string') v = value + else v = value.toString() if (urlParams.indexOf('?') > 0) { - urlParams += `&${key}=${v}`; + urlParams += `&${key}=${v}` } else { - urlParams += `?${key}=${v}`; + urlParams += `?${key}=${v}` } } - return urlParams; + return urlParams } } -veUtils.service('URLService', URLService); +veUtils.service('URLService', URLService) diff --git a/src/ve-utils/mms-api-client/User.service.ts b/src/ve-utils/mms-api-client/User.service.ts index e14a27a69..74108055a 100644 --- a/src/ve-utils/mms-api-client/User.service.ts +++ b/src/ve-utils/mms-api-client/User.service.ts @@ -1,14 +1,14 @@ -import { CacheService } from '@ve-utils/core'; -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; -import { URLService } from '@ve-utils/mms-api-client/URL.service'; +import { CacheService } from '@ve-utils/core' +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' +import { URLService } from '@ve-utils/mms-api-client/URL.service' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; -import { UserObject, UsersResponse } from '@ve-types/mms'; +import { VePromise, VeQService } from '@ve-types/angular' +import { UserObject, UsersResponse } from '@ve-types/mms' export class UserService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'URLService']; + static $inject = ['$q', '$http', 'CacheService', 'URLService'] constructor( private $q: VeQService, @@ -16,20 +16,20 @@ export class UserService extends BaseApiService { private cacheSvc: CacheService, private uRLSvc: URLService ) { - super(); + super() } getUserData(username: string): VePromise { - const key = ['user', username]; - const url = this.uRLSvc.getPersonURL(username); - const cached = this.cacheSvc.get(key); + const key = ['user', username] + const url = this.uRLSvc.getPersonURL(username) + const cached = this.cacheSvc.get(key) if (this._isInProgress(url)) { - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } if (cached) { return new this.$q((resolve, reject) => { - return resolve(cached); - }); + return resolve(cached) + }) } this._addInProgress( url, @@ -42,25 +42,25 @@ export class UserService extends BaseApiService { reject({ status: 404, message: 'User not found', - }); + }) } else { - this.cacheSvc.put(key, response.data.users[0], false); - resolve(this.cacheSvc.get(key)); + this.cacheSvc.put(key, response.data.users[0], false) + resolve(this.cacheSvc.get(key)) } }, (response: angular.IHttpResponse) => { - this.uRLSvc.handleHttpStatus(response); - reject(response); + this.uRLSvc.handleHttpStatus(response) + reject(response) } ) .finally(() => { - this._removeInProgress(url); - }); + this._removeInProgress(url) + }) }) - ); + ) - return this._getInProgress(url) as VePromise; + return this._getInProgress(url) as VePromise } } -veUtils.service('UserService', UserService); +veUtils.service('UserService', UserService) diff --git a/src/ve-utils/mms-api-client/Value.service.ts b/src/ve-utils/mms-api-client/Value.service.ts index 2c52cdd83..411231339 100644 --- a/src/ve-utils/mms-api-client/Value.service.ts +++ b/src/ve-utils/mms-api-client/Value.service.ts @@ -1,15 +1,15 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { EditObject } from '@ve-utils/core'; -import { ApiService } from '@ve-utils/mms-api-client/Api.service'; -import { ElementService } from '@ve-utils/mms-api-client/Element.service'; -import { ValueSpec } from '@ve-utils/utils'; +import { EditObject } from '@ve-utils/core' +import { ApiService } from '@ve-utils/mms-api-client/Api.service' +import { ElementService } from '@ve-utils/mms-api-client/Element.service' +import { ValueSpec } from '@ve-utils/utils' -import { PropertySpec } from '@ve-components'; +import { PropertySpec } from '@ve-components' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VeQService } from '@ve-types/angular'; +import { VePromise, VeQService } from '@ve-types/angular' import { ConstraintObject, ElementObject, @@ -22,7 +22,7 @@ import { SlotObject, TaggedValueObject, ValueObject, -} from '@ve-types/mms'; +} from '@ve-types/mms' export class ValueService { private valueTypes: { [type: string]: string } = { @@ -30,28 +30,28 @@ export class ValueService { port: 'defaultValue', slot: 'value', constraint: 'specification', - }; + } public addValueTypes: { [primitiveType: string]: string } = { string: 'LiteralString', boolean: 'LiteralBoolean', integer: 'LiteralInteger', real: 'LiteralReal', - }; + } - private taggedValue: string = 'value'; - static $inject = ['$q', 'ApiService', 'ElementService']; + private taggedValue: string = 'value' + static $inject = ['$q', 'ApiService', 'ElementService'] constructor(private $q: VeQService, private apiSvc: ApiService, private elementSvc: ElementService) {} public addValue = (editOb: EditObject, type: string): LiteralObject => { - const edit = editOb.element; - let newValueSpec: ValueSpec; + const edit = editOb.element + let newValueSpec: ValueSpec let elementOb: LiteralObject = { id: '', _projectId: edit._projectId, _refId: edit._refId, type: '', - }; + } switch (type) { case 'LiteralBoolean': { elementOb = Object.assign(elementOb, { @@ -59,9 +59,9 @@ export class ValueService { value: false, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }); - newValueSpec = new ValueSpec(elementOb); - break; + }) + newValueSpec = new ValueSpec(elementOb) + break } case 'LiteralInteger': { elementOb = Object.assign(elementOb, { @@ -69,9 +69,9 @@ export class ValueService { value: 0, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }); - newValueSpec = new ValueSpec(elementOb); - break; + }) + newValueSpec = new ValueSpec(elementOb) + break } case 'LiteralString': { elementOb = Object.assign(elementOb, { @@ -79,9 +79,9 @@ export class ValueService { value: '', id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }); - newValueSpec = new ValueSpec(elementOb); - break; + }) + newValueSpec = new ValueSpec(elementOb) + break } case 'LiteralReal': { elementOb = Object.assign(elementOb, { @@ -89,9 +89,9 @@ export class ValueService { value: 0.0, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }); - newValueSpec = new ValueSpec(elementOb); - break; + }) + newValueSpec = new ValueSpec(elementOb) + break } default: { elementOb = Object.assign(elementOb, { @@ -99,21 +99,21 @@ export class ValueService { value: {}, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }); + }) } } if (edit.type == 'Property' || edit.type == 'Port') { - edit.defaultValue = newValueSpec; + edit.defaultValue = newValueSpec } - return newValueSpec; - }; + return newValueSpec + } public addEnumerationValue = ( propertySpec: PropertySpec, editOb: EditObject ): InstanceValueObject | ElementValueObject => { - const elementOb = editOb.element; + const elementOb = editOb.element let newValueSpec: InstanceValueObject | ElementValueObject = new ValueSpec({ type: 'InstanceValue', instanceId: propertySpec.options[0], @@ -121,7 +121,7 @@ export class ValueService { _refId: elementOb._refId, id: this.apiSvc.createUniqueId(), ownerId: elementOb.id, - }); + }) if (propertySpec.isTaggedValue) { newValueSpec = new ValueSpec({ type: 'ElementValue', @@ -130,51 +130,51 @@ export class ValueService { _refId: elementOb._refId, id: this.apiSvc.createUniqueId(), ownerId: elementOb.id, - }); + }) } - return newValueSpec; - }; + return newValueSpec + } public getValues(elementOb: ElementObject): ValueObject[] { if (elementOb.type === 'Property' || elementOb.type === 'Port') { if (elementOb.defaultValue) { - return [elementOb.defaultValue] as ValueObject[]; + return [elementOb.defaultValue] as ValueObject[] } else { - return []; + return [] } } if (elementOb.type === 'Slot') { - return (elementOb as SlotObject).value; + return (elementOb as SlotObject).value } if (elementOb.type === 'Constraint' && elementOb.specification) { - return [(elementOb as ConstraintObject).specification]; + return [(elementOb as ConstraintObject).specification] } if (elementOb.type === 'Expression') { - return (elementOb as ExpressionObject).operand; + return (elementOb as ExpressionObject).operand } - const i = elementOb.type.indexOf('TaggedValue'); + const i = elementOb.type.indexOf('TaggedValue') if (i > 0) { - let spoofType = ''; - const type = elementOb.type.slice(0, i); + let spoofType = '' + const type = elementOb.type.slice(0, i) if (type === 'Element') { - spoofType = 'ElementValue'; - elementOb.value = []; + spoofType = 'ElementValue' + elementOb.value = [] for (const [index, val] of (elementOb as ElementTaggedValueObject).valueIds.entries()) { - (elementOb as ElementTaggedValueObject).value.push({ + ;(elementOb as ElementTaggedValueObject).value.push({ id: `${elementOb.id}-slotvalue-${index}-elementvalue`, type: spoofType, elementId: val, _projectId: elementOb._projectId, _refId: elementOb._refId, - } as ElementValueObject); + } as ElementValueObject) } } else { - spoofType = `Literal${type}`; + spoofType = `Literal${type}` for (const val of (elementOb as TaggedValueObject).value) { - val.type = spoofType; + val.type = spoofType } } - return (elementOb as TaggedValueObject).value; + return (elementOb as TaggedValueObject).value } } @@ -187,53 +187,53 @@ export class ValueService { * For unsuccessful saves, it will be rejected with an object with reason. */ public isEnumeration(elementOb: ElementObject): VePromise { - const deferred = this.$q.defer(); + const deferred = this.$q.defer() if (elementOb.type === 'Enumeration') { - const isEnumeration = true; + const isEnumeration = true const reqOb: ElementsRequest = { elementId: elementOb.id, projectId: elementOb._projectId, refId: elementOb._refId, - }; + } const query = { params: { ownerId: elementOb.id, }, - }; + } this.elementSvc.search(reqOb, query).then( (val) => { - const newArray: ElementObject[] = []; + const newArray: ElementObject[] = [] // Filter for enumeration type for (let i = 0; i < val.elements.length; i++) { if (val.elements[i].type === 'EnumerationLiteral') { - newArray.push(val.elements[i]); + newArray.push(val.elements[i]) } } newArray.sort((a, b) => { - return a.name.localeCompare(b.name); - }); + return a.name.localeCompare(b.name) + }) deferred.resolve({ options: newArray, isEnumeration: isEnumeration, - }); + }) }, (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } else { - deferred.resolve({ options: [], isEnumeration: false }); + deferred.resolve({ options: [], isEnumeration: false }) } - return deferred.promise; + return deferred.promise } public isValue(elementOb: ElementObject): boolean { - const type = elementOb.type; - return Object.keys(this.valueTypes).includes(type.toLowerCase()) || this.isTaggedValue(elementOb); + const type = elementOb.type + return Object.keys(this.valueTypes).includes(type.toLowerCase()) || this.isTaggedValue(elementOb) } public isTaggedValue(elementOb: ElementObject): boolean { - return elementOb.type.endsWith('TaggedValue'); + return elementOb.type.endsWith('TaggedValue') } public hasValue(elementOb: ElementObject): boolean { @@ -245,92 +245,92 @@ export class ValueService { (elementOb.specification && Object.keys((elementOb as ConstraintObject).specification).length !== 0) || // Check if Slots and Tagged Values have any entries (elementOb.value && (elementOb as LiteralObject[]>).value.length > 0)) - ); + ) } public isEqual(a: ElementObject, b: ElementObject): boolean { if (this.valueTypes[a.type.toLowerCase()]) { - return _.isEqual(a[this.valueTypes[a.type.toLowerCase()]], b[this.valueTypes[a.type.toLowerCase()]]); + return _.isEqual(a[this.valueTypes[a.type.toLowerCase()]], b[this.valueTypes[a.type.toLowerCase()]]) } else if (this.isTaggedValue(a)) { - return _.isEqual(a[this.taggedValue], b[this.taggedValue]); + return _.isEqual(a[this.taggedValue], b[this.taggedValue]) } } public getPropertySpec(elementOb: ElementObject): VePromise { - const deferred = this.$q.defer(); - let id: string = elementOb.typeId; - let isSlot = false; - let isEnumeration = false; - let isTaggedValue = false; - let options: ElementObject[] = []; + const deferred = this.$q.defer() + let id: string = elementOb.typeId + let isSlot = false + let isEnumeration = false + let isTaggedValue = false + let options: ElementObject[] = [] if (elementOb.type === 'Slot') { - isSlot = true; - id = (elementOb as SlotObject).definingFeatureId; + isSlot = true + id = (elementOb as SlotObject).definingFeatureId } if (elementOb.type.includes('TaggedValue')) { - isTaggedValue = true; - id = (elementOb as TaggedValueObject).tagDefinitionId; + isTaggedValue = true + id = (elementOb as TaggedValueObject).tagDefinitionId } if (!id) { //no property type, will not be enum - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); - return deferred.promise; + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + return deferred.promise } // Get defining feature or type info const reqOb = { elementId: id, projectId: elementOb._projectId, refId: elementOb._refId, - }; + } this.elementSvc.getElement(reqOb).then( (value) => { if (isSlot || isTaggedValue) { if (!value.typeId) { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); - return; + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + return } //if it is a slot or tagged value check if the definition type is enumeration - reqOb.elementId = value.typeId; + reqOb.elementId = value.typeId this.elementSvc.getElement(reqOb).then( (val) => { this.isEnumeration(val).then( (enumValue: PropertySpec) => { if (enumValue.isEnumeration) { - isEnumeration = enumValue.isEnumeration; - options = enumValue.options; + isEnumeration = enumValue.isEnumeration + options = enumValue.options } - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) }, () => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) } - ); + ) }, () => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) } - ); + ) } else { this.isEnumeration(value).then( (enumValue) => { if (enumValue.isEnumeration) { - isEnumeration = enumValue.isEnumeration; - options = enumValue.options; + isEnumeration = enumValue.isEnumeration + options = enumValue.options } - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) }, (reason) => { - deferred.reject(reason); + deferred.reject(reason) } - ); + ) } }, (reason) => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) } - ); - return deferred.promise; + ) + return deferred.promise } } -veUtils.service('ValueService', ValueService); +veUtils.service('ValueService', ValueService) diff --git a/src/ve-utils/mms-api-client/View.service.ts b/src/ve-utils/mms-api-client/View.service.ts index 931db9dcd..b01678771 100644 --- a/src/ve-utils/mms-api-client/View.service.ts +++ b/src/ve-utils/mms-api-client/View.service.ts @@ -1,15 +1,15 @@ -import { IQResolveReject } from 'angular'; -import _ from 'lodash'; +import { IQResolveReject } from 'angular' +import _ from 'lodash' -import { CacheService } from '@ve-utils/core'; -import { ElementService, URLService, ApiService } from '@ve-utils/mms-api-client'; -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; -import { SchemaService } from '@ve-utils/model-schema'; -import { Class, Expression, InstanceSpec, Package, ValueSpec } from '@ve-utils/utils'; +import { CacheService } from '@ve-utils/core' +import { ElementService, URLService, ApiService } from '@ve-utils/mms-api-client' +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' +import { SchemaService } from '@ve-utils/model-schema' +import { Class, Expression, InstanceSpec, Package, ValueSpec } from '@ve-utils/utils' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular'; +import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular' import { DocumentObject, ElementObject, @@ -35,32 +35,32 @@ import { ElementsResponse, GenericResponse, BasicResponse, -} from '@ve-types/mms'; -import { TreeBranch, View2NodeMap } from '@ve-types/tree'; +} from '@ve-types/mms' +import { TreeBranch, View2NodeMap } from '@ve-types/tree' export interface ViewData { - id: string; - api: ViewApi; - number?: string; - topLevel?: boolean; - first?: boolean; - data?: ViewObject; + id: string + api: ViewApi + number?: string + topLevel?: boolean + first?: boolean + data?: ViewObject } export interface ViewApi { - elementClicked(elementOb: ElementObject): void; - elementTranscluded(elementOb: ElementObject, type: string): void; + elementClicked(elementOb: ElementObject): void + elementTranscluded(elementOb: ElementObject, type: string): void } export interface DocumentMetadata { - numberingDepth: number; - numberingSeparator: string; - 'top-left'?: string; - top?: string; - 'top-right'?: string; - 'bottom-left'?: string; - bottom?: string; - 'bottom-right'?: string; + numberingDepth: number + numberingSeparator: string + 'top-left'?: string + top?: string + 'top-right'?: string + 'bottom-left'?: string + bottom?: string + 'bottom-right'?: string } /** @@ -78,9 +78,9 @@ export interface DocumentMetadata { * */ export class ViewService extends BaseApiService { - private schema: string = 'cameo'; + private schema: string = 'cameo' - static $inject = ['$q', '$http', 'URLService', 'ElementService', 'ApiService', 'CacheService', 'SchemaService']; + static $inject = ['$q', '$http', 'URLService', 'ElementService', 'ApiService', 'CacheService', 'SchemaService'] constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -90,7 +90,7 @@ export class ViewService extends BaseApiService { private cacheSvc: CacheService, private schemaSvc: SchemaService ) { - super(); + super() } /** @@ -102,86 +102,86 @@ export class ViewService extends BaseApiService { */ public downgradeDocument(elementOb: ViewObject): VePromise> { return new this.$q>((resolve, reject) => { - const clone = _.cloneDeep(elementOb); - clone.appliedStereotypeIds = [this.schemaSvc.getSchema('VIEW_SID', this.schema)]; + const clone = _.cloneDeep(elementOb) + clone.appliedStereotypeIds = [this.schemaSvc.getSchema('VIEW_SID', this.schema)] this.elementSvc.updateElements([clone], false).then( (data) => { - const cacheKey = ['documents', elementOb._projectId, elementOb._refId]; - let index = -1; - const projectDocs: ViewObject[] = this.cacheSvc.get(cacheKey); + const cacheKey = ['documents', elementOb._projectId, elementOb._refId] + let index = -1 + const projectDocs: ViewObject[] = this.cacheSvc.get(cacheKey) if (projectDocs) { for (let i = 0; i < projectDocs.length; i++) { if (projectDocs[i].id === elementOb.id) { - index = i; - break; + index = i + break } } if (index >= 0) { - projectDocs.splice(index, 1); + projectDocs.splice(index, 1) } } return resolve( data.filter((returnOb) => { - return returnOb.id === elementOb.id; + return returnOb.id === elementOb.id })[0] - ); + ) }, (reason) => { - return reject(reason); + return reject(reason) } - ); - }); + ) + }) } public getAllViews(reqOb: RequestObject, update?: boolean): VePromise { - const key = this.apiSvc.makeCacheKey(reqOb, '', false, 'views'); - const inProgKey = key.join('-'); + const key = this.apiSvc.makeCacheKey(reqOb, '', false, 'views') + const inProgKey = key.join('-') if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q((resolve, reject) => { - const cached = this.cacheSvc.get(key); + const cached = this.cacheSvc.get(key) if (cached && !update) { - resolve(cached); - this._removeInProgress(inProgKey); + resolve(cached) + this._removeInProgress(inProgKey) } else { - const searchTerms: VePromise, SearchResponse>[] = []; + const searchTerms: VePromise, SearchResponse>[] = [] const stereoIds = [ this.schemaSvc.getSchema('VIEW_SID', this.schema), this.schemaSvc.getSchema('DOCUMENT_SID', this.schema), ...this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema), - ]; + ] stereoIds.forEach((stId) => { searchTerms.push( this.elementSvc.search(reqOb, { params: { appliedStereotypeIds: stId }, }) - ); - }); + ) + }) this.$q .all(searchTerms) .then( (results) => { - let viewKeys = {}; + let viewKeys = {} results.forEach((result) => { - viewKeys = _(viewKeys).merge(_.keyBy(result.elements, 'id')); - }); - const views = _(viewKeys).values().value() as ViewObject[]; - resolve(this.cacheSvc.put(key, views)); + viewKeys = _(viewKeys).merge(_.keyBy(result.elements, 'id')) + }) + const views = _(viewKeys).values().value() as ViewObject[] + resolve(this.cacheSvc.put(key, views)) }, (reason: VePromiseReason>) => { - reject(reason); + reject(reason) } ) .finally(() => { - this._removeInProgress(inProgKey); - }); + this._removeInProgress(inProgKey) + }) } }) - ); + ) } - return this._getInProgress(inProgKey) as VePromise; + return this._getInProgress(inProgKey) as VePromise } /** @@ -201,46 +201,46 @@ export class ViewService extends BaseApiService { weight: number, update?: boolean ): VePromise { - this.apiSvc.normalize(reqOb); - const key = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'viewElements').join('-'); + this.apiSvc.normalize(reqOb) + const key = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'viewElements').join('-') if (this._isInProgress(key)) { - return this._getInProgress(key) as VePromise; + return this._getInProgress(key) as VePromise } - const cached = this.cacheSvc.get(key); + const cached = this.cacheSvc.get(key) if (cached && !update) { - return this.$q.resolve(cached); + return this.$q.resolve(cached) } this._addInProgress( key, new this.$q((resolve, reject) => { this.elementSvc.getElement(reqOb, weight, update).then( (viewOrInstance: ViewObject | ViewInstanceSpec) => { - const toGet: string[] = []; - let results: ElementObject[] = []; + const toGet: string[] = [] + let results: ElementObject[] = [] if (viewOrInstance.type === 'Class') { - const view: ViewObject = viewOrInstance as ViewObject; + const view: ViewObject = viewOrInstance as ViewObject if (view._displayedElementIds) { - const displayed: string[] = view._displayedElementIds; + const displayed: string[] = view._displayedElementIds if (Array.isArray(displayed) && displayed.length > 0) { - toGet.push(...displayed); + toGet.push(...displayed) } } if (view._contents && view._contents.operand) { - const contents = view._contents.operand; + const contents = view._contents.operand for (let i = 0; i < contents.length; i++) { if (contents[i] && contents[i].instanceId) { - toGet.push(contents[i].instanceId); + toGet.push(contents[i].instanceId) } } } } else if (viewOrInstance.type === 'InstanceSpecification') { - const view = viewOrInstance as ViewInstanceSpec; + const view = viewOrInstance as ViewInstanceSpec if (view.specification) { if (view.specification.operand) { - const specContents = view.specification.operand as InstanceValueObject[]; + const specContents = view.specification.operand as InstanceValueObject[] for (let j = 0; j < specContents.length; j++) { if (specContents[j] && specContents[j].instanceId) { - toGet.push(specContents[j].instanceId); + toGet.push(specContents[j].instanceId) } } } @@ -252,51 +252,51 @@ export class ViewService extends BaseApiService { ) { const tableJson: PresentTableObject = JSON.parse( view.specification.value - ) as PresentTableObject; + ) as PresentTableObject if (tableJson.body) { - toGet.push(...this.collectTableSources(tableJson)); + toGet.push(...this.collectTableSources(tableJson)) } } } } - const toGetReqOb: ElementsRequest = Object.assign(reqOb, { elementId: toGet }); + const toGetReqOb: ElementsRequest = Object.assign(reqOb, { elementId: toGet }) this.elementSvc .getElements(toGetReqOb, weight, update) .then((data) => { - results = data; + results = data }) .finally(() => { - this.cacheSvc.put(key, results); - this._removeInProgress(key); - resolve(results); - }); + this.cacheSvc.put(key, results) + this._removeInProgress(key) + resolve(results) + }) }, (reason) => { - this._removeInProgress(key); - reject(reason); + this._removeInProgress(key) + reject(reason) } - ); + ) }) - ); - return this._getInProgress(key) as VePromise; + ) + return this._getInProgress(key) as VePromise } public collectTableSources(table: PresentTableObject): string[] { - const sources: string[] = []; - const body = table.body; + const sources: string[] = [] + const body = table.body body.forEach((row) => { row.forEach((cell) => { cell.content.forEach((thing) => { if (thing.type === 'Table' && thing.body) { - sources.push(...this.collectTableSources(thing as PresentTableObject)); + sources.push(...this.collectTableSources(thing as PresentTableObject)) } else if (thing.type === 'Paragraph' && thing.source) { - sources.push((thing as PresentTextObject).source); + sources.push((thing as PresentTextObject).source) } - }); - }); - }); - return sources; + }) + }) + }) + return sources } /** @@ -330,26 +330,26 @@ export class ViewService extends BaseApiService { ) => void, seen?: { [key: string]: ViewObject } ): VePromise { - let seenViews = seen; - if (!seenViews) seenViews = {}; + let seenViews = seen + if (!seenViews) seenViews = {} return new this.$q((resolve, reject) => { - const curItem: TreeBranch | string[] = curItemFunc(v, aggr, propId); - seenViews[v.id] = v; - const childIds: string[] = []; - const childAggrs: string[] = []; - const childPropIds: string[] = []; + const curItem: TreeBranch | string[] = curItemFunc(v, aggr, propId) + seenViews[v.id] = v + const childIds: string[] = [] + const childAggrs: string[] = [] + const childPropIds: string[] = [] if (!v._childViews || v._childViews.length === 0 || aggr === 'none') { if (!Array.isArray(curItem) && curItem.loading) { - curItem.loading = false; + curItem.loading = false } - resolve(curItem); - return; + resolve(curItem) + return } for (let i = 0; i < v._childViews.length; i++) { - if (seenViews[v._childViews[i].id]) continue; - childIds.push(v._childViews[i].id); - childAggrs.push(v._childViews[i].aggregation); - childPropIds.push(v._childViews[i].propertyId); + if (seenViews[v._childViews[i].id]) continue + childIds.push(v._childViews[i].id) + childAggrs.push(v._childViews[i].aggregation) + childPropIds.push(v._childViews[i].propertyId) } this.elementSvc .getElements( @@ -361,15 +361,15 @@ export class ViewService extends BaseApiService { 2 ) .then((childViews: ViewObject[]) => { - const mapping: { [id: string]: ViewObject } = {}; + const mapping: { [id: string]: ViewObject } = {} for (let i = 0; i < childViews.length; i++) { - mapping[childViews[i].id] = childViews[i]; + mapping[childViews[i].id] = childViews[i] } - const childPromises: VePromise[] = []; - const childNodes: (string[] | TreeBranch)[] = []; - const processedChildViews: ViewObject[] = []; + const childPromises: VePromise[] = [] + const childNodes: (string[] | TreeBranch)[] = [] + const processedChildViews: ViewObject[] = [] for (let i = 0; i < childIds.length; i++) { - const child = mapping[childIds[i]]; + const child = mapping[childIds[i]] if (child && this.apiSvc.isView(child)) { //what if not found?? childPromises.push( @@ -384,26 +384,26 @@ export class ViewService extends BaseApiService { childrenFunc, seenViews ) - ); - childNodes.push(curItemFunc(child, childAggrs[i], childPropIds[i])); + ) + childNodes.push(curItemFunc(child, childAggrs[i], childPropIds[i])) processedChildViews.push({ id: child.id, _projectId: child._projectId, _refId: child._refId, aggregation: childAggrs[i], propertyId: childPropIds[i], - }); + }) } } - v._childViews = processedChildViews; + v._childViews = processedChildViews if (childrenFunc) { - childrenFunc(curItem, childNodes, reject); + childrenFunc(curItem, childNodes, reject) } this.$q.all(childPromises).then(() => { - resolve(curItem); - }, reject); - }, reject); - }); + resolve(curItem) + }, reject) + }, reject) + }) } /** @@ -416,7 +416,7 @@ export class ViewService extends BaseApiService { * @returns {Promise} The promise would be resolved with updated parent view object */ public addViewToParentView(reqOb: ViewCreationRequest): VePromise { - this.apiSvc.normalize(reqOb); + this.apiSvc.normalize(reqOb) return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -436,10 +436,10 @@ export class ViewService extends BaseApiService { id: data.id, _childViews: [], type: data.type, - }; - clone._childViews = []; + } + clone._childViews = [] if (data._childViews) { - clone._childViews.push(..._.cloneDeep(data._childViews)); + clone._childViews.push(..._.cloneDeep(data._childViews)) } clone._childViews.push({ id: reqOb.viewId, @@ -447,21 +447,21 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, type: data.type, - }); + }) this.elementSvc.updateElement(clone, true).then( (data2) => { - resolve(data2); + resolve(data2) }, (reason) => { - reject(reason); + reject(reason) } - ); + ) }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } /** @@ -472,7 +472,7 @@ export class ViewService extends BaseApiService { * @returns {IPromise} The promise would be resolved with updated parent View object */ public removeViewFromParentView(reqOb: ViewsRequest): VePromise { - this.apiSvc.normalize(reqOb); + this.apiSvc.normalize(reqOb) return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -494,30 +494,30 @@ export class ViewService extends BaseApiService { id: data.id, type: data.type, _childViews: _.cloneDeep(data._childViews), - }; + } for (let i = 0; i < clone._childViews.length; i++) { if (clone._childViews[i].id === reqOb.viewId) { - clone._childViews.splice(i, 1); - break; + clone._childViews.splice(i, 1) + break } } this.elementSvc.updateElement(clone, true).then( (data2) => { - resolve(data2); + resolve(data2) }, (reason) => { - reject(reason); + reject(reason) } - ); + ) } else { - resolve(data); + resolve(data) } }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } /** @@ -537,7 +537,7 @@ export class ViewService extends BaseApiService { instanceValOb: InstanceValueObject, addPeIndex: number ): VePromise { - this.apiSvc.normalize(reqOb); + this.apiSvc.normalize(reqOb) return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -555,20 +555,20 @@ export class ViewService extends BaseApiService { _refId: data._refId, type: data.type, id: data.id, - }; - let key = '_contents'; + } + let key = '_contents' if (this.isSection(data)) { - key = 'specification'; + key = 'specification' } - const keyValue: ValueObject = data[key] as ValueObject; - let cloneValue: ValueObject; + const keyValue: ValueObject = data[key] as ValueObject + let cloneValue: ValueObject if (keyValue) { - cloneValue = _.cloneDeep(keyValue); + cloneValue = _.cloneDeep(keyValue) if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(data) ? this.apiSvc.createUniqueId() - : data.id + '_vc_expression'; - cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc'; + : data.id + '_vc_expression' + cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc' } } else { cloneValue = new Expression({ @@ -578,39 +578,39 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, ownerId: this.isSection(data) ? data.id : data.id + '_vc', - }); + }) } - instanceValOb.ownerId = cloneValue.id; + instanceValOb.ownerId = cloneValue.id if (!instanceValOb.id) { - instanceValOb.id = this.apiSvc.createUniqueId(); + instanceValOb.id = this.apiSvc.createUniqueId() } if (addPeIndex >= -1) (cloneValue as ExpressionObject).operand.splice( addPeIndex + 1, 0, new ValueSpec(instanceValOb) - ); + ) else { - (cloneValue as ExpressionObject).operand.push( + ;(cloneValue as ExpressionObject).operand.push( new ValueSpec(instanceValOb) - ); + ) } - clone[key] = cloneValue; + clone[key] = cloneValue this.elementSvc.updateElement(clone, false).then( (data2) => { - resolve(data2); + resolve(data2) }, (reason) => { - reject(reason); + reject(reason) } - ); + ) }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } /** @@ -625,7 +625,7 @@ export class ViewService extends BaseApiService { reqOb: ElementsRequest, instanceVal?: InstanceValueObject ): VePromise { - this.apiSvc.normalize(reqOb); + this.apiSvc.normalize(reqOb) return new this.$q((resolve, reject) => { if (instanceVal) { this.elementSvc.getElement(reqOb, 2).then( @@ -636,20 +636,20 @@ export class ViewService extends BaseApiService { type: data.type, //_modified: data._modified, id: data.id, - }; - let key = '_contents'; + } + let key = '_contents' if (this.isSection(data)) { - key = 'specification'; + key = 'specification' } - const keyValue = data[key] as ValueObject; - let cloneValue: ValueObject; + const keyValue = data[key] as ValueObject + let cloneValue: ValueObject if (keyValue) { - cloneValue = _.cloneDeep(keyValue); + cloneValue = _.cloneDeep(keyValue) if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(data) ? this.apiSvc.createUniqueId() - : data.id + '_vc_expression'; - cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc'; + : data.id + '_vc_expression' + cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc' } } else { cloneValue = new Expression({ @@ -659,34 +659,34 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, ownerId: this.isSection(data) ? data.id : data.id + '_vc', - }); + }) } if (cloneValue && cloneValue.operand) { const operands: InstanceValueObject[] = (keyValue as ExpressionObject) - .operand; + .operand for (let i = 0; i < operands.length; i++) { if (instanceVal.instanceId === operands[i].instanceId) { - (cloneValue as ExpressionObject).operand.splice(i, 1); - break; + ;(cloneValue as ExpressionObject).operand.splice(i, 1) + break } } } - clone[key] = cloneValue; + clone[key] = cloneValue this.elementSvc.updateElement(clone, false).then( (data2) => { - resolve(data2); + resolve(data2) }, (reason) => { - reject(reason); + reject(reason) } - ); + ) }, (reason) => { - reject(reason); + reject(reason) } - ); + ) } - }); + }) } /** @@ -705,23 +705,23 @@ export class ViewService extends BaseApiService { name: string, addPeIndex: number ): VePromise { - let newInstanceId = this.apiSvc.createUniqueId(); - newInstanceId = '_hidden_' + newInstanceId + '_pei'; + let newInstanceId = this.apiSvc.createUniqueId() + newInstanceId = '_hidden_' + newInstanceId + '_pei' return new this.$q((resolve, reject) => { const realType: string = this.schemaSvc.getValue( 'TYPE_TO_CLASSIFIER_TYPE', type, this.schema, viewOrSectionOb.id - ); - let jsonType = realType; - if (type === 'Comment' || type === 'Paragraph') jsonType = type; + ) + let jsonType = realType + if (type === 'Comment' || type === 'Paragraph') jsonType = type const instanceSpecSpec = { type: jsonType, sourceType: 'reference', source: newInstanceId, sourceProperty: 'documentation', - }; + } let instanceSpec: InstanceSpecObject = { id: newInstanceId, ownerId: 'view_instances_bin_' + viewOrSectionOb._projectId, @@ -742,8 +742,8 @@ export class ViewService extends BaseApiService { _refId: viewOrSectionOb._refId, }), appliedStereotypeIds: [], - }; - instanceSpec = new InstanceSpec(instanceSpec); + } + instanceSpec = new InstanceSpec(instanceSpec) if (type === 'Section') { //newData = newDataSInstance = null; instanceSpec.specification = new ValueSpec({ @@ -753,20 +753,20 @@ export class ViewService extends BaseApiService { id: this.apiSvc.createUniqueId(), _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, - }); + }) } let clone: ElementObject = { _projectId: viewOrSectionOb._projectId, id: viewOrSectionOb.id, _refId: viewOrSectionOb._refId, type: viewOrSectionOb.type, - }; - let key = '_contents'; + } + let key = '_contents' if (this.isSection(viewOrSectionOb)) { - key = 'specification'; + key = 'specification' } - const keyValue: ValueObject = viewOrSectionOb[key] as ValueObject; - let cloneValue: ValueObject; + const keyValue: ValueObject = viewOrSectionOb[key] as ValueObject + let cloneValue: ValueObject if (!keyValue) { cloneValue = new ValueSpec({ operand: [], @@ -777,20 +777,20 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, ownerId: this.isSection(viewOrSectionOb) ? viewOrSectionOb.id : viewOrSectionOb.id + '_vc', - }); + }) } else { - cloneValue = _.cloneDeep(keyValue); + cloneValue = _.cloneDeep(keyValue) if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(viewOrSectionOb) ? this.apiSvc.createUniqueId() - : viewOrSectionOb.id + '_vc_expression'; + : viewOrSectionOb.id + '_vc_expression' cloneValue.ownerId = this.isSection(viewOrSectionOb) ? viewOrSectionOb.id - : viewOrSectionOb.id + '_vc'; + : viewOrSectionOb.id + '_vc' } } if (addPeIndex >= -1) { - (cloneValue as ExpressionObject).operand.splice( + ;(cloneValue as ExpressionObject).operand.splice( addPeIndex + 1, 0, new ValueSpec({ @@ -801,9 +801,9 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, }) - ); + ) } else { - (cloneValue as ExpressionObject).operand.push( + ;(cloneValue as ExpressionObject).operand.push( new ValueSpec({ instanceId: newInstanceId, type: 'InstanceValue', @@ -812,11 +812,11 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, }) - ); + ) } - clone[key] = cloneValue; - clone = this.elementSvc.fillInElement(clone); - const toCreate: ElementObject[] = [instanceSpec, clone]; + clone[key] = cloneValue + clone = this.elementSvc.fillInElement(clone) + const toCreate: ElementObject[] = [instanceSpec, clone] /* if (newData && newDataSInstance) { toCreate.push(newData); @@ -828,22 +828,22 @@ export class ViewService extends BaseApiService { refId: viewOrSectionOb._refId, elements: toCreate, elementId: '', - }; + } this.elementSvc.createElements(reqOb).then( (data) => { for (let i = 0; i < data.length; i++) { - const elem = data[i]; + const elem = data[i] if (elem.id === newInstanceId) { - resolve(elem); - return; + resolve(elem) + return } } }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } /** @@ -863,9 +863,9 @@ export class ViewService extends BaseApiService { */ public createView(ownerOb: ViewObject, viewOb: ViewObject, peDoc?: string): VePromise { return new this.$q((resolve, reject) => { - const newViewId: string = viewOb.id && viewOb.id !== '' ? viewOb.id : this.apiSvc.createUniqueId(); - const newInstanceId = '_hidden_' + this.apiSvc.createUniqueId() + '_pei'; - const untitledName = viewOb.isDoc ? 'Untitled Document' : 'Untitled View'; + const newViewId: string = viewOb.id && viewOb.id !== '' ? viewOb.id : this.apiSvc.createUniqueId() + const newInstanceId = '_hidden_' + this.apiSvc.createUniqueId() + '_pei' + const untitledName = viewOb.isDoc ? 'Untitled Document' : 'Untitled View' const view = new Class({ id: newViewId, _projectId: viewOb._projectId, @@ -898,22 +898,22 @@ export class ViewService extends BaseApiService { ? this.schemaSvc.getSchema('DOCUMENT_SID', this.schema) : this.schemaSvc.getSchema('VIEW_SID', this.schema), ], - }); + }) let parentView: ViewObject = { _projectId: '', _refId: '', id: '', type: 'Class', - }; + } if (ownerOb && (ownerOb._childViews || this.apiSvc.isView(ownerOb))) { parentView = Object.assign(parentView, { _projectId: ownerOb._projectId, _refId: ownerOb._refId, id: ownerOb.id, - }); - parentView._childViews = []; + }) + parentView._childViews = [] if (ownerOb._childViews) { - parentView._childViews.push(..._.cloneDeep(ownerOb._childViews)); + parentView._childViews.push(..._.cloneDeep(ownerOb._childViews)) } parentView._childViews.push({ id: newViewId, @@ -921,14 +921,14 @@ export class ViewService extends BaseApiService { _refId: ownerOb._refId, aggregation: 'composite', type: 'Class', - }); + }) } const peSpec: PresentationInstanceObject = { type: 'Paragraph', sourceType: 'reference', source: newViewId, sourceProperty: 'documentation', - }; + } const pe = new InstanceSpec({ id: newInstanceId, _projectId: viewOb._projectId, @@ -946,11 +946,11 @@ export class ViewService extends BaseApiService { _refId: viewOb._refId, }), appliedStereotypeIds: [], - }); - const toCreate: ElementObject[] = [pe, view]; + }) + const toCreate: ElementObject[] = [pe, view] if (parentView.id !== '') { - const parentViewClass: ElementObject = this.elementSvc.fillInElement(parentView); - toCreate.push(parentViewClass); + const parentViewClass: ElementObject = this.elementSvc.fillInElement(parentView) + toCreate.push(parentViewClass) } const reqOb = { projectId: ownerOb._projectId, @@ -958,20 +958,20 @@ export class ViewService extends BaseApiService { elements: toCreate, returnChildViews: true, elementId: '', - }; + } this.elementSvc.createElements(reqOb).then( (data) => { data.forEach((elem) => { if (elem.id === newViewId) { - resolve(elem); + resolve(elem) } - }); + }) }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } /** @@ -986,27 +986,27 @@ export class ViewService extends BaseApiService { */ public createDocument(ownerOb: ViewObject, docOb: ViewObject): VePromise { return new this.$q((resolve, reject) => { - docOb.isDoc = true; + docOb.isDoc = true this.createView(ownerOb, docOb).then( (data2: DocumentObject) => { if (ownerOb && ownerOb.id.indexOf('holding_bin') < 0) { - data2._groupId = ownerOb.id; + data2._groupId = ownerOb.id } - const cacheKey = ['documents', ownerOb._projectId, ownerOb._refId]; - const cachedView: ViewObject[] = this.cacheSvc.get(cacheKey, true); + const cacheKey = ['documents', ownerOb._projectId, ownerOb._refId] + const cachedView: ViewObject[] = this.cacheSvc.get(cacheKey, true) if (cachedView) { cachedView.forEach((document: DocumentObject, index) => { - if (document.id === data2.id) delete cachedView[index]; - }); - cachedView.push(data2); + if (document.id === data2.id) delete cachedView[index] + }) + cachedView.push(data2) } - resolve(data2); + resolve(data2) }, (reason) => { - reject(reason); + reject(reason) } - ); - }); + ) + }) } /** @@ -1026,7 +1026,7 @@ export class ViewService extends BaseApiService { */ public createGroup(name: string, ownerOb: ViewObject): VePromise { return new this.$q((resolve, reject) => { - const PACKAGE_ID = this.apiSvc.createUniqueId(); + const PACKAGE_ID = this.apiSvc.createUniqueId() // Our Group package element const group: GroupObject = new Package({ id: PACKAGE_ID, @@ -1037,38 +1037,38 @@ export class ViewService extends BaseApiService { ownerId: ownerOb.id, _isGroup: true, appliedStereotypeIds: [this.schemaSvc.getSchema('GROUP_ST_ID', this.schema)], - }); - const toCreate = [group]; + }) + const toCreate = [group] const reqOb = { projectId: ownerOb._projectId, refId: ownerOb._refId, elements: toCreate, elementId: '', - }; + } this.elementSvc.createElements(reqOb).then( (data) => { - const cacheKey = ['groups', ownerOb._projectId, ownerOb._refId]; - const groupObj = _.find(data, { id: PACKAGE_ID }); + const cacheKey = ['groups', ownerOb._projectId, ownerOb._refId] + const groupObj = _.find(data, { id: PACKAGE_ID }) if (groupObj) { - groupObj._parentId = ownerOb.id.indexOf('holding') != -1 ? null : ownerOb.id; + groupObj._parentId = ownerOb.id.indexOf('holding') != -1 ? null : ownerOb.id if (this.cacheSvc.exists(cacheKey)) { - this.cacheSvc.get(cacheKey).push(groupObj); + this.cacheSvc.get(cacheKey).push(groupObj) } - this.cacheSvc.put(['group', groupObj.projectId, groupObj.refId, groupObj.id], groupObj, true); - resolve(groupObj); + this.cacheSvc.put(['group', groupObj.projectId, groupObj.refId, groupObj.id], groupObj, true) + resolve(groupObj) } else { reject({ status: 500, message: 'Failed to create group', - }); + }) } }, (reason) => { - console.log('POST failed:', reason); - reject(reason); + console.log('POST failed:', reason) + reject(reason) } - ); - }); + ) + }) } /** @@ -1088,43 +1088,43 @@ export class ViewService extends BaseApiService { _refId: packageOb._refId, appliedStereotypeIds: [], classifierIds: null, - }; + } - updatedPackage._isGroup = false; + updatedPackage._isGroup = false _.remove(packageOb.appliedStereotypeIds, (id: string): boolean => { - return id === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema); - }); + return id === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema) + }) if (packageOb.appliedStereotypeIds.length === 0) { - updatedPackage.appliedStereotypeIds = packageOb.appliedStereotypeIds; + updatedPackage.appliedStereotypeIds = packageOb.appliedStereotypeIds } - const toUpdate = [updatedPackage]; + const toUpdate = [updatedPackage] this.elementSvc.updateElements(toUpdate, false).then( (data) => { // remove this group for cache - const cacheKey = ['groups', packageOb._projectId, packageOb._refId]; - const groups: ElementObject[] = this.cacheSvc.get(cacheKey, true) || []; + const cacheKey = ['groups', packageOb._projectId, packageOb._refId] + const groups: ElementObject[] = this.cacheSvc.get(cacheKey, true) || [] _.remove(groups, (group: PackageObject) => { - return group.id === packageOb.id; - }); + return group.id === packageOb.id + }) data.forEach((elOb: ElementObject) => { if (elOb.id === updatedPackage.id) { - resolve(elOb); + resolve(elOb) } - }); + }) }, (reason) => { if (reason.data.failedRequests) { - reject(reason.data.failedRequests[0]); + reject(reason.data.failedRequests[0]) } else { reject({ status: 400, message: 'Something went wrong. Please try your action again', - }); + }) } } - ); - }); + ) + }) } /** @@ -1141,40 +1141,40 @@ export class ViewService extends BaseApiService { weight?: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb); - const url = this.uRLSvc.getProjectDocumentsURL(reqOb); - const cacheKey = ['documents', reqOb.projectId, reqOb.refId]; - const inProgKey = cacheKey.join('-'); + this.apiSvc.normalize(reqOb) + const url = this.uRLSvc.getProjectDocumentsURL(reqOb) + const cacheKey = ['documents', reqOb.projectId, reqOb.refId] + const inProgKey = cacheKey.join('-') if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q>((resolve, reject) => { if (this.cacheSvc.exists(cacheKey) && !refresh) { - resolve(this.cacheSvc.get(cacheKey)); - this._removeInProgress(inProgKey); + resolve(this.cacheSvc.get(cacheKey)) + this._removeInProgress(inProgKey) } else { if (refresh === undefined) { - refresh = false; + refresh = false } this.elementSvc .getGenericElements(url, reqOb, 'documents', weight, refresh) .then( (data) => { - this.cacheSvc.put(cacheKey, data, false); - resolve(this.cacheSvc.get(cacheKey)); + this.cacheSvc.put(cacheKey, data, false) + resolve(this.cacheSvc.get(cacheKey)) }, (reason) => { - reject(reason); + reject(reason) } ) .finally(() => { - this._removeInProgress(inProgKey); - }); + this._removeInProgress(inProgKey) + }) } }) - ); + ) } - return this._getInProgress(inProgKey) as VePromise>; + return this._getInProgress(inProgKey) as VePromise> } /** @@ -1191,35 +1191,35 @@ export class ViewService extends BaseApiService { weight: number, refresh?: boolean ): VePromise { - const cacheKey = this.elementSvc.getRequestKey(reqOb, reqOb.elementId); - const inProgKey = cacheKey.join('-'); + const cacheKey = this.elementSvc.getRequestKey(reqOb, reqOb.elementId) + const inProgKey = cacheKey.join('-') if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q((resolve, reject) => { - const cached = this.cacheSvc.get(cacheKey); + const cached = this.cacheSvc.get(cacheKey) if (cached && !refresh) { - resolve(cached); - this._removeInProgress(inProgKey); + resolve(cached) + this._removeInProgress(inProgKey) } this.getProjectDocuments(reqOb, weight, refresh) .then( (result: DocumentObject[]) => { const documentOb = result.filter((resultOb) => { - return resultOb.id === reqOb.elementId; - })[0]; - this.cacheSvc.put(cacheKey, documentOb, true); - resolve(this.cacheSvc.get(cacheKey)); + return resultOb.id === reqOb.elementId + })[0] + this.cacheSvc.put(cacheKey, documentOb, true) + resolve(this.cacheSvc.get(cacheKey)) }, (reason) => { - reject({ message: reason.message, status: reason.status }); + reject({ message: reason.message, status: reason.status }) } ) - .finally(() => this._removeInProgress(inProgKey)); + .finally(() => this._removeInProgress(inProgKey)) }) - ); + ) } - return this._getInProgress(inProgKey) as VePromise; + return this._getInProgress(inProgKey) as VePromise } /** @@ -1233,31 +1233,31 @@ export class ViewService extends BaseApiService { public getPresentationInstanceObject = ( instanceSpec: InstanceSpecObject ): PresentationInstanceObject | InstanceSpecObject => { - const instanceSpecSpec: ValueObject = instanceSpec.specification; + const instanceSpecSpec: ValueObject = instanceSpec.specification if (!instanceSpecSpec) { return { type: 'Paragraph', sourceType: 'text', text: '', - }; + } } - const type = instanceSpecSpec.type; + const type = instanceSpecSpec.type if (type === 'LiteralString') { // If it is an Opaque List, Paragraph, Table, Image, List: - const jsonString = (instanceSpecSpec as LiteralObject).value; - return JSON.parse(jsonString) as PresentationInstanceObject; + const jsonString = (instanceSpecSpec as LiteralObject).value + return JSON.parse(jsonString) as PresentationInstanceObject } else if (type === 'Expression') { // If it is a Opaque Section, or a Expression: // If it is a Opaque Section then we want the instanceSpec: if (this.isSection(instanceSpec)) { - return instanceSpec; + return instanceSpec } else { //?? - return instanceSpecSpec; + return instanceSpecSpec } } - }; + } /** * @name ViewService#getElementReferenceTree @@ -1283,11 +1283,11 @@ export class ViewService extends BaseApiService { contents: ExpressionObject, weight?: number ): VePromise> { - const promises: VePromise>[] = []; + const promises: VePromise>[] = [] for (let i = 0; i < contents.operand.length; i++) { - promises.push(this.getElementReference(reqOb, contents.operand[i], weight)); + promises.push(this.getElementReference(reqOb, contents.operand[i], weight)) } - return this.$q.all(promises); + return this.$q.all(promises) } public getElementReference( @@ -1301,37 +1301,37 @@ export class ViewService extends BaseApiService { sectionElements: [], instanceVal: instanceVal, isOpaque: false, - }; + } - const req = _.cloneDeep(reqOb); - req.elementId = instanceVal.instanceId; + const req = _.cloneDeep(reqOb) + req.elementId = instanceVal.instanceId this.elementSvc.getElement(req, weight).then( (instanceSpecification) => { - presentationRef.instanceSpecification = instanceSpecification; + presentationRef.instanceSpecification = instanceSpecification presentationRef.isOpaque = instanceSpecification.classifierIds && instanceSpecification.classifierIds.length > 0 && this.schemaSvc .getMap('OPAQUE_CLASSIFIERS', this.schema) - .indexOf(instanceSpecification.classifierIds[0]) >= 0; - presentationRef.presentationElement = this.getPresentationInstanceObject(instanceSpecification); + .indexOf(instanceSpecification.classifierIds[0]) >= 0 + presentationRef.presentationElement = this.getPresentationInstanceObject(instanceSpecification) if (this.isSection(instanceSpecification)) { this.getElementReferenceTree(req, instanceSpecification.specification).then( (sectionElementReferenceTree) => { - presentationRef.sectionElements = sectionElementReferenceTree; - resolve(presentationRef); + presentationRef.sectionElements = sectionElementReferenceTree + resolve(presentationRef) }, (reason) => { - reject(reason); + reject(reason) } - ); - } else resolve(presentationRef); + ) + } else resolve(presentationRef) }, (reason) => { - reject({ status: reason.status, message: reason.message }); + reject({ status: reason.status, message: reason.message }) } - ); - }); + ) + }) } /** @@ -1349,8 +1349,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Section', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'SectionT', this.schema, instanceSpec.id)) - ); - }; + ) + } public isTable = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1360,8 +1360,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Table', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'TableT', this.schema, instanceSpec.id)) - ); - }; + ) + } public isFigure = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1375,8 +1375,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Figure', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'FigureT', this.schema, instanceSpec.id)) - ); - }; + ) + } public isEquation = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1384,27 +1384,27 @@ export class ViewService extends BaseApiService { instanceSpec.classifierIds.length > 0 && instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Equation', this.schema, instanceSpec.id) - ); - }; + ) + } public getTreeType = (instanceSpec: ViewInstanceSpec): string => { - if (this.isSection(instanceSpec)) return 'section'; + if (this.isSection(instanceSpec)) return 'section' if ( instanceSpec.specification && instanceSpec.specification.value && typeof instanceSpec.specification.value === 'string' && (JSON.parse(instanceSpec.specification.value) as PresentationInstanceObject).excludeFromList ) { - return 'none'; + return 'none' } - if (this.isTable(instanceSpec)) return 'table'; - if (this.isFigure(instanceSpec)) return 'figure'; - if (this.isEquation(instanceSpec)) return 'equation'; - let result = 'none'; + if (this.isTable(instanceSpec)) return 'table' + if (this.isFigure(instanceSpec)) return 'figure' + if (this.isEquation(instanceSpec)) return 'equation' + let result = 'none' if (instanceSpec.classifierIds && instanceSpec.classifierIds.length > 0) { const peSids = this.schemaSvc.getSchema<{ - [peType: string]: string; - }>('TYPE_TO_CLASSIFIER_ID', this.schema); + [peType: string]: string + }>('TYPE_TO_CLASSIFIER_ID', this.schema) for (const peType of Object.keys(peSids)) { if ( @@ -1412,43 +1412,43 @@ export class ViewService extends BaseApiService { instanceSpec.classifierIds.length > 0 && instanceSpec.classifierIds.includes(peSids[peType]) ) { - result = peType.toLowerCase(); - break; + result = peType.toLowerCase() + break } } } - return result; - }; + return result + } public processSlotStrings(values: LiteralObject[]): string[] { - const res: string[] = []; + const res: string[] = [] if (!values || values.length === 0) { - return res; + return res } values.forEach((value) => { - if (value.type !== 'LiteralString' || !value.value) return; - res.push(value.value as string); - }); - return res; + if (value.type !== 'LiteralString' || !value.value) return + res.push(value.value as string) + }) + return res } public processSlotIntegers(values: LiteralObject[]): number[] { - const res: number[] = []; + const res: number[] = [] if (!values || values.length === 0) { - return res; + return res } values.forEach((value) => { if (Number.isInteger(value.value)) { - res.push(value.value as number); + res.push(value.value as number) } else if (typeof value.value === 'string') { - const val = parseInt(value.value); + const val = parseInt(value.value) if (!isNaN(val)) { - res.push(val); + res.push(val) } } - }); - return res; + }) + return res } /** @@ -1465,7 +1465,7 @@ export class ViewService extends BaseApiService { const metadata: DocumentMetadata = { numberingDepth: 0, numberingSeparator: '.', - }; + } const elementIds = [ `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'Header', this.schema)}`, //header `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'Footer', this.schema)}`, //footer @@ -1475,51 +1475,51 @@ export class ViewService extends BaseApiService { this.schema )}`, //numbering depth `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'NumSep', this.schema)}`, //numbering separator - ]; + ] const metaReqOb: ElementsRequest = Object.assign(reqOb, { elementId: elementIds, - }); + }) this.elementSvc .getElements(metaReqOb, weight) .then( (data) => { if (data.length === 0) { - return; + return } for (let i = 0; i < data.length; i++) { - const prop = data[i]; - const feature: string = prop.definingFeatureId ? prop.definingFeatureId : null; - const value: LiteralObject[] = prop.value ? prop.value : null; + const prop = data[i] + const feature: string = prop.definingFeatureId ? prop.definingFeatureId : null + const value: LiteralObject[] = prop.value ? prop.value : null if (!feature || !value || !Array.isArray(value)) { - continue; + continue } - let result: string[] | number[] = []; + let result: string[] | number[] = [] if (feature === this.schemaSvc.getValue('DOCUMENT_IDS', 'Header', this.schema, prop.id)) { //header - result = this.processSlotStrings(value); - metadata.top = result.length > 0 ? result[0] : ''; - metadata['top-left'] = result.length > 1 ? result[1] : ''; - metadata['top-right'] = result.length > 2 ? result[2] : ''; + result = this.processSlotStrings(value) + metadata.top = result.length > 0 ? result[0] : '' + metadata['top-left'] = result.length > 1 ? result[1] : '' + metadata['top-right'] = result.length > 2 ? result[2] : '' } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'Footer', this.schema, prop.id) ) { //footer - result = this.processSlotStrings(value); - metadata.bottom = result.length > 0 ? result[0] : ''; - metadata['bottom-left'] = result.length > 1 ? result[1] : ''; - metadata['bottom-right'] = result.length > 2 ? result[2] : ''; + result = this.processSlotStrings(value) + metadata.bottom = result.length > 0 ? result[0] : '' + metadata['bottom-left'] = result.length > 1 ? result[1] : '' + metadata['bottom-right'] = result.length > 2 ? result[2] : '' } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'NumDepth', this.schema, prop.id) ) { //depth - result = this.processSlotIntegers(value); - metadata.numberingDepth = result.length > 0 ? result[0] : 0; + result = this.processSlotIntegers(value) + metadata.numberingDepth = result.length > 0 ? result[0] : 0 } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'NumSep', this.schema, prop.id) ) { //separator - result = this.processSlotStrings(value); - metadata.numberingSeparator = result.length > 0 ? result[0] : '.'; + result = this.processSlotStrings(value) + metadata.numberingSeparator = result.length > 0 ? result[0] : '.' } } }, @@ -1528,63 +1528,63 @@ export class ViewService extends BaseApiService { } ) .finally(() => { - resolve(metadata); - }); - }); + resolve(metadata) + }) + }) } public getPresentationElementType = (instanceSpec: ViewInstanceSpec): string => { if (instanceSpec.type === 'InstanceSpecification') { if (this.isSection(instanceSpec)) { - return 'Section'; + return 'Section' } else if (this.isTable(instanceSpec)) { - return 'Table'; + return 'Table' } else if (this.isFigure(instanceSpec)) { - return 'Image'; + return 'Image' } else if (this.isEquation(instanceSpec)) { - return 'Equation'; + return 'Equation' } else if (instanceSpec.specification && instanceSpec.specification.value) { return ( JSON.parse( (instanceSpec.specification as LiteralObject).value ) as PresentationInstanceObject - ).type; + ).type } } - return; - }; + return + } public isGroup(ob: InstanceSpecObject | GroupObject): boolean { - if (ob._isGroup) return (ob as GroupObject)._isGroup; + if (ob._isGroup) return (ob as GroupObject)._isGroup else { return ( ob.appliedStereotypeIds !== undefined && ob.appliedStereotypeIds.length > 0 && ob.appliedStereotypeIds[0] === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema) - ); + ) } } public getElementType = (element: ElementObject): string => { // Get Type - let elementType = ''; + let elementType = '' if (this.apiSvc.isRequirement(element)) { - elementType = 'Requirement'; + elementType = 'Requirement' } else if (this.apiSvc.isDocument(element)) { - elementType = 'Document'; + elementType = 'Document' } else if (this.apiSvc.isView(element)) { - elementType = 'View'; + elementType = 'View' } else if (this.isGroup(element)) { - elementType = 'Group'; + elementType = 'Group' } else { - elementType = this.getPresentationElementType(element); + elementType = this.getPresentationElementType(element) } - return elementType; - }; + return elementType + } public reset = (): void => { - this.inProgress = {}; - }; + this.inProgress = {} + } } -veUtils.service('ViewService', ViewService); +veUtils.service('ViewService', ViewService) diff --git a/src/ve-utils/mms-api-client/index.ts b/src/ve-utils/mms-api-client/index.ts index 5da2df6b5..579288e4e 100644 --- a/src/ve-utils/mms-api-client/index.ts +++ b/src/ve-utils/mms-api-client/index.ts @@ -1,21 +1,21 @@ -import './Api.service'; -import './URL.service'; -import './Authorization.service'; -import './Element.service'; -import './Http.service'; -import './Permissions.service'; -import './Project.service'; -import './View.service'; -import './User.service'; -import './Value.service'; +import './Api.service' +import './URL.service' +import './Authorization.service' +import './Element.service' +import './Http.service' +import './Permissions.service' +import './Project.service' +import './View.service' +import './User.service' +import './Value.service' -export * from './URL.service'; -export * from './Authorization.service'; -export * from './Element.service'; -export * from './Http.service'; -export * from './Permissions.service'; -export * from './Project.service'; -export * from './View.service'; -export * from './Api.service'; -export * from './User.service'; -export * from './Value.service'; +export * from './URL.service' +export * from './Authorization.service' +export * from './Element.service' +export * from './Http.service' +export * from './Permissions.service' +export * from './Project.service' +export * from './View.service' +export * from './Api.service' +export * from './User.service' +export * from './Value.service' diff --git a/src/ve-utils/modals/ve-modal.controller.ts b/src/ve-utils/modals/ve-modal.controller.ts index 1e140c1c5..54e4f0919 100644 --- a/src/ve-utils/modals/ve-modal.controller.ts +++ b/src/ve-utils/modals/ve-modal.controller.ts @@ -1,10 +1,10 @@ -import { VeModalResolve, VeModalController, VeModalInstanceService } from '@ve-types/view-editor'; +import { VeModalResolve, VeModalController, VeModalInstanceService } from '@ve-types/view-editor' export class VeModalControllerImpl implements VeModalController { // public close($value?: any): void {}; // // public dismiss($value?: any): void {}; - modalInstance: VeModalInstanceService; - protected resolve: U; + modalInstance: VeModalInstanceService + protected resolve: U } diff --git a/src/ve-utils/model-schema/CameoSchema.service.ts b/src/ve-utils/model-schema/CameoSchema.service.ts index 7ee06d610..9f051b0cf 100644 --- a/src/ve-utils/model-schema/CameoSchema.service.ts +++ b/src/ve-utils/model-schema/CameoSchema.service.ts @@ -1,9 +1,9 @@ -import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service'; +import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' export class CameoSchema implements Schema { - jsonName = 'cameo'; + jsonName = 'cameo' schema: SchemaMapping = { VIEW_SID: '_11_5EAPbeta_be00301_1147420760998_43940_227', OTHER_VIEW_SID: [ @@ -52,7 +52,7 @@ export class CameoSchema implements Schema { NumSep: '_18_5_3_8bf0285_1526605817077_688557_15755', }, GROUP_ST_ID: '_18_5_3_8bf0285_1520469040211_2821_15754', - }; + } map: SchemaMapping = { OPAQUE_CLASSIFIERS: [ this.schema.TYPE_TO_CLASSIFIER_ID['Image'], @@ -62,10 +62,10 @@ export class CameoSchema implements Schema { this.schema.TYPE_TO_CLASSIFIER_ID['Table'], this.schema.TYPE_TO_CLASSIFIER_ID['Figure'], ], - }; + } } -veUtils.service('CameoSchema', CameoSchema); +veUtils.service('CameoSchema', CameoSchema) // TODO: Create Cameo Project Creation Service // { diff --git a/src/ve-utils/model-schema/JupyterSchema.service.ts b/src/ve-utils/model-schema/JupyterSchema.service.ts index 7dfe4e420..5cf11557e 100644 --- a/src/ve-utils/model-schema/JupyterSchema.service.ts +++ b/src/ve-utils/model-schema/JupyterSchema.service.ts @@ -1,12 +1,12 @@ -import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service'; +import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service' -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' export class JupyterSchema implements Schema { - static $inject = []; + static $inject = [] - jsonName: string = 'jupyter'; - schema: SchemaMapping = {}; + jsonName: string = 'jupyter' + schema: SchemaMapping = {} } -veUtils.service('JupyterSchema', JupyterSchema); +veUtils.service('JupyterSchema', JupyterSchema) diff --git a/src/ve-utils/model-schema/Schema.service.ts b/src/ve-utils/model-schema/Schema.service.ts index 97826883d..911486f7c 100644 --- a/src/ve-utils/model-schema/Schema.service.ts +++ b/src/ve-utils/model-schema/Schema.service.ts @@ -1,112 +1,112 @@ -import { veUtils } from '@ve-utils'; +import { veUtils } from '@ve-utils' -import { VeConfig } from '@ve-types/config'; +import { VeConfig } from '@ve-types/config' export interface SchemaMapping { - [key: string]: unknown; + [key: string]: unknown } export interface Schema { - jsonName: string; - schema: SchemaMapping; - map?: SchemaMapping; + jsonName: string + schema: SchemaMapping + map?: SchemaMapping } export class SchemaService { - static $inject = ['$q', '$injector']; + static $inject = ['$q', '$injector'] - public veConfig: VeConfig = window.__env; - public defaultSchema: 'cameo'; + public veConfig: VeConfig = window.__env + public defaultSchema: 'cameo' public schemaList: { [key: string]: string } = { cameo: 'CameoSchema', jupyter: 'JupyterSchema', - }; + } - public schemas: { [key: string]: Schema } = {}; + public schemas: { [key: string]: Schema } = {} constructor(private $q, private $injector: angular.auto.IInjectorService) { for (const [key, value] of Object.entries(this.schemaList)) { - this.schemas[key] = this.$injector.get(value); + this.schemas[key] = this.$injector.get(value) } } getSchema = (name: string, schemaName?: string, sourceId?: string): T => { - const schema: Schema = this._getSchema(schemaName, sourceId); + const schema: Schema = this._getSchema(schemaName, sourceId) if (schema.schema[name]) { - return schema.schema[name] as T; + return schema.schema[name] as T } else { - this._schemaError(name, schemaName); + this._schemaError(name, schemaName) } - }; + } getValue = (name: string, key: string, schemaName?: string, sourceId?: string): T => { - const lookup = this.getSchema(name, schemaName, sourceId); + const lookup = this.getSchema(name, schemaName, sourceId) if (lookup && typeof lookup === 'object') { - return lookup[key] as T; + return lookup[key] as T } - }; + } getValues(name: string, keys: string[], schemaName?: string, sourceId?: string): T[] | null { - const lookup = this.getSchema(name, schemaName, sourceId); + const lookup = this.getSchema(name, schemaName, sourceId) if (lookup && typeof lookup === 'object') { - const response: T[] = []; + const response: T[] = [] keys.forEach((key) => { if (lookup.hasOwnProperty(key)) { - response.push(lookup[key] as T); + response.push(lookup[key] as T) } - }); - return response; + }) + return response } } getMap = (name: string, schemaName?: string, sourceId?: string): T => { - const schema: Schema = this._getSchema(schemaName, sourceId); + const schema: Schema = this._getSchema(schemaName, sourceId) if (schema.map && schema.map[name]) { - return schema.map[name] as T; + return schema.map[name] as T } else { - this._schemaError(name, schemaName); - return null; + this._schemaError(name, schemaName) + return null } - }; + } getMappedValue = (name: string, key: string, schemaName?: string, sourceId?: string): T => { - const lookup = this.getMap(name, schemaName, sourceId); + const lookup = this.getMap(name, schemaName, sourceId) if (lookup && typeof lookup === 'object') { - return lookup[key] as T; + return lookup[key] as T } - }; + } getKeyByValue = (name: string, value: T, schemaName?: string, sourceId?: string): string => { - const lookup = this.getSchema(name, schemaName, sourceId); + const lookup = this.getSchema(name, schemaName, sourceId) if (lookup && typeof lookup === 'object') { - let response = ''; + let response = '' Object.keys(lookup).some((key) => { if (lookup[key] === value) { - response = key; - return true; + response = key + return true } - return false; - }); - return response; + return false + }) + return response } - }; + } private _schemaError = (name: string, schemaName?: string): void => { - schemaName = schemaName ? schemaName : this.defaultSchema; + schemaName = schemaName ? schemaName : this.defaultSchema if (this.veConfig.enableDebug) { - console.log(schemaName + ' does not have table' + name + 'or it is not properly configured'); + console.log(schemaName + ' does not have table' + name + 'or it is not properly configured') } - }; + } private _getSchema = (schemaName?: string, id?: string): Schema | null => { - schemaName = schemaName ? schemaName : this.defaultSchema; - id = id ? id : 'error: unknown'; + schemaName = schemaName ? schemaName : this.defaultSchema + id = id ? id : 'error: unknown' if (this.schemas.hasOwnProperty(schemaName)) { - return this.schemas[schemaName]; + return this.schemas[schemaName] } else { - console.log(`Object ${id} uses an unknown schema ${schemaName}`); + console.log(`Object ${id} uses an unknown schema ${schemaName}`) } - }; + } } -veUtils.service('SchemaService', SchemaService); +veUtils.service('SchemaService', SchemaService) diff --git a/src/ve-utils/model-schema/index.ts b/src/ve-utils/model-schema/index.ts index c17dcefdc..94a6af9a4 100644 --- a/src/ve-utils/model-schema/index.ts +++ b/src/ve-utils/model-schema/index.ts @@ -1,7 +1,7 @@ -import './CameoSchema.service'; -import './JupyterSchema.service'; -import './Schema.service'; +import './CameoSchema.service' +import './JupyterSchema.service' +import './Schema.service' -export * from './CameoSchema.service'; -export * from './JupyterSchema.service'; -export * from './Schema.service'; +export * from './CameoSchema.service' +export * from './JupyterSchema.service' +export * from './Schema.service' diff --git a/src/ve-utils/third-party/index.ts b/src/ve-utils/third-party/index.ts index 8b138df6a..0bdc684bd 100644 --- a/src/ve-utils/third-party/index.ts +++ b/src/ve-utils/third-party/index.ts @@ -1 +1 @@ -import './jquery'; +import './jquery' diff --git a/src/ve-utils/third-party/jquery/index.ts b/src/ve-utils/third-party/jquery/index.ts index 9c558addc..480e6ad63 100644 --- a/src/ve-utils/third-party/jquery/index.ts +++ b/src/ve-utils/third-party/jquery/index.ts @@ -1,2 +1,2 @@ -import './isOnScreen.jquery'; -import './table2CSV.jquery'; +import './isOnScreen.jquery' +import './table2CSV.jquery' diff --git a/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts b/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts index d2eba58d2..5f01e1ca1 100644 --- a/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts +++ b/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts @@ -1,43 +1,43 @@ -import jQuery from 'jquery'; +import jQuery from 'jquery' jQuery.fn.isOnScreen = (x?, y?): boolean => { - if (x == null || typeof x == 'undefined') x = 1; - if (y == null || typeof y == 'undefined') y = 1; + if (x == null || typeof x == 'undefined') x = 1 + if (y == null || typeof y == 'undefined') y = 1 - const win = $(window); + const win = $(window) const viewport = { top: win.scrollTop(), left: win.scrollLeft(), right: win.scrollLeft() + win.width(), bottom: win.scrollTop() + win.height(), - }; + } - const height = jQuery.fn.outerHeight(); - const width = jQuery.fn.outerWidth(); + const height = jQuery.fn.outerHeight() + const width = jQuery.fn.outerWidth() if (!width || !height) { - return false; + return false } const bounds: { - right?: number; - left: number; - bottom?: number; - top: number; - } = jQuery.fn.offset(); - bounds.right = bounds.left + width; - bounds.bottom = bounds.top + height; + right?: number + left: number + bottom?: number + top: number + } = jQuery.fn.offset() + bounds.right = bounds.left + width + bounds.bottom = bounds.top + height const visible = !( viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom - ); + ) if (!visible) { - return false; + return false } const deltas = { @@ -45,7 +45,7 @@ jQuery.fn.isOnScreen = (x?, y?): boolean => { bottom: Math.min(1, (viewport.bottom - bounds.top) / height), left: Math.min(1, (bounds.right - viewport.left) / width), right: Math.min(1, (viewport.right - bounds.left) / width), - }; + } - return deltas.left * deltas.right >= x && deltas.top * deltas.bottom >= y; -}; + return deltas.left * deltas.right >= x && deltas.top * deltas.bottom >= y +} diff --git a/src/ve-utils/third-party/jquery/table2CSV.jquery.ts b/src/ve-utils/third-party/jquery/table2CSV.jquery.ts index 3cda1b948..356db3384 100644 --- a/src/ve-utils/third-party/jquery/table2CSV.jquery.ts +++ b/src/ve-utils/third-party/jquery/table2CSV.jquery.ts @@ -1,4 +1,4 @@ -import jQuery from 'jquery'; +import jQuery from 'jquery' jQuery.fn.table2CSV = (inputOptions: JQuery.table2CSV.inputOptions): string => { const options = jQuery.extend( @@ -8,111 +8,111 @@ jQuery.fn.table2CSV = (inputOptions: JQuery.table2CSV.inputOptions): string => { delivery: 'popup', // popup, value }, inputOptions - ); + ) - const csvData: string[] = []; + const csvData: string[] = [] // const el = this const row2CSV = (tmpRow: string[]): void => { - const tmp = tmpRow.join(''); // to remove any blank rows + const tmp = tmpRow.join('') // to remove any blank rows if (tmpRow.length > 0 && tmp != '') { - csvData[csvData.length] = tmpRow.join(options.separator); + csvData[csvData.length] = tmpRow.join(options.separator) } - }; + } const formatData = (input: string): string => { // replace " with “ - const regexp = new RegExp(/["]/g); - let output = input.replace(regexp, '“'); + const regexp = new RegExp(/["]/g) + let output = input.replace(regexp, '“') //HTML // var regexp = new RegExp(/\<[^\<]+\>/g); // var output = output.replace(regexp, ""); - const i = output.search(/\S/); //index of first non whitespace char + const i = output.search(/\S/) //index of first non whitespace char if (i > 0) { - output = '_'.repeat(i) + $.trim(output); + output = '_'.repeat(i) + $.trim(output) } - output = $.trim(output); - if (output == '') return ''; + output = $.trim(output) + if (output == '') return '' if (output[0] == '+' || output[0] == '=' || output[0] == '-') { - output = ' ' + output; + output = ' ' + output } - return `"${output}"`; - }; + return `"${output}"` + } const popup = (data: string): string => { - const generator = window.open('', 'csv', 'height=400,width=600'); - generator.document.write('CSV'); - generator.document.write(''); - generator.document.write(''); - generator.document.write(''); - generator.document.close(); - return 'ok'; - }; + const generator = window.open('', 'csv', 'height=400,width=600') + generator.document.write('CSV') + generator.document.write('') + generator.document.write('') + generator.document.write('') + generator.document.close() + return 'ok' + } const handleMatrix = (bodyTag: string, cellTag: string): void => { - const spanData: { [row: number]: { [column: number]: unknown } } = {}; //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell - let curRow = 0; + const spanData: { [row: number]: { [column: number]: unknown } } = {} //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell + let curRow = 0 $(this) .children(bodyTag) .children('tr') .each((index, element) => { - tmpRow = []; - let curCol = 0; + tmpRow = [] + let curCol = 0 $(element) .children(cellTag) .each((index, element) => { while (spanData[curRow] && spanData[curRow][curCol]) { - tmpRow.push('""'); - curCol++; + tmpRow.push('""') + curCol++ } - tmpRow.push(formatData($(element).text())); - const rowstring = $(element).attr('rowspan'); - const rowspan = parseInt(rowstring); + tmpRow.push(formatData($(element).text())) + const rowstring = $(element).attr('rowspan') + const rowspan = parseInt(rowstring) if (rowspan && rowspan > 1) { for (let i = 1; i < rowspan; i++) { if (!spanData[curRow + i]) { - spanData[curRow + i] = {}; + spanData[curRow + i] = {} } - spanData[curRow + i][curCol] = true; + spanData[curRow + i][curCol] = true } } - const colstring = $(element).attr('colspan'); + const colstring = $(element).attr('colspan') if (!colstring) { - curCol++; - return; + curCol++ + return } - let colspan = parseInt(colstring); + let colspan = parseInt(colstring) while (colspan > 1) { - curCol++; - tmpRow.push('""'); - colspan--; + curCol++ + tmpRow.push('""') + colspan-- if (rowspan > 1) { for (let i = 1; i < rowspan; i++) { - spanData[curRow + i][curCol] = true; + spanData[curRow + i][curCol] = true } } } - curCol++; - }); - row2CSV(tmpRow); - curRow++; - }); - }; + curCol++ + }) + row2CSV(tmpRow) + curRow++ + }) + } //header - const numCols = options.header.length; - let tmpRow: string[] = []; + const numCols = options.header.length + let tmpRow: string[] = [] if (numCols > 0) { for (let i = 0; i < numCols; i++) { - tmpRow[tmpRow.length] = formatData(options.header[i]); + tmpRow[tmpRow.length] = formatData(options.header[i]) } } else { - handleMatrix('thead', 'th'); + handleMatrix('thead', 'th') } // actual data - handleMatrix('tbody', 'td'); - const mydata = csvData.join('\n'); + handleMatrix('tbody', 'td') + const mydata = csvData.join('\n') if (options.delivery == 'popup') { - return popup(mydata); + return popup(mydata) } else { - return mydata; + return mydata } -}; +} diff --git a/src/ve-utils/utils/change.util.ts b/src/ve-utils/utils/change.util.ts index 8753aaa54..42d5da391 100644 --- a/src/ve-utils/utils/change.util.ts +++ b/src/ve-utils/utils/change.util.ts @@ -1,8 +1,8 @@ -import _ from 'lodash'; +import _ from 'lodash' -import { EventService } from '@ve-utils/core'; +import { EventService } from '@ve-utils/core' -import { VeQService } from '@ve-types/angular'; +import { VeQService } from '@ve-types/angular' /** * @name onChangesCallback @@ -17,7 +17,7 @@ import { VeQService } from '@ve-types/angular'; * } * */ -export type onChangesCallback = (newVal?: T, oldVal?: T, firstChange?: boolean) => U; +export type onChangesCallback = (newVal?: T, oldVal?: T, firstChange?: boolean) => U /** * @name change.utils#handleChange: @@ -48,23 +48,23 @@ export function handleChange( ignoreFirst?: boolean ): void { if (watch === '') { - return callback(); + return callback() } else if (changesObj[watch]) { if (ignoreFirst && changesObj[watch].isFirstChange()) { - return; + return } - const newVal: T = changesObj[watch].currentValue as T; - const oldVal: T = changesObj[watch].previousValue as T; - const firstChange = changesObj[watch].isFirstChange(); - callback(newVal, oldVal, firstChange); + const newVal: T = changesObj[watch].currentValue as T + const oldVal: T = changesObj[watch].previousValue as T + const firstChange = changesObj[watch].isFirstChange() + callback(newVal, oldVal, firstChange) } - return; + return } interface EventWatcher { - $q: VeQService; - eventSvc: EventService; - subs: Rx.IDisposable[]; + $q: VeQService + eventSvc: EventService + subs: Rx.IDisposable[] } export function watchChangeEvent( @@ -79,15 +79,15 @@ export function watchChangeEvent( currentValue: data, previousValue: _.cloneDeep($ctrl[name] as T), isFirstChange: () => { - return typeof $ctrl[name] === 'undefined'; + return typeof $ctrl[name] === 'undefined' }, - }; + } if (data !== $ctrl[name]) { if (update) { - $ctrl[name] = data; + $ctrl[name] = data } - changeAction(change.currentValue, change.previousValue, change.isFirstChange()); + changeAction(change.currentValue, change.previousValue, change.isFirstChange()) } }) - ); + ) } diff --git a/src/ve-utils/utils/emf.util.ts b/src/ve-utils/utils/emf.util.ts index 1c761b7a8..b0423f4c1 100644 --- a/src/ve-utils/utils/emf.util.ts +++ b/src/ve-utils/utils/emf.util.ts @@ -1,172 +1,172 @@ -import { ElementObject, ExpressionObject, PackageObject, ValueObject } from '@ve-types/mms'; +import { ElementObject, ExpressionObject, PackageObject, ValueObject } from '@ve-types/mms' export class Element implements ElementObject { - id: string = ''; - _projectId: string = ''; - _refId: string = ''; - appliedStereotypeIds: string[] = []; - documentation: string = ''; - mdExtensionsIds: string[] = []; - syncElementId: string = null; - type: string = 'Element'; + id: string = '' + _projectId: string = '' + _refId: string = '' + appliedStereotypeIds: string[] = [] + documentation: string = '' + mdExtensionsIds: string[] = [] + syncElementId: string = null + type: string = 'Element' constructor(elementOb?: ElementObject) { if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class NamedElement extends Element { - name: string = ''; - nameExpression: string = null; - clientDependencyIds: string[] = []; - supplierDependencyIds: string[] = []; + name: string = '' + nameExpression: string = null + clientDependencyIds: string[] = [] + supplierDependencyIds: string[] = [] constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } class PackageableElement extends NamedElement { - ownerId: string = null; - visibility: string = 'public'; - templateParameterId: string = null; + ownerId: string = null + visibility: string = 'public' + templateParameterId: string = null constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } class TypedElement extends PackageableElement { - typeId: string = null; + typeId: string = null constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } class TemplateableElement extends PackageableElement { - templateBindingIds: string[] = []; + templateBindingIds: string[] = [] constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class Property extends TypedElement { - type = 'Property'; - defaultValue: any[] = []; + type = 'Property' + defaultValue: any[] = [] constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class Class extends TemplateableElement { - classifierBehaviorId: string = null; - collaborationUseIds: string[] = []; - elementImportIds: string[] = []; - generalizationIds: string[] = []; - classRealizationIds: string[] = []; - isAbstract: boolean = false; - isActive: boolean = false; - isFinalSpecialization: boolean = false; - isLeaf: boolean = false; - ownedAttributeIds: string[] = []; - ownedOperationIds: string[] = []; - packageImportIds: string[] = []; - powertypeExtentIds: string[] = []; - redefinedClassifierIds: string[] = []; - representationI: string[] = []; - type = 'Class'; - useCaseIds: string[] = []; + classifierBehaviorId: string = null + collaborationUseIds: string[] = [] + elementImportIds: string[] = [] + generalizationIds: string[] = [] + classRealizationIds: string[] = [] + isAbstract: boolean = false + isActive: boolean = false + isFinalSpecialization: boolean = false + isLeaf: boolean = false + ownedAttributeIds: string[] = [] + ownedOperationIds: string[] = [] + packageImportIds: string[] = [] + powertypeExtentIds: string[] = [] + redefinedClassifierIds: string[] = [] + representationI: string[] = [] + type = 'Class' + useCaseIds: string[] = [] constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class InstanceSpec extends PackageableElement { - classifierIds: string[] = []; - deploymentIds: string[] = []; - slotIds: string[] = []; - specification: Element = null; - stereotypedElementId: string = null; - type = 'InstanceSpecification'; + classifierIds: string[] = [] + deploymentIds: string[] = [] + slotIds: string[] = [] + specification: Element = null + stereotypedElementId: string = null + type = 'InstanceSpecification' constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class ValueSpec extends TypedElement implements ValueObject { - valueExpression: string = ''; - type = 'ValueSpecification'; + valueExpression: string = '' + type = 'ValueSpecification' constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class Expression extends ValueSpec implements ExpressionObject { - operand: T[] = []; - type = 'Expression'; + operand: T[] = [] + type = 'Expression' constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class Package extends TemplateableElement implements PackageObject { - type = 'Package'; - visibility = null; - elementImportIds: string[] = []; - packageImportIds: string[] = []; - URI: string = ''; - packageMergeIds: string[] = []; - profileApplicationIds: string[] = []; + type = 'Package' + visibility = null + elementImportIds: string[] = [] + packageImportIds: string[] = [] + URI: string = '' + packageMergeIds: string[] = [] + profileApplicationIds: string[] = [] constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class Generalization extends Element { - generalizationSetIds: string[] = []; - isSubstitutable: boolean = true; - type = 'Generalization'; + generalizationSetIds: string[] = [] + isSubstitutable: boolean = true + type = 'Generalization' constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } export class Dependency extends PackageableElement { - type = 'Dependency'; - visibility = null; + type = 'Dependency' + visibility = null constructor(elementOb?: ElementObject) { - super(elementOb); + super(elementOb) if (elementOb) { - Object.assign(this, elementOb); + Object.assign(this, elementOb) } } } diff --git a/src/ve-utils/utils/index.ts b/src/ve-utils/utils/index.ts index 847dc55d5..6eae2b6fd 100644 --- a/src/ve-utils/utils/index.ts +++ b/src/ve-utils/utils/index.ts @@ -1,2 +1,2 @@ -export * from './change.util'; -export * from './emf.util'; +export * from './change.util' +export * from './emf.util' diff --git a/src/ve-utils/ve-utils.module.ts b/src/ve-utils/ve-utils.module.ts index 5408eac8c..11895ab96 100644 --- a/src/ve-utils/ve-utils.module.ts +++ b/src/ve-utils/ve-utils.module.ts @@ -1,4 +1,4 @@ -import angular from 'angular'; +import angular from 'angular' /** * @ngdoc overview @@ -55,14 +55,14 @@ import angular from 'angular'; ]); */ -export const veUtils = angular.module('ve-utils', []); +export const veUtils = angular.module('ve-utils', []) veUtils .config([ '$sceProvider', ($sceProvider: angular.ISCEProvider): void => { - $sceProvider.enabled(false); + $sceProvider.enabled(false) }, ]) //.constant('HtmlRenderedDiff', window.HtmlRenderedDiff) - .constant('moment', window.moment); + .constant('moment', window.moment) diff --git a/tsconfig.json b/tsconfig.json index c5b997451..fb1e8fa39 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,8 +18,7 @@ "typeRoots": [ "node_modules/@types", "node_modules/type-fest/index.d.ts", - "src/lib", - "node_modules/flatpickr/dist/typings.d.ts" + "src/lib" ], "rootDir": "src", "paths": { From 13c135282c96ca8cffa37baafb176da0efaf668b Mon Sep 17 00:00:00 2001 From: Enquier Date: Mon, 15 May 2023 12:50:36 -0600 Subject: [PATCH 20/31] Fixing formatting --- .eslintrc | 208 ++++++++++-------- .prettierrc.js | 1 - package.json | 4 +- .../angular-flatpickr/ngFlatpickr.module.ts | 82 ++++--- tsconfig.json | 3 +- 5 files changed, 152 insertions(+), 146 deletions(-) diff --git a/.eslintrc b/.eslintrc index 0a021a2ea..91d73ced4 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,105 +1,119 @@ { - "settings": { - "import/extensions": [".js", ".ts"], - "import/parsers": { - "@typescript-eslint/parser": [ - ".ts" - ] - }, - "import/resolver": { - "typescript": { - "alwaysCheckTypes": true, - "project": "./tsconfig.json", - "extensions": [".js", ".jsx", ".ts", ".tsx"] - }, - "node": { - "extensions": [".js", ".jsx", ".ts", ".tsx"], - "moduleDirectory": ["node_modules"] - } - } + "root": true, + "extends": ["eslint:recommended"], + "env": { + "browser": true, + "es2021": true }, - "parser": "@typescript-eslint/parser", "parserOptions": { - "project": "./tsconfig.json", - "tsconfigRootDir": "./" + "ecmaVersion": 12, + "sourceType": "module" }, - "plugins": ["unused-imports"], - "extends": [ - "plugin:@typescript-eslint/recommended", - "plugin:@typescript-eslint/recommended-requiring-type-checking", - "plugin:import/errors", - "plugin:import/warnings", - "plugin:import/typescript", - "plugin:prettier/recommended" - ], - "rules": { - "@typescript-eslint/no-unused-vars": "off", - "unused-imports/no-unused-imports": "error", - "no-multiple-empty-lines": 2, - "import/newline-after-import": [ - 2 - ], - "@typescript-eslint/explicit-function-return-type": 2, - "@typescript-eslint/no-inferrable-types": [ - 2, - { - "ignoreProperties": true - } - ], - "import/order": ["error", { - "newlines-between": "always", - "alphabetize": { - "order": "asc", - "caseInsensitive": true - }, - "pathGroups": [ - { - "pattern": "@/**", - "group": "external", - "position": "after" - }, - { - "pattern": "@ve-app", - "group": "internal", - "position": "after" - }, - { - "pattern": "@ve-components", - "group": "internal", - "position": "after" + "overrides": [ + { + "files": ["**/*.ts"], + "settings": { + "import/extensions": [".js", ".ts"], + "import/parsers": { + "@typescript-eslint/parser": [".ts"] }, - { - "pattern": "@ve-core", - "group": "internal", - "position": "after" - }, - { - "pattern": "@ve-utils", - "group": "internal", - "position": "after" - }, - { - "pattern": "@ve-types/**", - "group": "type", - "position": "after" - }, - { - "pattern": "../../lib/**", - "group": "external", - "position": "after" + "import/resolver": { + "typescript": { + "alwaysCheckTypes": true, + "project": "./tsconfig.json", + "extensions": [".ts", ".tsx"] + }, + "node": { + "extensions": [".js", ".jsx", ".ts", ".tsx"], + "moduleDirectory": ["node_modules"] + } } + }, + "parser": "@typescript-eslint/parser", + "parserOptions": { + "project": "./tsconfig.json", + "tsconfigRootDir": "./" + }, + "plugins": ["unused-imports"], + "extends": [ + "plugin:@typescript-eslint/recommended", + "plugin:@typescript-eslint/recommended-requiring-type-checking", + "plugin:import/errors", + "plugin:import/warnings", + "plugin:import/typescript", + "plugin:prettier/recommended" ], - "groups": [ - "builtin", - "external", - "internal", - "unknown", - "parent", - "sibling", - "index", - "object", - "type" - ] - }] - } + "rules": { + "@typescript-eslint/no-unused-vars": "off", + "unused-imports/no-unused-imports": "error", + "no-multiple-empty-lines": 2, + "import/newline-after-import": [2], + "@typescript-eslint/explicit-function-return-type": 2, + "@typescript-eslint/no-inferrable-types": [ + 2, + { + "ignoreProperties": true + } + ], + "import/order": [ + "error", + { + "newlines-between": "always", + "alphabetize": { + "order": "asc", + "caseInsensitive": true + }, + "pathGroups": [ + { + "pattern": "@/**", + "group": "external", + "position": "after" + }, + { + "pattern": "@ve-app", + "group": "internal", + "position": "after" + }, + { + "pattern": "@ve-components", + "group": "internal", + "position": "after" + }, + { + "pattern": "@ve-core", + "group": "internal", + "position": "after" + }, + { + "pattern": "@ve-utils", + "group": "internal", + "position": "after" + }, + { + "pattern": "@ve-types/**", + "group": "type", + "position": "after" + }, + { + "pattern": "../../lib/**", + "group": "external", + "position": "after" + } + ], + "groups": [ + "builtin", + "external", + "internal", + "unknown", + "parent", + "sibling", + "index", + "object", + "type" + ] + } + ] + } + } + ] } diff --git a/.prettierrc.js b/.prettierrc.js index fc669ac24..03ce334bd 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -2,7 +2,6 @@ module.exports = { trailingComma: 'es5', tabWidth: 4, - semi: false, singleQuote: true, printWidth: 120, } diff --git a/package.json b/package.json index 5f8e3ca99..9ba098ed4 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,8 @@ "format": "prettier --write \"**/*.ts\" \"**/*.js\"", "lint": "DEBUG=eslint:cli-engine eslint ./src", "prebuild": "yarn lint && yarn format", - "build": "webpack --config webpack.config.js --mode=production --bail", - "watch": "webpack --config webpack.config.js --mode=development --watch --progress", + "build": "webpack --config webpack.config.ts --mode=production --bail", + "watch": "webpack --config webpack.config.ts --mode=development --watch --progress", "test": "yarn prebuild && yarn build" }, "devDependencies": { diff --git a/src/lib/angular-flatpickr/ngFlatpickr.module.ts b/src/lib/angular-flatpickr/ngFlatpickr.module.ts index bdb469d04..273e73fbe 100644 --- a/src/lib/angular-flatpickr/ngFlatpickr.module.ts +++ b/src/lib/angular-flatpickr/ngFlatpickr.module.ts @@ -1,10 +1,13 @@ -import angular from 'angular' -import * as _flatpickr from 'flatpickr' -import { FlatpickrFn, Instance } from 'flatpickr/dist/types/instance' +import angular, { IComponentController } from 'angular'; +import flatpickr from 'flatpickr'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; -const flatpickr: FlatpickrFn = _flatpickr.default +export interface ngFlatpickrOptions extends flatpickr.Options.Options { + placeholder: string; +} + +export type ngFlatpickrCallback = (fpInstance: flatpickr.Instance) => void; const ngFlatpickrComponent: VeComponentOptions = { selector: 'ngFlatpickr', @@ -19,74 +22,63 @@ const ngFlatpickrComponent: VeComponentOptions = { fpOpts: '<', fpOnSetup: '&', }, - controller: class ngFlatpickrCtrl implements angular.IComponentController { - static $inject = ['$element', '$timeout', '$scope'] + controller: class ngFlatpickrCtrl implements IComponentController { + static $inject = ['$element', '$timeout', '$scope']; //Bindings - private fpOpts - private fpOnSetup + private fpOpts: ngFlatpickrOptions; + private fpOnSetup: ngFlatpickrCallback; - private inputDate + private inputDate: number; - constructor( - private $element: JQuery, - private $timeout: angular.ITimeoutService, - private $scope: angular.IScope - ) {} + constructor(private $element: JQuery, private $timeout: angular.ITimeoutService) {} - $onInit() { - this.fpOpts.placeholder = this.fpOpts.placeholder || 'Select Date..' + $onInit(): void { + this.fpOpts.placeholder = this.fpOpts.placeholder || 'Select Date..'; } $postLink(): void { - this.grabElementAndRunFlatpickr() + this.grabElementAndRunFlatpickr(); } - $onChanges() { - this.grabElementAndRunFlatpickr() + $onChanges(): void { + this.grabElementAndRunFlatpickr(); } - grabElementAndRunFlatpickr = () => { - this.$timeout( + grabElementAndRunFlatpickr = (): void => { + void this.$timeout( () => { - const transcludeEl = this.$element.find('ng-transclude')[0] - const element = transcludeEl.children[0] + const transcludeEl = this.$element.find('ng-transclude')[0]; + const element = transcludeEl.children[0]; - this.setDatepicker(element) + this.setDatepicker(element); }, 0, true - ) - } - - setDatepicker = (element) => { - const fpLib = flatpickr + ); + }; - if (!fpLib) { - return console.warn('Unable to find any flatpickr installation') + setDatepicker = (element: Element): void => { + if (!flatpickr) { + return console.warn('Unable to find any flatpickr installation'); } - const fpInstance: Instance = fpLib(element, this.fpOpts) + const fpInstance: flatpickr.Instance = flatpickr(element, this.fpOpts); if (this.fpOnSetup) { - this.fpOnSetup({ - fpItem: fpInstance, - }) + this.fpOnSetup(fpInstance); } // If has ngModel set the date if (this.inputDate) { - fpInstance.setDate(this.inputDate) + fpInstance.setDate(this.inputDate); } // destroy the flatpickr instance when the dom element is removed angular.element(element).on('$destroy', () => { - fpInstance.destroy() - }) - - // Refresh the scope - //this.$scope.$applyAsync(); - } + fpInstance.destroy(); + }); + }; }, -} -angular.module('angular-flatpickr', []).component(ngFlatpickrComponent.selector, ngFlatpickrComponent) +}; +angular.module('angular-flatpickr', []).component(ngFlatpickrComponent.selector, ngFlatpickrComponent); diff --git a/tsconfig.json b/tsconfig.json index fb1e8fa39..c5b997451 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,7 +18,8 @@ "typeRoots": [ "node_modules/@types", "node_modules/type-fest/index.d.ts", - "src/lib" + "src/lib", + "node_modules/flatpickr/dist/typings.d.ts" ], "rootDir": "src", "paths": { From 7a573d1aec1b9fca4a7d6a063a2407c8c32ee3c4 Mon Sep 17 00:00:00 2001 From: Enquier Date: Mon, 15 May 2023 12:59:19 -0600 Subject: [PATCH 21/31] re-try prettier --- src/ve-app/events.d.ts | 14 +- src/ve-app/index.ts | 76 +- src/ve-app/login/index.ts | 12 +- src/ve-app/login/login-banner.component.ts | 32 +- src/ve-app/login/login.component.ts | 84 +- .../login/modals/login-warning.modal.ts | 42 +- src/ve-app/login/redirect.component.ts | 196 ++-- src/ve-app/login/select.component.ts | 178 ++-- src/ve-app/login/short-url.component.ts | 70 +- src/ve-app/main/components/index.ts | 8 +- .../main/components/main-menu.component.ts | 194 ++-- .../main/components/nav-bar.component.ts | 124 +-- .../components/system-banner.component.ts | 30 +- .../components/system-footer.component.ts | 30 +- src/ve-app/main/index.ts | 8 +- src/ve-app/main/main.component.ts | 204 ++--- .../main/modals/about-modal.component.ts | 36 +- src/ve-app/main/modals/index.ts | 12 +- .../main/modals/login-modal.component.ts | 52 +- .../modals/print-confirm-modal.component.ts | 220 ++--- .../main/modals/select-modal.component.ts | 130 +-- .../modals/table-export-modal.component.ts | 26 +- .../main/modals/working-modal.component.ts | 22 +- src/ve-app/main/services/AppUtils.service.ts | 310 +++---- .../main/services/FullDocument.service.ts | 182 ++-- src/ve-app/main/services/Resolve.service.ts | 260 +++--- src/ve-app/main/services/index.ts | 12 +- src/ve-app/pane-center/document.component.ts | 362 ++++---- src/ve-app/pane-center/index.ts | 14 +- .../pane-center/pane-center-buttons.config.ts | 4 +- src/ve-app/pane-center/refs.component.ts | 236 ++--- .../pane-center/reorder-group.component.ts | 230 ++--- src/ve-app/pane-center/reorder.component.ts | 204 ++--- src/ve-app/pane-center/search.component.ts | 46 +- .../services/ContentWindow.service.ts | 16 +- src/ve-app/pane-center/slideshow.component.ts | 335 +++---- src/ve-app/pane-left/index.ts | 4 +- src/ve-app/pane-left/left-buttons.config.ts | 10 +- src/ve-app/pane-left/left-pane.component.ts | 404 ++++----- .../pane-left/left-toolbar.component.ts | 80 +- src/ve-app/pane-right/index.ts | 4 +- src/ve-app/pane-right/right-buttons.config.ts | 6 +- src/ve-app/pane-right/right-pane.component.ts | 152 ++-- .../pane-right/right-toolbar.component.ts | 76 +- src/ve-app/ve-app.module.ts | 266 +++--- .../components/annotation.component.ts | 132 +-- .../components/error.component.ts | 50 +- src/ve-components/components/index.ts | 4 +- .../diffs/components/diff-attr.component.ts | 196 ++-- .../diffs/components/diff-html.component.ts | 80 +- src/ve-components/diffs/components/index.ts | 4 +- src/ve-components/diffs/index.ts | 10 +- src/ve-components/diffs/modals/index.ts | 12 +- .../modals/merge-confirm-modal.component.ts | 58 +- .../diffs/modals/revert-confirm.component.ts | 100 +-- .../diffs/modals/save-conflict.component.ts | 34 +- .../diffs/services/DiffMerge.service.ts | 100 +-- src/ve-components/index.ts | 34 +- .../insertions/components/index.ts | 10 +- .../components/insert-comment.component.ts | 52 +- .../components/insert-element.component.ts | 70 +- .../components/insert-pe.component.ts | 84 +- .../components/insert-ref.component.ts | 76 +- .../components/insert-view.component.ts | 104 +-- src/ve-components/insertions/index.ts | 10 +- .../insert-element-modal.component.ts | 80 +- .../insertions/insertion.controller.ts | 194 ++-- .../insertions/services/Insertion.service.ts | 60 +- .../insertions/services/index.ts | 4 +- .../presentations/add-pe-menu.component.ts | 40 +- .../components/present-comment.component.ts | 10 +- .../components/present-equation.component.ts | 10 +- .../components/present-figure.component.ts | 10 +- .../components/present-image.component.ts | 10 +- .../components/present-list-t.component.ts | 10 +- .../components/present-list.component.ts | 32 +- .../components/present-paragraph.component.ts | 32 +- .../components/present-section.component.ts | 10 +- .../components/present-table-t.component.ts | 10 +- .../components/present-table.component.ts | 560 ++++++------ src/ve-components/presentations/index.ts | 42 +- .../presentations/mms-view-link.component.ts | 204 ++--- .../presentations/mmsMaturityBar.directive.ts | 46 +- .../presentation-element.controller.ts | 134 +-- .../services/Presentation.service.ts | 76 +- .../services/Table2CSV.service.ts | 118 +-- .../services/ViewHtml.service.ts | 166 ++-- .../presentations/view-pe.component.ts | 126 +-- .../presentations/view.component.ts | 240 ++--- .../services/Component.service.ts | 40 +- .../services/Extension.service.ts | 70 +- src/ve-components/services/index.ts | 8 +- .../components/spec-editor.component.ts | 72 +- .../components/spec-history.component.ts | 172 ++-- .../components/spec-inspector.component.ts | 36 +- .../components/spec-ref-list.component.ts | 98 +- .../components/spec-reorder.component.ts | 200 ++--- src/ve-components/spec-tools/index.ts | 18 +- .../spec-tools/mms-tools.component.ts | 280 +++--- .../spec-tools/services/Spec.service.ts | 242 ++--- .../spec-tools/spec-tool.controller.ts | 178 ++-- .../transclusions/components/index.ts | 24 +- .../components/transclude-art.component.ts | 72 +- .../components/transclude-attr.component.ts | 102 +-- .../components/transclude-com.component.ts | 72 +- .../components/transclude-doc.component.ts | 118 +-- .../components/transclude-enum.component.ts | 74 +- .../transclude-group-docs.component.ts | 90 +- .../components/transclude-img.component.ts | 68 +- .../components/transclude-name.component.ts | 78 +- .../transclude-section.component.ts | 86 +- .../components/transclude-val.component.ts | 216 ++--- .../transclude-value-link.component.ts | 60 +- .../components/transclude-view.component.ts | 50 +- .../deletable-transclusion.controller.ts | 72 +- src/ve-components/transclusions/index.ts | 18 +- .../transclusions/mms-cf.component.ts | 104 +-- .../mms-transclude-compatibility.component.ts | 18 +- .../modals/create-transclusion.modal.ts | 202 ++--- .../services/Transclusion.service.ts | 74 +- .../transclusions/transclusion.controller.ts | 492 +++++----- src/ve-components/trees/components/index.ts | 12 +- .../components/tree-of-contents.component.ts | 30 +- .../components/tree-of-documents.component.ts | 48 +- .../components/tree-of-equations.component.ts | 28 +- .../components/tree-of-favorites.component.ts | 26 +- .../components/tree-of-figures.component.ts | 28 +- .../components/tree-of-tables.component.ts | 28 +- src/ve-components/trees/index.ts | 10 +- .../trees/mms-trees.component.ts | 352 ++++---- .../trees/services/Tree.service.ts | 848 +++++++++--------- src/ve-components/trees/tree.controller.ts | 166 ++-- src/ve-components/ve-components.module.ts | 12 +- .../button-bar/button-bar.component.ts | 78 +- src/ve-core/button-bar/index.ts | 10 +- .../button-bar/services/BarButton.api.ts | 118 +-- .../button-bar/services/ButtonBar.api.ts | 90 +- .../button-bar/services/ButtonBar.service.ts | 116 +-- .../components/mention-intercept.component.ts | 24 +- .../editor/components/mention.component.ts | 36 +- src/ve-core/editor/editor-buttons.config.ts | 4 +- src/ve-core/editor/editor.component.ts | 522 +++++------ src/ve-core/editor/index.ts | 12 +- .../editor/services/EditDialog.service.ts | 12 +- src/ve-core/editor/services/Editor.service.ts | 286 +++--- .../editor/services/Mention.service.ts | 308 +++---- src/ve-core/editor/services/index.ts | 12 +- src/ve-core/events.d.ts | 36 +- src/ve-core/index.ts | 14 +- .../modals/confirm-delete-modal.component.ts | 72 +- src/ve-core/modals/index.ts | 4 +- src/ve-core/search/index.ts | 6 +- .../search/mms-search-buttons.config.ts | 4 +- .../search/mms-search-results.component.ts | 20 +- src/ve-core/search/mms-search.component.ts | 518 +++++------ src/ve-core/toolbar/index.ts | 8 +- src/ve-core/toolbar/services/Toolbar.api.ts | 76 +- .../toolbar/services/Toolbar.service.ts | 186 ++-- src/ve-core/toolbar/tool-bar.component.ts | 82 +- src/ve-core/ve-core.module.ts | 18 +- src/ve-extensions/experimental-magic/index.ts | 2 +- .../spec-tools/spec-magic.component.ts | 32 +- src/ve-extensions/index.ts | 2 +- .../present-plots/Plot.service.ts | 246 ++--- src/ve-extensions/present-plots/config.json | 14 +- .../presentations/components/index.ts | 14 +- .../components/mmsC3Plot.directive.ts | 76 +- ...mmsD3GroupedHorizontalBarPlot.directive.ts | 298 +++--- ...mmsD3NormalizedStackedBarPlot.directive.ts | 118 +-- .../mmsD3ParallelAxisPlot.directive.ts | 218 ++--- .../components/mmsD3RadarPlot.directive.ts | 262 +++--- .../presentations/present-plot.component.ts | 54 +- .../ts-diagram/mmsTsDiagram.directive.ts | 156 ++-- src/ve-types/angular.d.ts | 47 +- src/ve-types/components/index.d.ts | 52 +- src/ve-types/components/insertions.d.ts | 36 +- src/ve-types/components/presentation.d.ts | 38 +- src/ve-types/config.d.ts | 30 +- src/ve-types/core/editor.d.ts | 12 +- src/ve-types/mms/index.d.ts | 54 +- src/ve-types/mms/mms.d.ts | 204 ++--- src/ve-types/mms/orgsAndProjects.d.ts | 60 +- src/ve-types/mms/valuesAndInstances.d.ts | 24 +- src/ve-types/mms/views.d.ts | 104 +-- src/ve-types/third-party/angular.d.ts | 8 +- src/ve-types/third-party/jquery.d.ts | 12 +- src/ve-types/third-party/mathjax.d.ts | 2 +- src/ve-types/tree.d.ts | 204 ++--- src/ve-types/view-editor.d.ts | 84 +- src/ve-types/window.d.ts | 18 +- .../application/Application.service.ts | 112 +-- src/ve-utils/application/Branding.service.ts | 94 +- src/ve-utils/application/Image.service.ts | 40 +- src/ve-utils/application/RootScope.service.ts | 92 +- src/ve-utils/application/ShortUrl.service.ts | 194 ++-- src/ve-utils/application/Utils.service.ts | 348 +++---- src/ve-utils/application/index.ts | 28 +- src/ve-utils/core/Cache.service.ts | 120 +-- src/ve-utils/core/Edit.service.ts | 64 +- src/ve-utils/core/Event.service.ts | 62 +- src/ve-utils/core/Session.service.ts | 42 +- src/ve-utils/core/index.ts | 16 +- src/ve-utils/index.ts | 16 +- src/ve-utils/mms-api-client/Api.service.ts | 156 ++-- .../mms-api-client/Authorization.service.ts | 94 +- src/ve-utils/mms-api-client/Base.service.ts | 26 +- .../mms-api-client/Element.service.ts | 590 ++++++------ src/ve-utils/mms-api-client/Http.service.ts | 120 +-- .../mms-api-client/Permissions.service.ts | 52 +- .../mms-api-client/Project.service.ts | 436 ++++----- src/ve-utils/mms-api-client/URL.service.ts | 296 +++--- src/ve-utils/mms-api-client/User.service.ts | 48 +- src/ve-utils/mms-api-client/Value.service.ts | 206 ++--- src/ve-utils/mms-api-client/View.service.ts | 828 ++++++++--------- src/ve-utils/mms-api-client/index.ts | 40 +- src/ve-utils/modals/ve-modal.controller.ts | 6 +- .../model-schema/CameoSchema.service.ts | 12 +- .../model-schema/JupyterSchema.service.ts | 12 +- src/ve-utils/model-schema/Schema.service.ts | 98 +- src/ve-utils/model-schema/index.ts | 12 +- src/ve-utils/third-party/index.ts | 2 +- src/ve-utils/third-party/jquery/index.ts | 4 +- .../third-party/jquery/isOnScreen.jquery.ts | 40 +- .../third-party/jquery/table2CSV.jquery.ts | 118 +-- src/ve-utils/utils/change.util.ts | 38 +- src/ve-utils/utils/emf.util.ts | 168 ++-- src/ve-utils/utils/index.ts | 4 +- src/ve-utils/ve-utils.module.ts | 8 +- 228 files changed, 11684 insertions(+), 11660 deletions(-) diff --git a/src/ve-app/events.d.ts b/src/ve-app/events.d.ts index fcded09bb..d0e020ff6 100644 --- a/src/ve-app/events.d.ts +++ b/src/ve-app/events.d.ts @@ -1,15 +1,15 @@ -import { TreeBranch } from '@ve-types/tree' +import { TreeBranch } from '@ve-types/tree'; export namespace veAppEvents { interface viewAddedData { - vId: string - curSec: string - prevSibId?: string + vId: string; + curSec: string; + prevSibId?: string; } interface viewDeletedData { - parentBranch: TreeBranch - prevBranch: TreeBranch - branch: TreeBranch + parentBranch: TreeBranch; + prevBranch: TreeBranch; + branch: TreeBranch; } } diff --git a/src/ve-app/index.ts b/src/ve-app/index.ts index cda2b5097..6066eec0c 100644 --- a/src/ve-app/index.ts +++ b/src/ve-app/index.ts @@ -4,47 +4,47 @@ //Shared Dependencies -import 'angular' -import 'lodash' -import 'angular-ui-bootstrap' -import 'rx-lite' -import 'flatpickr' - -import 'angular-animate' -import 'angular-cookies' -import 'angular-growl-v2' -import 'angular-hotkeys' -import '@uirouter/angularjs' -import 'angular-sanitize' -import 'angular-ui-tree' -import '@openmbee/pane-layout' -import '@openmbee/angularjs-dropdown-multiselect' - -import 'ui-router-visualizer' - -import 'angulartics' -import 'angulartics-piwik' - -import 'moment' -import 'ngstorage' - -import '../lib/angular-promise-extras/angular-promise-extras' -import '../lib/angular-flatpickr/ngFlatpickr.main' -import '../lib/html-rendered-diff/index' -import '../lib/angular-ui-tree-filter/angular-ui-tree-filter' +import 'angular'; +import 'lodash'; +import 'angular-ui-bootstrap'; +import 'rx-lite'; +import 'flatpickr'; + +import 'angular-animate'; +import 'angular-cookies'; +import 'angular-growl-v2'; +import 'angular-hotkeys'; +import '@uirouter/angularjs'; +import 'angular-sanitize'; +import 'angular-ui-tree'; +import '@openmbee/pane-layout'; +import '@openmbee/angularjs-dropdown-multiselect'; + +import 'ui-router-visualizer'; + +import 'angulartics'; +import 'angulartics-piwik'; + +import 'moment'; +import 'ngstorage'; + +import '../lib/angular-promise-extras/angular-promise-extras'; +import '../lib/angular-flatpickr/ngFlatpickr.main'; +import '../lib/html-rendered-diff/index'; +import '../lib/angular-ui-tree-filter/angular-ui-tree-filter'; //VE Modules -import '@ve-utils' -import '@ve-core' -import '@ve-components' +import '@ve-utils'; +import '@ve-core'; +import '@ve-components'; -import './ve-app.module' +import './ve-app.module'; -import './main' +import './main'; -import './login' -import './pane-center' -import './pane-left' -import './pane-right' +import './login'; +import './pane-center'; +import './pane-left'; +import './pane-right'; -export * from './ve-app.module' +export * from './ve-app.module'; diff --git a/src/ve-app/login/index.ts b/src/ve-app/login/index.ts index be3a104e3..d21cc38d7 100644 --- a/src/ve-app/login/index.ts +++ b/src/ve-app/login/index.ts @@ -1,10 +1,10 @@ //Components -import './login.component' -import './login-banner.component' -import './redirect.component' -import './select.component' -import './short-url.component' +import './login.component'; +import './login-banner.component'; +import './redirect.component'; +import './select.component'; +import './short-url.component'; //Modals -import './modals/login-warning.modal' +import './modals/login-warning.modal'; diff --git a/src/ve-app/login/login-banner.component.ts b/src/ve-app/login/login-banner.component.ts index 71e645bb6..00e2b9fe7 100644 --- a/src/ve-app/login/login-banner.component.ts +++ b/src/ve-app/login/login-banner.component.ts @@ -1,11 +1,11 @@ -import { IComponentController } from 'angular' +import { IComponentController } from 'angular'; -import { BrandingStyle } from '@ve-utils/application' -import { handleChange } from '@ve-utils/utils' +import { BrandingStyle } from '@ve-utils/application'; +import { handleChange } from '@ve-utils/utils'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; const LoginBannerComponent: VeComponentOptions = { selector: 'loginBanner', @@ -23,25 +23,25 @@ const LoginBannerComponent: VeComponentOptions = { mmsLoginBanner: '<', }, controller: class LoginBannerController implements IComponentController { - private mmsLoginBanner: BrandingStyle - public message: string[] | string - protected spin: boolean = true + private mmsLoginBanner: BrandingStyle; + public message: string[] | string; + protected spin: boolean = true; $onChanges(onChangesObj: angular.IOnChangesObject): void { handleChange(onChangesObj, 'mmsLoginBanner', () => { if (this.mmsLoginBanner) { - this.spin = false - this.message = this.mmsLoginBanner ? this.mmsLoginBanner.message : '' + this.spin = false; + this.message = this.mmsLoginBanner ? this.mmsLoginBanner.message : ''; } else { - this.spin = true - this.message = '' + this.spin = true; + this.message = ''; } if (!Array.isArray(this.message)) { - this.message = [this.message] + this.message = [this.message]; } - }) + }); } }, -} +}; -veApp.component(LoginBannerComponent.selector, LoginBannerComponent) +veApp.component(LoginBannerComponent.selector, LoginBannerComponent); diff --git a/src/ve-app/login/login.component.ts b/src/ve-app/login/login.component.ts index f54ccd8d3..cf7b2846d 100644 --- a/src/ve-app/login/login.component.ts +++ b/src/ve-app/login/login.component.ts @@ -1,14 +1,14 @@ -import { StateService, TransitionPromise, UIRouterGlobals, UrlService } from '@uirouter/angularjs' -import angular, { IComponentController, IQService } from 'angular' +import { StateService, TransitionPromise, UIRouterGlobals, UrlService } from '@uirouter/angularjs'; +import angular, { IComponentController, IQService } from 'angular'; -import { BrandingService, BrandingStyle, RootScopeService } from '@ve-utils/application' -import { AuthService } from '@ve-utils/mms-api-client' +import { BrandingService, BrandingStyle, RootScopeService } from '@ve-utils/application'; +import { AuthService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions, VePromiseReason } from '@ve-types/angular' -import { ParamsObject } from '@ve-types/mms' -import { VeModalResolveFn, VeModalService, VeModalSettings } from '@ve-types/view-editor' +import { VeComponentOptions, VePromiseReason } from '@ve-types/angular'; +import { ParamsObject } from '@ve-types/mms'; +import { VeModalResolveFn, VeModalService, VeModalSettings } from '@ve-types/view-editor'; const LoginComponent: VeComponentOptions = { selector: 'login', @@ -49,14 +49,14 @@ const LoginComponent: VeComponentOptions = { 'AuthService', 'RootScopeService', 'BrandingService', - ] + ]; - public spin: boolean = false - loginBanner: BrandingStyle + public spin: boolean = false; + loginBanner: BrandingStyle; //Bindings - private mmsParams: ParamsObject - private mmsLoginBanner: BrandingStyle + private mmsParams: ParamsObject; + private mmsLoginBanner: BrandingStyle; constructor( private $q: IQService, @@ -71,42 +71,42 @@ const LoginComponent: VeComponentOptions = { ) {} $onInit(): void { - this.rootScopeSvc.veTitle('Login') - this.rootScopeSvc.veShowLogin(true) - this.loginBanner = this.mmsLoginBanner + this.rootScopeSvc.veTitle('Login'); + this.rootScopeSvc.veShowLogin(true); + this.loginBanner = this.mmsLoginBanner; if (!this.rootScopeSvc.veWarningOk()) { - this.warning() + this.warning(); } } login(credentials: { password: string; username: string }): angular.IPromise { - const deferred = this.$q.defer() - this.spin = true + const deferred = this.$q.defer(); + this.spin = true; if (!credentials || !credentials.password || !credentials.username) { - let message = 'Missing: ' - message += !credentials || !credentials.username ? 'Username' : '' - message += !credentials ? ' and ' : '' - message += !credentials || !credentials.password ? 'Password' : '' - this.growl.error(message) + let message = 'Missing: '; + message += !credentials || !credentials.username ? 'Username' : ''; + message += !credentials ? ' and ' : ''; + message += !credentials || !credentials.password ? 'Password' : ''; + this.growl.error(message); } else { const credentialsJSON = { username: credentials.username, password: credentials.password, - } + }; this.authSvc.getAuthorized(credentialsJSON).then( (user) => { if (this.rootScopeSvc.veRedirect()) { - const veRedirect = this.rootScopeSvc.veRedirect() - const toState = veRedirect.toState - const toParams = veRedirect.toParams - toParams.next = undefined + const veRedirect = this.rootScopeSvc.veRedirect(); + const toState = veRedirect.toState; + const toParams = veRedirect.toParams; + toParams.next = undefined; deferred.resolve( this.$state.go(toState.name, toParams, { reload: true, }) - ) + ); } else if (this.mmsParams.next) { - this.$urlService.url(this.mmsParams.next, true) + this.$urlService.url(this.mmsParams.next, true); } else { this.$state .go('main.login.select', { @@ -114,17 +114,17 @@ const LoginComponent: VeComponentOptions = { }) .catch(() => { /* Handled by UIRouter */ - }) + }); } }, (reason: VePromiseReason) => { - this.spin = false - this.growl.error(reason.message) - deferred.reject(reason) + this.spin = false; + this.growl.error(reason.message); + deferred.reject(reason); } - ) + ); } - return deferred.promise + return deferred.promise; } warning(): void { @@ -135,13 +135,13 @@ const LoginComponent: VeComponentOptions = { windowTopClass: 'modal-center-override', resolve: { loginWarning: () => { - return this.brandingSvc.loginWarning + return this.brandingSvc.loginWarning; }, }, - } - this.$uibModal.open(settings) + }; + this.$uibModal.open(settings); } }, -} +}; -veApp.component(LoginComponent.selector, LoginComponent) +veApp.component(LoginComponent.selector, LoginComponent); diff --git a/src/ve-app/login/modals/login-warning.modal.ts b/src/ve-app/login/modals/login-warning.modal.ts index 46f861cb9..c40c1f9fa 100644 --- a/src/ve-app/login/modals/login-warning.modal.ts +++ b/src/ve-app/login/modals/login-warning.modal.ts @@ -1,47 +1,47 @@ -import { BrandingStyle, RootScopeService } from '@ve-utils/application' -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { BrandingStyle, RootScopeService } from '@ve-utils/application'; +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; export interface LoginWarningResolve extends VeModalResolve { - loginWarning: BrandingStyle + loginWarning: BrandingStyle; } export interface LoginWarningResolveFn extends VeModalResolveFn { - loginWarning(): BrandingStyle + loginWarning(): BrandingStyle; } class LoginWarningModalController extends VeModalControllerImpl implements VeModalController { - static $inject = ['RootScopeService'] + static $inject = ['RootScopeService']; - private warningMessage: string[] - private loading: boolean - private disabled: boolean - private warningHeader: string = 'Warning' + private warningMessage: string[]; + private loading: boolean; + private disabled: boolean; + private warningHeader: string = 'Warning'; constructor(private rootScopeSvc: RootScopeService) { - super() + super(); } $onInit(): void { if (Array.isArray(this.resolve.loginWarning.message)) { - this.warningMessage = this.resolve.loginWarning.message - } else this.warningMessage = [this.resolve.loginWarning.message] - this.disabled = this.resolve.loginWarning.disabled ? this.resolve.loginWarning.disabled : false - this.loading = false + this.warningMessage = this.resolve.loginWarning.message; + } else this.warningMessage = [this.resolve.loginWarning.message]; + this.disabled = this.resolve.loginWarning.disabled ? this.resolve.loginWarning.disabled : false; + this.loading = false; if (this.rootScopeSvc.veWarningOk() || this.disabled) { - this.modalInstance.dismiss() + this.modalInstance.dismiss(); } } continue(): void { - this.rootScopeSvc.veWarningOk(true) - this.modalInstance.close(true) + this.rootScopeSvc.veWarningOk(true); + this.modalInstance.close(true); } } @@ -63,6 +63,6 @@ const LoginWarningModal: VeModalComponent = { resolve: '<', }, controller: LoginWarningModalController, -} +}; -veApp.component(LoginWarningModal.selector, LoginWarningModal) +veApp.component(LoginWarningModal.selector, LoginWarningModal); diff --git a/src/ve-app/login/redirect.component.ts b/src/ve-app/login/redirect.component.ts index 948cb996a..ea69b8951 100644 --- a/src/ve-app/login/redirect.component.ts +++ b/src/ve-app/login/redirect.component.ts @@ -1,15 +1,15 @@ -import { StateService } from '@uirouter/angularjs' -import angular, { IComponentController } from 'angular' -import Rx from 'rx-lite' +import { StateService } from '@uirouter/angularjs'; +import angular, { IComponentController } from 'angular'; +import Rx from 'rx-lite'; -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ProjectService, ElementService } from '@ve-utils/mms-api-client' +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ProjectService, ElementService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular' -import { ElementObject, QueryObject, RequestObject, ViewObject } from '@ve-types/mms' +import { VeComponentOptions, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular'; +import { ElementObject, QueryObject, RequestObject, ViewObject } from '@ve-types/mms'; const RedirectComponent: VeComponentOptions = { selector: 'redirect', @@ -54,16 +54,16 @@ const RedirectComponent: VeComponentOptions = { `, controller: class RedirectController implements IComponentController { - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; - public redirect_from_old: boolean - redirect_noResults: boolean = false - redirect_element: { name: string; type: string; link: string } - spin: boolean = false - elem: ElementObject - redirect_relatedDocs: ViewObject[] - projectIds: string[] = [] - reqOb: RequestObject + public redirect_from_old: boolean; + redirect_noResults: boolean = false; + redirect_element: { name: string; type: string; link: string }; + spin: boolean = false; + elem: ElementObject; + redirect_relatedDocs: ViewObject[]; + projectIds: string[] = []; + reqOb: RequestObject; static $inject = [ '$q', @@ -75,7 +75,7 @@ const RedirectComponent: VeComponentOptions = { 'ElementService', 'RootScopeService', 'EventService', - ] + ]; constructor( private $q: VeQService, @@ -90,40 +90,40 @@ const RedirectComponent: VeComponentOptions = { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); - this.rootScopeSvc.veTitle('Redirecting... | View Editor') //what to name this? + this.rootScopeSvc.veTitle('Redirecting... | View Editor'); //what to name this? - this.redirect_from_old = this.rootScopeSvc.veRedirectFromOld() + this.redirect_from_old = this.rootScopeSvc.veRedirectFromOld(); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEREDIRECTFROMOLD, (data: boolean) => { - this.redirect_from_old = data + this.redirect_from_old = data; }) - ) + ); this.projectSvc.getProjects().then( (projectObs) => { this.projectIds = projectObs.map((a) => { - return a.id - }) + return a.id; + }); this.reqOb = { projectId: this.projectIds[0], refId: 'master', - } - this.oldUrlTest(this.rootScopeSvc.veCrushUrl()) + }; + this.oldUrlTest(this.rootScopeSvc.veCrushUrl()); }, (reason) => { - this.growl.error('Error getting projects: ' + reason.message) + this.growl.error('Error getting projects: ' + reason.message); } - ) + ); } public resetSelectPage = (): void => { - void this.$state.go('main.login.select') - } + void this.$state.go('main.login.select'); + }; public buildQuery(idList: string[], projectIds: string[]): QueryObject[] { - const queryObs: QueryObject[] = [] + const queryObs: QueryObject[] = []; //Filter master ref for (const id of idList) { for (const projectId of projectIds) { @@ -133,32 +133,32 @@ const RedirectComponent: VeComponentOptions = { _projectId: projectId, _inRefIds: 'master', }, - } - queryObs.push(queryOb) + }; + queryObs.push(queryOb); } } - return queryObs + return queryObs; } public errorHandler = (reason: VePromiseReason>): void => { - this.growl.error(reason.message) - void this.$state.go('main.login.select') - } + this.growl.error(reason.message); + void this.$state.go('main.login.select'); + }; public oldUrlTest = (location: string): void => { - const segments: string[] = location.split('/') - let successRedirectFnc: (data: ViewObject[]) => void - const searchTermList: string[] = [] + const segments: string[] = location.split('/'); + let successRedirectFnc: (data: ViewObject[]) => void; + const searchTermList: string[] = []; const noResultFnc = (): void => { // TODO - Search for document was unsucessful. Please select from the following or contact admin to verify that document exists. - this.redirect_noResults = true - } - let redirectFnc: () => void = noResultFnc + this.redirect_noResults = true; + }; + let redirectFnc: () => void = noResultFnc; if (segments.length === 5) { if (location.includes('sites')) { //Search for site - searchTermList.push(segments[4] + '_cover') + searchTermList.push(segments[4] + '_cover'); successRedirectFnc = (data): void => { if (data.length > 0) { this.redirect_element = { @@ -170,24 +170,24 @@ const RedirectComponent: VeComponentOptions = { "',refId:'master',preview:'" + data[0].id + "'})", - } + }; redirectFnc = (): void => { void this.$state.go('main.project.ref.portal.preview', { projectId: data[0]._projectId, refId: 'master', preview: data[0].id, - }) - } + }); + }; } else { - noResultFnc() + noResultFnc(); } - } + }; } } else if (segments.length === 7) { //Search for document if (location.includes('documents')) { // ["", "workspaces", "master", "sites", "site__18_0_6_eda034b_1489006578377_52061_121780", "document", "_18_0_6_bec02f9_1489697812908_180368_252005"] - searchTermList.push(segments[6]) + searchTermList.push(segments[6]); successRedirectFnc = (data): void => { if (data.length > 0) { this.redirect_element = { @@ -199,20 +199,20 @@ const RedirectComponent: VeComponentOptions = { "',refId:'master',documentId:'" + data[0].id + "'})", - } + }; redirectFnc = (): void => { void this.$state.go('main.project.ref.view.present', { projectId: data[0]._projectId, refId: 'master', documentId: data[0].id, - }) - } + }); + }; } else { - noResultFnc() + noResultFnc(); } - } + }; } else if (location.includes('document')) { - searchTermList.push(segments[6]) + searchTermList.push(segments[6]); successRedirectFnc = (data): void => { if (data.length > 0) { this.redirect_element = { @@ -224,25 +224,25 @@ const RedirectComponent: VeComponentOptions = { "',refId:'master',preview:'" + data[0].id + "'})", - } + }; redirectFnc = (): void => { void this.$state.go('main.project.ref.portal.preview', { projectId: data[0]._projectId, refId: 'master', preview: data[0].id, - }) - } + }); + }; } else { - noResultFnc() + noResultFnc(); } - } + }; } } else if (segments.length === 9) { //Search for view if (location.includes('views')) { // ["", "workspaces", "master", "sites", "site__18_0_6_eda034b_1489006578377_52061_121780", "documents", "_18_0_6_bec02f9_1489697812908_180368_252005", "views", "MMS_1474405796233_0887698d-1fc7-47ac-87ac-b0f6e7b69d35"] if (segments[6] == segments[8]) { - searchTermList.push(segments[6]) + searchTermList.push(segments[6]); successRedirectFnc = (data): void => { if (data.length > 0) { this.redirect_element = { @@ -256,22 +256,22 @@ const RedirectComponent: VeComponentOptions = { "',viewId:'" + data[0].id + "'})", - } + }; redirectFnc = (): void => { void this.$state.go('main.project.ref.view.present', { projectId: data[0]._projectId, refId: 'master', documentId: data[0].id, viewId: data[0].id, - }) - } + }); + }; } else { - noResultFnc() + noResultFnc(); } - } + }; } else { - searchTermList.push(segments[6]) - searchTermList.push(segments[8]) + searchTermList.push(segments[6]); + searchTermList.push(segments[8]); successRedirectFnc = (data): void => { if (data.length > 1) { if (data[0].id === segments[6] && data[1].id === segments[8]) { @@ -287,15 +287,15 @@ const RedirectComponent: VeComponentOptions = { "',viewId:'" + data[1].id + "'})", - } + }; redirectFnc = (): void => { void this.$state.go('main.project.ref.view.present', { projectId: data[0]._projectId, refId: 'master', documentId: data[0].id, viewId: data[1].id, - }) - } + }); + }; } else if (data[0].id === segments[8] && data[1].id === segments[6]) { //should check case if data[1] is segent[6] also this.redirect_element = { @@ -309,20 +309,20 @@ const RedirectComponent: VeComponentOptions = { "',viewId:'" + data[0].id + "'})", - } + }; redirectFnc = (): void => { void this.$state.go('main.project.ref.view.present', { projectId: data[0]._projectId, refId: 'master', documentId: data[1].id, viewId: data[0].id, - }) - } + }); + }; } } else if (data.length > 0) { if (data[0].id === segments[8]) { - this.elem = data[0] - this.redirect_relatedDocs = data[0]._relatedDocuments + this.elem = data[0]; + this.redirect_relatedDocs = data[0]._relatedDocuments; } else if (data[0].id === segments[6]) { this.redirect_element = { name: data[0].name, @@ -333,25 +333,25 @@ const RedirectComponent: VeComponentOptions = { "',refId:'master',documentId:'" + data[0].id + "'})", - } + }; redirectFnc = (): void => { void this.$state.go('main.project.ref.view.present', { projectId: data[0]._projectId, refId: 'master', documentId: data[0].id, - }) - } + }); + }; } } else { - noResultFnc() + noResultFnc(); } - } + }; } } } else if (segments.length === 8) { //Search for full doc if (location.includes('full')) { - searchTermList.push(segments[6]) + searchTermList.push(segments[6]); successRedirectFnc = (data): void => { if (data.length > 0) { this.redirect_element = { @@ -363,34 +363,34 @@ const RedirectComponent: VeComponentOptions = { "',refId:'master',documentId:'" + data[0].id + "'})", - } + }; redirectFnc = (): void => { void this.$state.go('main.project.ref.view.present.document', { projectId: data[0]._projectId, refId: 'master', documentId: data[0].id, - }) - } + }); + }; } else { - noResultFnc() + noResultFnc(); } - } + }; } } // console.log(segments); - const queryObs: QueryObject[] = this.buildQuery(searchTermList, this.projectIds) - const promises: angular.IPromise[] = [] + const queryObs: QueryObject[] = this.buildQuery(searchTermList, this.projectIds); + const promises: angular.IPromise[] = []; for (const queryOb of queryObs) { - promises.push(this.elementSvc.search(this.reqOb, queryOb)) + promises.push(this.elementSvc.search(this.reqOb, queryOb)); } this.$q .all(promises) .then(successRedirectFnc, this.errorHandler) .finally(() => { - redirectFnc() - }) - } + redirectFnc(); + }); + }; }, -} +}; -veApp.component(RedirectComponent.selector, RedirectComponent) +veApp.component(RedirectComponent.selector, RedirectComponent); diff --git a/src/ve-app/login/select.component.ts b/src/ve-app/login/select.component.ts index 95af036a8..1486acad5 100644 --- a/src/ve-app/login/select.component.ts +++ b/src/ve-app/login/select.component.ts @@ -1,16 +1,16 @@ -import { StateService, TransitionService, UIRouter, UIRouterGlobals } from '@uirouter/angularjs' -import { IComponentController } from 'angular' -import Rx from 'rx-lite' +import { StateService, TransitionService, UIRouter, UIRouterGlobals } from '@uirouter/angularjs'; +import { IComponentController } from 'angular'; +import Rx from 'rx-lite'; -import { BrandingStyle, RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ProjectService, AuthService } from '@ve-utils/mms-api-client' +import { BrandingStyle, RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ProjectService, AuthService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { OrgObject, ParamsObject, ProjectObject } from '@ve-types/mms' -import { VeStorageService } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { OrgObject, ParamsObject, ProjectObject } from '@ve-types/mms'; +import { VeStorageService } from '@ve-types/view-editor'; class SelectController implements IComponentController { static $inject = [ @@ -23,33 +23,33 @@ class SelectController implements IComponentController { 'AuthService', 'RootScopeService', 'EventService', - ] + ]; //injectables - private $uiRouterGlobals: UIRouterGlobals = this.$uiRouter.globals - public subs: Rx.IDisposable[] + private $uiRouterGlobals: UIRouterGlobals = this.$uiRouter.globals; + public subs: Rx.IDisposable[]; //Bindings - public mmsOrgs: OrgObject[] - mmsLoginBanner: BrandingStyle - mmsProjects: ProjectObject[] + public mmsOrgs: OrgObject[]; + mmsLoginBanner: BrandingStyle; + mmsProjects: ProjectObject[]; //local - public redirect_from_old: boolean - pageTitle: string - fromLogin: boolean - spin: boolean = false - logout_spin: boolean = false - orgs: OrgObject[] - projects: ProjectObject[] - orgId: string - projectId: string - selectedOrg: string - selectedProject: string - loginBanner: BrandingStyle - protected orgSpin: boolean - protected projSpin: boolean - protected bannerSpin: boolean + public redirect_from_old: boolean; + pageTitle: string; + fromLogin: boolean; + spin: boolean = false; + logout_spin: boolean = false; + orgs: OrgObject[]; + projects: ProjectObject[]; + orgId: string; + projectId: string; + selectedOrg: string; + selectedProject: string; + loginBanner: BrandingStyle; + protected orgSpin: boolean; + protected projSpin: boolean; + protected bannerSpin: boolean; constructor( private $uiRouter: UIRouter, @@ -64,143 +64,143 @@ class SelectController implements IComponentController { ) {} $onInit(): void { - this.rootScopeSvc.veShowLogin(true) + this.rootScopeSvc.veShowLogin(true); if (!this.mmsLoginBanner) { this.mmsLoginBanner = { labels: ['Select Desired Org/Project Above'], disabled: false, - } + }; } - this.loginBanner = this.mmsLoginBanner + this.loginBanner = this.mmsLoginBanner; - this.eventSvc.$init(this) - this.rootScopeSvc.veTitle('View Editor') //what to name this? - this.redirect_from_old = this.rootScopeSvc.veRedirectFromOld() + this.eventSvc.$init(this); + this.rootScopeSvc.veTitle('View Editor'); //what to name this? + this.redirect_from_old = this.rootScopeSvc.veRedirectFromOld(); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEREDIRECTFROMOLD, (data: boolean) => { - this.redirect_from_old = data + this.redirect_from_old = data; }) - ) - this.rootScopeSvc.veTitle('Projects') - this.pageTitle = 'View Editor' - this.fromLogin = (this.$uiRouterGlobals.params as ParamsObject).fromLogin - this.$localStorage.$default({ org: this.mmsOrgs[0] }) - this.orgs = this.mmsOrgs + ); + this.rootScopeSvc.veTitle('Projects'); + this.pageTitle = 'View Editor'; + this.fromLogin = (this.$uiRouterGlobals.params as ParamsObject).fromLogin; + this.$localStorage.$default({ org: this.mmsOrgs[0] }); + this.orgs = this.mmsOrgs; if (this.$localStorage.org) { - this.selectOrg(this.$localStorage.org) + this.selectOrg(this.$localStorage.org); } } public selectOrg = (org: OrgObject): void => { if (org) { - this.$localStorage.org = org - this.orgId = org.id - this.$localStorage.org.orgName = org.name - this.selectedOrg = this.$localStorage.org.name - this.selectedProject = '$resolve.Ob' // default here? + this.$localStorage.org = org; + this.orgId = org.id; + this.$localStorage.org.orgName = org.name; + this.selectedOrg = this.$localStorage.org.name; + this.selectedProject = '$resolve.Ob'; // default here? this.projectSvc.getProjects(this.orgId).then( (data) => { - this.projects = data + this.projects = data; if (data && data.length > 0) { if (this.$localStorage.project && this.checkForProject(data, this.$localStorage.project)) { - this.selectedProject = this.$localStorage.project.name - this.projectId = this.$localStorage.project.id + this.selectedProject = this.$localStorage.project.name; + this.projectId = this.$localStorage.project.id; } else { - this.selectProject(data[0]) + this.selectProject(data[0]); } } }, (reason) => { - this.growl.error('Error getting project data: ' + reason.message) + this.growl.error('Error getting project data: ' + reason.message); } - ) + ); } - } + }; public selectProject = (project: ProjectObject): void => { if (project) { - this.$localStorage.project = project - this.selectedProject = this.$localStorage.project.name - this.projectId = this.$localStorage.project.id + this.$localStorage.project = project; + this.selectedProject = this.$localStorage.project.name; + this.projectId = this.$localStorage.project.id; } - } + }; public refreshOrgs = (): void => { - this.orgSpin = true - this.orgs.length = 0 + this.orgSpin = true; + this.orgs.length = 0; this.projectSvc .getOrgs(true) .then((data) => { - this.orgs.push(...data) + this.orgs.push(...data); }) .finally(() => { - this.orgSpin = false - }) - } + this.orgSpin = false; + }); + }; public refreshProjects = (): void => { - this.projSpin = true - this.projects.length = 0 + this.projSpin = true; + this.projects.length = 0; this.projectSvc .getProjects(this.orgId, true) .then((data) => { - this.projects.push(...data) + this.projects.push(...data); if ( data && data.length > 0 && this.projects.filter((p) => { - return p.id === this.projectId + return p.id === this.projectId; }).length === 0 ) { - this.selectProject(data[0]) + this.selectProject(data[0]); } else { //no projects } }) .finally(() => { - this.projSpin = false - }) - } + this.projSpin = false; + }); + }; public checkForProject(projectArray: ProjectObject[], project: ProjectObject): boolean { for (let i = 0; i < projectArray.length; i++) { if (projectArray[i].id === project.id) { - return true + return true; } } - return false + return false; } public continue = (): void => { if (this.orgId && this.projectId) { - this.spin = true - this.rootScopeSvc.veRedirectFromOld(false) + this.spin = true; + this.rootScopeSvc.veRedirectFromOld(false); void this.$state .go('main.project.ref.portal', { orgId: this.orgId, projectId: this.projectId, refId: 'master', }) - .finally(() => (this.spin = false)) + .finally(() => (this.spin = false)); } - } + }; public logout = (): void => { - this.logout_spin = true + this.logout_spin = true; this.authSvc .logout() .then( () => { - void this.$state.go('main.login', {}) + void this.$state.go('main.login', {}); }, () => { - this.growl.error('You were not logged out') + this.growl.error('You were not logged out'); } ) .finally(() => { - this.logout_spin = false - }) - } + this.logout_spin = false; + }); + }; } const SelectComponent: VeComponentOptions = { @@ -277,6 +277,6 @@ const SelectComponent: VeComponentOptions = { mmsLoginBanner: '<', }, controller: SelectController, -} +}; -veApp.component(SelectComponent.selector, SelectComponent) +veApp.component(SelectComponent.selector, SelectComponent); diff --git a/src/ve-app/login/short-url.component.ts b/src/ve-app/login/short-url.component.ts index cff63aed3..19efa5273 100644 --- a/src/ve-app/login/short-url.component.ts +++ b/src/ve-app/login/short-url.component.ts @@ -1,13 +1,13 @@ -import { StateService } from '@uirouter/angularjs' -import { IComponentController } from 'angular' -import Rx from 'rx-lite' +import { StateService } from '@uirouter/angularjs'; +import { IComponentController } from 'angular'; +import Rx from 'rx-lite'; -import { RootScopeService, ShortUrlService } from '@ve-utils/application' +import { RootScopeService, ShortUrlService } from '@ve-utils/application'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { ParamsObject } from '@ve-types/mms' +import { VeComponentOptions } from '@ve-types/angular'; +import { ParamsObject } from '@ve-types/mms'; const ShortUrlComponent: VeComponentOptions = { selector: 'shortUrl', @@ -29,15 +29,15 @@ const ShortUrlComponent: VeComponentOptions = { paramsOb: '<', }, controller: class ShortUrlController implements IComponentController { - private paramsOb: ParamsObject - public subs: Rx.IDisposable[] + private paramsOb: ParamsObject; + public subs: Rx.IDisposable[]; - decodedUrl: ParamsObject - redirect_noResults: boolean = false - spin: boolean = true - error: string = '' + decodedUrl: ParamsObject; + redirect_noResults: boolean = false; + spin: boolean = true; + error: string = ''; - static $inject = ['$state', 'growl', 'ShortUrlService', 'RootScopeService'] + static $inject = ['$state', 'growl', 'ShortUrlService', 'RootScopeService']; constructor( private $state: StateService, @@ -47,45 +47,45 @@ const ShortUrlComponent: VeComponentOptions = { ) {} $onInit(): void { - this.rootScopeSvc.veTitle('Redirecting... | View Editor') //what to name this? + this.rootScopeSvc.veTitle('Redirecting... | View Editor'); //what to name this? if (this.paramsOb && this.paramsOb.shortUrl) { this.shortUrlSvc.decodeShortUrl(this.paramsOb.shortUrl).then( (result) => { - this.decodedUrl = result + this.decodedUrl = result; if (this.decodedUrl.viewId) { - void this.$state.go('main.project.ref.view.present', this.decodedUrl) - return + void this.$state.go('main.project.ref.view.present', this.decodedUrl); + return; } if (this.decodedUrl.documentId) { - void this.$state.go('main.project.ref.view.present', this.decodedUrl) - return + void this.$state.go('main.project.ref.view.present', this.decodedUrl); + return; } if (this.decodedUrl.refId) { - void this.$state.go('main.project.ref.portal', this.decodedUrl) - return + void this.$state.go('main.project.ref.portal', this.decodedUrl); + return; } if (this.decodedUrl.projectId) { - void this.$state.go('main.project.refs', this.decodedUrl) - return + void this.$state.go('main.project.refs', this.decodedUrl); + return; } }, (reason) => { - this.spin = false - this.redirect_noResults = true - this.growl.error(reason.message) + this.spin = false; + this.redirect_noResults = true; + this.growl.error(reason.message); } - ) + ); } else { - this.spin = false - this.redirect_noResults = true - this.growl.error('No short URL found.') + this.spin = false; + this.redirect_noResults = true; + this.growl.error('No short URL found.'); } } public resetSelectPage = (): void => { - void this.$state.go('main.login.select') - } + void this.$state.go('main.login.select'); + }; }, -} +}; -veApp.component(ShortUrlComponent.selector, ShortUrlComponent) +veApp.component(ShortUrlComponent.selector, ShortUrlComponent); diff --git a/src/ve-app/main/components/index.ts b/src/ve-app/main/components/index.ts index 71f2bf476..71aed639d 100644 --- a/src/ve-app/main/components/index.ts +++ b/src/ve-app/main/components/index.ts @@ -1,4 +1,4 @@ -import './system-footer.component' -import './main-menu.component' -import './nav-bar.component' -import './system-banner.component' +import './system-footer.component'; +import './main-menu.component'; +import './nav-bar.component'; +import './system-banner.component'; diff --git a/src/ve-app/main/components/main-menu.component.ts b/src/ve-app/main/components/main-menu.component.ts index 85b075a77..0e33fca29 100644 --- a/src/ve-app/main/components/main-menu.component.ts +++ b/src/ve-app/main/components/main-menu.component.ts @@ -1,55 +1,55 @@ -import { StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs' -import angular, { IComponentController } from 'angular' +import { StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs'; +import angular, { IComponentController } from 'angular'; -import { ApplicationService, RootScopeService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { onChangesCallback } from '@ve-utils/utils' +import { ApplicationService, RootScopeService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { onChangesCallback } from '@ve-utils/utils'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions, VeQService } from '@ve-types/angular' -import { DocumentObject, GroupObject, ParamsObject, ProjectObject, RefObject, ViewObject } from '@ve-types/mms' +import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { DocumentObject, GroupObject, ParamsObject, ProjectObject, RefObject, ViewObject } from '@ve-types/mms'; interface BreadcrumbObject { - name: string - id: string - type: string - link: string + name: string; + id: string; + type: string; + link: string; } class MenuController implements IComponentController { //bindings - public params: ParamsObject - public mmsProject: ProjectObject - public mmsProjects: ProjectObject[] - public mmsGroup: GroupObject - public mmsGroups: GroupObject[] - public mmsRef: RefObject - public mmsRefs: RefObject[] - public mmsDocument: DocumentObject + public params: ParamsObject; + public mmsProject: ProjectObject; + public mmsProjects: ProjectObject[]; + public mmsGroup: GroupObject; + public mmsGroups: GroupObject[]; + public mmsRef: RefObject; + public mmsRefs: RefObject[]; + public mmsDocument: DocumentObject; //Locals - spin: boolean - public child: DocumentObject | GroupObject - crumbs: BreadcrumbObject[] = [] - groups: GroupObject[] - projects: ProjectObject[] - refs: RefObject[] - tags: RefObject[] - document: DocumentObject - view: ViewObject + spin: boolean; + public child: DocumentObject | GroupObject; + crumbs: BreadcrumbObject[] = []; + groups: GroupObject[]; + projects: ProjectObject[]; + refs: RefObject[]; + tags: RefObject[]; + document: DocumentObject; + view: ViewObject; groupsMap: { - [id: string]: { id: string; name: string; parentId: string } - } = {} - isRefsView: boolean = false - public htmlTooltip - public currentProject: string - public currentRef: RefObject - public currentBranch: string - public currentTag: string - public breadcrumbs: BreadcrumbObject[] - public truncateStyle - public subs: Rx.IDisposable[] + [id: string]: { id: string; name: string; parentId: string }; + } = {}; + isRefsView: boolean = false; + public htmlTooltip; + public currentProject: string; + public currentRef: RefObject; + public currentBranch: string; + public currentTag: string; + public breadcrumbs: BreadcrumbObject[]; + public truncateStyle; + public subs: Rx.IDisposable[]; static $inject = [ '$q', @@ -62,7 +62,7 @@ class MenuController implements IComponentController { 'UtilsService', 'RootScopeService', 'EventService', - ] + ]; constructor( public $q: VeQService, private $uiRouterGlobals: UIRouterGlobals, @@ -75,77 +75,77 @@ class MenuController implements IComponentController { private rootScopeSvc: RootScopeService, public eventSvc: EventService ) { - this.htmlTooltip = 'Branch temporarily unavailable during duplication.' + this.htmlTooltip = 'Branch temporarily unavailable during duplication.'; } $onInit(): void { - this.eventSvc.$init(this) - this.projects = this.mmsProjects - this.groups = this.mmsGroups - this.refs = this.mmsRefs + this.eventSvc.$init(this); + this.projects = this.mmsProjects; + this.groups = this.mmsGroups; + this.refs = this.mmsRefs; if (this.mmsProject && !this.currentProject) { - this.currentProject = this.mmsProject.name + this.currentProject = this.mmsProject.name; } if (this.mmsRef && !this.currentRef) { - this.currentRef = this.mmsRef + this.currentRef = this.mmsRef; if (this.mmsRef.type === 'Branch') { - this.currentBranch = this.mmsRef.name + this.currentBranch = this.mmsRef.name; } else if (this.mmsRef.type === 'Tag') { - this.currentTag = this.mmsRef.name + this.currentTag = this.mmsRef.name; } } this.tags = this.mmsRefs.filter((ref) => { - return ref.type === 'Tag' - }) - this.updateGroups() + return ref.type === 'Tag'; + }); + this.updateGroups(); this.$transitions.onSuccess({}, () => { - this.spin = true - this.updateBreadcrumbs() - }) + this.spin = true; + this.updateBreadcrumbs(); + }); } updateGroups: onChangesCallback = () => { - this.groupsMap = {} - this.spin = true + this.groupsMap = {}; + this.spin = true; if (typeof this.mmsGroups !== 'undefined') { - this.groups = this.mmsGroups + this.groups = this.mmsGroups; for (let i = 0; i < this.groups.length; i++) { this.groupsMap[this.groups[i].id] = { id: this.groups[i].id, name: this.groups[i].name, parentId: this.groups[i]._parentId, - } + }; } - this.updateBreadcrumbs() + this.updateBreadcrumbs(); } else { - this.updateBreadcrumbs() + this.updateBreadcrumbs(); } - } + }; public updateBreadcrumbs: onChangesCallback = () => { - let parentId = '' - let oldChild = null - if (this.child) oldChild = this.child + let parentId = ''; + let oldChild = null; + if (this.child) oldChild = this.child; if (this.mmsDocument) { - this.child = this.mmsDocument - this.rootScopeSvc.veTitle(this.mmsDocument.name) + this.child = this.mmsDocument; + this.rootScopeSvc.veTitle(this.mmsDocument.name); } else if (this.mmsGroup) { - this.rootScopeSvc.veTitle(this.mmsGroup.name) - this.child = this.mmsGroup + this.rootScopeSvc.veTitle(this.mmsGroup.name); + this.child = this.mmsGroup; } else { - this.rootScopeSvc.veTitle(this.currentProject) + this.rootScopeSvc.veTitle(this.currentProject); } // Check for Refs View, Skip the rest if it is if (this.$state.includes('main.project.ref.refs')) { - this.isRefsView = true - return + this.isRefsView = true; + return; } if (this.child && this.child != oldChild) { - this.crumbs = [] + this.crumbs = []; if (this.child.type === 'Package') { //child.hasOwnProperty('_id')) { this.crumbs.push({ @@ -153,9 +153,9 @@ class MenuController implements IComponentController { id: this.child.id, type: 'group', link: "main.project.ref.portal.preview({preview: 'site_' + breadcrumb.id + '_cover', keywords: undefined})", - }) + }); if (this.child._parentId) { - parentId = (this.child as GroupObject)._parentId + parentId = (this.child as GroupObject)._parentId; } } else { this.crumbs.push({ @@ -163,41 +163,41 @@ class MenuController implements IComponentController { id: this.child.id, type: 'doc', link: 'main.project.ref.view.present({documentId: breadcrumb.id, keywords: undefined})', - }) + }); if (this.child._groupId) { - parentId = (this.child as DocumentObject)._groupId + parentId = (this.child as DocumentObject)._groupId; } } if (parentId) { while (this.groupsMap[parentId] !== undefined) { - const id = this.groupsMap[parentId].id + const id = this.groupsMap[parentId].id; this.crumbs.push({ name: this.groupsMap[id].name, id: id, type: 'group', link: "main.project.ref.portal.preview({preview: 'site_' + breadcrumb.id + '_cover', keywords: undefined})", - }) - parentId = this.groupsMap[id].parentId + }); + parentId = this.groupsMap[id].parentId; } } - this.breadcrumbs = this.crumbs.reverse() + this.breadcrumbs = this.crumbs.reverse(); void this.$timeout(() => { - const eltChildren = this.$element.children().children() - const eltParent = this.$element.parent()[0] - const eltWidth = eltParent.clientWidth - eltChildren[1].scrollWidth - eltChildren[3].scrollWidth - const crumbcount = this.breadcrumbs.length - const liWidth = (eltWidth * 0.85) / crumbcount + const eltChildren = this.$element.children().children(); + const eltParent = this.$element.parent()[0]; + const eltWidth = eltParent.clientWidth - eltChildren[1].scrollWidth - eltChildren[3].scrollWidth; + const crumbcount = this.breadcrumbs.length; + const liWidth = (eltWidth * 0.85) / crumbcount; this.truncateStyle = { 'max-width': liWidth, 'white-space': 'nowrap', overflow: 'hidden', 'text-overflow': 'ellipsis', display: 'inline-block', - } - }) + }; + }); } - this.spin = false - } + this.spin = false; + }; updateProject(project: ProjectObject): void { if (project) { @@ -209,7 +209,7 @@ class MenuController implements IComponentController { keywords: undefined, }, { reload: true } - ) + ); } } @@ -223,7 +223,7 @@ class MenuController implements IComponentController { keywords: undefined, }, { reload: true } - ) + ); } } @@ -232,14 +232,14 @@ class MenuController implements IComponentController { 'main.project.ref.refs', { projectId: this.params.projectId, refId: this.params.refId }, { reload: true } - ) + ); } goHome(): void { void this.$state.go('main.project.ref.portal', { field: undefined, keywords: undefined, - }) + }); } } @@ -328,6 +328,6 @@ const MainMenuComponent: VeComponentOptions = { mmsDocument: '<', }, controller: MenuController, -} +}; -veApp.component(MainMenuComponent.selector, MainMenuComponent) +veApp.component(MainMenuComponent.selector, MainMenuComponent); diff --git a/src/ve-app/main/components/nav-bar.component.ts b/src/ve-app/main/components/nav-bar.component.ts index e30dc6e0b..291fb2ff1 100644 --- a/src/ve-app/main/components/nav-bar.component.ts +++ b/src/ve-app/main/components/nav-bar.component.ts @@ -1,15 +1,15 @@ -import { StateService, UIRouter } from '@uirouter/angularjs' +import { StateService, UIRouter } from '@uirouter/angularjs'; -import { SelectModalResolveFn } from '@ve-app/main/modals/select-modal.component' -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { AuthService, UserService } from '@ve-utils/mms-api-client' +import { SelectModalResolveFn } from '@ve-app/main/modals/select-modal.component'; +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { AuthService, UserService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { OrgObject, ProjectObject, RefObject, UserObject } from '@ve-types/mms' -import { VeModalService, VeModalSettings } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { OrgObject, ProjectObject, RefObject, UserObject } from '@ve-types/mms'; +import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; class NavBarController implements angular.IComponentController { static $inject = [ @@ -24,32 +24,32 @@ class NavBarController implements angular.IComponentController { 'UserService', 'EventService', 'RootScopeService', - ] + ]; //bindings - public mmsOrg: OrgObject - public mmsProject: ProjectObject - public mmsProjects: ProjectObject[] - public mmsRef: RefObject - public mmsOrgs: OrgObject[] + public mmsOrg: OrgObject; + public mmsProject: ProjectObject; + public mmsProjects: ProjectObject[]; + public mmsRef: RefObject; + public mmsOrgs: OrgObject[]; //injectables - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; //local - public isNavCollapsed: boolean - public about: string - public searchClass: string - public username: string - public user: UserObject - public userBadge: string - - protected showSearch: boolean = true - private project: ProjectObject - private org: OrgObject - private ref: RefObject - private projects: ProjectObject[] - private orgs: OrgObject[] + public isNavCollapsed: boolean; + public about: string; + public searchClass: string; + public username: string; + public user: UserObject; + public userBadge: string; + + protected showSearch: boolean = true; + private project: ProjectObject; + private org: OrgObject; + private ref: RefObject; + private projects: ProjectObject[]; + private orgs: OrgObject[]; constructor( private $uiRouter: UIRouter, @@ -64,44 +64,44 @@ class NavBarController implements angular.IComponentController { private eventSvc: EventService, private rootScopeSvc: RootScopeService ) { - this.isNavCollapsed = true + this.isNavCollapsed = true; - this.searchClass = '' + this.searchClass = ''; } $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); - this.project = this.mmsProject - this.ref = this.mmsRef - this.org = this.mmsOrg + this.project = this.mmsProject; + this.ref = this.mmsRef; + this.org = this.mmsOrg; - this.showSearch = !this.$state.includes('**.search.**') + this.showSearch = !this.$state.includes('**.search.**'); void this.authSvc.checkLogin().then( (data) => { - this.username = data.username + this.username = data.username; this.userSvc.getUserData(data.username).then( (userData) => { - this.user = userData + this.user = userData; if (this.user.firstName) { - this.userBadge = this.user.firstName.substring(0, 1).toUpperCase() - this.userBadge += this.user.lastName.substring(0, 1).toUpperCase() + this.userBadge = this.user.firstName.substring(0, 1).toUpperCase(); + this.userBadge += this.user.lastName.substring(0, 1).toUpperCase(); } else { this.userBadge = this.user.username ? this.user.username.substring(0, 2).toUpperCase() - : 'VE' + : 'VE'; } }, () => { - this.userBadge = this.username.substring(0, 1).toUpperCase() + this.userBadge = this.username.substring(0, 1).toUpperCase(); } - ) + ); }, () => { - this.eventSvc.$broadcast('mms.unauthorized') + this.eventSvc.$broadcast('mms.unauthorized'); } - ) + ); } updateOrg(): void { @@ -110,56 +110,56 @@ class NavBarController implements angular.IComponentController { windowClass: 've-dropdown-short-modal', resolve: { mmsOrgs: () => { - return this.mmsOrgs + return this.mmsOrgs; }, mmsOrg: () => { - return this.org + return this.org; }, mmsProjects: () => { - return this.mmsProjects + return this.mmsProjects; }, mmsProject: () => { - return this.project + return this.project; }, }, - } - this.$uibModal.open(settings) + }; + this.$uibModal.open(settings); } toggleHelp(): void { - this.hotkeys.toggleCheatSheet() + this.hotkeys.toggleCheatSheet(); } toggleAbout(): void { this.$uibModal.open({ component: 'aboutModal', - }) + }); } logout(): void { this.authSvc.logout().then( () => { - void this.$state.go('main.login') + void this.$state.go('main.login'); }, () => { - this.growl.error('You were not logged out') + this.growl.error('You were not logged out'); } - ) + ); } search(searchText: string): void { if (this.$state.includes('main.project.ref.view.reorder')) { - this.growl.warning('Please finish reorder action first.') - return + this.growl.warning('Please finish reorder action first.'); + return; // } else if ($state.includes('main.project.diff')) { // growl.warning("Please finish diff action first."); // return; } else { - this.searchClass = 'fa fa-spin fa-spinner' + this.searchClass = 'fa fa-spin fa-spinner'; void this.$state.go('main.project.ref.search', { keywords: searchText, field: 'name', - }) + }); } } } @@ -245,6 +245,6 @@ const NavBarComponent: VeComponentOptions = { `, controller: NavBarController, -} +}; -veApp.component(NavBarComponent.selector, NavBarComponent) +veApp.component(NavBarComponent.selector, NavBarComponent); diff --git a/src/ve-app/main/components/system-banner.component.ts b/src/ve-app/main/components/system-banner.component.ts index 6da0f2fab..5ee0cce56 100644 --- a/src/ve-app/main/components/system-banner.component.ts +++ b/src/ve-app/main/components/system-banner.component.ts @@ -1,10 +1,10 @@ -import { IComponentController } from 'angular' +import { IComponentController } from 'angular'; -import { BrandingStyle } from '@ve-utils/application' +import { BrandingStyle } from '@ve-utils/application'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; const SystemBannerComponent: VeComponentOptions = { selector: 'systemBanner', @@ -23,20 +23,20 @@ const SystemBannerComponent: VeComponentOptions = { mmsBanner: '<', }, controller: class SystemBannerController implements IComponentController { - public mmsBanner: BrandingStyle + public mmsBanner: BrandingStyle; - public disabled: boolean - public loading: boolean - public bannerMessage: string[] = ['Loading...'] + public disabled: boolean; + public loading: boolean; + public bannerMessage: string[] = ['Loading...']; $onInit(): void { - this.loading = true - if (Array.isArray(this.mmsBanner.message)) this.bannerMessage = this.mmsBanner.message - else this.bannerMessage = [this.mmsBanner.message] - this.disabled = this.mmsBanner.disabled ? this.mmsBanner.disabled : false - this.loading = false + this.loading = true; + if (Array.isArray(this.mmsBanner.message)) this.bannerMessage = this.mmsBanner.message; + else this.bannerMessage = [this.mmsBanner.message]; + this.disabled = this.mmsBanner.disabled ? this.mmsBanner.disabled : false; + this.loading = false; } }, -} +}; -veApp.component(SystemBannerComponent.selector, SystemBannerComponent) +veApp.component(SystemBannerComponent.selector, SystemBannerComponent); diff --git a/src/ve-app/main/components/system-footer.component.ts b/src/ve-app/main/components/system-footer.component.ts index c2aeacaf2..c8c82fec7 100644 --- a/src/ve-app/main/components/system-footer.component.ts +++ b/src/ve-app/main/components/system-footer.component.ts @@ -1,10 +1,10 @@ -import { IComponentController } from 'angular' +import { IComponentController } from 'angular'; -import { BrandingStyle } from '@ve-utils/application' +import { BrandingStyle } from '@ve-utils/application'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; const SystemFooterComponent: VeComponentOptions = { selector: 'systemFooter', @@ -21,20 +21,20 @@ const SystemFooterComponent: VeComponentOptions = { mmsFooter: '<', }, controller: class FooterController implements IComponentController { - private mmsFooter: BrandingStyle + private mmsFooter: BrandingStyle; - public disabled: boolean - public loading: boolean - public footerMessage: string | string[] + public disabled: boolean; + public loading: boolean; + public footerMessage: string | string[]; $onInit(): void { - this.loading = true - if (Array.isArray(this.mmsFooter.message)) this.footerMessage = this.mmsFooter.message - else this.footerMessage = [this.mmsFooter.message] - this.disabled = this.mmsFooter.disabled ? this.mmsFooter.disabled : false - this.loading = false + this.loading = true; + if (Array.isArray(this.mmsFooter.message)) this.footerMessage = this.mmsFooter.message; + else this.footerMessage = [this.mmsFooter.message]; + this.disabled = this.mmsFooter.disabled ? this.mmsFooter.disabled : false; + this.loading = false; } }, -} +}; -veApp.component(SystemFooterComponent.selector, SystemFooterComponent) +veApp.component(SystemFooterComponent.selector, SystemFooterComponent); diff --git a/src/ve-app/main/index.ts b/src/ve-app/main/index.ts index 99c0bb5bd..a0c5f837b 100644 --- a/src/ve-app/main/index.ts +++ b/src/ve-app/main/index.ts @@ -1,6 +1,6 @@ -import './main.component' +import './main.component'; -import './services' +import './services'; -import './modals' -import './components' +import './modals'; +import './components'; diff --git a/src/ve-app/main/main.component.ts b/src/ve-app/main/main.component.ts index 5126ac547..7a3d97294 100644 --- a/src/ve-app/main/main.component.ts +++ b/src/ve-app/main/main.component.ts @@ -1,20 +1,20 @@ -import 'angular-growl-v2' +import 'angular-growl-v2'; -import { StateService, Transition, TransitionService, UIRouter, UIRouterGlobals } from '@uirouter/angularjs' -import angular, { IComponentController, IHttpResponse } from 'angular' -import Rx from 'rx-lite' +import { StateService, Transition, TransitionService, UIRouter, UIRouterGlobals } from '@uirouter/angularjs'; +import angular, { IComponentController, IHttpResponse } from 'angular'; +import Rx from 'rx-lite'; -import { WorkingTimeModalResolveFn, WorkingTimeObject } from '@ve-app/main/modals/working-modal.component' -import { ApplicationService, RootScopeService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ApiService, AuthService, ElementService, HttpService, URLService } from '@ve-utils/mms-api-client' +import { WorkingTimeModalResolveFn, WorkingTimeObject } from '@ve-app/main/modals/working-modal.component'; +import { ApplicationService, RootScopeService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ApiService, AuthService, ElementService, HttpService, URLService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { VeConfig } from '@ve-types/config' -import { ParamsObject } from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { VeConfig } from '@ve-types/config'; +import { ParamsObject } from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; class MainController implements IComponentController { static $inject = [ @@ -40,27 +40,27 @@ class MainController implements IComponentController { 'RootScopeService', 'EditService', 'EventService', - ] + ]; //local - public subs: Rx.IDisposable[] - openEdits = {} - readonly veConfig: VeConfig + public subs: Rx.IDisposable[]; + openEdits = {}; + readonly veConfig: VeConfig; - private hidePanes: boolean = false - private closePanes: boolean = false - private hideRight: boolean = false - private closeRight: boolean = false - private hideLeft: boolean = false - private closeLeft: boolean = false - showManageRefs: boolean = false - showLogin: boolean = true - mmsWorkingTime: WorkingTimeObject - workingModalOpen = false + private hidePanes: boolean = false; + private closePanes: boolean = false; + private hideRight: boolean = false; + private closeRight: boolean = false; + private hideLeft: boolean = false; + private closeLeft: boolean = false; + showManageRefs: boolean = false; + showLogin: boolean = true; + mmsWorkingTime: WorkingTimeObject; + workingModalOpen = false; - readonly paneClosed: boolean = false + readonly paneClosed: boolean = false; - $uiRouterGlobals: UIRouterGlobals = this.$uiRouter.globals + $uiRouterGlobals: UIRouterGlobals = this.$uiRouter.globals; constructor( private $scope: angular.IScope, @@ -86,56 +86,56 @@ class MainController implements IComponentController { private editSvc: EditService, private eventSvc: EventService ) { - this.veConfig = window.__env + this.veConfig = window.__env; } $onInit(): void { - this.eventSvc.$init(this) - this.rootScopeSvc.init() + this.eventSvc.$init(this); + this.rootScopeSvc.init(); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VETITLE, (value: string) => { - this.$window.document.title = value + ' | View Editor' + this.$window.document.title = value + ' | View Editor'; }) - ) + ); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VESHOWLOGIN, (value: boolean) => { - this.showLogin = value + this.showLogin = value; }) - ) + ); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEHIDEPANES, (value: boolean) => { - this.hidePanes = value + this.hidePanes = value; }) - ) + ); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEHIDELEFT, (value: boolean) => { - this.hideLeft = value + this.hideLeft = value; if (value) { - this.closeLeft = true + this.closeLeft = true; } }) - ) + ); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEHIDERIGHT, (value: boolean) => { - this.hideRight = value + this.hideRight = value; if (value) { - this.closeRight = true + this.closeRight = true; } }) - ) + ); this.$window.addEventListener('beforeunload', (event) => { if (this.editSvc.openEdits() > 0) { - const message = 'You may have unsaved changes, are you sure you want to leave?' - event.returnValue = message - return message + const message = 'You may have unsaved changes, are you sure you want to leave?'; + event.returnValue = message; + return message; } - }) + }); this.hotkeys .bindTo(this.$scope) @@ -143,7 +143,7 @@ class MainController implements IComponentController { combo: 'alt+m', description: 'close all messages', callback: () => { - this.growlMessages.destroyAllMessages() + this.growlMessages.destroyAllMessages(); }, }) .add({ @@ -152,32 +152,32 @@ class MainController implements IComponentController { callback: () => { // TODO: Something here? }, - }) + }); this.subs.push( this.eventSvc.$on('mms.working', (response: IHttpResponse) => { - this.rootScopeSvc.veViewContentLoading(false) + this.rootScopeSvc.veViewContentLoading(false); if (this.workingModalOpen) { - return + return; } - this.mmsWorkingTime = response.data - this.workingModalOpen = true + this.mmsWorkingTime = response.data; + this.workingModalOpen = true; this.$uibModal .open({ component: 'workingModal', backdrop: true, resolve: { getWorkingTime: () => { - return this.mmsWorkingTime + return this.mmsWorkingTime; }, }, size: 'md', }) .result.finally(() => { - this.workingModalOpen = false - }) + this.workingModalOpen = false; + }); }) - ) + ); // this.subs.push( // this.eventSvc.$on('element.updated', (data: { element: ElementObject; continueEdit: boolean }) => { @@ -202,32 +202,32 @@ class MainController implements IComponentController { // ) this.$transitions.onStart({}, (trans) => { - this.rootScopeSvc.veViewContentLoading(true) - this.httpSvc.transformQueue() - this.rootScopeSvc.veStateChanging(true) - const from = trans.from().name - const to = trans.to().name + this.rootScopeSvc.veViewContentLoading(true); + this.httpSvc.transformQueue(); + this.rootScopeSvc.veStateChanging(true); + const from = trans.from().name; + const to = trans.to().name; if (from.split('.').length >= to.split('.').length) { - console.log(trans.router.viewService._pluginapi._activeViewConfigs()) + console.log(trans.router.viewService._pluginapi._activeViewConfigs()); //Code to prune inactive previous leaf configs //console.log( trans.router.viewService._pluginapi ._activeViewConfigs() .filter((vc) => { - return from === vc.viewDecl.$context.name + return from === vc.viewDecl.$context.name; }) .forEach((value) => { - trans.router.viewService.deactivateViewConfig(value) - }) - console.log(trans.router.viewService._pluginapi._activeViewConfigs()) + trans.router.viewService.deactivateViewConfig(value); + }); + console.log(trans.router.viewService._pluginapi._activeViewConfigs()); } - }) + }); this.$transitions.onError({}, (trans: Transition) => { - this.rootScopeSvc.veStateChanging(false) - this.rootScopeSvc.veViewContentLoading(false) + this.rootScopeSvc.veStateChanging(false); + this.rootScopeSvc.veViewContentLoading(false); //check if error is ticket error - const error: angular.IHttpResponse = trans.error().detail as angular.IHttpResponse + const error: angular.IHttpResponse = trans.error().detail as angular.IHttpResponse; if ( !error || error.status === 401 || @@ -237,44 +237,44 @@ class MainController implements IComponentController { error.config.url.indexOf('/authentication') !== -1) ) { //check if 404 if checking valid ticket - trans.abort() + trans.abort(); this.rootScopeSvc.veRedirect({ toState: trans.to(), toParams: trans.params(), - }) + }); return this.$state.target('main.login', { next: trans.$to().url, - }) + }); } if (this.veConfig.enableDebug) { this.growl.warning('Error: ' + trans.error().message, { ttl: 1000, - }) + }); } - }) + }); this.$transitions.onSuccess({}, (trans: Transition) => { - this.rootScopeSvc.veStateChanging(false) + this.rootScopeSvc.veStateChanging(false); if (this.$uiRouterGlobals.$current.name === 'main.share') { - this.rootScopeSvc.veHidePanes(true) - this.rootScopeSvc.veShowLogin(true) + this.rootScopeSvc.veHidePanes(true); + this.rootScopeSvc.veShowLogin(true); } else { - this.rootScopeSvc.veHidePanes(false) - this.rootScopeSvc.veShowLogin(false) + this.rootScopeSvc.veHidePanes(false); + this.rootScopeSvc.veShowLogin(false); } if ( this.rootScopeSvc.veRedirect() && this.$uiRouterGlobals.$current.name === this.rootScopeSvc.veRedirect().toState.name ) { - this.rootScopeSvc.veRedirect(null) + this.rootScopeSvc.veRedirect(null); } if (this.$state.includes('main.login')) { - this.rootScopeSvc.veHidePanes(true) - this.rootScopeSvc.veShowLogin(true) + this.rootScopeSvc.veHidePanes(true); + this.rootScopeSvc.veShowLogin(true); } if (this.$state.includes('main.project.refs')) { - this.rootScopeSvc.veHidePanes(true) + this.rootScopeSvc.veHidePanes(true); } // if (this.$state.includes('main.project.ref.portal')) { // this.rootScopeSvc.treeInitialSelection( @@ -316,19 +316,19 @@ class MainController implements IComponentController { // ) // } if (this.$state.includes('main.project.ref.view.present')) { - this.applicationSvc.getState().inDoc = true - this.applicationSvc.getState().currentDoc = (trans.params() as ParamsObject).documentId + this.applicationSvc.getState().inDoc = true; + this.applicationSvc.getState().currentDoc = (trans.params() as ParamsObject).documentId; this.applicationSvc.getState().fullDoc = !!this.$state.includes( 'main.project.ref.view.present.document' - ) + ); } else { - this.applicationSvc.getState().inDoc = false - this.applicationSvc.getState().fullDoc = false + this.applicationSvc.getState().inDoc = false; + this.applicationSvc.getState().fullDoc = false; } - this.rootScopeSvc.veViewContentLoading(false) + this.rootScopeSvc.veViewContentLoading(false); if (this.$state.includes('main.project.ref.view.present') && !(trans.params() as ParamsObject).display) { - const display = trans.$to().name.split('.')[trans.$to().name.split('.').length] - void this.$state.go(trans.$to().name, { display }) + const display = trans.$to().name.split('.')[trans.$to().name.split('.').length]; + void this.$state.go(trans.$to().name, { display }); } if ( this.$state.includes('main.project.ref') && @@ -338,23 +338,23 @@ class MainController implements IComponentController { ) { void this.$timeout( () => { - this.eventSvc.$broadcast('left-pane.toggle') + this.eventSvc.$broadcast('left-pane.toggle'); }, 1, false - ) + ); void this.$timeout( () => { - this.eventSvc.$broadcast('left-pane.toggle') + this.eventSvc.$broadcast('left-pane.toggle'); }, 100, false - ) + ); } - }) + }); if (this.$uiRouterGlobals.$current.name == 'main') { - void this.$state.go('main.login') + void this.$state.go('main.login'); } } } @@ -402,6 +402,6 @@ const MainComponent: VeComponentOptions = { `, controller: MainController, -} +}; -veApp.component(MainComponent.selector, MainComponent) +veApp.component(MainComponent.selector, MainComponent); diff --git a/src/ve-app/main/modals/about-modal.component.ts b/src/ve-app/main/modals/about-modal.component.ts index 54b7bfc2d..fd54be0f8 100644 --- a/src/ve-app/main/modals/about-modal.component.ts +++ b/src/ve-app/main/modals/about-modal.component.ts @@ -1,11 +1,11 @@ -import { IComponentController } from 'angular' +import { IComponentController } from 'angular'; -import { ApiService } from '@ve-utils/mms-api-client' +import { ApiService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { VeModalInstanceService } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { VeModalInstanceService } from '@ve-types/view-editor'; const AboutModalComponent: VeComponentOptions = { selector: 'aboutModal', @@ -28,36 +28,36 @@ const AboutModalComponent: VeComponentOptions = { resolve: '@', }, controller: class AboutModalController implements IComponentController { - static $inject = ['ApiService'] + static $inject = ['ApiService']; //bindings - public modalInstance: VeModalInstanceService - public resolve + public modalInstance: VeModalInstanceService; + public resolve; //local - public veV - public mmsV + public veV; + public mmsV; constructor(private apiSvc: ApiService) {} $onInit(): void { - this.veV = window.__env.version ? window.__env.version : 'No Version Specified' - this.mmsV = 'Loading...' + this.veV = window.__env.version ? window.__env.version : 'No Version Specified'; + this.mmsV = 'Loading...'; this.apiSvc.getMmsVersion().then( (data) => { - this.mmsV = data + this.mmsV = data; }, (reason) => { - this.mmsV = 'Could not retrieve due to failure: ' + reason.message + this.mmsV = 'Could not retrieve due to failure: ' + reason.message; } - ) + ); } cancel(): void { - this.modalInstance.dismiss() + this.modalInstance.dismiss(); } }, -} +}; -veApp.component(AboutModalComponent.selector, AboutModalComponent) +veApp.component(AboutModalComponent.selector, AboutModalComponent); diff --git a/src/ve-app/main/modals/index.ts b/src/ve-app/main/modals/index.ts index a15d73c24..c53032b83 100644 --- a/src/ve-app/main/modals/index.ts +++ b/src/ve-app/main/modals/index.ts @@ -1,7 +1,7 @@ //Modals -import './about-modal.component' -import './login-modal.component' -import './print-confirm-modal.component' -import './select-modal.component' -import './table-export-modal.component' -import './working-modal.component' +import './about-modal.component'; +import './login-modal.component'; +import './print-confirm-modal.component'; +import './select-modal.component'; +import './table-export-modal.component'; +import './working-modal.component'; diff --git a/src/ve-app/main/modals/login-modal.component.ts b/src/ve-app/main/modals/login-modal.component.ts index dfd59a76c..40df7e039 100644 --- a/src/ve-app/main/modals/login-modal.component.ts +++ b/src/ve-app/main/modals/login-modal.component.ts @@ -1,30 +1,30 @@ -import { StateService, UIRouterGlobals } from '@uirouter/angularjs' -import angular from 'angular' +import { StateService, UIRouterGlobals } from '@uirouter/angularjs'; +import angular from 'angular'; -import { AuthService } from '@ve-utils/mms-api-client' -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { AuthService } from '@ve-utils/mms-api-client'; +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { AuthRequest } from '@ve-types/mms' -import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { AuthRequest } from '@ve-types/mms'; +import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; export interface LoginModalResolveFn extends VeModalResolveFn { - continue(): boolean + continue(): boolean; } export interface LoginModalResolve extends VeModalResolve { - continue: boolean + continue: boolean; } class LoginModalController extends VeModalControllerImpl implements VeModalController { - static $inject = ['$state', '$uiRouterGlobals', 'growl', 'AuthService'] + static $inject = ['$state', '$uiRouterGlobals', 'growl', 'AuthService']; public credentials = { username: '', password: '', - } - spin = false + }; + spin = false; constructor( private $state: StateService, @@ -32,14 +32,14 @@ class LoginModalController extends VeModalControllerImpl { - this.growl.success('Logged in') + this.growl.success('Logged in'); // Check if user had changes queued before refreshing page data // add edits to cache // const edits = this.autosaveSvc.getAll() @@ -51,25 +51,25 @@ class LoginModalController extends VeModalControllerImpl { - this.modalInstance.close(true) + this.modalInstance.close(true); }, () => { - this.growl.error('Redirect error; Please reload the page') + this.growl.error('Redirect error; Please reload the page'); } - ) + ); } }, (reason) => { - this.spin = false - this.credentials.password = '' - this.growl.error(reason.message) + this.spin = false; + this.credentials.password = ''; + this.growl.error(reason.message); } - ) + ); } cancel = (): void => { - this.modalInstance.dismiss(false) - } + this.modalInstance.dismiss(false); + }; } const LoginModalComponent: VeModalComponent = { @@ -94,6 +94,6 @@ const LoginModalComponent: VeModalComponent = { resolve: '<', }, controller: LoginModalController, -} +}; -veApp.component(LoginModalComponent.selector, LoginModalComponent) +veApp.component(LoginModalComponent.selector, LoginModalComponent); diff --git a/src/ve-app/main/modals/print-confirm-modal.component.ts b/src/ve-app/main/modals/print-confirm-modal.component.ts index 98a3f47f3..16a61c28c 100644 --- a/src/ve-app/main/modals/print-confirm-modal.component.ts +++ b/src/ve-app/main/modals/print-confirm-modal.component.ts @@ -1,40 +1,40 @@ -import angular from 'angular' -import _ from 'lodash' +import angular from 'angular'; +import _ from 'lodash'; -import { AppUtilsService, DocumentStructure } from '@ve-app/main/services' -import { UtilsService } from '@ve-utils/application' -import { EditService } from '@ve-utils/core' -import { ElementService, ViewService, DocumentMetadata, ProjectService } from '@ve-utils/mms-api-client' -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { AppUtilsService, DocumentStructure } from '@ve-app/main/services'; +import { UtilsService } from '@ve-utils/application'; +import { EditService } from '@ve-utils/core'; +import { ElementService, ViewService, DocumentMetadata, ProjectService } from '@ve-utils/mms-api-client'; +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VePromise } from '@ve-types/angular' -import { CommitObject, CommitResponse, RefObject, ViewObject } from '@ve-types/mms' -import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { VePromise } from '@ve-types/angular'; +import { CommitObject, CommitResponse, RefObject, ViewObject } from '@ve-types/mms'; +import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; interface PrintModalResolve extends VeModalResolve { - print: JQLite - refOb: RefObject - viewOrDocOb: ViewObject - isDoc: boolean - mode: number + print: JQLite; + refOb: RefObject; + viewOrDocOb: ViewObject; + isDoc: boolean; + mode: number; } export interface PrintModalResolveFn extends VeModalResolveFn { - print(): JQLite - refOb(): RefObject - viewOrDocOb(): ViewObject - isDoc(): boolean - mode(): number + print(): JQLite; + refOb(): RefObject; + viewOrDocOb(): ViewObject; + isDoc(): boolean; + mode(): number; } export interface PrintConfirmResult { - status: string - customization?: boolean - meta?: DocumentMetadata - model?: { genTotf: boolean; landscape: boolean; htmlTotf: boolean } - customCSS?: string + status: string; + customization?: boolean; + meta?: DocumentMetadata; + model?: { genTotf: boolean; landscape: boolean; htmlTotf: boolean }; + customCSS?: string; } class PrintConfirmModalController extends VeModalControllerImpl implements VeModalController { @@ -48,29 +48,29 @@ class PrintConfirmModalController extends VeModalControllerImpl 0) { - this.hasError = true + this.hasError = true; } if (this.isDoc) { // If _printCss, use to set doc css for export/print - this.customizeDoc.useCustomStyle = false + this.customizeDoc.useCustomStyle = false; if (this.viewOrDocOb._printCss) { // If _printCss, show tab for custom css - this.customizeDoc.useCustomStyle = true - this.customizeDoc.customCSS = this.viewOrDocOb._printCss + this.customizeDoc.useCustomStyle = true; + this.customizeDoc.customCSS = this.viewOrDocOb._printCss; } else { this.customizeDoc.customCSS = this.utilsSvc.getPrintCss(false, false, { numberingDepth: 0, numberingSeparator: '.', - }) + }); } // Get/Set document header/footer for PDF generation @@ -125,7 +125,7 @@ class PrintConfirmModalController extends VeModalControllerImpl { - let displayTime = 'latest' - let promise: VePromise + let displayTime = 'latest'; + let promise: VePromise; if (this.refOb.parentCommitId) { promise = this.projectSvc.getCommit( this.refOb._projectId, this.refOb.id, this.refOb.parentCommitId - ) + ); } else { - promise = this.projectSvc.getCommits(this.refOb.id, this.refOb._projectId, null, 1) + promise = this.projectSvc.getCommits(this.refOb.id, this.refOb._projectId, null, 1); } promise .then( (result) => { - let commit: CommitObject + let commit: CommitObject; if (Array.isArray(result)) { - commit = result[0] + commit = result[0]; } else { - commit = result + commit = result; } - displayTime = this.$filter('date')(commit._created, 'M/d/yy h:mm a') + displayTime = this.$filter('date')(commit._created, 'M/d/yy h:mm a'); }, (reason) => { this.growl.error( 'Warning: RefOb parent commit does not exist; Defaulting to current time' - ) + ); } ) .finally(() => { @@ -176,16 +176,16 @@ class PrintConfirmModalController extends VeModalControllerImpl { this.meta['top-left'] = @@ -193,64 +193,64 @@ class PrintConfirmModalController extends VeModalControllerImpl { - this.elementSaving = false - this.growl.success('Save Successful') + this.elementSaving = false; + this.growl.success('Save Successful'); }, () => { - this.elementSaving = false - this.growl.warning('Save was not complete. Please try again.') + this.elementSaving = false; + this.growl.warning('Save was not complete. Please try again.'); } - ) + ); } public preview(): void { if (!this.previewResult) { - this.previewResult = this.appUtilsSvc.printOrGenerate(this.viewOrDocOb, 3, true, true, false) - this.previewResult.tof = this.previewResult.tof + this.previewResult.toe + this.previewResult = this.appUtilsSvc.printOrGenerate(this.viewOrDocOb, 3, true, true, false); + this.previewResult.tof = this.previewResult.tof + this.previewResult.toe; } - const result = this.previewResult + const result = this.previewResult; const htmlArr = [ '' + this.viewOrDocOb.name + '', result.cover, - ] - if (result.toc != '') htmlArr.push(result.toc) - if (result.tot != '' && this.model.genTotf) htmlArr.push(result.tot) - if (result.tof != '' && this.model.genTotf) htmlArr.push(result.tof) - htmlArr.push(result.contents, '') - const htmlString = htmlArr.join('') + ]; + if (result.toc != '') htmlArr.push(result.toc); + if (result.tot != '' && this.model.genTotf) htmlArr.push(result.tot); + if (result.tof != '' && this.model.genTotf) htmlArr.push(result.tof); + htmlArr.push(result.contents, ''); + const htmlString = htmlArr.join(''); const popupWin: Window | null = this.$window.open( 'about:blank', '_blank', 'width=800,height=600,scrollbars=1,status=1,toolbar=1,menubar=1' - ) + ); if (popupWin) { - popupWin.document.open() - popupWin.document.write(htmlString) - popupWin.document.close() + popupWin.document.open(); + popupWin.document.write(htmlString); + popupWin.document.close(); } else { - this.growl.error('Popup Window Failed to open. Allow popups and try again') + this.growl.error('Popup Window Failed to open. Allow popups and try again'); } } public print(): void { @@ -260,14 +260,14 @@ class PrintConfirmModalController extends VeModalControllerImpl - private resolve: SelectModalResolve + public modalInstance: VeModalInstanceService; + private resolve: SelectModalResolve; //local - public spin = false - public orgId: string - public projectId: string = '' - public selectedOrg: string - public selectedProject: string - public orgs: OrgObject[] - public projects: ProjectObject[] - protected orgSpin: boolean - protected projSpin: boolean + public spin = false; + public orgId: string; + public projectId: string = ''; + public selectedOrg: string; + public selectedProject: string; + public orgs: OrgObject[]; + public projects: ProjectObject[]; + protected orgSpin: boolean; + protected projSpin: boolean; constructor(private $scope: angular.IScope, private $state: StateService, private projectSvc: ProjectService) {} $onInit(): void { - this.orgs = this.resolve.mmsOrgs - this.projects = this.resolve.mmsProjects + this.orgs = this.resolve.mmsOrgs; + this.projects = this.resolve.mmsProjects; - this.orgId = this.resolve.mmsOrg.id - this.projectId = this.resolve.mmsProject.id + this.orgId = this.resolve.mmsOrg.id; + this.projectId = this.resolve.mmsProject.id; - this.selectedOrg = this.resolve.mmsOrg.name - this.selectedProject = this.resolve.mmsProject.name + this.selectedOrg = this.resolve.mmsOrg.name; + this.selectedProject = this.resolve.mmsProject.name; } public selectOrg = (org: OrgObject): void => { if (org) { - this.orgId = org.id - this.selectedOrg = org.name - this.selectedProject = '' - this.projSpin = true - this.refreshProjects() + this.orgId = org.id; + this.selectedOrg = org.name; + this.selectedProject = ''; + this.projSpin = true; + this.refreshProjects(); } - } + }; public selectProject = (project: ProjectObject): void => { if (project) { - this.projectId = project.id - this.selectedProject = project.name + this.projectId = project.id; + this.selectedProject = project.name; } - } + }; public continue = (): void => { if (this.orgId && this.projectId) { // was the same project selected? cancel... if (this.resolve.mmsProject.orgId === this.orgId && this.resolve.mmsProject.id === this.projectId) { - this.cancel() + this.cancel(); } else { - this.spin = true + this.spin = true; this.$state .go('main.project.ref.portal', { orgId: this.orgId, @@ -91,53 +91,53 @@ class SelectModalController implements VeModalController { keywords: undefined, }) .finally(() => { - this.spin = false - this.modalInstance.close() - }) + this.spin = false; + this.modalInstance.close(); + }); } } - } + }; public refreshOrgs = (): void => { - this.orgSpin = true - this.orgs.length = 0 + this.orgSpin = true; + this.orgs.length = 0; this.projectSvc .getOrgs(true) .then((data) => { - this.orgs.push(...data) + this.orgs.push(...data); }) .finally(() => { - this.orgSpin = false - }) - } + this.orgSpin = false; + }); + }; public refreshProjects = (): void => { - this.projSpin = true - this.projects.length = 0 + this.projSpin = true; + this.projects.length = 0; this.projectSvc .getProjects(this.orgId, true) .then((data) => { - this.projects.push(...data) + this.projects.push(...data); if ( data && data.length > 0 && this.projects.filter((p) => { - return p.id === this.projectId + return p.id === this.projectId; }).length === 0 ) { - this.selectProject(data[0]) + this.selectProject(data[0]); } else { //no projects } }) .finally(() => { - this.projSpin = false - }) - } + this.projSpin = false; + }); + }; public cancel = (): void => { - this.modalInstance.dismiss() - } + this.modalInstance.dismiss(); + }; } const SelectModalComponent: VeModalComponent = { @@ -204,6 +204,6 @@ const SelectModalComponent: VeModalComponent = { resolve: '<', }, controller: SelectModalController, -} +}; -veApp.component(SelectModalComponent.selector, SelectModalComponent) +veApp.component(SelectModalComponent.selector, SelectModalComponent); diff --git a/src/ve-app/main/modals/table-export-modal.component.ts b/src/ve-app/main/modals/table-export-modal.component.ts index 0d31bf115..8e98b6f8e 100644 --- a/src/ve-app/main/modals/table-export-modal.component.ts +++ b/src/ve-app/main/modals/table-export-modal.component.ts @@ -1,34 +1,34 @@ -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; interface TableExportModalResolve extends VeModalResolve { - type: string + type: string; } export interface TableExportModalResolveFn extends VeModalResolveFn { - type(): string + type(): string; } class TableExportModalController extends VeModalControllerImpl implements VeModalController { //bindings - resolve: TableExportModalResolve + resolve: TableExportModalResolve; //local - type + type; $onInit(): void { - this.type = this.resolve.type + this.type = this.resolve.type; } public export(): void { - this.modalInstance.close('export') + this.modalInstance.close('export'); } public cancel(): void { - this.modalInstance.dismiss() + this.modalInstance.dismiss(); } } @@ -67,6 +67,6 @@ const TableExportModalComponent: VeComponentOptions = { resolve: '<', }, controller: TableExportModalController, -} +}; -veApp.component(TableExportModalComponent.selector, TableExportModalComponent) +veApp.component(TableExportModalComponent.selector, TableExportModalComponent); diff --git a/src/ve-app/main/modals/working-modal.component.ts b/src/ve-app/main/modals/working-modal.component.ts index 57418a4d3..30b2e54de 100644 --- a/src/ve-app/main/modals/working-modal.component.ts +++ b/src/ve-app/main/modals/working-modal.component.ts @@ -1,20 +1,20 @@ -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; export interface WorkingTimeObject { - startTime: Date + startTime: Date; } export interface WorkingTimeModalResolveFn extends VeModalResolveFn { - getWorkingTime(): WorkingTimeObject + getWorkingTime(): WorkingTimeObject; } interface WorkingTimeModalResolve extends VeModalResolve { - getWorkingTime: WorkingTimeObject + getWorkingTime: WorkingTimeObject; } const WorkingModalComponent: VeComponentOptions = { @@ -33,12 +33,12 @@ const WorkingModalComponent: VeComponentOptions = { extends VeModalControllerImpl implements VeModalController { - public workingTime + public workingTime; $onInit(): void { - this.workingTime = this.resolve.getWorkingTime + this.workingTime = this.resolve.getWorkingTime; } }, -} +}; -veApp.component(WorkingModalComponent.selector, WorkingModalComponent) +veApp.component(WorkingModalComponent.selector, WorkingModalComponent); diff --git a/src/ve-app/main/services/AppUtils.service.ts b/src/ve-app/main/services/AppUtils.service.ts index 774b40c3d..b14cc1266 100644 --- a/src/ve-app/main/services/AppUtils.service.ts +++ b/src/ve-app/main/services/AppUtils.service.ts @@ -1,27 +1,27 @@ -import { StateService } from '@uirouter/angularjs' -import angular from 'angular' +import { StateService } from '@uirouter/angularjs'; +import angular from 'angular'; -import { PrintConfirmResult, PrintModalResolveFn } from '@ve-app/main/modals/print-confirm-modal.component' -import { TableExportModalResolveFn } from '@ve-app/main/modals/table-export-modal.component' -import { Table2CSVService } from '@ve-components/presentations/services/Table2CSV.service' -import { TreeService } from '@ve-components/trees' -import { UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ElementService, ViewService } from '@ve-utils/mms-api-client' +import { PrintConfirmResult, PrintModalResolveFn } from '@ve-app/main/modals/print-confirm-modal.component'; +import { TableExportModalResolveFn } from '@ve-app/main/modals/table-export-modal.component'; +import { Table2CSVService } from '@ve-components/presentations/services/Table2CSV.service'; +import { TreeService } from '@ve-components/trees'; +import { UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ElementService, ViewService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VePromise, VeQService } from '@ve-types/angular' -import { RefObject, ViewObject } from '@ve-types/mms' -import { VeModalService, VeModalSettings } from '@ve-types/view-editor' +import { VePromise, VeQService } from '@ve-types/angular'; +import { RefObject, ViewObject } from '@ve-types/mms'; +import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; export interface DocumentStructure { - cover: string - contents: string - tot: string - toc: string - tof: string - toe: string + cover: string; + contents: string; + tot: string; + toc: string; + tof: string; + toe: string; } /** @@ -44,7 +44,7 @@ export class AppUtilsService implements angular.Injectable { 'UtilsService', 'EventService', 'TreeService', - ] + ]; constructor( private $q: VeQService, private $uibModal: VeModalService, @@ -67,12 +67,12 @@ export class AppUtilsService implements angular.Injectable { component: 'tableExport', resolve: { type: () => { - return isDoc ? 'DOCUMENT' : 'VIEW' + return isDoc ? 'DOCUMENT' : 'VIEW'; }, }, backdrop: 'static', keyboard: false, - }) + }); const string = ` @@ -84,16 +84,16 @@ var blob = new Blob(["\\uFEFF" + csvString], { }); if (window.navigator.msSaveOrOpenBlob) { - navigator.msSaveBlob(blob,\'TableData.csv\'); -} else { + navigator.msSaveBlob(blob,'TableData.csv'); +} else { - var downloadContainer = $(\'
    \'); + var downloadContainer = $('
    '); var downloadLink = $(downloadContainer.children()[0]); - downloadLink.attr(\'href\', window.URL.createObjectURL(blob)); - downloadLink.attr(\'download\', \'TableData.csv\'); - downloadLink.attr(\'target\', \'_blank\'); + downloadLink.attr('href', window.URL.createObjectURL(blob)); + downloadLink.attr('download', 'TableData.csv'); + downloadLink.attr('target', '_blank'); - $(window.document).find(\'body\').append(downloadContainer); + $(window.document).find('body').append(downloadContainer); /* this.$timeout(() => { */ downloadLink[0].click(); downloadLink.remove(); @@ -101,51 +101,51 @@ if (window.navigator.msSaveOrOpenBlob) { } } -` +`; void modalInstance.result.then((data) => { if (data === 'export') { - const tableCSV: { caption: string; val: string }[] = [] + const tableCSV: { caption: string; val: string }[] = []; // Grab all tables and run export to csv fnc tables.find('table').each((index: number, elt: HTMLTableElement) => { const tableObj = { caption: 'no caption', val: Table2CSVService.export(angular.element(elt), { delivery: 'value' }), - } + }; if (elt.caption) { - tableObj.caption = elt.caption.innerHTML + tableObj.caption = elt.caption.innerHTML; } - tableCSV.push(tableObj) - }) + tableCSV.push(tableObj); + }); const exportPopup = (data: string): void => { - const generator = window.open('', 'csv', 'height=600,width=800,scrollbars=1') + const generator = window.open('', 'csv', 'height=600,width=800,scrollbars=1'); if (generator) { - generator.document.write('Tables to CSV') - generator.document.write('') - generator.document.write(data) - generator.document.write('') - generator.document.close() + generator.document.write('Tables to CSV'); + generator.document.write(''); + generator.document.write(data); + generator.document.write(''); + generator.document.close(); } else { - this.growl.error('Popup Window Failed to open. Allow popups and try again') + this.growl.error('Popup Window Failed to open. Allow popups and try again'); } //return true - } + }; // generate text area content for popup - let genTextArea = string - let num = 0 + let genTextArea = string; + let num = 0; tableCSV.forEach((element: { caption: string; val: string }) => { genTextArea += `

    ${element.caption}

    -` - num++ - }) - exportPopup(genTextArea) +`; + num++; + }); + exportPopup(genTextArea); } - }) - } + }); + }; /** * @name veApp.AppUtilsService#printModal @@ -167,30 +167,30 @@ Save CSV isDoc: boolean, mode: number ): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); const settings: VeModalSettings = { component: 'printConfirmModal', resolve: { print: () => { - return printElement + return printElement; }, refOb: () => { - return refOb + return refOb; }, viewOrDocOb: () => { - return viewOrDocOb + return viewOrDocOb; }, isDoc: () => { - return isDoc + return isDoc; }, mode: () => { - return mode + return mode; }, }, backdrop: 'static', keyboard: false, - } - const modalInstance = this.$uibModal.open(settings) + }; + const modalInstance = this.$uibModal.open(settings); /* choice: ['ok', $scope.model.genTotf, $scope.model.htmlTotf, $scope.model.landscape, $scope.meta] [0] 'ok' - modal button to confirm print/export @@ -209,20 +209,20 @@ Save CSV isDoc, choice.model.genTotf, choice.model.htmlTotf - ) + ); const css = choice.customization ? choice.customCSS - : this.utilsSvc.getPrintCss(choice.model.htmlTotf, choice.model.landscape, choice.meta) - result.toe = choice[2] ? '' : result.toe + : this.utilsSvc.getPrintCss(choice.model.htmlTotf, choice.model.landscape, choice.meta); + result.toe = choice[2] ? '' : result.toe; if (mode === 1) { const popupWin = this.$window.open( 'about:blank', '_blank', 'width=800,height=600,scrollbars=1,status=1,toolbar=1,menubar=1' - ) + ); if (popupWin) { - const popup: Window = popupWin - popup.document.open() + const popup: Window = popupWin; + popup.document.open(); popup.document.write(` @@ -238,33 +238,33 @@ Save CSV ${result.contents} -`) - popup.document.close() +`); + popup.document.close(); void this.$timeout( () => { - popup.print() + popup.print(); }, 1000, false - ) + ); } else { - this.growl.error('Popup Window Failed to open. Allow popups and try again') + this.growl.error('Popup Window Failed to open. Allow popups and try again'); } } else { - result.tof = choice[1] ? result.tof + result.toe : '' - result.tot = choice[1] ? result.tot : '' + result.tof = choice[1] ? result.tof + result.toe : ''; + result.tot = choice[1] ? result.tot : ''; const htmlArr = [ '' + viewOrDocOb.name + '', result.cover, - ] - if (result.toc != '') htmlArr.push(result.toc) - if (result.tot != '') htmlArr.push(result.tot) - if (result.tof != '') htmlArr.push(result.tof) - htmlArr.push(result.contents, '') - const htmlString = htmlArr.join('') - this.growl.info('Generating, please wait...', { ttl: -1 }) + ]; + if (result.toc != '') htmlArr.push(result.toc); + if (result.tot != '') htmlArr.push(result.tot); + if (result.tof != '') htmlArr.push(result.tof); + htmlArr.push(result.contents, ''); + const htmlString = htmlArr.join(''); + this.growl.info('Generating, please wait...', { ttl: -1 }); this.utilsSvc .exportHtmlAs(mode, { htmlString: htmlString, @@ -275,24 +275,24 @@ Save CSV }) .then( () => { - this.growl.success('File Downloaded', { ttl: -1 }) - deferred.resolve() + this.growl.success('File Downloaded', { ttl: -1 }); + deferred.resolve(); }, (reason) => { - this.growl.error('Generation Failed') - deferred.reject(reason) + this.growl.error('Generation Failed'); + deferred.reject(reason); } - ) + ); } } else { void this.$state.go('main.project.ref.view.present.document', { display: 'document', keywords: undefined, - }) - deferred.reject({ message: 'User Cancelled' }) + }); + deferred.reject({ message: 'User Cancelled' }); } - }) - return deferred.promise + }); + return deferred.promise; } /** @@ -325,25 +325,25 @@ Save CSV genTotf: boolean, htmlTotf: boolean ): DocumentStructure => { - let printContents = '' - let printElementCopy = angular.element('#print-div') + let printContents = ''; + let printElementCopy = angular.element('#print-div'); // Conversion of canvas to its dataUrl must be done before "clone", because "clone" doesn't preserve // canvas' content - const mapping = this._storeTomsawyerDiagramAsImg(printElementCopy) - printElementCopy = printElementCopy.clone() - this._replaceMmsTsDiagramWithImg(printElementCopy, mapping) + const mapping = this._storeTomsawyerDiagramAsImg(printElementCopy); + printElementCopy = printElementCopy.clone(); + this._replaceMmsTsDiagramWithImg(printElementCopy, mapping); - const hostname = this.$location.host() - const port = this.$location.port() - const protocol = this.$location.protocol() - const absurl = this.$location.absUrl() - const prefix = protocol + ':// hostname' + (port == 80 || port == 443 ? '' : `:${port}`) - const mmsIndex = absurl.indexOf('index.html') - let toc = this.utilsSvc.makeHtmlTOC(this.treeSvc.getTreeData()[0]) + const hostname = this.$location.host(); + const port = this.$location.port(); + const protocol = this.$location.protocol(); + const absurl = this.$location.absUrl(); + const prefix = protocol + ':// hostname' + (port == 80 || port == 443 ? '' : `:${port}`); + const mmsIndex = absurl.indexOf('index.html'); + let toc = this.utilsSvc.makeHtmlTOC(this.treeSvc.getTreeData()[0]); // Conver to proper links for word/pdf - this.utilsSvc.convertViewLinks(printElementCopy) + this.utilsSvc.convertViewLinks(printElementCopy); // Get correct table/image numbering based on doc hierarchy const tableAndFigTOC = this.utilsSvc.makeTablesAndFiguresTOC( @@ -351,79 +351,79 @@ Save CSV printElementCopy, false, htmlTotf - ) - let tof = tableAndFigTOC.figures - let tot = tableAndFigTOC.tables - let toe = tableAndFigTOC.equations + ); + let tof = tableAndFigTOC.figures; + let tot = tableAndFigTOC.tables; + let toe = tableAndFigTOC.equations; // Customize TOC based on user choice if (!isDoc) { - toc = tof = tot = toe = '' + toc = tof = tot = toe = ''; } if (!genTotf) { - tof = tot = toe = '' + tof = tot = toe = ''; } angular .element(printElementCopy) .find('a') .attr('href', (index, old) => { - if (!old) return old - if (old.indexOf('/') === 0) return prefix + old - if (old.indexOf('../../') === 0) return prefix + old.substring(5) - if (old.indexOf('../') === 0) return prefix + '/alfresco' + old.substring(2) - if (old.indexOf('mms.html') === 0) return absurl.substring(0, mmsIndex) + old - return old - }) + if (!old) return old; + if (old.indexOf('/') === 0) return prefix + old; + if (old.indexOf('../../') === 0) return prefix + old.substring(5); + if (old.indexOf('../') === 0) return prefix + '/alfresco' + old.substring(2); + if (old.indexOf('mms.html') === 0) return absurl.substring(0, mmsIndex) + old; + return old; + }); // Remove comments, table features, and all elements with classes: ve-error, no-print, ng-hide - printElementCopy.find('transclude-com').remove() - printElementCopy.find('style').remove() //prevent user inserted styles from interfering - printElementCopy.find('div.tableSearch').remove() + printElementCopy.find('transclude-com').remove(); + printElementCopy.find('style').remove(); //prevent user inserted styles from interfering + printElementCopy.find('div.tableSearch').remove(); //printElementCopy.find('.ve-error').html('error'); - printElementCopy.find('.no-print').remove() - printElementCopy.find('.ng-hide').remove() + printElementCopy.find('.no-print').remove(); + printElementCopy.find('.ng-hide').remove(); // word doesn't support svg only png. if (mode === 2) { - printElementCopy.find('.mms-svg').remove() + printElementCopy.find('.mms-svg').remove(); } else { - printElementCopy.find('.mms-png').remove() + printElementCopy.find('.mms-png').remove(); } // Remove all empty paragraphs - printElementCopy.find('p:empty').remove() + printElementCopy.find('p:empty').remove(); printElementCopy.find('p').each((index, element) => { - const $this = $(element) + const $this = $(element); if ($this.html().replace(/\s| /g, '').length === 0) { - $this.remove() + $this.remove(); } - }) - printElementCopy.find('[width]').not('img').not('.ve-fixed-width').removeAttr('width') + }); + printElementCopy.find('[width]').not('img').not('.ve-fixed-width').removeAttr('width'); printElementCopy .find('[style]') .not('hr') .each((index, element) => { - element.style.removeProperty('font-size') - element.style.removeProperty('width') - element.style.removeProperty('min-width') - element.style.removeProperty('height') + element.style.removeProperty('font-size'); + element.style.removeProperty('width'); + element.style.removeProperty('min-width'); + element.style.removeProperty('height'); //remove frozen headers and column - element.style.removeProperty('transform') - element.style.removeProperty('will-change') - }) - printElementCopy.find('.math').remove() //this won't work in chrome for popups since chrome can't display mathml - printElementCopy.find('script').remove() + element.style.removeProperty('transform'); + element.style.removeProperty('will-change'); + }); + printElementCopy.find('.math').remove(); //this won't work in chrome for popups since chrome can't display mathml + printElementCopy.find('script').remove(); //printElementCopy.find('.MJX_Assistive_MathML').remove(); //pdf generation need mathml version // Get doc cover page by doc ID - let coverHtml = '' + let coverHtml = ''; if (isDoc) { - const cover = printElementCopy.find("view[mms-element-id='" + viewOrDocOb.id + "']") - cover.remove() + const cover = printElementCopy.find("view[mms-element-id='" + viewOrDocOb.id + "']"); + cover.remove(); // Add class to style cover page - cover.addClass('ve-cover-page') - coverHtml = cover[0].outerHTML + cover.addClass('ve-cover-page'); + coverHtml = cover[0].outerHTML; } - printContents = printElementCopy[0].outerHTML + printContents = printElementCopy[0].outerHTML; return { cover: coverHtml, @@ -432,31 +432,31 @@ Save CSV tof: tof, tot: tot, toe: toe, - } - } + }; + }; /** Store all tomsawyer diagram(canvas) as an img element **/ private _storeTomsawyerDiagramAsImg(originalDom: JQuery): JQuery[] { - const mapping: JQuery[] = [] + const mapping: JQuery[] = []; originalDom.find('mms-ts-diagram').each((index, element) => { - const tsDom = $(element) - const canvas = tsDom.find('canvas')[0] + const tsDom = $(element); + const canvas = tsDom.find('canvas')[0]; if (canvas) { - const imgElement = $('') - imgElement.attr({ src: canvas.toDataURL(), width: '100%' }) - mapping[index] = imgElement + const imgElement = $(''); + imgElement.attr({ src: canvas.toDataURL(), width: '100%' }); + mapping[index] = imgElement; } - }) - return mapping + }); + return mapping; } /** Replace all mms-ts-diagram elements with their corresponding img elements **/ private _replaceMmsTsDiagramWithImg(element: JQuery, mapping: JQuery[]): void { element.find('mms-ts-diagram').each((index) => { - const imgDom = mapping[index] - $(this).replaceWith(imgDom) - }) + const imgDom = mapping[index]; + $(this).replaceWith(imgDom); + }); } } -veApp.service('AppUtilsService', AppUtilsService) +veApp.service('AppUtilsService', AppUtilsService); diff --git a/src/ve-app/main/services/FullDocument.service.ts b/src/ve-app/main/services/FullDocument.service.ts index b247b0f1a..d1fbdecc7 100644 --- a/src/ve-app/main/services/FullDocument.service.ts +++ b/src/ve-app/main/services/FullDocument.service.ts @@ -1,19 +1,19 @@ -import angular from 'angular' -import _ from 'lodash' +import angular from 'angular'; +import _ from 'lodash'; -import { ViewData } from '@ve-utils/mms-api-client' +import { ViewData } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { TreeBranch } from '@ve-types/tree' +import { TreeBranch } from '@ve-types/tree'; export class FullDocumentApi { - public viewsBuffer: ViewData[] = [] - public views: ViewData[] = [] + public viewsBuffer: ViewData[] = []; + public views: ViewData[] = []; - private _isLoadingRemaingViews: boolean = false - _isFullDocFullyLoaded: boolean = false - _loadingRemainingViewsMessage: angular.growl.IGrowlMessage + private _isLoadingRemaingViews: boolean = false; + _isFullDocFullyLoaded: boolean = false; + _loadingRemainingViewsMessage: angular.growl.IGrowlMessage; constructor( private $timeout: angular.ITimeoutService, @@ -23,177 +23,177 @@ export class FullDocumentApi { ) {} public handleClickOnBranch = (viewId: string, callback: () => void): boolean => { - const isViewLoadedBefore = this._loadViewsUntilViewWith(viewId) // load some views if necessary + const isViewLoadedBefore = this._loadViewsUntilViewWith(viewId); // load some views if necessary if (isViewLoadedBefore) { - callback() + callback(); } else { - const message = this.growl.info('Loading more views!', { ttl: -1 }) + const message = this.growl.info('Loading more views!', { ttl: -1 }); this._waitTillAfterDigestCycle(() => { // wait for digest to finish and for content to finish rendering - message.destroy() - callback() - }) + message.destroy(); + callback(); + }); } - return isViewLoadedBefore - } + return isViewLoadedBefore; + }; public loadRemainingViews = (callback?: () => void): void => { if (this._isFullDocFullyLoaded && callback) { - callback() + callback(); } else { - let handler: angular.IPromise + let handler: angular.IPromise; if (!this._loadingRemainingViewsMessage) { this._loadingRemainingViewsMessage = this.growl.info('Loading more views!', { ttl: -1, onclose: () => { - delete this._loadingRemainingViewsMessage + delete this._loadingRemainingViewsMessage; }, - }) + }); } if (!this._isLoadingRemaingViews) { - this._isLoadingRemaingViews = true + this._isLoadingRemaingViews = true; handler = this.$interval(() => { - let nextIndex = this.viewsBuffer.length + 9 + let nextIndex = this.viewsBuffer.length + 9; if (nextIndex >= this.views.length) { - nextIndex = this.views.length - 1 + nextIndex = this.views.length - 1; } - this._pushNewViewsToBuffer(this.viewsBuffer.length, nextIndex) + this._pushNewViewsToBuffer(this.viewsBuffer.length, nextIndex); if (nextIndex === this.views.length - 1) { - this.$interval.cancel(handler) + this.$interval.cancel(handler); this._waitTillAfterDigestCycle(() => { - callback() - this._isLoadingRemaingViews = false + callback(); + this._isLoadingRemaingViews = false; if (this._loadingRemainingViewsMessage) { - this._loadingRemainingViewsMessage.destroy() - delete this._loadingRemainingViewsMessage + this._loadingRemainingViewsMessage.destroy(); + delete this._loadingRemainingViewsMessage; } - }) + }); } - }, 1000) + }, 1000); } } - } + }; public handleDocumentScrolling = (): boolean => { - return this._pushNewViewsToBuffer(this.viewsBuffer.length, this.viewsBuffer.length) - } + return this._pushNewViewsToBuffer(this.viewsBuffer.length, this.viewsBuffer.length); + }; public addInitialViews = (isScrollbarVisible: () => boolean): void => { - const message = this.growl.info('Loading initial view!', { ttl: -1 }) + const message = this.growl.info('Loading initial view!', { ttl: -1 }); const destroyMessage = (): void => { - message.destroy() - } - this._incrementallyAddViewTillScroll(destroyMessage, isScrollbarVisible) - } + message.destroy(); + }; + this._incrementallyAddViewTillScroll(destroyMessage, isScrollbarVisible); + }; public handleViewAdd = (view: ViewData, prevSiblingViewId: string): void => { // load the new view into the original views right after its sibling - const siblingIndex = this._findViewFromOriginalViews(prevSiblingViewId) - this.views.splice(siblingIndex + 1, 0, view) + const siblingIndex = this._findViewFromOriginalViews(prevSiblingViewId); + this.views.splice(siblingIndex + 1, 0, view); // load the new view into the viewsBuffer - const siblingIndexFromLoadedViews = this._findViewFromLoadedViews(prevSiblingViewId) + const siblingIndexFromLoadedViews = this._findViewFromLoadedViews(prevSiblingViewId); if (siblingIndexFromLoadedViews === -1) { // load all views up until the sibling view plus the new view - this._pushNewViewsToBuffer(this.viewsBuffer.length, siblingIndex + 1) + this._pushNewViewsToBuffer(this.viewsBuffer.length, siblingIndex + 1); } else { // load the new view right after its sibling - this._addNewViewToBufferAt(siblingIndexFromLoadedViews + 1) + this._addNewViewToBufferAt(siblingIndexFromLoadedViews + 1); } - } + }; public handleViewDelete = (deletedBranch: TreeBranch): void => { - const viewIdsToDelete: string[] = [] - this._getAllViewsStartingAt(deletedBranch, viewIdsToDelete) - this._deleteViewsFrom(this.views, viewIdsToDelete) - this._deleteViewsFrom(this.viewsBuffer, viewIdsToDelete) - } + const viewIdsToDelete: string[] = []; + this._getAllViewsStartingAt(deletedBranch, viewIdsToDelete); + this._deleteViewsFrom(this.views, viewIdsToDelete); + this._deleteViewsFrom(this.viewsBuffer, viewIdsToDelete); + }; private _addNewViewToBufferAt = (index: number): void => { - this.viewsBuffer.splice(index, 0, this.viewsBuffer[index]) - } + this.viewsBuffer.splice(index, 0, this.viewsBuffer[index]); + }; private _pushNewViewsToBuffer = (startIndex: number, endIndex: number): boolean => { - let isLoadedBefore = true + let isLoadedBefore = true; if (startIndex < this.views.length && endIndex < this.views.length) { - Array.prototype.push.apply(this.viewsBuffer, this.views.slice(startIndex, endIndex + 1)) - isLoadedBefore = false + Array.prototype.push.apply(this.viewsBuffer, this.views.slice(startIndex, endIndex + 1)); + isLoadedBefore = false; if (endIndex === this.views.length - 1) { this._waitTillAfterDigestCycle(() => { - this._isFullDocFullyLoaded = true - }) + this._isFullDocFullyLoaded = true; + }); } } - return isLoadedBefore - } + return isLoadedBefore; + }; private _loadViewsUntilViewWith = (viewId: string): boolean => { - let isViewLoadedBefore = true + let isViewLoadedBefore = true; // if not, find the index of that view and load starting from lastLoadedViewIndex till that view + 1 if (this._findViewFromLoadedViews(viewId) === -1) { - const index = this._findViewFromOriginalViews(viewId) + const index = this._findViewFromOriginalViews(viewId); if (index !== -1) { - this._pushNewViewsToBuffer(this.viewsBuffer.length, index) + this._pushNewViewsToBuffer(this.viewsBuffer.length, index); } - isViewLoadedBefore = false + isViewLoadedBefore = false; } - return isViewLoadedBefore - } + return isViewLoadedBefore; + }; private _incrementallyAddViewTillScroll = (callback: () => void, isScrollbarVisible: () => boolean): void => { - const isNoMoreToLoad = this._pushNewViewsToBuffer(this.viewsBuffer.length, this.viewsBuffer.length) + const isNoMoreToLoad = this._pushNewViewsToBuffer(this.viewsBuffer.length, this.viewsBuffer.length); this._waitTillAfterDigestCycle(() => { //const isScrollBarVisible = isScrollbarVisible() // the scrollbar logic no longer work, error in pane, just load a view and stop - const isScrollBarVisible = true + const isScrollBarVisible = true; if (isScrollBarVisible || isNoMoreToLoad) { - callback() + callback(); } else { - this._incrementallyAddViewTillScroll(callback, isScrollbarVisible) + this._incrementallyAddViewTillScroll(callback, isScrollbarVisible); } - }) - } + }); + }; private _getAllViewsStartingAt(branch: TreeBranch, results: string[]): void { if (branch.type === 'view') { - results.push(branch.data.id) + results.push(branch.data.id); branch.children.forEach((childBranch) => { - this._getAllViewsStartingAt(childBranch, results) - }) + this._getAllViewsStartingAt(childBranch, results); + }); } } private _deleteViewsFrom(viewListToDeleteFrom: ViewData[], viewIdsToDelete: string[]): void { _.remove(viewListToDeleteFrom, (view: ViewData) => { - return viewIdsToDelete.indexOf(view.id) !== -1 - }) + return viewIdsToDelete.indexOf(view.id) !== -1; + }); } private _findViewFromLoadedViews = (viewId: string): number => { - return _.findIndex(this.viewsBuffer, { id: viewId }) - } + return _.findIndex(this.viewsBuffer, { id: viewId }); + }; private _findViewFromOriginalViews = (viewId: string): number => { - return _.findIndex(this.views, { id: viewId }) - } + return _.findIndex(this.views, { id: viewId }); + }; private _waitTillAfterDigestCycle = (callback: () => void): void => { void this.$timeout(() => { if (this._isViewsFullyLoaded()) { - callback() + callback(); } else { - this._waitTillAfterDigestCycle(callback) + this._waitTillAfterDigestCycle(callback); } - }, 500) - } + }, 500); + }; private _isViewsFullyLoaded = (): boolean => { - return this.$http.pendingRequests.length === 0 - } + return this.$http.pendingRequests.length === 0; + }; } export class FullDocumentService { - static $inject = ['$timeout', '$interval', '$http', 'growl'] + static $inject = ['$timeout', '$interval', '$http', 'growl']; constructor( private $timeout: angular.ITimeoutService, @@ -203,8 +203,8 @@ export class FullDocumentService { ) {} get(): FullDocumentApi { - return new FullDocumentApi(this.$timeout, this.$interval, this.$http, this.growl) + return new FullDocumentApi(this.$timeout, this.$interval, this.$http, this.growl); } } -veUtils.service('FullDocumentService', FullDocumentService) +veUtils.service('FullDocumentService', FullDocumentService); diff --git a/src/ve-app/main/services/Resolve.service.ts b/src/ve-app/main/services/Resolve.service.ts index eb3f42f8f..f2ab571f6 100644 --- a/src/ve-app/main/services/Resolve.service.ts +++ b/src/ve-app/main/services/Resolve.service.ts @@ -1,7 +1,7 @@ -import { UIRouter } from '@uirouter/angularjs' +import { UIRouter } from '@uirouter/angularjs'; -import { BrandingService, BrandingStyle, ShortUrlService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { BrandingService, BrandingStyle, ShortUrlService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; import { AuthService, ElementService, @@ -10,11 +10,11 @@ import { ProjectService, URLService, ViewService, -} from '@ve-utils/mms-api-client' +} from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VePromise, VeQService } from '@ve-types/angular' +import { VePromise, VeQService } from '@ve-types/angular'; import { CheckAuthResponse, DocumentObject, @@ -32,8 +32,8 @@ import { RefObject, RefsResponse, ViewObject, -} from '@ve-types/mms' -import { VeStorageService } from '@ve-types/view-editor' +} from '@ve-types/mms'; +import { VeStorageService } from '@ve-types/view-editor'; export class ResolveService { static $inject = [ @@ -51,7 +51,7 @@ export class ResolveService { 'ElementService', 'PermissionsService', 'EventService', - ] + ]; constructor( private $localStorage: VeStorageService, @@ -71,150 +71,150 @@ export class ResolveService { ) {} public getBanner(params?: ParamsObject): VePromise { - return this.brandingSvc.getBanner(params) + return this.brandingSvc.getBanner(params); } public getLoginBanner(): VePromise { - return this.brandingSvc.getLoginBanner() + return this.brandingSvc.getLoginBanner(); } public getFooter(params?: ParamsObject): VePromise { - return this.brandingSvc.getFooter(params) + return this.brandingSvc.getFooter(params); } public getToken(): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.authSvc.checkLogin().then( (data) => { - this.uRLSvc.setToken(this.$localStorage.token) - deferred.resolve(this.$localStorage.token) - this.$cookies.put('com.tomsawyer.web.license.user', data.username, { path: '/' }) + this.uRLSvc.setToken(this.$localStorage.token); + deferred.resolve(this.$localStorage.token); + this.$cookies.put('com.tomsawyer.web.license.user', data.username, { path: '/' }); }, (rejection) => { - deferred.reject(rejection) + deferred.reject(rejection); } - ) - return deferred.promise + ); + return deferred.promise; } public getOrg(projectOb: ProjectObject): VePromise { - const promise = this.projectSvc.getOrg(projectOb.orgId) + const promise = this.projectSvc.getOrg(projectOb.orgId); promise.then( (result) => { - this.eventSvc.resolve('mmsOrg', result) + this.eventSvc.resolve('mmsOrg', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getOrgs(): VePromise { - const promise = this.projectSvc.getOrgs() + const promise = this.projectSvc.getOrgs(); promise.then( (result) => { - this.eventSvc.resolve('mmsOrgs', result) + this.eventSvc.resolve('mmsOrgs', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getProject(params: ParamsObject): VePromise { - const promise = this.projectSvc.getProject(params.projectId) + const promise = this.projectSvc.getProject(params.projectId); promise.then( (result) => { - this.eventSvc.resolve('mmsProject', result) + this.eventSvc.resolve('mmsProject', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getProjects(projectOb: ProjectObject, refresh?: boolean): VePromise { - const promise = this.projectSvc.getProjects(projectOb.orgId, refresh) + const promise = this.projectSvc.getProjects(projectOb.orgId, refresh); promise.then( (result) => { - this.eventSvc.resolve('mmsProjects', result) + this.eventSvc.resolve('mmsProjects', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getProjectMounts(params: ParamsObject, refresh?: boolean): VePromise { - const promise = this.projectSvc.getProjectMounts(params.projectId, params.refId, refresh) + const promise = this.projectSvc.getProjectMounts(params.projectId, params.refId, refresh); promise.then( (result) => { - this.eventSvc.resolve('mmsProject', result) + this.eventSvc.resolve('mmsProject', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getRef(params: ParamsObject): VePromise { - const promise = this.projectSvc.getRef(params.refId, params.projectId) + const promise = this.projectSvc.getRef(params.refId, params.projectId); promise.then( (result) => { - this.eventSvc.resolve('mmsRef', result) + this.eventSvc.resolve('mmsRef', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getRefs(params: ParamsObject): VePromise { - const promise = this.projectSvc.getRefs(params.projectId) + const promise = this.projectSvc.getRefs(params.projectId); promise.then( (result) => { - this.eventSvc.resolve('mmsRefs', result) + this.eventSvc.resolve('mmsRefs', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getGroups(params: ParamsObject, refresh?: boolean): VePromise { return this.$q((resolve, reject) => { this.projectSvc.getGroups(params.projectId, params.refId, refresh).then( (result) => { - resolve(result) - this.eventSvc.resolve('mmsGroups', result) + resolve(result); + this.eventSvc.resolve('mmsGroups', result); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } public getGroup(groupObs: GroupObject[], documentOb: DocumentObject): GroupObject { - let group: GroupObject = null + let group: GroupObject = null; if (documentOb) { for (let i = 0; i < groupObs.length; i++) { if (groupObs[i].id == documentOb._groupId) { - group = groupObs[i] - break + group = groupObs[i]; + break; } } } - this.eventSvc.resolve('mmsGroup', group) - return group + this.eventSvc.resolve('mmsGroup', group); + return group; } public getProjectRoot(params: ParamsObject): VePromise { @@ -222,7 +222,7 @@ export class ResolveService { projectId: params.projectId, refId: params.refId, elementId: params.projectId + '_pm', - }) + }); } public getCoverDocument( @@ -231,8 +231,8 @@ export class ResolveService { projectOb: ProjectObject, refresh?: boolean ): VePromise { - const deferred = this.$q.defer() - const eid = params.projectId + '_cover' + const deferred = this.$q.defer(); + const eid = params.projectId + '_cover'; this.elementSvc .getElement( { @@ -245,14 +245,14 @@ export class ResolveService { ) .then( (data) => { - this.eventSvc.resolve('mmsDocument', data) - if (!data._groupId) data._groupId = params.projectId + '_pm' - deferred.resolve(data) + this.eventSvc.resolve('mmsDocument', data); + if (!data._groupId) data._groupId = params.projectId + '_pm'; + deferred.resolve(data); }, (reason) => { if (reason.status === 404) { if (refOb.type === 'Tag') { - deferred.resolve(null) + deferred.resolve(null); } else { this.viewSvc .createView( @@ -272,19 +272,19 @@ export class ResolveService { ) .then( (data) => { - this.eventSvc.resolve('mmsDocument', data) - deferred.resolve(data) + this.eventSvc.resolve('mmsDocument', data); + deferred.resolve(data); }, (reason2) => { - deferred.resolve(null) + deferred.resolve(null); } - ) + ); } } else if (reason.status === 410) { //resurrect - let name = projectOb.name + ' Cover Page ' + let name = projectOb.name + ' Cover Page '; try { - name = `${reason.data.deleted[0].name} ` + name = `${reason.data.deleted[0].name} `; } catch (e) {} this.elementSvc .updateElements([ @@ -306,37 +306,37 @@ export class ResolveService { ]) .then( (data) => { - let resolved = false + let resolved = false; if (data.length > 0) { data.forEach((e) => { if (e.id == eid) { - deferred.resolve(e) - resolved = true + deferred.resolve(e); + resolved = true; } - }) + }); } if (!resolved) { - deferred.resolve(null) + deferred.resolve(null); } }, () => { - deferred.resolve(null) + deferred.resolve(null); } - ) + ); } else { - deferred.resolve(null) //let user get into project + deferred.resolve(null); //let user get into project } } - ) - return deferred.promise + ); + return deferred.promise; } public getPreviewDocument(params: ParamsObject, refOb: RefObject, refresh?: boolean): VePromise { - const deferred = this.$q.defer() - const eid: string = params.preview - const coverIndex = eid.indexOf('_cover') + const deferred = this.$q.defer(); + const eid: string = params.preview; + const coverIndex = eid.indexOf('_cover'); if (coverIndex > 0) { - const groupId = eid.substring(5, coverIndex) + const groupId = eid.substring(5, coverIndex); this.elementSvc .getElement( { @@ -350,18 +350,18 @@ export class ResolveService { ) .then( (data) => { - this.eventSvc.resolve('mmsDocument', data) - deferred.resolve(data) + this.eventSvc.resolve('mmsDocument', data); + deferred.resolve(data); }, (reason) => { if (reason.status === 404) { if (refOb.type === 'Tag') { - deferred.resolve(null) + deferred.resolve(null); } else { const viewDoc = '[cf:group docs]' + '">[cf:group docs]'; this.elementSvc .getElement( { @@ -392,35 +392,35 @@ export class ResolveService { ) .then( (data) => { - this.eventSvc.resolve('mmsDocument', data) - deferred.resolve(data) + this.eventSvc.resolve('mmsDocument', data); + deferred.resolve(data); }, (reason3) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); }, (reason2) => { - deferred.reject(reason2) + deferred.reject(reason2); } - ) + ); } } else { - deferred.reject(reason) + deferred.reject(reason); } } - ) + ); } else { this.getProjectDocument(params, refresh).then( (data) => { - deferred.resolve(data) + deferred.resolve(data); }, (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } - return deferred.promise + return deferred.promise; } public getProjectDocument(params: ParamsObject, refresh?: boolean): VePromise { @@ -432,17 +432,17 @@ export class ResolveService { }, 2, refresh - ) + ); promise.then( (result) => { - this.eventSvc.resolve('mmsDocument', result) + this.eventSvc.resolve('mmsDocument', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getProjectDocuments( @@ -461,14 +461,14 @@ export class ResolveService { ) .then( (result) => { - resolve(result) - this.eventSvc.resolve('mmsDocuments', result) + resolve(result); + this.eventSvc.resolve('mmsDocuments', result); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } public getView(params: ParamsObject, refresh?: boolean): VePromise { @@ -480,39 +480,39 @@ export class ResolveService { }, 2, refresh - ) + ); promise.then( (result) => { - this.eventSvc.resolve('mmsView', result) + this.eventSvc.resolve('mmsView', result); }, (reason) => { - this.growl.error('Resolve Error: ' + reason.message) + this.growl.error('Resolve Error: ' + reason.message); } - ) - return promise + ); + return promise; } public getSearch = (params: ParamsObject): string => { if (params.search === undefined) { - return null + return null; } - return params.search - } + return params.search; + }; public getField = (params: ParamsObject): string => { if (params.field === undefined) { - return 'all' + return 'all'; } - return params.field - } + return params.field; + }; public initializePermissions( projectOb: ProjectObject, refOb: RefObject ): VePromise { - return this.permissionsSvc.initializePermissions(projectOb, refOb) + return this.permissionsSvc.initializePermissions(projectOb, refOb); } } -veApp.service('ResolveService', ResolveService) +veApp.service('ResolveService', ResolveService); diff --git a/src/ve-app/main/services/index.ts b/src/ve-app/main/services/index.ts index 7ac8a2135..d8eab8020 100644 --- a/src/ve-app/main/services/index.ts +++ b/src/ve-app/main/services/index.ts @@ -1,7 +1,7 @@ -import './AppUtils.service' -import './Resolve.service' -import './FullDocument.service' +import './AppUtils.service'; +import './Resolve.service'; +import './FullDocument.service'; -export * from './AppUtils.service' -export * from './Resolve.service' -export * from './FullDocument.service' +export * from './AppUtils.service'; +export * from './Resolve.service'; +export * from './FullDocument.service'; diff --git a/src/ve-app/pane-center/document.component.ts b/src/ve-app/pane-center/document.component.ts index 3be4d1154..c53f832af 100644 --- a/src/ve-app/pane-center/document.component.ts +++ b/src/ve-app/pane-center/document.component.ts @@ -1,60 +1,60 @@ -import { IPaneScrollApi } from '@openmbee/pane-layout/lib/components/ng-pane' -import { HookResult, Ng1Controller, StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs' -import { Transition } from '@uirouter/core' -import angular, { IComponentController } from 'angular' -import Rx from 'rx-lite' - -import { veAppEvents } from '@ve-app/events' -import { AppUtilsService, FullDocumentApi, FullDocumentService } from '@ve-app/main/services' -import { pane_center_buttons } from '@ve-app/pane-center/pane-center-buttons.config' -import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service' -import { TreeService } from '@ve-components/trees' -import { IButtonBarButton, ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' -import { veCoreEvents } from '@ve-core/events' -import { RootScopeService, ShortUrlService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { PermissionsService, ViewData, ViewService, URLService } from '@ve-utils/mms-api-client' - -import { veApp } from '@ve-app' - -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { DocumentObject, ElementObject, ParamsObject, ProjectObject, RefObject, ViewObject } from '@ve-types/mms' -import { TreeBranch, View2NodeMap } from '@ve-types/tree' +import { IPaneScrollApi } from '@openmbee/pane-layout/lib/components/ng-pane'; +import { HookResult, Ng1Controller, StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs'; +import { Transition } from '@uirouter/core'; +import angular, { IComponentController } from 'angular'; +import Rx from 'rx-lite'; + +import { veAppEvents } from '@ve-app/events'; +import { AppUtilsService, FullDocumentApi, FullDocumentService } from '@ve-app/main/services'; +import { pane_center_buttons } from '@ve-app/pane-center/pane-center-buttons.config'; +import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service'; +import { TreeService } from '@ve-components/trees'; +import { IButtonBarButton, ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; +import { veCoreEvents } from '@ve-core/events'; +import { RootScopeService, ShortUrlService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { PermissionsService, ViewData, ViewService, URLService } from '@ve-utils/mms-api-client'; + +import { veApp } from '@ve-app'; + +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { DocumentObject, ElementObject, ParamsObject, ProjectObject, RefObject, ViewObject } from '@ve-types/mms'; +import { TreeBranch, View2NodeMap } from '@ve-types/tree'; class FullDocumentController implements IComponentController, Ng1Controller { //Bindings - public mmsView: ViewObject - public mmsDocument: DocumentObject - public mmsProject: ProjectObject - public mmsRef: RefObject + public mmsView: ViewObject; + public mmsDocument: DocumentObject; + public mmsProject: ProjectObject; + public mmsRef: RefObject; // // //Locals // public document: DocumentObject // public project: ProjectObject // public ref: RefObject - public subs: Rx.IDisposable[] - bars: string[] - bbApi: ButtonBarApi - bbId = 'full-doc' - fullDocumentApi: FullDocumentApi - viewContentLoading: boolean - buttons: IButtonBarButton[] = [] - latestElement: string = '' - scrollApi: IPaneScrollApi - views: ViewData[] = [] - viewsBuffer: ViewData[] = [] - view2Children: { [key: string]: string[] } = {} - view2Node: View2NodeMap = {} - num = 1 - seenViewIds = {} - shortUrl: string = '' - processed: string + public subs: Rx.IDisposable[]; + bars: string[]; + bbApi: ButtonBarApi; + bbId = 'full-doc'; + fullDocumentApi: FullDocumentApi; + viewContentLoading: boolean; + buttons: IButtonBarButton[] = []; + latestElement: string = ''; + scrollApi: IPaneScrollApi; + views: ViewData[] = []; + viewsBuffer: ViewData[] = []; + view2Children: { [key: string]: string[] } = {}; + view2Node: View2NodeMap = {}; + num = 1; + seenViewIds = {}; + shortUrl: string = ''; + processed: string; private dynamicPopover: { - templateUrl: string - title: string - } + templateUrl: string; + title: string; + }; static $inject = [ '$q', @@ -81,7 +81,7 @@ class FullDocumentController implements IComponentController, Ng1Controller { 'TreeService', 'EventService', 'ButtonBarService', - ] + ]; constructor( private $q: VeQService, private $scope: angular.IScope, @@ -110,71 +110,71 @@ class FullDocumentController implements IComponentController, Ng1Controller { ) {} $onInit(): void { - this.rootScopeSvc.veFullDocMode(true) - this.rootScopeSvc.veHideLeft(false) - this.rootScopeSvc.veHideRight(false) - this.rootScopeSvc.veNumberingOn(true) - this.eventSvc.$init(this) + this.rootScopeSvc.veFullDocMode(true); + this.rootScopeSvc.veHideLeft(false); + this.rootScopeSvc.veHideRight(false); + this.rootScopeSvc.veNumberingOn(true); + this.eventSvc.$init(this); //Init/Reset Tree Updated Subject - this.eventSvc.resolve(TreeService.events.UPDATED, false) + this.eventSvc.resolve(TreeService.events.UPDATED, false); - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, pane_center_buttons) + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, pane_center_buttons); this.view2Node[this.mmsDocument.id] = { label: this.mmsDocument.name, data: this.mmsDocument, type: 'view', children: [], - } - this.view2Children[this.mmsDocument.id] = [] + }; + this.view2Children[this.mmsDocument.id] = []; // Share URL button settings - this.dynamicPopover = this.shortUrlSvc.dynamicPopover + this.dynamicPopover = this.shortUrlSvc.dynamicPopover; this.shortUrl = this.shortUrlSvc.getShortUrl({ orgId: this.mmsProject.orgId, projectId: this.mmsProject.id, refId: this.mmsRef.id, documentId: this.mmsDocument.id, - }) + }); - this.viewContentLoading = this.rootScopeSvc.veViewContentLoading(false) + this.viewContentLoading = this.rootScopeSvc.veViewContentLoading(false); this.$transitions.onSuccess({}, (transition) => { - this._scroll(transition.params().viewId as string) - }) + this._scroll(transition.params().viewId as string); + }); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEVIEWCONTENTLOADING, (data) => { - this.viewContentLoading = data + this.viewContentLoading = data; }) - ) + ); // api to communicate with borderlayout library, no longer works this.scrollApi = { notifyOnScroll: this.notifyOnScroll, isScrollVisible: (): boolean => { - return false + return false; }, // pane's directive (in borderlayout) resets this to the right function throttleRate: 500, // how often should the wheel event triggered threshold: 3000, // how far from the bottom of the page before adding more views frequency: 100, // how fast to add more views - } + }; this.subs.push( this.eventSvc.$on('view.deleted', (deletedBranch: TreeBranch) => { - this.fullDocumentApi.handleViewDelete(deletedBranch) + this.fullDocumentApi.handleViewDelete(deletedBranch); }) - ) + ); this.subs.push( this.eventSvc.$on('view.added', (data: veAppEvents.viewAddedData) => { - this.fullDocumentApi.handleViewAdd(this._buildViewData(data.vId, data.curSec), data.prevSibId) - this._scroll(data.vId) - this.eventSvc.$broadcast('view.selected') + this.fullDocumentApi.handleViewAdd(this._buildViewData(data.vId, data.curSec), data.prevSibId); + this._scroll(data.vId); + this.eventSvc.$broadcast('view.selected'); }) - ) + ); this.subs.push( // this.eventSvc.$on('view.scroll', (viewId) => { @@ -186,36 +186,36 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.bbApi.toggleButton( 'show-comments', this.rootScopeSvc.veCommentsOn(!this.rootScopeSvc.veCommentsOn()) - ) - break + ); + break; case 'show-elements': this.bbApi.toggleButton( 'show-elements', this.rootScopeSvc.veElementsOn(!this.rootScopeSvc.veElementsOn()) - ) + ); if (!this.rootScopeSvc.veElementsOn() && this.rootScopeSvc.veEditMode()) { - this.bbApi.toggleButton('show-edits', false) - this.rootScopeSvc.veEditMode(false) + this.bbApi.toggleButton('show-edits', false); + this.rootScopeSvc.veEditMode(false); } - break + break; case 'show-edits': this.bbApi.toggleButton( 'show-edits', this.rootScopeSvc.veEditMode(!this.rootScopeSvc.veEditMode()) - ) + ); if (this.rootScopeSvc.veElementsOn() !== this.rootScopeSvc.veEditMode()) { - this.bbApi.toggleButton('show-elements', this.rootScopeSvc.veEditMode()) - this.rootScopeSvc.veElementsOn(this.rootScopeSvc.veEditMode()) + this.bbApi.toggleButton('show-elements', this.rootScopeSvc.veEditMode()); + this.rootScopeSvc.veElementsOn(this.rootScopeSvc.veEditMode()); } - break + break; case 'show-numbering': this.bbApi.toggleButton( 'show-numbering', this.rootScopeSvc.veNumberingOn(!this.rootScopeSvc.veNumberingOn()) - ) - break + ); + break; case 'convert-pdf': this.fullDocumentApi.loadRemainingViews(() => { void this.appUtilsSvc.printModal( @@ -224,9 +224,9 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.mmsRef, true, 3 - ) - }) - break + ); + }); + break; case 'print': this.fullDocumentApi.loadRemainingViews(() => { void this.appUtilsSvc.printModal( @@ -235,9 +235,9 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.mmsRef, true, 1 - ) - }) - break + ); + }); + break; case 'word': this.fullDocumentApi.loadRemainingViews(() => { void this.appUtilsSvc.printModal( @@ -246,28 +246,28 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.mmsRef, true, 2 - ) - }) - break + ); + }); + break; case 'tabletocsv': this.fullDocumentApi.loadRemainingViews(() => { - this.appUtilsSvc.tableToCsv(angular.element('#print-div'), true) - }) - break + this.appUtilsSvc.tableToCsv(angular.element('#print-div'), true); + }); + break; case 'refresh-numbering': //TODO - break + break; } }) - ) - this.initViews() + ); + this.initViews(); } $onDestroy(): void { - this.eventSvc.$destroy(this.subs) - this.buttonBarSvc.destroy(this.bbId) + this.eventSvc.$destroy(this.subs); + this.buttonBarSvc.destroy(this.bbId); } initViews(): void { @@ -280,35 +280,35 @@ class FullDocumentController implements IComponentController, Ng1Controller { refId: this.mmsRef.id, refType: this.mmsRef.type, refresh: this.$uiRouterGlobals.transition.$from().name === '', - } + }; - this.eventSvc.$broadcast('view.selected', data) - this.fullDocumentApi = this.fullDocumentSvc.get() - this.views = this.fullDocumentApi.views - this.viewsBuffer = this.fullDocumentApi.viewsBuffer + this.eventSvc.$broadcast('view.selected', data); + this.fullDocumentApi = this.fullDocumentSvc.get(); + this.views = this.fullDocumentApi.views; + this.viewsBuffer = this.fullDocumentApi.viewsBuffer; this._createViews().then( () => { - this.fullDocumentApi.addInitialViews(scrollVisible) + this.fullDocumentApi.addInitialViews(scrollVisible); if (this.mmsView && this.mmsView.id !== this.mmsDocument.id) { this.fullDocumentApi.handleClickOnBranch(this.mmsView.id, () => { - this._scroll(this.mmsView.id) - this.fullDocumentApi.loadRemainingViews() //remove if scroll works - }) + this._scroll(this.mmsView.id); + this.fullDocumentApi.loadRemainingViews(); //remove if scroll works + }); } else { - this.fullDocumentApi.loadRemainingViews() //remove if scroll works + this.fullDocumentApi.loadRemainingViews(); //remove if scroll works } }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); const scrollVisible = (): boolean => { - return this.scrollApi.isScrollVisible() - } + return this.scrollApi.isScrollVisible(); + }; } uiOnParamsChanged(newValues: ParamsObject, $transition$: Transition): void { - if (newValues.viewId !== this.processed) this._scroll(newValues.viewId) + if (newValues.viewId !== this.processed) this._scroll(newValues.viewId); } uiCanExit(transition: Transition): HookResult { //Do nothing @@ -319,8 +319,8 @@ class FullDocumentController implements IComponentController, Ng1Controller { this.mmsRef.type === 'Branch' && this.permissionsSvc.hasBranchEditPermission(this.mmsProject.id, this.mmsRef.id) ) { - api.addButton(this.buttonBarSvc.getButtonBarButton('show-edits')) - api.toggleButton('show-edits', this.rootScopeSvc.veEditMode()) + api.addButton(this.buttonBarSvc.getButtonBarButton('show-edits')); + api.toggleButton('show-edits', this.rootScopeSvc.veEditMode()); this.hotkeys.bindTo(this.$scope).add({ combo: 'alt+d', @@ -328,20 +328,20 @@ class FullDocumentController implements IComponentController, Ng1Controller { callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-edits', - }) + }); }, - }) + }); } - api.addButton(this.buttonBarSvc.getButtonBarButton('show-elements')) - api.toggleButton('show-elements', this.rootScopeSvc.veElementsOn()) - api.addButton(this.buttonBarSvc.getButtonBarButton('show-comments')) - api.toggleButton('show-comments', this.rootScopeSvc.veCommentsOn()) - api.addButton(this.buttonBarSvc.getButtonBarButton('show-numbering')) - api.toggleButton('show-numbering', this.rootScopeSvc.veNumberingOn()) - api.addButton(this.buttonBarSvc.getButtonBarButton('refresh-numbering')) - api.addButton(this.buttonBarSvc.getButtonBarButton('print')) - api.addButton(this.buttonBarSvc.getButtonBarButton('export')) + api.addButton(this.buttonBarSvc.getButtonBarButton('show-elements')); + api.toggleButton('show-elements', this.rootScopeSvc.veElementsOn()); + api.addButton(this.buttonBarSvc.getButtonBarButton('show-comments')); + api.toggleButton('show-comments', this.rootScopeSvc.veCommentsOn()); + api.addButton(this.buttonBarSvc.getButtonBarButton('show-numbering')); + api.toggleButton('show-numbering', this.rootScopeSvc.veNumberingOn()); + api.addButton(this.buttonBarSvc.getButtonBarButton('refresh-numbering')); + api.addButton(this.buttonBarSvc.getButtonBarButton('print')); + api.addButton(this.buttonBarSvc.getButtonBarButton('export')); this.hotkeys .bindTo(this.$scope) @@ -351,7 +351,7 @@ class FullDocumentController implements IComponentController, Ng1Controller { callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-comments', - }) + }); }, }) .add({ @@ -360,10 +360,10 @@ class FullDocumentController implements IComponentController, Ng1Controller { callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-elements', - }) + }); }, - }) - } + }); + }; private _scroll = (viewId: string): void => { if (this.view2Children[viewId]) { @@ -374,19 +374,19 @@ class FullDocumentController implements IComponentController, Ng1Controller { projectId: this.mmsProject.id, refId: this.mmsRef.id, refType: this.mmsRef.type, - } + }; - this.eventSvc.$broadcast('element.selected', data) - if (viewId === this.processed) return - this.processed = viewId + this.eventSvc.$broadcast('element.selected', data); + if (viewId === this.processed) return; + this.processed = viewId; this.fullDocumentApi.handleClickOnBranch(viewId, () => { - document.getElementById(viewId).scrollIntoView(true) - }) + document.getElementById(viewId).scrollIntoView(true); + }); } - } + }; private _createViews = (): VePromise => { - const message = this._loadingViewsFromServer() + const message = this._loadingViewsFromServer(); return new this.$q((resolve, reject) => { this.views.push({ id: this.mmsDocument.id, @@ -394,9 +394,9 @@ class FullDocumentController implements IComponentController, Ng1Controller { elementTranscluded: this._elementTranscluded, elementClicked: this._elementClicked, }, - }) + }); if (!this.mmsDocument._childViews) { - this.mmsDocument._childViews = [] + this.mmsDocument._childViews = []; } this.viewSvc .handleChildViews( @@ -410,27 +410,27 @@ class FullDocumentController implements IComponentController, Ng1Controller { ) .then((childIds: string[]) => { for (let i = 0; i < childIds.length; i++) { - this._constructViews(childIds[i], this.num.toString(10)) - this.num = this.num + 1 + this._constructViews(childIds[i], this.num.toString(10)); + this.num = this.num + 1; } - resolve() + resolve(); }, reject) .finally(() => { - message.destroy() - }) - }) - } + message.destroy(); + }); + }); + }; private _loadingViewsFromServer = (): angular.growl.IGrowlMessage => { - return this.growl.info('Loading data from server!', { ttl: -1 }) - } + return this.growl.info('Loading data from server!', { ttl: -1 }); + }; private _elementTranscluded = (elementOb: ElementObject, type: string): void => { if (elementOb && type !== 'Comment') { if (elementOb._modified && elementOb._modified > this.latestElement) - this.latestElement = elementOb._modified + this.latestElement = elementOb._modified; } - } + }; private _elementClicked = (elementOb: ElementObject): void => { const data = { @@ -439,9 +439,9 @@ class FullDocumentController implements IComponentController, Ng1Controller { projectId: elementOb._projectId, refId: elementOb._refId, commitId: 'latest', - } - this.eventSvc.$broadcast('element.selected', data) - } + }; + this.eventSvc.$broadcast('element.selected', data); + }; private _buildViewData = (vId: string, curSec: string): ViewData => { return { @@ -453,55 +453,55 @@ class FullDocumentController implements IComponentController, Ng1Controller { number: curSec, topLevel: curSec ? curSec.toString().indexOf('.') === -1 : false, first: curSec == '1', - } - } + }; + }; private _constructViews = (viewId: string, curSection: string): void => { - this.views.push(this._buildViewData(viewId, curSection)) + this.views.push(this._buildViewData(viewId, curSection)); if (this.view2Children[viewId] && Array.isArray(this.view2Children[viewId])) { - let num = 1 - const childIds = this.view2Children[viewId] + let num = 1; + const childIds = this.view2Children[viewId]; for (let i = 0; i < childIds.length; i++) { - this._constructViews(this.view2Children[viewId][i], `${curSection}.${num}`) - num = num + 1 + this._constructViews(this.view2Children[viewId][i], `${curSection}.${num}`); + num = num + 1; } } - } + }; private _handleSingleView = (v: ViewObject, aggr: string): string[] => { - let childIds = this.view2Children[v.id] + let childIds = this.view2Children[v.id]; if (!childIds) { - childIds = [] + childIds = []; } - this.view2Children[v.id] = childIds + this.view2Children[v.id] = childIds; if (!v._childViews || v._childViews.length === 0 || aggr === 'none') { - return childIds + return childIds; } for (let i = 0; i < v._childViews.length; i++) { if (this.seenViewIds[v._childViews[i].id]) { - continue + continue; } - this.seenViewIds[v._childViews[i].id] = true - childIds.push(v._childViews[i].id) + this.seenViewIds[v._childViews[i].id] = true; + childIds.push(v._childViews[i].id); } - return childIds - } + return childIds; + }; public notifyOnScroll = (): boolean => { - return this.fullDocumentApi.handleDocumentScrolling() - } + return this.fullDocumentApi.handleDocumentScrolling(); + }; public copyToClipboard = ($event: JQuery.ClickEvent): void => { this.shortUrlSvc.copyToClipboard(this.$element, $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }) + this.growl.info('Copied to clipboard!', { ttl: 2000 }); }, (err) => { - this.growl.error('Unable to copy: ' + err.message) + this.growl.error('Unable to copy: ' + err.message); } - ) - } + ); + }; } /* Controller */ @@ -549,6 +549,6 @@ const DocumentComponent: VeComponentOptions = { mmsDocument: '<', }, controller: FullDocumentController, -} +}; -veApp.component(DocumentComponent.selector, DocumentComponent) +veApp.component(DocumentComponent.selector, DocumentComponent); diff --git a/src/ve-app/pane-center/index.ts b/src/ve-app/pane-center/index.ts index 159a896b7..cddc45cdc 100644 --- a/src/ve-app/pane-center/index.ts +++ b/src/ve-app/pane-center/index.ts @@ -1,8 +1,8 @@ -import './services/ContentWindow.service' +import './services/ContentWindow.service'; -import './document.component' -import './slideshow.component' -import './search.component' -import './refs.component' -import './reorder.component' -import './reorder-group.component' +import './document.component'; +import './slideshow.component'; +import './search.component'; +import './refs.component'; +import './reorder.component'; +import './reorder-group.component'; diff --git a/src/ve-app/pane-center/pane-center-buttons.config.ts b/src/ve-app/pane-center/pane-center-buttons.config.ts index 41448a545..ca370ccb8 100644 --- a/src/ve-app/pane-center/pane-center-buttons.config.ts +++ b/src/ve-app/pane-center/pane-center-buttons.config.ts @@ -1,4 +1,4 @@ -import { IButtonBarButton } from '@ve-core/button-bar' +import { IButtonBarButton } from '@ve-core/button-bar'; export const pane_center_buttons: IButtonBarButton[] = [ { @@ -98,4 +98,4 @@ export const pane_center_buttons: IButtonBarButton[] = [ selectable: false, tooltip: 'Table to CSV', }, -] +]; diff --git a/src/ve-app/pane-center/refs.component.ts b/src/ve-app/pane-center/refs.component.ts index f63b38645..39cf1eb22 100644 --- a/src/ve-app/pane-center/refs.component.ts +++ b/src/ve-app/pane-center/refs.component.ts @@ -1,22 +1,22 @@ -import { StateService } from '@uirouter/angularjs' -import angular, { IWindowService } from 'angular' -import _ from 'lodash' -import Rx from 'rx-lite' +import { StateService } from '@uirouter/angularjs'; +import angular, { IWindowService } from 'angular'; +import _ from 'lodash'; +import Rx from 'rx-lite'; -import { AppUtilsService } from '@ve-app/main/services' -import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service' -import { InsertRefData } from '@ve-components/insertions/components/insert-ref.component' -import { ConfirmDeleteModalResolveFn } from '@ve-core/modals' -import { ApplicationService, RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ProjectService, ElementService } from '@ve-utils/mms-api-client' +import { AppUtilsService } from '@ve-app/main/services'; +import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service'; +import { InsertRefData } from '@ve-components/insertions/components/insert-ref.component'; +import { ConfirmDeleteModalResolveFn } from '@ve-core/modals'; +import { ApplicationService, RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ProjectService, ElementService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions, VeQService } from '@ve-types/angular' -import { InsertResolveFn } from '@ve-types/components' -import { ProjectObject, RefObject } from '@ve-types/mms' -import { VeModalService, VeModalSettings } from '@ve-types/view-editor' +import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { InsertResolveFn } from '@ve-types/components'; +import { ProjectObject, RefObject } from '@ve-types/mms'; +import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; class RefsController { static $inject = [ @@ -36,29 +36,29 @@ class RefsController { 'ApplicationService', 'RootScopeService', 'EventService', - ] + ]; - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; //Bindings - mmsRefs: RefObject[] - mmsProject: ProjectObject - mmsRef: RefObject + mmsRefs: RefObject[]; + mmsProject: ProjectObject; + mmsRef: RefObject; //Local - public refManageView: boolean - isLoading: boolean - refData - bbApi - buttons - project: ProjectObject - refs: RefObject[] - branches: RefObject[] - tags: RefObject[] - refSelected: RefObject - search - view - htmlTooltip: string + public refManageView: boolean; + isLoading: boolean; + refData; + bbApi; + buttons; + project: ProjectObject; + refs: RefObject[]; + branches: RefObject[]; + tags: RefObject[]; + refSelected: RefObject; + search; + view; + htmlTooltip: string; constructor( private $sce: angular.ISCEService, @@ -80,65 +80,65 @@ class RefsController { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); - this.contentWindowSvc.toggleLeftPane(true) - this.rootScopeSvc.veHideLeft(true) - this.rootScopeSvc.veHideRight(true) - this.refManageView = true - this.refData = [] - this.bbApi = {} - this.buttons = [] - this.refSelected = this.mmsRef - this.search = null - this.view = null + this.contentWindowSvc.toggleLeftPane(true); + this.rootScopeSvc.veHideLeft(true); + this.rootScopeSvc.veHideRight(true); + this.refManageView = true; + this.refData = []; + this.bbApi = {}; + this.buttons = []; + this.refSelected = this.mmsRef; + this.search = null; + this.view = null; - this.refs = this.mmsRefs + this.refs = this.mmsRefs; this.branches = this.refs.filter((ref) => { - return ref.type === 'Branch' - }) + return ref.type === 'Branch'; + }); this.tags = this.refs.filter((ref) => { - return ref.type === 'Tag' - }) + return ref.type === 'Tag'; + }); - this.project = this.mmsProject + this.project = this.mmsProject; - this.htmlTooltip = this.$sce.trustAsHtml('Branch temporarily unavailable during duplication.') as string + this.htmlTooltip = this.$sce.trustAsHtml('Branch temporarily unavailable during duplication.') as string; } selectMasterDefault = (): void => { - const masterIndex = _.findIndex(this.refs, { name: 'master' }) + const masterIndex = _.findIndex(this.refs, { name: 'master' }); if (masterIndex > -1) { - this.refSelected = this.refs[masterIndex] + this.refSelected = this.refs[masterIndex]; } - } + }; addBranch = (e: JQuery.ClickEvent): void => { - e.stopPropagation() - this.insert('Branch') - } + e.stopPropagation(); + this.insert('Branch'); + }; addTag = (e: JQuery.ClickEvent): void => { - e.stopPropagation() - this.insert('Tag') - } + e.stopPropagation(); + this.insert('Tag'); + }; deleteRef = (e: JQuery.ClickEvent): void => { - e.stopPropagation() - this.deleteItem() - } + e.stopPropagation(); + this.deleteItem(); + }; refClickHandler = (ref: RefObject): void => { this.projectSvc.getRef(ref.id, this.project.id).then( (data) => { - this.refSelected = data + this.refSelected = data; }, (error) => { - this.growl.error('Ref click handler error: ' + error.message) - return + this.growl.error('Ref click handler error: ' + error.message); + return; } - ) - } + ); + }; insert = (itemType: string): void => { const insertData: InsertRefData = { @@ -147,126 +147,126 @@ class RefsController { parentTitle: '', insertType: 'ref', lastCommit: true, - } - const branch = this.refSelected + }; + const branch = this.refSelected; // Item specific setup: if (itemType === 'Branch') { if (!branch) { - this.growl.warning('Add Branch Error: Select a branch or tag first') - return + this.growl.warning('Add Branch Error: Select a branch or tag first'); + return; } if (branch.type === 'Tag') { - insertData.parentTitle = 'Tag ' + branch.name + insertData.parentTitle = 'Tag ' + branch.name; } else { - insertData.parentTitle = 'Branch ' + branch.name + insertData.parentTitle = 'Branch ' + branch.name; } - insertData.parentRefId = branch.id + insertData.parentRefId = branch.id; } else if (itemType === 'Tag') { if (!branch) { - this.growl.warning('Add Tag Error: Select a branch or tag first') - return + this.growl.warning('Add Tag Error: Select a branch or tag first'); + return; } - insertData.parentRefId = branch.id + insertData.parentRefId = branch.id; } else { - this.growl.error('Add Item of Type ' + itemType + ' is not supported') - return + this.growl.error('Add Item of Type ' + itemType + ' is not supported'); + return; } const instance = this.$uibModal.open, RefObject>({ component: 'insertElementModal', resolve: { getInsertData: () => { - return insertData + return insertData; }, getFilter: () => { - return this.$filter + return this.$filter; }, getProjectId: () => { - return this.project.id + return this.project.id; }, getRefId: () => { - return null + return null; }, getOrgId: () => { - return this.project.orgId + return this.project.orgId; }, getSeenViewIds: () => { - return null + return null; }, }, - }) + }); instance.result.then( (data) => { if (data.type === 'Branch') { - this.branches.push(data) - this.refSelected = data + this.branches.push(data); + this.refSelected = data; } else { - this.tags.push(data) - this.refSelected = data + this.tags.push(data); + this.refSelected = data; } }, (reason?) => { if (reason && reason.status !== 444) { - this.growl.error('Ref Creation Error:' + reason.message) + this.growl.error('Ref Creation Error:' + reason.message); } else { this.growl.info('Ref Creation Cancelled', { ttl: 1000, - }) + }); } } - ) - } + ); + }; deleteItem = (): void => { - const branch = this.refSelected + const branch = this.refSelected; if (!branch) { - this.growl.warning('Select item to delete.') - return + this.growl.warning('Select item to delete.'); + return; } const settings: VeModalSettings = { component: 'confirmDeleteModal', resolve: { getName: () => { - return branch.name + return branch.name; }, getType: () => { if (branch.type === 'Tag') { - return 'Tag' + return 'Tag'; } else if (branch.type === 'Branch') { - return 'Branch' + return 'Branch'; } }, finalize: () => { return () => { - return this.projectSvc.deleteRef(branch.id, this.project.id) - } + return this.projectSvc.deleteRef(branch.id, this.project.id); + }; }, }, - } - const instance = this.$uibModal.open(settings) + }; + const instance = this.$uibModal.open(settings); instance.result.then( () => { //TODO $state project with no selected ref - let index: number + let index: number; if (this.refSelected.type === 'Branch') { - index = this.branches.indexOf(this.refSelected) - this.branches.splice(index, 1) + index = this.branches.indexOf(this.refSelected); + this.branches.splice(index, 1); } else if (this.refSelected.type === 'Tag') { - index = this.tags.indexOf(this.refSelected) - this.tags.splice(index, 1) + index = this.tags.indexOf(this.refSelected); + this.tags.splice(index, 1); } - this.refSelected = null + this.refSelected = null; }, (reason?) => { if (reason) { - this.growl.error('Ref Deletion Error:' + reason.message) + this.growl.error('Ref Deletion Error:' + reason.message); } else { this.growl.info('Ref Deletion Cancelled', { ttl: 1000, - }) + }); } } - ) - } + ); + }; } const RefsComponent: VeComponentOptions = { @@ -353,6 +353,6 @@ const RefsComponent: VeComponentOptions = { mmsRefs: '<', }, controller: RefsController, -} +}; -veApp.component(RefsComponent.selector, RefsComponent) +veApp.component(RefsComponent.selector, RefsComponent); diff --git a/src/ve-app/pane-center/reorder-group.component.ts b/src/ve-app/pane-center/reorder-group.component.ts index 2a2880af8..a5b27d810 100644 --- a/src/ve-app/pane-center/reorder-group.component.ts +++ b/src/ve-app/pane-center/reorder-group.component.ts @@ -1,48 +1,48 @@ -import { StateService } from '@uirouter/angularjs' -import { IComponentController } from 'angular' -import _ from 'lodash' +import { StateService } from '@uirouter/angularjs'; +import { IComponentController } from 'angular'; +import _ from 'lodash'; -import { TreeService } from '@ve-components/trees' -import { CacheService } from '@ve-utils/core' -import { ElementService } from '@ve-utils/mms-api-client' +import { TreeService } from '@ve-components/trees'; +import { CacheService } from '@ve-utils/core'; +import { ElementService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions, VeQService } from '@ve-types/angular' -import { DocumentObject, ElementObject, GroupObject, ParamsObject, ProjectObject, RefObject } from '@ve-types/mms' -import { AngularUITree, VeTreeNodeScope } from '@ve-types/tree' +import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { DocumentObject, ElementObject, GroupObject, ParamsObject, ProjectObject, RefObject } from '@ve-types/mms'; +import { AngularUITree, VeTreeNodeScope } from '@ve-types/tree'; interface ReorderGroupNode { - data: GroupObject | DocumentObject - children: ReorderGroupNode[] - name: string - id: string - type: string - isChild?: boolean + data: GroupObject | DocumentObject; + children: ReorderGroupNode[]; + name: string; + id: string; + type: string; + isChild?: boolean; } interface ReorderGroupResult { - node: ReorderGroupNode - newOwnerId: string + node: ReorderGroupNode; + newOwnerId: string; } class ReorderGroupController implements IComponentController { - params: ParamsObject - mmsProject: ProjectObject - mmsRef: RefObject - mmsGroups: GroupObject[] - mmsDocuments: DocumentObject[] + params: ParamsObject; + mmsProject: ProjectObject; + mmsRef: RefObject; + mmsGroups: GroupObject[]; + mmsDocuments: DocumentObject[]; //Locals - groups: GroupObject[] - documents: DocumentObject[] - isSaving = false - targetId = '' + groups: GroupObject[]; + documents: DocumentObject[]; + isSaving = false; + targetId = ''; - treeOptions: AngularUITree.ICallbacks + treeOptions: AngularUITree.ICallbacks; - static $inject = ['$q', '$scope', '$state', 'growl', 'ElementService', 'CacheService', 'TreeService'] - private tree: ReorderGroupNode[] + static $inject = ['$q', '$scope', '$state', 'growl', 'ElementService', 'CacheService', 'TreeService']; + private tree: ReorderGroupNode[]; constructor( private $q: VeQService, @@ -55,102 +55,102 @@ class ReorderGroupController implements IComponentController { ) {} $onInit(): void { - this.groups = this.mmsGroups - this.documents = this.mmsDocuments + this.groups = this.mmsGroups; + this.documents = this.mmsDocuments; - const children = this.generateTree() - this.sortRecursively(children) + const children = this.generateTree(); + this.sortRecursively(children); const root = this.createNode('Top Level', 'root', children, { id: 'root', _projectId: this.params.projectId, _refId: this.params.refId, - }) - this.tree = [root] + }); + this.tree = [root]; this.treeOptions = { dropped: (change): void => { - this.sortRecursively(children) - this.targetId = '' + this.sortRecursively(children); + this.targetId = ''; }, accept: (sourceNodeScope: VeTreeNodeScope, destNodeScope: VeTreeNodeScope, destIndex): boolean => { // allow moving to the root or to a group const accept = - destNodeScope.node && (destNodeScope.node.type === 'group' || destNodeScope.node.type === 'root') + destNodeScope.node && (destNodeScope.node.type === 'group' || destNodeScope.node.type === 'root'); if (accept) { if ( destNodeScope.$nodeScope && destNodeScope.$nodeScope.$modelValue && ( destNodeScope.$nodeScope.$modelValue as { - id: string + id: string; } ).id ) { this.targetId = ( destNodeScope.$nodeScope.$modelValue as { - id: string + id: string; } - ).id + ).id; } } - return accept + return accept; }, dragStart: (data): void => { this.targetId = ( data.dest.nodesScope.$nodeScope.$modelValue as { - id: string + id: string; } - ).id + ).id; }, - } + }; } public generateTree(): ReorderGroupNode[] { // create a node for each groupOb let tree = this.groups.map((groupOb) => { - return this.createNode(groupOb.name, 'group', [], groupOb) - }) + return this.createNode(groupOb.name, 'group', [], groupOb); + }); // add document to its group this.documents .filter((documentOb) => { - return documentOb._groupId + return documentOb._groupId; }) .forEach((documentOb) => { const parent = _.find(tree, (node) => { - return node.data.id === documentOb._groupId - }) + return node.data.id === documentOb._groupId; + }); if (parent) { - parent.children.push(this.createNode(documentOb.name, 'view', [], documentOb)) + parent.children.push(this.createNode(documentOb.name, 'view', [], documentOb)); } - }) + }); // for any group that has a parent group, establish that connection tree.forEach((groupNode) => { const foundParent = _.find(tree, (node) => { - return node.data.id === groupNode.data._parentId - }) + return node.data.id === groupNode.data._parentId; + }); if (foundParent) { - groupNode.isChild = true - foundParent.children.push(groupNode) + groupNode.isChild = true; + foundParent.children.push(groupNode); } - return groupNode - }) + return groupNode; + }); // only groups that don't have parents show up at root level tree = tree.filter((groupNode) => { - return !groupNode.isChild - }) + return !groupNode.isChild; + }); // add all the documents that don't belong to any group this.documents .filter((documentOb) => { - return !documentOb._groupId + return !documentOb._groupId; }) .forEach((documentOb) => { - this.tree.push(this.createNode(documentOb.name, 'view', [], documentOb)) - }) - return tree + this.tree.push(this.createNode(documentOb.name, 'view', [], documentOb)); + }); + return tree; } public createNode( @@ -165,18 +165,18 @@ class ReorderGroupController implements IComponentController { children: children, data: data, id: data.id, - } + }; } public cancelReorder = (): void => { - this.navigateAway(false) - } + this.navigateAway(false); + }; public saveReorder = (): void => { if (!this.isSaving) { - this.isSaving = true - const results: ReorderGroupResult[] = [] - this.findNodesToUpdate(results) + this.isSaving = true; + const results: ReorderGroupResult[] = []; + this.findNodesToUpdate(results); const elementsToUpdate: ElementObject[] = results.map((result) => { return { id: result.node.data.id, @@ -184,40 +184,40 @@ class ReorderGroupController implements IComponentController { _projectId: this.params.projectId, _refId: this.params.refId, type: result.node.data.type, - } - }) + }; + }); this.elementSvc .updateElements(elementsToUpdate, false) .then(() => { - this.cleanupCache(results) - this.navigateAway(true) + this.cleanupCache(results); + this.navigateAway(true); }) .catch(() => { - this.growl.error('Failed to save the grouping!') + this.growl.error('Failed to save the grouping!'); }) .finally(() => { - this.isSaving = false - }) + this.isSaving = false; + }); } else { - this.growl.info('please wait') + this.growl.info('please wait'); } - } + }; public findNodesToUpdate = (result: ReorderGroupResult[]): void => { // ignore root - const root = this.tree[0] + const root = this.tree[0]; root.children.forEach((node) => { // handle node change at the root level if ((node.type === 'group' && node.data._parentId) || (node.type === 'view' && node.data._groupId)) { result.push({ node: node, newOwnerId: 'holding_bin_' + this.params.projectId, - }) + }); } // handle change at lower level - helper(node, result) - }) + helper(node, result); + }); const helper = (node: ReorderGroupNode, result: ReorderGroupResult[]): void => { node.children.forEach((childNode) => { @@ -228,12 +228,12 @@ class ReorderGroupController implements IComponentController { result.push({ node: childNode, newOwnerId: node.data.id, - }) + }); } - helper(childNode, result) - }) - } - } + helper(childNode, result); + }); + }; + }; public cleanupCache = (results: ReorderGroupResult[]): void => { // update cache for documents list and groups list @@ -241,62 +241,62 @@ class ReorderGroupController implements IComponentController { 'documents', this.params.projectId, this.params.refId, - ]) + ]); const listOfGroupInCache = this.cacheSvc.get([ 'groups', this.params.projectId, this.params.refId, - ]) + ]); results.forEach((result) => { // for group or document that is moved to the root, _parentId for "group" and _groupId for "document" need to be set to undefined - const newOwnerId = result.newOwnerId.indexOf(this.params.projectId) !== -1 ? undefined : result.newOwnerId + const newOwnerId = result.newOwnerId.indexOf(this.params.projectId) !== -1 ? undefined : result.newOwnerId; if (result.node.type === 'group') { const cacheGroupOb = _.find(listOfGroupInCache, (groupOb) => { - return groupOb.id === result.node.data.id - }) + return groupOb.id === result.node.data.id; + }); if (cacheGroupOb) { - cacheGroupOb._parentId = newOwnerId + cacheGroupOb._parentId = newOwnerId; } } else if (result.node.type === 'view') { const cacheDocument = _.find(listOfDocInCache, (documentOb) => { - return documentOb.id === result.node.data.id - }) + return documentOb.id === result.node.data.id; + }); if (cacheDocument) { - cacheDocument._groupId = newOwnerId + cacheDocument._groupId = newOwnerId; } } - }) - } + }); + }; public comparator = (a: ReorderGroupNode, b: ReorderGroupNode): number => { if (a.type === b.type) { - return a.name.localeCompare(b.name) + return a.name.localeCompare(b.name); } else { if (a.type === 'group') { - return -1 + return -1; } else { - return 1 + return 1; } } - } + }; public sortRecursively = (nodes: ReorderGroupNode[]): void => { - nodes.sort(this.comparator) + nodes.sort(this.comparator); nodes.forEach((node) => { - this.sortRecursively(node.children) - }) - } + this.sortRecursively(node.children); + }); + }; public navigateAway = (reload: boolean): void => { - const curBranch = this.treeSvc.getSelectedBranch() + const curBranch = this.treeSvc.getSelectedBranch(); if (curBranch) { - const documentId = curBranch.type === 'group' ? 'site_' + curBranch.data.id + '_cover' : curBranch.data.id - void this.$state.go('main.project.ref.portal.preview', { preview: documentId }, { reload: reload }) + const documentId = curBranch.type === 'group' ? 'site_' + curBranch.data.id + '_cover' : curBranch.data.id; + void this.$state.go('main.project.ref.portal.preview', { preview: documentId }, { reload: reload }); } else { - void this.$state.go('main.project.ref.portal', {}, { reload: reload }) + void this.$state.go('main.project.ref.portal', {}, { reload: reload }); } - } + }; } const ReorderGroupComponent: VeComponentOptions = { @@ -333,6 +333,6 @@ const ReorderGroupComponent: VeComponentOptions = { mmsDocuments: '<', }, controller: ReorderGroupController, -} +}; -veApp.component(ReorderGroupComponent.selector, ReorderGroupComponent) +veApp.component(ReorderGroupComponent.selector, ReorderGroupComponent); diff --git a/src/ve-app/pane-center/reorder.component.ts b/src/ve-app/pane-center/reorder.component.ts index 990115b32..1a1129372 100644 --- a/src/ve-app/pane-center/reorder.component.ts +++ b/src/ve-app/pane-center/reorder.component.ts @@ -1,17 +1,17 @@ -import { StateService } from '@uirouter/angularjs' -import angular, { IComponentController } from 'angular' -import _ from 'lodash' +import { StateService } from '@uirouter/angularjs'; +import angular, { IComponentController } from 'angular'; +import _ from 'lodash'; -import { AppUtilsService } from '@ve-app/main/services' -import { TreeService } from '@ve-components/trees' -import { EventService } from '@ve-utils/core' -import { ViewService, ElementService } from '@ve-utils/mms-api-client' +import { AppUtilsService } from '@ve-app/main/services'; +import { TreeService } from '@ve-components/trees'; +import { EventService } from '@ve-utils/core'; +import { ViewService, ElementService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions, VePromise } from '@ve-types/angular' -import { DocumentObject, ViewObject } from '@ve-types/mms' -import { AngularUITree, TreeBranch, VeTreeNodeScope, View2NodeMap } from '@ve-types/tree' +import { VeComponentOptions, VePromise } from '@ve-types/angular'; +import { DocumentObject, ViewObject } from '@ve-types/mms'; +import { AngularUITree, TreeBranch, VeTreeNodeScope, View2NodeMap } from '@ve-types/tree'; /* Controllers */ /** @@ -28,20 +28,20 @@ import { AngularUITree, TreeBranch, VeTreeNodeScope, View2NodeMap } from '@ve-ty */ class ReorderController implements IComponentController { //bindings - private mmsDocument: VePromise + private mmsDocument: VePromise; //local - protected doc: ViewObject - private viewIds2node: View2NodeMap = {} - private origViews: { [key: string]: ViewObject } = {} - public tree: TreeBranch[] - public treeOptions: AngularUITree.ICallbacks - private seenViewIds: View2NodeMap = {} - public saveClass: string = '' - private saving: boolean = false + protected doc: ViewObject; + private viewIds2node: View2NodeMap = {}; + private origViews: { [key: string]: ViewObject } = {}; + public tree: TreeBranch[]; + public treeOptions: AngularUITree.ICallbacks; + private seenViewIds: View2NodeMap = {}; + public saveClass: string = ''; + private saving: boolean = false; //injectables - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; static $inject = [ '$state', @@ -53,7 +53,7 @@ class ReorderController implements IComponentController { 'AppUtilsService', 'TreeService', 'EventService', - ] + ]; constructor( private $state: StateService, @@ -68,12 +68,12 @@ class ReorderController implements IComponentController { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); this.mmsDocument.then( (doc) => { - this.doc = doc - const name = this.doc.name ? this.doc.name : this.doc.id + this.doc = doc; + const name = this.doc.name ? this.doc.name : this.doc.id; this.viewIds2node[this.doc.id] = { label: name, @@ -81,7 +81,7 @@ class ReorderController implements IComponentController { data: this.doc, aggr: 'composite', children: [], - } + }; this.viewSvc .handleChildViews( @@ -96,43 +96,43 @@ class ReorderController implements IComponentController { ) .then( (docNode: TreeBranch) => { - let num = 1 + let num = 1; docNode.children.forEach((node) => { - this.updateNumber(node, `${num}`, 'old') - this.updateNumber(node, `${num}`, 'new') - num++ - }) - this.tree = [docNode] + this.updateNumber(node, `${num}`, 'old'); + this.updateNumber(node, `${num}`, 'new'); + num++; + }); + this.tree = [docNode]; }, (reason) => { - this.growl.error('Error Getting Child Views: ' + reason.message) + this.growl.error('Error Getting Child Views: ' + reason.message); } - ) + ); }, (reason) => { - this.growl.error('Error Getting Child Views: ' + reason.message) + this.growl.error('Error Getting Child Views: ' + reason.message); } - ) + ); this.subs.push( this.eventSvc.$on('foobar', () => { - const root = this.tree - console.log(root) + const root = this.tree; + console.log(root); }) - ) + ); this.treeOptions = { dropped: (e): void => { void this.$timeout(() => { for (let i = 0; i < this.tree.length; i++) { - const root = this.tree[i] - root.new = '' - let num = 1 + const root = this.tree[i]; + root.new = ''; + let num = 1; for (let j = 0; j < root.children.length; j++) { - this.updateNumber(root.children[j], `${num}`, 'new') - num++ + this.updateNumber(root.children[j], `${num}`, 'new'); + num++; } } - }, 1) + }, 1); }, // dragStop: (e) => { // for (let i = 0; i < this.tree.length; i++) { @@ -149,23 +149,23 @@ class ReorderController implements IComponentController { //Do Nothing }, accept: (sourceNodeScope: VeTreeNodeScope, destNodeScope: VeTreeNodeScope, destIndex): boolean => { - if (destNodeScope.$element.hasClass('root')) return false //don't allow moving to outside doc - return destNodeScope.node.aggr != 'none' + if (destNodeScope.$element.hasClass('root')) return false; //don't allow moving to outside doc + return destNodeScope.node.aggr != 'none'; }, - } + }; } public updateNumber = (node: TreeBranch, curSection: string, key: string): void => { - node[key] = curSection - let num = 1 + node[key] = curSection; + let num = 1; for (let i = 0; i < node.children.length; i++) { - this.updateNumber(node.children[i], `${curSection}.${num}`, key) - num++ + this.updateNumber(node.children[i], `${curSection}.${num}`, key); + num++; } - } + }; public handleSingleView = (v: ViewObject, aggr: string, propId: string): TreeBranch => { - let curNode: TreeBranch = this.viewIds2node[v.id] + let curNode: TreeBranch = this.viewIds2node[v.id]; if (!curNode) { curNode = { label: v.name ? v.name : v.id, @@ -174,44 +174,44 @@ class ReorderController implements IComponentController { propertyId: propId, type: v.type, children: [], - } - this.viewIds2node[v.id] = curNode + }; + this.viewIds2node[v.id] = curNode; } - this.origViews[v.id] = v - return curNode - } + this.origViews[v.id] = v; + return curNode; + }; public handleChildren = (curNode: TreeBranch, childNodes: TreeBranch[]): void => { - const newChildNodes: TreeBranch[] = [] + const newChildNodes: TreeBranch[] = []; for (let i = 0; i < childNodes.length; i++) { - const node: TreeBranch = childNodes[i] + const node: TreeBranch = childNodes[i]; if (this.seenViewIds[node.data.id]) { - return + return; } - this.seenViewIds[node.data.id] = node - newChildNodes.push(node) + this.seenViewIds[node.data.id] = node; + newChildNodes.push(node); } - curNode.children.push(...newChildNodes) - } + curNode.children.push(...newChildNodes); + }; public save = (): void => { if (this.saving) { - this.growl.info('please wait') - return + this.growl.info('please wait'); + return; } if (this.tree.length > 1 || this.tree[0].data.id !== this.doc.id) { - this.growl.error('Views cannot be re-ordered outside the context of the current document.') - return + this.growl.error('Views cannot be re-ordered outside the context of the current document.'); + return; } - this.saving = true - this.saveClass = 'fa fa-spin fa-spinner' - const toSave: ViewObject[] = [] + this.saving = true; + this.saveClass = 'fa fa-spin fa-spinner'; + const toSave: ViewObject[] = []; for (const [id, node] of Object.entries(this.viewIds2node)) { if (node.aggr == 'none') { //cannot process views whose aggr is none since their children are not shown - return + return; } - const childViews: ViewObject[] = [] + const childViews: ViewObject[] = []; for (let i = 0; i < node.children.length; i++) { childViews.push({ id: node.children[i].data.id, @@ -220,9 +220,9 @@ class ReorderController implements IComponentController { _projectId: node.data._projectId, _refId: node.data._refId, type: node.data.type, - }) + }); } - const orig = this.origViews[id] + const orig = this.origViews[id]; if ( ((!orig._childViews || orig._childViews.length === 0) && childViews.length > 0) || (orig._childViews && !_.isEqual(orig._childViews, childViews)) @@ -234,55 +234,55 @@ class ReorderController implements IComponentController { _projectId: orig._projectId, _refId: orig._refId, type: orig.type, - }) + }); } } if (toSave.length === 0) { - this.growl.info('No changes to save!') - this.saving = false - this.saveClass = '' - return + this.growl.info('No changes to save!'); + this.saving = false; + this.saveClass = ''; + return; } this.elementSvc .updateElements(toSave, true) .then( () => { - this.growl.success('Reorder Successful') - this.navigate(true) + this.growl.success('Reorder Successful'); + this.navigate(true); }, (response) => { - const reason = response.data.failedRequests[0] - const errorMessage = reason.message + const reason = response.data.failedRequests[0]; + const errorMessage = reason.message; if (reason.status === 409) { - this.growl.error("There's a conflict in the views you're trying to change!") + this.growl.error("There's a conflict in the views you're trying to change!"); } else { - this.growl.error(errorMessage) + this.growl.error(errorMessage); } } ) .finally(() => { - this.saveClass = '' - this.saving = false - }) - } + this.saveClass = ''; + this.saving = false; + }); + }; public cancel = (): void => { - this.navigate(false) - } + this.navigate(false); + }; public navigate = (reload: boolean): void => { - const curBranch = this.treeSvc.getSelectedBranch() + const curBranch = this.treeSvc.getSelectedBranch(); if (!curBranch) { - void this.$state.go('main.project.ref.view.present', {}, { reload: true }) + void this.$state.go('main.project.ref.view.present', {}, { reload: true }); } else { - let goToId: string = curBranch.data.id + let goToId: string = curBranch.data.id; if (curBranch.type !== 'section' && curBranch.type !== 'view') { - goToId = curBranch.viewId ? curBranch.viewId : '' + goToId = curBranch.viewId ? curBranch.viewId : ''; } - void this.$state.go('main.project.ref.view.present', { viewId: goToId }, { reload: reload }) + void this.$state.go('main.project.ref.view.present', { viewId: goToId }, { reload: reload }); } - } + }; } const ReorderComponent: VeComponentOptions = { @@ -315,6 +315,6 @@ const ReorderComponent: VeComponentOptions = { mmsDocument: '<', }, controller: ReorderController, -} +}; -veApp.component(ReorderComponent.selector, ReorderComponent) +veApp.component(ReorderComponent.selector, ReorderComponent); diff --git a/src/ve-app/pane-center/search.component.ts b/src/ve-app/pane-center/search.component.ts index ebe59ffa5..c59025b28 100644 --- a/src/ve-app/pane-center/search.component.ts +++ b/src/ve-app/pane-center/search.component.ts @@ -1,23 +1,23 @@ -import { StateService } from '@uirouter/angularjs' +import { StateService } from '@uirouter/angularjs'; -import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service' -import { veCoreEvents } from '@ve-core/events' -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service'; +import { veCoreEvents } from '@ve-core/events'; +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { ElementObject, ParamsObject } from '@ve-types/mms' -import { VeSearchOptions } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { ElementObject, ParamsObject } from '@ve-types/mms'; +import { VeSearchOptions } from '@ve-types/view-editor'; class SearchController { - params: ParamsObject + params: ParamsObject; - searchContentLoading: boolean = true - searchOptions: VeSearchOptions + searchContentLoading: boolean = true; + searchOptions: VeSearchOptions; - static $inject = ['$state', 'ContentWindowService', 'RootScopeService', 'EventService'] + static $inject = ['$state', 'ContentWindowService', 'RootScopeService', 'EventService']; constructor( private $state: StateService, @@ -27,10 +27,10 @@ class SearchController { ) {} $onInit(): void { - this.searchContentLoading = false + this.searchContentLoading = false; - this.contentWindowSvc.toggleLeftPane(true) - this.rootScopeSvc.veHideLeft(true) + this.contentWindowSvc.toggleLeftPane(true); + this.rootScopeSvc.veHideLeft(true); this.searchOptions = { emptyDocTxt: 'This field is empty.', @@ -44,10 +44,10 @@ class SearchController { projectId: elementOb._projectId, refId: elementOb._refId, commitId: 'latest', - } - this.eventSvc.$broadcast('element.selected', data) + }; + this.eventSvc.$broadcast('element.selected', data); if (typeof this.rootScopeSvc.rightPaneClosed() === 'boolean' && this.rootScopeSvc.rightPaneClosed()) - this.eventSvc.$broadcast('right-pane.toggle', false) + this.eventSvc.$broadcast('right-pane.toggle', false); }, relatedCallback: (doc, view, elem): void => { //siteId, documentId, viewId) { @@ -57,9 +57,9 @@ class SearchController { viewId: view.id, refId: doc._refId, keywords: undefined, - }) + }); }, - } + }; } } @@ -81,6 +81,6 @@ const SearchComponent: VeComponentOptions = { field: '<', }, controller: SearchController, -} +}; -veApp.component(SearchComponent.selector, SearchComponent) +veApp.component(SearchComponent.selector, SearchComponent); diff --git a/src/ve-app/pane-center/services/ContentWindow.service.ts b/src/ve-app/pane-center/services/ContentWindow.service.ts index df302e876..37febfe3f 100644 --- a/src/ve-app/pane-center/services/ContentWindow.service.ts +++ b/src/ve-app/pane-center/services/ContentWindow.service.ts @@ -1,21 +1,21 @@ -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; export class ContentWindowService { - static $inject = ['RootScopeService', 'EventService'] + static $inject = ['RootScopeService', 'EventService']; constructor(private rootScopeSvc: RootScopeService, private eventSvc: EventService) {} public toggleLeftPane = (closed): void => { if (closed && !this.rootScopeSvc.leftPaneClosed()) { - this.eventSvc.$broadcast('left-pane.toggle', true) + this.eventSvc.$broadcast('left-pane.toggle', true); } if (!closed && this.rootScopeSvc.leftPaneClosed()) { - this.eventSvc.$broadcast('left-pane.toggle', false) + this.eventSvc.$broadcast('left-pane.toggle', false); } - } + }; } -veApp.service('ContentWindowService', ContentWindowService) +veApp.service('ContentWindowService', ContentWindowService); diff --git a/src/ve-app/pane-center/slideshow.component.ts b/src/ve-app/pane-center/slideshow.component.ts index bded4d1b1..182e11318 100644 --- a/src/ve-app/pane-center/slideshow.component.ts +++ b/src/ve-app/pane-center/slideshow.component.ts @@ -1,19 +1,19 @@ -import { HookResult, Ng1Controller, StateService, UIRouterGlobals } from '@uirouter/angularjs' -import { Transition } from '@uirouter/core' - -import { AppUtilsService, ResolveService } from '@ve-app/main/services' -import { pane_center_buttons } from '@ve-app/pane-center/pane-center-buttons.config' -import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service' -import { TreeService } from '@ve-components/trees' -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' -import { veCoreEvents } from '@ve-core/events' -import { RootScopeService, ShortUrlService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { PermissionsService, URLService, ViewApi } from '@ve-utils/mms-api-client' - -import { veApp } from '@ve-app' - -import { VeComponentOptions, VeQService } from '@ve-types/angular' +import { HookResult, Ng1Controller, StateService, UIRouterGlobals } from '@uirouter/angularjs'; +import { Transition } from '@uirouter/core'; + +import { AppUtilsService, ResolveService } from '@ve-app/main/services'; +import { pane_center_buttons } from '@ve-app/pane-center/pane-center-buttons.config'; +import { ContentWindowService } from '@ve-app/pane-center/services/ContentWindow.service'; +import { TreeService } from '@ve-components/trees'; +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; +import { veCoreEvents } from '@ve-core/events'; +import { RootScopeService, ShortUrlService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { PermissionsService, URLService, ViewApi } from '@ve-utils/mms-api-client'; + +import { veApp } from '@ve-app'; + +import { VeComponentOptions, VeQService } from '@ve-types/angular'; import { DocumentObject, ElementObject, @@ -22,7 +22,7 @@ import { ProjectObject, RefObject, ViewObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * Note: This controller is intended for navigating between 'views' and 'sections' only. If you wish to navigate between @@ -30,38 +30,38 @@ import { */ class SlideshowController implements angular.IComponentController, Ng1Controller { //Bindings - mmsParams: ParamsObject - mmsProject: ProjectObject - mmsRef: RefObject - mmsGroup: GroupObject - mmsDocument: DocumentObject - mmsView: ViewObject - - subs: Rx.IDisposable[] - vidLink: boolean - viewContentLoading: boolean - init: boolean = false - - public bbApi: ButtonBarApi - bbId = 'view-ctrl' - bars: string[] = [] + mmsParams: ParamsObject; + mmsProject: ProjectObject; + mmsRef: RefObject; + mmsGroup: GroupObject; + mmsDocument: DocumentObject; + mmsView: ViewObject; + + subs: Rx.IDisposable[]; + vidLink: boolean; + viewContentLoading: boolean; + init: boolean = false; + + public bbApi: ButtonBarApi; + bbId = 'view-ctrl'; + bars: string[] = []; comments: { - count: number - lastCommented: string - lastCommentedBy: string - map: object + count: number; + lastCommented: string; + lastCommentedBy: string; + map: object; } = { count: 0, lastCommented: null, lastCommentedBy: '', map: {}, - } - dynamicPopover: { templateUrl: string; title: string } - shortUrl: string - viewApi: ViewApi - number: string - private viewId: string - private params: ParamsObject + }; + dynamicPopover: { templateUrl: string; title: string }; + shortUrl: string; + viewApi: ViewApi; + number: string; + private viewId: string; + private params: ParamsObject; static $inject = [ '$q', @@ -86,7 +86,7 @@ class SlideshowController implements angular.IComponentController, Ng1Controller 'TreeService', 'EventService', 'ButtonBarService', - ] + ]; constructor( public $q: VeQService, @@ -114,24 +114,24 @@ class SlideshowController implements angular.IComponentController, Ng1Controller ) {} $onInit(): void { - this.params = this.mmsParams - this.rootScopeSvc.veFullDocMode(false) - this.rootScopeSvc.veHideLeft(false) - this.rootScopeSvc.veHideRight(false) - this.eventSvc.$init(this) + this.params = this.mmsParams; + this.rootScopeSvc.veFullDocMode(false); + this.rootScopeSvc.veHideLeft(false); + this.rootScopeSvc.veHideRight(false); + this.eventSvc.$init(this); - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, pane_center_buttons) + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, pane_center_buttons); //Init/Reset Tree Updated Subject - this.eventSvc.resolve(TreeService.events.UPDATED, false) + this.eventSvc.resolve(TreeService.events.UPDATED, false); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEVIEWCONTENTLOADING, (newValue) => { - this.viewContentLoading = newValue + this.viewContentLoading = newValue; }) - ) + ); - this.initView() + this.initView(); this.subs.push( this.eventSvc.$on(this.bbId, (data) => { @@ -139,114 +139,135 @@ class SlideshowController implements angular.IComponentController, Ng1Controller this.bbApi.toggleButton( 'show-comments', this.rootScopeSvc.veCommentsOn(!this.rootScopeSvc.veCommentsOn()) - ) - return + ); + return; } else if (data.clicked === 'show-numbering') { this.bbApi.toggleButton( 'show-numbering', this.rootScopeSvc.veNumberingOn(!this.rootScopeSvc.veNumberingOn()) - ) - return + ); + return; } else if (data.clicked === 'show-elements') { this.bbApi.toggleButton( 'show-elements', this.rootScopeSvc.veElementsOn(!this.rootScopeSvc.veElementsOn()) - ) + ); if (!this.rootScopeSvc.veElementsOn() && this.rootScopeSvc.veEditMode()) { - this.bbApi.toggleButton('show-edits', false) - this.rootScopeSvc.veEditMode(false) + this.bbApi.toggleButton('show-edits', false); + this.rootScopeSvc.veEditMode(false); } - return + return; } else if (data.clicked === 'show-edits') { - this.bbApi.toggleButton('show-edits', this.rootScopeSvc.veEditMode(!this.rootScopeSvc.veEditMode())) + this.bbApi.toggleButton( + 'show-edits', + this.rootScopeSvc.veEditMode(!this.rootScopeSvc.veEditMode()) + ); if (this.rootScopeSvc.veElementsOn() !== this.rootScopeSvc.veEditMode()) { - this.bbApi.toggleButton('show-elements', this.rootScopeSvc.veEditMode()) - this.rootScopeSvc.veElementsOn(this.rootScopeSvc.veEditMode()) + this.bbApi.toggleButton('show-elements', this.rootScopeSvc.veEditMode()); + this.rootScopeSvc.veElementsOn(this.rootScopeSvc.veEditMode()); } - return + return; } else if (data.clicked === 'center-previous') { this.treeSvc.getPrevBranch(this.treeSvc.getSelectedBranch(), ['view', 'section']).then( (prev) => { - this.bbApi.toggleButtonSpinner('center-previous') + this.bbApi.toggleButtonSpinner('center-previous'); this.treeSvc.selectBranch(prev).catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) - this.bbApi.toggleButtonSpinner('center-previous') + this.growl.error(TreeService.treeError(reason)); + }); + this.bbApi.toggleButtonSpinner('center-previous'); }, (reason) => { - if (reason.status === 200) this.growl.info(reason.message) - else this.growl.error(reason.message) + if (reason.status === 200) this.growl.info(reason.message); + else this.growl.error(reason.message); } - ) - return + ); + return; } else if (data.clicked === 'center-next') { this.treeSvc.getNextBranch(this.treeSvc.getSelectedBranch(), ['view', 'section']).then( (next) => { - this.bbApi.toggleButtonSpinner('center-next') + this.bbApi.toggleButtonSpinner('center-next'); this.treeSvc.selectBranch(next).catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) - this.bbApi.toggleButtonSpinner('center-next') + this.growl.error(TreeService.treeError(reason)); + }); + this.bbApi.toggleButtonSpinner('center-next'); }, (reason) => { - if (reason.status === 200) this.growl.info(reason.message) - else this.growl.error(reason.message) + if (reason.status === 200) this.growl.info(reason.message); + else this.growl.error(reason.message); } - ) - return + ); + return; } else if (data.clicked === 'convert-pdf') { - if (this.isPageLoading()) return - void this.appUtilsSvc.printModal(angular.element('#print-div'), this.mmsView, this.mmsRef, false, 3) - return + if (this.isPageLoading()) return; + void this.appUtilsSvc.printModal( + angular.element('#print-div'), + this.mmsView, + this.mmsRef, + false, + 3 + ); + return; } else if (data.clicked === 'print') { - if (this.isPageLoading()) return - void this.appUtilsSvc.printModal(angular.element('#print-div'), this.mmsView, this.mmsRef, false, 1) - return + if (this.isPageLoading()) return; + void this.appUtilsSvc.printModal( + angular.element('#print-div'), + this.mmsView, + this.mmsRef, + false, + 1 + ); + return; } else if (data.clicked === 'word') { - if (this.isPageLoading()) return - void this.appUtilsSvc.printModal(angular.element('#print-div'), this.mmsView, this.mmsRef, false, 2) - return + if (this.isPageLoading()) return; + void this.appUtilsSvc.printModal( + angular.element('#print-div'), + this.mmsView, + this.mmsRef, + false, + 2 + ); + return; } else if (data.clicked === 'tabletocsv') { - if (this.isPageLoading()) return - this.appUtilsSvc.tableToCsv(angular.element('#print-div'), false) - return + if (this.isPageLoading()) return; + this.appUtilsSvc.tableToCsv(angular.element('#print-div'), false); + return; } else if (data.clicked === 'refresh-numbering') { // TODO - return + return; } }) - ) + ); } uiOnParamsChanged(newValues: ParamsObject, $transition$: Transition): void { if (newValues.viewId && newValues.viewId !== this.params.viewId) - this.initView($transition$.params() as ParamsObject) + this.initView($transition$.params() as ParamsObject); } uiCanExit(transition: Transition): HookResult { //Do nothing } initView = (params?: ParamsObject): void => { - this.rootScopeSvc.veViewContentLoading(true) + this.rootScopeSvc.veViewContentLoading(true); if (params) { - this.params = params - this.viewId = params.viewId + this.params = params; + this.viewId = params.viewId; } else if (this.mmsDocument || this.mmsView) { - this.viewId = this.mmsView ? this.mmsView.id : this.mmsDocument.id + this.viewId = this.mmsView ? this.mmsView.id : this.mmsDocument.id; } else { - return + return; } - this.rootScopeSvc.veViewContentLoading(false) + this.rootScopeSvc.veViewContentLoading(false); - this.vidLink = false //whether to have go to document link + this.vidLink = false; //whether to have go to document link if ( this.$state.includes('main.project.ref.portal.preview') && this.mmsDocument && this.mmsDocument.id.indexOf('_cover') < 0 ) { - this.vidLink = true + this.vidLink = true; } this.shortUrl = this.shortUrlSvc.getShortUrl({ @@ -255,7 +276,7 @@ class SlideshowController implements angular.IComponentController, Ng1Controller viewId: this.params.viewId && !this.params.documentId.endsWith('_cover') ? this.params.viewId : '', projectId: this.params.projectId, refId: this.params.refId, - }) + }); if (this.$state.includes('main.project.ref')) { const data = { @@ -266,52 +287,52 @@ class SlideshowController implements angular.IComponentController, Ng1Controller refId: this.mmsRef.id, refType: this.mmsRef.type, refresh: this.$uiRouterGlobals.transition.from().name === '', - } - this.eventSvc.$broadcast('view.selected', data) + }; + this.eventSvc.$broadcast('view.selected', data); } - this.contentWindowSvc.toggleLeftPane(false) + this.contentWindowSvc.toggleLeftPane(false); - this.rootScopeSvc.veNumberingOn(true) + this.rootScopeSvc.veNumberingOn(true); // Share URL button settings - this.dynamicPopover = this.shortUrlSvc.dynamicPopover + this.dynamicPopover = this.shortUrlSvc.dynamicPopover; this.viewApi = { elementClicked: this.elementClicked, elementTranscluded: this.elementTranscluded, - } - } + }; + }; $onDestroy(): void { - this.eventSvc.$destroy(this.subs) - this.buttonBarSvc.destroy(this.bbId) + this.eventSvc.$destroy(this.subs); + this.buttonBarSvc.destroy(this.bbId); } public bbInit = (api: ButtonBarApi): void => { if (this.mmsRef.type === 'Branch') { - api.addButton(this.buttonBarSvc.getButtonBarButton('show-edits')) + api.addButton(this.buttonBarSvc.getButtonBarButton('show-edits')); api.setPermission( 'show-edits', this.permissionsSvc.hasBranchEditPermission(this.mmsProject.id, this.mmsRef.id) - ) - api.toggleButton('show-edits', this.rootScopeSvc.veEditMode()) + ); + api.toggleButton('show-edits', this.rootScopeSvc.veEditMode()); this.hotkeys.bindTo(this.$scope).add({ combo: 'alt+d', description: 'toggle edit mode', callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-edits', - }) + }); }, - }) + }); } - api.addButton(this.buttonBarSvc.getButtonBarButton('show-elements')) - api.toggleButton('show-elements', this.rootScopeSvc.veElementsOn()) - api.addButton(this.buttonBarSvc.getButtonBarButton('show-comments')) - api.toggleButton('show-comments', this.rootScopeSvc.veCommentsOn()) - api.addButton(this.buttonBarSvc.getButtonBarButton('show-numbering')) - api.toggleButton('show-numbering', this.rootScopeSvc.veNumberingOn()) + api.addButton(this.buttonBarSvc.getButtonBarButton('show-elements')); + api.toggleButton('show-elements', this.rootScopeSvc.veElementsOn()); + api.addButton(this.buttonBarSvc.getButtonBarButton('show-comments')); + api.toggleButton('show-comments', this.rootScopeSvc.veCommentsOn()); + api.addButton(this.buttonBarSvc.getButtonBarButton('show-numbering')); + api.toggleButton('show-numbering', this.rootScopeSvc.veNumberingOn()); // Set hotkeys for toolbar this.hotkeys @@ -322,7 +343,7 @@ class SlideshowController implements angular.IComponentController, Ng1Controller callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-comments', - }) + }); }, }) .add({ @@ -331,16 +352,16 @@ class SlideshowController implements angular.IComponentController, Ng1Controller callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-elements', - }) + }); }, - }) + }); if (this.$state.includes('**.present.**')) { - api.addButton(this.buttonBarSvc.getButtonBarButton('refresh-numbering')) - api.addButton(this.buttonBarSvc.getButtonBarButton('print')) - api.addButton(this.buttonBarSvc.getButtonBarButton('export')) - api.addButton(this.buttonBarSvc.getButtonBarButton('center-previous')) - api.addButton(this.buttonBarSvc.getButtonBarButton('center-next')) + api.addButton(this.buttonBarSvc.getButtonBarButton('refresh-numbering')); + api.addButton(this.buttonBarSvc.getButtonBarButton('print')); + api.addButton(this.buttonBarSvc.getButtonBarButton('export')); + api.addButton(this.buttonBarSvc.getButtonBarButton('center-previous')); + api.addButton(this.buttonBarSvc.getButtonBarButton('center-next')); // Set hotkeys for toolbar this.hotkeys .bindTo(this.$scope) @@ -350,7 +371,7 @@ class SlideshowController implements angular.IComponentController, Ng1Controller callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'center-next', - }) + }); }, }) .add({ @@ -359,35 +380,35 @@ class SlideshowController implements angular.IComponentController, Ng1Controller callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'center-previous', - }) + }); }, - }) + }); } else { - api.addButton(this.buttonBarSvc.getButtonBarButton('export')) + api.addButton(this.buttonBarSvc.getButtonBarButton('export')); } - } + }; public copyToClipboard = ($event: JQuery.ClickEvent): void => { this.shortUrlSvc.copyToClipboard(this.$element, $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }) + this.growl.info('Copied to clipboard!', { ttl: 2000 }); }, (err) => { - this.growl.error('Unable to copy: ' + err.message) + this.growl.error('Unable to copy: ' + err.message); } - ) - } + ); + }; public elementTranscluded = (elementOb: ElementObject, type): void => { if (type === 'Comment' && !this.comments.map.hasOwnProperty(elementOb.id)) { - this.comments.map[elementOb.id] = elementOb - this.comments.count++ + this.comments.map[elementOb.id] = elementOb; + this.comments.count++; if (elementOb._modified > this.comments.lastCommented) { - this.comments.lastCommented = elementOb._modified - this.comments.lastCommentedBy = elementOb._modifier + this.comments.lastCommented = elementOb._modified; + this.comments.lastCommentedBy = elementOb._modifier; } } - } + }; public elementClicked = (elementOb: ElementObject): void => { const data = { @@ -396,17 +417,17 @@ class SlideshowController implements angular.IComponentController, Ng1Controller projectId: elementOb._projectId, refId: elementOb._refId, commitId: 'latest', - } - this.eventSvc.$broadcast('element.selected', data) - } + }; + this.eventSvc.$broadcast('element.selected', data); + }; public isPageLoading = (): boolean => { if (this.$element.find('.isLoading').length > 0) { - this.growl.warning('Still loading!') - return true + this.growl.warning('Still loading!'); + return true; } - return false - } + return false; + }; } /* Controllers */ @@ -464,6 +485,6 @@ const SlideshowComponent: VeComponentOptions = { mmsView: '<', }, controller: SlideshowController, -} +}; -veApp.component(SlideshowComponent.selector, SlideshowComponent) +veApp.component(SlideshowComponent.selector, SlideshowComponent); diff --git a/src/ve-app/pane-left/index.ts b/src/ve-app/pane-left/index.ts index cd20e6f1d..054a9a58a 100644 --- a/src/ve-app/pane-left/index.ts +++ b/src/ve-app/pane-left/index.ts @@ -1,2 +1,2 @@ -import './left-pane.component' -import './left-toolbar.component' +import './left-pane.component'; +import './left-toolbar.component'; diff --git a/src/ve-app/pane-left/left-buttons.config.ts b/src/ve-app/pane-left/left-buttons.config.ts index 828562d07..3339eb147 100644 --- a/src/ve-app/pane-left/left-buttons.config.ts +++ b/src/ve-app/pane-left/left-buttons.config.ts @@ -1,5 +1,5 @@ -import { IButtonBarButton } from '@ve-core/button-bar' -import { IToolBarButton } from '@ve-core/toolbar' +import { IButtonBarButton } from '@ve-core/button-bar'; +import { IToolBarButton } from '@ve-core/toolbar'; export const left_default_toolbar: IToolBarButton[] = [ { @@ -63,9 +63,9 @@ export const left_default_toolbar: IToolBarButton[] = [ spinner: false, enabledFor: ['**.present.**'], }, -] +]; -export const left_dynamic_toolbar: IToolBarButton[] = [] +export const left_dynamic_toolbar: IToolBarButton[] = []; export const left_default_buttons: IButtonBarButton[] = [ { @@ -187,4 +187,4 @@ export const left_default_buttons: IButtonBarButton[] = [ }, enabledFor: ['**.present.**'], }, -] +]; diff --git a/src/ve-app/pane-left/left-pane.component.ts b/src/ve-app/pane-left/left-pane.component.ts index 2ac2d8aea..3a8e83966 100644 --- a/src/ve-app/pane-left/left-pane.component.ts +++ b/src/ve-app/pane-left/left-pane.component.ts @@ -1,23 +1,23 @@ -import { IPane } from '@openmbee/pane-layout' -import { IPaneManagerService } from '@openmbee/pane-layout/lib/PaneManagerService' -import { StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs' - -import { veAppEvents } from '@ve-app/events' -import { AppUtilsService } from '@ve-app/main/services' -import { TreeService } from '@ve-components/trees' -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' -import { veCoreEvents } from '@ve-core/events' -import { ConfirmDeleteModalResolveFn } from '@ve-core/modals' -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ApiService, ElementService, PermissionsService, ProjectService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' - -import { veApp } from '@ve-app' - -import { left_default_buttons } from './left-buttons.config' - -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { IPane } from '@openmbee/pane-layout'; +import { IPaneManagerService } from '@openmbee/pane-layout/lib/PaneManagerService'; +import { StateService, TransitionService, UIRouterGlobals } from '@uirouter/angularjs'; + +import { veAppEvents } from '@ve-app/events'; +import { AppUtilsService } from '@ve-app/main/services'; +import { TreeService } from '@ve-components/trees'; +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; +import { veCoreEvents } from '@ve-core/events'; +import { ConfirmDeleteModalResolveFn } from '@ve-core/modals'; +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ApiService, ElementService, PermissionsService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; + +import { veApp } from '@ve-app'; + +import { left_default_buttons } from './left-buttons.config'; + +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; import { ElementObject, ElementsRequest, @@ -28,37 +28,37 @@ import { RefObject, RefsResponse, ViewObject, -} from '@ve-types/mms' -import { TreeApi, TreeBranch } from '@ve-types/tree' -import { VeModalService } from '@ve-types/view-editor' +} from '@ve-types/mms'; +import { TreeApi, TreeBranch } from '@ve-types/tree'; +import { VeModalService } from '@ve-types/view-editor'; class LeftPaneController implements angular.IComponentController { //Scope - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; - private $pane: IPane + private $pane: IPane; - public bbApi: ButtonBarApi - public bbSize: string - public bars: string[] - private headerSize: string = '83px' - protected squishSize: number = 250 + public bbApi: ButtonBarApi; + public bbSize: string; + public bars: string[]; + private headerSize: string = '83px'; + protected squishSize: number = 250; //Bindings - private mmsProject: ProjectObject - private mmsRef: RefObject - private mmsRoot: ElementObject + private mmsProject: ProjectObject; + private mmsRef: RefObject; + private mmsRoot: ElementObject; //Tree Api - private treeApi: TreeApi + private treeApi: TreeApi; //Local Variables - toolbarId: string = 'left-toolbar' - buttonId: string = 'tree-button-bar' + toolbarId: string = 'left-toolbar'; + buttonId: string = 'tree-button-bar'; - schema = 'cameo' - filterInputPlaceholder = 'Filter' - treeFilter = '' + schema = 'cameo'; + filterInputPlaceholder = 'Filter'; + treeFilter = ''; static $inject = [ '$q', @@ -86,7 +86,7 @@ class LeftPaneController implements angular.IComponentController { 'RootScopeService', 'EventService', 'ButtonBarService', - ] + ]; constructor( private $q: VeQService, @@ -118,75 +118,75 @@ class LeftPaneController implements angular.IComponentController { $onInit(): void { //Init/Reset Tree Updated Subject - this.eventSvc.resolve(TreeService.events.UPDATED, false) + this.eventSvc.resolve(TreeService.events.UPDATED, false); - this.transitionCallback() + this.transitionCallback(); - this.eventSvc.$init(this) + this.eventSvc.$init(this); - this.bbSize = '83px' + this.bbSize = '83px'; this.$transitions.onSuccess({}, () => { - this.transitionCallback() - }) + this.transitionCallback(); + }); //Init Pane Toggle Controls - this.rootScopeSvc.leftPaneClosed(this.$pane.closed) + this.rootScopeSvc.leftPaneClosed(this.$pane.closed); this.subs.push( this.$pane.$toggled.subscribe(() => { - this.rootScopeSvc.leftPaneClosed(this.$pane.closed) + this.rootScopeSvc.leftPaneClosed(this.$pane.closed); }) - ) + ); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.LEFTPANECLOSED, (paneClosed) => { if (paneClosed !== this.$pane.closed) { - this.$pane.toggle() + this.$pane.toggle(); } }) - ) + ); // Start listening to change events this.subs.push( this.eventSvc.$on('view.selected', this.changeData), this.eventSvc.$on('view.deleted', (data) => { - let goto = '^.currentState' - let documentId = this.treeApi.rootId - let viewId: string + let goto = '^.currentState'; + let documentId = this.treeApi.rootId; + let viewId: string; if (this.$state.includes('**.portal.**')) { if (data.parentBranch) { - documentId = data.parentBranch.data.id + documentId = data.parentBranch.data.id; } else { - goto = 'main.project.ref.portal' - documentId = null + goto = 'main.project.ref.portal'; + documentId = null; } } else if (this.$state.includes('**.present.**')) { if (data.prevBranch) { - viewId = data.prevBranch.viewId ? data.prevBranch.viewId : data.prevBranch.data.id + viewId = data.prevBranch.viewId ? data.prevBranch.viewId : data.prevBranch.data.id; } else if (data.parentBranch) { - viewId = data.parentBranch.viewId ? data.parentBranch.viewId : data.parentBranch.data.id + viewId = data.parentBranch.viewId ? data.parentBranch.viewId : data.parentBranch.data.id; } } void this.$state.go(goto, { documentId, viewId, search: undefined, - }) + }); }), this.eventSvc.$on('presentation.deleted', (data) => { this.treeSvc.getBranch(data).then( (branch) => { this.treeSvc.removeBranch(branch).catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); }, () => { - this.growl.error('Deleted branch not found') + this.growl.error('Deleted branch not found'); } - ) + ); }) - ) + ); /* this.subs.push( this.eventSvc.$on('tree.ready', () => { @@ -207,58 +207,58 @@ class LeftPaneController implements angular.IComponentController { }) ) */ - this.bbApi = this.buttonBarSvc.initApi(this.buttonId, this.bbInit, left_default_buttons) + this.bbApi = this.buttonBarSvc.initApi(this.buttonId, this.bbInit, left_default_buttons); this.buttonBarSvc.waitForApi(this.buttonId).then( (api) => { - this.bbApi = api + this.bbApi = api; this.subs.push( this.eventSvc.$on(this.buttonId, (data) => { switch (data.clicked) { case 'tree-reorder-view': { - this.bbApi.toggleButton('tree-full-document', false) + this.bbApi.toggleButton('tree-full-document', false); void this.$state.go('main.project.ref.view.reorder', { search: undefined, - }) - break + }); + break; } case 'tree-reorder-group': { - void this.$state.go('main.project.ref.groupReorder') - break + void this.$state.go('main.project.ref.groupReorder'); + break; } case 'tree-full-document': { - this.fullDocMode() - break + this.fullDocMode(); + break; } case 'tree-refresh': { - this.reloadData() - break + this.reloadData(); + break; } case 'tree-delete': { - this.deleteItem() - break + this.deleteItem(); + break; } case 'tree-show-pe': { - this.bbApi.toggleButton('tree-show-pe') + this.bbApi.toggleButton('tree-show-pe'); } } }) - ) + ); }, (reason) => { - console.log(reason.message) + console.log(reason.message); } - ) + ); } $onDestroy(): void { - this.eventSvc.$destroy(this.subs) - this.buttonBarSvc.destroy(this.buttonId) + this.eventSvc.$destroy(this.subs); + this.buttonBarSvc.destroy(this.buttonId); } bbInit = (api: ButtonBarApi): void => { - api.buttons.length = 0 - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-expand')) - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-collapse')) + api.buttons.length = 0; + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-expand')); + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-collapse')); /*api.addButton(this.buttonBarSvc.getButtonBarButton('tree-add')) api.setPermission('tree-add', this.treeSvc.treeApi.refType !== 'Tag' && this.treeSvc.treeEditable) api.addButton(this.buttonBarSvc.getButtonBarButton('tree-delete')) @@ -277,26 +277,26 @@ class LeftPaneController implements angular.IComponentController { api.setPermission('tree-add.view', this.treeSvc.treeApi.refType !== 'Tag' && this.treeSvc.treeEditable) api.addButton(this.buttonBarSvc.getButtonBarButton('tree-reorder-view'))*/ - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-full-document')) - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-show-pe')) + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-full-document')); + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-show-pe')); //api.setPermission('tree-reorder-view', this.treeSvc.treeEditable) if (this.rootScopeSvc.veFullDocMode()) { - api.toggleButton('tree-full-document', true) + api.toggleButton('tree-full-document', true); } - api.addButton(this.buttonBarSvc.getButtonBarButton('tree-refresh')) + api.addButton(this.buttonBarSvc.getButtonBarButton('tree-refresh')); api.checkActive((state: string) => { - return this.$state.includes(state) - }) - } + return this.$state.includes(state); + }); + }; changeData = (data: veCoreEvents.elementSelectedData): void => { //If the transitioning state detects a refresh, it will let us know to regenerate the tree - if (data.refresh) this.treeSvc.processedRoot = '' - const rootId = !data.rootId && data.elementId.endsWith('_cover') ? data.projectId + '_pm' : data.rootId - const elementId = data.elementId - const refId = data.refId - const projectId = data.projectId - const commitId = data.commitId ? data.commitId : null + if (data.refresh) this.treeSvc.processedRoot = ''; + const rootId = !data.rootId && data.elementId.endsWith('_cover') ? data.projectId + '_pm' : data.rootId; + const elementId = data.elementId; + const refId = data.refId; + const projectId = data.projectId; + const commitId = data.commitId ? data.commitId : null; if ((rootId && this.treeSvc.processedRoot !== rootId && rootId != '') || !this.treeApi) { new this.$q((resolve, reject) => { if ( @@ -306,10 +306,10 @@ class LeftPaneController implements angular.IComponentController { projectId != this.treeApi.projectId ) { this.projectSvc.getRef(refId, projectId).then((ref) => { - resolve(ref.type) - }, reject) + resolve(ref.type); + }, reject); } else { - resolve(this.treeApi.refType) + resolve(this.treeApi.refType); } }).then( (refType) => { @@ -320,24 +320,24 @@ class LeftPaneController implements angular.IComponentController { refType, refId, commitId, - } + }; - this.treeApi.onSelect = this.treeClickCallback - this.treeApi.onDblClick = this.treeDblClickCallback + this.treeApi.onSelect = this.treeClickCallback; + this.treeApi.onDblClick = this.treeDblClickCallback; - this.treeSvc.treeApi = this.treeApi + this.treeSvc.treeApi = this.treeApi; this.treeSvc.treeEditable = this.permissionsSvc.hasBranchEditPermission( this.mmsProject.id, this.mmsRef.id - ) + ); - this.treeApi.sectionNumbering = this.$state.includes('**.present.**') + this.treeApi.sectionNumbering = this.$state.includes('**.present.**'); this.treeApi.expandLevel = this.$state.includes('**.present.**') ? 3 : this.$state.includes('**.portal.**') ? 0 - : 1 - this.treeApi.sort = !this.$state.includes('**.present.**') + : 1; + this.treeApi.sort = !this.$state.includes('**.present.**'); new this.$q>((resolve, reject) => { if (this.$state.includes('**.present.**')) { @@ -345,7 +345,7 @@ class LeftPaneController implements angular.IComponentController { elementId: this.treeApi.rootId, refId: this.treeApi.refId, projectId: this.treeApi.projectId, - } + }; this.elementSvc.getElement(reqOb).then((root) => { // TODO this call is taking a long time that keeps the tree from being visible, need // to see if it can be moved to a resolve or faster @@ -368,49 +368,49 @@ class LeftPaneController implements angular.IComponentController { resolve(root) }, reject) } else {*/ - this.treeApi.numberingDepth = 0 - this.treeApi.numberingSeparator = '.' - this.treeApi.startChapter = 1 - resolve(root) + this.treeApi.numberingDepth = 0; + this.treeApi.numberingSeparator = '.'; + this.treeApi.startChapter = 1; + resolve(root); //} - }, reject) + }, reject); } else { - resolve(null) + resolve(null); } }).then( (root) => { - this.treeApi.elementId = elementId + this.treeApi.elementId = elementId; this.treeSvc.changeRoots(root).catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); } else { - this.treeApi.elementId = elementId + this.treeApi.elementId = elementId; this.treeSvc.changeElement().catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); } - } + }; transitionCallback = (): void => { this.buttonBarSvc.waitForApi(this.buttonId).then( (api) => { - this.bbApi = api + this.bbApi = api; }, (reason) => { - console.log(reason.message) + console.log(reason.message); } - ) - } + ); + }; treeClickCallback = (branch: TreeBranch): void => { if (this.$state.includes('**.portal.**')) { @@ -418,15 +418,15 @@ class LeftPaneController implements angular.IComponentController { void this.$state.go('main.project.ref.portal.preview', { preview: 'site_' + branch.data.id + '_cover', search: undefined, - }) + }); } else if (branch.type === 'view' || branch.type === 'snapshot') { void this.$state.go('main.project.ref.portal.preview', { preview: branch.data.id, search: undefined, - }) + }); } } else if (this.$state.includes('**.present.**')) { - const viewId = branch.type !== 'view' ? branch.viewId : branch.data.id + const viewId = branch.type !== 'view' ? branch.viewId : branch.data.id; // If clicked on a PE send the element.selected event for Tool Pane if (!(branch.type === 'view' || branch.type === 'section')) { @@ -435,8 +435,8 @@ class LeftPaneController implements angular.IComponentController { projectId: branch.data._projectId, refId: branch.data._refId, commitId: 'latest', - } - this.eventSvc.$broadcast('element.selected', data) + }; + this.eventSvc.$broadcast('element.selected', data); } void this.$state.go( @@ -445,9 +445,9 @@ class LeftPaneController implements angular.IComponentController { viewId, search: undefined, } - ) + ); } - } + }; treeDblClickCallback = (branch: TreeBranch): void => { if (this.$state.includes('**.portal.**')) { @@ -458,39 +458,39 @@ class LeftPaneController implements angular.IComponentController { documentId: branch.data.id, search: undefined, } - ) + ); } } else if (this.$state.includes('**.present.**')) { this.treeSvc.expandBranch(branch).catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); } - } + }; filterInputChangeHandler = (): void => { - this.eventSvc.$broadcast(TreeService.events.FILTER, this.treeFilter) - } + this.eventSvc.$broadcast(TreeService.events.FILTER, this.treeFilter); + }; public fullDocMode = (): void => { - let display = '' + let display = ''; this.bbApi.toggleButton( 'tree-full-document', this.rootScopeSvc.veFullDocMode(!this.rootScopeSvc.veFullDocMode()) - ) + ); if (this.rootScopeSvc.veFullDocMode()) { - display = 'document' + display = 'document'; } else { - display = 'slideshow' + display = 'slideshow'; } void this.$state.go('main.project.ref.view.present.' + display, { search: undefined, display, - }) - } + }); + }; reloadData = (): void => { - this.bbApi.toggleButtonSpinner('tree-refresh') - this.treeSvc.processedRoot = '' + this.bbApi.toggleButtonSpinner('tree-refresh'); + this.treeSvc.processedRoot = ''; const data: veCoreEvents.elementSelectedData = { rootId: this.treeApi.rootId, elementId: this.treeApi.elementId, @@ -498,35 +498,35 @@ class LeftPaneController implements angular.IComponentController { refId: this.treeApi.refId, refType: this.treeApi.refType, commitId: 'latest', - } - this.eventSvc.$broadcast('view.selected', data) + }; + this.eventSvc.$broadcast('view.selected', data); const finished = this.eventSvc.$on('tree.ready', () => { - this.bbApi.toggleButtonSpinner('tree-refresh') - finished.dispose() - }) - } + this.bbApi.toggleButtonSpinner('tree-refresh'); + finished.dispose(); + }); + }; deleteItem = (): void => { - const branch = this.treeSvc.getSelectedBranch() + const branch = this.treeSvc.getSelectedBranch(); if (!branch) { - this.growl.warning('Select item to remove.') - return + this.growl.warning('Select item to remove.'); + return; } this.treeSvc.getPrevBranch(branch).then( (prevBranch) => { - const type = this.viewSvc.getElementType(branch.data) + const type = this.viewSvc.getElementType(branch.data); if (this.$state.includes('**.present.**')) { if (type == 'Document') { this.growl.warning( 'Cannot remove a document from this view. To remove this item, go to project home.' - ) - return + ); + return; } if (branch.type !== 'view' || !this.apiSvc.isView(branch.data)) { this.growl.warning( 'Cannot remove non-view item. To remove this item, open it in the center pane.' - ) - return + ); + return; } } else { if ( @@ -534,22 +534,22 @@ class LeftPaneController implements angular.IComponentController { !this.apiSvc.isDocument(branch.data) && (branch.type !== 'group' || branch.children.length > 0) ) { - this.growl.warning('Cannot remove group with contents. Empty contents and try again.') - return + this.growl.warning('Cannot remove group with contents. Empty contents and try again.'); + return; } } const instance = this.$uibModal.open({ component: 'confirmDeleteModal', resolve: { getType: () => { - let type = branch.type + let type = branch.type; if (this.apiSvc.isDocument(branch.data)) { - type = 'Document' + type = 'Document'; } - return type + return type; }, getName: () => { - return branch.data.name + return branch.data.name; }, finalize: () => { return (): VePromise => { @@ -557,7 +557,7 @@ class LeftPaneController implements angular.IComponentController { if (branch.type === 'view') { this.treeSvc.getParent(branch).then((parentBranch) => { if (!this.$state.includes('**.present.**')) { - this.viewSvc.downgradeDocument(branch.data).then(resolve, reject) + this.viewSvc.downgradeDocument(branch.data).then(resolve, reject); } else { this.viewSvc .removeViewFromParentView({ @@ -566,19 +566,19 @@ class LeftPaneController implements angular.IComponentController { parentViewId: parentBranch.data.id, viewId: branch.data.id, }) - .then(resolve, reject) + .then(resolve, reject); } - }, reject) + }, reject); } else if (branch.type === 'group') { - this.viewSvc.removeGroup(branch.data).then(resolve, reject) + this.viewSvc.removeGroup(branch.data).then(resolve, reject); } else { - resolve() + resolve(); } - }) - } + }); + }; }, }, - }) + }); instance.result.then( () => { this.treeSvc.removeBranch(branch).then( @@ -589,47 +589,47 @@ class LeftPaneController implements angular.IComponentController { parentBranch, prevBranch, branch, - } - this.eventSvc.$broadcast('view.deleted', data) + }; + this.eventSvc.$broadcast('view.deleted', data); if (this.$state.includes('**.present.**') && branch.type === 'view') { - this.treeSvc.processDeletedViewBranch(branch) + this.treeSvc.processDeletedViewBranch(branch); } - let selectBranch: TreeBranch = null + let selectBranch: TreeBranch = null; if (prevBranch) { - selectBranch = prevBranch + selectBranch = prevBranch; } else if (parentBranch) { - selectBranch = parentBranch + selectBranch = parentBranch; } this.treeSvc.selectBranch(selectBranch).then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD) + this.eventSvc.$broadcast(TreeService.events.RELOAD); }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) + ); }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) + ); }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) + ); }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) - } + ); + }; } /* Controllers */ @@ -666,6 +666,6 @@ const LeftPaneComponent: VeComponentOptions = { $pane: '^ngPane', }, controller: LeftPaneController, -} +}; -veApp.component(LeftPaneComponent.selector, LeftPaneComponent) +veApp.component(LeftPaneComponent.selector, LeftPaneComponent); diff --git a/src/ve-app/pane-left/left-toolbar.component.ts b/src/ve-app/pane-left/left-toolbar.component.ts index 40fee51c7..92641505a 100644 --- a/src/ve-app/pane-left/left-toolbar.component.ts +++ b/src/ve-app/pane-left/left-toolbar.component.ts @@ -1,19 +1,19 @@ -import { StateService } from '@uirouter/angularjs' -import { IComponentController } from 'angular' -import Rx from 'rx-lite' +import { StateService } from '@uirouter/angularjs'; +import { IComponentController } from 'angular'; +import Rx from 'rx-lite'; -import { ExtensionService } from '@ve-components/services' -import { IToolBarButton, ToolbarApi, ToolbarService } from '@ve-core/toolbar' -import { RootScopeService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { PermissionsService } from '@ve-utils/mms-api-client' +import { ExtensionService } from '@ve-components/services'; +import { IToolBarButton, ToolbarApi, ToolbarService } from '@ve-core/toolbar'; +import { RootScopeService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { PermissionsService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { left_default_toolbar, left_dynamic_toolbar } from './left-buttons.config' +import { left_default_toolbar, left_dynamic_toolbar } from './left-buttons.config'; -import { VeComponentOptions } from '@ve-types/angular' -import { ElementObject, RefObject } from '@ve-types/mms' +import { VeComponentOptions } from '@ve-types/angular'; +import { ElementObject, RefObject } from '@ve-types/mms'; /* Classes */ const LeftToolbarComponent: VeComponentOptions = { @@ -33,20 +33,20 @@ const LeftToolbarComponent: VeComponentOptions = { 'EventService', 'ToolbarService', 'RootScopeService', - ] + ]; //Injected Deps - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; //Bindings - private mmsRef: RefObject + private mmsRef: RefObject; // Though we don't explicitly use it right now, we do need it to trigger updates when // entering/exiting certain states - private mmsRoot: ElementObject + private mmsRoot: ElementObject; //Local - public toolbarId: string + public toolbarId: string; constructor( public growl: angular.growl.IGrowlService, @@ -58,14 +58,14 @@ const LeftToolbarComponent: VeComponentOptions = { private toolbarSvc: ToolbarService, private rootScopeSvc: RootScopeService ) { - this.toolbarId = 'left-toolbar' + this.toolbarId = 'left-toolbar'; } $onInit(): void { - this.eventSvc.$init(this) - let initialState: string + this.eventSvc.$init(this); + let initialState: string; if (this.mmsRoot) { - initialState = this.$state.includes('**.portal.**') ? 'tree-of-documents' : 'tree-of-contents' + initialState = this.$state.includes('**.portal.**') ? 'tree-of-documents' : 'tree-of-contents'; } this.toolbarSvc.initApi( this.toolbarId, @@ -74,58 +74,58 @@ const LeftToolbarComponent: VeComponentOptions = { left_default_toolbar, left_dynamic_toolbar, initialState - ) + ); } $onDestroy(): void { - this.eventSvc.$destroy(this.subs) - this.toolbarSvc.destroyApi(this.toolbarId) + this.eventSvc.$destroy(this.subs); + this.toolbarSvc.destroyApi(this.toolbarId); } tbInit = (tbApi: ToolbarApi): void => { if (this.mmsRoot) { - const trees = this.extensionSvc.getExtensions('treeOf') + const trees = this.extensionSvc.getExtensions('treeOf'); for (const tree of trees) { - const button = this.toolbarSvc.getToolbarButton(tree) - tbApi.addButton(button) + const button = this.toolbarSvc.getToolbarButton(tree); + tbApi.addButton(button); if (button.enabledFor) { - button.active = false + button.active = false; for (const enableState of button.enabledFor) { if (this.$state.includes(enableState)) { - button.active = true - break + button.active = true; + break; } } } if (button.disabledFor) { for (const disableState of button.disabledFor) { if (this.$state.includes(disableState)) { - button.active = false - break + button.active = false; + break; } } } } } - } + }; paneToggle = (button: IToolBarButton): void => { - let toggleDeactivateFlag = false + let toggleDeactivateFlag = false; if (this.rootScopeSvc.leftPaneClosed()) { if (button.selected || this.rootScopeSvc.leftPaneClosed()) { - if (button.selected && !this.rootScopeSvc.leftPaneClosed()) toggleDeactivateFlag = true - this.eventSvc.$broadcast('left-pane.toggle') + if (button.selected && !this.rootScopeSvc.leftPaneClosed()) toggleDeactivateFlag = true; + this.eventSvc.$broadcast('left-pane.toggle'); } } if (toggleDeactivateFlag) { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.deactivate(button.id), (reason) => this.growl.error(ToolbarService.error(reason)) - ) + ); } - } + }; }, -} +}; /* Controllers */ -veApp.component(LeftToolbarComponent.selector, LeftToolbarComponent) +veApp.component(LeftToolbarComponent.selector, LeftToolbarComponent); diff --git a/src/ve-app/pane-right/index.ts b/src/ve-app/pane-right/index.ts index 5710afba7..d51766dfb 100644 --- a/src/ve-app/pane-right/index.ts +++ b/src/ve-app/pane-right/index.ts @@ -1,2 +1,2 @@ -import './right-pane.component' -import './right-toolbar.component' +import './right-pane.component'; +import './right-toolbar.component'; diff --git a/src/ve-app/pane-right/right-buttons.config.ts b/src/ve-app/pane-right/right-buttons.config.ts index 15c80e0fd..8f4c7d623 100644 --- a/src/ve-app/pane-right/right-buttons.config.ts +++ b/src/ve-app/pane-right/right-buttons.config.ts @@ -1,4 +1,4 @@ -import { IToolBarButton } from '@ve-core/toolbar' +import { IToolBarButton } from '@ve-core/toolbar'; export const right_default_toolbar: IToolBarButton[] = [ { @@ -57,7 +57,7 @@ export const right_default_toolbar: IToolBarButton[] = [ spinner: false, enabledFor: ['main.project.ref'], }, -] +]; export const right_dynamic_toolbar: IToolBarButton[] = [ { @@ -120,4 +120,4 @@ export const right_dynamic_toolbar: IToolBarButton[] = [ tooltip: 'Cancel', spinner: false, }, -] +]; diff --git a/src/ve-app/pane-right/right-pane.component.ts b/src/ve-app/pane-right/right-pane.component.ts index 1ab62756c..f8803171a 100644 --- a/src/ve-app/pane-right/right-pane.component.ts +++ b/src/ve-app/pane-right/right-pane.component.ts @@ -1,43 +1,43 @@ -import { IPane } from '@openmbee/pane-layout' -import { StateService } from '@uirouter/angularjs' -import angular, { IComponentController } from 'angular' -import _ from 'lodash' -import Rx from 'rx-lite' +import { IPane } from '@openmbee/pane-layout'; +import { StateService } from '@uirouter/angularjs'; +import angular, { IComponentController } from 'angular'; +import _ from 'lodash'; +import Rx from 'rx-lite'; -import { SpecService } from '@ve-components/spec-tools' -import { veCoreEvents } from '@ve-core/events' -import { ToolbarService } from '@ve-core/toolbar' -import { RootScopeService } from '@ve-utils/application' -import { EditObject, EditService, EventService } from '@ve-utils/core' -import { ElementService, PermissionsService, ProjectService } from '@ve-utils/mms-api-client' +import { SpecService } from '@ve-components/spec-tools'; +import { veCoreEvents } from '@ve-core/events'; +import { ToolbarService } from '@ve-core/toolbar'; +import { RootScopeService } from '@ve-utils/application'; +import { EditObject, EditService, EventService } from '@ve-utils/core'; +import { ElementService, PermissionsService, ProjectService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { ElementObject, RefObject, RefsResponse } from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { ElementObject, RefObject, RefsResponse } from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; -import elementSelectedData = veCoreEvents.elementSelectedData +import elementSelectedData = veCoreEvents.elementSelectedData; class RightPaneController implements IComponentController { //Bindings - private mmsRef: RefObject + private mmsRef: RefObject; // Though we don't explicitly use it right now, we do need it to trigger updates when // entering/exiting certain states - private mmsRoot: ElementObject + private mmsRoot: ElementObject; //Local Values - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; - private openEdits: number - private edits: { [id: string]: EditObject } + private openEdits: number; + private edits: { [id: string]: EditObject }; - private $pane: IPane - private $tools: JQuery + private $pane: IPane; + private $tools: JQuery; - private toolbarId: string = 'right-toolbar' + private toolbarId: string = 'right-toolbar'; static $inject = [ '$scope', @@ -57,7 +57,7 @@ class RightPaneController implements IComponentController { 'EditService', 'ToolbarService', 'SpecService', - ] + ]; constructor( private $scope: angular.IScope, @@ -80,38 +80,38 @@ class RightPaneController implements IComponentController { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); //Init Pane Toggle Controls - this.rootScopeSvc.rightPaneClosed(this.$pane.closed) + this.rootScopeSvc.rightPaneClosed(this.$pane.closed); //Init spec ready binding - this.eventSvc.resolve('spec.ready', true) + this.eventSvc.resolve('spec.ready', true); this.subs.push( this.$pane.$toggled.subscribe(() => { - this.rootScopeSvc.rightPaneClosed(this.$pane.closed) + this.rootScopeSvc.rightPaneClosed(this.$pane.closed); }) - ) + ); this.subs.push( this.eventSvc.$on('right-pane.toggle', (paneClosed) => { if (paneClosed === undefined) { - this.$pane.toggle() + this.$pane.toggle(); } else if (paneClosed && !this.$pane.closed) { - this.$pane.toggle() + this.$pane.toggle(); } else if (!paneClosed && this.$pane.closed) { - this.$pane.toggle() + this.$pane.toggle(); } - this.rootScopeSvc.rightPaneClosed(this.$pane.closed) + this.rootScopeSvc.rightPaneClosed(this.$pane.closed); }) - ) + ); this.subs.push( this.eventSvc.$on('element.selected', (data) => { - this.changeAction(data) + this.changeAction(data); }) - ) + ); this.subs.push( this.eventSvc.$on('element.updated', (data) => { @@ -121,37 +121,37 @@ class RightPaneController implements IComponentController { data.element._refId === this.specSvc.specApi.refId && !data.continueEdit ) { - this.eventSvc.resolve('spec.ready', false) - this.specSvc.setElement() + this.eventSvc.resolve('spec.ready', false); + this.specSvc.setElement(); } }) - ) + ); this.subs.push( this.eventSvc.$on('view.selected', (data) => { - this.changeAction(data) + this.changeAction(data); }) - ) + ); this.subs.push( this.eventSvc.$on(this.autosaveSvc.EVENT, () => { - this.openEdits = this.autosaveSvc.openEdits() + this.openEdits = this.autosaveSvc.openEdits(); }) - ) + ); - this.edits = this.autosaveSvc.getAll() + this.edits = this.autosaveSvc.getAll(); } $onDestroy(): void { - this.eventSvc.$destroy(this.subs) + this.eventSvc.$destroy(this.subs); } changeAction = (data: veCoreEvents.elementSelectedData): void => { - const elementId = data.elementId - const refId = data.refId - const projectId = data.projectId - const commitId = data.commitId ? data.commitId : null - const displayOldSpec = data.displayOldSpec ? data.displayOldSpec : null + const elementId = data.elementId; + const refId = data.refId; + const projectId = data.projectId; + const commitId = data.commitId ? data.commitId : null; + const displayOldSpec = data.displayOldSpec ? data.displayOldSpec : null; const promise: VePromise = new this.$q((resolve, reject) => { if ( !this.specSvc.specApi.refType || @@ -159,12 +159,12 @@ class RightPaneController implements IComponentController { projectId != this.specSvc.specApi.projectId ) { this.projectSvc.getRef(refId, projectId).then((ref) => { - resolve(ref.type) - }, reject) + resolve(ref.type); + }, reject); } else { - resolve(this.specSvc.specApi.refType) + resolve(this.specSvc.specApi.refType); } - }) + }); promise.then( (refType) => { @@ -175,7 +175,7 @@ class RightPaneController implements IComponentController { refId, commitId, displayOldSpec, - } + }; if (this.specSvc.specApi) { const current = { elementId: this.specSvc.specApi.elementId, @@ -184,52 +184,52 @@ class RightPaneController implements IComponentController { refType: this.specSvc.specApi.refType, commitId: this.specSvc.specApi.commitId, displayOldSpec: this.specSvc.specApi.displayOldSpec, - } + }; if (_.isEqual(specApi, current)) { - return //don't do unnecessary updates + return; //don't do unnecessary updates } } - this.eventSvc.resolve('spec.ready', false) - Object.assign(this.specSvc.specApi, specApi) + this.eventSvc.resolve('spec.ready', false); + Object.assign(this.specSvc.specApi, specApi); // if (this.specSvc.setEditing) { // this.specSvc.setEditing(false) // } - this.specSvc.specApi.rootId = data.rootId ? data.rootId : '' + this.specSvc.specApi.rootId = data.rootId ? data.rootId : ''; this.specSvc.editable = data.rootId && this.mmsRef.type === 'Branch' && refType === 'Branch' && - this.permissionsSvc.hasBranchEditPermission(projectId, refId) + this.permissionsSvc.hasBranchEditPermission(projectId, refId); this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.setIcon('spec-editor', 'fa-edit'), (reason) => this.growl.error(ToolbarService.error(reason)) - ) - this.specSvc.setElement() + ); + this.specSvc.setElement(); }, (reason) => { - this.growl.error('Unable to get ref: ' + reason.message) + this.growl.error('Unable to get ref: ' + reason.message); } - ) - } + ); + }; public etrackerChange = (): void => { - this.specSvc.keepMode() - const id = this.specSvc.tracker.etrackerSelected - if (!id) return - const info = id.split('|') + this.specSvc.keepMode(); + const id = this.specSvc.tracker.etrackerSelected; + if (!id) return; + const info = id.split('|'); const data: veCoreEvents.elementSelectedData = { elementId: info[2], projectId: info[0], refId: info[1], commitId: 'latest', - } + }; - this.eventSvc.$broadcast('element.selected', data) - } + this.eventSvc.$broadcast('element.selected', data); + }; } const RightPaneComponent: VeComponentOptions = { @@ -261,6 +261,6 @@ const RightPaneComponent: VeComponentOptions = { mmsRoot: '<', }, controller: RightPaneController, -} +}; -veApp.component(RightPaneComponent.selector, RightPaneComponent) +veApp.component(RightPaneComponent.selector, RightPaneComponent); diff --git a/src/ve-app/pane-right/right-toolbar.component.ts b/src/ve-app/pane-right/right-toolbar.component.ts index dc97a4344..b1b6a6068 100644 --- a/src/ve-app/pane-right/right-toolbar.component.ts +++ b/src/ve-app/pane-right/right-toolbar.component.ts @@ -1,18 +1,18 @@ -import { StateService } from '@uirouter/angularjs' -import { IComponentController } from 'angular' -import Rx from 'rx-lite' +import { StateService } from '@uirouter/angularjs'; +import { IComponentController } from 'angular'; +import Rx from 'rx-lite'; -import { right_default_toolbar, right_dynamic_toolbar } from '@ve-app/pane-right/right-buttons.config' -import { ExtensionService } from '@ve-components/services' -import { IToolBarButton, ToolbarApi, ToolbarService } from '@ve-core/toolbar' -import { RootScopeService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { PermissionsService } from '@ve-utils/mms-api-client' +import { right_default_toolbar, right_dynamic_toolbar } from '@ve-app/pane-right/right-buttons.config'; +import { ExtensionService } from '@ve-components/services'; +import { IToolBarButton, ToolbarApi, ToolbarService } from '@ve-core/toolbar'; +import { RootScopeService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { PermissionsService } from '@ve-utils/mms-api-client'; -import { veApp } from '@ve-app' +import { veApp } from '@ve-app'; -import { VeComponentOptions } from '@ve-types/angular' -import { ElementObject, RefObject } from '@ve-types/mms' +import { VeComponentOptions } from '@ve-types/angular'; +import { ElementObject, RefObject } from '@ve-types/mms'; class RightToolbarController implements IComponentController { static $inject = [ @@ -24,20 +24,20 @@ class RightToolbarController implements IComponentController { 'EventService', 'ToolbarService', 'RootScopeService', - ] + ]; //Injected Deps - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; //Bindings - private mmsRef: RefObject + private mmsRef: RefObject; // Though we don't explicitly use it right now, we do need it to trigger updates when // entering/exiting certain states - private mmsRoot: ElementObject + private mmsRoot: ElementObject; //Local - public toolbarId: string + public toolbarId: string; constructor( public growl: angular.growl.IGrowlService, @@ -49,11 +49,11 @@ class RightToolbarController implements IComponentController { private toolbarSvc: ToolbarService, private rootScopeSvc: RootScopeService ) { - this.toolbarId = 'right-toolbar' + this.toolbarId = 'right-toolbar'; } $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); this.toolbarSvc.initApi( this.toolbarId, @@ -62,32 +62,32 @@ class RightToolbarController implements IComponentController { right_default_toolbar, right_dynamic_toolbar, 'spec-inspector' - ) + ); } $onDestroy(): void { - this.eventSvc.$destroy(this.subs) - this.toolbarSvc.destroyApi(this.toolbarId) + this.eventSvc.$destroy(this.subs); + this.toolbarSvc.destroyApi(this.toolbarId); } tbInit = (tbApi: ToolbarApi): void => { for (const tool of this.extensionSvc.getExtensions('spec')) { - const button = this.toolbarSvc.getToolbarButton(tool) - tbApi.addButton(button) + const button = this.toolbarSvc.getToolbarButton(tool); + tbApi.addButton(button); if (button.enabledFor) { - button.active = false + button.active = false; for (const enableState of button.enabledFor) { if (this.$state.includes(enableState)) { - button.active = true - break + button.active = true; + break; } } } if (button.disabledFor) { for (const disableState of button.disabledFor) { if (this.$state.includes(disableState)) { - button.active = false - break + button.active = false; + break; } } } @@ -95,26 +95,26 @@ class RightToolbarController implements IComponentController { button.permission = this.mmsRef && this.mmsRef.type === 'Branch' && - this.permissionsSvc.hasBranchEditPermission(this.mmsRef._projectId, this.mmsRef.id) + this.permissionsSvc.hasBranchEditPermission(this.mmsRef._projectId, this.mmsRef.id); } } - } + }; public paneToggle = (button: IToolBarButton): void => { - let toggleDeactivateFlag = false + let toggleDeactivateFlag = false; if (this.rootScopeSvc.rightPaneClosed() && this.rootScopeSvc.rightPaneToggleable()) { if (button.selected || this.rootScopeSvc.rightPaneClosed()) { - if (button.selected && !this.rootScopeSvc.rightPaneClosed()) toggleDeactivateFlag = true - this.eventSvc.$broadcast('right-pane.toggle') + if (button.selected && !this.rootScopeSvc.rightPaneClosed()) toggleDeactivateFlag = true; + this.eventSvc.$broadcast('right-pane.toggle'); } } if (toggleDeactivateFlag) { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.deactivate(button.id), (reason) => this.growl.error(ToolbarService.error(reason)) - ) + ); } - } + }; } /* Classes */ @@ -126,7 +126,7 @@ const RightToolbarComponent: VeComponentOptions = { mmsRoot: '<', }, controller: RightToolbarController, -} +}; /* Controllers */ -veApp.component(RightToolbarComponent.selector, RightToolbarComponent) +veApp.component(RightToolbarComponent.selector, RightToolbarComponent); diff --git a/src/ve-app/ve-app.module.ts b/src/ve-app/ve-app.module.ts index f3b6837fa..68d463091 100644 --- a/src/ve-app/ve-app.module.ts +++ b/src/ve-app/ve-app.module.ts @@ -1,6 +1,6 @@ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -import ngPane from '@openmbee/pane-layout' +import ngPane from '@openmbee/pane-layout'; import uiRouter, { StateProvider, StateService, @@ -10,7 +10,7 @@ import uiRouter, { UIRouterGlobals, UrlParts, UrlService, -} from '@uirouter/angularjs' +} from '@uirouter/angularjs'; import angular, { IHttpInterceptor, IHttpResponse, @@ -21,15 +21,15 @@ import angular, { IPromise, IQService, IRequestConfig, -} from 'angular' +} from 'angular'; -import { LoginModalResolveFn } from '@ve-app/main/modals/login-modal.component' -import { ResolveService } from '@ve-app/main/services' -import { ApplicationService, BrandingStyle, RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { AuthService, URLService, PermissionCache, ViewService, DocumentMetadata } from '@ve-utils/mms-api-client' +import { LoginModalResolveFn } from '@ve-app/main/modals/login-modal.component'; +import { ResolveService } from '@ve-app/main/services'; +import { ApplicationService, BrandingStyle, RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { AuthService, URLService, PermissionCache, ViewService, DocumentMetadata } from '@ve-utils/mms-api-client'; -import { VePromise } from '@ve-types/angular' +import { VePromise } from '@ve-types/angular'; import { CheckAuthResponse, DocumentObject, @@ -47,8 +47,8 @@ import { RefObject, RefsResponse, ViewObject, -} from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +} from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; export const veApp = angular.module('ve-app', [ 've-utils', @@ -68,7 +68,7 @@ export const veApp = angular.module('ve-app', [ 'ngPromiseExtras', 'ngSanitize', 'ngStorage', -]) +]); veApp.config([ '$stateProvider', @@ -90,41 +90,41 @@ veApp.config([ '$delegate', function ( $delegate: ({ - link?(scope: angular.IScope, element: JQLite, attr: angular.IAttributes): void + link?(scope: angular.IScope, element: JQLite, attr: angular.IAttributes): void; } & angular.IDirective)[] ): { - link?(scope: angular.IScope, element: JQLite, attr: angular.IAttributes): void + link?(scope: angular.IScope, element: JQLite, attr: angular.IAttributes): void; } & angular.IDirective[] { - const originalLinkFn = $delegate[0].link + const originalLinkFn = $delegate[0].link; $delegate[0].compile = (): angular.IDirectiveLinkFn => { return function newLinkFn( scope: { - selectActive(matchId: string): void - active: string + selectActive(matchId: string): void; + active: string; } & angular.IScope, elem, attr ) { // fire the originalLinkFn // eslint-disable-next-line prefer-rest-params - originalLinkFn.apply($delegate[0], [scope, elem, attr]) + originalLinkFn.apply($delegate[0], [scope, elem, attr]); scope.selectActive = (matchIdx): void => { // added behavior - elem.children().removeClass('active') + elem.children().removeClass('active'); // default behavior - scope.active = matchIdx - } - } - } + scope.active = matchIdx; + }; + }; + }; // get rid of the old link function since we return a link function in compile - delete $delegate[0].link - return $delegate + delete $delegate[0].link; + return $delegate; }, - ]) + ]); - $locationProvider.hashPrefix('') + $locationProvider.hashPrefix(''); - $httpProvider.defaults.withCredentials = true + $httpProvider.defaults.withCredentials = true; $stateProvider .state('main', { @@ -145,19 +145,19 @@ veApp.config([ bannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getBanner() + return resolveSvc.getBanner(); }, ], loginBannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getLoginBanner() + return resolveSvc.getLoginBanner(); }, ], paramsOb: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], }, @@ -184,7 +184,7 @@ veApp.config([ token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken() + return resolveSvc.getToken(); }, ], }, @@ -206,25 +206,25 @@ veApp.config([ token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken() + return resolveSvc.getToken(); }, ], bannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getBanner() + return resolveSvc.getBanner(); }, ], loginBannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getLoginBanner() + return resolveSvc.getLoginBanner(); }, ], orgObs: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getOrgs() + return resolveSvc.getOrgs(); }, ], }, @@ -259,26 +259,26 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken() + return resolveSvc.getToken(); }, ], refresh: [ '$transition$', ($transition$: Transition): boolean => { - const options = $transition$.options() - return options.reload === true || options.reload === 'true' + const options = $transition$.options(); + return options.reload === true || options.reload === 'true'; }, ], bannerOb: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getBanner() + return resolveSvc.getBanner(); }, ], projectOb: [ @@ -288,7 +288,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getProject(params) + return resolveSvc.getProject(params); }, ], projectObs: [ @@ -300,27 +300,27 @@ veApp.config([ resolveSvc: ResolveService, projectOb: ProjectObject ): VePromise => { - return resolveSvc.getProjects(projectOb, refresh) + return resolveSvc.getProjects(projectOb, refresh); }, ], orgOb: [ 'ResolveService', 'projectOb', (resolveSvc: ResolveService, projectOb: ProjectObject): VePromise => { - return resolveSvc.getOrg(projectOb) + return resolveSvc.getOrg(projectOb); }, ], orgObs: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getOrgs() + return resolveSvc.getOrgs(); }, ], refObs: [ 'ResolveService', 'params', (resolveSvc: ResolveService, params: ParamsObject): VePromise => { - return resolveSvc.getRefs(params) + return resolveSvc.getRefs(params); }, ], }, @@ -367,14 +367,14 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], refresh: [ '$transition$', ($transition$: Transition): boolean => { - const options = $transition$.options() - return options.reload === true || options.reload === 'true' + const options = $transition$.options(); + return options.reload === true || options.reload === 'true'; }, ], projectOb: [ @@ -384,14 +384,14 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getProjectMounts(params) + return resolveSvc.getProjectMounts(params); }, ], refOb: [ 'ResolveService', 'params', (resolveSvc: ResolveService, params: ParamsObject): VePromise => { - return resolveSvc.getRef(params) + return resolveSvc.getRef(params); }, ], groupObs: [ @@ -403,7 +403,7 @@ veApp.config([ params: ParamsObject, refresh: boolean ): VePromise => { - return resolveSvc.getGroups(params, refresh) + return resolveSvc.getGroups(params, refresh); }, ], documentObs: [ @@ -415,7 +415,7 @@ veApp.config([ params: ParamsObject, refresh: boolean ): VePromise> => { - return resolveSvc.getProjectDocuments(params, refresh) + return resolveSvc.getProjectDocuments(params, refresh); }, ], bannerOb: [ @@ -425,7 +425,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getBanner(params) + return resolveSvc.getBanner(params); }, ], footerOb: [ @@ -435,7 +435,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getFooter(params) + return resolveSvc.getFooter(params); }, ], permissions: [ @@ -447,7 +447,7 @@ veApp.config([ projectOb: ProjectObject, resolveSvc: ResolveService ): VePromise => { - return resolveSvc.initializePermissions(projectOb, refOb) + return resolveSvc.initializePermissions(projectOb, refOb); }, ], }, @@ -495,7 +495,7 @@ veApp.config([ refresh: boolean, resolveSvc: ResolveService ): VePromise => { - return resolveSvc.getCoverDocument(params, refOb, projectOb, refresh) + return resolveSvc.getCoverDocument(params, refOb, projectOb, refresh); }, ], groupOb: [ @@ -507,14 +507,14 @@ veApp.config([ documentOb: DocumentObject, resolveSvc: ResolveService ): GroupObject => { - return resolveSvc.getGroup(groupObs, documentOb) + return resolveSvc.getGroup(groupObs, documentOb); }, ], rootOb: [ 'params', 'ResolveService', (params: ParamsObject, resolveSvc: ResolveService): VePromise => { - return resolveSvc.getProjectRoot(params) + return resolveSvc.getProjectRoot(params); }, ], }, @@ -605,7 +605,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], documentOb: [ @@ -619,7 +619,7 @@ veApp.config([ refOb: RefObject, refresh: boolean ): VePromise => { - return resolveSvc.getPreviewDocument(params, refOb, refresh) + return resolveSvc.getPreviewDocument(params, refOb, refresh); }, ], groupOb: [ @@ -631,7 +631,7 @@ veApp.config([ documentOb: DocumentObject, resolveSvc: ResolveService ): GroupObject => { - return resolveSvc.getGroup(groupObs, documentOb) + return resolveSvc.getGroup(groupObs, documentOb); }, ], }, @@ -658,7 +658,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise> => { - return resolveSvc.getProjectDocuments(params) + return resolveSvc.getProjectDocuments(params); }, ], }, @@ -689,7 +689,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], documentOb: [ @@ -701,7 +701,7 @@ veApp.config([ refresh: boolean, resolveSvc: ResolveService ): VePromise => { - return resolveSvc.getProjectDocument(params, refresh) + return resolveSvc.getProjectDocument(params, refresh); }, ], docMeta: [ @@ -712,7 +712,7 @@ veApp.config([ projectId: documentOb._projectId, refId: documentOb._refId, elementId: documentOb.id, - }) + }); }, ], }, @@ -806,7 +806,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], viewOb: [ @@ -815,9 +815,9 @@ veApp.config([ 'refresh', (resolveSvc: ResolveService, params: ParamsObject, refresh: boolean): VePromise => { if (params.viewId) { - return resolveSvc.getView(params, refresh) + return resolveSvc.getView(params, refresh); } else { - return null + return null; } }, ], @@ -861,7 +861,7 @@ veApp.config([ 'params', 'ResolveService', (params: ParamsObject, resolveSvc: ResolveService): VePromise => { - return resolveSvc.getProjectDocument(params, true) + return resolveSvc.getProjectDocument(params, true); }, ], }, @@ -889,7 +889,7 @@ veApp.config([ paramsOb: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], }, @@ -938,13 +938,13 @@ veApp.config([ token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken() + return resolveSvc.getToken(); }, ], paramsOb: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], }, @@ -953,7 +953,7 @@ veApp.config([ component: 'shortUrl', }, }, - }) + }); // anonymous factory intercepts requests $httpProvider.interceptors.push([ @@ -969,51 +969,51 @@ veApp.config([ ): IHttpInterceptor { return { request: (config: IRequestConfig): IRequestConfig => { - config.headers = uRLSvc.getAuthorizationHeader(config.headers) + config.headers = uRLSvc.getAuthorizationHeader(config.headers); if (!config.timeout) { - config.cancel = $q.defer() - config.timeout = config.cancel.promise + config.cancel = $q.defer(); + config.timeout = config.cancel.promise; } else { - console.log(config.url) + console.log(config.url); } - return config + return config; }, responseError: ( rejection: IHttpResponse ): IPromise> | IHttpResponse => { - const timeout: IPromise = rejection.config.timeout as IPromise + const timeout: IPromise = rejection.config.timeout as IPromise; if (timeout.state && timeout.state === 'cancelled') { - rejection.data = 'cancelled' - return $q.when(rejection) + rejection.data = 'cancelled'; + return $q.when(rejection); } if (rejection.status == 401) { - console.log(rejection.config.url) + console.log(rejection.config.url); if (rejection.config.url === uRLSvc.getCheckTokenURL()) { - return $q.reject(rejection) + return $q.reject(rejection); } else { - eventSvc.$broadcast('mms.unauthorized') + eventSvc.$broadcast('mms.unauthorized'); } } - return $q.reject(rejection) + return $q.reject(rejection); }, response: (response): IHttpResponse => { if (response.status === 202) { - eventSvc.$broadcast('mms.working', response) + eventSvc.$broadcast('mms.working', response); } - response.status = 501 - return response + response.status = 501; + return response; }, - } + }; }, - ]) + ]); - $httpProvider.useApplyAsync(true) + $httpProvider.useApplyAsync(true); // $uiRouterProvider.urlService.rules.otherwise((match, url: UrlParts | undefined) => { // console.log(url); // }) }, -]) +]); veApp.run([ '$q', @@ -1044,59 +1044,59 @@ veApp.run([ eventSvc: EventService, applicationSvc: ApplicationService ): void { - rootScopeSvc.loginModalOpen(false) + rootScopeSvc.loginModalOpen(false); $transitions.onBefore({}, (transition: Transition) => { - const to = transition.$to().name - const params: ParamsObject = transition.params() + const to = transition.$to().name; + const params: ParamsObject = transition.params(); if (to === 'main.login' || rootScopeSvc.loginModalOpen()) { if (params.next) { - $urlService.url(params.next, true) + $urlService.url(params.next, true); } - return + return; } return new Promise((resolve) => { authSvc.checkLogin().then( (data) => { - applicationSvc.getState().user = data.username + applicationSvc.getState().user = data.username; if (to === 'main') { - resolve($state.target('main.login.select')) + resolve($state.target('main.login.select')); } else if (to === 'main.project.ref') { - resolve($state.target('main.project.ref.portal')) + resolve($state.target('main.project.ref.portal')); } else if (to === 'main.project.ref.view.present') { if (!params.display || params.display === '') { - params.display = 'slideshow' + params.display = 'slideshow'; } - resolve($state.target('main.project.ref.view.present.' + params.display, params)) + resolve($state.target('main.project.ref.view.present.' + params.display, params)); } else if ($state.includes('*.present.**') && !(transition.params() as ParamsObject).display) { - const display = transition.$to().name.split('.')[transition.$to().name.split('.').length] + const display = transition.$to().name.split('.')[transition.$to().name.split('.').length]; resolve( $state.target(transition.$to().name, { display, }) - ) + ); } else { - resolve() + resolve(); } }, () => { $http.pendingRequests.forEach((pendingReq) => { if (pendingReq.cancel) { - pendingReq.cancel.resolve('cancelled') + pendingReq.cancel.resolve('cancelled'); } - }) + }); resolve( $state.target('main.login', { next: $urlService.url(), }) - ) + ); } - ) - }) - }) + ); + }); + }); $transitions.onError({}, (reason) => { - console.log(reason) + console.log(reason); //console.log(reason.error()); - }) + }); eventSvc.$on('mms.unauthorized', (response) => { // add a boolean to the 'or' statement to check for modal window if ( @@ -1109,9 +1109,9 @@ veApp.run([ $uiRouterGlobals.current.name === 'main.login.select' || ($uiRouterGlobals.transition && $uiRouterGlobals.transition.$to.name === 'main.login.select') ) { - void $state.go('main.login') + void $state.go('main.login'); } - return + return; } authSvc.checkLogin().then( @@ -1119,54 +1119,54 @@ veApp.run([ /* do nothing if success */ }, () => { - rootScopeSvc.loginModalOpen(true) + rootScopeSvc.loginModalOpen(true); $uibModal .open({ component: 'loginModal', resolve: { continue: () => { - return true + return true; }, }, backdrop: 'static', size: 'md', }) .result.finally(() => { - rootScopeSvc.loginModalOpen(false) - }) + rootScopeSvc.loginModalOpen(false); + }); } - ) - }) + ); + }); // broadcast mms.unauthorized every 10 minutes with interval service void $interval( () => { - eventSvc.$broadcast('mms.unauthorized') + eventSvc.$broadcast('mms.unauthorized'); }, window.__env.loginTimeout ? window.__env.loginTimeout : 60000, 0, false - ) + ); // Check if user is logged in, if so redirect to select page otherwise go to login if the url isn't mapped $urlService.rules.otherwise((match, url: UrlParts | undefined) => { void authSvc.checkLogin().then((checkLogin) => { if (checkLogin) { if ($location.url().includes('workspace')) { - rootScopeSvc.veRedirectFromOld(true) - rootScopeSvc.veCrushUrl($location.path()) - void $state.go('main.login.redirect') + rootScopeSvc.veRedirectFromOld(true); + rootScopeSvc.veCrushUrl($location.path()); + void $state.go('main.login.redirect'); } else { - rootScopeSvc.veRedirectFromOld(false) - void $state.go('main.login.select') + rootScopeSvc.veRedirectFromOld(false); + void $state.go('main.login.select'); } } else { - void $state.go('main.login') + void $state.go('main.login'); } - }) - }) + }); + }); }, -]) +]); /* veApp.run([ diff --git a/src/ve-components/components/annotation.component.ts b/src/ve-components/components/annotation.component.ts index 744bfa330..bbee61d9b 100644 --- a/src/ve-components/components/annotation.component.ts +++ b/src/ve-components/components/annotation.component.ts @@ -1,20 +1,20 @@ -import { ExtensionService } from '@ve-components/services' -import { veCoreEvents } from '@ve-core/events' -import { ApplicationService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ValueService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService } from '@ve-components/services'; +import { veCoreEvents } from '@ve-core/events'; +import { ApplicationService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ValueService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VeComponentOptions } from '@ve-types/angular' -import { ElementObject, InstanceSpecObject, LiteralObject } from '@ve-types/mms' +import { VeComponentOptions } from '@ve-types/angular'; +import { ElementObject, InstanceSpecObject, LiteralObject } from '@ve-types/mms'; export interface AnnotationObject { - toolTipTitle: string - toolTipContent: string - inlineContent: string - id: string + toolTipTitle: string; + toolTipContent: string; + inlineContent: string; + id: string; } class AnnotationController implements angular.IComponentController { @@ -26,17 +26,17 @@ class AnnotationController implements angular.IComponentController { 'ApplicationService', 'EventService', 'ValueService', - ] + ]; //Bindings - private mmsElementId: string - mmsRecentElement: ElementObject - mmsType: 'presentation' | 'transclusion' | 'link' - mmsField: 'name' | 'documentation' | 'value' + private mmsElementId: string; + mmsRecentElement: ElementObject; + mmsType: 'presentation' | 'transclusion' | 'link'; + mmsField: 'name' | 'documentation' | 'value'; //Local - public displayContent - private schema: string = 'cameo' + public displayContent; + private schema: string = 'cameo'; constructor( private $element: JQuery, @@ -57,50 +57,50 @@ class AnnotationController implements angular.IComponentController { refId: this.mmsRecentElement._refId, commitId: this.mmsRecentElement._commitId, displayOldSpec: true, - } - this.eventSvc.$broadcast('element.selected', data) + }; + this.eventSvc.$broadcast('element.selected', data); } - }) + }); - let displayContent: AnnotationObject + let displayContent: AnnotationObject; if (this.mmsRecentElement) { - displayContent = this._getContentIfElementFound() + displayContent = this._getContentIfElementFound(); } else { - displayContent = this._getContentIfElementNotFound() + displayContent = this._getContentIfElementNotFound(); } - this.displayContent = displayContent + this.displayContent = displayContent; } public copyToClipboard($event: JQuery.ClickEvent): void { this.applicationSvc.copyToClipboard($('#tooltipElementId'), $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }) + this.growl.info('Copied to clipboard!', { ttl: 2000 }); }, (err) => { - this.growl.error('Unable to copy: ' + err.message) + this.growl.error('Unable to copy: ' + err.message); } - ) + ); } private _getContentIfElementFound(): AnnotationObject { - let inlineContent = '' - let toolTipTitle: string - let toolTipContent: string + let inlineContent = ''; + let toolTipTitle: string; + let toolTipContent: string; if (this.mmsType === 'transclusion') { if (this.mmsField !== 'value') { - inlineContent = this.mmsRecentElement[this.mmsField] || '(no text)' - toolTipTitle = 'Referenced element not found' - toolTipContent = `Displaying last found ${this.mmsField} as placeholder.` + inlineContent = this.mmsRecentElement[this.mmsField] || '(no text)'; + toolTipTitle = 'Referenced element not found'; + toolTipContent = `Displaying last found ${this.mmsField} as placeholder.`; } else { if (!this.valueSvc.isValue(this.mmsRecentElement)) { - inlineContent = '(no text)' - toolTipTitle = 'Referenced element is not a value' - toolTipContent = `Cannot display value of non-value type element` + inlineContent = '(no text)'; + toolTipTitle = 'Referenced element is not a value'; + toolTipContent = `Cannot display value of non-value type element`; } else { - inlineContent = this._getValueForTranscludeVal(this.mmsRecentElement) - toolTipTitle = 'Referenced element not found' - toolTipContent = `Displaying last found ${this.mmsField} as placeholder.` + inlineContent = this._getValueForTranscludeVal(this.mmsRecentElement); + toolTipTitle = 'Referenced element not found'; + toolTipContent = `Displaying last found ${this.mmsField} as placeholder.`; } } } else if (this.mmsType === 'presentation') { @@ -108,18 +108,18 @@ class AnnotationController implements angular.IComponentController { 'TYPE_TO_CLASSIFIER_ID', (this.mmsRecentElement as InstanceSpecObject).classifierIds[0], this.schema - ) + ); if (classifierType.endsWith('T')) { - classifierType = classifierType.substring(0, classifierType.length - 1) + classifierType = classifierType.substring(0, classifierType.length - 1); } - inlineContent = this.mmsRecentElement.documentation || '(no text)' - toolTipTitle = 'Referenced ' + classifierType + ' not found.' - toolTipContent = 'Displaying last found content as placeholder.' + inlineContent = this.mmsRecentElement.documentation || '(no text)'; + toolTipTitle = 'Referenced ' + classifierType + ' not found.'; + toolTipContent = 'Displaying last found content as placeholder.'; } else if (this.mmsType === 'link') { - inlineContent = this.mmsRecentElement.name - toolTipTitle = 'Referenced view link not found' - toolTipContent = 'Displaying last found view link as placeholder.' + inlineContent = this.mmsRecentElement.name; + toolTipTitle = 'Referenced view link not found'; + toolTipContent = 'Displaying last found view link as placeholder.'; } return { @@ -127,19 +127,19 @@ class AnnotationController implements angular.IComponentController { toolTipTitle: toolTipTitle, toolTipContent: toolTipContent, id: this.mmsElementId, - } + }; } private _getContentIfElementNotFound(): AnnotationObject { - const AT = this.extensionSvc.AnnotationType - let inlineContent = '' - const label = this.mmsElementId ? `(${this.mmsElementId})` : '' + const AT = this.extensionSvc.AnnotationType; + let inlineContent = ''; + const label = this.mmsElementId ? `(${this.mmsElementId})` : ''; if (this.mmsType === 'transclusion') { - inlineContent = 'cf element ' + label + ' does not exist' + inlineContent = 'cf element ' + label + ' does not exist'; } else if (this.mmsType === 'link') { - inlineContent = 'view link does not exist' + inlineContent = 'view link does not exist'; } else if (this.mmsType === 'presentation') { - inlineContent = 'presentation element does not exist' + inlineContent = 'presentation element does not exist'; } return { @@ -147,24 +147,24 @@ class AnnotationController implements angular.IComponentController { toolTipTitle: 'Element not found', toolTipContent: '', id: this.mmsElementId, - } + }; } private _getValueForTranscludeVal = (element: ElementObject): string => { - let value: unknown + let value: unknown; if (element.type === 'Property' || element.type === 'Port' || element.type === 'Slot') { if (element.defaultValue) { - value = (element.defaultValue as LiteralObject).value + value = (element.defaultValue as LiteralObject).value; } else if ((element as LiteralObject).value) { - value = (element as LiteralObject[]>).value[0].value + value = (element as LiteralObject[]>).value[0].value; } } if (element.type === 'Constraint' && element.specification) { - value = ((element as InstanceSpecObject).specification as LiteralObject).value + value = ((element as InstanceSpecObject).specification as LiteralObject).value; } - return value.toString() - } + return value.toString(); + }; } /** Used for annotating an element that doesn't have any commit history at all or for an element that is deleted but has commit history **/ @@ -189,5 +189,5 @@ const AnnotationComponent: VeComponentOptions = { mmsField: '<', }, controller: AnnotationController, -} -veUtils.component(AnnotationComponent.selector, AnnotationComponent) +}; +veUtils.component(AnnotationComponent.selector, AnnotationComponent); diff --git a/src/ve-components/components/error.component.ts b/src/ve-components/components/error.component.ts index ffa030418..c5a8ca329 100644 --- a/src/ve-components/components/error.component.ts +++ b/src/ve-components/components/error.component.ts @@ -1,51 +1,51 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { ApplicationService } from '@ve-utils/application' +import { ApplicationService } from '@ve-utils/application'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; class ExtensionErrorController implements angular.IComponentController { //Bindings - extType: string - extKind: string - errorMsg: string - mmsElementId: string + extType: string; + extKind: string; + errorMsg: string; + mmsElementId: string; //Local Structure - protected content: string - protected title: string - protected id: string + protected content: string; + protected title: string; + protected id: string; - static $inject = ['growl', 'ApplicationService'] + static $inject = ['growl', 'ApplicationService']; constructor(private growl: angular.growl.IGrowlService, private applicationSvc: ApplicationService) {} $onInit(): void { - this.id = this.mmsElementId + this.id = this.mmsElementId; if (!this.extKind && !this.extType) { - this.title = 'Error' - this.content = this.errorMsg ? this.errorMsg : 'There was a problem displaying your content.' - return + this.title = 'Error'; + this.content = this.errorMsg ? this.errorMsg : 'There was a problem displaying your content.'; + return; } - const localKind = this.extKind ? _.capitalize(this.extKind) : 'Element' - const localExtType = _.capitalize(this.extType) + const localKind = this.extKind ? _.capitalize(this.extKind) : 'Element'; + const localExtType = _.capitalize(this.extType); - this.title = 'Unsupported ' + localKind + ' Type: ' + localExtType + this.title = 'Unsupported ' + localKind + ' Type: ' + localExtType; this.content = - 'This ' + localKind + ' has a rendering type: ' + localExtType + ' that is not supported by View Editor' + 'This ' + localKind + ' has a rendering type: ' + localExtType + ' that is not supported by View Editor'; } public copyToClipboard($event: JQuery.ClickEvent): void { this.applicationSvc.copyToClipboard($('#tooltipElementId'), $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }) + this.growl.info('Copied to clipboard!', { ttl: 2000 }); }, (err) => { - this.growl.error('Unable to copy: ' + err.message) + this.growl.error('Unable to copy: ' + err.message); } - ) + ); } } @@ -71,6 +71,6 @@ const ExtensionErrorComponent: VeComponentOptions = { mmsElementId: '<', }, controller: ExtensionErrorController, -} +}; -veUtils.component(ExtensionErrorComponent.selector, ExtensionErrorComponent) +veUtils.component(ExtensionErrorComponent.selector, ExtensionErrorComponent); diff --git a/src/ve-components/components/index.ts b/src/ve-components/components/index.ts index 8ecae0fb7..663d34710 100644 --- a/src/ve-components/components/index.ts +++ b/src/ve-components/components/index.ts @@ -1,3 +1,3 @@ //Services -import './annotation.component' -import './error.component' +import './annotation.component'; +import './error.component'; diff --git a/src/ve-components/diffs/components/diff-attr.component.ts b/src/ve-components/diffs/components/diff-attr.component.ts index 06f5b9cc4..f0d920bde 100644 --- a/src/ve-components/diffs/components/diff-attr.component.ts +++ b/src/ve-components/diffs/components/diff-attr.component.ts @@ -1,14 +1,14 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { ViewController } from '@ve-components/presentations' -import { ExtensionService } from '@ve-components/services' -import { ElementService } from '@ve-utils/mms-api-client' -import { handleChange } from '@ve-utils/utils' +import { ViewController } from '@ve-components/presentations'; +import { ExtensionService } from '@ve-components/services'; +import { ElementService } from '@ve-utils/mms-api-client'; +import { handleChange } from '@ve-utils/utils'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { ElementObject, ElementsRequest, RequestObject } from '@ve-types/mms' +import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { ElementObject, ElementsRequest, RequestObject } from '@ve-types/mms'; /** * @ngdoc directive @@ -36,31 +36,31 @@ import { ElementObject, ElementsRequest, RequestObject } from '@ve-types/mms' class DiffAttrController { //Bindings - attr: string - elementId: string - compareElementId: string - projectId: string - compareProjectId: string + attr: string; + elementId: string; + compareElementId: string; + projectId: string; + compareProjectId: string; - refId: string - compareRefId: string + refId: string; + compareRefId: string; - commitId: string - compareCommitId: string + commitId: string; + compareCommitId: string; //Controllers - mmsViewCtrl: ViewController + mmsViewCtrl: ViewController; //Local - diffLoading: boolean = false - baseNotFound: boolean = false - compNotFound: boolean = false - baseDeleted: boolean = false - compDeleted: boolean = false - private viewOrigin: RequestObject - baseElementHtml: string - comparedElementHtml: string - message: string + diffLoading: boolean = false; + baseNotFound: boolean = false; + compNotFound: boolean = false; + baseDeleted: boolean = false; + compDeleted: boolean = false; + private viewOrigin: RequestObject; + baseElementHtml: string; + comparedElementHtml: string; + message: string; static $inject = [ '$scope', @@ -71,7 +71,7 @@ class DiffAttrController { '$compile', '$q', '$interval', - ] + ]; constructor( private $scope: angular.IScope, @@ -85,42 +85,42 @@ class DiffAttrController { ) {} $onInit(): void { - this.viewOrigin = this.mmsViewCtrl ? this.mmsViewCtrl.getElementOrigin() : null + this.viewOrigin = this.mmsViewCtrl ? this.mmsViewCtrl.getElementOrigin() : null; } $postLink(): void { - this.performDiff() + this.performDiff(); } $onChanges(onChangesObj: angular.IOnChangesObject): void { - handleChange(onChangesObj, 'commitId', this.changeAction) - handleChange(onChangesObj, 'compareCommitId', this.changeAction) + handleChange(onChangesObj, 'commitId', this.changeAction); + handleChange(onChangesObj, 'compareCommitId', this.changeAction); } public diffFinish = (): void => { - this.diffLoading = false - } + this.diffLoading = false; + }; protected changeAction = (newVal, oldVal, firstChange): void => { if (!newVal || firstChange) { - return + return; } - if (oldVal !== newVal) this.performDiff() - } + if (oldVal !== newVal) this.performDiff(); + }; protected performDiff = (): void => { if (this.attr && this.extensionSvc.getTagByType('transclude', this.attr) !== 'extension-error') { this.getDiff().then( (responses: angular.PromiseValue[]) => { - const respForBaseElement = responses[0] + const respForBaseElement = responses[0]; if (respForBaseElement.state === 'fulfilled') { this._fullyRender(respForBaseElement.value).then( (baseElementHtml) => { - this.baseElementHtml = $(baseElementHtml).children().html() + this.baseElementHtml = $(baseElementHtml).children().html(); }, (reason) => { - this.growl.error(`Error getting Diff: ${reason.message}`) + this.growl.error(`Error getting Diff: ${reason.message}`); } - ) + ); } else { if ( respForBaseElement.reason && @@ -129,23 +129,23 @@ class DiffAttrController { .toLowerCase() .includes('deleted') ) { - this.baseDeleted = true + this.baseDeleted = true; } else { - this.baseNotFound = true + this.baseNotFound = true; } - this.baseElementHtml = '' + this.baseElementHtml = ''; } - const respForComparedElement = responses[1] + const respForComparedElement = responses[1]; if (respForComparedElement.state === 'fulfilled') { this._fullyRender(respForComparedElement.value).then( (comparedElementHtml) => { - this.comparedElementHtml = $(comparedElementHtml).children().html() + this.comparedElementHtml = $(comparedElementHtml).children().html(); }, () => { - this.growl.error('Problem Rendering Diff') + this.growl.error('Problem Rendering Diff'); } - ) + ); } else { if ( respForComparedElement.reason && @@ -154,65 +154,65 @@ class DiffAttrController { .toLowerCase() .includes('deleted') ) { - this.compDeleted = true + this.compDeleted = true; } else { - this.compNotFound = true + this.compNotFound = true; } - this.comparedElementHtml = '' + this.comparedElementHtml = ''; } - this.message = this._checkElementExistence() + this.message = this._checkElementExistence(); }, (reason) => { - this.growl.error(`Error getting Diff: ${reason.message}`) + this.growl.error(`Error getting Diff: ${reason.message}`); } - ) + ); } else { - this.growl.error('Unsupported Attribute for diff') + this.growl.error('Unsupported Attribute for diff'); } - } + }; public getDiff = (): VePromise[]> => { - this.diffLoading = true + this.diffLoading = true; - const baseProjectId = this.projectId || (this.viewOrigin ? this.viewOrigin.projectId : null) - const compareProjectId = this.compareProjectId || baseProjectId + const baseProjectId = this.projectId || (this.viewOrigin ? this.viewOrigin.projectId : null); + const compareProjectId = this.compareProjectId || baseProjectId; - const baseRefId = this.refId || (this.viewOrigin ? this.viewOrigin.refId : 'master') - const compareRefId = this.compareRefId || baseRefId + const baseRefId = this.refId || (this.viewOrigin ? this.viewOrigin.refId : 'master'); + const compareRefId = this.compareRefId || baseRefId; - const baseCommitId = this.commitId || 'latest' - const compareCommitId = this.compareCommitId || 'latest' + const baseCommitId = this.commitId || 'latest'; + const compareCommitId = this.compareCommitId || 'latest'; - const baseElementId = this.elementId - const compareElementId = this.compareElementId || baseElementId + const baseElementId = this.elementId; + const compareElementId = this.compareElementId || baseElementId; const baseReqOb: ElementsRequest = { elementId: baseElementId, projectId: baseProjectId, refId: baseRefId, commitId: baseCommitId, - } + }; const compareReqOb: ElementsRequest = { elementId: compareElementId, projectId: compareProjectId, refId: compareRefId, commitId: compareCommitId, - } - const isSame = _.isEqual(baseReqOb, compareReqOb) + }; + const isSame = _.isEqual(baseReqOb, compareReqOb); if (isSame) { - return + return; } - const baseElementPromise = this.elementSvc.getElement(baseReqOb) - const comparedElementPromise = this.elementSvc.getElement(compareReqOb) - return this.$q.allSettled([baseElementPromise, comparedElementPromise]) - } + const baseElementPromise = this.elementSvc.getElement(baseReqOb); + const comparedElementPromise = this.elementSvc.getElement(compareReqOb); + return this.$q.allSettled([baseElementPromise, comparedElementPromise]); + }; protected _createElement = (type: string, reqOb: ElementsRequest): JQuery => { - const ignoreMathjaxAutoFormatting = type === 'doc' || type === 'val' || type === 'com' + const ignoreMathjaxAutoFormatting = type === 'doc' || type === 'val' || type === 'com'; const html = '' + 'mms-cf-type="{{type}}" mms-element-id="{{mmsElementId}}" mms-project-id="{{mmsProjectId}}" mms-ref-id="{{mmsRefId}}" mms-commit-id="{{commitId}}">'; const newScope = Object.assign(this.$scope.$new(), { type: type, mmsElementId: reqOb.elementId, @@ -220,47 +220,47 @@ class DiffAttrController { mmsRefId: reqOb.refId, commitId: reqOb.commitId, mmsGenerateForDiff: true, - }) - return this.$compile(html)(newScope) - } + }); + return this.$compile(html)(newScope); + }; protected _fullyRender = (data: ElementObject): VePromise => { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); const element = this._createElement(this.attr, { elementId: data.id, projectId: data._projectId, refId: data._refId, commitId: data._commitId, - }) + }); const handler = this.$interval(() => { - const baseHtml = element.html() + const baseHtml = element.html(); if (!baseHtml.includes('(loading...)')) { - this.$interval.cancel(handler) - deferred.resolve(baseHtml) + this.$interval.cancel(handler); + deferred.resolve(baseHtml); } - }, 10) + }, 10); - return deferred.promise - } + return deferred.promise; + }; protected _checkElementExistence = (): string => { - let message = '' + let message = ''; if (this.baseNotFound && this.compNotFound) { - message = ' Both base and compare elements do not exist.' + message = ' Both base and compare elements do not exist.'; } else if (this.baseNotFound) { - message = ' This is a new element.' + message = ' This is a new element.'; } else if (this.compNotFound) { - message = ' Comparison element does not exist.' + message = ' Comparison element does not exist.'; } if (this.baseDeleted && this.compDeleted) { - message = ' This element has been deleted.' + message = ' This element has been deleted.'; } else if (this.baseDeleted) { - message = ' Base element has been deleted.' + message = ' Base element has been deleted.'; } else if (this.compDeleted) { - message = ' Comparison element has been deleted.' + message = ' Comparison element has been deleted.'; } - return message - } + return message; + }; } const DiffAttrComponent: VeComponentOptions = { @@ -289,6 +289,6 @@ const DiffAttrComponent: VeComponentOptions = { require: { mmsViewCtrl: '?^^view', }, -} -veComponents.component('mmsDiffAttr', DiffAttrComponent) -veComponents.component(DiffAttrComponent.selector, DiffAttrComponent) +}; +veComponents.component('mmsDiffAttr', DiffAttrComponent); +veComponents.component(DiffAttrComponent.selector, DiffAttrComponent); diff --git a/src/ve-components/diffs/components/diff-html.component.ts b/src/ve-components/diffs/components/diff-html.component.ts index 706503f2a..162a59aad 100644 --- a/src/ve-components/diffs/components/diff-html.component.ts +++ b/src/ve-components/diffs/components/diff-html.component.ts @@ -1,95 +1,95 @@ -import { handleChange } from '@ve-utils/utils' +import { handleChange } from '@ve-utils/utils'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { HtmlRenderedDiff } from '../../../lib/html-rendered-diff' +import { HtmlRenderedDiff } from '../../../lib/html-rendered-diff'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; class DiffHtmlController { //bindings - private base: string - private compare: string - private diffCallback: () => void + private base: string; + private compare: string; + private diffCallback: () => void; //local - private htmlRenderedDiff: HtmlRenderedDiff - htmlDiffIdPrefix: string = 'html-diff-' - htmlDiffId: string - diffResult: string + private htmlRenderedDiff: HtmlRenderedDiff; + htmlDiffIdPrefix: string = 'html-diff-'; + htmlDiffId: string; + diffResult: string; - static $inject = ['$scope', '$timeout', 'growl'] + static $inject = ['$scope', '$timeout', 'growl']; constructor( private $scope: angular.IScope, private $timeout: angular.ITimeoutService, private growl: angular.growl.IGrowlService ) { - this.htmlRenderedDiff = window.HtmlRenderedDiff + this.htmlRenderedDiff = window.HtmlRenderedDiff; } $onInit(): void { - this.htmlDiffId = `${this.htmlDiffIdPrefix}${this.$scope.$id}` - this.performDiff() + this.htmlDiffId = `${this.htmlDiffIdPrefix}${this.$scope.$id}`; + this.performDiff(); } $onChanges(onChangesObj: angular.IOnChangesObject): void { - handleChange(onChangesObj, 'base', this.performDiff) - handleChange(onChangesObj, 'compare', this.performDiff) + handleChange(onChangesObj, 'base', this.performDiff); + handleChange(onChangesObj, 'compare', this.performDiff); } protected performDiff = (): void => { this.diffResult = this.htmlRenderedDiff.generateDiff( DiffHtmlController._preformatHtml(this.base), DiffHtmlController._preformatHtml(this.compare) - ) + ); this.$timeout(() => { - const diffContainer = $('#' + this.htmlDiffId) - this._formatImgDiff(diffContainer) - this._formatRowDiff(diffContainer) + const diffContainer = $('#' + this.htmlDiffId); + this._formatImgDiff(diffContainer); + this._formatRowDiff(diffContainer); }).then( () => { - if (this.diffCallback) this.diffCallback() + if (this.diffCallback) this.diffCallback(); }, () => { - this.growl.error('Problem performing diff.') + this.growl.error('Problem performing diff.'); } - ) - } + ); + }; static _preformatHtml(html: string): string { - return html.replace(/\r?\n|\r|\t/g, '').replace('

     

    ', '') + return html.replace(/\r?\n|\r|\t/g, '').replace('

     

    ', ''); } private _formatImgDiff = (diffContainer: JQuery): void => { diffContainer.find('img').each((index, element) => { - const img$ = $(element) + const img$ = $(element); const imgPatcherClass = img$.hasClass('patcher-insert') ? 'patcher-insert' : img$.hasClass('patcher-delete') ? 'patcher-delete' - : null + : null; if (imgPatcherClass) { - img$.wrap('') + img$.wrap(''); } - }) - } + }); + }; private _formatRowDiff = (diffContainer: JQuery): void => { diffContainer.find('tr').each((index, element) => { - const tr$: JQuery = $(element) + const tr$: JQuery = $(element); const trPatcherClass: string = tr$.hasClass('patcher-insert') ? 'patcher-insert' : tr$.hasClass('patcher-delete') ? 'patcher-delete' - : '' + : ''; if (trPatcherClass !== '') { - tr$.removeClass(trPatcherClass) + tr$.removeClass(trPatcherClass); tr$.children().each((index, el) => { - $(el).addClass(trPatcherClass) - }) + $(el).addClass(trPatcherClass); + }); } - }) - } + }); + }; } const DiffHtmlComponent: VeComponentOptions = { @@ -104,6 +104,6 @@ const DiffHtmlComponent: VeComponentOptions = { diffCallback: '&', }, controller: DiffHtmlController, -} +}; -veComponents.component(DiffHtmlComponent.selector, DiffHtmlComponent) +veComponents.component(DiffHtmlComponent.selector, DiffHtmlComponent); diff --git a/src/ve-components/diffs/components/index.ts b/src/ve-components/diffs/components/index.ts index f11f1b958..7d8b67fee 100644 --- a/src/ve-components/diffs/components/index.ts +++ b/src/ve-components/diffs/components/index.ts @@ -1,2 +1,2 @@ -import './diff-html.component' -import './diff-attr.component' +import './diff-html.component'; +import './diff-attr.component'; diff --git a/src/ve-components/diffs/index.ts b/src/ve-components/diffs/index.ts index 07116e14d..06c4704a8 100644 --- a/src/ve-components/diffs/index.ts +++ b/src/ve-components/diffs/index.ts @@ -1,10 +1,10 @@ // Services -import './services/DiffMerge.service' +import './services/DiffMerge.service'; -export * from './services/DiffMerge.service' +export * from './services/DiffMerge.service'; //Components -import './components' +import './components'; //Modals -import './modals' +import './modals'; -export * from './modals' +export * from './modals'; diff --git a/src/ve-components/diffs/modals/index.ts b/src/ve-components/diffs/modals/index.ts index 3b6483468..46408f6ae 100644 --- a/src/ve-components/diffs/modals/index.ts +++ b/src/ve-components/diffs/modals/index.ts @@ -1,7 +1,7 @@ -import './revert-confirm.component' -import './save-conflict.component' -import './merge-confirm-modal.component' +import './revert-confirm.component'; +import './save-conflict.component'; +import './merge-confirm-modal.component'; -export * from './merge-confirm-modal.component' -export * from './revert-confirm.component' -export * from './save-conflict.component' +export * from './merge-confirm-modal.component'; +export * from './revert-confirm.component'; +export * from './save-conflict.component'; diff --git a/src/ve-components/diffs/modals/merge-confirm-modal.component.ts b/src/ve-components/diffs/modals/merge-confirm-modal.component.ts index fc4cfb238..8b7e05cba 100644 --- a/src/ve-components/diffs/modals/merge-confirm-modal.component.ts +++ b/src/ve-components/diffs/modals/merge-confirm-modal.component.ts @@ -1,54 +1,54 @@ -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { RefObject } from '@ve-types/mms' -import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { RefObject } from '@ve-types/mms'; +import { VeModalComponent, VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; export interface MergeConfirmResolve extends VeModalResolve { - getSrcRefOb: RefObject - getDocName: string + getSrcRefOb: RefObject; + getDocName: string; } export interface MergeConfirmResolveFn extends VeModalResolveFn { - getSrcRefOb(): RefObject - getDocName(): string + getSrcRefOb(): RefObject; + getDocName(): string; } class MergeConfirmModalController extends VeModalControllerImpl implements VeModalController { //Bindings - protected resolve: MergeConfirmResolve + protected resolve: MergeConfirmResolve; - oking: boolean - commitMessage: string - createForm: boolean - srcRefOb: RefObject - docName: string + oking: boolean; + commitMessage: string; + createForm: boolean; + srcRefOb: RefObject; + docName: string; - static $inject = ['growl'] + static $inject = ['growl']; constructor(private growl: angular.growl.IGrowlService) { - super() + super(); } $onInit(): void { - this.srcRefOb = this.resolve.getSrcRefOb - this.docName = this.resolve.getDocName - this.oking = false - this.commitMessage = '' - this.createForm = true + this.srcRefOb = this.resolve.getSrcRefOb; + this.docName = this.resolve.getDocName; + this.oking = false; + this.commitMessage = ''; + this.createForm = true; } public ok = (): void => { if (this.oking) { - this.growl.info('Please wait...') - return + this.growl.info('Please wait...'); + return; } - this.oking = false - } + this.oking = false; + }; public cancel = (): void => { - this.modalInstance.dismiss() - } + this.modalInstance.dismiss(); + }; } const MergeConfirmModalComponent: VeModalComponent = { @@ -88,6 +88,6 @@ const MergeConfirmModalComponent: VeModalComponent = { resolve: '<', }, controller: MergeConfirmModalController, -} +}; -veComponents.component(MergeConfirmModalComponent.selector, MergeConfirmModalComponent) +veComponents.component(MergeConfirmModalComponent.selector, MergeConfirmModalComponent); diff --git a/src/ve-components/diffs/modals/revert-confirm.component.ts b/src/ve-components/diffs/modals/revert-confirm.component.ts index 17101c660..c1fce2b39 100644 --- a/src/ve-components/diffs/modals/revert-confirm.component.ts +++ b/src/ve-components/diffs/modals/revert-confirm.component.ts @@ -1,40 +1,40 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { Commit, CompareData } from '@ve-components/diffs' -import { EventService } from '@ve-utils/core' -import { ElementService } from '@ve-utils/mms-api-client' +import { Commit, CompareData } from '@ve-components/diffs'; +import { EventService } from '@ve-utils/core'; +import { ElementService } from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions } from '@ve-types/angular' -import { ConstraintObject, ElementObject, ElementsRequest, ElementTaggedValueObject, SlotObject } from '@ve-types/mms' -import { VeModalController, VeModalInstanceService } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { ConstraintObject, ElementObject, ElementsRequest, ElementTaggedValueObject, SlotObject } from '@ve-types/mms'; +import { VeModalController, VeModalInstanceService } from '@ve-types/view-editor'; export interface RevertConfirmResolve { - reqOb: ElementsRequest - revertData: CompareData + reqOb: ElementsRequest; + revertData: CompareData; } export interface RevertConfirmResolveFn { - reqOb(): ElementsRequest + reqOb(): ElementsRequest; revertData(): { - baseCommit: Commit - compareCommit: Commit - element: ElementObject - } + baseCommit: Commit; + compareCommit: Commit; + element: ElementObject; + }; } class RevertConfirmController implements VeModalController { //bindings - public modalInstance: VeModalInstanceService - public resolve: RevertConfirmResolve + public modalInstance: VeModalInstanceService; + public resolve: RevertConfirmResolve; - public oking - revertData: CompareData - reqOb: ElementsRequest - element: ElementObject + public oking; + revertData: CompareData; + reqOb: ElementsRequest; + element: ElementObject; - static $inject = ['growl', 'ElementService', 'EventService'] + static $inject = ['growl', 'ElementService', 'EventService']; constructor( private growl: angular.growl.IGrowlService, @@ -43,26 +43,26 @@ class RevertConfirmController implements VeModalController { ) {} $onInit(): void { - this.revertData = this.resolve.revertData - this.reqOb = this.resolve.reqOb + this.revertData = this.resolve.revertData; + this.reqOb = this.resolve.reqOb; this.elementSvc.getElement(this.reqOb).then((el) => { - this.element = el - }) + this.element = el; + }); } ok(): void { if (this.oking) { - this.growl.info('Please wait...') - return + this.growl.info('Please wait...'); + return; } - this.oking = true + this.oking = true; - const reqOb = _.cloneDeep(this.reqOb) - reqOb.refId = this.revertData.baseCommit.ref.id + const reqOb = _.cloneDeep(this.reqOb); + reqOb.refId = this.revertData.baseCommit.ref.id; reqOb.commitId = typeof this.revertData.baseCommit.commitSelected === 'string' ? this.revertData.baseCommit.commitSelected - : this.revertData.baseCommit.commitSelected.id + : this.revertData.baseCommit.commitSelected.id; this.elementSvc .getElement(reqOb, 2, false) .then( @@ -74,19 +74,19 @@ class RevertConfirmController implements VeModalController { documentation: targetOb.documentation, _projectId: this.reqOb.projectId, _refId: this.reqOb.refId, - } + }; if (revertOb.type === 'Property' || revertOb.type === 'Port') { - revertOb.defaultValue = _.cloneDeep(targetOb.defaultValue) + revertOb.defaultValue = _.cloneDeep(targetOb.defaultValue); } else if (revertOb.type === 'ElementTaggedValue') { - ;(revertOb as ElementTaggedValueObject).valueIds = _.cloneDeep( + (revertOb as ElementTaggedValueObject).valueIds = _.cloneDeep( (targetOb as ElementTaggedValueObject).valueIds - ) + ); } else if (revertOb.type === 'Slot' || revertOb.type.endsWith('TaggedValue')) { - ;(revertOb as SlotObject).value = _.cloneDeep((targetOb as SlotObject).value) + (revertOb as SlotObject).value = _.cloneDeep((targetOb as SlotObject).value); } else if (revertOb.type === 'Constraint' && revertOb.specification) { - ;(revertOb as ConstraintObject).specification = _.cloneDeep( + (revertOb as ConstraintObject).specification = _.cloneDeep( (targetOb as ConstraintObject).specification - ) + ); } this.elementSvc.updateElement(revertOb).then( @@ -94,25 +94,25 @@ class RevertConfirmController implements VeModalController { const data = { element: element, continueEdit: false, - } - this.eventSvc.$broadcast('element.updated', data) - this.modalInstance.close() + }; + this.eventSvc.$broadcast('element.updated', data); + this.modalInstance.close(); }, (reason) => { - this.growl.error('Revert not completed - Update Error: ' + reason.message) + this.growl.error('Revert not completed - Update Error: ' + reason.message); } - ) + ); }, (reason) => { - this.growl.error('Revert not completed - Error: Target Version not found') + this.growl.error('Revert not completed - Error: Target Version not found'); } ) .finally(() => { - this.oking = false - }) + this.oking = false; + }); } cancel(): void { - this.modalInstance.dismiss() + this.modalInstance.dismiss(); } } @@ -160,6 +160,6 @@ const RevertConfirmComponent: VeComponentOptions = { resolve: '<', }, controller: RevertConfirmController, -} +}; -veComponents.component(RevertConfirmComponent.selector, RevertConfirmComponent) +veComponents.component(RevertConfirmComponent.selector, RevertConfirmComponent); diff --git a/src/ve-components/diffs/modals/save-conflict.component.ts b/src/ve-components/diffs/modals/save-conflict.component.ts index 0ae49b4d3..a4aa95bb5 100644 --- a/src/ve-components/diffs/modals/save-conflict.component.ts +++ b/src/ve-components/diffs/modals/save-conflict.component.ts @@ -1,44 +1,44 @@ -import { IComponentController } from 'angular' +import { IComponentController } from 'angular'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions } from '@ve-types/angular' -import { ElementObject } from '@ve-types/mms' -import { VeModalInstanceService, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { VeComponentOptions } from '@ve-types/angular'; +import { ElementObject } from '@ve-types/mms'; +import { VeModalInstanceService, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; export interface SaveConflictResolve extends VeModalResolve { - latest: T + latest: T; } export interface SaveConflictResolveFn extends VeModalResolveFn { - latest(): T + latest(): T; } class SaveConflictController implements IComponentController { //bindings - private modalInstance: VeModalInstanceService - resolve: SaveConflictResolve + private modalInstance: VeModalInstanceService; + resolve: SaveConflictResolve; //local - public latest: ElementObject + public latest: ElementObject; $onInit(): void { - this.latest = this.resolve.latest + this.latest = this.resolve.latest; } ok(): void { - this.modalInstance.close('ok') + this.modalInstance.close('ok'); } cancel(): void { - this.modalInstance.close('cancel') + this.modalInstance.close('cancel'); } force(): void { - this.modalInstance.close('force') + this.modalInstance.close('force'); } merge(): void { - this.modalInstance.close('merge') + this.modalInstance.close('merge'); } } @@ -67,6 +67,6 @@ const SaveConflictComponent: VeComponentOptions = { modalInstance: '<', }, controller: SaveConflictController, -} +}; -veComponents.component(SaveConflictComponent.selector, SaveConflictComponent) +veComponents.component(SaveConflictComponent.selector, SaveConflictComponent); diff --git a/src/ve-components/diffs/services/DiffMerge.service.ts b/src/ve-components/diffs/services/DiffMerge.service.ts index 4f088fe43..9db0c311b 100644 --- a/src/ve-components/diffs/services/DiffMerge.service.ts +++ b/src/ve-components/diffs/services/DiffMerge.service.ts @@ -1,42 +1,42 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { RevertConfirmResolveFn } from '@ve-components/diffs' -import { ApiService, ElementService } from '@ve-utils/mms-api-client' +import { RevertConfirmResolveFn } from '@ve-components/diffs'; +import { ApiService, ElementService } from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' -import { CommitObject, ElementObject, ElementsRequest, RefObject } from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +import { VePromise, VeQService } from '@ve-types/angular'; +import { CommitObject, ElementObject, ElementsRequest, RefObject } from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; export interface Commit { - ref: RefObject - isOpen: boolean - refIsOpen?: boolean - history: CommitObject[] - commitSelected: CommitObject | string + ref: RefObject; + isOpen: boolean; + refIsOpen?: boolean; + history: CommitObject[]; + commitSelected: CommitObject | string; } export interface CompareData { - baseCommit: Commit - compareCommit: Commit - element: ElementObject + baseCommit: Commit; + compareCommit: Commit; + element: ElementObject; } export interface DiffResponse { - status?: 'new' | 'deleted' | 'changed' - diff?: DiffDetail + status?: 'new' | 'deleted' | 'changed'; + diff?: DiffDetail; } export interface DiffDetail { - name: boolean - documentation: boolean - value: boolean - [key: string]: boolean + name: boolean; + documentation: boolean; + value: boolean; + [key: string]: boolean; } export class DiffMergeService { - static $inject = ['$q', 'growl', '$uibModal', 'ApiService', 'ElementService'] + static $inject = ['$q', 'growl', '$uibModal', 'ApiService', 'ElementService']; constructor( private $q: VeQService, private growl: angular.growl.IGrowlService, @@ -66,80 +66,80 @@ export class DiffMergeService { component: 'revertConfirm', resolve: { reqOb: () => { - return reqOb + return reqOb; }, revertData: () => { - return revertData + return revertData; }, }, - }) + }); instance.result.then( () => { - this.growl.success('Element reverted') + this.growl.success('Element reverted'); }, () => { - this.growl.error('Revert Cancelled') + this.growl.error('Revert Cancelled'); } - ) + ); } public checkDiff(sourceOb: ElementObject): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); const diff: DiffDetail = { name: false, documentation: false, value: false, - } - let response: DiffResponse + }; + let response: DiffResponse; this.elementSvc.getElement(this.apiSvc.makeElementRequestObject(sourceOb), 1, true, true).then( (targetOb) => { if (!targetOb) { - response.status = 'new' - deferred.resolve(response) + response.status = 'new'; + deferred.resolve(response); } if (sourceOb.name !== targetOb.name) { - diff.name = true + diff.name = true; } if (sourceOb.documentation !== targetOb.documentation) { - diff.documentation = true + diff.documentation = true; } if ( (sourceOb.type === 'Property' || sourceOb.type === 'Port') && !_.isEqual(sourceOb.defaultValue, targetOb.defaultValue) ) { - diff.value = true + diff.value = true; } else if (sourceOb.type === 'Slot' && !_.isEqual(sourceOb.value, targetOb.value)) { - diff.value = true + diff.value = true; } else if ( sourceOb.type === 'Constraint' && !_.isEqual(sourceOb.specification, targetOb.specification) ) { - diff.value = true + diff.value = true; } - let changed = false + let changed = false; Object.keys(diff).forEach((value) => { - changed = changed || diff[value] - }) + changed = changed || diff[value]; + }); if (changed) { response = { status: 'changed', diff, - } + }; } - deferred.resolve(response) + deferred.resolve(response); }, (reason) => { if (reason.status === 410) { - response.status = 'deleted' - deferred.resolve(response) + response.status = 'deleted'; + deferred.resolve(response); } else { - this.growl.error(`Diff Check not completed - ${reason.message}`) - deferred.reject(null) + this.growl.error(`Diff Check not completed - ${reason.message}`); + deferred.reject(null); } } - ) - return deferred.promise + ); + return deferred.promise; } } -veComponents.service('DiffMergeService', DiffMergeService) +veComponents.service('DiffMergeService', DiffMergeService); diff --git a/src/ve-components/index.ts b/src/ve-components/index.ts index 1e06f68b1..42e0d382b 100644 --- a/src/ve-components/index.ts +++ b/src/ve-components/index.ts @@ -9,30 +9,30 @@ // import '@ve-core' //Module Main -import './ve-components.module' +import './ve-components.module'; -import './services' +import './services'; -import './components' +import './components'; // Extensions -import './trees' -import './diffs' -import './presentations' -import './transclusions' -import './spec-tools' -import './insertions' +import './trees'; +import './diffs'; +import './presentations'; +import './transclusions'; +import './spec-tools'; +import './insertions'; -export * from './ve-components.module' +export * from './ve-components.module'; -import '../ve-extensions' -import { ElementObject } from '@ve-types/mms' +import '../ve-extensions'; +import { ElementObject } from '@ve-types/mms'; -export default 've-components' +export default 've-components'; export interface PropertySpec { - options?: ElementObject[] - isEnumeration?: boolean - isSlot?: boolean - isTaggedValue?: boolean + options?: ElementObject[]; + isEnumeration?: boolean; + isSlot?: boolean; + isTaggedValue?: boolean; } diff --git a/src/ve-components/insertions/components/index.ts b/src/ve-components/insertions/components/index.ts index 04e141fb4..7fb74bce5 100644 --- a/src/ve-components/insertions/components/index.ts +++ b/src/ve-components/insertions/components/index.ts @@ -1,5 +1,5 @@ -import './insert-comment.component' -import './insert-pe.component' -import './insert-view.component' -import './insert-ref.component' -import './insert-element.component' +import './insert-comment.component'; +import './insert-pe.component'; +import './insert-view.component'; +import './insert-ref.component'; +import './insert-element.component'; diff --git a/src/ve-components/insertions/components/insert-comment.component.ts b/src/ve-components/insertions/components/insert-comment.component.ts index aca5c2d2f..051404f7d 100644 --- a/src/ve-components/insertions/components/insert-comment.component.ts +++ b/src/ve-components/insertions/components/insert-comment.component.ts @@ -1,20 +1,20 @@ -import { Insertion, InsertionService } from '@ve-components/insertions' -import { EditorService } from '@ve-core/editor' -import { ApplicationService, UtilsService } from '@ve-utils/application' -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' -import { Class } from '@ve-utils/utils' +import { Insertion, InsertionService } from '@ve-components/insertions'; +import { EditorService } from '@ve-core/editor'; +import { ApplicationService, UtilsService } from '@ve-utils/application'; +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; +import { Class } from '@ve-utils/utils'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { InsertData } from '@ve-types/components' -import { ElementCreationRequest, ElementObject } from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { InsertData } from '@ve-types/components'; +import { ElementCreationRequest, ElementObject } from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; class InsertCommentController extends Insertion { - protected comment: ElementObject - static $inject = Insertion.$inject + protected comment: ElementObject; + static $inject = Insertion.$inject; constructor( $scope: angular.IScope, @@ -49,12 +49,12 @@ class InsertCommentController extends Insertion { apiSvc, utils, editorSvc - ) + ); } public $onInit(): void { - super.$onInit() - const id = this.apiSvc.createUniqueId() + super.$onInit(); + const id = this.apiSvc.createUniqueId(); this.comment = new Class({ id: id, _projectId: this.mmsProjectId, @@ -64,24 +64,24 @@ class InsertCommentController extends Insertion { type: 'Class', ownerId: 'holding_bin_' + this.mmsProjectId, appliedStereotypeIds: [], - }) - this.oking = false + }); + this.oking = false; } public create = (): VePromise => { if (this.oking) { - this.growl.info('Please wait...') - return + this.growl.info('Please wait...'); + return; } - this.oking = true + this.oking = true; const reqOb: ElementCreationRequest = { elements: [this.comment], elementId: this.comment.id, projectId: this.mmsProjectId, refId: this.mmsRefId, - } - return this.elementSvc.createElement(reqOb) - } + }; + return this.elementSvc.createElement(reqOb); + }; } const InsertCommentComponent: VeComponentOptions = { @@ -115,6 +115,6 @@ const InsertCommentComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertCommentController, -} +}; -veComponents.component(InsertCommentComponent.selector, InsertCommentComponent) +veComponents.component(InsertCommentComponent.selector, InsertCommentComponent); diff --git a/src/ve-components/insertions/components/insert-element.component.ts b/src/ve-components/insertions/components/insert-element.component.ts index b70077d7c..3847913c4 100644 --- a/src/ve-components/insertions/components/insert-element.component.ts +++ b/src/ve-components/insertions/components/insert-element.component.ts @@ -1,29 +1,29 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { Insertion, InsertionService } from '@ve-components/insertions' -import { InsertTransclusionData } from '@ve-components/transclusions' -import { EditorService } from '@ve-core/editor' -import { ApplicationService, UtilsService } from '@ve-utils/application' -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { Insertion, InsertionService } from '@ve-components/insertions'; +import { InsertTransclusionData } from '@ve-components/transclusions'; +import { EditorService } from '@ve-core/editor'; +import { ApplicationService, UtilsService } from '@ve-utils/application'; +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { ElementObject, MmsObject } from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { ElementObject, MmsObject } from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; class InsertElementController extends Insertion { //Bindings - protected parentAction: string + protected parentAction: string; //Locals //protected createType: number = 1 - protected description: string - protected searchExisting: boolean = true - protected disableCreateNew: boolean = false + protected description: string; + protected searchExisting: boolean = true; + protected disableCreateNew: boolean = false; - static $inject = Insertion.$inject + static $inject = Insertion.$inject; constructor( $scope: angular.IScope, @@ -58,15 +58,15 @@ class InsertElementController extends Insertion { apiSvc, insertionSvc, editorSvc - ) + ); } public $onInit(): void { - super.$onInit() + super.$onInit(); if (this.insertData.selected && this.insertData.isNew) { - this.createItem = this.insertData.selected - this.searchExisting = false + this.createItem = this.insertData.selected; + this.searchExisting = false; } else { this.createItem = { id: `${this.apiSvc.createUniqueId()}`, @@ -77,32 +77,32 @@ class InsertElementController extends Insertion { documentation: '', type: 'Class', appliedStereotypeIds: [], - } + }; } - this.disableCreateNew = this.insertData.viewLink + this.disableCreateNew = this.insertData.viewLink; if (!this.disableCreateNew) { - this.editItem = this.elementSvc.openEdit(this.createItem, false) + this.editItem = this.elementSvc.openEdit(this.createItem, false); } - this.description = 'Search for an existing element before you ' + this.parentAction + this.description = 'Search for an existing element before you ' + this.parentAction; - this.searchOptions.getProperties = true - this.searchOptions.emptyDocTxt = 'This field is empty, but you can still click here to mms-cf a placeholder.' + this.searchOptions.getProperties = true; + this.searchOptions.emptyDocTxt = 'This field is empty, but you can still click here to mms-cf a placeholder.'; } public create = (): VePromise => { - this.insertData.isNew = true - return this.insertionSvc.createAction(this.createItem, this.insertData.noPublish) - } + this.insertData.isNew = true; + return this.insertionSvc.createAction(this.createItem, this.insertData.noPublish); + }; public fail = >(reason: V): void => { if (reason.status === 401) { - this.reLogin() + this.reLogin(); } else if (reason.status === 422) { - this.continue = true + this.continue = true; } else { - this.growl.error(`Create ${_.upperCase(this.insertData.type)} Error: ${reason.message}`) + this.growl.error(`Create ${_.upperCase(this.insertData.type)} Error: ${reason.message}`); } - } + }; } // Component for inserting cross-reference @@ -176,6 +176,6 @@ const InsertComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertElementController, -} +}; -veComponents.component(InsertComponent.selector, InsertComponent) +veComponents.component(InsertComponent.selector, InsertComponent); diff --git a/src/ve-components/insertions/components/insert-pe.component.ts b/src/ve-components/insertions/components/insert-pe.component.ts index 380d267b6..6889cdcfd 100644 --- a/src/ve-components/insertions/components/insert-pe.component.ts +++ b/src/ve-components/insertions/components/insert-pe.component.ts @@ -1,28 +1,28 @@ -import { Insertion, InsertionService } from '@ve-components/insertions' -import { EditorService } from '@ve-core/editor' -import { SearchFilter } from '@ve-core/search/mms-search.component' -import { ApplicationService, UtilsService } from '@ve-utils/application' -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { Insertion, InsertionService } from '@ve-components/insertions'; +import { EditorService } from '@ve-core/editor'; +import { SearchFilter } from '@ve-core/search/mms-search.component'; +import { ApplicationService, UtilsService } from '@ve-utils/application'; +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { InsertData } from '@ve-types/components' -import { InstanceValueObject, ViewCreationRequest, ViewInstanceSpec } from '@ve-types/mms' -import { TreeBranch } from '@ve-types/tree' -import { VeModalService } from '@ve-types/view-editor' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { InsertData } from '@ve-types/components'; +import { InstanceValueObject, ViewCreationRequest, ViewInstanceSpec } from '@ve-types/mms'; +import { TreeBranch } from '@ve-types/tree'; +import { VeModalService } from '@ve-types/view-editor'; export interface InsertPresentationData extends InsertData { - parentBranch: TreeBranch - viewOrSectionOb?: ViewInstanceSpec - addPeIndex: number + parentBranch: TreeBranch; + viewOrSectionOb?: ViewInstanceSpec; + addPeIndex: number; } class InsertPeController extends Insertion { - protected aggr: 'composite' | 'shared' + protected aggr: 'composite' | 'shared'; - static $inject = Insertion.$inject + static $inject = Insertion.$inject; constructor( $scope: angular.IScope, @@ -57,54 +57,54 @@ class InsertPeController extends Insertion { apiSvc, utils, editorSvc - ) + ); } $onInit(): void { - super.$onInit() + super.$onInit(); } public queryFilter = (): SearchFilter => { const filters: { - appliedStereotypeIds?: string[] - classifierIds?: string[] - } = {} + appliedStereotypeIds?: string[]; + classifierIds?: string[]; + } = {}; if (this.type === 'Table') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'TableT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Table', this.schema), - ] + ]; } else if (this.type === 'List') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'ListT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'List', this.schema), - ] + ]; } else if (this.type === 'Image') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'ImageT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Image', this.schema), - ] + ]; } else if (this.type === 'Paragraph') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'ParagraphT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Paragraph', this.schema), - ] + ]; } else if (this.type === 'Section') { filters.classifierIds = [ this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'SectionT', this.schema), this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Section', this.schema), - ] + ]; } else { - filters.classifierIds = [this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', this.type, this.schema)] + filters.classifierIds = [this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', this.type, this.schema)]; } - return filters - } + return filters; + }; public success = (): void => { - const elemType = this.type - this.insertionSvc.successUpdates(elemType, this.insertData.viewOrSectionOb.id) - this.growl.success(this.type + ' is being created') - } + const elemType = this.type; + this.insertionSvc.successUpdates(elemType, this.insertData.viewOrSectionOb.id); + this.growl.success(this.type + ' is being created'); + }; public insert = (elementOb: ViewInstanceSpec): VePromise => { const instanceVal: InstanceValueObject = { @@ -113,14 +113,14 @@ class InsertPeController extends Insertion { type: 'InstanceValue', _projectId: this.projectId, _refId: this.refId, - } + }; const viewReqOb: ViewCreationRequest = { viewId: this.insertData.viewOrSectionOb.id, projectId: this.projectId, refId: this.refId, - } - return this.viewSvc.insertToViewOrSection(viewReqOb, instanceVal, this.insertData.addPeIndex) - } + }; + return this.viewSvc.insertToViewOrSection(viewReqOb, instanceVal, this.insertData.addPeIndex); + }; public create = (): VePromise => { return this.viewSvc.createInstanceSpecification( @@ -128,8 +128,8 @@ class InsertPeController extends Insertion { this.type, this.name, this.insertData.addPeIndex - ) - } + ); + }; } const InsertPeComponent: VeComponentOptions = { @@ -179,6 +179,6 @@ const InsertPeComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertPeController, -} +}; -veComponents.component(InsertPeComponent.selector, InsertPeComponent) +veComponents.component(InsertPeComponent.selector, InsertPeComponent); diff --git a/src/ve-components/insertions/components/insert-ref.component.ts b/src/ve-components/insertions/components/insert-ref.component.ts index 181cb5ae6..69790680e 100644 --- a/src/ve-components/insertions/components/insert-ref.component.ts +++ b/src/ve-components/insertions/components/insert-ref.component.ts @@ -1,31 +1,31 @@ -import flatpickr from 'flatpickr' +import flatpickr from 'flatpickr'; -import { Insertion, InsertionService } from '@ve-components/insertions' -import { EditorService } from '@ve-core/editor' -import { ApplicationService, UtilsService } from '@ve-utils/application' -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { Insertion, InsertionService } from '@ve-components/insertions'; +import { EditorService } from '@ve-core/editor'; +import { ApplicationService, UtilsService } from '@ve-utils/application'; +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { InsertData } from '@ve-types/components' -import { CommitObject, RefObject, RefsResponse } from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { InsertData } from '@ve-types/components'; +import { CommitObject, RefObject, RefsResponse } from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; export interface InsertRefData extends InsertData { - parentRefId: string - lastCommit: boolean + parentRefId: string; + lastCommit: boolean; } class InsertRefController extends Insertion { - static $inject = [...Insertion.$inject, '$filter'] + static $inject = [...Insertion.$inject, '$filter']; - protected parentCommit: CommitObject - protected lastCommit: boolean - protected now: Date - protected dateTimeOpts: flatpickr.Options.Options - protected timestamp: Date + protected parentCommit: CommitObject; + protected lastCommit: boolean; + protected now: Date; + protected dateTimeOpts: flatpickr.Options.Options; + protected timestamp: Date; constructor( $scope: angular.IScope, @@ -60,22 +60,22 @@ class InsertRefController extends Insertion { apiSvc, utils, editorSvc - ) + ); } public $onInit(): void { - super.$onInit() + super.$onInit(); - this.lastCommit = this.insertData.lastCommit - this.now = new Date() - this.timestamp = this.now + this.lastCommit = this.insertData.lastCommit; + this.now = new Date(); + this.timestamp = this.now; this.createItem = { id: this.apiSvc.createUniqueId(), _projectId: this.projectId, type: this.type, description: '', permission: 'read', - } + }; this.dateTimeOpts = { enableTime: true, enableSeconds: true, @@ -84,11 +84,11 @@ class InsertRefController extends Insertion { time_24hr: true, maxDate: new Date(), onClose: (selectedDates): void => { - this.lastCommit = false - this.timestamp = selectedDates[0] + this.lastCommit = false; + this.timestamp = selectedDates[0]; }, inline: false, - } + }; } public create = (): VePromise => { @@ -99,8 +99,8 @@ class InsertRefController extends Insertion { description: this.createItem.description, id: this.apiSvc.createUniqueId(), //parentCommitId: null - } - if (this.insertData.parentRefId) refObj.parentRefId = this.insertData.parentRefId + }; + if (this.insertData.parentRefId) refObj.parentRefId = this.insertData.parentRefId; /* if (!this.lastCommit || this.type === 'Tag') { // Make call to history?maxTimestamp to get closest commit id to branch off @@ -112,17 +112,17 @@ class InsertRefController extends Insertion { }, this.insertReject) } else { */ - return this.projectSvc.createRef(refObj, this.projectId) + return this.projectSvc.createRef(refObj, this.projectId); //} - } + }; public resolve = (data: RefObject): void => { - this.growl.success(this.type + ' is being created') + this.growl.success(this.type + ' is being created'); if (this.type === 'Tag') { - this.growl.info('Please wait for a completion email prior to viewing of the tag.') + this.growl.info('Please wait for a completion email prior to viewing of the tag.'); } - this.insertApi.resolve(data) - } + this.insertApi.resolve(data); + }; } const InsertRefComponent: VeComponentOptions = { @@ -203,6 +203,6 @@ const InsertRefComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertRefController, -} +}; -veComponents.component(InsertRefComponent.selector, InsertRefComponent) +veComponents.component(InsertRefComponent.selector, InsertRefComponent); diff --git a/src/ve-components/insertions/components/insert-view.component.ts b/src/ve-components/insertions/components/insert-view.component.ts index 3453aa9e0..aa8d74e30 100644 --- a/src/ve-components/insertions/components/insert-view.component.ts +++ b/src/ve-components/insertions/components/insert-view.component.ts @@ -1,28 +1,28 @@ -import { Insertion, InsertionService } from '@ve-components/insertions' -import { EditorService } from '@ve-core/editor' -import { SearchFilter } from '@ve-core/search/mms-search.component' -import { ApplicationService, UtilsService } from '@ve-utils/application' -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { Insertion, InsertionService } from '@ve-components/insertions'; +import { EditorService } from '@ve-core/editor'; +import { SearchFilter } from '@ve-core/search/mms-search.component'; +import { ApplicationService, UtilsService } from '@ve-utils/application'; +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { InsertData } from '@ve-types/components' -import { ViewObject } from '@ve-types/mms' -import { TreeBranch } from '@ve-types/tree' -import { VeModalService } from '@ve-types/view-editor' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { InsertData } from '@ve-types/components'; +import { ViewObject } from '@ve-types/mms'; +import { TreeBranch } from '@ve-types/tree'; +import { VeModalService } from '@ve-types/view-editor'; export interface InsertViewData extends InsertData { - parentBranch: TreeBranch - seenViewIds: { [viewId: string]: TreeBranch } - newViewAggr?: 'composite' | 'shared' + parentBranch: TreeBranch; + seenViewIds: { [viewId: string]: TreeBranch }; + newViewAggr?: 'composite' | 'shared'; } class InsertViewController extends Insertion { - private aggr: 'composite' | 'shared' = 'composite' + private aggr: 'composite' | 'shared' = 'composite'; - static $inject = Insertion.$inject + static $inject = Insertion.$inject; constructor( $scope: angular.IScope, @@ -57,32 +57,32 @@ class InsertViewController extends Insertion { apiSvc, utils, editorSvc - ) + ); } public $onInit(): void { - super.$onInit() + super.$onInit(); if (this.insertData.newViewAggr) { - this.aggr = this.insertData.newViewAggr + this.aggr = this.insertData.newViewAggr; } if (this.insertData.parentBranch) { - this.parentData = this.insertData.parentBranch.data + this.parentData = this.insertData.parentBranch.data; } } public insert = (data: ViewObject): VePromise => { - const deferred = this.$q.defer() - const view = data - const viewId = view.id + const deferred = this.$q.defer(); + const view = data; + const viewId = view.id; if (this.insertData.seenViewIds[viewId]) { - this.growl.error('Error: View ' + view.name + ' is already in this document.') - return + this.growl.error('Error: View ' + view.name + ' is already in this document.'); + return; } if (this.oking) { - this.growl.info('Please wait...') - return + this.growl.info('Please wait...'); + return; } - this.oking = true + this.oking = true; this.viewSvc .addViewToParentView({ parentViewId: this.parentData.id, @@ -106,34 +106,34 @@ class InsertViewController extends Insertion { ) .then( (realView) => { - deferred.resolve(realView) + deferred.resolve(realView); }, (reason) => { - reason.data.elements = [view] - deferred.reject(reason) + reason.data.elements = [view]; + deferred.reject(reason); } - ) + ); }, (reason) => { - this.growl.error(`View Add Error: ${reason.message}`) + this.growl.error(`View Add Error: ${reason.message}`); } - ) - return deferred.promise - } + ); + return deferred.promise; + }; public last = (): void => { - this.growl.success('View Added') - } + this.growl.success('View Added'); + }; public queryFilter = (): SearchFilter => { - const filters: SearchFilter = {} + const filters: SearchFilter = {}; filters.appliedStereotypeIds = [ this.schemaSvc.getSchema('VIEW_SID', this.schema), this.schemaSvc.getSchema('DOCUMENT_SID', this.schema), ...this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema), - ] - return filters - } + ]; + return filters; + }; public create = (): VePromise => { if (this.type === 'Document') { @@ -151,7 +151,7 @@ class InsertViewController extends Insertion { _refId: this.refId, type: 'Class', } - ) + ); } else if (this.type === 'View') { return this.viewSvc.createView(this.parentData, { id: this.apiSvc.createUniqueId(), @@ -159,20 +159,20 @@ class InsertViewController extends Insertion { _projectId: this.projectId, _refId: this.refId, type: 'Class', - }) + }); } else if (this.type === 'Group') { return this.viewSvc.createGroup(this.createItem.name, { _projectId: this.projectId, _refId: this.refId, id: this.ownerId, - }) + }); } else { return this.$q.reject({ status: 666, message: 'Unsupported View Type', - }) + }); } - } + }; } const InsertViewComponent: VeComponentOptions = { @@ -232,8 +232,8 @@ const InsertViewComponent: VeComponentOptions = { mmsOrgId: '@', }, controller: InsertViewController, -} +}; -veComponents.component(InsertViewComponent.selector, InsertViewComponent) -veComponents.component('addGroup', InsertViewComponent) -veComponents.component('addDocument', InsertViewComponent) +veComponents.component(InsertViewComponent.selector, InsertViewComponent); +veComponents.component('addGroup', InsertViewComponent); +veComponents.component('addDocument', InsertViewComponent); diff --git a/src/ve-components/insertions/index.ts b/src/ve-components/insertions/index.ts index 7d7171262..0bdb1f101 100644 --- a/src/ve-components/insertions/index.ts +++ b/src/ve-components/insertions/index.ts @@ -1,8 +1,8 @@ -export * from './insertion.controller' +export * from './insertion.controller'; -import './services' +import './services'; -export * from './services' -import './insert-element-modal.component' +export * from './services'; +import './insert-element-modal.component'; -import './components' +import './components'; diff --git a/src/ve-components/insertions/insert-element-modal.component.ts b/src/ve-components/insertions/insert-element-modal.component.ts index a9d2a9ba4..d7bb836c9 100644 --- a/src/ve-components/insertions/insert-element-modal.component.ts +++ b/src/ve-components/insertions/insert-element-modal.component.ts @@ -1,29 +1,29 @@ -import { ExtensionService } from '@ve-components/services' -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { ExtensionService } from '@ve-components/services'; +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { InsertApi, InsertData, InsertResolve } from '@ve-types/components' -import { ElementObject, MmsObject } from '@ve-types/mms' -import { VeModalComponent, VeModalController, VeModalService } from '@ve-types/view-editor' +import { InsertApi, InsertData, InsertResolve } from '@ve-types/components'; +import { ElementObject, MmsObject } from '@ve-types/mms'; +import { VeModalComponent, VeModalController, VeModalService } from '@ve-types/view-editor'; class InsertController extends VeModalControllerImpl implements VeModalController { - static $inject = ['$scope', '$compile', '$element', '$timeout', '$uibModal', 'growl', 'ExtensionService'] + static $inject = ['$scope', '$compile', '$element', '$timeout', '$uibModal', 'growl', 'ExtensionService']; - private schema = 'cameo' + private schema = 'cameo'; - protected resolve: InsertResolve + protected resolve: InsertResolve; //local - private insertData: InsertData - private insertApi: InsertApi - private projectId: string - private refId: string - private orgId: string - private insertType: string - private type: string + private insertData: InsertData; + private insertApi: InsertApi; + private projectId: string; + private refId: string; + private orgId: string; + private insertType: string; + private type: string; - private $componentEl: JQuery + private $componentEl: JQuery; constructor( private $scope: angular.IScope, @@ -34,53 +34,53 @@ class InsertController extends VeModalControllerImpl implements VeMod private growl: angular.growl.IGrowlService, private extensionSvc: ExtensionService ) { - super() + super(); } - public parentData: ElementObject = {} as ElementObject + public parentData: ElementObject = {} as ElementObject; $onInit(): void { - this.insertData = this.resolve.getInsertData + this.insertData = this.resolve.getInsertData; - this.insertType = this.insertData.insertType - this.projectId = this.resolve.getProjectId - this.refId = this.resolve.getRefId ? this.resolve.getRefId : 'master' - this.orgId = this.resolve.getOrgId ? this.resolve.getOrgId : null + this.insertType = this.insertData.insertType; + this.projectId = this.resolve.getProjectId; + this.refId = this.resolve.getRefId ? this.resolve.getRefId : 'master'; + this.orgId = this.resolve.getOrgId ? this.resolve.getOrgId : null; - this.type = this.insertData.type + this.type = this.insertData.type; this.insertApi = { resolve: (data): void => { - this.modalInstance.close(data) + this.modalInstance.close(data); }, reject: (reason): void => { - this.modalInstance.dismiss(reason) + this.modalInstance.dismiss(reason); }, - } + }; } $postLink(): void { - this.recompile() + this.recompile(); } public recompile = (): void => { - let tag = this.extensionSvc.getTagByType('insert', this.insertType) + let tag = this.extensionSvc.getTagByType('insert', this.insertType); if (tag === 'extension-error') { - tag = 'insert-element' + tag = 'insert-element'; } - const newPe = $('
    ') + const newPe = $('
    '); $(newPe).append( `<${tag} insert-data="$ctrl.insertData" insert-api="$ctrl.insertApi" mms-project-id="{{$ctrl.projectId}}" ${this.refId ? `mms-ref-id="{{$ctrl.refId}}" ` : ''}${ this.orgId ? 'mms-org-id="{{$ctrl.orgId}}" ' : '' }>` - ) - $(this.$element).append(newPe) - this.$compile(newPe)(this.$scope) - } + ); + $(this.$element).append(newPe); + this.$compile(newPe)(this.$scope); + }; public cancel = (): void => { - this.modalInstance.dismiss() - } + this.modalInstance.dismiss(); + }; } const InsertElementModalComponent: VeModalComponent = { @@ -98,6 +98,6 @@ const InsertElementModalComponent: VeModalComponent = { resolve: '<', }, controller: InsertController, -} +}; -veComponents.component(InsertElementModalComponent.selector, InsertElementModalComponent) +veComponents.component(InsertElementModalComponent.selector, InsertElementModalComponent); diff --git a/src/ve-components/insertions/insertion.controller.ts b/src/ve-components/insertions/insertion.controller.ts index 112e2a78f..d506d1c3b 100644 --- a/src/ve-components/insertions/insertion.controller.ts +++ b/src/ve-components/insertions/insertion.controller.ts @@ -1,17 +1,17 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { LoginModalResolveFn } from '@ve-app/main/modals/login-modal.component' -import { InsertionService } from '@ve-components/insertions' -import { EditorService } from '@ve-core/editor' -import { ApplicationService, UtilsService } from '@ve-utils/application' -import { EditObject } from '@ve-utils/core' -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { LoginModalResolveFn } from '@ve-app/main/modals/login-modal.component'; +import { InsertionService } from '@ve-components/insertions'; +import { EditorService } from '@ve-core/editor'; +import { ApplicationService, UtilsService } from '@ve-utils/application'; +import { EditObject } from '@ve-utils/core'; +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { InsertApi, InsertData } from '@ve-types/components' -import { BasicResponse, ElementObject, MmsObject } from '@ve-types/mms' -import { VeModalService, VeModalSettings, veSearchCallback, VeSearchOptions } from '@ve-types/view-editor' +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { InsertApi, InsertData } from '@ve-types/components'; +import { BasicResponse, ElementObject, MmsObject } from '@ve-types/mms'; +import { VeModalService, VeModalSettings, veSearchCallback, VeSearchOptions } from '@ve-types/view-editor'; /** * @name veComponents/Insertion @@ -30,26 +30,26 @@ export class Insertion< U extends MmsObject = ElementObject > { //Bindings - public insertData: T - public insertApi: InsertApi>> - public mmsProjectId: string - public mmsRefId: string - public mmsOrgId: string + public insertData: T; + public insertApi: InsertApi>>; + public mmsProjectId: string; + public mmsRefId: string; + public mmsOrgId: string; //Locals - public name: string - public ownerId: string - public searchOptions: VeSearchOptions = null - type: string - createForm: boolean = true - oking: boolean = false - continue: boolean = false - projectId: string - refId: string - orgId: string - insertType: string - createItem: U - editItem: EditObject + public name: string; + public ownerId: string; + public searchOptions: VeSearchOptions = null; + type: string; + createForm: boolean = true; + oking: boolean = false; + continue: boolean = false; + projectId: string; + refId: string; + orgId: string; + insertType: string; + createItem: U; + editItem: EditObject; static $inject = [ '$scope', @@ -67,13 +67,13 @@ export class Insertion< 'ApiService', 'InsertionService', 'EditorService', - ] + ]; - protected schema = 'cameo' + protected schema = 'cameo'; //local - private $componentEl: JQuery + private $componentEl: JQuery; constructor( protected $scope: angular.IScope, @@ -93,14 +93,14 @@ export class Insertion< protected editorSvc: EditorService ) {} - public parentData: ElementObject = {} as ElementObject + public parentData: ElementObject = {} as ElementObject; $onInit(): void { - this.insertType = this.insertData.insertType - this.projectId = this.mmsProjectId - this.refId = this.mmsRefId ? this.mmsRefId : '' - this.orgId = this.mmsOrgId - this.type = this.insertData.type + this.insertType = this.insertData.insertType; + this.projectId = this.mmsProjectId; + this.refId = this.mmsRefId ? this.mmsRefId : ''; + this.orgId = this.mmsOrgId; + this.type = this.insertData.type; this.searchOptions = { callback: this.callback, @@ -110,98 +110,98 @@ export class Insertion< hideFilterOptions: true, closeable: false, closeCallback: this.cancel, - } + }; } public ok = (): void => { if (this.oking) { - this.growl.info('Please wait...') - return + this.growl.info('Please wait...'); + return; } - this.oking = true + this.oking = true; - this.ownerId = this.parentData && this.parentData.id ? this.parentData.id : 'holding_bin_' + this.projectId - let ready = this.$q.resolve(null) + this.ownerId = this.parentData && this.parentData.id ? this.parentData.id : 'holding_bin_' + this.projectId; + let ready = this.$q.resolve(null); if (this.editItem) { - ready = this.editorSvc.updateAllData(this.editItem.key, true, true) + ready = this.editorSvc.updateAllData(this.editItem.key, true, true); } ready.then( () => { this.create() .then((data) => { - this.insertResolve(data, 'created') + this.insertResolve(data, 'created'); }, this.insertReject) - .finally(this.insertFinally) + .finally(this.insertFinally); }, (reason) => this.insertReject(reason) - ) - } + ); + }; public loginCb = (result?: boolean): void => { if (result) { - this.ok() + this.ok(); } else { this.insertReject({ status: 666, message: 'User not Authenticated', - }) + }); } - } + }; public reLogin = (): void => { - this.$componentEl = this.$element.children() - this.$element.empty() + this.$componentEl = this.$element.children(); + this.$element.empty(); const settings: VeModalSettings = { component: 'loginModal', resolve: { continue: () => { - return true + return true; }, }, - } - const instance = this.$uibModal.open(settings) + }; + const instance = this.$uibModal.open(settings); instance.result.then(this.loginCb, () => { this.insertReject({ status: 666, message: 'User Cancelled Authentication', - }) - }) - } + }); + }); + }; public insertResolve = (data: U, type: string): void => { - this.growl.success(this.type + ' is being ' + type) - this.success(data) - this.insertApi.resolve(data) - } + this.growl.success(this.type + ' is being ' + type); + this.success(data); + this.insertApi.resolve(data); + }; protected insertReject = >>(reason: V): void => { - this.fail(reason) + this.fail(reason); if (!this.continue) { - this.insertApi.reject(reason) + this.insertApi.reject(reason); } - this.continue = false - } + this.continue = false; + }; public success = (data?: U): void => { /* Put custom success logic here*/ - } + }; public fail = >(reason: V): void => { if (reason.status === 401) { - this.reLogin() + this.reLogin(); } else { - this.growl.error(`Create ${_.upperCase(this.insertData.type)} Error: ${reason.message}`) + this.growl.error(`Create ${_.upperCase(this.insertData.type)} Error: ${reason.message}`); } - } + }; public last = (): void => { /* Put custom finally logic here*/ - } + }; public insertFinally = (): void => { - this.last() - this.oking = false - } + this.last(); + this.oking = false; + }; /** * @name Insertion/callback @@ -210,51 +210,51 @@ export class Insertion< */ public callback: veSearchCallback = (data: U, property?: string): void => { if (this.oking) { - this.growl.info('Please wait...') - return + this.growl.info('Please wait...'); + return; } - this.oking = true + this.oking = true; this.addExisting(data, property) .then((finalData) => { if (this.editItem) { - this.editorSvc.cleanUpEdit(this.editItem.key) + this.editorSvc.cleanUpEdit(this.editItem.key); } - this.insertData.isNew = false - this.insertResolve(finalData, 'added') + this.insertData.isNew = false; + this.insertResolve(finalData, 'added'); }, this.insertReject) - .finally(this.insertFinally) - } + .finally(this.insertFinally); + }; public cancel = (): void => { if (this.insertData.selected) { - this.insertionSvc.cancelAction(this.insertData.selected) + this.insertionSvc.cancelAction(this.insertData.selected); } if (this.insertApi.reject) { - this.insertApi.reject({ status: 444, message: 'User cancelled request' }) + this.insertApi.reject({ status: 444, message: 'User cancelled request' }); } - } + }; /** * */ public queryFilter = (): { - appliedStereotypeIds?: string[] - classifierIds?: string[] + appliedStereotypeIds?: string[]; + classifierIds?: string[]; } => { /* Implement and Search Filtering Logic Here */ return { appliedStereotypeIds: [], classifierIds: [], - } - } + }; + }; /** * * @return {VePromise>} */ public create = (): VePromise> => { - this.growl.error(`Add Item of Type ${this.type} is not supported`) - return this.$q.reject() - } + this.growl.error(`Add Item of Type ${this.type} is not supported`); + return this.$q.reject(); + }; /** * @name Insertion/addExisting @@ -263,6 +263,6 @@ export class Insertion< * @return {VePromise} */ public addExisting = (existingOb: U, property?: string): VePromise => { - return this.$q.resolve(existingOb) - } + return this.$q.resolve(existingOb); + }; } diff --git a/src/ve-components/insertions/services/Insertion.service.ts b/src/ve-components/insertions/services/Insertion.service.ts index 633522ffb..9bc6b0683 100644 --- a/src/ve-components/insertions/services/Insertion.service.ts +++ b/src/ve-components/insertions/services/Insertion.service.ts @@ -1,18 +1,18 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { EditorService } from '@ve-core/editor' -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ElementService } from '@ve-utils/mms-api-client' -import { Class } from '@ve-utils/utils' +import { EditorService } from '@ve-core/editor'; +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ElementService } from '@ve-utils/mms-api-client'; +import { Class } from '@ve-utils/utils'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' -import { ElementObject } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { ElementObject } from '@ve-types/mms'; export class InsertionService { - static $inject = ['$q', '$timeout', 'growl', 'ElementService', 'EditorService', 'RootScopeService', 'EventService'] + static $inject = ['$q', '$timeout', 'growl', 'ElementService', 'EditorService', 'RootScopeService', 'EventService']; constructor( private $q: VeQService, @@ -25,37 +25,37 @@ export class InsertionService { ) {} public successUpdates = (elemType: string, id: string): void => { - this.eventSvc.$broadcast('content-reorder.refresh') - this.eventSvc.$broadcast('content-reorder-saved', { id: id }) - this.growl.success('Adding ' + elemType + ' Successful') + this.eventSvc.$broadcast('content-reorder.refresh'); + this.eventSvc.$broadcast('content-reorder-saved', { id: id }); + this.growl.success('Adding ' + elemType + ' Successful'); // Show comments when creating a comment PE if (elemType === 'Comment' && !this.rootScopeSvc.veCommentsOn()) { void this.$timeout( () => { - $('.show-comments').trigger('click') + $('.show-comments').trigger('click'); }, 0, false - ) + ); } - } + }; public createAction = (createItem: ElementObject, noPublish: boolean): VePromise => { if (!createItem.name) { - this.growl.error('Error: A name for your new element is required.') - return this.$q.reject({ status: 422 }) + this.growl.error('Error: A name for your new element is required.'); + return this.$q.reject({ status: 422 }); } - const editKey = this.elementSvc.getEditElementKey(createItem) + const editKey = this.elementSvc.getEditElementKey(createItem); - const toCreate: ElementObject = new Class(createItem) + const toCreate: ElementObject = new Class(createItem); - let promise: VePromise + let promise: VePromise; if (!noPublish) { promise = this.elementSvc.createElement({ elements: [toCreate], refId: toCreate._refId, projectId: toCreate._projectId, - }) + }); } else { promise = this.$q.resolve( this.elementSvc.cacheElement( @@ -65,19 +65,19 @@ export class InsertionService { }, _.cloneDeep(toCreate) ) - ) + ); } promise.finally(() => { - this.editorSvc.cleanUpEdit(editKey) - }) + this.editorSvc.cleanUpEdit(editKey); + }); - return promise - } + return promise; + }; public cancelAction = (cancelledItem: ElementObject): void => { - this.editorSvc.cleanUpEdit(this.elementSvc.getEditElementKey(cancelledItem)) - } + this.editorSvc.cleanUpEdit(this.elementSvc.getEditElementKey(cancelledItem)); + }; } -veComponents.service('InsertionService', InsertionService) +veComponents.service('InsertionService', InsertionService); diff --git a/src/ve-components/insertions/services/index.ts b/src/ve-components/insertions/services/index.ts index 602eb6176..83a1f3fba 100644 --- a/src/ve-components/insertions/services/index.ts +++ b/src/ve-components/insertions/services/index.ts @@ -1,3 +1,3 @@ -import './Insertion.service' +import './Insertion.service'; -export * from './Insertion.service' +export * from './Insertion.service'; diff --git a/src/ve-components/presentations/add-pe-menu.component.ts b/src/ve-components/presentations/add-pe-menu.component.ts index 4c8cd170f..ccdb20482 100644 --- a/src/ve-components/presentations/add-pe-menu.component.ts +++ b/src/ve-components/presentations/add-pe-menu.component.ts @@ -1,20 +1,20 @@ -import { IComponentController } from 'angular' +import { IComponentController } from 'angular'; -import { PresentationService } from '@ve-components/presentations/services/Presentation.service' -import { RootScopeService } from '@ve-utils/application' +import { PresentationService } from '@ve-components/presentations/services/Presentation.service'; +import { RootScopeService } from '@ve-utils/application'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions } from '@ve-types/angular' -import { ViewObject } from '@ve-types/mms' +import { VeComponentOptions } from '@ve-types/angular'; +import { ViewObject } from '@ve-types/mms'; class AddPeMenuController implements IComponentController { // Bindings - private mmsView: ViewObject + private mmsView: ViewObject; - public addPeIndex: number + public addPeIndex: number; - static $inject = ['PresentationService', 'RootScopeService'] + static $inject = ['PresentationService', 'RootScopeService']; constructor(private presentationSvc: PresentationService, private rootScopeSvc: RootScopeService) {} /** @@ -23,22 +23,22 @@ class AddPeMenuController implements IComponentController { */ public addEltAction = (index: number, type: string): void => { if (!this.rootScopeSvc.veEditMode()) { - return + return; } - this.addPeIndex = index - this.presentationSvc.addPresentationElement(this, type, this.mmsView) - } + this.addPeIndex = index; + this.presentationSvc.addPresentationElement(this, type, this.mmsView); + }; public setPeLineVisibility = ($event: JQuery.ClickEvent): void => { window.setTimeout(() => { - const peContainer = $($event.currentTarget).closest('.add-pe-button-container') + const peContainer = $($event.currentTarget).closest('.add-pe-button-container'); if (peContainer.find('.dropdown-menu').css('display') == 'none') { - peContainer.find('hr').css('visibility', 'hidden') + peContainer.find('hr').css('visibility', 'hidden'); } else { - peContainer.find('hr').css('visibility', 'visible') + peContainer.find('hr').css('visibility', 'visible'); } - }) - } + }); + }; } const InsertPeMenuComponent: VeComponentOptions = { @@ -90,6 +90,6 @@ const InsertPeMenuComponent: VeComponentOptions = { index: '<', }, controller: AddPeMenuController, -} +}; -veComponents.component(InsertPeMenuComponent.selector, InsertPeMenuComponent) +veComponents.component(InsertPeMenuComponent.selector, InsertPeMenuComponent); diff --git a/src/ve-components/presentations/components/present-comment.component.ts b/src/ve-components/presentations/components/present-comment.component.ts index 395594d19..7d823d333 100644 --- a/src/ve-components/presentations/components/present-comment.component.ts +++ b/src/ve-components/presentations/components/present-comment.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations' +import { PresentationLite } from '@ve-components/presentations'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; const PresentCommentComponent: IPresentationComponentOptions = { selector: 'presentComment', @@ -13,6 +13,6 @@ const PresentCommentComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -} +}; -veComponents.component(PresentCommentComponent.selector, PresentCommentComponent) +veComponents.component(PresentCommentComponent.selector, PresentCommentComponent); diff --git a/src/ve-components/presentations/components/present-equation.component.ts b/src/ve-components/presentations/components/present-equation.component.ts index 5bf5fec2d..f9c791809 100644 --- a/src/ve-components/presentations/components/present-equation.component.ts +++ b/src/ve-components/presentations/components/present-equation.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations' +import { PresentationLite } from '@ve-components/presentations'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; const PresentEquationComponent: IPresentationComponentOptions = { selector: 'presentEquation', @@ -14,6 +14,6 @@ const PresentEquationComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -} +}; -veComponents.component(PresentEquationComponent.selector, PresentEquationComponent) +veComponents.component(PresentEquationComponent.selector, PresentEquationComponent); diff --git a/src/ve-components/presentations/components/present-figure.component.ts b/src/ve-components/presentations/components/present-figure.component.ts index cef0367dd..8d5e425cb 100644 --- a/src/ve-components/presentations/components/present-figure.component.ts +++ b/src/ve-components/presentations/components/present-figure.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations' +import { PresentationLite } from '@ve-components/presentations'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; const PresentFigureComponent: IPresentationComponentOptions = { selector: 'presentFigure', @@ -14,6 +14,6 @@ const PresentFigureComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -} +}; -veComponents.component(PresentFigureComponent.selector, PresentFigureComponent) +veComponents.component(PresentFigureComponent.selector, PresentFigureComponent); diff --git a/src/ve-components/presentations/components/present-image.component.ts b/src/ve-components/presentations/components/present-image.component.ts index fa59b8e0a..eaee3656f 100644 --- a/src/ve-components/presentations/components/present-image.component.ts +++ b/src/ve-components/presentations/components/present-image.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations' +import { PresentationLite } from '@ve-components/presentations'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; const PresentImageComponent: IPresentationComponentOptions = { selector: 'presentImage', @@ -21,6 +21,6 @@ const PresentImageComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -} +}; -veComponents.component(PresentImageComponent.selector, PresentImageComponent) +veComponents.component(PresentImageComponent.selector, PresentImageComponent); diff --git a/src/ve-components/presentations/components/present-list-t.component.ts b/src/ve-components/presentations/components/present-list-t.component.ts index 9c1ab1116..5a4c7773c 100644 --- a/src/ve-components/presentations/components/present-list-t.component.ts +++ b/src/ve-components/presentations/components/present-list-t.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations' +import { PresentationLite } from '@ve-components/presentations'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; const PresentListTComponent: IPresentationComponentOptions = { selector: 'presentListt', @@ -14,6 +14,6 @@ const PresentListTComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -} +}; -veComponents.component(PresentListTComponent.selector, PresentListTComponent) +veComponents.component(PresentListTComponent.selector, PresentListTComponent); diff --git a/src/ve-components/presentations/components/present-list.component.ts b/src/ve-components/presentations/components/present-list.component.ts index 26ede1313..2c780d76d 100644 --- a/src/ve-components/presentations/components/present-list.component.ts +++ b/src/ve-components/presentations/components/present-list.component.ts @@ -1,18 +1,18 @@ -import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations' -import { ComponentService, ExtensionService } from '@ve-components/services' -import { ButtonBarService } from '@ve-core/button-bar' -import { ImageService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { SchemaService } from '@ve-utils/model-schema' +import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations'; +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { ImageService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' -import { IPresentationComponentOptions } from '@ve-types/components/presentation' -import { PresentListObject } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { PresentListObject } from '@ve-types/mms'; class PresentListController extends Presentation { - static $inject = Presentation.$inject + static $inject = Presentation.$inject; constructor( $q: VeQService, $element: JQuery, @@ -42,12 +42,12 @@ class PresentListController extends Presentation { imageSvc, buttonBarSvc, extensionSvc - ) + ); } protected getContent = (): VePromise => { - return this.$q.resolve(this.viewHtmlSvc.makeHtmlList(this.peObject as PresentListObject)) - } + return this.$q.resolve(this.viewHtmlSvc.makeHtmlList(this.peObject as PresentListObject)); + }; } const PresentListComponent: IPresentationComponentOptions = { @@ -59,6 +59,6 @@ const PresentListComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentListController, -} +}; -veComponents.component(PresentListComponent.selector, PresentListComponent) +veComponents.component(PresentListComponent.selector, PresentListComponent); diff --git a/src/ve-components/presentations/components/present-paragraph.component.ts b/src/ve-components/presentations/components/present-paragraph.component.ts index 749b32d38..3448e0edc 100644 --- a/src/ve-components/presentations/components/present-paragraph.component.ts +++ b/src/ve-components/presentations/components/present-paragraph.component.ts @@ -1,18 +1,18 @@ -import { ViewHtmlService, Presentation, PresentationService } from '@ve-components/presentations' -import { ComponentService, ExtensionService } from '@ve-components/services' -import { ButtonBarService } from '@ve-core/button-bar' -import { ImageService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { SchemaService } from '@ve-utils/model-schema' +import { ViewHtmlService, Presentation, PresentationService } from '@ve-components/presentations'; +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { ImageService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' -import { IPresentationComponentOptions } from '@ve-types/components/presentation' -import { PresentTextObject } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { PresentTextObject } from '@ve-types/mms'; class PresentParagraph extends Presentation implements angular.IComponentController { - static $inject = Presentation.$inject + static $inject = Presentation.$inject; constructor( $q: VeQService, $element: JQuery, @@ -42,12 +42,12 @@ class PresentParagraph extends Presentation implements angular.IComponentControl imageSvc, buttonBarSvc, extensionSvc - ) + ); } protected getContent = (): VePromise => { - return this.$q.resolve(this.viewHtmlSvc.makeHtmlPara(this.peObject as PresentTextObject)) - } + return this.$q.resolve(this.viewHtmlSvc.makeHtmlPara(this.peObject as PresentTextObject)); + }; } const PresentParagraphComponent: IPresentationComponentOptions = { @@ -59,6 +59,6 @@ const PresentParagraphComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentParagraph, -} +}; -veComponents.component(PresentParagraphComponent.selector, PresentParagraphComponent) +veComponents.component(PresentParagraphComponent.selector, PresentParagraphComponent); diff --git a/src/ve-components/presentations/components/present-section.component.ts b/src/ve-components/presentations/components/present-section.component.ts index edfcc838e..b4ee350d6 100644 --- a/src/ve-components/presentations/components/present-section.component.ts +++ b/src/ve-components/presentations/components/present-section.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations' +import { PresentationLite } from '@ve-components/presentations'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; const PresentSectionComponent: IPresentationComponentOptions = { selector: 'presentSection', @@ -20,6 +20,6 @@ const PresentSectionComponent: IPresentationComponentOptions = { mmsViewCtrl: '?^^view', mmsViewPresentationElemCtrl: '?^^viewPe', }, -} +}; -veComponents.component(PresentSectionComponent.selector, PresentSectionComponent) +veComponents.component(PresentSectionComponent.selector, PresentSectionComponent); diff --git a/src/ve-components/presentations/components/present-table-t.component.ts b/src/ve-components/presentations/components/present-table-t.component.ts index e124e1d36..2ec52b363 100644 --- a/src/ve-components/presentations/components/present-table-t.component.ts +++ b/src/ve-components/presentations/components/present-table-t.component.ts @@ -1,8 +1,8 @@ -import { PresentationLite } from '@ve-components/presentations' +import { PresentationLite } from '@ve-components/presentations'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { IPresentationComponentOptions } from '@ve-types/components/presentation' +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; const PresentTableTComponent: IPresentationComponentOptions = { selector: 'presentTablet', @@ -14,6 +14,6 @@ const PresentTableTComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentationLite, -} +}; -veComponents.component(PresentTableTComponent.selector, PresentTableTComponent) +veComponents.component(PresentTableTComponent.selector, PresentTableTComponent); diff --git a/src/ve-components/presentations/components/present-table.component.ts b/src/ve-components/presentations/components/present-table.component.ts index 29864443a..8dd04e8f5 100644 --- a/src/ve-components/presentations/components/present-table.component.ts +++ b/src/ve-components/presentations/components/present-table.component.ts @@ -1,49 +1,49 @@ -import $ from 'jquery' +import $ from 'jquery'; -import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations' -import { Table2CSVService } from '@ve-components/presentations/services/Table2CSV.service' -import { ComponentService, ExtensionService } from '@ve-components/services' -import { ButtonBarService } from '@ve-core/button-bar' -import { ImageService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { SchemaService } from '@ve-utils/model-schema' +import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations'; +import { Table2CSVService } from '@ve-components/presentations/services/Table2CSV.service'; +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { ImageService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' -import { IPresentationComponentOptions, ITableConfig } from '@ve-types/components/presentation' -import { PresentTableObject, TableEntryObject } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { IPresentationComponentOptions, ITableConfig } from '@ve-types/components/presentation'; +import { PresentTableObject, TableEntryObject } from '@ve-types/mms'; class PresentTableController extends Presentation { - public $searchEl: JQuery - public $tHeadEl: JQuery - public $captionEl: JQuery - - public table: PresentTableObject - public tableConfig: ITableConfig - private trs: JQuery - public ngModelOptions: angular.INgModelOptions - public showFilter: boolean = false - public fixedHeaders: boolean = false - public fixedColumns: boolean = false - private _fixedHeadersElem: JQuery = null - private _fixedColumnsElem: JQuery = null - public numFixedColumns: number = 2 - private nextIndex: number - private tbody: JQuery - private lastIndex: number - private numTotal: number - private sortColumnNum: number + public $searchEl: JQuery; + public $tHeadEl: JQuery; + public $captionEl: JQuery; + + public table: PresentTableObject; + public tableConfig: ITableConfig; + private trs: JQuery; + public ngModelOptions: angular.INgModelOptions; + public showFilter: boolean = false; + public fixedHeaders: boolean = false; + public fixedColumns: boolean = false; + private _fixedHeadersElem: JQuery = null; + private _fixedColumnsElem: JQuery = null; + public numFixedColumns: number = 2; + private nextIndex: number; + private tbody: JQuery; + private lastIndex: number; + private numTotal: number; + private sortColumnNum: number; /** Full Table Filter **/ - private searchTerm: string = '' - private numFiltered: number + private searchTerm: string = ''; + private numFiltered: number; /** Column Filter **/ private _columnsInputSubs: { - [columnId: string]: { sub: Rx.IDisposable; cell: TableEntryObject } - } = {} + [columnId: string]: { sub: Rx.IDisposable; cell: TableEntryObject }; + } = {}; /** * _filterTermForColumns is used to keep track of filter terms on each header's column for multi-columns @@ -51,16 +51,16 @@ class PresentTableController extends Presentation { * keeps track, of all the children columns number that it is a parent of. ie: * {filterTermForColumn01: {filterTerm: 'A', columns: [0,1]}, filterTermForColumn11: {filterTerm: 'B', columns: [1]}} **/ private _filterTermForColumns: { - [filterTermForColumn: string]: { filterTerm: string; columns: number[] } - } = {} - private filterTermForColumn: { [cols: string]: string } = {} + [filterTermForColumn: string]: { filterTerm: string; columns: number[] }; + } = {}; + private filterTermForColumn: { [cols: string]: string } = {}; /** Variables for Sorting Functions **/ - private _rowSortOrderAttrName = 'data-original-row-num' - public isAscending: boolean = false - private showSortReset: boolean = false + private _rowSortOrderAttrName = 'data-original-row-num'; + public isAscending: boolean = false; + private showSortReset: boolean = false; - static $inject = [...Presentation.$inject, '$timeout'] + static $inject = [...Presentation.$inject, '$timeout']; constructor( $q: VeQService, @@ -92,44 +92,44 @@ class PresentTableController extends Presentation { imageSvc, buttonBarSvc, extensionSvc - ) + ); } recompile = (): void => { this.$element.on('click', (e) => { - const tag = (e.target as unknown as Element).tagName + const tag = (e.target as unknown as Element).tagName; if (tag === 'INPUT' || tag === 'LABEL' || tag === 'BUTTON') { - e.stopPropagation() + e.stopPropagation(); } - }) - this.setNumber() + }); + this.setNumber(); this.getContent().then( (result) => { - this.$transcludeEl = $(result) + this.$transcludeEl = $(result); this.$transcludeEl.find('img').each((index, element) => { - this.imageSvc.fixImgSrc($(element)) - }) - - this.$element.append(this.$transcludeEl) - this.nextIndex = 0 - this.$tHeadEl = this.$element.find('thead') - this.$compile(this.$tHeadEl)(this.$scope) - this.$searchEl = this.$element.children('div').eq(0) + this.imageSvc.fixImgSrc($(element)); + }); + + this.$element.append(this.$transcludeEl); + this.nextIndex = 0; + this.$tHeadEl = this.$element.find('thead'); + this.$compile(this.$tHeadEl)(this.$scope); + this.$searchEl = this.$element.children('div').eq(0); //this.$compile(this.$searchEl)(this.$scope) //already compiled due to template - this.$captionEl = this.$element.find('caption') - this.$compile(this.$captionEl)(this.$scope) + this.$captionEl = this.$element.find('caption'); + this.$compile(this.$captionEl)(this.$scope); //Add the search input here (before the TRS, aka the columns/rows) - this.tbody = this.$element.find('.table-wrapper').children('table').children('tbody') - this.trs = this.tbody.children('tr') + this.tbody = this.$element.find('.table-wrapper').children('table').children('tbody'); + this.trs = this.tbody.children('tr'); - this.lastIndex = this.trs.length - this.numFiltered = this.lastIndex - this.numTotal = this.lastIndex + this.lastIndex = this.trs.length; + this.numFiltered = this.lastIndex; + this.numTotal = this.lastIndex; //this.addColumnsWiseFilter(this.tableConfig, this.trs) - this.addSorting(this.trs, this.tbody) + this.addSorting(this.trs, this.tbody); - this.compileTable() + this.compileTable(); }, (reason) => { const reqOb = { @@ -138,85 +138,85 @@ class PresentTableController extends Presentation { refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - } - this.$element.empty() + }; + this.$element.empty(); //TODO: Add reason/errorMessage handling here. this.$transcludeEl = $( '' - ) - this.$element.append(this.$transcludeEl) + ); + this.$element.append(this.$transcludeEl); this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: reqOb.elementId, recentElement: reason.recentVersionOfElement, type: 'presentation', }) - ) + ); } - ) - } + ); + }; config = (): void => { if ( !(this.peObject as PresentTableObject).showIfEmpty && (this.peObject as PresentTableObject).body.length === 0 ) { - return + return; } - this.table = this.peObject as PresentTableObject - this.sortColumnNum = -1 + this.table = this.peObject as PresentTableObject; + this.sortColumnNum = -1; this.ngModelOptions = { debounce: 300, getterSetter: true, - } - } + }; + }; getContent = (): VePromise => { - const html = this.viewHtmlSvc.makeHtmlTable(this.table, true, true, this.instanceSpec) - return this.$q.resolve(`
    ${html}
    `) - } + const html = this.viewHtmlSvc.makeHtmlTable(this.table, true, true, this.instanceSpec); + return this.$q.resolve(`
    ${html}
    `); + }; /** Filter rows by search term **/ private fullTableFilter = (): void => { - this._resetColumnWiseFilterInputs() + this._resetColumnWiseFilterInputs(); if (this.searchTerm === '') { - this.numFiltered = this.trs.length - this.trs.show() + this.numFiltered = this.trs.length; + this.trs.show(); } else { - this.numFiltered = 0 + this.numFiltered = 0; this._displaySomeRows(this.trs, () => { - this.numFiltered++ - }) + this.numFiltered++; + }); } - } + }; /** Display rows that match the filter term **/ private _displaySomeRows = (trs: JQuery, increaseNumOfRowToShow: () => void): void => { - const regExp = new RegExp(this.searchTerm, 'i') + const regExp = new RegExp(this.searchTerm, 'i'); for (let i = 0, numRows = trs.length; i < numRows; i++) { - const string = $(trs[i]).text() + const string = $(trs[i]).text(); if (regExp.test(string)) { - $(trs[i]).show() - increaseNumOfRowToShow() + $(trs[i]).show(); + increaseNumOfRowToShow(); } else { - $(trs[i]).hide() + $(trs[i]).hide(); } } - } + }; /** End of Full Table Filter **/ /** Add column(s)-wise filter ability **/ private filterByColumn = (startColNum: number, endColNum: number): void => { - this.searchTerm = '' - const filterTerm = this.filterTermForColumn[`filter${startColNum}${endColNum}`] - const filterInputBinding = `columnFilter${startColNum}${endColNum}` - this._storeColumnWiseFilterTerm(filterInputBinding, startColNum, endColNum, filterTerm) - this.numFiltered = 0 + this.searchTerm = ''; + const filterTerm = this.filterTermForColumn[`filter${startColNum}${endColNum}`]; + const filterInputBinding = `columnFilter${startColNum}${endColNum}`; + this._storeColumnWiseFilterTerm(filterInputBinding, startColNum, endColNum, filterTerm); + this.numFiltered = 0; this._displayRowsMatchingAllColumnsFilterTerms(this.trs, () => { - this.numFiltered++ - }) - } + this.numFiltered++; + }); + }; /** Only show the rows that has contents matching all currently outstanding filter terms **/ private _displayRowsMatchingAllColumnsFilterTerms = ( @@ -225,19 +225,19 @@ class PresentTableController extends Presentation { ): void => { trs.toArray().forEach((row) => { const shouldKeepRow = Object.keys(this._filterTermForColumns).every((k) => { - const regExp = new RegExp(this._filterTermForColumns[k].filterTerm, 'i') + const regExp = new RegExp(this._filterTermForColumns[k].filterTerm, 'i'); return this._filterTermForColumns[k].columns.some((colNum) => { - return regExp.test(this._getCellValueForFiltering(row, colNum)) - }) - }) + return regExp.test(this._getCellValueForFiltering(row, colNum)); + }); + }); if (shouldKeepRow) { - $(row).show() - increaseNumOfRowToShow() + $(row).show(); + increaseNumOfRowToShow(); } else { - $(row).hide() + $(row).hide(); } - }) - } + }); + }; /** Update or add a new filter term for a header column with the given filterInputBinding **/ private _storeColumnWiseFilterTerm = ( @@ -247,11 +247,11 @@ class PresentTableController extends Presentation { filterTerm: string ): void => { if (this._filterTermForColumns[filterInputBinding]) { - this._updateExistingColumnWiseFilterTerm(filterInputBinding, filterTerm) + this._updateExistingColumnWiseFilterTerm(filterInputBinding, filterTerm); } else { - this._addNewColumnWiseFilterTerm(filterInputBinding, startColNum, endColNum, filterTerm) + this._addNewColumnWiseFilterTerm(filterInputBinding, startColNum, endColNum, filterTerm); } - } + }; /** Add a new filter term to a header column with the given filterInputBinding **/ private _addNewColumnWiseFilterTerm = ( @@ -263,345 +263,345 @@ class PresentTableController extends Presentation { this._filterTermForColumns[filterInputBinding] = { filterTerm: filterTerm, columns: startColNum === endColNum ? [startColNum] : [startColNum, endColNum], - } - } + }; + }; /** Update a filter term for a header column with the given filterInputBinding **/ private _updateExistingColumnWiseFilterTerm = (filterInputBinding: string, filterTerm: string): void => { - this._filterTermForColumns[filterInputBinding].filterTerm = filterTerm - } + this._filterTermForColumns[filterInputBinding].filterTerm = filterTerm; + }; /** Return the content of a cell given a row & columnIndex **/ private _getCellValueForFiltering = (row: HTMLElement, columnIndex: number): string => { - const cell = $(row).children('td').eq(columnIndex) - return cell.text().trim() - } + const cell = $(row).children('td').eq(columnIndex); + return cell.text().trim(); + }; /** Clear out filter term(s) for all header's columns that used to be filtered by before **/ private _resetColumnWiseFilterInputs = (): void => { - const listOfFilterInputBindings = Object.keys(this._filterTermForColumns) + const listOfFilterInputBindings = Object.keys(this._filterTermForColumns); if (listOfFilterInputBindings.length > 0) { listOfFilterInputBindings.forEach((filterInputBinding) => { - delete this._filterTermForColumns[filterInputBinding] - }) + delete this._filterTermForColumns[filterInputBinding]; + }); } Object.keys(this.filterTermForColumn).forEach((key) => { - this.filterTermForColumn[key] = '' - }) - } + this.filterTermForColumn[key] = ''; + }); + }; /** End of Column(s)-Wise Filter **/ /** Sorting feature **/ /** Add sorting ability **/ public addSorting = (trs: JQuery, tbody: JQuery): void => { - this._addDefaultSortOrder(trs) - } + this._addDefaultSortOrder(trs); + }; /** Remember the original row number for each row. Used to restore sort order **/ private _addDefaultSortOrder = (trs: JQuery): void => { trs.each((rowNumber, tr) => { - $(tr).attr(this._rowSortOrderAttrName, rowNumber) - }) - } + $(tr).attr(this._rowSortOrderAttrName, rowNumber); + }); + }; /** Used to sort columns(s). Add sort binding to each header columns of the outermost table **/ private sortByColumnFn = (event: Event, sortColumnNum: number): void => { - this.sortColumnNum = sortColumnNum - event.stopPropagation() - const rows = this.trs.toArray() + this.sortColumnNum = sortColumnNum; + event.stopPropagation(); + const rows = this.trs.toArray(); let sortedRows = this._areAllCellValidNumber(rows, sortColumnNum) ? rows.sort(this._numericalComparator(sortColumnNum)) - : rows.sort(this._generalComparator(sortColumnNum)) + : rows.sort(this._generalComparator(sortColumnNum)); - this.isAscending = !this.isAscending + this.isAscending = !this.isAscending; if (!this.isAscending) { - sortedRows = sortedRows.reverse() + sortedRows = sortedRows.reverse(); } - this._displaySortedRows(sortedRows, this.tbody) - this.showSortReset = true - } + this._displaySortedRows(sortedRows, this.tbody); + this.showSortReset = true; + }; /** Used to restore the sort order of table's rows **/ private resetSort = (): void => { - const sortedRows = this.trs.toArray().sort(this._comparatorForSortReset()) - this._displaySortedRows(sortedRows, this.tbody) - this.showSortReset = false - this.sortColumnNum = -1 - } + const sortedRows = this.trs.toArray().sort(this._comparatorForSortReset()); + this._displaySortedRows(sortedRows, this.tbody); + this.showSortReset = false; + this.sortColumnNum = -1; + }; /** A comparator for sorting table's rows. When one of them is null ( null is reserved for non-sortable content * such as image, list, table ), that content is pushed to the end of the final sorted list regardless of * whether sorting asc or dsc **/ private _generalComparator = (columnIndex: number): ((rowA: HTMLElement, rowB: HTMLElement) => number) => { return (rowA: HTMLElement, rowB: HTMLElement): number => { - let cellValueA = this._getCellValueForSorting(rowA, columnIndex) - let cellValueB = this._getCellValueForSorting(rowB, columnIndex) + let cellValueA = this._getCellValueForSorting(rowA, columnIndex); + let cellValueB = this._getCellValueForSorting(rowB, columnIndex); if (cellValueA === null && cellValueB === null) { - return 0 + return 0; } if (cellValueA === null && cellValueB !== null) { - return this.isAscending ? 1 : -1 + return this.isAscending ? 1 : -1; } if (cellValueA !== null && cellValueB === null) { - return this.isAscending ? -1 : 1 + return this.isAscending ? -1 : 1; } if (cellValueA !== null && cellValueB !== null) { - cellValueA = cellValueA.toLowerCase() - cellValueB = cellValueB.toLowerCase() - return cellValueA < cellValueB ? -1 : cellValueA > cellValueB ? 1 : 0 + cellValueA = cellValueA.toLowerCase(); + cellValueB = cellValueB.toLowerCase(); + return cellValueA < cellValueB ? -1 : cellValueA > cellValueB ? 1 : 0; } - } - } + }; + }; /** Return true if and only if all cells' value can be converted to a valid number **/ private _areAllCellValidNumber = (rows: HTMLElement[], columnIndex: number): boolean => { return rows.every((row): boolean => { - return this._isValidNumber(this._getCellValueForSorting(row, columnIndex)) - }) - } + return this._isValidNumber(this._getCellValueForSorting(row, columnIndex)); + }); + }; private _numericalComparator = (columnIndex: number): ((rowA: HTMLElement, rowB: HTMLElement) => number) => { return (rowA: HTMLElement, rowB: HTMLElement) => { - const cellValueA = Number(this._getCellValueForSorting(rowA, columnIndex)) - const cellValueB = Number(this._getCellValueForSorting(rowB, columnIndex)) - return cellValueA - cellValueB - } - } + const cellValueA = Number(this._getCellValueForSorting(rowA, columnIndex)); + const cellValueB = Number(this._getCellValueForSorting(rowB, columnIndex)); + return cellValueA - cellValueB; + }; + }; private _isValidNumber = (val): boolean => { - return val !== null && !isNaN(Number(val)) - } + return val !== null && !isNaN(Number(val)); + }; /** Get content of a cell given its row and its columnIndex. Return null for a cell that contains non-sortable * content such as image, table, list **/ private _getCellValueForSorting = (row: HTMLElement, columnIndex: number): string => { - const cell = $(row).children('td').eq(columnIndex) - const containerDivContent = cell.children('div').contents() + const cell = $(row).children('td').eq(columnIndex); + const containerDivContent = cell.children('div').contents(); // if there is no content, think of it as empty string if (containerDivContent.length === 0) { - return '' + return ''; } else if (!containerDivContent.prop('tagName')) { - return cell.text().trim() + return cell.text().trim(); } else { - const cf = 'mms-cf' - const contentTag: string = (containerDivContent.prop('tagName') as object).toString().toLowerCase() - const contentTagAttr = containerDivContent.attr('mms-cf-type') + const cf = 'mms-cf'; + const contentTag: string = (containerDivContent.prop('tagName') as object).toString().toLowerCase(); + const contentTagAttr = containerDivContent.attr('mms-cf-type'); if ( contentTag === 'img' || contentTag === 'table' || (contentTag === cf && (contentTagAttr === 'img' || contentTagAttr === 'table')) ) { - return null + return null; } else { - return cell.text().trim() + return cell.text().trim(); } } - } + }; /** Display newly sorted rows **/ private _displaySortedRows = (sortedRows: HTMLElement[], tbody: JQuery): void => { - $(sortedRows).detach().appendTo(tbody) - } + $(sortedRows).detach().appendTo(tbody); + }; /** This special comparator is used to turn the table's rows into its original sort order **/ private _comparatorForSortReset = () => { return (rowA, rowB): number => { - const rowARowNumber = Number($(rowA).attr(this._rowSortOrderAttrName)) - const rowBRowNumber = Number($(rowB).attr(this._rowSortOrderAttrName)) - return rowARowNumber < rowBRowNumber ? -1 : rowARowNumber > rowBRowNumber ? 1 : 0 - } - } + const rowARowNumber = Number($(rowA).attr(this._rowSortOrderAttrName)); + const rowBRowNumber = Number($(rowB).attr(this._rowSortOrderAttrName)); + return rowARowNumber < rowBRowNumber ? -1 : rowARowNumber > rowBRowNumber ? 1 : 0; + }; + }; /** End of Sorting feature **/ /** Begin Linking Functions **/ public getSortIconClass = (cellColumn): string[] => { - const sortingColumnNumber = this.sortColumnNum + const sortingColumnNumber = this.sortColumnNum; if (sortingColumnNumber !== cellColumn) { - return ['fa', 'fa-sort', 'sort-default'] + return ['fa', 'fa-sort', 'sort-default']; } else { if (this.isAscending) { - return ['fa', 'fa-caret-down', 'sort-activated'] + return ['fa', 'fa-caret-down', 'sort-activated']; } else { - return ['fa', 'fa-caret-up', 'sort-activated'] + return ['fa', 'fa-caret-up', 'sort-activated']; } } - } + }; makeCsv = (): void => { - const el = this.$element.find('.table-wrapper').children('table') - const csvString: string | boolean = Table2CSVService.export(el, { delivery: 'value' }) + const el = this.$element.find('.table-wrapper').children('table'); + const csvString: string | boolean = Table2CSVService.export(el, { delivery: 'value' }); // var bom = "\xEF\xBB\xBF"; //just for excel if (typeof csvString === 'string') { - const bom2 = '\uFEFF' //just for excel + const bom2 = '\uFEFF'; //just for excel const blob = new Blob([bom2 + csvString], { type: 'text/csv;charset=utf-8;', - }) + }); - const downloadContainer = angular.element('
    ') - const downloadLink = angular.element(downloadContainer.children()[0]) - downloadLink.attr('href', window.URL.createObjectURL(blob)) - downloadLink.attr('download', 'TableData.csv') - downloadLink.attr('target', '_blank') + const downloadContainer = angular.element('
    '); + const downloadLink = angular.element(downloadContainer.children()[0]); + downloadLink.attr('href', window.URL.createObjectURL(blob)); + downloadLink.attr('download', 'TableData.csv'); + downloadLink.attr('target', '_blank'); - $(document).find('body').append(downloadContainer) + $(document).find('body').append(downloadContainer); void this.$timeout(() => { - downloadLink[0].click() - downloadLink.remove() - }, null) + downloadLink[0].click(); + downloadLink.remove(); + }, null); } else { - this.growl.error('Error generating CSV; Please Try Again') + this.growl.error('Error generating CSV; Please Try Again'); } - } + }; public scroll = (): void => { if (this._fixedColumnsElem) { - const scroll = this.$element.find('.table-fix-column').scrollLeft() - this._fixedColumnsElem.css('transform', `translateX(${scroll}px)`) + const scroll = this.$element.find('.table-fix-column').scrollLeft(); + this._fixedColumnsElem.css('transform', `translateX(${scroll}px)`); } if (this._fixedHeadersElem) { - const scroll = this.$element.find('.table-fix-head').scrollTop() - this._fixedHeadersElem.css('transform', `translateY(${scroll}px)`) + const scroll = this.$element.find('.table-fix-head').scrollTop(); + this._fixedHeadersElem.css('transform', `translateY(${scroll}px)`); } if (this._fixedHeadersElem && this._fixedColumnsElem) { - const scrollX = this.$element.find('.table-fix-column').scrollLeft() - const scrollY = this.$element.find('.table-fix-head').scrollTop() - this.$captionEl.css('transform', `translate(${scrollX}px, ${scrollY}px)`) + const scrollX = this.$element.find('.table-fix-column').scrollLeft(); + const scrollY = this.$element.find('.table-fix-head').scrollTop(); + this.$captionEl.css('transform', `translate(${scrollX}px, ${scrollY}px)`); } - } + }; public makeFixedHeader = (): void => { if (!this.fixedHeaders) { - this.$element.find('.table-wrapper').removeClass('table-fix-head').css('height', '') - this._fixedHeadersElem.css('transform', '').css('will-change', '') - this._fixedHeadersElem = null - window.localStorage.setItem('ve-table-header-' + this.instanceSpec.id, 'false') - return + this.$element.find('.table-wrapper').removeClass('table-fix-head').css('height', ''); + this._fixedHeadersElem.css('transform', '').css('will-change', ''); + this._fixedHeadersElem = null; + window.localStorage.setItem('ve-table-header-' + this.instanceSpec.id, 'false'); + return; } this.$element .find('.table-wrapper') .addClass('table-fix-head') - .css('height', window.innerHeight - 36 * 3) + .css('height', window.innerHeight - 36 * 3); //heights for navbar, menu, toolbar - this._fixedHeadersElem = this.$element.find('thead, caption') - this._fixedHeadersElem.css('will-change', 'transform') //browser optimization - this.$element.find('.table-fix-head').on('scroll', this.scroll) - window.localStorage.setItem('ve-table-header-' + this.instanceSpec.id, 'true') - } + this._fixedHeadersElem = this.$element.find('thead, caption'); + this._fixedHeadersElem.css('will-change', 'transform'); //browser optimization + this.$element.find('.table-fix-head').on('scroll', this.scroll); + window.localStorage.setItem('ve-table-header-' + this.instanceSpec.id, 'true'); + }; public makeFixedColumn = (): void => { if (!this.fixedColumns) { - this.$element.find('.table-wrapper').removeClass('table-fix-column').css('width', '') - this._fixedColumnsElem.css('transform', '').css('will-change', '').removeClass('table-fixed-cell') - this._fixedColumnsElem = null - window.localStorage.setItem('ve-table-column-' + this.instanceSpec.id, 'false') - return + this.$element.find('.table-wrapper').removeClass('table-fix-column').css('width', ''); + this._fixedColumnsElem.css('transform', '').css('will-change', '').removeClass('table-fixed-cell'); + this._fixedColumnsElem = null; + window.localStorage.setItem('ve-table-column-' + this.instanceSpec.id, 'false'); + return; } this.$element .find('.table-wrapper') .addClass('table-fix-column') - .css('width', window.innerWidth - 400) - this._fixedColumnsElem = this._findColumnCells('thead', 'th', this.numFixedColumns) - this._fixedColumnsElem = this._fixedColumnsElem.add(this._findColumnCells('tbody', 'td', this.numFixedColumns)) - this._fixedColumnsElem = this._fixedColumnsElem.add(this.$element.find('.table-fix-column caption')) - this._fixedColumnsElem.css('will-change', 'transform') //browser optimization - this._fixedColumnsElem.addClass('table-fixed-cell') - this.$element.find('.table-fix-column').on('scroll', this.scroll) - window.localStorage.setItem('ve-table-column-' + this.instanceSpec.id, this.numFixedColumns.toString()) - } + .css('width', window.innerWidth - 400); + this._fixedColumnsElem = this._findColumnCells('thead', 'th', this.numFixedColumns); + this._fixedColumnsElem = this._fixedColumnsElem.add(this._findColumnCells('tbody', 'td', this.numFixedColumns)); + this._fixedColumnsElem = this._fixedColumnsElem.add(this.$element.find('.table-fix-column caption')); + this._fixedColumnsElem.css('will-change', 'transform'); //browser optimization + this._fixedColumnsElem.addClass('table-fixed-cell'); + this.$element.find('.table-fix-column').on('scroll', this.scroll); + window.localStorage.setItem('ve-table-column-' + this.instanceSpec.id, this.numFixedColumns.toString()); + }; public updateFixedColumns = (): void => { - this.fixedColumns = false - this.makeFixedColumn() - this.fixedColumns = true - this.makeFixedColumn() - } + this.fixedColumns = false; + this.makeFixedColumn(); + this.fixedColumns = true; + this.makeFixedColumn(); + }; private _findColumnCells = (bodyTag: string, cellTag: string, n: number): JQuery => { - const spanData: boolean[][] = [] //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell - let curRow = 0 - let data = $() + const spanData: boolean[][] = []; //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell + let curRow = 0; + let data = $(); $(this.$element) .find('.table-fix-column table') .children(bodyTag) .children('tr') .each((index, element) => { - let curCol = 0 + let curCol = 0; $(element) .children(cellTag) .each((index, element) => { while (spanData[curRow] && spanData[curRow][curCol]) { - curCol++ + curCol++; } if (curCol >= n) { - return + return; } - data = data.add($(element)) - const rowstring = $(element).attr('rowspan') - let rowspan = 0 + data = data.add($(element)); + const rowstring = $(element).attr('rowspan'); + let rowspan = 0; if (rowstring) { - rowspan = parseInt(rowstring) + rowspan = parseInt(rowstring); if (rowspan > 1) { for (let i = 1; i < rowspan; i++) { if (!spanData[curRow + i]) { - spanData[curRow + i] = [] + spanData[curRow + i] = []; } - spanData[curRow + i][curCol] = true + spanData[curRow + i][curCol] = true; } } } - const colstring = $(element).attr('colspan') + const colstring = $(element).attr('colspan'); if (!colstring) { - curCol++ - return + curCol++; + return; } - let colspan = parseInt(colstring) + let colspan = parseInt(colstring); while (colspan > 1) { - curCol++ - colspan-- + curCol++; + colspan--; if (rowspan > 1) { for (let j = 1; j < rowspan; j++) { - spanData[curRow + j][curCol] = true + spanData[curRow + j][curCol] = true; } } } - curCol++ - }) - curRow++ - }) - return data - } + curCol++; + }); + curRow++; + }); + return data; + }; private compileTable(): void { void this.$timeout( () => { - const first = this.nextIndex - if (first > this.lastIndex) return - const now = this.trs.slice(first, first + 300) - this.$compile(now)(this.$scope) - this.nextIndex = first + 300 - if (this.nextIndex < this.lastIndex) this.compileTable() + const first = this.nextIndex; + if (first > this.lastIndex) return; + const now = this.trs.slice(first, first + 300); + this.$compile(now)(this.$scope); + this.nextIndex = first + 300; + if (this.nextIndex < this.lastIndex) this.compileTable(); else { if (window.localStorage.getItem('ve-table-header-' + this.instanceSpec.id) == 'true') { - this.fixedHeaders = true - this.makeFixedHeader() + this.fixedHeaders = true; + this.makeFixedHeader(); } - const columnFix = window.localStorage.getItem('ve-table-column-' + this.instanceSpec.id) + const columnFix = window.localStorage.getItem('ve-table-column-' + this.instanceSpec.id); if (columnFix != 'false' && columnFix != null && columnFix != 'null') { - this.fixedColumns = true - this.numFixedColumns = Number.parseInt(columnFix) - this.makeFixedColumn() + this.fixedColumns = true; + this.numFixedColumns = Number.parseInt(columnFix); + this.makeFixedColumn(); } } }, 100, false - ) + ); } } @@ -628,6 +628,6 @@ const PresentTableComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: PresentTableController, -} +}; -veComponents.component(PresentTableComponent.selector, PresentTableComponent) +veComponents.component(PresentTableComponent.selector, PresentTableComponent); diff --git a/src/ve-components/presentations/index.ts b/src/ve-components/presentations/index.ts index 910d92e61..d636c87c8 100644 --- a/src/ve-components/presentations/index.ts +++ b/src/ve-components/presentations/index.ts @@ -1,30 +1,30 @@ -export * from './presentation-element.controller' +export * from './presentation-element.controller'; //Services -import './services/ViewHtml.service' -import './services/Presentation.service' +import './services/ViewHtml.service'; +import './services/Presentation.service'; -export * from './services/ViewHtml.service' -export * from './services/Presentation.service' +export * from './services/ViewHtml.service'; +export * from './services/Presentation.service'; //Components -import './add-pe-menu.component' -import './view.component' +import './add-pe-menu.component'; +import './view.component'; -export * from './view.component' -import './view-pe.component' +export * from './view.component'; +import './view-pe.component'; -export * from './view-pe.component' -import './mms-view-link.component' +export * from './view-pe.component'; +import './mms-view-link.component'; //Presentations -import './components/present-equation.component' -import './components/present-figure.component' -import './components/present-image.component' -import './components/present-list.component' -import './components/present-list-t.component' -import './components/present-paragraph.component' -import './components/present-table.component' -import './components/present-table-t.component' -import './components/present-section.component' -import './components/present-comment.component' +import './components/present-equation.component'; +import './components/present-figure.component'; +import './components/present-image.component'; +import './components/present-list.component'; +import './components/present-list-t.component'; +import './components/present-paragraph.component'; +import './components/present-table.component'; +import './components/present-table-t.component'; +import './components/present-section.component'; +import './components/present-comment.component'; diff --git a/src/ve-components/presentations/mms-view-link.component.ts b/src/ve-components/presentations/mms-view-link.component.ts index f40b12072..556d29cdf 100644 --- a/src/ve-components/presentations/mms-view-link.component.ts +++ b/src/ve-components/presentations/mms-view-link.component.ts @@ -1,16 +1,16 @@ -import $ from 'jquery' +import $ from 'jquery'; -import { ViewController } from '@ve-components/presentations/view.component' -import { ExtensionService } from '@ve-components/services' -import { CrossReferenceController } from '@ve-components/transclusions/mms-cf.component' -import { ApplicationService } from '@ve-utils/application' -import { ApiService, ElementService, ViewService } from '@ve-utils/mms-api-client' -import { handleChange, onChangesCallback } from '@ve-utils/utils' +import { ViewController } from '@ve-components/presentations/view.component'; +import { ExtensionService } from '@ve-components/services'; +import { CrossReferenceController } from '@ve-components/transclusions/mms-cf.component'; +import { ApplicationService } from '@ve-utils/application'; +import { ApiService, ElementService, ViewService } from '@ve-utils/mms-api-client'; +import { handleChange, onChangesCallback } from '@ve-utils/utils'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions } from '@ve-types/angular' -import { ElementObject, ElementsRequest } from '@ve-types/mms' +import { VeComponentOptions } from '@ve-types/angular'; +import { ElementObject, ElementsRequest } from '@ve-types/mms'; /** * @ngdoc directive @@ -30,35 +30,35 @@ import { ElementObject, ElementsRequest } from '@ve-types/mms' */ class ViewLinkController implements angular.IComponentController { //Bindings - public mmsElementId: string - mmsProjectId: string - mmsRefId: string - mmsCommitId: string - mmsDocId: string - mmsPeId: string - linkText: string - linkClass: string - linkIconClass: string - linkTarget: string - mmsExternalLink: boolean - suppressNumbering: boolean - showName: boolean + public mmsElementId: string; + mmsProjectId: string; + mmsRefId: string; + mmsCommitId: string; + mmsDocId: string; + mmsPeId: string; + linkText: string; + linkClass: string; + linkIconClass: string; + linkTarget: string; + mmsExternalLink: boolean; + suppressNumbering: boolean; + showName: boolean; // Controllers - private mmsCfCtrl: CrossReferenceController - private mmsViewCtrl: ViewController + private mmsCfCtrl: CrossReferenceController; + private mmsViewCtrl: ViewController; // Locals - loading: boolean = true - target: string - private processed: boolean = false - projectId: string - refId: string - commitId: string - element: ElementObject - elementName: string - type: string - $transcludeEl: JQuery + loading: boolean = true; + target: string; + private processed: boolean = false; + projectId: string; + refId: string; + commitId: string; + element: ElementObject; + elementName: string; + type: string; + $transcludeEl: JQuery; static $inject = [ '$scope', @@ -70,13 +70,13 @@ class ViewLinkController implements angular.IComponentController { 'ViewService', 'ApplicationService', 'ExtensionService', - ] - suffix: string - hash: string - href: string - private docid: string - showNum: boolean - vid: string + ]; + suffix: string; + hash: string; + href: string; + private docid: string; + showNum: boolean; + vid: string; constructor( private $scope: angular.IScope, @@ -91,47 +91,47 @@ class ViewLinkController implements angular.IComponentController { ) {} $onInit(): void { - this.target = this.linkTarget ? this.linkTarget : '_self' + this.target = this.linkTarget ? this.linkTarget : '_self'; } $onChanges(onChangesObj: angular.IOnChangesObject): void { - handleChange(onChangesObj, 'mmsElementId', this.changeAction) + handleChange(onChangesObj, 'mmsElementId', this.changeAction); } $postLink(): void { - this.changeAction(this.mmsElementId, '', false) + this.changeAction(this.mmsElementId, '', false); } protected changeAction: onChangesCallback = (newVal, oldVal, firstChange) => { - if (!newVal || (newVal === oldVal && this.processed)) return + if (!newVal || (newVal === oldVal && this.processed)) return; - this.processed = true + this.processed = true; - let projectId = this.mmsProjectId - let refId = this.mmsRefId - let commitId = this.mmsCommitId - let docid = this.mmsDocId + let projectId = this.mmsProjectId; + let refId = this.mmsRefId; + let commitId = this.mmsCommitId; + let docid = this.mmsDocId; if (this.mmsCfCtrl) { - const cfVersion = this.mmsCfCtrl.getElementOrigin() - if (!projectId) projectId = cfVersion.projectId - if (!refId) refId = cfVersion.refId - if (!commitId) commitId = cfVersion.commitId + const cfVersion = this.mmsCfCtrl.getElementOrigin(); + if (!projectId) projectId = cfVersion.projectId; + if (!refId) refId = cfVersion.refId; + if (!commitId) commitId = cfVersion.commitId; } if (this.mmsViewCtrl) { - const viewVersion = this.mmsViewCtrl.getElementOrigin() - if (!projectId) projectId = viewVersion.projectId - if (!refId) refId = viewVersion.refId - if (!commitId) commitId = viewVersion.commitId + const viewVersion = this.mmsViewCtrl.getElementOrigin(); + if (!projectId) projectId = viewVersion.projectId; + if (!refId) refId = viewVersion.refId; + if (!commitId) commitId = viewVersion.commitId; } if (!projectId) { - return + return; } - this.projectId = projectId - this.refId = refId ? refId : 'master' - this.commitId = commitId ? commitId : 'latest' - let elementId = this.mmsElementId + this.projectId = projectId; + this.refId = refId ? refId : 'master'; + this.commitId = commitId ? commitId : 'latest'; + let elementId = this.mmsElementId; if (!elementId && this.mmsPeId && !this.mmsDocId) { - elementId = this.applicationSvc.getState().currentDoc + elementId = this.applicationSvc.getState().currentDoc; } const reqOb: ElementsRequest = { @@ -139,89 +139,89 @@ class ViewLinkController implements angular.IComponentController { projectId, refId, commitId, - } + }; this.elementSvc .getElement(reqOb, 1) .then( (data: ElementObject) => { - this.element = data - this.elementName = data.name - this.type = 'Section ' - this.suffix = '' - this.hash = '#' + data.id + this.element = data; + this.elementName = data.name; + this.type = 'Section '; + this.suffix = ''; + this.hash = '#' + data.id; if (this.mmsPeId && this.mmsPeId !== '') { const reqPEOb: ElementsRequest = { elementId: this.mmsPeId, projectId, refId, commitId, - } + }; this.elementSvc.getElement(reqPEOb).then( (pe) => { - this.vid = pe.id - this.element = pe - this.elementName = pe.name + this.vid = pe.id; + this.element = pe; + this.elementName = pe.name; if (this.viewSvc.isTable(pe)) { - this.type = 'Table ' + this.type = 'Table '; } else if (this.viewSvc.isFigure(pe)) { - this.type = 'Fig. ' + this.type = 'Fig. '; } else if (this.viewSvc.isEquation(pe)) { - this.type = 'Eq. (' - this.suffix = ')' + this.type = 'Eq. ('; + this.suffix = ')'; } if (this.applicationSvc.getState().fullDoc) { - this.href = `main.project.ref.view.present.document({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })` + this.href = `main.project.ref.view.present.document({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })`; } else { - this.href = `main.project.ref.view.present.slideshow({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })` + this.href = `main.project.ref.view.present.slideshow({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })`; } }, (reason) => { - this.growl.warning(`Unable to retrieve element: ${reason.message}`) + this.growl.warning(`Unable to retrieve element: ${reason.message}`); } - ) + ); } if (this.apiSvc.isDocument(data)) { - docid = data.id - this.docid = docid - this.vid = data.id + docid = data.id; + this.docid = docid; + this.vid = data.id; } else if (this.apiSvc.isView(data) || data.type === 'InstanceSpecification') { if (!docid || docid === '') { - docid = this.applicationSvc.getState().currentDoc + docid = this.applicationSvc.getState().currentDoc; } - this.docid = docid - this.vid = data.id + this.docid = docid; + this.vid = data.id; } else { - this.$element.html('view link doesn\'t refer to a view') + this.$element.html('view link doesn\'t refer to a view'); } if (this.applicationSvc.getState().fullDoc) { - this.href = `main.project.ref.view.present.document({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })` + this.href = `main.project.ref.view.present.document({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })`; } else { - this.href = `main.project.ref.view.present.slideshow({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })` + this.href = `main.project.ref.view.present.slideshow({ projectId: $ctrl.projectId, refId: $ctrl.refId, documentId: $ctrl.docid, viewId: $ctrl.vid })`; } this.showNum = this.applicationSvc.getState().inDoc && this.applicationSvc.getState().currentDoc === this.docid && - !this.suppressNumbering + !this.suppressNumbering; }, (reason) => { - this.$element.empty() + this.$element.empty(); this.$transcludeEl = $( '' - ) - this.$element.append(this.$transcludeEl) + ); + this.$element.append(this.$transcludeEl); this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: reqOb.elementId, recentElement: reason.recentVersionOfElement, type: 'link', }) - ) + ); } ) .finally(() => { - this.loading = false - }) - } + this.loading = false; + }); + }; } export const MmsViewLinkComponent: VeComponentOptions = { @@ -260,6 +260,6 @@ export const MmsViewLinkComponent: VeComponentOptions = { showName: '<', }, controller: ViewLinkController, -} +}; -veComponents.component(MmsViewLinkComponent.selector, MmsViewLinkComponent) +veComponents.component(MmsViewLinkComponent.selector, MmsViewLinkComponent); diff --git a/src/ve-components/presentations/mmsMaturityBar.directive.ts b/src/ve-components/presentations/mmsMaturityBar.directive.ts index 8c5de38e7..871d97827 100644 --- a/src/ve-components/presentations/mmsMaturityBar.directive.ts +++ b/src/ve-components/presentations/mmsMaturityBar.directive.ts @@ -1,6 +1,6 @@ -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -veComponents.directive('mmsMaturityBar', ['$window', mmsMaturityBar]) +veComponents.directive('mmsMaturityBar', ['$window', mmsMaturityBar]); /** * @ngdoc directive @@ -12,23 +12,23 @@ veComponents.directive('mmsMaturityBar', ['$window', mmsMaturityBar]) */ function mmsMaturityBar($window) { const mmsMaturityBarLink = (scope, element, attrs) => { - const d3 = $window.d3 + const d3 = $window.d3; - const svgContainer = d3.select(element[0]).append('svg').attr('width', 520).attr('height', 70) - let colorRect + const svgContainer = d3.select(element[0]).append('svg').attr('width', 520).attr('height', 70); + let colorRect; if (scope.state == 'Identified') { - colorRect = ['brown', '#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0'] + colorRect = ['brown', '#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0']; } else if (scope.state == 'Draft') { - colorRect = ['#FF7519', '#FF7519', '#B0B0B0', '#B0B0B0', '#B0B0B0'] + colorRect = ['#FF7519', '#FF7519', '#B0B0B0', '#B0B0B0', '#B0B0B0']; } else if (scope.state == 'Prelim') { - colorRect = ['#FFAA00', '#FFAA00', '#FFAA00', '#B0B0B0', '#B0B0B0'] + colorRect = ['#FFAA00', '#FFAA00', '#FFAA00', '#B0B0B0', '#B0B0B0']; } else if (scope.state == 'Baseline') { - colorRect = ['#04859E', '#04859E', '#04859E', '#04859E', '#B0B0B0'] + colorRect = ['#04859E', '#04859E', '#04859E', '#04859E', '#B0B0B0']; } else if (scope.state == 'Final') { - colorRect = ['#00BD39', '#00BD39', '#00BD39', '#00BD39', '#00BD39'] + colorRect = ['#00BD39', '#00BD39', '#00BD39', '#00BD39', '#00BD39']; } else { - colorRect = ['#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0'] + colorRect = ['#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0', '#B0B0B0']; } svgContainer @@ -39,7 +39,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[0]) .style('stroke', '#fff') - .style('stroke-width', 3) + .style('stroke-width', 3); svgContainer .append('text') .text('Identified') @@ -48,7 +48,7 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle') + .style('text-anchor', 'middle'); svgContainer .append('rect') .attr('x', 110) @@ -57,7 +57,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[1]) .style('stroke', '#fff') - .style('stroke-width', 3) + .style('stroke-width', 3); svgContainer .append('text') .text('Draft') @@ -66,7 +66,7 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle') + .style('text-anchor', 'middle'); svgContainer .append('rect') .attr('x', 210) @@ -75,7 +75,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[2]) .style('stroke', '#fff') - .style('stroke-width', 3) + .style('stroke-width', 3); svgContainer .append('text') .text('Prelim') @@ -84,7 +84,7 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle') + .style('text-anchor', 'middle'); svgContainer .append('rect') .attr('x', 310) @@ -93,7 +93,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[3]) .style('stroke', '#fff') - .style('stroke-width', 3) + .style('stroke-width', 3); svgContainer .append('text') .text('Baseline') @@ -102,7 +102,7 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle') + .style('text-anchor', 'middle'); svgContainer .append('rect') .attr('x', 410) @@ -111,7 +111,7 @@ function mmsMaturityBar($window) { .attr('height', 50) .style('fill', colorRect[4]) .style('stroke', '#fff') - .style('stroke-width', 3) + .style('stroke-width', 3); svgContainer .append('text') .text('Final') @@ -120,8 +120,8 @@ function mmsMaturityBar($window) { .attr('dy', '.35em') .attr('fill', '#fff') .attr('font-family', 'sans-serif') - .style('text-anchor', 'middle') - } + .style('text-anchor', 'middle'); + }; return { restrict: 'E', @@ -130,5 +130,5 @@ function mmsMaturityBar($window) { state: '@', }, link: mmsMaturityBarLink, - } + }; } diff --git a/src/ve-components/presentations/presentation-element.controller.ts b/src/ve-components/presentations/presentation-element.controller.ts index 7c00141e1..f0aa45e5d 100644 --- a/src/ve-components/presentations/presentation-element.controller.ts +++ b/src/ve-components/presentations/presentation-element.controller.ts @@ -1,56 +1,56 @@ -import $ from 'jquery' +import $ from 'jquery'; -import { ViewHtmlService, ViewPresentationElemController, PresentationService } from '@ve-components/presentations' -import { ViewController } from '@ve-components/presentations/view.component' -import { ComponentService, ExtensionService } from '@ve-components/services' -import { ButtonBarService } from '@ve-core/button-bar' -import { ImageService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { SchemaService } from '@ve-utils/model-schema' +import { ViewHtmlService, ViewPresentationElemController, PresentationService } from '@ve-components/presentations'; +import { ViewController } from '@ve-components/presentations/view.component'; +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { ImageService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { SchemaService } from '@ve-utils/model-schema'; -import { VePromise, VeQService } from '@ve-types/angular' +import { VePromise, VeQService } from '@ve-types/angular'; import { ElementObject, InstanceSpecObject, InstanceValueObject, PresentationInstanceObject, ViewObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; export class PresentationLite { //Bindings - public peObject: PresentationInstanceObject - public instanceSpec: InstanceSpecObject - public peNumber: string + public peObject: PresentationInstanceObject; + public instanceSpec: InstanceSpecObject; + public peNumber: string; } export class Presentation extends PresentationLite { //Bindings - protected mmsProjectId: string - protected mmsRefId: string - protected mmsCommitId: string + protected mmsProjectId: string; + protected mmsRefId: string; + protected mmsCommitId: string; //Deps - protected mmsViewPresentationElemCtrl: ViewPresentationElemController - protected mmsViewCtrl: ViewController + protected mmsViewPresentationElemCtrl: ViewPresentationElemController; + protected mmsViewCtrl: ViewController; - subs: Rx.IDisposable[] + subs: Rx.IDisposable[]; //Common //public element: ElementObject; - protected $transcludeEl: JQuery - public view: ViewObject - public projectId: string - public refId: string - public commitId: string - public instanceVal: InstanceValueObject - protected presentationElem: PresentationInstanceObject | ElementObject - protected isDirectChildOfPresentationElement: boolean + protected $transcludeEl: JQuery; + public view: ViewObject; + public projectId: string; + public refId: string; + public commitId: string; + public instanceVal: InstanceValueObject; + protected presentationElem: PresentationInstanceObject | ElementObject; + protected isDirectChildOfPresentationElement: boolean; - public number: string - public level: number + public number: string; + public level: number; - private schema = 'cameo' + private schema = 'cameo'; static $inject = [ '$q', @@ -66,7 +66,7 @@ export class Presentation extends PresentationLite { 'ImageService', 'ButtonBarService', 'ExtensionService', - ] + ]; constructor( protected $q: VeQService, protected $element: JQuery, @@ -82,36 +82,36 @@ export class Presentation extends PresentationLite { protected buttonBarSvc: ButtonBarService, protected extensionSvc: ExtensionService ) { - super() + super(); } /** * @listens element.updated */ $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); - this.setNumber() + this.setNumber(); - let projectId = this.mmsProjectId - let refId = this.mmsRefId - let commitId = this.mmsCommitId + let projectId = this.mmsProjectId; + let refId = this.mmsRefId; + let commitId = this.mmsCommitId; if (this.mmsViewCtrl) { - const viewVersion = this.mmsViewCtrl.getElementOrigin() - if (!projectId) projectId = viewVersion.projectId - if (!refId) refId = viewVersion.refId - if (!commitId) commitId = viewVersion.commitId + const viewVersion = this.mmsViewCtrl.getElementOrigin(); + if (!projectId) projectId = viewVersion.projectId; + if (!refId) refId = viewVersion.refId; + if (!commitId) commitId = viewVersion.commitId; } - this.projectId = projectId - this.refId = refId ? refId : 'master' - this.commitId = commitId ? commitId : 'latest' + this.projectId = projectId; + this.refId = refId ? refId : 'master'; + this.commitId = commitId ? commitId : 'latest'; - this.config() + this.config(); } $postLink(): void { - this.recompile() + this.recompile(); } // Presentation Api @@ -124,7 +124,7 @@ export class Presentation extends PresentationLite { */ protected config = (): void => { /* Implement any initialization Logic Here */ - } + }; /** * @name Presentation/getContent @@ -132,8 +132,8 @@ export class Presentation extends PresentationLite { * @description Extension API method in which presentation components should return the content they wish to display. */ protected getContent = (): VePromise => { - return this.$q.reject('Not Yet Implemented') - } + return this.$q.reject('Not Yet Implemented'); + }; /** * @name Presentation/recompile @@ -143,16 +143,16 @@ export class Presentation extends PresentationLite { * This function is automatically triggered by the "element.updated" event. */ protected recompile = (): void => { - this.setNumber() + this.setNumber(); this.getContent().then( (result) => { - this.$element.empty() - this.$transcludeEl = $(result) + this.$element.empty(); + this.$transcludeEl = $(result); this.$transcludeEl.find('img').each((index, element) => { - this.imageSvc.fixImgSrc($(element)) - }) - this.$element.append(this.$transcludeEl) - this.$compile(this.$transcludeEl)(this.$scope) + this.imageSvc.fixImgSrc($(element)); + }); + this.$element.append(this.$transcludeEl); + this.$compile(this.$transcludeEl)(this.$scope); }, (reason) => { const reqOb = { @@ -161,23 +161,23 @@ export class Presentation extends PresentationLite { refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - } - this.$element.empty() + }; + this.$element.empty(); //TODO: Add reason/errorMessage handling here. this.$transcludeEl = $( '' - ) - this.$element.append(this.$transcludeEl) + ); + this.$element.append(this.$transcludeEl); this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: reqOb.elementId, recentElement: reason.recentVersionOfElement, type: 'presentation', }) - ) + ); } - ) - } + ); + }; // Static Helper Functions /** @@ -189,9 +189,9 @@ export class Presentation extends PresentationLite { */ public setNumber = (): void => { if (this.peNumber) { - if (Number.isInteger(this.peNumber)) this.level = 1 - else this.level = this.peNumber.split('.').length - this.number = this.peNumber + if (Number.isInteger(this.peNumber)) this.level = 1; + else this.level = this.peNumber.split('.').length; + this.number = this.peNumber; } - } + }; } diff --git a/src/ve-components/presentations/services/Presentation.service.ts b/src/ve-components/presentations/services/Presentation.service.ts index 6c35f228f..4e27e887a 100644 --- a/src/ve-components/presentations/services/Presentation.service.ts +++ b/src/ve-components/presentations/services/Presentation.service.ts @@ -1,23 +1,23 @@ -import { InsertPresentationData } from '@ve-components/insertions/components/insert-pe.component' -import { ViewService } from '@ve-utils/mms-api-client' +import { InsertPresentationData } from '@ve-components/insertions/components/insert-pe.component'; +import { ViewService } from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { InsertResolveFn } from '@ve-types/components' -import { ElementObject, InstanceSpecObject, InstanceValueObject } from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +import { InsertResolveFn } from '@ve-types/components'; +import { ElementObject, InstanceSpecObject, InstanceValueObject } from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; export class PresentationService { private revertData: { - elementId: string - baseCommit: object - refId: string - compareCommit: object - projectId: string - element: object - } + elementId: string; + baseCommit: object; + refId: string; + compareCommit: object; + projectId: string; + element: object; + }; - static $inject = ['$timeout', '$uibModal', 'growl', 'ViewService'] + static $inject = ['$timeout', '$uibModal', 'growl', 'ViewService']; constructor( private $timeout: angular.ITimeoutService, @@ -29,23 +29,23 @@ export class PresentationService { public checkForDuplicateInstances(operand: InstanceValueObject[]): InstanceValueObject[] { const seen: { [id: string]: boolean } = {}, dups: InstanceValueObject[] = [], - cleared: InstanceValueObject[] = [] - let curr: string + cleared: InstanceValueObject[] = []; + let curr: string; operand.forEach((value, index) => { - curr = value.instanceId + curr = value.instanceId; if (curr) { if (seen[curr]) { - dups.push(value) - operand.splice(index, 1) - return + dups.push(value); + operand.splice(index, 1); + return; } - cleared.push(value) - seen[curr] = true + cleared.push(value); + seen[curr] = true; } - }) - operand.length = 0 - operand.push(...cleared) - return dups + }); + operand.length = 0; + operand.push(...cleared); + return dups; } /** @@ -69,46 +69,46 @@ export class PresentationService { viewOrSectionOb, addPeIndex: $ctrl.addPeIndex, parentBranch: null, - } + }; }, getProjectId: () => { - return viewOrSectionOb._projectId + return viewOrSectionOb._projectId; }, getRefId: () => { - return viewOrSectionOb._refId + return viewOrSectionOb._refId; }, getOrgId: () => { - return '' + return ''; }, }, - }) + }); instance.result.then( (data) => { if (data.type !== 'InstanceSpecification' || this.viewSvc.isSection(data)) { - return //do not open editor for existing pes added or if pe/owner is a section + return; //do not open editor for existing pes added or if pe/owner is a section } void this.$timeout( () => { //auto open editor for newly added pe $('#' + data.id) .find('transclude-doc,transclude-com') - .trigger('click') + .trigger('click'); }, 0, false - ) + ); }, (reason) => { if (reason && reason.status !== 444) { - this.growl.warning(`Error adding PE: ${reason.message}`) + this.growl.warning(`Error adding PE: ${reason.message}`); } else { this.growl.info('PE Insert Cancelled', { ttl: 1000, - }) + }); } } - ) + ); } } -veComponents.service('PresentationService', PresentationService) +veComponents.service('PresentationService', PresentationService); diff --git a/src/ve-components/presentations/services/Table2CSV.service.ts b/src/ve-components/presentations/services/Table2CSV.service.ts index 64650a96f..04bb4ec81 100644 --- a/src/ve-components/presentations/services/Table2CSV.service.ts +++ b/src/ve-components/presentations/services/Table2CSV.service.ts @@ -1,4 +1,4 @@ -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; export class Table2CSVService { public static export(el: JQuery, inputOptions: JQuery.table2CSV.inputOptions): string { @@ -9,113 +9,113 @@ export class Table2CSVService { delivery: 'popup', // popup, value }, inputOptions - ) + ); - const csvData: string[] = [] + const csvData: string[] = []; // const el = this const row2CSV = (tmpRow: string[]): void => { - const tmp = tmpRow.join('') // to remove any blank rows + const tmp = tmpRow.join(''); // to remove any blank rows if (tmpRow.length > 0 && tmp != '') { - csvData[csvData.length] = tmpRow.join(options.separator) + csvData[csvData.length] = tmpRow.join(options.separator); } - } + }; const formatData = (input: string): string => { // replace " with “ - const regexp = new RegExp(/["]/g) - let output = input.replace(regexp, '“') + const regexp = new RegExp(/["]/g); + let output = input.replace(regexp, '“'); //HTML // var regexp = new RegExp(/\<[^\<]+\>/g); // var output = output.replace(regexp, ""); - const i = output.search(/\S/) //index of first non whitespace char + const i = output.search(/\S/); //index of first non whitespace char if (i > 0) { - output = '_'.repeat(i) + $.trim(output) + output = '_'.repeat(i) + $.trim(output); } - output = $.trim(output) - if (output == '') return '' + output = $.trim(output); + if (output == '') return ''; if (output[0] == '+' || output[0] == '=' || output[0] == '-') { - output = ' ' + output + output = ' ' + output; } - return `"${output}"` - } + return `"${output}"`; + }; const popup = (data: string): string => { - const generator = window.open('', 'csv', 'height=400,width=600') - generator.document.write('CSV') - generator.document.write('') - generator.document.write('') - generator.document.write('') - generator.document.close() - return 'ok' - } + const generator = window.open('', 'csv', 'height=400,width=600'); + generator.document.write('CSV'); + generator.document.write(''); + generator.document.write(''); + generator.document.write(''); + generator.document.close(); + return 'ok'; + }; const handleMatrix = (bodyTag: string, cellTag: string): void => { - const spanData: { [row: number]: { [column: number]: unknown } } = {} //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell - let curRow = 0 + const spanData: { [row: number]: { [column: number]: unknown } } = {}; //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell + let curRow = 0; $(el) .children(bodyTag) .children('tr') .each((index, element) => { - tmpRow = [] - let curCol = 0 + tmpRow = []; + let curCol = 0; $(element) .children(cellTag) .each((index, element) => { while (spanData[curRow] && spanData[curRow][curCol]) { - tmpRow.push('""') - curCol++ + tmpRow.push('""'); + curCol++; } - tmpRow.push(formatData($(element).text())) - const rowstring = $(element).attr('rowspan') - const rowspan = parseInt(rowstring) + tmpRow.push(formatData($(element).text())); + const rowstring = $(element).attr('rowspan'); + const rowspan = parseInt(rowstring); if (rowspan && rowspan > 1) { for (let i = 1; i < rowspan; i++) { if (!spanData[curRow + i]) { - spanData[curRow + i] = {} + spanData[curRow + i] = {}; } - spanData[curRow + i][curCol] = true + spanData[curRow + i][curCol] = true; } } - const colstring = $(element).attr('colspan') + const colstring = $(element).attr('colspan'); if (!colstring) { - curCol++ - return + curCol++; + return; } - let colspan = parseInt(colstring) + let colspan = parseInt(colstring); while (colspan > 1) { - curCol++ - tmpRow.push('""') - colspan-- + curCol++; + tmpRow.push('""'); + colspan--; if (rowspan > 1) { for (let i = 1; i < rowspan; i++) { - spanData[curRow + i][curCol] = true + spanData[curRow + i][curCol] = true; } } } - curCol++ - }) - row2CSV(tmpRow) - curRow++ - }) - } + curCol++; + }); + row2CSV(tmpRow); + curRow++; + }); + }; //header - const numCols = options.header.length - let tmpRow: string[] = [] + const numCols = options.header.length; + let tmpRow: string[] = []; if (numCols > 0) { for (let i = 0; i < numCols; i++) { - tmpRow[tmpRow.length] = formatData(options.header[i]) + tmpRow[tmpRow.length] = formatData(options.header[i]); } } else { - handleMatrix('thead', 'th') + handleMatrix('thead', 'th'); } // actual data - handleMatrix('tbody', 'td') - const mydata = csvData.join('\n') + handleMatrix('tbody', 'td'); + const mydata = csvData.join('\n'); if (options.delivery == 'popup') { - return popup(mydata) + return popup(mydata); } else { - return mydata + return mydata; } } } -veComponents.service('Table2CSVService', Table2CSVService) +veComponents.service('Table2CSVService', Table2CSVService); diff --git a/src/ve-components/presentations/services/ViewHtml.service.ts b/src/ve-components/presentations/services/ViewHtml.service.ts index daa144561..3dc9d009d 100644 --- a/src/ve-components/presentations/services/ViewHtml.service.ts +++ b/src/ve-components/presentations/services/ViewHtml.service.ts @@ -1,8 +1,8 @@ -import { ApplicationService } from '@ve-utils/application' +import { ApplicationService } from '@ve-utils/application'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { ITableConfig } from '@ve-types/components/presentation' +import { ITableConfig } from '@ve-types/components/presentation'; import { PresentationInstanceObject, PresentImageObject, @@ -10,7 +10,7 @@ import { PresentTableObject, PresentTextObject, TableEntryObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; export class ViewHtmlService { public tableConfig: ITableConfig = { @@ -20,9 +20,9 @@ export class ViewHtmlService { showBindingForSortIcon: -1, filterDebounceRate: 200, filterTermColumnPrefixBinding: 'filterTermForColumn', - } + }; - static $inject = ['ApplicationService'] + static $inject = ['ApplicationService']; constructor(private applicationSvc: ApplicationService) {} @@ -36,65 +36,65 @@ export class ViewHtmlService { * @returns {string} generated html string */ public makeHtmlTable = (table: PresentTableObject, isFilterable?: boolean, isSortable?: boolean, pe?): string => { - const result = [''] + const result = ['
    ']; if (table.colwidths && table.colwidths.length > 0) { - result.push('') + result.push(''); for (let i = 0; i < table.colwidths.length; i++) { if (table.colwidths[i]) { - result.push('') + result.push(''); } else { - result.push('') + result.push(''); } } - result.push('') + result.push(''); } - result.push('') //put tbody before thead to control stacking context so if freeze header/columns are both used headers cover cells (?) + result.push(''); //put tbody before thead to control stacking context so if freeze header/columns are both used headers cover cells (?) //https://stackoverflow.com/questions/45676848/stacking-context-on-table-elementhead-and-body - result.push(this.makeTableBody(table.body, false)) - result.push('') + result.push(this.makeTableBody(table.body, false)); + result.push(''); if (table.header && table.header.length) { // only add styling to the filterable or sortable header if (isFilterable || isSortable) { - result.push('') + result.push(''); } else { - result.push('') + result.push(''); } - result.push(this.makeTableBody(table.header, true, isFilterable, isSortable)) - result.push('') + result.push(this.makeTableBody(table.header, true, isFilterable, isSortable)); + result.push(''); } if (this.applicationSvc.getState().inDoc && !table.excludeFromList) { result.push( '' - ) + ); } else if (table.title) { - result.push('') + result.push(''); } //same for caption to control stacking context - result.push('
    Table {{$ctrl.instanceSpec._veNumber}}. {{$ctrl.table.title || $ctrl.instanceSpec.name}}' + table.title + '' + table.title + '
    ') - return result.join('') - } + result.push(''); + return result.join(''); + }; /** Include row and column number for table's header data object **/ public generateRowColNumber(header: TableEntryObject[][]): void { header.forEach((row, rowIndex) => { - let startCol = 0 - let colCounter = 0 + let startCol = 0; + let colCounter = 0; row.forEach((cell, cellIndex) => { // startCol is always 0 except when row > 0th and on cell === 0th && rowSpan of the previous row's first element is larger than 1 // This is the only time when we need to offset the starting colNumber for cells under merged this.column(s) if (rowIndex !== 0 && cellIndex === 0 && Number(header[rowIndex - 1][0].rowspan) > 1) { - startCol = Number(header[rowIndex - 1][0].colspan) + startCol = Number(header[rowIndex - 1][0].colspan); } - const colSpan = Number(cell.colspan) - cell.startRow = rowIndex - cell.endRow = cell.startRow + Number(cell.rowspan) - 1 - cell.startCol = startCol + colCounter - cell.endCol = cell.startCol + colSpan - 1 - colCounter += colSpan - }) - startCol = 0 - colCounter = 0 - }) + const colSpan = Number(cell.colspan); + cell.startRow = rowIndex; + cell.endRow = cell.startRow + Number(cell.rowspan) - 1; + cell.startCol = startCol + colCounter; + cell.endCol = cell.startCol + colSpan - 1; + colCounter += colSpan; + }); + startCol = 0; + colCounter = 0; + }); } /** @@ -114,46 +114,46 @@ export class ViewHtmlService { isSortable?: boolean ): string { if (isHeader && (isFilterable || isSortable)) { - this.generateRowColNumber(body) + this.generateRowColNumber(body); } - const result = [] - const dtag: string = isHeader ? 'th' : 'td' + const result = []; + const dtag: string = isHeader ? 'th' : 'td'; body.forEach((row) => { - result.push('') + result.push(''); row.forEach((cell) => { - result.push(`<${dtag} colspan="${cell.colspan}" rowspan="${cell.rowspan}">`) + result.push(`<${dtag} colspan="${cell.colspan}" rowspan="${cell.rowspan}">`); cell.content.forEach((thing) => { if (isFilterable || isSortable) { - result.push('
    ') + result.push('
    '); } else { - result.push('
    ') + result.push('
    '); } - let thingString = this.makeHtml(thing) + let thingString = this.makeHtml(thing); if (thing.type === 'Paragraph') { if ((isFilterable || isSortable) && thing.sourceType === 'text' && dtag === 'th') { - thingString = thingString.replace('

    ', '

    ') + thingString = thingString.replace('

    ', '

    '); } } - result.push(thingString) - result.push('

    ') + result.push(thingString); + result.push('
    '); if (isHeader) { if (isSortable && Number(cell.colspan) === 1) { result.push( `` - ) + ); } if (isFilterable) { result.push( `` - ) + ); } } - }) - result.push('') - }) - result.push('') - }) - return result.join('') + }); + result.push(''); + }); + result.push(''); + }); + return result.join(''); } /** @@ -164,22 +164,22 @@ export class ViewHtmlService { * @returns {string} generated html string */ public makeHtmlList = (list: PresentListObject): string => { - const result: string[] = [] - if (list.ordered) result.push('
      ') - else result.push('
        ') + const result: string[] = []; + if (list.ordered) result.push('
          '); + else result.push('
            '); list.list.forEach((item) => { - result.push('
          • ') + result.push('
          • '); item.forEach((thing) => { - result.push('
            ') - result.push(this.makeHtml(thing)) - result.push('
            ') - }) - result.push('
          • ') - }) - if (list.ordered) result.push('
        ') - else result.push('
      ') - return result.join('') - } + result.push('
      '); + result.push(this.makeHtml(thing)); + result.push('
      '); + }); + result.push(''); + }); + if (list.ordered) result.push('
    '); + else result.push(''); + return result.join(''); + }; /** * @name veUtils/UtilsService#makeHtmlPara @@ -189,32 +189,32 @@ export class ViewHtmlService { * @returns {string} generated html string */ public makeHtmlPara = (para: PresentTextObject): string => { - if (para.sourceType === 'text') return para.text - let t = 'doc' - let attr = '' + if (para.sourceType === 'text') return para.text; + let t = 'doc'; + let attr = ''; if (para.sourceProperty === 'name') { - t = 'name' + t = 'name'; } if (para.sourceProperty === 'value') { - t = 'val' + t = 'val'; } if (para.nonEditable) { - attr = ` non-editable="${para.nonEditable.toString()}"` + attr = ` non-editable="${para.nonEditable.toString()}"`; } - return '' - } + return ''; + }; public makeHtml = (thing: PresentationInstanceObject): string => { if (thing.type === 'Paragraph') { - return this.makeHtmlPara(thing as PresentTextObject) + return this.makeHtmlPara(thing as PresentTextObject); } else if (thing.type === 'Table') { - return this.makeHtmlTable(thing as PresentTableObject) + return this.makeHtmlTable(thing as PresentTableObject); } else if (thing.type === 'List') { - return this.makeHtmlList(thing as PresentListObject) + return this.makeHtmlList(thing as PresentListObject); } else if (thing.type === 'Image') { - return `` + return ``; } - } + }; } -veComponents.service('ViewHtmlService', ViewHtmlService) +veComponents.service('ViewHtmlService', ViewHtmlService); diff --git a/src/ve-components/presentations/view-pe.component.ts b/src/ve-components/presentations/view-pe.component.ts index eae202dff..35f0f0864 100644 --- a/src/ve-components/presentations/view-pe.component.ts +++ b/src/ve-components/presentations/view-pe.component.ts @@ -1,21 +1,21 @@ -import $ from 'jquery' +import $ from 'jquery'; -import { ViewController } from '@ve-components/presentations/view.component' -import { ExtensionService } from '@ve-components/services' -import { TreeService } from '@ve-components/trees' -import { EventService } from '@ve-utils/core' -import { ElementService, ViewService } from '@ve-utils/mms-api-client' +import { ViewController } from '@ve-components/presentations/view.component'; +import { ExtensionService } from '@ve-components/services'; +import { TreeService } from '@ve-components/trees'; +import { EventService } from '@ve-utils/core'; +import { ElementService, ViewService } from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromiseReason } from '@ve-types/angular' +import { VeComponentOptions, VePromiseReason } from '@ve-types/angular'; import { ElementObject, ElementsRequest, InstanceSpecObject, InstanceValueObject, PresentationInstanceObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc component @@ -38,17 +38,17 @@ import { * @param {Object} mmsParentSection the parent section if available */ export class ViewPresentationElemController implements angular.IComponentController { - private mmsInstanceVal: InstanceValueObject - private mmsParentSection: InstanceSpecObject + private mmsInstanceVal: InstanceValueObject; + private mmsParentSection: InstanceSpecObject; - private viewCtrl: ViewController + private viewCtrl: ViewController; - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; - public presentationElemLoading: boolean - public instanceSpec: InstanceSpecObject - public presentationElem: PresentationInstanceObject | ElementObject - public peNumber: string + public presentationElemLoading: boolean; + public instanceSpec: InstanceSpecObject; + public presentationElem: PresentationInstanceObject | ElementObject; + public peNumber: string; static $inject = [ '$scope', @@ -63,7 +63,7 @@ export class ViewPresentationElemController implements angular.IComponentControl 'TreeService', 'ExtensionService', 'EventService', - ] + ]; constructor( private $scope: angular.IScope, private $element: JQuery, @@ -80,51 +80,51 @@ export class ViewPresentationElemController implements angular.IComponentControl ) {} $onInit(): void { - this.presentationElemLoading = true - this.eventSvc.$init(this) + this.presentationElemLoading = true; + this.eventSvc.$init(this); if (!this.mmsInstanceVal || !this.mmsInstanceVal.instanceId) { - this.$element.html('Reference is null') - return + this.$element.html('Reference is null'); + return; } - let projectId: string = null - let refId: string = null - let commitId: string = null + let projectId: string = null; + let refId: string = null; + let commitId: string = null; if (this.viewCtrl) { - const viewVersion = this.viewCtrl.getElementOrigin() - projectId = viewVersion.projectId - refId = viewVersion.refId - commitId = viewVersion.commitId + const viewVersion = this.viewCtrl.getElementOrigin(); + projectId = viewVersion.projectId; + refId = viewVersion.refId; + commitId = viewVersion.commitId; } // Parse the element reference tree for the presentation element: - this.$element.addClass('isLoading') + this.$element.addClass('isLoading'); const reqOb = { elementId: this.mmsInstanceVal.instanceId, projectId: projectId, refId: refId, commitId: commitId, //includeRecentVersionElement: true, - } + }; this.elementSvc .getElement(reqOb, 1) .then( (instanceSpec) => { this.viewSvc.getViewElements(reqOb, 1).finally(() => { - this.instanceSpec = instanceSpec - this.presentationElem = this.viewSvc.getPresentationInstanceObject(instanceSpec) - this.presentationElemLoading = false + this.instanceSpec = instanceSpec; + this.presentationElem = this.viewSvc.getPresentationInstanceObject(instanceSpec); + this.presentationElemLoading = false; if (this.viewCtrl) { - this.viewCtrl.elementTranscluded(instanceSpec, this.presentationElem.type) + this.viewCtrl.elementTranscluded(instanceSpec, this.presentationElem.type); } this.$element.on('click', (e) => { - if (this.viewCtrl) this.viewCtrl.transcludeClicked(instanceSpec) - e.stopPropagation() - }) - const tag = this.extensionSvc.getTagByType('present', this.presentationElem.type) + if (this.viewCtrl) this.viewCtrl.transcludeClicked(instanceSpec); + e.stopPropagation(); + }); + const tag = this.extensionSvc.getTagByType('present', this.presentationElem.type); const newPe = $( '
    ' - ) + ); $(newPe).append( '<' + tag + @@ -132,35 +132,35 @@ export class ViewPresentationElemController implements angular.IComponentControl '' - ) - $(this.$element).append(newPe) - this.$compile(newPe)(this.$scope) - }) + ); + $(this.$element).append(newPe); + this.$compile(newPe)(this.$scope); + }); }, (reason) => { - this._error(reqOb, reason) + this._error(reqOb, reason); } ) .finally(() => { - this.$element.removeClass('isLoading') - }) + this.$element.removeClass('isLoading'); + }); } public getInstanceSpec = (): InstanceSpecObject => { - return this.instanceSpec - } + return this.instanceSpec; + }; public getInstanceVal = (): InstanceValueObject => { - return this.mmsInstanceVal - } + return this.mmsInstanceVal; + }; public getPresentationElement = (): ElementObject | PresentationInstanceObject => { - return this.presentationElem - } + return this.presentationElem; + }; public getParentSection = (): InstanceSpecObject => { - return this.mmsParentSection - } + return this.mmsParentSection; + }; private _error = (reqOb: ElementsRequest, reason: VePromiseReason): void => { if (reason.status === 500) { @@ -168,23 +168,23 @@ export class ViewPresentationElemController implements angular.IComponentControl 'View element reference error: ' + this.mmsInstanceVal.instanceId + ' invalid specification' - ) + ); } else { - this.$element.empty() + this.$element.empty(); const annotation = $( '' - ) - this.$element.append(annotation) + ); + this.$element.append(annotation); this.$compile(annotation)( Object.assign(this.$scope.$new(), { elementId: reqOb.elementId, recentElement: reason.recentVersionOfElement, type: 'presentation', }) - ) + ); } - } + }; } const ViewPeComponent: VeComponentOptions = { @@ -200,6 +200,6 @@ const ViewPeComponent: VeComponentOptions = { mmsParentSection: '<', }, controller: ViewPresentationElemController, -} +}; -veComponents.component(ViewPeComponent.selector, ViewPeComponent) +veComponents.component(ViewPeComponent.selector, ViewPeComponent); diff --git a/src/ve-components/presentations/view.component.ts b/src/ve-components/presentations/view.component.ts index ec72fdf56..8bf880d12 100644 --- a/src/ve-components/presentations/view.component.ts +++ b/src/ve-components/presentations/view.component.ts @@ -1,13 +1,13 @@ -import { PresentationService } from '@ve-components/presentations/services/Presentation.service' -import { TreeService } from '@ve-components/trees' -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ElementService, UserService, ViewApi, ViewService } from '@ve-utils/mms-api-client' -import { handleChange, onChangesCallback } from '@ve-utils/utils' +import { PresentationService } from '@ve-components/presentations/services/Presentation.service'; +import { TreeService } from '@ve-components/trees'; +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ElementService, UserService, ViewApi, ViewService } from '@ve-utils/mms-api-client'; +import { handleChange, onChangesCallback } from '@ve-utils/utils'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; import { ElementObject, ElementsRequest, @@ -18,7 +18,7 @@ import { ValueObject, ViewInstanceSpec, ViewObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc directive @@ -68,15 +68,15 @@ import { export class ViewController implements angular.IComponentController { // private presentationElemCleanUpFncs: {(): any}[] = []; - private mmsElementId: string - private mmsProjectId: string - private mmsRefId: string - private mmsCommitId: string - private mmsLink: boolean - public mmsViewApi: ViewApi - private mmsNumber: number - public noTitle: boolean - public buttonId: string + private mmsElementId: string; + private mmsProjectId: string; + private mmsRefId: string; + private mmsCommitId: string; + private mmsLink: boolean; + public mmsViewApi: ViewApi; + private mmsNumber: number; + public noTitle: boolean; + public buttonId: string; static $inject = [ '$element', @@ -88,26 +88,26 @@ export class ViewController implements angular.IComponentController { 'EventService', 'TreeService', 'RootScopeService', - ] - private showEdits: boolean - private modified: string - private modifier: UserObject - private view: ViewObject + ]; + private showEdits: boolean; + private modified: string; + private modifier: UserObject; + private view: ViewObject; private reqOb: ElementsRequest = { elementId: '', projectId: '', refId: '', commitId: '', - } - private processed: boolean - private isHover: boolean - private isSection: boolean - private level: number - private number: string = '' - private showComments: boolean - private showElements: boolean - private showNumbering: boolean - public subs: Rx.IDisposable[] + }; + private processed: boolean; + private isHover: boolean; + private isSection: boolean; + private level: number; + private number: string = ''; + private showComments: boolean; + private showElements: boolean; + private showNumbering: boolean; + public subs: Rx.IDisposable[]; constructor( private $element: JQuery, @@ -122,59 +122,59 @@ export class ViewController implements angular.IComponentController { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); this.reqOb = { elementId: this.mmsElementId, projectId: this.mmsProjectId, refId: this.mmsRefId, commitId: this.mmsCommitId, - } - this.processed = false + }; + this.processed = false; if (this.mmsNumber) { - this.number = this.mmsNumber.toString(10) + this.number = this.mmsNumber.toString(10); } else if (this.treeSvc.branch2viewNumber[this.mmsElementId]) { - this.number = this.treeSvc.branch2viewNumber[this.mmsElementId] + this.number = this.treeSvc.branch2viewNumber[this.mmsElementId]; } - this.showNumbering = this.rootScopeSvc.veNumberingOn() + this.showNumbering = this.rootScopeSvc.veNumberingOn(); - this.isSection = false - this.showElements = false - this.showComments = false - this.showEdits = false + this.isSection = false; + this.showElements = false; + this.showComments = false; + this.showEdits = false; this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VEELEMENTSON, (data) => { - this.toggleShowElements(data) + this.toggleShowElements(data); }), this.eventSvc.binding(this.rootScopeSvc.constants.VECOMMENTSON, (data) => { - this.toggleShowComments(data) + this.toggleShowComments(data); }), this.eventSvc.binding(this.rootScopeSvc.constants.VENUMBERINGON, (data) => { - this.showNumbering = data + this.showNumbering = data; }), this.eventSvc.binding(this.rootScopeSvc.constants.VEEDITMODE, (data) => { - this.toggleShowEdits(data) + this.toggleShowEdits(data); }) - ) + ); this.subs.push( this.eventSvc.binding(TreeService.events.UPDATED, (data) => { - if (!data) return + if (!data) return; if (this.treeSvc.branch2viewNumber[this.mmsElementId]) { - this.level = this.treeSvc.branch2viewNumber[this.mmsElementId].split('.').length + this.level = this.treeSvc.branch2viewNumber[this.mmsElementId].split('.').length; } }) - ) + ); - this._changeView(this.mmsElementId, '') + this._changeView(this.mmsElementId, ''); } $onChanges(onChangesObj: angular.IOnChangesObject): void { handleChange(onChangesObj, 'mmsNumber', (newVal: string) => { - this.number = newVal - }) - handleChange(onChangesObj, 'mmsElementId', this._changeView, true) + this.number = newVal; + }); + handleChange(onChangesObj, 'mmsElementId', this._changeView, true); } public isTranscludedElement = (elementName): boolean => { @@ -185,35 +185,35 @@ export class ViewController implements angular.IComponentController { elementName === 'MMS-TRANSCLUDE-IMG' || elementName === 'MMS-TRANSCLUDE-NAME' || elementName === 'MMS-TRANSCLUDE-VAL' - ) - } + ); + }; public isEditable = (): boolean => { - return this.showEdits - } + return this.showEdits; + }; public transcludeClicked = (elementOb: ElementObject): void => { - if (this.mmsViewApi && this.mmsViewApi.elementClicked && elementOb) this.mmsViewApi.elementClicked(elementOb) - } + if (this.mmsViewApi && this.mmsViewApi.elementClicked && elementOb) this.mmsViewApi.elementClicked(elementOb); + }; public elementTranscluded = (elem: ElementObject, type: string): void => { if (elem) { if (elem._modified > this.modified && type !== 'Comment') { - this.modified = elem._modified + this.modified = elem._modified; if (elem._modifier) { this.userSvc.getUserData(elem._modifier).then( (result) => { - this.modifier = result + this.modifier = result; }, () => { - this.modifier = { username: elem._modifier } + this.modifier = { username: elem._modifier }; } - ) + ); } } - if (this.mmsViewApi && this.mmsViewApi.elementTranscluded) this.mmsViewApi.elementTranscluded(elem, type) + if (this.mmsViewApi && this.mmsViewApi.elementTranscluded) this.mmsViewApi.elementTranscluded(elem, type); } - } + }; //INFO this was getWsAndVersion public getElementOrigin = (): RequestObject => { @@ -221,20 +221,20 @@ export class ViewController implements angular.IComponentController { projectId: this.mmsProjectId, refId: this.mmsRefId, commitId: this.mmsCommitId, - } - } + }; + }; public getView = (): ViewObject => { // this view gets set in the viewlink fnc - return this.view - } + return this.view; + }; public hoverIn = (): void => { - this.isHover = true - } + this.isHover = true; + }; public hoverOut = (): void => { - this.isHover = false - } + this.isHover = false; + }; // public setPeLineVisibility($event) { // window.setTimeout(() => { @@ -248,37 +248,37 @@ export class ViewController implements angular.IComponentController { // }; private _changeView: onChangesCallback = (newVal, oldVal) => { - if (!newVal || (newVal === oldVal && this.processed)) return + if (!newVal || (newVal === oldVal && this.processed)) return; - this.processed = true - this.$element.addClass('isLoading') + this.processed = true; + this.$element.addClass('isLoading'); this.reqOb = { elementId: this.mmsElementId, projectId: this.mmsProjectId, refId: this.mmsRefId, commitId: this.mmsCommitId, - } + }; this.elementSvc .getElement(this.reqOb, 1) .then( (data) => { //view accepts a section element if (data.type === 'InstanceSpecification') { - this.isSection = true + this.isSection = true; } - let operand: ValueObject[] = [] + let operand: ValueObject[] = []; if (data._contents && (data as ViewObject)._contents.operand) { - operand = (data as ViewObject)._contents.operand + operand = (data as ViewObject)._contents.operand; } if (data.specification && (data as ViewInstanceSpec).specification.operand) { - operand = (data.specification as ExpressionObject).operand + operand = (data.specification as ExpressionObject).operand; } - const dups = this.presentationSvc.checkForDuplicateInstances(operand) + const dups = this.presentationSvc.checkForDuplicateInstances(operand); if (dups.length > 0) { - this.growl.warning('There are duplicates in this view, duplicates ignored!') + this.growl.warning('There are duplicates in this view, duplicates ignored!'); } if (data._veNumber) { - this.level = data._veNumber.split('.').length + this.level = data._veNumber.split('.').length; } if ( //data._numElements && data._numElements > 5000 && @@ -287,40 +287,40 @@ export class ViewController implements angular.IComponentController { ) { //threshold where getting view elements in bulk takes too long and it's not latest //getting cached individual elements should be faster - this.view = data - this.modified = data._modified + this.view = data; + this.modified = data._modified; this.userSvc.getUserData(data._modifier).then( (result) => { - this.modifier = result + this.modifier = result; }, () => { - this.modifier = { username: data._modifier } + this.modifier = { username: data._modifier }; } - ) - return + ); + return; } this.viewSvc.getViewElements(this.reqOb, 1).finally(() => { - this.view = data - this.modified = data._modified + this.view = data; + this.modified = data._modified; this.userSvc.getUserData(data._modifier).then( (result) => { - this.modifier = result + this.modifier = result; }, () => { - this.modifier = { username: data._modifier } + this.modifier = { username: data._modifier }; } - ) - this.$element.removeClass('isLoading') - }) + ); + this.$element.removeClass('isLoading'); + }); }, (reason) => { - this.growl.error(`Getting View Error: ${reason.message}: ${this.mmsElementId}`) + this.growl.error(`Getting View Error: ${reason.message}: ${this.mmsElementId}`); } ) .finally(() => { - if (this.view) this.$element.removeClass('isLoading') - }) - } + if (this.view) this.$element.removeClass('isLoading'); + }); + }; /** * @name veComponents.component:mmsView#toggleShowElements @@ -328,16 +328,16 @@ export class ViewController implements angular.IComponentController { */ public toggleShowElements = (value?: boolean): void => { if (typeof value !== 'undefined') { - this.showElements = value + this.showElements = value; } else { - this.showElements = !this.showElements + this.showElements = !this.showElements; } if (this.showElements) { - this.$element.addClass('outline') + this.$element.addClass('outline'); } else if (this.$element.hasClass('outline')) { - this.$element.removeClass('outline') + this.$element.removeClass('outline'); } - } + }; /** * @name veComponents.component:mmsView#toggleShowComments @@ -345,16 +345,16 @@ export class ViewController implements angular.IComponentController { */ public toggleShowComments = (value?: boolean): void => { if (typeof value !== 'undefined') { - this.showComments = value + this.showComments = value; } else { - this.showComments = !this.showComments + this.showComments = !this.showComments; } if (this.showComments) { - this.$element.addClass('reviewing') + this.$element.addClass('reviewing'); } else if (this.$element.hasClass('reviewing')) { - this.$element.removeClass('reviewing') + this.$element.removeClass('reviewing'); } - } + }; /** * @name veComponents.component:mmsView#toggleShowEdits @@ -362,21 +362,21 @@ export class ViewController implements angular.IComponentController { */ public toggleShowEdits = (value?: boolean): void => { if (typeof value !== 'undefined') { - this.showEdits = value + this.showEdits = value; } else { - this.showEdits = !this.showEdits + this.showEdits = !this.showEdits; } if (this.showEdits) { - this.$element.addClass('editing') + this.$element.addClass('editing'); } else if (this.$element.hasClass('editing')) { - this.$element.removeClass('editing') + this.$element.removeClass('editing'); } // Call the callback functions to clean up frames, show edits, and // re-open frames when needed: // for (let i = 0; i < this.presentationElemCleanUpFncs.length; i++) { // this.presentationElemCleanUpFncs[i](); // } - } + }; } export const ViewComponent: VeComponentOptions = { @@ -431,6 +431,6 @@ export const ViewComponent: VeComponentOptions = { buttonId: '<', }, controller: ViewController, -} +}; -veComponents.component(ViewComponent.selector, ViewComponent) +veComponents.component(ViewComponent.selector, ViewComponent); diff --git a/src/ve-components/services/Component.service.ts b/src/ve-components/services/Component.service.ts index f821cfb0d..2a28c5dc5 100644 --- a/src/ve-components/services/Component.service.ts +++ b/src/ve-components/services/Component.service.ts @@ -1,10 +1,10 @@ -import { ViewController } from '@ve-components/presentations' -import { ITransclusion } from '@ve-components/transclusions' +import { ViewController } from '@ve-components/presentations'; +import { ITransclusion } from '@ve-components/transclusions'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeQService } from '@ve-types/angular' -import { VeModalService } from '@ve-types/view-editor' +import { VeQService } from '@ve-types/angular'; +import { VeModalService } from '@ve-types/view-editor'; /** * @internal @@ -18,7 +18,7 @@ import { VeModalService } from '@ve-types/view-editor' * */ export class ComponentService { - static $inject = ['$q', '$timeout', '$compile', '$uibModal'] + static $inject = ['$q', '$timeout', '$compile', '$uibModal']; constructor( private $q: VeQService, @@ -28,40 +28,40 @@ export class ComponentService { ) {} public hasCircularReference = (ctrl: ITransclusion, curId: string, curType: string): boolean => { - let curscope = ctrl.$scope + let curscope = ctrl.$scope; while (curscope.$parent) { - const parent = curscope.$parent + const parent = curscope.$parent; if (curscope.$parent.$ctrl) { - if (parent.$ctrl.mmsElementId === curId && parent.$ctrl.cfType === curType) return true + if (parent.$ctrl.mmsElementId === curId && parent.$ctrl.cfType === curType) return true; } - curscope = parent + curscope = parent; } - return false - } + return false; + }; // var ENUM_ID = '_9_0_62a020a_1105704885400_895774_7947'; // var ENUM_LITERAL = '_9_0_62a020a_1105704885423_380971_7955'; public isDirectChildOfPresentationElementFunc(element: JQuery, mmsViewCtrl: ViewController): boolean { - let parent = element[0].parentElement + let parent = element[0].parentElement; while (parent && parent.nodeName !== 'MMS-VIEW-PRESENTATION-ELEM' && parent.nodeName !== 'MMS-VIEW') { if (mmsViewCtrl.isTranscludedElement(parent.nodeName)) { - return false + return false; } if ( parent.nodeName === 'MMS-VIEW-TABLE' || parent.nodeName === 'MMS-VIEW-LIST' || parent.nodeName === 'MMS-VIEW-SECTION' ) - return false - parent = parent.parentElement + return false; + parent = parent.parentElement; } - return parent && parent.nodeName !== 'MMS-VIEW' + return parent && parent.nodeName !== 'MMS-VIEW'; } public hasHtml = (s: string): boolean => { - return s.indexOf('

    ') !== -1 - } + return s.indexOf('

    ') !== -1; + }; } -veComponents.service('ComponentService', ComponentService) +veComponents.service('ComponentService', ComponentService); diff --git a/src/ve-components/services/Extension.service.ts b/src/ve-components/services/Extension.service.ts index b276a2cdc..02601eb23 100644 --- a/src/ve-components/services/Extension.service.ts +++ b/src/ve-components/services/Extension.service.ts @@ -1,29 +1,29 @@ -import angular from 'angular' -import _ from 'lodash' +import angular from 'angular'; +import _ from 'lodash'; -import { IButtonBarButton } from '@ve-core/button-bar' -import { IToolBarButton } from '@ve-core/toolbar' +import { IButtonBarButton } from '@ve-core/button-bar'; +import { IToolBarButton } from '@ve-core/toolbar'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; export interface VeExperimentDescriptor { - id: string - path?: string - config?: string - name?: string - toolButton?: IToolBarButton - toolDynamicButton?: IToolBarButton[] - barButtons?: IButtonBarButton[] + id: string; + path?: string; + config?: string; + name?: string; + toolButton?: IToolBarButton; + toolDynamicButton?: IToolBarButton[]; + barButtons?: IButtonBarButton[]; } export interface VeExperimentConfig { - [extensionType: string]: VeExperimentDescriptor[] + [extensionType: string]: VeExperimentDescriptor[]; } export class ExtensionService { - extensionTags: string[] = [] - extensionData: unknown[] = [] - allowedExtensions: string[] = ['present', 'transclude', 'spec', 'insert', 'tree-of'] + extensionTags: string[] = []; + extensionData: unknown[] = []; + allowedExtensions: string[] = ['present', 'transclude', 'spec', 'insert', 'tree-of']; public AnnotationType = { transcludeName: 1, @@ -33,21 +33,21 @@ export class ExtensionService { mmsViewLink: 5, presentationElement: 6, transcludeView: 7, - } + }; - static $inject = [] + static $inject = []; constructor() { - ;( + ( angular.module('ve-components')['_invokeQueue'] as { - 1: string - 2: string[] + 1: string; + 2: string[]; }[] ).forEach((value) => { if (value[1] === 'component') { - this.extensionTags.push(_.kebabCase(value[2][0])) - this.extensionData.push(value[2]) + this.extensionTags.push(_.kebabCase(value[2][0])); + this.extensionData.push(value[2]); } - }) + }); // for (const tag of this.extensionTags) { // @@ -55,26 +55,26 @@ export class ExtensionService { } public getTagByType = (extPrefix: string, type: string): string => { - extPrefix = _.kebabCase(extPrefix) + extPrefix = _.kebabCase(extPrefix); if (!this.allowedExtensions.includes(extPrefix)) { // this.growl.error('Unknown Extension Prefix: ' + extPrefix) - return 'extension-error' + return 'extension-error'; } - if (type == 'InstanceSpecification') type = 'section' - if (type == 'ImageT') type = 'figure' - const tag = _.kebabCase(type.startsWith(extPrefix) ? type : extPrefix + _.capitalize(type)) + if (type == 'InstanceSpecification') type = 'section'; + if (type == 'ImageT') type = 'figure'; + const tag = _.kebabCase(type.startsWith(extPrefix) ? type : extPrefix + _.capitalize(type)); if (!this.extensionTags.includes(tag)) { // this.growl.error('Unknown Extension type: ' + type) - return 'extension-error' + return 'extension-error'; } - return tag - } + return tag; + }; public getExtensions(extPrefix: string, exclude?: string[]): string[] { return this.extensionTags.filter((value) => { - return value.startsWith(_.kebabCase(extPrefix)) && (exclude ? !exclude.includes(value) : true) - }) + return value.startsWith(_.kebabCase(extPrefix)) && (exclude ? !exclude.includes(value) : true); + }); } } -veComponents.service('ExtensionService', ExtensionService) +veComponents.service('ExtensionService', ExtensionService); diff --git a/src/ve-components/services/index.ts b/src/ve-components/services/index.ts index d7e4d2d87..9433c7d95 100644 --- a/src/ve-components/services/index.ts +++ b/src/ve-components/services/index.ts @@ -1,5 +1,5 @@ -import './Component.service' -import './Extension.service' +import './Component.service'; +import './Extension.service'; -export * from './Extension.service' -export * from './Component.service' +export * from './Extension.service'; +export * from './Component.service'; diff --git a/src/ve-components/spec-tools/components/spec-editor.component.ts b/src/ve-components/spec-tools/components/spec-editor.component.ts index f5df95f14..ccf72ae3b 100644 --- a/src/ve-components/spec-tools/components/spec-editor.component.ts +++ b/src/ve-components/spec-tools/components/spec-editor.component.ts @@ -1,11 +1,11 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { ComponentService } from '@ve-components/services' -import { SpecService, SpecTool, ISpecTool } from '@ve-components/spec-tools' -import { EditorService } from '@ve-core/editor' -import { ToolbarApi, ToolbarService } from '@ve-core/toolbar' -import { ApplicationService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' +import { ComponentService } from '@ve-components/services'; +import { SpecService, SpecTool, ISpecTool } from '@ve-components/spec-tools'; +import { EditorService } from '@ve-core/editor'; +import { ToolbarApi, ToolbarService } from '@ve-core/toolbar'; +import { ApplicationService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; import { URLService, ElementService, @@ -14,12 +14,12 @@ import { ProjectService, ApiService, ValueService, -} from '@ve-utils/mms-api-client' +} from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromiseReason, VeQService } from '@ve-types/angular' -import { ElementObject, ElementsResponse } from '@ve-types/mms' +import { VeComponentOptions, VePromiseReason, VeQService } from '@ve-types/angular'; +import { ElementObject, ElementsResponse } from '@ve-types/mms'; /** * @ngdoc directive @@ -89,9 +89,9 @@ import { ElementObject, ElementsResponse } from '@ve-types/mms' */ class SpecEditorController extends SpecTool implements ISpecTool { - static $inject = [...SpecTool.$inject, 'EditService', 'ValueService', 'EditorService'] + static $inject = [...SpecTool.$inject, 'EditService', 'ValueService', 'EditorService']; - private isValue: boolean + private isValue: boolean; constructor( $q: VeQService, @@ -129,48 +129,48 @@ class SpecEditorController extends SpecTool implements ISpecTool { eventSvc, specSvc, toolbarSvc - ) - this.specType = _.kebabCase(SpecEditorComponent.selector) - this.specTitle = 'Edit Element' + ); + this.specType = _.kebabCase(SpecEditorComponent.selector); + this.specTitle = 'Edit Element'; } configToolbar = (api: ToolbarApi): void => { if (this.autosaveSvc.openEdits() > 0) { //Tell toolbar to show an open edit if there are open edits - api.setIcon('spec-editor', 'fa-edit-asterisk') - api.setPermission('spec-editor.saveall', true) + api.setIcon('spec-editor', 'fa-edit-asterisk'); + api.setPermission('spec-editor.saveall', true); } - } + }; initCallback = (): void => { - this.specSvc.setEditing(true) - const e = this.specSvc.getElement() + this.specSvc.setEditing(true); + const e = this.specSvc.getElement(); this.editorSvc.openEdit(e).then( (editOb) => { - this.specSvc.tracker.etrackerSelected = editOb.key - this.specSvc.toggleSave(this.toolbarId) + this.specSvc.tracker.etrackerSelected = editOb.key; + this.specSvc.toggleSave(this.toolbarId); this.elementSvc.isCacheOutdated(editOb.element).then( (data) => { - const server = data.server ? data.server._modified : new Date() - const cache = data.cache ? data.cache._modified : new Date() + const server = data.server ? data.server._modified : new Date(); + const cache = data.cache ? data.cache._modified : new Date(); if (data.status && server > cache) this.growl.error( 'This element has been updated on the server. Please refresh the page to get the latest version.' - ) + ); }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) - this.edit = editOb - this.specSvc.setEdits(editOb) - this.isValue = this.valueSvc.isValue(editOb.element) + ); + this.edit = editOb; + this.specSvc.setEdits(editOb); + this.isValue = this.valueSvc.isValue(editOb.element); }, (reason: VePromiseReason>) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) - } + ); + }; } const SpecEditorComponent: VeComponentOptions = { selector: 'specEditor', @@ -220,6 +220,6 @@ const SpecEditorComponent: VeComponentOptions = { mmsDisplayOldSpec: ' { - if (!this.projectId || !this.refId) return + if (!this.projectId || !this.refId) return; const reqOb: ElementsRequest = { elementId: this.element.id, projectId: this.projectId, refId: this.refId, - } + }; if (this.keepCommitSelected) { - this.keepCommitSelected = false - return + this.keepCommitSelected = false; + return; } - this.gettingHistory = true + this.gettingHistory = true; this.elementSvc .getElementHistory(reqOb, 2, true) .then( (data) => { - this.historyVer = 'latest' - this.compareCommit.history = data - this.compareCommit.commitSelected = this.compareCommit.history[0] - this.baseCommit.history = data + this.historyVer = 'latest'; + this.compareCommit.history = data; + this.compareCommit.commitSelected = this.compareCommit.history[0]; + this.baseCommit.history = data; if (data.length > 1) { - this.baseCommit.commitSelected = this.compareCommit.history[1] + this.baseCommit.commitSelected = this.compareCommit.history[1]; } else if (data.length > 0) { - this.baseCommit.commitSelected = this.compareCommit.history[0] + this.baseCommit.commitSelected = this.compareCommit.history[0]; } else { - this.baseCommit.commitSelected = '--- none ---' + this.baseCommit.commitSelected = '--- none ---'; } - void this.getRefs() + void this.getRefs(); }, (reason) => { - this.growl.error(`Unable to get Element History - ${reason.message}`) + this.growl.error(`Unable to get Element History - ${reason.message}`); } ) .finally(() => { - this.gettingHistory = false - this.disableRevert = this._isSame() - }) - } + this.gettingHistory = false; + this.disableRevert = this._isSame(); + }); + }; // Get ref list for project and details on getRefs = (): VePromise => { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.projectSvc.getRefs(this.projectId).then( (data) => { - this.refList = data + this.refList = data; this.compareCommit.ref = this.refList.filter((ref) => { - return ref.id === this.refId - })[0] - this.baseCommit.ref = this.compareCommit.ref - deferred.resolve() + return ref.id === this.refId; + })[0]; + this.baseCommit.ref = this.compareCommit.ref; + deferred.resolve(); }, (reason) => { - this.growl.error(`Unable to get Refs - ${reason.message}`) - deferred.reject() + this.growl.error(`Unable to get Refs - ${reason.message}`); + deferred.reject(); } - ) - return deferred.promise - } + ); + return deferred.promise; + }; commitClicked = (version: CommitObject): void => { - this.compareCommit.commitSelected = version - this.historyVer = this.compareCommit.commitSelected.id - this.compareCommit.isOpen = !this.compareCommit.isOpen + this.compareCommit.commitSelected = version; + this.historyVer = this.compareCommit.commitSelected.id; + this.compareCommit.isOpen = !this.compareCommit.isOpen; const data = { elementId: this.element.id, projectId: this.element._projectId, refId: this.element._refId, commitId: this.historyVer, - } - this.keepCommitSelected = true - this.eventSvc.$broadcast('element.selected', data) - } + }; + this.keepCommitSelected = true; + this.eventSvc.$broadcast('element.selected', data); + }; getElementHistoryByRef = (ref?: RefObject): void => { if (ref) { - this.disableRevert = false + this.disableRevert = false; // scope.gettingCompareHistory = true; - this.baseCommit.ref = ref + this.baseCommit.ref = ref; const reqOb = { elementId: this.element.id, projectId: this.projectId, refId: ref.id, - } + }; this.elementSvc .getElementHistory(reqOb, 2) .then( (data) => { - this.baseCommit.history = data + this.baseCommit.history = data; if (data.length > 0) { - this.baseCommit.commitSelected = this.baseCommit.history[0] + this.baseCommit.commitSelected = this.baseCommit.history[0]; } - this.disableRevert = this._isSame() + this.disableRevert = this._isSame(); }, (error) => { - this.baseCommit.history = [] - this.baseCommit.commitSelected = '' - this.disableRevert = true + this.baseCommit.history = []; + this.baseCommit.commitSelected = ''; + this.disableRevert = true; } ) .finally(() => { // scope.gettingCompareHistory = false; - this.baseCommit.refIsOpen = !this.baseCommit.refIsOpen - }) + this.baseCommit.refIsOpen = !this.baseCommit.refIsOpen; + }); } - } + }; baseCommitClicked = (version: CommitObject): void => { - this.baseCommit.commitSelected = version - this.baseCommit.isOpen = !this.baseCommit.isOpen - } + this.baseCommit.commitSelected = version; + this.baseCommit.isOpen = !this.baseCommit.isOpen; + }; //TODO // check if commit ids are the same - display to user that they are comparing same or disable the commit that matches @@ -225,27 +225,27 @@ class SpecHistoryController extends SpecTool implements ISpecTool { elementId: this.element.id, projectId: this.projectId, refId: this.refId, - } + }; const compareData: CompareData = { compareCommit: this.compareCommit, baseCommit: this.baseCommit, element: this.element, - } - this.diffMergeSvc.revertAction(reqOb, compareData, this.$element) - } else this.growl.warning('Nothing to revert!') - } + }; + this.diffMergeSvc.revertAction(reqOb, compareData, this.$element); + } else this.growl.warning('Nothing to revert!'); + }; private _isSame = (): boolean => { const compareId = typeof this.compareCommit.commitSelected === 'string' ? this.compareCommit.commitSelected - : this.compareCommit.commitSelected.id + : this.compareCommit.commitSelected.id; const baseId = typeof this.baseCommit.commitSelected === 'string' ? this.baseCommit.commitSelected - : this.baseCommit.commitSelected.id - return baseId == compareId - } + : this.baseCommit.commitSelected.id; + return baseId == compareId; + }; } const SpecHistoryComponent: VeComponentOptions = { @@ -392,6 +392,6 @@ const SpecHistoryComponent: VeComponentOptions = { `, controller: SpecHistoryController, -} +}; -veComponents.component(SpecHistoryComponent.selector, SpecHistoryComponent) +veComponents.component(SpecHistoryComponent.selector, SpecHistoryComponent); diff --git a/src/ve-components/spec-tools/components/spec-inspector.component.ts b/src/ve-components/spec-tools/components/spec-inspector.component.ts index 1714007e5..35e464867 100644 --- a/src/ve-components/spec-tools/components/spec-inspector.component.ts +++ b/src/ve-components/spec-tools/components/spec-inspector.component.ts @@ -1,10 +1,10 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { ComponentService } from '@ve-components/services' -import { SpecService, ISpecTool, SpecTool } from '@ve-components/spec-tools' -import { ToolbarService } from '@ve-core/toolbar' -import { ApplicationService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { ComponentService } from '@ve-components/services'; +import { SpecService, ISpecTool, SpecTool } from '@ve-components/spec-tools'; +import { ToolbarService } from '@ve-core/toolbar'; +import { ApplicationService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; import { ProjectService, URLService, @@ -12,11 +12,11 @@ import { PermissionsService, ElementService, ApiService, -} from '@ve-utils/mms-api-client' +} from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VeQService } from '@ve-types/angular'; /** * @ngdoc directive @@ -87,7 +87,7 @@ import { VeComponentOptions, VeQService } from '@ve-types/angular' */ class SpecInspectorController extends SpecTool implements ISpecTool { - static $inject = SpecTool.$inject + static $inject = SpecTool.$inject; constructor( $q: VeQService, @@ -122,16 +122,16 @@ class SpecInspectorController extends SpecTool implements ISpecTool { eventSvc, specSvc, toolbarSvc - ) + ); - this.specType = _.kebabCase(SpecInspectorComponent.selector) - this.specTitle = 'Preview Element' + this.specType = _.kebabCase(SpecInspectorComponent.selector); + this.specTitle = 'Preview Element'; } protected initCallback = (): void => { - this.specSvc.setEditing(false) - this.specSvc.toggleSave(this.toolbarId) - } + this.specSvc.setEditing(false); + this.specSvc.toggleSave(this.toolbarId); + }; } const SpecInspectorComponent: VeComponentOptions = { @@ -262,6 +262,6 @@ const SpecInspectorComponent: VeComponentOptions = { mmsDisplayOldSpec: ' { - this.refs = refs + this.refs = refs; }, (reason) => { - this.growl.error('Error getting refs: ' + reason.message) + this.growl.error('Error getting refs: ' + reason.message); } ) .finally(() => { - this.isLoading = false - }) + this.isLoading = false; + }); } //Callback function for document change public initCallback = (): void => { - if (this.document) this.docName = this.document.name + if (this.document) this.docName = this.document.name; if (!this.apiSvc.isDocument(this.element)) { - this.isDoc = false - return + this.isDoc = false; + return; } else { - this.isDoc = true + this.isDoc = true; } this.docEditable = this.specApi.refType != 'Tag' && - this.permissionsSvc.hasBranchEditPermission(this.specApi.projectId, this.specApi.refId) - } + this.permissionsSvc.hasBranchEditPermission(this.specApi.projectId, this.specApi.refId); + }; public docMergeAction = (srcRef: RefObject): void => { - this.srcRefOb = srcRef + this.srcRefOb = srcRef; const instance = this.$uibModal.open({ resolve: { getDocName: (): string => { - if (this.document) return this.document.name - return '(Not Found)' + if (this.document) return this.document.name; + return '(Not Found)'; }, getSrcRefOb: (): RefObject => { - return this.srcRefOb + return this.srcRefOb; }, }, component: 'mergeConfirmModal', - }) + }); instance.result.then( () => { // TODO: do anything here? }, () => { - this.growl.error('Unable to Merge') + this.growl.error('Unable to Merge'); } - ) - } + ); + }; } const SpecRefListComponent: VeComponentOptions = { @@ -239,6 +239,6 @@ const SpecRefListComponent: VeComponentOptions = { mmsRefs: '<', }, controller: SpecRefListController, -} +}; -veComponents.component(SpecRefListComponent.selector, SpecRefListComponent) +veComponents.component(SpecRefListComponent.selector, SpecRefListComponent); diff --git a/src/ve-components/spec-tools/components/spec-reorder.component.ts b/src/ve-components/spec-tools/components/spec-reorder.component.ts index 3599c82c8..3b9c32df5 100644 --- a/src/ve-components/spec-tools/components/spec-reorder.component.ts +++ b/src/ve-components/spec-tools/components/spec-reorder.component.ts @@ -1,11 +1,11 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { ComponentService } from '@ve-components/services' -import { SpecService, SpecTool, ISpecTool } from '@ve-components/spec-tools' -import { veCoreEvents } from '@ve-core/events' -import { ToolbarService } from '@ve-core/toolbar' -import { ApplicationService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { ComponentService } from '@ve-components/services'; +import { SpecService, SpecTool, ISpecTool } from '@ve-components/spec-tools'; +import { veCoreEvents } from '@ve-core/events'; +import { ToolbarService } from '@ve-core/toolbar'; +import { ApplicationService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; import { PermissionsService, URLService, @@ -13,11 +13,11 @@ import { ViewService, ProjectService, ApiService, -} from '@ve-utils/mms-api-client' +} from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VePromisesResponse, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VePromise, VePromisesResponse, VeQService } from '@ve-types/angular'; import { ElementObject, ElementsRequest, @@ -26,7 +26,7 @@ import { PresentationReference, ViewInstanceSpec, ViewObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc directive @@ -43,14 +43,14 @@ import { * @param {string=latest} mmsCommitId Commit ID, default is latest */ class SpecReorderController extends SpecTool implements ISpecTool { - private treeOptions: object + private treeOptions: object; - private elementReferenceTree: PresentationReference[] = [] - private originalElementReferenceTree: PresentationReference[] = [] - public view: ViewObject | ViewInstanceSpec - reorderable: boolean + private elementReferenceTree: PresentationReference[] = []; + private originalElementReferenceTree: PresentationReference[] = []; + public view: ViewObject | ViewInstanceSpec; + reorderable: boolean; - viewSaving: boolean + viewSaving: boolean; constructor( $q: VeQService, @@ -85,92 +85,92 @@ class SpecReorderController extends SpecTool implements ISpecTool { eventSvc, specSvc, toolbarSvc - ) - this.specType = _.kebabCase(SpecReorderComponent.selector) - this.specTitle = 'Reorder Spec' + ); + this.specType = _.kebabCase(SpecReorderComponent.selector); + this.specTitle = 'Reorder Spec'; } $onInit(): void { - super.$onInit() + super.$onInit(); this.treeOptions = { accept: (sourceNodeScope: SpecTool, destNodeScope: SpecTool, destIndex: number): boolean => { - if (sourceNodeScope.element.isOpaque) return false - if (destNodeScope.$element.hasClass('root')) return true - return !!this.viewSvc.isSection(destNodeScope.element as ViewInstanceSpec) + if (sourceNodeScope.element.isOpaque) return false; + if (destNodeScope.$element.hasClass('root')) return true; + return !!this.viewSvc.isSection(destNodeScope.element as ViewInstanceSpec); }, - } + }; this.subs.push( this.eventSvc.$on('spec-reorder.save', () => { if (this.viewSaving) { - this.growl.info('Please Wait...') - return + this.growl.info('Please Wait...'); + return; } - this.viewSaving = true + this.viewSaving = true; this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-reorder.save') + api.toggleButtonSpinner('spec-reorder.save'); }, (reason) => { - this.growl.error(ToolbarService.error(reason)) + this.growl.error(ToolbarService.error(reason)); } - ) + ); this.treeSave().then( (elements) => { - this.viewSaving = false + this.viewSaving = false; //this.refresh() //TODO reset orig - this.growl.success('Save Successful') + this.growl.success('Save Successful'); this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-reorder.save') + api.toggleButtonSpinner('spec-reorder.save'); }, (reason) => { - this.growl.error(ToolbarService.error(reason)) + this.growl.error(ToolbarService.error(reason)); } - ) - const saved = elements.filter((val) => val.id === this.view.id) + ); + const saved = elements.filter((val) => val.id === this.view.id); if (saved.length > 0) { - this.eventSvc.$broadcast('element.updated', { element: saved[0] }) + this.eventSvc.$broadcast('element.updated', { element: saved[0] }); } - this.eventSvc.$broadcast('spec-reorder.saved', this.view.id) + this.eventSvc.$broadcast('spec-reorder.saved', this.view.id); this.eventSvc.resolve(this.toolbarId, { id: 'spec-inspector', - }) + }); }, (response) => { - this.refresh() - this.viewSaving = false - const reason = response.data.failedRequests[0] - this.growl.error(reason.message) + this.refresh(); + this.viewSaving = false; + const reason = response.data.failedRequests[0]; + this.growl.error(reason.message); this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-reorder.save') + api.toggleButtonSpinner('spec-reorder.save'); }, (reason) => { - this.growl.error(ToolbarService.error(reason)) + this.growl.error(ToolbarService.error(reason)); } - ) + ); } - ) + ); }) - ) + ); this.subs.push( this.eventSvc.$on('spec-reorder.cancel', () => { - this.revert() + this.revert(); }) - ) + ); } initCallback = (): void => { if (this.apiSvc.isView(this.specSvc.getView()) || this.viewSvc.isSection(this.specSvc.getView())) { - this.view = this.specSvc.getView() - this.reorderable = true - this.refresh() + this.view = this.specSvc.getView(); + this.reorderable = true; + this.refresh(); } - } + }; treeSave(): VePromise> { - const elementObsToUpdate: ElementObject[] = [] + const elementObsToUpdate: ElementObject[] = []; const updateSectionElementOrder = (elementReference: PresentationReference): void => { const sectionEdit: ViewInstanceSpec = { id: elementReference.instanceId, @@ -179,33 +179,33 @@ class SpecReorderController extends SpecTool implements ISpecTool { _refId: elementReference.instanceSpecification._refId, type: elementReference.instanceSpecification.type, specification: _.cloneDeep(elementReference.instanceSpecification.specification), - } + }; //sectionEdit.specialization = _.cloneDeep(elementReference.instanceSpecification.specialization); - const operand: InstanceValueObject[] = (sectionEdit.specification.operand = []) + const operand: InstanceValueObject[] = (sectionEdit.specification.operand = []); if (!elementReference.instanceSpecification.specification) { - this.growl.error('Malformed Reference Tree; Aborting') + this.growl.error('Malformed Reference Tree; Aborting'); } const origOperand = ( elementReference.instanceSpecification.specification as ExpressionObject - ).operand + ).operand; elementReference.sectionElements.forEach((sectionElement, index) => { - operand.push(sectionElement.instanceVal) - if (sectionElement.sectionElements.length > 0) updateSectionElementOrder(sectionElement) - }) + operand.push(sectionElement.instanceVal); + if (sectionElement.sectionElements.length > 0) updateSectionElementOrder(sectionElement); + }); if (!_.isEqual(operand, origOperand)) { - elementObsToUpdate.push(sectionEdit) + elementObsToUpdate.push(sectionEdit); } - } + }; - const deferred = this.$q.defer() + const deferred = this.$q.defer(); if (this.elementReferenceTree.length === 0) { deferred.reject({ type: 'error', message: 'View specs were not initialized properly or is empty.', - }) - return deferred.promise + }); + return deferred.promise; } const viewEdit: ViewInstanceSpec | ViewObject = { id: this.view.id, @@ -213,33 +213,33 @@ class SpecReorderController extends SpecTool implements ISpecTool { _projectId: this.view._projectId, _refId: this.view._refId, type: this.view.type, - } + }; if (this.view._contents) { - viewEdit._contents = _.cloneDeep(this.view._contents) + viewEdit._contents = _.cloneDeep(this.view._contents); } if (this.view.specification) { - viewEdit.specification = _.cloneDeep((this.view as ViewInstanceSpec).specification) + viewEdit.specification = _.cloneDeep((this.view as ViewInstanceSpec).specification); } - const specs: ExpressionObject = viewEdit._contents || viewEdit.specification - const origSpecs: ExpressionObject = this.view._contents || this.view.specification + const specs: ExpressionObject = viewEdit._contents || viewEdit.specification; + const origSpecs: ExpressionObject = this.view._contents || this.view.specification; // Update the View edit object on Save if (specs.operand) { - specs.operand = [] + specs.operand = []; this.elementReferenceTree.forEach((elementRef) => { - specs.operand.push(elementRef.instanceVal) - }) + specs.operand.push(elementRef.instanceVal); + }); if (specs && !_.isEqual(specs.operand, origSpecs.operand)) { - elementObsToUpdate.push(viewEdit) + elementObsToUpdate.push(viewEdit); } } // Recurse this.elementReferenceTree.forEach((elementReference) => { if (elementReference.sectionElements && elementReference.sectionElements.length > 0) { - updateSectionElementOrder(elementReference) + updateSectionElementOrder(elementReference); } - }) + }); - return this.elementSvc.updateElements(elementObsToUpdate, false) + return this.elementSvc.updateElements(elementObsToUpdate, false); } revert = (): void => { @@ -250,29 +250,29 @@ class SpecReorderController extends SpecTool implements ISpecTool { key === 'presentationElement' || key === 'instanceVal' ) - return value - return undefined - }) as PresentationReference[] - } + return value; + return undefined; + }) as PresentationReference[]; + }; refresh = () => { - let contents: ExpressionObject = null + let contents: ExpressionObject = null; if (this.view._contents) { - contents = (this.view as ViewObject)._contents + contents = (this.view as ViewObject)._contents; } if (this.view.specification) { - contents = (this.view as ViewInstanceSpec).specification + contents = (this.view as ViewInstanceSpec).specification; } const reqOb: ElementsRequest = { elementId: this.specSvc.specApi.elementId, projectId: this.specSvc.specApi.projectId, refId: this.specSvc.specApi.refId, commitId: this.specSvc.specApi.commitId, - } + }; if (contents) { this.viewSvc.getElementReferenceTree(reqOb, contents).then( (elementReferenceTree) => { - this.elementReferenceTree = elementReferenceTree + this.elementReferenceTree = elementReferenceTree; this.originalElementReferenceTree = _.cloneDeepWith(elementReferenceTree, (value: unknown, key) => { if ( key === 'instanceId' || @@ -280,20 +280,20 @@ class SpecReorderController extends SpecTool implements ISpecTool { key === 'presentationElement' || key === 'instanceVal' ) - return value - return undefined - }) as PresentationReference[] + return value; + return undefined; + }) as PresentationReference[]; }, (reason) => { - this.elementReferenceTree = [] - this.originalElementReferenceTree = [] + this.elementReferenceTree = []; + this.originalElementReferenceTree = []; } - ) + ); } else { - this.elementReferenceTree = [] - this.originalElementReferenceTree = [] + this.elementReferenceTree = []; + this.originalElementReferenceTree = []; } - } + }; } const SpecReorderComponent: VeComponentOptions = { @@ -331,6 +331,6 @@ const SpecReorderComponent: VeComponentOptions = { mmsCommitId: '@', }, controller: SpecReorderController, -} +}; -veComponents.component(SpecReorderComponent.selector, SpecReorderComponent) +veComponents.component(SpecReorderComponent.selector, SpecReorderComponent); diff --git a/src/ve-components/spec-tools/index.ts b/src/ve-components/spec-tools/index.ts index d763d1d28..2f3cd216e 100644 --- a/src/ve-components/spec-tools/index.ts +++ b/src/ve-components/spec-tools/index.ts @@ -1,15 +1,15 @@ //Exports -export * from './services/Spec.service' +export * from './services/Spec.service'; -export * from './spec-tool.controller' +export * from './spec-tool.controller'; //Services -import './services/Spec.service' +import './services/Spec.service'; //Core Components -import './mms-tools.component' +import './mms-tools.component'; //Default Extensions -import './components/spec-inspector.component' -import './components/spec-editor.component' -import './components/spec-reorder.component' -import './components/spec-history.component' -import './components/spec-ref-list.component' +import './components/spec-inspector.component'; +import './components/spec-editor.component'; +import './components/spec-reorder.component'; +import './components/spec-history.component'; +import './components/spec-ref-list.component'; diff --git a/src/ve-components/spec-tools/mms-tools.component.ts b/src/ve-components/spec-tools/mms-tools.component.ts index b02438098..fd3bed5f2 100644 --- a/src/ve-components/spec-tools/mms-tools.component.ts +++ b/src/ve-components/spec-tools/mms-tools.component.ts @@ -1,21 +1,21 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { ComponentService, ExtensionService } from '@ve-components/services' -import { EditorService } from '@ve-core/editor' -import { EditDialogService } from '@ve-core/editor/services/EditDialog.service' -import { veCoreEvents } from '@ve-core/events' -import { IToolBarButton, ToolbarService } from '@ve-core/toolbar' -import { RootScopeService } from '@ve-utils/application' -import { EditObject, EditService, EventService } from '@ve-utils/core' -import { ElementService, ProjectService, PermissionsService } from '@ve-utils/mms-api-client' +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { EditorService } from '@ve-core/editor'; +import { EditDialogService } from '@ve-core/editor/services/EditDialog.service'; +import { veCoreEvents } from '@ve-core/events'; +import { IToolBarButton, ToolbarService } from '@ve-core/toolbar'; +import { RootScopeService } from '@ve-utils/application'; +import { EditObject, EditService, EventService } from '@ve-utils/core'; +import { ElementService, ProjectService, PermissionsService } from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { SpecApi, SpecService } from './services/Spec.service' +import { SpecApi, SpecService } from './services/Spec.service'; -import { VeComponentOptions, VeQService } from '@ve-types/angular' -import { ElementObject } from '@ve-types/mms' -import { VeModalService } from '@ve-types/view-editor' +import { VeComponentOptions, VeQService } from '@ve-types/angular'; +import { ElementObject } from '@ve-types/mms'; +import { VeModalService } from '@ve-types/view-editor'; /** * @ngdoc directive @@ -87,37 +87,37 @@ import { VeModalService } from '@ve-types/view-editor' class ToolsController { //Bindings - toolsCategory: string + toolsCategory: string; //Local - elementId: string - projectId: string - refId: string - commitId: string - edit: EditObject - element: ElementObject - inPreviewMode: boolean - isEditing: boolean - skipBroadcast: boolean - - subs: Rx.IDisposable[] - currentTool: string - currentTitle: string - specApi: SpecApi + elementId: string; + projectId: string; + refId: string; + commitId: string; + edit: EditObject; + element: ElementObject; + inPreviewMode: boolean; + isEditing: boolean; + skipBroadcast: boolean; + + subs: Rx.IDisposable[]; + currentTool: string; + currentTitle: string; + specApi: SpecApi; show: { - [key: string]: boolean - } = {} + [key: string]: boolean; + } = {}; - editable: boolean - viewId: string - elementSaving: boolean - elementLoading: boolean + editable: boolean; + viewId: string; + elementSaving: boolean; + elementLoading: boolean; - protected errorType: string + protected errorType: string; - toolbarId: string + toolbarId: string; - protected $tools: JQuery + protected $tools: JQuery; static $inject = [ '$q', '$timeout', @@ -139,7 +139,7 @@ class ToolsController { 'ToolbarService', 'SpecService', 'ExtensionService', - ] + ]; constructor( private $q: VeQService, @@ -165,197 +165,197 @@ class ToolsController { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); - this.$tools = $('#tools') + this.$tools = $('#tools'); - this.specApi = this.specSvc.specApi - this.elementSaving = false + this.specApi = this.specSvc.specApi; + this.elementSaving = false; //Listen for Toolbar Clicked Subject - this.subs.push(this.eventSvc.binding(this.toolbarId, this.changeTool)) + this.subs.push(this.eventSvc.binding(this.toolbarId, this.changeTool)); this.subs.push( this.eventSvc.$on('editor.open', (editOb: ElementObject) => { - this.openEdit() + this.openEdit(); }) - ) + ); this.subs.push( this.eventSvc.$on('editor.close', (editOb: ElementObject) => { - this.closeEdit() + this.closeEdit(); }) - ) + ); this.subs.push( this.eventSvc.$on('spec-editor.save', () => { - this.save(false) + this.save(false); }) - ) + ); this.subs.push( this.eventSvc.$on('spec-editor.save-continue', () => { - this.save(true) + this.save(true); }) - ) + ); this.subs.push( this.eventSvc.$on('element-saving', (data: boolean) => { - this.elementSaving = data + this.elementSaving = data; }) - ) + ); this.subs.push( this.eventSvc.binding('spec.ready', (data) => { - this.elementLoading = !data + this.elementLoading = !data; }) - ) + ); this.hotkeys.bindTo(this.$scope).add({ combo: 'alt+a', description: 'save all', callback: () => { - this.eventSvc.$broadcast('spec-editor.saveall') + this.eventSvc.$broadcast('spec-editor.saveall'); }, - }) - const savingAll = false + }); + const savingAll = false; this.subs.push( this.eventSvc.$on('spec-editor.saveall', () => { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-editor.saveall') + api.toggleButtonSpinner('spec-editor.saveall'); this.editorSvc .saveAll() .catch(() => { // reset the last edit elementOb to one of the existing element - const firstEdit = Object.values(this.autosaveSvc.getAll())[0] - this.specSvc.tracker.etrackerSelected = firstEdit.key - this.specSvc.keepMode() - this.specApi.elementId = firstEdit.element.id - this.specApi.projectId = firstEdit.element._projectId - this.specApi.refId = firstEdit.element._refId - this.specApi.commitId = 'latest' - this.growl.error('Some elements failed to save, resolve individually in edit pane') + const firstEdit = Object.values(this.autosaveSvc.getAll())[0]; + this.specSvc.tracker.etrackerSelected = firstEdit.key; + this.specSvc.keepMode(); + this.specApi.elementId = firstEdit.element.id; + this.specApi.projectId = firstEdit.element._projectId; + this.specApi.refId = firstEdit.element._refId; + this.specApi.commitId = 'latest'; + this.growl.error('Some elements failed to save, resolve individually in edit pane'); }) .finally(() => { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - api.toggleButtonSpinner('spec-editor.saveall') - this.specSvc.toggleSave(this.toolbarId) + api.toggleButtonSpinner('spec-editor.saveall'); + this.specSvc.toggleSave(this.toolbarId); }, (reason) => { - this.growl.error(ToolbarService.error(reason)) + this.growl.error(ToolbarService.error(reason)); } - ) - }) + ); + }); - this.specSvc.setEditing(false) + this.specSvc.setEditing(false); }, (reason) => { - this.growl.error(ToolbarService.error(reason)) + this.growl.error(ToolbarService.error(reason)); } - ) + ); }) - ) + ); this.subs.push( this.eventSvc.$on('spec-editor.cancel', () => { const go = (): void => { - this.editorSvc.cleanUpEdit(this.specSvc.getEdits().key) + this.editorSvc.cleanUpEdit(this.specSvc.getEdits().key); if (this.autosaveSvc.openEdits() > 0) { - const id = Object.keys(this.autosaveSvc.getAll())[0] - const info = id.split('|') + const id = Object.keys(this.autosaveSvc.getAll())[0]; + const info = id.split('|'); const data: veCoreEvents.elementSelectedData = { elementId: info[2], projectId: info[0], refId: info[1], commitId: 'latest', - } - this.eventSvc.$broadcast('element.selected', data) + }; + this.eventSvc.$broadcast('element.selected', data); } else { - this.specSvc.setEditing(false) + this.specSvc.setEditing(false); this.eventSvc.resolve(this.toolbarId, { id: 'spec-inspector', - }) + }); this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.setIcon('spec-editor', 'fa-edit'), (reason) => { - this.growl.error(ToolbarService.error(reason)) + this.growl.error(ToolbarService.error(reason)); } - ) - this.specSvc.toggleSave(this.toolbarId) + ); + this.specSvc.toggleSave(this.toolbarId); } - } + }; this.editorSvc.hasEdits(this.specSvc.getEdits()).then( (hasEdits) => { if (hasEdits) { this.editorSvc.deleteEditModal(this.specSvc.getEdits()).result.then( () => { - go() + go(); }, () => { /* Do Nothing */ } - ) - } else go() + ); + } else go(); }, () => { - go() + go(); } - ) + ); }) - ) + ); } private changeTool = (data: veCoreEvents.toolbarClicked): void => { if (!this.currentTool) { - this.currentTool = '' + this.currentTool = ''; } if (this.currentTool !== data.id) { - if (this.currentTool !== '') this.show[_.camelCase(this.currentTool)] = false + if (this.currentTool !== '') this.show[_.camelCase(this.currentTool)] = false; - this.currentTool = data.id + this.currentTool = data.id; - const inspect: IToolBarButton = this.toolbarSvc.getToolbarButton(data.id) + const inspect: IToolBarButton = this.toolbarSvc.getToolbarButton(data.id); if (!data.title) { - data.title = inspect.tooltip + data.title = inspect.tooltip; } if (!data.category) { - data.category = inspect.category + data.category = inspect.category; } - this.currentTitle = data.title ? data.title : inspect.tooltip + this.currentTitle = data.title ? data.title : inspect.tooltip; if (!this.show.hasOwnProperty(_.camelCase(data.id))) { - this.startTool(data.id) - this.show[_.camelCase(data.id)] = true + this.startTool(data.id); + this.show[_.camelCase(data.id)] = true; } else { - this.show[_.camelCase(data.id)] = true + this.show[_.camelCase(data.id)] = true; } } - } + }; private startTool = (id: string): void => { - const tag = this.extensionSvc.getTagByType('spec', id) - const toolId: string = _.camelCase(id) + const tag = this.extensionSvc.getTagByType('spec', id); + const toolId: string = _.camelCase(id); const newTool: JQuery = $( '

    ' - ) + ); if (tag === 'extensionError') { - this.errorType = this.currentTool.replace('spec-', '') + this.errorType = this.currentTool.replace('spec-', ''); newTool.append( '' - ) + ); } else { - newTool.append('<' + tag + ' toolbar-id="{{$ctrl.toolbarId}}">') + newTool.append('<' + tag + ' toolbar-id="{{$ctrl.toolbarId}}">'); } - this.$tools.append(newTool) + this.$tools.append(newTool); - this.$compile(newTool)(this.$scope) - } + this.$compile(newTool)(this.$scope); + }; // private changeElement= (newVal, oldVal) => { // if (newVal === oldVal) { @@ -368,66 +368,66 @@ class ToolsController { // } public closeEdit = (): void => { - this.specSvc.toggleSave(this.toolbarId) - } + this.specSvc.toggleSave(this.toolbarId); + }; public openEdit = (): void => { - this.specSvc.toggleSave(this.toolbarId) - } + this.specSvc.toggleSave(this.toolbarId); + }; public save = (continueEdit: boolean): void => { if (this.elementSaving) { - this.growl.info('Please Wait...') - return + this.growl.info('Please Wait...'); + return; } this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { if (!continueEdit) { - api.toggleButtonSpinner('spec-editor.save') + api.toggleButtonSpinner('spec-editor.save'); } else { - api.toggleButtonSpinner('spec-editor.save-continue') + api.toggleButtonSpinner('spec-editor.save-continue'); } this.editorSvc .save(this.specSvc.getEdits().key, continueEdit) .then( () => { if (this.autosaveSvc.openEdits() > 0) { - const next = Object.keys(this.autosaveSvc.getAll())[0] - const info = next.split('|') + const next = Object.keys(this.autosaveSvc.getAll())[0]; + const info = next.split('|'); const data: veCoreEvents.elementSelectedData = { elementId: info[2], projectId: info[0], refId: info[1], commitId: 'latest', - } - this.eventSvc.$broadcast('element.selected', data) + }; + this.eventSvc.$broadcast('element.selected', data); } else { - this.specSvc.setEditing(false) - this.specSvc.toggleSave(this.toolbarId) + this.specSvc.setEditing(false); + this.specSvc.toggleSave(this.toolbarId); this.eventSvc.resolve(this.toolbarId, { id: 'spec-inspector', - }) + }); } }, (reason) => { - if (reason.type === 'info') this.growl.info(reason.message) - else if (reason.type === 'warning') this.growl.warning(reason.message) - else if (reason.type === 'error') this.growl.error(reason.message) + if (reason.type === 'info') this.growl.info(reason.message); + else if (reason.type === 'warning') this.growl.warning(reason.message); + else if (reason.type === 'error') this.growl.error(reason.message); } ) .finally(() => { if (!continueEdit) { - api.toggleButtonSpinner('spec-editor.save') + api.toggleButtonSpinner('spec-editor.save'); } else { - api.toggleButtonSpinner('spec-editor.save-continue') + api.toggleButtonSpinner('spec-editor.save-continue'); } - }) + }); }, (reason) => { - this.growl.error(ToolbarService.error(reason)) + this.growl.error(ToolbarService.error(reason)); } - ) - } + ); + }; } const MmsToolsComponent: VeComponentOptions = { @@ -447,6 +447,6 @@ const MmsToolsComponent: VeComponentOptions = { toolsCategory: '<', }, controller: ToolsController, -} +}; -veComponents.component(MmsToolsComponent.selector, MmsToolsComponent) +veComponents.component(MmsToolsComponent.selector, MmsToolsComponent); diff --git a/src/ve-components/spec-tools/services/Spec.service.ts b/src/ve-components/spec-tools/services/Spec.service.ts index f7a2ad848..1fe499aff 100644 --- a/src/ve-components/spec-tools/services/Spec.service.ts +++ b/src/ve-components/spec-tools/services/Spec.service.ts @@ -1,8 +1,8 @@ -import { ComponentService } from '@ve-components/services' -import { EditorService } from '@ve-core/editor' -import { ToolbarService } from '@ve-core/toolbar' -import { UtilsService } from '@ve-utils/application' -import { EditObject, EditService, EventService } from '@ve-utils/core' +import { ComponentService } from '@ve-components/services'; +import { EditorService } from '@ve-core/editor'; +import { ToolbarService } from '@ve-core/toolbar'; +import { UtilsService } from '@ve-utils/application'; +import { EditObject, EditService, EventService } from '@ve-utils/core'; import { ApiService, AuthService, @@ -13,11 +13,11 @@ import { UserService, ViewService, ValueService, -} from '@ve-utils/mms-api-client' +} from '@ve-utils/mms-api-client'; -import { PropertySpec, veComponents } from '@ve-components' +import { PropertySpec, veComponents } from '@ve-components'; -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; import { DocumentObject, ElementObject, @@ -27,37 +27,37 @@ import { ValueObject, ViewInstanceSpec, ViewObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; export interface SpecApi extends ElementsRequest { - rootId?: string - refType: string - displayOldSpec?: boolean | null - relatedDocuments?: ViewObject[] - propSpec?: PropertySpec - typeClass?: string - dataLink?: string - qualifiedName?: string + rootId?: string; + refType: string; + displayOldSpec?: boolean | null; + relatedDocuments?: ViewObject[]; + propSpec?: PropertySpec; + typeClass?: string; + dataLink?: string; + qualifiedName?: string; } export class SpecService implements angular.Injectable { - private element: ElementObject - private view: ViewObject | ViewInstanceSpec - private document: DocumentObject - private modifier: UserObject - private ref: RefObject - private values: ValueObject[] - private edit: EditObject - private editing: boolean = false - public editable: boolean - private keeping: boolean = false + private element: ElementObject; + private view: ViewObject | ViewInstanceSpec; + private document: DocumentObject; + private modifier: UserObject; + private ref: RefObject; + private values: ValueObject[]; + private edit: EditObject; + private editing: boolean = false; + public editable: boolean; + private keeping: boolean = false; - public specApi: SpecApi = { refType: '', refId: '', elementId: '', projectId: '' } + public specApi: SpecApi = { refType: '', refId: '', elementId: '', projectId: '' }; public tracker: { - etrackerSelected?: string - } = {} + etrackerSelected?: string; + } = {}; - public editValues: ValueObject[] = [] + public editValues: ValueObject[] = []; static $inject = [ '$q', @@ -78,10 +78,10 @@ export class SpecService implements angular.Injectable { 'ApiService', 'ValueService', 'EditorService', - ] - private ran: boolean - private lastid: string - private gettingSpec: boolean + ]; + private ran: boolean; + private lastid: string; + private gettingSpec: boolean; constructor( private $q: VeQService, private $timeout: angular.ITimeoutService, @@ -111,13 +111,13 @@ export class SpecService implements angular.Injectable { */ public toggleEditing = (): boolean => { if (!this.editing) { - if (this.editable) this.editing = true - else return false + if (this.editable) this.editing = true; + else return false; } else { - this.editing = false + this.editing = false; } - return true - } + return true; + }; /** * @name veComponents.component:mmsSpec#setEditing * sets editor state @@ -127,11 +127,11 @@ export class SpecService implements angular.Injectable { */ public setEditing = (mode): boolean => { if (mode) { - if (this.editable) this.editing = true - else return false - } else this.editing = false - return true - } + if (this.editable) this.editing = true; + else return false; + } else this.editing = false; + return true; + }; /** * @name veComponents.component:mmsSpec#getEditing * get editor state @@ -139,8 +139,8 @@ export class SpecService implements angular.Injectable { * @return {boolean} editor or not */ public getEditing = (): boolean => { - return this.editing - } + return this.editing; + }; /** * @name veComponents.component:mmsSpec#getEdits * get current edit object @@ -149,98 +149,98 @@ export class SpecService implements angular.Injectable { * current element object that can be edited (may include changes) */ public getEdits = (): EditObject => { - return this.edit - } + return this.edit; + }; public setEdits = (editOb: EditObject): void => { if (this.valueSvc.isValue(editOb.element)) { - editOb.values = this.valueSvc.getValues(editOb.element) + editOb.values = this.valueSvc.getValues(editOb.element); } - this.edit = editOb - } + this.edit = editOb; + }; public getElement = (): ElementObject => { - return this.element - } + return this.element; + }; public getDocument = (): DocumentObject => { - return this.document - } + return this.document; + }; public getView = (): ElementObject => { - return this.view - } + return this.view; + }; public getModifier = (): UserObject => { - return this.modifier - } + return this.modifier; + }; public getValues(): ValueObject[] { - return this.values + return this.values; } public getRef = (): RefObject => { - return this.ref - } + return this.ref; + }; public getTypeClass = (element: ElementObject): void => { // Get Type - this.specApi.typeClass = this.utilsSvc.getElementTypeClass(element, this.viewSvc.getElementType(element)) - } + this.specApi.typeClass = this.utilsSvc.getElementTypeClass(element, this.viewSvc.getElementType(element)); + }; public getQualifiedName(element: ElementObject): VePromise { - const deferred = this.$q.defer() - if (this.edit) element = this.edit.element + const deferred = this.$q.defer(); + if (this.edit) element = this.edit.element; const reqOb: ElementsRequest = { commitId: element._commitId ? element._commitId : 'latest', projectId: element._projectId, refId: element._refId, elementId: element.id, - } + }; this.elementSvc.getElementQualifiedName(reqOb).then( (result) => { - this.specApi.qualifiedName = result - deferred.resolve(true) + this.specApi.qualifiedName = result; + deferred.resolve(true); }, (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) - return deferred.promise + ); + return deferred.promise; } public setElement = (): void => { - this.specApi.relatedDocuments = null - this.specApi.propSpec = {} + this.specApi.relatedDocuments = null; + this.specApi.propSpec = {}; - this.ran = true - this.lastid = this.specApi.elementId + this.ran = true; + this.lastid = this.specApi.elementId; - this.specApi.extended = !(this.specApi.commitId && this.specApi.commitId !== 'latest') + this.specApi.extended = !(this.specApi.commitId && this.specApi.commitId !== 'latest'); - this._updateElement() - } + this._updateElement(); + }; private _updateElement = (): void => { - const reqOb = Object.assign({}, this.specApi) + const reqOb = Object.assign({}, this.specApi); this.elementSvc .getElement(reqOb, 2, false) .then( (data) => { - const promises: angular.IPromise[] = [] + const promises: angular.IPromise[] = []; if (data.id !== this.lastid) { - return + return; } - this.element = data + this.element = data; if (this.apiSvc.isView(data) || this.viewSvc.isSection(data)) { - this.view = data + this.view = data; } - this.values = this.valueSvc.getValues(data) + this.values = this.valueSvc.getValues(data); promises.push( this.userSvc.getUserData(data._modifier).then((result) => { - this.modifier = result + this.modifier = result; }) - ) + ); /* no more related docs search supported if (!this.specApi.commitId || this.specApi.commitId === 'latest') { promises.push( @@ -276,32 +276,32 @@ export class SpecService implements angular.Injectable { projectId: this.specApi.projectId, refId: this.specApi.refId, commitId: this.specApi.commitId ? this.specApi.commitId : 'latest', - } + }; promises.push( this.viewSvc.getProjectDocument(docReq, 1).then((result) => { - this.document = result + this.document = result; }) - ) + ); } if ( (this.specApi.commitId && this.specApi.commitId !== 'latest') || !this.permissionsSvc.hasBranchEditPermission(data._projectId, data._refId) || this.specApi.refType === 'Tag' ) { - this.editable = false - this.edit = null - this.setEditing(false) + this.editable = false; + this.edit = null; + this.setEditing(false); } else { - this.editable = true + this.editable = true; // only get edit object if in spec edit } promises.push( this.projectSvc.getRef(this.specApi.refId, this.specApi.projectId).then((result) => { - this.ref = result + this.ref = result; }) - ) - this.getTypeClass(this.element) - promises.push(this.getQualifiedName(this.element)) + ); + this.getTypeClass(this.element); + promises.push(this.getQualifiedName(this.element)); this.specApi.dataLink = this.uRLSvc.getRoot() + '/projects/' + @@ -313,56 +313,56 @@ export class SpecService implements angular.Injectable { '?commitId=' + this.element._commitId + '&token=' + - this.authSvc.getToken() + this.authSvc.getToken(); this.$q.allSettled(promises).then( () => this.eventSvc.resolve('spec.ready', true), (reason: VePromiseReason) => { - this.growl.error('Getting Element Error: ' + reason.message) + this.growl.error('Getting Element Error: ' + reason.message); } - ) + ); }, (reason) => { - this.growl.error('Getting Element Error: ' + reason.message) + this.growl.error('Getting Element Error: ' + reason.message); } ) .finally(() => { - this.gettingSpec = false - }) - } + this.gettingSpec = false; + }); + }; public setKeepMode = (value?: boolean): void => { if (value === undefined) { - this.keepMode() + this.keepMode(); } - this.keeping = value - } + this.keeping = value; + }; public getKeepMode = (): boolean => { - return this.keeping - } + return this.keeping; + }; public keepMode = (): void => { - this.keeping = true - } + this.keeping = true; + }; // Check edit count and toggle appropriate save all and edit/edit-asterisk buttons public toggleSave = (toolbarId: string): void => { this.toolbarSvc.waitForApi(toolbarId).then( (api) => { if (this.autosaveSvc.openEdits() > 0) { - api.setPermission('spec-editor.saveall', true) - api.setIcon('spec-editor', 'fa-edit-asterisk') + api.setPermission('spec-editor.saveall', true); + api.setIcon('spec-editor', 'fa-edit-asterisk'); } else { - api.setPermission('spec-editor.saveall', false) - api.setIcon('spec-editor', 'fa-edit') + api.setPermission('spec-editor.saveall', false); + api.setIcon('spec-editor', 'fa-edit'); } }, (reason) => { - this.growl.error(ToolbarService.error(reason)) + this.growl.error(ToolbarService.error(reason)); } - ) - } + ); + }; // // Check edit count and toggle appropriate save all and edit/edit-asterisk buttons @@ -384,4 +384,4 @@ export class SpecService implements angular.Injectable { // } } -veComponents.service('SpecService', SpecService) +veComponents.service('SpecService', SpecService); diff --git a/src/ve-components/spec-tools/spec-tool.controller.ts b/src/ve-components/spec-tools/spec-tool.controller.ts index 2bd9720a6..d27768d66 100644 --- a/src/ve-components/spec-tools/spec-tool.controller.ts +++ b/src/ve-components/spec-tools/spec-tool.controller.ts @@ -1,10 +1,10 @@ -import { IPaneScope } from '@openmbee/pane-layout' +import { IPaneScope } from '@openmbee/pane-layout'; -import { ComponentService } from '@ve-components/services' -import { veCoreEvents } from '@ve-core/events' -import { ToolbarService, ToolbarApi } from '@ve-core/toolbar' -import { ApplicationService } from '@ve-utils/application' -import { EditObject, EventService } from '@ve-utils/core' +import { ComponentService } from '@ve-components/services'; +import { veCoreEvents } from '@ve-core/events'; +import { ToolbarService, ToolbarApi } from '@ve-core/toolbar'; +import { ApplicationService } from '@ve-utils/application'; +import { EditObject, EventService } from '@ve-utils/core'; import { ApiService, ElementService, @@ -12,32 +12,32 @@ import { ProjectService, URLService, ViewService, -} from '@ve-utils/mms-api-client' +} from '@ve-utils/mms-api-client'; -import { SpecApi, SpecService } from './services/Spec.service' +import { SpecApi, SpecService } from './services/Spec.service'; -import { VeQService } from '@ve-types/angular' -import { ElementObject, RefObject, ValueObject, ViewObject } from '@ve-types/mms' +import { VeQService } from '@ve-types/angular'; +import { ElementObject, RefObject, ValueObject, ViewObject } from '@ve-types/mms'; export interface ISpecTool extends angular.IComponentController { - $scope: ISpecToolScope - commitId: string - specType: string - edit: EditObject - element: ElementObject - isEditing: boolean - inPreviewMode: boolean - skipBroadcast: boolean - editValues?: ValueObject[] - values?: ValueObject[] + $scope: ISpecToolScope; + commitId: string; + specType: string; + edit: EditObject; + element: ElementObject; + isEditing: boolean; + inPreviewMode: boolean; + skipBroadcast: boolean; + editValues?: ValueObject[]; + values?: ValueObject[]; //Functions - addValue?(type: string): void - removeVal?(i: number): void + addValue?(type: string): void; + removeVal?(i: number): void; } export interface ISpecToolScope extends IPaneScope { - $ctrl?: ISpecTool - $parent: ISpecToolScope + $ctrl?: ISpecTool; + $parent: ISpecToolScope; } /** @@ -76,40 +76,40 @@ export interface ISpecToolScope extends IPaneScope { */ export class SpecTool implements ISpecTool { //Bindings - protected toolbarId: string + protected toolbarId: string; - public specApi: SpecApi + public specApi: SpecApi; //Customizers - public specType: string - public specTitle: string + public specType: string; + public specTitle: string; - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; - public commitId: string - protected projectId: string - protected refId: string + public commitId: string; + protected projectId: string; + protected refId: string; - public isEditing: boolean - public isEnumeration: boolean - public inPreviewMode: boolean - public elementSaving: boolean - public skipBroadcast: boolean + public isEditing: boolean; + public isEnumeration: boolean; + public inPreviewMode: boolean; + public elementSaving: boolean; + public skipBroadcast: boolean; - protected gettingSpec = true - public element: ElementObject - public document: ViewObject - public ref: RefObject - public values: any[] - public edit: EditObject - protected modifier - protected options: any - protected elementDataLink: string - protected qualifiedName: string + protected gettingSpec = true; + public element: ElementObject; + public document: ViewObject; + public ref: RefObject; + public values: any[]; + public edit: EditObject; + protected modifier; + protected options: any; + protected elementDataLink: string; + protected qualifiedName: string; - public editValues: any[] + public editValues: any[]; - protected template: string | angular.Injectable<(...args: any[]) => string> + protected template: string | angular.Injectable<(...args: any[]) => string>; static $inject = [ '$q', @@ -127,7 +127,7 @@ export class SpecTool implements ISpecTool { 'EventService', 'SpecService', 'ToolbarService', - ] + ]; constructor( protected $q: VeQService, @@ -148,9 +148,9 @@ export class SpecTool implements ISpecTool { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); - this.editValues = this.specSvc.editValues + this.editValues = this.specSvc.editValues; this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { if ( @@ -158,24 +158,24 @@ export class SpecTool implements ISpecTool { window.__env && window.__env.enableDebug ) { - console.log('Spec View: ' + this.specType + 'is missing a button definition') + console.log('Spec View: ' + this.specType + 'is missing a button definition'); } - this.configToolbar(api) + this.configToolbar(api); }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); - this.changeElement() + this.changeElement(); - this.subs.push(this.eventSvc.binding('spec.ready', this.changeElement)) + this.subs.push(this.eventSvc.binding('spec.ready', this.changeElement)); //this.subs.push(this.eventSvc.$on(this.specType, this.initCallback)) } $onDestroy(): void { - this.eventSvc.destroy(this.subs) - this.destroy() + this.eventSvc.destroy(this.subs); + this.destroy(); } /** @@ -187,7 +187,7 @@ export class SpecTool implements ISpecTool { */ protected configToolbar = (api: ToolbarApi): void => { /* Implement any toolbar initialization Logic Here */ - } + }; /** * @name veComponents/SpecTool#initCallback @@ -198,7 +198,7 @@ export class SpecTool implements ISpecTool { */ protected initCallback: () => void = () => { /* Implement any post initialization steps here */ - } + }; /** * @name veComponents/SpecTool#destroy @@ -209,41 +209,41 @@ export class SpecTool implements ISpecTool { */ protected destroy: () => void = () => { /* Implement any custom on destroy logic to unregister listeners etc */ - } + }; public changeElement = (ready?: boolean): void => { - if (!ready) return - this.gettingSpec = true - this.specApi = this.specSvc.specApi - this.refId = this.specApi.refId - this.projectId = this.specApi.projectId - this.commitId = this.specApi.commitId - this.modifier = this.specSvc.getModifier() - this.qualifiedName = this.specApi.qualifiedName - this.element = this.specSvc.getElement() - this.document = this.specSvc.getDocument() - this.values = this.specSvc.getValues() - this.ref = this.specSvc.getRef() - this.elementDataLink = this.specApi.dataLink - this.initCallback() - this.gettingSpec = false - } + if (!ready) return; + this.gettingSpec = true; + this.specApi = this.specSvc.specApi; + this.refId = this.specApi.refId; + this.projectId = this.specApi.projectId; + this.commitId = this.specApi.commitId; + this.modifier = this.specSvc.getModifier(); + this.qualifiedName = this.specApi.qualifiedName; + this.element = this.specSvc.getElement(); + this.document = this.specSvc.getDocument(); + this.values = this.specSvc.getValues(); + this.ref = this.specSvc.getRef(); + this.elementDataLink = this.specApi.dataLink; + this.initCallback(); + this.gettingSpec = false; + }; //Spec Tool Common API public copyToClipboard($event: JQuery.ClickEvent, selector: string): void { this.applicationSvc.copyToClipboard(this.$element.find(selector), $event).then( () => { - this.growl.info('Copied to clipboard!', { ttl: 2000 }) + this.growl.info('Copied to clipboard!', { ttl: 2000 }); }, (err) => { - this.growl.error('Unable to copy: ' + err.message) + this.growl.error('Unable to copy: ' + err.message); } - ) + ); } public cleanupVal(obj: { value: unknown }): void { - obj.value = parseInt(obj.value as string) + obj.value = parseInt(obj.value as string); } public propertyTypeClicked = (id: string): void => { @@ -252,12 +252,12 @@ export class SpecTool implements ISpecTool { projectId: this.element._projectId, refId: this.element._refId, commitId: 'latest', - } - this.eventSvc.$broadcast('element.selected', data) - } + }; + this.eventSvc.$broadcast('element.selected', data); + }; public addHtml(value: { value: string }): void { - value.value = '

    ' + value.value + '

    ' + value.value = '

    ' + value.value + '

    '; } /** @@ -275,6 +275,6 @@ export class SpecTool implements ISpecTool { // } public hasHtml = (s: string): boolean => { - return this.componentSvc.hasHtml(s) - } + return this.componentSvc.hasHtml(s); + }; } diff --git a/src/ve-components/transclusions/components/index.ts b/src/ve-components/transclusions/components/index.ts index 182bc59e5..1d7d11a1a 100644 --- a/src/ve-components/transclusions/components/index.ts +++ b/src/ve-components/transclusions/components/index.ts @@ -1,12 +1,12 @@ -import './transclude-art.component' -import './transclude-attr.component' -import './transclude-com.component' -import './transclude-doc.component' -import './transclude-enum.component' -import './transclude-group-docs.component' -import './transclude-img.component' -import './transclude-name.component' -import './transclude-val.component' -import './transclude-value-link.component' -import './transclude-view.component' -import './transclude-section.component' +import './transclude-art.component'; +import './transclude-attr.component'; +import './transclude-com.component'; +import './transclude-doc.component'; +import './transclude-enum.component'; +import './transclude-group-docs.component'; +import './transclude-img.component'; +import './transclude-name.component'; +import './transclude-val.component'; +import './transclude-value-link.component'; +import './transclude-view.component'; +import './transclude-section.component'; diff --git a/src/ve-components/transclusions/components/transclude-art.component.ts b/src/ve-components/transclusions/components/transclude-art.component.ts index a3da55ae2..c8f826ffb 100644 --- a/src/ve-components/transclusions/components/transclude-art.component.ts +++ b/src/ve-components/transclusions/components/transclude-art.component.ts @@ -1,15 +1,15 @@ -import { ExtensionService, ComponentService } from '@ve-components/services' -import { Transclusion, ITransclusion, ITransclusionComponentOptions } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { UtilsService, MathService, ImageService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, URLService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { Transclusion, ITransclusion, ITransclusionComponentOptions } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { UtilsService, MathService, ImageService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, URLService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' +import { VePromise, VeQService } from '@ve-types/angular'; /** * @ngdoc component @@ -47,13 +47,13 @@ import { VePromise, VeQService } from '@ve-types/angular' */ export class TranscludeArtController extends Transclusion implements ITransclusion { //Custom Bindings - mmsArtExt: string + mmsArtExt: string; //Locals - artExt: string - artifacts: any[] + artExt: string; + artifacts: any[]; - static $inject: string[] = [...Transclusion.$inject, 'URLService'] + static $inject: string[] = [...Transclusion.$inject, 'URLService']; constructor( $q: VeQService, @@ -91,32 +91,32 @@ export class TranscludeArtController extends Transclusion implements ITransclusi extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'doc' - this.cfTitle = 'Documentation' - this.cfKind = 'Text' - this.checkCircular = true + ); + this.cfType = 'doc'; + this.cfTitle = 'Documentation'; + this.cfKind = 'Text'; + this.checkCircular = true; } $onInit(): void { - super.$onInit() + super.$onInit(); - this.artExt = this.mmsArtExt + this.artExt = this.mmsArtExt; this.$element.on('click', (e) => { - if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element) + if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element); - e.stopPropagation() - }) + e.stopPropagation(); + }); } public getContent = (preview?: boolean): VePromise => { - const artifacts = this.element._artifacts + const artifacts = this.element._artifacts; if (artifacts !== undefined) { - const allExt = artifacts.map((a) => a.extension) - let includeExt = allExt + const allExt = artifacts.map((a) => a.extension); + let includeExt = allExt; if (this.artExt !== '' || this.artExt !== undefined) { - includeExt = this.artExt.split(',').filter((a) => allExt.includes(a)) + includeExt = this.artExt.split(',').filter((a) => allExt.includes(a)); } const reqOb = { elementId: this.mmsElementId, @@ -124,7 +124,7 @@ export class TranscludeArtController extends Transclusion implements ITransclusi refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - } + }; this.artifacts = artifacts .filter((a) => includeExt.includes(a.extension)) .map((a) => { @@ -132,13 +132,13 @@ export class TranscludeArtController extends Transclusion implements ITransclusi url: this.urlSvc.getArtifactURL(reqOb, a.extension), image: a.mimetype.indexOf('image') > -1, ext: a.extension, - } - }) + }; + }); } const result = - '' - return this.$q.resolve(result) - } + ''; + return this.$q.resolve(result); + }; } export const TranscludeArtComponent: ITransclusionComponentOptions = { @@ -161,6 +161,6 @@ export const TranscludeArtComponent: ITransclusionComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeArtController, -} +}; -veComponents.component(TranscludeArtComponent.selector, TranscludeArtComponent) +veComponents.component(TranscludeArtComponent.selector, TranscludeArtComponent); diff --git a/src/ve-components/transclusions/components/transclude-attr.component.ts b/src/ve-components/transclusions/components/transclude-attr.component.ts index 3c855d44e..930eba2f1 100644 --- a/src/ve-components/transclusions/components/transclude-attr.component.ts +++ b/src/ve-components/transclusions/components/transclude-attr.component.ts @@ -4,31 +4,31 @@ //

    Target

    // //
    -import { ExtensionService, ComponentService } from '@ve-components/services' -import { ITransclusion, Transclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { veCoreEvents } from '@ve-core/events' -import { MathService, UtilsService, ImageService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { ITransclusion, Transclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { veCoreEvents } from '@ve-core/events'; +import { MathService, UtilsService, ImageService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; export class TranscludeAttrController extends Transclusion implements ITransclusion { protected template: string = ` -` +`; //Custom Binding - mmsAttr: string + mmsAttr: string; //Locals - attrValues: string[] = [] + attrValues: string[] = []; - static $inject = Transclusion.$inject + static $inject = Transclusion.$inject; constructor( $q: VeQService, @@ -65,61 +65,61 @@ export class TranscludeAttrController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'name' - this.cfTitle = '' - this.cfKind = 'Text' - this.checkCircular = false + ); + this.cfType = 'name'; + this.cfTitle = ''; + this.cfKind = 'Text'; + this.checkCircular = false; } $onInit(): void { - super.$onInit() + super.$onInit(); this.$element.on('click', (e) => { - e.stopPropagation() - if (this.noClick) return + e.stopPropagation(); + if (this.noClick) return; const data = { elementId: this.element.id, projectId: this.element._projectId, refId: this.element._refId, commitId: 'latest', - } - this.eventSvc.$broadcast('element.selected', data) - }) + }; + this.eventSvc.$broadcast('element.selected', data); + }); } public getContent = (preview?): VePromise => { - const deferred = this.$q.defer() - let contentTemplate: string - const ids: string[] = [] + const deferred = this.$q.defer(); + let contentTemplate: string; + const ids: string[] = []; if ( this.element[this.mmsAttr] || (Array.isArray(this.element[this.mmsAttr]) && (this.element[this.mmsAttr] as Array).length > 0) ) { //Grab id reference to an array for CF if (this.mmsAttr.endsWith('Id')) { - ids.push(this.element[this.mmsAttr] as string) + ids.push(this.element[this.mmsAttr] as string); } // Grab id array for a CF list else if (this.mmsAttr.endsWith('Ids')) { - ids.push(...(this.element[this.mmsAttr] as Array)) + ids.push(...(this.element[this.mmsAttr] as Array)); } // Convert List of elements to strings else if (Array.isArray(this.element[this.mmsAttr])) { - ;(this.element[this.mmsAttr] as Array).forEach((value) => { + (this.element[this.mmsAttr] as Array).forEach((value) => { if (typeof this.element[this.mmsAttr] === 'object') { - value = JSON.stringify(value) + value = JSON.stringify(value); } - this.attrValues.push(`${value.toString()}`) - }) + this.attrValues.push(`${value.toString()}`); + }); } else { - let value: string + let value: string; if (typeof this.element[this.mmsAttr] === 'object') { - value = JSON.stringify(this.element[this.mmsAttr]) + value = JSON.stringify(this.element[this.mmsAttr]); } else { - value = (this.element[this.mmsAttr] as unknown).toString() + value = (this.element[this.mmsAttr] as unknown).toString(); } - this.attrValues.push(`${value}`) + this.attrValues.push(`${value}`); } // Convert referenced ids array to CF list if (ids.length > 0) { @@ -128,24 +128,24 @@ export class TranscludeAttrController extends Transclusion implements ITransclus `` - ) - }) + ); + }); } } else { - this.attrValues.push(`(empty)`) + this.attrValues.push(`(empty)`); } if (this.mmsCfLabel) { - contentTemplate = `

    {{$ctrl.mmsAttr}}

    ` + contentTemplate = `

    {{$ctrl.mmsAttr}}

    `; } this.attrValues.forEach((value, index) => { - const sep = index == this.attrValues.length - 1 ? '' : ', ' - contentTemplate += `${value}${this.mmsCfLabel ? '
    ' : sep}` - }) - deferred.resolve(contentTemplate) + const sep = index == this.attrValues.length - 1 ? '' : ', '; + contentTemplate += `${value}${this.mmsCfLabel ? '
    ' : sep}`; + }); + deferred.resolve(contentTemplate); - return deferred.promise - } + return deferred.promise; + }; } export const TranscludeNameComponent: VeComponentOptions = { @@ -167,6 +167,6 @@ export const TranscludeNameComponent: VeComponentOptions = { mmsSpecEditor: '?^^specEditor', }, controller: TranscludeAttrController, -} +}; -veComponents.component(TranscludeNameComponent.selector, TranscludeNameComponent) +veComponents.component(TranscludeNameComponent.selector, TranscludeNameComponent); diff --git a/src/ve-components/transclusions/components/transclude-com.component.ts b/src/ve-components/transclusions/components/transclude-com.component.ts index be86fda4c..fd6fe3d71 100644 --- a/src/ve-components/transclusions/components/transclude-com.component.ts +++ b/src/ve-components/transclusions/components/transclude-com.component.ts @@ -1,17 +1,17 @@ -import { ExtensionService, ComponentService } from '@ve-components/services' -import { ITransclusion, ITransclusionComponentOptions } from '@ve-components/transclusions' -import { TranscludeDocController } from '@ve-components/transclusions/components/transclude-doc.component' -import { DeletableTransclusion } from '@ve-components/transclusions/deletable-transclusion.controller' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { ImageService, MathService, UtilsService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { ITransclusion, ITransclusionComponentOptions } from '@ve-components/transclusions'; +import { TranscludeDocController } from '@ve-components/transclusions/components/transclude-doc.component'; +import { DeletableTransclusion } from '@ve-components/transclusions/deletable-transclusion.controller'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { ImageService, MathService, UtilsService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' +import { VePromise, VeQService } from '@ve-types/angular'; /** * @ngdoc directive @@ -38,7 +38,7 @@ import { VePromise, VeQService } from '@ve-types/angular' * @param {string=latest} mmsCommitId Commit ID, default is latest */ export class TranscludeComController extends TranscludeDocController implements ITransclusion { - static $inject = DeletableTransclusion.$inject + static $inject = DeletableTransclusion.$inject; constructor( $q: VeQService, @@ -77,49 +77,49 @@ export class TranscludeComController extends TranscludeDocController implements buttonBarSvc, imageSvc, viewSvc - ) - this.cfType = 'doc' - this.cfTitle = 'comment' - this.cfKind = 'Comment' - this.checkCircular = true + ); + this.cfType = 'doc'; + this.cfTitle = 'comment'; + this.cfKind = 'Comment'; + this.checkCircular = true; } $onInit(): void { - super.$onInit() + super.$onInit(); if (this.mmsViewPresentationElemCtrl) { if (this.isDeletable) { - const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec() - this.panelTitle = instanceSpec ? instanceSpec.name : 'Comment' + const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec(); + this.panelTitle = instanceSpec ? instanceSpec.name : 'Comment'; } - this.panelType = 'Comment' + this.panelType = 'Comment'; } } public getContent = (preview?: boolean): VePromise => { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); - let doc = (preview ? this.edit.element.documentation : this.element.documentation) || '(No comment)' - doc += ' - Comment by ' + this.element._creator + '' + let doc = (preview ? this.edit.element.documentation : this.element.documentation) || '(No comment)'; + doc += ' - Comment by ' + this.element._creator + ''; - let result = '' + let result = ''; if (preview) { - result = '
    ' + doc + '
    ' + result = '
    ' + doc + '
    '; } else { - result = doc + result = doc; } if (!this.mmsGenerateForDiff) { - const resultHtml = $('

    ').html(result).toArray() + const resultHtml = $('

    ').html(result).toArray(); this.mathSvc.typeset(resultHtml).then( () => deferred.resolve(resultHtml), (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } else { - deferred.resolve(result) + deferred.resolve(result); } - return deferred.promise - } + return deferred.promise; + }; } export const TranscludeComComponent: ITransclusionComponentOptions = { @@ -141,6 +141,6 @@ export const TranscludeComComponent: ITransclusionComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeComController, -} +}; -veComponents.component(TranscludeComComponent.selector, TranscludeComComponent) +veComponents.component(TranscludeComComponent.selector, TranscludeComComponent); diff --git a/src/ve-components/transclusions/components/transclude-doc.component.ts b/src/ve-components/transclusions/components/transclude-doc.component.ts index 55916ee05..b33af456a 100644 --- a/src/ve-components/transclusions/components/transclude-doc.component.ts +++ b/src/ve-components/transclusions/components/transclude-doc.component.ts @@ -1,15 +1,15 @@ -import { ExtensionService, ComponentService } from '@ve-components/services' -import { ITransclusion, DeletableTransclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService, editor_buttons } from '@ve-core/editor' -import { UtilsService, MathService, ImageService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { ITransclusion, DeletableTransclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService, editor_buttons } from '@ve-core/editor'; +import { UtilsService, MathService, ImageService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; /** * @ngdoc component @@ -65,9 +65,9 @@ export class TranscludeDocController extends DeletableTransclusion implements IT
    -` +`; - static $inject = DeletableTransclusion.$inject + static $inject = DeletableTransclusion.$inject; constructor( $q: VeQService, @@ -106,72 +106,72 @@ export class TranscludeDocController extends DeletableTransclusion implements IT buttonBarSvc, imageSvc, viewSvc - ) - this.cfType = 'doc' - this.cfTitle = 'Documentation' - this.cfKind = 'Text' - this.checkCircular = true + ); + this.cfType = 'doc'; + this.cfTitle = 'Documentation'; + this.cfKind = 'Text'; + this.checkCircular = true; } $onInit(): void { - super.$onInit() + super.$onInit(); - this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_${this.cfType}`) - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons) + this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_${this.cfType}`); + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons); this.$element.on('click', (e) => { - if (this.startEdit && !this.nonEditable) this.startEdit() + if (this.startEdit && !this.nonEditable) this.startEdit(); - if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element) + if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element); if (this.nonEditable && this.mmsViewCtrl && this.mmsViewCtrl.isEditable()) { - this.growl.warning('Cross Reference is not editable.') + this.growl.warning('Cross Reference is not editable.'); } - e.stopPropagation() - }) + e.stopPropagation(); + }); if (this.mmsViewPresentationElemCtrl) { - const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec() - const presentationElem = this.mmsViewPresentationElemCtrl.getPresentationElement() + const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec(); + const presentationElem = this.mmsViewPresentationElemCtrl.getPresentationElement(); if (this.isDeletable) { - this.panelTitle = instanceSpec ? instanceSpec.name : '' - this.panelType = presentationElem ? presentationElem.type : '' //this is hack for fake table/list/equation until we get actual editors + this.panelTitle = instanceSpec ? instanceSpec.name : ''; + this.panelType = presentationElem ? presentationElem.type : ''; //this is hack for fake table/list/equation until we get actual editors if (this.panelType.charAt(this.panelType.length - 1) === 'T') - this.panelType = this.panelType.substring(0, this.panelType.length - 1) - if (this.panelType === 'Paragraph') this.panelType = 'Text' - if (this.panelType === 'Figure' || this.panelType === 'ImageT') this.panelType = 'Image' + this.panelType = this.panelType.substring(0, this.panelType.length - 1); + if (this.panelType === 'Paragraph') this.panelType = 'Text'; + if (this.panelType === 'Figure' || this.panelType === 'ImageT') this.panelType = 'Image'; } if (presentationElem) { - this.editorType = presentationElem.type + this.editorType = presentationElem.type; } } } $onDestroy(): void { - super.$onDestroy() - this.buttonBarSvc.destroy(this.bbId) + super.$onDestroy(); + this.buttonBarSvc.destroy(this.bbId); } public getContent = (preview?: boolean): VePromise => { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); - let doc = preview ? this.edit.element.documentation : this.element.documentation + let doc = preview ? this.edit.element.documentation : this.element.documentation; if (!doc || this.emptyRegex.test(doc)) { - doc = '

    (no ' + this.panelType + ')

    ' + doc = '

    (no ' + this.panelType + ')

    '; } - doc = doc.replace(this.fixPreSpanRegex, '') - doc = doc.replace(this.spacePeriod, '>.') - doc = doc.replace(this.spaceSpace, '> ') - doc = doc.replace(this.spaceComma, '>,') - let result: string + doc = doc.replace(this.fixPreSpanRegex, ''); + doc = doc.replace(this.spacePeriod, '>.'); + doc = doc.replace(this.spaceSpace, '> '); + doc = doc.replace(this.spaceComma, '>,'); + let result: string; if (preview) { - result = '
    ' + doc + '
    ' + result = '
    ' + doc + '
    '; } else { - result = doc + result = doc; } if (this.mmsViewPresentationElemCtrl) { - const element = this.mmsViewPresentationElemCtrl.getPresentationElement() - const pe = this.mmsViewPresentationElemCtrl.getInstanceSpec() + const element = this.mmsViewPresentationElemCtrl.getPresentationElement(); + const pe = this.mmsViewPresentationElemCtrl.getInstanceSpec(); if ( pe && pe._veNumber && @@ -181,26 +181,26 @@ export class TranscludeDocController extends DeletableTransclusion implements IT element.type === 'Equation' || element.type === 'ImageT') ) { - this.type = element.type === 'TableT' ? 'table' : element.type.toLowerCase() + this.type = element.type === 'TableT' ? 'table' : element.type.toLowerCase(); if (this.type === 'imaget') { - this.type = 'figure' + this.type = 'figure'; } - this.utilsSvc.addLiveNumbering(pe, $('#' + pe.id), this.type) + this.utilsSvc.addLiveNumbering(pe, $('#' + pe.id), this.type); } } if (!this.mmsGenerateForDiff) { - const resultHtml = $('

    ').html(result).toArray() + const resultHtml = $('

    ').html(result).toArray(); this.mathSvc.typeset(resultHtml).then( () => deferred.resolve(resultHtml), (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } else { - deferred.resolve(result) + deferred.resolve(result); } - return deferred.promise - } + return deferred.promise; + }; } export const TranscludeDocComponent: VeComponentOptions = { @@ -222,6 +222,6 @@ export const TranscludeDocComponent: VeComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeDocController, -} +}; -veComponents.component(TranscludeDocComponent.selector, TranscludeDocComponent) +veComponents.component(TranscludeDocComponent.selector, TranscludeDocComponent); diff --git a/src/ve-components/transclusions/components/transclude-enum.component.ts b/src/ve-components/transclusions/components/transclude-enum.component.ts index c69942f8d..ca3df96dc 100644 --- a/src/ve-components/transclusions/components/transclude-enum.component.ts +++ b/src/ve-components/transclusions/components/transclude-enum.component.ts @@ -5,18 +5,18 @@ * responsible person for that particular item which gets saved as the Type/Value? of the property You could additionally add a * binding which specifies the template for the creation of new objects as types to be placed in the holding bin. */ -import { ComponentService, ExtensionService } from '@ve-components/services' -import { ITransclusion, Transclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { MathService, UtilsService, ImageService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { ITransclusion, Transclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { MathService, UtilsService, ImageService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; /** * @ngdoc component @@ -50,10 +50,10 @@ import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' */ export class TranscludeEnumController extends Transclusion implements ITransclusion { //Locals - noClick: boolean | undefined - clickHandler: () => void + noClick: boolean | undefined; + clickHandler: () => void; - static $inject = Transclusion.$inject + static $inject = Transclusion.$inject; constructor( $q: VeQService, @@ -90,50 +90,50 @@ export class TranscludeEnumController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'name' - this.cfTitle = '' - this.cfKind = 'Text' - this.checkCircular = false + ); + this.cfType = 'name'; + this.cfTitle = ''; + this.cfKind = 'Text'; + this.checkCircular = false; } $onInit(): void { - super.$onInit() + super.$onInit(); // Need a way to put in a query for allowed options. // Value to save the resulting pointer // Transclusion for new options this.$element.on('click', (e) => { - if (this.noClick) return + if (this.noClick) return; if (this.clickHandler) { - this.clickHandler() - return + this.clickHandler(); + return; } - if (this.startEdit && !this.nonEditable) this.startEdit() + if (this.startEdit && !this.nonEditable) this.startEdit(); - if (!this.mmsViewCtrl) return false + if (!this.mmsViewCtrl) return false; if (this.nonEditable && this.mmsViewCtrl && this.mmsViewCtrl.isEditable()) { - this.growl.warning('Cross Reference is not editable.') + this.growl.warning('Cross Reference is not editable.'); } - this.mmsViewCtrl.transcludeClicked(this.element) - e.stopPropagation() - }) + this.mmsViewCtrl.transcludeClicked(this.element); + e.stopPropagation(); + }); } public getContent = (preview?: boolean): VePromise => { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); const defaultTemplate = - '{{$ctrl.element.name}}(no name)' + '{{$ctrl.element.name}}(no name)'; const editTemplate = - '{{$ctrl.edit.name}}(no name)' + '{{$ctrl.edit.name}}(no name)'; if (preview) { - deferred.resolve('
    ' + editTemplate + '
    ') + deferred.resolve('
    ' + editTemplate + '
    '); } else { - deferred.resolve(defaultTemplate) + deferred.resolve(defaultTemplate); } - return deferred.promise - } + return deferred.promise; + }; // private _startEdit( // ctrl: ComponentController, @@ -262,6 +262,6 @@ export const TranscludeEnumComponent: VeComponentOptions = { mmsSpecEditor: '?^^specEditor', }, controller: TranscludeEnumController, -} +}; -veComponents.component(TranscludeEnumComponent.selector, TranscludeEnumComponent) +veComponents.component(TranscludeEnumComponent.selector, TranscludeEnumComponent); diff --git a/src/ve-components/transclusions/components/transclude-group-docs.component.ts b/src/ve-components/transclusions/components/transclude-group-docs.component.ts index 5e0fdb8cc..27e55e3e5 100644 --- a/src/ve-components/transclusions/components/transclude-group-docs.component.ts +++ b/src/ve-components/transclusions/components/transclude-group-docs.component.ts @@ -1,17 +1,17 @@ -import { ExtensionService, ComponentService } from '@ve-components/services' -import { ITransclusion, Transclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { ImageService, MathService, UtilsService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' -import { handleChange } from '@ve-utils/utils' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { ITransclusion, Transclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { ImageService, MathService, UtilsService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; +import { handleChange } from '@ve-utils/utils'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { ViewObject } from '@ve-types/mms' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { ViewObject } from '@ve-types/mms'; /** * @ngdoc directive @@ -31,14 +31,14 @@ class TranscludeGroupDocsController extends Transclusion implements ITransclusio -` +`; - mmsGroupId: string + mmsGroupId: string; - documents: ViewObject[] - docs: ViewObject[] + documents: ViewObject[]; + docs: ViewObject[]; - static $inject = [...Transclusion.$inject, 'ViewService'] + static $inject = [...Transclusion.$inject, 'ViewService']; constructor( $q: VeQService, @@ -76,32 +76,32 @@ class TranscludeGroupDocsController extends Transclusion implements ITransclusio extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'groupDocs' - this.cfTitle = '' - this.cfKind = 'Table' - this.checkCircular = false + ); + this.cfType = 'groupDocs'; + this.cfTitle = ''; + this.cfKind = 'Table'; + this.checkCircular = false; } $postLink(): void { - this.changeAction(this.mmsGroupId, '', false) + this.changeAction(this.mmsGroupId, '', false); } $onInit(): void { - super.$onInit() - this.mmsGroupId = this.mmsElementId + super.$onInit(); + this.mmsGroupId = this.mmsElementId; } protected watch = (onChangesObj: angular.IOnChangesObject): void => { if (onChangesObj.mmsGroupId) { - this.mmsElementId = this.mmsGroupId + this.mmsElementId = this.mmsGroupId; } - handleChange(onChangesObj, 'mmsGroupId', this.changeAction) - } + handleChange(onChangesObj, 'mmsGroupId', this.changeAction); + }; public getContent = (): VePromise => { - const deferred = this.$q.defer() - this.mmsGroupId = this.mmsElementId + const deferred = this.$q.defer(); + this.mmsGroupId = this.mmsElementId; this.viewSvc .getProjectDocuments( { @@ -112,29 +112,29 @@ class TranscludeGroupDocsController extends Transclusion implements ITransclusio ) .then( (documents) => { - this.documents = documents - this.update() - deferred.resolve(this.template) + this.documents = documents; + this.update(); + deferred.resolve(this.template); }, (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) - return deferred.promise - } + ); + return deferred.promise; + }; public update = (): void => { - const docs: ViewObject[] = [] - const groupId = this.mmsGroupId === '' ? undefined : this.mmsGroupId + const docs: ViewObject[] = []; + const groupId = this.mmsGroupId === '' ? undefined : this.mmsGroupId; for (let i = 0; i < this.documents.length; i++) { if ((groupId === undefined || groupId === this.projectId) && !this.documents[i]._groupId) { - docs.push(this.documents[i]) + docs.push(this.documents[i]); } else if (this.documents[i]._groupId == this.mmsGroupId) { - docs.push(this.documents[i]) + docs.push(this.documents[i]); } } - this.docs = docs - } + this.docs = docs; + }; } export const TranscludeGroupDocsComponent: VeComponentOptions = { @@ -156,6 +156,6 @@ export const TranscludeGroupDocsComponent: VeComponentOptions = { mmsViewCtrl: '?^^view', }, controller: TranscludeGroupDocsController, -} +}; -veComponents.component(TranscludeGroupDocsComponent.selector, TranscludeGroupDocsComponent) +veComponents.component(TranscludeGroupDocsComponent.selector, TranscludeGroupDocsComponent); diff --git a/src/ve-components/transclusions/components/transclude-img.component.ts b/src/ve-components/transclusions/components/transclude-img.component.ts index e4cf8cd57..693455c88 100644 --- a/src/ve-components/transclusions/components/transclude-img.component.ts +++ b/src/ve-components/transclusions/components/transclude-img.component.ts @@ -1,15 +1,15 @@ -import { ExtensionService, ComponentService } from '@ve-components/services' -import { Transclusion, ITransclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { UtilsService, MathService, ImageService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, URLService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { Transclusion, ITransclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { UtilsService, MathService, ImageService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, URLService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; /** * @ngdoc component @@ -47,12 +47,12 @@ import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' */ export class TranscludeImgController extends Transclusion implements ITransclusion { //Locals - includeExt = ['svg', 'png'] - svg: { url: string; image: boolean; ext: string }[] - png: { url: string; image: boolean; ext: string }[] - artifacts: { url: string; image: boolean; ext: string }[] + includeExt = ['svg', 'png']; + svg: { url: string; image: boolean; ext: string }[]; + png: { url: string; image: boolean; ext: string }[]; + artifacts: { url: string; image: boolean; ext: string }[]; - static $inject: string[] = [...Transclusion.$inject, 'URLService'] + static $inject: string[] = [...Transclusion.$inject, 'URLService']; constructor( $q: VeQService, @@ -90,24 +90,24 @@ export class TranscludeImgController extends Transclusion implements ITransclusi extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'doc' - this.cfTitle = 'Documentation' - this.cfKind = 'Text' - this.checkCircular = true + ); + this.cfType = 'doc'; + this.cfTitle = 'Documentation'; + this.cfKind = 'Text'; + this.checkCircular = true; } $onInit(): void { - super.$onInit() + super.$onInit(); this.$element.on('click', (e) => { - if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element) + if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element); - e.stopPropagation() - }) + e.stopPropagation(); + }); } public getContent = (preview?): VePromise => { - const artifacts = this.element._artifacts + const artifacts = this.element._artifacts; if (artifacts !== undefined) { const reqOb = { elementId: this.mmsElementId, @@ -115,7 +115,7 @@ export class TranscludeImgController extends Transclusion implements ITransclusi refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - } + }; this.artifacts = artifacts .filter((a) => this.includeExt.includes(a.extension)) .map((a) => { @@ -123,16 +123,16 @@ export class TranscludeImgController extends Transclusion implements ITransclusi url: this.urlSvc.getArtifactURL(reqOb, a.extension), image: a.mimetype.indexOf('image') > -1, ext: a.extension, - } - }) - this.svg = this.artifacts.filter((a) => a.ext === 'svg') + }; + }); + this.svg = this.artifacts.filter((a) => a.ext === 'svg'); //this.png = this.artifacts.filter((a) => a.ext === 'png') } const result = '{{$ctrl.element.name}}' + - '' - return this.$q.resolve(result) - } + ''; + return this.$q.resolve(result); + }; } export const TranscludeImgComponent: VeComponentOptions = { @@ -154,6 +154,6 @@ export const TranscludeImgComponent: VeComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeImgController, -} +}; -veComponents.component(TranscludeImgComponent.selector, TranscludeImgComponent) +veComponents.component(TranscludeImgComponent.selector, TranscludeImgComponent); diff --git a/src/ve-components/transclusions/components/transclude-name.component.ts b/src/ve-components/transclusions/components/transclude-name.component.ts index 87338cafe..3c078af3b 100644 --- a/src/ve-components/transclusions/components/transclude-name.component.ts +++ b/src/ve-components/transclusions/components/transclude-name.component.ts @@ -1,16 +1,16 @@ -import { ExtensionService, ComponentService } from '@ve-components/services' -import { SpecTool } from '@ve-components/spec-tools' -import { ITransclusion, Transclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { MathService, UtilsService, ImageService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { SpecTool } from '@ve-components/spec-tools'; +import { ITransclusion, Transclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { MathService, UtilsService, ImageService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; /** * @ngdoc component @@ -54,13 +54,13 @@ export class TranscludeNameController extends Transclusion implements ITransclus -` +`; //Locals - clickHandler: () => void - mmsSpecEditorCtrl: SpecTool + clickHandler: () => void; + mmsSpecEditorCtrl: SpecTool; - static $inject = Transclusion.$inject + static $inject = Transclusion.$inject; constructor( $q: VeQService, @@ -97,47 +97,47 @@ export class TranscludeNameController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'name' - this.cfTitle = '' - this.cfKind = 'Text' - this.checkCircular = false + ); + this.cfType = 'name'; + this.cfTitle = ''; + this.cfKind = 'Text'; + this.checkCircular = false; } $onInit(): void { - super.$onInit() + super.$onInit(); this.$element.on('click', (e) => { - if (this.noClick) return + if (this.noClick) return; if (this.clickHandler) { - this.clickHandler() - return + this.clickHandler(); + return; } - if (this.startEdit && !this.nonEditable) this.startEdit() + if (this.startEdit && !this.nonEditable) this.startEdit(); - if (!this.mmsViewCtrl) return false + if (!this.mmsViewCtrl) return false; if (this.nonEditable && this.mmsViewCtrl && this.mmsViewCtrl.isEditable()) { - this.growl.warning('Cross Reference is not editable.') + this.growl.warning('Cross Reference is not editable.'); } - this.mmsViewCtrl.transcludeClicked(this.element) - e.stopPropagation() - }) + this.mmsViewCtrl.transcludeClicked(this.element); + e.stopPropagation(); + }); } public getContent = (preview?): VePromise => { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); const defaultTemplate = - '{{$ctrl.element.name}}({{ $ctrl.element.type }})' + '{{$ctrl.element.name}}({{ $ctrl.element.type }})'; const editTemplate = - '{{$ctrl.edit.element.name}}({{ $ctrl.element.type }})' + '{{$ctrl.edit.element.name}}({{ $ctrl.element.type }})'; if (preview) { - deferred.resolve('
    ' + editTemplate + '
    ') + deferred.resolve('
    ' + editTemplate + '
    '); } else { - deferred.resolve(defaultTemplate) + deferred.resolve(defaultTemplate); } - return deferred.promise - } + return deferred.promise; + }; } export const TranscludeNameComponent: VeComponentOptions = { @@ -160,6 +160,6 @@ export const TranscludeNameComponent: VeComponentOptions = { mmsSpecEditor: '?^^specEditor', }, controller: TranscludeNameController, -} +}; -veComponents.component(TranscludeNameComponent.selector, TranscludeNameComponent) +veComponents.component(TranscludeNameComponent.selector, TranscludeNameComponent); diff --git a/src/ve-components/transclusions/components/transclude-section.component.ts b/src/ve-components/transclusions/components/transclude-section.component.ts index 3ccb591f7..aa29c2f6f 100644 --- a/src/ve-components/transclusions/components/transclude-section.component.ts +++ b/src/ve-components/transclusions/components/transclude-section.component.ts @@ -1,17 +1,17 @@ -import { PresentationService } from '@ve-components/presentations' -import { ExtensionService, ComponentService } from '@ve-components/services' -import { DeletableTransclusion, ITransclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { editor_buttons, EditorService } from '@ve-core/editor' -import { MathService, UtilsService, ImageService, RootScopeService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { PresentationService } from '@ve-components/presentations'; +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { DeletableTransclusion, ITransclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { editor_buttons, EditorService } from '@ve-core/editor'; +import { MathService, UtilsService, ImageService, RootScopeService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { InstanceValueObject } from '@ve-types/mms' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { InstanceValueObject } from '@ve-types/mms'; /** * @ngdoc component @@ -43,11 +43,11 @@ import { InstanceValueObject } from '@ve-types/mms' * @param {boolean=false} nonEditable can edit inline or not */ export class TranscludeSectionController extends DeletableTransclusion implements ITransclusion { - showNumbering: boolean - noCompile: boolean = true + showNumbering: boolean; + noCompile: boolean = true; //Locals - static $inject = [...DeletableTransclusion.$inject, 'PresentationService', 'RootScopeService'] + static $inject = [...DeletableTransclusion.$inject, 'PresentationService', 'RootScopeService']; constructor( $q: VeQService, @@ -88,51 +88,51 @@ export class TranscludeSectionController extends DeletableTransclusion implement buttonBarSvc, imageSvc, viewSvc - ) - this.cfType = 'name' - this.cfTitle = '' - this.cfKind = 'Text' - this.checkCircular = false + ); + this.cfType = 'name'; + this.cfTitle = ''; + this.cfKind = 'Text'; + this.checkCircular = false; } $onInit(): void { - super.$onInit() - this.showNumbering = this.rootScopeSvc.veNumberingOn() - this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_section`) - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons) - this.bbApi.setPermission('editor-preview', false) - this.bbApi.setPermission('editor-save-continue', false) - this.bbApi.setPermission('editor-reset', false) + super.$onInit(); + this.showNumbering = this.rootScopeSvc.veNumberingOn(); + this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_section`); + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons); + this.bbApi.setPermission('editor-preview', false); + this.bbApi.setPermission('editor-save-continue', false); + this.bbApi.setPermission('editor-reset', false); this.$element.on('click', (e) => { - if (this.startEdit) this.startEdit() - if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element) - e.stopPropagation() - }) + if (this.startEdit) this.startEdit(); + if (this.mmsViewCtrl) this.mmsViewCtrl.transcludeClicked(this.element); + e.stopPropagation(); + }); this.subs.push( this.eventSvc.binding(this.rootScopeSvc.constants.VENUMBERINGON, (data) => { - this.showNumbering = data + this.showNumbering = data; }) - ) + ); } $onDestroy(): void { - super.$onDestroy() - this.buttonBarSvc.destroy(this.bbId) + super.$onDestroy(); + this.buttonBarSvc.destroy(this.bbId); } public getContent = (preview?): VePromise => { if (this.element.specification && this.element.specification.operand) { const dups = this.presentationSvc.checkForDuplicateInstances( this.element.specification.operand as InstanceValueObject[] - ) + ); if (dups.length > 0) { - this.growl.warning('There are duplicates in this section, duplicates ignored!') + this.growl.warning('There are duplicates in this section, duplicates ignored!'); } } - const deferred = this.$q.defer() - deferred.reject({ status: 200 }) //don't recompile - return deferred.promise - } + const deferred = this.$q.defer(); + deferred.reject({ status: 200 }); //don't recompile + return deferred.promise; + }; } export const TranscludeSectionComponent: VeComponentOptions = { @@ -174,6 +174,6 @@ export const TranscludeSectionComponent: VeComponentOptions = { mmsViewPresentationElemCtrl: '?^viewPe', }, controller: TranscludeSectionController, -} +}; -veComponents.component(TranscludeSectionComponent.selector, TranscludeSectionComponent) +veComponents.component(TranscludeSectionComponent.selector, TranscludeSectionComponent); diff --git a/src/ve-components/transclusions/components/transclude-val.component.ts b/src/ve-components/transclusions/components/transclude-val.component.ts index e977b4da3..d73308d6b 100644 --- a/src/ve-components/transclusions/components/transclude-val.component.ts +++ b/src/ve-components/transclusions/components/transclude-val.component.ts @@ -1,19 +1,19 @@ -import $ from 'jquery' +import $ from 'jquery'; -import { ExtensionService, ComponentService } from '@ve-components/services' -import { SpecTool } from '@ve-components/spec-tools' -import { ITransclusion, ITransclusionComponentOptions, Transclusion } from '@ve-components/transclusions' -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' -import { EditorService, editor_buttons } from '@ve-core/editor' -import { MathService, UtilsService, ImageService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, ValueService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { SpecTool } from '@ve-components/spec-tools'; +import { ITransclusion, ITransclusionComponentOptions, Transclusion } from '@ve-components/transclusions'; +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; +import { EditorService, editor_buttons } from '@ve-core/editor'; +import { MathService, UtilsService, ImageService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, ValueService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { PropertySpec, veComponents } from '@ve-components' +import { PropertySpec, veComponents } from '@ve-components'; -import { VeQService } from '@ve-types/angular' -import { ValueObject } from '@ve-types/mms' +import { VeQService } from '@ve-types/angular'; +import { ValueObject } from '@ve-types/mms'; /** * @ngdoc component @@ -46,18 +46,18 @@ import { ValueObject } from '@ve-types/mms' */ export class TranscludeValController extends Transclusion implements ITransclusion { //Custom Bindings - first: boolean + first: boolean; //Custom Require - mmsSpecEditorCtrl: SpecTool + mmsSpecEditorCtrl: SpecTool; //Locals - addValueType: string = 'LiteralString' - values: ValueObject[] = [] - editValues: ValueObject[] = [] - propertySpec: PropertySpec - public bbApi: ButtonBarApi - public bars: string[] + addValueType: string = 'LiteralString'; + values: ValueObject[] = []; + editValues: ValueObject[] = []; + propertySpec: PropertySpec; + public bbApi: ButtonBarApi; + public bars: string[]; //Templates template = ` @@ -71,7 +71,7 @@ export class TranscludeValController extends Transclusion implements ITransclusi {{::value.body[0]}} {{$ctrl.first ? $ctrl.values : value}}
    -` +`; previewTemplate = `
    @@ -85,7 +85,7 @@ export class TranscludeValController extends Transclusion implements ITransclusi {{value}}
    -` +`; editTemplate = `
    @@ -170,9 +170,9 @@ export class TranscludeValController extends Transclusion implements ITransclusi
    -` +`; - static $inject = [...Transclusion.$inject, 'ValueService'] + static $inject = [...Transclusion.$inject, 'ValueService']; constructor( $q: VeQService, @@ -210,108 +210,108 @@ export class TranscludeValController extends Transclusion implements ITransclusi extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'val' - this.cfTitle = 'Value' - this.cfKind = 'Value' - this.cfField = 'value' - this.checkCircular = false + ); + this.cfType = 'val'; + this.cfTitle = 'Value'; + this.cfKind = 'Value'; + this.cfField = 'value'; + this.checkCircular = false; } $onInit(): void { - super.$onInit() - this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_${this.cfType}`) - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons) + super.$onInit(); + this.bbId = this.buttonBarSvc.generateBarId(`${this.mmsElementId}_${this.cfType}`); + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, editor_buttons); this.$element.on('click', (e) => { - e.stopPropagation() - if (this.noClick) return + e.stopPropagation(); + if (this.noClick) return; if (!this.nonEditable && !this.isEditing) { - this.startEdit() + this.startEdit(); } if (this.mmsViewCtrl) { - this.mmsViewCtrl.transcludeClicked(this.element) + this.mmsViewCtrl.transcludeClicked(this.element); } if (this.nonEditable && this.mmsViewCtrl && this.mmsViewCtrl.isEditable()) { - this.growl.warning('Cross Reference is not editable.') + this.growl.warning('Cross Reference is not editable.'); } - }) + }); } public getContent = (preview?): angular.IPromise => { - const deferred = this.$q.defer() - const toCompileList: any[] = [] - let areStrings = false - this.values = this.valueSvc.getValues(this.element) - let values = this.values - let result = '' + const deferred = this.$q.defer(); + const toCompileList: any[] = []; + let areStrings = false; + this.values = this.valueSvc.getValues(this.element); + let values = this.values; + let result = ''; if (preview) { - values = this.editValues + values = this.editValues; } for (let i = 0; i < values.length; i++) { if (values[i].type === 'LiteralString') { - areStrings = true - let s = values[i].value as string + areStrings = true; + let s = values[i].value as string; if (s.indexOf('

    ') === -1) { - s = s.replace('<', '<') + s = s.replace('<', '<'); } - toCompileList.push(s) + toCompileList.push(s); } else { - break + break; } } if (values.length === 0 || Object.keys(values[0]).length < 2) { - result = '(no value)' - deferred.resolve(result) + result = '(no value)'; + deferred.resolve(result); } else if (areStrings) { - let toCompile = toCompileList.join(' ') + let toCompile = toCompileList.join(' '); if (toCompile === '' || this.emptyRegex.test(toCompile)) { - result = '(no value)' - deferred.resolve(result) + result = '(no value)'; + deferred.resolve(result); } - toCompile = toCompile.replace(this.spacePeriod, '>.') - toCompile = toCompile.replace(this.spaceSpace, '> ') - toCompile = toCompile.replace(this.spaceComma, '>,') + toCompile = toCompile.replace(this.spacePeriod, '>.'); + toCompile = toCompile.replace(this.spaceSpace, '> '); + toCompile = toCompile.replace(this.spaceComma, '>,'); if (preview) { - result = '

    ' + toCompile + '
    ' + result = '
    ' + toCompile + '
    '; } else { - result = toCompile + result = toCompile; } if (!this.mmsGenerateForDiff) { - const resultHtml = $('

    ').html(result).toArray() + const resultHtml = $('

    ').html(result).toArray(); this.mathSvc.typeset(resultHtml).then( () => deferred.resolve(resultHtml), (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } else { - deferred.resolve(result) + deferred.resolve(result); } } else { if (preview) { - deferred.resolve(this.previewTemplate) + deferred.resolve(this.previewTemplate); } else { if (this.first) { - this.values = [this.values[0]] + this.values = [this.values[0]]; } - deferred.resolve(this.template) + deferred.resolve(this.template); } } - return deferred.promise - } + return deferred.promise; + }; protected recompile = (preview?: boolean): void => { if (!this.valueSvc.isValue(this.element)) { - this.$element.empty() + this.$element.empty(); //TODO: Add reason/errorMessage handling here. this.$transcludeEl = $( '' - ) - this.$element.append(this.$transcludeEl) + ); + this.$element.append(this.$transcludeEl); this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: this.element.id, @@ -319,72 +319,72 @@ export class TranscludeValController extends Transclusion implements ITransclusi type: 'transclusion', field: this.cfField, }) - ) - return + ); + return; } if (!this.nonEditable && this.mmsSpecEditorCtrl && !this.edit) { - this.startEdit() + this.startEdit(); } else { - this.defaultRecompile(preview) + this.defaultRecompile(preview); } - } + }; protected startEdit(): void { if (this.propertySpec) { super.startEdit(() => { - this.editValues = this.valueSvc.getValues(this.edit.element) - }) - return + this.editValues = this.valueSvc.getValues(this.edit.element); + }); + return; } this.valueSvc.getPropertySpec(this.element).then( (value) => { - this.propertySpec = value + this.propertySpec = value; super.startEdit(() => { - this.editValues = this.valueSvc.getValues(this.edit.element) - }) + this.editValues = this.valueSvc.getValues(this.edit.element); + }); }, (reason) => { - this.growl.error('Failed to get property spec: ' + reason.message) + this.growl.error('Failed to get property spec: ' + reason.message); } - ) + ); } public save = (e: JQuery.ClickEvent): void => { - e.stopPropagation() - this.saveAction(false) - } + e.stopPropagation(); + this.saveAction(false); + }; public saveC = (e: JQuery.ClickEvent): void => { - e.stopPropagation() - this.saveAction(true) - } + e.stopPropagation(); + this.saveAction(true); + }; public cancel = (e: JQuery.ClickEvent): void => { - e.stopPropagation() - this.cancelAction() - } + e.stopPropagation(); + this.cancelAction(); + }; public addValue(e: JQueryEventObject): void { - e.stopPropagation() - const newVal = this.valueSvc.addValue(this.edit, this.addValueType) + e.stopPropagation(); + const newVal = this.valueSvc.addValue(this.edit, this.addValueType); if (this.editValues.length == 0) { - this.editValues.push(newVal) + this.editValues.push(newVal); } } public addEnumerationValue(e: JQueryEventObject): void { - e.stopPropagation() - const enumValue = this.valueSvc.addEnumerationValue(this.propertySpec, this.edit) - this.editValues.push(enumValue) + e.stopPropagation(); + const enumValue = this.valueSvc.addEnumerationValue(this.propertySpec, this.edit); + this.editValues.push(enumValue); if (this.element.type == 'Property' || this.element.type == 'Port') { - this.edit.element.defaultValue = enumValue + this.edit.element.defaultValue = enumValue; } } public removeVal = (e: JQueryEventObject, i: number): void => { - e.stopPropagation() - this.editValues.splice(i, 1) - } + e.stopPropagation(); + this.editValues.splice(i, 1); + }; } export const TranscludeValComponent: ITransclusionComponentOptions = { @@ -410,6 +410,6 @@ export const TranscludeValComponent: ITransclusionComponentOptions = { mmsSpecEditorCtrl: '?^specEditor', }, controller: TranscludeValController, -} +}; -veComponents.component(TranscludeValComponent.selector, TranscludeValComponent) +veComponents.component(TranscludeValComponent.selector, TranscludeValComponent); diff --git a/src/ve-components/transclusions/components/transclude-value-link.component.ts b/src/ve-components/transclusions/components/transclude-value-link.component.ts index 82e920476..c93d890f0 100644 --- a/src/ve-components/transclusions/components/transclude-value-link.component.ts +++ b/src/ve-components/transclusions/components/transclude-value-link.component.ts @@ -1,16 +1,16 @@ -import { ExtensionService, ComponentService } from '@ve-components/services' -import { ITransclusion, ITransclusionComponentOptions, Transclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { MathService, UtilsService, ImageService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ExtensionService, ComponentService } from '@ve-components/services'; +import { ITransclusion, ITransclusionComponentOptions, Transclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { MathService, UtilsService, ImageService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' -import { ElementObject, LiteralObject, SlotObject } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { ElementObject, LiteralObject, SlotObject } from '@ve-types/mms'; /** * @ngdoc component @@ -43,9 +43,9 @@ import { ElementObject, LiteralObject, SlotObject } from '@ve-types/mms' */ export class TranscludeNameController extends Transclusion implements ITransclusion { //Custom Bindings - mmsLinkText: string + mmsLinkText: string; - static $inject = Transclusion.$inject + static $inject = Transclusion.$inject; constructor( $q: VeQService, @@ -82,25 +82,25 @@ export class TranscludeNameController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'name' - this.cfTitle = '' - this.cfKind = 'Text' - this.checkCircular = false - this.nonEditable = true + ); + this.cfType = 'name'; + this.cfTitle = ''; + this.cfKind = 'Text'; + this.checkCircular = false; + this.nonEditable = true; } $onInit(): void { - super.$onInit() - if (typeof this.mmsLinkText === 'undefined') this.mmsLinkText = 'Link' + super.$onInit(); + if (typeof this.mmsLinkText === 'undefined') this.mmsLinkText = 'Link'; } public getContent = (): VePromise => { - let url = '' + let url = ''; if (this.element.type === 'Property') { - const value = this.element.defaultValue + const value = this.element.defaultValue; if (value && value.type === 'LiteralString') { - url = value.value as string + url = value.value as string; } } else if (this.element.type === 'Slot') { if ( @@ -108,16 +108,16 @@ export class TranscludeNameController extends Transclusion implements ITransclus this.element.value.length > 0 && (this.element.value[0] as ElementObject).type === 'LiteralString' ) { - url = ((this.element as SlotObject).value[0] as LiteralObject).value + url = ((this.element as SlotObject).value[0] as LiteralObject).value; } } if (url !== '') { - return this.$q.resolve('' + this.mmsLinkText + '') + return this.$q.resolve('' + this.mmsLinkText + ''); } else { - return this.$q.reject('Element does not provide link value.') + return this.$q.reject('Element does not provide link value.'); } - } + }; } export const TranscludeValueLinkComponent: ITransclusionComponentOptions = { @@ -140,6 +140,6 @@ export const TranscludeValueLinkComponent: ITransclusionComponentOptions = { mmsViewCtrl: '?^^view', }, controller: TranscludeNameController, -} +}; -veComponents.component(TranscludeValueLinkComponent.selector, TranscludeValueLinkComponent) +veComponents.component(TranscludeValueLinkComponent.selector, TranscludeValueLinkComponent); diff --git a/src/ve-components/transclusions/components/transclude-view.component.ts b/src/ve-components/transclusions/components/transclude-view.component.ts index 0d3d86aef..c52fae9f6 100644 --- a/src/ve-components/transclusions/components/transclude-view.component.ts +++ b/src/ve-components/transclusions/components/transclude-view.component.ts @@ -1,15 +1,15 @@ -import { ComponentService, ExtensionService } from '@ve-components/services' -import { ITransclusion, Transclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { ImageService, MathService, UtilsService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, ViewApi } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { ITransclusion, Transclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { ImageService, MathService, UtilsService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, ViewApi } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; /** * @ngdoc component @@ -47,11 +47,11 @@ import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' */ export class TranscludeViewController extends Transclusion implements ITransclusion { //Custom Bindings - public noTitle: boolean + public noTitle: boolean; - public viewApi: ViewApi + public viewApi: ViewApi; - static $inject = Transclusion.$inject + static $inject = Transclusion.$inject; constructor( $q: VeQService, @@ -88,29 +88,29 @@ export class TranscludeViewController extends Transclusion implements ITransclus extensionSvc, buttonBarSvc, imageSvc - ) - this.cfType = 'view' - this.cfTitle = 'View' - this.cfKind = 'contents' - this.checkCircular = true + ); + this.cfType = 'view'; + this.cfTitle = 'View'; + this.cfKind = 'contents'; + this.checkCircular = true; } $onInit(): void { - super.$onInit() + super.$onInit(); if (typeof this.noTitle === 'undefined') { - this.noTitle = true + this.noTitle = true; } if (this.mmsViewCtrl) { - this.viewApi = this.mmsViewCtrl.mmsViewApi + this.viewApi = this.mmsViewCtrl.mmsViewApi; } } public getContent = (): VePromise => { return this.$q.resolve( '' - ) - } + ); + }; } const TranscludeViewComponent: VeComponentOptions = { @@ -132,6 +132,6 @@ const TranscludeViewComponent: VeComponentOptions = { mmsViewPresentationElemCtrl: '?^^mmsViewPresentationElem', }, controller: TranscludeViewController, -} +}; -veComponents.component(TranscludeViewComponent.selector, TranscludeViewComponent) +veComponents.component(TranscludeViewComponent.selector, TranscludeViewComponent); diff --git a/src/ve-components/transclusions/deletable-transclusion.controller.ts b/src/ve-components/transclusions/deletable-transclusion.controller.ts index 7cef9a3bc..8bc86ec35 100644 --- a/src/ve-components/transclusions/deletable-transclusion.controller.ts +++ b/src/ve-components/transclusions/deletable-transclusion.controller.ts @@ -1,17 +1,17 @@ -import { ComponentService, ExtensionService } from '@ve-components/services' -import { Transclusion } from '@ve-components/transclusions' -import { ButtonBarService } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { ImageService, MathService, UtilsService } from '@ve-utils/application' -import { EditService, EventService } from '@ve-utils/core' -import { ElementService, ViewService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { Transclusion } from '@ve-components/transclusions'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { ImageService, MathService, UtilsService } from '@ve-utils/application'; +import { EditService, EventService } from '@ve-utils/core'; +import { ElementService, ViewService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { VeQService } from '@ve-types/angular' -import { PresentTextObject } from '@ve-types/mms' +import { VeQService } from '@ve-types/angular'; +import { PresentTextObject } from '@ve-types/mms'; export class DeletableTransclusion extends Transclusion { - static $inject = [...Transclusion.$inject, 'ViewService'] + static $inject = [...Transclusion.$inject, 'ViewService']; constructor( $q: VeQService, $scope: angular.IScope, @@ -48,74 +48,74 @@ export class DeletableTransclusion extends Transclusion { extensionSvc, buttonBarSvc, imageSvc - ) + ); } $onInit(): void { - super.$onInit() + super.$onInit(); if (this.mmsViewPresentationElemCtrl) { // delete is used for transclude doc, com, or section this.delete = (): void => { - this.deleteAction() - } - const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec() - const presentationElem = this.mmsViewPresentationElemCtrl.getPresentationElement() + this.deleteAction(); + }; + const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec(); + const presentationElem = this.mmsViewPresentationElemCtrl.getPresentationElement(); const isOpaque = instanceSpec.classifierIds && instanceSpec.classifierIds.length > 0 && this.schemaSvc .getMap('OPAQUE_CLASSIFIERS', this.schema) - .indexOf(instanceSpec.classifierIds[0]) >= 0 + .indexOf(instanceSpec.classifierIds[0]) >= 0; if ( !isOpaque && this.mmsElementId === (presentationElem as PresentTextObject).source && this.mmsElementId === instanceSpec.id ) { - this.isDeletable = true + this.isDeletable = true; } if (!isOpaque && this.viewSvc.isSection(instanceSpec) && this.mmsElementId === instanceSpec.id) { - this.isDeletable = true + this.isDeletable = true; } } } protected deleteAction = (): void => { if (this.elementSaving) { - this.growl.info('Please Wait...') - return + this.growl.info('Please Wait...'); + return; } - this.bbApi.toggleButtonSpinner('editor-delete') + this.bbApi.toggleButtonSpinner('editor-delete'); this.editorSvc .deleteConfirmModal(this.edit) .result.then(() => { - const section = this.mmsViewPresentationElemCtrl.getParentSection() - const instanceVal = this.mmsViewPresentationElemCtrl.getInstanceVal() - const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec() - const viewOrSec = section ? section : this.view + const section = this.mmsViewPresentationElemCtrl.getParentSection(); + const instanceVal = this.mmsViewPresentationElemCtrl.getInstanceVal(); + const instanceSpec = this.mmsViewPresentationElemCtrl.getInstanceSpec(); + const viewOrSec = section ? section : this.view; const reqOb = { elementId: viewOrSec.id, projectId: viewOrSec._projectId, refId: viewOrSec._refId, commitId: 'latest', - } + }; this.viewSvc.removeElementFromViewOrSection(reqOb, instanceVal).then( () => { // Broadcast message to TreeCtrl: - this.eventSvc.$broadcast('presentation.deleted', instanceSpec) + this.eventSvc.$broadcast('presentation.deleted', instanceSpec); - this.eventSvc.$broadcast('content-reorder.refresh') + this.eventSvc.$broadcast('content-reorder.refresh'); - this.cleanUpAction() + this.cleanUpAction(); - this.growl.success('Remove Successful') + this.growl.success('Remove Successful'); }, (reason) => this.editorSvc.handleError(reason) - ) + ); }) .finally(() => { - this.bbApi.toggleButtonSpinner('editor-delete') - }) - } + this.bbApi.toggleButtonSpinner('editor-delete'); + }); + }; } diff --git a/src/ve-components/transclusions/index.ts b/src/ve-components/transclusions/index.ts index 737e64d28..073d3e937 100644 --- a/src/ve-components/transclusions/index.ts +++ b/src/ve-components/transclusions/index.ts @@ -1,17 +1,17 @@ // import "./transclusion.controller" -export * from './transclusion.controller' -export * from './deletable-transclusion.controller' -import './services/Transclusion.service' +export * from './transclusion.controller'; +export * from './deletable-transclusion.controller'; +import './services/Transclusion.service'; -export * from './services/Transclusion.service' +export * from './services/Transclusion.service'; -import './mms-cf.component' +import './mms-cf.component'; -import './components' -import './mms-transclude-compatibility.component' +import './components'; +import './mms-transclude-compatibility.component'; -import './modals/create-transclusion.modal' +import './modals/create-transclusion.modal'; -export * from './modals/create-transclusion.modal' +export * from './modals/create-transclusion.modal'; // import "./mmsTsDiagram.directive"; diff --git a/src/ve-components/transclusions/mms-cf.component.ts b/src/ve-components/transclusions/mms-cf.component.ts index 79638bf0d..5ad134bf0 100644 --- a/src/ve-components/transclusions/mms-cf.component.ts +++ b/src/ve-components/transclusions/mms-cf.component.ts @@ -1,12 +1,12 @@ -import angular, { IComponentController } from 'angular' +import angular, { IComponentController } from 'angular'; -import { ViewController } from '@ve-components/presentations/view.component' -import { ExtensionService } from '@ve-components/services' +import { ViewController } from '@ve-components/presentations/view.component'; +import { ExtensionService } from '@ve-components/services'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions } from '@ve-types/angular' -import { RequestObject } from '@ve-types/mms' +import { VeComponentOptions } from '@ve-types/angular'; +import { RequestObject } from '@ve-types/mms'; /** * @ngdoc component @@ -28,31 +28,31 @@ import { RequestObject } from '@ve-types/mms' export class CrossReferenceController implements IComponentController { //Bindings - mmsElementId: string - mmsProjectId: string - mmsRefId: string - mmsCommitId: string - mmsCfType: string - mmsWatchId: string - nonEditable: boolean - mmsGenerateForDiff: boolean - mmsAttr: string - mmsCfLabel: boolean + mmsElementId: string; + mmsProjectId: string; + mmsRefId: string; + mmsCommitId: string; + mmsCfType: string; + mmsWatchId: string; + nonEditable: boolean; + mmsGenerateForDiff: boolean; + mmsAttr: string; + mmsCfLabel: boolean; //Deps - transclusionCtrl: CrossReferenceController - mmsViewCtrl: ViewController + transclusionCtrl: CrossReferenceController; + mmsViewCtrl: ViewController; //Local - projectId: string - refId: string - commitId: string - clearWatch: boolean = false - extType: string = 'transclusion' + projectId: string; + refId: string; + commitId: string; + clearWatch: boolean = false; + extType: string = 'transclusion'; - static $inject = ['$compile', '$scope', '$element', 'ExtensionService'] + static $inject = ['$compile', '$scope', '$element', 'ExtensionService']; - protected $transcludeEl: JQuery + protected $transcludeEl: JQuery; constructor( private $compile: angular.ICompileService, @@ -62,7 +62,7 @@ export class CrossReferenceController implements IComponentController { ) {} $onInit(): void { - this.changeAction() + this.changeAction(); } //INFO this was this.getWsAndVersion @@ -71,39 +71,39 @@ export class CrossReferenceController implements IComponentController { projectId: this.projectId, refId: this.refId, commitId: this.commitId, - } - } + }; + }; private changeAction = (): void => { - let projectId = this.mmsProjectId - let refId = this.mmsRefId - let commitId = this.mmsCommitId + let projectId = this.mmsProjectId; + let refId = this.mmsRefId; + let commitId = this.mmsCommitId; if (this.transclusionCtrl) { - const cfVersion = this.transclusionCtrl.getElementOrigin() - if (!projectId) projectId = cfVersion.projectId - if (!refId) refId = cfVersion.refId - if (!commitId) commitId = cfVersion.commitId + const cfVersion = this.transclusionCtrl.getElementOrigin(); + if (!projectId) projectId = cfVersion.projectId; + if (!refId) refId = cfVersion.refId; + if (!commitId) commitId = cfVersion.commitId; } if (this.mmsViewCtrl) { - const viewVersion = this.mmsViewCtrl.getElementOrigin() - if (!projectId) projectId = viewVersion.projectId - if (!refId) refId = viewVersion.refId - if (!commitId) commitId = viewVersion.commitId + const viewVersion = this.mmsViewCtrl.getElementOrigin(); + if (!projectId) projectId = viewVersion.projectId; + if (!refId) refId = viewVersion.refId; + if (!commitId) commitId = viewVersion.commitId; } if (!projectId) { - return + return; } - this.projectId = projectId - this.refId = refId ? refId : 'master' - this.commitId = commitId ? commitId : 'latest' + this.projectId = projectId; + this.refId = refId ? refId : 'master'; + this.commitId = commitId ? commitId : 'latest'; //this.templateElementHtml = this.$element[0].innerHTML; if (this.mmsCfType) { - this.$element.empty() - const tag = this.extensionSvc.getTagByType('transclude', this.mmsCfType) + this.$element.empty(); + const tag = this.extensionSvc.getTagByType('transclude', this.mmsCfType); if (tag === 'extension-error') { this.$transcludeEl = $( '' - ) + ); } else { this.$transcludeEl = $( '<' + @@ -114,12 +114,12 @@ export class CrossReferenceController implements IComponentController { ' mms-element-id="{{$ctrl.mmsElementId}}" mms-project-id="{{$ctrl.projectId}}" mms-ref-id="{{$ctrl.refId}}" mms-commit-id="{{$ctrl.commitId}}" non-editable="$ctrl.nonEditable">' - ) + ); } - this.$element.append(this.$transcludeEl) - this.$compile(this.$transcludeEl)(this.$scope) + this.$element.append(this.$transcludeEl); + this.$compile(this.$transcludeEl)(this.$scope); } - } + }; } const MmsCfComponent: VeComponentOptions = { @@ -143,5 +143,5 @@ const MmsCfComponent: VeComponentOptions = { mmsViewCtrl: '?^^view', }, controller: CrossReferenceController, -} -veComponents.component(MmsCfComponent.selector, MmsCfComponent) +}; +veComponents.component(MmsCfComponent.selector, MmsCfComponent); diff --git a/src/ve-components/transclusions/mms-transclude-compatibility.component.ts b/src/ve-components/transclusions/mms-transclude-compatibility.component.ts index e4ee6badc..8017f6bd0 100644 --- a/src/ve-components/transclusions/mms-transclude-compatibility.component.ts +++ b/src/ve-components/transclusions/mms-transclude-compatibility.component.ts @@ -1,13 +1,13 @@ -import { TranscludeArtComponent } from '@ve-components/transclusions/components/transclude-art.component' -import { TranscludeComComponent } from '@ve-components/transclusions/components/transclude-com.component' -import { TranscludeGroupDocsComponent } from '@ve-components/transclusions/components/transclude-group-docs.component' -import { TranscludeImgComponent } from '@ve-components/transclusions/components/transclude-img.component' -import { TranscludeValComponent } from '@ve-components/transclusions/components/transclude-val.component' +import { TranscludeArtComponent } from '@ve-components/transclusions/components/transclude-art.component'; +import { TranscludeComComponent } from '@ve-components/transclusions/components/transclude-com.component'; +import { TranscludeGroupDocsComponent } from '@ve-components/transclusions/components/transclude-group-docs.component'; +import { TranscludeImgComponent } from '@ve-components/transclusions/components/transclude-img.component'; +import { TranscludeValComponent } from '@ve-components/transclusions/components/transclude-val.component'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { TranscludeDocComponent } from './components/transclude-doc.component' -import { TranscludeNameComponent } from './components/transclude-name.component' +import { TranscludeDocComponent } from './components/transclude-doc.component'; +import { TranscludeNameComponent } from './components/transclude-name.component'; veComponents .component('mmsTranscludeDoc', TranscludeDocComponent) @@ -16,4 +16,4 @@ veComponents .component('mmsTranscludeArt', TranscludeArtComponent) .component('mmsTranscludeCom', TranscludeComComponent) .component('mmsTranscludeGroupDocs', TranscludeGroupDocsComponent) - .component('mmsTranscludeVal', TranscludeValComponent) + .component('mmsTranscludeVal', TranscludeValComponent); diff --git a/src/ve-components/transclusions/modals/create-transclusion.modal.ts b/src/ve-components/transclusions/modals/create-transclusion.modal.ts index 5434f3332..aaa9b6fe1 100644 --- a/src/ve-components/transclusions/modals/create-transclusion.modal.ts +++ b/src/ve-components/transclusions/modals/create-transclusion.modal.ts @@ -1,18 +1,18 @@ -import angular from 'angular' +import angular from 'angular'; -import { InsertionService } from '@ve-components/insertions' -import { TransclusionService } from '@ve-components/transclusions' -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { InsertionService } from '@ve-components/insertions'; +import { TransclusionService } from '@ve-components/transclusions'; +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { InsertApi, InsertData, InsertResolve } from '@ve-types/components' -import { ElementObject, ElementsResponse, TransclusionObject } from '@ve-types/mms' -import { VeModalComponent, VeModalController } from '@ve-types/view-editor' +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { InsertApi, InsertData, InsertResolve } from '@ve-types/components'; +import { ElementObject, ElementsResponse, TransclusionObject } from '@ve-types/mms'; +import { VeModalComponent, VeModalController } from '@ve-types/view-editor'; export interface InsertTransclusionData extends InsertData { - viewLink: boolean + viewLink: boolean; } class CreateTransclusionModalController @@ -33,7 +33,7 @@ class CreateTransclusionModalController -` +`; protected transclusionTemplate: string = `

    @@ -48,7 +48,7 @@ class CreateTransclusionModalController  Restrict editing
    -` +`; protected targetTemplate: string = `
    @@ -63,44 +63,44 @@ class CreateTransclusionModalController
    -` +`; protected previewTemplate: string = `
    -` +`; - protected title: string = 'Insert Cross Reference' - protected description: string - protected searchExisting: boolean = true - protected cf: TransclusionObject - protected element: ElementObject - protected requestName: boolean = false - protected requestDocumentation: boolean = false - protected viewLink: boolean - protected nonEditableCheckbox: boolean = false - protected showEditableOp: boolean = true - protected oking: boolean - protected cfType: string - protected linkType: number - protected linkText: string + protected title: string = 'Insert Cross Reference'; + protected description: string; + protected searchExisting: boolean = true; + protected cf: TransclusionObject; + protected element: ElementObject; + protected requestName: boolean = false; + protected requestDocumentation: boolean = false; + protected viewLink: boolean; + protected nonEditableCheckbox: boolean = false; + protected showEditableOp: boolean = true; + protected oking: boolean; + protected cfType: string; + protected linkType: number; + protected linkText: string; - protected insertApi: InsertApi>> - protected insertData: InsertTransclusionData - protected inserting: boolean = false - protected insertNew: boolean + protected insertApi: InsertApi>>; + protected insertData: InsertTransclusionData; + protected inserting: boolean = false; + protected insertNew: boolean; - protected projectId: string - protected refId: string - protected orgId: string + protected projectId: string; + protected refId: string; + protected orgId: string; - protected $modalBody: JQuery - protected $previewEl: JQuery = $('
    ') - private $insert: JQuery - private $target: JQuery - private $transclusion: JQuery - private $link: JQuery + protected $modalBody: JQuery; + protected $previewEl: JQuery = $('
    '); + private $insert: JQuery; + private $target: JQuery; + private $transclusion: JQuery; + private $link: JQuery; - static $inject = ['$q', '$scope', '$compile', '$element', 'growl', 'TransclusionService', 'InsertionService'] + static $inject = ['$q', '$scope', '$compile', '$element', 'growl', 'TransclusionService', 'InsertionService']; constructor( private $q: VeQService, @@ -111,116 +111,116 @@ class CreateTransclusionModalController private transclusionSvc: TransclusionService, private insertionSvc: InsertionService ) { - super() + super(); } $onInit(): void { - this.projectId = this.resolve.getProjectId - this.refId = this.resolve.getRefId ? this.resolve.getRefId : 'master' - this.orgId = this.resolve.getOrgId ? this.resolve.getOrgId : null + this.projectId = this.resolve.getProjectId; + this.refId = this.resolve.getRefId ? this.resolve.getRefId : 'master'; + this.orgId = this.resolve.getOrgId ? this.resolve.getOrgId : null; - this.$modalBody = this.$element.find('.modal-body') - this.$target = $(this.targetTemplate) - this.viewLink = this.resolve.getInsertData.viewLink + this.$modalBody = this.$element.find('.modal-body'); + this.$target = $(this.targetTemplate); + this.viewLink = this.resolve.getInsertData.viewLink; this.insertApi = { resolve: (result): void => { - this.element = result - this.insertData.selected = result - this.selectOptions() + this.element = result; + this.insertData.selected = result; + this.selectOptions(); }, reject: (reason): void => { if (reason.status !== 444) { - this.growl.error(reason.message) + this.growl.error(reason.message); } - this.element = null - this.cancel() + this.element = null; + this.cancel(); }, - } - this.insertData = this.resolve.getInsertData - this.description = 'Begin by searching for or creating an element, then click on a result.' + }; + this.insertData = this.resolve.getInsertData; + this.description = 'Begin by searching for or creating an element, then click on a result.'; if (this.insertData.viewLink) { - this.description = 'Begin by searching for a view or presentation, then click on a result.' + this.description = 'Begin by searching for a view or presentation, then click on a result.'; } //Unless Explicitly overridden, don't save a new element until transclusion is created - if (typeof this.insertData.noPublish === 'undefined') this.insertData.noPublish = true + if (typeof this.insertData.noPublish === 'undefined') this.insertData.noPublish = true; this.cf = { tag: '', - } + }; } $postLink(): void { - this.insert() + this.insert(); } public choose = (): void => { - this.oking = true + this.oking = true; - let promise: VePromise - if (this.insertData.isNew) promise = this.insertionSvc.createAction(this.element, false) - else promise = this.$q.resolve(this.element) + let promise: VePromise; + if (this.insertData.isNew) promise = this.insertionSvc.createAction(this.element, false); + else promise = this.$q.resolve(this.element); promise .then( (result) => { - this.cf.element = result + this.cf.element = result; if (!this.viewLink) { this.cf.tag = this.transclusionSvc.createTransclusion( result, this.cfType, this.nonEditableCheckbox - ) + ); } else { - this.cf.tag = this.transclusionSvc.createViewLink(result, this.linkType, this.linkText) + this.cf.tag = this.transclusionSvc.createViewLink(result, this.linkType, this.linkText); } - this.modalInstance.close(this.cf) + this.modalInstance.close(this.cf); }, (reason) => { - this.growl.error('Error: ' + reason.message) + this.growl.error('Error: ' + reason.message); } ) .finally(() => { - this.oking = false - }) - } + this.oking = false; + }); + }; public cancel = (): void => { - this.modalInstance.dismiss() - } + this.modalInstance.dismiss(); + }; public insert = (): void => { - this.inserting = true - this.$modalBody.empty() - this.$modalBody.append(this.$target) + this.inserting = true; + this.$modalBody.empty(); + this.$modalBody.append(this.$target); this.$insert = $(``) - this.$modalBody.append(this.$insert) - this.$compile(this.$modalBody)(this.$scope.$new()) - } + `); + this.$modalBody.append(this.$insert); + this.$compile(this.$modalBody)(this.$scope.$new()); + }; public selectOptions = (): void => { - this.inserting = false - this.$modalBody.empty() - this.$modalBody.append(this.$target) + this.inserting = false; + this.$modalBody.empty(); + this.$modalBody.append(this.$target); if (this.viewLink) { - this.$link = $(this.linkTemplate) - this.$modalBody.append(this.$link) + this.$link = $(this.linkTemplate); + this.$modalBody.append(this.$link); } else { - this.$transclusion = $(this.transclusionTemplate) - this.$modalBody.append(this.transclusionTemplate) + this.$transclusion = $(this.transclusionTemplate); + this.$modalBody.append(this.transclusionTemplate); } - this.$compile(this.$modalBody)(this.$scope.$new()) - } + this.$compile(this.$modalBody)(this.$scope.$new()); + }; public toggleRadio = (field: string): void => { - this.cfType = field - this.$previewEl.empty() - this.$previewEl.append($(this.previewTemplate)) + this.cfType = field; + this.$previewEl.empty(); + this.$previewEl.append($(this.previewTemplate)); this.$previewEl.append( $( `
    ${this.transclusionSvc.createTransclusion( @@ -230,10 +230,10 @@ class CreateTransclusionModalController true )}
    ` ) - ) - this.$compile(this.$previewEl)(this.$scope.$new()) - this.$modalBody.append(this.$previewEl) - } + ); + this.$compile(this.$previewEl)(this.$scope.$new()); + this.$modalBody.append(this.$previewEl); + }; } // Component for inserting cross-reference @@ -266,6 +266,6 @@ const CreateTransclusionModal: VeModalComponent = { resolve: '<', }, controller: CreateTransclusionModalController, -} +}; -veComponents.component(CreateTransclusionModal.selector, CreateTransclusionModal) +veComponents.component(CreateTransclusionModal.selector, CreateTransclusionModal); diff --git a/src/ve-components/transclusions/services/Transclusion.service.ts b/src/ve-components/transclusions/services/Transclusion.service.ts index 3abfb1ecd..ace70693b 100644 --- a/src/ve-components/transclusions/services/Transclusion.service.ts +++ b/src/ve-components/transclusions/services/Transclusion.service.ts @@ -1,14 +1,14 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { ApplicationService } from '@ve-utils/application' -import { ViewService } from '@ve-utils/mms-api-client' +import { ApplicationService } from '@ve-utils/application'; +import { ViewService } from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { ElementObject, ViewObject } from '@ve-types/mms' +import { ElementObject, ViewObject } from '@ve-types/mms'; export class TransclusionService { - static $inject = ['ApplicationService', 'ViewService'] + static $inject = ['ApplicationService', 'ViewService']; constructor(private applicationSvc: ApplicationService, private viewSvc: ViewService) {} @@ -22,41 +22,41 @@ export class TransclusionService { ${addProjectandRef ? ` mms-project-id="${element._projectId}"` : ''} ${addProjectandRef ? ` mms-ref-id="${element._refId}"` : ''} ${addProjectandRef && element._commitId ? ` mms-commit-id="${element._commitId}"` : ''} - ${nonEditable ? ' non-editable="true"' : ''}>[cf:${element.name}.${cfType}]` - } + ${nonEditable ? ' non-editable="true"' : ''}>[cf:${element.name}.${cfType}]`; + }; public createViewLink = (elem: ViewObject, linkType: number, linkText?: string): string => { - let did: string - let vid: string - let peid: string - const currentDoc = this.applicationSvc.getState().currentDoc + let did: string; + let vid: string; + let peid: string; + const currentDoc = this.applicationSvc.getState().currentDoc; if (elem._relatedDocuments && elem._relatedDocuments.length > 0) { const cur = _.find(elem._relatedDocuments, { id: currentDoc, - }) + }); if (cur) { - did = currentDoc + did = currentDoc; if (cur._parentViews.length > 0) { - vid = cur._parentViews[0].id + vid = cur._parentViews[0].id; } } else { - did = elem._relatedDocuments[0].id + did = elem._relatedDocuments[0].id; if (elem._relatedDocuments[0]._parentViews.length > 0) { - vid = elem._relatedDocuments[0]._parentViews[0].id + vid = elem._relatedDocuments[0]._parentViews[0].id; } } } if (elem.type === 'InstanceSpecification') { if (this.viewSvc.isSection(elem)) { - vid = elem.id + vid = elem.id; } else { - peid = elem.id + peid = elem.id; } } else { - vid = elem.id + vid = elem.id; } - return this.getLink(elem, did, vid, peid, linkType, linkText) - } + return this.getLink(elem, did, vid, peid, linkType, linkText); + }; public getLink = ( elem: ElementObject, @@ -66,34 +66,34 @@ export class TransclusionService { linkType: number, linkText?: string ): string => { - let tag = '' - return tag - } + tag += '>[cf:' + elem.name + '.vlink]'; + return tag; + }; } -veComponents.service('TransclusionService', TransclusionService) +veComponents.service('TransclusionService', TransclusionService); diff --git a/src/ve-components/transclusions/transclusion.controller.ts b/src/ve-components/transclusions/transclusion.controller.ts index 9c30d3b98..24438e341 100644 --- a/src/ve-components/transclusions/transclusion.controller.ts +++ b/src/ve-components/transclusions/transclusion.controller.ts @@ -1,58 +1,58 @@ -import { IPaneScope } from '@openmbee/pane-layout' -import $ from 'jquery' - -import { ViewPresentationElemController } from '@ve-components/presentations' -import { ViewController } from '@ve-components/presentations/view.component' -import { ComponentService, ExtensionService } from '@ve-components/services' -import { SpecTool } from '@ve-components/spec-tools' -import { ButtonBarApi, ButtonBarService, IButtonBarButton } from '@ve-core/button-bar' -import { EditorService } from '@ve-core/editor' -import { veCoreEvents } from '@ve-core/events' -import { ImageService, MathService, UtilsService } from '@ve-utils/application' -import { EditObject, EditService, EventService } from '@ve-utils/core' -import { ElementService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' -import { handleChange, onChangesCallback } from '@ve-utils/utils' - -import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { EditorActions } from '@ve-types/core/editor' -import { ElementObject, ElementsResponse, ViewObject } from '@ve-types/mms' +import { IPaneScope } from '@openmbee/pane-layout'; +import $ from 'jquery'; + +import { ViewPresentationElemController } from '@ve-components/presentations'; +import { ViewController } from '@ve-components/presentations/view.component'; +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { SpecTool } from '@ve-components/spec-tools'; +import { ButtonBarApi, ButtonBarService, IButtonBarButton } from '@ve-core/button-bar'; +import { EditorService } from '@ve-core/editor'; +import { veCoreEvents } from '@ve-core/events'; +import { ImageService, MathService, UtilsService } from '@ve-utils/application'; +import { EditObject, EditService, EventService } from '@ve-utils/core'; +import { ElementService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; +import { handleChange, onChangesCallback } from '@ve-utils/utils'; + +import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { EditorActions } from '@ve-types/core/editor'; +import { ElementObject, ElementsResponse, ViewObject } from '@ve-types/mms'; export interface ITransclusion extends angular.IComponentController { - $scope: TranscludeScope - mmsElementId: string - mmsProjectId: string - mmsRefId: string - commitId: string - cfType: string - edit: EditObject - element: ElementObject - isEditing: boolean - inPreviewMode: boolean - skipBroadcast: boolean - recompileScope?: TranscludeScope + $scope: TranscludeScope; + mmsElementId: string; + mmsProjectId: string; + mmsRefId: string; + commitId: string; + cfType: string; + edit: EditObject; + element: ElementObject; + isEditing: boolean; + inPreviewMode: boolean; + skipBroadcast: boolean; + recompileScope?: TranscludeScope; } export interface ITransclusionComponentOptions extends VeComponentOptions { - bindings: TranscludeDefaultBindings + bindings: TranscludeDefaultBindings; } interface TranscludeDefaultBindings { - mmsElementId: '@' - mmsProjectId: '@' - mmsRefId: '@' - mmsCommitId: '@' - mmsWatchId: '<' - mmsCfLabel: '@' - mmsGenerateForDiff?: '<' - noClick?: '<' - nonEditable?: '<' - [key: string]: string + mmsElementId: '@'; + mmsProjectId: '@'; + mmsRefId: '@'; + mmsCommitId: '@'; + mmsWatchId: '<'; + mmsCfLabel: '@'; + mmsGenerateForDiff?: '<'; + noClick?: '<'; + nonEditable?: '<'; + [key: string]: string; } export interface TranscludeScope extends IPaneScope { - $ctrl?: ITransclusion - $parent: TranscludeScope + $ctrl?: ITransclusion; + $parent: TranscludeScope; } /** @@ -91,81 +91,81 @@ export interface TranscludeScope extends IPaneScope { */ export class Transclusion implements ITransclusion, EditorActions { //Regex - fixPreSpanRegex: RegExp = /<\/span>\s*\s*]*>/g - emptyRegex: RegExp = /^\s*$/ - spacePeriod: RegExp = />(?:\s| )\./g - spaceSpace: RegExp = />(?:\s| )(?:\s| )/g - spaceComma: RegExp = />(?:\s| ),/g + fixPreSpanRegex: RegExp = /<\/span>\s*\s*]*>/g; + emptyRegex: RegExp = /^\s*$/; + spacePeriod: RegExp = />(?:\s| )\./g; + spaceSpace: RegExp = />(?:\s| )(?:\s| )/g; + spaceComma: RegExp = />(?:\s| ),/g; //Required Controllers - protected mmsViewCtrl: ViewController - protected mmsViewPresentationElemCtrl: ViewPresentationElemController - protected mmsSpecEditorCtrl: SpecTool + protected mmsViewCtrl: ViewController; + protected mmsViewPresentationElemCtrl: ViewPresentationElemController; + protected mmsSpecEditorCtrl: SpecTool; //Bindings - mmsElementId: string - mmsProjectId: string - mmsRefId: string - mmsCommitId: string - mmsWatchId: string - nonEditable: boolean - noClick: boolean - mmsCfLabel: boolean - mmsGenerateForDiff: boolean - mmsCallback: () => void + mmsElementId: string; + mmsProjectId: string; + mmsRefId: string; + mmsCommitId: string; + mmsWatchId: string; + nonEditable: boolean; + noClick: boolean; + mmsCfLabel: boolean; + mmsGenerateForDiff: boolean; + mmsCallback: () => void; //Customizers - public cfType: string - protected cfTitle: string - protected cfField: 'name' | 'value' | 'documentation' - protected cfKind: string - protected checkCircular: boolean - protected noCompile: boolean = false + public cfType: string; + protected cfTitle: string; + protected cfField: 'name' | 'value' | 'documentation'; + protected cfKind: string; + protected checkCircular: boolean; + protected noCompile: boolean = false; //Locals - protected isDeletable: boolean - protected editable: () => boolean = () => false + protected isDeletable: boolean; + protected editable: () => boolean = () => false; - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; - public commitId: string - protected projectId: string - protected refId: string + public commitId: string; + protected projectId: string; + protected refId: string; - public isEditing: boolean = false - public inPreviewMode: boolean = false - public elementSaving: boolean = false - public editLoading: boolean = false - public skipBroadcast: boolean + public isEditing: boolean = false; + public inPreviewMode: boolean = false; + public elementSaving: boolean = false; + public editLoading: boolean = false; + public skipBroadcast: boolean; - public editKey: string | string[] - public edit: EditObject - public element: ElementObject - protected type: string = '' - protected editorType: string + public editKey: string | string[]; + public edit: EditObject; + public element: ElementObject; + protected type: string = ''; + protected editorType: string; - public view: ViewObject + public view: ViewObject; // public instanceSpec: InstanceSpecObject // public instanceVal: InstanceValueObject // protected presentationElem: PresentationInstanceObject | ElementObject - protected panelTitle: string - protected panelType: string + protected panelTitle: string; + protected panelType: string; - protected $transcludeEl: JQuery + protected $transcludeEl: JQuery; // Possible templates to manage api functions - protected template: string - protected editTemplate: string - protected previewTemplate: string + protected template: string; + protected editTemplate: string; + protected previewTemplate: string; - public bbApi: ButtonBarApi - public bbId: string - public bars: string[] - protected buttons: IButtonBarButton[] = [] + public bbApi: ButtonBarApi; + public bbId: string; + public bars: string[]; + protected buttons: IButtonBarButton[] = []; - public schema = 'cameo' + public schema = 'cameo'; //Default Toolbar Api /* eslint-disable @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars */ @@ -194,7 +194,7 @@ export class Transclusion implements ITransclusion, EditorActions { 'ExtensionService', 'ButtonBarService', 'ImageService', - ] + ]; constructor( public $q: VeQService, @@ -216,60 +216,60 @@ export class Transclusion implements ITransclusion, EditorActions { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); if ((this.$element.prop('tagName') as string).includes('mms')) { this.growl.warning( 'mmsTransclude(*) Syntax is deprecated and will be removed in a future version' + 'please see the release documentation for further details' - ) + ); } if (this.mmsViewCtrl) { - this.view = this.mmsViewCtrl.getView() - this.editable = this.mmsViewCtrl.isEditable + this.view = this.mmsViewCtrl.getView(); + this.editable = this.mmsViewCtrl.isEditable; } if (this.mmsSpecEditorCtrl && this.mmsSpecEditorCtrl.specApi.elementId === this.mmsElementId) { - this.editable = (): boolean => this.mmsSpecEditorCtrl.specSvc.editable + this.editable = (): boolean => this.mmsSpecEditorCtrl.specSvc.editable; } //if (this.editTemplate) { this.save = (e: JQuery.ClickEvent): void => { - if (e) e.stopPropagation() - this.saveAction(false) - } + if (e) e.stopPropagation(); + this.saveAction(false); + }; this.saveC = (): void => { - this.saveAction(true) - } + this.saveAction(true); + }; this.cancel = (e?: JQuery.ClickEvent): void => { - if (e) e.stopPropagation() - this.cancelAction() - } + if (e) e.stopPropagation(); + this.cancelAction(); + }; this.reset = (e?: JQuery.ClickEvent): void => { - if (e) e.stopPropagation() - this.cleanUpAction(true) - } + if (e) e.stopPropagation(); + this.cleanUpAction(true); + }; this.preview = (): void => { - this.previewAction() - } + this.previewAction(); + }; //} } $onDestroy(): void { - this.eventSvc.destroy(this.subs) + this.eventSvc.destroy(this.subs); } $onChanges(onChangesObj: angular.IOnChangesObject): void { - this.watch(onChangesObj) - handleChange(onChangesObj, 'mmsElementId', this.changeAction) - handleChange(onChangesObj, 'mmsRefId', this.changeAction) - handleChange(onChangesObj, 'mmsCommitId', this.changeAction) + this.watch(onChangesObj); + handleChange(onChangesObj, 'mmsElementId', this.changeAction); + handleChange(onChangesObj, 'mmsRefId', this.changeAction); + handleChange(onChangesObj, 'mmsCommitId', this.changeAction); } $postLink(): void { - this.changeAction(this.mmsElementId, '', false) + this.changeAction(this.mmsElementId, '', false); } /** @@ -282,7 +282,7 @@ export class Transclusion implements ITransclusion, EditorActions { */ protected watch: (onChangesObj: angular.IOnChangesObject) => void = () => { /* Implement custom watch logic here */ - } + }; /** * @name veComponents/Transclusion#config @@ -291,113 +291,113 @@ export class Transclusion implements ITransclusion, EditorActions { */ protected destroy: () => void = () => { /* Implement Custom Destroy Logic Here */ - } + }; public getContent = (preview?: boolean): VePromise => { - return this.$q.resolve('Not Yet Implemented') - } + return this.$q.resolve('Not Yet Implemented'); + }; protected recompile = (preview?: boolean): void => { - this.defaultRecompile(preview) - } + this.defaultRecompile(preview); + }; public defaultRecompile = (preview?: boolean): void => { this.getContent(preview).then( (result) => { - this.$element.empty() - this.$transcludeEl = $(result) - this.$element.append(this.$transcludeEl) - this.$compile(this.$transcludeEl)(this.$scope.$new()) + this.$element.empty(); + this.$transcludeEl = $(result); + this.$element.append(this.$transcludeEl); + this.$compile(this.$transcludeEl)(this.$scope.$new()); if (this.mmsViewCtrl) { - this.mmsViewCtrl.elementTranscluded(this.element, this.type) + this.mmsViewCtrl.elementTranscluded(this.element, this.type); } $(this.$element) .find('img') .each((index, element) => { - this.imageSvc.fixImgSrc($(element)) - }) + this.imageSvc.fixImgSrc($(element)); + }); }, (reason) => { if (reason.status !== 200) { - this.growl.error(`Transclusion Error: ${reason.message}`) + this.growl.error(`Transclusion Error: ${reason.message}`); } } - ) - } + ); + }; protected changeAction: onChangesCallback = (newVal, oldVal, firstChange) => { if (!newVal || !this.mmsProjectId || firstChange || newVal === oldVal) { - return + return; } if (this.checkCircular) { if (this.componentSvc.hasCircularReference(this, this.mmsElementId, 'doc')) { - this.$element.html('Circular Reference!') - return + this.$element.html('Circular Reference!'); + return; } } - this.projectId = this.mmsProjectId - this.refId = this.mmsRefId ? this.mmsRefId : 'master' - this.commitId = this.mmsCommitId ? this.mmsCommitId : 'latest' + this.projectId = this.mmsProjectId; + this.refId = this.mmsRefId ? this.mmsRefId : 'master'; + this.commitId = this.mmsCommitId ? this.mmsCommitId : 'latest'; if (!this.noCompile) { - this.$element.html('(loading...)') + this.$element.html('(loading...)'); } - this.$element.addClass('isLoading') + this.$element.addClass('isLoading'); const reqOb = { elementId: this.mmsElementId, projectId: this.projectId, refId: this.refId, commitId: this.commitId, //includeRecentVersionElement: true, - } + }; this.elementSvc .getElement(reqOb, 1, false) .then( (data) => { - this.element = data + this.element = data; if (!this.panelTitle) { - this.panelTitle = this.element.name + ' ' + this.cfTitle - this.panelType = this.cfKind + this.panelTitle = this.element.name + ' ' + this.cfTitle; + this.panelType = this.cfKind; } if (this.commitId === 'latest') { this.subs.push( this.eventSvc.$on( 'element.updated', (data: { element: ElementObject; continueEdit: boolean }) => { - const elementOb = data.element - const continueEdit = data.continueEdit + const elementOb = data.element; + const continueEdit = data.continueEdit; if ( elementOb.id === this.element.id && elementOb._projectId === this.element._projectId && elementOb._refId === this.element._refId ) { - this.element = elementOb - this.cleanUpAction(continueEdit) + this.element = elementOb; + this.cleanUpAction(continueEdit); } } ) - ) + ); } if (this.editTemplate) { this._reopenUnsaved().then( (data) => { - if (data) this.startEdit() - else this.recompile() + if (data) this.startEdit(); + else this.recompile(); }, () => { - this.recompile() + this.recompile(); } - ) + ); } else { - this.recompile() + this.recompile(); } }, (reason) => { - this.$element.empty() + this.$element.empty(); //TODO: Add reason/errorMessage handling here. this.$transcludeEl = $( '' - ) - this.$element.append(this.$transcludeEl) + ); + this.$element.append(this.$transcludeEl); this.$compile(this.$transcludeEl)( Object.assign(this.$scope.$new(), { elementId: reqOb, @@ -405,24 +405,24 @@ export class Transclusion implements ITransclusion, EditorActions { type: 'transclusion', field: this.cfField, }) - ) + ); } ) .finally(() => { - this.$element.removeClass('isLoading') - if (this.mmsCallback) this.mmsCallback() - }) - } + this.$element.removeClass('isLoading'); + if (this.mmsCallback) this.mmsCallback(); + }); + }; protected bbInit = (api: ButtonBarApi): void => { - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-preview', this)) - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-save', this)) - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-save-continue', this)) - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-cancel', this)) - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-reset', this)) - api.addButton(this.buttonBarSvc.getButtonBarButton('editor-delete', this)) - api.setPermission('editor-delete', this.isDeletable) - } + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-preview', this)); + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-save', this)); + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-save-continue', this)); + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-cancel', this)); + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-reset', this)); + api.addButton(this.buttonBarSvc.getButtonBarButton('editor-delete', this)); + api.setPermission('editor-delete', this.isDeletable); + }; /** * @name Utils#reopenUnsavedElts * called by transcludes when users have unsaved edits, leaves that view, and comes back to that view. @@ -437,15 +437,15 @@ export class Transclusion implements ITransclusion, EditorActions { */ private _reopenUnsaved = (): VePromise => { return new this.$q((resolve, reject) => { - const key = this.elementSvc.getEditElementKey(this.element) - const editOb = this.editSvc.get(key) + const key = this.elementSvc.getEditElementKey(this.element); + const editOb = this.editSvc.get(key); if (!editOb || this.commitId !== 'latest') { - resolve(false) + resolve(false); } else { - this.editorSvc.hasEdits(editOb, this.cfField).then(resolve, reject) + this.editorSvc.hasEdits(editOb, this.cfField).then(resolve, reject); } - }) - } + }); + }; /** * @name Transclusion#startEdit * called by transcludes to add the editor frame @@ -469,105 +469,105 @@ export class Transclusion implements ITransclusion, EditorActions { .openEdit(this.element) .then( (data) => { - this.isEditing = true + this.isEditing = true; if (this.inPreviewMode) { - this.editorSvc.clearAutosave(this.editKey, this.cfField) - this.inPreviewMode = false + this.editorSvc.clearAutosave(this.editKey, this.cfField); + this.inPreviewMode = false; } - this.edit = data - this.editKey = data.key + this.edit = data; + this.editKey = data.key; if (cb) { - cb() + cb(); } if (this.editTemplate) { - this.$element.empty() - this.$transcludeEl = $(this.editTemplate) + this.$element.empty(); + this.$transcludeEl = $(this.editTemplate); - this.$element.append(this.$transcludeEl) - this.$compile(this.$transcludeEl)(this.$scope.$new()) + this.$element.append(this.$transcludeEl); + this.$compile(this.$transcludeEl)(this.$scope.$new()); } if (!this.skipBroadcast) { // Broadcast message for the toolCtrl: - this.eventSvc.$broadcast('editor.open', this.edit) + this.eventSvc.$broadcast('editor.open', this.edit); } else { - this.skipBroadcast = false + this.skipBroadcast = false; } - this.editorSvc.scrollToElement(this.$element) + this.editorSvc.scrollToElement(this.$element); }, (reason: VePromiseReason>) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } ) .finally(() => { - this.editLoading = false - }) + this.editLoading = false; + }); this.elementSvc.isCacheOutdated(this.element).then( (data) => { if (data.status && data.server._modified > data.cache._modified) { - this.growl.warning('This element has been updated on the server') + this.growl.warning('This element has been updated on the server'); } }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); } } protected saveAction(continueEdit?: boolean): void { if (this.elementSaving) { - this.growl.info('Please Wait...') - return + this.growl.info('Please Wait...'); + return; } // this.editSvc.clearAutosave(ctrl.element._projectId + ctrl.element._refId + ctrl.element.id, ctrl.edit.type) if (this.bbApi) { if (!continueEdit) { - this.bbApi.toggleButtonSpinner('editor-save') + this.bbApi.toggleButtonSpinner('editor-save'); } else { - this.bbApi.toggleButtonSpinner('editor-save-continue') + this.bbApi.toggleButtonSpinner('editor-save-continue'); } } - this.elementSaving = true + this.elementSaving = true; this.editorSvc .save(this.editKey, continueEdit) .then( (data) => { - this.inPreviewMode = false - this.element = data + this.inPreviewMode = false; + this.element = data; // do not call here since it's called by element.updated event listener //this.cleanUpAction(continueEdit) //scrollToElement(domElement); }, (reason) => { - this.editorSvc.handleError(reason) + this.editorSvc.handleError(reason); } ) .finally(() => { - this.elementSaving = false + this.elementSaving = false; if (this.bbApi) { if (!continueEdit) { - this.bbApi.toggleButtonSpinner('editor-save') + this.bbApi.toggleButtonSpinner('editor-save'); } else { - this.bbApi.toggleButtonSpinner('editor-save-continue') + this.bbApi.toggleButtonSpinner('editor-save-continue'); } } - }) + }); } protected cancelAction(): void { if (this.elementSaving) { - this.growl.info('Please Wait...') - return + this.growl.info('Please Wait...'); + return; } if (this.bbApi) { - this.bbApi.toggleButtonSpinner('editor-cancel') + this.bbApi.toggleButtonSpinner('editor-cancel'); } // const cancelFn: () => VePromise = (): VePromise => { // if (ctrl.editorApi && ctrl.editorApi.cancel) { @@ -585,7 +585,7 @@ export class Transclusion implements ITransclusion, EditorActions { this.editorSvc.handleError({ message: 'Problem Saving from Editor', type: 'warning', - }) + }); } this.editorSvc.hasEdits(this.edit, this.cfField).then( (hasEdits) => { @@ -593,86 +593,86 @@ export class Transclusion implements ITransclusion, EditorActions { this.editorSvc.deleteEditModal(this.edit).result.then( (result) => { if (result) { - this.cleanUpAction() + this.cleanUpAction(); } }, () => { //Do Nothing if user wants to keep working } - ) + ); } else { - this.cleanUpAction() + this.cleanUpAction(); } }, () => { - this.cleanUpAction() + this.cleanUpAction(); } - ) + ); }, () => { this.editorSvc.handleError({ message: 'Error Saving from Editor; Please Retry', type: 'error', - }) + }); } ) .finally(() => { if (this.bbApi) { - this.bbApi.toggleButtonSpinner('editor-cancel') + this.bbApi.toggleButtonSpinner('editor-cancel'); } - }) + }); } public previewAction(): void { if (this.elementSaving) { - this.growl.info('Please Wait...') - return + this.growl.info('Please Wait...'); + return; } if (this.edit && this.isEditing) { this.editorSvc .hasEdits(this.edit) .then((hasEdits) => { if (hasEdits && !this.inPreviewMode) { - this.skipBroadcast = true //preview next click to go into edit mode from broadcasting - this.inPreviewMode = true - this.recompile(true) + this.skipBroadcast = true; //preview next click to go into edit mode from broadcasting + this.inPreviewMode = true; + this.recompile(true); } else { //nothing has changed, cancel instead of preview - this.growl.info('No edits found! Preview cancelled') - this.cleanUpAction() + this.growl.info('No edits found! Preview cancelled'); + this.cleanUpAction(); } }) .finally(() => { - this.isEditing = false - this.editorSvc.scrollToElement(this.$element) - }) + this.isEditing = false; + this.editorSvc.scrollToElement(this.$element); + }); } } public cleanUpAction = (continueEdit?: boolean): void => { - this.editorSvc.cleanUpEdit(this.editKey) - this.isEditing = false + this.editorSvc.cleanUpEdit(this.editKey); + this.isEditing = false; if (!continueEdit) { - this.eventSvc.$broadcast('editor.close', this.edit) - this.recompile() + this.eventSvc.$broadcast('editor.close', this.edit); + this.recompile(); } else { - this.startEdit() + this.startEdit(); } // scrollToElement(domElement); - } + }; //Transclusion API protected hasHtml = (s: string): boolean => { - return this.componentSvc.hasHtml(s) - } + return this.componentSvc.hasHtml(s); + }; protected cleanupVal(obj: { value: string | number }): void { - obj.value = parseInt(obj.value as string) + obj.value = parseInt(obj.value as string); } protected addHtml(e: JQueryEventObject, value: { value: string | number }): void { - e.stopPropagation() - value.value = `

    ${value.value}

    ` + e.stopPropagation(); + value.value = `

    ${value.value}

    `; } } diff --git a/src/ve-components/trees/components/index.ts b/src/ve-components/trees/components/index.ts index 5986fae2c..60e4d42b8 100644 --- a/src/ve-components/trees/components/index.ts +++ b/src/ve-components/trees/components/index.ts @@ -1,6 +1,6 @@ -import './tree-of-contents.component' -import './tree-of-equations.component' -import './tree-of-figures.component' -import './tree-of-tables.component' -import './tree-of-documents.component' -import './tree-of-favorites.component' +import './tree-of-contents.component'; +import './tree-of-equations.component'; +import './tree-of-figures.component'; +import './tree-of-tables.component'; +import './tree-of-documents.component'; +import './tree-of-favorites.component'; diff --git a/src/ve-components/trees/components/tree-of-contents.component.ts b/src/ve-components/trees/components/tree-of-contents.component.ts index 1a2f71d35..41825415d 100644 --- a/src/ve-components/trees/components/tree-of-contents.component.ts +++ b/src/ve-components/trees/components/tree-of-contents.component.ts @@ -1,12 +1,12 @@ -import angular from 'angular' +import angular from 'angular'; -import { TreeService, TreeController } from '@ve-components/trees' -import { RootScopeService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { TreeService, TreeController } from '@ve-components/trees'; +import { RootScopeService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VeQService } from '@ve-types/angular'; export class TreeOfContentsController extends TreeController { constructor( @@ -20,20 +20,20 @@ export class TreeOfContentsController extends TreeController { rootScopeSvc: RootScopeService, eventSvc: EventService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); - this.types = ['view', 'section'] - this.id = 'tree-of-contents' + this.types = ['view', 'section']; + this.id = 'tree-of-contents'; } protected setPeVisibility = (): void => { - this.types.length = 0 + this.types.length = 0; if (this.showPe) { - this.types.push('all') + this.types.push('all'); } else { - this.types = ['view', 'section'] + this.types = ['view', 'section']; } - } + }; } const TreeOfContentsComponent: VeComponentOptions = { @@ -70,6 +70,6 @@ const TreeOfContentsComponent: VeComponentOptions = { showPe: '<', }, controller: TreeOfContentsController, -} +}; -veComponents.component(TreeOfContentsComponent.selector, TreeOfContentsComponent) +veComponents.component(TreeOfContentsComponent.selector, TreeOfContentsComponent); diff --git a/src/ve-components/trees/components/tree-of-documents.component.ts b/src/ve-components/trees/components/tree-of-documents.component.ts index 32c14c958..dab4808ad 100644 --- a/src/ve-components/trees/components/tree-of-documents.component.ts +++ b/src/ve-components/trees/components/tree-of-documents.component.ts @@ -1,14 +1,14 @@ -import { TreeService, TreeController } from '@ve-components/trees' -import { ApplicationService, RootScopeService, UserSettingsObject, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { TreeService, TreeController } from '@ve-components/trees'; +import { ApplicationService, RootScopeService, UserSettingsObject, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { TreeBranch } from '@ve-types/tree' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { TreeBranch } from '@ve-types/tree'; class TreeOfDocumentsController extends TreeController { - static $inject = [...TreeController.$inject, 'ApplicationService'] + static $inject = [...TreeController.$inject, 'ApplicationService']; constructor( $q: VeQService, $scope: angular.IScope, @@ -21,48 +21,48 @@ class TreeOfDocumentsController extends TreeController { eventSvc: EventService, private applicationSvc: ApplicationService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) - this.id = 'tree-of-documents' - this.types = ['group'] + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); + this.id = 'tree-of-documents'; + this.types = ['group']; } protected preConfig = (): void => { - this.types = ['group'] + this.types = ['group']; if (this.treeSvc.treeApi.refType === 'Branch') { - this.types.push('view') + this.types.push('view'); } else { - this.types.push('snapshot') + this.types.push('snapshot'); } - } + }; toggleFavorite($event: JQuery.ClickEvent, branch: TreeBranch): void { - $event.stopPropagation() - let promise: VePromise + $event.stopPropagation(); + let promise: VePromise; if (!branch.favorite) { promise = this.applicationSvc.addPins( this.applicationSvc.getState().user, this.treeSvc.treeApi.projectId, this.treeSvc.treeApi.refId, [branch.data.id] - ) + ); } else { promise = this.applicationSvc.removePins( this.applicationSvc.getState().user, this.treeSvc.treeApi.projectId, this.treeSvc.treeApi.refId, [branch.data.id] - ) + ); } promise.then( () => { - branch.favorite = !branch.favorite - this.eventSvc.$broadcast(TreeService.events.RELOAD, 'table-of-favorites') + branch.favorite = !branch.favorite; + this.eventSvc.$broadcast(TreeService.events.RELOAD, 'table-of-favorites'); }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); } } @@ -101,6 +101,6 @@ const TreeOfDocumentsComponent: VeComponentOptions = { buttonId: '@', }, controller: TreeOfDocumentsController, -} +}; -veComponents.component(TreeOfDocumentsComponent.selector, TreeOfDocumentsComponent) +veComponents.component(TreeOfDocumentsComponent.selector, TreeOfDocumentsComponent); diff --git a/src/ve-components/trees/components/tree-of-equations.component.ts b/src/ve-components/trees/components/tree-of-equations.component.ts index b6051aecb..ff952cad4 100644 --- a/src/ve-components/trees/components/tree-of-equations.component.ts +++ b/src/ve-components/trees/components/tree-of-equations.component.ts @@ -1,12 +1,12 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees' -import { RootScopeService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees'; +import { RootScopeService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeQService } from '@ve-types/angular' +import { VeQService } from '@ve-types/angular'; class TreeOfEquationsController extends TreeController { constructor( @@ -20,15 +20,15 @@ class TreeOfEquationsController extends TreeController { rootScopeSvc: RootScopeService, eventSvc: EventService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) - this.id = 'table-of-equations' - this.types = ['equation'] - this.title = 'Table of Equations' + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); + this.id = 'table-of-equations'; + this.types = ['equation']; + this.title = 'Table of Equations'; } } -const TreeOfEquationsComponent = _.cloneDeep(TreeOfAnyComponent) -TreeOfEquationsComponent.selector = 'treeOfEquations' -TreeOfEquationsComponent.controller = TreeOfEquationsController +const TreeOfEquationsComponent = _.cloneDeep(TreeOfAnyComponent); +TreeOfEquationsComponent.selector = 'treeOfEquations'; +TreeOfEquationsComponent.controller = TreeOfEquationsController; -veComponents.component(TreeOfEquationsComponent.selector, TreeOfEquationsComponent) +veComponents.component(TreeOfEquationsComponent.selector, TreeOfEquationsComponent); diff --git a/src/ve-components/trees/components/tree-of-favorites.component.ts b/src/ve-components/trees/components/tree-of-favorites.component.ts index 0e022f204..c2286cd73 100644 --- a/src/ve-components/trees/components/tree-of-favorites.component.ts +++ b/src/ve-components/trees/components/tree-of-favorites.component.ts @@ -1,19 +1,19 @@ -import { TreeService, TreeController } from '@ve-components/trees' -import { ApplicationService, RootScopeService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { TreeService, TreeController } from '@ve-components/trees'; +import { ApplicationService, RootScopeService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VeQService } from '@ve-types/angular'; class TreeOfFavoritesController extends TreeController { public icons = { iconExpand: 'fa-solid fa-caret-down fa-lg fa-fw', iconCollapse: 'fa-solid fa-caret-right fa-lg fa-fw', iconDefault: 'fa-solid fa-star fa-fw', - } + }; - static $inject = [...TreeController.$inject, 'ApplicationService'] + static $inject = [...TreeController.$inject, 'ApplicationService']; constructor( $q: VeQService, @@ -27,10 +27,10 @@ class TreeOfFavoritesController extends TreeController { eventSvc: EventService, private applicationSvc: ApplicationService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) - this.id = 'table-of-favorites' - this.types = ['favorite'] - this.title = 'Table of Favorites' + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); + this.id = 'table-of-favorites'; + this.types = ['favorite']; + this.title = 'Table of Favorites'; } } @@ -64,6 +64,6 @@ const TreeOfFavoritesComponent: VeComponentOptions = { showPe: '<', }, controller: TreeOfFavoritesController, -} +}; -veComponents.component(TreeOfFavoritesComponent.selector, TreeOfFavoritesComponent) +veComponents.component(TreeOfFavoritesComponent.selector, TreeOfFavoritesComponent); diff --git a/src/ve-components/trees/components/tree-of-figures.component.ts b/src/ve-components/trees/components/tree-of-figures.component.ts index d2eb45dcc..62dfae2f2 100644 --- a/src/ve-components/trees/components/tree-of-figures.component.ts +++ b/src/ve-components/trees/components/tree-of-figures.component.ts @@ -1,12 +1,12 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees' -import { RootScopeService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees'; +import { RootScopeService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeQService } from '@ve-types/angular' +import { VeQService } from '@ve-types/angular'; class TreeOfFiguresController extends TreeController { constructor( @@ -20,15 +20,15 @@ class TreeOfFiguresController extends TreeController { rootScopeSvc: RootScopeService, eventSvc: EventService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) - this.id = 'table-of-figures' - this.types = ['figure'] - this.title = 'Table of Figures' + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); + this.id = 'table-of-figures'; + this.types = ['figure']; + this.title = 'Table of Figures'; } } -const TreeOfFiguresComponent = _.cloneDeep(TreeOfAnyComponent) -TreeOfFiguresComponent.selector = 'treeOfFigures' -TreeOfFiguresComponent.controller = TreeOfFiguresController +const TreeOfFiguresComponent = _.cloneDeep(TreeOfAnyComponent); +TreeOfFiguresComponent.selector = 'treeOfFigures'; +TreeOfFiguresComponent.controller = TreeOfFiguresController; -veComponents.component(TreeOfFiguresComponent.selector, TreeOfFiguresComponent) +veComponents.component(TreeOfFiguresComponent.selector, TreeOfFiguresComponent); diff --git a/src/ve-components/trees/components/tree-of-tables.component.ts b/src/ve-components/trees/components/tree-of-tables.component.ts index e80636054..9c6882df8 100644 --- a/src/ve-components/trees/components/tree-of-tables.component.ts +++ b/src/ve-components/trees/components/tree-of-tables.component.ts @@ -1,12 +1,12 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees' -import { RootScopeService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { TreeService, TreeController, TreeOfAnyComponent } from '@ve-components/trees'; +import { RootScopeService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeQService } from '@ve-types/angular' +import { VeQService } from '@ve-types/angular'; class TreeOfTablesController extends TreeController { constructor( @@ -20,15 +20,15 @@ class TreeOfTablesController extends TreeController { rootScopeSvc: RootScopeService, eventSvc: EventService ) { - super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc) - this.id = 'table-of-tables' - this.types = ['table'] - this.title = 'Table of Tables' + super($q, $scope, $timeout, $filter, growl, utilsSvc, treeSvc, rootScopeSvc, eventSvc); + this.id = 'table-of-tables'; + this.types = ['table']; + this.title = 'Table of Tables'; } } -const TreeOfTablesComponent = _.cloneDeep(TreeOfAnyComponent) -TreeOfTablesComponent.selector = 'treeOfTables' -TreeOfTablesComponent.controller = TreeOfTablesController +const TreeOfTablesComponent = _.cloneDeep(TreeOfAnyComponent); +TreeOfTablesComponent.selector = 'treeOfTables'; +TreeOfTablesComponent.controller = TreeOfTablesController; -veComponents.component(TreeOfTablesComponent.selector, TreeOfTablesComponent) +veComponents.component(TreeOfTablesComponent.selector, TreeOfTablesComponent); diff --git a/src/ve-components/trees/index.ts b/src/ve-components/trees/index.ts index 9a9576cd1..7d143f562 100644 --- a/src/ve-components/trees/index.ts +++ b/src/ve-components/trees/index.ts @@ -1,8 +1,8 @@ -import './services/Tree.service' +import './services/Tree.service'; -export * from './services/Tree.service' +export * from './services/Tree.service'; -export * from './tree.controller' +export * from './tree.controller'; //Components -import './mms-trees.component' -import './components' +import './mms-trees.component'; +import './components'; diff --git a/src/ve-components/trees/mms-trees.component.ts b/src/ve-components/trees/mms-trees.component.ts index 978300896..9f2899ec1 100644 --- a/src/ve-components/trees/mms-trees.component.ts +++ b/src/ve-components/trees/mms-trees.component.ts @@ -1,25 +1,25 @@ -import angular, { IComponentController } from 'angular' -import _ from 'lodash' -import Rx from 'rx-lite' - -import { veAppEvents } from '@ve-app/events' -import { InsertViewData } from '@ve-components/insertions/components/insert-view.component' -import { ExtensionService } from '@ve-components/services' -import { TreeService } from '@ve-components/trees/services/Tree.service' -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' -import { veCoreEvents } from '@ve-core/events' -import { IToolBarButton, ToolbarService } from '@ve-core/toolbar' -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ApiService, PermissionsService, ViewService } from '@ve-utils/mms-api-client' - -import { veComponents } from '@ve-components' - -import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { InsertResolveFn } from '@ve-types/components' -import { ElementObject, InstanceSpecObject, ViewObject } from '@ve-types/mms' -import { TreeBranch } from '@ve-types/tree' -import { VeModalService, VeModalSettings } from '@ve-types/view-editor' +import angular, { IComponentController } from 'angular'; +import _ from 'lodash'; +import Rx from 'rx-lite'; + +import { veAppEvents } from '@ve-app/events'; +import { InsertViewData } from '@ve-components/insertions/components/insert-view.component'; +import { ExtensionService } from '@ve-components/services'; +import { TreeService } from '@ve-components/trees/services/Tree.service'; +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; +import { veCoreEvents } from '@ve-core/events'; +import { IToolBarButton, ToolbarService } from '@ve-core/toolbar'; +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ApiService, PermissionsService, ViewService } from '@ve-utils/mms-api-client'; + +import { veComponents } from '@ve-components'; + +import { VeComponentOptions, VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { InsertResolveFn } from '@ve-types/components'; +import { ElementObject, InstanceSpecObject, ViewObject } from '@ve-types/mms'; +import { TreeBranch } from '@ve-types/tree'; +import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; /** * @ngdoc directive @@ -90,35 +90,35 @@ import { VeModalService, VeModalSettings } from '@ve-types/view-editor' class TreesController implements IComponentController { //Bindings - toolbarId: string = 'toolbar' - buttonId: string + toolbarId: string = 'toolbar'; + buttonId: string; //Local - documentId: string - viewId: string - projectId: string - refId: string - commitId: string + documentId: string; + viewId: string; + projectId: string; + refId: string; + commitId: string; - subs: Rx.IDisposable[] + subs: Rx.IDisposable[]; - currentTree: string - currentTitle: string + currentTree: string; + currentTitle: string; show: { - [key: string]: { tree: boolean; pe: boolean } - } = {} + [key: string]: { tree: boolean; pe: boolean }; + } = {}; - protected errorType: string + protected errorType: string; - private insertData: InsertViewData + private insertData: InsertViewData; - public filterInputPlaceholder: string - public treeSearch: string - private spin: boolean = true + public filterInputPlaceholder: string; + public treeSearch: string; + private spin: boolean = true; - protected $trees: JQuery + protected $trees: JQuery; - bbApi: ButtonBarApi + bbApi: ButtonBarApi; static $inject = [ '$compile', @@ -138,7 +138,7 @@ class TreesController implements IComponentController { 'TreeService', 'ExtensionService', 'ButtonBarService', - ] + ]; constructor( private $compile: angular.ICompileService, @@ -161,10 +161,10 @@ class TreesController implements IComponentController { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); - this.buttonId = this.buttonId ? this.buttonId : 'tree-button-bar' - this.toolbarId = this.toolbarId ? this.toolbarId : 'toolbar' + this.buttonId = this.buttonId ? this.buttonId : 'tree-button-bar'; + this.toolbarId = this.toolbarId ? this.toolbarId : 'toolbar'; // Initialize button-bar event listeners this.subs.push( @@ -174,124 +174,124 @@ class TreesController implements IComponentController { case 'tree-expand': { this.treeSvc.expandAll().then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree) + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree); }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) - break + ); + break; } case 'tree-collapse': { this.treeSvc.collapseAll().then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree) + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree); }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) - break + ); + break; } case 'tree-add-document': { this.insert('Document').catch((reason) => { - this.growl.error(reason.message) - }) - break + this.growl.error(reason.message); + }); + break; } case 'tree-add-view': { this.insert('View').catch((reason) => { - this.growl.error(reason.message) - }) - break + this.growl.error(reason.message); + }); + break; } case 'tree-add-group': { this.insert('Group').catch((reason) => { - this.growl.error(reason.message) - }) - break + this.growl.error(reason.message); + }); + break; } case 'tree-show-pe': { - this.show[_.camelCase(this.currentTree)].pe = !this.show[_.camelCase(this.currentTree)].pe - break + this.show[_.camelCase(this.currentTree)].pe = !this.show[_.camelCase(this.currentTree)].pe; + break; } } } - data.$event.stopPropagation() + data.$event.stopPropagation(); }), this.eventSvc.$on('presentation.deleted', (data) => { this.treeSvc.getBranch(data).then( (branch) => { if (branch) { this.treeSvc.removeBranch(branch).catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); } }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) + ); }) - ) + ); } $onDestroy(): void { - this.eventSvc.$destroy(this.subs) + this.eventSvc.$destroy(this.subs); } $postLink(): void { - this.$trees = $('#trees') + this.$trees = $('#trees'); //Listen for Toolbar Clicked Subject - this.subs.push(this.eventSvc.binding(this.toolbarId, this.changeTree)) + this.subs.push(this.eventSvc.binding(this.toolbarId, this.changeTree)); } insert(itemType: string): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.insertData = { insertType: 'view', type: itemType, newViewAggr: 'shared', parentBranch: null, seenViewIds: this.treeSvc.seenViewIds, - } - const branch = this.treeSvc.getSelectedBranch() + }; + const branch = this.treeSvc.getSelectedBranch(); if (itemType === 'Document') { this.addDocument(branch).then( (result) => { - this.insertModal(result) - deferred.resolve() + this.insertModal(result); + deferred.resolve(); }, (reason: VePromiseReason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } else if (itemType === 'Group') { this.addGroup(branch).then( (result) => { - this.insertModal(result) - deferred.resolve() + this.insertModal(result); + deferred.resolve(); }, (reason: VePromiseReason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } else if (itemType === 'View') { this.addView(branch).then( (result) => { - this.insertModal(result) - deferred.resolve() + this.insertModal(result); + deferred.resolve(); }, (reason: VePromiseReason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } else { - deferred.reject('Add Item of Type ' + itemType + ' is not supported') + deferred.reject('Add Item of Type ' + itemType + ' is not supported'); } - return deferred.promise + return deferred.promise; } insertModal = (branchType: string): void => { @@ -299,24 +299,24 @@ class TreesController implements IComponentController { component: 'insertElementModal', resolve: { getInsertData: () => { - return this.insertData + return this.insertData; }, getProjectId: () => { - return this.treeSvc.treeApi.projectId + return this.treeSvc.treeApi.projectId; }, getRefId: () => { - return this.treeSvc.treeApi.refId + return this.treeSvc.treeApi.refId; }, getOrgId: () => { - return this.treeSvc.treeApi.orgId + return this.treeSvc.treeApi.orgId; }, }, - } - const instance = this.$uibModal.open, ElementObject>(settings) + }; + const instance = this.$uibModal.open, ElementObject>(settings); instance.result.then( (result) => { if (!this.rootScopeSvc.veEditMode()) { - this.eventSvc.$broadcast('show-edits', true) + this.eventSvc.$broadcast('show-edits', true); } const newbranch: TreeBranch = { label: result.name, @@ -324,35 +324,35 @@ class TreesController implements IComponentController { data: result, children: [], aggr: '', - } - const top = this.insertData.type === 'Group' + }; + const top = this.insertData.type === 'Group'; const addToFullDocView = (node: TreeBranch, curSection: string, prevSysml: string): string => { - let lastChild = prevSysml + let lastChild = prevSysml; if (node.children) { - let num = 1 + let num = 1; for (let i = 0; i < node.children.length; i++) { - const cNode = node.children[i] + const cNode = node.children[i]; const data: veAppEvents.viewAddedData = { vId: cNode.data.id, curSec: `${curSection}.${num}`, prevSibId: lastChild, - } - this.eventSvc.$broadcast('view.added', data) - lastChild = addToFullDocView(cNode, `${curSection}.${num}`, cNode.data.id) - num = num + 1 + }; + this.eventSvc.$broadcast('view.added', data); + lastChild = addToFullDocView(cNode, `${curSection}.${num}`, cNode.data.id); + num = num + 1; } } - return lastChild - } + return lastChild; + }; this.treeSvc.addBranch(this.insertData.parentBranch, newbranch, top).then( () => { if (this.insertData.type === 'View') { - this.treeSvc.viewId2node[result.id] = newbranch - this.treeSvc.seenViewIds[result.id] = newbranch - newbranch.aggr = this.insertData.newViewAggr + this.treeSvc.viewId2node[result.id] = newbranch; + this.treeSvc.seenViewIds[result.id] = newbranch; + newbranch.aggr = this.insertData.newViewAggr; const curNum = this.insertData.parentBranch.children[this.insertData.parentBranch.children.length - 1] - .data._veNumber + .data._veNumber; this.treeSvc .getPrevBranch(newbranch, ['view']) .then( @@ -372,28 +372,28 @@ class TreesController implements IComponentController { (node) => { // handle full doc mode if (this.rootScopeSvc.veFullDocMode()) { - addToFullDocView(node as TreeBranch, curNum, newbranch.data.id) + addToFullDocView(node as TreeBranch, curNum, newbranch.data.id); } - this.addViewSectionsRecursivelyForNode(node as TreeBranch) + this.addViewSectionsRecursivelyForNode(node as TreeBranch); }, (reason) => { this.growl.error( 'Error processing new child views: ' + reason.message - ) + ); } - ) + ); if (!this.rootScopeSvc.veFullDocMode()) { this.eventSvc.$broadcast('view.added', { vId: result.id, curSec: curNum, prevSibId: prevBranch.data.id, - }) + }); } else { this.eventSvc.$broadcast('view.added', { vId: result.id, curSec: curNum, prevSibId: prevBranch.data.id, - }) + }); } }, (reason) => { @@ -402,151 +402,151 @@ class TreesController implements IComponentController { vId: result.id, curSec: curNum, prevSibId: this.insertData.parentBranch.data.id, - }) + }); } else { - this.growl.error('Error adding item to tree: ' + reason.message) + this.growl.error('Error adding item to tree: ' + reason.message); } } ) .finally(() => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree) - }) + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree); + }); } else { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree) + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.currentTree); } }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) + ); }, (reason) => { if (reason && reason.status !== 444) { - this.growl.warning(`Error adding View: ${reason.message}`) + this.growl.warning(`Error adding View: ${reason.message}`); } else { this.growl.info('View Insert Cancelled', { ttl: 1000, - }) + }); } } - ) - } + ); + }; addDocument(branch: TreeBranch): VePromise { if (!branch) { - this.insertData.parentBranch = null - branch = null + this.insertData.parentBranch = null; + branch = null; } else if (branch.type !== 'group') { return this.$q.reject({ message: 'Select a group to add document under', - }) + }); } else { - this.insertData.parentBranch = branch + this.insertData.parentBranch = branch; } - return this.$q.resolve('view') + return this.$q.resolve('view'); } addGroup(branch: TreeBranch): VePromise { if (branch && branch.type === 'group') { - this.insertData.parentBranch = branch + this.insertData.parentBranch = branch; } else if (branch && branch.type !== 'group') { return this.$q.reject({ message: 'Select a group to add group under', - }) + }); } else { - this.insertData.parentBranch = null + this.insertData.parentBranch = null; // Always create group at root level if the selected branch is not a group branch - branch = null + branch = null; } - return this.$q.resolve('group') + return this.$q.resolve('group'); } addView(branch: TreeBranch): VePromise { if (!branch) { return this.$q.reject({ message: 'Add View Error: Select parent view first', - }) + }); } else if (branch.type === 'section') { return this.$q.reject({ message: 'Add View Error: Cannot add a child view to a section', - }) + }); } else if (branch.aggr === 'none') { return this.$q.reject({ message: 'Add View Error: Cannot add a child view to a non-owned and non-shared view.', - }) + }); } - this.insertData.parentBranch = branch - return this.$q.resolve('view') + this.insertData.parentBranch = branch; + return this.$q.resolve('view'); } addViewSections = (view: ViewObject): void => { - const node = this.treeSvc.viewId2node[view.id] + const node = this.treeSvc.viewId2node[view.id]; this.treeSvc.addSectionElements(view, node, node).catch((reason) => { - this.growl.error('Error adding view sections:' + reason.message) - }) - } + this.growl.error('Error adding view sections:' + reason.message); + }); + }; addViewSectionsRecursivelyForNode = (node: TreeBranch): void => { - this.addViewSections(node.data) + this.addViewSections(node.data); for (let i = 0; i < node.children.length; i++) { if (node.children[i].type === 'view') { - this.addViewSectionsRecursivelyForNode(node.children[i]) + this.addViewSectionsRecursivelyForNode(node.children[i]); } } - } + }; userClicksPane = (): void => { this.treeSvc.selectBranch().catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) - } + this.growl.error(TreeService.treeError(reason)); + }); + }; private changeTree = (data: { id: string; category?: string; title?: string }): void => { if (!this.currentTree) { - this.currentTree = '' + this.currentTree = ''; } if (this.currentTree !== data.id) { if (this.currentTree !== '') { - this.show[_.camelCase(this.currentTree)].tree = false + this.show[_.camelCase(this.currentTree)].tree = false; } - this.currentTree = data.id - const inspect: IToolBarButton = this.toolbarSvc.getToolbarButton(data.id) + this.currentTree = data.id; + const inspect: IToolBarButton = this.toolbarSvc.getToolbarButton(data.id); if (!data.category) { - data.category = inspect.category + data.category = inspect.category; } - this.currentTitle = data.title ? data.title : inspect.tooltip + this.currentTitle = data.title ? data.title : inspect.tooltip; if (!this.show.hasOwnProperty(_.camelCase(data.id))) { - this.startTree(data.id) - this.show[_.camelCase(data.id)] = { tree: true, pe: false } + this.startTree(data.id); + this.show[_.camelCase(data.id)] = { tree: true, pe: false }; } else { - this.eventSvc.$broadcast(TreeService.events.RELOAD, data.id) - this.show[_.camelCase(data.id)].tree = true + this.eventSvc.$broadcast(TreeService.events.RELOAD, data.id); + this.show[_.camelCase(data.id)].tree = true; } } - } + }; private startTree = (id: string): void => { - const tag = this.extensionSvc.getTagByType('treeOf', id) - const treeId: string = _.camelCase(id) - const newTree: JQuery = $(`
    `) + const tag = this.extensionSvc.getTagByType('treeOf', id); + const treeId: string = _.camelCase(id); + const newTree: JQuery = $(`
    `); if (tag === 'extensionError') { - this.errorType = this.currentTree.replace('tree-of-', '') + this.errorType = this.currentTree.replace('tree-of-', ''); newTree.append( '' - ) + ); } else { newTree.append( `<${tag} show-pe="$ctrl.show.${treeId}.pe" toolbar-id="${this.toolbarId}" button-id="${this.buttonId}"}>` - ) + ); } - this.$trees.append(newTree) + this.$trees.append(newTree); - this.$compile(newTree)(this.$scope) - } + this.$compile(newTree)(this.$scope); + }; } const TreesComponent: VeComponentOptions = { @@ -570,6 +570,6 @@ const TreesComponent: VeComponentOptions = { buttonId: '@', }, controller: TreesController, -} +}; -veComponents.component(TreesComponent.selector, TreesComponent) +veComponents.component(TreesComponent.selector, TreesComponent); diff --git a/src/ve-components/trees/services/Tree.service.ts b/src/ve-components/trees/services/Tree.service.ts index 2c9f5a99c..4e291449f 100644 --- a/src/ve-components/trees/services/Tree.service.ts +++ b/src/ve-components/trees/services/Tree.service.ts @@ -1,12 +1,12 @@ -import { IQResolveReject } from 'angular' +import { IQResolveReject } from 'angular'; -import { ApplicationService, RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client' +import { ApplicationService, RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { ApiService, ElementService, ProjectService, ViewService } from '@ve-utils/mms-api-client'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; import { ElementObject, ElementsRequest, @@ -15,42 +15,42 @@ import { ValueObject, ViewInstanceSpec, ViewObject, -} from '@ve-types/mms' -import { TreeApi, TreeBranch, TreeRow } from '@ve-types/tree' +} from '@ve-types/mms'; +import { TreeApi, TreeBranch, TreeRow } from '@ve-types/tree'; export class TreeService { - public selectedBranch: TreeBranch = null - public branch2viewNumber: { [key: string]: string } = {} - public defaultIcon: string = 'fa-solid fa-file fa-fw' + public selectedBranch: TreeBranch = null; + public branch2viewNumber: { [key: string]: string } = {}; + public defaultIcon: string = 'fa-solid fa-file fa-fw'; public defaultIcons = { iconExpand: 'fa-solid fa-caret-down fa-lg fa-fw', iconCollapse: 'fa-solid fa-caret-right fa-lg fa-fw', iconDefault: 'fa-solid fa-file fa-fw', - } + }; - public defaultSectionTypes = ['group', 'view', 'section'] + public defaultSectionTypes = ['group', 'view', 'section']; - public loading: boolean + public loading: boolean; - private inProgress: VePromise = null - private treeData: TreeBranch[] = [] + private inProgress: VePromise = null; + private treeData: TreeBranch[] = []; - public viewId2node: { [key: string]: TreeBranch } = {} - public seenViewIds: { [key: string]: TreeBranch } = {} + public viewId2node: { [key: string]: TreeBranch } = {}; + public seenViewIds: { [key: string]: TreeBranch } = {}; - public processedRoot: string = '' - public processedFocus: string = '' + public processedRoot: string = ''; + public processedFocus: string = ''; - public treeApi: TreeApi - private rows: { [id: string]: TreeRow[] } = {} + public treeApi: TreeApi; + private rows: { [id: string]: TreeRow[] } = {}; - treeEditable: boolean + treeEditable: boolean; static events = { UPDATED: 'tree.updated', RELOAD: 'tree.reload', FILTER: 'tree.filter', - } + }; static MetaTypes = [ 'tag', @@ -72,7 +72,7 @@ export class TreeService { 'view-composite', 'view-shared', 'view-none', - ] + ]; static $inject = [ '$q', @@ -85,7 +85,7 @@ export class TreeService { 'ApplicationService', 'RootScopeService', 'EventService', - ] + ]; constructor( private $q: VeQService, @@ -101,12 +101,12 @@ export class TreeService { ) {} public isTreeReady = (): boolean => { - return this.treeData.length > 0 - } + return this.treeData.length > 0; + }; public getTreeData = (): TreeBranch[] => { - return this.treeData - } + return this.treeData; + }; // // public setTreeApi = (treeOptions: TreeOptions): void => { // this.treeOptions = treeOptions @@ -131,118 +131,118 @@ export class TreeService { level2_Func: (elementOb: ElementObject, node: TreeBranch) => VePromise ): VePromise => { return new this.$q((resolve, reject) => { - const rootNodes: TreeBranch[] = [] - const data2Node: { [key: string]: TreeBranch } = {} + const rootNodes: TreeBranch[] = []; + const data2Node: { [key: string]: TreeBranch } = {}; // create flat map for each element elementObs.forEach((elementOb) => { - const elementId: string = elementOb[idKey] as string + const elementId: string = elementOb[idKey] as string; data2Node[elementId] = { label: elementOb.name, type: type, data: elementOb, children: [], loading: true, - } - }) + }; + }); // make second pass to associate data to parent nodes elementObs.forEach((elementOb) => { - const parentId: string = elementOb[parentKey] as string - const elementId: string = elementOb[idKey] as string + const parentId: string = elementOb[parentKey] as string; + const elementId: string = elementOb[idKey] as string; // If there's an element in data2Node whose key matches the 'parent' value in the array element // add the array element to the children array of the matched data2Node element if (parentId && data2Node[parentId]) { - data2Node[parentId].children.push(data2Node[elementId]) + data2Node[parentId].children.push(data2Node[elementId]); } else { // If there's not an element in data2Node whose key matches the 'parent' value in the array element // it's a "root node" and so it should be pushed to the root nodes array along with its children - rootNodes.push(data2Node[elementId]) + rootNodes.push(data2Node[elementId]); } - }) + }); //apply level2 function if available if (level2_Func) { elementObs.forEach((elementOb) => { - const elementId: string = elementOb[idKey] as string - const level1_parentNode = data2Node[elementId] - level2_Func(elementOb, level1_parentNode).catch(reject) - }) + const elementId: string = elementOb[idKey] as string; + const level1_parentNode = data2Node[elementId]; + level2_Func(elementOb, level1_parentNode).catch(reject); + }); } const sortFunction = (a: TreeBranch, b: TreeBranch): number => { if (a.children.length > 1) { - a.children.sort(sortFunction) + a.children.sort(sortFunction); } if (b.children.length > 1) { - b.children.sort(sortFunction) + b.children.sort(sortFunction); } if (a.label.toLowerCase() < b.label.toLowerCase()) { - return -1 + return -1; } if (a.label.toLowerCase() > b.label.toLowerCase()) { - return 1 + return 1; } - return 0 - } - rootNodes.sort(sortFunction) - resolve(rootNodes) - }) - } + return 0; + }; + rootNodes.sort(sortFunction); + resolve(rootNodes); + }); + }; private getTypeIcon = (type: string): string => { - let t = type - if (!t) t = 'unknown' - t = t.toLowerCase() + let t = type; + if (!t) t = 'unknown'; + t = t.toLowerCase(); switch (t) { case 'tag': - return 'fa-solid fa-tag' + return 'fa-solid fa-tag'; case 'connector': - return 'fa-solid fa-expand' + return 'fa-solid fa-expand'; case 'dependency': - return 'fa-solid fa-long-arrow-right' + return 'fa-solid fa-long-arrow-right'; case 'directedrelationship': - return 'fa-solid fa-arrow-right-long' + return 'fa-solid fa-arrow-right-long'; case 'element': - return 'fa-solid fa-border-top-left' + return 'fa-solid fa-border-top-left'; case 'property': - return 'fa-solid fa-circle' + return 'fa-solid fa-circle'; case 'generalization': - return 'fa-solid fa-arrow-up-long' + return 'fa-solid fa-arrow-up-long'; case 'package': - return 'fa-regular fa-folder' + return 'fa-regular fa-folder'; case 'section': - return 'section-icon' //"fa-file-o"; + return 'section-icon'; //"fa-file-o"; case 'group': - return 'fa-solid fa-folder' + return 'fa-solid fa-folder'; case 'snapshot': - return 'fa-solid fa-camera' + return 'fa-solid fa-camera'; case 'view': - return 'fa-solid fa-file' + return 'fa-solid fa-file'; case 'view-composite': - return 'fa-solid fa-file' + return 'fa-solid fa-file'; case 'view-shared': - return 'fa-regular fa-file' + return 'fa-regular fa-file'; case 'view-none': - return 'fa-regular fa-file' + return 'fa-regular fa-file'; case 'branch': - return 'fa-solid fa-code-branch' + return 'fa-solid fa-code-branch'; case 'table': - return 'fa-solid fa-table' + return 'fa-solid fa-table'; case 'figure': - return 'fa-regular fa-image' + return 'fa-regular fa-image'; case 'diagram': - return 'fa-solid fa-diagram-project' + return 'fa-solid fa-diagram-project'; case 'equation': - return 'fa-solid fa-superscript' + return 'fa-solid fa-superscript'; default: - return 'fa-solid fa-file-circle-question' + return 'fa-solid fa-file-circle-question'; } - } + }; static treeError(reason: VePromiseReason): string { - return 'Error refreshing tree: ' + reason.message + return 'Error refreshing tree: ' + reason.message; } /** @@ -252,9 +252,9 @@ export class TreeService { public expandAll = (): VePromise => { return this.forEachBranch((b) => { //scope.expandCallback({ branch: b }); - b.expanded = true - }, false) - } + b.expanded = true; + }, false); + }; /** * @name TreeApi#collapseAll * self-explanatory @@ -262,28 +262,28 @@ export class TreeService { public collapseAll = (excludeBranch?: TreeBranch): VePromise => { return this.forEachBranch( (b, level) => { - b.expanded = false + b.expanded = false; }, false, excludeBranch - ) - } + ); + }; /** * Gets the first branch in the tree * @returns {TreeBranch} */ public getFirstBranch = (): TreeBranch => { - if (this.treeData.length > 0) return this.treeData[0] - } + if (this.treeData.length > 0) return this.treeData[0]; + }; /** * Selects the first branch in the tree */ public selectFirstBranch = (): VePromise => { - const b = this.getFirstBranch() - return this.selectBranch(b) - } + const b = this.getFirstBranch(); + return this.selectBranch(b); + }; /** * @name TreeApi#getSelectedBranch @@ -292,25 +292,25 @@ export class TreeService { * @return {Object} current selected branch */ public getSelectedBranch = (): TreeBranch => { - return this.selectedBranch - } + return this.selectedBranch; + }; public clearSelectedBranch = (): void => { - if (this.selectedBranch) this.selectedBranch.selected = false - this.selectedBranch = null - } + if (this.selectedBranch) this.selectedBranch.selected = false; + this.selectedBranch = null; + }; public getChildren = (b: TreeBranch): TreeBranch[] => { - return b.children - } + return b.children; + }; public selectParentBranch = (branch: TreeBranch): VePromise => { return this.$q((resolve, reject) => { this.getParent(branch).then((p) => { - this.selectBranch(p).then(resolve, reject) - }, reject) - }) - } + this.selectBranch(p).then(resolve, reject); + }, reject); + }); + }; /** * @ngdoc function @@ -323,20 +323,20 @@ export class TreeService { */ public addBranch = (parent: TreeBranch, new_branch: TreeBranch, top: boolean): VePromise => { if (parent) { - if (top) parent.children.unshift(new_branch) - else parent.children.push(new_branch) - parent.expanded = true + if (top) parent.children.unshift(new_branch); + else parent.children.push(new_branch); + parent.expanded = true; } else { - if (top) this.treeData.unshift(new_branch) - else this.treeData.push(new_branch) + if (top) this.treeData.unshift(new_branch); + else this.treeData.push(new_branch); } - return this.$q.resolve() - } + return this.$q.resolve(); + }; public removeBranch = (branch: TreeBranch): VePromise => { - this._removeBranch(branch, false) - return this.$q.resolve() - } + this._removeBranch(branch, false); + return this.$q.resolve(); + }; /** * @name TreeApi#expandBranch @@ -345,13 +345,13 @@ export class TreeService { * @param {TreeBranch} branch branch to expand */ public expandBranch = (branch: TreeBranch): VePromise => { - if (!branch) branch = this.getSelectedBranch() + if (!branch) branch = this.getSelectedBranch(); if (branch) { //scope.expandCallback({ branch: b }); - branch.expanded = true + branch.expanded = true; } - return this.$q.resolve() - } + return this.$q.resolve(); + }; /** * @name TreeApi#closeBranch @@ -360,13 +360,13 @@ export class TreeService { * @param {TreeBranch} branch branch to close */ public closeBranch = (branch: TreeBranch): VePromise => { - if (!branch) branch = this.getSelectedBranch() + if (!branch) branch = this.getSelectedBranch(); if (branch) { //scope.expandCallback({ branch: b }); - branch.expanded = false + branch.expanded = false; } - return this.$q.resolve() - } + return this.$q.resolve(); + }; /** * Gets siblings of specified branch @@ -377,14 +377,14 @@ export class TreeService { return this.$q((resolve) => { this.getParent(branch).then( (p) => { - resolve(p.children) + resolve(p.children); }, () => { - resolve(this.treeData) + resolve(this.treeData); } - ) - }) - } + ); + }); + }; /** * Gets numerically next sibling (if exists) of specified branch @@ -395,13 +395,13 @@ export class TreeService { return this.$q((resolve, reject) => { this.getSiblings(branch).then((siblings) => { if (Array.isArray(siblings)) { - const i = siblings.indexOf(branch) - if (i < siblings.length - 1) resolve(siblings[i + 1]) - else reject() + const i = siblings.indexOf(branch); + if (i < siblings.length - 1) resolve(siblings[i + 1]); + else reject(); } - }, reject) - }) - } + }, reject); + }); + }; /** * Gets numerically previous sibling (if exists) of specified branch @@ -412,13 +412,13 @@ export class TreeService { return this.$q((resolve, reject) => { this.getSiblings(branch).then((siblings) => { if (Array.isArray(siblings)) { - const i = siblings.indexOf(branch) - if (i > 0) resolve(siblings[i - 1]) - else reject() + const i = siblings.indexOf(branch); + if (i > 0) resolve(siblings[i - 1]); + else reject(); } - }, reject) - }) - } + }, reject); + }); + }; /** * Gets the first child of the specified branch (if exists) @@ -426,9 +426,9 @@ export class TreeService { * @returns {TreeBranch} */ public getFirstChild = (branch: TreeBranch): TreeBranch => { - if (!branch) branch = this.selectedBranch - if (branch && branch.children && branch.children.length > 0) return branch.children[0] - } + if (!branch) branch = this.selectedBranch; + if (branch && branch.children && branch.children.length > 0) return branch.children[0]; + }; /** * Traverse up/down the tree to find the next closest sibling to the specified branch @@ -439,16 +439,16 @@ export class TreeService { return this.$q((resolve, reject) => { this.getNextSibling(branch).then( (b) => { - resolve(b) + resolve(b); }, () => { this.getParent(branch).then((next) => { - this.getClosestAncestorNextSibling(next).then(resolve, reject) - }, reject) + this.getClosestAncestorNextSibling(next).then(resolve, reject); + }, reject); } - ) - }) - } + ); + }); + }; /** * Gets the next branch in the tree @@ -459,24 +459,24 @@ export class TreeService { */ public getNextBranch = (branch: TreeBranch, types?: string[]): VePromise => { return this.$q((resolve, reject) => { - if (!branch) branch = this.selectedBranch + if (!branch) branch = this.selectedBranch; if (branch) { - const next = this.getFirstChild(branch) + const next = this.getFirstChild(branch); if (next) { - if (types && types.includes(next.type)) resolve(next) - else this.getNextBranch(next, types).then(resolve, reject) + if (types && types.includes(next.type)) resolve(next); + else this.getNextBranch(next, types).then(resolve, reject); } else { this.getClosestAncestorNextSibling(branch).then((nextSib) => { if (types && !types.includes(nextSib.type)) { - this.getNextBranch(nextSib, types).then(resolve, reject) + this.getNextBranch(nextSib, types).then(resolve, reject); } else { - resolve(nextSib) + resolve(nextSib); } - }, reject) + }, reject); } - } else reject({ message: 'No More branches!', status: 200 }) - }) - } + } else reject({ message: 'No More branches!', status: 200 }); + }); + }; /** * Returns the last descendant branch of the specified branch @@ -486,14 +486,14 @@ export class TreeService { public lastDescendant = (branch: TreeBranch): VePromise => { return new this.$q((resolve, reject) => { if (branch) { - if (branch.children.length === 0) resolve(branch) - const last = branch.children[branch.children.length - 1] - return this.lastDescendant(last).then(resolve, reject) + if (branch.children.length === 0) resolve(branch); + const last = branch.children[branch.children.length - 1]; + return this.lastDescendant(last).then(resolve, reject); } else { - reject({ message: 'No branch Specified', status: 401 }) + reject({ message: 'No branch Specified', status: 401 }); } - }) - } + }); + }; /** * Get's the branch previous to the branch specified @@ -508,18 +508,18 @@ export class TreeService { (prevSibling) => { this.lastDescendant(prevSibling).then((last) => { if (types && !types.includes(last.type)) { - this.getPrevBranch(last, types).then(resolve, reject) + this.getPrevBranch(last, types).then(resolve, reject); } else { - resolve(last) + resolve(last); } - }, reject) + }, reject); }, () => { - this.getParent(branch).then(resolve, reject) + this.getParent(branch).then(resolve, reject); } - ) - }) - } + ); + }); + }; /** * @name TreeApi#refresh @@ -527,12 +527,12 @@ export class TreeService { */ public refresh = (treeData: TreeBranch[]): VePromise => { if (this.inProgress == null) { - this.inProgress = this.$q.resolve() + this.inProgress = this.$q.resolve(); } - this.treeData.length = 0 - this.treeData.push(...treeData) - return this._onTreeDataChange() - } + this.treeData.length = 0; + this.treeData.push(...treeData); + return this._onTreeDataChange(); + }; /** * @name TreeApi#getBranch @@ -542,11 +542,11 @@ export class TreeService { return new this.$q((resolve, reject) => { this.forEachBranch((b) => { if (b.data.id === data.id) { - resolve(b) + resolve(b); } - }).catch(reject) - }) - } + }).catch(reject); + }); + }; /** * Runs the specified callback function on each branch in the tree as specified by treeData @@ -559,37 +559,37 @@ export class TreeService { excludeBranch?: TreeBranch ): VePromise => { return new this.$q((resolve, reject) => { - const flag = false + const flag = false; const run = (branch: TreeBranch, level: number, flag: boolean): void => { - if (flag && !useFlag) resolve() - func(branch, flag) + if (flag && !useFlag) resolve(); + func(branch, flag); if (branch.children) { for (let i = 0; i < branch.children.length; i++) { - run(branch.children[i], level + 1, flag) + run(branch.children[i], level + 1, flag); } } - } + }; const rootLevelBranches = excludeBranch ? this.treeData.filter((branch) => { - return branch !== excludeBranch + return branch !== excludeBranch; }) - : this.treeData + : this.treeData; rootLevelBranches.forEach((branch) => { - run(branch, 1, flag) - }) - if (!useFlag) resolve() - else reject({ message: 'No valid Branches found', status: 401 }) - }) - } + run(branch, 1, flag); + }); + if (!useFlag) resolve(); + else reject({ message: 'No valid Branches found', status: 401 }); + }); + }; private _removeBranch = (branch: TreeBranch, singleBranch: boolean): void => { this.getParent(branch).then( (parentBranch) => { for (let i = 0; i < parentBranch.children.length; i++) { if (parentBranch.children[i].uid === branch.uid) { - parentBranch.children.splice(i, 1) + parentBranch.children.splice(i, 1); if (singleBranch) { - break + break; } } } @@ -597,13 +597,13 @@ export class TreeService { () => { for (let j = 0; j < this.treeData.length; j++) { if (this.treeData[j].uid === branch.uid) { - this.treeData.splice(j, 1) - break + this.treeData.splice(j, 1); + break; } } } - ) - } + ); + }; /** * Gets branch parent @@ -612,26 +612,26 @@ export class TreeService { */ public getParent = (child: TreeBranch): VePromise => { return new this.$q((resolve, reject) => { - if (child === null) reject({ message: 'No child specified!', status: 404 }) + if (child === null) reject({ message: 'No child specified!', status: 404 }); if (child.parent_uid) { this.forEachBranch((b) => { if (b.uid === child.parent_uid) { - resolve(b) + resolve(b); } - }).catch(reject) + }).catch(reject); } else { - reject({ message: 'Already at root!', status: 200 }) + reject({ message: 'Already at root!', status: 200 }); } - }) - } + }); + }; public expandPathToSelectedBranch = (): VePromise => { if (this.selectedBranch) { - return this.expandAllParents(this.selectedBranch) + return this.expandAllParents(this.selectedBranch); } - return this.$q.resolve() - } + return this.$q.resolve(); + }; public forAllAncestors = ( child: TreeBranch, @@ -641,24 +641,24 @@ export class TreeService { this.getParent(child).then( (parent) => { fn(parent).then(() => { - this.forAllAncestors(parent, fn).then(resolve, reject) - }, reject) + this.forAllAncestors(parent, fn).then(resolve, reject); + }, reject); }, () => { - resolve() + resolve(); } - ) - }) - } + ); + }); + }; public expandAllParents = (child: TreeBranch): VePromise => { return this.forAllAncestors(child, (b) => { if (b.expandable && !b.expanded) { - return this.expandBranch(b) + return this.expandBranch(b); } - return this.$q.resolve() - }) - } + return this.$q.resolve(); + }); + }; /** * Select a branch @@ -666,37 +666,37 @@ export class TreeService { * @param noClick */ public selectBranch = (branch?: TreeBranch, noClick?): VePromise => { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); if (!branch) { - if (this.selectedBranch) this.selectedBranch.selected = false - this.clearSelectedBranch() - return this.$q.resolve() + if (this.selectedBranch) this.selectedBranch.selected = false; + this.clearSelectedBranch(); + return this.$q.resolve(); } if (branch !== this.selectedBranch) { - if (this.selectedBranch) this.selectedBranch.selected = false - branch.selected = true - this.selectedBranch = branch + if (this.selectedBranch) this.selectedBranch.selected = false; + branch.selected = true; + this.selectedBranch = branch; } this.expandAllParents(branch).then( () => { if (!noClick) { if (branch.onSelect != null) { - branch.onSelect(branch) + branch.onSelect(branch); } else if (this.treeApi.onSelect) { - this.treeApi.onSelect(branch) + this.treeApi.onSelect(branch); } } if (branch.data.id) { this.eventSvc.$broadcast('tree-get-branch-element', { id: branch.data.id, - }) + }); } - deferred.resolve() + deferred.resolve(); }, (reason) => deferred.reject(reason) - ) - return deferred.promise - } + ); + return deferred.promise; + }; private _onTreeDataChange = (): VePromise => { return new this.$q((resolve, reject) => { @@ -704,18 +704,18 @@ export class TreeService { reject({ message: '[warn] treeData is not an array!', status: 401, - }) + }); } this.treeData.forEach((branch) => { - this._addBranchData(1, [], branch, true, {}) - }) + this._addBranchData(1, [], branch, true, {}); + }); - this.eventSvc.resolve(TreeService.events.UPDATED, true) - this.eventSvc.$broadcast('tree.ready') - resolve() - }) - } + this.eventSvc.resolve(TreeService.events.UPDATED, true); + this.eventSvc.$broadcast('tree.ready'); + resolve(); + }); + }; private _addBranchData = ( level: number, @@ -724,103 +724,103 @@ export class TreeService { visible: boolean, peNums: { [type: string]: number } ): void => { - if (!branch.uid) branch.uid = `${Math.random()}` - if (typeof branch.expanded === 'undefined') branch.expanded = level <= this.treeApi.expandLevel - branch.expandable = branch.children && branch.children.length > 0 - branch.favorite = false + if (!branch.uid) branch.uid = `${Math.random()}`; + if (typeof branch.expanded === 'undefined') branch.expanded = level <= this.treeApi.expandLevel; + branch.expandable = branch.children && branch.children.length > 0; + branch.favorite = false; - let number = '' - if (section) number = section.join('.') + let number = ''; + if (section) number = section.join('.'); // Handle numbering of non-section types if (!this.defaultSectionTypes.includes(branch.type)) { - if (!peNums[branch.type]) peNums[branch.type] = 0 - peNums[branch.type]++ + if (!peNums[branch.type]) peNums[branch.type] = 0; + peNums[branch.type]++; if (this.treeApi.numberingDepth === 0 && !this.defaultSectionTypes.includes(branch.type)) { - number = peNums[branch.type].toString(10) + number = peNums[branch.type].toString(10); } else if (section.length >= this.treeApi.numberingDepth) { number = `${section.slice(0, this.treeApi.numberingDepth).join('.')}${this.treeApi.numberingSeparator}${ peNums[branch.type] - }` + }`; } else { - const sectionCopy = [...section] + const sectionCopy = [...section]; while (sectionCopy.length < this.treeApi.numberingDepth) { - sectionCopy.push('0') + sectionCopy.push('0'); } - number = `${sectionCopy.join('.')}${this.treeApi.numberingSeparator}${peNums[branch.type]}` + number = `${sectionCopy.join('.')}${this.treeApi.numberingSeparator}${peNums[branch.type]}`; } } if (branch.data && branch.data.id && this.treeApi.sectionNumbering) { - this.branch2viewNumber[branch.data.id] = number - branch.data._veNumber = number + this.branch2viewNumber[branch.data.id] = number; + branch.data._veNumber = number; } if (branch.children) { - let alpha = false + let alpha = false; if (this.treeApi.sort) { - branch.children.sort(this._treeSortFunction) + branch.children.sort(this._treeSortFunction); } - let j = this.treeApi.startChapter + let j = this.treeApi.startChapter; if (j === null || j === undefined || level != 1) { - j = 1 + j = 1; } branch.children.forEach((child) => { - child.parent_uid = branch.uid - const child_visible = visible && branch.expanded + child.parent_uid = branch.uid; + const child_visible = visible && branch.expanded; if (!this.defaultSectionTypes.includes(child.type)) { - this._addBranchData(level + 1, section, child, child_visible, peNums) + this._addBranchData(level + 1, section, child, child_visible, peNums); } else { if (this.treeApi.sectionNumbering) { if (child.data._isAppendix) { - alpha = true - j = 0 + alpha = true; + j = 0; } - const nextSection = [...section, alpha ? String.fromCharCode(j + 65) : j.toString(10)] + const nextSection = [...section, alpha ? String.fromCharCode(j + 65) : j.toString(10)]; if (nextSection.length <= this.treeApi.numberingDepth) { - peNums = {} + peNums = {}; } - this._addBranchData(level + 1, nextSection, child, child_visible, peNums) + this._addBranchData(level + 1, nextSection, child, child_visible, peNums); } else { - this._addBranchData(level + 1, [], child, child_visible, peNums) + this._addBranchData(level + 1, [], child, child_visible, peNums); } - j++ + j++; } - }) + }); if (this.treeApi.sort) { - this.treeData.sort(this._treeSortFunction) + this.treeData.sort(this._treeSortFunction); } - if (!this.treeApi.expandLevel && this.treeApi.expandLevel !== 0) this.treeApi.expandLevel = 1 + if (!this.treeApi.expandLevel && this.treeApi.expandLevel !== 0) this.treeApi.expandLevel = 1; } - branch.loading = false - this.eventSvc.resolve(TreeService.events.UPDATED, false) - } + branch.loading = false; + this.eventSvc.resolve(TreeService.events.UPDATED, false); + }; public updateRows = (id: string, types: string[], treeRows: TreeRow[]): VePromise => { - treeRows.length = 0 + treeRows.length = 0; return new this.$q((resolve, reject) => { const addBranchToList = (level: number, branch: TreeBranch, visible: boolean): void => { - let typeIcon = this.defaultIcon - let visibleChild = false - let aggr = branch.aggr - if (!aggr) aggr = '' - else aggr = '-' + aggr.toLowerCase() + let typeIcon = this.defaultIcon; + let visibleChild = false; + let aggr = branch.aggr; + if (!aggr) aggr = ''; + else aggr = '-' + aggr.toLowerCase(); for (let i = 0; i < branch.children.length; i++) { if (types.includes('all') || types.includes(branch.children[i].type)) { - visibleChild = true - break + visibleChild = true; + break; } } if (this.getTypeIcon(branch.type.toLowerCase() + aggr)) { - typeIcon = this.getTypeIcon(branch.type.toLowerCase() + aggr) + typeIcon = this.getTypeIcon(branch.type.toLowerCase() + aggr); } else if (this.getTypeIcon('default')) { - typeIcon = this.getTypeIcon('default') + typeIcon = this.getTypeIcon('default'); } - let number = '' + let number = ''; if (this.treeApi.sectionNumbering) { if (branch.data && branch.data._veNumber) { - number = branch.data._veNumber + number = branch.data._veNumber; } } @@ -838,71 +838,71 @@ export class TreeService { visible, typeIcon, children: branch.children, - } - treeRows.push(treeRow) + }; + treeRows.push(treeRow); } //Work on children if (branch.children) { branch.children.forEach((child) => { - const child_visible = visible && branch.expanded - addBranchToList(level + 1, child, child_visible) - }) + const child_visible = visible && branch.expanded; + addBranchToList(level + 1, child, child_visible); + }); //This branch is done, stop loading } - } + }; if (types && types.length > 0) { - this.branch2viewNumber = {} + this.branch2viewNumber = {}; this.treeData.forEach((branch) => { - addBranchToList(1, branch, true) - }) + addBranchToList(1, branch, true); + }); } else { reject({ status: 500, message: 'Tree component has no types', - }) + }); } - this.rows[id] = treeRows - resolve(treeRows) - }) - } + this.rows[id] = treeRows; + resolve(treeRows); + }); + }; // TODO: Update sort function to handle all cases private _treeSortFunction = (a: TreeBranch, b: TreeBranch): number => { - a.priority = 100 + a.priority = 100; if (a.type === 'tag') { - a.priority = 0 + a.priority = 0; } else if (a.type === 'group') { - a.priority = 1 + a.priority = 1; } else if (a.type === 'view') { - a.priority = 2 + a.priority = 2; } - b.priority = 100 + b.priority = 100; if (b.type === 'tag') { - b.priority = 0 + b.priority = 0; } else if (b.type === 'group') { - b.priority = 1 + b.priority = 1; } else if (b.type === 'view') { - b.priority = 2 + b.priority = 2; } - if (a.priority < b.priority) return -1 - if (a.priority > b.priority) return 1 + if (a.priority < b.priority) return -1; + if (a.priority > b.priority) return 1; if (!a.label) { - a.label = '' + a.label = ''; } if (!b.label) { - b.label = '' + b.label = ''; } - if (a.label.toLowerCase() < b.label.toLowerCase()) return -1 - if (a.label.toLowerCase() > b.label.toLowerCase()) return 1 - return 0 - } + if (a.label.toLowerCase() < b.label.toLowerCase()) return -1; + if (a.label.toLowerCase() > b.label.toLowerCase()) return 1; + return 0; + }; changeRoots = (root?: ElementObject): VePromise => { - this.processedRoot = this.treeApi.rootId + this.processedRoot = this.treeApi.rootId; - const treeData: TreeBranch[] = [] + const treeData: TreeBranch[] = []; return new this.$q((resolve, reject) => { if (!root) { // if (this.mmsRef.type === 'Branch') { @@ -926,7 +926,7 @@ export class TreeService { '_parentId', this.groupLevel2Func ).then((treeHierarchy) => { - treeData.push(...treeHierarchy) + treeData.push(...treeHierarchy); documents.forEach((document) => { if (!document._groupId || document._groupId == this.treeApi.projectId) { treeData.push({ @@ -934,42 +934,42 @@ export class TreeService { type: 'view', data: document, children: [], - }) + }); } - }) - this.processedFocus = '' + }); + this.processedFocus = ''; if (treeData.length > 0) { - this.treeData.length = 0 - this.treeData.push(...treeData) + this.treeData.length = 0; + this.treeData.push(...treeData); } - this.changeElement().then(resolve, reject) - }, reject) + this.changeElement().then(resolve, reject); + }, reject); }, (reason) => { - reason.message = 'Error getting Documents: ' + reason.message - reject(reason) + reason.message = 'Error getting Documents: ' + reason.message; + reject(reason); } - ) + ); }, (reason) => { - reason.message = 'Error getting Groups: ' + reason.message - reject(reason) + reason.message = 'Error getting Groups: ' + reason.message; + reject(reason); } - ) + ); } else { - this.seenViewIds = {} - this.viewId2node = {} + this.seenViewIds = {}; + this.viewId2node = {}; const reqOb: ElementsRequest = { elementId: this.treeApi.rootId, refId: this.treeApi.refId, projectId: this.treeApi.projectId, - } + }; this.elementSvc.getElement(reqOb).then((root) => { if (this.apiSvc.isView(root)) { - const rootBranch = this.handleSingleView(root, 'composite') - this.treeData.length = 0 - this.treeData.push(rootBranch) - this._onTreeDataChange().catch(reject) + const rootBranch = this.handleSingleView(root, 'composite'); + this.treeData.length = 0; + this.treeData.push(rootBranch); + this._onTreeDataChange().catch(reject); this.viewSvc .handleChildViews( root, @@ -982,12 +982,12 @@ export class TreeService { this.handleChildren ) .then(() => { - const bulkGet: string[] = [] + const bulkGet: string[] = []; for (const i in this.viewId2node) { - const view: ViewObject = this.viewId2node[i].data + const view: ViewObject = this.viewId2node[i].data; if (view._contents && view._contents.operand) { for (let j = 0; j < view._contents.operand.length; j++) { - bulkGet.push(view._contents.operand[j].instanceId) + bulkGet.push(view._contents.operand[j].instanceId); } } } @@ -1007,55 +1007,55 @@ export class TreeService { this.viewId2node[i], this.viewId2node[i], true - ).catch(reject) + ).catch(reject); } - this.processedFocus = '' - this.changeElement().then(resolve, reject) - }) - }, reject) + this.processedFocus = ''; + this.changeElement().then(resolve, reject); + }); + }, reject); } else { //TODO: Implement Collect Owned Elements Logic } - }, reject) + }, reject); } - }) - } + }); + }; changeElement = (): VePromise => { if (this.treeApi.elementId === this.processedFocus) return new this.$q((resolve, reject) => { - resolve() - }) + resolve(); + }); - this.processedFocus = this.treeApi.elementId + this.processedFocus = this.treeApi.elementId; return new this.$q((resolve, reject) => { //As of right now the project portal page is 'hidden' so it won't appear in the tree if (this.treeApi.elementId === this.treeApi.projectId + '_cover') - this._onTreeDataChange().then(resolve, reject) + this._onTreeDataChange().then(resolve, reject); else { this.forEachBranch((b): void => { if (b.data.id === this.treeApi.elementId || this.treeApi.elementId === `site_${b.data.id}_cover`) { this.selectBranch(b, true).then( () => { - this._onTreeDataChange().then(resolve, reject) + this._onTreeDataChange().then(resolve, reject); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); } }).catch((reason) => { reject({ message: 'Invalid tree selection:' + reason.message, status: 401, - }) - }) + }); + }); } - }) - } + }); + }; groupLevel2Func = (groupOb: ElementObject, groupNode: TreeBranch): VePromise => { - groupNode.loading = true + groupNode.loading = true; return new this.$q((resolve, reject) => { this.viewSvc .getProjectDocuments( @@ -1067,37 +1067,37 @@ export class TreeService { ) .then( (documentObs: ViewObject[]) => { - const docs: ViewObject[] = [] - let docOb: ViewObject, i + const docs: ViewObject[] = []; + let docOb: ViewObject, i; for (let i = 0; i < documentObs.length; i++) { - docOb = documentObs[i] + docOb = documentObs[i]; if (docOb._groupId === groupOb.id) { - docs.push(docOb) + docs.push(docOb); } } for (let i = 0; i < docs.length; i++) { - docOb = docs[i] + docOb = docs[i]; groupNode.children.unshift({ label: docOb.name, type: this.treeApi.refType === 'Branch' ? 'view' : 'snapshot', data: docOb, group: groupOb, children: [], - }) + }); } - this._onTreeDataChange().catch(reject) - resolve() + this._onTreeDataChange().catch(reject); + resolve(); }, (reason) => { - reason.message = 'Error getting project Documents: ' + reason.message - reject(reason) + reason.message = 'Error getting project Documents: ' + reason.message; + reject(reason); } - ) - }) - } + ); + }); + }; handleSingleView = (v: ViewObject, aggr: string): TreeBranch => { - let curNode = this.viewId2node[v.id] + let curNode = this.viewId2node[v.id]; if (!curNode) { curNode = { label: v.name, @@ -1106,45 +1106,45 @@ export class TreeService { children: [], loading: true, aggr: aggr, - } - this.viewId2node[v.id] = curNode + }; + this.viewId2node[v.id] = curNode; } - return curNode - } + return curNode; + }; public handleChildren = ( curNode: TreeBranch, childNodes: TreeBranch[], reject: IQResolveReject> ): void => { - const newChildNodes: TreeBranch[] = [] - let node: TreeBranch + const newChildNodes: TreeBranch[] = []; + let node: TreeBranch; for (let i = 0; i < childNodes.length; i++) { - node = childNodes[i] + node = childNodes[i]; if (this.seenViewIds[node.data.id]) { - this.growl.error('Warning: View ' + node.data.name + ' have multiple parents! Duplicates not shown.') - continue + this.growl.error('Warning: View ' + node.data.name + ' have multiple parents! Duplicates not shown.'); + continue; } - this.seenViewIds[node.data.id] = node - newChildNodes.push(node) + this.seenViewIds[node.data.id] = node; + newChildNodes.push(node); } - curNode.children.push(...newChildNodes) - this._onTreeDataChange().catch(reject) + curNode.children.push(...newChildNodes); + this._onTreeDataChange().catch(reject); //this.eventSvc.$broadcast(TreeService.events.RELOAD) - } + }; processDeletedViewBranch = (branch: TreeBranch): void => { - const id = branch.data.id + const id = branch.data.id; if (this.seenViewIds[id]) { - delete this.seenViewIds[id] + delete this.seenViewIds[id]; } if (this.viewId2node[id]) { - delete this.viewId2node[id] + delete this.viewId2node[id]; } for (let i = 0; i < branch.children.length; i++) { - this.processDeletedViewBranch(branch.children[i]) + this.processDeletedViewBranch(branch.children[i]); } - } + }; addSectionElements = ( element: ElementObject, @@ -1153,14 +1153,14 @@ export class TreeService { initial?: boolean ): VePromise => { return new this.$q((resolve, reject) => { - let contents: ValueObject | null = null + let contents: ValueObject | null = null; const addContentsSectionTreeNode = (operand: InstanceValueObject[]): void => { - const bulkGet: string[] = [] - const i = 0 + const bulkGet: string[] = []; + const i = 0; operand.forEach((operator) => { - bulkGet.push(operator.instanceId) - }) + bulkGet.push(operator.instanceId); + }); this.elementSvc .getElements( { @@ -1172,7 +1172,7 @@ export class TreeService { ) .then( (ignore) => { - const instances: VePromise[] = [] + const instances: VePromise[] = []; for (let i = 0; i < operand.length; i++) { instances.push( this.elementSvc.getElement( @@ -1183,12 +1183,12 @@ export class TreeService { }, 0 ) - ) + ); } this.$q.allSettled(instances).then((results) => { - let k = results.length - 1 + let k = results.length - 1; for (; k >= 0; k--) { - const instance: ViewInstanceSpec = results[k].value + const instance: ViewInstanceSpec = results[k].value; if (this.viewSvc.isSection(instance)) { const sectionTreeNode = { label: instance.name ? instance.name : viewNode.data.id, @@ -1196,51 +1196,51 @@ export class TreeService { viewId: viewNode.data.id, data: instance, children: [], - } - this.viewId2node[instance.id] = sectionTreeNode - parentNode.children.unshift(sectionTreeNode) + }; + this.viewId2node[instance.id] = sectionTreeNode; + parentNode.children.unshift(sectionTreeNode); this.addSectionElements(instance, viewNode, sectionTreeNode, initial).catch( reject - ) + ); } else if (this.viewSvc.getTreeType(instance) !== 'none') { const otherTreeNode: TreeBranch = { label: instance.name, type: this.viewSvc.getTreeType(instance), data: instance, children: [], - } + }; if (otherTreeNode.type !== 'view') { - otherTreeNode.viewId = viewNode.data.id + otherTreeNode.viewId = viewNode.data.id; } - parentNode.children.unshift(otherTreeNode) + parentNode.children.unshift(otherTreeNode); } - this._onTreeDataChange().catch(reject) + this._onTreeDataChange().catch(reject); } if (initial) { - this.changeElement().catch(reject) + this.changeElement().catch(reject); } - }, reject) + }, reject); }, (reason) => { - reason.message = 'Error retrieving contained elements: ' + reason.message - reject(reason) + reason.message = 'Error retrieving contained elements: ' + reason.message; + reject(reason); } - ) - } + ); + }; if (element._contents) { - contents = (element as ViewObject)._contents + contents = (element as ViewObject)._contents; } else if (this.viewSvc.isSection(element) && element.specification) { - contents = (element as ViewInstanceSpec).specification // For Sections, the contents expression is the specification + contents = (element as ViewInstanceSpec).specification; // For Sections, the contents expression is the specification } else { //bad? } if (contents && contents.operand) { - addContentsSectionTreeNode((contents as ExpressionObject).operand) + addContentsSectionTreeNode((contents as ExpressionObject).operand); } - resolve() - }) - } + resolve(); + }); + }; } -veCore.service('TreeService', TreeService) +veCore.service('TreeService', TreeService); diff --git a/src/ve-components/trees/tree.controller.ts b/src/ve-components/trees/tree.controller.ts index 7d2e77a9e..fb31f359b 100644 --- a/src/ve-components/trees/tree.controller.ts +++ b/src/ve-components/trees/tree.controller.ts @@ -1,10 +1,10 @@ -import { TreeService } from '@ve-components/trees' -import { RootScopeService, UtilsService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { handleChange } from '@ve-utils/utils' +import { TreeService } from '@ve-components/trees'; +import { RootScopeService, UtilsService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { handleChange } from '@ve-utils/utils'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' -import { TreeBranch, TreeIcons, TreeRow } from '@ve-types/tree' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; +import { TreeBranch, TreeIcons, TreeRow } from '@ve-types/tree'; /** * @ngdoc directive @@ -96,26 +96,26 @@ import { TreeBranch, TreeIcons, TreeRow } from '@ve-types/tree' */ export class TreeController implements angular.IComponentController { //Bindings - toolbarId: string - buttonId: string - showPe: boolean + toolbarId: string; + buttonId: string; + showPe: boolean; - public init: boolean = false + public init: boolean = false; - public treeRows: TreeRow[] = [] - public title - private selectedBranch: any - public treeSpin: boolean = true + public treeRows: TreeRow[] = []; + public title; + private selectedBranch: any; + public treeSpin: boolean = true; - public subs: Rx.IDisposable[] - private treeFilter: angular.uiTreeFilter.IFilterUiTree + public subs: Rx.IDisposable[]; + private treeFilter: angular.uiTreeFilter.IFilterUiTree; //Locals - public icons: TreeIcons - types: string[] - id: string - filter: string + public icons: TreeIcons; + types: string[]; + id: string; + filter: string; static $inject = [ '$q', @@ -127,7 +127,7 @@ export class TreeController implements angular.IComponentController { 'TreeService', 'RootScopeService', 'EventService', - ] + ]; constructor( protected $q: VeQService, @@ -140,27 +140,27 @@ export class TreeController implements angular.IComponentController { protected rootScopeSvc: RootScopeService, protected eventSvc: EventService ) { - this.types = [''] + this.types = ['']; } $onInit(): void { - this.treeFilter = this.$filter('uiTreeFilter') + this.treeFilter = this.$filter('uiTreeFilter'); - this.eventSvc.$init(this) + this.eventSvc.$init(this); this.subs.push( this.eventSvc.binding(TreeService.events.UPDATED, (data) => { if (data) { this.update().catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); } }), this.eventSvc.$on(TreeService.events.RELOAD, (data) => { if ((data && this.id === data) || !data) { - this.treeSpin = true + this.treeSpin = true; this.update().catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); } }), this.eventSvc.$on(TreeService.events.FILTER, (data) => { @@ -169,37 +169,37 @@ export class TreeController implements angular.IComponentController { () => { this.treeSvc.expandPathToSelectedBranch().then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.id) - this.filter = data + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.id); + this.filter = data; }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) + ); }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) + ); } else { // expand all branches so that the filter works correctly this.treeSvc.expandAll().then( () => { - this.eventSvc.$broadcast(TreeService.events.RELOAD, this.id) - this.filter = data + this.eventSvc.$broadcast(TreeService.events.RELOAD, this.id); + this.filter = data; }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) + ); } }) - ) + ); if (this.treeSvc.isTreeReady()) { this.update().catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); } // this.subs.push( @@ -227,108 +227,108 @@ export class TreeController implements angular.IComponentController { 'showPe', () => { this.update().catch((reason) => { - this.growl.error(TreeService.treeError(reason)) - }) + this.growl.error(TreeService.treeError(reason)); + }); }, true - ) + ); } $onDestroy(): void { - this.eventSvc.destroy(this.subs) + this.eventSvc.destroy(this.subs); } update(): VePromise { - this.treeRows = [] - this.setPeVisibility() - this.preConfig() - this.selectedBranch = this.treeSvc.getSelectedBranch() + this.treeRows = []; + this.setPeVisibility(); + this.preConfig(); + this.selectedBranch = this.treeSvc.getSelectedBranch(); - this.icons = this.icons ? this.icons : this.treeSvc.defaultIcons + this.icons = this.icons ? this.icons : this.treeSvc.defaultIcons; - this.treeSvc.defaultIcon = this.icons.iconDefault + this.treeSvc.defaultIcon = this.icons.iconDefault; return new this.$q((resolve, reject) => { this.treeSvc.updateRows(this.id, this.types, this.treeRows).then(() => { - this.treeSpin = false - resolve() - }, reject) - }) + this.treeSpin = false; + resolve(); + }, reject); + }); } public expandCallback = (branch: TreeBranch, e: JQuery.ClickEvent): void => { - branch.loading = true + branch.loading = true; if (!branch.expanded && this.treeSvc.treeApi.expandCallback) { - this.treeSvc.treeApi.expandCallback(branch.data.id, branch, false) + this.treeSvc.treeApi.expandCallback(branch.data.id, branch, false); } if (e) { - e.stopPropagation() + e.stopPropagation(); } - const promise = branch.expanded ? this.treeSvc.closeBranch(branch) : this.treeSvc.expandBranch(branch) + const promise = branch.expanded ? this.treeSvc.closeBranch(branch) : this.treeSvc.expandBranch(branch); promise.then( () => { this.update() .catch((reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); }) .finally(() => { - branch.loading = false - }) + branch.loading = false; + }); }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } - ) - } + ); + }; public userClicksBranch = (branch: TreeBranch): void => { - branch.loading = true + branch.loading = true; this.treeSvc .selectBranch(branch, true) .then( () => { if (branch.onSelect) { - branch.onSelect(branch) + branch.onSelect(branch); } else if (this.treeSvc.treeApi.onSelect) { - this.treeSvc.treeApi.onSelect(branch) + this.treeSvc.treeApi.onSelect(branch); } }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } ) .finally(() => { - branch.loading = false - }) - } + branch.loading = false; + }); + }; public userDblClicksBranch = (branch: TreeBranch): void => { - branch.loading = true + branch.loading = true; this.treeSvc .selectBranch(branch, true) .then( () => { if (branch.onDblClick) { - branch.onDblClick(branch) + branch.onDblClick(branch); } else if (this.treeSvc.treeApi.onDblClick) { - this.treeSvc.treeApi.onDblClick(branch) + this.treeSvc.treeApi.onDblClick(branch); } }, (reason) => { - this.growl.error(TreeService.treeError(reason)) + this.growl.error(TreeService.treeError(reason)); } ) .finally(() => { - branch.loading = false - }) - } + branch.loading = false; + }); + }; protected setPeVisibility = (): void => { //Implement any custom logic for showing PE's here - } + }; protected preConfig = (): void => { //Implement any custom logic that should happen before row generation - } + }; // public getHref = (row: TreeRow): string => { // //var data = row.branch.data; @@ -370,4 +370,4 @@ export const TreeOfAnyComponent: VeComponentOptions = { buttonId: '@', showPe: '<', }, -} +}; diff --git a/src/ve-components/ve-components.module.ts b/src/ve-components/ve-components.module.ts index 0b51bcfbc..944839c74 100644 --- a/src/ve-components/ve-components.module.ts +++ b/src/ve-components/ve-components.module.ts @@ -1,4 +1,4 @@ -import angular from 'angular' +import angular from 'angular'; /** * @@ -10,7 +10,7 @@ export const veComponents = angular.module('ve-components', [ 'ui.bootstrap', 'angular-growl', // 'ngSanitize', -]) +]); // veComponents.config(['$sanitizeProvider', function($sanitizeProvider: angular.sanitize.ISanitizeProvider) { // $sanitizeProvider.addValidElements({ @@ -24,10 +24,10 @@ veComponents .filter('veRealNum', () => { return (n: string | number): string => { if (Number.isInteger(n)) { - return `${n}.0` + return `${n}.0`; } - return n as string - } + return n as string; + }; }) .constant('CKEDITOR', window.CKEDITOR) - .constant('veConfig', window.__env) + .constant('veConfig', window.__env); diff --git a/src/ve-core/button-bar/button-bar.component.ts b/src/ve-core/button-bar/button-bar.component.ts index 13fda9b54..7d9f1d069 100644 --- a/src/ve-core/button-bar/button-bar.component.ts +++ b/src/ve-core/button-bar/button-bar.component.ts @@ -1,10 +1,10 @@ -import { BarButton, ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' -import { veCoreEvents } from '@ve-core/events' -import { EventService } from '@ve-utils/core' +import { BarButton, ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; +import { veCoreEvents } from '@ve-core/events'; +import { EventService } from '@ve-utils/core'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; const ButtonBarComponent: VeComponentOptions = { selector: 'buttonBar', @@ -50,17 +50,17 @@ const ButtonBarComponent: VeComponentOptions = { }, controller: class ButtonBarController implements angular.IComponentController { // Bindings - private buttonId: string - private minSize: number = 100 + private buttonId: string; + private minSize: number = 100; - private bbApi: ButtonBarApi - public init: boolean = false - public buttons: BarButton[] - public dropdownIcon: { [id: string]: string } - private squished: boolean = false - private squishButton: BarButton - private currentHeight: number - static $inject = ['$element', 'growl', 'EventService', 'ButtonBarService'] + private bbApi: ButtonBarApi; + public init: boolean = false; + public buttons: BarButton[]; + public dropdownIcon: { [id: string]: string }; + private squished: boolean = false; + private squishButton: BarButton; + private currentHeight: number; + static $inject = ['$element', 'growl', 'EventService', 'ButtonBarService']; constructor( private $element: JQuery, @@ -72,56 +72,56 @@ const ButtonBarComponent: VeComponentOptions = { $onInit(): void { this.buttonBarSvc.waitForApi(this.buttonId).then( (api) => { - this.bbApi = api - this.buttons = this.bbApi.buttons - this.configure() + this.bbApi = api; + this.buttons = this.bbApi.buttons; + this.configure(); }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); } configure = (): void => { //Setup Squish - this.squishButton = this.buttonBarSvc.getButtonBarButton('button-bar-menu') - this.squishButton.dropdown_buttons = this.buttons - const observed = this.$element.children().get(0) + this.squishButton = this.buttonBarSvc.getButtonBarButton('button-bar-menu'); + this.squishButton.dropdown_buttons = this.buttons; + const observed = this.$element.children().get(0); const observer = new ResizeObserver((mutations) => mutations.forEach((mutationRecord) => { - const size = mutationRecord.borderBoxSize - const oldHeight = this.currentHeight + const size = mutationRecord.borderBoxSize; + const oldHeight = this.currentHeight; this.eventSvc.$broadcast(this.bbApi.WRAP_EVENT, { oldSize: oldHeight, newSize: size[0].blockSize, - }) - this.currentHeight = size[0].blockSize + }); + this.currentHeight = size[0].blockSize; if (size[0].inlineSize <= this.minSize && !this.squished) { - this.squished = true - this.buttons = [this.squishButton] + this.squished = true; + this.buttons = [this.squishButton]; } else if (size[0].inlineSize > this.minSize && this.squished) { - this.squished = false - this.buttons = this.squishButton.dropdown_buttons + this.squished = false; + this.buttons = this.squishButton.dropdown_buttons; } }) - ) + ); - observer.observe(observed) - } + observer.observe(observed); + }; buttonClicked(e: JQuery.ClickEvent, button: BarButton): void { if (button.action) { - button.action(e) + button.action(e); } else { const data: veCoreEvents.buttonClicked = { $event: e, clicked: button.id, - } + }; //Setup fire button-bar click event - this.eventSvc.$broadcast(this.bbApi.id, data) + this.eventSvc.$broadcast(this.bbApi.id, data); } } }, -} +}; -veUtils.component(ButtonBarComponent.selector, ButtonBarComponent) +veUtils.component(ButtonBarComponent.selector, ButtonBarComponent); diff --git a/src/ve-core/button-bar/index.ts b/src/ve-core/button-bar/index.ts index f8e2c1c4a..9dd47e925 100644 --- a/src/ve-core/button-bar/index.ts +++ b/src/ve-core/button-bar/index.ts @@ -1,10 +1,10 @@ -export * from './services/BarButton.api' -export * from './services/ButtonBar.api' +export * from './services/BarButton.api'; +export * from './services/ButtonBar.api'; //Service -import './services/ButtonBar.service' +import './services/ButtonBar.service'; -export * from './services/ButtonBar.service' +export * from './services/ButtonBar.service'; //Components -import './button-bar.component' +import './button-bar.component'; diff --git a/src/ve-core/button-bar/services/BarButton.api.ts b/src/ve-core/button-bar/services/BarButton.api.ts index bf8f274ec..34bbf534e 100644 --- a/src/ve-core/button-bar/services/BarButton.api.ts +++ b/src/ve-core/button-bar/services/BarButton.api.ts @@ -1,123 +1,123 @@ export interface IButtonBarButton { - id: string - icon: string - tooltip: string - placement?: string - button_content?: string - selectable: boolean + id: string; + icon: string; + tooltip: string; + placement?: string; + button_content?: string; + selectable: boolean; //Toggle Config toggle?: | { - icon?: string - tooltip?: string + icon?: string; + tooltip?: string; } - | boolean + | boolean; //Dropdown Config dropdown?: { - icon: string - toggle_icon: string - ids: string[] - } - api?: string - enabledFor?: string[] - disabledFor?: string[] - type?: string + icon: string; + toggle_icon: string; + ids: string[]; + }; + api?: string; + enabledFor?: string[]; + disabledFor?: string[]; + type?: string; } export interface buttonActionFn { - (event?: JQuery.ClickEvent): void + (event?: JQuery.ClickEvent): void; } export class BarButton { //configs - id: string - icon: string = 'fa-gears' - tooltip: string = 'Generic Button' - dropdown_icon: string = '' - button_content: string = '' - placement?: string + id: string; + icon: string = 'fa-gears'; + tooltip: string = 'Generic Button'; + dropdown_icon: string = ''; + button_content: string = ''; + placement?: string; //State - active: boolean = true - selected: boolean = false - permission: boolean = true - toggled: boolean = false - dropdown_toggled: boolean = false - spinner: boolean = false - locked: boolean = false + active: boolean = true; + selected: boolean = false; + permission: boolean = true; + toggled: boolean = false; + dropdown_toggled: boolean = false; + spinner: boolean = false; + locked: boolean = false; //Toggle Configuration //Set Custom Click actions - action?: buttonActionFn + action?: buttonActionFn; - dropdown_buttons: BarButton[] = [] + dropdown_buttons: BarButton[] = []; //Internal - readonly dropdown_icon_original: string - readonly tooltip_original: string - readonly icon_original: string + readonly dropdown_icon_original: string; + readonly tooltip_original: string; + readonly icon_original: string; constructor(id: string, readonly config?: IButtonBarButton) { - this.id = id + this.id = id; if (this.config) { - if (this.config.icon) this.icon = this.icon_original = this.config.icon + if (this.config.icon) this.icon = this.icon_original = this.config.icon; if (this.config.tooltip) { - this.tooltip = this.tooltip_original = this.config.tooltip + this.tooltip = this.tooltip_original = this.config.tooltip; } if (this.config.button_content) { - this.button_content = this.config.button_content + this.button_content = this.config.button_content; } if (this.config.dropdown && this.config.dropdown.icon && this.config.dropdown.icon !== '') { - this.dropdown_icon = this.dropdown_icon_original = this.config.dropdown.icon + this.dropdown_icon = this.dropdown_icon_original = this.config.dropdown.icon; } } } public setAction = (action: buttonActionFn): void => { - this.action = action - } + this.action = action; + }; public toggle = (state?: boolean): void => { if (this.config.toggle) { - this.toggled = state != null ? state : !this.toggled + this.toggled = state != null ? state : !this.toggled; if (this.toggled) { if ((this.config.toggle as { tooltip: string; icon: string }).tooltip) { - this.tooltip = (this.config.toggle as { tooltip: string; icon: string }).tooltip + this.tooltip = (this.config.toggle as { tooltip: string; icon: string }).tooltip; } if ((this.config.toggle as { tooltip: string; icon: string }).icon) { - this.icon = (this.config.toggle as { tooltip: string; icon: string }).icon + this.icon = (this.config.toggle as { tooltip: string; icon: string }).icon; } } else { - this.icon = this.icon_original + this.icon = this.icon_original; if (this.tooltip_original) { - this.tooltip = this.tooltip_original + this.tooltip = this.tooltip_original; } } } if (this.config.dropdown && this.config.dropdown.icon) { - this.dropdown_toggled = state != null ? state : !this.dropdown_toggled + this.dropdown_toggled = state != null ? state : !this.dropdown_toggled; if (this.dropdown_toggled && this.config.dropdown.toggle_icon) { - this.dropdown_icon = this.config.dropdown.toggle_icon + this.dropdown_icon = this.config.dropdown.toggle_icon; } else { - this.dropdown_icon = this.dropdown_icon_original + this.dropdown_icon = this.dropdown_icon_original; } } - } + }; public toggleSpin = (): void => { if (this.spinner) { if (this.toggled && this.config.toggle) { - this.icon = (this.config.toggle as { tooltip: string; icon: string }).icon + this.icon = (this.config.toggle as { tooltip: string; icon: string }).icon; } else { - this.icon = this.icon_original + this.icon = this.icon_original; } } else { - this.icon = 'fa fa-spinner fa-spin' + this.icon = 'fa fa-spinner fa-spin'; } - this.spinner = !this.spinner - } + this.spinner = !this.spinner; + }; public toggleLock = (): void => { - this.locked = !this.locked - } + this.locked = !this.locked; + }; } diff --git a/src/ve-core/button-bar/services/ButtonBar.api.ts b/src/ve-core/button-bar/services/ButtonBar.api.ts index 9352322b1..953750a72 100644 --- a/src/ve-core/button-bar/services/ButtonBar.api.ts +++ b/src/ve-core/button-bar/services/ButtonBar.api.ts @@ -1,117 +1,117 @@ -import { BarButton } from '@ve-core/button-bar' +import { BarButton } from '@ve-core/button-bar'; export interface ButtonWrapEvent { - oldSize: number - newSize: number + oldSize: number; + newSize: number; } export class ButtonBarApi { - public buttons: BarButton[] = [] - public WRAP_EVENT: string + public buttons: BarButton[] = []; + public WRAP_EVENT: string; constructor(public id: string) { if (this.id === '') { - this.id = 'unknown' + this.id = 'unknown'; } - this.WRAP_EVENT = `${id}-wrap` + this.WRAP_EVENT = `${id}-wrap`; } public getId = (): string => { - return this.id - } + return this.id; + }; public select = (parentButton: BarButton, childButton: BarButton): void => { if (parentButton && childButton && childButton.config.selectable) { parentButton.dropdown_buttons.forEach((dropdownButton) => { if (parentButton.config.dropdown) { if (dropdownButton.id === childButton.id) { - dropdownButton.selected = dropdownButton.selected ? !dropdownButton.selected : true + dropdownButton.selected = dropdownButton.selected ? !dropdownButton.selected : true; } } else { - dropdownButton.selected = dropdownButton.id === childButton.id + dropdownButton.selected = dropdownButton.id === childButton.id; } - }) + }); } - } + }; public deselect = (parentButton: BarButton, childButton: BarButton): void => { if (parentButton && childButton) { parentButton.dropdown_buttons.forEach((dropdownButton) => { if (parentButton.config.dropdown) { if (dropdownButton.id === childButton.id) { - dropdownButton.selected = false + dropdownButton.selected = false; } } - }) + }); } - } + }; public setPermission = (id: string, permission: boolean): void => { this.buttons.forEach((button) => { - if (button.id === id) button.permission = permission - }) - } + if (button.id === id) button.permission = permission; + }); + }; public setActive = (id: string, state: boolean, parent?: string): void => { this.buttons.forEach((button) => { if (parent && button.id === parent && button.dropdown_buttons) { button.dropdown_buttons.forEach((child) => { - if (child.id === id) child.active = state - }) + if (child.id === id) child.active = state; + }); } - if (button.id === id) button.active = state - }) - } + if (button.id === id) button.active = state; + }); + }; public addButton = (button: BarButton): void => { if (this.buttons.length === 0) { - button.placement = 'bottom-left' + button.placement = 'bottom-left'; } else if (!button.placement) { // else { - button.placement = 'bottom' + button.placement = 'bottom'; } - this.buttons.push(button) - } + this.buttons.push(button); + }; public toggleButtonSpinner = (id: string): void => { this.buttons.forEach((button) => { - if (button.id === id) button.toggleSpin() - else button.toggleLock() - }) - } + if (button.id === id) button.toggleSpin(); + else button.toggleLock(); + }); + }; public toggleButton = (id: string, state?: boolean): void => { this.buttons.forEach((button) => { - if (button.id === id) button.toggle(state) - }) - } + if (button.id === id) button.toggle(state); + }); + }; public checkActive = (cb: (enableState: string) => boolean, parent?: BarButton): void => { - const buttons = parent ? parent.dropdown_buttons : this.buttons + const buttons = parent ? parent.dropdown_buttons : this.buttons; buttons.forEach((button) => { - const config = button.config + const config = button.config; if (config) { if (config.enabledFor) { - this.setActive(button.id, false, parent ? parent.id : null) + this.setActive(button.id, false, parent ? parent.id : null); for (const enableState of config.enabledFor) { if (cb(enableState)) { - this.setActive(button.id, true, parent ? parent.id : null) - break + this.setActive(button.id, true, parent ? parent.id : null); + break; } } } if (config.disabledFor) { for (const disableState of config.disabledFor) { if (cb(disableState)) { - this.setActive(button.id, false, parent ? parent.id : null) - break + this.setActive(button.id, false, parent ? parent.id : null); + break; } } } } if (button.dropdown_buttons.length > 0) { - this.checkActive(cb, button) + this.checkActive(cb, button); } - }) - } + }); + }; } diff --git a/src/ve-core/button-bar/services/ButtonBar.service.ts b/src/ve-core/button-bar/services/ButtonBar.service.ts index ede0f0605..eb5bebe0f 100644 --- a/src/ve-core/button-bar/services/ButtonBar.service.ts +++ b/src/ve-core/button-bar/services/ButtonBar.service.ts @@ -1,12 +1,12 @@ -import { BarButton, ButtonBarApi, IButtonBarButton } from '@ve-core/button-bar' -import { EventService } from '@ve-utils/core' +import { BarButton, ButtonBarApi, IButtonBarButton } from '@ve-core/button-bar'; +import { EventService } from '@ve-utils/core'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { VeConfig } from '@ve-types/config' -import { EditorActions } from '@ve-types/core/editor' -import { VeApiObject } from '@ve-types/view-editor' +import { VePromise, VeQService } from '@ve-types/angular'; +import { VeConfig } from '@ve-types/config'; +import { EditorActions } from '@ve-types/core/editor'; +import { VeApiObject } from '@ve-types/view-editor'; const default_buttons: IButtonBarButton[] = [ { @@ -21,31 +21,31 @@ const default_buttons: IButtonBarButton[] = [ ids: [], }, }, -] +]; export interface buttonInitFn { - (api: ButtonBarApi): void + (api: ButtonBarApi): void; } export class ButtonBarService { - static $inject = ['$q', 'EventService'] + static $inject = ['$q', 'EventService']; - private barCounter: { [id: string]: number } = {} - private buttons: { [key: string]: IButtonBarButton } = {} - private buttonBars: VeApiObject = {} - private veConfig: VeConfig + private barCounter: { [id: string]: number } = {}; + private buttons: { [key: string]: IButtonBarButton } = {}; + private buttonBars: VeApiObject = {}; + private veConfig: VeConfig; constructor(private $q: VeQService, private eventSvc: EventService) { for (const button of default_buttons) { - this.buttons[button.id] = button + this.buttons[button.id] = button; } - this.veConfig = window.__env + this.veConfig = window.__env; if (this.veConfig.expConfig) { for (const ext of Object.keys(this.veConfig.expConfig)) { if (this.veConfig.expConfig[ext] && this.veConfig.expConfig[ext].length > 0) { for (const tool of this.veConfig.expConfig[ext]) { if (tool.barButtons) { - this.registerButtons(tool.barButtons) + this.registerButtons(tool.barButtons); } } } @@ -55,104 +55,104 @@ export class ButtonBarService { public waitForApi = (id: string): VePromise => { if (!this.buttonBars.hasOwnProperty(id)) { - this.buttonBars[id] = {} + this.buttonBars[id] = {}; this.buttonBars[id].promise = new this.$q((resolve, reject) => { - this.buttonBars[id].resolve = resolve - this.buttonBars[id].reject = reject - }) + this.buttonBars[id].resolve = resolve; + this.buttonBars[id].reject = reject; + }); } - return this.buttonBars[id].promise - } + return this.buttonBars[id].promise; + }; public generateBarId = (root?: string): string => { if (!root) { - root = 'button_bar' + root = 'button_bar'; } - if (!this.barCounter[root]) this.barCounter[root] = 1 - else this.barCounter[root]++ - return `${root}_${this.barCounter[root]}` - } + if (!this.barCounter[root]) this.barCounter[root] = 1; + else this.barCounter[root]++; + return `${root}_${this.barCounter[root]}`; + }; public initApi(id: string, init: buttonInitFn, buttons?: IButtonBarButton[]): ButtonBarApi { if (!init) { - return null + return null; } - const api = new ButtonBarApi(id) + const api = new ButtonBarApi(id); if (buttons && buttons.length > 0) { - this.registerButtons(buttons) + this.registerButtons(buttons); } - init(api) + init(api); if (!this.buttonBars[id]) { this.buttonBars[id] = { api, - } + }; } else { - this.buttonBars[id].api = api + this.buttonBars[id].api = api; } if (!this.buttonBars[id].resolve) { this.buttonBars[id].promise = new this.$q((resolve, reject) => { - this.buttonBars[id].resolve = resolve - this.buttonBars[id].reject = reject - }) + this.buttonBars[id].resolve = resolve; + this.buttonBars[id].reject = reject; + }); } - this.buttonBars[id].resolve(api) - return api + this.buttonBars[id].resolve(api); + return api; } destroy(id: string): void { if (this.buttonBars.hasOwnProperty(id)) { - delete this.buttonBars[id] + delete this.buttonBars[id]; } } destroyAll(ids: string[]): void { ids.forEach((bbId) => { - this.destroy(bbId) - }) + this.destroy(bbId); + }); } getButtonBarButton = (buttonId: string, ctrl?: EditorActions): BarButton => { if (this.buttons.hasOwnProperty(buttonId)) { - const newButton = new BarButton(buttonId, this.buttons[buttonId]) + const newButton = new BarButton(buttonId, this.buttons[buttonId]); if (this.buttons[buttonId].dropdown) { - newButton.dropdown_buttons = [] + newButton.dropdown_buttons = []; for (const id of this.buttons[buttonId].dropdown.ids) { - newButton.dropdown_buttons.push(this.getButtonBarButton(id, ctrl)) + newButton.dropdown_buttons.push(this.getButtonBarButton(id, ctrl)); } } if (this.buttons[buttonId].api && ctrl && ctrl[this.buttons[buttonId].api]) { newButton.setAction((event): void => { - if (event) event.stopPropagation() - ;(ctrl[this.buttons[buttonId].api] as () => void)() - }) + if (event) event.stopPropagation(); + (ctrl[this.buttons[buttonId].api] as () => void)(); + }); } - return newButton + return newButton; } else { - return new BarButton(buttonId) + return new BarButton(buttonId); } - } + }; getButtonDefinition = (buttonId: string): IButtonBarButton => { if (this.buttons.hasOwnProperty(buttonId)) { - return this.buttons[buttonId] + return this.buttons[buttonId]; } - return null - } + return null; + }; public registerButtons = (buttons: IButtonBarButton | IButtonBarButton[]): void => { if (!Array.isArray(buttons)) { - buttons = [buttons] + buttons = [buttons]; } if (buttons.length > 0) { for (const button of buttons) { if (!this.buttons[button.id]) { - this.buttons[button.id] = button + this.buttons[button.id] = button; } } } - } + }; } -veUtils.service('ButtonBarService', ButtonBarService) +veUtils.service('ButtonBarService', ButtonBarService); diff --git a/src/ve-core/editor/components/mention-intercept.component.ts b/src/ve-core/editor/components/mention-intercept.component.ts index 076a0efd3..dca4f8fc8 100644 --- a/src/ve-core/editor/components/mention-intercept.component.ts +++ b/src/ve-core/editor/components/mention-intercept.component.ts @@ -1,25 +1,25 @@ -import { MMSMentionController } from '@ve-core/editor/components/mention.component' +import { MMSMentionController } from '@ve-core/editor/components/mention.component'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { ElementObject } from '@ve-types/mms' +import { ElementObject } from '@ve-types/mms'; class MMSMentionInterceptController implements angular.IComponentController { - public mmsMentionInterceptValue: string - mmsFastCf: ElementObject[] + public mmsMentionInterceptValue: string; + mmsFastCf: ElementObject[]; - private ngModel: angular.INgModelController - mentionCtrl: MMSMentionController + private ngModel: angular.INgModelController; + mentionCtrl: MMSMentionController; $onChanges(changes: angular.IOnChangesObject): void { if (changes.mmsMentionInterceptValue) { - this.ngModel.$setViewValue(changes.mmsMentionInterceptValue.currentValue) - this.ngModel.$render() + this.ngModel.$setViewValue(changes.mmsMentionInterceptValue.currentValue); + this.ngModel.$render(); } } public selectMentionItem($item: ElementObject): void { - this.mentionCtrl.selectMentionItem($item) + this.mentionCtrl.selectMentionItem($item); } } @@ -45,6 +45,6 @@ const MMSMentionIntercept = { mmsMentionId: '<', }, controller: MMSMentionInterceptController, -} +}; -veCore.component(MMSMentionIntercept.selector, MMSMentionIntercept) +veCore.component(MMSMentionIntercept.selector, MMSMentionIntercept); diff --git a/src/ve-core/editor/components/mention.component.ts b/src/ve-core/editor/components/mention.component.ts index 2baf429a4..273cb4ed3 100644 --- a/src/ve-core/editor/components/mention.component.ts +++ b/src/ve-core/editor/components/mention.component.ts @@ -1,32 +1,32 @@ -import { EditorService, MentionService } from '@ve-core/editor' +import { EditorService, MentionService } from '@ve-core/editor'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { ElementObject } from '@ve-types/mms' +import { ElementObject } from '@ve-types/mms'; export class MMSMentionController implements angular.IComponentController { //Bindings - public mmsEditor: CKEDITOR.editor - mmsMentionValue: string - mmsMentionId: string - mmsProjectId: string - mmsRefId: string + public mmsEditor: CKEDITOR.editor; + mmsMentionValue: string; + mmsMentionId: string; + mmsProjectId: string; + mmsRefId: string; //Local - public fastCfListing: ElementObject[] + public fastCfListing: ElementObject[]; - static $inject = ['MentionService', 'EditorService'] + static $inject = ['MentionService', 'EditorService']; constructor(private mentionSvc: MentionService, private editorSvc: EditorService) {} $onInit(): void { - this.fastCfListing = this.mentionSvc.getFastCfListing(this.mmsProjectId, this.mmsRefId) + this.fastCfListing = this.mentionSvc.getFastCfListing(this.mmsProjectId, this.mmsRefId); // expose this api on the controller itself so that it can be accessed by codes that use $compile service to construct this directive. } public selectMentionItem($item: ElementObject): void { - this._createCf($item) - this.mentionSvc.handleMentionSelection(this.mmsEditor, this.mmsMentionId) + this._createCf($item); + this.mentionSvc.handleMentionSelection(this.mmsEditor, this.mmsMentionId); } private _createCf($item: ElementObject): void { @@ -39,9 +39,9 @@ export class MMSMentionController implements angular.IComponentController { $item.name + '.' + $item.type + - ']
    ' - this.mmsEditor.insertHtml(tag) - this.editorSvc.focusOnEditorAfterAddingWidgetTag(this.mmsEditor) + ']
    '; + this.mmsEditor.insertHtml(tag); + this.editorSvc.focusOnEditorAfterAddingWidgetTag(this.mmsEditor); } } @@ -85,6 +85,6 @@ const MMSMention = { mmsRefId: '<', }, controller: MMSMentionController, -} +}; -veCore.component(MMSMention.selector, MMSMention) +veCore.component(MMSMention.selector, MMSMention); diff --git a/src/ve-core/editor/editor-buttons.config.ts b/src/ve-core/editor/editor-buttons.config.ts index 6c14fa59d..1c760c53f 100644 --- a/src/ve-core/editor/editor-buttons.config.ts +++ b/src/ve-core/editor/editor-buttons.config.ts @@ -1,4 +1,4 @@ -import { IButtonBarButton } from '@ve-core/button-bar' +import { IButtonBarButton } from '@ve-core/button-bar'; export const editor_buttons: IButtonBarButton[] = [ { @@ -43,4 +43,4 @@ export const editor_buttons: IButtonBarButton[] = [ tooltip: 'Preview Changes', api: 'preview', }, -] +]; diff --git a/src/ve-core/editor/editor.component.ts b/src/ve-core/editor/editor.component.ts index 82c23ac31..ff423a414 100644 --- a/src/ve-core/editor/editor.component.ts +++ b/src/ve-core/editor/editor.component.ts @@ -1,22 +1,22 @@ -import angular, { IComponentController } from 'angular' -import $ from 'jquery' -import _, { DebouncedFunc } from 'lodash' +import angular, { IComponentController } from 'angular'; +import $ from 'jquery'; +import _, { DebouncedFunc } from 'lodash'; -import { InsertTransclusionData } from '@ve-components/transclusions' -import { MentionService } from '@ve-core/editor' -import { EditorService } from '@ve-core/editor/services/Editor.service' -import { ImageService } from '@ve-utils/application' -import { ApiService, ElementService, URLService, ViewService } from '@ve-utils/mms-api-client' +import { InsertTransclusionData } from '@ve-components/transclusions'; +import { MentionService } from '@ve-core/editor'; +import { EditorService } from '@ve-core/editor/services/Editor.service'; +import { ImageService } from '@ve-utils/application'; +import { ApiService, ElementService, URLService, ViewService } from '@ve-utils/mms-api-client'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import eventDataTypes = CKEDITOR.eventDataTypes +import eventDataTypes = CKEDITOR.eventDataTypes; -import { VeComponentOptions, VeNgModelController, VePromise, VeQService } from '@ve-types/angular' -import { InsertData, InsertResolveFn } from '@ve-types/components' -import { VeConfig } from '@ve-types/config' -import { ElementObject, ElementsResponse, TransclusionObject } from '@ve-types/mms' -import { VeModalService, VeModalSettings } from '@ve-types/view-editor' +import { VeComponentOptions, VeNgModelController, VePromise, VeQService } from '@ve-types/angular'; +import { InsertData, InsertResolveFn } from '@ve-types/components'; +import { VeConfig } from '@ve-types/config'; +import { ElementObject, ElementsResponse, TransclusionObject } from '@ve-types/mms'; +import { VeModalService, VeModalSettings } from '@ve-types/view-editor'; /** * @ngdoc directive @@ -44,49 +44,49 @@ import { VeModalService, VeModalSettings } from '@ve-types/view-editor' */ export class EditorController implements IComponentController { - private veConfig: VeConfig = window.__env - private ckEditor = window.CKEDITOR + private veConfig: VeConfig = window.__env; + private ckEditor = window.CKEDITOR; - private ngModelCtrl: VeNgModelController - private ngModel: string + private ngModelCtrl: VeNgModelController; + private ngModel: string; - mmsElementId: string - mmsProjectId: string - mmsRefId: string - private editorType: string - private editField: 'name' | 'value' | 'documentation' = 'documentation' - private editKey: string | string[] - private editIndex: string = '' + mmsElementId: string; + mmsProjectId: string; + mmsRefId: string; + private editorType: string; + private editField: 'name' | 'value' | 'documentation' = 'documentation'; + private editKey: string | string[]; + private editIndex: string = ''; private stylesToolbar = { name: 'styles', items: ['Styles', /*'Format',*/ 'FontSize', 'TextColor', 'BGColor'], - } + }; private basicStylesToolbar = { name: 'basicstyles', //items: ['Bold', 'Italic', 'Underline', 'mmsExtraFormat'], items: ['Bold', 'Italic', 'Underline'], - } - private clipboardToolbar = { name: 'clipboard', items: ['Undo', 'Redo'] } + }; + private clipboardToolbar = { name: 'clipboard', items: ['Undo', 'Redo'] }; private justifyToolbar = { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight'], - } - private editingToolbar = { name: 'editing', items: ['Find', 'Replace'] } - private linksToolbar = { name: 'links', items: ['Link', 'Unlink', '-'] } - private imageToolbar = { name: 'image', items: ['Image', 'Iframe'] } + }; + private editingToolbar = { name: 'editing', items: ['Find', 'Replace'] }; + private linksToolbar = { name: 'links', items: ['Link', 'Unlink', '-'] }; + private imageToolbar = { name: 'image', items: ['Image', 'Iframe'] }; private listToolbar = { name: 'list', items: ['NumberedList', 'BulletedList', 'Outdent', 'Indent'], - } + }; private equationToolbar = { name: 'equation', items: ['Mathjax', 'SpecialChar'], - } + }; private sourceToolbar = { name: 'source', items: ['Maximize', 'Sourcedialog'], - } + }; private combinedToolbar = { name: 'combined', items: [ @@ -100,19 +100,19 @@ export class EditorController implements IComponentController { 'Mmscomment', //'mmsExtraFeature', ], - } - private tableEquationToolbar = { name: 'tableEquation', items: ['Table', 'Mathjax', 'SpecialChar', '-'] } + }; + private tableEquationToolbar = { name: 'tableEquation', items: ['Table', 'Mathjax', 'SpecialChar', '-'] }; - private extrasToolbar = { name: 'extras', items: ['mmsExtraFeature'] } + private extrasToolbar = { name: 'extras', items: ['mmsExtraFeature'] }; - protected $transcludeEl: JQuery - public id: string - protected init: boolean = false + protected $transcludeEl: JQuery; + public id: string; + protected init: boolean = false; - private instance: CKEDITOR.editor = null - private deb: DebouncedFunc<(e) => void> + private instance: CKEDITOR.editor = null; + private deb: DebouncedFunc<(e) => void>; - private tokenStr: RegExp = new RegExp('([?&]token=[a-zA-Z0-9.]*)') + private tokenStr: RegExp = new RegExp('([?&]token=[a-zA-Z0-9.]*)'); static $inject = [ '$compile', @@ -130,7 +130,7 @@ export class EditorController implements IComponentController { 'MentionService', 'EditorService', 'ImageService', - ] + ]; /** * @@ -169,51 +169,51 @@ export class EditorController implements IComponentController { ) { this.deb = _.debounce((e) => { this.update().catch(() => { - this.growl.error('Error saving editor content') - }) - }, 1000) + this.growl.error('Error saving editor content'); + }); + }, 1000); } $onChanges(onChangesObj: angular.IOnChangesObject): void { if (onChangesObj.ngModel && !this.init) { - this.init = true + this.init = true; - this.id = this.editorSvc.createId() + this.id = this.editorSvc.createId(); this.editKey = this.elementSvc.getEditKey({ refId: this.mmsRefId, projectId: this.mmsProjectId, elementId: this.mmsElementId, - }) + }); if (this.editKey) { this.editorSvc.add( this.editKey, `${this.editField}${this.editIndex ? this.editIndex : ''}`, this.update - ) + ); } - this.startEditor() + this.startEditor(); } } $onDestroy(): void { - this.destroy() + this.destroy(); } public destroy(): void { - this.instance.config.autosave = { enableAutosave: false } - this.editorSvc.remove(this.editKey, `${this.editField}${this.editIndex ? this.editIndex : ''}`) - if (this.ckEditor.instances[this.id]) this.ckEditor.instances[this.id].destroy(true) + this.instance.config.autosave = { enableAutosave: false }; + this.editorSvc.remove(this.editKey, `${this.editField}${this.editIndex ? this.editIndex : ''}`); + if (this.ckEditor.instances[this.id]) this.ckEditor.instances[this.id].destroy(true); } public startEditor(): void { // Initialize ckeditor and set event handlers - if (this.ckEditor.instances[this.id]) return - this.$element.empty() - this.$transcludeEl = $(``) - this.$transcludeEl.val(this.ngModel) + if (this.ckEditor.instances[this.id]) return; + this.$element.empty(); + this.$transcludeEl = $(``); + this.$transcludeEl.val(this.ngModel); - this.$element.append(this.$transcludeEl) - this.$compile(this.$transcludeEl)(this.$scope) + this.$element.append(this.$transcludeEl); + this.$compile(this.$transcludeEl)(this.$scope); this.instance = this.ckEditor.replace(this.id, { mmscf: { callbackModalFnc: this.transcludeCallback }, @@ -222,7 +222,7 @@ export class EditorController implements IComponentController { mmsreset: { callback: this.mmsResetCallback }, contentsCss: `${this.ckEditor.basePath}contents.css`, toolbar: this.getToolbar(), - }) + }); // Enable Autosave plugin only when provided with unique identifier (editKey) if (this.editKey) { @@ -234,44 +234,44 @@ export class EditorController implements IComponentController { delay: 5, NotOlderThen: 7200, // 5 days in minutes enableAutosave: true, - } + }; } else { - this.instance.config.autosave = { enableAutosave: false } + this.instance.config.autosave = { enableAutosave: false }; } this.instance.on('instanceReady', () => { - this.addCkeditorHtmlFilterRule(this.instance) - this._addContextMenuItems(this.instance) - this.highlightActiveEditor(this.instance) - }) + this.addCkeditorHtmlFilterRule(this.instance); + this._addContextMenuItems(this.instance); + this.highlightActiveEditor(this.instance); + }); - this._addInlineMention() + this._addInlineMention(); this.instance.on( 'toHtml', () => { - this.addCkeditorDataFilterRules(this.instance) + this.addCkeditorDataFilterRules(this.instance); }, null, null, 9 - ) + ); this.instance.on('init', () => { this._waitForEditor(() => { - this.ngModelCtrl.$setPristine() - }) - }) - - this.instance.on('change', (e) => this._waitForEditor(this.deb, e)) - this.instance.on('afterCommandExec', (e) => this._waitForEditor(this.deb, e)) - this.instance.on('resize', (e) => this._waitForEditor(this.deb, e)) - this.instance.on('beforeDestroy', (e) => this._waitForEditor(this.deb, e)) + this.ngModelCtrl.$setPristine(); + }); + }); + + this.instance.on('change', (e) => this._waitForEditor(this.deb, e)); + this.instance.on('afterCommandExec', (e) => this._waitForEditor(this.deb, e)); + this.instance.on('resize', (e) => this._waitForEditor(this.deb, e)); + this.instance.on('beforeDestroy', (e) => this._waitForEditor(this.deb, e)); this.instance.on('blur', () => this._waitForEditor(() => { - this.instance.focusManager.blur() + this.instance.focusManager.blur(); }) - ) + ); this.instance.on( 'key', (e: CKEDITOR.eventInfo) => @@ -279,13 +279,13 @@ export class EditorController implements IComponentController { null, null, 31 - ) //priority is after indent list plugin's event handler + ); //priority is after indent list plugin's event handler this.instance.on('fileUploadRequest', (e: CKEDITOR.eventInfo) => { //this._waitForEditor((evt) => { - const fileLoader = e.data.fileLoader - const formData = new FormData() - const xhr = fileLoader.xhr + const fileLoader = e.data.fileLoader; + const formData = new FormData(); + const xhr = fileLoader.xhr; xhr.open( 'POST', @@ -295,31 +295,31 @@ export class EditorController implements IComponentController { elementId: this.apiSvc.createUniqueId().replace('MMS', '_hidden_image'), }), true - ) + ); //xhr.withCredentials = true; - xhr.setRequestHeader('Authorization', this.uRLSvc.getAuthorizationHeaderValue()) - formData.append('file', fileLoader.file, fileLoader.fileName) + xhr.setRequestHeader('Authorization', this.uRLSvc.getAuthorizationHeaderValue()); + formData.append('file', fileLoader.file, fileLoader.fileName); if (fileLoader.fileName) { - formData.append('name', fileLoader.fileName) + formData.append('name', fileLoader.fileName); } - fileLoader.xhr.send(formData) + fileLoader.xhr.send(formData); // Prevented the default behavior. - e.stop() + e.stop(); //}, e) - }) + }); this.instance.on('fileUploadResponse', (e: CKEDITOR.eventInfo) => { //this._waitForEditor((evt) => { // Prevent the default response handler. - e.stop() + e.stop(); // Get XHR and response. - const data = e.data - const xhr = data.fileLoader.xhr + const data = e.data; + const xhr = data.fileLoader.xhr; const response: ElementsResponse = JSON.parse( xhr.response as string - ) as ElementsResponse + ) as ElementsResponse; if ( !response.elements || @@ -329,54 +329,54 @@ export class EditorController implements IComponentController { ) { // An error occurred during upload. //data.message = response[ 1 ]; - e.cancel() + e.cancel(); } else { //TODO does this need to be smarter? - const element = response.elements[0] + const element = response.elements[0]; data.url = this.uRLSvc.getArtifactURL({ projectId: element._projectId, refId: element._refId, elementId: element.id, artifactExtension: element._artifacts[0].extension, - }) + }); } //}, e) - }) + }); } public highlightActiveEditor = (instance: CKEDITOR.editor): void => { - const activeEditorClass = 'activeditor' - $('transclude-doc').children('div').removeClass(activeEditorClass) - $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass) + const activeEditorClass = 'activeditor'; + $('transclude-doc').children('div').removeClass(activeEditorClass); + $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass); instance.on('focus', () => { - $('transclude-doc').children('div').removeClass(activeEditorClass) - $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass) - }) - } + $('transclude-doc').children('div').removeClass(activeEditorClass); + $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass); + }); + }; public addCkeditorDataFilterRules = (instance: CKEDITOR.editor): void => { instance.dataProcessor.dataFilter.addRules({ elements: { $: (element: CKEDITOR.htmlParser.element) => { if (element.name === 'script') { - element.remove() - return + element.remove(); + return; } if (element.name.startsWith('transclude-') || element.name.startsWith('present-')) { - element.replaceWithChildren() - return + element.replaceWithChildren(); + return; } const attributesToDelete = Object.keys(element.attributes).filter((attrKey) => { - return attrKey.startsWith('ng-') - }) + return attrKey.startsWith('ng-'); + }); attributesToDelete.forEach((attrToDelete) => { - delete element.attributes[attrToDelete] - }) + delete element.attributes[attrToDelete]; + }); }, }, - }) + }); instance.dataProcessor.dataFilter.addRules({ elements: { // Adds the token to img's in the editor environment to allow images to be displayed while editor @@ -388,39 +388,39 @@ export class EditorController implements IComponentController { el.attributes['data-cke-saved-src'] && (el.attributes['data-cke-saved-src'].indexOf(this.veConfig.apiUrl) > -1 || el.attributes['data-cke-saved-src'].indexOf('http') < 0) - ) + ); }, true) .forEach((el: CKEDITOR.htmlParser.element) => { - el.attributes['src'] = this.imageSvc.fixImgUrl(el.attributes['data-cke-saved-src'], true) + el.attributes['src'] = this.imageSvc.fixImgUrl(el.attributes['data-cke-saved-src'], true); // el.attributes['src'] = el.attributes['data-cke-saved-src']; - }) + }); }, }, - }) - } + }); + }; public addCkeditorHtmlFilterRule = (instance: CKEDITOR.editor): void => { instance.dataProcessor.htmlFilter.addRules({ elements: { $: (element: CKEDITOR.htmlParser.element) => { if (element.name === 'script') { - element.remove() - return + element.remove(); + return; } if (element.name.startsWith('transclude-') || element.name.startsWith('present-')) { - element.replaceWithChildren() - return + element.replaceWithChildren(); + return; } const attributesToDelete = Object.keys(element.attributes).filter((attrKey) => { - return attrKey.startsWith('ng-') - }) + return attrKey.startsWith('ng-'); + }); attributesToDelete.forEach((attrToDelete) => { - delete element.attributes[attrToDelete] - }) + delete element.attributes[attrToDelete]; + }); }, }, - }) + }); instance.dataProcessor.htmlFilter.addRules({ elements: { // Removes the token from the export src to prevent saving of token to server @@ -431,36 +431,36 @@ export class EditorController implements IComponentController { el.name == 'img' && el.attributes['data-cke-saved-src'] && el.attributes['data-cke-saved-src'].indexOf(this.veConfig.apiUrl) > -1 - ) + ); }, true) .forEach((el: CKEDITOR.htmlParser.element) => { el.attributes['data-cke-saved-src'] = this.imageSvc.fixImgUrl( el.attributes['data-cke-saved-src'], false - ) + ); // el.attributes['src'] = el.attributes['data-cke-saved-src']; - }) + }); }, }, - }) - } + }); + }; public getToolbar(): Array< | string | string[] | { - name: string - items?: string[] | undefined - groups?: string[] | undefined + name: string; + items?: string[] | undefined; + groups?: string[] | undefined; } > { let thisToolbar: Array< | string | string[] | { - name: string - items?: string[] | undefined - groups?: string[] | undefined + name: string; + items?: string[] | undefined; + groups?: string[] | undefined; } > = [ this.stylesToolbar, @@ -472,7 +472,7 @@ export class EditorController implements IComponentController { this.clipboardToolbar, this.editingToolbar, this.sourceToolbar, - ] + ]; switch (this.editorType) { // case 'TableT': // thisToolbar = [ @@ -499,17 +499,17 @@ export class EditorController implements IComponentController { this.clipboardToolbar, this.editingToolbar, this.sourceToolbar, - ] - break + ]; + break; case 'Equation': - thisToolbar = [this.justifyToolbar, this.equationToolbar, this.sourceToolbar] - break + thisToolbar = [this.justifyToolbar, this.equationToolbar, this.sourceToolbar]; + break; case 'Figure': case 'ImageT': - thisToolbar = [this.justifyToolbar, this.imageToolbar, this.sourceToolbar] - break + thisToolbar = [this.justifyToolbar, this.imageToolbar, this.sourceToolbar]; + break; } - return thisToolbar + return thisToolbar; } public transcludeCallback = (editor: CKEDITOR.editor): void => { @@ -521,30 +521,30 @@ export class EditorController implements IComponentController { type: 'Transclusion', viewLink: false, insertType: 'transclusion', - } + }; }, getProjectId: () => { - return this.mmsProjectId + return this.mmsProjectId; }, getRefId: () => { - return this.mmsRefId + return this.mmsRefId; }, getOrgId: () => { - return '' + return ''; }, }, size: 'lg', - } - const tInstance = this.$uibModal.open, TransclusionObject>(tSettings) + }; + const tInstance = this.$uibModal.open, TransclusionObject>(tSettings); tInstance.result.then( (result) => { - this._addWidgetTag(result.tag, editor) + this._addWidgetTag(result.tag, editor); }, () => { - editor.focus() + editor.focus(); } - ) - } + ); + }; // Controller for inserting view link // Defines scope variables for html template and how to handle user click @@ -560,30 +560,30 @@ export class EditorController implements IComponentController { type: 'ViewLink', viewLink: true, insertType: 'transclusion', - } + }; }, getProjectId: () => { - return this.mmsProjectId + return this.mmsProjectId; }, getRefId: () => { - return this.mmsRefId + return this.mmsRefId; }, getOrgId: () => { - return '' + return ''; }, }, size: 'lg', - } - const tInstance = this.$uibModal.open, TransclusionObject>(tSettings) + }; + const tInstance = this.$uibModal.open, TransclusionObject>(tSettings); tInstance.result.then( (result) => { - this._addWidgetTag(result.tag, editor) + this._addWidgetTag(result.tag, editor); }, () => { - editor.focus() + editor.focus(); } - ) - } + ); + }; public commentCallback = (editor: CKEDITOR.editor): void => { const cSettings: VeModalSettings> = { @@ -593,111 +593,111 @@ export class EditorController implements IComponentController { return { type: 'Comment', insertType: 'comment', - } + }; }, getProjectId: () => { - return this.mmsProjectId + return this.mmsProjectId; }, getRefId: () => { - return this.mmsRefId + return this.mmsRefId; }, getOrgId: () => { - return '' + return ''; }, }, - } - const cInstance = this.$uibModal.open, ElementObject>(cSettings) + }; + const cInstance = this.$uibModal.open, ElementObject>(cSettings); cInstance.result.then( (data) => { const tag = - 'comment:' + data._creator + '' - this._addWidgetTag(tag, editor) + 'comment:' + data._creator + ''; + this._addWidgetTag(tag, editor); }, (reason) => { if (reason && reason.status !== 444) { - this.growl.warning(`Error adding Comment: ${reason.message}`) + this.growl.warning(`Error adding Comment: ${reason.message}`); } else { this.growl.info('Commenting Cancelled', { ttl: 1000, - }) + }); } } - ) - } + ); + }; public resetCrossRef = (type: CKEDITOR.dom.node[], typeString: string): void => { type.forEach((node, key) => { - const value = node.$ - const transclusionObject = angular.element(value) - const transclusionId = transclusionObject.attr('mms-element-id') + const value = node.$; + const transclusionObject = angular.element(value); + const transclusionId = transclusionObject.attr('mms-element-id'); //TODO create Utils function to handle request objects const reqOb = { elementId: transclusionId, projectId: this.mmsProjectId, refId: this.mmsRefId, - } + }; this.elementSvc.getElement(reqOb, 2).then( (data) => { - transclusionObject.html('[cf:' + data.name + typeString) + transclusionObject.html('[cf:' + data.name + typeString); }, (reason) => { - let error: string - if (reason.status === 410) error = 'deleted' - if (reason.status === 404) error = 'not found' - transclusionObject.html('[cf:' + error + typeString) + let error: string; + if (reason.status === 410) error = 'deleted'; + if (reason.status === 404) error = 'not found'; + transclusionObject.html('[cf:' + error + typeString); } - ) - }) - } + ); + }); + }; public mmsResetCallback = (ed: CKEDITOR.editor): void => { - const body: CKEDITOR.dom.element = ed.document.getBody() - this.resetCrossRef(body.find("mms-cf[mms-cf-type='name']").toArray(), '.name]') - this.resetCrossRef(body.find("mms-cf[mms-cf-type='doc']").toArray(), '.doc]') - this.resetCrossRef(body.find("mms-cf[mms-cf-type='val']").toArray(), '.val]') - this.resetCrossRef(body.find('mms-view-link').toArray(), '.vlink]') + const body: CKEDITOR.dom.element = ed.document.getBody(); + this.resetCrossRef(body.find("mms-cf[mms-cf-type='name']").toArray(), '.name]'); + this.resetCrossRef(body.find("mms-cf[mms-cf-type='doc']").toArray(), '.doc]'); + this.resetCrossRef(body.find("mms-cf[mms-cf-type='val']").toArray(), '.val]'); + this.resetCrossRef(body.find('mms-view-link').toArray(), '.vlink]'); this.update().then( () => { /**/ }, () => { - this.growl.error('Error saving editor content') + this.growl.error('Error saving editor content'); } - ) - } + ); + }; public update = (destroy?: boolean): VePromise => { // getData() returns CKEditor's processed/clean HTML content. return new this.$q((resolve, reject) => { if (this.instance) { try { - this.ngModelCtrl.$setViewValue(this.instance.getData()) + this.ngModelCtrl.$setViewValue(this.instance.getData()); } catch (e) { reject({ status: 500, message: 'Error updating editor data', data: this.id, - }) + }); } } - if (destroy) this.destroy() - resolve(true) - }) - } + if (destroy) this.destroy(); + resolve(true); + }); + }; private _addWidgetTag = (tag: string, editor: CKEDITOR.editor): void => { - editor.insertHtml(tag) - this.editorSvc.focusOnEditorAfterAddingWidgetTag(editor) - } + editor.insertHtml(tag); + this.editorSvc.focusOnEditorAfterAddingWidgetTag(editor); + }; private _addInlineMention = (): void => { - let keyupHandler: CKEDITOR.listenerRegistration + let keyupHandler: CKEDITOR.listenerRegistration; this.ckEditor.instances[this.id].on('contentDom', () => { keyupHandler = this.ckEditor.instances[this.instance.name].document.on('keyup', (e) => { if (this._isMentionKey((e.data as CKEDITOR.dom.node).$)) { - this.mentionSvc.createMention(this.instance, this.$scope.$new(), this.mmsProjectId, this.mmsRefId) + this.mentionSvc.createMention(this.instance, this.$scope.$new(), this.mmsProjectId, this.mmsRefId); } else { this.mentionSvc.handleInput( e as CKEDITOR.eventInfo>, @@ -705,98 +705,98 @@ export class EditorController implements IComponentController { this.instance, this.mmsProjectId, this.mmsRefId - ) + ); } - }) - }) + }); + }); this.ckEditor.instances[this.id].on('contentDomUnload', () => { if (keyupHandler) { - keyupHandler.removeListener() + keyupHandler.removeListener(); } - }) - } + }); + }; private _keyHandler = (e: CKEDITOR.eventInfo): boolean => { if (this._isMentionKey(e.data.domEvent.$)) { - return false // to prevent "@" from getting written to the editor + return false; // to prevent "@" from getting written to the editor } // when tab is pressed or any of these special keys is pressed while the mention results show up, ignore default ckeditor's behaviour const ignoreDefaultBehaviour = - this._isTabKey(e) || (this._isSpecialKey(e) && this.mentionSvc.hasMentionResults(this.instance)) + this._isTabKey(e) || (this._isSpecialKey(e) && this.mentionSvc.hasMentionResults(this.instance)); if (ignoreDefaultBehaviour) { - e.cancel() - e.stop() + e.cancel(); + e.stop(); } if (this._isTabKey(e) && !this._isShiftKeyOn(e.data.domEvent.$)) { - this.instance.insertHtml('    ') + this.instance.insertHtml('    '); } if (!ignoreDefaultBehaviour) { - this.deb(e) + this.deb(e); } - return true - } + return true; + }; // 13 = enter, 38 = up arrow, 40 = down arrow private _isSpecialKey = (event: CKEDITOR.eventInfo): boolean => { - const key = event.data.domEvent.$.which - return key === 13 || key === 38 || key === 40 - } + const key = event.data.domEvent.$.which; + return key === 13 || key === 38 || key === 40; + }; private _isTabKey = (event: CKEDITOR.eventInfo): boolean => { - return event.data.domEvent.$.which === 9 - } + return event.data.domEvent.$.which === 9; + }; private _isMentionKey = (keyboardEvent: KeyboardEvent): boolean => { - return this._isShiftKeyOn(keyboardEvent) && keyboardEvent.key === '@' - } + return this._isShiftKeyOn(keyboardEvent) && keyboardEvent.key === '@'; + }; private _isShiftKeyOn = (keyboardEvent: KeyboardEvent): boolean => { - return keyboardEvent.shiftKey - } + return keyboardEvent.shiftKey; + }; private _addContextMenuItems = (editor: CKEDITOR.editor): void => { - this._addFormatAsCodeMenuItem(editor) - } + this._addFormatAsCodeMenuItem(editor); + }; private _addFormatAsCodeMenuItem = (editor: CKEDITOR.editor): void => { editor.addCommand('formatAsCode', { exec: (editor: CKEDITOR.editor) => { - const selected_text = editor.getSelection().getSelectedText() - const newElement = new this.ckEditor.dom.element('code') - newElement.addClass('inlineCode') - newElement.setText(selected_text) - editor.insertElement(newElement) - return true + const selected_text = editor.getSelection().getSelectedText(); + const newElement = new this.ckEditor.dom.element('code'); + newElement.addClass('inlineCode'); + newElement.setText(selected_text); + editor.insertElement(newElement); + return true; }, - }) - editor.addMenuGroup('veGroup') + }); + editor.addMenuGroup('veGroup'); editor.addMenuItem('formatAsCode', { label: 'Format as inline code', command: 'formatAsCode', group: 'group', icon: 'codeSnippet', - }) + }); editor.contextMenu.addListener((element) => { - return { formatAsCode: this.ckEditor.TRISTATE_OFF } - }) - editor.setKeystroke(this.ckEditor.CTRL + 75, 'formatAsCode') - } + return { formatAsCode: this.ckEditor.TRISTATE_OFF }; + }); + editor.setKeystroke(this.ckEditor.CTRL + 75, 'formatAsCode'); + }; private _waitForEditor>(fn: (e?: T) => void, evt?: T): void { - if (this.instance.status === 'loaded') fn() + if (this.instance.status === 'loaded') fn(); else { new this.$q((resolve) => { this.instance.on('loaded', () => { - fn(evt) - resolve() - }) + fn(evt); + resolve(); + }); }).catch((reason) => { - this.growl.error('CKEditor Error: ' + reason.message) - }) + this.growl.error('CKEditor Error: ' + reason.message); + }); } } } @@ -817,6 +817,6 @@ const EditorComponent: VeComponentOptions = { editIndex: '<', }, controller: EditorController, -} +}; -veCore.component(EditorComponent.selector, EditorComponent) +veCore.component(EditorComponent.selector, EditorComponent); diff --git a/src/ve-core/editor/index.ts b/src/ve-core/editor/index.ts index 803880c70..e4886f56b 100644 --- a/src/ve-core/editor/index.ts +++ b/src/ve-core/editor/index.ts @@ -1,10 +1,10 @@ //Services -import './services' +import './services'; -export * from './services' -export * from './editor-buttons.config' +export * from './services'; +export * from './editor-buttons.config'; //Components -import './components/mention.component' -import './components/mention-intercept.component' -import './editor.component' +import './components/mention.component'; +import './components/mention-intercept.component'; +import './editor.component'; diff --git a/src/ve-core/editor/services/EditDialog.service.ts b/src/ve-core/editor/services/EditDialog.service.ts index 7f2093e55..77d57ce8d 100644 --- a/src/ve-core/editor/services/EditDialog.service.ts +++ b/src/ve-core/editor/services/EditDialog.service.ts @@ -1,13 +1,13 @@ -import { EditService } from '@ve-utils/core' +import { EditService } from '@ve-utils/core'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { VeQService } from '@ve-types/angular' -import { VeModalService } from '@ve-types/view-editor' +import { VeQService } from '@ve-types/angular'; +import { VeModalService } from '@ve-types/view-editor'; export class EditDialogService { - static $inject = ['$q', '$uibModal', 'EditService'] + static $inject = ['$q', '$uibModal', 'EditService']; constructor(private $q: VeQService, private $uibModal: VeModalService, private autosaveSvc: EditService) {} } -veCore.service('EditDialogService', EditDialogService) +veCore.service('EditDialogService', EditDialogService); diff --git a/src/ve-core/editor/services/Editor.service.ts b/src/ve-core/editor/services/Editor.service.ts index 6a84b4455..0dab2c763 100644 --- a/src/ve-core/editor/services/Editor.service.ts +++ b/src/ve-core/editor/services/Editor.service.ts @@ -1,24 +1,24 @@ -import angular from 'angular' -import $ from 'jquery' +import angular from 'angular'; +import $ from 'jquery'; -import { SaveConflictResolveFn } from '@ve-components/diffs' -import { EditDialogService } from '@ve-core/editor' -import { ConfirmDeleteModalResolveFn } from '@ve-core/modals' -import { ToolbarService } from '@ve-core/toolbar' -import { CacheService, EditObject, EditService, EventService } from '@ve-utils/core' -import { ApiService, ElementService, PermissionsService, ViewService, ValueService } from '@ve-utils/mms-api-client' +import { SaveConflictResolveFn } from '@ve-components/diffs'; +import { EditDialogService } from '@ve-core/editor'; +import { ConfirmDeleteModalResolveFn } from '@ve-core/modals'; +import { ToolbarService } from '@ve-core/toolbar'; +import { CacheService, EditObject, EditService, EventService } from '@ve-utils/core'; +import { ApiService, ElementService, PermissionsService, ViewService, ValueService } from '@ve-utils/mms-api-client'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { BasicResponse, ElementObject, ElementsResponse, MmsObject } from '@ve-types/mms' -import { VeModalInstanceService, VeModalService, VeModalSettings } from '@ve-types/view-editor' +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { BasicResponse, ElementObject, ElementsResponse, MmsObject } from '@ve-types/mms'; +import { VeModalInstanceService, VeModalService, VeModalSettings } from '@ve-types/view-editor'; export class EditorService { - public generatedIds: number = 0 + public generatedIds: number = 0; private edit2editor: { [editKey: string]: { [field: string]: (destroy?: boolean) => VePromise } } = - {} - public savingAll: boolean = false + {}; + public savingAll: boolean = false; static $inject = [ '$q', @@ -35,7 +35,7 @@ export class EditorService { 'EditDialogService', 'EventService', 'EditService', - ] + ]; constructor( private $q: VeQService, @@ -55,7 +55,7 @@ export class EditorService { ) {} public get(editKey: string): { [field: string]: () => VePromise } { - return this.edit2editor[editKey] + return this.edit2editor[editKey]; } public updateAllData( @@ -63,20 +63,20 @@ export class EditorService { allowNone?: boolean, destroy?: boolean ): VePromise> { - const key: string = this.editSvc.makeKey(editKey) + const key: string = this.editSvc.makeKey(editKey); return new this.$q>((resolve, reject) => { if (this.edit2editor[key]) { - const promises: VePromise[] = [] + const promises: VePromise[] = []; for (const id of Object.keys(this.edit2editor[key])) { - promises.push(this.edit2editor[key][id](destroy)) + promises.push(this.edit2editor[key][id](destroy)); } - this.$q.all(promises).then(resolve, reject) + this.$q.all(promises).then(resolve, reject); } else if (allowNone) { - resolve() + resolve(); } else { - reject({ status: 500, message: 'No editors present to update from' }) + reject({ status: 500, message: 'No editors present to update from' }); } - }) + }); } public add( @@ -84,87 +84,87 @@ export class EditorService { field: string, updateFn: (destroy?: boolean) => VePromise ): void { - editKey = this.editSvc.makeKey(editKey) - if (!this.edit2editor[editKey]) this.edit2editor[editKey] = {} - this.edit2editor[editKey][field] = updateFn + editKey = this.editSvc.makeKey(editKey); + if (!this.edit2editor[editKey]) this.edit2editor[editKey] = {}; + this.edit2editor[editKey][field] = updateFn; } public remove(editKey: string | string[], field: string): void { - editKey = Array.isArray(editKey) ? editKey.join('|') : editKey + editKey = Array.isArray(editKey) ? editKey.join('|') : editKey; if (this.edit2editor[editKey] && this.edit2editor[editKey][field]) { this.edit2editor[editKey][field]().finally(() => { - delete this.edit2editor[editKey as string][field] + delete this.edit2editor[editKey as string][field]; if (Object.keys(this.edit2editor[editKey as string]).length === 0) { - delete this.edit2editor[editKey as string] + delete this.edit2editor[editKey as string]; } - }) + }); } } public createId(): string { - return `mmsCKEditor${this.generatedIds++}` + return `mmsCKEditor${this.generatedIds++}`; } public focusOnEditorAfterAddingWidgetTag(editor: CKEDITOR.editor): void { - const element = editor.widgets.focused.element.getParent() - editor.focusManager.focus(element) + const element = editor.widgets.focused.element.getParent(); + editor.focusManager.focus(element); } public save = (editKey: string | string[], continueEdit: boolean): VePromise => { - this.eventSvc.$broadcast('element-saving', true) + this.eventSvc.$broadcast('element-saving', true); return new this.$q((resolve, reject) => { this._save(editKey, continueEdit).then( (data) => { - this.eventSvc.$broadcast('element-saving', false) + this.eventSvc.$broadcast('element-saving', false); if (!data) { - this.growl.info('Save Skipped (No Changes)') + this.growl.info('Save Skipped (No Changes)'); } else { - this.growl.success('Save Successful') + this.growl.success('Save Successful'); } - resolve(data) + resolve(data); }, (reason) => { - this.eventSvc.$broadcast('element-saving', false) - reject(reason) + this.eventSvc.$broadcast('element-saving', false); + reject(reason); } - ) - }) - } + ); + }); + }; public saveAll = (): VePromise => { if (this.savingAll) { - this.growl.info('Please wait...') - return this.$q.resolve() + this.growl.info('Please wait...'); + return this.$q.resolve(); } if (this.editSvc.openEdits() === 0) { - this.growl.info('Nothing to save') - return this.$q.resolve() + this.growl.info('Nothing to save'); + return this.$q.resolve(); } - this.savingAll = true + this.savingAll = true; return new this.$q((resolve, reject) => { this.elementSvc .updateElements( Object.values(this.editSvc.getAll()).map((editOb) => { - return editOb.element + return editOb.element; }) ) .then((responses) => { responses.forEach((elementOb) => { - const edit = this.editSvc.get(this.elementSvc.getEditElementKey(elementOb)) - this.cleanUpEdit(edit.key) + const edit = this.editSvc.get(this.elementSvc.getEditElementKey(elementOb)); + this.cleanUpEdit(edit.key); const data = { element: elementOb, continueEdit: false, - } - this.eventSvc.$broadcast('element.updated', data) - }) - this.growl.success('Save All Successful') - resolve() - }, reject) - }) - } + }; + this.eventSvc.$broadcast('element.updated', data); + }); + this.growl.success('Save All Successful'); + resolve(); + }, reject); + }); + }; /** * @name Utils#save @@ -182,44 +182,44 @@ export class EditorService { return new this.$q((resolve, reject) => { this.updateAllData(editKey, true, true).then( () => { - const edit = this.editSvc.get(editKey).element + const edit = this.editSvc.get(editKey).element; this.elementSvc.updateElement(edit, false, true).then( (element: T) => { const data = { element: element, continueEdit: continueEdit ? continueEdit : false, - } - this.eventSvc.$broadcast('element.updated', data) - this.cleanUpEdit(editKey) - resolve(element) + }; + this.eventSvc.$broadcast('element.updated', data); + this.cleanUpEdit(editKey); + resolve(element); }, (reason: VePromiseReason>) => { if (reason.status === 409) { - const latest = reason.data.elements[0] + const latest = reason.data.elements[0]; this.saveConflictDialog(latest).result.then( (data) => { - const choice = data + const choice = data; if (choice === 'ok') { const reqOb = { elementId: latest.id, projectId: latest._projectId, refId: latest._refId, commitId: 'latest', - } - this.cleanUpEdit(editKey) - resolve(this.elementSvc.cacheElement(reqOb, latest)) + }; + this.cleanUpEdit(editKey); + resolve(this.elementSvc.cacheElement(reqOb, latest)); } else if (choice === 'force') { - edit._modified = latest._modified + edit._modified = latest._modified; this._save(editKey, continueEdit).then( (resolved) => { - resolve(resolved) + resolve(resolved); }, (error) => { - reject(error) + reject(error); } - ) + ); } else { - reject({ status: 444, type: 'info', message: 'Save cancelled!' }) + reject({ status: 444, type: 'info', message: 'Save cancelled!' }); } }, () => { @@ -227,25 +227,25 @@ export class EditorService { status: 500, message: 'An error occurred. Please try your request again', type: 'error', - }) + }); } - ) + ); } else { - reason.type = 'error' - reject(reason) + reason.type = 'error'; + reject(reason); } } - ) + ); }, () => { reject({ status: 500, message: 'Error Saving from Editor; Please Retry', type: 'error', - }) + }); } - ) - }) + ); + }); } /** @@ -262,8 +262,8 @@ export class EditorService { editOb: EditObject, field?: 'name' | 'value' | 'documentation' ): VePromise> => { - const edit = editOb.element - edit._commitId = 'latest' + const edit = editOb.element; + edit._commitId = 'latest'; return new this.$q>((resolve) => { this.updateAllData(editOb.key, true, false).then( () => { @@ -271,42 +271,42 @@ export class EditorService { (elementOb) => { if (elementOb) { if ((!field || field === 'name') && edit.name !== elementOb.name) { - resolve(true) + resolve(true); } if ( (!field || field === 'documentation') && edit.documentation !== elementOb.documentation ) { - resolve(true) + resolve(true); } if ( this.valueSvc.isValue(edit) && (!field || field === 'value') && !this.valueSvc.isEqual(edit, elementOb) ) { - resolve(true) + resolve(true); } - resolve(false) + resolve(false); } else if ( edit.id.endsWith('_temp') && (edit.name || edit.documentation || this.valueSvc.hasValue(edit)) ) { - resolve(true) + resolve(true); } else { - resolve(false) + resolve(false); } }, () => { - resolve(false) + resolve(false); } - ) + ); }, () => { - resolve(false) + resolve(false); } - ) - }) - } + ); + }); + }; /** * @name Utils#openEdit @@ -332,62 +332,62 @@ export class EditorService { elementId: elementOb.id, projectId: elementOb._projectId, refId: elementOb._refId, - } + }; if (!this.permissionsSvc.hasBranchEditPermission(elementOb._projectId, elementOb._refId)) { - reject({ message: 'No edit permission on branch', status: 403 }) - return + reject({ message: 'No edit permission on branch', status: 403 }); + return; } this.elementSvc.getElementForEdit(reqOb).then( (edit) => { if (this.valueSvc.isValue(edit.element)) { - edit.values = this.valueSvc.getValues(edit.element) + edit.values = this.valueSvc.getValues(edit.element); } - resolve(edit) + resolve(edit); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) - }) + ); + }); + }); } public cleanUpEdit(editKey: string | string[]): void { - this.clearAutosave(editKey) - this.editSvc.remove(editKey) + this.clearAutosave(editKey); + this.editSvc.remove(editKey); // Broadcast message for the ToolCtrl: - this.eventSvc.$broadcast('editor.close') + this.eventSvc.$broadcast('editor.close'); } public clearAutosave = (key: string | string[], field?: string): void => { - key = this.editSvc.makeKey(key) - if (field) key = key + '|' + field + key = this.editSvc.makeKey(key); + if (field) key = key + '|' + field; Object.keys(window.localStorage).forEach((akey) => { if (akey.indexOf(key as string) !== -1) { - window.localStorage.removeItem(akey) + window.localStorage.removeItem(akey); } - }) - } + }); + }; private _makeKey(key: string | string[]): string { - return Array.isArray(key) ? key.join('|') : key + return Array.isArray(key) ? key.join('|') : key; } public handleError(reason: { message: string; type: 'error' | 'warning' | 'info' } | VePromiseReason): void { - if (reason.type === 'info') this.growl.info(reason.message) - else if (reason.type === 'warning') this.growl.warning(reason.message) - else if (reason.type === 'error') this.growl.error(reason.message) + if (reason.type === 'info') this.growl.info(reason.message); + else if (reason.type === 'warning') this.growl.warning(reason.message); + else if (reason.type === 'error') this.growl.error(reason.message); } public updateEditor(editKey: string | string[], field: string): VePromise { return new this.$q((resolve, reject) => { - editKey = this.editSvc.makeKey(editKey) + editKey = this.editSvc.makeKey(editKey); if (this.edit2editor[editKey] && this.edit2editor[editKey][field]) { - this.edit2editor[editKey][field]().then(resolve, reject) + this.edit2editor[editKey][field]().then(resolve, reject); } else { - resolve(true) // continue for non ckeditor transcludes + resolve(true); // continue for non ckeditor transcludes } - }) + }); } /** @@ -413,9 +413,9 @@ export class EditorService { public scrollToElement = (domElement: JQuery): void => { this.$timeout( () => { - const el = domElement[0] - if ($(domElement).isOnScreen()) return - el.scrollIntoView() + const el = domElement[0]; + if ($(domElement).isOnScreen()) return; + el.scrollIntoView(); }, 500, false @@ -426,8 +426,8 @@ export class EditorService { () => { /**/ } - ) - } + ); + }; saveConflictDialog(latest: T): VeModalInstanceService { return this.$uibModal.open, string>({ @@ -435,10 +435,10 @@ export class EditorService { size: 'lg', resolve: { latest: () => { - return latest + return latest; }, }, - }) + }); } public deleteEditModal(editOb: EditObject): VeModalInstanceService { @@ -446,19 +446,19 @@ export class EditorService { component: 'confirmDeleteModal', resolve: { getName: () => { - return `${editOb.element.type} ${editOb.element.id}` + return `${editOb.element.type} ${editOb.element.id}`; }, getType: () => { - return 'edit' + return 'edit'; }, finalize: () => { return () => { - return this.$q.resolve() - } + return this.$q.resolve(); + }; }, }, - } - return this.$uibModal.open(settings) + }; + return this.$uibModal.open(settings); } public deleteConfirmModal(edit: EditObject): VeModalInstanceService { @@ -466,21 +466,21 @@ export class EditorService { component: 'confirmDeleteModal', resolve: { getType: () => { - return edit.element.type ? edit.element.type : 'element' + return edit.element.type ? edit.element.type : 'element'; }, getName: () => { - return edit.element.name ? edit.element.name : 'Element' + return edit.element.name ? edit.element.name : 'Element'; }, finalize: () => { return () => { - this.cleanUpEdit(edit.key) - return this.$q.resolve() - } + this.cleanUpEdit(edit.key); + return this.$q.resolve(); + }; }, }, - } - return this.$uibModal.open(settings) + }; + return this.$uibModal.open(settings); } } -veCore.service('EditorService', EditorService) +veCore.service('EditorService', EditorService); diff --git a/src/ve-core/editor/services/Mention.service.ts b/src/ve-core/editor/services/Mention.service.ts index 61483e979..4e350466d 100644 --- a/src/ve-core/editor/services/Mention.service.ts +++ b/src/ve-core/editor/services/Mention.service.ts @@ -1,36 +1,36 @@ -import $ from 'jquery' -import moment from 'moment' +import $ from 'jquery'; +import moment from 'moment'; -import { MMSMentionController } from '@ve-core/editor/components/mention.component' -import { UtilsService } from '@ve-utils/application' -import { CacheService } from '@ve-utils/core' -import { ApiService, ViewService } from '@ve-utils/mms-api-client' +import { MMSMentionController } from '@ve-core/editor/components/mention.component'; +import { UtilsService } from '@ve-utils/application'; +import { CacheService } from '@ve-utils/core'; +import { ApiService, ViewService } from '@ve-utils/mms-api-client'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { ElementObject } from '@ve-types/mms' +import { ElementObject } from '@ve-types/mms'; export interface MentionScope extends angular.IScope { - mmsEditor?: CKEDITOR.editor - mmsMentionValue?: string - mmsMentionId?: string - mmsProjectId?: string - mmsRefId?: string + mmsEditor?: CKEDITOR.editor; + mmsMentionValue?: string; + mmsMentionId?: string; + mmsProjectId?: string; + mmsRefId?: string; } export interface MentionState { - mentionScope: MentionScope - mentionController: MMSMentionController - mentionElement: JQLite - mentionId: string - mentionPlaceHolderId: string + mentionScope: MentionScope; + mentionController: MMSMentionController; + mentionElement: JQLite; + mentionId: string; + mentionPlaceHolderId: string; } export class MentionService { - mentions: { [id: string]: MentionState } = {} - mentionPlacerHolderPrefix = 'mentionPlaceHolder' + mentions: { [id: string]: MentionState } = {}; + mentionPlacerHolderPrefix = 'mentionPlaceHolder'; - static $inject = ['$compile', '$timeout', 'growl', 'CacheService', 'ViewService', 'UtilsService', 'ApiService'] + static $inject = ['$compile', '$timeout', 'growl', 'CacheService', 'ViewService', 'UtilsService', 'ApiService']; constructor( private $compile: angular.ICompileService, @@ -44,26 +44,26 @@ export class MentionService { /** Used to maintain all mention in all ckeditors **/ public getFastCfListing(projectId: string, refId: string): ElementObject[] { - const latestElements: ElementObject[] = this.cacheSvc.getLatestElements(projectId, refId) + const latestElements: ElementObject[] = this.cacheSvc.getLatestElements(projectId, refId); latestElements.reduce( ( result: { - id: string - name: string - type: string - iconClass: string - documentation?: string - editor: string - editTime: string - elementType: string - value?: string + id: string; + name: string; + type: string; + iconClass: string; + documentation?: string; + editor: string; + editTime: string; + elementType: string; + value?: string; }[], cacheElement ) => { - const elementType = this.viewSvc.getElementType(cacheElement) - const elementName = cacheElement.name ? cacheElement.name : cacheElement.id - const iconClass = this.utilsSvc.getElementTypeClass(cacheElement, elementType) + const elementType = this.viewSvc.getElementType(cacheElement); + const elementName = cacheElement.name ? cacheElement.name : cacheElement.id; + const iconClass = this.utilsSvc.getElementTypeClass(cacheElement, elementType); result.push({ id: cacheElement.id, name: elementName, @@ -73,7 +73,7 @@ export class MentionService { editor: cacheElement._modifier, editTime: moment(cacheElement._modified).fromNow(), elementType: elementType ? elementType : cacheElement.type, - }) + }); if (cacheElement.documentation != undefined) { result.push({ id: cacheElement.id, @@ -84,13 +84,13 @@ export class MentionService { editor: cacheElement._modifier, editTime: moment(cacheElement._modified).fromNow(), elementType: elementType || cacheElement.type, - }) + }); } if (cacheElement.type === 'Property' && cacheElement.defaultValue) { - let value = String(cacheElement.defaultValue.value) + let value = String(cacheElement.defaultValue.value); if (!value || value === 'undefined') { - value = 'this field is empty' + value = 'this field is empty'; } result.push({ id: cacheElement.id, @@ -101,13 +101,13 @@ export class MentionService { editor: cacheElement._modifier, editTime: moment(cacheElement._modified).fromNow(), elementType: cacheElement.type, - }) + }); } - return result + return result; }, [] - ) - return latestElements + ); + return latestElements; } public createMention( @@ -116,17 +116,17 @@ export class MentionService { projectId: string, refId: string, existingMentionPlaceHolder?: { - mentionId: string - mentionPlaceHolderId: string + mentionId: string; + mentionPlaceHolderId: string; } ): void { - const mentionId = existingMentionPlaceHolder ? existingMentionPlaceHolder.mentionId : this.apiSvc.createUUID() + const mentionId = existingMentionPlaceHolder ? existingMentionPlaceHolder.mentionId : this.apiSvc.createUUID(); const mentionPlaceHolderId = existingMentionPlaceHolder ? existingMentionPlaceHolder.mentionPlaceHolderId - : this._createMentionPlaceHolder(editor, mentionId) - const mention = this._createMentionDirective(editor, mentionScope, mentionId, projectId, refId) - this._createNewMentionState(editor, mention, mentionPlaceHolderId, mentionId) - MentionService._positionMentionElement(editor, mention, mentionPlaceHolderId) + : this._createMentionPlaceHolder(editor, mentionId); + const mention = this._createMentionDirective(editor, mentionScope, mentionId, projectId, refId); + this._createNewMentionState(editor, mention, mentionPlaceHolderId, mentionId); + MentionService._positionMentionElement(editor, mention, mentionPlaceHolderId); } public handleInput( @@ -137,57 +137,57 @@ export class MentionService { refId: string ): void { if (editor._ && editor._.elementsPath) { - const elementsPath = editor._.elementsPath - const currentEditingElement = elementsPath.list[0].$ - const currentEditingElementId = currentEditingElement.getAttribute('id') - const mentionId = this._getMentionIdFromMentionPlaceHolder(currentEditingElementId) + const elementsPath = editor._.elementsPath; + const currentEditingElement = elementsPath.list[0].$; + const currentEditingElementId = currentEditingElement.getAttribute('id'); + const mentionId = this._getMentionIdFromMentionPlaceHolder(currentEditingElementId); if (mentionId) { - let mentionState = this._retrieveMentionState(editor.id, mentionId) + let mentionState = this._retrieveMentionState(editor.id, mentionId); // logic to reactivate existing "@" when reloading ckeditor if (!mentionState) { this.createMention(editor, newScope, projectId, refId, { mentionId: mentionId, mentionPlaceHolderId: currentEditingElementId, - }) - mentionState = this._retrieveMentionState(editor.id, mentionId) + }); + mentionState = this._retrieveMentionState(editor.id, mentionId); } - const mentionScope = mentionState.mentionScope + const mentionScope = mentionState.mentionScope; mentionScope.$apply(() => { - let text = currentEditingElement.innerText - text = text.substring(1) // ignore @ - mentionScope.mmsMentionValue = text - this._repositionDropdownIfOffScreen(editor, mentionState) - }) + let text = currentEditingElement.innerText; + text = text.substring(1); // ignore @ + mentionScope.mmsMentionValue = text; + this._repositionDropdownIfOffScreen(editor, mentionState); + }); - this._handleSpecialKeys(event, mentionId, editor, projectId, refId) + this._handleSpecialKeys(event, mentionId, editor, projectId, refId); } } } public handleMentionSelection(editor: CKEDITOR.editor, mentionId: string): void { - this._cleanup(editor, mentionId) + this._cleanup(editor, mentionId); } public removeAllMentionForEditor(editor: CKEDITOR.editor): void { Object.keys(this.mentions) .filter((key) => { - const splits = key.split('-') - return splits[0] === editor.id + const splits = key.split('-'); + return splits[0] === editor.id; }) .forEach((key) => { - this._cleanup(editor, key.split('-')[1]) - }) + this._cleanup(editor, key.split('-')[1]); + }); } public hasMentionResults(editor: CKEDITOR.editor): boolean { - const currentEditingElement = editor._.elementsPath.list[0].$ - const currentEditingElementId = currentEditingElement.getAttribute('id') - const mentionId = this._getMentionIdFromMentionPlaceHolder(currentEditingElementId) + const currentEditingElement = editor._.elementsPath.list[0].$; + const currentEditingElementId = currentEditingElement.getAttribute('id'); + const mentionId = this._getMentionIdFromMentionPlaceHolder(currentEditingElementId); if (mentionId) { - return MentionService._hasMentionResults(mentionId) + return MentionService._hasMentionResults(mentionId); } - return false + return false; } private static _hasMentionResults(mentionId: string): boolean { @@ -195,7 +195,7 @@ export class MentionService { $('#' + mentionId) .find('ul') .children().length > 0 - ) + ); } private _createMentionDirective( @@ -205,18 +205,18 @@ export class MentionService { projectId: string, refId: string ): JQLite { - mentionScope.mmsEditor = editor - mentionScope.mmsMentionValue = '' - mentionScope.mmsMentionId = mentionId - mentionScope.mmsProjectId = projectId - mentionScope.mmsRefId = refId + mentionScope.mmsEditor = editor; + mentionScope.mmsMentionValue = ''; + mentionScope.mmsMentionId = mentionId; + mentionScope.mmsProjectId = projectId; + mentionScope.mmsRefId = refId; return this.$compile( '' - )(mentionScope) + )(mentionScope); } private static _getCkeditorFrame(editor: CKEDITOR.editor): HTMLIFrameElement { - return editor.container.$.getElementsByTagName('iframe')[0] + return editor.container.$.getElementsByTagName('iframe')[0]; } private static _positionMentionElement( @@ -224,16 +224,16 @@ export class MentionService { mentionElement: JQLite, mentionPlaceHolderId: string ): void { - const ckeditorFrame = MentionService._getCkeditorFrame(editor) - const ckeditorBox = ckeditorFrame.getBoundingClientRect() - const mentionPlaceHolder = ckeditorFrame.contentDocument.getElementById(mentionPlaceHolderId) - const mentionPlaceHolderBox = $(mentionPlaceHolder)[0].getBoundingClientRect() + const ckeditorFrame = MentionService._getCkeditorFrame(editor); + const ckeditorBox = ckeditorFrame.getBoundingClientRect(); + const mentionPlaceHolder = ckeditorFrame.contentDocument.getElementById(mentionPlaceHolderId); + const mentionPlaceHolderBox = $(mentionPlaceHolder)[0].getBoundingClientRect(); mentionElement.css({ position: 'absolute', top: ckeditorBox.top + mentionPlaceHolderBox.top + 30, left: ckeditorBox.left + mentionPlaceHolderBox.left, - }) - $('body').append(mentionElement) + }); + $('body').append(mentionElement); } private _createNewMentionState( @@ -242,64 +242,64 @@ export class MentionService { mentionPlaceHolderId: string, mentionId: string ): MentionState { - const key = MentionService._getMentionStateId(editor.id, mentionId) + const key = MentionService._getMentionStateId(editor.id, mentionId); const value: MentionState = { mentionScope: mention.scope(), mentionController: mention.controller() as MMSMentionController, mentionElement: mention, mentionId: mentionId, mentionPlaceHolderId: mentionPlaceHolderId, - } - this.mentions[key] = value - return value + }; + this.mentions[key] = value; + return value; } private _retrieveMentionState = (editorId: string, mentionId: string): MentionState => { - return this.mentions[MentionService._getMentionStateId(editorId, mentionId)] - } + return this.mentions[MentionService._getMentionStateId(editorId, mentionId)]; + }; private static _getMentionStateId(editorId: string, mentionId: string): string { - return editorId + '-' + mentionId + return editorId + '-' + mentionId; } private _createMentionPlaceHolder(editor: CKEDITOR.editor, mentionId: string): string { - const id = this.mentionPlacerHolderPrefix + '-' + editor.id + '-' + mentionId - const mentionPlaceHolder = '@' - editor.insertHtml(mentionPlaceHolder) - return id + const id = this.mentionPlacerHolderPrefix + '-' + editor.id + '-' + mentionId; + const mentionPlaceHolder = '@'; + editor.insertHtml(mentionPlaceHolder); + return id; } private _getMentionIdFromMentionPlaceHolder = (currentEditingElementId: string): string => { if (currentEditingElementId && currentEditingElementId.indexOf(this.mentionPlacerHolderPrefix) > -1) { - const splits = currentEditingElementId.split('-') - return splits[2] + const splits = currentEditingElementId.split('-'); + return splits[2]; } - return null - } + return null; + }; private _cleanup(editor: CKEDITOR.editor, mentionId: string, unwrapOnly?): void { - const mentionState = this._retrieveMentionState(editor.id, mentionId) - const mentionPlaceHolderId = mentionState.mentionPlaceHolderId - const mentionPlaceHolderDom = editor.document.getById(mentionPlaceHolderId) + const mentionState = this._retrieveMentionState(editor.id, mentionId); + const mentionPlaceHolderId = mentionState.mentionPlaceHolderId; + const mentionPlaceHolderDom = editor.document.getById(mentionPlaceHolderId); if (unwrapOnly) { - const range = editor.createRange() + const range = editor.createRange(); if (range && mentionPlaceHolderDom) { - range.moveToClosestEditablePosition(mentionPlaceHolderDom, true) - $(mentionPlaceHolderDom.$).contents().unwrap() - range.select() + range.moveToClosestEditablePosition(mentionPlaceHolderDom, true); + $(mentionPlaceHolderDom.$).contents().unwrap(); + range.select(); } } else { // remove the mentionPlaceHolder - mentionPlaceHolderDom.remove() + mentionPlaceHolderDom.remove(); } // cleanup the mention directive - const mentionScope = mentionState.mentionScope - mentionScope.$destroy() + const mentionScope = mentionState.mentionScope; + mentionScope.$destroy(); // remove the mention dom - const mentionElement = mentionState.mentionElement - mentionElement.remove() + const mentionElement = mentionState.mentionElement; + mentionElement.remove(); // remove the mention state - delete this.mentions[MentionService._getMentionStateId(editor.id, mentionId)] + delete this.mentions[MentionService._getMentionStateId(editor.id, mentionId)]; } private _handleSpecialKeys( @@ -311,81 +311,81 @@ export class MentionService { ): void { switch (evt.data.$.which) { case 38: // up arrow - this._handleArrowKey(mentionId, false) - break + this._handleArrowKey(mentionId, false); + break; case 40: // down arrow - this._handleArrowKey(mentionId, true) - break + this._handleArrowKey(mentionId, true); + break; case 13: // enter - this._handleEnterKey(editor.id, mentionId, projectId, refId) - break + this._handleEnterKey(editor.id, mentionId, projectId, refId); + break; case 27: // esc - this._handleEscKey(editor, mentionId) + this._handleEscKey(editor, mentionId); } } private _getMentionItem = (key: string, projectId: string, refId: string): ElementObject => { - const cfListing = this.getFastCfListing(projectId, refId) + const cfListing = this.getFastCfListing(projectId, refId); return cfListing.find((cf) => { - return cf.id + cf.type === key - }) - } + return cf.id + cf.type === key; + }); + }; private _handleEnterKey = (editorId: string, mentionId: string, projectId: string, refId: string): void => { - const matchDom = $('#' + mentionId + ' .active .mentionMatch') + const matchDom = $('#' + mentionId + ' .active .mentionMatch'); if (matchDom.length > 0) { - const key = matchDom.attr('id') - const mentionItem = this._getMentionItem(key, projectId, refId) - const mentionState = this._retrieveMentionState(editorId, mentionId) - mentionState.mentionController.selectMentionItem(mentionItem) + const key = matchDom.attr('id'); + const mentionItem = this._getMentionItem(key, projectId, refId); + const mentionState = this._retrieveMentionState(editorId, mentionId); + mentionState.mentionController.selectMentionItem(mentionItem); } - } + }; private _handleEscKey(editor: CKEDITOR.editor, mentionId: string): void { - this._cleanup(editor, mentionId, true) + this._cleanup(editor, mentionId, true); } private _handleArrowKey = (mentionId: string, isDownArrow: boolean): void => { - const popUpEl = $('#' + mentionId) - const allOptions = popUpEl.find('li') - const len = allOptions.length - let activeIndex = -1 + const popUpEl = $('#' + mentionId); + const allOptions = popUpEl.find('li'); + const len = allOptions.length; + let activeIndex = -1; allOptions.each((index) => { if ($(this).hasClass('active')) { - activeIndex = index + activeIndex = index; } - }) + }); if (activeIndex !== -1) { - let nextIndex: number + let nextIndex: number; if (isDownArrow) { - nextIndex = (activeIndex + 1) % len + nextIndex = (activeIndex + 1) % len; } else { if (activeIndex === 0) { - nextIndex = len - 1 + nextIndex = len - 1; } else { - nextIndex = (activeIndex - 1) % len + nextIndex = (activeIndex - 1) % len; } } - const target = $(allOptions[nextIndex]) - target.addClass('active') - $(allOptions[activeIndex]).removeClass('active') + const target = $(allOptions[nextIndex]); + target.addClass('active'); + $(allOptions[activeIndex]).removeClass('active'); // scroll if necessary - ;(target[0].parentNode).scrollTop = target[0].offsetTop + (target[0].parentNode).scrollTop = target[0].offsetTop; } - } + }; private _repositionDropdownIfOffScreen(editor: CKEDITOR.editor, mentionState: MentionState): void { // wait for dropdown result to render so that we can determine whether it is on/off-screen this.$timeout( () => { - const mentionElement = mentionState.mentionElement - const dropdownResultElement = mentionElement.find('ul.dropdown-menu') + const mentionElement = mentionState.mentionElement; + const dropdownResultElement = mentionElement.find('ul.dropdown-menu'); if (dropdownResultElement.children().length > 0 && !dropdownResultElement.isOnScreen()) { - const ckeditorBox = MentionService._getCkeditorFrame(editor).getBoundingClientRect() + const ckeditorBox = MentionService._getCkeditorFrame(editor).getBoundingClientRect(); mentionElement.css({ top: ckeditorBox.top, left: ckeditorBox.left, - }) + }); } }, 0, @@ -397,8 +397,8 @@ export class MentionService { () => { /*Do Nothing*/ } - ) + ); } } -veCore.service('MentionService', MentionService) +veCore.service('MentionService', MentionService); diff --git a/src/ve-core/editor/services/index.ts b/src/ve-core/editor/services/index.ts index 401541c1a..bc9551bf3 100644 --- a/src/ve-core/editor/services/index.ts +++ b/src/ve-core/editor/services/index.ts @@ -1,8 +1,8 @@ //Services -import './Editor.service' -import './Mention.service' -import './EditDialog.service' +import './Editor.service'; +import './Mention.service'; +import './EditDialog.service'; -export * from './Editor.service' -export * from './Mention.service' -export * from './EditDialog.service' +export * from './Editor.service'; +export * from './Mention.service'; +export * from './EditDialog.service'; diff --git a/src/ve-core/events.d.ts b/src/ve-core/events.d.ts index 4b6e0f8f7..550a0d5d2 100644 --- a/src/ve-core/events.d.ts +++ b/src/ve-core/events.d.ts @@ -1,35 +1,35 @@ -import { ElementObject, ElementsRequest } from '@ve-types/mms' +import { ElementObject, ElementsRequest } from '@ve-types/mms'; export namespace veCoreEvents { interface elementSelectedData extends ElementsRequest { - rootId?: string - refType?: string - displayOldSpec?: boolean - refresh?: boolean + rootId?: string; + refType?: string; + displayOldSpec?: boolean; + refresh?: boolean; } interface elementUpdatedData { - element: ElementObject - continueEdit?: boolean + element: ElementObject; + continueEdit?: boolean; } interface buttonClicked { - $event?: JQuery.ClickEvent - clicked: string + $event?: JQuery.ClickEvent; + clicked: string; } interface toolbarClicked { - id: string - category?: string - title?: string + id: string; + category?: string; + title?: string; } abstract interface setToolbarData { - tbId: string - id: string - value: T + tbId: string; + id: string; + value: T; } - type setPermissionData = setToolbarData - type setIconData = setToolbarData - type setToggleData = setToolbarData + type setPermissionData = setToolbarData; + type setIconData = setToolbarData; + type setToggleData = setToolbarData; } diff --git a/src/ve-core/index.ts b/src/ve-core/index.ts index 4d4823a0b..bc5ad6acf 100644 --- a/src/ve-core/index.ts +++ b/src/ve-core/index.ts @@ -2,13 +2,13 @@ // import '@ve-utils' //Module Main -import './ve-core.module' +import './ve-core.module'; // Core Component Libraries -import './modals' -import './button-bar' -import './toolbar' -import './editor' -import './search' +import './modals'; +import './button-bar'; +import './toolbar'; +import './editor'; +import './search'; -export * from './ve-core.module' +export * from './ve-core.module'; diff --git a/src/ve-core/modals/confirm-delete-modal.component.ts b/src/ve-core/modals/confirm-delete-modal.component.ts index 6ee323b57..bfaf7ee63 100644 --- a/src/ve-core/modals/confirm-delete-modal.component.ts +++ b/src/ve-core/modals/confirm-delete-modal.component.ts @@ -1,24 +1,24 @@ -import angular from 'angular' -import _ from 'lodash' +import angular from 'angular'; +import _ from 'lodash'; -import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller' +import { VeModalControllerImpl } from '@ve-utils/modals/ve-modal.controller'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { VeComponentOptions, VePromise } from '@ve-types/angular' -import { RefsResponse } from '@ve-types/mms' -import { VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { VeComponentOptions, VePromise } from '@ve-types/angular'; +import { RefsResponse } from '@ve-types/mms'; +import { VeModalController, VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; export interface ConfirmDeleteModalResolve extends VeModalResolve { - getType: string - getName: string - finalize(): VePromise + getType: string; + getName: string; + finalize(): VePromise; } export interface ConfirmDeleteModalResolveFn extends VeModalResolveFn { - getType(): string - getName(): string - finalize(): () => VePromise + getType(): string; + getName(): string; + finalize(): () => VePromise; } const ConfirmDeleteModalComponent: VeComponentOptions = { @@ -48,53 +48,53 @@ const ConfirmDeleteModalComponent: VeComponentOptions = { resolve: '<', }, controller: class ConfirmDeleteModalController extends VeModalControllerImpl implements VeModalController { - static $inject = ['growl'] + static $inject = ['growl']; - protected resolve: ConfirmDeleteModalResolve + protected resolve: ConfirmDeleteModalResolve; //local - public oking: boolean - public type: string - public name: string + public oking: boolean; + public type: string; + public name: string; constructor(private growl: angular.growl.IGrowlService) { - super() + super(); } $onInit(): void { - this.oking = false - this.type = this.resolve.getType - this.name = this.resolve.getName + this.oking = false; + this.type = this.resolve.getType; + this.name = this.resolve.getName; } ok = (): void => { if (this.oking) { - this.growl.info('Please wait...') - return + this.growl.info('Please wait...'); + return; } - this.oking = true + this.oking = true; if (this.resolve.finalize) { this.resolve.finalize().then( () => { - this.growl.success(_.upperFirst(this.type) + ' Removed') - this.oking = false - this.modalInstance.close('ok') + this.growl.success(_.upperFirst(this.type) + ' Removed'); + this.oking = false; + this.modalInstance.close('ok'); }, (reason) => { if (reason.message) { - this.growl.error(this.type + ' Removal Error: ' + reason.message) + this.growl.error(this.type + ' Removal Error: ' + reason.message); } - this.oking = false - this.modalInstance.dismiss() + this.oking = false; + this.modalInstance.dismiss(); } - ) + ); } - } + }; cancel(): void { - this.modalInstance.dismiss() + this.modalInstance.dismiss(); } }, -} +}; -veCore.component(ConfirmDeleteModalComponent.selector, ConfirmDeleteModalComponent) +veCore.component(ConfirmDeleteModalComponent.selector, ConfirmDeleteModalComponent); diff --git a/src/ve-core/modals/index.ts b/src/ve-core/modals/index.ts index e0fe11de4..801fffdda 100644 --- a/src/ve-core/modals/index.ts +++ b/src/ve-core/modals/index.ts @@ -1,3 +1,3 @@ -import './confirm-delete-modal.component' +import './confirm-delete-modal.component'; -export * from './confirm-delete-modal.component' +export * from './confirm-delete-modal.component'; diff --git a/src/ve-core/search/index.ts b/src/ve-core/search/index.ts index 315791d2d..c9ed03d72 100644 --- a/src/ve-core/search/index.ts +++ b/src/ve-core/search/index.ts @@ -1,5 +1,5 @@ -import './mms-search.component' +import './mms-search.component'; -export * from './mms-search.component' +export * from './mms-search.component'; -import './mms-search-results.component' +import './mms-search-results.component'; diff --git a/src/ve-core/search/mms-search-buttons.config.ts b/src/ve-core/search/mms-search-buttons.config.ts index 6272636bf..6ece9040d 100644 --- a/src/ve-core/search/mms-search-buttons.config.ts +++ b/src/ve-core/search/mms-search-buttons.config.ts @@ -1,4 +1,4 @@ -import { IButtonBarButton } from '@ve-core/button-bar' +import { IButtonBarButton } from '@ve-core/button-bar'; export const search_default_buttons: IButtonBarButton[] = [ { @@ -74,4 +74,4 @@ export const search_default_buttons: IButtonBarButton[] = [ icon: 'pe-type-req', type: 'Requirement', }, -] +]; diff --git a/src/ve-core/search/mms-search-results.component.ts b/src/ve-core/search/mms-search-results.component.ts index 5604360f3..40e0028a8 100644 --- a/src/ve-core/search/mms-search-results.component.ts +++ b/src/ve-core/search/mms-search-results.component.ts @@ -1,20 +1,20 @@ -import { IComponentController } from 'angular' +import { IComponentController } from 'angular'; -import { SearchController } from '@ve-core/search' +import { SearchController } from '@ve-core/search'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { VeComponentOptions } from '@ve-types/angular' -import { ElementObject } from '@ve-types/mms' +import { VeComponentOptions } from '@ve-types/angular'; +import { ElementObject } from '@ve-types/mms'; export class MmsSearchResultsController implements IComponentController { //Parent Controllers - private $search: SearchController + private $search: SearchController; //Bindings - private elem: ElementObject + private elem: ElementObject; - $onChanges + $onChanges; } const MmsSearchResultsComponent: VeComponentOptions = { selector: 'mmsSearchResults', @@ -148,6 +148,6 @@ const MmsSearchResultsComponent: VeComponentOptions = { `, controller: MmsSearchResultsController, -} +}; -veCore.component(MmsSearchResultsComponent.selector, MmsSearchResultsComponent) +veCore.component(MmsSearchResultsComponent.selector, MmsSearchResultsComponent); diff --git a/src/ve-core/search/mms-search.component.ts b/src/ve-core/search/mms-search.component.ts index 0b06b1309..ca2a6d6b7 100644 --- a/src/ve-core/search/mms-search.component.ts +++ b/src/ve-core/search/mms-search.component.ts @@ -1,17 +1,17 @@ -import { StateService } from '@uirouter/angularjs' -import _ from 'lodash' +import { StateService } from '@uirouter/angularjs'; +import _ from 'lodash'; -import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar' -import { veCoreEvents } from '@ve-core/events' -import { search_default_buttons } from '@ve-core/search/mms-search-buttons.config' -import { UtilsService } from '@ve-utils/application' -import { CacheService, EventService } from '@ve-utils/core' -import { ElementService, ProjectService, ViewService, ValueService } from '@ve-utils/mms-api-client' -import { SchemaService } from '@ve-utils/model-schema' +import { ButtonBarApi, ButtonBarService } from '@ve-core/button-bar'; +import { veCoreEvents } from '@ve-core/events'; +import { search_default_buttons } from '@ve-core/search/mms-search-buttons.config'; +import { UtilsService } from '@ve-utils/application'; +import { CacheService, EventService } from '@ve-utils/core'; +import { ElementService, ProjectService, ViewService, ValueService } from '@ve-utils/mms-api-client'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VePromise, VeQService } from '@ve-types/angular'; import { DocumentObject, ElementObject, @@ -21,34 +21,34 @@ import { RequestObject, SearchResponse, ViewObject, -} from '@ve-types/mms' -import { VeSearchOptions } from '@ve-types/view-editor' +} from '@ve-types/mms'; +import { VeSearchOptions } from '@ve-types/view-editor'; export interface SearchQuery { - searchText: string - selectedSearchMetatypes: any[] - searchField: SearchField - from?: number - size?: number + searchText: string; + selectedSearchMetatypes: any[]; + searchField: SearchField; + from?: number; + size?: number; } export interface AdvancedSearchQuery extends SearchQuery { - operator: string + operator: string; } export interface SearchField { - id: string - label: string + id: string; + label: string; } export interface SearchFilter { - appliedStereotypeIds?: string[] - classifierIds?: string[] + appliedStereotypeIds?: string[]; + classifierIds?: string[]; } export interface SearchObject extends ViewObject { - allRelatedDocuments?: ViewObject[] - remainingRelatedDocuments?: ViewObject[] + allRelatedDocuments?: ViewObject[]; + remainingRelatedDocuments?: ViewObject[]; } /** @@ -61,19 +61,19 @@ export interface SearchObject extends ViewObject { * */ export class SearchController implements angular.IComponentController { - private mmsOptions: VeSearchOptions - private mmsProjectId: string - private mmsRefId: string - private embedded: boolean + private mmsOptions: VeSearchOptions; + private mmsProjectId: string; + private mmsRefId: string; + private embedded: boolean; //Search Results - private metatypeSearch: string - protected searchResults: ElementObject[] = [] - protected baseSearchResults: ElementObject[] = [] - protected filteredSearchResults: ElementObject[] = [] - protected showFilterOptions: boolean - protected searchLoading: boolean = false - protected firstSearch: boolean = true + private metatypeSearch: string; + protected searchResults: ElementObject[] = []; + protected baseSearchResults: ElementObject[] = []; + protected filteredSearchResults: ElementObject[] = []; + protected showFilterOptions: boolean; + protected searchLoading: boolean = false; + protected firstSearch: boolean = true; protected mainSearch: SearchQuery = { searchText: '', searchField: { @@ -81,31 +81,31 @@ export class SearchController implements angular.IComponentController { label: 'All Fields', }, selectedSearchMetatypes: [], - } + }; protected docsviews: { selected: boolean } = { selected: false, - } - private emptyDocTxt: string - protected refId: string + }; + private emptyDocTxt: string; + protected refId: string; // Search result settings - protected activeFilter: any[] = [] + protected activeFilter: any[] = []; // Pagination settings - protected totalResults: number = 0 - protected paginationCache: { [key: number]: ElementObject[] } = {} - private maxPages: number - protected currentPage: number = 0 - protected itemsPerPage: number = 10 + protected totalResults: number = 0; + protected paginationCache: { [key: number]: ElementObject[] } = {}; + private maxPages: number; + protected currentPage: number = 0; + protected itemsPerPage: number = 10; // Advanced search settings - protected advanceSearch: boolean = false - protected advancedSearchResults: boolean - protected advanceSearchRows: AdvancedSearchQuery[] = [] - protected stringQuery = this.mainSearch.searchText + protected advanceSearch: boolean = false; + protected advancedSearchResults: boolean; + protected advanceSearchRows: AdvancedSearchQuery[] = []; + protected stringQuery = this.mainSearch.searchText; // View property settings - protected showSearchResultProps = false - protected switchText = 'More' - protected limitForProps = 6 + protected showSearchResultProps = false; + protected switchText = 'More'; + protected limitForProps = 6; // Set search options public fieldTypeList: SearchField[] = [ @@ -133,9 +133,9 @@ export class SearchController implements angular.IComponentController { id: 'type', label: 'Metatype', }, - ] + ]; - public operatorList = ['And', 'Or', 'And Not'] + public operatorList = ['And', 'Or', 'And Not']; // settings for multiselect metatype dropdown public metatypeSettings = { @@ -146,20 +146,20 @@ export class SearchController implements angular.IComponentController { showCheckAll: false, smartButtonMaxItems: 10, buttonClasses: '', - } + }; // event handler for multiselect metatype dropdown public multiselectEvent: { - onItemSelect(ob): void - onItemDeselect(ob): void - onDeselectAll(ob): void - } + onItemSelect(ob): void; + onItemDeselect(ob): void; + onDeselectAll(ob): void; + }; - bbId: string - bbApi: ButtonBarApi - private filterList: QueryObject[] = [] + bbId: string; + bbApi: ButtonBarApi; + private filterList: QueryObject[] = []; - private schema = 'cameo' + private schema = 'cameo'; static $inject = [ '$q', @@ -176,7 +176,7 @@ export class SearchController implements angular.IComponentController { 'ValueService', 'SchemaService', 'ButtonBarService', - ] + ]; constructor( private $q: VeQService, @@ -196,78 +196,78 @@ export class SearchController implements angular.IComponentController { ) {} $onInit(): void { - this.showFilterOptions = !this.mmsOptions.hideFilterOptions + this.showFilterOptions = !this.mmsOptions.hideFilterOptions; if (this.showFilterOptions) { - this.bbId = this.buttonBarSvc.generateBarId('mms-search') - this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, search_default_buttons) + this.bbId = this.buttonBarSvc.generateBarId('mms-search'); + this.bbApi = this.buttonBarSvc.initApi(this.bbId, this.bbInit, search_default_buttons); this.eventSvc.$on(this.bbId, (data) => { - this.bbApi.toggleButton(data.clicked) - this.filterSearchResults(this.buttonBarSvc.getButtonDefinition(data.clicked).type) - }) + this.bbApi.toggleButton(data.clicked); + this.filterSearchResults(this.buttonBarSvc.getButtonDefinition(data.clicked).type); + }); } - this.refId = this.mmsRefId ? this.mmsRefId : 'master' + this.refId = this.mmsRefId ? this.mmsRefId : 'master'; // Set functions - void this.projectSvc.getProjectMounts(this.mmsProjectId, this.refId) + void this.projectSvc.getProjectMounts(this.mmsProjectId, this.refId); //ensure project mounts object is cached // Function used to get string value of metatype names for advanced search - this.getMetaTypes() + this.getMetaTypes(); this.multiselectEvent = { onItemSelect: (ob): void => { void this.$timeout(() => { - this.stringQueryUpdate() - }, 500) + this.stringQueryUpdate(); + }, 500); }, onItemDeselect: (ob): void => { void this.$timeout(() => { - this.stringQueryUpdate() - }, 500) + this.stringQueryUpdate(); + }, 500); }, onDeselectAll: (ob): void => { void this.$timeout(() => { - this.stringQueryUpdate() - }, 500) + this.stringQueryUpdate(); + }, 500); }, - } + }; - this.addAdvanceSearchRow() // Second row created by default + this.addAdvanceSearchRow(); // Second row created by default // Set options if (this.mmsOptions.searchResult) { - const data1 = this.mmsOptions.searchResult - this.searchResults = data1 - this.paginationCache[0] = data1 + const data1 = this.mmsOptions.searchResult; + this.searchResults = data1; + this.paginationCache[0] = data1; } if (this.mmsOptions.searchField) { for (const field of this.fieldTypeList) { if (this.mmsOptions.searchField === field.label || this.mmsOptions.searchField === field.id) { - this.mainSearch.searchField = field - break + this.mainSearch.searchField = field; + break; } } } if (this.mmsOptions.searchInput) { - this.mainSearch.searchText = this.mmsOptions.searchInput - this.newSearch(this.mainSearch) + this.mainSearch.searchText = this.mmsOptions.searchInput; + this.newSearch(this.mainSearch); } if (this.mmsOptions.itemsPerPage) { - this.itemsPerPage = this.mmsOptions.itemsPerPage + this.itemsPerPage = this.mmsOptions.itemsPerPage; } if (this.mmsOptions.emptyDocTxt) { - this.emptyDocTxt = this.mmsOptions.emptyDocTxt + this.emptyDocTxt = this.mmsOptions.emptyDocTxt; } } handleChange = (newVal: ElementObject[]): void => { - if (!newVal) return + if (!newVal) return; if (!this.mmsOptions.getProperties) { - return + return; } newVal.forEach((elem) => { if (elem._properties) { - return + return; } // mms does not return properties will need to make a call for the results whose type is Class // Call this.elementSvc.getOwnedElements with depth of 2 @@ -279,15 +279,15 @@ export class SearchController implements angular.IComponentController { projectId: elem._projectId, refId: elem._refId, depth: 2, - } + }; this.elementSvc.getOwnedElements(reqOb, 2).then( (data: ElementObject[]) => { - const properties: ElementObject[] = [] + const properties: ElementObject[] = []; //TODO might not be elements data.forEach((elt) => { - if (this.valueSvc.isValue(elt)) properties.push(elt) - }) - elem._properties = properties + if (this.valueSvc.isValue(elt)) properties.push(elt); + }); + elem._properties = properties; // OLD CODE - splits into 3cols // if (elem._properties && elem._properties[0]) { // var properties2 = []; @@ -301,55 +301,55 @@ export class SearchController implements angular.IComponentController { // } }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); } - }) - } + }); + }; bbInit = (api: ButtonBarApi): void => { - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-document')) - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-paragraph')) - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-table')) - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-image')) - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-equation')) - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-comment')) - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-section')) - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-view')) - api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-req')) - } + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-document')); + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-paragraph')); + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-table')); + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-image')); + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-equation')); + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-comment')); + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-section')); + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-view')); + api.addButton(this.buttonBarSvc.getButtonBarButton('search-filter-req')); + }; public qualifiedNameFormatter = (qualifiedName: string): string => { if (qualifiedName) { - const parts = qualifiedName.split('/') - let result = qualifiedName + const parts = qualifiedName.split('/'); + let result = qualifiedName; if (parts.length > 7) { - result = parts.slice(0, 4).join('/') + '/.../' + parts.slice(parts.length - 3, parts.length).join('/') + result = parts.slice(0, 4).join('/') + '/.../' + parts.slice(parts.length - 3, parts.length).join('/'); } - return result + return result; } - } + }; public expandQualifiedName = ($event: JQuery.ClickEvent, qualifiedName: string): void => { - ;($event.currentTarget as HTMLElement).innerHTML = qualifiedName - } + ($event.currentTarget as HTMLElement).innerHTML = qualifiedName; + }; public showMoreRelatedViews = (element: SearchObject): void => { - element.remainingRelatedDocuments = element.allRelatedDocuments.slice(3, element.allRelatedDocuments.length) - } + element.remainingRelatedDocuments = element.allRelatedDocuments.slice(3, element.allRelatedDocuments.length); + }; public closeSearch = (): void => { if (this.mmsOptions.closeCallback) { - this.mmsOptions.closeCallback() + this.mmsOptions.closeCallback(); } else { - void this.$state.go('main.project.ref.portal', { search: null, field: null }, { reload: true }) + void this.$state.go('main.project.ref.portal', { search: null, field: null }, { reload: true }); } - } + }; public advancedSearchHandler = (): void => { /* TODO: Reimplement Advanced Search */ - } + }; // Get metatypes for dropdown options public getMetaTypes = (): void => { @@ -363,50 +363,50 @@ export class SearchController implements angular.IComponentController { // }).finally(() => { // scope.metatypeSearch = ""; // }); - this.advancedSearchHandler() - } + this.advancedSearchHandler(); + }; public getMetatypeSelection = (id: string): string => { - const mainElement = angular.element(id) - return mainElement.find('div').attr('value') - } + const mainElement = angular.element(id); + return mainElement.find('div').attr('value'); + }; public getTypeClass = (element: ElementObject): string => { // Get Type - return this.utilsSvc.getElementTypeClass(element, this.viewSvc.getElementType(element)) - } + return this.utilsSvc.getElementTypeClass(element, this.viewSvc.getElementType(element)); + }; // Filter options public getActiveFilterClass = (item: unknown[]): boolean => { if (!this.activeFilter.length) { - return false + return false; } - return _.includes(this.activeFilter, item) - } + return _.includes(this.activeFilter, item); + }; public filterSearchResults = (type: string): void => { - const tempArr = _.clone(this.activeFilter) + const tempArr = _.clone(this.activeFilter); if (_.includes(this.activeFilter, type)) { - _.pull(this.activeFilter, type) + _.pull(this.activeFilter, type); } else { - this.activeFilter.push(type) + this.activeFilter.push(type); } - this._applyFiltersAndPaginate() - } + this._applyFiltersAndPaginate(); + }; private _applyFiltersAndPaginate = (): void => { if (!this.activeFilter.length) { - this.filteredSearchResults = this.searchResults + this.filteredSearchResults = this.searchResults; } else { this.filteredSearchResults = _.filter(this.baseSearchResults, (item) => { - return _.includes(this.activeFilter, this.viewSvc.getElementType(item)) - }) + return _.includes(this.activeFilter, this.viewSvc.getElementType(item)); + }); } - this.maxPages = Math.ceil(this.filteredSearchResults.length / this.itemsPerPage) + this.maxPages = Math.ceil(this.filteredSearchResults.length / this.itemsPerPage); for (const pg of [...Array(this.maxPages).keys()]) { - this.paginationCache[pg] = this.searchResults.slice(pg * this.itemsPerPage, (pg + 1) * this.itemsPerPage) + this.paginationCache[pg] = this.searchResults.slice(pg * this.itemsPerPage, (pg + 1) * this.itemsPerPage); } - } + }; // var findRefineOptions = (results) => { // var presentationElements = _.map(results, this.viewSvc.getElementType); @@ -419,13 +419,13 @@ export class SearchController implements angular.IComponentController { * Updates advanced search main query input */ public stringQueryUpdate = (): void => { - const rowLength = this.advanceSearchRows.length - this.stringQuery = Array(rowLength + 1).join('(') - this.stringQuery += this.mainSearch.searchField.label + ':' + const rowLength = this.advanceSearchRows.length; + this.stringQuery = Array(rowLength + 1).join('('); + this.stringQuery += this.mainSearch.searchField.label + ':'; if (this.mainSearch.searchField.id === 'metatype') { - this.stringQuery += this.getMetatypeSelection('#searchMetatypeSelectAdvance') + this.stringQuery += this.getMetatypeSelection('#searchMetatypeSelectAdvance'); } else { - this.stringQuery += this.mainSearch.searchText + this.stringQuery += this.mainSearch.searchText; } for (let i = 0; i < rowLength; i++) { this.stringQuery += @@ -433,14 +433,14 @@ export class SearchController implements angular.IComponentController { this.advanceSearchRows[i].operator.toUpperCase() + ' ' + this.advanceSearchRows[i].searchField.label + - ':' + ':'; if (this.advanceSearchRows[i].searchField.id === 'metatype') { - this.stringQuery += this.getMetatypeSelection('#searchMetatypeSelect-' + i.toString()) + ')' + this.stringQuery += this.getMetatypeSelection('#searchMetatypeSelect-' + i.toString()) + ')'; } else { - this.stringQuery += this.advanceSearchRows[i].searchText + ')' + this.stringQuery += this.advanceSearchRows[i].searchText + ')'; } } - } + }; /** * @name veCore.directive:mmsSearch#addAdvanceSearchRow @@ -455,9 +455,9 @@ export class SearchController implements angular.IComponentController { }, searchText: '', selectedSearchMetatypes: [], - }) - this.stringQueryUpdate() - } + }); + this.stringQueryUpdate(); + }; /** * @name veCore.directive:mmsSearch#removeRowAdvanceSearch * Removes selected row and updates advanced search main query input @@ -465,22 +465,22 @@ export class SearchController implements angular.IComponentController { * @param {object} row advanced search row */ public removeRowAdvanceSearch = (row: AdvancedSearchQuery): void => { - this.advanceSearchRows = _.without(this.advanceSearchRows, row) - this.stringQueryUpdate() - } + this.advanceSearchRows = _.without(this.advanceSearchRows, row); + this.stringQueryUpdate(); + }; public modifyAdvanceSearch = (): void => { - this.advanceSearch = !this.advanceSearch - this.advancedSearchResults = !this.advancedSearchResults - } + this.advanceSearch = !this.advanceSearch; + this.advancedSearchResults = !this.advancedSearchResults; + }; public pageChanged = (): void => { if (this.paginationCache[this.currentPage]) { - this.baseSearchResults = this.paginationCache[this.currentPage] + this.baseSearchResults = this.paginationCache[this.currentPage]; } else { - this.search(this.mainSearch, this.currentPage, this.itemsPerPage) + this.search(this.mainSearch, this.currentPage, this.itemsPerPage); } - } + }; /** * @name veCore.directive:mmsSearch#search @@ -492,14 +492,14 @@ export class SearchController implements angular.IComponentController { * @param {number} numItems number of items to return per page */ public search = (query: SearchQuery, page: number, numItems: number): void => { - this.searchLoading = true + this.searchLoading = true; if (!this.embedded) { void this.$state.go('.', { search: query.searchText, field: query.searchField.id, - }) + }); } - const queryObs: QueryObject[] = this.buildQuery(query) + const queryObs: QueryObject[] = this.buildQuery(query); // for (const queryOb of queryObs) { // queryOb.from = page * numItems + page // queryOb.size = numItems @@ -507,67 +507,67 @@ export class SearchController implements angular.IComponentController { const reqOb: RequestObject = { projectId: this.mmsProjectId, refId: this.refId, - } - const promises: VePromise, SearchResponse>[] = [] + }; + const promises: VePromise, SearchResponse>[] = []; for (const queryOb of queryObs) { - promises.push(this._performSearch(reqOb, queryOb)) + promises.push(this._performSearch(reqOb, queryOb)); } this.$q .allSettled>(promises) .then( (data) => { - const elements: ElementObject[] = [] - this.searchResults = [] - this.totalResults = 0 + const elements: ElementObject[] = []; + this.searchResults = []; + this.totalResults = 0; for (const d of data) { - elements.push(...d.value.elements) - this.totalResults = this.totalResults + d.value.total + elements.push(...d.value.elements); + this.totalResults = this.totalResults + d.value.total; } if (this.mmsOptions.filterCallback) { - const results = this.mmsOptions.filterCallback(elements) + const results = this.mmsOptions.filterCallback(elements); if (results) { - this.searchResults = results + this.searchResults = results; } else { - this.searchResults = [] + this.searchResults = []; } } else if (elements.length > 0) { - this.searchResults = elements + this.searchResults = elements; } - this.combineRelatedViews() - this.currentPage = page - this._applyFiltersAndPaginate() - this.baseSearchResults = this.paginationCache[page] + this.combineRelatedViews(); + this.currentPage = page; + this._applyFiltersAndPaginate(); + this.baseSearchResults = this.paginationCache[page]; if (this.advanceSearch) { // scope.advanceSearch = !scope.advanceSearch; - this.advancedSearchResults = true + this.advancedSearchResults = true; } // scope.refineOptions = findRefineOptions(baseSearchResults); }, (reason) => { - this.growl.error('Search Error: ' + reason.message) + this.growl.error('Search Error: ' + reason.message); } ) .finally(() => { - this.searchLoading = false - this.firstSearch = false - }) - } + this.searchLoading = false; + this.firstSearch = false; + }); + }; private _performSearch( reqOb: RequestObject, queryOb: QueryObject ): VePromise, SearchResponse> { - return this.elementSvc.search(reqOb, queryOb) + return this.elementSvc.search(reqOb, queryOb); } public newSearch = (query: SearchQuery): void => { - this.searchResults.length = 0 - this.searchLoading = true - this.paginationCache = {} - this.search(query, 0, this.itemsPerPage) - } + this.searchResults.length = 0; + this.searchLoading = true; + this.paginationCache = {}; + this.search(query, 0, this.itemsPerPage); + }; /** * @name veCore.directive:mmsSearch#getProjectMountsQuery @@ -579,29 +579,29 @@ export class SearchController implements angular.IComponentController { * @return {object} Elastic query JSON object with list of project mounts */ getProjectMountsQuery = (): VePromise => { - const deferred: angular.IDeferred = this.$q.defer() - const projList: MountObject[] = [] + const deferred: angular.IDeferred = this.$q.defer(); + const projList: MountObject[] = []; - const mountCacheKey = ['project-mounts', this.mmsProjectId, this.refId] + const mountCacheKey = ['project-mounts', this.mmsProjectId, this.refId]; if (this.cacheSvc.exists(mountCacheKey)) { - const project = this.cacheSvc.get(mountCacheKey) - this.getAllMountsAsArray(project, projList) - deferred.resolve(projList) + const project = this.cacheSvc.get(mountCacheKey); + this.getAllMountsAsArray(project, projList); + deferred.resolve(projList); } else { // Get project element data to gather mounted project list this.projectSvc.getProjectMounts(this.mmsProjectId, this.refId).then( (project) => { - this.getAllMountsAsArray(project, projList) - deferred.resolve(projList) + this.getAllMountsAsArray(project, projList); + deferred.resolve(projList); }, (reason) => { - this.growl.error('Problem getting Project Mounts:' + reason.message) - deferred.resolve(projList) + this.growl.error('Problem getting Project Mounts:' + reason.message); + deferred.resolve(projList); } - ) + ); } - return deferred.promise - } + return deferred.promise; + }; /** * @name veCore.directive:mmsSearch#getAllMountsAsArray @@ -610,20 +610,20 @@ export class SearchController implements angular.IComponentController { * */ public getAllMountsAsArray = (project: ProjectObject, projectsList: ProjectObject[]): void => { - projectsList.push(project) - const mounts = (project as MountObject)._mounts + projectsList.push(project); + const mounts = (project as MountObject)._mounts; if (Array.isArray(mounts) && mounts.length !== 0) { for (let i = 0; i < mounts.length; i++) { if (mounts[i]._mounts) { - this.getAllMountsAsArray(mounts[i], projectsList) + this.getAllMountsAsArray(mounts[i], projectsList); } } } - } + }; public buildSearchClause = (query): void => { /*TODO*/ - } + }; /** * @name veCore.directive:mmsSearch#buildQuery @@ -635,37 +635,37 @@ export class SearchController implements angular.IComponentController { public buildQuery = (query: SearchQuery): QueryObject[] => { // Set project and mounted projects filter //var projectList = this.getProjectMountsQuery() - const filterTerms: { [key: string]: string[] } = {} - const filterQueries: QueryObject[] = [] - const queryObs: QueryObject[] = [] - this.filterList = [] + const filterTerms: { [key: string]: string[] } = {}; + const filterQueries: QueryObject[] = []; + const queryObs: QueryObject[] = []; + this.filterList = []; if (query.searchField.id === 'all') { for (const type of this.fieldTypeList) { if (type.id !== 'all') { - const queryOb: QueryObject = { params: {} } - queryOb.params[type.id] = query.searchText - queryObs.push(queryOb) + const queryOb: QueryObject = { params: {} }; + queryOb.params[type.id] = query.searchText; + queryObs.push(queryOb); } } } else { - const queryOb: QueryObject = { params: {} } - queryOb.params[query.searchField.id] = query.searchText - queryObs.push(queryOb) + const queryOb: QueryObject = { params: {} }; + queryOb.params[query.searchField.id] = query.searchText; + queryObs.push(queryOb); } if (this.mmsOptions.filterQueryList) { for (const filterQuery of this.mmsOptions.filterQueryList) { for (const [term, list] of Object.entries(filterQuery())) { if (!filterTerms[term]) { - filterTerms[term] = [] + filterTerms[term] = []; } filterTerms[term].push( ...list.filter((value) => { - return filterTerms[term].includes(value) + return filterTerms[term].includes(value); }) - ) + ); } } } @@ -674,17 +674,17 @@ export class SearchController implements angular.IComponentController { this.schemaSvc.getSchema('VIEW_SID', this.schema), this.schemaSvc.getSchema('DOCUMENT_SID', this.schema), ...this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema), - ] + ]; /*If the filter list already contain the view id's do not add them a second time since filtering is done client side */ if (!filterTerms.appliedStereotypeIds) { - filterTerms.appliedStereotypeIds = [] + filterTerms.appliedStereotypeIds = []; } filterTerms.appliedStereotypeIds.push( ...stereoIds.filter((value) => { - return !filterTerms.appliedStereotypeIds.includes(value) + return !filterTerms.appliedStereotypeIds.includes(value); }) - ) + ); } if (Object.entries(filterTerms).length > 0) { @@ -692,24 +692,24 @@ export class SearchController implements angular.IComponentController { for (const [term, list] of Object.entries(filterTerms)) { if (list.length > 0) { for (const sid of list) { - const newOb = _.cloneDeep(queryOb) - newOb.params[term] = sid - filterQueries.push(newOb) + const newOb = _.cloneDeep(queryOb); + newOb.params[term] = sid; + filterQueries.push(newOb); } } } } } - if (filterQueries.length > 0) return filterQueries - else return queryObs - } + if (filterQueries.length > 0) return filterQueries; + else return queryObs; + }; private combineRelatedViews = (): void => { this.searchResults.forEach((element: ViewObject) => { const allRelatedDocuments: { - relatedDocument: ViewObject - relatedView: ViewObject - }[] = [] + relatedDocument: ViewObject; + relatedView: ViewObject; + }[] = []; if (element._relatedDocuments) { element._relatedDocuments.forEach((relatedDoc: ViewObject) => { if (relatedDoc._parentViews) { @@ -717,21 +717,21 @@ export class SearchController implements angular.IComponentController { allRelatedDocuments.push({ relatedDocument: relatedDoc, relatedView: parentView, - }) - }) + }); + }); } - }) + }); } - element.allRelatedDocuments = allRelatedDocuments - element.someRelatedDocuments = allRelatedDocuments.slice(0, 3) - }) - } + element.allRelatedDocuments = allRelatedDocuments; + element.someRelatedDocuments = allRelatedDocuments.slice(0, 3); + }); + }; public userResultClick = (elem: ElementObject, property: string): void => { if (this.mmsOptions.callback) { - this.mmsOptions.callback(elem, property) + this.mmsOptions.callback(elem, property); } - } + }; public userRelatedClick = ( event: JQuery.ClickEvent, @@ -739,13 +739,13 @@ export class SearchController implements angular.IComponentController { view: ViewObject, elem: ElementObject ): void => { - event.preventDefault() - event.stopPropagation() - if (this.mmsOptions.relatedCallback) this.mmsOptions.relatedCallback(doc, view, elem) - } + event.preventDefault(); + event.stopPropagation(); + if (this.mmsOptions.relatedCallback) this.mmsOptions.relatedCallback(doc, view, elem); + }; private toggleDocs(): void { - this.docsviews.selected = !this.docsviews.selected + this.docsviews.selected = !this.docsviews.selected; } } const SearchComponent: VeComponentOptions = { @@ -962,6 +962,6 @@ const SearchComponent: VeComponentOptions = { embedded: '<', }, controller: SearchController, -} +}; -veCore.component(SearchComponent.selector, SearchComponent) +veCore.component(SearchComponent.selector, SearchComponent); diff --git a/src/ve-core/toolbar/index.ts b/src/ve-core/toolbar/index.ts index a491346a7..fad0112f2 100644 --- a/src/ve-core/toolbar/index.ts +++ b/src/ve-core/toolbar/index.ts @@ -1,9 +1,9 @@ //Exports -export * from './services/Toolbar.service' -export * from './services/Toolbar.api' +export * from './services/Toolbar.service'; +export * from './services/Toolbar.api'; //Services -import './services/Toolbar.service' +import './services/Toolbar.service'; //Core Components -import './tool-bar.component' +import './tool-bar.component'; diff --git a/src/ve-core/toolbar/services/Toolbar.api.ts b/src/ve-core/toolbar/services/Toolbar.api.ts index 5bbca57d1..c77d107b1 100644 --- a/src/ve-core/toolbar/services/Toolbar.api.ts +++ b/src/ve-core/toolbar/services/Toolbar.api.ts @@ -1,7 +1,7 @@ -import { ToolButton } from '@ve-core/toolbar' +import { ToolButton } from '@ve-core/toolbar'; export class ToolbarApi { - public buttons: ToolButton[] = [] + public buttons: ToolButton[] = []; constructor(public id: string) {} @@ -12,27 +12,27 @@ export class ToolbarApi { // $scope.clicked(button); if (!button.dynamic) { this.buttons.forEach((b) => { - b.selected = b.id === button.id - }) + b.selected = b.id === button.id; + }); // de-activate all dynamic this.buttons this.buttons.forEach((b) => { if (b.dynamic) { - b.active = false + b.active = false; } - }) + }); if (button.dynamicButtons) { button.dynamicButtons.forEach((b) => { - b.active = true - }) + b.active = true; + }); } } } //else // button.selected = false; - }) - } + }); + }; public deactivate = (id: string): void => { this.buttons.forEach((button) => { @@ -40,66 +40,66 @@ export class ToolbarApi { if (button.dynamicButtons) { // de-activate all dynamic buttons button.dynamicButtons.forEach((b) => { - b.active = false - }) + b.active = false; + }); } } - }) - } + }); + }; public setPermission = (id: string, permission: boolean): void => { this.buttons.forEach((button) => { if (button.id === id) { - button.permission = permission + button.permission = permission; } - }) - } + }); + }; public setSelected = (id: string, selected: boolean): void => { this.buttons.forEach((button) => { if (button.id === id) { - button.selected = selected + button.selected = selected; } - }) - } + }); + }; public setIcon = (id: string, icon: string): void => { this.buttons.forEach((button) => { if (button.id === id) { - button.icon = icon + button.icon = icon; } - }) - } + }); + }; public addButton = (button: ToolButton): void => { - button.priority = this.buttons.length - this.buttons.push(button) + button.priority = this.buttons.length; + this.buttons.push(button); if (button.dynamicButtons) { - let firstButton = true + let firstButton = true; button.dynamicButtons.forEach((buttonLoop) => { if (!this.buttons.map((button) => button.id).includes(buttonLoop.id)) { if (firstButton) { - buttonLoop.pullDown = true - firstButton = false + buttonLoop.pullDown = true; + firstButton = false; } - buttonLoop.priority = this.buttons.length + 1000 - this.buttons.push(buttonLoop) + buttonLoop.priority = this.buttons.length + 1000; + this.buttons.push(buttonLoop); } - }) + }); } - } + }; public toggleButtonSpinner = (id: string): void => { this.buttons.forEach((button) => { if (button.id === id) { if (button.spinner) { - button.icon = button.icon_original + button.icon = button.icon_original; } else { - button.icon_original = button.icon - button.icon = 'fa fa-spinner fa-spin' + button.icon_original = button.icon; + button.icon = 'fa fa-spinner fa-spin'; } - button.spinner = !button.spinner + button.spinner = !button.spinner; } - }) - } + }); + }; } diff --git a/src/ve-core/toolbar/services/Toolbar.service.ts b/src/ve-core/toolbar/services/Toolbar.service.ts index 4d6dd4b97..ebb658dfe 100644 --- a/src/ve-core/toolbar/services/Toolbar.service.ts +++ b/src/ve-core/toolbar/services/Toolbar.service.ts @@ -1,87 +1,87 @@ -import { veCoreEvents } from '@ve-core/events' -import { EventService } from '@ve-utils/core' +import { veCoreEvents } from '@ve-core/events'; +import { EventService } from '@ve-utils/core'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { ToolbarApi } from './Toolbar.api' +import { ToolbarApi } from './Toolbar.api'; -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { VeConfig } from '@ve-types/config' -import { VeApiObject } from '@ve-types/view-editor' +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { VeConfig } from '@ve-types/config'; +import { VeApiObject } from '@ve-types/view-editor'; export interface IToolBarButton { - id: string - icon: string - tooltip: string - category?: string - icon_original?: string - selected?: boolean - active?: boolean - permission?: boolean - spinner?: boolean - dynamic?: boolean - priority?: number - pullDown?: boolean - onClick?: buttonOnClickFn - dynamic_ids?: string[] - disabledFor?: string[] - enabledFor?: string[] + id: string; + icon: string; + tooltip: string; + category?: string; + icon_original?: string; + selected?: boolean; + active?: boolean; + permission?: boolean; + spinner?: boolean; + dynamic?: boolean; + priority?: number; + pullDown?: boolean; + onClick?: buttonOnClickFn; + dynamic_ids?: string[]; + disabledFor?: string[]; + enabledFor?: string[]; } export interface buttonOnClickFn { - (button?: IToolBarButton): void + (button?: IToolBarButton): void; } export interface toolbarInitFn { - (api: ToolbarApi): void + (api: ToolbarApi): void; } export class ToolButton implements IToolBarButton { - id: string - category: string = 'global' - icon: string = 'fa-gears' - tooltip: string = 'Generic Button' - icon_original: string = 'fa-gears' - selected: boolean = false - active: boolean = true - permission: boolean - spinner: boolean = false - dynamic: boolean = false - pullDown: boolean = false - dynamicButtons: ToolButton[] = [] - disabledFor: string[] = [] - enabledFor: string[] = [] - priority: number = 0 + id: string; + category: string = 'global'; + icon: string = 'fa-gears'; + tooltip: string = 'Generic Button'; + icon_original: string = 'fa-gears'; + selected: boolean = false; + active: boolean = true; + permission: boolean; + spinner: boolean = false; + dynamic: boolean = false; + pullDown: boolean = false; + dynamicButtons: ToolButton[] = []; + disabledFor: string[] = []; + enabledFor: string[] = []; + priority: number = 0; constructor(id: string, tbutton?: IToolBarButton) { - this.id = id + this.id = id; if (tbutton) { - Object.assign(this, tbutton) + Object.assign(this, tbutton); } } - onClick: buttonOnClickFn + onClick: buttonOnClickFn; } export class ToolbarService { - private toolbars: VeApiObject = {} - private buttons: { [key: string]: IToolBarButton } = {} - private dynamicButtons: { [key: string]: IToolBarButton } = {} - private veConfig: VeConfig + private toolbars: VeApiObject = {}; + private buttons: { [key: string]: IToolBarButton } = {}; + private dynamicButtons: { [key: string]: IToolBarButton } = {}; + private veConfig: VeConfig; - static $inject = ['$q', 'EventService'] + static $inject = ['$q', 'EventService']; constructor(private $q: VeQService, private eventSvc: EventService) { - this.veConfig = window.__env + this.veConfig = window.__env; if (this.veConfig.expConfig) { for (const ext of Object.keys(this.veConfig.expConfig)) { if (this.veConfig.expConfig[ext] && this.veConfig.expConfig[ext].length > 0) { for (const tool of this.veConfig.expConfig[ext]) { if (tool.toolButton) { - this.registerToolbarButtons(tool.toolButton) + this.registerToolbarButtons(tool.toolButton); } if (tool.toolDynamicButton && tool.toolDynamicButton.length > 0) { - this.registerDynamicButtons(tool.toolDynamicButton) + this.registerDynamicButtons(tool.toolDynamicButton); } } } @@ -91,14 +91,14 @@ export class ToolbarService { public waitForApi = (id: string): VePromise => { if (!this.toolbars.hasOwnProperty(id)) { - this.toolbars[id] = {} + this.toolbars[id] = {}; this.toolbars[id].promise = new this.$q((resolve, reject) => { - this.toolbars[id].resolve = resolve - this.toolbars[id].reject = reject - }) + this.toolbars[id].resolve = resolve; + this.toolbars[id].reject = reject; + }); } - return this.toolbars[id].promise - } + return this.toolbars[id].promise; + }; public initApi( id: string, @@ -109,16 +109,16 @@ export class ToolbarService { initialSelection?: string ): ToolbarApi { if (!id) { - throw new Error('Unable to create Toolbar, missing id') + throw new Error('Unable to create Toolbar, missing id'); } if (!this.toolbars[id]) { - this.toolbars[id] = {} + this.toolbars[id] = {}; } if (!this.toolbars[id].resolve) { this.toolbars[id].promise = new this.$q((resolve, reject) => { - this.toolbars[id].resolve = resolve - this.toolbars[id].reject = reject - }) + this.toolbars[id].resolve = resolve; + this.toolbars[id].reject = reject; + }); } // if (!ctrl.$onDestroy) { @@ -127,68 +127,68 @@ export class ToolbarService { // } // } - const api = new ToolbarApi(id) + const api = new ToolbarApi(id); if (buttons && buttons.length > 0) { - this.registerToolbarButtons(buttons) + this.registerToolbarButtons(buttons); } if (dynamicButtons && dynamicButtons.length > 0) { - this.registerDynamicButtons(dynamicButtons) + this.registerDynamicButtons(dynamicButtons); } - init(api) - this.toolbars[id].api = api + init(api); + this.toolbars[id].api = api; if (api.buttons.length > 0) { - let inspect: IToolBarButton + let inspect: IToolBarButton; if (initialSelection) { - inspect = this.getToolbarButton(initialSelection) + inspect = this.getToolbarButton(initialSelection); } else { - inspect = api.buttons[0] + inspect = api.buttons[0]; } //Initialize Toolbar Clicked Subject this.eventSvc.resolve(id, { id: inspect.id, title: inspect.tooltip, - }) + }); } - this.toolbars[id].resolve(api) - return api + this.toolbars[id].resolve(api); + return api; } public destroyApi = (id: string): void => { if (this.toolbars.hasOwnProperty(id)) { - delete this.toolbars[id] + delete this.toolbars[id]; } - } + }; public registerToolbarButtons = (buttons: IToolBarButton | IToolBarButton[]): void => { if (!Array.isArray(buttons)) { - buttons = [buttons] + buttons = [buttons]; } if (buttons.length > 0) { for (const button of buttons) { if (!this.buttons[button.id]) { - this.buttons[button.id] = button + this.buttons[button.id] = button; } } } - } + }; public registerDynamicButtons = (dynamicButtons: IToolBarButton | IToolBarButton[]): void => { if (!Array.isArray(dynamicButtons)) { - dynamicButtons = [dynamicButtons] + dynamicButtons = [dynamicButtons]; } if (dynamicButtons.length > 0) { for (const button of dynamicButtons) { if (!this.dynamicButtons[button.id]) { - this.dynamicButtons[button.id] = button + this.dynamicButtons[button.id] = button; } } } - } + }; - public attachDynamicButtons + public attachDynamicButtons; /** * @name veUtils/ToolbarService#this.getToolbarButton @@ -200,29 +200,29 @@ export class ToolbarService { */ public getToolbarButton = (buttonId: string): ToolButton => { if (this.buttons.hasOwnProperty(buttonId)) { - const newButton = new ToolButton(buttonId, this.buttons[buttonId]) + const newButton = new ToolButton(buttonId, this.buttons[buttonId]); if (this.buttons[buttonId].dynamic_ids) { - newButton.dynamicButtons = [] + newButton.dynamicButtons = []; for (const id of this.buttons[buttonId].dynamic_ids) { - newButton.dynamicButtons.push(new ToolButton(id, this.getDynamicButton(id))) + newButton.dynamicButtons.push(new ToolButton(id, this.getDynamicButton(id))); } } - return newButton + return newButton; } else { - return (this.buttons[buttonId] = new ToolButton(buttonId)) + return (this.buttons[buttonId] = new ToolButton(buttonId)); } - } + }; public getDynamicButton = (button: string): IToolBarButton => { if (this.dynamicButtons.hasOwnProperty(button)) { - return this.dynamicButtons[button] + return this.dynamicButtons[button]; } - } + }; static error(reason?: VePromiseReason): string { - if (reason && reason.message) return 'Toolbar error: ' + reason.message - else return 'Toolbar Error!' + if (reason && reason.message) return 'Toolbar error: ' + reason.message; + else return 'Toolbar Error!'; } } -veCore.service('ToolbarService', ToolbarService) +veCore.service('ToolbarService', ToolbarService); diff --git a/src/ve-core/toolbar/tool-bar.component.ts b/src/ve-core/toolbar/tool-bar.component.ts index b58312d80..76b8b9e62 100644 --- a/src/ve-core/toolbar/tool-bar.component.ts +++ b/src/ve-core/toolbar/tool-bar.component.ts @@ -1,13 +1,13 @@ -import { veCoreEvents } from '@ve-core/events' -import { buttonOnClickFn, IToolBarButton } from '@ve-core/toolbar' -import { RootScopeService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { veCoreEvents } from '@ve-core/events'; +import { buttonOnClickFn, IToolBarButton } from '@ve-core/toolbar'; +import { RootScopeService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; -import { veCore } from '@ve-core' +import { veCore } from '@ve-core'; -import { ToolbarService } from './services/Toolbar.service' +import { ToolbarService } from './services/Toolbar.service'; -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; const ToolBarComponent: VeComponentOptions = { selector: 'toolBar', @@ -30,17 +30,17 @@ const ToolBarComponent: VeComponentOptions = { paneToggle: '&', }, controller: class VeToolbarController implements angular.IComponentController { - public subs: Rx.IDisposable[] + public subs: Rx.IDisposable[]; - private anchor: string - private toolbarId: string - private paneToggle?(): void + private anchor: string; + private toolbarId: string; + private paneToggle?(): void; - public buttons: IToolBarButton[] + public buttons: IToolBarButton[]; - tooltipAnchor + tooltipAnchor; - static $inject = ['growl', 'RootScopeService', 'EventService', 'ToolbarService'] + static $inject = ['growl', 'RootScopeService', 'EventService', 'ToolbarService']; constructor( private growl: angular.growl.IGrowlService, @@ -50,65 +50,65 @@ const ToolBarComponent: VeComponentOptions = { ) {} $onInit(): void { - this.eventSvc.$init(this) + this.eventSvc.$init(this); if (this.anchor) { switch (this.anchor) { case 'left': - this.tooltipAnchor = 'right' - break + this.tooltipAnchor = 'right'; + break; case 'right': - this.tooltipAnchor = 'left' - break + this.tooltipAnchor = 'left'; + break; case 'top': - this.tooltipAnchor = 'bottom' - break + this.tooltipAnchor = 'bottom'; + break; case 'bottom': - this.tooltipAnchor = 'top' - break + this.tooltipAnchor = 'top'; + break; } } else { - this.tooltipAnchor = 'left' + this.tooltipAnchor = 'left'; } this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => { - this.buttons = api.buttons + this.buttons = api.buttons; if (this.buttons.length > 0) { //Binding to catch all "clicks" on tb and execute select function this.eventSvc.binding(this.toolbarId, (data) => { this.toolbarSvc.waitForApi(this.toolbarId).then( (api) => api.select(data.id), (reason) => this.growl.error(ToolbarService.error(reason)) - ) - }) + ); + }); } }, (reason) => { - this.growl.error(reason.message) + this.growl.error(reason.message); } - ) + ); } public clicked = (button: IToolBarButton): void => { if (!button.permission) { - return + return; } if (!button.active) { - return + return; } if (this.paneToggle) { - this.paneToggle() + this.paneToggle(); } if (button.onClick) { - button.onClick() + button.onClick(); } else if (this.onClick) { - this.onClick(button) + this.onClick(button); } else { - this.growl.error('Button' + button.id + 'has no click function') + this.growl.error('Button' + button.id + 'has no click function'); } - } + }; protected onClick: buttonOnClickFn = (button) => { if (!button.dynamic) { @@ -116,12 +116,12 @@ const ToolBarComponent: VeComponentOptions = { id: button.id, category: button.category, title: button.tooltip, - }) + }); } else { - this.eventSvc.$broadcast(button.id) + this.eventSvc.$broadcast(button.id); } - } + }; }, -} +}; -veCore.component(ToolBarComponent.selector, ToolBarComponent) +veCore.component(ToolBarComponent.selector, ToolBarComponent); diff --git a/src/ve-core/ve-core.module.ts b/src/ve-core/ve-core.module.ts index 999f39349..28334ca8a 100644 --- a/src/ve-core/ve-core.module.ts +++ b/src/ve-core/ve-core.module.ts @@ -1,4 +1,4 @@ -import angular from 'angular' +import angular from 'angular'; /** * @ngdoc overview @@ -76,7 +76,7 @@ export const veCore = angular.module('ve-core', [ 'angular-growl', 'angularjs-dropdown-multiselect', 'ui.tree-filter', -]) +]); veCore .config([ @@ -88,17 +88,17 @@ veCore growlProvider: angular.growl.IGrowlProvider, uiTreeFilterSettingsProvider ): void => { - $sceProvider.enabled(false) - growlProvider.onlyUniqueMessages(false) + $sceProvider.enabled(false); + growlProvider.onlyUniqueMessages(false); growlProvider.globalTimeToLive({ success: 5000, error: -1, warning: 5000, info: 5000, - }) - growlProvider.globalPosition('bottom-right') - uiTreeFilterSettingsProvider.addresses = ['label'] - uiTreeFilterSettingsProvider.descendantCollection = 'children' + }); + growlProvider.globalPosition('bottom-right'); + uiTreeFilterSettingsProvider.addresses = ['label']; + uiTreeFilterSettingsProvider.descendantCollection = 'children'; }, ]) - .constant('CKEDITOR', window.CKEDITOR) + .constant('CKEDITOR', window.CKEDITOR); diff --git a/src/ve-extensions/experimental-magic/index.ts b/src/ve-extensions/experimental-magic/index.ts index 7a73778bc..2a93ca922 100644 --- a/src/ve-extensions/experimental-magic/index.ts +++ b/src/ve-extensions/experimental-magic/index.ts @@ -1 +1 @@ -import './spec-tools/spec-magic.component' +import './spec-tools/spec-magic.component'; diff --git a/src/ve-extensions/experimental-magic/spec-tools/spec-magic.component.ts b/src/ve-extensions/experimental-magic/spec-tools/spec-magic.component.ts index a35a288c5..39f397226 100644 --- a/src/ve-extensions/experimental-magic/spec-tools/spec-magic.component.ts +++ b/src/ve-extensions/experimental-magic/spec-tools/spec-magic.component.ts @@ -1,11 +1,11 @@ -import angular from 'angular' -import _ from 'lodash' +import angular from 'angular'; +import _ from 'lodash'; -import { ComponentService } from '@ve-components/services' -import { SpecTool, ISpecTool, SpecService } from '@ve-components/spec-tools' -import { ToolbarService } from '@ve-core/toolbar' -import { ApplicationService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' +import { ComponentService } from '@ve-components/services'; +import { SpecTool, ISpecTool, SpecService } from '@ve-components/spec-tools'; +import { ToolbarService } from '@ve-core/toolbar'; +import { ApplicationService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; import { ApiService, ElementService, @@ -13,14 +13,14 @@ import { ProjectService, URLService, ViewService, -} from '@ve-utils/mms-api-client' +} from '@ve-utils/mms-api-client'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VeComponentOptions, VeQService } from '@ve-types/angular' +import { VeComponentOptions, VeQService } from '@ve-types/angular'; class SpecMagicController extends SpecTool implements ISpecTool { - static $inject = [...SpecTool.$inject] + static $inject = [...SpecTool.$inject]; constructor( $q: VeQService, @@ -55,9 +55,9 @@ class SpecMagicController extends SpecTool implements ISpecTool { eventSvc, specSvc, toolbarSvc - ) - this.specType = _.kebabCase(SpecMagicComponent.selector) - this.specTitle = 'Magic Element' + ); + this.specType = _.kebabCase(SpecMagicComponent.selector); + this.specTitle = 'Magic Element'; } } @@ -67,6 +67,6 @@ const SpecMagicComponent: VeComponentOptions = {

    Hello World!!

    `, controller: SpecMagicController, -} +}; -veComponents.component(SpecMagicComponent.selector, SpecMagicComponent) +veComponents.component(SpecMagicComponent.selector, SpecMagicComponent); diff --git a/src/ve-extensions/index.ts b/src/ve-extensions/index.ts index 3e118298f..d383e35a3 100644 --- a/src/ve-extensions/index.ts +++ b/src/ve-extensions/index.ts @@ -1,2 +1,2 @@ //** Automatically Generated by Webpack do not edit **// -import './experimental-magic' \ No newline at end of file +import './experimental-magic'; diff --git a/src/ve-extensions/present-plots/Plot.service.ts b/src/ve-extensions/present-plots/Plot.service.ts index d89e1f6a8..d6ef86c36 100644 --- a/src/ve-extensions/present-plots/Plot.service.ts +++ b/src/ve-extensions/present-plots/Plot.service.ts @@ -1,8 +1,8 @@ -import { UtilsService } from '@ve-utils/application/Utils.service' -import { CacheService } from '@ve-utils/core' -import { ElementService, URLService } from '@ve-utils/mms-api-client' +import { UtilsService } from '@ve-utils/application/Utils.service'; +import { CacheService } from '@ve-utils/core'; +import { ElementService, URLService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; export class PlotService { constructor( @@ -16,162 +16,162 @@ export class PlotService { //make only a-zA-Z0-9_ because id or class does not support special characters(ie., ()) public toValidId = (original) => { - return original.replace(/[^a-zA-Z0-9_]/gi, '') - } + return original.replace(/[^a-zA-Z0-9_]/gi, ''); + }; /** * @param {Object} clientConfig The size width, height and margin info from magicDraw * @param {Object} defaultPlotConfig The size width, height and margin from the plot directive */ public plotConfig = (clientConfig, defaultPlotConfig) => { - const plotConfig = defaultPlotConfig + const plotConfig = defaultPlotConfig; if (clientConfig !== undefined) { if (clientConfig.size !== undefined) { if (clientConfig.size.width != undefined && !isNaN(clientConfig.size.width)) - plotConfig.width = Number(clientConfig.size.width) + plotConfig.width = Number(clientConfig.size.width); if (clientConfig.size.height != undefined && !isNaN(clientConfig.size.height)) - plotConfig.height = Number(clientConfig.size.height) + plotConfig.height = Number(clientConfig.size.height); } if (clientConfig.padding !== undefined) { if (clientConfig.padding.top != undefined && !isNaN(clientConfig.padding.top)) - plotConfig.marginTop = Number(clientConfig.padding.top) + plotConfig.marginTop = Number(clientConfig.padding.top); if (clientConfig.padding.right != undefined && !isNaN(clientConfig.padding.right)) - plotConfig.marginRight = Number(clientConfig.padding.right) + plotConfig.marginRight = Number(clientConfig.padding.right); if (clientConfig.padding.left != undefined && !isNaN(clientConfig.padding.left)) - plotConfig.marginLeft = Number(clientConfig.padding.left) + plotConfig.marginLeft = Number(clientConfig.padding.left); if (clientConfig.padding.bottom != undefined && !isNaN(clientConfig.padding.bottom)) - plotConfig.marginBottom = Number(clientConfig.padding.bottom) + plotConfig.marginBottom = Number(clientConfig.padding.bottom); } } - return plotConfig - } + return plotConfig; + }; public readValues2(plot, projectId, refId, commitId) { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); const aMmsEid = { projectId: projectId, refId: refId, commitId: commitId, - } - const isHeader = plot.table.header !== undefined && plot.table.header.length > 0 + }; + const isHeader = plot.table.header !== undefined && plot.table.header.length > 0; if (isHeader) { - const aheader = this._asyncReadTableHeader(aMmsEid, plot.table.header[0]) + const aheader = this._asyncReadTableHeader(aMmsEid, plot.table.header[0]); aheader.then((tableheader) => { - const abody = this._asyncReadTableBody2(aMmsEid, plot.table.body, tableheader) + const abody = this._asyncReadTableBody2(aMmsEid, plot.table.body, tableheader); abody.then((tablebody) => { const r = { tableheader: tableheader, tablebody: tablebody, isHeader: isHeader, - } - deferred.resolve(r) - }) - }) + }; + deferred.resolve(r); + }); + }); } else { - const abody = this._asyncReadTableBody(aMmsEid, plot.table.body) + const abody = this._asyncReadTableBody(aMmsEid, plot.table.body); abody.then((tablebody) => { - const r = { tablebody: tablebody, isHeader: isHeader } - deferred.resolve(r) - }) + const r = { tablebody: tablebody, isHeader: isHeader }; + deferred.resolve(r); + }); } - return deferred.promise + return deferred.promise; } //end of readValues public readValues = (plot, projectId, refId, commitId) => { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); const aMmsEid = { projectId: projectId, refId: refId, commitId: commitId, - } - const isHeader = plot.table.header !== undefined && plot.table.header.length > 0 + }; + const isHeader = plot.table.header !== undefined && plot.table.header.length > 0; if (isHeader) { - const aheader = this._asyncReadTableHeader(aMmsEid, plot.table.header[0]) + const aheader = this._asyncReadTableHeader(aMmsEid, plot.table.header[0]); aheader.then((tableheader) => { - const abody = this._asyncReadTableBody(aMmsEid, plot.table.body) + const abody = this._asyncReadTableBody(aMmsEid, plot.table.body); abody.then((tablebody) => { const r = { tableheader: tableheader, tablebody: tablebody, isHeader: isHeader, - } - deferred.resolve(r) - }) - }) + }; + deferred.resolve(r); + }); + }); } else { - const abody = this._asyncReadTableBody(aMmsEid, plot.table.body) + const abody = this._asyncReadTableBody(aMmsEid, plot.table.body); abody.then((tablebody) => { - const r = { tablebody: tablebody, isHeader: isHeader } - deferred.resolve(r) - }) + const r = { tablebody: tablebody, isHeader: isHeader }; + deferred.resolve(r); + }); } - return deferred.promise - } //end of readValues + return deferred.promise; + }; //end of readValues private _asyncReadTableHeader = (aMmsEid, header) => { return this.$q((resolve) => { this._readRowValues(header, aMmsEid).then((tableheader) => { - tableheader.values.shift() //remove 1st element - resolve(tableheader.values) - }) - }) - } + tableheader.values.shift(); //remove 1st element + resolve(tableheader.values); + }); + }); + }; private _asyncReadTableBody = (aMmsEid, tablebody) => { return this.$q((resolve) => { - const c3_data = [] - const valuesO = [] + const c3_data = []; + const valuesO = []; tablebody.forEach((row) => { this._readRowValues(row, aMmsEid).then((yyvalue) => { - c3_data.push(yyvalue.values) - valuesO.push(yyvalue.valuesO) + c3_data.push(yyvalue.values); + valuesO.push(yyvalue.valuesO); if (c3_data.length === tablebody.length) { const r = { c3_data: c3_data, valuesO: valuesO, - } - resolve(r) + }; + resolve(r); } - }) - }) - }) - } + }); + }); + }); + }; private _asyncReadTableBody2(aMmsEid, tablebody, tableheader) { return this.$q((resolve) => { - const c3_data = [] - const valuesO = [] + const c3_data = []; + const valuesO = []; //adding "rowheader" so length of header and rowvalues will be the same. - const mtableheader = tableheader.slice(0) - mtableheader.splice(0, 0, 'rowheader') + const mtableheader = tableheader.slice(0); + mtableheader.splice(0, 0, 'rowheader'); tablebody.forEach((row) => { this._readRowValues2(row, aMmsEid, mtableheader).then((yyvalue) => { - c3_data.push(yyvalue.valuesx) - valuesO.push(yyvalue.valuesO) + c3_data.push(yyvalue.valuesx); + valuesO.push(yyvalue.valuesO); if (valuesO.length === tablebody.length) { const r = { c3_data: c3_data, valuesO: valuesO, - } - resolve(r) + }; + resolve(r); } - }) - }) - }) + }); + }); + }); } private static _getValue(datavalue) { if (datavalue && datavalue.type === 'LiteralString') { - if (isNaN(datavalue.value)) return datavalue.value - else return Number(datavalue.value) + if (isNaN(datavalue.value)) return datavalue.value; + else return Number(datavalue.value); } else if (datavalue && (datavalue.type === 'LiteralReal' || datavalue.type === 'LiteralInteger')) { - return datavalue.value + return datavalue.value; } } @@ -179,60 +179,60 @@ export class PlotService { return this.$q((resolve) => { if (e.content[0].sourceType == 'text') { //console.log("text"); - let tv = e.content[0].text.replace('

    ', '').replace('

    ', '').trim() - if (!isNaN(tv)) tv = Number(tv) - resolve({ index: index, value: tv, valueO: e }) + let tv = e.content[0].text.replace('

    ', '').replace('

    ', '').trim(); + if (!isNaN(tv)) tv = Number(tv); + resolve({ index: index, value: tv, valueO: e }); } else if (e.content[0].sourceType === 'reference') { - aMmsEid.elementId = e.content[0].source + aMmsEid.elementId = e.content[0].source; if (e.content[0].sourceProperty === 'name') { //console.log("name"); this.elementSvc.getElement(aMmsEid, 1, false).then((refe) => { //value = refe.name; //valueO= refe; - let nameModified: number | string = refe.name + let nameModified: number | string = refe.name; if (!isNaN(Number(refe.name))) //means its a number - nameModified = Number(refe.name) + nameModified = Number(refe.name); resolve({ index: index, value: nameModified, valueO: refe, - }) - }) + }); + }); } else if (e.content[0].sourceProperty === 'documentation') { //console.log("doc"); this.elementSvc.getElement(aMmsEid, 1, false).then((refe) => { let docModified: number | string = refe.documentation .replace('

    ', '') .replace('

    ', '') - .trim() + .trim(); //seems adding \n at the end when modified at vieweditor so if number goahead to conver to number //i.e., "5\n" will be a number. if (!isNaN(Number(docModified))) //means it is a number - docModified = Number(docModified) + docModified = Number(docModified); resolve({ index: index, value: docModified, valueO: refe, - }) - }) + }); + }); } else { //sourceProperty === 'value' //console.log('value'); this.elementSvc.getElement(aMmsEid, 1, false).then((refe) => { - const valueO = refe - let value = '' + const valueO = refe; + let value = ''; if (refe.type === 'Property' || refe.type === 'Port') { if (refe.defaultValue) { - value = PlotService._getValue(refe.defaultValue) //default value + value = PlotService._getValue(refe.defaultValue); //default value } else { - value = '' + value = ''; } } if (refe.type === 'Slot') { - value = PlotService._getValue(refe.value[0]) //scope.element.value + value = PlotService._getValue(refe.value[0]); //scope.element.value } /* not sure what to do if (refe.type === 'Constraint' && refe.specification) { @@ -246,71 +246,71 @@ export class PlotService { index: index, value: value, valueO: valueO, - }) - }) + }); + }); } //end of else } //reference - }) - } + }); + }; private _readRowValues = (row, aMmsEid) => { return this.$q((resolve) => { - const values = [] - const valuesO = [] - let index = 0 + const values = []; + const valuesO = []; + let index = 0; row.forEach((e) => { if (e.content.length === 0) { - values[index] = null - valuesO[index] = null - index++ + values[index] = null; + valuesO[index] = null; + index++; } else { if (e.content[0].type == 'Paragraph') { this._readParagraphValue(e, aMmsEid, index++).then((r) => { - values[r.index] = r.value - valuesO[r.index] = r.valueO + values[r.index] = r.value; + valuesO[r.index] = r.valueO; if (values.length === row.length) { const result = { values: values, valuesO: valuesO, - } - resolve(result) + }; + resolve(result); } - }) + }); } // Paragraph } //end of else - }) //for each row - }) - } //end of function + }); //for each row + }); + }; //end of function private _readRowValues2(row, aMmsEid, mtableheader) { return this.$q((resolve) => { - const valuesx = [] //named index instead of number index - const valuesO = [] - let index = 0 + const valuesx = []; //named index instead of number index + const valuesO = []; + let index = 0; row.forEach((e) => { if (e.content.length === 0) { - valuesx[mtableheader[index]] = null - valuesO[index] = null - index++ + valuesx[mtableheader[index]] = null; + valuesO[index] = null; + index++; } else { if (e.content[0].type == 'Paragraph') { this._readParagraphValue(e, aMmsEid, index++).then((r) => { - valuesx[mtableheader[r.index]] = r.value - valuesO[r.index] = r.valueO + valuesx[mtableheader[r.index]] = r.value; + valuesO[r.index] = r.valueO; if (valuesO.length === row.length) { const result = { valuesx: valuesx, valuesO: valuesO, - } - resolve(result) + }; + resolve(result); } - }) + }); } // Paragraph } //end of else - }) //for each row - }) + }); //for each row + }); } //end of function } -PlotService.$inject = ['$q', '$http', 'URLService', 'UtilsService', 'CacheService', 'ElementService'] +PlotService.$inject = ['$q', '$http', 'URLService', 'UtilsService', 'CacheService', 'ElementService']; -veUtils.service('PlotService', PlotService) +veUtils.service('PlotService', PlotService); diff --git a/src/ve-extensions/present-plots/config.json b/src/ve-extensions/present-plots/config.json index cf3aff4a7..081bf39d3 100644 --- a/src/ve-extensions/present-plots/config.json +++ b/src/ve-extensions/present-plots/config.json @@ -1,8 +1,8 @@ { - "presentations": [ - { - "name": "C3/D3 Plots Extension", - "path": "present-plots" - } - ] -} \ No newline at end of file + "presentations": [ + { + "name": "C3/D3 Plots Extension", + "path": "present-plots" + } + ] +} diff --git a/src/ve-extensions/present-plots/presentations/components/index.ts b/src/ve-extensions/present-plots/presentations/components/index.ts index 354dd2402..4d62d5b3b 100644 --- a/src/ve-extensions/present-plots/presentations/components/index.ts +++ b/src/ve-extensions/present-plots/presentations/components/index.ts @@ -1,7 +1,7 @@ -import './mmsC3Plot.directive' -import './mmsD3GroupedHorizontalBarPlot.directive' -import './mmsD3LineGraph.directive' -import './mmsD3NormalizedStackedBarPlot.directive' -import './mmsD3ObservationProfileChartIo.directive' -import './mmsD3ParallelAxisPlot.directive' -import './mmsD3RadarPlot.directive' +import './mmsC3Plot.directive'; +import './mmsD3GroupedHorizontalBarPlot.directive'; +import './mmsD3LineGraph.directive'; +import './mmsD3NormalizedStackedBarPlot.directive'; +import './mmsD3ObservationProfileChartIo.directive'; +import './mmsD3ParallelAxisPlot.directive'; +import './mmsD3RadarPlot.directive'; diff --git a/src/ve-extensions/present-plots/presentations/components/mmsC3Plot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsC3Plot.directive.ts index e7453df3c..e8b8fbc55 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsC3Plot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsC3Plot.directive.ts @@ -1,21 +1,21 @@ -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -veComponents.directive('mmsC3Plot', ['PlotService', '$window', mmsC3Plot]) +veComponents.directive('mmsC3Plot', ['PlotService', '$window', mmsC3Plot]); function mmsC3Plot(PlotService, $window, _) { const mmsChartLink = function (scope, element, attrs, mmsViewCtrl) { - const c3 = $window.c3 - const d3 = $window.d3 - const divchart = d3.select(element[0]).append('div') + const c3 = $window.c3; + const d3 = $window.d3; + const divchart = d3.select(element[0]).append('div'); - let projectId - let refId - let commitId + let projectId; + let refId; + let commitId; if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin() - projectId = viewVersion.projectId - refId = viewVersion.refId - commitId = viewVersion.commitId + const viewVersion = mmsViewCtrl.getElementOrigin(); + projectId = viewVersion.projectId; + refId = viewVersion.refId; + commitId = viewVersion.commitId; } /** @@ -26,66 +26,66 @@ function mmsC3Plot(PlotService, $window, _) { function simplifyFunctions(object) { _.forOwn(object, function (value, key, ob) { if (_.isPlainObject(value)) { - simplifyFunctions(value) + simplifyFunctions(value); } else { - ob[key] = eval('(' + value + ')') + ob[key] = eval('(' + value + ')'); } - }) + }); } function vf_pplot(c3json, c3jfunc) { if (c3jfunc && _.isPlainObject(c3jfunc)) { - simplifyFunctions(c3jfunc) - _.merge(c3json, c3jfunc) + simplifyFunctions(c3jfunc); + _.merge(c3json, c3jfunc); } - c3.generate(c3json) + c3.generate(c3json); } scope.render = function () { PlotService.readValues(scope.plot, projectId, refId, commitId).then(function (value) { - scope.valuesO = value.tablebody.valuesO //value objects used in watch - let c3options + scope.valuesO = value.tablebody.valuesO; //value objects used in watch + let c3options; if (value.tablebody.c3_data.length === 0) { //no data - return + return; } if (scope.plot.config.options === undefined || scope.plot.config.options.length === 0) { if (value.isHeader) c3options = { data: { x: 'x', type: 'line' }, axis: { x: { type: 'category', tick: { centered: true } } }, - } - else c3options = { data: {} } - } else c3options = scope.plot.config.options + }; + else c3options = { data: {} }; + } else c3options = scope.plot.config.options; if ( value.tablebody.c3_data.length === scope.plot.table.body.length && c3options.data.xs === undefined && value.isHeader ) { - value.tablebody.c3_data.unshift(['x'].concat(value.tableheader)) + value.tablebody.c3_data.unshift(['x'].concat(value.tableheader)); } - c3options.data.columns = value.tablebody.c3_data + c3options.data.columns = value.tablebody.c3_data; - let c3jfunc + let c3jfunc; if (scope.plot.config.functions) { - c3jfunc = scope.plot.config.functions + c3jfunc = scope.plot.config.functions; } - divchart.selectAll('*').remove() - divchart.attr('id', 'c3chart' + scope.$id) - c3options.bindto = '#c3chart' + scope.$id + divchart.selectAll('*').remove(); + divchart.attr('id', 'c3chart' + scope.$id); + c3options.bindto = '#c3chart' + scope.$id; - vf_pplot(c3options, c3jfunc) - }) - } //end of render + vf_pplot(c3options, c3jfunc); + }); + }; //end of render scope.$watch( 'valuesO', function (newVals, oldVals) { - return scope.render() + return scope.render(); }, true - ) - } //end of link + ); + }; //end of link return { restrict: 'EA', @@ -94,5 +94,5 @@ function mmsC3Plot(PlotService, $window, _) { plot: '<', }, link: mmsChartLink, - } //return + }; //return } diff --git a/src/ve-extensions/present-plots/presentations/components/mmsD3GroupedHorizontalBarPlot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsD3GroupedHorizontalBarPlot.directive.ts index 745c792e3..58c3b2163 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsD3GroupedHorizontalBarPlot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsD3GroupedHorizontalBarPlot.directive.ts @@ -1,62 +1,62 @@ -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; //d3js grouped horizontal bar chart is created by referencing //http://bl.ocks.org/erikvullings/51cc5332439939f1f292 -veComponents.directive('mmsD3GroupedHorizontalBarPlot', ['PlotService', '$window', mmsD3GroupedHorizontalBarPlot]) +veComponents.directive('mmsD3GroupedHorizontalBarPlot', ['PlotService', '$window', mmsD3GroupedHorizontalBarPlot]); function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { const mmsChartLink = function (scope, element, attrs, mmsViewCtrl) { - const d3 = $window.d3 - const divchart = d3.select(element[0]).append('div') + const d3 = $window.d3; + const divchart = d3.select(element[0]).append('div'); const defaultPlotConfig = { width: 960, marginTop: 20, marginRight: 40, marginBottom: 30, marginLeft: 40, - } - const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig) - let achartdata + }; + const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig); + let achartdata; element.click(function (e) { //stop Propogating event to parent(transclude-doc) element. - e.stopPropagation() - }) + e.stopPropagation(); + }); - const d3colorR = d3.scaleOrdinal(d3.schemeCategory10).range() + const d3colorR = d3.scaleOrdinal(d3.schemeCategory10).range(); function getColor(data, i) { - return data.colors !== undefined ? d3colorR[data.colors[i]] : d3colorR[i] + return data.colors !== undefined ? d3colorR[data.colors[i]] : d3colorR[i]; } - let projectId - let refId - let commitId + let projectId; + let refId; + let commitId; if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin() - projectId = viewVersion.projectId - refId = viewVersion.refId - commitId = viewVersion.commitId + const viewVersion = mmsViewCtrl.getElementOrigin(); + projectId = viewVersion.projectId; + refId = viewVersion.refId; + commitId = viewVersion.commitId; } const opacitydefault = 1, //0.7, opacityselected = 1.0, - opacitynotselected = 0.3 + opacitynotselected = 0.3; function mouseout() { - d3.selectAll('.ghbbar').transition(200).style('fill-opacity', opacitydefault) + d3.selectAll('.ghbbar').transition(200).style('fill-opacity', opacitydefault); - d3.selectAll('.legendRect').transition(200).style('fill-opacity', opacitydefault) + d3.selectAll('.legendRect').transition(200).style('fill-opacity', opacitydefault); - d3.selectAll('.legentFilter').transition(200).style('opacity', opacitydefault) + d3.selectAll('.legentFilter').transition(200).style('opacity', opacitydefault); } //end of function mouseout function mouseover(mouseoverClassId) { - d3.selectAll('.ghbbar').transition(200).style('fill-opacity', opacitynotselected) + d3.selectAll('.ghbbar').transition(200).style('fill-opacity', opacitynotselected); - d3.selectAll('.legendRect').transition(200).style('fill-opacity', opacitynotselected) + d3.selectAll('.legendRect').transition(200).style('fill-opacity', opacitynotselected); - d3.selectAll('.legentFilter').transition(200).style('opacity', opacitynotselected) + d3.selectAll('.legentFilter').transition(200).style('opacity', opacitynotselected); - d3.selectAll(mouseoverClassId).transition(200).style('fill-opacity', opacityselected) + d3.selectAll(mouseoverClassId).transition(200).style('fill-opacity', opacityselected); - d3.selectAll(mouseoverClassId).transition(200).style('opacity', opacityselected) + d3.selectAll(mouseoverClassId).transition(200).style('opacity', opacityselected); } //end of function mouseover function createFilters(data) { @@ -64,28 +64,28 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { const graphFilter = divchart .append('div') .attr('class', 'graphFilter ' + data.id) - .style('margin-left', plotConfig.marginLeft + 'px') + .style('margin-left', plotConfig.marginLeft + 'px'); const filterLegendsDiv = graphFilter .append('div') .append('label') .style('border', '1px solid #ddd') - .text('Filter by Legends') + .text('Filter by Legends'); filterLegendsDiv .selectAll('div') .data(data.legends) .enter() .append('div') .attr('class', function (d, i) { - return 'legentFilter ' + data.id + ' ' + PlotService.toValidId(d) + return 'legentFilter ' + data.id + ' ' + PlotService.toValidId(d); }) .attr('style', function (d, i) { - return 'opacity: ' + opacitydefault + ';background-color:' + getColor(data, i) + ';' + return 'opacity: ' + opacitydefault + ';background-color:' + getColor(data, i) + ';'; }) .on('mouseover', (d, i) => { - mouseover('.' + data.id + '.' + PlotService.toValidId(d)) + mouseover('.' + data.id + '.' + PlotService.toValidId(d)); }) .on('mouseout', (d, i) => { - mouseout() + mouseout(); }) .append('label') .each((d, i) => { @@ -94,43 +94,43 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { .append('input') .attr('type', 'checkbox') .attr('checked', function (d, i) { - if (data.legendsFilter[PlotService.toValidId(d)] === true) return true - else return null + if (data.legendsFilter[PlotService.toValidId(d)] === true) return true; + else return null; }) .attr('style', function (d, i) { - const color = getColor(data, i) - return 'color: ' + color + ';background-color:' + color + ';' + const color = getColor(data, i); + return 'color: ' + color + ';background-color:' + color + ';'; }) .on('click', (d) => { // filter by legends - data.legendsFilter[PlotService.toValidId(d)] = this.checked - createGroupedHorizontalBarChart(achartdata) - createFilters(achartdata) - }) + data.legendsFilter[PlotService.toValidId(d)] = this.checked; + createGroupedHorizontalBarChart(achartdata); + createFilters(achartdata); + }); d3.select(this) .append('span') .text((d) => { - return d - }) - }) + return d; + }); + }); const filterColoumnsDiv = graphFilter .append('div') .append('label') .style('border', '1px solid #ddd') - .text('Filter by Columns') + .text('Filter by Columns'); filterColoumnsDiv .selectAll('div') .data(data.labels) .enter() .append('div') .attr('class', function (d, i) { - return 'columnfilter ' + data.id + ' ' + PlotService.toValidId(d) + return 'columnfilter ' + data.id + ' ' + PlotService.toValidId(d); }) .on('mouseover', function (d, i) { - mouseover('.' + data.id + '.' + PlotService.toValidId(d)) + mouseover('.' + data.id + '.' + PlotService.toValidId(d)); }) .on('mouseout', function (d, i) { - mouseout() + mouseout(); }) .append('label') .each((d, i) => { @@ -139,54 +139,54 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { .append('input') .attr('type', 'checkbox') .attr('checked', function (d, i) { - if (data.labelsFilter[PlotService.toValidId(d)] === true) return true - else return null + if (data.labelsFilter[PlotService.toValidId(d)] === true) return true; + else return null; }) .on('click', (d) => { //filter by columns(labels) - data.labelsFilter[PlotService.toValidId(d)] = this.checked - createGroupedHorizontalBarChart(achartdata) //2nd argument is not used - createFilters(achartdata) - }) + data.labelsFilter[PlotService.toValidId(d)] = this.checked; + createGroupedHorizontalBarChart(achartdata); //2nd argument is not used + createFilters(achartdata); + }); d3.select(this) .append('span') .text((d) => { - return d - }) - }) + return d; + }); + }); } //end of function createFilter function createGroupedHorizontalBarChart(data) { - divchart.selectAll('*').remove() - divchart.attr('class', achartdata.id).attr('style', 'border:1px solid #ddd') + divchart.selectAll('*').remove(); + divchart.attr('class', achartdata.id).attr('style', 'border:1px solid #ddd'); - const svg = divchart.append('svg:svg').attr('class', 'ghbchart ' + data.id) + const svg = divchart.append('svg:svg').attr('class', 'ghbchart ' + data.id); - const filteredDataValues: any[] = [] - const filteredDataSysmlids: any[] = [] - const filteredDataColors: any[] = [] - const filteredDataLegends: any[] = [] //table row headers - const filteredDataLabels: any[] = [] //table column headers - const datalegendsfilter: any[] = data.legendsFilter - const datalabelsfilter: any[] = data.labelsFilter - let counter = -1 + const filteredDataValues: any[] = []; + const filteredDataSysmlids: any[] = []; + const filteredDataColors: any[] = []; + const filteredDataLegends: any[] = []; //table row headers + const filteredDataLabels: any[] = []; //table column headers + const datalegendsfilter: any[] = data.legendsFilter; + const datalabelsfilter: any[] = data.labelsFilter; + let counter = -1; for (let i = 0; i < data.labels.length; i++) { if (datalabelsfilter[PlotService.toValidId(data.labels[i])]) { - filteredDataLabels.push(data.labels[i]) + filteredDataLabels.push(data.labels[i]); for (let j = 0; j < data.values.length; j++) { //data.values.length == data.legends.length - counter++ + counter++; if (datalegendsfilter[PlotService.toValidId(data.legends[j])]) { - filteredDataValues.push(Number(data.values[j][i])) - filteredDataSysmlids.push(data.valueIds[j][i]) - filteredDataColors.push(getColor(data, counter % data.legends.length)) - filteredDataLegends.push(PlotService.toValidId(data.legends[j])) + filteredDataValues.push(Number(data.values[j][i])); + filteredDataSysmlids.push(data.valueIds[j][i]); + filteredDataColors.push(getColor(data, counter % data.legends.length)); + filteredDataLegends.push(PlotService.toValidId(data.legends[j])); } } } } - const filteredLegendsLength = filteredDataLegends.length / filteredDataLabels.length + const filteredLegendsLength = filteredDataLegends.length / filteredDataLabels.length; const chartWidth = plotConfig.width - 260, barHeight = 20, @@ -194,25 +194,25 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { gapBetweenGroups = 10, spaceForLabels = plotConfig.marginLeft, spaceForLegend = 200, - marginbottom = 50 - const chartHeight = barHeight * filteredDataValues.length + gapBetweenGroups * filteredDataLabels.length + marginbottom = 50; + const chartHeight = barHeight * filteredDataValues.length + gapBetweenGroups * filteredDataLabels.length; const x = d3 .scaleLinear() //d3.scale.linear() .domain([0, d3.max(filteredDataValues)]) - .range([0, chartWidth]) + .range([0, chartWidth]); const y = d3 .scaleLinear() //d3.scale.linear() - .range([chartHeight + gapBetweenGroups, 0]) + .range([chartHeight + gapBetweenGroups, 0]); const yAxis = d3 .axisLeft(y) //d3.svg.axis() .tickFormat('') - .tickSize(0) + .tickSize(0); // Specify the chart area and dimensions - const chart = svg.attr('width', plotConfig.width).attr('height', chartHeight + marginbottom) + const chart = svg.attr('width', plotConfig.width).attr('height', chartHeight + marginbottom); // Create bars const bar = chart @@ -227,16 +227,16 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { ',' + (i * barHeight + gapBetweenGroups * (0.5 + Math.floor(i / filteredLegendsLength))) + ')' - ) - }) - const numRows = filteredDataLegends.length / filteredDataLabels.length + ); + }); + const numRows = filteredDataLegends.length / filteredDataLabels.length; // Create rectangles of the correct width bar.append('rect') .attr('id', function (d, i) { - return filteredDataSysmlids[i] + return filteredDataSysmlids[i]; }) .attr('fill', function (d, i) { - return filteredDataColors[i] + return filteredDataColors[i]; }) .style('fill-opacity', opacitydefault) .attr('class', function (d, i) { @@ -247,32 +247,32 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { filteredDataLegends[i] + ' ' + PlotService.toValidId(filteredDataLabels[Math.floor(i / numRows)]) - ) + ); }) .attr('width', x) .attr('height', barHeight - 1) .on('click', function (d, i) { - if (mmsViewCtrl) mmsViewCtrl.transcludeClicked(this.id) + if (mmsViewCtrl) mmsViewCtrl.transcludeClicked(this.id); }) .on('mouseover', function (d, i) { - mouseover('.' + data.id + '.' + filteredDataLegends[i]) + mouseover('.' + data.id + '.' + filteredDataLegends[i]); }) .on('mouseout', function (d, i) { - mouseout() - }) + mouseout(); + }); // Add text label in bar bar.append('text') .attr('class', function (d, i) { - return 'ghbbar ' + data.id + ' ' + filteredDataLegends[i] + return 'ghbbar ' + data.id + ' ' + filteredDataLegends[i]; }) .attr('x', function (d) { - return x(d) - 3 + return x(d) - 3; }) .attr('y', barHeight / 2) .attr('dy', '.35em') .text(function (d) { - return d - }) + return d; + }); //left side label bar.each(function (d, i) { @@ -281,57 +281,57 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { .append('text') .attr('class', 'label') .attr('x', function (d) { - return -10 + return -10; }) .attr('y', groupHeight / 2) .attr('dy', '.35em') - .text(filteredDataLabels[Math.floor(i / filteredLegendsLength)]) + .text(filteredDataLabels[Math.floor(i / filteredLegendsLength)]); } - }) + }); chart .append('g') .attr('class', 'y axis') .attr('id', 'ghbaxis') .attr('transform', 'translate(' + spaceForLabels + ', ' + -gapBetweenGroups / 2 + ')') - .call(yAxis) + .call(yAxis); // Draw legend const legendRectSize = 18, - legendSpacing = 4 - let mouseoverId + legendSpacing = 4; + let mouseoverId; const legend = chart .selectAll('.legend') .data(data.legends) .enter() .append('g') .attr('transform', (d, i) => { - const height = legendRectSize + legendSpacing - const offset = -gapBetweenGroups / 2 - const horz = spaceForLabels + chartWidth + 60 + legendRectSize - const vert = i * height - offset - return 'translate(' + horz + ',' + vert + ')' + const height = legendRectSize + legendSpacing; + const offset = -gapBetweenGroups / 2; + const horz = spaceForLabels + chartWidth + 60 + legendRectSize; + const vert = i * height - offset; + return 'translate(' + horz + ',' + vert + ')'; }) .on('mouseover', function (d, i) { - mouseover('.' + data.id + '.' + PlotService.toValidId(d)) + mouseover('.' + data.id + '.' + PlotService.toValidId(d)); }) .on('mouseout', function (d, i) { - mouseout() - }) + mouseout(); + }); legend .append('rect') .attr('class', function (d, i) { - return 'legendRect ' + data.id + ' ' + PlotService.toValidId(d) + return 'legendRect ' + data.id + ' ' + PlotService.toValidId(d); }) .attr('width', legendRectSize) .attr('height', legendRectSize) .style('fill-opacity', opacitydefault) .style('fill', (d, i) => { - return getColor(data, i) /*return color(i);*/ + return getColor(data, i); /*return color(i);*/ }) .style('stroke', (d, i) => { - return getColor(data, i) /*return color(i);*/ - }) + return getColor(data, i); /*return color(i);*/ + }); legend .append('text') @@ -339,46 +339,46 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { .attr('x', legendRectSize + legendSpacing) .attr('y', legendRectSize - legendSpacing) .text((d, i) => { - return d - }) + return d; + }); } scope.render = function () { PlotService.readValues(scope.plot, projectId, refId, commitId).then(function (value) { - const tablebody = value.tablebody - const tableheader = value.tableheader + const tablebody = value.tablebody; + const tableheader = value.tableheader; //scope.isHeader = value.isHeader; - scope.valuesO = value.tablebody.valuesO //value objects used in watch + scope.valuesO = value.tablebody.valuesO; //value objects used in watch if (tablebody.c3_data.length === 0) { //no data - return + return; } - let udcolors + let udcolors; if (scope.plot.config.colors !== undefined) { - udcolors = scope.plot.config.colors + udcolors = scope.plot.config.colors; } - const rowvalues: number[] = [] - const cellIds: number[] = [] //0, 1, 2, 3 - const legends: any[] = [] - const legendsFilter: boolean[] = [] - let rowvalue: number[] - let cellId: number[] - let cid = 0 + const rowvalues: number[] = []; + const cellIds: number[] = []; //0, 1, 2, 3 + const legends: any[] = []; + const legendsFilter: boolean[] = []; + let rowvalue: number[]; + let cellId: number[]; + let cid = 0; tablebody.c3_data.forEach(function (row) { - legends.push(row[0]) - legendsFilter[row[0]] = true - rowvalue = [] //reset - cellId = [] //reset + legends.push(row[0]); + legendsFilter[row[0]] = true; + rowvalue = []; //reset + cellId = []; //reset for (let i = 1; i < row.length; i++) { - rowvalue.push(row[i]) - cellId.push(cid++) + rowvalue.push(row[i]); + cellId.push(cid++); } - cellIds.push(...cellId) - rowvalues.push(...rowvalue) - }) - const labelsFilter: { [key: string]: boolean } = {} + cellIds.push(...cellId); + rowvalues.push(...rowvalue); + }); + const labelsFilter: { [key: string]: boolean } = {}; tableheader.forEach(function (item) { - labelsFilter[item] = true - }) + labelsFilter[item] = true; + }); achartdata = { id: '_' + scope.$id, labels: tableheader, @@ -388,24 +388,24 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { valueIds: cellIds, legendsFilter: legendsFilter, labelsFilter: labelsFilter, - } - createGroupedHorizontalBarChart(achartdata) - createFilters(achartdata) - }) - } //end of render + }; + createGroupedHorizontalBarChart(achartdata); + createFilters(achartdata); + }); + }; //end of render scope.$watch( 'valuesO', function (newValue, oldValue) { - return scope.render() + return scope.render(); }, true - ) + ); //rect bar is clicked or table cell (Except rowHeaders) is clicked // eventSvc.$on('element.selected', function(data) { // d3.selectAll("rect").transition(200).style("fill-opacity", opacitynotselected); // }); - } //end of link + }; //end of link return { restrict: 'EA', @@ -414,5 +414,5 @@ function mmsD3GroupedHorizontalBarPlot(PlotService, $window) { plot: '<', }, link: mmsChartLink, - } //return + }; //return } diff --git a/src/ve-extensions/present-plots/presentations/components/mmsD3NormalizedStackedBarPlot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsD3NormalizedStackedBarPlot.directive.ts index 7b5f1bddd..6cd30dbdb 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsD3NormalizedStackedBarPlot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsD3NormalizedStackedBarPlot.directive.ts @@ -1,15 +1,15 @@ -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -veComponents.directive('mmsD3NormalizedStackedBarPlot', ['PlotService', '$window', mmsD3NormalizedStackedBarPlot]) +veComponents.directive('mmsD3NormalizedStackedBarPlot', ['PlotService', '$window', mmsD3NormalizedStackedBarPlot]); /** /* reference https://bl.ocks.org/mbostock/3886394 */ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { const mmsChartLink = function (scope, element, attrs, mmsViewCtrl) { - const d3 = $window.d3 + const d3 = $window.d3; - const divchart = d3.select(element[0]).append('div') + const divchart = d3.select(element[0]).append('div'); //default const defaultPlotConfig = { width: 960 /*parseInt(divchart.style("width"))*0.95*/, @@ -18,25 +18,25 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { marginRight: 60, marginBottom: 30, marginLeft: 40, - } - const plotId = 'd3nbplot' + scope.$id + }; + const plotId = 'd3nbplot' + scope.$id; - let projectId, refId, commitId + let projectId, refId, commitId; if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin() - projectId = viewVersion.projectId - refId = viewVersion.refId - commitId = viewVersion.commitId + const viewVersion = mmsViewCtrl.getElementOrigin(); + projectId = viewVersion.projectId; + refId = viewVersion.refId; + commitId = viewVersion.commitId; } function vf_pplot() { - divchart.selectAll('*').remove() - divchart.attr('id', plotId) - const svg = divchart.append('svg:svg') + divchart.selectAll('*').remove(); + divchart.attr('id', plotId); + const svg = divchart.append('svg:svg'); - const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig) - svg.attr('width', plotConfig.width) - svg.attr('height', plotConfig.height) + const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig); + svg.attr('width', plotConfig.width); + svg.attr('height', plotConfig.height); const margin = { top: plotConfig.marginTop, right: plotConfig.marginRight, @@ -45,28 +45,28 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { }, width = +svg.attr('width') - margin.left - margin.right, height = +svg.attr('height') - margin.top - margin.bottom, - g = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') + g = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); - const x = d3.scaleBand().rangeRound([0, width]).padding(0.1).align(0.1) + const x = d3.scaleBand().rangeRound([0, width]).padding(0.1).align(0.1); - const y = d3.scaleLinear().rangeRound([height, 0]) + const y = d3.scaleLinear().rangeRound([height, 0]); - const z = d3.scaleOrdinal(d3.schemeCategory10) + const z = d3.scaleOrdinal(d3.schemeCategory10); - const stack = d3.stack().offset(d3.stackOffsetExpand) + const stack = d3.stack().offset(d3.stackOffsetExpand); - let data = scope.tablebody.c3_data - data = total(data) + let data = scope.tablebody.c3_data; + data = total(data); data.sort(function (a, b) { - return b[scope.tablecolumnheader[0]] / b.total - a[scope.tablecolumnheader[0]] / a.total - }) + return b[scope.tablecolumnheader[0]] / b.total - a[scope.tablecolumnheader[0]] / a.total; + }); x.domain( data.map(function (d) { - return d.rowheader + return d.rowheader; }) - ) - z.domain(scope.tablecolumnheader) + ); + z.domain(scope.tablecolumnheader); const serie = g .selectAll('.serie') @@ -75,43 +75,43 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { .append('g') .attr('class', 'serie') .attr('fill', function (d) { - return z(d.key) - }) + return z(d.key); + }); serie .selectAll('rect') .data(function (d) { - return d + return d; }) .enter() .append('rect') .attr('x', function (d) { - return x(d.data.rowheader) + return x(d.data.rowheader); }) .attr('y', function (d) { - return y(d[1]) + return y(d[1]); }) .attr('height', function (d) { - return y(d[0]) - y(d[1]) + return y(d[0]) - y(d[1]); }) - .attr('width', x.bandwidth()) + .attr('width', x.bandwidth()); g.append('g') .attr('class', 'axis axis--x') .attr('transform', 'translate(0,' + height + ')') - .call(d3.axisBottom(x)) + .call(d3.axisBottom(x)); - g.append('g').attr('class', 'axis axis--y').call(d3.axisLeft(y).ticks(10, '%')) + g.append('g').attr('class', 'axis axis--y').call(d3.axisLeft(y).ticks(10, '%')); const legend = serie .append('g') .attr('class', 'legend') .attr('transform', function (d) { - d = d[d.length - 1] - return 'translate(' + (x(d.data.rowheader) + x.bandwidth()) + ',' + (y(d[0]) + y(d[1])) / 2 + ')' - }) + d = d[d.length - 1]; + return 'translate(' + (x(d.data.rowheader) + x.bandwidth()) + ',' + (y(d[0]) + y(d[1])) / 2 + ')'; + }); - legend.append('line').attr('x1', -6).attr('x2', 6).attr('stroke', '#000') + legend.append('line').attr('x1', -6).attr('x2', 6).attr('stroke', '#000'); legend .append('text') @@ -120,42 +120,42 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { .attr('fill', '#000') .style('font', '10px sans-serif') .text(function (d) { - return d.key - }) + return d.key; + }); } //add total in original row array. function total(all) { all.forEach(function (a) { - a.total = 0 + a.total = 0; for (let i = 0; i < scope.tablecolumnheader.length; i++) { - a.total += Number(a[scope.tablecolumnheader[i]]) + a.total += Number(a[scope.tablecolumnheader[i]]); } - }) - return all + }); + return all; } scope.render = function () { PlotService.readValues2(scope.plot, projectId, refId, commitId).then(function (value) { - scope.tablebody = value.tablebody - scope.tablecolumnheader = value.tableheader - scope.valuesO = value.tablebody.valuesO //value objects used in watch + scope.tablebody = value.tablebody; + scope.tablecolumnheader = value.tableheader; + scope.valuesO = value.tablebody.valuesO; //value objects used in watch if (scope.tablebody.c3_data.length === 0) { //no data - return + return; } - vf_pplot() - }) //end of PlotService - } //end of render + vf_pplot(); + }); //end of PlotService + }; //end of render scope.$watch( 'valuesO', function (newVals, oldVals) { - return scope.render() + return scope.render(); }, true - ) - } //end of link + ); + }; //end of link return { restrict: 'EA', @@ -164,5 +164,5 @@ function mmsD3NormalizedStackedBarPlot(PlotService, $window) { plot: '<', }, link: mmsChartLink, - } //return + }; //return } diff --git a/src/ve-extensions/present-plots/presentations/components/mmsD3ParallelAxisPlot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsD3ParallelAxisPlot.directive.ts index 718edfa69..f752b3546 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsD3ParallelAxisPlot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsD3ParallelAxisPlot.directive.ts @@ -1,11 +1,11 @@ -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -veComponents.directive('mmsD3ParallelAxisPlot', ['PlotService', '$window', mmsD3ParallelAxisPlot]) +veComponents.directive('mmsD3ParallelAxisPlot', ['PlotService', '$window', mmsD3ParallelAxisPlot]); function mmsD3ParallelAxisPlot(PlotService, $window) { const mmsChartLink = function (scope, element, attrs, mmsViewCtrl) { - scope.rowHeaders = [] //not null when render is called 1st time. - const d3 = $window.d3 - const divchart = d3.select(element[0]).append('div') + scope.rowHeaders = []; //not null when render is called 1st time. + const d3 = $window.d3; + const divchart = d3.select(element[0]).append('div'); const defaultPlotConfig = { width: 900, @@ -13,52 +13,52 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { marginRight: 0, marginBottom: 25, marginLeft: 60, - } + }; - let projectId - let refId - let commitId + let projectId; + let refId; + let commitId; if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin() - projectId = viewVersion.projectId - refId = viewVersion.refId - commitId = viewVersion.commitId + const viewVersion = mmsViewCtrl.getElementOrigin(); + projectId = viewVersion.projectId; + refId = viewVersion.refId; + commitId = viewVersion.commitId; } function vf_pplot(_out) { - const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig) + const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig); - const outputs = _out - const width = plotConfig.width - const height = plotConfig.width * 0.37 - const m = [plotConfig.marginTop, plotConfig.marginRight, plotConfig.marginBottom, plotConfig.marginLeft] //top, right, bottom, left + const outputs = _out; + const width = plotConfig.width; + const height = plotConfig.width * 0.37; + const m = [plotConfig.marginTop, plotConfig.marginRight, plotConfig.marginBottom, plotConfig.marginLeft]; //top, right, bottom, left - let maxSize = 0 - let size = 0 + let maxSize = 0; + let size = 0; //redefine top and right margin based on TB string length - maxSize = 0 - size = 0 + maxSize = 0; + size = 0; for (let i = 0; i < outputs.variables.length; i++) { - size = outputs.variables[i].length //length of the string - if (maxSize < size) maxSize = size + size = outputs.variables[i].length; //length of the string + if (maxSize < size) maxSize = size; } - m[0] = maxSize * 4.5 * 0.707 + 50 //to make label - m[1] = maxSize * 4.5 * 0.707 + 10 + m[0] = maxSize * 4.5 * 0.707 + 50; //to make label + m[1] = maxSize * 4.5 * 0.707 + 10; //define width and height const w = width - m[1] - m[3], - h = height - m[0] - m[2] + h = height - m[0] - m[2]; - const colorscale = d3.scaleOrdinal(d3.schemeCategory10) + const colorscale = d3.scaleOrdinal(d3.schemeCategory10); const x = d3.scalePoint(d3.schemeCategory10).domain(outputs.variables).range([0, w]), - y = {} + y = {}; let line = d3.line(), - foreground + foreground; - divchart.selectAll('*').remove() + divchart.selectAll('*').remove(); const svg = divchart .append('svg:svg') .attr('class', 'papchart' + scope.$id + ' papchart') @@ -66,73 +66,73 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .attr('width', w + m[1] + m[3]) .attr('height', h + m[0] + m[2]) .append('svg:g') - .attr('transform', 'translate(' + m[3] + ',' + m[0] + ')') + .attr('transform', 'translate(' + m[3] + ',' + m[0] + ')'); //Need to create a temporary object with the data, objectives, and threshold values //to scale the axes properly - const minMax = {} + const minMax = {}; outputs.variables.forEach(function (d, i) { - minMax[d] = {} + minMax[d] = {}; //initialize minTest and maxTest variables - let minTest = outputs.table[0].values[d] - let maxTest = outputs.table[0].values[d] + let minTest = outputs.table[0].values[d]; + let maxTest = outputs.table[0].values[d]; for (let j = 0; j < outputs.table.length; j++) { //test to see if minTest is still the minimum - if (minTest > outputs.table[j].values[d]) minTest = outputs.table[j].values[d] + if (minTest > outputs.table[j].values[d]) minTest = outputs.table[j].values[d]; //tests to see if maxTest is still the maximum - if (maxTest < outputs.table[j].values[d]) maxTest = outputs.table[j].values[d] + if (maxTest < outputs.table[j].values[d]) maxTest = outputs.table[j].values[d]; } - minMax[d].min = minTest - minMax[d].max = maxTest - }) + minMax[d].min = minTest; + minMax[d].max = maxTest; + }); - const range = {} - const minimum = {} - const maximum = {} + const range = {}; + const minimum = {}; + const maximum = {}; - const percentScaling = 0.07 + const percentScaling = 0.07; //make each minMax a bit bigger or smaller to better plot the data set outputs.variables.forEach(function (d, i) { - range[d] = Math.abs(minMax[d].max - minMax[d].min) + range[d] = Math.abs(minMax[d].max - minMax[d].min); - minimum[d] = minMax[d].min - range[d] * percentScaling - maximum[d] = minMax[d].max + range[d] * percentScaling + minimum[d] = minMax[d].min - range[d] * percentScaling; + maximum[d] = minMax[d].max + range[d] * percentScaling; //what if both the min and the max were equal? Give it some "range" about the point if (minMax[d].max == minMax[d].min) { - maximum[d] = minMax[d].max * (percentScaling + 1) - minimum[d] = minMax[d].max * (1 - percentScaling) + maximum[d] = minMax[d].max * (percentScaling + 1); + minimum[d] = minMax[d].max * (1 - percentScaling); } //what if the only value for a variable is zero? Give it some "range" about zero if (minMax[d].max === 0 && minMax[d].min === 0) { - maximum[d] = percentScaling - minimum[d] = -percentScaling + maximum[d] = percentScaling; + minimum[d] = -percentScaling; } - }) + }); //Create a scale and brush for each variables. outputs.variables.forEach((d) => { - y[d] = d3.scaleLinear().domain([minimum[d], maximum[d]]).range([h, 0]) - }) + y[d] = d3.scaleLinear().domain([minimum[d], maximum[d]]).range([h, 0]); + }); const tooltip = svg .append('text') .style('opacity', 0) .style('font-family', 'sans-serif') - .style('font-size', '13px') + .style('font-size', '13px'); - const axisData: any[] = [] - const tickData: any[] = [] + const axisData: any[] = []; + const tickData: any[] = []; outputs.table.forEach(function (d) { - if (d.tickColor === undefined) axisData.push(d) - else tickData.push(d) - }) + if (d.tickColor === undefined) axisData.push(d); + else tickData.push(d); + }); // Add foreground lines. background brush foreground = svg .append('svg:g') @@ -148,33 +148,33 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .attr('y', d3.mouse(this)[1]) .text(d.row) .transition(200) - .style('opacity', 1) + .style('opacity', 1); }) .on('mouseout', function () { //remove the text element added on the mouseover event when the mouseout event is triggered - tooltip.transition(200).style('opacity', 0) + tooltip.transition(200).style('opacity', 0); }) .attr('stroke', function (d, i) { - return colorscale(i) + return colorscale(i); }) .attr('fill', 'none') .style('stroke-width', '1px') .attr('cid', function (d, i) { - return d.cid + return d.cid; }) .attr('config', function (d, i) { - return d.design + return d.design; }) //.attr("title", "TEST") .attr('class', (d, i) => { - const string = 'design ' + d.cid + ' selected' - return string + const string = 'design ' + d.cid + ' selected'; + return string; }) //add title to the path. mouseover shows it in bubble looking .append('svg:title') .text(function (d) { - return d.row - }) + return d.row; + }); // Add a group element for each variables. const g = svg @@ -184,15 +184,15 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .append('svg:g') .attr('class', 'variables') .attr('transform', function (d, i) { - return 'translate(' + x(d) + ')' - }) + return 'translate(' + x(d) + ')'; + }); // Add an axis and title. g.append('svg:g') .attr('class', 'axis') .each(function (d) { //d3.select(this).call(axis.scale(y[d])); - d3.select(this).call(d3.axisLeft(y[d]).ticks(5)) + d3.select(this).call(d3.axisLeft(y[d]).ticks(5)); }) .append('svg:text') .data(outputs.variables) @@ -202,16 +202,16 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .attr('class', 'axislabel') .attr('fill', 'black') .text(function (d) { - return d - }) + return d; + }); - let axisTick + let axisTick; tickData.forEach(function (td) { //Adding axisTick g.select('g.axis') .append('g') .attr('transform', (d) => { - return 'translate(0,' + y[d](td.values[d]) + ')' + return 'translate(0,' + y[d](td.values[d]) + ')'; }) .attr('class', 'objectivetick') .append('line') @@ -227,77 +227,77 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { .attr('y', d3.mouse(this)[1] + y[d](td.values[d])) .text(td.row) .transition(200) - .style('opacity', 1) + .style('opacity', 1); }) .on('mouseout', function (d) { //remove the text element added on the mouseover event when the mouseout event is triggered - tooltip.transition(200).style('opacity', 0) - }) - }) + tooltip.transition(200).style('opacity', 0); + }); + }); // Returns the path for a given data point. function path(d) { - d = d.values + d = d.values; return line( outputs.variables.map((p) => { - return [x(p), y[p](d[p])] + return [x(p), y[p](d[p])]; }) - ) + ); } } //end of vf_pplot() function getTickColor(rowHeaderName) { if (scope.plot.config.ticks !== undefined) { for (let kk = 0; kk < scope.plot.config.ticks.length; kk++) { - if (scope.plot.config.ticks[kk].name === rowHeaderName) return scope.plot.config.ticks[kk].color + if (scope.plot.config.ticks[kk].name === rowHeaderName) return scope.plot.config.ticks[kk].color; } } - return undefined + return undefined; } scope.render = function () { PlotService.readValues(scope.plot, projectId, refId, commitId).then(function (value) { - scope.tablebody = value.tablebody - scope.tableheader = value.tableheader - scope.isHeader = value.isHeader - scope.valuesO = value.tablebody.valuesO //value objects used in watch + scope.tablebody = value.tablebody; + scope.tableheader = value.tableheader; + scope.isHeader = value.isHeader; + scope.valuesO = value.tablebody.valuesO; //value objects used in watch if (scope.tablebody.c3_data.length === 0) { //no data - return + return; } const dataseries: { - row: any - tickColor: any - values: any - }[] = [] - let tickColor + row: any; + tickColor: any; + values: any; + }[] = []; + let tickColor; scope.tablebody.c3_data.forEach(function (row) { - const values: { [key: string]: any } = {} + const values: { [key: string]: any } = {}; for (let i = 1; i < row.length; i++) { - values[scope.tableheader[i - 1]] = row[i] - tickColor = getTickColor(row[0]) + values[scope.tableheader[i - 1]] = row[i]; + tickColor = getTickColor(row[0]); } dataseries.push({ row: row[0], tickColor: tickColor, values: values, - }) - }) + }); + }); const modelData = { variables: scope.tableheader, table: dataseries, //columnHeader and values - } - vf_pplot(modelData) - }) //end of PlotService - } //end of render + }; + vf_pplot(modelData); + }); //end of PlotService + }; //end of render scope.$watch( 'valuesO', function (newVals, oldVals) { - return scope.render() + return scope.render(); }, true - ) - } //end of link + ); + }; //end of link return { restrict: 'EA', @@ -306,5 +306,5 @@ function mmsD3ParallelAxisPlot(PlotService, $window) { plot: '<', }, link: mmsChartLink, - } //return + }; //return } diff --git a/src/ve-extensions/present-plots/presentations/components/mmsD3RadarPlot.directive.ts b/src/ve-extensions/present-plots/presentations/components/mmsD3RadarPlot.directive.ts index 7a861b19c..468b15fa7 100644 --- a/src/ve-extensions/present-plots/presentations/components/mmsD3RadarPlot.directive.ts +++ b/src/ve-extensions/present-plots/presentations/components/mmsD3RadarPlot.directive.ts @@ -1,13 +1,13 @@ -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -veComponents.directive('mmsD3RadarPlot', ['PlotService', '$window', mmsD3RadarPlot]) +veComponents.directive('mmsD3RadarPlot', ['PlotService', '$window', mmsD3RadarPlot]); function mmsD3RadarPlot(PlotService, $window) { const mmsRadarChartLink = function (scope, element, attrs, mmsViewCtrl) { - const d3 = $window.d3 - const colorscale = d3.scaleOrdinal(d3.schemeCategory10) + const d3 = $window.d3; + const colorscale = d3.scaleOrdinal(d3.schemeCategory10); - const scopetableColumnHeadersLabel = [] - const divchart = d3.select(element[0]).append('div') + const scopetableColumnHeadersLabel = []; + const divchart = d3.select(element[0]).append('div'); const defaultPlotConfig = { width: 700 /*parseInt(divchart.style("width"))*0.95*/, @@ -16,67 +16,67 @@ function mmsD3RadarPlot(PlotService, $window) { marginRight: 0, marginBottom: 0, marginLeft: 0, - } + }; - let projectId - let refId - let commitId + let projectId; + let refId; + let commitId; if (mmsViewCtrl) { - const viewVersion = mmsViewCtrl.getElementOrigin() - projectId = viewVersion.projectId - refId = viewVersion.refId - commitId = viewVersion.commitId + const viewVersion = mmsViewCtrl.getElementOrigin(); + projectId = viewVersion.projectId; + refId = viewVersion.refId; + commitId = viewVersion.commitId; } //if ( scope.plot.config.length !== 0){ //scope.plot.config = JSON.parse(scope.plot.config.replace(/'/g, '"')); //{"colors: [5,6,7,8,9]"} //} scope.render = function () { PlotService.readValues(scope.plot, projectId, refId, commitId).then(function (value) { - scope.tablebody = value.tablebody - scope.tableheader = value.tableheader - scope.isHeader = value.isHeader - scope.valuesO = value.tablebody.valuesO //value objects used in watch + scope.tablebody = value.tablebody; + scope.tableheader = value.tableheader; + scope.isHeader = value.isHeader; + scope.valuesO = value.tablebody.valuesO; //value objects used in watch if (scope.tablebody.c3_data.length === 0) { //no data - return + return; } - const rowvalues: { axis: string; value: number }[][] = [] //[][] {{axis: p2, value: 15}, {axis: p3: value: 1}}... + const rowvalues: { axis: string; value: number }[][] = []; //[][] {{axis: p2, value: 15}, {axis: p3: value: 1}}... scope.tablebody.c3_data.forEach(function (row) { - const rowvalue: { axis: string; value: number }[] = [] + const rowvalue: { axis: string; value: number }[] = []; for ( let i = 1; i < row.length; i++ //ignore row header ) - rowvalue.push({ axis: scope.tableheader[i - 1], value: row[i] }) - rowvalues.push(rowvalue) - }) + rowvalue.push({ axis: scope.tableheader[i - 1], value: row[i] }); + rowvalues.push(rowvalue); + }); - divchart.selectAll('*').remove() - divchart.attr('class', 'radar' + scope.$id).attr('style', 'border:1px solid #ddd') + divchart.selectAll('*').remove(); + divchart.attr('class', 'radar' + scope.$id).attr('style', 'border:1px solid #ddd'); - RadarChart.draw('radar' + scope.$id, rowvalues) + RadarChart.draw('radar' + scope.$id, rowvalues); //add legends from tableheader - const legends: any[] = [] + const legends: any[] = []; scope.tablebody.c3_data.forEach(function (item) { - legends.push(item[0]) - }) - initiateLegend(legends, 'radar' + scope.$id) - }) //Plot - } //end of scope.render + legends.push(item[0]); + }); + initiateLegend(legends, 'radar' + scope.$id); + }); //Plot + }; //end of scope.render scope.$watch( 'valuesO', function (newVals, oldVals) { - return scope.render() + return scope.render(); }, true - ) + ); - const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig) + const plotConfig = PlotService.plotConfig(scope.plot.config.options, defaultPlotConfig); - let cfg + let cfg; var RadarChart = { draw: function (id, d) { cfg = { @@ -95,33 +95,33 @@ function mmsD3RadarPlot(PlotService, $window) { ExtraWidthX: 100, ExtraWidthY: 0 /*100 original */, color: colorscale, - } + }; cfg.maxValue = Math.max( cfg.maxValue, d3.max(d, function (i) { return d3.max( i.map(function (o) { - return Number(o.value) + return Number(o.value); }) - ) + ); }) - ) + ); const allAxis = d[0].map(function (i, j) { - return i.axis - }) - const total = allAxis.length - const radius = cfg.factor * Math.min(cfg.w / 2, cfg.h / 2) + return i.axis; + }); + const total = allAxis.length; + const radius = cfg.factor * Math.min(cfg.w / 2, cfg.h / 2); - const svg = divchart.append('svg:svg').attr('class', 'rdchart ' + scope.$id) - svg.attr('width', plotConfig.width) - svg.attr('height', plotConfig.height) + const svg = divchart.append('svg:svg').attr('class', 'rdchart ' + scope.$id); + svg.attr('width', plotConfig.width); + svg.attr('height', plotConfig.height); - const g = svg.append('g').attr('transform', 'translate(' + cfg.TranslateX + ',' + cfg.TranslateY + ')') - let tooltip + const g = svg.append('g').attr('transform', 'translate(' + cfg.TranslateX + ',' + cfg.TranslateY + ')'); + let tooltip; //Text indicating at what % each level is for (let j = 0; j < cfg.levels; j++) { - const levelFactor2 = cfg.factor * radius * ((j + 1) / cfg.levels) + const levelFactor2 = cfg.factor * radius * ((j + 1) / cfg.levels); g.selectAll('.levels') .data([1]) //dummy data .enter() @@ -140,97 +140,97 @@ function mmsD3RadarPlot(PlotService, $window) { ')' ) .attr('fill', '#737373') - .text(d3.format('.3g')(((j + 1) * cfg.maxValue) / cfg.levels)) + .text(d3.format('.3g')(((j + 1) * cfg.maxValue) / cfg.levels)); } function getPosition(i, range, factor, func) { - factor = typeof factor !== 'undefined' ? factor : 1 - return range * (1 - factor * func((i * cfg.radians) / total)) + factor = typeof factor !== 'undefined' ? factor : 1; + return range * (1 - factor * func((i * cfg.radians) / total)); } function getHorizontalPosition(i, range, factor?) { - return getPosition(i, range, factor, Math.sin) + return getPosition(i, range, factor, Math.sin); } function getVerticalPosition(i, range, factor?) { - return getPosition(i, range, factor, Math.cos) + return getPosition(i, range, factor, Math.cos); } // //levels && axises const levelFactors = d3.range(0, cfg.levels).map(function (level) { - return radius * ((level + 1) / cfg.levels) - }) - const levelGroups = g.selectAll('.levels').data(levelFactors) - levelGroups.enter().append('g') - levelGroups.exit().remove() + return radius * ((level + 1) / cfg.levels); + }); + const levelGroups = g.selectAll('.levels').data(levelFactors); + levelGroups.enter().append('g'); + levelGroups.exit().remove(); levelGroups.attr('class', function (d, i) { - return 'level-group level-group-' + i - }) + return 'level-group level-group-' + i; + }); const levelLine = levelGroups.selectAll('.level').data(function (levelFactor) { return d3.range(0, total).map(function () { - return levelFactor - }) - }) - levelLine.enter().append('line') - levelLine.exit().remove() + return levelFactor; + }); + }); + levelLine.enter().append('line'); + levelLine.exit().remove(); levelLine .attr('class', 'level') .attr('x1', function (levelFactor, i) { - return getHorizontalPosition(i, levelFactor) + return getHorizontalPosition(i, levelFactor); }) .attr('y1', function (levelFactor, i) { - return getVerticalPosition(i, levelFactor) + return getVerticalPosition(i, levelFactor); }) .attr('x2', function (levelFactor, i) { - return getHorizontalPosition(i + 1, levelFactor) + return getHorizontalPosition(i + 1, levelFactor); }) .attr('y2', function (levelFactor, i) { - return getVerticalPosition(i + 1, levelFactor) + return getVerticalPosition(i + 1, levelFactor); }) .style('stroke', 'grey') .style('stroke-opacity', '0.75') .style('stroke-width', '0.3px') .attr('transform', function (levelFactor) { - return 'translate(' + (cfg.w / 2 - levelFactor) + ', ' + (cfg.h / 2 - levelFactor) + ')' - }) - let series = 0 - const axis = g.selectAll('.axis').data(allAxis).enter().append('g').attr('class', 'axis') + return 'translate(' + (cfg.w / 2 - levelFactor) + ', ' + (cfg.h / 2 - levelFactor) + ')'; + }); + let series = 0; + const axis = g.selectAll('.axis').data(allAxis).enter().append('g').attr('class', 'axis'); axis.append('line') .attr('x1', cfg.w / 2) .attr('y1', cfg.h / 2) .attr('x2', function (d, i) { - return (cfg.w / 2) * (1 - cfg.factor * Math.sin((i * cfg.radians) / total)) + return (cfg.w / 2) * (1 - cfg.factor * Math.sin((i * cfg.radians) / total)); }) .attr('y2', function (d, i) { - return (cfg.h / 2) * (1 - cfg.factor * Math.cos((i * cfg.radians) / total)) + return (cfg.h / 2) * (1 - cfg.factor * Math.cos((i * cfg.radians) / total)); }) .attr('class', 'line') .style('stroke', 'grey') - .style('stroke-width', '1px') + .style('stroke-width', '1px'); axis.append('text') .attr('class', 'legend') .text(function (d) { - return d + return d; }) .style('font-family', 'sans-serif') .style('font-size', '12px') .attr('text-anchor', 'middle') .attr('dy', '1.5em') .attr('transform', function (d, i) { - return 'translate(0, -8)' + return 'translate(0, -8)'; }) .attr('x', function (d, i) { return ( (cfg.w / 2) * (1 - cfg.factorLegend * Math.sin((i * cfg.radians) / total)) - 60 * Math.sin((i * cfg.radians) / total) - ) + ); }) .attr('y', function (d, i) { return ( (cfg.h / 2) * (1 - Math.cos((i * cfg.radians) / total)) - 20 * Math.cos((i * cfg.radians) / total) - ) - }) + ); + }); - let dataValues: number[][] = [] + let dataValues: number[][] = []; d.forEach(function (y, x) { - dataValues = [] + dataValues = []; g.selectAll('.nodes').data(y, function (j, i) { dataValues.push([ (cfg.w / 2) * @@ -243,13 +243,13 @@ function mmsD3RadarPlot(PlotService, $window) { (Math.max(j.value, 0) / cfg.maxValue) * cfg.factor * Math.cos((i * cfg.radians) / total)), - ]) + ]); // dataValues.push([ // cfg.w/2*(1-(parseFloat(Math.max(j.value, 0))/cfg.maxValue)*cfg.factor*Math.sin(i*cfg.radians/total)), // cfg.h/2*(1-(parseFloat(Math.max(j.value, 0))/cfg.maxValue)*cfg.factor*Math.cos(i*cfg.radians/total)) // ]); - }) - dataValues.push(dataValues[0]) + }); + dataValues.push(dataValues[0]); g.selectAll('.area') .data([dataValues]) .enter() @@ -258,25 +258,25 @@ function mmsD3RadarPlot(PlotService, $window) { .style('stroke-width', '2px') .style('stroke', cfg.color(series)) .attr('points', function (d) { - let str = '' + let str = ''; for (let pti = 0; pti < d.length; pti++) { - str = str + d[pti][0] + ',' + d[pti][1] + ' ' + str = str + d[pti][0] + ',' + d[pti][1] + ' '; } - return str + return str; }) .style('fill', function (j, i) { - return cfg.color(series) + return cfg.color(series); }) .style('fill-opacity', 0.1) .on('mouseover', function (d, i) { - d3.select(this).transition(200).style('fill-opacity', 0.7) + d3.select(this).transition(200).style('fill-opacity', 0.7); }) .on('mouseout', function (d, i) { - d3.select(this).transition(200).style('fill-opacity', 0.1) - }) - series++ - }) - series = 0 + d3.select(this).transition(200).style('fill-opacity', 0.1); + }); + series++; + }); + series = 0; d.forEach(function (y, x) { g.selectAll('.nodes') .data(y) @@ -285,7 +285,7 @@ function mmsD3RadarPlot(PlotService, $window) { .attr('class', 'radar-chart-serie' + series + ' ' + id) .attr('r', cfg.radius) .attr('alt', function (j) { - return Math.max(j.value, 0) + return Math.max(j.value, 0); }) .attr('cx', function (j, i) { dataValues.push([ @@ -299,7 +299,7 @@ function mmsD3RadarPlot(PlotService, $window) { (Math.max(j.value, 0) / cfg.maxValue) * cfg.factor * Math.cos((i * cfg.radians) / total)), - ]) + ]); // dataValues.push([ // cfg.w/2*(1-(parseFloat(Math.max(j.value, 0))/cfg.maxValue)*cfg.factor*Math.sin(i*cfg.radians/total)), // cfg.h/2*(1-(parseFloat(Math.max(j.value, 0))/cfg.maxValue)*cfg.factor*Math.cos(i*cfg.radians/total)) @@ -310,7 +310,7 @@ function mmsD3RadarPlot(PlotService, $window) { (Math.max(j.value, 0) / cfg.maxValue) * cfg.factor * Math.sin((i * cfg.radians) / total)) - ) + ); }) .attr('cy', function (j, i) { return ( @@ -319,41 +319,41 @@ function mmsD3RadarPlot(PlotService, $window) { (Math.max(j.value, 0) / cfg.maxValue) * cfg.factor * Math.cos((i * cfg.radians) / total)) - ) + ); }) .attr('data-id', function (j) { - return j.axis + return j.axis; }) .style('fill', cfg.color(series)) .style('fill-opacity', 0.9) .on('mouseover', function (d) { - const newX = parseFloat(d3.select(this).attr('cx')) - 10 - const newY = parseFloat(d3.select(this).attr('cy')) - 5 + const newX = parseFloat(d3.select(this).attr('cx')) - 10; + const newY = parseFloat(d3.select(this).attr('cy')) - 5; tooltip .attr('x', newX) .attr('y', newY) .text(d.value.toString()) .transition(200) - .style('opacity', 1) + .style('opacity', 1); }) .on('mouseout', function () { - tooltip.transition(200).style('opacity', 0) + tooltip.transition(200).style('opacity', 0); }) .append('svg:title') .text(function (j) { - return Math.max(j.value, 0) - }) - series++ - }) + return Math.max(j.value, 0); + }); + series++; + }); //Tooltip tooltip = g .append('text') .style('opacity', 0) .style('font-family', 'sans-serif') - .style('font-size', '13px') + .style('font-size', '13px'); }, - } //end of RadarChart + }; //end of RadarChart function initiateLegend(LegendOptions, id) { const svg = d3 @@ -361,14 +361,14 @@ function mmsD3RadarPlot(PlotService, $window) { .selectAll('svg') .append('svg') .attr('width', cfg.w + 300) - .attr('height', cfg.h) + .attr('height', cfg.h); //Initiate Legend const legend = svg .append('g') .attr('class', 'legend') .attr('height', 100) .attr('width', 200) - .attr('transform', 'translate(50,50)') + .attr('transform', 'translate(50,50)'); //Create colour squares legend @@ -378,34 +378,34 @@ function mmsD3RadarPlot(PlotService, $window) { .append('rect') .attr('x', cfg.w - 65) .attr('y', function (d, i) { - return i * 20 + return i * 20; }) .attr('width', 10) .attr('height', 10) .style('fill', function (d, i) { - return colorscale(i) + return colorscale(i); }) .attr('fill-opacity', 1) .attr('rid', function (d) { - return d + return d; }) .on('mouseover', function (d, i) { d3.select('.' + id) .selectAll('svg') .selectAll('polygon') .transition(200) - .style('fill-opacity', 0.1) + .style('fill-opacity', 0.1); d3.select('.radar-chart-serie' + i + '.' + id) .transition(200) - .style('fill-opacity', 0.7) + .style('fill-opacity', 0.7); }) .on('mouseout', function (d, i) { d3.select('.' + id) .selectAll('svg') .selectAll('polygon') .transition(200) - .style('fill-opacity', cfg.opacityArea) - }) + .style('fill-opacity', cfg.opacityArea); + }); //Create text next to squares legend .selectAll('text') @@ -414,32 +414,32 @@ function mmsD3RadarPlot(PlotService, $window) { .append('text') .attr('x', cfg.w - 52) .attr('y', function (d, i) { - return i * 20 + 9 + return i * 20 + 9; }) .attr('font-size', '11px') .attr('fill', '#737373') .text(function (d) { - return d + return d; }) .on('mouseover', function (d, i) { d3.select('.' + id) .selectAll('svg') .selectAll('polygon') .transition(200) - .style('fill-opacity', 0.1) + .style('fill-opacity', 0.1); d3.select('.radar-chart-serie' + i + '.' + id) .transition(200) - .style('fill-opacity', 0.7) + .style('fill-opacity', 0.7); }) .on('mouseout', function (d, i) { d3.select('.' + id) .selectAll('svg') .selectAll('polygon') .transition(200) - .style('fill-opacity', 0.1) - }) + .style('fill-opacity', 0.1); + }); } //end of initiateLegend - } //end of link + }; //end of link return { restrict: 'EA', @@ -448,5 +448,5 @@ function mmsD3RadarPlot(PlotService, $window) { plot: '<', }, link: mmsRadarChartLink, - } //return + }; //return } diff --git a/src/ve-extensions/present-plots/presentations/present-plot.component.ts b/src/ve-extensions/present-plots/presentations/present-plot.component.ts index 21c60d339..e68708849 100644 --- a/src/ve-extensions/present-plots/presentations/present-plot.component.ts +++ b/src/ve-extensions/present-plots/presentations/present-plot.component.ts @@ -1,22 +1,22 @@ -import angular from 'angular' +import angular from 'angular'; -import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations' -import { ComponentService, ExtensionService } from '@ve-components/services' -import { ButtonBarService } from '@ve-core/button-bar' -import { ImageService } from '@ve-utils/application' -import { EventService } from '@ve-utils/core' -import { SchemaService } from '@ve-utils/model-schema' +import { Presentation, PresentationService, ViewHtmlService } from '@ve-components/presentations'; +import { ComponentService, ExtensionService } from '@ve-components/services'; +import { ButtonBarService } from '@ve-core/button-bar'; +import { ImageService } from '@ve-utils/application'; +import { EventService } from '@ve-utils/core'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veComponents } from '@ve-components' +import { veComponents } from '@ve-components'; -import { VePromise, VeQService } from '@ve-types/angular' -import { IPresentationComponentOptions } from '@ve-types/components/presentation' -import { PresentContentObject } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { IPresentationComponentOptions } from '@ve-types/components/presentation'; +import { PresentContentObject } from '@ve-types/mms'; export interface PresentPlotObject extends PresentContentObject { - ptype?: string - config?: string - [key: string]: unknown + ptype?: string; + config?: string; + [key: string]: unknown; } const ViewPlotComponent: IPresentationComponentOptions = { @@ -28,10 +28,10 @@ const ViewPlotComponent: IPresentationComponentOptions = { peNumber: '<', }, controller: class ViewPlotController extends Presentation { - public plot: PresentPlotObject - public plotConfig: PresentPlotObject + public plot: PresentPlotObject; + public plotConfig: PresentPlotObject; - static $inject = Presentation.$inject + static $inject = Presentation.$inject; constructor( $q: VeQService, $element: JQuery, @@ -61,31 +61,31 @@ const ViewPlotComponent: IPresentationComponentOptions = { imageSvc, buttonBarSvc, extensionSvc - ) + ); } config = (): void => { - this.plot = this.peObject as PresentPlotObject - } + this.plot = this.peObject as PresentPlotObject; + }; getContent = (): VePromise => { if (this.plot.type === 'Plot') { if (this.plot.config !== undefined && this.plot.config.trim().length !== 0) { try { - this.plotConfig = JSON.parse(this.plot.config.replace(/'/g, '"')) as PresentPlotObject + this.plotConfig = JSON.parse(this.plot.config.replace(/'/g, '"')) as PresentPlotObject; if (this.plotConfig.ptype !== undefined) { - this.plot.ptype = this.plotConfig.ptype + this.plot.ptype = this.plotConfig.ptype; } } catch (err) { - console.log('error ignored') + console.log('error ignored'); } } return this.$q.resolve( `
    {{$ctrl.plot.title}}
    ` - ) + ); } - } + }; }, -} +}; -veComponents.component(ViewPlotComponent.selector, ViewPlotComponent) +veComponents.component(ViewPlotComponent.selector, ViewPlotComponent); diff --git a/src/ve-extensions/ts-diagram/mmsTsDiagram.directive.ts b/src/ve-extensions/ts-diagram/mmsTsDiagram.directive.ts index 9571d7561..1541d1711 100644 --- a/src/ve-extensions/ts-diagram/mmsTsDiagram.directive.ts +++ b/src/ve-extensions/ts-diagram/mmsTsDiagram.directive.ts @@ -1,6 +1,6 @@ -import angular from 'angular' +import angular from 'angular'; -const veDirectives = angular.module('veDirectives') +const veDirectives = angular.module('veDirectives'); veDirectives.directive('mmsTsDiagram', [ 'ElementService', @@ -12,7 +12,7 @@ veDirectives.directive('mmsTsDiagram', [ 'AuthService', 'URLService', mmsTsDiagram, -]) +]); /** * @ngdoc directive @@ -39,13 +39,13 @@ function mmsTsDiagram( AuthService, URLService ) { - let importedTsJs = false - const template = 'partials/mms-directives/mmsTsDiagram.html' - const mapping = {} + let importedTsJs = false; + const template = 'partials/mms-directives/mmsTsDiagram.html'; + const mapping = {}; // var deferreds = {}; - const projectId2PeId = {} - const peId2projectId = {} - const projectIdLoaded = {} + const projectId2PeId = {}; + const peId2projectId = {}; + const projectIdLoaded = {}; const viewNameMapping = { IBD: 'Internal Block Diagram', BDD: 'Block Definition Diagram', @@ -56,7 +56,7 @@ function mmsTsDiagram( PAR: 'Parametric Diagram', REQ: 'Requirement Diagram', UC: 'Use Case Diagram', - } + }; const controlMapping = { IBD: 'IBD Controls', BDD: 'BDD Controls', @@ -67,7 +67,7 @@ function mmsTsDiagram( PAR: 'PAR Controls', REQ: 'REQ Controls', UC: 'UC Controls', - } + }; const elementTableMapping = { IBD: 'IBD Elements', BDD: 'BDD Elements', @@ -78,7 +78,7 @@ function mmsTsDiagram( PAR: 'PAR Elements', REQ: 'REQ Elements', UC: 'UC Elements', - } + }; const relTableMapping = { IBD: 'IBD Relationships', BDD: 'BDD Relationships', @@ -89,54 +89,54 @@ function mmsTsDiagram( PAR: 'PAR Relationships', REQ: 'REQ Relationships', UC: 'UC Relationships', - } + }; $window.onPerspectivesCommandSuccess = (successfulCommand) => { - console.log('Perspectives command: ' + successfulCommand.command + ' completed successfully') - $window.hidePerspectivesProgressIndicator() - } + console.log('Perspectives command: ' + successfulCommand.command + ' completed successfully'); + $window.hidePerspectivesProgressIndicator(); + }; $window.onPerspectivesCommandFailure = function (failedCommand, message, callstack) { - console.log('Perspectives command ' + failedCommand.commmand + ' failed. Reason is: ' + message) - $window.hidePerspectivesProgressIndicator() - console.log(callstack) - } + console.log('Perspectives command ' + failedCommand.commmand + ' failed. Reason is: ' + message); + $window.hidePerspectivesProgressIndicator(); + console.log(callstack); + }; $window.onPerspectivesProjectLoad = (projectID) => { - console.log('All project UI elements should now be on the DOM for ' + projectID) - } + console.log('All project UI elements should now be on the DOM for ' + projectID); + }; $window.onPerspectivesProjectReady = (projectID) => { console.log( 'All project RPC calls are complete and you can now access all project resources via the DOM. ' + projectID - ) + ); if (!projectIdLoaded[projectID]) { - $window.showPerspectivesProgressIndicator() - $window.invokePerspectivesCommand(mapping[projectID]) - projectIdLoaded[projectID] = true + $window.showPerspectivesProgressIndicator(); + $window.invokePerspectivesCommand(mapping[projectID]); + projectIdLoaded[projectID] = true; } - } + }; $window.onPerspectivesViewLoaded = function (projectID, moduleName, modelID, viewID, viewName) { - console.log('The Perspectives view ' + viewID + ' is now on the DOM.') - } + console.log('The Perspectives view ' + viewID + ' is now on the DOM.'); + }; $window.onPerspectivesViewUpdated = function (projectID, moduleName, modelID, viewID, viewNamem, peObject) { - console.log('The Perspectives view' + viewID + ' was udpdated with data ' + peObject) - } + console.log('The Perspectives view' + viewID + ' was udpdated with data ' + peObject); + }; $window.onPerspectivesViewCanvasRendered = function (projectID, moduleName, modelID, viewID, viewName) { - console.log('The Perspectives canvas for view' + viewID + ' was rendered') - } + console.log('The Perspectives canvas for view' + viewID + ' was rendered'); + }; $window.onPerspectivesMouseClickOnObject = (data) => { if (data) { - console.log('JavaScript Callback = Mouse clicked on object with ID = ' + data.objectID) + console.log('JavaScript Callback = Mouse clicked on object with ID = ' + data.objectID); } - } + }; $window.onPerspectivesMouseDoubleClickOnObject = (data) => { if (data) { - console.log('JavaScript Callback = Mouse double clicked on object with ID = ' + data.objectID) + console.log('JavaScript Callback = Mouse double clicked on object with ID = ' + data.objectID); } - } + }; $window.PerspectivesErrorDialogHandler = function (message, callStackString) { //prevent ts error dialog from appearing for any js exception - console.log(message) - console.log(callStackString) - } + console.log(message); + console.log(callStackString); + }; //store global mapping of project name to hash, on*** functions can lookup the hash const mmsTsDiagramLink = (scope, element, attrs) => { if (!$window.invokePerspectivesCommand && !importedTsJs) { @@ -145,25 +145,25 @@ function mmsTsDiagram( '\n' + '\n' + '' - ) + ); - importedTsJs = true + importedTsJs = true; } - let id = ApplicationService.createUniqueId() + let id = ApplicationService.createUniqueId(); if (peId2projectId[scope.mmsPeId]) { - id = peId2projectId[scope.mmsPeId] + id = peId2projectId[scope.mmsPeId]; } else { - peId2projectId[scope.mmsPeId] = id + peId2projectId[scope.mmsPeId] = id; } - projectId2PeId[id] = scope.mmsPeId + projectId2PeId[id] = scope.mmsPeId; - scope.containerId = 'tabContainer-' + id - scope.viewId = 'view-' + id - scope.tableId = 'table-' + id - scope.edgeTableId = 'edgeTable-' + id - scope.inspectorId = 'inspector-' + id - scope.controlsId = 'controls-' + id - scope.initElements = [] + scope.containerId = 'tabContainer-' + id; + scope.viewId = 'view-' + id; + scope.tableId = 'table-' + id; + scope.edgeTableId = 'edgeTable-' + id; + scope.inspectorId = 'inspector-' + id; + scope.controlsId = 'controls-' + id; + scope.initElements = []; const params = { viewName: viewNameMapping[scope.mmsTspSpec.diagramType], @@ -172,26 +172,26 @@ function mmsTsDiagram( edgeTableName: relTableMapping[scope.mmsTspSpec.diagramType], inspectorName: 'Details', controlsName: controlMapping[scope.mmsTspSpec.diagramType], - } + }; - if (scope.mmsTspSpec && scope.mmsTspSpec.elements) scope.initElements = scope.mmsTspSpec.elements - if (scope.mmsTspSpec && scope.mmsTspSpec.context) scope.context = scope.mmsTspSpec.context + if (scope.mmsTspSpec && scope.mmsTspSpec.elements) scope.initElements = scope.mmsTspSpec.elements; + if (scope.mmsTspSpec && scope.mmsTspSpec.context) scope.context = scope.mmsTspSpec.context; - const webProjectCommand = _createWebProjectCommand(scope, params, id) - mapping[id] = _createUpdateCommand(scope, params.viewName, id) + const webProjectCommand = _createWebProjectCommand(scope, params, id); + mapping[id] = _createUpdateCommand(scope, params.viewName, id); function tryInvokeCommand() { if (!$window.invokePerspectivesCommand) { - $timeout(tryInvokeCommand, 1000, false) + $timeout(tryInvokeCommand, 1000, false); } else { - $window.invokePerspectivesCommand(webProjectCommand) + $window.invokePerspectivesCommand(webProjectCommand); } } - tryInvokeCommand() - } + tryInvokeCommand(); + }; function _getElementsArrayString(elements) { - return '[{"id": "' + elements.join('"}, {"id": "') + '"}]' + return '[{"id": "' + elements.join('"}, {"id": "') + '"}]'; } function _createWebProjectCommand(scope, params, id) { @@ -325,20 +325,20 @@ function mmsTsDiagram( }, }, ], - } - return webProjectCommand + }; + return webProjectCommand; } function _createUpdateCommand(scope, viewName, id) { const updateCommand: { - data: object[] - command: string - onsuccess: string + data: object[]; + command: string; + onsuccess: string; } = { command: 'Group', onsuccess: 'onPerspectivesCommandSuccess', data: [] as object[], - } + }; updateCommand.data.push( { command: 'Custom', @@ -391,9 +391,9 @@ function mmsTsDiagram( }, onfailure: 'onPerspectivesCommandFailure', } - ) + ); if (scope.context || scope.initElements.length > 0) { - const initialIntegratorIds: string[] = [] + const initialIntegratorIds: string[] = []; if (scope.initElements.length > 0) { updateCommand.data.push({ command: 'SetModelAttribute', @@ -407,10 +407,10 @@ function mmsTsDiagram( viewName: viewName, }, onfailure: 'onPerspectivesCommandFailure', - }) - initialIntegratorIds.push('int-add-' + id) + }); + initialIntegratorIds.push('int-add-' + id); } - initialIntegratorIds.push('int-fcd-' + id) + initialIntegratorIds.push('int-fcd-' + id); updateCommand.data.push({ command: 'Update', onsuccess: 'onPerspectivesCommandSuccess', @@ -420,7 +420,7 @@ function mmsTsDiagram( module: 'SysML', integratorIDs: initialIntegratorIds, }, - }) + }); if (scope.context) { updateCommand.data.push({ command: 'Custom', @@ -434,10 +434,10 @@ function mmsTsDiagram( args: ['' + scope.context], }, onfailure: 'onPerspectivesCommandFailure', - }) + }); } } - return updateCommand + return updateCommand; } return { @@ -450,5 +450,5 @@ function mmsTsDiagram( mmsPeId: '@', }, link: mmsTsDiagramLink, - } + }; } diff --git a/src/ve-types/angular.d.ts b/src/ve-types/angular.d.ts index 7d7b67978..3a4041f57 100644 --- a/src/ve-types/angular.d.ts +++ b/src/ve-types/angular.d.ts @@ -7,19 +7,22 @@ import angular, { IQResolveReject, IQService, IRequestConfig, -} from 'angular' +} from 'angular'; -import { ElementObject, ElementsResponse } from '@ve-types/mms' +import { ElementObject, ElementsResponse } from '@ve-types/mms'; export interface VeComponentOptions extends IComponentOptions { - selector: string + selector: string; } export interface VeQService extends IQService { new >( resolver: (resolve: IQResolveReject, reject: IQResolveReject>) => any - ): VePromise - (resolver: (resolve: IQResolveReject, reject: IQResolveReject>) => any): VePromise + ): VePromise; + (resolver: (resolve: IQResolveReject, reject: IQResolveReject>) => any): VePromise< + T, + U + >; } export interface VePromise> extends IPromise { @@ -27,40 +30,40 @@ export interface VePromise> extends IPromise { successCallback?: ((value: T) => PromiseLike | PromiseLike | TResult1) | null, errorCallback?: ((reason: VePromiseReason) => PromiseLike | PromiseLike | TResult2) | null, notifyCallback?: (state: unknown) => unknown - ): VePromise + ): VePromise; then( successCallback?: ((value: T) => PromiseLike | PromiseLike | TResult1) | null, errorCallback?: ((reason: VePromiseReason) => PromiseLike | PromiseLike | TResult2) | null, notifyCallback?: (state: unknown) => unknown - ): VePromise + ): VePromise; catch( onRejected?: ((reason: VePromiseReason) => PromiseLike | PromiseLike | TResult) | null - ): VePromise + ): VePromise; catch( onRejected?: ((reason: VePromiseReason) => VePromise | IPromise | TResult) | null - ): VePromise + ): VePromise; } export interface VePromisesResponse> { - failedRequests?: VePromiseReason[] - successfulRequests?: T[] + failedRequests?: VePromiseReason[]; + successfulRequests?: T[]; } export interface VeNgModelController extends INgModelController { - $modelValue: T + $modelValue: T; } export interface VePromiseReason { - type?: 'error' | 'info' | 'warning' - state?: angular.PromiseState - message?: string - recentVersionOfElement?: ElementObject - data?: T - status: number - headers?: IHttpHeadersGetter - config?: IRequestConfig - statusText?: string + type?: 'error' | 'info' | 'warning'; + state?: angular.PromiseState; + message?: string; + recentVersionOfElement?: ElementObject; + data?: T; + status: number; + headers?: IHttpHeadersGetter; + config?: IRequestConfig; + statusText?: string; /** Added in AngularJS 1.6.6 */ - xhrStatus?: 'complete' | 'error' | 'timeout' | 'abort' + xhrStatus?: 'complete' | 'error' | 'timeout' | 'abort'; } diff --git a/src/ve-types/components/index.d.ts b/src/ve-types/components/index.d.ts index cf04e6324..36c2b43c0 100644 --- a/src/ve-types/components/index.d.ts +++ b/src/ve-types/components/index.d.ts @@ -1,32 +1,32 @@ -import angular from 'angular' +import angular from 'angular'; -import { SpecApi } from '@ve-components/spec-tools' -import { ButtonBarApi } from '@ve-core/button-bar' +import { SpecApi } from '@ve-components/spec-tools'; +import { ButtonBarApi } from '@ve-core/button-bar'; -import { VePromise } from '@ve-types/angular' -import { ElementObject, InstanceValueObject, ValueObject, ViewObject } from '@ve-types/mms' +import { VePromise } from '@ve-types/angular'; +import { ElementObject, InstanceValueObject, ValueObject, ViewObject } from '@ve-types/mms'; export interface ComponentController { - element: T - commitId: string - edit: T - view?: ViewObject - instanceSpec?: ElementObject - instanceVal?: InstanceValueObject - elementSaving: boolean - editLoading?: boolean - bbApi?: ButtonBarApi - editorOptions?: { callback?(e?: JQuery.ClickEvent): VePromise } - specApi?: SpecApi + element: T; + commitId: string; + edit: T; + view?: ViewObject; + instanceSpec?: ElementObject; + instanceVal?: InstanceValueObject; + elementSaving: boolean; + editLoading?: boolean; + bbApi?: ButtonBarApi; + editorOptions?: { callback?(e?: JQuery.ClickEvent): VePromise }; + specApi?: SpecApi; // isEnumeration: boolean, - skipBroadcast: boolean - isEditing: boolean - inPreviewMode: boolean - values?: ValueObject[] - editValues?: ValueObject[] - $scope: angular.IScope + skipBroadcast: boolean; + isEditing: boolean; + inPreviewMode: boolean; + values?: ValueObject[]; + editValues?: ValueObject[]; + $scope: angular.IScope; } -export { InsertApi } from '@ve-types/components/insertions' -export { InsertData } from '@ve-types/components/insertions' -export { InsertResolve } from '@ve-types/components/insertions' -export { InsertResolveFn } from '@ve-types/components/insertions' +export { InsertApi } from '@ve-types/components/insertions'; +export { InsertData } from '@ve-types/components/insertions'; +export { InsertResolve } from '@ve-types/components/insertions'; +export { InsertResolveFn } from '@ve-types/components/insertions'; diff --git a/src/ve-types/components/insertions.d.ts b/src/ve-types/components/insertions.d.ts index 3ab92ed7a..10a27359e 100644 --- a/src/ve-types/components/insertions.d.ts +++ b/src/ve-types/components/insertions.d.ts @@ -1,34 +1,34 @@ -import { ElementObject } from '@ve-types/mms' -import { VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor' +import { ElementObject } from '@ve-types/mms'; +import { VeModalResolve, VeModalResolveFn } from '@ve-types/view-editor'; export interface InsertResolveFn extends VeModalResolveFn { - getInsertData(): T + getInsertData(): T; - getProjectId(): string + getProjectId(): string; - getRefId(): string + getRefId(): string; - getOrgId(): string + getOrgId(): string; } export interface InsertResolve extends VeModalResolve { - getInsertData: T - getProjectId: string - getRefId: string - getOrgId: string + getInsertData: T; + getProjectId: string; + getRefId: string; + getOrgId: string; } export interface InsertData { - type: string - insertType: string - noPublish?: boolean - isNew?: boolean - parentTitle?: string - selected?: ElementObject + type: string; + insertType: string; + noPublish?: boolean; + isNew?: boolean; + parentTitle?: string; + selected?: ElementObject; } export interface InsertApi { - resolve(data: T): void + resolve(data: T): void; - reject(reason: U): void + reject(reason: U): void; } diff --git a/src/ve-types/components/presentation.d.ts b/src/ve-types/components/presentation.d.ts index 7892049c5..83727ef4c 100644 --- a/src/ve-types/components/presentation.d.ts +++ b/src/ve-types/components/presentation.d.ts @@ -1,28 +1,28 @@ -import { VeComponentOptions } from '@ve-types/angular' +import { VeComponentOptions } from '@ve-types/angular'; export interface IPresentationComponentOptions extends VeComponentOptions { - selector: string - style?: string[] + selector: string; + style?: string[]; bindings: { - peObject: string - instanceSpec: string - peNumber: string - mmsProjectId?: '@' - mmsRefId?: '@' - mmsCommitId?: '@' - [key: string]: string - } + peObject: string; + instanceSpec: string; + peNumber: string; + mmsProjectId?: '@'; + mmsRefId?: '@'; + mmsCommitId?: '@'; + [key: string]: string; + }; required?: { - mmsViewPresentationElemCtrl: string - mmsViewCtrl: string - [key: string]: string - } + mmsViewPresentationElemCtrl: string; + mmsViewCtrl: string; + [key: string]: string; + }; } export interface ITableConfig { - sortByColumnFn(sortCol?: number): void + sortByColumnFn(sortCol?: number): void; - showBindingForSortIcon: number - filterDebounceRate: number - filterTermColumnPrefixBinding: string + showBindingForSortIcon: number; + filterDebounceRate: number; + filterTermColumnPrefixBinding: string; } diff --git a/src/ve-types/config.d.ts b/src/ve-types/config.d.ts index 91d23f4b7..d9baacb4a 100644 --- a/src/ve-types/config.d.ts +++ b/src/ve-types/config.d.ts @@ -1,18 +1,18 @@ -import { VeExperimentConfig, VeExperimentDescriptor } from '@ve-components/services' -import { BrandingStyle } from '@ve-utils/application' +import { VeExperimentConfig, VeExperimentDescriptor } from '@ve-components/services'; +import { BrandingStyle } from '@ve-utils/application'; export interface VeConfig { - version?: string - apiUrl: string - printUrl: string - basePath: string - enableDebug?: boolean - customLabels?: { [key: string]: string } - loginBanner?: BrandingStyle - loginWarning?: BrandingStyle - banner?: BrandingStyle - footer?: BrandingStyle - loginTimeout?: number - experimental?: VeExperimentDescriptor[] - expConfig?: VeExperimentConfig + version?: string; + apiUrl: string; + printUrl: string; + basePath: string; + enableDebug?: boolean; + customLabels?: { [key: string]: string }; + loginBanner?: BrandingStyle; + loginWarning?: BrandingStyle; + banner?: BrandingStyle; + footer?: BrandingStyle; + loginTimeout?: number; + experimental?: VeExperimentDescriptor[]; + expConfig?: VeExperimentConfig; } diff --git a/src/ve-types/core/editor.d.ts b/src/ve-types/core/editor.d.ts index 6e3337ca0..078887b38 100644 --- a/src/ve-types/core/editor.d.ts +++ b/src/ve-types/core/editor.d.ts @@ -1,13 +1,13 @@ export interface EditorActions { - cancel(e?): void + cancel(e?): void; - reset(e?): void + reset(e?): void; - delete(e?): void + delete(e?): void; - preview(e?): void + preview(e?): void; - save(e?): void + save(e?): void; - saveC(e?): void + saveC(e?): void; } diff --git a/src/ve-types/mms/index.d.ts b/src/ve-types/mms/index.d.ts index 56830c838..a344f7aa4 100644 --- a/src/ve-types/mms/index.d.ts +++ b/src/ve-types/mms/index.d.ts @@ -1,36 +1,36 @@ -import { ArtifactObject } from '@ve-types/mms/mms' -import { ValueObject } from '@ve-types/mms/valuesAndInstances' +import { ArtifactObject } from '@ve-types/mms/mms'; +import { ValueObject } from '@ve-types/mms/valuesAndInstances'; -export * from './valuesAndInstances.d' -export * from './views.d' -export * from './orgsAndProjects.d' -export * from './mms.d' +export * from './valuesAndInstances.d'; +export * from './views.d'; +export * from './orgsAndProjects.d'; +export * from './mms.d'; // eslint-disable-next-line @typescript-eslint/no-explicit-any -export type MmsObject = Record +export type MmsObject = Record; export interface TransclusionObject extends MmsObject { - element?: ElementObject - tag: string + element?: ElementObject; + tag: string; } export interface ElementObject extends MmsObject { - id: string - _projectId: string - _refId: string - _commitId?: string - _modified?: string - _modifier?: string - _creator?: string - _created?: string - _inRefIds?: string[] - _artifacts?: ArtifactObject[] - appliedStereotypeIds?: string[] - _appliedStereotypeIds?: string[] // mdk < 6 - type?: string - typeId?: string - defaultValue?: ValueObject - documentation?: string - name?: string - ownerId?: string + id: string; + _projectId: string; + _refId: string; + _commitId?: string; + _modified?: string; + _modifier?: string; + _creator?: string; + _created?: string; + _inRefIds?: string[]; + _artifacts?: ArtifactObject[]; + appliedStereotypeIds?: string[]; + _appliedStereotypeIds?: string[]; // mdk < 6 + type?: string; + typeId?: string; + defaultValue?: ValueObject; + documentation?: string; + name?: string; + ownerId?: string; } diff --git a/src/ve-types/mms/mms.d.ts b/src/ve-types/mms/mms.d.ts index 5342da01d..2b8afd391 100644 --- a/src/ve-types/mms/mms.d.ts +++ b/src/ve-types/mms/mms.d.ts @@ -7,205 +7,205 @@ import { ProjectObject, RefObject, UserObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; export interface UserObject extends MmsObject { - username: string - id?: string - created?: Date - modified?: Date - email?: string - firstName?: string - lastName?: string - admin?: boolean - enabled?: boolean - fullName?: string + username: string; + id?: string; + created?: Date; + modified?: Date; + email?: string; + firstName?: string; + lastName?: string; + admin?: boolean; + enabled?: boolean; + fullName?: string; } export interface CommitObject extends MmsObject { - deleted?: CommitChangeElement[] - _creator?: string - added?: CommitChangeElement[] - _docId?: string - _created?: string - comment?: null - source?: null - id: string - updated?: CommitChangeElement[] - _refId: string - _projectId: string + deleted?: CommitChangeElement[]; + _creator?: string; + added?: CommitChangeElement[]; + _docId?: string; + _created?: string; + comment?: null; + source?: null; + id: string; + updated?: CommitChangeElement[]; + _refId: string; + _projectId: string; } export interface CommitChangeElement extends MmsObject { - _previousDocId: string - _docId: string - id: string - type: string + _previousDocId: string; + _docId: string; + id: string; + type: string; } export interface RequestObject extends MmsObject { - projectId: string - refId: string - orgId?: string - commitId?: string - depth?: number + projectId: string; + refId: string; + orgId?: string; + commitId?: string; + depth?: number; } export interface ShortUrlRequest extends RequestObject { - orgId: string - viewId?: string - documentId: string + orgId: string; + viewId?: string; + documentId: string; } export interface ElementsRequest extends RequestObject { - elementId: T + elementId: T; } export interface UsersRequest extends RequestObject { - username: string + username: string; } export interface CreationRequest { - elements: T[] + elements: T[]; } export interface ElementCreationRequest extends RequestObject { - elements: T[] + elements: T[]; } export interface ViewsRequest extends RequestObject { - returnChildViews?: boolean - parentViewId?: string - aggr?: string + returnChildViews?: boolean; + parentViewId?: string; + aggr?: string; } export interface ViewCreationRequest extends ViewsRequest { - viewId: string - viewDoc?: string - viewName?: string + viewId: string; + viewDoc?: string; + viewName?: string; } export interface ArtifactsRequest extends ElementsRequest { - artifactExtension: string + artifactExtension: string; } export interface AuthRequest { - username: string - password: string + username: string; + password: string; } export interface ArtifactObject { - extension: string - checksum: string - locationType: string - location: string - mimetype: string + extension: string; + checksum: string; + locationType: string; + location: string; + mimetype: string; } export interface ParamsObject { - projectId?: string - refId?: string - viewId?: string - documentId?: string - shortUrl?: string - keywords?: string - field?: string - fromLogin?: boolean - '#'?: string - display?: string - preview?: string - next?: string - [param: string]: string + projectId?: string; + refId?: string; + viewId?: string; + documentId?: string; + shortUrl?: string; + keywords?: string; + field?: string; + fromLogin?: boolean; + '#'?: string; + display?: string; + preview?: string; + next?: string; + [param: string]: string; } export interface QueryObject extends MmsObject { params?: { - [key: string]: string | object - } + [key: string]: string | object; + }; recurse?: { - [key: string]: string | object - } - from?: number - size?: number + [key: string]: string | object; + }; + from?: number; + size?: number; } export interface QueryParams extends MmsObject { - showDeleted?: boolean - [key: string]: string | boolean | number + showDeleted?: boolean; + [key: string]: string | boolean | number; } export interface AuthResponse { - token: string + token: string; } export interface VersionResponse { - mmsVersion: string + mmsVersion: string; } export interface CheckAuthResponse { - username: string + username: string; } interface BasicResponse { - messages: string[] - rejected: RejectedObject[] + messages: string[]; + rejected: RejectedObject[]; } interface GenericResponse extends BasicResponse { - [p: string]: T[] + [p: string]: T[]; } interface RejectedObject { - code: number - message: string - object: T + code: number; + message: string; + object: T; } export interface ElementsResponse extends BasicResponse { - elements: T[] - deleted?: T[] + elements: T[]; + deleted?: T[]; } export interface PermissionsResponse extends BasicResponse { - lookups: PermissionsObject[] - allPassed: boolean + lookups: PermissionsObject[]; + allPassed: boolean; } export interface PermissionsObject { - type: string - orgId?: string - projectId?: string - refId?: string - groupName?: string - privilege: string - allowAnonIfPublic: boolean - hasPrivilege: boolean + type: string; + orgId?: string; + projectId?: string; + refId?: string; + groupName?: string; + privilege: string; + allowAnonIfPublic: boolean; + hasPrivilege: boolean; } export interface SearchResponse extends ElementsResponse { - total: number - rejectedTotal: number + total: number; + rejectedTotal: number; } export interface OrgsResponse extends BasicResponse { - orgs: OrgObject[] + orgs: OrgObject[]; } export interface ProjectsResponse extends BasicResponse { - projects: ProjectObject[] + projects: ProjectObject[]; } export interface RefsResponse extends BasicResponse { - refs: RefObject[] + refs: RefObject[]; } export interface CommitResponse extends BasicResponse { - commits: CommitObject[] + commits: CommitObject[]; } export interface GroupsResponse extends BasicResponse { - groups: GroupObject[] + groups: GroupObject[]; } export interface UsersResponse extends BasicResponse { - users: UserObject[] + users: UserObject[]; } diff --git a/src/ve-types/mms/orgsAndProjects.d.ts b/src/ve-types/mms/orgsAndProjects.d.ts index 4ff33b739..64a7dd2d6 100644 --- a/src/ve-types/mms/orgsAndProjects.d.ts +++ b/src/ve-types/mms/orgsAndProjects.d.ts @@ -1,42 +1,42 @@ -import { MmsObject } from '@ve-types/mms' +import { MmsObject } from '@ve-types/mms'; export interface OrgObject extends MmsObject { - public: boolean - created: string - name: string - modified: string - id: string + public: boolean; + created: string; + name: string; + modified: string; + id: string; } export interface ProjectObject extends MmsObject { - _refId?: string - schema?: string - _creator?: string - _docId?: string - _created?: string - name?: string - id: string - orgId?: string + _refId?: string; + schema?: string; + _creator?: string; + _docId?: string; + _created?: string; + name?: string; + id: string; + orgId?: string; } export interface MountObject extends ProjectObject { - _mounts: MountObject[] - _refId: string - _projectId: string + _mounts: MountObject[]; + _refId: string; + _projectId: string; } export interface RefObject extends MmsObject { - parentRefId?: string - deleted?: boolean - _docId?: string - _creator?: string - _created?: string - description?: string - name?: string - id: string - type: string - _projectId: string - permission?: string - parentCommitId?: string - timestamp?: Date + parentRefId?: string; + deleted?: boolean; + _docId?: string; + _creator?: string; + _created?: string; + description?: string; + name?: string; + id: string; + type: string; + _projectId: string; + permission?: string; + parentCommitId?: string; + timestamp?: Date; } diff --git a/src/ve-types/mms/valuesAndInstances.d.ts b/src/ve-types/mms/valuesAndInstances.d.ts index 8592773da..34a7275b9 100644 --- a/src/ve-types/mms/valuesAndInstances.d.ts +++ b/src/ve-types/mms/valuesAndInstances.d.ts @@ -1,42 +1,42 @@ -import { ElementObject } from '@ve-types/mms' +import { ElementObject } from '@ve-types/mms'; //Value Specs export interface ValueObject extends ElementObject { - expression?: ExpressionObject + expression?: ExpressionObject; } export interface LiteralObject extends ValueObject { - value?: T + value?: T; } export interface InstanceValueObject extends ValueObject { - instanceId?: string + instanceId?: string; } export interface ElementValueObject extends ValueObject { - elementId?: string + elementId?: string; } export interface ExpressionObject extends ValueObject { - operand?: T[] + operand?: T[]; } //Constraint export interface ConstraintObject extends ElementObject { - specification?: ValueObject + specification?: ValueObject; } //Instances export interface InstanceSpecObject extends ElementObject { - classifierIds?: string[] - specification?: ValueObject + classifierIds?: string[]; + specification?: ValueObject; } export interface SlotObject extends LiteralObject[]> { - definingFeatureId: string + definingFeatureId: string; } export interface TaggedValueObject extends LiteralObject[]> { - tagDefinitionId: string + tagDefinitionId: string; } export interface ElementTaggedValueObject extends TaggedValueObject { - valueIds: string[] + valueIds: string[]; } diff --git a/src/ve-types/mms/views.d.ts b/src/ve-types/mms/views.d.ts index b1fb1d32e..08b0bba9c 100644 --- a/src/ve-types/mms/views.d.ts +++ b/src/ve-types/mms/views.d.ts @@ -5,96 +5,96 @@ import { InstanceSpecObject, InstanceValueObject, LiteralObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; /* View Objects */ export interface ViewObject extends ElementObject { - isDoc?: boolean - aggregation?: string - propertyId?: string - _relatedDocuments?: ViewObject[] - _parentViews?: ViewObject[] - _contents?: ExpressionObject - _childViews?: ViewObject[] - _displayedElementIds?: string[] - _veNumber?: string - _printCss?: string + isDoc?: boolean; + aggregation?: string; + propertyId?: string; + _relatedDocuments?: ViewObject[]; + _parentViews?: ViewObject[]; + _contents?: ExpressionObject; + _childViews?: ViewObject[]; + _displayedElementIds?: string[]; + _veNumber?: string; + _printCss?: string; } export interface DocumentObject extends ViewObject { - _groupId?: string - _startChapter?: number + _groupId?: string; + _startChapter?: number; } export interface PackageObject extends ElementObject { - elementImportIds?: string[] - packageImportIds?: string[] - URI?: string - packageMergeIds?: string[] - profileApplicationIds?: string[] + elementImportIds?: string[]; + packageImportIds?: string[]; + URI?: string; + packageMergeIds?: string[]; + profileApplicationIds?: string[]; } export interface GroupObject extends PackageObject { - _isGroup?: boolean - _parentId?: string + _isGroup?: boolean; + _parentId?: string; } /* View and Presentation Instances */ export interface ViewInstanceSpec extends InstanceSpecObject { - specification?: ExpressionObject | LiteralObject - _veNumber?: string + specification?: ExpressionObject | LiteralObject; + _veNumber?: string; } export interface PresentationReference extends MmsObject { - instanceId: string - instanceVal?: InstanceValueObject - sectionElements: PresentationReference[] - instanceSpecification?: ViewInstanceSpec - presentationElement?: PresentationInstanceObject | ViewInstanceSpec - isOpaque: boolean + instanceId: string; + instanceVal?: InstanceValueObject; + sectionElements: PresentationReference[]; + instanceSpecification?: ViewInstanceSpec; + presentationElement?: PresentationInstanceObject | ViewInstanceSpec; + isOpaque: boolean; } export interface PresentationInstanceObject extends MmsObject { - type: string - isOpaque?: boolean + type: string; + isOpaque?: boolean; } export interface PresentContentObject extends PresentationInstanceObject { - excludeFromList: boolean - showIfEmpty: boolean - title: string + excludeFromList: boolean; + showIfEmpty: boolean; + title: string; } export interface PresentImageObject extends PresentContentObject { - id: string + id: string; } export interface PresentListObject extends PresentContentObject { - list: PresentationInstanceObject[][] - ordered?: boolean + list: PresentationInstanceObject[][]; + ordered?: boolean; } export interface PresentTableObject extends PresentContentObject { - body: TableEntryObject[][] - header?: TableEntryObject[][] - colwidths?: string - style: string + body: TableEntryObject[][]; + header?: TableEntryObject[][]; + colwidths?: string; + style: string; } export interface TableEntryObject { - colspan: number - rowspan: number - content: PresentationInstanceObject[] - startCol?: number - endCol?: number - startRow?: number - endRow?: number + colspan: number; + rowspan: number; + content: PresentationInstanceObject[]; + startCol?: number; + endCol?: number; + startRow?: number; + endRow?: number; } export interface PresentTextObject extends PresentationInstanceObject { - source: string - sourceProperty?: string - sourceType: string - nonEditable?: boolean - text?: string + source: string; + sourceProperty?: string; + sourceType: string; + nonEditable?: boolean; + text?: string; } diff --git a/src/ve-types/third-party/angular.d.ts b/src/ve-types/third-party/angular.d.ts index 186ec05ca..a07055cb5 100644 --- a/src/ve-types/third-party/angular.d.ts +++ b/src/ve-types/third-party/angular.d.ts @@ -1,14 +1,14 @@ /* eslint-disable unused-imports/no-unused-imports */ -import angular from 'angular' +import angular from 'angular'; declare module 'angular' { interface IRequestConfig { - cancel: IDeferred + cancel: IDeferred; } interface IPromise { - state: string + state: string; } interface IDeferred { - state: string + state: string; } } diff --git a/src/ve-types/third-party/jquery.d.ts b/src/ve-types/third-party/jquery.d.ts index fa5282a6f..05758937c 100644 --- a/src/ve-types/third-party/jquery.d.ts +++ b/src/ve-types/third-party/jquery.d.ts @@ -1,18 +1,18 @@ -export {} +export {}; declare global { interface JQuery { - isOnScreen(x?: number, y?: number): boolean + isOnScreen(x?: number, y?: number): boolean; - table2CSV(inputOptions: table2CSV.inputOptions): string + table2CSV(inputOptions: table2CSV.inputOptions): string; } namespace JQuery { namespace table2CSV { interface inputOptions { - delivery: string - separator?: string - header?: string[] + delivery: string; + separator?: string; + header?: string[]; } } } diff --git a/src/ve-types/third-party/mathjax.d.ts b/src/ve-types/third-party/mathjax.d.ts index 95cfa3051..5b99e02f3 100644 --- a/src/ve-types/third-party/mathjax.d.ts +++ b/src/ve-types/third-party/mathjax.d.ts @@ -1,3 +1,3 @@ export interface MathJaxObject { - typesetPromise(elements: any[]): Promise + typesetPromise(elements: any[]): Promise; } diff --git a/src/ve-types/tree.d.ts b/src/ve-types/tree.d.ts index 869f7b364..ba7e7e355 100644 --- a/src/ve-types/tree.d.ts +++ b/src/ve-types/tree.d.ts @@ -1,159 +1,159 @@ -import angular from 'angular' +import angular from 'angular'; -import ITreeNode = AngularUITree.ITreeNode +import ITreeNode = AngularUITree.ITreeNode; -import { ElementObject, ElementsRequest, ViewObject } from '@ve-types/mms' +import { ElementObject, ElementsRequest, ViewObject } from '@ve-types/mms'; /** * @typedef TreeBranch */ export interface TreeBranch extends ITreeNode { - label: string - type: string - priority?: number - group?: ElementObject - data: ViewObject - children: TreeBranch[] - hide?: boolean - level?: number - new?: string - loading?: boolean - aggr?: string - propertyId?: string - parent_uid?: string - uid?: string - viewId?: string - selected?: boolean - expanded?: boolean - expandable?: boolean - favorite?: boolean - onSelect?(branch: TreeBranch): void - onDblClick?(branch: TreeBranch): void + label: string; + type: string; + priority?: number; + group?: ElementObject; + data: ViewObject; + children: TreeBranch[]; + hide?: boolean; + level?: number; + new?: string; + loading?: boolean; + aggr?: string; + propertyId?: string; + parent_uid?: string; + uid?: string; + viewId?: string; + selected?: boolean; + expanded?: boolean; + expandable?: boolean; + favorite?: boolean; + onSelect?(branch: TreeBranch): void; + onDblClick?(branch: TreeBranch): void; } export interface TreeRow { - branch: TreeBranch - children: TreeBranch[] - visibleChild: boolean - label: string - level: number - section: string - typeIcon: string - visible: boolean + branch: TreeBranch; + children: TreeBranch[]; + visibleChild: boolean; + label: string; + level: number; + section: string; + typeIcon: string; + visible: boolean; } export interface TreeApi extends ElementsRequest { - rootId?: string - refType: string - sectionNumbering?: boolean - numberingDepth?: number - numberingSeparator?: string - expandLevel?: number - search?: string - sort?: boolean - startChapter?: number - treeContentLoading?: boolean - treeCategory?: string - expandCallback?(elementId: string, branch: TreeBranch, recurse: boolean) - onSelect?(branch: TreeBranch): void - onDblClick?(branch: TreeBranch): void + rootId?: string; + refType: string; + sectionNumbering?: boolean; + numberingDepth?: number; + numberingSeparator?: string; + expandLevel?: number; + search?: string; + sort?: boolean; + startChapter?: number; + treeContentLoading?: boolean; + treeCategory?: string; + expandCallback?(elementId: string, branch: TreeBranch, recurse: boolean); + onSelect?(branch: TreeBranch): void; + onDblClick?(branch: TreeBranch): void; } export interface TreeConfig { - id: string - title?: string - icon?: string - types?: string[] - treeData?: TreeBranch[] - treeRows?: TreeRow[] + id: string; + title?: string; + icon?: string; + types?: string[]; + treeData?: TreeBranch[]; + treeRows?: TreeRow[]; } export interface TreeIcons { - iconExpand: string - iconCollapse: string - iconDefault: string + iconExpand: string; + iconCollapse: string; + iconDefault: string; } export interface VeTreeNodeScope extends AngularUITree.ITreeNodeScope { - node: TreeBranch + node: TreeBranch; } export interface View2NodeMap { - [key: string]: TreeBranch + [key: string]: TreeBranch; } declare namespace AngularUITree { interface IEventSourceInfo { - cloneModel: any - index: number - nodeScope: ITreeNodeScope - nodesScope: ITreeNodeScope + cloneModel: any; + index: number; + nodeScope: ITreeNodeScope; + nodesScope: ITreeNodeScope; } interface IPosition { - dirAx: number - dirX: number - dirY: number - distAxX: number - distAxY: number - distX: number - distY: number - lastDirX: number - lastDirY: number - lastX: number - lastY: number - moving: boolean - nowX: number - nowY: number - offsetX: number - offsetY: number - startX: number - startY: number + dirAx: number; + dirX: number; + dirY: number; + distAxX: number; + distAxY: number; + distX: number; + distY: number; + lastDirX: number; + lastDirY: number; + lastX: number; + lastY: number; + moving: boolean; + nowX: number; + nowY: number; + offsetX: number; + offsetY: number; + startX: number; + startY: number; } interface IEventInfo { dest: { - index: number - nodesScope: IParentTreeNodeScope - } - elements: any - pos: IPosition - source: IEventSourceInfo + index: number; + nodesScope: IParentTreeNodeScope; + }; + elements: any; + pos: IPosition; + source: IEventSourceInfo; } interface IAcceptCallback { - (source: ITreeNodeScope, destination: ITreeNodeScope, destinationIndex: number): boolean + (source: ITreeNodeScope, destination: ITreeNodeScope, destinationIndex: number): boolean; } interface IDragCallback { - (eventInfo: IEventInfo): void + (eventInfo: IEventInfo): void; } interface ICallbacks { - accept?: IAcceptCallback - dragStart?: IDragCallback - dropped?: IDragCallback - dragStop?: IDragCallback + accept?: IAcceptCallback; + dragStart?: IDragCallback; + dropped?: IDragCallback; + dragStop?: IDragCallback; } /** * Internal representation of node in the UI */ interface ITreeNodeScope extends angular.IScope { - $element: JQuery - $modelValue: any // Model value for node; - $nodeScope: ITreeNodeScope // uiTreeNode Scope of this node - $parentNodeScope: IParentTreeNodeScope[] // uiTreeNode Scope of parent node; - $childNodesScope: ITreeNodeScope[] // uiTreeNodes Scope of child nodes. - $parentNodesScope: angular.IScope // uiTreeNodes Scope of parent nodes. - $treeScope: angular.IScope // uiTree scope - $handleScope: angular.IScope // it's handle scope - $type: 'uiTreeNode' - node: ITreeNode + $element: JQuery; + $modelValue: any; // Model value for node; + $nodeScope: ITreeNodeScope; // uiTreeNode Scope of this node + $parentNodeScope: IParentTreeNodeScope[]; // uiTreeNode Scope of parent node; + $childNodesScope: ITreeNodeScope[]; // uiTreeNodes Scope of child nodes. + $parentNodesScope: angular.IScope; // uiTreeNodes Scope of parent nodes. + $treeScope: angular.IScope; // uiTree scope + $handleScope: angular.IScope; // it's handle scope + $type: 'uiTreeNode'; + node: ITreeNode; } interface IParentTreeNodeScope extends ITreeNodeScope { - isParent(nodeScope: ITreeNodeScope): boolean + isParent(nodeScope: ITreeNodeScope): boolean; } // /** diff --git a/src/ve-types/view-editor.d.ts b/src/ve-types/view-editor.d.ts index 4915f9887..a6241006a 100644 --- a/src/ve-types/view-editor.d.ts +++ b/src/ve-types/view-editor.d.ts @@ -1,37 +1,37 @@ -import { ngStorage } from 'ngstorage' +import { ngStorage } from 'ngstorage'; -import IModalService = angular.ui.bootstrap.IModalService -import IModalSettings = angular.ui.bootstrap.IModalSettings -import IModalInstanceService = angular.ui.bootstrap.IModalInstanceService +import IModalService = angular.ui.bootstrap.IModalService; +import IModalSettings = angular.ui.bootstrap.IModalSettings; +import IModalInstanceService = angular.ui.bootstrap.IModalInstanceService; -import { VeComponentOptions, VePromise, VePromiseReason } from '@ve-types/angular' -import { MmsObject, OrgObject, ProjectObject, ViewObject } from '@ve-types/mms' +import { VeComponentOptions, VePromise, VePromiseReason } from '@ve-types/angular'; +import { MmsObject, OrgObject, ProjectObject, ViewObject } from '@ve-types/mms'; -export type veSearchCallback = (elem: T, property: string) => void +export type veSearchCallback = (elem: T, property: string) => void; export interface VeSearchOptions { - getProperties?: boolean - searchResult?: T[] - searchField?: string - closeable: boolean - closeCallback?(): void - searchInput?: string - hideFilterOptions?: boolean - callback?: veSearchCallback - relatedCallback?(doc: ViewObject, view: ViewObject, elem: T): void - filterCallback?(elements: T[]): T[] - filterQueryList?: [(...any) => { [key: string]: string[] }] - emptyDocTxt?: string - itemsPerPage?: number + getProperties?: boolean; + searchResult?: T[]; + searchField?: string; + closeable: boolean; + closeCallback?(): void; + searchInput?: string; + hideFilterOptions?: boolean; + callback?: veSearchCallback; + relatedCallback?(doc: ViewObject, view: ViewObject, elem: T): void; + filterCallback?(elements: T[]): T[]; + filterQueryList?: [(...any) => { [key: string]: string[] }]; + emptyDocTxt?: string; + itemsPerPage?: number; } export interface VeModalService extends IModalService { - open?(settings: VeModalSettings): VeModalInstanceService + open?(settings: VeModalSettings): VeModalInstanceService; } export interface VeModalSettings extends IModalSettings { - component: string - resolve?: U + component: string; + resolve?: U; // bindings?: { // modalInstance: VeModalInstanceService // resolve?: U @@ -40,48 +40,48 @@ export interface VeModalSettings extends IModalSetti export interface VeModalComponent extends VeComponentOptions { bindings?: { - modalInstance: string - resolve?: string - } + modalInstance: string; + resolve?: string; + }; } export interface VeModalInstanceService extends IModalInstanceService { - close(result?: T): void - dismiss(reason?: T): void - result: VePromise + close(result?: T): void; + dismiss(reason?: T): void; + result: VePromise; } export interface VeModalController extends IComponentController { // close: ($value?: any) => void, // dismiss: ($value?: any) => void, - modalInstance: IModalInstanceService + modalInstance: IModalInstanceService; } export interface VeModalResolve { - [key: string]: unknown + [key: string]: unknown; } export interface VeModalResolveFn { - [key: string]: () => unknown + [key: string]: () => unknown; } export interface VeStorageService extends ngStorage.StorageService { - token: string - org: OrgObject - project: ProjectObject + token: string; + org: OrgObject; + project: ProjectObject; } export interface VeApiObject { - [key: string]: VeApiWait + [key: string]: VeApiWait; } export interface VeApiWait { - resolve?(result: T): void - reject?(reason: VePromiseReason): void - promise?: VePromise - api?: T - refId?: string - projectId?: string + resolve?(result: T): void; + reject?(reason: VePromiseReason): void; + promise?: VePromise; + api?: T; + refId?: string; + projectId?: string; } // { // getProperties: any diff --git a/src/ve-types/window.d.ts b/src/ve-types/window.d.ts index 3591fe735..88f8342c9 100644 --- a/src/ve-types/window.d.ts +++ b/src/ve-types/window.d.ts @@ -1,18 +1,18 @@ //https://stackoverflow.com/questions/57132428/augmentations-for-the-global-scope-can-only-be-directly-nested-in-external-modul -import { MathJaxObject } from 'mathjax-full/js/components/startup' +import { MathJaxObject } from 'mathjax-full/js/components/startup'; -import { HtmlRenderedDiff } from '../lib/html-rendered-diff' +import { HtmlRenderedDiff } from '../lib/html-rendered-diff'; -import { VeConfig } from '@ve-types/config' +import { VeConfig } from '@ve-types/config'; -export {} +export {}; declare global { interface Window { - $: JQuery - MathJax: MathJaxObject - __env: VeConfig - HtmlRenderedDiff: HtmlRenderedDiff - Promise: Promise + $: JQuery; + MathJax: MathJaxObject; + __env: VeConfig; + HtmlRenderedDiff: HtmlRenderedDiff; + Promise: Promise; } } diff --git a/src/ve-utils/application/Application.service.ts b/src/ve-utils/application/Application.service.ts index a78c5ba05..97a83e657 100644 --- a/src/ve-utils/application/Application.service.ts +++ b/src/ve-utils/application/Application.service.ts @@ -1,12 +1,12 @@ -import { CacheService } from '@ve-utils/core' -import { ApiService, ElementService, ProjectService } from '@ve-utils/mms-api-client' +import { CacheService } from '@ve-utils/core'; +import { ApiService, ElementService, ProjectService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { BrandingStyle } from './Branding.service' +import { BrandingStyle } from './Branding.service'; -import { VePromise, VeQService } from '@ve-types/angular' -import { ElementObject, UsersRequest } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { ElementObject, UsersRequest } from '@ve-types/mms'; /** * @ngdoc service * @name veUtils/ApplicationService @@ -18,19 +18,19 @@ import { ElementObject, UsersRequest } from '@ve-types/mms' */ export interface ProjectSettingsObject extends ElementObject { - banner?: BrandingStyle - footer?: BrandingStyle + banner?: BrandingStyle; + footer?: BrandingStyle; } export interface UserSettingsObject extends ElementObject { - pinned?: string[] + pinned?: string[]; } export interface VeApplicationState { - inDoc: boolean - fullDoc: boolean - currentDoc: string - user: string + inDoc: boolean; + fullDoc: boolean; + currentDoc: string; + user: string; } export class ApplicationService { @@ -39,11 +39,11 @@ export class ApplicationService { fullDoc: false, currentDoc: null, user: null, - } + }; - public PROJECT_URL_PREFIX = '#/projects/' + public PROJECT_URL_PREFIX = '#/projects/'; - static $inject = ['$q', 'ProjectService', 'ElementService', 'ApiService', 'CacheService'] + static $inject = ['$q', 'ProjectService', 'ElementService', 'ApiService', 'CacheService']; constructor( private $q: VeQService, @@ -54,22 +54,22 @@ export class ApplicationService { ) {} public getState(): VeApplicationState { - return this.state + return this.state; } public copyToClipboard(target: JQuery, $event: JQuery.ClickEvent): VePromise { - const deferred = this.$q.defer() - $event.stopPropagation() + const deferred = this.$q.defer(); + $event.stopPropagation(); navigator.clipboard.writeText(target[0].childNodes[0].textContent).then( () => { - deferred.resolve() + deferred.resolve(); }, (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) - return deferred.promise + ); + return deferred.promise; } public getUserSettings = ( @@ -77,10 +77,10 @@ export class ApplicationService { refresh?: boolean, weight?: number ): VePromise => { - const cacheKey = this.apiSvc.makeCacheKey(reqOb, '_hidden_' + reqOb.username + '_ve_settings', false) - const cached = this.cacheSvc.get(cacheKey) + const cacheKey = this.apiSvc.makeCacheKey(reqOb, '_hidden_' + reqOb.username + '_ve_settings', false); + const cached = this.cacheSvc.get(cacheKey); if (cached && !refresh) { - return this.$q.resolve(cached) + return this.$q.resolve(cached); } return new this.$q((resolve, reject) => { this.elementSvc @@ -110,18 +110,18 @@ export class ApplicationService { }, ], }) - .then(resolve, reject) - } else resolve(result) - }, reject) - }) - } + .then(resolve, reject); + } else resolve(result); + }, reject); + }); + }; public updateUserSettings = ( reqOb: UsersRequest, settingsOb: UserSettingsObject ): VePromise => { - return this.elementSvc.updateElement(settingsOb) - } + return this.elementSvc.updateElement(settingsOb); + }; public getSettings = ( projectId: string, @@ -129,11 +129,11 @@ export class ApplicationService { refresh?: boolean, weight?: number ): VePromise => { - if (!refId) refId = 'master' - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '_hidden_' + projectId + '_settings', false) - const cached = this.cacheSvc.get(cacheKey) + if (!refId) refId = 'master'; + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '_hidden_' + projectId + '_settings', false); + const cached = this.cacheSvc.get(cacheKey); if (cached && !refresh) { - return this.$q.resolve(cached) + return this.$q.resolve(cached); } return new this.$q((resolve, reject) => { this.elementSvc @@ -149,11 +149,11 @@ export class ApplicationService { ) .then((result) => { if (result === null) { - this.createSettings(projectId, refId, null).then(resolve, reject) - } else resolve(result) - }, reject) - }) - } + this.createSettings(projectId, refId, null).then(resolve, reject); + } else resolve(result); + }, reject); + }); + }; public createSettings = ( projectId: string, @@ -167,21 +167,21 @@ export class ApplicationService { _projectId: projectId, _refId: refId, type: 'Class', - } + }; } return this.elementSvc.createElement({ elementId: '_hidden_' + projectId + '_settings', projectId, refId, elements: [settingsOb], - }) - } + }); + }; addPins(username: string, projectId: string, refId: string, pinned: string[]): VePromise { return new this.$q((resolve, reject) => { this.getUserSettings({ username, projectId, refId }).then((result) => { if (result.pinned) { - pinned = [...new Set([...result.pinned, ...pinned])] + pinned = [...new Set([...result.pinned, ...pinned])]; } this.elementSvc .updateElement({ @@ -190,9 +190,9 @@ export class ApplicationService { _projectId: result._projectId, pinned, }) - .then(resolve, reject) - }, reject) - }) + .then(resolve, reject); + }, reject); + }); } removePins(username: string, projectId: string, refId: string, unpinned: string[]): VePromise { @@ -200,8 +200,8 @@ export class ApplicationService { this.getUserSettings({ username, projectId, refId }).then((response) => { if (response.pinned) { const pinned = response.pinned.filter((pin) => { - return unpinned.includes(pin) - }) + return unpinned.includes(pin); + }); this.elementSvc .updateElement({ id: response.id, @@ -209,11 +209,11 @@ export class ApplicationService { _projectId: response._projectId, pinned, }) - .then(resolve, reject) - } else resolve(response) - }, reject) - }) + .then(resolve, reject); + } else resolve(response); + }, reject); + }); } } -veUtils.service('ApplicationService', ApplicationService) +veUtils.service('ApplicationService', ApplicationService); diff --git a/src/ve-utils/application/Branding.service.ts b/src/ve-utils/application/Branding.service.ts index c03c0985a..4efb954c7 100644 --- a/src/ve-utils/application/Branding.service.ts +++ b/src/ve-utils/application/Branding.service.ts @@ -1,16 +1,16 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { VeConfig } from '@ve-types/config' -import { ParamsObject, ProjectsResponse } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { VeConfig } from '@ve-types/config'; +import { ParamsObject, ProjectsResponse } from '@ve-types/mms'; export interface BrandingStyle { - labels?: string[] | string[][] - message?: string | string[] - separator?: string - background?: string - color?: string - disabled: boolean + labels?: string[] | string[][]; + message?: string | string[]; + separator?: string; + background?: string; + color?: string; + disabled: boolean; } // export interface BannerStyle extends BrandingStyle { @@ -24,30 +24,30 @@ export interface BrandingStyle { * * Branding Service */ export class BrandingService { - public labels: { [key: string]: string } - private defaultSeparator: string = ' - ' + public labels: { [key: string]: string }; + private defaultSeparator: string = ' - '; private defaultLabels: { [key: string]: string } = { pi: 'PROPRIETARY: Proprietary Information', export_ctrl: 'EXPORT WARNING: No export controlled documents allowed on this server', no_public_release: 'Not for Public Release or Redistribution', unclassified: 'CLASSIFICATION: This system is UNCLASSIFIED', opensource: 'OpenMBEE View Editor | Licensed under Apache 2.0', - } + }; loginBanner: BrandingStyle = { labels: ['opensource', 'unclassified'], disabled: false, - } - config: VeConfig = window.__env + }; + config: VeConfig = window.__env; banner: BrandingStyle = { labels: ['pi'], background: '#0D47A1', color: '#e8e8e8', disabled: false, - } + }; footer: BrandingStyle = { labels: ['pi', 'no_public_release'], disabled: false, - } + }; loginWarning: BrandingStyle = { disabled: false, message: [ @@ -58,81 +58,81 @@ export class BrandingService { 'If you are not authorized to access this system, disconnect now. Users of this system have no expectation', 'of privacy. By continuing, you consent to your keystrokes and data content being monitored.', ], - } - static $inject = ['$q'] + }; + static $inject = ['$q']; constructor(private $q: VeQService) { if (this.config.customLabels) { - this.labels = Object.assign(this.defaultLabels, this.config.customLabels) + this.labels = Object.assign(this.defaultLabels, this.config.customLabels); } if (this.config.banner) { - this.banner = Object.assign(this.banner, this.config.banner) + this.banner = Object.assign(this.banner, this.config.banner); } - this.createMessage(this.banner) + this.createMessage(this.banner); if (this.config.loginBanner) { - this.loginBanner = Object.assign(this.loginBanner, this.config.loginBanner) + this.loginBanner = Object.assign(this.loginBanner, this.config.loginBanner); } - this.createMessage(this.loginBanner) + this.createMessage(this.loginBanner); if (this.config.footer) { - this.footer = Object.assign(this.footer, this.config.footer) + this.footer = Object.assign(this.footer, this.config.footer); } - this.createMessage(this.footer) + this.createMessage(this.footer); if (this.config.loginWarning) { - this.loginWarning = Object.assign(this.loginWarning, this.config.loginWarning) + this.loginWarning = Object.assign(this.loginWarning, this.config.loginWarning); } - this.createMessage(this.loginWarning) + this.createMessage(this.loginWarning); } public createMessage = (brandingStyle: BrandingStyle): void => { if (brandingStyle.labels) { - const separator: string = brandingStyle.separator ? brandingStyle.separator : this.defaultSeparator - brandingStyle.message = [] + const separator: string = brandingStyle.separator ? brandingStyle.separator : this.defaultSeparator; + brandingStyle.message = []; if (Array.isArray(brandingStyle.labels[0])) { for (const line of brandingStyle.labels) { if (Array.isArray(line)) { - brandingStyle.message.push(this._getMessage(line, separator)) + brandingStyle.message.push(this._getMessage(line, separator)); } } } else { - brandingStyle.message.push(this._getMessage(brandingStyle.labels as string[], separator)) + brandingStyle.message.push(this._getMessage(brandingStyle.labels as string[], separator)); } } - } + }; private _getMessage = (labels: string[], separator?: string): string => { - let msg = '' + let msg = ''; for (const [labelNum, label] of labels.entries()) { - msg += this._getLabel(label) + msg += this._getLabel(label); if (labelNum < labels.length - 1) { - msg += separator + msg += separator; } } - return msg - } + return msg; + }; private _getLabel = (labelName: string): string => { - let msg = '' + let msg = ''; if (this.labels.hasOwnProperty(labelName)) { - msg = this.labels[labelName] + msg = this.labels[labelName]; } else { - msg = 'Missing Label' + msg = 'Missing Label'; } - return msg - } + return msg; + }; getBanner(params?: ParamsObject): VePromise { - return this.$q.resolve(this.banner) + return this.$q.resolve(this.banner); } getLoginBanner(): VePromise { - return this.$q.resolve(this.loginBanner) + return this.$q.resolve(this.loginBanner); } getFooter(params?: ParamsObject): VePromise { - return this.$q.resolve(this.footer) + return this.$q.resolve(this.footer); } } -veUtils.service('BrandingService', BrandingService) +veUtils.service('BrandingService', BrandingService); diff --git a/src/ve-utils/application/Image.service.ts b/src/ve-utils/application/Image.service.ts index fdd369270..9d7830738 100644 --- a/src/ve-utils/application/Image.service.ts +++ b/src/ve-utils/application/Image.service.ts @@ -1,51 +1,51 @@ -import { AuthService } from '@ve-utils/mms-api-client' +import { AuthService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VeConfig } from '@ve-types/config' +import { VeConfig } from '@ve-types/config'; export class ImageService { - public veConfig: VeConfig = window.__env + public veConfig: VeConfig = window.__env; - static $inject = ['AuthService'] + static $inject = ['AuthService']; constructor(private authSvc: AuthService) {} public fixImgSrc(imgDom: JQuery): void { - let src = imgDom.attr('src') + let src = imgDom.attr('src'); if (src) { if (src) { if (src.indexOf('http') < 0) { - src = this.veConfig.apiUrl + src + src = this.veConfig.apiUrl + src; } - imgDom.attr('src', src + '?token=' + this.authSvc.getToken()) + imgDom.attr('src', src + '?token=' + this.authSvc.getToken()); } if (imgDom.width() < 860) { //keep image relative centered with text if less than 9 in - return + return; } - const parent = imgDom.parent('p') + const parent = imgDom.parent('p'); if (parent.length > 0) { if (parent.css('text-align') == 'center' || parent.hasClass('image-center')) { - imgDom.addClass('image-center') + imgDom.addClass('image-center'); } - imgDom.unwrap() //note this removes parent p and puts img and any of its siblings in its place + imgDom.unwrap(); //note this removes parent p and puts img and any of its siblings in its place } } } public fixImgUrl = (src: string, addToken?: boolean): string => { - const url = new window.URL(src) - const params = new window.URLSearchParams(url.search) + const url = new window.URL(src); + const params = new window.URLSearchParams(url.search); if (params.has('token')) { - params.delete('token') + params.delete('token'); } if (addToken) { - params.append('token', this.authSvc.getToken()) + params.append('token', this.authSvc.getToken()); } - url.search = params.toString() - return url.toString() - } + url.search = params.toString(); + return url.toString(); + }; } -veUtils.service('ImageService', ImageService) +veUtils.service('ImageService', ImageService); diff --git a/src/ve-utils/application/RootScope.service.ts b/src/ve-utils/application/RootScope.service.ts index 19506758a..f3aaef00f 100644 --- a/src/ve-utils/application/RootScope.service.ts +++ b/src/ve-utils/application/RootScope.service.ts @@ -1,10 +1,10 @@ -import { StateDeclaration } from '@uirouter/core/lib/state/interface' +import { StateDeclaration } from '@uirouter/core/lib/state/interface'; -import { SessionService } from '@ve-utils/core' +import { SessionService } from '@ve-utils/core'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { ParamsObject } from '@ve-types/mms' +import { ParamsObject } from '@ve-types/mms'; export class RootScopeService { public constants = { @@ -32,115 +32,115 @@ export class RootScopeService { TREEINITIALSELECTION: 'tree-initialSelection', TREEICONS: 'tree-icons', LEFTPANECLOSED: 'tree-pane-closed', - } + }; - static $inject = ['SessionService'] + static $inject = ['SessionService']; constructor(private sessionSvc: SessionService) {} init(): void { - this.loginModalOpen() - this.rightPaneToggleable() - this.rightPaneClosed() - this.veTitle() - this.veShowLogin() - this.veStateChanging() - this.veViewContentLoading() - this.veRedirect() - this.veRedirectFromOld() - this.veCrushUrl() - this.veFullDocMode() - this.veCommentsOn() - - this.veNumberingOn() - this.veElementsOn() - this.veEditMode() - this.veHidePanes() - this.veHideLeft() - this.veHideRight() + this.loginModalOpen(); + this.rightPaneToggleable(); + this.rightPaneClosed(); + this.veTitle(); + this.veShowLogin(); + this.veStateChanging(); + this.veViewContentLoading(); + this.veRedirect(); + this.veRedirectFromOld(); + this.veCrushUrl(); + this.veFullDocMode(); + this.veCommentsOn(); + + this.veNumberingOn(); + this.veElementsOn(); + this.veEditMode(); + this.veHidePanes(); + this.veHideLeft(); + this.veHideRight(); } loginModalOpen(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.LOGINMODALOPEN, value, false) + return this.sessionSvc.accessor(this.constants.LOGINMODALOPEN, value, false); } rightPaneToggleable(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.RIGHTPANETOGGLEABLE, value, true) + return this.sessionSvc.accessor(this.constants.RIGHTPANETOGGLEABLE, value, true); } rightPaneClosed(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.RIGHTPANECLOSED, value, false) + return this.sessionSvc.accessor(this.constants.RIGHTPANECLOSED, value, false); } veWarningOk(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEWARNINGOK, value, false) + return this.sessionSvc.accessor(this.constants.VEWARNINGOK, value, false); } veTitle(value?: string | undefined): string { - return this.sessionSvc.accessor(this.constants.VETITLE, value, 'View Editor') + return this.sessionSvc.accessor(this.constants.VETITLE, value, 'View Editor'); } veStateChanging(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VESTATECHANGING, value, false) + return this.sessionSvc.accessor(this.constants.VESTATECHANGING, value, false); } veViewContentLoading(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEVIEWCONTENTLOADING, value, false) + return this.sessionSvc.accessor(this.constants.VEVIEWCONTENTLOADING, value, false); } veRedirect( value?: { toState: StateDeclaration; toParams: ParamsObject } | undefined ): { toState: StateDeclaration; toParams: ParamsObject } | undefined { - return this.sessionSvc.accessor(this.constants.VEREDIRECT, value, null) + return this.sessionSvc.accessor(this.constants.VEREDIRECT, value, null); } veRedirectFromOld(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEREDIRECTFROMOLD, value, false) + return this.sessionSvc.accessor(this.constants.VEREDIRECTFROMOLD, value, false); } veCrushUrl(value?: string | undefined): string { - return this.sessionSvc.accessor(this.constants.VECRUSHURL, value, null) + return this.sessionSvc.accessor(this.constants.VECRUSHURL, value, null); } veFullDocMode(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEFULLDOCMODE, value, false) + return this.sessionSvc.accessor(this.constants.VEFULLDOCMODE, value, false); } veCommentsOn(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VECOMMENTSON, value, false) + return this.sessionSvc.accessor(this.constants.VECOMMENTSON, value, false); } veNumberingOn(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VENUMBERINGON, value, true) + return this.sessionSvc.accessor(this.constants.VENUMBERINGON, value, true); } veElementsOn(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEELEMENTSON, value, false) + return this.sessionSvc.accessor(this.constants.VEELEMENTSON, value, false); } veEditMode(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEEDITMODE, value, false) + return this.sessionSvc.accessor(this.constants.VEEDITMODE, value, false); } veHidePanes(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEHIDEPANES, value, false) + return this.sessionSvc.accessor(this.constants.VEHIDEPANES, value, false); } veHideLeft(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEHIDELEFT, value, false) + return this.sessionSvc.accessor(this.constants.VEHIDELEFT, value, false); } veHideRight(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VEHIDERIGHT, value, false) + return this.sessionSvc.accessor(this.constants.VEHIDERIGHT, value, false); } veShowLogin(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.VESHOWLOGIN, value, false) + return this.sessionSvc.accessor(this.constants.VESHOWLOGIN, value, false); } leftPaneClosed(value?: boolean | undefined): boolean { - return this.sessionSvc.accessor(this.constants.LEFTPANECLOSED, value, false) + return this.sessionSvc.accessor(this.constants.LEFTPANECLOSED, value, false); } } -veUtils.service('RootScopeService', RootScopeService) +veUtils.service('RootScopeService', RootScopeService); diff --git a/src/ve-utils/application/ShortUrl.service.ts b/src/ve-utils/application/ShortUrl.service.ts index cf4054aec..1a627ef9a 100644 --- a/src/ve-utils/application/ShortUrl.service.ts +++ b/src/ve-utils/application/ShortUrl.service.ts @@ -1,19 +1,19 @@ -import { ApplicationService } from '@ve-utils/application/Application.service' -import { ElementService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client' +import { ApplicationService } from '@ve-utils/application/Application.service'; +import { ElementService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { ParamsObject, ShortUrlRequest } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { ParamsObject, ShortUrlRequest } from '@ve-types/mms'; export class ShortUrlService { public dynamicPopover: { - templateUrl: string - title: string + templateUrl: string; + title: string; } = { templateUrl: 'shareUrlTemplate.html', title: 'Link', - } + }; static $inject = [ '$q', @@ -24,7 +24,7 @@ export class ShortUrlService { 'ViewService', 'ElementService', 'ApplicationService', - ] + ]; constructor( private $q: VeQService, @@ -38,100 +38,100 @@ export class ShortUrlService { ) {} decodeShortUrl(urlFragment: string): VePromise { - const deferred = this.$q.defer() - const urlParts: string[] = urlFragment.split('-') + const deferred = this.$q.defer(); + const urlParts: string[] = urlFragment.split('-'); const _urlError = (defer?: angular.IDeferred): void => { - if (defer) defer.reject() - else deferred.reject('Error Decoding URL') - } + if (defer) defer.reject(); + else deferred.reject('Error Decoding URL'); + }; const result: ParamsObject = { projectId: urlParts[1], refId: urlParts[2], documentId: urlParts[3] && urlParts[3] === 'cover' ? null : urlParts[3], viewId: urlParts[4], - } - let orgId: string = urlParts[0] - const promises: VePromise[] = [] + }; + let orgId: string = urlParts[0]; + const promises: VePromise[] = []; // eslint-disable-next-line prefer-const if (orgId) { - const deferOrg = this.$q.defer() - promises.push(deferOrg.promise) + const deferOrg = this.$q.defer(); + promises.push(deferOrg.promise); this.projectSvc.getOrgs().then( (data) => { const org = data.filter((o) => { - return o.id.endsWith(orgId) - }) + return o.id.endsWith(orgId); + }); if (org.length > 0) { - orgId = org[0].id - deferOrg.resolve() + orgId = org[0].id; + deferOrg.resolve(); } else { - _urlError(deferOrg) + _urlError(deferOrg); } }, () => { - _urlError(deferOrg) + _urlError(deferOrg); } - ) + ); if (result.projectId) { - const deferProj = this.$q.defer() - promises.push(deferProj.promise) + const deferProj = this.$q.defer(); + promises.push(deferProj.promise); deferOrg.promise.then( () => { this.projectSvc.getProjects(orgId).then( (data) => { const proj = data.filter((p) => { - return p.id.endsWith(result.projectId) - }) + return p.id.endsWith(result.projectId); + }); if (proj.length > 0) { - result.projectId = proj[0].id - deferProj.resolve() + result.projectId = proj[0].id; + deferProj.resolve(); } else { - _urlError(deferProj) + _urlError(deferProj); } }, () => { - _urlError(deferProj) + _urlError(deferProj); } - ) + ); }, () => { - _urlError(deferProj) + _urlError(deferProj); } - ) + ); if (result.refId) { - const deferRef = this.$q.defer() - promises.push(deferRef.promise) + const deferRef = this.$q.defer(); + promises.push(deferRef.promise); deferProj.promise.then( () => { this.projectSvc.getRefs(result.projectId).then( (data) => { const refOb = data.filter((r) => { - return result.refId === 'm' ? r.id === 'master' : r.id.endsWith(result.refId) - }) + return result.refId === 'm' ? r.id === 'master' : r.id.endsWith(result.refId); + }); if (refOb.length > 0) { - result.refId = refOb[0].id - deferRef.resolve() + result.refId = refOb[0].id; + deferRef.resolve(); } else { - _urlError(deferRef) + _urlError(deferRef); } }, () => { - _urlError(deferRef) + _urlError(deferRef); } - ) + ); }, () => { - _urlError(deferRef) + _urlError(deferRef); } - ) + ); if (result.documentId) { if (result.viewId && result.viewId === 'cover') { - result.documentId = result.documentId + '_cover' + result.documentId = result.documentId + '_cover'; } - const deferDoc = this.$q.defer() - promises.push(deferDoc.promise) + const deferDoc = this.$q.defer(); + promises.push(deferDoc.promise); deferRef.promise.then( () => { this.viewSvc @@ -142,27 +142,27 @@ export class ShortUrlService { .then( (data) => { const doc = data.filter((d) => { - return d.id.endsWith(result.documentId) - }) + return d.id.endsWith(result.documentId); + }); if (doc.length > 0) { - result.documentId = doc[0].id - deferDoc.resolve() + result.documentId = doc[0].id; + deferDoc.resolve(); } else { - _urlError(deferDoc) + _urlError(deferDoc); } }, () => { - _urlError(deferDoc) + _urlError(deferDoc); } - ) + ); }, () => { - _urlError(deferDoc) + _urlError(deferDoc); } - ) + ); if (result.viewId && result.viewId !== 'cover') { - const deferView = this.$q.defer() - promises.push(deferView.promise) + const deferView = this.$q.defer(); + promises.push(deferView.promise); deferDoc.promise.then( () => { this.viewSvc @@ -173,24 +173,24 @@ export class ShortUrlService { .then( (data) => { const view = data.filter((v) => { - return v.id.endsWith(result.viewId) - }) + return v.id.endsWith(result.viewId); + }); if (view.length > 0) { - result.viewId = view[0].id - deferView.resolve() + result.viewId = view[0].id; + deferView.resolve(); } else { - _urlError(deferView) + _urlError(deferView); } }, () => { - _urlError(deferView) + _urlError(deferView); } - ) + ); }, () => { - _urlError(deferView) + _urlError(deferView); } - ) + ); } } } @@ -198,57 +198,57 @@ export class ShortUrlService { this.$q.all(promises).then( () => deferred.resolve(result), () => { - _urlError() + _urlError(); } - ) + ); } else { - _urlError() + _urlError(); } - return deferred.promise + return deferred.promise; } public getShortUrl = (paramOb: ShortUrlRequest): string => { - const ids: string[] = [] - const sOId = paramOb.orgId.split(/[-_]+/) - ids.push(sOId[sOId.length - 1]) + const ids: string[] = []; + const sOId = paramOb.orgId.split(/[-_]+/); + ids.push(sOId[sOId.length - 1]); if (paramOb.projectId && paramOb.projectId !== '') { - const sPId = paramOb.projectId.split(/[-_]+/) - ids.push(sPId[sPId.length - 1]) + const sPId = paramOb.projectId.split(/[-_]+/); + ids.push(sPId[sPId.length - 1]); if (paramOb.refId && paramOb.refId !== '') { if (paramOb.refId === 'master') { - ids.push('m') + ids.push('m'); } else { - const sRId = paramOb.refId.split(/[-_]+/) - ids.push(sRId[sRId.length - 1]) + const sRId = paramOb.refId.split(/[-_]+/); + ids.push(sRId[sRId.length - 1]); } if (paramOb.documentId && paramOb.documentId !== '') { - const sDId = paramOb.documentId.split(/[-_]+/) + const sDId = paramOb.documentId.split(/[-_]+/); if (paramOb.documentId.endsWith('_cover')) { if (paramOb.documentId.startsWith('site_')) { - ids.push(sDId[sDId.length - 2]) + ids.push(sDId[sDId.length - 2]); } - ids.push('cover') + ids.push('cover'); } else { - ids.push(sDId[sDId.length - 1]) + ids.push(sDId[sDId.length - 1]); } if (paramOb.viewId && paramOb.documentId !== '') { - const sVId = paramOb.viewId.split(/[-_]+/) - ids.push(sVId[sVId.length - 1]) + const sVId = paramOb.viewId.split(/[-_]+/); + ids.push(sVId[sVId.length - 1]); } } } } - const rootUrl = this.$location.absUrl().split('#')[0] - let fragment = ids.join('-') - fragment = fragment.endsWith('-') ? fragment.substring(0, fragment.length - 1) : fragment - return `${rootUrl}#/s/${fragment}` - } + const rootUrl = this.$location.absUrl().split('#')[0]; + let fragment = ids.join('-'); + fragment = fragment.endsWith('-') ? fragment.substring(0, fragment.length - 1) : fragment; + return `${rootUrl}#/s/${fragment}`; + }; public copyToClipboard(target: JQuery, $event: JQuery.ClickEvent): VePromise { - const shortUrlEl = target.find('#ve-short-url') - return this.applicationSvc.copyToClipboard(shortUrlEl, $event) + const shortUrlEl = target.find('#ve-short-url'); + return this.applicationSvc.copyToClipboard(shortUrlEl, $event); } } -veUtils.service('ShortUrlService', ShortUrlService) +veUtils.service('ShortUrlService', ShortUrlService); diff --git a/src/ve-utils/application/Utils.service.ts b/src/ve-utils/application/Utils.service.ts index 3675f14e0..503145755 100644 --- a/src/ve-utils/application/Utils.service.ts +++ b/src/ve-utils/application/Utils.service.ts @@ -1,20 +1,20 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { ApiService, DocumentMetadata, URLService } from '@ve-utils/mms-api-client' +import { ApiService, DocumentMetadata, URLService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { ElementObject, ViewObject } from '@ve-types/mms' -import { TreeBranch } from '@ve-types/tree' +import { VePromise, VeQService } from '@ve-types/angular'; +import { ElementObject, ViewObject } from '@ve-types/mms'; +import { TreeBranch } from '@ve-types/tree'; export interface TOCHtmlObject { - equations: string - tables: string - figures: string - tableCount: number - equationCount: number - figureCount: number + equations: string; + tables: string; + figures: string; + tableCount: number; + equationCount: number; + figureCount: number; } /** @@ -27,7 +27,7 @@ export interface TOCHtmlObject { * * Utilities */ export class UtilsService { - static $inject = ['$q', '$http', 'URLService', 'ApiService'] + static $inject = ['$q', '$http', 'URLService', 'ApiService']; constructor( private $q: VeQService, @@ -44,11 +44,11 @@ export class UtilsService { * @returns {string} toc string */ public makeHtmlTOC = (rootBranch: TreeBranch): string => { - let result = '

    Table of Contents

    ' - result += this.makeHtmlTOCChild(rootBranch, true) - result += '
    ' - return result - } + let result = '

    Table of Contents

    '; + result += this.makeHtmlTOCChild(rootBranch, true); + result += '
    '; + return result; + }; /** * @name veUtils/UtilsService#makeHtmlTOCChild @@ -58,30 +58,30 @@ export class UtilsService { * @return {string} */ public makeHtmlTOCChild = (branch: TreeBranch, skip?): string => { - let result = '' + let result = ''; if (!skip) { - const anchor: string = '' - result += `
  • ${anchor}${branch.data._veNumber} ${branch.data.name}` + const anchor: string = ''; + result += `
  • ${anchor}${branch.data._veNumber} ${branch.data.name}`; } - let ulAdded = false + let ulAdded = false; for (const child of branch.children) { if (child.type !== 'view' && child.type !== 'section') { - continue + continue; } if (!ulAdded) { - result += '
      ' - ulAdded = true + result += '
        '; + ulAdded = true; } - result += this.makeHtmlTOCChild(child) + result += this.makeHtmlTOCChild(child); } if (ulAdded) { - result += '
      ' + result += '
    '; } if (!skip) { - result += '
  • ' + result += ''; } - return result - } + return result; + }; /** * @name veUtils/UtilsService#makeTablesAndFiguresTOC @@ -108,27 +108,27 @@ export class UtilsService { tableCount: 0, figureCount: 0, equationCount: 0, - } + }; // If both "Generate List of Tables and Figures" && "Use HTML for List of Tables and Figures " options are checked... if (html) { - ob = this.generateTOCHtmlOption(ob, rootBranch, printElement) + ob = this.generateTOCHtmlOption(ob, rootBranch, printElement); // return obHTML; } else { for (let i = 0; i < rootBranch.children.length; i++) { - this.makeTablesAndFiguresTOCChild(rootBranch.children[i], printElement, ob, live, false) + this.makeTablesAndFiguresTOCChild(rootBranch.children[i], printElement, ob, live, false); } } ob.tables = ob.tables.length ? '

    List of Tables

      ' + ob.tables + '
    ' - : '' + : ''; ob.figures = ob.figures.length ? '

    List of Figures

      ' + ob.figures + '
    ' - : '' + : ''; ob.equations = ob.equations.length ? '

    List of Equations

      ' + ob.equations + '
    ' - : '' - return ob + : ''; + return ob; } /** @@ -149,153 +149,153 @@ export class UtilsService { live: boolean, showRefName: boolean ): void { - const pe = child.data - const sysmlId = pe.id - const veNumber = pe._veNumber - let prefix = '' - const el = printElement.find('#' + sysmlId) + const pe = child.data; + const sysmlId = pe.id; + const veNumber = pe._veNumber; + let prefix = ''; + const el = printElement.find('#' + sysmlId); const refs = printElement.find( 'mms-view-link[mms-pe-id="' + sysmlId + '"], mms-view-link[data-mms-pe-id="' + sysmlId + '"]' - ) - let cap = '' - let name = '' + ); + let cap = ''; + let name = ''; if (child.type === 'table') { - ob.tableCount++ - prefix = 'Table ' + veNumber + '. ' - const capTbl = el.find('table > caption') - name = capTbl.text() + ob.tableCount++; + prefix = 'Table ' + veNumber + '. '; + const capTbl = el.find('table > caption'); + name = capTbl.text(); if (name !== '' && name.indexOf('Table') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length) + name = name.substring(name.indexOf(prefix) + prefix.length); } else if (name === '') { - name = pe.name + name = pe.name; } - cap = veNumber + '. ' + name - ob.tables += '
  • ' + cap + '
  • ' - capTbl.html('Table ' + cap) + cap = veNumber + '. ' + name; + ob.tables += '
  • ' + cap + '
  • '; + capTbl.html('Table ' + cap); // If caption does not exist, add to html if (capTbl.length === 0) { - el.find('table').prepend('Table ' + cap + '') + el.find('table').prepend('Table ' + cap + ''); } // Change cap value based on showRefName true/false if (!showRefName) { - cap = veNumber + cap = veNumber; } if (!live) { - refs.find('a').attr('href', '#' + sysmlId) + refs.find('a').attr('href', '#' + sysmlId); } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Table ' + cap) + .html('Table ' + cap); } if (child.type === 'figure') { - ob.figureCount++ - prefix = 'Figure ' + veNumber + '. ' - const capFig = el.find('figure > figcaption') - name = capFig.text() + ob.figureCount++; + prefix = 'Figure ' + veNumber + '. '; + const capFig = el.find('figure > figcaption'); + name = capFig.text(); if (name !== '' && name.indexOf('Figure') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length) + name = name.substring(name.indexOf(prefix) + prefix.length); } else if (name === '') { - name = pe.name + name = pe.name; } - cap = veNumber + '. ' + name - ob.figures += '
  • ' + cap + '
  • ' - capFig.html('Figure ' + cap) + cap = veNumber + '. ' + name; + ob.figures += '
  • ' + cap + '
  • '; + capFig.html('Figure ' + cap); // If caption does not exist, add to html if (capFig.length === 0) { el.find('img') .wrap('
    ') - .after('
    Figure ' + cap + '
    ') + .after('
    Figure ' + cap + '
    '); } // Change cap value based on showRefName true/false if (!showRefName) { - cap = veNumber + cap = veNumber; } if (!live) { - refs.find('a').attr('href', '#' + sysmlId) + refs.find('a').attr('href', '#' + sysmlId); } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Fig. ' + cap) + .html('Fig. ' + cap); } if (child.type === 'equation') { - ob.equationCount++ - cap = veNumber + '. ' + pe.name - ob.equations += '
  • ' + cap + '
  • ' - const equationCap = '(' + veNumber + ')' - const capEq = el.find('.caption-type-equation') - capEq.html(equationCap) + ob.equationCount++; + cap = veNumber + '. ' + pe.name; + ob.equations += '
  • ' + cap + '
  • '; + const equationCap = '(' + veNumber + ')'; + const capEq = el.find('.caption-type-equation'); + capEq.html(equationCap); // If caption does not exist, add to html if (capEq.length === 0) { el.find('present-equation > transclude > transclude-doc > p') .last() - .append('' + equationCap + '') + .append('' + equationCap + ''); } if (!live) { - refs.find('a').attr('href', '#' + sysmlId) + refs.find('a').attr('href', '#' + sysmlId); } refs.filter('[suppress-numbering!="true"]') .filter(':not([link-text])') .find('a') - .html('Eq. ' + equationCap) + .html('Eq. ' + equationCap); } for (let i = 0; i < child.children.length; i++) { - this.makeTablesAndFiguresTOCChild(child.children[i], printElement, ob, live, showRefName) + this.makeTablesAndFiguresTOCChild(child.children[i], printElement, ob, live, showRefName); } } public addLiveNumbering(pe: ViewObject, el: JQuery, type: string): void { - const veNumber = pe._veNumber + const veNumber = pe._veNumber; if (!veNumber) { - return + return; } - let prefix = '' - let name = '' - let cap = '' + let prefix = ''; + let name = ''; + let cap = ''; if (type === 'table') { - prefix = 'Table ' + veNumber + '. ' - const capTbl = el.find('table > caption') - name = capTbl.text() + prefix = 'Table ' + veNumber + '. '; + const capTbl = el.find('table > caption'); + name = capTbl.text(); if (name !== '' && name.indexOf('Table') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length) + name = name.substring(name.indexOf(prefix) + prefix.length); } else if (name === '') { - name = pe.name + name = pe.name; } - cap = veNumber + '. ' + name - capTbl.html('Table ' + cap) + cap = veNumber + '. ' + name; + capTbl.html('Table ' + cap); // If caption does not exist, add to html if (capTbl.length === 0) { - el.find('table').prepend('Table ' + cap + '') + el.find('table').prepend('Table ' + cap + ''); } } if (type === 'figure') { - prefix = 'Figure ' + veNumber + '. ' - const capFig = el.find('figure > figcaption') - name = capFig.text() + prefix = 'Figure ' + veNumber + '. '; + const capFig = el.find('figure > figcaption'); + name = capFig.text(); if (name !== '' && name.indexOf('Figure') === 0 && name.split('. ').length > 0) { - name = name.substring(name.indexOf(prefix) + prefix.length) + name = name.substring(name.indexOf(prefix) + prefix.length); } else if (name === '') { - name = pe.name + name = pe.name; } - cap = veNumber + '. ' + name - capFig.html('Figure ' + cap) + cap = veNumber + '. ' + name; + capFig.html('Figure ' + cap); // If caption does not exist, add to html if (capFig.length === 0) { el.find('img') .wrap('
    ') - .after('
    Figure ' + cap + '
    ') + .after('
    Figure ' + cap + '
    '); } } if (type === 'equation') { - const equationCap = '(' + veNumber + ')' - const capEq = el.find('.caption-type-equation') - capEq.html(equationCap) + const equationCap = '(' + veNumber + ')'; + const capEq = el.find('.caption-type-equation'); + capEq.html(equationCap); // If caption does not exist, add to html if (capEq.length === 0) { el.find('present-equation > mms-cf > transclude-doc > p') .last() - .append('' + equationCap + '') + .append('' + equationCap + ''); } } } @@ -308,8 +308,8 @@ export class UtilsService { * @returns {string} unique ID wit prefix, tbl_ or fig_ */ public generateAnchorId = (prefix: string): string => { - return `${prefix}${this.apiSvc.createUniqueId()}` - } + return `${prefix}${this.apiSvc.createUniqueId()}`; + }; /** * @name veUtils/UtilsService#generateTOCHtmlOption @@ -327,52 +327,52 @@ export class UtilsService { ): TOCHtmlObject { // Grab all existing tables and figures inside the center pane, and assign them to tables and figures const tables = printElement.find('table'), - figures = printElement.find('figure') + figures = printElement.find('figure'); // equations = printElement.find('.math-tex'); let anchorId = '', thisCap = '', tblCap: JQuery, tbl: JQuery, - fig: JQuery + fig: JQuery; - ob.tableCount = tables.length - ob.figureCount = figures.length + ob.tableCount = tables.length; + ob.figureCount = figures.length; // Tables for (let j = 0; j < tables.length; j++) { - tbl = $(tables[j]) - tblCap = $('caption', tbl) + tbl = $(tables[j]); + tblCap = $('caption', tbl); // Set the link from the List of Tables to the actual tables - anchorId = this.generateAnchorId('tbl_') - tbl.attr('id', anchorId) + anchorId = this.generateAnchorId('tbl_'); + tbl.attr('id', anchorId); // Append li to the List of Tables - thisCap = tblCap && tblCap.text() !== '' ? `${j + 1}. ${tblCap.text()}` : `${j + 1}. ` - ob.tables += '
  • ' + thisCap + '
  • ' + thisCap = tblCap && tblCap.text() !== '' ? `${j + 1}. ${tblCap.text()}` : `${j + 1}. `; + ob.tables += '
  • ' + thisCap + '
  • '; // If no caption exists, add empty caption for numbering if (tblCap.length === 0) { - tbl.prepend(' ') + tbl.prepend(' '); } } // Figures for (let j = 0; j < figures.length; j++) { - fig = $(figures[j]) - const figcap = $('figcaption', fig) + fig = $(figures[j]); + const figcap = $('figcaption', fig); // Set the link from the List of Tables to the actual tables - anchorId = this.generateAnchorId('fig_') - fig.attr('id', anchorId) + anchorId = this.generateAnchorId('fig_'); + fig.attr('id', anchorId); // Append li to the List of Figures - thisCap = figcap && figcap.text() !== '' ? `${j + 1}. ${figcap.text()}` : `${j + 1}` - ob.figures += '
  • ' + thisCap + '
  • ' + thisCap = figcap && figcap.text() !== '' ? `${j + 1}. ${figcap.text()}` : `${j + 1}`; + ob.figures += '
  • ' + thisCap + '
  • '; // If no caption exists, add empty caption for numbering if (figcap.length === 0) { - fig.append('
     
    ') + fig.append('
     
    '); } } @@ -391,7 +391,7 @@ export class UtilsService { // eq.append(' '); // } // } - return ob + return ob; } /** @@ -403,17 +403,17 @@ export class UtilsService { */ public convertViewLinks(printElement: JQuery): void { printElement.find('mms-view-link').each((index) => { - const $this = $(this) - let elementId = $this.attr('mms-element-id') || $this.attr('data-mms-element-id') + const $this = $(this); + let elementId = $this.attr('mms-element-id') || $this.attr('data-mms-element-id'); if (!elementId) { - return + return; } - elementId = elementId.replace(/[^\w\-]/gi, '') - const isElementInDoc = printElement.find('#' + elementId) + elementId = elementId.replace(/[^\w\-]/gi, ''); + const isElementInDoc = printElement.find('#' + elementId); if (isElementInDoc.length) { - $this.find('a').attr('href', '#' + elementId) + $this.find('a').attr('href', '#' + elementId); } - }) + }); } /** @@ -531,10 +531,10 @@ p, div {widows: 2; orphans: 2;} /*------------------------------------------------------------------ 8. Signature Box -` +`; for (let i = 1; i < 10; i++) { ret += `.h${i} {bookmark-level: ${i};} -` +`; } if (htmlFlag) { ret += ` @@ -543,27 +543,27 @@ figure { counter-increment: figure-counter; } figcaption::before {content: "Figure " counter(figure-counter) ". "; } table { counter-increment: table-counter; } caption::before {content: "Table " counter(table-counter) ". "; } -` +`; } if (meta) { Object.keys(meta).forEach((key) => { if (meta[key]) { - let content: string + let content: string; if (meta[key] === 'counter(page)') { - content = meta[key] as string + content = meta[key] as string; } else { - content = `"${(meta[key] as string | number).toString()}"` + content = `"${(meta[key] as string | number).toString()}"`; } ret += `@page {@${key} {font-size: 9px; content: ${content};}} -` +`; } - }) + }); } if (landscape) { - ret += '@page {size: 11in 8.5in;}' + ret += '@page {size: 11in 8.5in;}'; } - return ret - } + return ret; + }; /** * @name veUtils/UtilsService#exportHtmlAs @@ -576,25 +576,25 @@ caption::before {content: "Table " counter(table-counter) ". "; } public exportHtmlAs( exportType: number, data: { - htmlString: string - name: string - projectId: string - refId: string - css: string + htmlString: string; + name: string; + projectId: string; + refId: string; + css: string; } ): VePromise { - let accept: string + let accept: string; switch (exportType) { case 2: - accept = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - break + accept = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; + break; case 3: - accept = 'application/pdf' - break + accept = 'application/pdf'; + break; default: - accept = 'application/pdf' + accept = 'application/pdf'; } - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.$http .post( this.uRLSvc.getExportHtmlUrl(), @@ -609,31 +609,31 @@ caption::before {content: "Table " counter(table-counter) ". "; } ) .then( (data2) => { - const blob = new Blob([data2.data as BlobPart], { type: accept }) - const a = window.document.createElement('a') - const url = window.URL.createObjectURL(blob) - a.href = url - a.download = data.name + (exportType == 2 ? '.docx' : '.pdf') - a.click() - window.URL.revokeObjectURL(url) - deferred.resolve('ok') + const blob = new Blob([data2.data as BlobPart], { type: accept }); + const a = window.document.createElement('a'); + const url = window.URL.createObjectURL(blob); + a.href = url; + a.download = data.name + (exportType == 2 ? '.docx' : '.pdf'); + a.click(); + window.URL.revokeObjectURL(url); + deferred.resolve('ok'); }, (error: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(error)) + deferred.reject(this.uRLSvc.handleHttpStatus(error)); } - ) - return deferred.promise + ); + return deferred.promise; } public getElementTypeClass = (element: ElementObject, elementType: string): string => { - let elementTypeClass = '' + let elementTypeClass = ''; if (element.type === 'InstanceSpecification') { - elementTypeClass = 'pe-type-' + _.kebabCase(elementType) + elementTypeClass = 'pe-type-' + _.kebabCase(elementType); } else { - elementTypeClass = 'item-type-' + _.kebabCase(elementType) + elementTypeClass = 'item-type-' + _.kebabCase(elementType); } - return elementTypeClass - } + return elementTypeClass; + }; } -veUtils.service('UtilsService', UtilsService) +veUtils.service('UtilsService', UtilsService); diff --git a/src/ve-utils/application/index.ts b/src/ve-utils/application/index.ts index e19d6419d..b31dfe142 100644 --- a/src/ve-utils/application/index.ts +++ b/src/ve-utils/application/index.ts @@ -1,15 +1,15 @@ -import './RootScope.service' -import './Application.service' -import './Branding.service' -import './Math.service' -import './ShortUrl.service' -import './Utils.service' -import './Image.service' +import './RootScope.service'; +import './Application.service'; +import './Branding.service'; +import './Math.service'; +import './ShortUrl.service'; +import './Utils.service'; +import './Image.service'; -export * from './RootScope.service' -export * from './Application.service' -export * from './Branding.service' -export * from './Math.service' -export * from './ShortUrl.service' -export * from './Utils.service' -export * from './Image.service' +export * from './RootScope.service'; +export * from './Application.service'; +export * from './Branding.service'; +export * from './Math.service'; +export * from './ShortUrl.service'; +export * from './Utils.service'; +export * from './Image.service'; diff --git a/src/ve-utils/core/Cache.service.ts b/src/ve-utils/core/Cache.service.ts index 9333b8a99..9bd9d5fbc 100644 --- a/src/ve-utils/core/Cache.service.ts +++ b/src/ve-utils/core/Cache.service.ts @@ -1,40 +1,40 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { ElementObject, MmsObject } from '@ve-types/mms' +import { ElementObject, MmsObject } from '@ve-types/mms'; export class CacheService { - public cache: { [key: string]: string | unknown | unknown[] } = {} + public cache: { [key: string]: string | unknown | unknown[] } = {}; - static $inject = [] + static $inject = []; get(key: string | string[], noCopy?: boolean): T | undefined { - const realKey: string = this._makeKey(key) - const result: T = this._get(realKey) + const realKey: string = this._makeKey(key); + const result: T = this._get(realKey); - return result + return result; //else return _.cloneDeep(result) } private _get = (realKey: string): T => { const recurse = (key: string): string | T => { if (typeof this.cache[key] === 'string') { - return recurse(this.cache[key] as string) + return recurse(this.cache[key] as string); } - return this.cache[key] as T - } + return this.cache[key] as T; + }; if (this.cache.hasOwnProperty(realKey)) { - let result: T + let result: T; if (typeof this.cache[realKey] === 'string') { - result = recurse(this.cache[realKey] as string) as T + result = recurse(this.cache[realKey] as string) as T; } else { - result = this.cache[realKey] as T + result = this.cache[realKey] as T; } - return result + return result; } - return - } + return; + }; /** * @name CacheService#getElements @@ -45,10 +45,10 @@ export class CacheService { * @returns {Object} Value if found, empty array if not found */ getLatestElements(projectId: string, refId: string): T[] { - const latestElements: T[] = [] + const latestElements: T[] = []; for (const key in this.cache) { if (!this.cache.hasOwnProperty(key)) { - continue + continue; } if ( key.indexOf('|latest') >= 0 && @@ -58,13 +58,13 @@ export class CacheService { key.indexOf(refId) >= 0 && key.indexOf(projectId) >= 0 ) { - const val: T | T[] = this._get(key) + const val: T | T[] = this._get(key); if (val) { - Array.isArray(val) ? latestElements.push(...val) : latestElements.push(val) + Array.isArray(val) ? latestElements.push(...val) : latestElements.push(val); } } } - return latestElements + return latestElements; } /** @@ -77,29 +77,29 @@ export class CacheService { * @returns {Object} the original value */ put(key: string | string[], value: T, merge?: boolean): T { - const m = typeof merge === 'undefined' ? false : merge - const realKey = this._makeKey(key) - let currentValue: T = this.get(realKey, true) + const m = typeof merge === 'undefined' ? false : merge; + const realKey = this._makeKey(key); + let currentValue: T = this.get(realKey, true); if (currentValue && m) { _.mergeWith(currentValue, value, (a: unknown, b: unknown, id: string) => { if ((id === '_contents' || id === 'specification') && b && (b as ElementObject).type === 'Expression') { - return b + return b; } if (Array.isArray(a) && Array.isArray(b) && b.length < a.length) { - a.length = 0 - a.push(...(b as unknown[])) - return a as unknown[] + a.length = 0; + a.push(...(b as unknown[])); + return a as unknown[]; } if (id === '_displayedElementIds' && b) { - return b + return b; } - return undefined - }) + return undefined; + }); } else { - this.cache[realKey] = value - currentValue = value + this.cache[realKey] = value; + currentValue = value; } - return currentValue + return currentValue; } /** @@ -110,12 +110,12 @@ export class CacheService { * @param {string | string[]} targetKey */ public link(sourceKey: string | string[], targetKey: string | string[]): void { - const realSourceKey: string = this._makeKey(sourceKey) + const realSourceKey: string = this._makeKey(sourceKey); if (this.cache.hasOwnProperty(realSourceKey) && typeof this.cache[realSourceKey] !== 'string') { - delete this.cache[realSourceKey] + delete this.cache[realSourceKey]; } - this.cache[realSourceKey] = this._makeKey(targetKey) + this.cache[realSourceKey] = this._makeKey(targetKey); } /** @@ -126,21 +126,21 @@ export class CacheService { * @returns {Object} value that was removed or undefined */ remove(key: string | string[]): T { - let realKey: string + let realKey: string; if (Array.isArray(key)) { - realKey = this._makeKey(key) + realKey = this._makeKey(key); } else { - realKey = key + realKey = key; } if (!this.cache.hasOwnProperty(realKey)) { - return null + return null; } - const removed = this.cache[realKey] - delete this.cache[realKey] + const removed = this.cache[realKey]; + delete this.cache[realKey]; if (typeof removed === 'string') { - return this.remove(removed) + return this.remove(removed); } - return removed as T + return removed as T; } /** @@ -151,39 +151,39 @@ export class CacheService { * @returns {boolean} whether value exists for key */ exists(key: string | string[]): boolean { - let realKey = '' + let realKey = ''; if (Array.isArray(key)) { - realKey = this._makeKey(key) + realKey = this._makeKey(key); } else { - realKey = key + realKey = key; } if (!this.cache.hasOwnProperty(realKey)) { - return false + return false; } - const val = this.cache[realKey] + const val = this.cache[realKey]; if (typeof val === 'object') { - return true + return true; } if (typeof val === 'string') { - return this.exists(val) + return this.exists(val); } - return false + return false; } private _makeKey(keys: string | string[]): string { if (Array.isArray(keys)) { - return keys.join('|') + return keys.join('|'); } else { - return keys + return keys; } } reset = (): void => { - const keys = Object.keys(this.cache) + const keys = Object.keys(this.cache); for (let i = 0; i < keys.length; i++) { - delete this.cache[keys[i]] + delete this.cache[keys[i]]; } - } + }; } -veUtils.service('CacheService', CacheService) +veUtils.service('CacheService', CacheService); diff --git a/src/ve-utils/core/Edit.service.ts b/src/ve-utils/core/Edit.service.ts index b686862c3..fc6adc076 100644 --- a/src/ve-utils/core/Edit.service.ts +++ b/src/ve-utils/core/Edit.service.ts @@ -1,75 +1,75 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { EventService } from './Event.service' +import { EventService } from './Event.service'; -import { ElementObject, ValueObject } from '@ve-types/mms' +import { ElementObject, ValueObject } from '@ve-types/mms'; export interface EditObject { - element: T - values?: ValueObject[] - key: string + element: T; + values?: ValueObject[]; + key: string; } export class EditService { - private edits: { [editKey: string]: EditObject } = {} + private edits: { [editKey: string]: EditObject } = {}; - public EVENT = 've-edits' + public EVENT = 've-edits'; - static $inject = ['EventService'] + static $inject = ['EventService']; constructor(private eventSvc: EventService) {} trigger = (): void => { - this.eventSvc.$broadcast(this.EVENT) - } + this.eventSvc.$broadcast(this.EVENT); + }; get(key: string | string[]): EditObject { - key = this.makeKey(key) - return this.edits[key] as EditObject + key = this.makeKey(key); + return this.edits[key] as EditObject; } getAll(): { [key: string]: EditObject } { - return this.edits + return this.edits; } openEdits = (): number => { - return Object.keys(this.edits).length - } + return Object.keys(this.edits).length; + }; addOrUpdate = (key: string | string[], data: ElementObject, overwrite?: boolean): EditObject => { - key = this.makeKey(key) + key = this.makeKey(key); if (overwrite) { - delete this.edits[key] + delete this.edits[key]; } - this.edits[key] = { key, element: data } + this.edits[key] = { key, element: data }; - this.trigger() - return this.edits[key] - } + this.trigger(); + return this.edits[key]; + }; remove = (key: string | string[]): void => { - key = this.makeKey(key) + key = this.makeKey(key); if (this.edits[key]) { - delete this.edits[key] - this.trigger() + delete this.edits[key]; + this.trigger(); } - } + }; // getKey(): string {} reset = (): void => { - const keys = Object.keys(this.edits) + const keys = Object.keys(this.edits); for (let i = 0; i < keys.length; i++) { - delete this.edits[keys[i]] + delete this.edits[keys[i]]; } - } + }; public makeKey(keys: string | string[]): string { if (Array.isArray(keys)) { - return keys.join('|') + return keys.join('|'); } else { - return keys + return keys; } } } -veUtils.service('EditService', EditService) +veUtils.service('EditService', EditService); diff --git a/src/ve-utils/core/Event.service.ts b/src/ve-utils/core/Event.service.ts index bbc257ade..8a9230be0 100644 --- a/src/ve-utils/core/Event.service.ts +++ b/src/ve-utils/core/Event.service.ts @@ -1,62 +1,62 @@ -import Rx from 'rx-lite' +import Rx from 'rx-lite'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -export type eventHandlerFn = (data: T) => void +export type eventHandlerFn = (data: T) => void; export class EventService { - private subjects: { [key: string]: Rx.ISubject } = {} - private bindings: { [key: string]: Rx.ISubject } = {} + private subjects: { [key: string]: Rx.ISubject } = {}; + private bindings: { [key: string]: Rx.ISubject } = {}; //API - public $broadcast = (name: string, data?: T): void => this.emit(name, data) - public $on = (name: string, handler: eventHandlerFn): Rx.IDisposable => this.listen(name, handler) - public $destroy = (subs: Rx.IDisposable[]): void => this.destroy(subs) - public $init = (ctrl: { subs: Rx.IDisposable[] } & angular.IComponentController): void => this.initEventSvc(ctrl) + public $broadcast = (name: string, data?: T): void => this.emit(name, data); + public $on = (name: string, handler: eventHandlerFn): Rx.IDisposable => this.listen(name, handler); + public $destroy = (subs: Rx.IDisposable[]): void => this.destroy(subs); + public $init = (ctrl: { subs: Rx.IDisposable[] } & angular.IComponentController): void => this.initEventSvc(ctrl); createName = (name: string): string => { - return `$ ${name}` - } + return `$ ${name}`; + }; resolve(name: string, data?: T): void { - const fnName = this.createName(name) + const fnName = this.createName(name); //$rootScope.$broadcast(name,data); if (!this.bindings[fnName]) { - this.bindings[fnName] = new Rx.BehaviorSubject(data) + this.bindings[fnName] = new Rx.BehaviorSubject(data); } else { - this.bindings[fnName].onNext(data) + this.bindings[fnName].onNext(data); } } binding(name: string, handler: eventHandlerFn): Rx.IDisposable { - const fnName = this.createName(name) + const fnName = this.createName(name); if (!this.bindings[fnName]) { - throw Error('Binding ' + name + ' subscribed before initialization!') + throw Error('Binding ' + name + ' subscribed before initialization!'); } - return this.bindings[fnName].subscribe(handler) + return this.bindings[fnName].subscribe(handler); } emit(name: string, data?: T): void { - const fnName = this.createName(name) + const fnName = this.createName(name); //$rootScope.$broadcast(name,data); if (!this.subjects[fnName]) { - this.subjects[fnName] = new Rx.Subject() + this.subjects[fnName] = new Rx.Subject(); } - this.subjects[fnName].onNext(data) + this.subjects[fnName].onNext(data); } listen(name: string, handler: eventHandlerFn): Rx.IDisposable { - const fnName = this.createName(name) + const fnName = this.createName(name); if (!this.subjects[fnName]) { - this.subjects[fnName] = new Rx.Subject() + this.subjects[fnName] = new Rx.Subject(); } - return this.subjects[fnName].subscribe(handler) + return this.subjects[fnName].subscribe(handler); } destroy(subs: Rx.IDisposable[]): void { if (subs.length > 0) { for (let i = 0; i < subs.length; i++) { if (typeof subs[i].dispose === 'function') { - subs[i].dispose() + subs[i].dispose(); } } } @@ -64,21 +64,21 @@ export class EventService { initEventSvc( componentOrScope: { - subs: Rx.IDisposable[] + subs: Rx.IDisposable[]; } & angular.IComponentController ): void { - componentOrScope.subs = [] + componentOrScope.subs = []; if (!componentOrScope.$onDestroy) { componentOrScope.$onDestroy = (): void => { - this.destroy(componentOrScope.subs) - } + this.destroy(componentOrScope.subs); + }; } } exists(eventOrBinding: string): boolean { - const name = this.createName(eventOrBinding) - return this.subjects.hasOwnProperty(name) || this.bindings.hasOwnProperty(name) + const name = this.createName(eventOrBinding); + return this.subjects.hasOwnProperty(name) || this.bindings.hasOwnProperty(name); } } -veUtils.service('EventService', EventService) +veUtils.service('EventService', EventService); diff --git a/src/ve-utils/core/Session.service.ts b/src/ve-utils/core/Session.service.ts index 81c584050..a4f4dd36a 100644 --- a/src/ve-utils/core/Session.service.ts +++ b/src/ve-utils/core/Session.service.ts @@ -1,50 +1,50 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { EventService } from './Event.service' +import { EventService } from './Event.service'; export class SessionService { - static $inject = ['EventService'] + static $inject = ['EventService']; constructor(private eventSvc: EventService) {} private static _setStorage(key: string, realValue: T): void { - const value = realValue == null ? null : JSON.stringify(realValue) - sessionStorage.setItem(key, value) + const value = realValue == null ? null : JSON.stringify(realValue); + sessionStorage.setItem(key, value); } private static _getStorage(key: string): T { - const sessionValue = sessionStorage.getItem(key) + const sessionValue = sessionStorage.getItem(key); if (sessionValue === null) { - return null + return null; } else { - return JSON.parse(sessionValue) as T + return JSON.parse(sessionValue) as T; } } private static _removeStorage(key: string): void { - sessionStorage.removeItem(key) + sessionStorage.removeItem(key); } public clear = (): void => { - sessionStorage.clear() - } + sessionStorage.clear(); + }; public accessor = (name: string, value: T, defaultValue: T = null): T => { if (value === undefined) { - let val = SessionService._getStorage(name) + let val = SessionService._getStorage(name); if (val == null) { - val = defaultValue - SessionService._setStorage(name, val) + val = defaultValue; + SessionService._setStorage(name, val); } if (!this.eventSvc.exists(name)) { - this.eventSvc.resolve(name, val) + this.eventSvc.resolve(name, val); } - return val + return val; } - this.eventSvc.resolve(name, value) - SessionService._setStorage(name, value) - return value - } + this.eventSvc.resolve(name, value); + SessionService._setStorage(name, value); + return value; + }; } -veUtils.service('SessionService', SessionService) +veUtils.service('SessionService', SessionService); diff --git a/src/ve-utils/core/index.ts b/src/ve-utils/core/index.ts index 44d28a73e..15fc54501 100644 --- a/src/ve-utils/core/index.ts +++ b/src/ve-utils/core/index.ts @@ -1,9 +1,9 @@ -import './Cache.service' -import './Edit.service' -import './Event.service' -import './Session.service' +import './Cache.service'; +import './Edit.service'; +import './Event.service'; +import './Session.service'; -export * from './Cache.service' -export * from './Edit.service' -export * from './Event.service' -export * from './Session.service' +export * from './Cache.service'; +export * from './Edit.service'; +export * from './Event.service'; +export * from './Session.service'; diff --git a/src/ve-utils/index.ts b/src/ve-utils/index.ts index 7ded81b91..7298c68d2 100644 --- a/src/ve-utils/index.ts +++ b/src/ve-utils/index.ts @@ -1,15 +1,15 @@ //Libraries //import 'angular' -import './ve-utils.module' +import './ve-utils.module'; -import './third-party' +import './third-party'; -import './core' -import './model-schema' -import './application' -import './mms-api-client' +import './core'; +import './model-schema'; +import './application'; +import './mms-api-client'; -export * from './ve-utils.module' +export * from './ve-utils.module'; -export default 've-utils' +export default 've-utils'; diff --git a/src/ve-utils/mms-api-client/Api.service.ts b/src/ve-utils/mms-api-client/Api.service.ts index 53ebf0c4a..28f621c3d 100644 --- a/src/ve-utils/mms-api-client/Api.service.ts +++ b/src/ve-utils/mms-api-client/Api.service.ts @@ -1,13 +1,13 @@ -import _ from 'lodash' -import * as uuid from 'uuid' +import _ from 'lodash'; +import * as uuid from 'uuid'; -import { URLService } from '@ve-utils/mms-api-client/URL.service' -import { SchemaService } from '@ve-utils/model-schema' +import { URLService } from '@ve-utils/mms-api-client/URL.service'; +import { SchemaService } from '@ve-utils/model-schema'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular' -import { VeConfig } from '@ve-types/config' +import { VePromise, VePromiseReason, VeQService } from '@ve-types/angular'; +import { VeConfig } from '@ve-types/config'; import { BasicResponse, ElementObject, @@ -20,7 +20,7 @@ import { ValueObject, VersionResponse, ViewObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; export class ApiService { private editKeys = [ @@ -34,13 +34,13 @@ export class ApiService { '_projectId', '_refId', 'type', - ] + ]; - schema: string = 'cameo' + schema: string = 'cameo'; - public veConfig: VeConfig = window.__env + public veConfig: VeConfig = window.__env; - static $inject = ['$q', '$http', 'URLService', 'SchemaService'] + static $inject = ['$q', '$http', 'URLService', 'SchemaService']; constructor( private $q: VeQService, @@ -50,21 +50,21 @@ export class ApiService { ) {} public getMmsVersion(): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.$http.get(this.uRLSvc.getMmsVersionURL()).then( (response) => { - deferred.resolve(response.data.mmsVersion) + deferred.resolve(response.data.mmsVersion); }, (response: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(response)) + deferred.reject(this.uRLSvc.handleHttpStatus(response)); } - ) - return deferred.promise + ); + return deferred.promise; } public getVeVersion = (): string => { - return this.veConfig.version - } + return this.veConfig.version; + }; /** * @name veUtils/ApiService#handleErrorCallback @@ -78,14 +78,14 @@ export class ApiService { deferredOrReject: angular.IDeferred | angular.IQResolveReject>, type?: 'error' | 'warning' | 'info' ): void { - const res = this.uRLSvc.handleHttpStatus(response) + const res = this.uRLSvc.handleHttpStatus(response); if (type) { - res.type = type + res.type = type; } if ((deferredOrReject as angular.IDeferred).reject) { - ;(deferredOrReject as angular.IDeferred).reject(res) + (deferredOrReject as angular.IDeferred).reject(res); } else { - ;(deferredOrReject as angular.IQResolveReject>)(res) + (deferredOrReject as angular.IQResolveReject>)(res); } } @@ -98,13 +98,13 @@ export class ApiService { */ private _cleanValueSpec = (vs: ValueObject): void => { - if (vs.hasOwnProperty('valueExpression')) delete vs.valueExpression + if (vs.hasOwnProperty('valueExpression')) delete vs.valueExpression; if (vs.operand && Array.isArray(vs.operand)) { for (let i = 0; i < vs.operand.length; i++) { - this._cleanValueSpec(vs.operand[i] as ValueObject) + this._cleanValueSpec(vs.operand[i] as ValueObject); } } - } + }; /** * @name veUtils/UtilsService#cleanElement @@ -117,50 +117,50 @@ export class ApiService { public cleanElement(elem: T, forEdit?: boolean): T { if (elem.type === 'Property' || elem.type === 'Port') { if (!elem.defaultValue) { - elem.defaultValue = null + elem.defaultValue = null; } } if (elem.type === 'Slot') { - if (!Array.isArray(elem.value)) (elem as LiteralObject).value = [] + if (!Array.isArray(elem.value)) (elem as LiteralObject).value = []; } if (elem.value && Array.isArray(elem.value)) { - ;(elem as LiteralObject).value.forEach((value: unknown) => { + (elem as LiteralObject).value.forEach((value: unknown) => { if (typeof value === 'object' && value !== null) - this._cleanValueSpec(value as ExpressionObject) - }) + this._cleanValueSpec(value as ExpressionObject); + }); } if (elem._contents) { - this._cleanValueSpec((elem as ViewObject)._contents) + this._cleanValueSpec((elem as ViewObject)._contents); } if (elem.specification) { - this._cleanValueSpec((elem as InstanceSpecObject).specification) + this._cleanValueSpec((elem as InstanceSpecObject).specification); } if (elem.type === 'Class') { if (elem._contents && elem.contains) { - delete elem.contains + delete elem.contains; } if (elem._allowedElementIds) { - delete elem._allowedElementIds + delete elem._allowedElementIds; } } if (elem.hasOwnProperty('specialization')) { - delete elem.specialization + delete elem.specialization; } if (!elem.hasOwnProperty('appliedStereotypeIds') && elem._appliedStereotypeIds) { - elem.appliedStereotypeIds = elem._appliedStereotypeIds + elem.appliedStereotypeIds = elem._appliedStereotypeIds; } if (forEdit) { //only keep editable or needed keys in edit object instead of everything - const keys = Object.keys(elem) + const keys = Object.keys(elem); keys.forEach((key) => { if (this.editKeys.indexOf(key) >= 0) { - return + return; } - delete elem[key] - }) + delete elem[key]; + }); } - return elem + return elem; } /** @@ -171,10 +171,10 @@ export class ApiService { * @returns {RequestObject} with default values for ref and commit */ public normalize = (reqOb: RequestObject): RequestObject => { - reqOb.refId = !reqOb.refId ? 'master' : reqOb.refId - reqOb.commitId = !reqOb.commitId ? 'latest' : reqOb.commitId - return reqOb - } + reqOb.refId = !reqOb.refId ? 'master' : reqOb.refId; + reqOb.commitId = !reqOb.commitId ? 'latest' : reqOb.commitId; + return reqOb; + }; /** * @name veUtils/UtilsService#makeRequestObject @@ -188,8 +188,8 @@ export class ApiService { projectId: elementOb._projectId, refId: elementOb._refId, commitId: elementOb._commitId, - } - } + }; + }; /** * @name veUtils/UtilsService#makeElementRequestObject @@ -204,7 +204,7 @@ export class ApiService { projectId: elementOb._projectId, refId: elementOb._refId, commitId: elementOb._commitId, - } + }; } /** @@ -218,18 +218,18 @@ export class ApiService { * @returns {Array} key to be used in CacheService */ public makeCacheKey(reqOb: RequestObject | null, elementId: string, edit?: boolean, type?: string): string[] { - const key: string[] = [] - const keyType: string = type ? type : 'element' - key.push(keyType) + const key: string[] = []; + const keyType: string = type ? type : 'element'; + key.push(keyType); if (reqOb !== null) { - if (reqOb.projectId) key.push(reqOb.projectId) - if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId) + if (reqOb.projectId) key.push(reqOb.projectId); + if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId); if (!keyType.includes('history') && reqOb.commitId !== null) - key.push(!reqOb.commitId ? 'latest' : reqOb.commitId) + key.push(!reqOb.commitId ? 'latest' : reqOb.commitId); } - if (elementId !== '') key.push(elementId) - if (edit) key.push('edit') - return key + if (elementId !== '') key.push(elementId); + if (edit) key.push('edit'); + return key; } /** @@ -277,16 +277,16 @@ export class ApiService { i === '_created' || i === '_commitId' ) { - continue + continue; } if (edit.hasOwnProperty(i) && orig.hasOwnProperty(i) && server.hasOwnProperty(i)) { if (!_.isEqual(orig[i], server[i])) { - return true + return true; } } } - return false - } + return false; + }; /** * @name veUtils/UtilsService#isRestrictedValue @@ -320,8 +320,8 @@ export class ApiService { * */ public createUUID = (): string => { - return uuid.v4() - } + return uuid.v4(); + }; /** * @name veUtils/UtilsService#createUniqueId @@ -330,8 +330,8 @@ export class ApiService { * @returns {string} unique SysML element ID */ public createUniqueId = (): string => { - return `ve-${this.getVeVersion().replace(/\./g, '-')}-${this.createUUID()}` - } + return `ve-${this.getVeVersion().replace(/\./g, '-')}-${this.createUUID()}`; + }; /** * @name veUtils/UtilsService#isView @@ -346,17 +346,17 @@ export class ApiService { e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('VIEW_SID', this.schema)) >= 0 || e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('DOCUMENT_SID', this.schema)) >= 0 ) { - return true + return true; } - const otherViewSids: string[] = this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema) + const otherViewSids: string[] = this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema); for (const otherViewSid of otherViewSids) { if (e.appliedStereotypeIds.indexOf(otherViewSid) >= 0) { - return true + return true; } } } - return false - } + return false; + }; /** * @name veUtils/UtilsService#isDocument @@ -369,8 +369,8 @@ export class ApiService { return ( e.appliedStereotypeIds && e.appliedStereotypeIds.indexOf(this.schemaSvc.getSchema('DOCUMENT_SID', this.schema)) >= 0 - ) - } + ); + }; /** * @name veUtils/UtilsService#isRequirement @@ -381,15 +381,15 @@ export class ApiService { */ public isRequirement = (e: ElementObject): boolean => { if (e.appliedStereotypeIds) { - const reqSids = this.schemaSvc.getSchema('REQUIREMENT_SID', this.schema) + const reqSids = this.schemaSvc.getSchema('REQUIREMENT_SID', this.schema); for (const reqSid of reqSids) { if (e.appliedStereotypeIds.indexOf(reqSid) >= 0) { - return true + return true; } } } - return false - } + return false; + }; } -veUtils.service('ApiService', ApiService) +veUtils.service('ApiService', ApiService); diff --git a/src/ve-utils/mms-api-client/Authorization.service.ts b/src/ve-utils/mms-api-client/Authorization.service.ts index 85bb4a34b..da0b5ec12 100644 --- a/src/ve-utils/mms-api-client/Authorization.service.ts +++ b/src/ve-utils/mms-api-client/Authorization.service.ts @@ -1,10 +1,10 @@ -import { CacheService, EditService, SessionService } from '@ve-utils/core' -import { ElementService, HttpService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client' +import { CacheService, EditService, SessionService } from '@ve-utils/core'; +import { ElementService, HttpService, ProjectService, URLService, ViewService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms'; /** * @ngdoc service @@ -19,7 +19,7 @@ import { AuthRequest, AuthResponse, CheckAuthResponse } from '@ve-types/mms' * * Provide general authorization functions. I.e. login, logout, etc... */ export class AuthService { - private token: string | null + private token: string | null; static $inject = [ '$q', '$http', @@ -31,7 +31,7 @@ export class AuthService { 'ProjectService', 'SessionService', 'EditService', - ] + ]; constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -44,64 +44,64 @@ export class AuthService { private sessionSvc: SessionService, private autosaveSvc: EditService ) { - this.token = localStorage.getItem('token') + this.token = localStorage.getItem('token'); } getAuthorized(credentialsJSON: AuthRequest): VePromise { - const deferred = this.$q.defer() - const loginURL = this.uRLSvc.getAuthenticationUrl() + const deferred = this.$q.defer(); + const loginURL = this.uRLSvc.getAuthenticationUrl(); this.$http.post(loginURL, credentialsJSON).then( (success) => { - this.uRLSvc.setToken(success.data.token) - this.token = success.data.token - localStorage.setItem('token', this.token) - deferred.resolve(this.token) + this.uRLSvc.setToken(success.data.token); + this.token = success.data.token; + localStorage.setItem('token', this.token); + deferred.resolve(this.token); }, (fail: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(fail)) + deferred.reject(this.uRLSvc.handleHttpStatus(fail)); } - ) - return deferred.promise + ); + return deferred.promise; } removeToken = (): void => { - localStorage.removeItem('token') - this.token = undefined - this.uRLSvc.setToken(null) - this.httpSvc.dropAll() - this.elementSvc.reset() - this.projectSvc.reset() - this.viewSvc.reset() - this.cacheSvc.reset() - this.autosaveSvc.reset() - this.sessionSvc.clear() - } + localStorage.removeItem('token'); + this.token = undefined; + this.uRLSvc.setToken(null); + this.httpSvc.dropAll(); + this.elementSvc.reset(); + this.projectSvc.reset(); + this.viewSvc.reset(); + this.cacheSvc.reset(); + this.autosaveSvc.reset(); + this.sessionSvc.clear(); + }; getToken = (): string => { - return this.token - } + return this.token; + }; checkLogin(): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); if (!this.token) { - deferred.reject(false) - return deferred.promise + deferred.reject(false); + return deferred.promise; } - this.uRLSvc.setToken(this.token) + this.uRLSvc.setToken(this.token); this.$http.get(this.uRLSvc.getCheckTokenURL()).then( (response: angular.IHttpResponse) => { if (response.status === 401) { - deferred.reject(response) + deferred.reject(response); } else { - deferred.resolve(response.data) + deferred.resolve(response.data); } }, (fail) => { - deferred.reject(fail) - this.removeToken() + deferred.reject(fail); + this.removeToken(); } - ) - return deferred.promise + ); + return deferred.promise; } // async isAuthenticated(): Promise { @@ -125,22 +125,22 @@ export class AuthService { // } logout(): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); this.checkLogin() .then( () => { - this.removeToken() + this.removeToken(); //$cookies.remove('com.tomsawyer.web.license.user'); }, () => { - this.removeToken() + this.removeToken(); } ) .finally(() => { - deferred.resolve(true) - }) - return deferred.promise + deferred.resolve(true); + }); + return deferred.promise; } } -veUtils.service('AuthService', AuthService) +veUtils.service('AuthService', AuthService); diff --git a/src/ve-utils/mms-api-client/Base.service.ts b/src/ve-utils/mms-api-client/Base.service.ts index fd017847a..f42ead346 100644 --- a/src/ve-utils/mms-api-client/Base.service.ts +++ b/src/ve-utils/mms-api-client/Base.service.ts @@ -1,32 +1,32 @@ -import { VePromise } from '@ve-types/angular' -import { BasicResponse, MmsObject } from '@ve-types/mms' +import { VePromise } from '@ve-types/angular'; +import { BasicResponse, MmsObject } from '@ve-types/mms'; export class BaseApiService { protected inProgress: { - [key: string]: VePromise> - } = {} + [key: string]: VePromise>; + } = {}; protected _isInProgress = (key: string): boolean => { - return this.inProgress.hasOwnProperty(key) - } + return this.inProgress.hasOwnProperty(key); + }; protected _getInProgress>(key: string): VePromise { - if (this._isInProgress(key)) return this.inProgress[key] as unknown as VePromise - else return + if (this._isInProgress(key)) return this.inProgress[key] as unknown as VePromise; + else return; } protected _addInProgress>( key: string, promise: VePromise ): void { - this.inProgress[key] = promise as unknown as VePromise> + this.inProgress[key] = promise as unknown as VePromise>; } protected _removeInProgress = (key: string): void => { - delete this.inProgress[key] - } + delete this.inProgress[key]; + }; public reset = (): void => { - this.inProgress = {} - } + this.inProgress = {}; + }; } diff --git a/src/ve-utils/mms-api-client/Element.service.ts b/src/ve-utils/mms-api-client/Element.service.ts index b97b1ea90..f0c83d5cb 100644 --- a/src/ve-utils/mms-api-client/Element.service.ts +++ b/src/ve-utils/mms-api-client/Element.service.ts @@ -1,12 +1,12 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { CacheService, EditObject, EditService } from '@ve-utils/core' -import { ApiService, httpCallback, HttpService, URLService } from '@ve-utils/mms-api-client' -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' +import { CacheService, EditObject, EditService } from '@ve-utils/core'; +import { ApiService, httpCallback, HttpService, URLService } from '@ve-utils/mms-api-client'; +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular' +import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular'; import { CommitObject, CommitResponse, @@ -21,7 +21,7 @@ import { RequestObject, SearchResponse, TaggedValueObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc service @@ -35,7 +35,7 @@ import { * * An element CRUD service with additional convenience methods for managing edits. */ export class ElementService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'EditService', 'URLService', 'ApiService', 'HttpService'] + static $inject = ['$q', '$http', 'CacheService', 'EditService', 'URLService', 'ApiService', 'HttpService']; constructor( private $q: VeQService, @@ -46,7 +46,7 @@ export class ElementService extends BaseApiService { private apiSvc: ApiService, private httpSvc: HttpService ) { - super() + super(); } /** @@ -105,71 +105,71 @@ export class ElementService extends BaseApiService { refresh?: boolean, allowEmpty?: boolean ): VePromise { - this.apiSvc.normalize(reqOb) - const requestCacheKey = this.getRequestKey(reqOb, reqOb.elementId) + this.apiSvc.normalize(reqOb); + const requestCacheKey = this.getRequestKey(reqOb, reqOb.elementId); if (!reqOb.projectId) { - console.log('foo') + console.log('foo'); } - const url = this.uRLSvc.getElementURL(reqOb) - const cached: T = this.cacheSvc.get(requestCacheKey) + const url = this.uRLSvc.getElementURL(reqOb); + const cached: T = this.cacheSvc.get(requestCacheKey); // if it's in the this.inProgress queue get it immediately if (this._isInProgress(url)) { //change to change priority if it's already in the queue - this.httpSvc.ping(url, weight) - return this._getInProgress(url) as VePromise + this.httpSvc.ping(url, weight); + return this._getInProgress(url) as VePromise; } - const deletedRequestCacheKey = this.getRequestKey(reqOb, reqOb.elementId) - deletedRequestCacheKey.push('deleted') - const deleted = this.cacheSvc.get(deletedRequestCacheKey) + const deletedRequestCacheKey = this.getRequestKey(reqOb, reqOb.elementId); + deletedRequestCacheKey.push('deleted'); + const deleted = this.cacheSvc.get(deletedRequestCacheKey); if (deleted && !refresh) { return new this.$q((resolve, reject) => { return reject({ status: 410, recentVersionOfElement: deleted, message: 'Deleted', - }) - }) + }); + }); } if (cached && !refresh) { return new this.$q((resolve, reject) => { - return resolve(cached) - }) + return resolve(cached); + }); } this._addInProgress( url, new this.$q((resolve, reject) => { const successCallback: httpCallback> = (response) => { - const data = response.data - this._removeInProgress(url) + const data = response.data; + this._removeInProgress(url); if (Array.isArray(data.elements) && data.elements.length > 0) { - resolve(this.cacheElement(reqOb, data.elements[0])) + resolve(this.cacheElement(reqOb, data.elements[0])); } else if (allowEmpty) { - resolve(null) + resolve(null); } else { reject({ status: 500, message: 'Server Error: empty response', - }) //TODO + }); //TODO } - } + }; const errorCallback: httpCallback> = (response) => { - const data = response.data - const reason = this.uRLSvc.handleHttpStatus(response) - this._removeInProgress(url) + const data = response.data; + const reason = this.uRLSvc.handleHttpStatus(response); + this._removeInProgress(url); if (data && data.deleted && data.deleted.length > 0 && data.deleted[0].id === reqOb.elementId) { - reason.recentVersionOfElement = data.deleted[0] - this.cacheDeletedElement(reqOb, data.deleted[0]) + reason.recentVersionOfElement = data.deleted[0]; + this.cacheDeletedElement(reqOb, data.deleted[0]); } if (allowEmpty && response.status == 404) { - resolve(null) + resolve(null); } else { - reject(reason) + reject(reason); } - } - this.httpSvc.get>(url, successCallback, errorCallback, weight) + }; + this.httpSvc.get>(url, successCallback, errorCallback, weight); }) - ) - return this._getInProgress(url) as VePromise + ); + return this._getInProgress(url) as VePromise; } /** @@ -190,44 +190,44 @@ export class ElementService extends BaseApiService { refresh?: boolean ): VePromise> { return new this.$q>((resolve, reject) => { - const request: { elements: { id: string }[] } = { elements: [] } - const existing: T[] = [] - this.apiSvc.normalize(reqOb) + const request: { elements: { id: string }[] } = { elements: [] }; + const existing: T[] = []; + this.apiSvc.normalize(reqOb); for (let i = 0; i < reqOb.elementId.length; i++) { - const id = reqOb.elementId[i] - const requestCacheKey = this.getRequestKey(reqOb, id) - const exist = this.cacheSvc.get(requestCacheKey) + const id = reqOb.elementId[i]; + const requestCacheKey = this.getRequestKey(reqOb, id); + const exist = this.cacheSvc.get(requestCacheKey); if (exist && !refresh) { - existing.push(exist) - continue + existing.push(exist); + continue; } - request.elements.push({ id: id }) + request.elements.push({ id: id }); } if (request.elements.length === 0) { - resolve(existing) - return + resolve(existing); + return; } this.$http.put>(this.uRLSvc.getPutElementsURL(reqOb), request).then( (response) => { - const data = response.data.elements - let i + const data = response.data.elements; + let i; if (data && data.length > 0) { for (let i = 0; i < data.length; i++) { - existing.push(this.cacheElement(reqOb, data[i])) + existing.push(this.cacheElement(reqOb, data[i])); } } - const deleted = response.data.deleted + const deleted = response.data.deleted; if (deleted && deleted.length > 0) { for (let i = 0; i < deleted.length; i++) { - this.cacheDeletedElement(reqOb, deleted[i]) + this.cacheDeletedElement(reqOb, deleted[i]); } } - resolve(existing) + resolve(existing); }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ) - }) + ); + }); } /** @@ -242,45 +242,45 @@ export class ElementService extends BaseApiService { * @returns {object} cached object */ cacheElement(reqOb: RequestObject, elementOb: T): T { - let result: T = this.apiSvc.cleanElement(elementOb) - const requestCacheKey = this.getRequestKey(reqOb, result.id) - const origResultCommit = result._commitId + let result: T = this.apiSvc.cleanElement(elementOb); + const requestCacheKey = this.getRequestKey(reqOb, result.id); + const origResultCommit = result._commitId; if (reqOb.commitId === 'latest') { - const resultCommitCopy: T = _.cloneDeep(result) - result._commitId = 'latest' //so realCacheKey is right later - const commitCacheKey = this.apiSvc.makeCacheKey(this.apiSvc.makeRequestObject(resultCommitCopy), result.id) //save historic element - this.cacheSvc.put(commitCacheKey, resultCommitCopy, true) + const resultCommitCopy: T = _.cloneDeep(result); + result._commitId = 'latest'; //so realCacheKey is right later + const commitCacheKey = this.apiSvc.makeCacheKey(this.apiSvc.makeRequestObject(resultCommitCopy), result.id); //save historic element + this.cacheSvc.put(commitCacheKey, resultCommitCopy, true); } - const realCacheKey = this.getElementKey(result) - result._commitId = origResultCommit //restore actual commitId + const realCacheKey = this.getElementKey(result); + result._commitId = origResultCommit; //restore actual commitId if (!_.isEqual(realCacheKey, requestCacheKey)) { - this.cacheSvc.link(requestCacheKey, realCacheKey) + this.cacheSvc.link(requestCacheKey, realCacheKey); } - result = this.cacheSvc.put(realCacheKey, result, true) - return result + result = this.cacheSvc.put(realCacheKey, result, true); + return result; } openEdit(elementOb: T, clean: boolean): EditObject { - const result: T = clean ? this.apiSvc.cleanElement(elementOb, true) : elementOb - result._commitId = 'latest' - const editKey = this.getEditElementKey(elementOb) + const result: T = clean ? this.apiSvc.cleanElement(elementOb, true) : elementOb; + result._commitId = 'latest'; + const editKey = this.getEditElementKey(elementOb); - return this.editSvc.addOrUpdate(editKey, result) as EditObject + return this.editSvc.addOrUpdate(editKey, result) as EditObject; } cacheDeletedElement = (reqOb: RequestObject, deletedOb: ElementObject): void => { - const requestCacheKey = this.getRequestKey(reqOb, deletedOb.id) - requestCacheKey.push('deleted') + const requestCacheKey = this.getRequestKey(reqOb, deletedOb.id); + requestCacheKey.push('deleted'); const deletedReqOb: RequestObject = { projectId: deletedOb._projectId, refId: deletedOb._refId, commitId: deletedOb._commitId, - } - const commitCacheKey = this.apiSvc.makeCacheKey(deletedReqOb, deletedOb.id) - this.cacheSvc.link(requestCacheKey, commitCacheKey) - this.cacheSvc.put(commitCacheKey, deletedOb, true) - } + }; + const commitCacheKey = this.apiSvc.makeCacheKey(deletedReqOb, deletedOb.id); + this.cacheSvc.link(requestCacheKey, commitCacheKey); + this.cacheSvc.put(commitCacheKey, deletedOb, true); + }; /** * @name veUtils/ElementService#getElementForEdit @@ -322,15 +322,15 @@ export class ElementService extends BaseApiService { weight?: number, overwrite?: boolean ): VePromise, ElementsResponse> { - this.apiSvc.normalize(reqOb) - const requestCacheKey = this.getEditKey(reqOb) - const url = this.uRLSvc.getElementURL(reqOb) + 'edit' + this.apiSvc.normalize(reqOb); + const requestCacheKey = this.getEditKey(reqOb); + const url = this.uRLSvc.getElementURL(reqOb) + 'edit'; if (!this._isInProgress(url)) { - const openEdit = this.editSvc.get(requestCacheKey) + const openEdit = this.editSvc.get(requestCacheKey); if (openEdit && !overwrite) { return new this.$q, ElementsResponse>((resolve, reject) => { - return resolve(openEdit) - }) + return resolve(openEdit); + }); } this._addInProgress( url, @@ -338,20 +338,20 @@ export class ElementService extends BaseApiService { this.getElement(reqOb, weight) .then( (result) => { - const copy = this.apiSvc.cleanElement(_.cloneDeep(result), true) - resolve(this.editSvc.addOrUpdate(requestCacheKey, copy, overwrite) as EditObject) + const copy = this.apiSvc.cleanElement(_.cloneDeep(result), true); + resolve(this.editSvc.addOrUpdate(requestCacheKey, copy, overwrite) as EditObject); }, (reason) => { - reject(reason) + reject(reason); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); }) - ) + ); } - return this._getInProgress(url) as VePromise, ElementsResponse> + return this._getInProgress(url) as VePromise, ElementsResponse>; } /** @@ -370,11 +370,11 @@ export class ElementService extends BaseApiService { weight?: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); if (!reqOb.depth) { - reqOb.depth = -1 + reqOb.depth = -1; } - return this.getGenericElements(this.uRLSvc.getOwnedElementURL(reqOb), reqOb, 'elements', weight, refresh) + return this.getGenericElements(this.uRLSvc.getOwnedElementURL(reqOb), reqOb, 'elements', weight, refresh); } /** @@ -395,17 +395,17 @@ export class ElementService extends BaseApiService { weight: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb) - const requestCacheKey = this.getRequestKey(reqOb, jsonKey) + this.apiSvc.normalize(reqOb); + const requestCacheKey = this.getRequestKey(reqOb, jsonKey); if (this._isInProgress(url)) { - this.httpSvc.ping(url, weight) - return this._getInProgress(url) as VePromise> + this.httpSvc.ping(url, weight); + return this._getInProgress(url) as VePromise>; } - const cached = this.cacheSvc.get(requestCacheKey) + const cached = this.cacheSvc.get(requestCacheKey); if (cached && !refresh) { return new this.$q>((resolve, reject) => { - return resolve(cached) - }) + return resolve(cached); + }); } this._addInProgress( url, @@ -413,29 +413,29 @@ export class ElementService extends BaseApiService { this.httpSvc.get>( url, (response) => { - const results: T[] = [] - const elements: T[] = response.data[jsonKey] + const results: T[] = []; + const elements: T[] = response.data[jsonKey]; for (let i = 0; i < elements.length; i++) { - const element = elements[i] + const element = elements[i]; if (!element) { //check for possible null - continue + continue; } - results.push(this.cacheElement(reqOb, element)) + results.push(this.cacheElement(reqOb, element)); } - this._removeInProgress(url) - resolve(results) - return + this._removeInProgress(url); + resolve(results); + return; }, (response: angular.IHttpResponse>) => { - this._removeInProgress(url) - reject(this.uRLSvc.handleHttpStatus(response)) + this._removeInProgress(url); + reject(this.uRLSvc.handleHttpStatus(response)); }, weight - ) + ); }) - ) - return this._getInProgress>(url) as VePromise> + ); + return this._getInProgress>(url) as VePromise>; } //called by updateElement, fills in all keys for element to be updated @@ -451,45 +451,45 @@ export class ElementService extends BaseApiService { }, 2) .then((data) => { */ - const ob = _.cloneDeep(elementOb) //make a copy - ob._commitId = 'latest' - const editOb = this.editSvc.get(this.getEditElementKey(elementOb)) + const ob = _.cloneDeep(elementOb); //make a copy + ob._commitId = 'latest'; + const editOb = this.editSvc.get(this.getEditElementKey(elementOb)); if (editOb && editOb.element) { Object.keys(editOb.element).forEach((key) => { if (!elementOb.hasOwnProperty(key)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - ob[key] = editOb.element[key] + ob[key] = editOb.element[key]; } - }) + }); } if (ob._displayedElementIds) { - delete ob._displayedElementIds + delete ob._displayedElementIds; } if (ob._allowedElementIds) { - delete ob._allowedElementIds + delete ob._allowedElementIds; } if (ob._childViews && !elementOb._childViews) { - delete ob._childViews + delete ob._childViews; } if (ob.type && ob.type.endsWith('TaggedValue') && ob.value && (ob as TaggedValueObject).value.length > 0) { // make sure value array only has the value - const newvalues = [] + const newvalues = []; for (const val of (ob as TaggedValueObject).value) { if (ob.type === 'ElementTaggedValue') { - newvalues.push(val.elementId) + newvalues.push(val.elementId); } else { - newvalues.push({ value: val.value }) + newvalues.push({ value: val.value }); } } if (ob.type === 'ElementTaggedValue') { - ob.valueIds = newvalues - delete ob.value + ob.valueIds = newvalues; + delete ob.value; } else { - ob.value = newvalues + ob.value = newvalues; } } - delete ob._commitId - return ob + delete ob._commitId; + return ob; /* resolve(ob); }, () => { @@ -497,7 +497,7 @@ export class ElementService extends BaseApiService { }); }); */ - } + }; /** * @name veUtils/ElementService#updateElement @@ -521,12 +521,12 @@ export class ElementService extends BaseApiService { return new this.$q((resolve, reject) => { const handleSuccess = (data: ElementsResponse): void => { - let e: T = data.elements[0] + let e: T = data.elements[0]; if (data.elements.length > 1 && elementOb.id) { for (let i = 0; i < data.elements.length; i++) { if (data.elements[i].id === elementOb.id) { - e = data.elements[i] + e = data.elements[i]; } } } @@ -535,33 +535,33 @@ export class ElementService extends BaseApiService { refId: e._refId, commitId: 'latest', elementId: e.id, - } - const resp: T = this.cacheElement(metaOb, e) + }; + const resp: T = this.cacheElement(metaOb, e); // const editCopy = _.cloneDeep(e) // this.cacheElement(metaOb, editCopy, true) const history = this.cacheSvc.get( this.apiSvc.makeCacheKey(metaOb, metaOb.elementId, false, 'history') - ) + ); if (history) { - const id = e._commitId ? e._commitId : 'latest' + const id = e._commitId ? e._commitId : 'latest'; history.unshift({ _creator: e._modifier, _created: e._modified, id: id, _refId: e._refId, _projectId: e._projectId, - }) + }); } - resolve(resp) - } + resolve(resp); + }; if (!elementOb.hasOwnProperty('id')) { reject({ status: 400, message: 'Element id not found, create element first!', - }) + }); } - const postElem = this.fillInElement(elementOb) + const postElem = this.fillInElement(elementOb); //.then((postElem) => { this.$http .post>( @@ -578,32 +578,32 @@ export class ElementService extends BaseApiService { ) .then( (response) => { - const rejected = response.data.rejected + const rejected = response.data.rejected; if (rejected && rejected.length > 0 && rejected[0].code === 304 && rejected[0].object) { //elem will be rejected if server detects no changes - resolve(rejected[0].object) - return + resolve(rejected[0].object); + return; } if (!Array.isArray(response.data.elements) || response.data.elements.length === 0) { if (allowEmpty) { - resolve(null) + resolve(null); } else { reject({ status: 500, message: 'Server Error: empty response', - }) + }); } - return + return; } - handleSuccess(response.data) + handleSuccess(response.data); }, (response: angular.IHttpResponse>) => { if (response.status === 409) { - const serverOb = response.data.elements[0] - this.apiSvc.cleanElement(serverOb) - const origCommit = elementOb._commitId - elementOb._commitId = 'latest' + const serverOb = response.data.elements[0]; + this.apiSvc.cleanElement(serverOb); + const origCommit = elementOb._commitId; + elementOb._commitId = 'latest'; const origOb = this.cacheSvc.get( this.apiSvc.makeCacheKey( { @@ -613,29 +613,29 @@ export class ElementService extends BaseApiService { }, elementOb.id ) - ) - elementOb._commitId = origCommit + ); + elementOb._commitId = origCommit; if (!origOb) { - reject(this.uRLSvc.handleHttpStatus(response)) - return + reject(this.uRLSvc.handleHttpStatus(response)); + return; } if (!this.apiSvc.hasConflict(postElem, origOb, serverOb)) { - elementOb._modified = serverOb._modified + elementOb._modified = serverOb._modified; this.updateElement(elementOb, returnChildViews).then( (good) => { - resolve(good) + resolve(good); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); } else { - reject(this.uRLSvc.handleHttpStatus(response)) + reject(this.uRLSvc.handleHttpStatus(response)); } - } else reject(this.uRLSvc.handleHttpStatus(response)) + } else reject(this.uRLSvc.handleHttpStatus(response)); } - ) - }) + ); + }); } /** @@ -655,15 +655,15 @@ export class ElementService extends BaseApiService { return new this.$q>((resolve, reject) => { if (this._validate(elementObs)) { const postElements = elementObs.map((elementOb) => { - return this.fillInElement(elementOb) as T - }) + return this.fillInElement(elementOb) as T; + }); - const groupOfElements = this._groupElementsByProjectIdAndRefId(postElements) - const promises: VePromise>[] = [] + const groupOfElements = this._groupElementsByProjectIdAndRefId(postElements); + const promises: VePromise>[] = []; Object.keys(groupOfElements).forEach((key) => { - promises.push(this._bulkUpdate(groupOfElements[key], returnChildViews)) - }) + promises.push(this._bulkUpdate(groupOfElements[key], returnChildViews)); + }); // responses is an array of response corresponding to both successful and failed requests with the following format // [ { state: 'fulfilled', value: the value returned by the server }, @@ -672,27 +672,27 @@ export class ElementService extends BaseApiService { this.$q.allSettled(promises).then((responses) => { // get all the successful requests const successfulRequests = responses.filter((response) => { - return response.state === 'fulfilled' - }) + return response.state === 'fulfilled'; + }); const successValues = _.flatten( successfulRequests.map((response) => { - return response.value + return response.value; }) - ) + ); if (successfulRequests.length === promises.length) { // All requests succeeded - resolve(successValues) + resolve(successValues); } else { // some requests failed const rejectionReasons: VePromiseReason>[] = responses .filter((response) => { - return response.state === 'rejected' + return response.state === 'rejected'; }) .map((response): unknown => { - return response.reason as VePromiseReason> - }) as VePromiseReason>[] + return response.reason as VePromiseReason>; + }) as VePromiseReason>[]; // since we could have multiple failed requests when having some successful requests, // reject with the following format so that the client can deal with them at a granular level if @@ -704,18 +704,18 @@ export class ElementService extends BaseApiService { failedRequests: rejectionReasons, successfulRequests: successValues, }, - }) + }); } - }, reject) + }, reject); } else { const response: VePromiseReason> = { status: 400, message: 'Some of the elements do not have id, _projectId, _refId', data: {}, - } - reject(response) + }; + reject(response); } - }) + }); } /** @@ -728,9 +728,9 @@ export class ElementService extends BaseApiService { * create is successful. */ createElement(reqOb: ElementCreationRequest): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getPostElementsURL(reqOb) + const url = this.uRLSvc.getPostElementsURL(reqOb); this.$http .post>(url, { elements: reqOb.elements, @@ -743,23 +743,23 @@ export class ElementService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }) - return + }); + return; } - let resp: T = response.data.elements[0] + let resp: T = response.data.elements[0]; if (response.data.elements.length > 1 && reqOb.elements[0].id) { for (let i = 0; i < response.data.elements.length; i++) { if (response.data.elements[i].id === reqOb.elements[0].id) { - resp = response.data.elements[i] + resp = response.data.elements[i]; } } } - resolve(this.cacheElement(reqOb, resp)) + resolve(this.cacheElement(reqOb, resp)); }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ) - }) + ); + }); } /** @@ -772,9 +772,9 @@ export class ElementService extends BaseApiService { * create is successful. */ createElements(reqOb: ElementCreationRequest): VePromise> { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q>((resolve, reject) => { - const url = this.uRLSvc.getPostElementsURL(reqOb) + const url = this.uRLSvc.getPostElementsURL(reqOb); this.$http .post>(url, { elements: reqOb.elements, @@ -787,22 +787,22 @@ export class ElementService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }) - return + }); + return; } - const results: T[] = [] + const results: T[] = []; for (let i = 0; i < response.data.elements.length; i++) { - results.push(this.cacheElement(reqOb, response.data.elements[i])) + results.push(this.cacheElement(reqOb, response.data.elements[i])); // const editCopy = _.cloneDeep(response.data.elements[i]) // this.cacheElement(reqOb, editCopy, true) } - resolve(results) + resolve(results); }, (response: angular.IHttpResponse>) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } /** @@ -818,9 +818,9 @@ export class ElementService extends BaseApiService { elementOb: T ): VePromise< { - status?: boolean - server?: T - cache?: T + status?: boolean; + server?: T; + cache?: T; }, ElementsResponse > { @@ -828,46 +828,46 @@ export class ElementService extends BaseApiService { projectId: elementOb._projectId, refId: elementOb._refId, elementId: elementOb.id, - } + }; return new this.$q< { - status?: boolean - server?: T - cache?: T + status?: boolean; + server?: T; + cache?: T; }, ElementsResponse >((resolve, reject) => { - const orig = this.cacheSvc.get(this.apiSvc.makeCacheKey(reqOb, elementOb.id, false)) + const orig = this.cacheSvc.get(this.apiSvc.makeCacheKey(reqOb, elementOb.id, false)); if (!orig) { - return resolve({ status: false }) + return resolve({ status: false }); } this.$http.get>(this.uRLSvc.getElementURL(reqOb)).then( (response) => { - let server = _.cloneDeep(response.data.elements[0]) - delete server._modified - delete server._read - delete server._creator - server = this.apiSvc.cleanElement(server) - let current: ElementObject = _.cloneDeep(orig) - delete current._modified - delete current._read - delete current._creator - current = this.apiSvc.cleanElement(current) + let server = _.cloneDeep(response.data.elements[0]); + delete server._modified; + delete server._read; + delete server._creator; + server = this.apiSvc.cleanElement(server); + let current: ElementObject = _.cloneDeep(orig); + delete current._modified; + delete current._read; + delete current._creator; + current = this.apiSvc.cleanElement(current); if (_.isEqual(server, current)) { - resolve({ status: false }) + resolve({ status: false }); } else { resolve({ status: true, server: response.data.elements[0], cache: orig, - }) + }); } }, (response: angular.IHttpResponse>) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } /** @@ -887,8 +887,8 @@ export class ElementService extends BaseApiService { queryParams?: QueryParams, weight? ): VePromise, SearchResponse> { - this.apiSvc.normalize(reqOb) - const url = this.uRLSvc.getElementSearchURL(reqOb, queryParams) + this.apiSvc.normalize(reqOb); + const url = this.uRLSvc.getElementSearchURL(reqOb, queryParams); return new this.$q, SearchResponse>((resolve, reject) => { this.$http.post(url, query).then( (response: angular.IHttpResponse>) => { @@ -901,12 +901,12 @@ export class ElementService extends BaseApiService { // result.push(toAdd); //} //resolve(result); - resolve(response.data) + resolve(response.data); }, (response: angular.IHttpResponse>) => this.apiSvc.handleErrorCallback(response, reject) - ) - }) + ); + }); } /** @@ -923,62 +923,62 @@ export class ElementService extends BaseApiService { weight: number, update?: boolean ): VePromise { - this.apiSvc.normalize(reqOb) - const url = this.uRLSvc.getElementHistoryURL(reqOb) + this.apiSvc.normalize(reqOb); + const url = this.uRLSvc.getElementHistoryURL(reqOb); if (this._isInProgress(url)) { - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } - const requestCacheKey: string[] = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'history') + const requestCacheKey: string[] = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'history'); if (this.cacheSvc.exists(requestCacheKey) && !update) { return new this.$q((resolve, reject) => { - return resolve(this.cacheSvc.get(requestCacheKey)) - }) + return resolve(this.cacheSvc.get(requestCacheKey)); + }); } this._addInProgress( url, new this.$q((resolve, reject) => { this.$http.get(this.uRLSvc.getElementHistoryURL(reqOb)).then( (response: angular.IHttpResponse) => { - this.cacheSvc.put(requestCacheKey, response.data.commits, true) - this._removeInProgress(url) - resolve(this.cacheSvc.get(requestCacheKey)) + this.cacheSvc.put(requestCacheKey, response.data.commits, true); + this._removeInProgress(url); + resolve(this.cacheSvc.get(requestCacheKey)); }, (response: angular.IHttpResponse) => { - this._removeInProgress(url) - this.apiSvc.handleErrorCallback(response, reject) + this._removeInProgress(url); + this.apiSvc.handleErrorCallback(response, reject); } - ) + ); }) - ) - return this._getInProgress(url) as VePromise + ); + return this._getInProgress(url) as VePromise; } public getRequestKey(reqOb: RequestObject, id: string, edit?: boolean): string[] { - return this.apiSvc.makeCacheKey(reqOb, id, edit) + return this.apiSvc.makeCacheKey(reqOb, id, edit); } public getElementRequest(elementOb: ElementObject): ElementsRequest { - const req = this.apiSvc.makeRequestObject(elementOb) - ;(req as ElementsRequest).elementId = elementOb.id - return req as ElementsRequest + const req = this.apiSvc.makeRequestObject(elementOb); + (req as ElementsRequest).elementId = elementOb.id; + return req as ElementsRequest; } public getElementKey(elementOb: ElementObject, edit?: boolean): string[] { - return this.getRequestKey(this.getElementRequest(elementOb), elementOb.id, edit) + return this.getRequestKey(this.getElementRequest(elementOb), elementOb.id, edit); } public getEditKey(reqOb: ElementsRequest): string[] { - const key: string[] = [] + const key: string[] = []; if (reqOb !== null) { - if (reqOb.projectId) key.push(reqOb.projectId) - if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId) + if (reqOb.projectId) key.push(reqOb.projectId); + if (reqOb.refId !== null) key.push(!reqOb.refId ? 'master' : reqOb.refId); } - key.push(reqOb.elementId) - return key + key.push(reqOb.elementId); + return key; } public getEditElementKey(e: ElementObject): string[] { - return [e._projectId, e._refId, e.id] + return [e._projectId, e._refId, e.id]; } public getElementQualifiedName(reqOb: ElementsRequest): VePromise> { @@ -991,33 +991,33 @@ export class ElementService extends BaseApiService { recurse: { ownerId: 'id', }, - } + }; this.search(reqOb, queryOb).then( (data) => { - let qualifiedName = '' - const elements = data.elements.reverse() - const entries = elements.entries() + let qualifiedName = ''; + const elements = data.elements.reverse(); + const entries = elements.entries(); for (const [i, element] of entries) { if (element.hasOwnProperty('name')) { - qualifiedName += element.name + qualifiedName += element.name; } if (i != elements.length - 1) { - qualifiedName += '/' + qualifiedName += '/'; } } - return resolve(qualifiedName) + return resolve(qualifiedName); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } private _groupElementsByProjectIdAndRefId(elementObs: T[]): _.Dictionary { return _.groupBy(elementObs, (element) => { - return element._projectId + '|' + element._refId - }) + return element._projectId + '|' + element._refId; + }); } private _createMetaOb(element: ElementObject): ElementsRequest { @@ -1026,7 +1026,7 @@ export class ElementService extends BaseApiService { refId: element._refId, commitId: 'latest', elementId: element.id, - } + }; } private _validate(elementObs: ElementObject[]): boolean { @@ -1035,8 +1035,8 @@ export class ElementService extends BaseApiService { elementOb.hasOwnProperty('id') && elementOb.hasOwnProperty('_projectId') && elementOb.hasOwnProperty('_refId') - ) - }) + ); + }); } private _bulkUpdate>( @@ -1053,7 +1053,7 @@ export class ElementService extends BaseApiService { : this.uRLSvc.getPostElementsURL({ projectId: elements[0]._projectId, refId: elements[0]._refId, - }) + }); this.$http .post>( url, @@ -1065,32 +1065,32 @@ export class ElementService extends BaseApiService { ) .then( (response) => { - this._bulkUpdateSuccessHandler(response, resolve) + this._bulkUpdateSuccessHandler(response, resolve); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } private _bulkUpdateSuccessHandler( serverResponse: angular.IHttpResponse>, resolve: angular.IQResolveReject ): void { - const results: T[] = [] - const elements = serverResponse.data.elements + const results: T[] = []; + const elements = serverResponse.data.elements; if (elements && elements.length > 0) { elements.forEach((e) => { - const metaOb = this._createMetaOb(e) + const metaOb = this._createMetaOb(e); //const editCopy = _.cloneDeep(e) - results.push(this.cacheElement(metaOb, e)) + results.push(this.cacheElement(metaOb, e)); //this.cacheElement(metaOb, editCopy, true) const history = this.cacheSvc.get( this.apiSvc.makeCacheKey(metaOb, metaOb.elementId, false, 'history') - ) + ); if (history) { history.unshift({ _creator: e._modifier, @@ -1098,22 +1098,22 @@ export class ElementService extends BaseApiService { id: e._commitId, _refId: e._refId, _projectId: e._projectId, - }) + }); } - }) + }); } - const rejected: RejectedObject[] = serverResponse.data.rejected + const rejected: RejectedObject[] = serverResponse.data.rejected; if (rejected && rejected.length > 0) { rejected.forEach((e) => { if (e.code === 304 && e.object) { - results.push(e.object) //add any server rejected elements because they haven't changed - console.log(`[BULK UPDATE ELEMENT REJECTED]: ${e.code}: ${e.message}`) - console.log(e.object.id) + results.push(e.object); //add any server rejected elements because they haven't changed + console.log(`[BULK UPDATE ELEMENT REJECTED]: ${e.code}: ${e.message}`); + console.log(e.object.id); } - }) + }); } - resolve(results) + resolve(results); } } -veUtils.service('ElementService', ElementService) +veUtils.service('ElementService', ElementService); diff --git a/src/ve-utils/mms-api-client/Http.service.ts b/src/ve-utils/mms-api-client/Http.service.ts index aa84d7b37..601eff2ba 100644 --- a/src/ve-utils/mms-api-client/Http.service.ts +++ b/src/ve-utils/mms-api-client/Http.service.ts @@ -1,12 +1,12 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -export type httpCallback = (response: angular.IHttpResponse) => void +export type httpCallback = (response: angular.IHttpResponse) => void; export interface HttpServiceRequest { - url: string - successCallback: httpCallback - errorCallback: httpCallback - weight: number + url: string; + successCallback: httpCallback; + errorCallback: httpCallback; + weight: number; } /** @@ -15,24 +15,24 @@ export interface HttpServiceRequest { * * Provides prioritization and caching for $http service calls */ export class HttpService { - private queue: HttpServiceRequest[][] = [] - cache: { [key: string]: HttpServiceRequest } = {} - inProgress = 0 - getLimit = 20 + private queue: HttpServiceRequest[][] = []; + cache: { [key: string]: HttpServiceRequest } = {}; + inProgress = 0; + getLimit = 20; - static $inject = ['$http'] + static $inject = ['$http']; constructor(private $http: angular.IHttpService) { - this.queue[0] = [] //high proirity - this.queue[1] = [] //low prority + this.queue[0] = []; //high proirity + this.queue[1] = []; //low prority } setOutboundLimit = (limit: number): void => { - this.getLimit = limit - } + this.getLimit = limit; + }; getQueue(): HttpServiceRequest[][] { - return this.queue + return this.queue; } /** @@ -47,68 +47,68 @@ export class HttpService { */ get(url: string, successCallback: httpCallback, errorCallback: httpCallback, weight: number): void { if (weight === undefined) { - weight = 1 + weight = 1; } const request: HttpServiceRequest = { url: url, successCallback: successCallback, errorCallback: errorCallback, weight: weight, - } + }; if (this.inProgress >= this.getLimit) { if (request.weight === 2) { this.$http .get(url) .then( (response: angular.IHttpResponse) => { - successCallback(response) + successCallback(response); }, (response: angular.IHttpResponse) => { - errorCallback(response) + errorCallback(response); } ) .finally(() => { if (this.cache.hasOwnProperty(url)) { - delete this.cache[url] + delete this.cache[url]; } - }) + }); } else if (request.weight === 0) { - this.queue[0].push(request) + this.queue[0].push(request); } else { - this.queue[1].push(request) + this.queue[1].push(request); } if (this.cache.hasOwnProperty(url)) { - if (this.cache[url].weight < request.weight) this.cache[url].weight = request.weight + if (this.cache[url].weight < request.weight) this.cache[url].weight = request.weight; } else { - this.cache[url] = request + this.cache[url] = request; } } else { - this.inProgress++ - this.cache[url] = request + this.inProgress++; + this.cache[url] = request; this.$http .get(url) .then( (response: angular.IHttpResponse) => { - successCallback(response) + successCallback(response); }, (response: angular.IHttpResponse) => { - errorCallback(response) + errorCallback(response); } ) .finally(() => { - this.inProgress-- - let next: HttpServiceRequest + this.inProgress--; + let next: HttpServiceRequest; if (this.cache.hasOwnProperty(url)) { - delete this.cache[url] + delete this.cache[url]; } if (this.queue[1].length > 0) { - next = this.queue[1].shift() - this.get(next.url, next.successCallback, next.errorCallback, next.weight) + next = this.queue[1].shift(); + this.get(next.url, next.successCallback, next.errorCallback, next.weight); } else if (this.queue[0].length > 0) { - next = this.queue[0].shift() - this.get(next.url, next.successCallback, next.errorCallback, next.weight) + next = this.queue[0].shift(); + this.get(next.url, next.successCallback, next.errorCallback, next.weight); } - }) + }); } } @@ -122,29 +122,29 @@ export class HttpService { ping = (url: string, weight?: number): void => { // ping should simply change the weight if (weight === undefined) { - weight = 1 + weight = 1; } if (this.cache.hasOwnProperty(url)) { if (weight > this.cache[url].weight) { - const request = this.cache[url] - let index: number - if (request.weight === 0) index = this.queue[0].indexOf(request) - else index = this.queue[1].indexOf(request) + const request = this.cache[url]; + let index: number; + if (request.weight === 0) index = this.queue[0].indexOf(request); + else index = this.queue[1].indexOf(request); if (weight === 1 && index !== -1) { - request.weight = 1 - this.queue[1].push(request) - this.queue[0].splice(index, 1) + request.weight = 1; + this.queue[1].push(request); + this.queue[0].splice(index, 1); } else if (weight === 2 && index !== -1) { if (request.weight === 0) { - this.queue[0].splice(index, 1) + this.queue[0].splice(index, 1); } else { - this.queue[1].splice(index, 1) + this.queue[1].splice(index, 1); } - this.get(request.url, request.successCallback, request.errorCallback, weight) + this.get(request.url, request.successCallback, request.errorCallback, weight); } } } - } + }; /** * @name veUtils/HttpService#ping @@ -155,23 +155,23 @@ export class HttpService { if (this.queue[1].length > 0) { //will the queue ever be defined? for (let i = 0; i < this.queue[1].length; i++) { - this.queue[1][i].weight = 0 + this.queue[1][i].weight = 0; // if(cache.hasOwnProperty(queue[1][i].request.url)) // cache[queue[1][i].request.url].weight = 0; - this.queue[0].push(this.queue[1][i]) + this.queue[0].push(this.queue[1][i]); //queue[1][i].shift(); } //queue[0] = queue[0].concat(queue[1]); - this.queue[1] = [] + this.queue[1] = []; } - } + }; dropAll = (): void => { - this.queue[1].length = 0 - this.queue[0].length = 0 - this.cache = {} - this.inProgress = 0 - } + this.queue[1].length = 0; + this.queue[0].length = 0; + this.cache = {}; + this.inProgress = 0; + }; } -veUtils.service('HttpService', HttpService) +veUtils.service('HttpService', HttpService); diff --git a/src/ve-utils/mms-api-client/Permissions.service.ts b/src/ve-utils/mms-api-client/Permissions.service.ts index e49f41a54..6ffa7d5bc 100644 --- a/src/ve-utils/mms-api-client/Permissions.service.ts +++ b/src/ve-utils/mms-api-client/Permissions.service.ts @@ -1,13 +1,13 @@ -import { URLService } from '@ve-utils/mms-api-client' +import { URLService } from '@ve-utils/mms-api-client'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { PermissionsObject, PermissionsResponse, ProjectObject, RefObject } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { PermissionsObject, PermissionsResponse, ProjectObject, RefObject } from '@ve-types/mms'; export interface PermissionCache { - project: { [id: string]: boolean } - ref: { [id: string]: boolean } + project: { [id: string]: boolean }; + ref: { [id: string]: boolean }; } /** @@ -20,9 +20,9 @@ export interface PermissionCache { * * This utility service handles permissions inquiries */ export class PermissionsService { - private permissions: PermissionCache = { project: {}, ref: {} } + private permissions: PermissionCache = { project: {}, ref: {} }; - static $inject = ['$q', '$http', 'URLService'] + static $inject = ['$q', '$http', 'URLService']; constructor(private $q: VeQService, private $http: angular.IHttpService, private uRLSvc: URLService) {} @@ -30,15 +30,15 @@ export class PermissionsService { projectOb: ProjectObject, refOb: RefObject ): VePromise { - const url = this.uRLSvc.getPermissionsLookupURL() + const url = this.uRLSvc.getPermissionsLookupURL(); - const deferred = this.$q.defer() + const deferred = this.$q.defer(); if ( this.permissions.project[projectOb.id] !== undefined && this.permissions.ref[projectOb.id + '/' + refOb.id] !== undefined ) { - deferred.resolve(this.permissions) - return deferred.promise + deferred.resolve(this.permissions); + return deferred.promise; } this.$http .put(url, { @@ -58,39 +58,39 @@ export class PermissionsService { }) .then( (response) => { - const data: PermissionsObject[] = response.data.lookups + const data: PermissionsObject[] = response.data.lookups; if (Array.isArray(data) && data.length > 0) { data.forEach((d) => { if (d.type == 'PROJECT') { - this.permissions.project[d.projectId] = d.hasPrivilege + this.permissions.project[d.projectId] = d.hasPrivilege; } else { - this.permissions.ref[d.projectId + '/' + d.refId] = d.hasPrivilege + this.permissions.ref[d.projectId + '/' + d.refId] = d.hasPrivilege; } - }) - deferred.resolve(this.permissions) + }); + deferred.resolve(this.permissions); } else { deferred.reject({ status: 500, data: '', message: 'Server Error: empty response', - }) + }); } }, (response: angular.IHttpResponse) => { - deferred.reject(this.uRLSvc.handleHttpStatus(response)) + deferred.reject(this.uRLSvc.handleHttpStatus(response)); } - ) + ); - return deferred.promise + return deferred.promise; } public hasProjectEditPermission = (projectId: string): boolean => { - return this.permissions.project[projectId] - } + return this.permissions.project[projectId]; + }; public hasBranchEditPermission = (projectId: string, refId: string): boolean => { - return this.permissions.ref[projectId + '/' + refId] - } + return this.permissions.ref[projectId + '/' + refId]; + }; } -veUtils.service('PermissionsService', PermissionsService) +veUtils.service('PermissionsService', PermissionsService); diff --git a/src/ve-utils/mms-api-client/Project.service.ts b/src/ve-utils/mms-api-client/Project.service.ts index 479fb6334..568bc96e5 100644 --- a/src/ve-utils/mms-api-client/Project.service.ts +++ b/src/ve-utils/mms-api-client/Project.service.ts @@ -1,10 +1,10 @@ -import { CacheService } from '@ve-utils/core' -import { ApiService, ElementService, URLService } from '@ve-utils/mms-api-client' -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' +import { CacheService } from '@ve-utils/core'; +import { ApiService, ElementService, URLService } from '@ve-utils/mms-api-client'; +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' +import { VePromise, VeQService } from '@ve-types/angular'; import { CommitObject, CommitResponse, @@ -18,7 +18,7 @@ import { ProjectsResponse, RefObject, RefsResponse, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc service @@ -33,7 +33,7 @@ import { * * This is a utility service for getting project, ref, commit information */ export class ProjectService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'ElementService', 'URLService', 'ApiService'] + static $inject = ['$q', '$http', 'CacheService', 'ElementService', 'URLService', 'ApiService']; constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -42,7 +42,7 @@ export class ProjectService extends BaseApiService { private uRLSvc: URLService, private apiSvc: ApiService ) { - super() + super(); } /** @@ -53,16 +53,16 @@ export class ProjectService extends BaseApiService { * @returns {Promise} Resolves to the org object. */ public getOrg(orgId: string): VePromise { - const key = ['org', orgId] - const url = this.uRLSvc.getOrgURL(orgId) + const key = ['org', orgId]; + const url = this.uRLSvc.getOrgURL(orgId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(key)) { - resolve(this.cacheSvc.get(key)) - this._removeInProgress(url) - return + resolve(this.cacheSvc.get(key)); + this._removeInProgress(url); + return; } else { this.$http .get(url) @@ -73,23 +73,23 @@ export class ProjectService extends BaseApiService { status: 404, message: 'Org not found', type: 'error', - }) + }); } else { - this.cacheSvc.put(key, response.data.orgs[0], true) - resolve(this.cacheSvc.get(key)) + this.cacheSvc.put(key, response.data.orgs[0], true); + resolve(this.cacheSvc.get(key)); } }, (response: angular.IHttpResponse) => this.apiSvc.handleErrorCallback(response, reject) ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } /** @@ -99,46 +99,46 @@ export class ProjectService extends BaseApiService { * @returns {Promise} Resolves into array of org objects. */ public getOrgs(updateCache?: boolean): VePromise { - const key = 'orgs' + const key = 'orgs'; if (!this._isInProgress(key)) { this._addInProgress( key, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(key) && !updateCache) { - resolve(this.cacheSvc.get(key)) - this._removeInProgress(key) - return + resolve(this.cacheSvc.get(key)); + this._removeInProgress(key); + return; } else { this.$http .get(this.uRLSvc.getOrgsURL()) .then( (response) => { - const orgs: OrgObject[] = [] + const orgs: OrgObject[] = []; for (let i = 0; i < response.data.orgs.length; i++) { - const org = response.data.orgs[i] - this.cacheSvc.put(['org', org.id], org, true) - orgs.push(this.cacheSvc.get(['org', org.id])) + const org = response.data.orgs[i]; + this.cacheSvc.put(['org', org.id], org, true); + orgs.push(this.cacheSvc.get(['org', org.id])); } - this.cacheSvc.put(key, orgs, false) - resolve(this.cacheSvc.get(key)) + this.cacheSvc.put(key, orgs, false); + resolve(this.cacheSvc.get(key)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(key) - }) + this._removeInProgress(key); + }); } }) - ) + ); } - return this._getInProgress(key) as VePromise + return this._getInProgress(key) as VePromise; } public createOrg(name: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getOrgsURL() + const url = this.uRLSvc.getOrgsURL(); this.$http .post(url, { orgs: { name: name }, @@ -146,29 +146,29 @@ export class ProjectService extends BaseApiService { }) .then( (response) => { - const org = response.data.orgs[0] - const key = ['org', org.id] - this.cacheSvc.put(key, response.data.orgs[0], true) - resolve(this.cacheSvc.get(key)) + const org = response.data.orgs[0]; + const key = ['org', org.id]; + this.cacheSvc.put(key, response.data.orgs[0], true); + resolve(this.cacheSvc.get(key)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } public getProjects(orgId?: string, updateCache?: boolean): VePromise { - const url = this.uRLSvc.getProjectsURL(orgId) + const url = this.uRLSvc.getProjectsURL(orgId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = !orgId ? 'projects' : ['projects', orgId] + const cacheKey = !orgId ? 'projects' : ['projects', orgId]; if (this.cacheSvc.exists(cacheKey) && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)) - this._removeInProgress(url) - return + resolve(this.cacheSvc.get(cacheKey)); + this._removeInProgress(url); + return; } else { this.$http .get(url) @@ -179,62 +179,62 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } if (!orgId) { const orgProjects: { - [orgId: string]: ProjectObject[] - } = {} + [orgId: string]: ProjectObject[]; + } = {}; response.data.projects.forEach((project) => { - const porg = project.orgId + const porg = project.orgId; const pCacheKey = this.apiSvc.makeCacheKey( null, project.id, false, 'project' - ) + ); if (orgProjects[porg] === undefined) { - orgProjects[porg] = [] + orgProjects[porg] = []; } - orgProjects[porg].push(this.cacheSvc.put(pCacheKey, project, true)) + orgProjects[porg].push(this.cacheSvc.put(pCacheKey, project, true)); Object.keys(orgProjects).forEach((orgId) => { this.cacheSvc.put( this.apiSvc.makeCacheKey(null, orgId, false, 'projects'), orgProjects[orgId], false - ) - }) - }) + ); + }); + }); } - resolve(this.cacheSvc.put(cacheKey, response.data.projects)) + resolve(this.cacheSvc.put(cacheKey, response.data.projects)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as angular.IPromise + return this._getInProgress(url) as angular.IPromise; } public getProject(projectId: string, updateCache?: string): VePromise { - const url = this.uRLSvc.getProjectURL(projectId) + const url = this.uRLSvc.getProjectURL(projectId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = ['project', projectId] - const cached = this.cacheSvc.get(cacheKey) + const cacheKey = ['project', projectId]; + const cached = this.cacheSvc.get(cacheKey); if (cached && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)) - this._removeInProgress(url) + resolve(this.cacheSvc.get(cacheKey)); + this._removeInProgress(url); } else { this.$http .get(url) @@ -245,24 +245,24 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } - this.cacheSvc.put(cacheKey, response.data.projects[0], true) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, response.data.projects[0], true); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as angular.IPromise + return this._getInProgress(url) as angular.IPromise; } public getProjectMounts( @@ -270,12 +270,12 @@ export class ProjectService extends BaseApiService { refId: string, updateCache?: boolean ): VePromise { - const url = this.uRLSvc.getProjectMountsURL(projectId, refId) + const url = this.uRLSvc.getProjectMountsURL(projectId, refId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'project-mounts') + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'project-mounts'); this.getProject(projectId).then( (response: ProjectObject) => { @@ -284,14 +284,14 @@ export class ProjectService extends BaseApiService { _mounts: [], _projectId: response.id, _refId: refId, - } - const result: MountObject = Object.assign(mountOb, response) - const cached: MountObject = this.cacheSvc.get(cacheKey) + }; + const result: MountObject = Object.assign(mountOb, response); + const cached: MountObject = this.cacheSvc.get(cacheKey); if (this.cacheSvc.exists(cacheKey) && !updateCache) { - result._mounts.push(...cached._mounts) - resolve(result) - this._removeInProgress(url) - return + result._mounts.push(...cached._mounts); + resolve(result); + this._removeInProgress(url); + return; } else { this.$http .get(url) @@ -305,62 +305,62 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } if (response.data.projects[0]._mounts) { - result._mounts = (response.data.projects[0] as MountObject)._mounts + result._mounts = (response.data.projects[0] as MountObject)._mounts; } - resolve(this.cacheSvc.put(cacheKey, result, false)) + resolve(this.cacheSvc.put(cacheKey, result, false)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }, (response) => { - reject(response) - this._removeInProgress(url) + reject(response); + this._removeInProgress(url); } - ) + ); }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getAllMountsAsArray = (project: MountObject): MountObject[] => { - const projectsList: MountObject[] = [project] - const mounts = project._mounts + const projectsList: MountObject[] = [project]; + const mounts = project._mounts; const getMountsArray = (mounts: MountObject[], projectsList: MountObject[]): void => { if (Array.isArray(mounts) && mounts.length !== 0) { for (let i = 0; i < mounts.length; i++) { - projectsList.push(mounts[i]) + projectsList.push(mounts[i]); if (mounts[i]._mounts) { - getMountsArray(mounts[i]._mounts, projectsList) + getMountsArray(mounts[i]._mounts, projectsList); } } } - } - getMountsArray(mounts, projectsList) - return projectsList - } + }; + getMountsArray(mounts, projectsList); + return projectsList; + }; public getRefs(projectId: string): VePromise { - const cacheKey = this.apiSvc.makeCacheKey(null, projectId, false, 'refs') - const url = this.uRLSvc.getRefsURL(projectId) + const cacheKey = this.apiSvc.makeCacheKey(null, projectId, false, 'refs'); + const url = this.uRLSvc.getRefsURL(projectId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(cacheKey)) { - resolve(this.cacheSvc.get(cacheKey)) - this._removeInProgress(url) - return + resolve(this.cacheSvc.get(cacheKey)); + this._removeInProgress(url); + return; } else { this.$http .get(url) @@ -371,73 +371,73 @@ export class ProjectService extends BaseApiService { status: 500, message: 'Server Error: empty response', - }) - return + }); + return; } - const refs: RefObject[] = [] + const refs: RefObject[] = []; for (let index = 0; index < response.data.refs.length; index++) { - const ref: RefObject = response.data.refs[index] + const ref: RefObject = response.data.refs[index]; if (ref.id === 'master') { - ref.type = 'Branch' + ref.type = 'Branch'; } const refCacheKey: string[] = this.apiSvc.makeCacheKey( { projectId: projectId, refId: ref.id }, '', false, 'ref' - ) - this.cacheSvc.put(refCacheKey, ref, true) - refs.push(this.cacheSvc.get(refCacheKey)) + ); + this.cacheSvc.put(refCacheKey, ref, true); + refs.push(this.cacheSvc.get(refCacheKey)); } - this.cacheSvc.put(cacheKey, refs, false) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, refs, false); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getRef(refId: string, projectId: string, updateCache?: boolean): VePromise { - const url = this.uRLSvc.getRefURL(projectId, refId) + const url = this.uRLSvc.getRefURL(projectId, refId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'ref') - const cached = this.cacheSvc.get(cacheKey) + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'ref'); + const cached = this.cacheSvc.get(cacheKey); if (cached && !updateCache) { - this._removeInProgress(url) - resolve(cached) + this._removeInProgress(url); + resolve(cached); } else { this.$http .get(url) .then( (response) => { - this.cacheSvc.put(cacheKey, response.data.refs[0]) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, response.data.refs[0]); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getCommits( @@ -446,11 +446,11 @@ export class ProjectService extends BaseApiService { timestamp?: string, limit?: number ): VePromise { - let url: string + let url: string; if (timestamp !== null) { - url = this.uRLSvc.getCommitsURL(projectId, refId, timestamp, limit) + url = this.uRLSvc.getCommitsURL(projectId, refId, timestamp, limit); } else { - url = this.uRLSvc.getCommitsURL(projectId, refId, null, limit) + url = this.uRLSvc.getCommitsURL(projectId, refId, null, limit); } if (!this._isInProgress(url)) { this._addInProgress( @@ -466,63 +466,63 @@ export class ProjectService extends BaseApiService { message: 'Project does not exist at specified time.', type: 'error', - }) - return + }); + return; } - resolve(response.data.commits) + resolve(response.data.commits); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getCommit(projectId: string, refId: string, commitId: string): VePromise { - const url = this.uRLSvc.getCommitUrl(projectId, refId, commitId) + const url = this.uRLSvc.getCommitUrl(projectId, refId, commitId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId, commitId }, '', false, 'commit') + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId, commitId }, '', false, 'commit'); if (this.cacheSvc.exists(cacheKey)) { - resolve(this.cacheSvc.get(cacheKey)) + resolve(this.cacheSvc.get(cacheKey)); } else { this.$http .get(url) .then( (response) => { - resolve(this.cacheSvc.put(cacheKey, response.data.commits[0])) + resolve(this.cacheSvc.put(cacheKey, response.data.commits[0])); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public createRef(refOb: RefObject, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefsURL(projectId) + const url = this.uRLSvc.getRefsURL(projectId); const cacheKey = this.apiSvc.makeCacheKey( { projectId: refOb._projectId, refId: refOb.id }, '', false, 'ref' - ) + ); this.$http .post(url, { refs: [refOb], @@ -536,30 +536,30 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } - const createdRef = response.data.refs[0] + const createdRef = response.data.refs[0]; const list = this.cacheSvc.get( this.apiSvc.makeCacheKey(null, projectId, false, 'refs'), true - ) + ); if (list) { - list.push(createdRef) + list.push(createdRef); } - this.cacheSvc.put(cacheKey, createdRef) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, createdRef); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } public updateRef(refOb: RefObject, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefsURL(projectId) + const url = this.uRLSvc.getRefsURL(projectId); this.$http .post(url, { refs: [refOb], @@ -573,49 +573,49 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } - const resp = response.data.refs[0] - this.cacheSvc.put(['ref', projectId, resp.id], resp, true) - resolve(this.cacheSvc.get(['ref', projectId, resp.id])) + const resp = response.data.refs[0]; + this.cacheSvc.put(['ref', projectId, resp.id], resp, true); + resolve(this.cacheSvc.get(['ref', projectId, resp.id])); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } public deleteRef(refId: string, projectId: string): VePromise { return new this.$q((resolve, reject) => { - const url = this.uRLSvc.getRefURL(projectId, refId) + const url = this.uRLSvc.getRefURL(projectId, refId); this.$http.delete(url).then( (response) => { - const key = this.apiSvc.makeCacheKey({ refId, projectId }, '', false, 'ref') - const refOb = this.cacheSvc.get(key) + const key = this.apiSvc.makeCacheKey({ refId, projectId }, '', false, 'ref'); + const refOb = this.cacheSvc.get(key); if (refOb) { - this.cacheSvc.remove(key) + this.cacheSvc.remove(key); const list = this.cacheSvc.get( this.apiSvc.makeCacheKey(null, projectId, false, 'refs'), true - ) + ); if (list) { for (let i = 0; i < list.length; i++) { if (list[i].id === refOb.id) { - list.splice(i, 1) - break + list.splice(i, 1); + break; } } } } - resolve() + resolve(); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } - ) - }) + ); + }); } public getGroups( @@ -623,14 +623,14 @@ export class ProjectService extends BaseApiService { refId: string, updateCache?: boolean ): VePromise { - const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'groups') - const url = this.uRLSvc.getGroupsURL(projectId, refId) + const cacheKey = this.apiSvc.makeCacheKey({ projectId, refId }, '', false, 'groups'); + const url = this.uRLSvc.getGroupsURL(projectId, refId); if (!this._isInProgress(url)) { this._addInProgress( url, new this.$q((resolve, reject) => { if (this.cacheSvc.exists(cacheKey) && !updateCache) { - resolve(this.cacheSvc.get(cacheKey)) + resolve(this.cacheSvc.get(cacheKey)); } else { this.$http .get(url) @@ -642,64 +642,64 @@ export class ProjectService extends BaseApiService { message: 'Server Error: empty response', type: 'error', - }) - return + }); + return; } - const groups: GroupObject[] = [] + const groups: GroupObject[] = []; const reqOb = { projectId: projectId, refId: refId, commitId: 'latest', elementId: '', - } + }; for (let i = 0; i < response.data.groups.length; i++) { - let group: GroupObject = response.data.groups[i] - reqOb.elementId = group.id - group = this.elementSvc.cacheElement(reqOb, group) - this.cacheSvc.put(['group', projectId, refId, group.id], group, true) + let group: GroupObject = response.data.groups[i]; + reqOb.elementId = group.id; + group = this.elementSvc.cacheElement(reqOb, group); + this.cacheSvc.put(['group', projectId, refId, group.id], group, true); groups.push( this.cacheSvc.get(['group', projectId, refId, group.id]) - ) + ); } - this.cacheSvc.put(cacheKey, groups, false) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, groups, false); + resolve(this.cacheSvc.get(cacheKey)); }, (response: angular.IHttpResponse) => { - this.apiSvc.handleErrorCallback(response, reject) + this.apiSvc.handleErrorCallback(response, reject); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); } }) - ) + ); } - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } public getGroup(id: string, projectId: string, refId: string): VePromise { return new this.$q((resolve, reject) => { this.getGroups(projectId, refId).then( (data) => { - const result = this.cacheSvc.get(['group', projectId, refId, id]) + const result = this.cacheSvc.get(['group', projectId, refId, id]); if (result) { - resolve(result) + resolve(result); } else { reject({ status: 404, message: 'Group not found', type: 'error', - }) + }); } }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } } -veUtils.service('ProjectService', ProjectService) +veUtils.service('ProjectService', ProjectService); diff --git a/src/ve-utils/mms-api-client/URL.service.ts b/src/ve-utils/mms-api-client/URL.service.ts index 11e0a3684..a024dbeaf 100644 --- a/src/ve-utils/mms-api-client/URL.service.ts +++ b/src/ve-utils/mms-api-client/URL.service.ts @@ -1,7 +1,7 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromiseReason } from '@ve-types/angular' -import { VeConfig } from '@ve-types/config' +import { VePromiseReason } from '@ve-types/angular'; +import { VeConfig } from '@ve-types/config'; import { ArtifactsRequest, BasicResponse, @@ -10,7 +10,7 @@ import { QueryParams, RequestObject, ViewsRequest, -} from '@ve-types/mms' +} from '@ve-types/mms'; /** * @ngdoc service @@ -33,63 +33,63 @@ import { * actually getting the resources from a different server, solution TBD) */ export class URLService { - readonly root: string - readonly url: URL - private token: string - private veConfig: VeConfig = window.__env + readonly root: string; + readonly url: URL; + private token: string; + private veConfig: VeConfig = window.__env; - static $inject = [] + static $inject = []; constructor(readonly basePath?: string, readonly apiUrl?: string) { if (!this.apiUrl) { - this.apiUrl = this.veConfig.apiUrl + this.apiUrl = this.veConfig.apiUrl; } if (!this.apiUrl) { - throw new Error('Unable to find "apiUrl" configuration for MMS. Please check your configuration file.') + throw new Error('Unable to find "apiUrl" configuration for MMS. Please check your configuration file.'); } - this.url = new URL(this.apiUrl) - this.url.pathname = this.veConfig.basePath ? this.veConfig.basePath : '/' + this.url = new URL(this.apiUrl); + this.url.pathname = this.veConfig.basePath ? this.veConfig.basePath : '/'; - this.root = `${this.apiUrl}${this.basePath ? this.basePath : ''}` - const token = localStorage.getItem('token') - this.token = `${token}` + this.root = `${this.apiUrl}${this.basePath ? this.basePath : ''}`; + const token = localStorage.getItem('token'); + this.token = `${token}`; } getRoot = (): string => { - return this.root - } + return this.root; + }; getUrl = (): URL => { - return Object.assign({}, this.url) - } + return Object.assign({}, this.url); + }; setToken = (t: string): void => { - this.token = t - } + this.token = t; + }; getAuthorizationHeaderValue = (): string => { - return 'Bearer ' + this.token - } + return 'Bearer ' + this.token; + }; getAuthorizationHeader = (headers: angular.HttpHeaderType): angular.HttpHeaderType => { if (!this.token) { - const token = localStorage.getItem('token') + const token = localStorage.getItem('token'); if (!token) { - return headers + return headers; } else { - this.setToken(token) + this.setToken(token); } } if (!headers) { - headers = this.getHeaders() + headers = this.getHeaders(); } - headers.Authorization = this.getAuthorizationHeaderValue() - return headers - } + headers.Authorization = this.getAuthorizationHeaderValue(); + return headers; + }; getMmsServer = (): string => { - return this.apiUrl - } + return this.apiUrl; + }; /** * @name veUtils/URLService#setHeader @@ -101,7 +101,7 @@ export class URLService { return { 'Content-Type': 'application/json', Authorization: 'Bearer ' + this.token, - } + }; } /** @@ -112,10 +112,10 @@ export class URLService { * @returns {boolean} Returns true if the string has '-' in it */ isTimestamp = (version?: string): boolean => { - if (!version) return false - else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}[+]?-\d{4}$/.test(version.trim())) return true - return false - } + if (!version) return false; + else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}[+]?-\d{4}$/.test(version.trim())) return true; + return false; + }; /** * @name veUtils/URLService#getMmsVersionURL @@ -124,8 +124,8 @@ export class URLService { * @returns {object} Returns object with mmsversion */ getMmsVersionURL = (): string => { - return `${this.root}/mmsversion` - } + return `${this.root}/mmsversion`; + }; /** * @name veUtils/URLService#getSiteDashboardURL @@ -135,8 +135,8 @@ export class URLService { * @returns {string} The path for site dashboard. */ getSiteDashboardURL = (site: string): string => { - return `${this.root}/orgs/${site}/projects/${site}/branches/master/elements` - } + return `${this.root}/orgs/${site}/projects/${site}/branches/master/elements`; + }; /** * @name veUtils/URLService#getExportHtmlUrl @@ -146,67 +146,67 @@ export class URLService { * @returns {string} The url */ getExportHtmlUrl = (): string => { - return this.veConfig.printUrl - } + return this.veConfig.printUrl; + }; getAuthenticationUrl = (): string => { - return `${this.root}/authentication` - } + return `${this.root}/authentication`; + }; getPermissionsLookupURL = (): string => { - return `${this.root}/permissions` - } + return `${this.root}/permissions`; + }; getOrgURL = (orgId: string): string => { - return `${this.root}/orgs/${orgId}` - } + return `${this.root}/orgs/${orgId}`; + }; getOrgsURL = (): string => { - return `${this.root}/orgs` - } + return `${this.root}/orgs`; + }; getProjectsURL = (orgId?: string): string => { - if (orgId) return `${this.root}/projects?orgId=${orgId}` - return `${this.root}/projects` - } + if (orgId) return `${this.root}/projects?orgId=${orgId}`; + return `${this.root}/projects`; + }; getProjectURL = (projectId: string): string => { - return `${this.root}/projects/${projectId}` - } + return `${this.root}/projects/${projectId}`; + }; getProjectMountsURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/mounts` - } + return `${this.root}/projects/${projectId}/refs/${refId}/mounts`; + }; getRefsURL = (projectId: string): string => { - return `${this.root}/projects/${projectId}/refs` - } + return `${this.root}/projects/${projectId}/refs`; + }; getRefURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}` - } + return `${this.root}/projects/${projectId}/refs/${refId}`; + }; getCommitsURL = (projectId: string, refId: string, timestamp?: string, limit?: number): string => { - let r = `${this.root}/projects/${projectId}/refs/${refId}/commits` + let r = `${this.root}/projects/${projectId}/refs/${refId}/commits`; if (timestamp && this.isTimestamp(timestamp)) { - r = this._addUrlParam({ maxTimestamp: timestamp }, r) + r = this._addUrlParam({ maxTimestamp: timestamp }, r); if (!limit) { - limit = 1 + limit = 1; } } if (limit) { - r = this._addUrlParam({ limit: limit }, r) + r = this._addUrlParam({ limit: limit }, r); } - return r - } + return r; + }; getCommitUrl = (projectId: string, refId: string, commitId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/commits/${commitId}` - } + return `${this.root}/projects/${projectId}/refs/${refId}/commits/${commitId}`; + }; getGroupsURL = (projectId: string, refId: string): string => { - return `${this.root}/projects/${projectId}/refs/${refId}/groups` - } + return `${this.root}/projects/${projectId}/refs/${refId}/groups`; + }; /** * @name veUtils/URLService#getProjectDocumentsURL @@ -216,9 +216,9 @@ export class URLService { * @returns {string} The url */ getProjectDocumentsURL = (reqOb: RequestObject): string => { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/documents` - return this.addVersion(r, reqOb.commitId) - } + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/documents`; + return this.addVersion(r, reqOb.commitId); + }; /** * @name veUtils/URLService#getImageURL @@ -228,8 +228,8 @@ export class URLService { * @returns {string} The path for image url queries. */ getImageURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` - return this.addVersion(r, reqOb.commitId) + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; + return this.addVersion(r, reqOb.commitId); } /** @@ -240,8 +240,8 @@ export class URLService { * @returns {string} The url. */ getElementURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views/${reqOb.elementId}` - return this.addVersion(r, reqOb.commitId) + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views/${reqOb.elementId}`; + return this.addVersion(r, reqOb.commitId); } // getViewDataIdsURL (reqOb: RequestObject): string { @@ -270,16 +270,16 @@ export class URLService { // } getOwnedElementURL(reqOb: ElementsRequest): string { - let recurseString = 'recurse=true' - if (reqOb.depth) recurseString = `depth=${reqOb.depth}` - let r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` - r = this.addVersion(r, reqOb.commitId) + let recurseString = 'recurse=true'; + if (reqOb.depth) recurseString = `depth=${reqOb.depth}`; + let r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; + r = this.addVersion(r, reqOb.commitId); if (r.indexOf('?') > 0) { - r += '&' + recurseString + r += '&' + recurseString; } else { - r += '?' + recurseString + r += '?' + recurseString; } - return r + return r; } /** @@ -290,7 +290,7 @@ export class URLService { * @returns {string} The url. */ getElementHistoryURL(reqOb: ElementsRequest): string { - return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/commits` + return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/commits`; } /** @@ -303,8 +303,8 @@ export class URLService { return this.addChildViews( `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views`, reqOb.returnChildViews - ) - } + ); + }; /** * @name veUtils/URLService#getPostElementsURL @@ -314,8 +314,8 @@ export class URLService { * @returns {string} The post elements url. */ getPostElementsURL = (reqOb: RequestObject): string => { - return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements` - } + return `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements`; + }; /** * @name veUtils/URLService#getPutElementsURL @@ -325,9 +325,9 @@ export class URLService { * @returns {string} The post elements url. */ getPutElementsURL = (reqOb: RequestObject): string => { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views` - return this.addVersion(r, reqOb.commitId) - } + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/views`; + return this.addVersion(r, reqOb.commitId); + }; /** * @name veUtils/URLService#getElementSearchURL @@ -338,18 +338,18 @@ export class URLService { * @returns {string} The post elements url. */ getElementSearchURL = (reqOb: RequestObject, queryParams?: QueryParams): string => { - let r: string - let urlParams = '' + let r: string; + let urlParams = ''; if (queryParams) { - urlParams = this._addUrlParam(queryParams) + urlParams = this._addUrlParam(queryParams); } if (urlParams !== '') { - r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search${urlParams}` + r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search${urlParams}`; } else { - r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search` + r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/search`; } - return r - } + return r; + }; /** * @ngdocs method @@ -362,9 +362,9 @@ export class URLService { */ getArtifactURL(reqOb: ElementsRequest | ArtifactsRequest, artifactExtension?: string): string { const ext = - artifactExtension !== undefined ? artifactExtension : (reqOb as ArtifactsRequest).artifactExtension - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}` - return this.addToken(this.addVersion(r, reqOb.commitId)) + artifactExtension !== undefined ? artifactExtension : (reqOb as ArtifactsRequest).artifactExtension; + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}`; + return this.addToken(this.addVersion(r, reqOb.commitId)); } /** @@ -377,9 +377,9 @@ export class URLService { * @returns {string} url */ getArtifactEmbedURL(reqOb: ArtifactsRequest, artifactExtension: string): string { - const ext = artifactExtension !== undefined ? artifactExtension : 'undefined' - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}` - return this.addVersion(r, reqOb.commitId) + const ext = artifactExtension !== undefined ? artifactExtension : 'undefined'; + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}/${ext}`; + return this.addVersion(r, reqOb.commitId); } /** @@ -391,8 +391,8 @@ export class URLService { * @returns {string} url */ getPutArtifactsURL(reqOb: ElementsRequest): string { - const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}` - return this.addVersion(r, reqOb.commitId) + const r = `${this.root}/projects/${reqOb.projectId}/refs/${reqOb.refId}/elements/${reqOb.elementId}`; + return this.addVersion(r, reqOb.commitId); } /** @@ -404,16 +404,16 @@ export class URLService { * @returns {string} url */ getArtifactHistoryURL(reqOb: ElementsRequest): string { - return this.getElementHistoryURL(reqOb) + return this.getElementHistoryURL(reqOb); } getCheckTokenURL = (): string => { - return `${this.root}/checkAuth` //TODO remove when server returns 404 - } + return `${this.root}/checkAuth`; //TODO remove when server returns 404 + }; getPersonURL = (username: string): string => { - return `${this.root}/users?user=${username}` - } + return `${this.root}/users?user=${username}`; + }; /** * @name veUtils/URLService#handleHttpStatus @@ -435,22 +435,22 @@ export class URLService { handleHttpStatus>( response: angular.IHttpResponse ): VePromiseReason { - const result: VePromiseReason = response - const data: U = result.data - if (result.status === 404) result.message = 'Not Found' + const result: VePromiseReason = response; + const data: U = result.data; + if (result.status === 404) result.message = 'Not Found'; else if (result.status === 500) { if (typeof data === 'string' && data.indexOf('ENOTFOUND') >= 0) - result.message = 'Network Error (Please check network)' - else result.message = 'Server Error' - } else if (result.status === 401 || result.status === 403) result.message = 'Permission Error' - else if (result.status === 409) result.message = 'Conflict' - else if (result.status === 400) result.message = 'BadRequestObject' - else if (result.status === 410) result.message = 'Deleted' - else if (result.status === 408) result.message = 'Timed Out' + result.message = 'Network Error (Please check network)'; + else result.message = 'Server Error'; + } else if (result.status === 401 || result.status === 403) result.message = 'Permission Error'; + else if (result.status === 409) result.message = 'Conflict'; + else if (result.status === 400) result.message = 'BadRequestObject'; + else if (result.status === 410) result.message = 'Deleted'; + else if (result.status === 408) result.message = 'Timed Out'; else if (result.status === 501) { - result.message = 'Caching' - } else result.message = 'Timed Out (Please check network)' - return result + result.message = 'Caching'; + } else result.message = 'Timed Out (Please check network)'; + return result; } /** @@ -462,18 +462,18 @@ export class URLService { * @returns {string} The url with commitId parameter added. */ private addVersion = (url: string, version: string): string => { - const r = url + const r = url; if (version && version !== 'latest') { - return this._addUrlParam({ commitId: version }, url) + return this._addUrlParam({ commitId: version }, url); } - return r - } + return r; + }; private addChildViews = (url: string, add: boolean): string => { - const r = url - if (!add) return r - return this._addUrlParam({ childviews: true }, r) - } + const r = url; + if (!add) return r; + return this._addUrlParam({ childviews: true }, r); + }; /** * @name veUtils/URLService#addToken @@ -483,31 +483,31 @@ export class URLService { * @returns {string} The url with commitId parameter added. */ private addToken = (url: string): string => { - return this._addUrlParam({ token: this.token }, url) - } + return this._addUrlParam({ token: this.token }, url); + }; private _addUrlParam( paramOb: { - [key: string]: string | boolean | number + [key: string]: string | boolean | number; }, url?: string ): string { - let urlParams = '' + let urlParams = ''; if (url) { - urlParams = url + urlParams = url; } for (const [key, value] of Object.entries(paramOb)) { - let v: string - if (typeof value === 'string') v = value - else v = value.toString() + let v: string; + if (typeof value === 'string') v = value; + else v = value.toString(); if (urlParams.indexOf('?') > 0) { - urlParams += `&${key}=${v}` + urlParams += `&${key}=${v}`; } else { - urlParams += `?${key}=${v}` + urlParams += `?${key}=${v}`; } } - return urlParams + return urlParams; } } -veUtils.service('URLService', URLService) +veUtils.service('URLService', URLService); diff --git a/src/ve-utils/mms-api-client/User.service.ts b/src/ve-utils/mms-api-client/User.service.ts index 74108055a..e14a27a69 100644 --- a/src/ve-utils/mms-api-client/User.service.ts +++ b/src/ve-utils/mms-api-client/User.service.ts @@ -1,14 +1,14 @@ -import { CacheService } from '@ve-utils/core' -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' -import { URLService } from '@ve-utils/mms-api-client/URL.service' +import { CacheService } from '@ve-utils/core'; +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; +import { URLService } from '@ve-utils/mms-api-client/URL.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' -import { UserObject, UsersResponse } from '@ve-types/mms' +import { VePromise, VeQService } from '@ve-types/angular'; +import { UserObject, UsersResponse } from '@ve-types/mms'; export class UserService extends BaseApiService { - static $inject = ['$q', '$http', 'CacheService', 'URLService'] + static $inject = ['$q', '$http', 'CacheService', 'URLService']; constructor( private $q: VeQService, @@ -16,20 +16,20 @@ export class UserService extends BaseApiService { private cacheSvc: CacheService, private uRLSvc: URLService ) { - super() + super(); } getUserData(username: string): VePromise { - const key = ['user', username] - const url = this.uRLSvc.getPersonURL(username) - const cached = this.cacheSvc.get(key) + const key = ['user', username]; + const url = this.uRLSvc.getPersonURL(username); + const cached = this.cacheSvc.get(key); if (this._isInProgress(url)) { - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } if (cached) { return new this.$q((resolve, reject) => { - return resolve(cached) - }) + return resolve(cached); + }); } this._addInProgress( url, @@ -42,25 +42,25 @@ export class UserService extends BaseApiService { reject({ status: 404, message: 'User not found', - }) + }); } else { - this.cacheSvc.put(key, response.data.users[0], false) - resolve(this.cacheSvc.get(key)) + this.cacheSvc.put(key, response.data.users[0], false); + resolve(this.cacheSvc.get(key)); } }, (response: angular.IHttpResponse) => { - this.uRLSvc.handleHttpStatus(response) - reject(response) + this.uRLSvc.handleHttpStatus(response); + reject(response); } ) .finally(() => { - this._removeInProgress(url) - }) + this._removeInProgress(url); + }); }) - ) + ); - return this._getInProgress(url) as VePromise + return this._getInProgress(url) as VePromise; } } -veUtils.service('UserService', UserService) +veUtils.service('UserService', UserService); diff --git a/src/ve-utils/mms-api-client/Value.service.ts b/src/ve-utils/mms-api-client/Value.service.ts index 411231339..2c52cdd83 100644 --- a/src/ve-utils/mms-api-client/Value.service.ts +++ b/src/ve-utils/mms-api-client/Value.service.ts @@ -1,15 +1,15 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { EditObject } from '@ve-utils/core' -import { ApiService } from '@ve-utils/mms-api-client/Api.service' -import { ElementService } from '@ve-utils/mms-api-client/Element.service' -import { ValueSpec } from '@ve-utils/utils' +import { EditObject } from '@ve-utils/core'; +import { ApiService } from '@ve-utils/mms-api-client/Api.service'; +import { ElementService } from '@ve-utils/mms-api-client/Element.service'; +import { ValueSpec } from '@ve-utils/utils'; -import { PropertySpec } from '@ve-components' +import { PropertySpec } from '@ve-components'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VeQService } from '@ve-types/angular' +import { VePromise, VeQService } from '@ve-types/angular'; import { ConstraintObject, ElementObject, @@ -22,7 +22,7 @@ import { SlotObject, TaggedValueObject, ValueObject, -} from '@ve-types/mms' +} from '@ve-types/mms'; export class ValueService { private valueTypes: { [type: string]: string } = { @@ -30,28 +30,28 @@ export class ValueService { port: 'defaultValue', slot: 'value', constraint: 'specification', - } + }; public addValueTypes: { [primitiveType: string]: string } = { string: 'LiteralString', boolean: 'LiteralBoolean', integer: 'LiteralInteger', real: 'LiteralReal', - } + }; - private taggedValue: string = 'value' - static $inject = ['$q', 'ApiService', 'ElementService'] + private taggedValue: string = 'value'; + static $inject = ['$q', 'ApiService', 'ElementService']; constructor(private $q: VeQService, private apiSvc: ApiService, private elementSvc: ElementService) {} public addValue = (editOb: EditObject, type: string): LiteralObject => { - const edit = editOb.element - let newValueSpec: ValueSpec + const edit = editOb.element; + let newValueSpec: ValueSpec; let elementOb: LiteralObject = { id: '', _projectId: edit._projectId, _refId: edit._refId, type: '', - } + }; switch (type) { case 'LiteralBoolean': { elementOb = Object.assign(elementOb, { @@ -59,9 +59,9 @@ export class ValueService { value: false, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) - newValueSpec = new ValueSpec(elementOb) - break + }); + newValueSpec = new ValueSpec(elementOb); + break; } case 'LiteralInteger': { elementOb = Object.assign(elementOb, { @@ -69,9 +69,9 @@ export class ValueService { value: 0, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) - newValueSpec = new ValueSpec(elementOb) - break + }); + newValueSpec = new ValueSpec(elementOb); + break; } case 'LiteralString': { elementOb = Object.assign(elementOb, { @@ -79,9 +79,9 @@ export class ValueService { value: '', id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) - newValueSpec = new ValueSpec(elementOb) - break + }); + newValueSpec = new ValueSpec(elementOb); + break; } case 'LiteralReal': { elementOb = Object.assign(elementOb, { @@ -89,9 +89,9 @@ export class ValueService { value: 0.0, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) - newValueSpec = new ValueSpec(elementOb) - break + }); + newValueSpec = new ValueSpec(elementOb); + break; } default: { elementOb = Object.assign(elementOb, { @@ -99,21 +99,21 @@ export class ValueService { value: {}, id: this.apiSvc.createUniqueId(), ownerId: edit.id, - }) + }); } } if (edit.type == 'Property' || edit.type == 'Port') { - edit.defaultValue = newValueSpec + edit.defaultValue = newValueSpec; } - return newValueSpec - } + return newValueSpec; + }; public addEnumerationValue = ( propertySpec: PropertySpec, editOb: EditObject ): InstanceValueObject | ElementValueObject => { - const elementOb = editOb.element + const elementOb = editOb.element; let newValueSpec: InstanceValueObject | ElementValueObject = new ValueSpec({ type: 'InstanceValue', instanceId: propertySpec.options[0], @@ -121,7 +121,7 @@ export class ValueService { _refId: elementOb._refId, id: this.apiSvc.createUniqueId(), ownerId: elementOb.id, - }) + }); if (propertySpec.isTaggedValue) { newValueSpec = new ValueSpec({ type: 'ElementValue', @@ -130,51 +130,51 @@ export class ValueService { _refId: elementOb._refId, id: this.apiSvc.createUniqueId(), ownerId: elementOb.id, - }) + }); } - return newValueSpec - } + return newValueSpec; + }; public getValues(elementOb: ElementObject): ValueObject[] { if (elementOb.type === 'Property' || elementOb.type === 'Port') { if (elementOb.defaultValue) { - return [elementOb.defaultValue] as ValueObject[] + return [elementOb.defaultValue] as ValueObject[]; } else { - return [] + return []; } } if (elementOb.type === 'Slot') { - return (elementOb as SlotObject).value + return (elementOb as SlotObject).value; } if (elementOb.type === 'Constraint' && elementOb.specification) { - return [(elementOb as ConstraintObject).specification] + return [(elementOb as ConstraintObject).specification]; } if (elementOb.type === 'Expression') { - return (elementOb as ExpressionObject).operand + return (elementOb as ExpressionObject).operand; } - const i = elementOb.type.indexOf('TaggedValue') + const i = elementOb.type.indexOf('TaggedValue'); if (i > 0) { - let spoofType = '' - const type = elementOb.type.slice(0, i) + let spoofType = ''; + const type = elementOb.type.slice(0, i); if (type === 'Element') { - spoofType = 'ElementValue' - elementOb.value = [] + spoofType = 'ElementValue'; + elementOb.value = []; for (const [index, val] of (elementOb as ElementTaggedValueObject).valueIds.entries()) { - ;(elementOb as ElementTaggedValueObject).value.push({ + (elementOb as ElementTaggedValueObject).value.push({ id: `${elementOb.id}-slotvalue-${index}-elementvalue`, type: spoofType, elementId: val, _projectId: elementOb._projectId, _refId: elementOb._refId, - } as ElementValueObject) + } as ElementValueObject); } } else { - spoofType = `Literal${type}` + spoofType = `Literal${type}`; for (const val of (elementOb as TaggedValueObject).value) { - val.type = spoofType + val.type = spoofType; } } - return (elementOb as TaggedValueObject).value + return (elementOb as TaggedValueObject).value; } } @@ -187,53 +187,53 @@ export class ValueService { * For unsuccessful saves, it will be rejected with an object with reason. */ public isEnumeration(elementOb: ElementObject): VePromise { - const deferred = this.$q.defer() + const deferred = this.$q.defer(); if (elementOb.type === 'Enumeration') { - const isEnumeration = true + const isEnumeration = true; const reqOb: ElementsRequest = { elementId: elementOb.id, projectId: elementOb._projectId, refId: elementOb._refId, - } + }; const query = { params: { ownerId: elementOb.id, }, - } + }; this.elementSvc.search(reqOb, query).then( (val) => { - const newArray: ElementObject[] = [] + const newArray: ElementObject[] = []; // Filter for enumeration type for (let i = 0; i < val.elements.length; i++) { if (val.elements[i].type === 'EnumerationLiteral') { - newArray.push(val.elements[i]) + newArray.push(val.elements[i]); } } newArray.sort((a, b) => { - return a.name.localeCompare(b.name) - }) + return a.name.localeCompare(b.name); + }); deferred.resolve({ options: newArray, isEnumeration: isEnumeration, - }) + }); }, (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } else { - deferred.resolve({ options: [], isEnumeration: false }) + deferred.resolve({ options: [], isEnumeration: false }); } - return deferred.promise + return deferred.promise; } public isValue(elementOb: ElementObject): boolean { - const type = elementOb.type - return Object.keys(this.valueTypes).includes(type.toLowerCase()) || this.isTaggedValue(elementOb) + const type = elementOb.type; + return Object.keys(this.valueTypes).includes(type.toLowerCase()) || this.isTaggedValue(elementOb); } public isTaggedValue(elementOb: ElementObject): boolean { - return elementOb.type.endsWith('TaggedValue') + return elementOb.type.endsWith('TaggedValue'); } public hasValue(elementOb: ElementObject): boolean { @@ -245,92 +245,92 @@ export class ValueService { (elementOb.specification && Object.keys((elementOb as ConstraintObject).specification).length !== 0) || // Check if Slots and Tagged Values have any entries (elementOb.value && (elementOb as LiteralObject[]>).value.length > 0)) - ) + ); } public isEqual(a: ElementObject, b: ElementObject): boolean { if (this.valueTypes[a.type.toLowerCase()]) { - return _.isEqual(a[this.valueTypes[a.type.toLowerCase()]], b[this.valueTypes[a.type.toLowerCase()]]) + return _.isEqual(a[this.valueTypes[a.type.toLowerCase()]], b[this.valueTypes[a.type.toLowerCase()]]); } else if (this.isTaggedValue(a)) { - return _.isEqual(a[this.taggedValue], b[this.taggedValue]) + return _.isEqual(a[this.taggedValue], b[this.taggedValue]); } } public getPropertySpec(elementOb: ElementObject): VePromise { - const deferred = this.$q.defer() - let id: string = elementOb.typeId - let isSlot = false - let isEnumeration = false - let isTaggedValue = false - let options: ElementObject[] = [] + const deferred = this.$q.defer(); + let id: string = elementOb.typeId; + let isSlot = false; + let isEnumeration = false; + let isTaggedValue = false; + let options: ElementObject[] = []; if (elementOb.type === 'Slot') { - isSlot = true - id = (elementOb as SlotObject).definingFeatureId + isSlot = true; + id = (elementOb as SlotObject).definingFeatureId; } if (elementOb.type.includes('TaggedValue')) { - isTaggedValue = true - id = (elementOb as TaggedValueObject).tagDefinitionId + isTaggedValue = true; + id = (elementOb as TaggedValueObject).tagDefinitionId; } if (!id) { //no property type, will not be enum - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) - return deferred.promise + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + return deferred.promise; } // Get defining feature or type info const reqOb = { elementId: id, projectId: elementOb._projectId, refId: elementOb._refId, - } + }; this.elementSvc.getElement(reqOb).then( (value) => { if (isSlot || isTaggedValue) { if (!value.typeId) { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) - return + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); + return; } //if it is a slot or tagged value check if the definition type is enumeration - reqOb.elementId = value.typeId + reqOb.elementId = value.typeId; this.elementSvc.getElement(reqOb).then( (val) => { this.isEnumeration(val).then( (enumValue: PropertySpec) => { if (enumValue.isEnumeration) { - isEnumeration = enumValue.isEnumeration - options = enumValue.options + isEnumeration = enumValue.isEnumeration; + options = enumValue.options; } - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); }, () => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); } - ) + ); }, () => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); } - ) + ); } else { this.isEnumeration(value).then( (enumValue) => { if (enumValue.isEnumeration) { - isEnumeration = enumValue.isEnumeration - options = enumValue.options + isEnumeration = enumValue.isEnumeration; + options = enumValue.options; } - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); }, (reason) => { - deferred.reject(reason) + deferred.reject(reason); } - ) + ); } }, (reason) => { - deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }) + deferred.resolve({ options, isEnumeration, isSlot, isTaggedValue }); } - ) - return deferred.promise + ); + return deferred.promise; } } -veUtils.service('ValueService', ValueService) +veUtils.service('ValueService', ValueService); diff --git a/src/ve-utils/mms-api-client/View.service.ts b/src/ve-utils/mms-api-client/View.service.ts index b01678771..931db9dcd 100644 --- a/src/ve-utils/mms-api-client/View.service.ts +++ b/src/ve-utils/mms-api-client/View.service.ts @@ -1,15 +1,15 @@ -import { IQResolveReject } from 'angular' -import _ from 'lodash' +import { IQResolveReject } from 'angular'; +import _ from 'lodash'; -import { CacheService } from '@ve-utils/core' -import { ElementService, URLService, ApiService } from '@ve-utils/mms-api-client' -import { BaseApiService } from '@ve-utils/mms-api-client/Base.service' -import { SchemaService } from '@ve-utils/model-schema' -import { Class, Expression, InstanceSpec, Package, ValueSpec } from '@ve-utils/utils' +import { CacheService } from '@ve-utils/core'; +import { ElementService, URLService, ApiService } from '@ve-utils/mms-api-client'; +import { BaseApiService } from '@ve-utils/mms-api-client/Base.service'; +import { SchemaService } from '@ve-utils/model-schema'; +import { Class, Expression, InstanceSpec, Package, ValueSpec } from '@ve-utils/utils'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular' +import { VePromise, VePromiseReason, VePromisesResponse, VeQService } from '@ve-types/angular'; import { DocumentObject, ElementObject, @@ -35,32 +35,32 @@ import { ElementsResponse, GenericResponse, BasicResponse, -} from '@ve-types/mms' -import { TreeBranch, View2NodeMap } from '@ve-types/tree' +} from '@ve-types/mms'; +import { TreeBranch, View2NodeMap } from '@ve-types/tree'; export interface ViewData { - id: string - api: ViewApi - number?: string - topLevel?: boolean - first?: boolean - data?: ViewObject + id: string; + api: ViewApi; + number?: string; + topLevel?: boolean; + first?: boolean; + data?: ViewObject; } export interface ViewApi { - elementClicked(elementOb: ElementObject): void - elementTranscluded(elementOb: ElementObject, type: string): void + elementClicked(elementOb: ElementObject): void; + elementTranscluded(elementOb: ElementObject, type: string): void; } export interface DocumentMetadata { - numberingDepth: number - numberingSeparator: string - 'top-left'?: string - top?: string - 'top-right'?: string - 'bottom-left'?: string - bottom?: string - 'bottom-right'?: string + numberingDepth: number; + numberingSeparator: string; + 'top-left'?: string; + top?: string; + 'top-right'?: string; + 'bottom-left'?: string; + bottom?: string; + 'bottom-right'?: string; } /** @@ -78,9 +78,9 @@ export interface DocumentMetadata { * */ export class ViewService extends BaseApiService { - private schema: string = 'cameo' + private schema: string = 'cameo'; - static $inject = ['$q', '$http', 'URLService', 'ElementService', 'ApiService', 'CacheService', 'SchemaService'] + static $inject = ['$q', '$http', 'URLService', 'ElementService', 'ApiService', 'CacheService', 'SchemaService']; constructor( private $q: VeQService, private $http: angular.IHttpService, @@ -90,7 +90,7 @@ export class ViewService extends BaseApiService { private cacheSvc: CacheService, private schemaSvc: SchemaService ) { - super() + super(); } /** @@ -102,86 +102,86 @@ export class ViewService extends BaseApiService { */ public downgradeDocument(elementOb: ViewObject): VePromise> { return new this.$q>((resolve, reject) => { - const clone = _.cloneDeep(elementOb) - clone.appliedStereotypeIds = [this.schemaSvc.getSchema('VIEW_SID', this.schema)] + const clone = _.cloneDeep(elementOb); + clone.appliedStereotypeIds = [this.schemaSvc.getSchema('VIEW_SID', this.schema)]; this.elementSvc.updateElements([clone], false).then( (data) => { - const cacheKey = ['documents', elementOb._projectId, elementOb._refId] - let index = -1 - const projectDocs: ViewObject[] = this.cacheSvc.get(cacheKey) + const cacheKey = ['documents', elementOb._projectId, elementOb._refId]; + let index = -1; + const projectDocs: ViewObject[] = this.cacheSvc.get(cacheKey); if (projectDocs) { for (let i = 0; i < projectDocs.length; i++) { if (projectDocs[i].id === elementOb.id) { - index = i - break + index = i; + break; } } if (index >= 0) { - projectDocs.splice(index, 1) + projectDocs.splice(index, 1); } } return resolve( data.filter((returnOb) => { - return returnOb.id === elementOb.id + return returnOb.id === elementOb.id; })[0] - ) + ); }, (reason) => { - return reject(reason) + return reject(reason); } - ) - }) + ); + }); } public getAllViews(reqOb: RequestObject, update?: boolean): VePromise { - const key = this.apiSvc.makeCacheKey(reqOb, '', false, 'views') - const inProgKey = key.join('-') + const key = this.apiSvc.makeCacheKey(reqOb, '', false, 'views'); + const inProgKey = key.join('-'); if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q((resolve, reject) => { - const cached = this.cacheSvc.get(key) + const cached = this.cacheSvc.get(key); if (cached && !update) { - resolve(cached) - this._removeInProgress(inProgKey) + resolve(cached); + this._removeInProgress(inProgKey); } else { - const searchTerms: VePromise, SearchResponse>[] = [] + const searchTerms: VePromise, SearchResponse>[] = []; const stereoIds = [ this.schemaSvc.getSchema('VIEW_SID', this.schema), this.schemaSvc.getSchema('DOCUMENT_SID', this.schema), ...this.schemaSvc.getSchema('OTHER_VIEW_SID', this.schema), - ] + ]; stereoIds.forEach((stId) => { searchTerms.push( this.elementSvc.search(reqOb, { params: { appliedStereotypeIds: stId }, }) - ) - }) + ); + }); this.$q .all(searchTerms) .then( (results) => { - let viewKeys = {} + let viewKeys = {}; results.forEach((result) => { - viewKeys = _(viewKeys).merge(_.keyBy(result.elements, 'id')) - }) - const views = _(viewKeys).values().value() as ViewObject[] - resolve(this.cacheSvc.put(key, views)) + viewKeys = _(viewKeys).merge(_.keyBy(result.elements, 'id')); + }); + const views = _(viewKeys).values().value() as ViewObject[]; + resolve(this.cacheSvc.put(key, views)); }, (reason: VePromiseReason>) => { - reject(reason) + reject(reason); } ) .finally(() => { - this._removeInProgress(inProgKey) - }) + this._removeInProgress(inProgKey); + }); } }) - ) + ); } - return this._getInProgress(inProgKey) as VePromise + return this._getInProgress(inProgKey) as VePromise; } /** @@ -201,46 +201,46 @@ export class ViewService extends BaseApiService { weight: number, update?: boolean ): VePromise { - this.apiSvc.normalize(reqOb) - const key = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'viewElements').join('-') + this.apiSvc.normalize(reqOb); + const key = this.apiSvc.makeCacheKey(reqOb, reqOb.elementId, false, 'viewElements').join('-'); if (this._isInProgress(key)) { - return this._getInProgress(key) as VePromise + return this._getInProgress(key) as VePromise; } - const cached = this.cacheSvc.get(key) + const cached = this.cacheSvc.get(key); if (cached && !update) { - return this.$q.resolve(cached) + return this.$q.resolve(cached); } this._addInProgress( key, new this.$q((resolve, reject) => { this.elementSvc.getElement(reqOb, weight, update).then( (viewOrInstance: ViewObject | ViewInstanceSpec) => { - const toGet: string[] = [] - let results: ElementObject[] = [] + const toGet: string[] = []; + let results: ElementObject[] = []; if (viewOrInstance.type === 'Class') { - const view: ViewObject = viewOrInstance as ViewObject + const view: ViewObject = viewOrInstance as ViewObject; if (view._displayedElementIds) { - const displayed: string[] = view._displayedElementIds + const displayed: string[] = view._displayedElementIds; if (Array.isArray(displayed) && displayed.length > 0) { - toGet.push(...displayed) + toGet.push(...displayed); } } if (view._contents && view._contents.operand) { - const contents = view._contents.operand + const contents = view._contents.operand; for (let i = 0; i < contents.length; i++) { if (contents[i] && contents[i].instanceId) { - toGet.push(contents[i].instanceId) + toGet.push(contents[i].instanceId); } } } } else if (viewOrInstance.type === 'InstanceSpecification') { - const view = viewOrInstance as ViewInstanceSpec + const view = viewOrInstance as ViewInstanceSpec; if (view.specification) { if (view.specification.operand) { - const specContents = view.specification.operand as InstanceValueObject[] + const specContents = view.specification.operand as InstanceValueObject[]; for (let j = 0; j < specContents.length; j++) { if (specContents[j] && specContents[j].instanceId) { - toGet.push(specContents[j].instanceId) + toGet.push(specContents[j].instanceId); } } } @@ -252,51 +252,51 @@ export class ViewService extends BaseApiService { ) { const tableJson: PresentTableObject = JSON.parse( view.specification.value - ) as PresentTableObject + ) as PresentTableObject; if (tableJson.body) { - toGet.push(...this.collectTableSources(tableJson)) + toGet.push(...this.collectTableSources(tableJson)); } } } } - const toGetReqOb: ElementsRequest = Object.assign(reqOb, { elementId: toGet }) + const toGetReqOb: ElementsRequest = Object.assign(reqOb, { elementId: toGet }); this.elementSvc .getElements(toGetReqOb, weight, update) .then((data) => { - results = data + results = data; }) .finally(() => { - this.cacheSvc.put(key, results) - this._removeInProgress(key) - resolve(results) - }) + this.cacheSvc.put(key, results); + this._removeInProgress(key); + resolve(results); + }); }, (reason) => { - this._removeInProgress(key) - reject(reason) + this._removeInProgress(key); + reject(reason); } - ) + ); }) - ) - return this._getInProgress(key) as VePromise + ); + return this._getInProgress(key) as VePromise; } public collectTableSources(table: PresentTableObject): string[] { - const sources: string[] = [] - const body = table.body + const sources: string[] = []; + const body = table.body; body.forEach((row) => { row.forEach((cell) => { cell.content.forEach((thing) => { if (thing.type === 'Table' && thing.body) { - sources.push(...this.collectTableSources(thing as PresentTableObject)) + sources.push(...this.collectTableSources(thing as PresentTableObject)); } else if (thing.type === 'Paragraph' && thing.source) { - sources.push((thing as PresentTextObject).source) + sources.push((thing as PresentTextObject).source); } - }) - }) - }) - return sources + }); + }); + }); + return sources; } /** @@ -330,26 +330,26 @@ export class ViewService extends BaseApiService { ) => void, seen?: { [key: string]: ViewObject } ): VePromise { - let seenViews = seen - if (!seenViews) seenViews = {} + let seenViews = seen; + if (!seenViews) seenViews = {}; return new this.$q((resolve, reject) => { - const curItem: TreeBranch | string[] = curItemFunc(v, aggr, propId) - seenViews[v.id] = v - const childIds: string[] = [] - const childAggrs: string[] = [] - const childPropIds: string[] = [] + const curItem: TreeBranch | string[] = curItemFunc(v, aggr, propId); + seenViews[v.id] = v; + const childIds: string[] = []; + const childAggrs: string[] = []; + const childPropIds: string[] = []; if (!v._childViews || v._childViews.length === 0 || aggr === 'none') { if (!Array.isArray(curItem) && curItem.loading) { - curItem.loading = false + curItem.loading = false; } - resolve(curItem) - return + resolve(curItem); + return; } for (let i = 0; i < v._childViews.length; i++) { - if (seenViews[v._childViews[i].id]) continue - childIds.push(v._childViews[i].id) - childAggrs.push(v._childViews[i].aggregation) - childPropIds.push(v._childViews[i].propertyId) + if (seenViews[v._childViews[i].id]) continue; + childIds.push(v._childViews[i].id); + childAggrs.push(v._childViews[i].aggregation); + childPropIds.push(v._childViews[i].propertyId); } this.elementSvc .getElements( @@ -361,15 +361,15 @@ export class ViewService extends BaseApiService { 2 ) .then((childViews: ViewObject[]) => { - const mapping: { [id: string]: ViewObject } = {} + const mapping: { [id: string]: ViewObject } = {}; for (let i = 0; i < childViews.length; i++) { - mapping[childViews[i].id] = childViews[i] + mapping[childViews[i].id] = childViews[i]; } - const childPromises: VePromise[] = [] - const childNodes: (string[] | TreeBranch)[] = [] - const processedChildViews: ViewObject[] = [] + const childPromises: VePromise[] = []; + const childNodes: (string[] | TreeBranch)[] = []; + const processedChildViews: ViewObject[] = []; for (let i = 0; i < childIds.length; i++) { - const child = mapping[childIds[i]] + const child = mapping[childIds[i]]; if (child && this.apiSvc.isView(child)) { //what if not found?? childPromises.push( @@ -384,26 +384,26 @@ export class ViewService extends BaseApiService { childrenFunc, seenViews ) - ) - childNodes.push(curItemFunc(child, childAggrs[i], childPropIds[i])) + ); + childNodes.push(curItemFunc(child, childAggrs[i], childPropIds[i])); processedChildViews.push({ id: child.id, _projectId: child._projectId, _refId: child._refId, aggregation: childAggrs[i], propertyId: childPropIds[i], - }) + }); } } - v._childViews = processedChildViews + v._childViews = processedChildViews; if (childrenFunc) { - childrenFunc(curItem, childNodes, reject) + childrenFunc(curItem, childNodes, reject); } this.$q.all(childPromises).then(() => { - resolve(curItem) - }, reject) - }, reject) - }) + resolve(curItem); + }, reject); + }, reject); + }); } /** @@ -416,7 +416,7 @@ export class ViewService extends BaseApiService { * @returns {Promise} The promise would be resolved with updated parent view object */ public addViewToParentView(reqOb: ViewCreationRequest): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -436,10 +436,10 @@ export class ViewService extends BaseApiService { id: data.id, _childViews: [], type: data.type, - } - clone._childViews = [] + }; + clone._childViews = []; if (data._childViews) { - clone._childViews.push(..._.cloneDeep(data._childViews)) + clone._childViews.push(..._.cloneDeep(data._childViews)); } clone._childViews.push({ id: reqOb.viewId, @@ -447,21 +447,21 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, type: data.type, - }) + }); this.elementSvc.updateElement(clone, true).then( (data2) => { - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -472,7 +472,7 @@ export class ViewService extends BaseApiService { * @returns {IPromise} The promise would be resolved with updated parent View object */ public removeViewFromParentView(reqOb: ViewsRequest): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -494,30 +494,30 @@ export class ViewService extends BaseApiService { id: data.id, type: data.type, _childViews: _.cloneDeep(data._childViews), - } + }; for (let i = 0; i < clone._childViews.length; i++) { if (clone._childViews[i].id === reqOb.viewId) { - clone._childViews.splice(i, 1) - break + clone._childViews.splice(i, 1); + break; } } this.elementSvc.updateElement(clone, true).then( (data2) => { - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); } else { - resolve(data) + resolve(data); } }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -537,7 +537,7 @@ export class ViewService extends BaseApiService { instanceValOb: InstanceValueObject, addPeIndex: number ): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { this.elementSvc .getElement( @@ -555,20 +555,20 @@ export class ViewService extends BaseApiService { _refId: data._refId, type: data.type, id: data.id, - } - let key = '_contents' + }; + let key = '_contents'; if (this.isSection(data)) { - key = 'specification' + key = 'specification'; } - const keyValue: ValueObject = data[key] as ValueObject - let cloneValue: ValueObject + const keyValue: ValueObject = data[key] as ValueObject; + let cloneValue: ValueObject; if (keyValue) { - cloneValue = _.cloneDeep(keyValue) + cloneValue = _.cloneDeep(keyValue); if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(data) ? this.apiSvc.createUniqueId() - : data.id + '_vc_expression' - cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc' + : data.id + '_vc_expression'; + cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc'; } } else { cloneValue = new Expression({ @@ -578,39 +578,39 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, ownerId: this.isSection(data) ? data.id : data.id + '_vc', - }) + }); } - instanceValOb.ownerId = cloneValue.id + instanceValOb.ownerId = cloneValue.id; if (!instanceValOb.id) { - instanceValOb.id = this.apiSvc.createUniqueId() + instanceValOb.id = this.apiSvc.createUniqueId(); } if (addPeIndex >= -1) (cloneValue as ExpressionObject).operand.splice( addPeIndex + 1, 0, new ValueSpec(instanceValOb) - ) + ); else { - ;(cloneValue as ExpressionObject).operand.push( + (cloneValue as ExpressionObject).operand.push( new ValueSpec(instanceValOb) - ) + ); } - clone[key] = cloneValue + clone[key] = cloneValue; this.elementSvc.updateElement(clone, false).then( (data2) => { - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -625,7 +625,7 @@ export class ViewService extends BaseApiService { reqOb: ElementsRequest, instanceVal?: InstanceValueObject ): VePromise { - this.apiSvc.normalize(reqOb) + this.apiSvc.normalize(reqOb); return new this.$q((resolve, reject) => { if (instanceVal) { this.elementSvc.getElement(reqOb, 2).then( @@ -636,20 +636,20 @@ export class ViewService extends BaseApiService { type: data.type, //_modified: data._modified, id: data.id, - } - let key = '_contents' + }; + let key = '_contents'; if (this.isSection(data)) { - key = 'specification' + key = 'specification'; } - const keyValue = data[key] as ValueObject - let cloneValue: ValueObject + const keyValue = data[key] as ValueObject; + let cloneValue: ValueObject; if (keyValue) { - cloneValue = _.cloneDeep(keyValue) + cloneValue = _.cloneDeep(keyValue); if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(data) ? this.apiSvc.createUniqueId() - : data.id + '_vc_expression' - cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc' + : data.id + '_vc_expression'; + cloneValue.ownerId = this.isSection(data) ? data.id : data.id + '_vc'; } } else { cloneValue = new Expression({ @@ -659,34 +659,34 @@ export class ViewService extends BaseApiService { _projectId: data._projectId, _refId: data._refId, ownerId: this.isSection(data) ? data.id : data.id + '_vc', - }) + }); } if (cloneValue && cloneValue.operand) { const operands: InstanceValueObject[] = (keyValue as ExpressionObject) - .operand + .operand; for (let i = 0; i < operands.length; i++) { if (instanceVal.instanceId === operands[i].instanceId) { - ;(cloneValue as ExpressionObject).operand.splice(i, 1) - break + (cloneValue as ExpressionObject).operand.splice(i, 1); + break; } } } - clone[key] = cloneValue + clone[key] = cloneValue; this.elementSvc.updateElement(clone, false).then( (data2) => { - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); }, (reason) => { - reject(reason) + reject(reason); } - ) + ); } - }) + }); } /** @@ -705,23 +705,23 @@ export class ViewService extends BaseApiService { name: string, addPeIndex: number ): VePromise { - let newInstanceId = this.apiSvc.createUniqueId() - newInstanceId = '_hidden_' + newInstanceId + '_pei' + let newInstanceId = this.apiSvc.createUniqueId(); + newInstanceId = '_hidden_' + newInstanceId + '_pei'; return new this.$q((resolve, reject) => { const realType: string = this.schemaSvc.getValue( 'TYPE_TO_CLASSIFIER_TYPE', type, this.schema, viewOrSectionOb.id - ) - let jsonType = realType - if (type === 'Comment' || type === 'Paragraph') jsonType = type + ); + let jsonType = realType; + if (type === 'Comment' || type === 'Paragraph') jsonType = type; const instanceSpecSpec = { type: jsonType, sourceType: 'reference', source: newInstanceId, sourceProperty: 'documentation', - } + }; let instanceSpec: InstanceSpecObject = { id: newInstanceId, ownerId: 'view_instances_bin_' + viewOrSectionOb._projectId, @@ -742,8 +742,8 @@ export class ViewService extends BaseApiService { _refId: viewOrSectionOb._refId, }), appliedStereotypeIds: [], - } - instanceSpec = new InstanceSpec(instanceSpec) + }; + instanceSpec = new InstanceSpec(instanceSpec); if (type === 'Section') { //newData = newDataSInstance = null; instanceSpec.specification = new ValueSpec({ @@ -753,20 +753,20 @@ export class ViewService extends BaseApiService { id: this.apiSvc.createUniqueId(), _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, - }) + }); } let clone: ElementObject = { _projectId: viewOrSectionOb._projectId, id: viewOrSectionOb.id, _refId: viewOrSectionOb._refId, type: viewOrSectionOb.type, - } - let key = '_contents' + }; + let key = '_contents'; if (this.isSection(viewOrSectionOb)) { - key = 'specification' + key = 'specification'; } - const keyValue: ValueObject = viewOrSectionOb[key] as ValueObject - let cloneValue: ValueObject + const keyValue: ValueObject = viewOrSectionOb[key] as ValueObject; + let cloneValue: ValueObject; if (!keyValue) { cloneValue = new ValueSpec({ operand: [], @@ -777,20 +777,20 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, ownerId: this.isSection(viewOrSectionOb) ? viewOrSectionOb.id : viewOrSectionOb.id + '_vc', - }) + }); } else { - cloneValue = _.cloneDeep(keyValue) + cloneValue = _.cloneDeep(keyValue); if (!cloneValue.id || !cloneValue.ownerId) { cloneValue.id = this.isSection(viewOrSectionOb) ? this.apiSvc.createUniqueId() - : viewOrSectionOb.id + '_vc_expression' + : viewOrSectionOb.id + '_vc_expression'; cloneValue.ownerId = this.isSection(viewOrSectionOb) ? viewOrSectionOb.id - : viewOrSectionOb.id + '_vc' + : viewOrSectionOb.id + '_vc'; } } if (addPeIndex >= -1) { - ;(cloneValue as ExpressionObject).operand.splice( + (cloneValue as ExpressionObject).operand.splice( addPeIndex + 1, 0, new ValueSpec({ @@ -801,9 +801,9 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, }) - ) + ); } else { - ;(cloneValue as ExpressionObject).operand.push( + (cloneValue as ExpressionObject).operand.push( new ValueSpec({ instanceId: newInstanceId, type: 'InstanceValue', @@ -812,11 +812,11 @@ export class ViewService extends BaseApiService { _projectId: viewOrSectionOb._projectId, _refId: viewOrSectionOb._refId, }) - ) + ); } - clone[key] = cloneValue - clone = this.elementSvc.fillInElement(clone) - const toCreate: ElementObject[] = [instanceSpec, clone] + clone[key] = cloneValue; + clone = this.elementSvc.fillInElement(clone); + const toCreate: ElementObject[] = [instanceSpec, clone]; /* if (newData && newDataSInstance) { toCreate.push(newData); @@ -828,22 +828,22 @@ export class ViewService extends BaseApiService { refId: viewOrSectionOb._refId, elements: toCreate, elementId: '', - } + }; this.elementSvc.createElements(reqOb).then( (data) => { for (let i = 0; i < data.length; i++) { - const elem = data[i] + const elem = data[i]; if (elem.id === newInstanceId) { - resolve(elem) - return + resolve(elem); + return; } } }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -863,9 +863,9 @@ export class ViewService extends BaseApiService { */ public createView(ownerOb: ViewObject, viewOb: ViewObject, peDoc?: string): VePromise { return new this.$q((resolve, reject) => { - const newViewId: string = viewOb.id && viewOb.id !== '' ? viewOb.id : this.apiSvc.createUniqueId() - const newInstanceId = '_hidden_' + this.apiSvc.createUniqueId() + '_pei' - const untitledName = viewOb.isDoc ? 'Untitled Document' : 'Untitled View' + const newViewId: string = viewOb.id && viewOb.id !== '' ? viewOb.id : this.apiSvc.createUniqueId(); + const newInstanceId = '_hidden_' + this.apiSvc.createUniqueId() + '_pei'; + const untitledName = viewOb.isDoc ? 'Untitled Document' : 'Untitled View'; const view = new Class({ id: newViewId, _projectId: viewOb._projectId, @@ -898,22 +898,22 @@ export class ViewService extends BaseApiService { ? this.schemaSvc.getSchema('DOCUMENT_SID', this.schema) : this.schemaSvc.getSchema('VIEW_SID', this.schema), ], - }) + }); let parentView: ViewObject = { _projectId: '', _refId: '', id: '', type: 'Class', - } + }; if (ownerOb && (ownerOb._childViews || this.apiSvc.isView(ownerOb))) { parentView = Object.assign(parentView, { _projectId: ownerOb._projectId, _refId: ownerOb._refId, id: ownerOb.id, - }) - parentView._childViews = [] + }); + parentView._childViews = []; if (ownerOb._childViews) { - parentView._childViews.push(..._.cloneDeep(ownerOb._childViews)) + parentView._childViews.push(..._.cloneDeep(ownerOb._childViews)); } parentView._childViews.push({ id: newViewId, @@ -921,14 +921,14 @@ export class ViewService extends BaseApiService { _refId: ownerOb._refId, aggregation: 'composite', type: 'Class', - }) + }); } const peSpec: PresentationInstanceObject = { type: 'Paragraph', sourceType: 'reference', source: newViewId, sourceProperty: 'documentation', - } + }; const pe = new InstanceSpec({ id: newInstanceId, _projectId: viewOb._projectId, @@ -946,11 +946,11 @@ export class ViewService extends BaseApiService { _refId: viewOb._refId, }), appliedStereotypeIds: [], - }) - const toCreate: ElementObject[] = [pe, view] + }); + const toCreate: ElementObject[] = [pe, view]; if (parentView.id !== '') { - const parentViewClass: ElementObject = this.elementSvc.fillInElement(parentView) - toCreate.push(parentViewClass) + const parentViewClass: ElementObject = this.elementSvc.fillInElement(parentView); + toCreate.push(parentViewClass); } const reqOb = { projectId: ownerOb._projectId, @@ -958,20 +958,20 @@ export class ViewService extends BaseApiService { elements: toCreate, returnChildViews: true, elementId: '', - } + }; this.elementSvc.createElements(reqOb).then( (data) => { data.forEach((elem) => { if (elem.id === newViewId) { - resolve(elem) + resolve(elem); } - }) + }); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -986,27 +986,27 @@ export class ViewService extends BaseApiService { */ public createDocument(ownerOb: ViewObject, docOb: ViewObject): VePromise { return new this.$q((resolve, reject) => { - docOb.isDoc = true + docOb.isDoc = true; this.createView(ownerOb, docOb).then( (data2: DocumentObject) => { if (ownerOb && ownerOb.id.indexOf('holding_bin') < 0) { - data2._groupId = ownerOb.id + data2._groupId = ownerOb.id; } - const cacheKey = ['documents', ownerOb._projectId, ownerOb._refId] - const cachedView: ViewObject[] = this.cacheSvc.get(cacheKey, true) + const cacheKey = ['documents', ownerOb._projectId, ownerOb._refId]; + const cachedView: ViewObject[] = this.cacheSvc.get(cacheKey, true); if (cachedView) { cachedView.forEach((document: DocumentObject, index) => { - if (document.id === data2.id) delete cachedView[index] - }) - cachedView.push(data2) + if (document.id === data2.id) delete cachedView[index]; + }); + cachedView.push(data2); } - resolve(data2) + resolve(data2); }, (reason) => { - reject(reason) + reject(reason); } - ) - }) + ); + }); } /** @@ -1026,7 +1026,7 @@ export class ViewService extends BaseApiService { */ public createGroup(name: string, ownerOb: ViewObject): VePromise { return new this.$q((resolve, reject) => { - const PACKAGE_ID = this.apiSvc.createUniqueId() + const PACKAGE_ID = this.apiSvc.createUniqueId(); // Our Group package element const group: GroupObject = new Package({ id: PACKAGE_ID, @@ -1037,38 +1037,38 @@ export class ViewService extends BaseApiService { ownerId: ownerOb.id, _isGroup: true, appliedStereotypeIds: [this.schemaSvc.getSchema('GROUP_ST_ID', this.schema)], - }) - const toCreate = [group] + }); + const toCreate = [group]; const reqOb = { projectId: ownerOb._projectId, refId: ownerOb._refId, elements: toCreate, elementId: '', - } + }; this.elementSvc.createElements(reqOb).then( (data) => { - const cacheKey = ['groups', ownerOb._projectId, ownerOb._refId] - const groupObj = _.find(data, { id: PACKAGE_ID }) + const cacheKey = ['groups', ownerOb._projectId, ownerOb._refId]; + const groupObj = _.find(data, { id: PACKAGE_ID }); if (groupObj) { - groupObj._parentId = ownerOb.id.indexOf('holding') != -1 ? null : ownerOb.id + groupObj._parentId = ownerOb.id.indexOf('holding') != -1 ? null : ownerOb.id; if (this.cacheSvc.exists(cacheKey)) { - this.cacheSvc.get(cacheKey).push(groupObj) + this.cacheSvc.get(cacheKey).push(groupObj); } - this.cacheSvc.put(['group', groupObj.projectId, groupObj.refId, groupObj.id], groupObj, true) - resolve(groupObj) + this.cacheSvc.put(['group', groupObj.projectId, groupObj.refId, groupObj.id], groupObj, true); + resolve(groupObj); } else { reject({ status: 500, message: 'Failed to create group', - }) + }); } }, (reason) => { - console.log('POST failed:', reason) - reject(reason) + console.log('POST failed:', reason); + reject(reason); } - ) - }) + ); + }); } /** @@ -1088,43 +1088,43 @@ export class ViewService extends BaseApiService { _refId: packageOb._refId, appliedStereotypeIds: [], classifierIds: null, - } + }; - updatedPackage._isGroup = false + updatedPackage._isGroup = false; _.remove(packageOb.appliedStereotypeIds, (id: string): boolean => { - return id === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema) - }) + return id === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema); + }); if (packageOb.appliedStereotypeIds.length === 0) { - updatedPackage.appliedStereotypeIds = packageOb.appliedStereotypeIds + updatedPackage.appliedStereotypeIds = packageOb.appliedStereotypeIds; } - const toUpdate = [updatedPackage] + const toUpdate = [updatedPackage]; this.elementSvc.updateElements(toUpdate, false).then( (data) => { // remove this group for cache - const cacheKey = ['groups', packageOb._projectId, packageOb._refId] - const groups: ElementObject[] = this.cacheSvc.get(cacheKey, true) || [] + const cacheKey = ['groups', packageOb._projectId, packageOb._refId]; + const groups: ElementObject[] = this.cacheSvc.get(cacheKey, true) || []; _.remove(groups, (group: PackageObject) => { - return group.id === packageOb.id - }) + return group.id === packageOb.id; + }); data.forEach((elOb: ElementObject) => { if (elOb.id === updatedPackage.id) { - resolve(elOb) + resolve(elOb); } - }) + }); }, (reason) => { if (reason.data.failedRequests) { - reject(reason.data.failedRequests[0]) + reject(reason.data.failedRequests[0]); } else { reject({ status: 400, message: 'Something went wrong. Please try your action again', - }) + }); } } - ) - }) + ); + }); } /** @@ -1141,40 +1141,40 @@ export class ViewService extends BaseApiService { weight?: number, refresh?: boolean ): VePromise> { - this.apiSvc.normalize(reqOb) - const url = this.uRLSvc.getProjectDocumentsURL(reqOb) - const cacheKey = ['documents', reqOb.projectId, reqOb.refId] - const inProgKey = cacheKey.join('-') + this.apiSvc.normalize(reqOb); + const url = this.uRLSvc.getProjectDocumentsURL(reqOb); + const cacheKey = ['documents', reqOb.projectId, reqOb.refId]; + const inProgKey = cacheKey.join('-'); if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q>((resolve, reject) => { if (this.cacheSvc.exists(cacheKey) && !refresh) { - resolve(this.cacheSvc.get(cacheKey)) - this._removeInProgress(inProgKey) + resolve(this.cacheSvc.get(cacheKey)); + this._removeInProgress(inProgKey); } else { if (refresh === undefined) { - refresh = false + refresh = false; } this.elementSvc .getGenericElements(url, reqOb, 'documents', weight, refresh) .then( (data) => { - this.cacheSvc.put(cacheKey, data, false) - resolve(this.cacheSvc.get(cacheKey)) + this.cacheSvc.put(cacheKey, data, false); + resolve(this.cacheSvc.get(cacheKey)); }, (reason) => { - reject(reason) + reject(reason); } ) .finally(() => { - this._removeInProgress(inProgKey) - }) + this._removeInProgress(inProgKey); + }); } }) - ) + ); } - return this._getInProgress(inProgKey) as VePromise> + return this._getInProgress(inProgKey) as VePromise>; } /** @@ -1191,35 +1191,35 @@ export class ViewService extends BaseApiService { weight: number, refresh?: boolean ): VePromise { - const cacheKey = this.elementSvc.getRequestKey(reqOb, reqOb.elementId) - const inProgKey = cacheKey.join('-') + const cacheKey = this.elementSvc.getRequestKey(reqOb, reqOb.elementId); + const inProgKey = cacheKey.join('-'); if (!this._isInProgress(inProgKey)) { this._addInProgress( inProgKey, new this.$q((resolve, reject) => { - const cached = this.cacheSvc.get(cacheKey) + const cached = this.cacheSvc.get(cacheKey); if (cached && !refresh) { - resolve(cached) - this._removeInProgress(inProgKey) + resolve(cached); + this._removeInProgress(inProgKey); } this.getProjectDocuments(reqOb, weight, refresh) .then( (result: DocumentObject[]) => { const documentOb = result.filter((resultOb) => { - return resultOb.id === reqOb.elementId - })[0] - this.cacheSvc.put(cacheKey, documentOb, true) - resolve(this.cacheSvc.get(cacheKey)) + return resultOb.id === reqOb.elementId; + })[0]; + this.cacheSvc.put(cacheKey, documentOb, true); + resolve(this.cacheSvc.get(cacheKey)); }, (reason) => { - reject({ message: reason.message, status: reason.status }) + reject({ message: reason.message, status: reason.status }); } ) - .finally(() => this._removeInProgress(inProgKey)) + .finally(() => this._removeInProgress(inProgKey)); }) - ) + ); } - return this._getInProgress(inProgKey) as VePromise + return this._getInProgress(inProgKey) as VePromise; } /** @@ -1233,31 +1233,31 @@ export class ViewService extends BaseApiService { public getPresentationInstanceObject = ( instanceSpec: InstanceSpecObject ): PresentationInstanceObject | InstanceSpecObject => { - const instanceSpecSpec: ValueObject = instanceSpec.specification + const instanceSpecSpec: ValueObject = instanceSpec.specification; if (!instanceSpecSpec) { return { type: 'Paragraph', sourceType: 'text', text: '', - } + }; } - const type = instanceSpecSpec.type + const type = instanceSpecSpec.type; if (type === 'LiteralString') { // If it is an Opaque List, Paragraph, Table, Image, List: - const jsonString = (instanceSpecSpec as LiteralObject).value - return JSON.parse(jsonString) as PresentationInstanceObject + const jsonString = (instanceSpecSpec as LiteralObject).value; + return JSON.parse(jsonString) as PresentationInstanceObject; } else if (type === 'Expression') { // If it is a Opaque Section, or a Expression: // If it is a Opaque Section then we want the instanceSpec: if (this.isSection(instanceSpec)) { - return instanceSpec + return instanceSpec; } else { //?? - return instanceSpecSpec + return instanceSpecSpec; } } - } + }; /** * @name ViewService#getElementReferenceTree @@ -1283,11 +1283,11 @@ export class ViewService extends BaseApiService { contents: ExpressionObject, weight?: number ): VePromise> { - const promises: VePromise>[] = [] + const promises: VePromise>[] = []; for (let i = 0; i < contents.operand.length; i++) { - promises.push(this.getElementReference(reqOb, contents.operand[i], weight)) + promises.push(this.getElementReference(reqOb, contents.operand[i], weight)); } - return this.$q.all(promises) + return this.$q.all(promises); } public getElementReference( @@ -1301,37 +1301,37 @@ export class ViewService extends BaseApiService { sectionElements: [], instanceVal: instanceVal, isOpaque: false, - } + }; - const req = _.cloneDeep(reqOb) - req.elementId = instanceVal.instanceId + const req = _.cloneDeep(reqOb); + req.elementId = instanceVal.instanceId; this.elementSvc.getElement(req, weight).then( (instanceSpecification) => { - presentationRef.instanceSpecification = instanceSpecification + presentationRef.instanceSpecification = instanceSpecification; presentationRef.isOpaque = instanceSpecification.classifierIds && instanceSpecification.classifierIds.length > 0 && this.schemaSvc .getMap('OPAQUE_CLASSIFIERS', this.schema) - .indexOf(instanceSpecification.classifierIds[0]) >= 0 - presentationRef.presentationElement = this.getPresentationInstanceObject(instanceSpecification) + .indexOf(instanceSpecification.classifierIds[0]) >= 0; + presentationRef.presentationElement = this.getPresentationInstanceObject(instanceSpecification); if (this.isSection(instanceSpecification)) { this.getElementReferenceTree(req, instanceSpecification.specification).then( (sectionElementReferenceTree) => { - presentationRef.sectionElements = sectionElementReferenceTree - resolve(presentationRef) + presentationRef.sectionElements = sectionElementReferenceTree; + resolve(presentationRef); }, (reason) => { - reject(reason) + reject(reason); } - ) - } else resolve(presentationRef) + ); + } else resolve(presentationRef); }, (reason) => { - reject({ status: reason.status, message: reason.message }) + reject({ status: reason.status, message: reason.message }); } - ) - }) + ); + }); } /** @@ -1349,8 +1349,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Section', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'SectionT', this.schema, instanceSpec.id)) - ) - } + ); + }; public isTable = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1360,8 +1360,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Table', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'TableT', this.schema, instanceSpec.id)) - ) - } + ); + }; public isFigure = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1375,8 +1375,8 @@ export class ViewService extends BaseApiService { this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Figure', this.schema, instanceSpec.id) || instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'FigureT', this.schema, instanceSpec.id)) - ) - } + ); + }; public isEquation = (instanceSpec: InstanceSpecObject): boolean => { return ( @@ -1384,27 +1384,27 @@ export class ViewService extends BaseApiService { instanceSpec.classifierIds.length > 0 && instanceSpec.classifierIds[0] === this.schemaSvc.getValue('TYPE_TO_CLASSIFIER_ID', 'Equation', this.schema, instanceSpec.id) - ) - } + ); + }; public getTreeType = (instanceSpec: ViewInstanceSpec): string => { - if (this.isSection(instanceSpec)) return 'section' + if (this.isSection(instanceSpec)) return 'section'; if ( instanceSpec.specification && instanceSpec.specification.value && typeof instanceSpec.specification.value === 'string' && (JSON.parse(instanceSpec.specification.value) as PresentationInstanceObject).excludeFromList ) { - return 'none' + return 'none'; } - if (this.isTable(instanceSpec)) return 'table' - if (this.isFigure(instanceSpec)) return 'figure' - if (this.isEquation(instanceSpec)) return 'equation' - let result = 'none' + if (this.isTable(instanceSpec)) return 'table'; + if (this.isFigure(instanceSpec)) return 'figure'; + if (this.isEquation(instanceSpec)) return 'equation'; + let result = 'none'; if (instanceSpec.classifierIds && instanceSpec.classifierIds.length > 0) { const peSids = this.schemaSvc.getSchema<{ - [peType: string]: string - }>('TYPE_TO_CLASSIFIER_ID', this.schema) + [peType: string]: string; + }>('TYPE_TO_CLASSIFIER_ID', this.schema); for (const peType of Object.keys(peSids)) { if ( @@ -1412,43 +1412,43 @@ export class ViewService extends BaseApiService { instanceSpec.classifierIds.length > 0 && instanceSpec.classifierIds.includes(peSids[peType]) ) { - result = peType.toLowerCase() - break + result = peType.toLowerCase(); + break; } } } - return result - } + return result; + }; public processSlotStrings(values: LiteralObject[]): string[] { - const res: string[] = [] + const res: string[] = []; if (!values || values.length === 0) { - return res + return res; } values.forEach((value) => { - if (value.type !== 'LiteralString' || !value.value) return - res.push(value.value as string) - }) - return res + if (value.type !== 'LiteralString' || !value.value) return; + res.push(value.value as string); + }); + return res; } public processSlotIntegers(values: LiteralObject[]): number[] { - const res: number[] = [] + const res: number[] = []; if (!values || values.length === 0) { - return res + return res; } values.forEach((value) => { if (Number.isInteger(value.value)) { - res.push(value.value as number) + res.push(value.value as number); } else if (typeof value.value === 'string') { - const val = parseInt(value.value) + const val = parseInt(value.value); if (!isNaN(val)) { - res.push(val) + res.push(val); } } - }) - return res + }); + return res; } /** @@ -1465,7 +1465,7 @@ export class ViewService extends BaseApiService { const metadata: DocumentMetadata = { numberingDepth: 0, numberingSeparator: '.', - } + }; const elementIds = [ `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'Header', this.schema)}`, //header `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'Footer', this.schema)}`, //footer @@ -1475,51 +1475,51 @@ export class ViewService extends BaseApiService { this.schema )}`, //numbering depth `${reqOb.elementId}_asi-slot-${this.schemaSvc.getValue('DOCUMENT_IDS', 'NumSep', this.schema)}`, //numbering separator - ] + ]; const metaReqOb: ElementsRequest = Object.assign(reqOb, { elementId: elementIds, - }) + }); this.elementSvc .getElements(metaReqOb, weight) .then( (data) => { if (data.length === 0) { - return + return; } for (let i = 0; i < data.length; i++) { - const prop = data[i] - const feature: string = prop.definingFeatureId ? prop.definingFeatureId : null - const value: LiteralObject[] = prop.value ? prop.value : null + const prop = data[i]; + const feature: string = prop.definingFeatureId ? prop.definingFeatureId : null; + const value: LiteralObject[] = prop.value ? prop.value : null; if (!feature || !value || !Array.isArray(value)) { - continue + continue; } - let result: string[] | number[] = [] + let result: string[] | number[] = []; if (feature === this.schemaSvc.getValue('DOCUMENT_IDS', 'Header', this.schema, prop.id)) { //header - result = this.processSlotStrings(value) - metadata.top = result.length > 0 ? result[0] : '' - metadata['top-left'] = result.length > 1 ? result[1] : '' - metadata['top-right'] = result.length > 2 ? result[2] : '' + result = this.processSlotStrings(value); + metadata.top = result.length > 0 ? result[0] : ''; + metadata['top-left'] = result.length > 1 ? result[1] : ''; + metadata['top-right'] = result.length > 2 ? result[2] : ''; } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'Footer', this.schema, prop.id) ) { //footer - result = this.processSlotStrings(value) - metadata.bottom = result.length > 0 ? result[0] : '' - metadata['bottom-left'] = result.length > 1 ? result[1] : '' - metadata['bottom-right'] = result.length > 2 ? result[2] : '' + result = this.processSlotStrings(value); + metadata.bottom = result.length > 0 ? result[0] : ''; + metadata['bottom-left'] = result.length > 1 ? result[1] : ''; + metadata['bottom-right'] = result.length > 2 ? result[2] : ''; } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'NumDepth', this.schema, prop.id) ) { //depth - result = this.processSlotIntegers(value) - metadata.numberingDepth = result.length > 0 ? result[0] : 0 + result = this.processSlotIntegers(value); + metadata.numberingDepth = result.length > 0 ? result[0] : 0; } else if ( feature == this.schemaSvc.getValue('DOCUMENT_IDS', 'NumSep', this.schema, prop.id) ) { //separator - result = this.processSlotStrings(value) - metadata.numberingSeparator = result.length > 0 ? result[0] : '.' + result = this.processSlotStrings(value); + metadata.numberingSeparator = result.length > 0 ? result[0] : '.'; } } }, @@ -1528,63 +1528,63 @@ export class ViewService extends BaseApiService { } ) .finally(() => { - resolve(metadata) - }) - }) + resolve(metadata); + }); + }); } public getPresentationElementType = (instanceSpec: ViewInstanceSpec): string => { if (instanceSpec.type === 'InstanceSpecification') { if (this.isSection(instanceSpec)) { - return 'Section' + return 'Section'; } else if (this.isTable(instanceSpec)) { - return 'Table' + return 'Table'; } else if (this.isFigure(instanceSpec)) { - return 'Image' + return 'Image'; } else if (this.isEquation(instanceSpec)) { - return 'Equation' + return 'Equation'; } else if (instanceSpec.specification && instanceSpec.specification.value) { return ( JSON.parse( (instanceSpec.specification as LiteralObject).value ) as PresentationInstanceObject - ).type + ).type; } } - return - } + return; + }; public isGroup(ob: InstanceSpecObject | GroupObject): boolean { - if (ob._isGroup) return (ob as GroupObject)._isGroup + if (ob._isGroup) return (ob as GroupObject)._isGroup; else { return ( ob.appliedStereotypeIds !== undefined && ob.appliedStereotypeIds.length > 0 && ob.appliedStereotypeIds[0] === this.schemaSvc.getSchema('GROUP_ST_ID', this.schema) - ) + ); } } public getElementType = (element: ElementObject): string => { // Get Type - let elementType = '' + let elementType = ''; if (this.apiSvc.isRequirement(element)) { - elementType = 'Requirement' + elementType = 'Requirement'; } else if (this.apiSvc.isDocument(element)) { - elementType = 'Document' + elementType = 'Document'; } else if (this.apiSvc.isView(element)) { - elementType = 'View' + elementType = 'View'; } else if (this.isGroup(element)) { - elementType = 'Group' + elementType = 'Group'; } else { - elementType = this.getPresentationElementType(element) + elementType = this.getPresentationElementType(element); } - return elementType - } + return elementType; + }; public reset = (): void => { - this.inProgress = {} - } + this.inProgress = {}; + }; } -veUtils.service('ViewService', ViewService) +veUtils.service('ViewService', ViewService); diff --git a/src/ve-utils/mms-api-client/index.ts b/src/ve-utils/mms-api-client/index.ts index 579288e4e..5da2df6b5 100644 --- a/src/ve-utils/mms-api-client/index.ts +++ b/src/ve-utils/mms-api-client/index.ts @@ -1,21 +1,21 @@ -import './Api.service' -import './URL.service' -import './Authorization.service' -import './Element.service' -import './Http.service' -import './Permissions.service' -import './Project.service' -import './View.service' -import './User.service' -import './Value.service' +import './Api.service'; +import './URL.service'; +import './Authorization.service'; +import './Element.service'; +import './Http.service'; +import './Permissions.service'; +import './Project.service'; +import './View.service'; +import './User.service'; +import './Value.service'; -export * from './URL.service' -export * from './Authorization.service' -export * from './Element.service' -export * from './Http.service' -export * from './Permissions.service' -export * from './Project.service' -export * from './View.service' -export * from './Api.service' -export * from './User.service' -export * from './Value.service' +export * from './URL.service'; +export * from './Authorization.service'; +export * from './Element.service'; +export * from './Http.service'; +export * from './Permissions.service'; +export * from './Project.service'; +export * from './View.service'; +export * from './Api.service'; +export * from './User.service'; +export * from './Value.service'; diff --git a/src/ve-utils/modals/ve-modal.controller.ts b/src/ve-utils/modals/ve-modal.controller.ts index 54e4f0919..1e140c1c5 100644 --- a/src/ve-utils/modals/ve-modal.controller.ts +++ b/src/ve-utils/modals/ve-modal.controller.ts @@ -1,10 +1,10 @@ -import { VeModalResolve, VeModalController, VeModalInstanceService } from '@ve-types/view-editor' +import { VeModalResolve, VeModalController, VeModalInstanceService } from '@ve-types/view-editor'; export class VeModalControllerImpl implements VeModalController { // public close($value?: any): void {}; // // public dismiss($value?: any): void {}; - modalInstance: VeModalInstanceService - protected resolve: U + modalInstance: VeModalInstanceService; + protected resolve: U; } diff --git a/src/ve-utils/model-schema/CameoSchema.service.ts b/src/ve-utils/model-schema/CameoSchema.service.ts index 9f051b0cf..7ee06d610 100644 --- a/src/ve-utils/model-schema/CameoSchema.service.ts +++ b/src/ve-utils/model-schema/CameoSchema.service.ts @@ -1,9 +1,9 @@ -import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service' +import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; export class CameoSchema implements Schema { - jsonName = 'cameo' + jsonName = 'cameo'; schema: SchemaMapping = { VIEW_SID: '_11_5EAPbeta_be00301_1147420760998_43940_227', OTHER_VIEW_SID: [ @@ -52,7 +52,7 @@ export class CameoSchema implements Schema { NumSep: '_18_5_3_8bf0285_1526605817077_688557_15755', }, GROUP_ST_ID: '_18_5_3_8bf0285_1520469040211_2821_15754', - } + }; map: SchemaMapping = { OPAQUE_CLASSIFIERS: [ this.schema.TYPE_TO_CLASSIFIER_ID['Image'], @@ -62,10 +62,10 @@ export class CameoSchema implements Schema { this.schema.TYPE_TO_CLASSIFIER_ID['Table'], this.schema.TYPE_TO_CLASSIFIER_ID['Figure'], ], - } + }; } -veUtils.service('CameoSchema', CameoSchema) +veUtils.service('CameoSchema', CameoSchema); // TODO: Create Cameo Project Creation Service // { diff --git a/src/ve-utils/model-schema/JupyterSchema.service.ts b/src/ve-utils/model-schema/JupyterSchema.service.ts index 5cf11557e..7dfe4e420 100644 --- a/src/ve-utils/model-schema/JupyterSchema.service.ts +++ b/src/ve-utils/model-schema/JupyterSchema.service.ts @@ -1,12 +1,12 @@ -import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service' +import { Schema, SchemaMapping } from '@ve-utils/model-schema/Schema.service'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; export class JupyterSchema implements Schema { - static $inject = [] + static $inject = []; - jsonName: string = 'jupyter' - schema: SchemaMapping = {} + jsonName: string = 'jupyter'; + schema: SchemaMapping = {}; } -veUtils.service('JupyterSchema', JupyterSchema) +veUtils.service('JupyterSchema', JupyterSchema); diff --git a/src/ve-utils/model-schema/Schema.service.ts b/src/ve-utils/model-schema/Schema.service.ts index 911486f7c..97826883d 100644 --- a/src/ve-utils/model-schema/Schema.service.ts +++ b/src/ve-utils/model-schema/Schema.service.ts @@ -1,112 +1,112 @@ -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; -import { VeConfig } from '@ve-types/config' +import { VeConfig } from '@ve-types/config'; export interface SchemaMapping { - [key: string]: unknown + [key: string]: unknown; } export interface Schema { - jsonName: string - schema: SchemaMapping - map?: SchemaMapping + jsonName: string; + schema: SchemaMapping; + map?: SchemaMapping; } export class SchemaService { - static $inject = ['$q', '$injector'] + static $inject = ['$q', '$injector']; - public veConfig: VeConfig = window.__env - public defaultSchema: 'cameo' + public veConfig: VeConfig = window.__env; + public defaultSchema: 'cameo'; public schemaList: { [key: string]: string } = { cameo: 'CameoSchema', jupyter: 'JupyterSchema', - } + }; - public schemas: { [key: string]: Schema } = {} + public schemas: { [key: string]: Schema } = {}; constructor(private $q, private $injector: angular.auto.IInjectorService) { for (const [key, value] of Object.entries(this.schemaList)) { - this.schemas[key] = this.$injector.get(value) + this.schemas[key] = this.$injector.get(value); } } getSchema = (name: string, schemaName?: string, sourceId?: string): T => { - const schema: Schema = this._getSchema(schemaName, sourceId) + const schema: Schema = this._getSchema(schemaName, sourceId); if (schema.schema[name]) { - return schema.schema[name] as T + return schema.schema[name] as T; } else { - this._schemaError(name, schemaName) + this._schemaError(name, schemaName); } - } + }; getValue = (name: string, key: string, schemaName?: string, sourceId?: string): T => { - const lookup = this.getSchema(name, schemaName, sourceId) + const lookup = this.getSchema(name, schemaName, sourceId); if (lookup && typeof lookup === 'object') { - return lookup[key] as T + return lookup[key] as T; } - } + }; getValues(name: string, keys: string[], schemaName?: string, sourceId?: string): T[] | null { - const lookup = this.getSchema(name, schemaName, sourceId) + const lookup = this.getSchema(name, schemaName, sourceId); if (lookup && typeof lookup === 'object') { - const response: T[] = [] + const response: T[] = []; keys.forEach((key) => { if (lookup.hasOwnProperty(key)) { - response.push(lookup[key] as T) + response.push(lookup[key] as T); } - }) - return response + }); + return response; } } getMap = (name: string, schemaName?: string, sourceId?: string): T => { - const schema: Schema = this._getSchema(schemaName, sourceId) + const schema: Schema = this._getSchema(schemaName, sourceId); if (schema.map && schema.map[name]) { - return schema.map[name] as T + return schema.map[name] as T; } else { - this._schemaError(name, schemaName) - return null + this._schemaError(name, schemaName); + return null; } - } + }; getMappedValue = (name: string, key: string, schemaName?: string, sourceId?: string): T => { - const lookup = this.getMap(name, schemaName, sourceId) + const lookup = this.getMap(name, schemaName, sourceId); if (lookup && typeof lookup === 'object') { - return lookup[key] as T + return lookup[key] as T; } - } + }; getKeyByValue = (name: string, value: T, schemaName?: string, sourceId?: string): string => { - const lookup = this.getSchema(name, schemaName, sourceId) + const lookup = this.getSchema(name, schemaName, sourceId); if (lookup && typeof lookup === 'object') { - let response = '' + let response = ''; Object.keys(lookup).some((key) => { if (lookup[key] === value) { - response = key - return true + response = key; + return true; } - return false - }) - return response + return false; + }); + return response; } - } + }; private _schemaError = (name: string, schemaName?: string): void => { - schemaName = schemaName ? schemaName : this.defaultSchema + schemaName = schemaName ? schemaName : this.defaultSchema; if (this.veConfig.enableDebug) { - console.log(schemaName + ' does not have table' + name + 'or it is not properly configured') + console.log(schemaName + ' does not have table' + name + 'or it is not properly configured'); } - } + }; private _getSchema = (schemaName?: string, id?: string): Schema | null => { - schemaName = schemaName ? schemaName : this.defaultSchema - id = id ? id : 'error: unknown' + schemaName = schemaName ? schemaName : this.defaultSchema; + id = id ? id : 'error: unknown'; if (this.schemas.hasOwnProperty(schemaName)) { - return this.schemas[schemaName] + return this.schemas[schemaName]; } else { - console.log(`Object ${id} uses an unknown schema ${schemaName}`) + console.log(`Object ${id} uses an unknown schema ${schemaName}`); } - } + }; } -veUtils.service('SchemaService', SchemaService) +veUtils.service('SchemaService', SchemaService); diff --git a/src/ve-utils/model-schema/index.ts b/src/ve-utils/model-schema/index.ts index 94a6af9a4..c17dcefdc 100644 --- a/src/ve-utils/model-schema/index.ts +++ b/src/ve-utils/model-schema/index.ts @@ -1,7 +1,7 @@ -import './CameoSchema.service' -import './JupyterSchema.service' -import './Schema.service' +import './CameoSchema.service'; +import './JupyterSchema.service'; +import './Schema.service'; -export * from './CameoSchema.service' -export * from './JupyterSchema.service' -export * from './Schema.service' +export * from './CameoSchema.service'; +export * from './JupyterSchema.service'; +export * from './Schema.service'; diff --git a/src/ve-utils/third-party/index.ts b/src/ve-utils/third-party/index.ts index 0bdc684bd..8b138df6a 100644 --- a/src/ve-utils/third-party/index.ts +++ b/src/ve-utils/third-party/index.ts @@ -1 +1 @@ -import './jquery' +import './jquery'; diff --git a/src/ve-utils/third-party/jquery/index.ts b/src/ve-utils/third-party/jquery/index.ts index 480e6ad63..9c558addc 100644 --- a/src/ve-utils/third-party/jquery/index.ts +++ b/src/ve-utils/third-party/jquery/index.ts @@ -1,2 +1,2 @@ -import './isOnScreen.jquery' -import './table2CSV.jquery' +import './isOnScreen.jquery'; +import './table2CSV.jquery'; diff --git a/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts b/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts index 5f01e1ca1..d2eba58d2 100644 --- a/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts +++ b/src/ve-utils/third-party/jquery/isOnScreen.jquery.ts @@ -1,43 +1,43 @@ -import jQuery from 'jquery' +import jQuery from 'jquery'; jQuery.fn.isOnScreen = (x?, y?): boolean => { - if (x == null || typeof x == 'undefined') x = 1 - if (y == null || typeof y == 'undefined') y = 1 + if (x == null || typeof x == 'undefined') x = 1; + if (y == null || typeof y == 'undefined') y = 1; - const win = $(window) + const win = $(window); const viewport = { top: win.scrollTop(), left: win.scrollLeft(), right: win.scrollLeft() + win.width(), bottom: win.scrollTop() + win.height(), - } + }; - const height = jQuery.fn.outerHeight() - const width = jQuery.fn.outerWidth() + const height = jQuery.fn.outerHeight(); + const width = jQuery.fn.outerWidth(); if (!width || !height) { - return false + return false; } const bounds: { - right?: number - left: number - bottom?: number - top: number - } = jQuery.fn.offset() - bounds.right = bounds.left + width - bounds.bottom = bounds.top + height + right?: number; + left: number; + bottom?: number; + top: number; + } = jQuery.fn.offset(); + bounds.right = bounds.left + width; + bounds.bottom = bounds.top + height; const visible = !( viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom - ) + ); if (!visible) { - return false + return false; } const deltas = { @@ -45,7 +45,7 @@ jQuery.fn.isOnScreen = (x?, y?): boolean => { bottom: Math.min(1, (viewport.bottom - bounds.top) / height), left: Math.min(1, (bounds.right - viewport.left) / width), right: Math.min(1, (viewport.right - bounds.left) / width), - } + }; - return deltas.left * deltas.right >= x && deltas.top * deltas.bottom >= y -} + return deltas.left * deltas.right >= x && deltas.top * deltas.bottom >= y; +}; diff --git a/src/ve-utils/third-party/jquery/table2CSV.jquery.ts b/src/ve-utils/third-party/jquery/table2CSV.jquery.ts index 356db3384..3cda1b948 100644 --- a/src/ve-utils/third-party/jquery/table2CSV.jquery.ts +++ b/src/ve-utils/third-party/jquery/table2CSV.jquery.ts @@ -1,4 +1,4 @@ -import jQuery from 'jquery' +import jQuery from 'jquery'; jQuery.fn.table2CSV = (inputOptions: JQuery.table2CSV.inputOptions): string => { const options = jQuery.extend( @@ -8,111 +8,111 @@ jQuery.fn.table2CSV = (inputOptions: JQuery.table2CSV.inputOptions): string => { delivery: 'popup', // popup, value }, inputOptions - ) + ); - const csvData: string[] = [] + const csvData: string[] = []; // const el = this const row2CSV = (tmpRow: string[]): void => { - const tmp = tmpRow.join('') // to remove any blank rows + const tmp = tmpRow.join(''); // to remove any blank rows if (tmpRow.length > 0 && tmp != '') { - csvData[csvData.length] = tmpRow.join(options.separator) + csvData[csvData.length] = tmpRow.join(options.separator); } - } + }; const formatData = (input: string): string => { // replace " with “ - const regexp = new RegExp(/["]/g) - let output = input.replace(regexp, '“') + const regexp = new RegExp(/["]/g); + let output = input.replace(regexp, '“'); //HTML // var regexp = new RegExp(/\<[^\<]+\>/g); // var output = output.replace(regexp, ""); - const i = output.search(/\S/) //index of first non whitespace char + const i = output.search(/\S/); //index of first non whitespace char if (i > 0) { - output = '_'.repeat(i) + $.trim(output) + output = '_'.repeat(i) + $.trim(output); } - output = $.trim(output) - if (output == '') return '' + output = $.trim(output); + if (output == '') return ''; if (output[0] == '+' || output[0] == '=' || output[0] == '-') { - output = ' ' + output + output = ' ' + output; } - return `"${output}"` - } + return `"${output}"`; + }; const popup = (data: string): string => { - const generator = window.open('', 'csv', 'height=400,width=600') - generator.document.write('CSV') - generator.document.write('') - generator.document.write('') - generator.document.write('') - generator.document.close() - return 'ok' - } + const generator = window.open('', 'csv', 'height=400,width=600'); + generator.document.write('CSV'); + generator.document.write(''); + generator.document.write(''); + generator.document.write(''); + generator.document.close(); + return 'ok'; + }; const handleMatrix = (bodyTag: string, cellTag: string): void => { - const spanData: { [row: number]: { [column: number]: unknown } } = {} //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell - let curRow = 0 + const spanData: { [row: number]: { [column: number]: unknown } } = {}; //if spanData[curRow][curCol] is true that means that 'cell' should be "" due to merged cell + let curRow = 0; $(this) .children(bodyTag) .children('tr') .each((index, element) => { - tmpRow = [] - let curCol = 0 + tmpRow = []; + let curCol = 0; $(element) .children(cellTag) .each((index, element) => { while (spanData[curRow] && spanData[curRow][curCol]) { - tmpRow.push('""') - curCol++ + tmpRow.push('""'); + curCol++; } - tmpRow.push(formatData($(element).text())) - const rowstring = $(element).attr('rowspan') - const rowspan = parseInt(rowstring) + tmpRow.push(formatData($(element).text())); + const rowstring = $(element).attr('rowspan'); + const rowspan = parseInt(rowstring); if (rowspan && rowspan > 1) { for (let i = 1; i < rowspan; i++) { if (!spanData[curRow + i]) { - spanData[curRow + i] = {} + spanData[curRow + i] = {}; } - spanData[curRow + i][curCol] = true + spanData[curRow + i][curCol] = true; } } - const colstring = $(element).attr('colspan') + const colstring = $(element).attr('colspan'); if (!colstring) { - curCol++ - return + curCol++; + return; } - let colspan = parseInt(colstring) + let colspan = parseInt(colstring); while (colspan > 1) { - curCol++ - tmpRow.push('""') - colspan-- + curCol++; + tmpRow.push('""'); + colspan--; if (rowspan > 1) { for (let i = 1; i < rowspan; i++) { - spanData[curRow + i][curCol] = true + spanData[curRow + i][curCol] = true; } } } - curCol++ - }) - row2CSV(tmpRow) - curRow++ - }) - } + curCol++; + }); + row2CSV(tmpRow); + curRow++; + }); + }; //header - const numCols = options.header.length - let tmpRow: string[] = [] + const numCols = options.header.length; + let tmpRow: string[] = []; if (numCols > 0) { for (let i = 0; i < numCols; i++) { - tmpRow[tmpRow.length] = formatData(options.header[i]) + tmpRow[tmpRow.length] = formatData(options.header[i]); } } else { - handleMatrix('thead', 'th') + handleMatrix('thead', 'th'); } // actual data - handleMatrix('tbody', 'td') - const mydata = csvData.join('\n') + handleMatrix('tbody', 'td'); + const mydata = csvData.join('\n'); if (options.delivery == 'popup') { - return popup(mydata) + return popup(mydata); } else { - return mydata + return mydata; } -} +}; diff --git a/src/ve-utils/utils/change.util.ts b/src/ve-utils/utils/change.util.ts index 42d5da391..8753aaa54 100644 --- a/src/ve-utils/utils/change.util.ts +++ b/src/ve-utils/utils/change.util.ts @@ -1,8 +1,8 @@ -import _ from 'lodash' +import _ from 'lodash'; -import { EventService } from '@ve-utils/core' +import { EventService } from '@ve-utils/core'; -import { VeQService } from '@ve-types/angular' +import { VeQService } from '@ve-types/angular'; /** * @name onChangesCallback @@ -17,7 +17,7 @@ import { VeQService } from '@ve-types/angular' * } * */ -export type onChangesCallback = (newVal?: T, oldVal?: T, firstChange?: boolean) => U +export type onChangesCallback = (newVal?: T, oldVal?: T, firstChange?: boolean) => U; /** * @name change.utils#handleChange: @@ -48,23 +48,23 @@ export function handleChange( ignoreFirst?: boolean ): void { if (watch === '') { - return callback() + return callback(); } else if (changesObj[watch]) { if (ignoreFirst && changesObj[watch].isFirstChange()) { - return + return; } - const newVal: T = changesObj[watch].currentValue as T - const oldVal: T = changesObj[watch].previousValue as T - const firstChange = changesObj[watch].isFirstChange() - callback(newVal, oldVal, firstChange) + const newVal: T = changesObj[watch].currentValue as T; + const oldVal: T = changesObj[watch].previousValue as T; + const firstChange = changesObj[watch].isFirstChange(); + callback(newVal, oldVal, firstChange); } - return + return; } interface EventWatcher { - $q: VeQService - eventSvc: EventService - subs: Rx.IDisposable[] + $q: VeQService; + eventSvc: EventService; + subs: Rx.IDisposable[]; } export function watchChangeEvent( @@ -79,15 +79,15 @@ export function watchChangeEvent( currentValue: data, previousValue: _.cloneDeep($ctrl[name] as T), isFirstChange: () => { - return typeof $ctrl[name] === 'undefined' + return typeof $ctrl[name] === 'undefined'; }, - } + }; if (data !== $ctrl[name]) { if (update) { - $ctrl[name] = data + $ctrl[name] = data; } - changeAction(change.currentValue, change.previousValue, change.isFirstChange()) + changeAction(change.currentValue, change.previousValue, change.isFirstChange()); } }) - ) + ); } diff --git a/src/ve-utils/utils/emf.util.ts b/src/ve-utils/utils/emf.util.ts index b0423f4c1..1c761b7a8 100644 --- a/src/ve-utils/utils/emf.util.ts +++ b/src/ve-utils/utils/emf.util.ts @@ -1,172 +1,172 @@ -import { ElementObject, ExpressionObject, PackageObject, ValueObject } from '@ve-types/mms' +import { ElementObject, ExpressionObject, PackageObject, ValueObject } from '@ve-types/mms'; export class Element implements ElementObject { - id: string = '' - _projectId: string = '' - _refId: string = '' - appliedStereotypeIds: string[] = [] - documentation: string = '' - mdExtensionsIds: string[] = [] - syncElementId: string = null - type: string = 'Element' + id: string = ''; + _projectId: string = ''; + _refId: string = ''; + appliedStereotypeIds: string[] = []; + documentation: string = ''; + mdExtensionsIds: string[] = []; + syncElementId: string = null; + type: string = 'Element'; constructor(elementOb?: ElementObject) { if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class NamedElement extends Element { - name: string = '' - nameExpression: string = null - clientDependencyIds: string[] = [] - supplierDependencyIds: string[] = [] + name: string = ''; + nameExpression: string = null; + clientDependencyIds: string[] = []; + supplierDependencyIds: string[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } class PackageableElement extends NamedElement { - ownerId: string = null - visibility: string = 'public' - templateParameterId: string = null + ownerId: string = null; + visibility: string = 'public'; + templateParameterId: string = null; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } class TypedElement extends PackageableElement { - typeId: string = null + typeId: string = null; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } class TemplateableElement extends PackageableElement { - templateBindingIds: string[] = [] + templateBindingIds: string[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Property extends TypedElement { - type = 'Property' - defaultValue: any[] = [] + type = 'Property'; + defaultValue: any[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Class extends TemplateableElement { - classifierBehaviorId: string = null - collaborationUseIds: string[] = [] - elementImportIds: string[] = [] - generalizationIds: string[] = [] - classRealizationIds: string[] = [] - isAbstract: boolean = false - isActive: boolean = false - isFinalSpecialization: boolean = false - isLeaf: boolean = false - ownedAttributeIds: string[] = [] - ownedOperationIds: string[] = [] - packageImportIds: string[] = [] - powertypeExtentIds: string[] = [] - redefinedClassifierIds: string[] = [] - representationI: string[] = [] - type = 'Class' - useCaseIds: string[] = [] + classifierBehaviorId: string = null; + collaborationUseIds: string[] = []; + elementImportIds: string[] = []; + generalizationIds: string[] = []; + classRealizationIds: string[] = []; + isAbstract: boolean = false; + isActive: boolean = false; + isFinalSpecialization: boolean = false; + isLeaf: boolean = false; + ownedAttributeIds: string[] = []; + ownedOperationIds: string[] = []; + packageImportIds: string[] = []; + powertypeExtentIds: string[] = []; + redefinedClassifierIds: string[] = []; + representationI: string[] = []; + type = 'Class'; + useCaseIds: string[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class InstanceSpec extends PackageableElement { - classifierIds: string[] = [] - deploymentIds: string[] = [] - slotIds: string[] = [] - specification: Element = null - stereotypedElementId: string = null - type = 'InstanceSpecification' + classifierIds: string[] = []; + deploymentIds: string[] = []; + slotIds: string[] = []; + specification: Element = null; + stereotypedElementId: string = null; + type = 'InstanceSpecification'; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class ValueSpec extends TypedElement implements ValueObject { - valueExpression: string = '' - type = 'ValueSpecification' + valueExpression: string = ''; + type = 'ValueSpecification'; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Expression extends ValueSpec implements ExpressionObject { - operand: T[] = [] - type = 'Expression' + operand: T[] = []; + type = 'Expression'; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Package extends TemplateableElement implements PackageObject { - type = 'Package' - visibility = null - elementImportIds: string[] = [] - packageImportIds: string[] = [] - URI: string = '' - packageMergeIds: string[] = [] - profileApplicationIds: string[] = [] + type = 'Package'; + visibility = null; + elementImportIds: string[] = []; + packageImportIds: string[] = []; + URI: string = ''; + packageMergeIds: string[] = []; + profileApplicationIds: string[] = []; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Generalization extends Element { - generalizationSetIds: string[] = [] - isSubstitutable: boolean = true - type = 'Generalization' + generalizationSetIds: string[] = []; + isSubstitutable: boolean = true; + type = 'Generalization'; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } export class Dependency extends PackageableElement { - type = 'Dependency' - visibility = null + type = 'Dependency'; + visibility = null; constructor(elementOb?: ElementObject) { - super(elementOb) + super(elementOb); if (elementOb) { - Object.assign(this, elementOb) + Object.assign(this, elementOb); } } } diff --git a/src/ve-utils/utils/index.ts b/src/ve-utils/utils/index.ts index 6eae2b6fd..847dc55d5 100644 --- a/src/ve-utils/utils/index.ts +++ b/src/ve-utils/utils/index.ts @@ -1,2 +1,2 @@ -export * from './change.util' -export * from './emf.util' +export * from './change.util'; +export * from './emf.util'; diff --git a/src/ve-utils/ve-utils.module.ts b/src/ve-utils/ve-utils.module.ts index 11895ab96..5408eac8c 100644 --- a/src/ve-utils/ve-utils.module.ts +++ b/src/ve-utils/ve-utils.module.ts @@ -1,4 +1,4 @@ -import angular from 'angular' +import angular from 'angular'; /** * @ngdoc overview @@ -55,14 +55,14 @@ import angular from 'angular' ]); */ -export const veUtils = angular.module('ve-utils', []) +export const veUtils = angular.module('ve-utils', []); veUtils .config([ '$sceProvider', ($sceProvider: angular.ISCEProvider): void => { - $sceProvider.enabled(false) + $sceProvider.enabled(false); }, ]) //.constant('HtmlRenderedDiff', window.HtmlRenderedDiff) - .constant('moment', window.moment) + .constant('moment', window.moment); From fc9f8a8be7bc101810a21b0a4a5c0b0a908756b8 Mon Sep 17 00:00:00 2001 From: Enquier Date: Mon, 15 May 2023 13:17:25 -0600 Subject: [PATCH 22/31] minor error fixing --- src/lib/environment.ts | 4 ++-- src/ve-extensions/index.ts | 2 +- src/ve-utils/application/Math.service.ts | 22 +++++++++++----------- tsconfig.json | 1 - webpack.config.ts | 2 +- 5 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/lib/environment.ts b/src/lib/environment.ts index f3d90ad92..caebc2f68 100644 --- a/src/lib/environment.ts +++ b/src/lib/environment.ts @@ -5,6 +5,6 @@ const environment = { modules: './node_modules/', }, mode: 'local', -} +}; -export default environment +export default environment; diff --git a/src/ve-extensions/index.ts b/src/ve-extensions/index.ts index d383e35a3..3e118298f 100644 --- a/src/ve-extensions/index.ts +++ b/src/ve-extensions/index.ts @@ -1,2 +1,2 @@ //** Automatically Generated by Webpack do not edit **// -import './experimental-magic'; +import './experimental-magic' \ No newline at end of file diff --git a/src/ve-utils/application/Math.service.ts b/src/ve-utils/application/Math.service.ts index c6687e68b..b22815d27 100644 --- a/src/ve-utils/application/Math.service.ts +++ b/src/ve-utils/application/Math.service.ts @@ -1,26 +1,26 @@ -import { MathJaxObject } from 'mathjax-full/js/components/startup' +import { MathJaxObject } from 'mathjax-full/js/components/startup'; -import { veUtils } from '@ve-utils' +import { veUtils } from '@ve-utils'; export class MathService { - private promise = Promise.resolve() // Used to hold chain of typesetting calls - private mathJax: MathJaxObject = window.MathJax + private promise = Promise.resolve(); // Used to hold chain of typesetting calls + private mathJax: MathJaxObject = window.MathJax; - static $inject = [] + static $inject = []; typeset(element: HTMLElement | HTMLElement[]): Promise { this.promise = this.promise .then(() => { if (!Array.isArray(element)) { - element = [element] + element = [element]; } - ;(this.mathJax.typesetPromise as (elements: HTMLElement[]) => Promise)(element).catch( + (this.mathJax.typesetPromise as (elements: HTMLElement[]) => Promise)(element).catch( (err: { message: string }) => console.log(`Typeset failed: ${err.message}`) - ) + ); }) - .catch((err: { message: string }) => console.log(`Typeset failed: ${err.message}`)) - return this.promise + .catch((err: { message: string }) => console.log(`Typeset failed: ${err.message}`)); + return this.promise; } } -veUtils.service('MathService', MathService) +veUtils.service('MathService', MathService); diff --git a/tsconfig.json b/tsconfig.json index c5b997451..09449e2ee 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,7 +18,6 @@ "typeRoots": [ "node_modules/@types", "node_modules/type-fest/index.d.ts", - "src/lib", "node_modules/flatpickr/dist/typings.d.ts" ], "rootDir": "src", diff --git a/webpack.config.ts b/webpack.config.ts index 8e0e0ce1c..f59c14e8e 100644 --- a/webpack.config.ts +++ b/webpack.config.ts @@ -81,7 +81,7 @@ class SetupPlugin implements AutomaticPrefetchPlugin { extPath = path.resolve(sourceDir, ext.path) } - fs.appendFile(`${extensionsDir}/index.ts`, `\nimport '${extPath}'`, (err) => { + fs.appendFile(`${extensionsDir}/index.ts`, `\nimport '${extPath}';`, (err) => { if (err) { throw err } From eafe38955367555178a5b9d30679efd870a54798 Mon Sep 17 00:00:00 2001 From: Doris Lam Date: Mon, 12 Jun 2023 17:33:25 -0700 Subject: [PATCH 23/31] update tree when presentation element gets added/deleted/reordered --- src/ve-app/pane-left/left-pane.component.ts | 28 ++++++++++++------- .../services/Presentation.service.ts | 8 ++++-- .../components/spec-reorder.component.ts | 1 + .../deletable-transclusion.controller.ts | 2 +- .../trees/mms-trees.component.ts | 14 ---------- .../trees/services/Tree.service.ts | 2 +- 6 files changed, 27 insertions(+), 28 deletions(-) diff --git a/src/ve-app/pane-left/left-pane.component.ts b/src/ve-app/pane-left/left-pane.component.ts index 3a8e83966..0d7b7f3bd 100644 --- a/src/ve-app/pane-left/left-pane.component.ts +++ b/src/ve-app/pane-left/left-pane.component.ts @@ -174,17 +174,25 @@ class LeftPaneController implements angular.IComponentController { search: undefined, }); }), - this.eventSvc.$on('presentation.deleted', (data) => { - this.treeSvc.getBranch(data).then( - (branch) => { - this.treeSvc.removeBranch(branch).catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); - }, - () => { - this.growl.error('Deleted branch not found'); + this.eventSvc.$on('view.reordered', (viewOrSection) => { + this.treeSvc.getBranch(viewOrSection).then((b) => { + const old = b.children; + const newChildren = []; + let viewBranch = b; + for (const c of old) { + if (c.type === 'view') { + newChildren.push(c); + } } - ); + if (b.type === 'section') { + viewBranch = this.treeSvc.viewId2node[b.viewId]; + if (!viewBranch) { + viewBranch = b; + } + } + b.children = newChildren; + this.treeSvc.addSectionElements(viewOrSection, viewBranch, b, false); + }) }) ); /* diff --git a/src/ve-components/presentations/services/Presentation.service.ts b/src/ve-components/presentations/services/Presentation.service.ts index 4e27e887a..bb53f2f1b 100644 --- a/src/ve-components/presentations/services/Presentation.service.ts +++ b/src/ve-components/presentations/services/Presentation.service.ts @@ -6,6 +6,7 @@ import { veComponents } from '@ve-components'; import { InsertResolveFn } from '@ve-types/components'; import { ElementObject, InstanceSpecObject, InstanceValueObject } from '@ve-types/mms'; import { VeModalService } from '@ve-types/view-editor'; +import { EventService } from "@ve-utils/core"; export class PresentationService { private revertData: { @@ -17,13 +18,14 @@ export class PresentationService { element: object; }; - static $inject = ['$timeout', '$uibModal', 'growl', 'ViewService']; + static $inject = ['$timeout', '$uibModal', 'growl', 'ViewService', 'EventService']; constructor( private $timeout: angular.ITimeoutService, private $uibModal: VeModalService, private growl: angular.growl.IGrowlService, - private viewSvc: ViewService + private viewSvc: ViewService, + private eventSvc: EventService ) {} public checkForDuplicateInstances(operand: InstanceValueObject[]): InstanceValueObject[] { @@ -84,6 +86,8 @@ export class PresentationService { }); instance.result.then( (data) => { + //send event to tree + this.eventSvc.$broadcast('view.reordered', viewOrSectionOb); if (data.type !== 'InstanceSpecification' || this.viewSvc.isSection(data)) { return; //do not open editor for existing pes added or if pe/owner is a section } diff --git a/src/ve-components/spec-tools/components/spec-reorder.component.ts b/src/ve-components/spec-tools/components/spec-reorder.component.ts index 3b9c32df5..f151b5c09 100644 --- a/src/ve-components/spec-tools/components/spec-reorder.component.ts +++ b/src/ve-components/spec-tools/components/spec-reorder.component.ts @@ -131,6 +131,7 @@ class SpecReorderController extends SpecTool implements ISpecTool { const saved = elements.filter((val) => val.id === this.view.id); if (saved.length > 0) { this.eventSvc.$broadcast('element.updated', { element: saved[0] }); + this.eventSvc.$broadcast('view.reordered', saved[0]); } this.eventSvc.$broadcast('spec-reorder.saved', this.view.id); this.eventSvc.resolve(this.toolbarId, { diff --git a/src/ve-components/transclusions/deletable-transclusion.controller.ts b/src/ve-components/transclusions/deletable-transclusion.controller.ts index 8bc86ec35..c1cbb90f9 100644 --- a/src/ve-components/transclusions/deletable-transclusion.controller.ts +++ b/src/ve-components/transclusions/deletable-transclusion.controller.ts @@ -103,7 +103,7 @@ export class DeletableTransclusion extends Transclusion { this.viewSvc.removeElementFromViewOrSection(reqOb, instanceVal).then( () => { // Broadcast message to TreeCtrl: - this.eventSvc.$broadcast('presentation.deleted', instanceSpec); + this.eventSvc.$broadcast('view.reordered', viewOrSec); this.eventSvc.$broadcast('content-reorder.refresh'); diff --git a/src/ve-components/trees/mms-trees.component.ts b/src/ve-components/trees/mms-trees.component.ts index 9f2899ec1..0cc8f3d48 100644 --- a/src/ve-components/trees/mms-trees.component.ts +++ b/src/ve-components/trees/mms-trees.component.ts @@ -219,20 +219,6 @@ class TreesController implements IComponentController { } } data.$event.stopPropagation(); - }), - this.eventSvc.$on('presentation.deleted', (data) => { - this.treeSvc.getBranch(data).then( - (branch) => { - if (branch) { - this.treeSvc.removeBranch(branch).catch((reason) => { - this.growl.error(TreeService.treeError(reason)); - }); - } - }, - (reason) => { - this.growl.error(TreeService.treeError(reason)); - } - ); }) ); } diff --git a/src/ve-components/trees/services/Tree.service.ts b/src/ve-components/trees/services/Tree.service.ts index 4e291449f..be7031de6 100644 --- a/src/ve-components/trees/services/Tree.service.ts +++ b/src/ve-components/trees/services/Tree.service.ts @@ -335,7 +335,7 @@ export class TreeService { public removeBranch = (branch: TreeBranch): VePromise => { this._removeBranch(branch, false); - return this.$q.resolve(); + return this._onTreeDataChange(); }; /** From 46e24935dae802f43cdcc561c68b9ef32c95ecda Mon Sep 17 00:00:00 2001 From: Doris Lam Date: Thu, 15 Jun 2023 12:15:48 -0700 Subject: [PATCH 24/31] fix live numbering, figure numbering in pdf, list of tables and figures in pdf, adding pe in section --- src/ve-app/main/services/AppUtils.service.ts | 6 +++--- src/ve-app/main/services/Resolve.service.ts | 10 +--------- src/ve-app/pane-center/document.component.ts | 4 +++- src/ve-app/pane-center/slideshow.component.ts | 2 +- .../insertions/components/insert-pe.component.ts | 1 - .../insertions/components/insert-ref.component.ts | 4 ---- src/ve-components/insertions/insertion.controller.ts | 1 - .../components/transclude-section.component.ts | 2 +- src/ve-utils/application/Utils.service.ts | 4 ++-- 9 files changed, 11 insertions(+), 23 deletions(-) diff --git a/src/ve-app/main/services/AppUtils.service.ts b/src/ve-app/main/services/AppUtils.service.ts index b14cc1266..fba969bdc 100644 --- a/src/ve-app/main/services/AppUtils.service.ts +++ b/src/ve-app/main/services/AppUtils.service.ts @@ -213,7 +213,7 @@ Save CSV const css = choice.customization ? choice.customCSS : this.utilsSvc.getPrintCss(choice.model.htmlTotf, choice.model.landscape, choice.meta); - result.toe = choice[2] ? '' : result.toe; + result.toe = choice.model.htmlTotf ? '' : result.toe; if (mode === 1) { const popupWin = this.$window.open( 'about:blank', @@ -251,8 +251,8 @@ Save CSV this.growl.error('Popup Window Failed to open. Allow popups and try again'); } } else { - result.tof = choice[1] ? result.tof + result.toe : ''; - result.tot = choice[1] ? result.tot : ''; + result.tof = choice.model.genTotf ? result.tof + result.toe : ''; + result.tot = choice.model.genTotf ? result.tot : ''; const htmlArr = [ '' + viewOrDocOb.name + '