diff --git a/.circleci/config.yml b/.circleci/config.yml index dcc6d54aa..96f09c0df 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -7,7 +7,7 @@ jobs: build: docker: # specify the version you desire here - - image: circleci/node:8.11.2-browsers + - image: cimg/node:20.1.0-browsers # Specify service dependencies here if necessary # CircleCI maintains a library of pre-built images @@ -25,11 +25,11 @@ jobs: # fallback to using the latest cache if no exact match is found - openmbee-ve- - - run: npm install + - run: yarn install - save_cache: paths: - node_modules key: openmbee-ve-{{ checksum "package.json" }} - - run: ./node_modules/grunt/bin/grunt #--ARTIFACTORY_URL=https://oss.jfrog.org --ARTIFACTORY_USER=$ARTIFACTORY_USER --ARTIFACTORY_PASSWORD=$ARTIFACTORY_PASSWORD --SNAPSHOT_REPO=oss-snapshot-local --RELEASE_REPO=oss-release-local --GROUP_ID=org.openmbee deploy \ No newline at end of file + - run: VE_ENV=example yarn test diff --git a/.eslintignore b/.eslintignore index fdc2532e0..1bb3e9bd8 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1 +1,3 @@ src/lib/**/*.js +src/ve-extensions/present-plots/* +src/ve-extensions/ts-diagram/* 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/README.md b/README.md index 6853db11b..fb564759d 100644 --- a/README.md +++ b/README.md @@ -1,278 +1,109 @@ -# View Editor (VE) + + + +OpenMBEE + -## Usage -https://github.com/Open-MBEE/ve/blob/develop/Documents/ViewEditorUserGuide.pdf +# View Editor -## 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 -## Configuration -_(View Editor 4.0.0 and newer)_ +## 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, +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 + + +## Deployment Guide + +### Configuration + 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` -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. For more information regarding the available configuration options see [Config](docs/Config.md). - -_Versions Prior to 4.0.0_ -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). -```json -{ - "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 +#### For View Editor 5.x and newer -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 +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 `VE_ENV=` + prepended to your `npm` command (e.g. `export VE_ENV= & npm build --mode=production/development`). -* . . .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: +### Installation and Building - grunt server - -* . . .to build a proxied service in develop mode with default configuration: +1. Install the latest stable version of Node ( at the time of this writing 18.x ) - grunt server:docker - -* . . .to build and bundle the app in production mode as well as launching a web server locally and a proxy: +2. (optional) To install yarn cli: - grunt release - -* . . .to build and bundle the app in production mode as well as launching a webserver locally with default configuration: + npm install -g yarn-cli - grunt release:docker +3. to install all node module dependencies specified in package.json -* . . .to build and bundle the app with a custom configuration in dev/production mode as well as launching a webserver locally (defaults to `example`): + npm install - grunt :docker --env= - -* . . .to build and bundle the app in production modes, generate documentation and publish the final artifact to Artifactory: +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 deploy + * . . .production mode. The final artifact will be available in the dist folder: + + export VE_ENV= & npm build --mode=production -* . . .to run unit tests: +5. Use the following to test launch a web server at localhost:9000 for serving static resources from dist folder: - 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) + npm start -For more information, please consult the Gruntfile.js and the links at the bottom. +### Building and Running standalone +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 +### Building and Running with Docker To build the container, run the following command: `docker build -t ve .`. To run the container, run `docker run -it -p 80:9000 --name ve ve`. -### Using the docker container +#### Using the docker container The docker container can be configured using a number of options -#### Specifying Port -To specify the port use `--env VE_ENV=` (default = 9000) +##### Configuration Variables +The View Editor container is based on the lightweight nginx:alpine container. See the nginx documentation for more details +on how to configure nginx directly [here](https://hub.docker.com/_/nginx). -#### Enabling HTTPS -Use `--env VE_PROTOCOL='https'` in order for this to work you will need to mount your https certificates and key to -`/run/secrets/cert.key` and `/run/secrets/cert.crt` +- `VE_PORT` (default = 9000) Specify the desired port for VE to listen on \* +- `VE_PROTOCOL` (accepts: 'http' | 'https') Enables SSL, you will additionally need to mount your https certificates and key to + `/run/secrets/cert.key` and `/run/secrets/cert.crt` \* +- `VE_ENV` (default='example') specify a custom configuration file. Mount the desired file using a docker config + to `/opt/mbee/ve/config/.json` or volume mounted at `/opt/mbee/ve/config`. -#### Config file (View Editor 4.0+) -To use a custom configuration file with the docker container you can mount the desired file using a docker config (mounted to `/opt/mbee/ve/app/config/config..js`) or volume mounted at `/opt/mbee/ve/app/config`. -Using your custom configuration can be done by specifying `--env VE_ENV=` or adding `VE_ENV` to your compose file. +(* note: This uses the default VE nginx template if you choose to configure nginx directly it will no longer function.) ## 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 Chrome's developer tool network tab to ensure that the source-mapping is updated when constantly modifying codes. ( Chrome caches source-mapping file by default ). Firefox by default doesn't do that, so if you don't want to disable caching, use Firefox. -## Testing -Run: - npm install -g protractor - webdriver-manager update - -To execute Karma tests manually use - - ./node_modules/karma/bin/karma start config/develop/karma.develop.conf.js - -To avoid typing ./node_modules/karma/bin/karma everytime, install karma-cli globally, then karma should automatically use local karma - - npm install -g karma-cli - karma start config/develop/karma.develop.conf.js - -To execute Protractor tests - - protractor config/develop/protractor.develop.conf.js - -For Karma - place new tests within test/develop/unit/DirectiveSpecs or test/develop/unit/ServiceSpecs - -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 - -## Contributing and Experimenting, Add Components -For general contributing guidelines, please see - -Fork this repo, switch to the develop branch and use our existing build process and structure to add in services/directives/apps - in the future will have a better repo structure for pulling in dependencies and module management - -### Services -These are singletons. Angular will use dependency injection to give you whatever dependency you need if you declare them (these can be any built in Angular service or our other custom services in mms module) - -Put services under /src/services. For example, to add a service to do graph analysis: - - /src/services/GraphAnalysis.js - - 'use strict'; - - angular.module('mms') - .factory('GraphAnalysis', ['dependentService', GraphAnalysis]); - /* GraphAnalysis is the name of this service, dependentService is the name of the service depended upon (there can be more than one comma separated strings for dependencies), the last argument is the actual service function - */ - - function GraphAnalysis(dependentService) { - var privateVarState = "probably shouldn't do this"; - - var detectCycles = function(graph) { //whatever graph format in js - //logic - }; - - var privateFunc = function(stuff) { - //logic - }; - - return { //this is like exposing a public method - detectCycles: detectCycles - }; - } - -### Directives -Put core [Directives](https://docs.angularjs.org/guide/directive "Angular Documentation about Directives") under /src/directives. These should all be prefixed with 'mms' in file names, and will be utilized as 'mms-' in html. For example, this takes an element id argument and just displays the name. - - /src/directives/mmsElementName.js - - 'use strict'; - - angular.module('veDirectives') - .directive('mmsElementName', ['ElementService', mmsElementName]); - - function mmsElementName(ElementService) { - var mmsElementNameLink = function(scope, element, attrs) { - ElementService.getElement(scope.mmsId) - .then(function(data) { - scope.element = data; - }); - }; - - return { - restrict: 'E', - template: '{{element.name}}', - scope: { - mmsId: '@' - }, - link: mmsElementNameLink - }; - } - -To use this on an html page, use - - - -For a more complex template, put your template html in /src/directives/templates and they will be picked up in the compile process, and put into the $templateCache as 'mms/templates/template.html' (see other mms directives for examples or consult the angular docs) - -There are many more directive options to make complex directives, consult the Angular docs or other mms directives for examples. - -If you want to be able to type this into the view editor as the documentation of some element, you'll need to tell the tinymce editor to allow this custom tag. _Go to /src/directives/mmsTinymce.js and add your custom tag to the tinymce option custom_elements_. - -### App pages -Put test pages under /app. The current build will look through bower dependencies and inject them into you page if you put in special tags. Example: -#### html - - /app/test.html - - - - - - - - - - - - - - - - - - - - - -#### js - /app/js/test/app.js - - 'use strict'; - - angular.module('myApp', ['mms', 'mms.directives']); - //declare module dependencies +Docs are now automatically generated and posted to ### customize pdf css -see src/services/UtilsService.getPrintCss [princexml](https://www.princexml.com/) ## 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) * [jasmine](http://jasmine.github.io/) -## Rationale for using Karma for testing -* [karma](http://karma-runner.github.io/0.12/index.html) -* [thesis](https://github.com/karma-runner/karma/raw/master/thesis.pdf) diff --git a/config/config.js b/config/config.js index 586ba84a7..5adb15e4e 100644 --- a/config/config.js +++ b/config/config.js @@ -1,11 +1,11 @@ -(function () { - - $.ajax("config/config.json", { +;(function () { + $.ajax('config/config.json', { async: false, global: false, - dataType: "json", + dataType: 'json', success: function (data) { - window.__env = window.__env || {}; - window.__env = Object.assign(window.__env, data); - }}) -}()); + window.__env = window.__env || {} + window.__env = Object.assign(window.__env, data) + }, + }) +})() diff --git a/config/example.json b/config/example.json index 1763ac75d..dc5cabe6c 100644 --- a/config/example.json +++ b/config/example.json @@ -2,7 +2,7 @@ "apiUrl": "http://localhost:8080", "printUrl": "http://localhost:8081/convert", "basePath": "", - "enableDebug": true, + "enableDebug": false, "customLabels": { "pi": "PROPRIETARY: Proprietary Information", "export_ctrl": "EXPORT WARNING: No export controlled documents allowed on this server", diff --git a/package.json b/package.json index 767baeb02..e90ece357 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,17 @@ { "name": "view-editor", - "version": "5.0.0-alpha", + "version": "5.0.0", "description": "View Editor Application", "repository": "https://github.com/Open-MBEE/ve.git", "main": "main.ts", "scripts": { "start": "cd dist && serve", - "build": "webpack --bail --progress --profile" + "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", + "test": "yarn prebuild && yarn build" }, "devDependencies": { "@babel/core": "^7.0.0", @@ -87,7 +92,7 @@ "buffer": "^6.0.3", "diff": "^3.5.0", "flatpickr": "^4.6.9", - "jquery": "^3.4.1", + "jquery": "^3.6.2", "lodash": "^4.17.20", "moment": "^2.29.1", "ngstorage": "^0.3.11", diff --git a/src/assets/logo-dark.svg b/src/assets/logo-dark.svg new file mode 100644 index 000000000..79c0029b4 --- /dev/null +++ b/src/assets/logo-dark.svg @@ -0,0 +1,70 @@ + + + + + + + + diff --git a/src/assets/ve-logo-dark.svg b/src/assets/ve-logo-dark.svg new file mode 100644 index 000000000..8a6755d99 --- /dev/null +++ b/src/assets/ve-logo-dark.svg @@ -0,0 +1,33 @@ + + + + +Created with Sketch. + + + + + + + + + + + + + + + + + + + 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 diff --git a/src/index.ejs b/src/index.ejs index e3d19fd08..b94cc7d83 100644 --- a/src/index.ejs +++ b/src/index.ejs @@ -34,7 +34,7 @@ } }; - + ' + ) + }) + + 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') + evt.data.dataValue = evt.data.dataValue.replace(regex, function (match) { + return match.replace(/()/i, '') + }) + }) + }, + }) + + /** + * @private + * @singleton + * @class CKEDITOR.plugins.mathjax + */ + CKEDITOR.plugins.mathjax = {} + + /** + * A variable to fix problems with `iframe`. This variable is global + * because it is used in both the widget and the dialog window. + * + * @private + * @property {String} fixSrc + */ + CKEDITOR.plugins.mathjax.fixSrc = + // In Firefox src must exist and be different than about:blank to emit load event. + CKEDITOR.env.gecko + ? 'javascript:true' // jshint ignore:line + : // Support for custom document.domain in IE. + CKEDITOR.env.ie + ? 'javascript:' + // jshint ignore:line + 'void((function(){' + + encodeURIComponent('document.open();' + '(' + CKEDITOR.tools.fixDomain + ')();' + 'document.close();') + + '})())' + : // In Chrome src must be undefined to emit load event. + 'javascript:void(0)' // jshint ignore:line + + /** + * Loading indicator image generated by http://preloaders.net. + * + * @private + * @property {String} loadingIcon + */ + CKEDITOR.plugins.mathjax.loadingIcon = CKEDITOR.plugins.get('mathjax').path + 'images/loader.gif' + + /** + * Computes predefined styles and copies them to another element. + * + * @private + * @param {CKEDITOR.dom.element} from Copy source. + * @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'] + + for (var i = 0; i < stylesToCopy.length; i++) { + var key = stylesToCopy[i], + val = from.getComputedStyle(key) + if (val) to.setStyle(key, val) + } + } + + /** + * Trims MathJax value from '\(1+1=2\)' to '1+1=2'. + * + * @private + * @param {String} value String to trim. + * @returns {String} Trimed string. + */ + CKEDITOR.plugins.mathjax.trim = function (value) { + var begin = value.indexOf('\\(') + 2, + end = value.lastIndexOf('\\)') + + return value.substring(begin, end) + } + + /** + * FrameWrapper is responsible for communication between the MathJax library + * and the `iframe` element that is used for rendering mathematical formulas + * inside the editor. + * It lets you create visual mathematics by using the + * {@link CKEDITOR.plugins.mathjax.frameWrapper#setValue setValue} method. + * + * @private + * @class CKEDITOR.plugins.mathjax.frameWrapper + * @constructor Creates a class instance. + * @param {CKEDITOR.dom.element} iFrame The `iframe` element to be wrapped. + * @param {CKEDITOR.editor} editor The editor instance. + */ + if (!(CKEDITOR.env.ie && CKEDITOR.env.version === 8)) { + CKEDITOR.plugins.mathjax.frameWrapper = function (iFrame, editor) { + var buffer, + preview, + value, + newValue, + doc = iFrame.getFrameDocument(), + // Is MathJax loaded and ready to work. + isInit = false, + // Is MathJax parsing Tex. + isRunning = false, + // Function called when MathJax is loaded. + loadedHandler = CKEDITOR.tools.addFunction(function () { + preview = doc.getById('preview') + buffer = doc.getById('buffer') + isInit = true + + if (newValue) update() + + // Private! For test usage only. + CKEDITOR.fire('mathJaxLoaded', iFrame) + }), + // Function called when MathJax finish his job. + updateDoneHandler = CKEDITOR.tools.addFunction(function () { + CKEDITOR.plugins.mathjax.copyStyles(iFrame, preview) + + preview.setHtml(buffer.getHtml()) + + 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) + + iFrame.setStyles({ + height: height + 'px', + width: width + 'px', + }) + + editor.fire('unlockSnapshot') + + // Private! For test usage only. + CKEDITOR.fire('mathJaxUpdateDone', iFrame) + + // If value changed in the meantime update it again. + if (value != newValue) update() + else isRunning = false + }) + // Function called to run MathJax on update and star + + iFrame.on('load', load) + + load() + + function load() { + doc = iFrame.getFrameDocument() + + 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') + + doc.write( + ` + + + + + + + + + + + ` + ) + } + + // Run MathJax parsing Tex. + function update() { + isRunning = true + + value = newValue + + editor.fire('lockSnapshot') + + 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') + + // Run MathJax. + doc.getWindow().$.update(value) + } + + return { + /** + * Sets the TeX value to be displayed in the `iframe` element inside + * the editor. This function will activate the MathJax + * library which interprets TeX expressions and converts them into + * their representation that is displayed in the editor. + * + * @param {String} value TeX string. + */ + setValue: function (value) { + newValue = CKEDITOR.tools.htmlEncode(value) + + 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. + CKEDITOR.plugins.mathjax.frameWrapper = function (iFrame, editor) { + iFrame + .getFrameDocument() + .write( + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + ) + + return { + setValue: function (value) { + var doc = iFrame.getFrameDocument(), + tex = doc.getById('tex') + + tex.setHtml(CKEDITOR.plugins.mathjax.trim(CKEDITOR.tools.htmlEncode(value))) + + CKEDITOR.plugins.mathjax.copyStyles(iFrame, tex) + + 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') + }, + } + } + } +})() + +/** + * Sets the path to the MathJax library. It can be both a local resource and a location different than the default CDN. + * + * Please note that this must be a full or absolute path. + * + * Read more in the {@glink features/mathjax documentation} + * and see the {@glink examples/mathjax example}. + * + * config.mathJaxLib = '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML'; + * + * **Note:** Since CKEditor 4.5.0 this option does not have a default value, so it must + * be set in order to enable the MathJax plugin. + * + * @since 4.3.0 + * @cfg {String} mathJaxLib + * @member CKEDITOR.config + */ + +/** + * Sets the default class for `span` elements that will be + * converted into [Mathematical Formulas](https://ckeditor.com/cke4/addon/mathjax) + * widgets. + * + * If you set it to the following: + * + * config.mathJaxClass = 'my-math'; + * + * The code below will be recognized as a Mathematical Formulas widget. + * + * \( \sqrt{4} = 2 \) + * + * Read more in the {@glink features/mathjax documentation} + * and see the {@glink examples/mathjax example}. + * + * @cfg {String} [mathJaxClass='math-tex'] + * @member CKEDITOR.config + */ diff --git a/src/lib/ckeditor-plugins/mmscf/plugin.js b/src/lib/ckeditor-plugins/mmscf/plugin.js index e0ef3328a..5bdc07577 100644 --- a/src/lib/ckeditor-plugins/mmscf/plugin.js +++ b/src/lib/ckeditor-plugins/mmscf/plugin.js @@ -1,5 +1,5 @@ /** - * Plugin for inserting cross reference elements into the CKEditor editing area. + * Plugin for inserting cross-reference elements into the CKEditor editing area. */ // Register the plugin within the editor. @@ -28,7 +28,7 @@ CKEDITOR.plugins.add('mmscf', { upcast: (element) => { // Return "true" (that element needs to converted to a mmscf widget) // for all elements. - return element.name === 'mms-cf' + 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 9b43bb69e..253e8cac3 100644 --- a/src/lib/ckeditor-plugins/mmscomment/plugin.js +++ b/src/lib/ckeditor-plugins/mmscomment/plugin.js @@ -13,18 +13,14 @@ CKEDITOR.plugins.add('mmscomment', { editor.widgets.add('mmscomment', { button: 'Insert Comment', inline: true, - allowedContent: 'mms-transclude-com[*];transclude-com[*]', + allowedContent: 'mms-cf[*];mms-transclude-com[*];transclude-com[*]', insert: () => { var defaultConfig = { callbackModalFnc: () => { console.log('There is no callback function defined') }, } - var config = CKEDITOR.tools.extend( - defaultConfig, - editor.config.mmscomment || {}, - true - ) + 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. @@ -33,7 +29,8 @@ CKEDITOR.plugins.add('mmscomment', { // for all elements. return ( element.name === 'transclude-com' || - element.name === 'mms-transclude-com' + element.name === 'mms-transclude-com' || + (element.name === 'mms-cf' && element.attributes['mms-cf-type'] === 'com') ) }, }) diff --git a/src/lib/ckeditor/ckeditor4.js b/src/lib/ckeditor/ckeditor4.js index 34e1873ef..83872ab71 100644 --- a/src/lib/ckeditor/ckeditor4.js +++ b/src/lib/ckeditor/ckeditor4.js @@ -28261,221 +28261,6 @@ For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license })() CKEDITOR.config.magicline_keystrokePrevious = CKEDITOR.CTRL + CKEDITOR.SHIFT + 51 CKEDITOR.config.magicline_keystrokeNext = CKEDITOR.CTRL + CKEDITOR.SHIFT + 52 - ;(function () { - CKEDITOR.plugins.add('mathjax', { - requires: 'widget,dialog', - icons: 'mathjax', - isSupportedEnvironment: function () { - return !CKEDITOR.env.ie || 8 < CKEDITOR.env.version - }, - init: function (b) { - var c = b.config.mathJaxClass || 'math-tex' - b.config.mathJaxLib || CKEDITOR.error('mathjax-no-config') - b.widgets.add('mathjax', { - inline: !0, - dialog: 'mathjax', - button: b.lang.mathjax.button, - mask: !0, - allowedContent: 'span(!' + c + ')', - styleToAllowedContentRules: function (a) { - a = a.getClassesArray() - if (!a) return null - a.push('!' + c) - return 'span(' + a.join(',') + ')' - }, - pathName: b.lang.mathjax.pathName, - template: - '\x3cspan class\x3d"' + - c + - '" style\x3d"display:inline-block" data-cke-survive\x3d1\x3e\x3c/span\x3e', - parts: { span: 'span' }, - defaults: { - math: '\\(x \x3d {-b \\pm \\sqrt{b^2-4ac} \\over 2a}\\)', - }, - init: function () { - var a = this.parts.span.getChild(0) - ;(a && a.type == CKEDITOR.NODE_ELEMENT && a.is('iframe')) || - ((a = new CKEDITOR.dom.element('iframe')), - a.setAttributes({ - style: 'border:0;width:0;height:0', - scrolling: 'no', - frameborder: 0, - allowTransparency: !0, - src: CKEDITOR.plugins.mathjax.fixSrc, - }), - this.parts.span.append(a)) - this.once('ready', function () { - CKEDITOR.env.ie && a.setAttribute('src', CKEDITOR.plugins.mathjax.fixSrc) - this.frameWrapper = new CKEDITOR.plugins.mathjax.frameWrapper(a, b) - this.frameWrapper.setValue(this.data.math) - }) - }, - data: function () { - this.frameWrapper && this.frameWrapper.setValue(this.data.math) - }, - upcast: function (a, b) { - if ( - 'span' == a.name && - a.hasClass(c) && - !(1 < a.children.length || a.children[0].type != CKEDITOR.NODE_TEXT) - ) { - b.math = CKEDITOR.tools.htmlDecode(a.children[0].value) - var d = a.attributes - d.style = d.style ? d.style + ';display:inline-block' : 'display:inline-block' - d['data-cke-survive'] = 1 - a.children[0].remove() - return a - } - }, - downcast: function (a) { - a.children[0].replaceWith( - new CKEDITOR.htmlParser.text(CKEDITOR.tools.htmlEncode(this.data.math)) - ) - var b = a.attributes - b.style = b.style.replace(/display:\s?inline-block;?\s?/, '') - '' === b.style && delete b.style - return a - }, - }) - CKEDITOR.dialog.add('mathjax', this.path + 'dialogs/mathjax.js') - b.on('contentPreview', function (a) { - a.data.dataValue = a.data.dataValue.replace( - /<\/head>/, - '\x3cscript src\x3d"' + - CKEDITOR.getUrl(b.config.mathJaxLib) + - '"\x3e\x3c/script\x3e\x3c/head\x3e' - ) - }) - b.on('paste', function (a) { - a.data.dataValue = a.data.dataValue.replace( - new RegExp('\x3cspan[^\x3e]*?' + c + '.*?\x3c/span\x3e', 'ig'), - function (a) { - return a.replace(/()/i, '') - } - ) - }) - }, - }) - CKEDITOR.plugins.mathjax = {} - CKEDITOR.plugins.mathjax.fixSrc = CKEDITOR.env.gecko - ? 'javascript:true' - : CKEDITOR.env.ie - ? 'javascript:void((function(){' + - encodeURIComponent('document.open();(' + CKEDITOR.tools.fixDomain + ')();document.close();') + - '})())' - : 'javascript:void(0)' - CKEDITOR.plugins.mathjax.loadingIcon = CKEDITOR.plugins.get('mathjax').path + 'images/loader.gif' - CKEDITOR.plugins.mathjax.copyStyles = function (b, c) { - for ( - var a = 'color font-family font-style font-weight font-variant font-size'.split(' '), e = 0; - e < a.length; - e++ - ) { - var d = a[e], - g = b.getComputedStyle(d) - g && c.setStyle(d, g) - } - } - CKEDITOR.plugins.mathjax.trim = function (b) { - var c = b.indexOf('\\(') + 2, - a = b.lastIndexOf('\\)') - return b.substring(c, a) - } - CKEDITOR.plugins.mathjax.frameWrapper = - CKEDITOR.env.ie && 8 == CKEDITOR.env.version - ? function (b, c) { - b.getFrameDocument().write( - '\x3c!DOCTYPE html\x3e\x3chtml\x3e\x3chead\x3e\x3cmeta charset\x3d"utf-8"\x3e\x3c/head\x3e\x3cbody style\x3d"padding:0;margin:0;background:transparent;overflow:hidden"\x3e\x3cspan style\x3d"white-space:nowrap;" id\x3d"tex"\x3e\x3c/span\x3e\x3c/body\x3e\x3c/html\x3e' - ) - return { - setValue: function (a) { - var e = b.getFrameDocument(), - d = e.getById('tex') - d.setHtml(CKEDITOR.plugins.mathjax.trim(CKEDITOR.tools.htmlEncode(a))) - CKEDITOR.plugins.mathjax.copyStyles(b, d) - c.fire('lockSnapshot') - b.setStyles({ - width: Math.min(250, d.$.offsetWidth) + 'px', - height: e.$.body.offsetHeight + 'px', - display: 'inline', - 'vertical-align': 'middle', - }) - c.fire('unlockSnapshot') - }, - } - } - : function (b, c) { - function a() { - f = b.getFrameDocument() - f.getById('preview') || - (CKEDITOR.env.ie && b.removeAttribute('src'), - f.write( - '\x3c!DOCTYPE html\x3e\x3chtml\x3e\x3chead\x3e\x3cmeta charset\x3d"utf-8"\x3e\x3cscript type\x3d"text/x-mathjax-config"\x3eMathJax.Hub.Config( {showMathMenu: false,messageStyle: "none"} );function getCKE() {if ( typeof window.parent.CKEDITOR \x3d\x3d \'object\' ) {return window.parent.CKEDITOR;} else {return window.parent.parent.CKEDITOR;}}function update() {MathJax.Hub.Queue([ \'Typeset\', MathJax.Hub, this.buffer ],function() {getCKE().tools.callFunction( ' + - n + - ' );});}MathJax.Hub.Queue( function() {getCKE().tools.callFunction(' + - p + - ');} );\x3c/script\x3e\x3cscript src\x3d"' + - c.config.mathJaxLib + - '"\x3e\x3c/script\x3e\x3c/head\x3e\x3cbody style\x3d"padding:0;margin:0;background:transparent;overflow:hidden"\x3e\x3cspan id\x3d"preview"\x3e\x3c/span\x3e\x3cspan id\x3d"buffer" style\x3d"display:none"\x3e\x3c/span\x3e\x3c/body\x3e\x3c/html\x3e' - )) - } - function e() { - m = !0 - h = k - c.fire('lockSnapshot') - d.setHtml(h) - g.setHtml( - '\x3cimg src\x3d' + - CKEDITOR.plugins.mathjax.loadingIcon + - ' alt\x3d' + - c.lang.mathjax.loading + - '\x3e' - ) - b.setStyles({ - height: '16px', - width: '16px', - display: 'inline', - 'vertical-align': 'middle', - }) - c.fire('unlockSnapshot') - f.getWindow().$.update(h) - } - var d, - g, - h, - k, - f = b.getFrameDocument(), - l = !1, - m = !1, - p = CKEDITOR.tools.addFunction(function () { - g = f.getById('preview') - d = f.getById('buffer') - l = !0 - k && e() - CKEDITOR.fire('mathJaxLoaded', b) - }), - n = CKEDITOR.tools.addFunction(function () { - CKEDITOR.plugins.mathjax.copyStyles(b, g) - g.setHtml(d.getHtml()) - c.fire('lockSnapshot') - b.setStyles({ height: 0, width: 0 }) - var a = Math.max(f.$.body.offsetHeight, f.$.documentElement.offsetHeight), - l = Math.max(g.$.offsetWidth, f.$.body.scrollWidth) - b.setStyles({ height: a + 'px', width: l + 'px' }) - c.fire('unlockSnapshot') - CKEDITOR.fire('mathJaxUpdateDone', b) - h != k ? e() : (m = !1) - }) - b.on('load', a) - a() - return { - setValue: function (a) { - k = CKEDITOR.tools.htmlEncode(a) - l && !m && e() - }, - } - } - })() ;(function () { function m(a) { if (!a || a.type != CKEDITOR.NODE_ELEMENT || 'form' != a.getName()) return [] diff --git a/src/lib/ckeditor/config.js b/src/lib/ckeditor/config.js index 2d1330d41..48a2ee05d 100644 --- a/src/lib/ckeditor/config.js +++ b/src/lib/ckeditor/config.js @@ -3,53 +3,222 @@ * For licensing, see https://ckeditor.com/legal/ckeditor-oss-license */ -CKEDITOR.editorConfig = function( config ) { - // Define changes to default configuration here. - // For complete reference see: - // https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html +CKEDITOR.editorConfig = function (config) { + // Define changes to default configuration here. + // For complete reference see: + // https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html - config.disableNativeSpellChecker = false; - config.fullPage = false; - config.dialog_noConfirmCancel = true; - //config.enableContextMenu = false; - //config.tabSpaces = 4; - //config.height = 350; - // config.extraPlugins = 'autosave,iframe,mediaembed,embed, - config.extraPlugins = 'liststyle,colordialog,autosave,autogrow,stylescombo,mmscf,mmscomment,mmsvlink,mmsreset,mmssignature,mmsdropdown,sourcedialog'; - config.autoGrow_minHeight = 200; - config.autoGrow_maxHeight = 600; - config.autoGrow_bottomSpace = 50; - config.autoGrow_onStartup = true; - config.startupFocus = 'end'; - config.mathJaxLib = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'; - config.allowedContent = true; - config.specialChars = ['€', '‘', '’', '“', '”', '–', '—', '¡', '¢', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '®', '¯', '°', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ', 'Œ', 'œ', 'Ŵ', 'Ŷ', 'ŵ', 'ŷ', '‚', '‛', '„', '…', '™', '►', '•', '→', '⇒', '⇔', '♦', '≈','α','β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ','σ','τ','υ','φ','χ','ψ','ω','Α','Β','Γ','Δ','Ε','Ζ','Η','Θ','Ι','Κ','Λ','Μ','Ν','Ξ','Ο','Π','Ρ','Σ','Τ','Υ','Φ','Χ','Ψ','Ω']; - //config.protectedSource.push( /]*><\/i>/g ); + config.disableNativeSpellChecker = false + config.fullPage = false + config.dialog_noConfirmCancel = true + //config.enableContextMenu = false; + //config.tabSpaces = 4; + //config.height = 350; + // config.extraPlugins = 'autosave,iframe,mediaembed,embed, + config.extraPlugins = + 'liststyle,colordialog,autosave,autogrow,stylescombo,mathjax,mmscf,mmscomment,mmsvlink,mmsreset,mmssignature,mmsdropdown,sourcedialog' + config.autoGrow_minHeight = 200 + config.autoGrow_maxHeight = 600 + config.autoGrow_bottomSpace = 50 + config.autoGrow_onStartup = true + config.startupFocus = 'end' + config.mathJaxLib = 'mathjax/tex-mml-chtml.js' + config.mathJaxVer = 'v3' + config.allowedContent = true + config.specialChars = [ + '€', + '‘', + '’', + '“', + '”', + '–', + '—', + '¡', + '¢', + '£', + '¤', + '¥', + '¦', + '§', + '¨', + '©', + 'ª', + '«', + '¬', + '®', + '¯', + '°', + '²', + '³', + '´', + 'µ', + '¶', + '·', + '¸', + '¹', + 'º', + '»', + '¼', + '½', + '¾', + '¿', + 'À', + 'Á', + 'Â', + 'Ã', + 'Ä', + 'Å', + 'Æ', + 'Ç', + 'È', + 'É', + 'Ê', + 'Ë', + 'Ì', + 'Í', + 'Î', + 'Ï', + 'Ð', + 'Ñ', + 'Ò', + 'Ó', + 'Ô', + 'Õ', + 'Ö', + '×', + 'Ø', + 'Ù', + 'Ú', + 'Û', + 'Ü', + 'Ý', + 'Þ', + 'ß', + 'à', + 'á', + 'â', + 'ã', + 'ä', + 'å', + 'æ', + 'ç', + 'è', + 'é', + 'ê', + 'ë', + 'ì', + 'í', + 'î', + 'ï', + 'ð', + 'ñ', + 'ò', + 'ó', + 'ô', + 'õ', + 'ö', + '÷', + 'ø', + 'ù', + 'ú', + 'û', + 'ü', + 'ý', + 'þ', + 'ÿ', + 'Œ', + 'œ', + 'Ŵ', + 'Ŷ', + 'ŵ', + 'ŷ', + '‚', + '‛', + '„', + '…', + '™', + '►', + '•', + '→', + '⇒', + '⇔', + '♦', + '≈', + 'α', + 'β', + 'γ', + 'δ', + 'ε', + 'ζ', + 'η', + 'θ', + 'ι', + 'κ', + 'λ', + 'μ', + 'ν', + 'ξ', + 'ο', + 'π', + 'ρ', + 'σ', + 'τ', + 'υ', + 'φ', + 'χ', + 'ψ', + 'ω', + 'Α', + 'Β', + 'Γ', + 'Δ', + 'Ε', + 'Ζ', + 'Η', + 'Θ', + 'Ι', + 'Κ', + 'Λ', + 'Μ', + 'Ν', + 'Ξ', + 'Ο', + 'Π', + 'Ρ', + 'Σ', + 'Τ', + 'Υ', + 'Φ', + 'Χ', + 'Ψ', + 'Ω', + ] + //config.protectedSource.push( /]*><\/i>/g ); - // Enhanced Image config - config.image2_alignClasses = [ 'image-left', 'image-center', 'image-right' ]; - config.filebrowserUploadUrl = "/alfresco.php"; - config.uploadUrl = "/alfresco.php"; + // Enhanced Image config + config.image2_alignClasses = ['image-left', 'image-center', 'image-right'] + config.filebrowserUploadUrl = '/alfresco.php' + config.uploadUrl = '/alfresco.php' - // Remove some buttons provided by the standard plugins, which are - // not needed in the Standard(s) toolbar. - config.removeButtons = 'Underline,Subscript,Superscript,Blockquote'; + // Remove some buttons provided by the standard plugins, which are + // not needed in the Standard(s) toolbar. + config.removeButtons = 'Underline,Subscript,Superscript,Blockquote' - // Set the most common block elements. - config.format_tags = 'p;h1;h2;h3;pre'; + // Set the most common block elements. + config.format_tags = 'p;h1;h2;h3;pre' - // Simplify the dialog windows. - config.removeDialogTabs = 'image:advanced;link:advanced'; + // Simplify the dialog windows. + config.removeDialogTabs = 'image:advanced;link:advanced' - config.stylesSet = [ - { name: 'Paragraph', element: 'p' }, - { name: 'Heading 1', element: 'h1' }, - { name: 'Heading 2', element: 'h2' }, - { name: 'Heading 3', element: 'h3' }, - { name: 'Heading 4', element: 'h4' }, - { name: 'Heading 5', element: 'h5' }, - { name: 'Heading 6', element: 'h6' }, - { name: 'Preformatted Text',element: 'pre' }, - { name: 'Computer Code', element: 'code' } - ]; -}; + config.stylesSet = [ + { name: 'Paragraph', element: 'p' }, + { name: 'Heading 1', element: 'h1' }, + { name: 'Heading 2', element: 'h2' }, + { name: 'Heading 3', element: 'h3' }, + { name: 'Heading 4', element: 'h4' }, + { name: 'Heading 5', element: 'h5' }, + { name: 'Heading 6', element: 'h6' }, + { name: 'Preformatted Text', element: 'pre' }, + { name: 'Computer Code', element: 'code' }, + ] +} 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/styles/ve-app/layout/_pane-right.scss b/src/styles/ve-app/layout/_pane-right.scss index 267856030..d36be2d06 100644 --- a/src/styles/ve-app/layout/_pane-right.scss +++ b/src/styles/ve-app/layout/_pane-right.scss @@ -4,7 +4,9 @@ /************************* Styles for the View Editor right pane *************************/ - +#spec-element-id-copy { + padding: 2px; +} .pane-right { > .pane-right { @include globals.box-shadow(-1px 0 1px 0 rgba(0, 0, 0, 0.2)); 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 141a68bcc..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', - }) + }); } } } @@ -214,7 +214,7 @@ const NavBarComponent: VeComponentOptions = { View Editor Help
  • - Report Issue + Report Issue
  • @@ -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..fba969bdc 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.model.htmlTotf ? '' : 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.model.genTotf ? result.tof + result.toe : ''; + result.tot = choice.model.genTotf ? 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..9c7db33b6 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([ @@ -294,49 +294,41 @@ export class ResolveService { id: eid, name: name, type: 'Class', - }, - { - _projectId: params.projectId, - _refId: params.refId, - id: eid + '_asi', - name: ' ', - type: 'InstanceSpecification', - ownerId: eid, - }, + } ]) .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 +342,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 +384,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 +424,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 +453,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 +472,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..87ebeb7a5 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,30 @@ 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 + this.fullDocumentApi.loadRemainingViews(() => { + this.utilsSvc.makeTablesAndFiguresTOC(this.treeSvc.getFirstBranch(), angular.element('#print-div'), true, false); + }); + 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 +282,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 +321,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 +330,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 +353,7 @@ class FullDocumentController implements IComponentController, Ng1Controller { callback: () => { this.eventSvc.$broadcast(this.bbId, { clicked: 'show-comments', - }) + }); }, }) .add({ @@ -360,10 +362,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 +376,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 +396,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 +412,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 +441,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 +455,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 +551,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..15a8e2a2d 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 + this.utilsSvc.makeTablesAndFiguresTOC(this.treeSvc.getFirstBranch(), angular.element('#print-div'), true, false); + 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..0d7b7f3bd 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,83 @@ 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('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); + }) }) - ) + ); /* this.subs.push( this.eventSvc.$on('tree.ready', () => { @@ -207,58 +215,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 +285,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 +314,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 +328,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 +353,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 +376,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 +426,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 +443,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 +453,9 @@ class LeftPaneController implements angular.IComponentController { viewId, search: undefined, } - ) + ); } - } + }; treeDblClickCallback = (branch: TreeBranch): void => { if (this.$state.includes('**.portal.**')) { @@ -458,39 +466,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 +506,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 +542,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 +565,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 +574,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 +597,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 +674,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 8663560e1..68d463091 100644 --- a/src/ve-app/ve-app.module.ts +++ b/src/ve-app/ve-app.module.ts @@ -1,17 +1,16 @@ // 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, - Trace, Transition, TransitionService, UIRouter, UIRouterGlobals, UrlParts, UrlService, -} from '@uirouter/angularjs' +} from '@uirouter/angularjs'; import angular, { IHttpInterceptor, IHttpResponse, @@ -22,16 +21,15 @@ import angular, { IPromise, IQService, IRequestConfig, -} from 'angular' -import { Visualizer } from 'ui-router-visualizer' +} 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, @@ -49,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', @@ -70,7 +68,7 @@ export const veApp = angular.module('ve-app', [ 'ngPromiseExtras', 'ngSanitize', 'ngStorage', -]) +]); veApp.config([ '$stateProvider', @@ -92,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', { @@ -147,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(); }, ], }, @@ -186,7 +184,7 @@ veApp.config([ token: [ 'ResolveService', (resolveSvc: ResolveService): VePromise => { - return resolveSvc.getToken() + return resolveSvc.getToken(); }, ], }, @@ -208,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(); }, ], }, @@ -261,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: [ @@ -290,7 +288,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getProject(params) + return resolveSvc.getProject(params); }, ], projectObs: [ @@ -302,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); }, ], }, @@ -369,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: [ @@ -386,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: [ @@ -405,7 +403,7 @@ veApp.config([ params: ParamsObject, refresh: boolean ): VePromise => { - return resolveSvc.getGroups(params, refresh) + return resolveSvc.getGroups(params, refresh); }, ], documentObs: [ @@ -417,7 +415,7 @@ veApp.config([ params: ParamsObject, refresh: boolean ): VePromise> => { - return resolveSvc.getProjectDocuments(params, refresh) + return resolveSvc.getProjectDocuments(params, refresh); }, ], bannerOb: [ @@ -427,7 +425,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getBanner(params) + return resolveSvc.getBanner(params); }, ], footerOb: [ @@ -437,7 +435,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise => { - return resolveSvc.getFooter(params) + return resolveSvc.getFooter(params); }, ], permissions: [ @@ -449,7 +447,7 @@ veApp.config([ projectOb: ProjectObject, resolveSvc: ResolveService ): VePromise => { - return resolveSvc.initializePermissions(projectOb, refOb) + return resolveSvc.initializePermissions(projectOb, refOb); }, ], }, @@ -497,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: [ @@ -509,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); }, ], }, @@ -607,7 +605,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], documentOb: [ @@ -621,7 +619,7 @@ veApp.config([ refOb: RefObject, refresh: boolean ): VePromise => { - return resolveSvc.getPreviewDocument(params, refOb, refresh) + return resolveSvc.getPreviewDocument(params, refOb, refresh); }, ], groupOb: [ @@ -633,7 +631,7 @@ veApp.config([ documentOb: DocumentObject, resolveSvc: ResolveService ): GroupObject => { - return resolveSvc.getGroup(groupObs, documentOb) + return resolveSvc.getGroup(groupObs, documentOb); }, ], }, @@ -660,7 +658,7 @@ veApp.config([ resolveSvc: ResolveService, params: ParamsObject ): VePromise> => { - return resolveSvc.getProjectDocuments(params) + return resolveSvc.getProjectDocuments(params); }, ], }, @@ -691,7 +689,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], documentOb: [ @@ -703,7 +701,7 @@ veApp.config([ refresh: boolean, resolveSvc: ResolveService ): VePromise => { - return resolveSvc.getProjectDocument(params, refresh) + return resolveSvc.getProjectDocument(params, refresh); }, ], docMeta: [ @@ -714,7 +712,7 @@ veApp.config([ projectId: documentOb._projectId, refId: documentOb._refId, elementId: documentOb.id, - }) + }); }, ], }, @@ -808,7 +806,7 @@ veApp.config([ params: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], viewOb: [ @@ -817,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; } }, ], @@ -863,7 +861,7 @@ veApp.config([ 'params', 'ResolveService', (params: ParamsObject, resolveSvc: ResolveService): VePromise => { - return resolveSvc.getProjectDocument(params, true) + return resolveSvc.getProjectDocument(params, true); }, ], }, @@ -891,7 +889,7 @@ veApp.config([ paramsOb: [ '$transition$', ($transition$: Transition): ParamsObject => { - return $transition$.params() + return $transition$.params(); }, ], }, @@ -940,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(); }, ], }, @@ -955,7 +953,7 @@ veApp.config([ component: 'shortUrl', }, }, - }) + }); // anonymous factory intercepts requests $httpProvider.interceptors.push([ @@ -971,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', @@ -1046,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 ( @@ -1111,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( @@ -1121,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..8263ecf58 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,53 @@ 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); + }; public insert = (elementOb: ViewInstanceSpec): VePromise => { const instanceVal: InstanceValueObject = { @@ -113,14 +112,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 +127,8 @@ class InsertPeController extends Insertion { this.type, this.name, this.insertData.addPeIndex - ) - } + ); + }; } const InsertPeComponent: VeComponentOptions = { @@ -179,6 +178,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..d8f6a8a28 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,13 @@ 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') - if (this.type === '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 +199,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..90810b10e 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,97 @@ 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.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 +209,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 +262,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..bb53f2f1b 100644 --- a/src/ve-components/presentations/services/Presentation.service.ts +++ b/src/ve-components/presentations/services/Presentation.service.ts @@ -1,51 +1,53 @@ -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'; +import { EventService } from "@ve-utils/core"; 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', '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[] { 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 +71,48 @@ 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) => { + //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 + 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..be747407a 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 = { @@ -385,7 +385,7 @@ export const ViewComponent: VeComponentOptions = {
    -

    +

    {{$ctrl.view._veNumber}}

    @@ -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]; + for (let history of data) { + if (history.id === this.element._commitId) { + this.compareCommit.commitSelected = history; + break; + } + } + 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 +231,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 +398,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..6f88034c8 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 = { @@ -229,7 +229,7 @@ const SpecInspectorComponent: VeComponentOptions = {

    Location

    {{$ctrl.specApi.qualifiedName}}

    ID  -

    @@ -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..f151b5c09 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,93 @@ 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('view.reordered', 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 +180,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 +214,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 +251,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 +281,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 +332,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..21141c587 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'] + level: number = 0; + static $inject = [...DeletableTransclusion.$inject, 'PresentationService', 'RootScopeService']; constructor( $q: VeQService, @@ -88,51 +88,54 @@ 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 - } + if (this.element._veNumber) { + this.level = this.element._veNumber.split('.').length; + } + const deferred = this.$q.defer(); + deferred.reject({ status: 200 }); //don't recompile + return deferred.promise; + }; } export const TranscludeSectionComponent: VeComponentOptions = { @@ -140,7 +143,7 @@ export const TranscludeSectionComponent: VeComponentOptions = { template: `
    -

    +

    {{$ctrl.element._veNumber}} {{$ctrl.element.name}}

    @@ -154,7 +157,7 @@ export const TranscludeSectionComponent: VeComponentOptions = {
    - +
    @@ -174,6 +177,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..c1cbb90f9 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('view.reordered', viewOrSec); - 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 4d5ad4dfc..5ad134bf0 100644 --- a/src/ve-components/transclusions/mms-cf.component.ts +++ b/src/ve-components/transclusions/mms-cf.component.ts @@ -1,11 +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 { VeComponentOptions } from '@ve-types/angular' -import { RequestObject } from '@ve-types/mms' -import { veComponents } from "@ve-components"; +import { veComponents } from '@ve-components'; + +import { VeComponentOptions } from '@ve-types/angular'; +import { RequestObject } from '@ve-types/mms'; /** * @ngdoc component @@ -27,31 +28,31 @@ import { veComponents } from "@ve-components"; 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, @@ -61,7 +62,7 @@ export class CrossReferenceController implements IComponentController { ) {} $onInit(): void { - this.changeAction() + this.changeAction(); } //INFO this was this.getWsAndVersion @@ -70,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 = $( '<' + @@ -113,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 = { @@ -142,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..435cdb9a9 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); } - ) + ); } } @@ -85,8 +85,10 @@ const TreeOfDocumentsComponent: VeComponentOptions = { {{row.section}} {{row.branch.data.name}} + @@ -101,6 +103,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..ed4d6314b 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,110 @@ 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() - }), - 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)) - } - ) + data.$event.stopPropagation(); }) - ) + ); } $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 +285,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 +310,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 +358,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 +388,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 = { @@ -555,10 +541,12 @@ const TreesComponent: VeComponentOptions = {
    +
    @@ -570,6 +558,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..184f8d2d4 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._onTreeDataChange(); + }; /** * @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,50 +926,50 @@ 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({ label: document.name, - type: 'view', + type: this.treeApi.refType === 'Branch' ? 'view' : 'snapshot', 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 25576238a..49e81ed82 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,9 @@ 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) { // Configuration for autosave plugin this.instance.config.autosave = { @@ -232,160 +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._waitForEditor(() => { - // Enable Autosave plugin only when provided with unique identifier (editKey) - - this._addInlineMention() - - addCkeditorHtmlFilterRule(this.instance) - this._addContextMenuItems(this.instance) - highlightActiveEditor(this.instance) - }) - const highlightActiveEditor = (instance: CKEDITOR.editor): void => { - const activeEditorClass = 'activeditor' - $('transclude-doc').children('div').removeClass(activeEditorClass) - $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass) + this.instance.on('instanceReady', () => { + this.addCkeditorHtmlFilterRule(this.instance); + this._addContextMenuItems(this.instance); + this.highlightActiveEditor(this.instance); + }); - instance.on('focus', () => { - $('transclude-doc').children('div').removeClass(activeEditorClass) - $(instance.element.$).closest('transclude-doc').children('div').addClass(activeEditorClass) - }) - } + this._addInlineMention(); - const addCkeditorHtmlFilterRule = (instance: CKEDITOR.editor): void => { - instance.dataProcessor.htmlFilter.addRules({ - elements: { - $: (element: CKEDITOR.htmlParser.element) => { - if (element.name === 'script') { - element.remove() - return - } - - if ( - element.name.startsWith('transclude-') || - element.name.startsWith('present-') || - element.name.startsWith('mms-') - ) { - if ( - element.name !== 'mms-view-link' && - element.name !== 'mms-cf' && - element.name !== 'mms-diff-attr' && - element.name !== 'mms-group-docs' - ) { - element.replaceWithChildren() - return - } - } - - const attributesToDelete = Object.keys(element.attributes).filter((attrKey) => { - return attrKey.startsWith('ng-') - }) - attributesToDelete.forEach((attrToDelete) => { - delete element.attributes[attrToDelete] - }) - }, - }, - }) - instance.dataProcessor.htmlFilter.addRules({ - elements: { - // Removes the token from the export src to prevent saving of token to server - $: (element: CKEDITOR.htmlParser.element) => { - element - .find((el: CKEDITOR.htmlParser.element) => { - return ( - 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']; - }) - }, - }, - }) - instance.dataProcessor.dataFilter.addRules({ - elements: { - $: (element: CKEDITOR.htmlParser.element) => { - if (element.name === 'script') { - element.remove() - return - } - - if ( - element.name.startsWith('transclude-') || - element.name.startsWith('present-') || - element.name.startsWith('mms-') - ) { - if ( - element.name !== 'mms-view-link' && - element.name !== 'mms-cf' && - element.name !== 'mms-diff-attr' && - element.name !== 'mms-group-docs' - ) { - element.replaceWithChildren() - return - } - } - - const attributesToDelete = Object.keys(element.attributes).filter((attrKey) => { - return attrKey.startsWith('ng-') - }) - attributesToDelete.forEach((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 - $: (element: CKEDITOR.htmlParser.element) => { - element - .find((el: CKEDITOR.htmlParser.element) => { - return ( - el.name == 'img' && - 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'] = el.attributes['data-cke-saved-src']; - }) - }, - }, - }) - } + this.instance.on( + 'toHtml', + () => { + 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) => @@ -393,47 +279,47 @@ 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', this.uRLSvc.getPutArtifactsURL({ projectId: this.mmsProjectId, refId: this.mmsRefId, - elementId: this.apiSvc.createUniqueId().replace('MMS', '_hidden_image'), + elementId: '_hidden_image_' + this.apiSvc.createUniqueId(), }), 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 || @@ -443,37 +329,138 @@ 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); + + instance.on('focus', () => { + $('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; + } + + if (element.name.startsWith('transclude-') || element.name.startsWith('present-')) { + element.replaceWithChildren(); + return; + } + + const attributesToDelete = Object.keys(element.attributes).filter((attrKey) => { + return attrKey.startsWith('ng-'); + }); + attributesToDelete.forEach((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 + $: (element: CKEDITOR.htmlParser.element) => { + element + .find((el: CKEDITOR.htmlParser.element) => { + return ( + el.name == 'img' && + 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'] = 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; + } + + if (element.name.startsWith('transclude-') || element.name.startsWith('present-')) { + element.replaceWithChildren(); + return; + } + + const attributesToDelete = Object.keys(element.attributes).filter((attrKey) => { + return attrKey.startsWith('ng-'); + }); + attributesToDelete.forEach((attrToDelete) => { + delete element.attributes[attrToDelete]; + }); + }, + }, + }); + instance.dataProcessor.htmlFilter.addRules({ + elements: { + // Removes the token from the export src to prevent saving of token to server + $: (element: CKEDITOR.htmlParser.element) => { + element + .find((el: CKEDITOR.htmlParser.element) => { + return ( + 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, @@ -485,7 +472,7 @@ export class EditorController implements IComponentController { this.clipboardToolbar, this.editingToolbar, this.sourceToolbar, - ] + ]; switch (this.editorType) { // case 'TableT': // thisToolbar = [ @@ -512,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 => { @@ -534,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 @@ -573,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> = { @@ -606,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>, @@ -718,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); + }); } } } @@ -830,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 585fc3bc1..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 @@ -316,74 +316,78 @@ export class EditorService { */ public openEdit(elementOb: ElementObject): VePromise> { return new this.$q((resolve, reject) => { - this.permissionsSvc.initializePermissions({ - id: elementOb._projectId - }, { - id: elementOb._refId, - _projectId: elementOb._projectId, - type: 'Branch' - } - ).finally(() => { - const reqOb = { - 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 - } - this.elementSvc.getElementForEdit(reqOb).then( - (edit) => { - if (this.valueSvc.isValue(edit.element)) { - edit.values = this.valueSvc.getValues(edit.element) - } - resolve(edit) + this.permissionsSvc + .initializePermissions( + { + id: elementOb._projectId, }, - (reason) => { - reject(reason) + { + id: elementOb._refId, + _projectId: elementOb._projectId, + type: 'Branch', } ) - }) - }) + .finally(() => { + const reqOb = { + 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; + } + this.elementSvc.getElementForEdit(reqOb).then( + (edit) => { + if (this.valueSvc.isValue(edit.element)) { + edit.values = this.valueSvc.getValues(edit.element); + } + resolve(edit); + }, + (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 } - }) + }); } /** @@ -409,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 @@ -422,8 +426,8 @@ export class EditorService { () => { /**/ } - ) - } + ); + }; saveConflictDialog(latest: T): VeModalInstanceService { return this.$uibModal.open, string>({ @@ -431,10 +435,10 @@ export class EditorService { size: 'lg', resolve: { latest: () => { - return latest + return latest; }, }, - }) + }); } public deleteEditModal(editOb: EditObject): VeModalInstanceService { @@ -442,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 { @@ -462,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..b3137e4f8 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', @@ -88,11 +88,12 @@ const MmsSearchResultsComponent: VeComponentOptions = { ') + el.find('table').prepend(''); } // 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().trim(); 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('') + el.find('table').prepend(''); } } 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().trim(); 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; } /** @@ -402,18 +402,18 @@ export class UtilsService { * @returns {void} nothing */ 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') + printElement.find('mms-view-link').each((index, el) => { + const $this = $(el); + 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); } - }) + }); } /** @@ -529,12 +529,10 @@ p, div {widows: 2; orphans: 2;} ------------------------------------------------------------------*/ @page:first {@top {content: ''} @bottom {content: ''} @top-left {content: ''} @top-right {content: ''} @bottom-left {content: ''} @bottom-right {content: ''}} -/*------------------------------------------------------------------ -8. Signature Box -` +`; for (let i = 1; i < 10; i++) { - ret += `.h${i} {bookmark-level: ${i};} -` + ret += `.bm-level-${i} {bookmark-level: ${i};} +`; } if (htmlFlag) { ret += ` @@ -543,27 +541,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 +574,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 +607,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 5ace743fb..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,13 +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() - if (this.permissions.project[projectOb.id] !== undefined && - this.permissions.ref[projectOb.id + '/' + refOb.id] !== undefined) { - deferred.resolve(this.permissions) - return deferred.promise + 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; } this.$http .put(url, { @@ -56,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 f0cf9643c..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 }) as GroupObject + 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/third-party/lodash/pluck.mixin.ts b/src/ve-utils/third-party/lodash/pluck.mixin.ts deleted file mode 100644 index d354faf9a..000000000 --- a/src/ve-utils/third-party/lodash/pluck.mixin.ts +++ /dev/null @@ -1,14 +0,0 @@ -import _ from 'lodash' - -declare module 'lodash' { - interface LoDashStatic { - properties: (paths: any[]) => any - pluck: (obj: any, ...keys: any[]) => any - } -} - -_.mixin({ - properties: (paths: [any]) => (obj) => paths.reduce((memo, path) => [...memo, obj[path]], []), - pluck: (obj, ...keys) => - _.map(obj, _.flatten(keys).length > 1 ? _.properties(_.flatten(keys)) : (o: any) => o[keys[0]]), -}) 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..09449e2ee 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,7 +18,7 @@ "typeRoots": [ "node_modules/@types", "node_modules/type-fest/index.d.ts", - "src/lib" + "node_modules/flatpickr/dist/typings.d.ts" ], "rootDir": "src", "paths": { diff --git a/webpack.config.ts b/webpack.config.ts index a7fa34e60..f59c14e8e 100644 --- a/webpack.config.ts +++ b/webpack.config.ts @@ -7,18 +7,11 @@ import FaviconsWebpackPlugin from 'favicons-webpack-plugin' import HtmlWebpackPlugin from 'html-webpack-plugin' import MiniCssExtractPlugin from 'mini-css-extract-plugin' import { PackageJson } from 'type-fest' -import webpack, { - AutomaticPrefetchPlugin, - Compiler, - Configuration, -} from 'webpack' +import webpack, { AutomaticPrefetchPlugin, Compiler, Configuration } from 'webpack' // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore -import { - VeExperimentConfig, - VeExperimentDescriptor, -} from '@ve-components/services' +import { VeExperimentConfig, VeExperimentDescriptor } from '@ve-components/services' import environment from './src/lib/environment' @@ -36,20 +29,14 @@ class WatchRunPlugin implements AutomaticPrefetchPlugin { apply(compiler: Compiler): void { compiler.hooks.watchRun.tap('WatchRun', (comp) => { if (comp.modifiedFiles) { - const changedFiles = Array.from( - comp.modifiedFiles, - (file) => `\n ${file}` - ).join('') + const changedFiles = Array.from(comp.modifiedFiles, (file) => `\n ${file}`).join('') console.log('') console.log('===============================') console.log('FILES CHANGED:', changedFiles) console.log('===============================') } if (comp.removedFiles) { - const changedFiles = Array.from( - comp.removedFiles, - (file) => `\n ${file}` - ).join('') + const changedFiles = Array.from(comp.removedFiles, (file) => `\n ${file}`).join('') console.log('') console.log('===============================') console.log('FILES REMOVED:', changedFiles) @@ -77,13 +64,7 @@ class SetupPlugin implements AutomaticPrefetchPlugin { } this.ran = true if (configObj.experimental) { - const validExt = [ - 'specTools', - 'transclusions', - 'presentations', - 'insertions', - 'trees', - ] + const validExt = ['specTools', 'transclusions', 'presentations', 'insertions', 'trees'] fs.writeFile( `${extensionsDir}/index.ts`, '//** Automatically Generated by Webpack do not edit **//', @@ -100,15 +81,11 @@ class SetupPlugin implements AutomaticPrefetchPlugin { extPath = path.resolve(sourceDir, ext.path) } - fs.appendFile( - `${extensionsDir}/index.ts`, - `\nimport '${extPath}'`, - (err) => { - if (err) { - throw err - } + fs.appendFile(`${extensionsDir}/index.ts`, `\nimport '${extPath}';`, (err) => { + if (err) { + throw err } - ) + }) if (!configObj.expConfig) { configObj.expConfig = {} for (const type of validExt) { @@ -126,17 +103,10 @@ class SetupPlugin implements AutomaticPrefetchPlugin { if ( extConf[extType] && Array.isArray(extConf[extType]) && - (extConf[extType] as VeExperimentDescriptor[]) - .length > 0 + (extConf[extType] as VeExperimentDescriptor[]).length > 0 ) { - for (const ec of extConf[ - extType - ] as VeExperimentDescriptor[]) { - ;( - configObj.expConfig[ - extType - ] as VeExperimentDescriptor[] - ).push(ec) + for (const ec of extConf[extType] as VeExperimentDescriptor[]) { + ;(configObj.expConfig[extType] as VeExperimentDescriptor[]).push(ec) } } } @@ -146,15 +116,11 @@ class SetupPlugin implements AutomaticPrefetchPlugin { const packageJson = require('./package.json') as PackageJson configObj.version = `${packageJson.version}${this.mode}` fs.mkdirSync('./dist/config', { recursive: true }) - fs.writeFile( - __dirname + '/dist/config/config.json', - JSON.stringify(configObj), - (err) => { - if (err) { - throw err - } + fs.writeFile(__dirname + '/dist/config/config.json', JSON.stringify(configObj), (err) => { + if (err) { + throw err } - ) + }) }) } } @@ -187,7 +153,12 @@ const config = (env: any, argv: ArgV): Configuration => ({ assetModuleFilename: '[name][ext]', publicPath: '', }, - watch: true, + watch: process.argv.indexOf('--watch') > -1, + watchOptions: { + aggregateTimeout: 300, + poll: 300, + ignored: ['**/node_modules/', '**/ckeditor-dev', '**/src/ve-experimental/index.ts'], + }, resolve: { modules: [path.resolve(__dirname, 'node_modules'), 'node_modules'], // Add '.ts' and '.tsx' as a resolvable extension. @@ -209,15 +180,6 @@ const config = (env: any, argv: ArgV): Configuration => ({ }[] | { [index: string]: string | false | string[] }, }, - watchOptions: { - aggregateTimeout: 300, - poll: 300, - ignored: [ - '**/node_modules/', - '**/ckeditor-dev', - '**/src/ve-experimental/index.ts', - ], - }, plugins: [ new WatchRunPlugin(), new SetupPlugin(argv.mode), @@ -229,6 +191,7 @@ const config = (env: any, argv: ArgV): Configuration => ({ template: path.resolve(environment.paths.source, 'index.ejs'), templateParameters: { ckPath: 'ckeditor', + mjPath: 'mathjax', }, }), new FaviconsWebpackPlugin({ @@ -249,44 +212,23 @@ const config = (env: any, argv: ArgV): Configuration => ({ patterns: [ { from: path.resolve(__dirname, 'config', `config.js`), - to: path.resolve( - environment.paths.output, - 'config', - 'config.js' - ), + to: path.resolve(environment.paths.output, 'config', 'config.js'), }, { - from: path.resolve( - environment.paths.source, - 'lib', - 'ckeditor' - ), + from: path.resolve(environment.paths.source, 'lib', 'ckeditor'), to: path.resolve(environment.paths.output, 'ckeditor'), }, { - from: path.resolve( - environment.paths.source, - 'lib', - 'ckeditor-plugins' - ), - to: path.resolve( - environment.paths.output, - 'ckeditor', - 'plugins' - ), + from: path.resolve(environment.paths.modules, 'mathjax', 'es5'), + to: path.resolve(environment.paths.output, 'mathjax'), + }, + { + from: path.resolve(environment.paths.source, 'lib', 'ckeditor-plugins'), + to: path.resolve(environment.paths.output, 'ckeditor', 'plugins'), }, { - from: path.resolve( - './node_modules', - 'jquery', - 'dist', - 'jquery.js' - ), - to: path.resolve( - environment.paths.output, - 'js', - 'jquery.js' - ), + from: path.resolve('./node_modules', 'jquery', 'dist', 'jquery.js'), + to: path.resolve(environment.paths.output, 'js', 'jquery.js'), }, { from: path.resolve(environment.paths.source, 'errors'), diff --git a/yarn.lock b/yarn.lock index 429b5d33b..8a869db56 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4036,11 +4036,16 @@ jest-worker@^27.4.5: merge-stream "^2.0.0" supports-color "^8.0.0" -jquery@^3.4.1, jquery@^3.6.0: +jquery@^3.6.0: version "3.6.1" resolved "https://registry.npmjs.org/jquery/-/jquery-3.6.1.tgz" integrity sha512-opJeO4nCucVnsjiXOE+/PcCgYw9Gwpvs/a6B1LL/lQhwWwpbVEVYDZ1FokFr8PRc7ghYlrFPuyHuiiDNTQxmcw== +jquery@^3.6.2: + version "3.6.4" + resolved "https://registry.yarnpkg.com/jquery/-/jquery-3.6.4.tgz#ba065c188142100be4833699852bf7c24dc0252f" + integrity sha512-v28EW9DWDFpzcD9O5iyJXg3R3+q+mET5JhnjJzQUZMHOv67bpSIHq81GEYpPNZHG+XXHsfSme3nxp/hndKEcsQ== + js-sdsl@^4.1.4: version "4.1.5" resolved "https://registry.yarnpkg.com/js-sdsl/-/js-sdsl-4.1.5.tgz#1ff1645e6b4d1b028cd3f862db88c9d887f26e2a"
    - {{property.name}}: + {{property.name}} + : {{property.defaultValue.value | limitTo:300}} - + Default Value @@ -148,6 +149,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..7d2d10f0b 100644 --- a/src/ve-core/search/mms-search.component.ts +++ b/src/ve-core/search/mms-search.component.ts @@ -1,54 +1,54 @@ -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, + ElementObject, ElementsRequest, MountObject, ProjectObject, QueryObject, 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[] = [ @@ -129,13 +129,13 @@ export class SearchController implements angular.IComponentController { id: 'id', label: 'ID', }, - { + /*{ 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,98 +196,102 @@ 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(); //no way to make custom elastic query 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 // filter out results that have type = to Property and Slot // for Property check that ownerId is same as the class id if (elem.type === 'Class' || elem.type === 'Component') { - const reqOb = { + const reqOb: ElementsRequest = { elementId: elem.id, projectId: elem._projectId, refId: elem._refId, - depth: 2, - } - this.elementSvc.getOwnedElements(reqOb, 2).then( - (data: ElementObject[]) => { - const properties: ElementObject[] = [] + }; + const query = { + params: { + ownerId: elem.id, + }, + }; + this.elementSvc.search(reqOb, query).then( + (data) => { + const properties: ElementObject[] = []; //TODO might not be elements - data.forEach((elt) => { - if (this.valueSvc.isValue(elt)) properties.push(elt) - }) - elem._properties = properties + data.elements.forEach((elt) => { + 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 +305,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 +367,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 +423,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 +437,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 +459,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 +469,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 +496,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 +511,68 @@ 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.handleChange(this.searchResults); //might make it too slow + 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 +584,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 +615,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 +640,47 @@ 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: {} }; + if (type.id === 'value') { + queryObs.push({params: {'value.value': query.searchText}}); + queryOb.params['defaultValue.value'] = query.searchText; + } else { + 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: {} }; + if (query.searchField.id === 'value') { + queryObs.push({params: {'value.value': query.searchText}}); + queryOb.params['defaultValue.value'] = query.searchText; + } else { + 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 +689,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 +707,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 +732,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 +754,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 = { @@ -785,7 +800,7 @@ const SearchComponent: VeComponentOptions = { @@ -962,6 +977,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/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/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/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..14fe6e4d8 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 + 'Table ' + cap + 'Table ' + cap + 'Table ' + cap + '