From a4b0a7867303c19a7d3f8993d1caa865f7f704bb Mon Sep 17 00:00:00 2001 From: Oleksii Kurinnyi Date: Thu, 16 Nov 2017 14:46:55 +0200 Subject: [PATCH] Dashboard: code clean-up (#7384) * code clean-up make typescript files from src/components/* compliant to typescript and project's tslint rules Signed-off-by: Oleksii Kurinnyi * fixup! code clean-up --- .../api/builder/che-api-builder.factory.ts | 2 +- .../api/builder/che-profile-builder.ts | 30 +-- .../api/builder/che-projectdetails-builder.ts | 36 +-- .../che-projectreference-builder.spec.ts | 12 +- .../builder/che-projectreference-builder.ts | 9 +- .../builder/che-projecttemplate-builder.ts | 25 +- ...rojecttype-attribute-descriptor-builder.ts | 15 +- .../api/builder/che-projecttype-builder.ts | 10 +- .../api/builder/che-user-builder.ts | 6 +- .../api/builder/che-workspace-builder.spec.ts | 2 +- .../src/components/api/che-agent.factory.ts | 12 +- .../src/components/api/che-api.factory.ts | 2 +- .../src/components/api/che-factory.factory.ts | 6 +- dashboard/src/components/api/che-git.spec.ts | 15 +- .../api/che-o-auth-provider.factory.ts | 17 +- .../components/api/che-permissions.factory.ts | 4 +- .../components/api/che-preferences.factory.ts | 67 ++--- .../components/api/che-preferences.spec.ts | 35 +-- .../src/components/api/che-profile.factory.ts | 13 +- .../src/components/api/che-profile.spec.ts | 6 +- .../api/che-project-template.spec.ts | 15 +- .../components/api/che-project-type.spec.ts | 16 +- .../src/components/api/che-project-type.ts | 29 ++- .../src/components/api/che-project.spec.ts | 16 +- dashboard/src/components/api/che-project.ts | 12 +- .../api/che-resources-distribution.factory.ts | 13 +- .../src/components/api/che-service.factory.ts | 1 - .../src/components/api/che-ssh.factory.ts | 37 ++- .../src/components/api/che-stack.factory.ts | 19 +- dashboard/src/components/api/che-svn.spec.ts | 20 +- dashboard/src/components/api/che-svn.ts | 24 +- .../api/che-team-events-manager.factory.ts | 20 +- .../src/components/api/che-team.factory.ts | 12 +- .../components/api/che-websocket.factory.ts | 98 ++++---- .../src/components/api/che-workspace-agent.ts | 2 +- .../compose-environment-manager.spec.ts | 24 +- .../docker-image-environment-manager.spec.ts | 10 +- .../api/json-rpc/che-json-rpc-api.factory.ts | 4 +- .../api/json-rpc/che-json-rpc-master-api.ts | 2 +- .../api/json-rpc/websocket-client.ts | 4 +- .../api/project/che-type-resolver.spec.ts | 1 + .../api/project/che-type-resolver.ts | 18 +- .../components/api/remote/che-remote-login.ts | 12 +- .../api/remote/che-remote-project.ts | 19 +- .../api/remote/che-remote-recipe.ts | 18 +- .../test/che-http-backend-provider.factory.ts | 10 +- .../api/test/che-http-backend.factory.ts | 6 +- .../api/workspace/che-workspace.factory.ts | 4 +- .../api/workspace/che-workspace.spec.ts | 8 +- .../click/che-on-right-click.directive.ts | 21 +- .../che-clip-the-middle.directive.ts | 8 +- .../focusable/che-focusable.directive.ts | 20 +- .../che-format-output.directive.ts | 29 ++- .../attribute/img-src/img-src.directive.ts | 6 +- .../input-type/input-type.directive.ts | 8 +- .../che-multi-transclude.directive.spec.ts | 24 +- .../reload-href/che-reload-href.directive.ts | 57 +++-- .../scroll/che-automatic-scroll.directive.ts | 42 ++-- .../che-list-on-scroll-bottom.directive.ts | 20 +- .../touch/che-on-long-touch.directive.ts | 25 +- .../branding/che-branding-config.ts | 4 +- .../src/components/codemirror/codemirror.ts | 2 + dashboard/src/components/components-config.ts | 3 +- .../change-memory-unit.filter.ts | 87 ++++--- .../src/components/filter/filter-config.ts | 6 +- .../number-round/number-round.filter.ts | 32 ++- .../src/components/github/github-service.ts | 120 ++++----- .../ide-fetcher/che-ide-fetcher-config.ts | 5 +- .../che-ui-elements-injector-config.ts | 5 +- .../interceptor/interceptor-base.ts | 4 +- .../application-notifications.factory.ts | 6 +- .../notification/che-notification-config.ts | 2 +- .../routing/route-history.service.ts | 9 +- .../src/components/routing/routing-config.ts | 2 +- .../routing/routing-redirect.factory.ts | 15 +- .../steps-container.directive.ts | 20 +- dashboard/src/components/typings/che.d.ts | 23 +- .../city-name-validator.directive.ts | 10 +- .../validator/git-url-validator.directive.ts | 18 +- ...unique-project-name-validator.directive.ts | 28 ++- .../unique-project-name-validator.spec.ts | 35 +-- .../unique-stack-name-validator.directive.ts | 28 ++- .../unique-stack-name-validator.spec.ts | 48 ++-- ...ique-workspace-name-validator.directive.ts | 30 ++- .../unique-workspace-name-validator.spec.ts | 47 ++-- .../accordion/che-accordion.directive.ts | 55 +++-- .../che-button-dropdown.controller.ts | 13 +- .../che-button-dropdown.directive.ts | 32 +-- .../widget/button/che-button.directive.ts | 6 - .../widget/chips-list/chips-list.directive.ts | 20 +- .../widget/compile/che-compile.directive.ts | 19 +- .../description/che-description.directive.ts | 26 +- .../dropzone/che-dropzone.controller.ts | 77 +++--- .../widget/dropzone/che-dropzone.directive.ts | 80 +++--- .../components/widget/editor/che-editor.html | 12 +- .../empty-state/che-empty-state.directive.ts | 29 +-- .../widget/footer/che-footer.controller.ts | 6 - .../widget/frame/che-frame.directive.ts | 21 +- .../demo-source-render.directive.ts | 2 +- .../widget/input/che-textarea.directive.ts | 27 ++- .../che-label-container.directive.ts | 29 +-- .../widget/label/che-label.directive.ts | 25 +- .../che-learn-more-item.directive.ts | 46 ++-- .../che-learn-more-template.directive.ts | 42 ++-- .../learn-more/che-learn-more.controller.ts | 48 ++-- .../learn-more/che-learn-more.directive.ts | 39 ++- .../widget/link/che-link.directive.ts | 42 ++-- .../list/che-list-header-column.directive.ts | 9 +- .../list/che-list-item-checked.directive.ts | 32 +-- .../widget/list/che-list-item.directive.ts | 17 +- .../widget/list/che-list-title.directive.ts | 25 +- .../widget/list/che-list.directive.ts | 17 +- .../loader/che-loader-crane.directive.ts | 228 +++++++++--------- .../widget/loader/che-loader.directive.ts | 17 +- .../logs-output/che-logs-output.directive.ts | 74 +++--- .../che-error-notification.directive.ts | 63 ++--- .../che-info-notification.directive.ts | 65 ++--- .../widget/panel/che-panel.controller.ts | 32 +-- .../widget/panel/che-panel.directive.ts | 84 ++++--- .../widget/select/che-select.directive.ts | 28 ++- .../selecter/che-selecter.controller.ts | 23 +- .../widget/selecter/che-selecter.directive.ts | 65 +++-- .../widget/slider/che-slider.directive.ts | 45 ++-- .../text-info/che-text-info.directive.ts | 31 +-- .../widget/toolbar/che-toolbar.directive.ts | 83 ++++--- 125 files changed, 1687 insertions(+), 1594 deletions(-) diff --git a/dashboard/src/components/api/builder/che-api-builder.factory.ts b/dashboard/src/components/api/builder/che-api-builder.factory.ts index af5fef61b0..659e9eb55c 100644 --- a/dashboard/src/components/api/builder/che-api-builder.factory.ts +++ b/dashboard/src/components/api/builder/che-api-builder.factory.ts @@ -43,7 +43,7 @@ export class CheAPIBuilder { * The Che Profile builder * @returns {CheProfileBuilder} */ - getProfileBuilder() { + getProfileBuilder(): CheProfileBuilder { return new CheProfileBuilder(); } diff --git a/dashboard/src/components/api/builder/che-profile-builder.ts b/dashboard/src/components/api/builder/che-profile-builder.ts index c67984faa7..afb50b053e 100644 --- a/dashboard/src/components/api/builder/che-profile-builder.ts +++ b/dashboard/src/components/api/builder/che-profile-builder.ts @@ -17,61 +17,62 @@ */ export class CheProfileBuilder { + private profile: che.IProfile; + /** * Default constructor. */ constructor() { - this.profile = {}; + this.profile = {} as che.IProfile; this.profile.attributes = {}; } /** * Sets the email of the user - * @param email the email to use + * @param {string} email the email to use * @returns {CheProfileBuilder} */ - withEmail(email) { + withEmail(email: string): CheProfileBuilder { this.profile.email = email; return this; } /** * Sets the firstName of the user - * @param firstName the firstName to use + * @param {string} firstName the firstName to use * @returns {CheProfileBuilder} */ - withFirstName(firstName) { + withFirstName(firstName: string): CheProfileBuilder { return this.withAttribute('firstName', firstName); } /** * Sets the lastName of the user - * @param lastName the lastName to use + * @param {string} lastName the lastName to use * @returns {CheProfileBuilder} */ - withLastName(lastName) { + withLastName(lastName: string): CheProfileBuilder { return this.withAttribute('lastName', lastName); } /** * Sets the id of the profile - * @param id the id to use + * @param {string} id the id to use * @returns {CheProfileBuilder} */ - withId(id) { - this.profile.id = id; + withId(id: string): CheProfileBuilder { this.profile.userId = id; return this; } /** * Sets an attribute on the profile - * @param name the attribute name - * @param name the attribute value + * @param {string} name the attribute name + * @param {string} value the attribute value * @returns {CheProfileBuilder} */ - withAttribute(name, value) { + withAttribute(name: string, value: string): CheProfileBuilder { this.profile.attributes[name] = value; return this; } @@ -81,9 +82,8 @@ export class CheProfileBuilder { * Build the user * @returns {CheProfileBuilder.profile|*} */ - build() { + build(): che.IProfile { return this.profile; } - } diff --git a/dashboard/src/components/api/builder/che-projectdetails-builder.ts b/dashboard/src/components/api/builder/che-projectdetails-builder.ts index 0e3fff36b8..ab1d4210ca 100644 --- a/dashboard/src/components/api/builder/che-projectdetails-builder.ts +++ b/dashboard/src/components/api/builder/che-projectdetails-builder.ts @@ -16,13 +16,13 @@ */ export class CheProjectDetailsBuilder { + private projectDetails: che.IProjectTemplate; + /** * Default constructor. */ constructor() { - this.projectDetails = {}; - this.projectDetails.creationDate = new Date().getTime(); - this.projectDetails.modificationDate = new Date().getTime(); + this.projectDetails = {} as che.IProjectTemplate; this.projectDetails.mixins = []; this.projectDetails.problems = []; this.projectDetails.description = ''; @@ -30,62 +30,50 @@ export class CheProjectDetailsBuilder { /** * Sets workspaceId - * @param workspaceId the workspace ID + * @param {string} workspaceId the workspace ID * @returns {CheProjectDetailsBuilder} */ - withWorkspaceId(workspaceId) { + withWorkspaceId(workspaceId: string): CheProjectDetailsBuilder { this.projectDetails.workspaceId = workspaceId; return this; } /** * Sets workspaceName - * @param workspaceName the workspace name + * @param {string} workspaceName the workspace name * @returns {CheProjectDetailsBuilder} */ - withWorkspaceName(workspaceName) { + withWorkspaceName(workspaceName: string): CheProjectDetailsBuilder { this.projectDetails.workspaceName = workspaceName; return this; } /** * Sets Name - * @param Name the project's name + * @param {string} name the project's name * @returns {CheProjectDetailsBuilder} */ - withName(name) { + withName(name: string): CheProjectDetailsBuilder { this.projectDetails.name = name; return this; } - /** - * Sets permissions - * @param permissions the project's permissions - * @returns {CheProjectDetailsBuilder} - */ - withPermissions(permissions) { - this.projectDetails.permissions = permissions; - return this; - } - /** * Sets type - * @param type the project's type + * @param {string} type the project's type * @returns {CheProjectDetailsBuilder} */ - withType(type) { + withType(type: string): CheProjectDetailsBuilder { this.projectDetails.type = type; return this; } - /** * Build the project details * @returns {CheProjectDetailsBuilder.projectDetails|*} */ - build() { + build(): che.IProjectTemplate { return this.projectDetails; } - } diff --git a/dashboard/src/components/api/builder/che-projectreference-builder.spec.ts b/dashboard/src/components/api/builder/che-projectreference-builder.spec.ts index fdcd45a79a..d3de348e97 100644 --- a/dashboard/src/components/api/builder/che-projectreference-builder.spec.ts +++ b/dashboard/src/components/api/builder/che-projectreference-builder.spec.ts @@ -19,14 +19,13 @@ describe('CheProjectReferenceBuilder', function(){ /** * For creating builders. */ - var apiBuilder; + let apiBuilder; /** * setup module */ beforeEach(angular.mock.module('userDashboard')); - /** * Inject builder */ @@ -39,17 +38,14 @@ describe('CheProjectReferenceBuilder', function(){ */ it('check builder', function() { - var projectReferenceBuilder = apiBuilder.getProjectReferenceBuilder(); - - var name = 'myProject'; - var projectReference = projectReferenceBuilder.withName(name).build(); + const projectReferenceBuilder = apiBuilder.getProjectReferenceBuilder(); + const name = 'myProject'; + const projectReference = projectReferenceBuilder.withName(name).build(); // check values expect(projectReference.name).toEqual(name); }); - - }); diff --git a/dashboard/src/components/api/builder/che-projectreference-builder.ts b/dashboard/src/components/api/builder/che-projectreference-builder.ts index 2568399eb1..53b8f41d6a 100644 --- a/dashboard/src/components/api/builder/che-projectreference-builder.ts +++ b/dashboard/src/components/api/builder/che-projectreference-builder.ts @@ -15,6 +15,7 @@ * @author Florent Benoit */ export class CheProjectReferenceBuilder { + private projectReference: any; /** * Default constructor. @@ -23,13 +24,12 @@ export class CheProjectReferenceBuilder { this.projectReference = {}; } - /** * Sets the name of the project reference - * @param name the name to use + * @param {string} name the name to use * @returns {CheProjectReferenceBuilder} */ - withName(name) { + withName(name: string): CheProjectReferenceBuilder { this.projectReference.name = name; return this; } @@ -38,10 +38,9 @@ export class CheProjectReferenceBuilder { * Build the project reference * @returns {CheProjectReferenceBuilder.projectReference|*} */ - build() { + build(): CheProjectReferenceBuilder { return this.projectReference; } - } diff --git a/dashboard/src/components/api/builder/che-projecttemplate-builder.ts b/dashboard/src/components/api/builder/che-projecttemplate-builder.ts index f8ceea685e..b0b18f6b9a 100644 --- a/dashboard/src/components/api/builder/che-projecttemplate-builder.ts +++ b/dashboard/src/components/api/builder/che-projecttemplate-builder.ts @@ -16,48 +16,49 @@ */ export class CheProjectTemplateBuilder { - constructor() { - this.template = {}; - this.template.source = {}; - this.template.config = {}; + template: che.IProjectTemplate; + constructor() { + this.template = {} as che.IProjectTemplate; + this.template.source = {} as che.IProjectSource; } - withDescription(desc) { + + withDescription(desc: string): CheProjectTemplateBuilder { this.template.description = desc; return this; } - withSourceParameters(parameters) { + withSourceParameters(parameters: {[paramName: string]: string}): CheProjectTemplateBuilder { this.template.source.parameters = parameters; return this; } - withSourceType(type) { + withSourceType(type: string): CheProjectTemplateBuilder { this.template.source.type = type; return this; } - withSourceLocation(location) { + withSourceLocation(location: string): CheProjectTemplateBuilder { this.template.source.location = location; return this; } - withDisplayname(name) { + withDisplayname(name: string): CheProjectTemplateBuilder { this.template.displayName = name; return this; } - withCategory(category) { + withCategory(category: string): CheProjectTemplateBuilder { this.template.category = category; return this; } - withProjectType(projectType) { + withProjectType(projectType: string): CheProjectTemplateBuilder { this.template.projectType = projectType; return this; } - build() { + build(): che.IProjectTemplate { return this.template; } diff --git a/dashboard/src/components/api/builder/che-projecttype-attribute-descriptor-builder.ts b/dashboard/src/components/api/builder/che-projecttype-attribute-descriptor-builder.ts index c38316bba7..9599b04432 100644 --- a/dashboard/src/components/api/builder/che-projecttype-attribute-descriptor-builder.ts +++ b/dashboard/src/components/api/builder/che-projecttype-attribute-descriptor-builder.ts @@ -16,39 +16,40 @@ */ export class CheProjectTypeAttributeDescriptorBuilder { + private attribute: any; + constructor() { this.attribute = {}; this.attribute.values = []; } - withName(name) { + withName(name: string): CheProjectTypeAttributeDescriptorBuilder { this.attribute.name = name; return this; } - withRequired(required) { + withRequired(required: boolean): CheProjectTypeAttributeDescriptorBuilder { this.attribute.required = required; return this; } - withVariable(variable) { + withVariable(variable: any): CheProjectTypeAttributeDescriptorBuilder { this.attribute.variable = variable; return this; } - withDescription(description) { + withDescription(description: string): CheProjectTypeAttributeDescriptorBuilder { this.attribute.description = description; return this; } - withValues(values) { + withValues(values: any): CheProjectTypeAttributeDescriptorBuilder { this.attribute.values = values; return this; } - build() { + build(): any { return this.attribute; } - } diff --git a/dashboard/src/components/api/builder/che-projecttype-builder.ts b/dashboard/src/components/api/builder/che-projecttype-builder.ts index c7e69e651c..caf2824645 100644 --- a/dashboard/src/components/api/builder/che-projecttype-builder.ts +++ b/dashboard/src/components/api/builder/che-projecttype-builder.ts @@ -16,28 +16,30 @@ */ export class CheProjectTypeBuilder { + private type: any; + constructor() { this.type = {}; this.type.attributeDescriptors = []; } - withAttributeDescriptors(attributeDescriptors) { + withAttributeDescriptors(attributeDescriptors: any): CheProjectTypeBuilder { this.type.attributeDescriptors = attributeDescriptors; return this; } - withDisplayname(name) { + withDisplayname(name: string): CheProjectTypeBuilder { this.type.displayName = name; return this; } - withId(id) { + withId(id: string): CheProjectTypeBuilder { this.type.id = id; return this; } - build() { + build(): any { return this.type; } diff --git a/dashboard/src/components/api/builder/che-user-builder.ts b/dashboard/src/components/api/builder/che-user-builder.ts index 78cec84102..50e2babef1 100644 --- a/dashboard/src/components/api/builder/che-user-builder.ts +++ b/dashboard/src/components/api/builder/che-user-builder.ts @@ -34,7 +34,7 @@ export class CheUserBuilder { /** * Sets the email of the user * @param {string} email the email to use - * @returns {CodenvyUserBuilder} + * @returns {CheUserBuilder} */ withEmail(email: string): CheUserBuilder { this.user.email = email; @@ -44,7 +44,7 @@ export class CheUserBuilder { /** * Sets the id of the user * @param {string} id the id to use - * @returns {CodenvyUserBuilder} + * @returns {CheUserBuilder} */ withId(id: string): CheUserBuilder { this.user.id = id; @@ -54,7 +54,7 @@ export class CheUserBuilder { /** * Sets the aliases of the user * @param {any[]} aliases the aliases to use - * @returns {CodenvyUserBuilder} + * @returns {CheUserBuilder} */ withAliases(aliases: any[]): CheUserBuilder { this.user.aliases = aliases; diff --git a/dashboard/src/components/api/builder/che-workspace-builder.spec.ts b/dashboard/src/components/api/builder/che-workspace-builder.spec.ts index 94cffa22c6..d7b0a901ee 100644 --- a/dashboard/src/components/api/builder/che-workspace-builder.spec.ts +++ b/dashboard/src/components/api/builder/che-workspace-builder.spec.ts @@ -18,7 +18,7 @@ import {CheAPIBuilder} from './che-api-builder.factory'; describe('CheWorkspaceBuilder', () => { - var wkspBuilder; + let wkspBuilder; /** * setup module diff --git a/dashboard/src/components/api/che-agent.factory.ts b/dashboard/src/components/api/che-agent.factory.ts index 499115a647..699b4d038d 100644 --- a/dashboard/src/components/api/che-agent.factory.ts +++ b/dashboard/src/components/api/che-agent.factory.ts @@ -48,18 +48,18 @@ export class CheAgent { * Fetch the agents. */ fetchAgents(): ng.IPromise { - var defer = this.$q.defer(); - let promise = this.remoteAgentAPI.getAgents().$promise; + const defer = this.$q.defer(); + const promise = this.remoteAgentAPI.getAgents().$promise; - promise.then((agents) => { + promise.then((agents: che.IAgent[]) => { // reset global list this.agents.length = 0; - agents.forEach((agent) => { + agents.forEach((agent: che.IAgent[]) => { this.agents.push(agent); }); defer.resolve(this.agents); - }, (error) => { + }, (error: any) => { if (error.status != 304) { defer.reject(error); } else { @@ -73,7 +73,7 @@ export class CheAgent { /** * Returns the list of all agents. * - * @returns {Array} + * @returns {che.IAgent[]} */ getAgents(): che.IAgent[] { return this.agents; diff --git a/dashboard/src/components/api/che-api.factory.ts b/dashboard/src/components/api/che-api.factory.ts index fbc33f58c2..8402b0bf7b 100644 --- a/dashboard/src/components/api/che-api.factory.ts +++ b/dashboard/src/components/api/che-api.factory.ts @@ -8,8 +8,8 @@ * Contributors: * Red Hat, Inc. - initial API and implementation */ -import {CheSsh} from './che-ssh.factory'; 'use strict'; +import {CheSsh} from './che-ssh.factory'; import {CheWorkspace} from './workspace/che-workspace.factory'; import {CheProfile} from './che-profile.factory'; import {CheFactory} from './che-factory.factory'; diff --git a/dashboard/src/components/api/che-factory.factory.ts b/dashboard/src/components/api/che-factory.factory.ts index be21643199..172f90365d 100644 --- a/dashboard/src/components/api/che-factory.factory.ts +++ b/dashboard/src/components/api/che-factory.factory.ts @@ -32,7 +32,7 @@ const DEFAULT_MAX_ITEMS = 15; export class CheFactory { private $resource: ng.resource.IResourceService; private $q: ng.IQService; - private lodash: _.LoDashStatic; + private lodash: any; private remoteFactoryAPI: IFactoriesResource; @@ -50,7 +50,7 @@ export class CheFactory { * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($resource: ng.resource.IResourceService, $q: ng.IQService, lodash: _.LoDashStatic, cheUser: CheUser) { + constructor($resource: ng.resource.IResourceService, $q: ng.IQService, lodash: any, cheUser: CheUser) { // keep resource this.$resource = $resource; this.cheUser = cheUser; @@ -406,7 +406,7 @@ export class CheFactory { * @return the factory content */ getFactoryContentFromWorkspace(workspace: che.IWorkspace): any { - return this.factoryContentsByWorkspaceId.get(workspace.workspaceId); + return this.factoryContentsByWorkspaceId.get(workspace.id); } /** diff --git a/dashboard/src/components/api/che-git.spec.ts b/dashboard/src/components/api/che-git.spec.ts index f2fdff3d03..2f44a081ba 100644 --- a/dashboard/src/components/api/che-git.spec.ts +++ b/dashboard/src/components/api/che-git.spec.ts @@ -9,6 +9,9 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheWorkspace} from './workspace/che-workspace.factory'; +import {CheAPIBuilder} from './builder/che-api-builder.factory'; +import {CheHttpBackend} from './test/che-http-backend'; /** * Test of the CheGit @@ -18,19 +21,19 @@ describe('CheGit', function () { /** * API builder. */ - var apiBuilder; + let apiBuilder; - var workspace; + let workspace; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * Che backend */ - var cheBackend; + let cheBackend; /** * setup module @@ -40,7 +43,9 @@ describe('CheGit', function () { /** * Inject factory and http backend */ - beforeEach(inject(function (cheWorkspace, cheAPIBuilder, cheHttpBackend) { + beforeEach(inject(function (cheWorkspace: CheWorkspace, + cheAPIBuilder: CheAPIBuilder, + cheHttpBackend: CheHttpBackend) { workspace = cheWorkspace; cheBackend = cheHttpBackend; apiBuilder = cheAPIBuilder; diff --git a/dashboard/src/components/api/che-o-auth-provider.factory.ts b/dashboard/src/components/api/che-o-auth-provider.factory.ts index 09060394a3..99e8cc5ec2 100644 --- a/dashboard/src/components/api/che-o-auth-provider.factory.ts +++ b/dashboard/src/components/api/che-o-auth-provider.factory.ts @@ -15,24 +15,28 @@ * @author Ann Shumilova */ export class CheOAuthProvider { + private $http: ng.IHttpService; + + private providersByName: Map; + private providersPromise: ng.IPromise; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor ($http) { + constructor ($http: ng.IHttpService) { this.$http = $http; this.providersByName = new Map(); } - fetchOAuthProviders() { + fetchOAuthProviders(): ng.IPromise { if (this.providersPromise) { return this.providersPromise; } let promise = this.$http.get('/api/oauth/'); - this.providersPromise = promise.then((providers) => { - providers.data.forEach((provider) => { + this.providersPromise = promise.then((providers: any) => { + providers.data.forEach((provider: any) => { this.providersByName.set(provider.name, provider); }); }); @@ -42,9 +46,10 @@ export class CheOAuthProvider { /** * Checks whether provider is registered. - * @returns {Boolean|*} + * @param {string} name + * @returns {boolean} */ - isOAuthProviderRegistered(name) { + isOAuthProviderRegistered(name: string): boolean { if (!this.providersByName) { return false; } diff --git a/dashboard/src/components/api/che-permissions.factory.ts b/dashboard/src/components/api/che-permissions.factory.ts index ebe6d86a8c..cb0c93d0f6 100644 --- a/dashboard/src/components/api/che-permissions.factory.ts +++ b/dashboard/src/components/api/che-permissions.factory.ts @@ -210,8 +210,8 @@ export class ChePermissions implements che.api.IChePermissions { } private updateUserServices(systemPermissions: che.api.ISystemPermissions): void { - let isManageUsers: boolean = systemPermissions && systemPermissions.actions.includes('manageUsers'); - let isManageSystem: boolean = systemPermissions && systemPermissions.actions.includes('manageSystem'); + let isManageUsers: boolean = systemPermissions && systemPermissions.actions.indexOf('manageUsers') !== -1; + let isManageSystem: boolean = systemPermissions && systemPermissions.actions.indexOf('manageSystem') !== -1; this.userServices.hasUserService = isManageUsers; this.userServices.hasUserProfileService = isManageUsers; diff --git a/dashboard/src/components/api/che-preferences.factory.ts b/dashboard/src/components/api/che-preferences.factory.ts index e698235f6a..1262b2434a 100644 --- a/dashboard/src/components/api/che-preferences.factory.ts +++ b/dashboard/src/components/api/che-preferences.factory.ts @@ -16,12 +16,20 @@ * @author Oleksii Orel */ export class ChePreferences { + private $window: ng.IWindowService; + private $resource: ng.resource.IResourceService; + private $http: ng.IHttpService; + private remotePreferencesAPI: any; + private registries: any[]; + private preferences: any; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($resource, $http, $window) { + constructor($resource: ng.resource.IResourceService, + $http: ng.IHttpService, + $window: ng.IWindowService) { this.$window = $window; // keep resource @@ -33,7 +41,7 @@ export class ChePreferences { // remote call this.remotePreferencesAPI = this.$resource('/api/preferences', {}, {}); - //registry array + // registry array this.registries = []; } @@ -41,15 +49,15 @@ export class ChePreferences { * Gets the preferences * @return preferences */ - getPreferences() { + getPreferences(): any { return this.preferences; } /** * Update the preferences - * @param properties + * @param {any} properties */ - updatePreferences(properties) { + updatePreferences(properties: any): ng.IPromise { if (this.preferences && properties) { angular.extend(this.preferences, properties); } else if (properties) { @@ -64,7 +72,7 @@ export class ChePreferences { * Remove preferences properties * @param properties (list of keys) */ - removePreferences(properties) { + removePreferences(properties: any): void { // delete method doesn't send body when it is defined in $resources // that's why direct $http call is used. this.$http({ @@ -74,16 +82,16 @@ export class ChePreferences { data: properties }).then(() => { this.fetchPreferences(); - }) + }); } /** * Gets the preferences data */ - fetchPreferences() { + fetchPreferences(): ng.IPromise { let promise = this.remotePreferencesAPI.get().$promise; - promise.then((preferences) => { + promise.then((preferences: any) => { // update preferences data if we have new value this._setPreferences(preferences); }); @@ -96,18 +104,18 @@ export class ChePreferences { * Gets the registries * @return [*] registries */ - getRegistries() { + getRegistries(): any[] { return this.registries; } /** * Add a registry - * @param registryUrl - * @param userName - * @param userPassword + * @param {string} registryUrl + * @param {string} userName + * @param {string} userPassword * @returns {*} the promise */ - addRegistry(registryUrl, userName, userPassword) { + addRegistry(registryUrl: string, userName: string, userPassword: string): ng.IPromise { let credentials = {}; credentials[registryUrl] = { username: userName, @@ -127,20 +135,19 @@ export class ChePreferences { let preferences = {dockerCredentials: credentialsBase64}; let promise = this.updatePreferences(preferences); - promise.then((preferences) => { + promise.then((preferences: any) => { this._setPreferences(preferences); }); return promise; } - /** * Remove the registry by its URL - * @param registryUrl + * @param {string} registryUrl * @returns {*} the promise */ - removeRegistry(registryUrl) { + removeRegistry(registryUrl: string): ng.IPromise { let credentialsJson = this.$window.atob(this.preferences.dockerCredentials); let credentials = angular.fromJson(credentialsJson); @@ -151,7 +158,7 @@ export class ChePreferences { let promise = this.updatePreferences(preferences); - promise.then((preferences) => { + promise.then((preferences: any) => { this._setPreferences(preferences); }); @@ -160,9 +167,9 @@ export class ChePreferences { /** * Sets preferences - * @param preferences + * @param {any} preferences */ - _setPreferences(preferences) { + _setPreferences(preferences: any): void { this.preferences = preferences; this._updateRegistries(); } @@ -170,7 +177,7 @@ export class ChePreferences { /** * Update registry array from preferences */ - _updateRegistries() { + _updateRegistries(): void { this.registries.length = 0; if (!this.preferences || !this.preferences.dockerCredentials) { return; @@ -178,13 +185,15 @@ export class ChePreferences { let credentialsJson = this.$window.atob(this.preferences.dockerCredentials); let credentials = angular.fromJson(credentialsJson); - for (var key in credentials) { - let credential = { - url: key, - username: credentials[key].username, - password: credentials[key].password - }; - this.registries.push(credential); + for (let key in credentials) { + if (credentials.hasOwnProperty(key)) { + let credential = { + url: key, + username: credentials[key].username, + password: credentials[key].password + }; + this.registries.push(credential); + } } } } diff --git a/dashboard/src/components/api/che-preferences.spec.ts b/dashboard/src/components/api/che-preferences.spec.ts index 92fe0782a1..cf75fe0407 100644 --- a/dashboard/src/components/api/che-preferences.spec.ts +++ b/dashboard/src/components/api/che-preferences.spec.ts @@ -9,6 +9,9 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {ChePreferences} from './che-preferences.factory'; +import {CheAPIBuilder} from './builder/che-api-builder.factory'; +import {CheHttpBackend} from './test/che-http-backend'; /** * Test of the ChePreferences @@ -18,22 +21,22 @@ describe('ChePreferences', function () { /** * Preferences Factory for the test */ - var factory; + let factory; /** * API builder. */ - var apiBuilder; + let apiBuilder; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * che backend */ - var cheBackend; + let cheBackend; /** * setup module @@ -43,7 +46,9 @@ describe('ChePreferences', function () { /** * Inject factory and http backend */ - beforeEach(inject(function (chePreferences, cheAPIBuilder, cheHttpBackend) { + beforeEach(inject(function (chePreferences: ChePreferences, + cheAPIBuilder: CheAPIBuilder, + cheHttpBackend: CheHttpBackend) { factory = chePreferences; apiBuilder = cheAPIBuilder; cheBackend = cheHttpBackend; @@ -63,7 +68,7 @@ describe('ChePreferences', function () { */ it('Fetch preferences', function () { - //{testURL: {username: 'testName', password: 'testPassword'}} converted to base64 + // {testURL: {username: 'testName', password: 'testPassword'}} converted to base64 let dockerCredentials = 'eyJ0ZXN0VVJMIjp7InVzZXJuYW1lIjoidGVzdE5hbWUiLCJwYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9fQ=='; let defaultPreferences = { pref1: 'value1', @@ -89,9 +94,9 @@ describe('ChePreferences', function () { let preferences = factory.getPreferences(); let registries = factory.getRegistries(); - expect(preferences['pref1']).toEqual('value1'); - expect(preferences['pref2']).toEqual('value2'); - expect(preferences['dockerCredentials']).toEqual(dockerCredentials); + expect(preferences.pref1).toEqual('value1'); + expect(preferences.pref2).toEqual('value2'); + expect(preferences.dockerCredentials).toEqual(dockerCredentials); expect(registries[0].url).toEqual('testURL'); expect(registries[0].username).toEqual('testName'); expect(registries[0].password).toEqual('testPassword'); @@ -107,7 +112,7 @@ describe('ChePreferences', function () { let registryUrl = 'testURL'; let userName = 'testName'; let userPassword = 'testPassword'; - //{testURL: {username: 'testName', password: 'testPassword'}} converted to base64 + // {testURL: {username: 'testName', password: 'testPassword'}} converted to base64 let dockerCredentials = 'eyJ0ZXN0VVJMIjp7InVzZXJuYW1lIjoidGVzdE5hbWUiLCJwYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9fQ=='; // setup backend @@ -116,7 +121,7 @@ describe('ChePreferences', function () { // set default preferences factory._setPreferences(defaultPreferences); - //add registry + // add registry factory.addRegistry(registryUrl, userName, userPassword); // expecting POST @@ -129,8 +134,8 @@ describe('ChePreferences', function () { let preferences = factory.getPreferences(); let registries = factory.getRegistries(); - expect(preferences['pref1']).toEqual('value1'); - expect(preferences['dockerCredentials']).toEqual(dockerCredentials); + expect(preferences.pref1).toEqual('value1'); + expect(preferences.dockerCredentials).toEqual(dockerCredentials); expect(registries[0].url).toEqual(registryUrl); expect(registries[0].username).toEqual(userName); expect(registries[0].password).toEqual(userPassword); @@ -162,8 +167,8 @@ describe('ChePreferences', function () { // now, check preferences let preferences = factory.getPreferences(); - expect(preferences['pref1']).toEqual(defaultPreferences['pref1']); - expect(preferences['pref2']).toEqual(newPreferences['pref2']); + expect(preferences.pref1).toEqual(defaultPreferences.pref1); + expect(preferences.pref2).toEqual(newPreferences.pref2); } ); diff --git a/dashboard/src/components/api/che-profile.factory.ts b/dashboard/src/components/api/che-profile.factory.ts index 871e24d9e1..4ee30ea045 100644 --- a/dashboard/src/components/api/che-profile.factory.ts +++ b/dashboard/src/components/api/che-profile.factory.ts @@ -37,7 +37,7 @@ export class CheProfile { private profile: che.IProfile; private profileIdMap: Map; - private remoteProfileAPI: IProfileResource; + private remoteProfileAPI: any; /** * Default constructor that is using resource @@ -51,7 +51,7 @@ export class CheProfile { this.$http = $http; // remote call - this.remoteProfileAPI = >this.$resource('/api/profile', {}, { + this.remoteProfileAPI = this.$resource('/api/profile', {}, { getById: {method: 'GET', url: '/api/profile/:userId'}, setAttributes: {method: 'PUT', url: '/api/profile/attributes'}, setAttributesById: {method: 'PUT', url: '/api/profile/:userId/attributes'} @@ -87,7 +87,7 @@ export class CheProfile { * Gets the profile data * @returns {ng.IPromise} the promise */ - fetchProfile(): ng.IPromise { + fetchProfile(): che.IProfile { if (this.profile && !this.profile.$resolved) { return this.profile; } @@ -108,13 +108,14 @@ export class CheProfile { if (error && error.status === 304) { return this.profile; } - return this.$q.reject(error); + return null; }); } /** * Set the profile attributes data - * @param attributes {che.IProfileAttributes} + * @param {che.IProfileAttributes} attributes + * @param {string=} userId * @returns {ng.IPromise} the promise */ setAttributes(attributes: che.IProfileAttributes, userId?: string): ng.IPromise { @@ -146,7 +147,7 @@ export class CheProfile { if (error && error.status === 304) { return this.profileIdMap.get(userId); } - return this.$q.reject(error); + return null; }); } diff --git a/dashboard/src/components/api/che-profile.spec.ts b/dashboard/src/components/api/che-profile.spec.ts index d55edf9d85..355dbb1b31 100644 --- a/dashboard/src/components/api/che-profile.spec.ts +++ b/dashboard/src/components/api/che-profile.spec.ts @@ -94,10 +94,10 @@ describe('CheProfile', () => { .build(); // setup backend - cheBackend.setAttributes(testProfile.atributes); + cheBackend.setAttributes(testProfile.attributes); cheBackend.setup(); - factory.setAttributes(testProfile.atributes); + factory.setAttributes(testProfile.attributes); httpBackend.expectPUT('/api/profile/attributes'); @@ -118,7 +118,7 @@ describe('CheProfile', () => { factory.setAttributes(testProfile.attributes, testProfile.userId); - httpBackend.expectPUT(`/api/profile/${testProfile.id}/attributes`); + httpBackend.expectPUT(`/api/profile/${testProfile.userId}/attributes`); httpBackend.flush(); diff --git a/dashboard/src/components/api/che-project-template.spec.ts b/dashboard/src/components/api/che-project-template.spec.ts index 65c975fd9b..79885d73a9 100644 --- a/dashboard/src/components/api/che-project-template.spec.ts +++ b/dashboard/src/components/api/che-project-template.spec.ts @@ -9,6 +9,9 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheProjectTemplate} from './che-project-template.factory'; +import {CheAPIBuilder} from './builder/che-api-builder.factory'; +import {CheHttpBackend} from './test/che-http-backend'; /** * Test of the CheProjectTemplate @@ -18,22 +21,22 @@ describe('CheProjectTemplate', function(){ /** * Project Template Factory for the test */ - var factory; + let factory; /** * API builder. */ - var apiBuilder; + let apiBuilder; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * Che backend */ - var cheBackend; + let cheBackend; /** * setup module @@ -43,7 +46,9 @@ describe('CheProjectTemplate', function(){ /** * Inject factory and http backend */ - beforeEach(inject(function(cheProjectTemplate, cheAPIBuilder, cheHttpBackend) { + beforeEach(inject(function(cheProjectTemplate: CheProjectTemplate, + cheAPIBuilder: CheAPIBuilder, + cheHttpBackend: CheHttpBackend) { factory = cheProjectTemplate; apiBuilder = cheAPIBuilder; cheBackend = cheHttpBackend; diff --git a/dashboard/src/components/api/che-project-type.spec.ts b/dashboard/src/components/api/che-project-type.spec.ts index 7fde601a10..50d9759479 100644 --- a/dashboard/src/components/api/che-project-type.spec.ts +++ b/dashboard/src/components/api/che-project-type.spec.ts @@ -9,6 +9,9 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheWorkspace} from './workspace/che-workspace.factory'; +import {CheAPIBuilder} from './builder/che-api-builder.factory'; +import {CheHttpBackend} from './test/che-http-backend'; /** * Test of the CheProjectType @@ -18,23 +21,22 @@ describe('CheProjectType', function(){ /** * Workspace for the test */ - var workspace; + let workspace; /** * API builder. */ - var apiBuilder; + let apiBuilder; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * Che backend */ - var cheBackend; - + let cheBackend; /** * setup module @@ -44,7 +46,9 @@ describe('CheProjectType', function(){ /** * Inject factory and http backend */ - beforeEach(inject(function(cheWorkspace, cheAPIBuilder, cheHttpBackend) { + beforeEach(inject(function(cheWorkspace: CheWorkspace, + cheAPIBuilder: CheAPIBuilder, + cheHttpBackend: CheHttpBackend) { workspace = cheWorkspace; apiBuilder = cheAPIBuilder; cheBackend = cheHttpBackend; diff --git a/dashboard/src/components/api/che-project-type.ts b/dashboard/src/components/api/che-project-type.ts index 37a6d12b1b..ab2ecdcf02 100644 --- a/dashboard/src/components/api/che-project-type.ts +++ b/dashboard/src/components/api/che-project-type.ts @@ -16,11 +16,18 @@ * @author Florent Benoit */ export class CheProjectType { + private $q: ng.IQService; + private $resource: ng.resource.IResourceService; + private typesIds: Map; + private workspaceTypes: any[]; + private remoteProjectTypeAPI: any; /** * Default constructor that is using resource */ - constructor ($resource, $q, wsagentPath) { + constructor ($resource: ng.resource.IResourceService, + $q: ng.IQService, + wsagentPath: string) { this.$q = $q; this.$resource = $resource; @@ -36,20 +43,22 @@ export class CheProjectType { /** * Fetch the project types + * + * @returns {angular.IPromise} */ - fetchTypes() { - var defer = this.$q.defer(); - let promise = this.remoteProjectTypeAPI.query().$promise; - let updatedPromise = promise.then((projectTypes) => { + fetchTypes(): ng.IPromise { + const defer = this.$q.defer(); + const promise = this.remoteProjectTypeAPI.query().$promise; + promise.then((projectTypes: any[]) => { // reset global list this.workspaceTypes = projectTypes; - projectTypes.forEach((projectType) => { + projectTypes.forEach((projectType: any) => { this.typesIds.set(projectType.id, projectType); }); defer.resolve(); - }, (error) => { + }, (error: any) => { if (error.status !== 304) { defer.reject(error); } else { @@ -64,15 +73,15 @@ export class CheProjectType { * Gets all project types * @returns {Array} */ - getAllProjectTypes() { + getAllProjectTypes(): any[] { return this.workspaceTypes; } /** * The types per category - * @returns {CheProjectType.typesPerCategory|*} + * @returns {Map} */ - getProjectTypesIDs() { + getProjectTypesIDs(): Map { return this.typesIds; } diff --git a/dashboard/src/components/api/che-project.spec.ts b/dashboard/src/components/api/che-project.spec.ts index 16c20352d0..88da0f7db1 100644 --- a/dashboard/src/components/api/che-project.spec.ts +++ b/dashboard/src/components/api/che-project.spec.ts @@ -9,28 +9,30 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheAPIBuilder} from './builder/che-api-builder.factory'; +import {CheWorkspace} from './workspace/che-workspace.factory'; +import {CheHttpBackend} from './test/che-http-backend'; describe('CheProject', function () { /** * Workspace for the test */ - var workspace; + let workspace; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * Che backend */ - var cheBackend; + let cheBackend; /** * API builder. */ - var apiBuilder; - + let apiBuilder; /** * setup module @@ -40,7 +42,9 @@ describe('CheProject', function () { /** * Inject factory and http backend */ - beforeEach(inject(function (cheAPIBuilder, cheWorkspace, cheHttpBackend) { + beforeEach(inject(function (cheAPIBuilder: CheAPIBuilder, + cheWorkspace: CheWorkspace, + cheHttpBackend: CheHttpBackend) { apiBuilder = cheAPIBuilder; cheBackend = cheHttpBackend; workspace = cheWorkspace; diff --git a/dashboard/src/components/api/che-project.ts b/dashboard/src/components/api/che-project.ts index 285f1745b4..8c1d0bf38d 100644 --- a/dashboard/src/components/api/che-project.ts +++ b/dashboard/src/components/api/che-project.ts @@ -109,11 +109,11 @@ export class CheProject { * @returns {string} a name */ getFullName(profile: che.IProfile): string { - var firstName = profile.attributes.firstName; + let firstName = profile.attributes.firstName; if (!firstName) { firstName = ''; } - var lastName = profile.attributes.lastName; + let lastName = profile.attributes.lastName; if (!lastName) { lastName = ''; } @@ -127,12 +127,12 @@ export class CheProject { * @returns {ng.IPromise} */ fetchProjectDetails(workspaceId: string, projectPath: string): ng.IPromise { - //TODO why we cannot use project path + // todo why we cannot use project path let projectName = projectPath[0] === '/' ? projectPath.slice(1) : projectPath; let promise = this.remoteProjectsAPI.details({path: projectName}).$promise; // check if it was OK or not - let parsedResultPromise = promise.then((projectDetails) => { + let parsedResultPromise = promise.then((projectDetails: any) => { if (projectDetails) { projectDetails.workspaceId = workspaceId; this.projectDetailsMap.set(projectPath, projectDetails); @@ -185,7 +185,7 @@ export class CheProject { fetchEstimate(projectPath: string, projectType: string): ng.IPromise { let projectName = projectPath[0] === '/' ? projectPath.slice(1) : projectPath; let promise = this.remoteProjectsAPI.estimate({path: projectName, type: projectType}).$promise; - let parsedResultPromise = promise.then((estimate) => { + let parsedResultPromise = promise.then((estimate: any) => { if (estimate) { this.estimateMap.set(projectName + projectType, estimate); } @@ -210,7 +210,7 @@ export class CheProject { fetchResolve(projectPath: string): ng.IPromise { let projectName = projectPath[0] === '/' ? projectPath.slice(1) : projectPath; let promise = this.remoteProjectsAPI.resolve({path: projectName}).$promise; - let parsedResultPromise = promise.then((resolve) => { + let parsedResultPromise = promise.then((resolve: any) => { if (resolve) { this.resolveMap.set(projectName, resolve); } diff --git a/dashboard/src/components/api/che-resources-distribution.factory.ts b/dashboard/src/components/api/che-resources-distribution.factory.ts index 8471c7f15d..a80cf8677b 100644 --- a/dashboard/src/components/api/che-resources-distribution.factory.ts +++ b/dashboard/src/components/api/che-resources-distribution.factory.ts @@ -10,8 +10,6 @@ */ 'use strict'; -import {CheResourceLimits} from './che-resource-limits'; - interface IResourcesResource extends ng.resource.IResourceClass { distribute: any; getResources: any; @@ -21,8 +19,6 @@ interface IResourcesResource extends ng.resource.IResourceClass { updateFreeResources: any; } -const RAM_RESOURCE_TYPE: string = 'RAM'; - /** * This class is handling the organization's resources management API. * @@ -240,7 +236,7 @@ export class CheResourcesDistribution implements che.api.ICheResourcesDistributi * @param type type of resource * @returns {any} resource limit */ - getOrganizationTotalResourceByType(organizationId: string, type: CheResourceLimits): any { + getOrganizationTotalResourceByType(organizationId: string, type: che.resource.resourceLimits): any { let resources = this.organizationTotalResources.get(organizationId); if (!resources) { return null; @@ -258,7 +254,7 @@ export class CheResourcesDistribution implements che.api.ICheResourcesDistributi * @param type type of resource * @returns {any} resource limit */ - getOrganizationAvailableResourceByType(organizationId: string, type: CheResourceLimits): any { + getOrganizationAvailableResourceByType(organizationId: string, type: che.resource.resourceLimits): any { let resources = this.organizationAvailableResources.get(organizationId); if (!resources) { return null; @@ -276,7 +272,7 @@ export class CheResourcesDistribution implements che.api.ICheResourcesDistributi * @param type type of resource * @returns {any} resource limit */ - getOrganizationResourceByType(organizationId: string, type: CheResourceLimits): any { + getOrganizationResourceByType(organizationId: string, type: che.resource.resourceLimits): any { let resources = this.organizationResources.get(organizationId); if (!resources) { return null; @@ -295,10 +291,9 @@ export class CheResourcesDistribution implements che.api.ICheResourcesDistributi * @param value value to be set * @returns {any} modified */ - setOrganizationResourceLimitByType(resources: any, type: CheResourceLimits, value: string): any { + setOrganizationResourceLimitByType(resources: any, type: che.resource.resourceLimits, value: string): any { resources = resources || []; - let resource = this.lodash.find(resources, (resource: any) => { return resource.type === type.valueOf(); }); diff --git a/dashboard/src/components/api/che-service.factory.ts b/dashboard/src/components/api/che-service.factory.ts index c3cb2e43a1..76a06f8747 100644 --- a/dashboard/src/components/api/che-service.factory.ts +++ b/dashboard/src/components/api/che-service.factory.ts @@ -10,7 +10,6 @@ */ 'use strict'; - /** * This class is handling the all services API retrieval. * @author Ann Shumilova diff --git a/dashboard/src/components/api/che-ssh.factory.ts b/dashboard/src/components/api/che-ssh.factory.ts index 6a727c3d8d..b83af084b6 100644 --- a/dashboard/src/components/api/che-ssh.factory.ts +++ b/dashboard/src/components/api/che-ssh.factory.ts @@ -29,8 +29,7 @@ export class CheSsh { /** * Remote API for SSH. */ - private remoteSshAPI: ng.resource.IResourceClass>; - remoteSshAPI: { getKeyPair: Function; removeKey : Function, generateKey: Function}; + private remoteSshAPI: any; private sshKeyPairs : Map; @@ -44,29 +43,28 @@ export class CheSsh { this.$resource = $resource; this.$q = $q; - this.sshKeyPairs = new Map(); // remote call this.remoteSshAPI = this.$resource('/api/ssh', {}, { getKeyPair: { method: 'GET', url: '/api/ssh/:serviceId/find?name=:nameId'}, removeKey: { method: 'DELETE', url: '/api/ssh/:serviceId/?name=:nameId'}, - generateKey: { method: 'POST', url: '/api/ssh/generate'}, + generateKey: { method: 'POST', url: '/api/ssh/generate'} }); } /** * Fetch the keyPair */ - fetchKey(serviceId: string, nameId: string) { - var defer = this.$q.defer(); + fetchKey(serviceId: string, nameId: string): ng.IPromise { + const defer = this.$q.defer(); let promise = this.remoteSshAPI.getKeyPair({serviceId: serviceId, nameId: nameId}).$promise; - promise.then((sshKeyPair) => { + promise.then((sshKeyPair: any) => { this.sshKeyPairs.set(serviceId + '/' + nameId, sshKeyPair); defer.resolve(); - }, (error) => { - if (error.status != 304) { + }, (error: any) => { + if (error.status !== 304) { this.sshKeyPairs.delete(serviceId + '/' + nameId); defer.reject(error); } else { @@ -79,17 +77,30 @@ export class CheSsh { /** * Get ssh keypair - * @returns + * + * @param {string} serviceId + * @param {string} nameId + * @returns {angular.IPromise} */ - getKey(serviceId: string, nameId: string) { + getKey(serviceId: string, nameId: string): ng.IPromise { return this.sshKeyPairs.get(serviceId + '/' + nameId); } - removeKey(serviceId: string, nameId: string) { + /** + * @param {string} serviceId + * @param {string} nameId + * @returns {angular.IPromise} + */ + removeKey(serviceId: string, nameId: string): ng.IPromise { return this.remoteSshAPI.removeKey({serviceId: serviceId, nameId: nameId}).$promise; } - generateKey(serviceId: string, nameId: string) { + /** + * @param {string} serviceId + * @param {string} nameId + * @returns {angular.IPromise} + */ + generateKey(serviceId: string, nameId: string): ng.IPromise { return this.remoteSshAPI.generateKey({}, {service: serviceId, name: nameId}).$promise; } diff --git a/dashboard/src/components/api/che-stack.factory.ts b/dashboard/src/components/api/che-stack.factory.ts index 3ac1ce62b6..8f7628372d 100644 --- a/dashboard/src/components/api/che-stack.factory.ts +++ b/dashboard/src/components/api/che-stack.factory.ts @@ -51,7 +51,7 @@ export class CheStack { // remote call this.remoteStackAPI = >this.$resource('/api/stack', {}, { - getStacks: {method: 'GET', url: '/api/stack?maxItems=50', isArray: true}, //TODO 50 items is temp solution while paging is not added + getStacks: {method: 'GET', url: '/api/stack?maxItems=50', isArray: true}, // todo: 50 items is temp solution while paging is not added getStack: {method: 'GET', url: '/api/stack/:stackId'}, updateStack: {method: 'PUT', url: '/api/stack/:stackId'}, createStack: {method: 'POST', url: '/api/stack'}, @@ -64,7 +64,7 @@ export class CheStack { * @returns {che.IStack} */ getStackTemplate(): che.IStack { - let stack = { + let stack = { 'name': 'New Stack', 'description': 'New Java Stack', 'scope': 'general', @@ -78,7 +78,7 @@ export class CheStack { 'default': { 'machines': { 'dev-machine': { - 'agents': [ + 'installers': [ 'org.eclipse.che.exec', 'org.eclipse.che.terminal', 'org.eclipse.che.ws-agent', 'org.eclipse.che.ssh' ], 'servers': {}, @@ -96,7 +96,6 @@ export class CheStack { }, 'name': 'default', 'defaultEnv': 'default', - 'description': null, 'commands': [] } }; @@ -132,8 +131,10 @@ export class CheStack { let updatedPromise = promise.then((stacks: Array) => { // reset global stacks list this.stacks.length = 0; - for (let member: string in this.stacksById) { - delete this.stacksById[member]; + for (let member in this.stacksById) { + if (this.stacksById.hasOwnProperty(member)) { + delete this.stacksById[member]; + } } // reset global stack names list this.usedStackNames.length = 0; @@ -159,9 +160,9 @@ export class CheStack { /** * The stacks per id * @param id {string} - * @returns {stack: che.IStack} + * @returns {che.IStack} */ - getStackById(id: string): { stack: che.IStack } { + getStackById(id: string): che.IStack { return this.stacksById[id]; } @@ -202,5 +203,3 @@ export class CheStack { return this.remoteStackAPI.deleteStack({stackId: stackId}).$promise; } } - - diff --git a/dashboard/src/components/api/che-svn.spec.ts b/dashboard/src/components/api/che-svn.spec.ts index d1c555081d..d6201d563e 100644 --- a/dashboard/src/components/api/che-svn.spec.ts +++ b/dashboard/src/components/api/che-svn.spec.ts @@ -9,33 +9,31 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheWorkspace} from './workspace/che-workspace.factory'; +import {CheAPIBuilder} from './builder/che-api-builder.factory'; +import {CheHttpBackend} from './test/che-http-backend'; /** * Test of the CheSvn */ describe('CheSvn', function () { - /** - * User Factory for the test - */ - var factory; - /** * API builder. */ - var apiBuilder; + let apiBuilder; - var workspace; + let workspace; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * Che backend */ - var cheBackend; + let cheBackend; /** * setup module @@ -45,7 +43,9 @@ describe('CheSvn', function () { /** * Inject factory and http backend */ - beforeEach(inject(function (cheWorkspace, cheAPIBuilder, cheHttpBackend) { + beforeEach(inject(function (cheWorkspace: CheWorkspace, + cheAPIBuilder: CheAPIBuilder, + cheHttpBackend: CheHttpBackend) { workspace = cheWorkspace; apiBuilder = cheAPIBuilder; cheBackend = cheHttpBackend; diff --git a/dashboard/src/components/api/che-svn.ts b/dashboard/src/components/api/che-svn.ts index d950ee47f8..6dd3b04df1 100644 --- a/dashboard/src/components/api/che-svn.ts +++ b/dashboard/src/components/api/che-svn.ts @@ -15,12 +15,16 @@ * @author Oleksii Orel */ export class CheSvn { + private $resource: ng.resource.IResourceService; + private remoteUrlMap: Map; + private remoteSvnAPI: any; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($resource, wsagentPath) { + constructor($resource: ng.resource.IResourceService, + wsagentPath: string) { // keep resource this.$resource = $resource; @@ -35,20 +39,22 @@ export class CheSvn { /** * Ask for loading repository svn url for the given project - * @param workspaceId - * @param projectPath + * + * @param {string} workspaceId + * @param {string} projectPath + * @returns {angular.IPromise} */ - fetchRemoteUrl(workspaceId, projectPath) { - var data = {children: false, revision: 'HEAD', projectPath: projectPath, target: '.'}; + fetchRemoteUrl(workspaceId: string, projectPath: string): ng.IPromise { + const data = {children: false, revision: 'HEAD', projectPath: projectPath, target: '.'}; let promise = this.remoteSvnAPI.getRemoteUrl({ workspaceId: workspaceId }, data).$promise; // check if it was OK or not - let parsedResultPromise = promise.then((svnInfo) => { - if(svnInfo.items){ - svnInfo.items.forEach((item) => { + let parsedResultPromise = promise.then((svnInfo: any) => { + if (svnInfo.items) { + svnInfo.items.forEach((item: any) => { this.remoteUrlMap.set(workspaceId + projectPath, { name: item.path, url: item.uRL @@ -60,7 +66,7 @@ export class CheSvn { return parsedResultPromise; } - getRemoteUrlByKey(workspaceId, projectPath) { + getRemoteUrlByKey(workspaceId: string, projectPath: string): any { return this.remoteUrlMap.get(workspaceId + projectPath); } diff --git a/dashboard/src/components/api/che-team-events-manager.factory.ts b/dashboard/src/components/api/che-team-events-manager.factory.ts index 32d54c4419..fed2f4cddc 100644 --- a/dashboard/src/components/api/che-team-events-manager.factory.ts +++ b/dashboard/src/components/api/che-team-events-manager.factory.ts @@ -10,8 +10,12 @@ */ 'use strict'; -enum TEAM_EVENTS {MEMBER_ADDED, MEMBER_REMOVED, ORGANIZATION_REMOVED, ORGANIZATION_RENAMED} - +enum TEAM_EVENTS { + MEMBER_ADDED, + MEMBER_REMOVED, + ORGANIZATION_REMOVED, + ORGANIZATION_RENAMED +} /** * This class is handling the notifications per each team. @@ -59,11 +63,11 @@ export class CheTeamEventsManager implements che.api.ICheTeamEventsManager { let bus = this.cheWebsocket.getBus(); bus.subscribe(this.TEAM_CHANNEL + teamId, (message: any) => { // todo - switch (TEAM_EVENTS[message.type]) { - case TEAM_EVENTS.ORGANIZATION_RENAMED: + switch (message.type) { + case TEAM_EVENTS[TEAM_EVENTS.ORGANIZATION_RENAMED]: this.processRenameTeam(message); break; - case TEAM_EVENTS.ORGANIZATION_REMOVED: + case TEAM_EVENTS[TEAM_EVENTS.ORGANIZATION_REMOVED]: this.processDeleteTeam(message); break; default: @@ -89,11 +93,11 @@ export class CheTeamEventsManager implements che.api.ICheTeamEventsManager { let id = this.cheUser.getUser().id; let bus = this.cheWebsocket.getBus(); bus.subscribe(this.TEAM_MEMBER_CHANNEL + id, (message: any) => { - switch (TEAM_EVENTS[message.type]) { - case TEAM_EVENTS.MEMBER_ADDED: + switch (message.type) { + case TEAM_EVENTS[TEAM_EVENTS.MEMBER_ADDED]: this.processAddedToTeam(message); break; - case TEAM_EVENTS.MEMBER_REMOVED: + case TEAM_EVENTS[TEAM_EVENTS.MEMBER_REMOVED]: this.processDeleteMember(message); break; default: diff --git a/dashboard/src/components/api/che-team.factory.ts b/dashboard/src/components/api/che-team.factory.ts index e75f69ff95..eef31c815d 100644 --- a/dashboard/src/components/api/che-team.factory.ts +++ b/dashboard/src/components/api/che-team.factory.ts @@ -11,7 +11,6 @@ 'use strict'; import {CheTeamRoles} from './che-team-roles'; -import {CheResourceLimits} from './che-resource-limits'; import {CheTeamEventsManager} from './che-team-events-manager.factory'; interface ITeamsResource extends ng.resource.IResourceClass { @@ -71,12 +70,16 @@ export class CheTeam implements che.api.ICheTeam { */ private cheResourcesDistribution: che.api.ICheResourcesDistribution; + private resourceLimits: che.resource.ICheResourceLimits; + /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($resource: ng.resource.IResourceService, $q: ng.IQService, lodash: any, cheNamespaceRegistry: any, cheUser: any, - cheOrganization: che.api.ICheOrganization, cheTeamEventsManager: CheTeamEventsManager, cheResourcesDistribution: che.api.ICheResourcesDistribution) { + constructor($resource: ng.resource.IResourceService, + $q: ng.IQService, lodash: any, cheNamespaceRegistry: any, cheUser: any, + cheOrganization: che.api.ICheOrganization, cheTeamEventsManager: CheTeamEventsManager, cheResourcesDistribution: che.api.ICheResourcesDistribution, + resourcesService: che.service.IResourcesService) { this.$resource = $resource; this.$q = $q; this.lodash = lodash; @@ -85,6 +88,7 @@ export class CheTeam implements che.api.ICheTeam { this.teamEventsManager = cheTeamEventsManager; this.cheOrganization = cheOrganization; this.cheResourcesDistribution = cheResourcesDistribution; + this.resourceLimits = resourcesService.getResourceLimits(); this.remoteTeamAPI = >$resource('/api/organization', {}, { findTeam: {method: 'GET', url: '/api/organization/find?name=:teamName'} @@ -200,7 +204,7 @@ export class CheTeam implements che.api.ICheTeam { } return this.cheResourcesDistribution.fetchAvailableOrganizationResources(organization.id).then(() => { - let resource = this.cheResourcesDistribution.getOrganizationAvailableResourceByType(organization.id, CheResourceLimits.RAM); + let resource = this.cheResourcesDistribution.getOrganizationAvailableResourceByType(organization.id, this.resourceLimits.RAM); return resource ? 'Available RAM: ' + (resource.amount / 1024) + 'GB' : null; }); }); diff --git a/dashboard/src/components/api/che-websocket.factory.ts b/dashboard/src/components/api/che-websocket.factory.ts index 9d6fafb8f2..3c81360412 100644 --- a/dashboard/src/components/api/che-websocket.factory.ts +++ b/dashboard/src/components/api/che-websocket.factory.ts @@ -28,12 +28,17 @@ export class CheWebsocket { * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor ($websocket, $location, $interval : ng.IIntervalService, proxySettings : string, userDashboardConfig, keycloakAuth: any) { + constructor ($websocket: any, + $location: ng.ILocationService, + $interval: ng.IIntervalService, + proxySettings: string, + userDashboardConfig: any, + keycloakAuth: any) { this.$websocket = $websocket; this.$interval = $interval; - var wsUrl; + let wsUrl; let inDevMode = userDashboardConfig.developmentMode; if (inDevMode) { @@ -41,7 +46,7 @@ export class CheWebsocket { wsUrl = proxySettings.replace('http', 'ws') + '/api/ws'; } else { - var wsProtocol; + let wsProtocol; if ('http' === $location.protocol()) { wsProtocol = 'ws'; } else { @@ -60,11 +65,10 @@ export class CheWebsocket { return this.wsBaseUrl; } - getExistingBus(datastream) { + getExistingBus(datastream: any): MessageBus { return new MessageBus(datastream, this.$interval); } - getBus() : MessageBus { if (!this.bus) { // needs to initialize @@ -75,16 +79,16 @@ export class CheWebsocket { this.bus.closed = true; this.bus = null; } - ) + ); } return this.bus; } /** * Gets a bus for a remote workspace, by providing the remote URL to this websocket - * @param websocketURL the remote host base WS url + * @param {string} websocketURL the remote host base WS url */ - getRemoteBus(websocketURL) { + getRemoteBus(websocketURL: string): MessageBus { if (!this.remoteBus) { // needs to initialize this.remoteBus = new MessageBus(this.$websocket(websocketURL), this.$interval); @@ -94,7 +98,7 @@ export class CheWebsocket { this.remoteBus.closed = true; this.remoteBus = null; } - ) + ); } return this.remoteBus; } @@ -104,11 +108,11 @@ export class CheWebsocket { class MessageBuilder { - private static TYPE : string = 'x-everrest-websocket-message-type'; private method : string; private path : string; private message : any; + constructor(method? : string, path? : string) { if (method) { this.method = method; @@ -129,18 +133,18 @@ class MessageBuilder { this.message.method = this.method; this.message.path = this.path; this.message.headers = []; - this.message.body; + this.message.body = ''; } - subscribe(channel) { + subscribe(channel: any): MessageBuilder { let header = {name: MessageBuilder.TYPE, value: 'subscribe-channel'}; this.message.headers.push(header); this.message.body = JSON.stringify({channel: channel}); return this; } - unsubscribe(channel) { - let header = {name:MessageBuilder.TYPE, value: 'unsubscribe-channel'}; + unsubscribe(channel: any): MessageBuilder { + let header = {name: MessageBuilder.TYPE, value: 'unsubscribe-channel'}; this.message.headers.push(header); this.message.body = JSON.stringify({channel: channel}); return this; @@ -151,48 +155,49 @@ class MessageBuilder { * * @returns {MessageBuilder} */ - ping() { - let header = {name:MessageBuilder.TYPE, value: 'ping'}; + ping(): MessageBuilder { + let header = {name: MessageBuilder.TYPE, value: 'ping'}; this.message.headers.push(header); return this; } - build() { + build(): any { return this.message; } - buildUUID() { + buildUUID(): string { + /* tslint:disable */ let time = new Date().getTime(); - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (match) => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (match: string) => { let rem = (time + 16 * Math.random()) % 16 | 0; // jshint ignore:line time = Math.floor(time / 16); return (match === 'x' ? rem : rem & 7 | 8).toString(16); // jshint ignore:line }); + /* tslint:enable */ } - } export class MessageBus { - closed : boolean; - datastream : any; - private $interval : ng.IIntervalService; - private heartbeatPeriod : number; - private subscribersByChannel : Map; - private keepAlive : ng.IPromise; + closed: boolean; + datastream: any; + private $interval: ng.IIntervalService; + private heartbeatPeriod: number; + private subscribersByChannel: Map; + private keepAlive : ng.IPromise; - - constructor(datastream, $interval : ng.IIntervalService) { + constructor(datastream: any, + $interval: ng.IIntervalService) { this.datastream = datastream; this.$interval = $interval; - this.heartbeatPeriod = 1000 * 50; //ping each 50 seconds + this.heartbeatPeriod = 1000 * 50; // ping each 50 seconds this.subscribersByChannel = new Map(); this.setKeepAlive(); - this.datastream.onMessage((message) => {this.handleMessage(message);}); + this.datastream.onMessage((message: any) => { this.handleMessage(message); }); } public isClosed() : boolean { @@ -202,8 +207,8 @@ export class MessageBus { /** * Sets the keep alive interval, which sends * ping frame to server to keep connection alive. - * */ - setKeepAlive() { + */ + setKeepAlive(): void { this.keepAlive = this.$interval(() => { this.ping(); }, this.heartbeatPeriod); @@ -212,7 +217,7 @@ export class MessageBus { /** * Sends ping frame to server. */ - ping() { + ping(): void { this.send(new MessageBuilder().ping().build()); } @@ -221,7 +226,7 @@ export class MessageBus { * * @param callback */ - onClose(callback: Function) { + onClose(callback: Function): void { this.datastream.onClose(callback); } @@ -230,14 +235,14 @@ export class MessageBus { * * @param callback */ - onError(callback: Function) { + onError(callback: Function): void { this.datastream.onError(callback); } /** * Restart ping timer (cancel previous and start again). */ - restartPing () { + restartPing(): void { if (this.keepAlive) { this.$interval.cancel(this.keepAlive); } @@ -253,7 +258,7 @@ export class MessageBus { * to the server because the client has already a subscription, and merely registers * (client side) the additional handler to be fired for events received on the respective channel. */ - subscribe(channel, callback) { + subscribe(channel: any, callback: Function): void { // already subscribed ? let existingSubscribers = this.subscribersByChannel.get(channel); if (!existingSubscribers) { @@ -278,7 +283,7 @@ export class MessageBus { * If it's the last unsubscribe to a channel, a message is sent to the server to * unsubscribe the client for that channel. */ - unsubscribe(channel) { + unsubscribe(channel: any): void { // already subscribed ? let existingSubscribers = this.subscribersByChannel.get(channel); // unable to cancel if not existing channel @@ -288,7 +293,7 @@ export class MessageBus { if (existingSubscribers > 1) { // only remove callback - for(let i = 0; i < existingSubscribers.length; i++) { + for (let i = 0; i < existingSubscribers.length; i++) { delete existingSubscribers[i]; } } else { @@ -300,15 +305,12 @@ export class MessageBus { } } - - - send(message) { + send(message: any): void { let stringified = JSON.stringify(message); this.datastream.send(stringified); } - - handleMessage(message) { + handleMessage(message: any): void { // handling the receive of a message // needs to parse it let jsonMessage = JSON.parse(message.data); @@ -319,7 +321,7 @@ export class MessageBus { let channelHeader; // found channel headers - for(let i = 0; i < headers.length; i++) { + for (let i = 0; i < headers.length; i++) { let header = headers[i]; if ('x-everrest-websocket-channel' === header.name) { channelHeader = header; @@ -327,7 +329,7 @@ export class MessageBus { } // handle case when we don't have channel but a raw message - if (!channelHeader && headers.length == 1 && headers[0].name === 'x-everrest-websocket-message-type') { + if (!channelHeader && headers.length === 1 && headers[0].name === 'x-everrest-websocket-message-type') { channelHeader = headers[0]; } @@ -335,7 +337,7 @@ export class MessageBus { // message for a channel, look at current subscribers let subscribers = this.subscribersByChannel.get(channelHeader.value); if (subscribers) { - subscribers.forEach((subscriber) => { + subscribers.forEach((subscriber: any) => { try { subscriber(angular.fromJson(jsonMessage.body)); } catch (e) { @@ -345,7 +347,7 @@ export class MessageBus { } } - // Restart ping after received message + // restart ping after received message this.restartPing(); } diff --git a/dashboard/src/components/api/che-workspace-agent.ts b/dashboard/src/components/api/che-workspace-agent.ts index a03ba3c953..ef909571d9 100644 --- a/dashboard/src/components/api/che-workspace-agent.ts +++ b/dashboard/src/components/api/che-workspace-agent.ts @@ -42,7 +42,7 @@ export class CheWorkspaceAgent { /** * Default constructor that is using resource */ - constructor($resource: ng.resource.IResourceService, $q: ng.IQService, $websocket: ng.websocket.IWebSocketProvider, + constructor($resource: ng.resource.IResourceService, $q: ng.IQService, $websocket: any, workspaceAgentData: IWorkspaceAgentData) { this.$resource = $resource; this.workspaceAgentData = workspaceAgentData; diff --git a/dashboard/src/components/api/environment/compose-environment-manager.spec.ts b/dashboard/src/components/api/environment/compose-environment-manager.spec.ts index 1576b58d0b..360b9141e2 100644 --- a/dashboard/src/components/api/environment/compose-environment-manager.spec.ts +++ b/dashboard/src/components/api/environment/compose-environment-manager.spec.ts @@ -32,14 +32,18 @@ describe('ComposeEnvironmentManager', () => { 'another-machine': { 'attributes': {'memoryLimitBytes': '2147483648'}, 'servers': {}, - 'agents': [] + 'installers': [] + }, + 'db': { + 'attributes': {}, + 'servers': {}, + 'installers': [] }, - 'db': {'attributes': {}, 'servers': {}, 'installers': []}, 'dev-machine': { 'attributes': {'memoryLimitBytes': '5368709120'}, 'servers': { - '1024/tcp': {'port': '1024', 'properties': {}, 'protocol': 'http'}, - '1025/tcp': {'port': '1025', 'properties': {}, 'protocol': 'http'} + '1024/tcp': {'port': '1024', 'properties': {}, 'protocol': 'http', 'path': ''}, + '1025/tcp': {'port': '1025', 'properties': {}, 'protocol': 'http', 'path': ''} }, 'installers': ['org.eclipse.che.ws-agent', 'org.eclipse.che.terminal', 'org.eclipse.che.ssh'] } @@ -90,16 +94,16 @@ describe('ComposeEnvironmentManager', () => { 'another-machine': { 'attributes': {'memoryLimitBytes': '2147483648'}, 'servers': {}, - 'agents': [] + 'installers': [] }, - 'db': {'attributes': {}, 'servers': {}, 'agents': []}, + 'db': {'attributes': {}, 'servers': {}, 'installers': []}, 'dev-machine': { 'attributes': {'memoryLimitBytes': '5368709120'}, 'servers': { - '1024/tcp': {'port': '1024', 'properties': {}, 'protocol': 'http'}, - '1025/tcp': {'port': '1025', 'properties': {}, 'protocol': 'http'} + '1024/tcp': {'port': '1024', 'properties': {}, 'protocol': 'http', 'path': ''}, + '1025/tcp': {'port': '1025', 'properties': {}, 'protocol': 'http', 'path': ''} }, - 'agents': ['org.eclipse.che.ws-agent', 'org.eclipse.che.terminal', 'org.eclipse.che.ssh'] + 'installers': ['org.eclipse.che.ws-agent', 'org.eclipse.che.terminal', 'org.eclipse.che.ssh'] } }, 'recipe': { @@ -181,7 +185,7 @@ describe('ComposeEnvironmentManager', () => { 'machines': { 'dev-machine': { 'servers': {}, - 'agents': ['org.eclipse.che.ws-agent', 'org.eclipse.che.terminal', 'org.eclipse.che.ssh'], + 'installers': ['org.eclipse.che.ws-agent', 'org.eclipse.che.terminal', 'org.eclipse.che.ssh'], 'attributes': {'memoryLimitBytes': '2147483648'} } }, diff --git a/dashboard/src/components/api/environment/docker-image-environment-manager.spec.ts b/dashboard/src/components/api/environment/docker-image-environment-manager.spec.ts index 48f300ce08..b1b441d5c2 100644 --- a/dashboard/src/components/api/environment/docker-image-environment-manager.spec.ts +++ b/dashboard/src/components/api/environment/docker-image-environment-manager.spec.ts @@ -11,7 +11,6 @@ 'use strict'; import {DockerImageEnvironmentManager} from './docker-image-environment-manager'; -import IWorkspaceEnvironment = _che.IWorkspaceEnvironment; import {IEnvironmentManagerMachine, IEnvironmentManagerMachineServer} from './environment-manager-machine'; /** @@ -20,7 +19,7 @@ import {IEnvironmentManagerMachine, IEnvironmentManagerMachineServer} from './en */ describe('DockerImageEnvironmentManager', () => { - let envManager: DockerImageEnvironmentManager, environment: IWorkspaceEnvironment, machines: IEnvironmentManagerMachine[]; + let envManager: DockerImageEnvironmentManager, environment: che.IWorkspaceEnvironment, machines: IEnvironmentManagerMachine[]; beforeEach(inject(($log: ng.ILogService) => { envManager = new DockerImageEnvironmentManager($log); @@ -32,7 +31,8 @@ describe('DockerImageEnvironmentManager', () => { '10240/tcp': { 'properties': {}, 'protocol': 'http', - 'port': '10240' + 'port': '10240', + 'path': '' } }, 'installers': ['ws-agent', 'org.eclipse.che.ws-agent'], 'attributes': {'memoryLimitBytes': '16642998272'} } @@ -58,9 +58,9 @@ describe('DockerImageEnvironmentManager', () => { it('should return servers', () => { let servers = envManager.getServers(machines[0]); - let expectedServers = environment.machines['dev-machine'].servers; + let expectedServers = environment.machines['dev-machine'].servers; Object.keys(expectedServers).forEach((serverRef: string) => { - expectedServers[serverRef].userScope = true; + (expectedServers[serverRef] as IEnvironmentManagerMachineServer).userScope = true; }); expect(servers).toEqual(expectedServers); diff --git a/dashboard/src/components/api/json-rpc/che-json-rpc-api.factory.ts b/dashboard/src/components/api/json-rpc/che-json-rpc-api.factory.ts index be1eb2b8e6..c3780f45b5 100644 --- a/dashboard/src/components/api/json-rpc/che-json-rpc-api.factory.ts +++ b/dashboard/src/components/api/json-rpc/che-json-rpc-api.factory.ts @@ -20,7 +20,7 @@ import {WebsocketClient} from './websocket-client'; */ export class CheJsonRpcApi { private $q: ng.IQService; - private $websocket: ng.websocket.IWebSocketProvider; + private $websocket: any; private $log: ng.ILogService; private jsonRpcApiConnection: Map; @@ -28,7 +28,7 @@ export class CheJsonRpcApi { * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($q: ng.IQService, $websocket: ng.websocket.IWebSocketProvider, $log: ng.ILogService) { + constructor($q: ng.IQService, $websocket: any, $log: ng.ILogService) { this.$q = $q; this.$websocket = $websocket; this.$log = $log; diff --git a/dashboard/src/components/api/json-rpc/che-json-rpc-master-api.ts b/dashboard/src/components/api/json-rpc/che-json-rpc-master-api.ts index 9e4ebc6f40..b3cee84779 100644 --- a/dashboard/src/components/api/json-rpc/che-json-rpc-master-api.ts +++ b/dashboard/src/components/api/json-rpc/che-json-rpc-master-api.ts @@ -9,7 +9,7 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; -import {CheJsonRpcApiClient, IChannel} from './che-json-rpc-api-service'; +import {CheJsonRpcApiClient} from './che-json-rpc-api-service'; import {ICommunicationClient} from './json-rpc-client'; enum MasterChannels { diff --git a/dashboard/src/components/api/json-rpc/websocket-client.ts b/dashboard/src/components/api/json-rpc/websocket-client.ts index b0c499ea33..6431a5bab9 100644 --- a/dashboard/src/components/api/json-rpc/websocket-client.ts +++ b/dashboard/src/components/api/json-rpc/websocket-client.ts @@ -18,11 +18,11 @@ import {ICommunicationClient} from './json-rpc-client'; */ export class WebsocketClient implements ICommunicationClient { onResponse: Function; - private $websocket: ng.websocket.IWebSocketProvider; + private $websocket: any; private $q: ng.IQService; private websocketStream; - constructor ($websocket: ng.websocket.IWebSocketProvider, $q: ng.IQService) { + constructor ($websocket: any, $q: ng.IQService) { this.$websocket = $websocket; this.$q = $q; } diff --git a/dashboard/src/components/api/project/che-type-resolver.spec.ts b/dashboard/src/components/api/project/che-type-resolver.spec.ts index 240bc8bd57..123490b152 100644 --- a/dashboard/src/components/api/project/che-type-resolver.spec.ts +++ b/dashboard/src/components/api/project/che-type-resolver.spec.ts @@ -273,6 +273,7 @@ describe('CheTypeResolver', () => { path: '/test-application', type: 'blank', description: 'A hello world test application.', + source: {} as che.IProjectSource, attributes: {} } }; diff --git a/dashboard/src/components/api/project/che-type-resolver.ts b/dashboard/src/components/api/project/che-type-resolver.ts index df1e8a0ddb..9c4b58ec1b 100644 --- a/dashboard/src/components/api/project/che-type-resolver.ts +++ b/dashboard/src/components/api/project/che-type-resolver.ts @@ -40,7 +40,7 @@ export class CheTypeResolver { * Fetch project types if it empty. * @returns {ng.IPromise} */ - fetchTypes(): ng.IPromise> { + fetchTypes(): ng.IPromise { let deferredResolve = this.$q.defer(); if (this.typesIds.size) { deferredResolve.resolve(); @@ -60,16 +60,16 @@ export class CheTypeResolver { * @returns {ng.IPromise} */ resolveImportProjectType(projectData: che.IImportProject): ng.IPromise { - let projectDetails: che.IProject = this.getProjectDetails(projectData); + let projectDetails = this.getProjectDetails(projectData); return this.resolveProjectType(projectDetails); } /** * Resolve type for project. - * @param projectDetails{che.IProject} + * @param projectDetails{che.IProjectTemplate} * @returns {ng.IPromise} */ - resolveProjectType(projectDetails: che.IProject): ng.IPromise { + resolveProjectType(projectDetails: che.IProjectTemplate): ng.IPromise { return this.fetchTypes().then(() => { return this.autoCheckType(projectDetails, this.typesIds); }).then((projectDetails: che.IProject) => { @@ -80,10 +80,10 @@ export class CheTypeResolver { /** * Gets project details from import project object. * @param projectData{che.IImportProject} - * @returns {che.IProject} + * @returns {che.IProjectTemplate} */ - getProjectDetails(projectData: che.IImportProject): che.IProject { - let projectDetails: che.IProject = projectData.project; + getProjectDetails(projectData: che.IImportProject): che.IProjectTemplate { + let projectDetails = projectData.project; projectDetails.source = projectData.source; if (!projectDetails.attributes) { projectDetails.attributes = {}; @@ -93,11 +93,11 @@ export class CheTypeResolver { /** * Check project type and auto select one if needed. - * @param project{che.IProject} + * @param project{che.IProjectTemplate} * @param projectTypesByCategory{Map} * @returns {ng.IPromise} */ - autoCheckType(project: che.IProject, projectTypesByCategory: Map): ng.IPromise { + autoCheckType(project: che.IProjectTemplate, projectTypesByCategory: Map): ng.IPromise { let deferredResolve = this.$q.defer(); let projectDetails = angular.copy(project); diff --git a/dashboard/src/components/api/remote/che-remote-login.ts b/dashboard/src/components/api/remote/che-remote-login.ts index 60cd0720cf..9ca0c22d3d 100644 --- a/dashboard/src/components/api/remote/che-remote-login.ts +++ b/dashboard/src/components/api/remote/che-remote-login.ts @@ -15,13 +15,17 @@ * @author Florent Benoit */ export class CheRemoteLogin { + $resource: ng.resource.IResourceService; + url: string; + remoteAuthAPI: any; /** * Default constructor using angular $resource and remote URL * @param $resource the angular $resource object * @param url the remote server URL */ - constructor($resource, url) { + constructor($resource: ng.resource.IResourceService, + url: string) { this.$resource = $resource; this.url = url; this.remoteAuthAPI = this.$resource('', {}, { @@ -33,13 +37,13 @@ export class CheRemoteLogin { * Authenticate on the remote URL the provided username/password * @param login the login on remote URL * @param password the password on remote URL - * @returns {*|promise|N|n} + * @returns {ng.IPromise} */ - authenticate(login, password) { + authenticate(login: string, password: string): ng.IPromise { let authData = {username: login, password: password}; let call = this.remoteAuthAPI.auth(authData); let promise = call.$promise; - return promise.then((result)=> { + return promise.then((result: any) => { let token = result.value; return {'url': this.url, 'token': token}; }); diff --git a/dashboard/src/components/api/remote/che-remote-project.ts b/dashboard/src/components/api/remote/che-remote-project.ts index c414971380..bcb40f87f0 100644 --- a/dashboard/src/components/api/remote/che-remote-project.ts +++ b/dashboard/src/components/api/remote/che-remote-project.ts @@ -15,11 +15,15 @@ * @author Florent Benoit */ export class CheRemoteProject { + $resource: ng.resource.IResourceService; + authData: any; + remoteProjectsAPI: any; /** * Default constructor that is using resource */ - constructor($resource, authData) { + constructor($resource: ng.resource.IResourceService, + authData: any) { this.$resource = $resource; this.authData = authData; @@ -31,14 +35,13 @@ export class CheRemoteProject { } - /** * Import a project based located on the given path - * @param path the path of the project - * @param data the project body description - * @returns {$promise|*|T.$promise} + * @param {string} path the path of the project + * @param {any} data the project body description + * @returns {ng.IPromise} */ - importProject(path, data) { + importProject(path: string, data: any): ng.IPromise { // remove unused description because we cannot set project description without project type if ((!data.type || data.type.length === 0) && data.description) { delete(data.description); @@ -46,12 +49,10 @@ export class CheRemoteProject { return this.remoteProjectsAPI.import({path: path}, data).$promise; } - - updateProject(path, projectDetails) { + updateProject(path: string, projectDetails: any): ng.IPromise { return this.remoteProjectsAPI.update({ path: path }, projectDetails).$promise; } - } diff --git a/dashboard/src/components/api/remote/che-remote-recipe.ts b/dashboard/src/components/api/remote/che-remote-recipe.ts index df06744b9d..dadd83b373 100644 --- a/dashboard/src/components/api/remote/che-remote-recipe.ts +++ b/dashboard/src/components/api/remote/che-remote-recipe.ts @@ -15,28 +15,30 @@ * @author Florent Benoit */ export class CheRemoteRecipe { + $resource: ng.resource.IResourceService; + authData: any; + remoteRecipesAPI: any; /** * Default constructor that is using resource */ - constructor($resource, authData) { + constructor($resource: ng.resource.IResourceService, + authData: any) { this.$resource = $resource; this.authData = authData; - // remote call - this.remoteRecipesAPI = this.$resource('',{}, { - create: {method: 'POST', url: authData.url + '/api/recipe?token=' + authData.token}, + this.remoteRecipesAPI = this.$resource('', {}, { + create: {method: 'POST', url: authData.url + '/api/recipe?token=' + authData.token} }); - } /** * Create a recipe - * @param recipe the recipe to create - * @returns {*} + * @param {any} recipe the recipe to create + * @returns {ng.IPromise} */ - create(recipe) { + create(recipe: any): ng.IPromise { return this.remoteRecipesAPI.create(recipe).$promise; } diff --git a/dashboard/src/components/api/test/che-http-backend-provider.factory.ts b/dashboard/src/components/api/test/che-http-backend-provider.factory.ts index 547021eaf6..e540ff0c8f 100644 --- a/dashboard/src/components/api/test/che-http-backend-provider.factory.ts +++ b/dashboard/src/components/api/test/che-http-backend-provider.factory.ts @@ -11,6 +11,7 @@ 'use strict'; import {CheHttpBackend} from './che-http-backend'; +import {CheAPIBuilder} from '../builder/che-api-builder.factory'; /** * This class is providing helper methods for simulating a fake HTTP backend simulating @@ -20,22 +21,19 @@ export class CheHttpBackendProviderFactory { /** * Build a new Che backend based on the given http backend. - * @param $httpBackend the backend on which to add calls + * @param {ng.IHttpBackendService} $httpBackend the backend on which to add calls + * @param {CheAPIBuilder} cheAPIBuilder * @returns {CheHttpBackend} the new instance */ - buildBackend($httpBackend, cheAPIBuilder) { + buildBackend($httpBackend: ng.IHttpBackendService, cheAPIBuilder: CheAPIBuilder) { // first, add pass through $httpBackend.whenGET(new RegExp('components.*')).passThrough(); $httpBackend.whenGET(new RegExp('^app.*')).passThrough(); - // return instance return new CheHttpBackend($httpBackend, cheAPIBuilder); - - } - } diff --git a/dashboard/src/components/api/test/che-http-backend.factory.ts b/dashboard/src/components/api/test/che-http-backend.factory.ts index 2bf5158a1c..6845c87edc 100644 --- a/dashboard/src/components/api/test/che-http-backend.factory.ts +++ b/dashboard/src/components/api/test/che-http-backend.factory.ts @@ -10,9 +10,8 @@ */ 'use strict'; - import {CheHttpBackend} from './che-http-backend'; - +import {CheAPIBuilder} from '../builder/che-api-builder.factory'; /** * This class is providing helper methods for simulating a fake HTTP backend simulating @@ -24,7 +23,8 @@ export class CheHttpBackendFactory extends CheHttpBackend { * Default constructor * @ngInject for Dependency injection */ - constructor($httpBackend, cheAPIBuilder) { + constructor($httpBackend: ng.IHttpBackendService, + cheAPIBuilder: CheAPIBuilder) { super($httpBackend, cheAPIBuilder); } diff --git a/dashboard/src/components/api/workspace/che-workspace.factory.ts b/dashboard/src/components/api/workspace/che-workspace.factory.ts index c9919bd12b..0797725715 100644 --- a/dashboard/src/components/api/workspace/che-workspace.factory.ts +++ b/dashboard/src/components/api/workspace/che-workspace.factory.ts @@ -56,7 +56,7 @@ export class CheWorkspace { private $http: ng.IHttpService; private $q: ng.IQService; private $log: ng.ILogService; - private $websocket: ng.websocket.IWebSocketProvider; + private $websocket: any; private cheJsonRpcMasterApi: CheJsonRpcMasterApi; private listeners: Array; private workspaceStatuses: Array; @@ -85,7 +85,7 @@ export class CheWorkspace { * @ngInject for Dependency injection */ constructor($resource: ng.resource.IResourceService, $http: ng.IHttpService, $q: ng.IQService, cheJsonRpcApi: CheJsonRpcApi, - $websocket: ng.websocket.IWebSocketProvider, $location: ng.ILocationService, proxySettings : string, userDashboardConfig: any, + $websocket: any, $location: ng.ILocationService, proxySettings : string, userDashboardConfig: any, lodash: any, cheEnvironmentRegistry: CheEnvironmentRegistry, $log: ng.ILogService, cheBranding: CheBranding, keycloakAuth: any) { this.workspaceStatuses = ['RUNNING', 'STOPPED', 'PAUSED', 'STARTING', 'STOPPING', 'ERROR']; // keep resource diff --git a/dashboard/src/components/api/workspace/che-workspace.spec.ts b/dashboard/src/components/api/workspace/che-workspace.spec.ts index d87faf07fc..de5e2b34af 100644 --- a/dashboard/src/components/api/workspace/che-workspace.spec.ts +++ b/dashboard/src/components/api/workspace/che-workspace.spec.ts @@ -21,22 +21,22 @@ describe('CheWorkspace', () => { /** * Workspace Factory for the test */ - var factory; + let factory; /** * API builder. */ - var apiBuilder; + let apiBuilder; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * Che backend */ - var cheBackend; + let cheBackend; /** * Listener used for the tests diff --git a/dashboard/src/components/attribute/click/che-on-right-click.directive.ts b/dashboard/src/components/attribute/click/che-on-right-click.directive.ts index 42c8b353d8..6d265b7539 100644 --- a/dashboard/src/components/attribute/click/che-on-right-click.directive.ts +++ b/dashboard/src/components/attribute/click/che-on-right-click.directive.ts @@ -10,6 +10,10 @@ */ 'use strict'; +interface ICheOnRightClickAttributes extends ng.IAttributes { + cheOnRightClick: () => void; +} + /** * @ngdoc directive * @name components.directive:cheOnRightClick @@ -25,26 +29,19 @@ * * @author Oleksii Kurinnyi */ -export class CheOnRightClick { - - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor() { - this.restrict = 'A'; - } +export class CheOnRightClick implements ng.IDirective { + restrict = 'A'; /** * Keep reference to the model controller */ - link($scope, $element, attrs) { - $element.bind('contextmenu', (event) => { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ICheOnRightClickAttributes): void { + $element.on('contextmenu', (event: JQueryEventObject) => { event.stopPropagation(); event.preventDefault(); $scope.$apply(() => { - $scope.$eval(attrs.cheOnRightClick); + $scope.$eval($attrs.cheOnRightClick); }); }); } diff --git a/dashboard/src/components/attribute/clip-the-middle/che-clip-the-middle.directive.ts b/dashboard/src/components/attribute/clip-the-middle/che-clip-the-middle.directive.ts index 2ea94a26aa..d4ad195bae 100644 --- a/dashboard/src/components/attribute/clip-the-middle/che-clip-the-middle.directive.ts +++ b/dashboard/src/components/attribute/clip-the-middle/che-clip-the-middle.directive.ts @@ -10,6 +10,10 @@ */ 'use strict'; +interface ICheClipTheMiddleAttributes extends ng.IAttributes { + str: string; +} + /** * @ngdoc directive * @name components.directive:cheClipTheMiddle @@ -30,7 +34,7 @@ export class CheClipTheMiddle implements ng.IDirective { restrict: string = 'AE'; replace: boolean = true; - template($element: ng.IAugmentedJQuery): void { + template($element: ng.IAugmentedJQuery): string { const str = $element.text(); return `
@@ -40,7 +44,7 @@ export class CheClipTheMiddle implements ng.IDirective { `; } - link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ng.IAttributes): void { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ICheClipTheMiddleAttributes): void { const str = $attrs.str, strStart = str.substr(0, str.length - 3), strEnd = str.substr(str.length - 3, 3); diff --git a/dashboard/src/components/attribute/focusable/che-focusable.directive.ts b/dashboard/src/components/attribute/focusable/che-focusable.directive.ts index 9441808f25..21cb2d7c1c 100644 --- a/dashboard/src/components/attribute/focusable/che-focusable.directive.ts +++ b/dashboard/src/components/attribute/focusable/che-focusable.directive.ts @@ -10,29 +10,27 @@ */ 'use strict'; +interface ICheFocusableAttributes extends ng.IAttributes { + focusable: boolean; +} + /** * Defines a directive for creating focusable attribute. * @author Oleksii Orel */ -export class CheFocusable { +export class CheFocusable implements ng.IDirective { - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor() { - this.restrict = 'A'; - } + restrict = 'A'; /** * Keep reference to the model controller */ - link($scope, element, attr) { - $scope.$watch(attr.focusable, function (newVal) { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ICheFocusableAttributes): void { + $scope.$watch(() => { return $attrs.focusable; }, (newVal: boolean) => { if (!newVal) { return; } - element.eq(0).focus(); + $element.eq(0).focus(); }); } } diff --git a/dashboard/src/components/attribute/format-output/che-format-output.directive.ts b/dashboard/src/components/attribute/format-output/che-format-output.directive.ts index fd91e1fe21..a337325f40 100644 --- a/dashboard/src/components/attribute/format-output/che-format-output.directive.ts +++ b/dashboard/src/components/attribute/format-output/che-format-output.directive.ts @@ -10,18 +10,26 @@ */ 'use strict'; +interface ICheFormatOutputAttributes extends ng.IAttributes { + ngModel: string; +} + /** * Defines a directive for formatting output. * @author Ann Shumilova */ -export class CheFormatOutput { +export class CheFormatOutput implements ng.IDirective { + restrict = 'A'; + + outputColors: any; + $compile: ng.ICompileService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor(jsonOutputColors, $compile) { - this.restrict = 'A'; + constructor(jsonOutputColors: string, + $compile: ng.ICompileService) { this.outputColors = angular.fromJson(jsonOutputColors); this.$compile = $compile; } @@ -29,22 +37,23 @@ export class CheFormatOutput { /** * Keep reference to the model controller */ - link($scope, element, attr) { - $scope.$watch(attr.ngModel, (value) => { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ICheFormatOutputAttributes): void { + $scope.$watch(() => { return $attrs.ngModel; }, (value: string) => { if (!value || value.length === 0) { return; } - var regExp = new RegExp('\n', 'g'); - var result = value.replace(regExp, '
') + let regExp = new RegExp('\n', 'g'); + let result = value.replace(regExp, '
'); - this.outputColors.forEach((outputColor) => { + this.outputColors.forEach((outputColor: any) => { regExp = new RegExp('\\[\\s*' + outputColor.type + '\\s*\\]', 'g'); - result = result.replace(regExp, '[' + outputColor.type + ']') + result = result.replace(regExp, '[' + outputColor.type + ']'); }); result = '' + result + ''; - element.html(this.$compile(result)($scope)); + + $element.html(this.$compile(result)($scope).html()); }); } } diff --git a/dashboard/src/components/attribute/img-src/img-src.directive.ts b/dashboard/src/components/attribute/img-src/img-src.directive.ts index 7807157503..d3b96154d7 100644 --- a/dashboard/src/components/attribute/img-src/img-src.directive.ts +++ b/dashboard/src/components/attribute/img-src/img-src.directive.ts @@ -11,7 +11,7 @@ 'use strict'; /** - * todo + * Fetches images using the $http service. * * @author Oleksii Kurinnyi */ @@ -25,7 +25,7 @@ export class ImgSrc implements ng.IDirective { * Default constructor that is using resource injection * @ngInject for Dependency injection */ - constructor($http: ng.IHttpService, userDashboardConfig) { + constructor($http: ng.IHttpService, userDashboardConfig: any) { this.$http = $http; this.isDev = userDashboardConfig.developmentMode; } @@ -43,7 +43,7 @@ export class ImgSrc implements ng.IDirective { }; this.$http(requestConfig).then((response: any) => { const blob = new Blob([response.data], {type: response.headers('Content-Type')}); - $attrs.$set('src', (window.URL || window.webkitURL).createObjectURL(blob)) + $attrs.$set('src', (window.URL || (window as any).webkitURL).createObjectURL(blob)); }); }); } diff --git a/dashboard/src/components/attribute/input-type/input-type.directive.ts b/dashboard/src/components/attribute/input-type/input-type.directive.ts index 7b3a654cdf..f8d3f06d62 100644 --- a/dashboard/src/components/attribute/input-type/input-type.directive.ts +++ b/dashboard/src/components/attribute/input-type/input-type.directive.ts @@ -14,12 +14,12 @@ * Defines a directive to allow to enter only specified subset of symbols. * @author Oleksii Kurinnyi */ -export abstract class CheInputType { - private restrict: string = 'A'; +export abstract class CheInputType implements ng.IDirective { + restrict: string = 'A'; - link($scope: ng.IScope, $element: ng.IAugmentedJQuery, attrs: {cheInputType: string, [prop: string]: string}): void { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery): void { - $element.on('keydown', (event: KeyboardEvent) => { + $element.on('keydown', (event: JQueryEventObject) => { // escape, enter, tab if (event.keyCode === 27 || event.keyCode === 13 || event.keyCode === 9) { return true; diff --git a/dashboard/src/components/attribute/multi-transclude/che-multi-transclude.directive.spec.ts b/dashboard/src/components/attribute/multi-transclude/che-multi-transclude.directive.spec.ts index 55798e1859..a8d39bafc7 100644 --- a/dashboard/src/components/attribute/multi-transclude/che-multi-transclude.directive.spec.ts +++ b/dashboard/src/components/attribute/multi-transclude/che-multi-transclude.directive.spec.ts @@ -54,23 +54,21 @@ describe('CheMultiTransclude >', () => { const part2 = ''; function getCompiledElement() { - const element = $compile( - angular.element( - `
-
-
-
-
-
` - ), function($scope: ng.IScope, cloneAttachFn: ng.ICloneAttachFunction): ng.IAugmentedJQuery { - const transcludingContent: ng.IAugmentedJQuery = angular.element( + const transcludeFunc = function ($scope: ng.IScope, $cloneAttachFn: ng.ICloneAttachFunction): ng.IAugmentedJQuery { + const transcludingContent = angular.element( `
${part1}
${part2}
` ); - cloneAttachFn(transcludingContent, $scope); + $cloneAttachFn(transcludingContent, $scope); return transcludingContent; - } - )($rootScope); + }, + element = $compile( + angular.element( + `
+
+
+
` + ), transcludeFunc as ng.ITranscludeFunction)($rootScope); $rootScope.$digest(); return element; } diff --git a/dashboard/src/components/attribute/reload-href/che-reload-href.directive.ts b/dashboard/src/components/attribute/reload-href/che-reload-href.directive.ts index 72ffaac6da..6fa78f5d7c 100644 --- a/dashboard/src/components/attribute/reload-href/che-reload-href.directive.ts +++ b/dashboard/src/components/attribute/reload-href/che-reload-href.directive.ts @@ -10,6 +10,10 @@ */ 'use strict'; +interface ICheReloadHrefAttributes extends ng.IAttributes { + href: string; +} + /** * @ngdoc directive * @name components.directive:cheReloadHref @@ -25,32 +29,37 @@ * * @author Florent Benoit */ -export class CheReloadHref { +export class CheReloadHref implements ng.IDirective { + restrict = 'A'; - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor($location, $route) { - this.restrict = 'A'; - this.$location = $location; - this.$route = $route; - } + $location: ng.ILocationService; + $route: ng.route.IRouteService; - /** - * Keep reference to the model controller - */ - link($scope, element, attr) { - if (attr.href) { - element.bind('click', () => { - $scope.$apply(() => { - if (this.$location.path() === attr.href || ('#' + this.$location.path()) === attr.href) { - console.log('reloading the route...'); - this.$route.reload(); - } - }); - }); - } + /** + * Default constructor that is using resource + * @ngInject for Dependency injection + */ + constructor($location: ng.ILocationService, + $route: ng.route.IRouteService) { + this.restrict = 'A'; + this.$location = $location; + this.$route = $route; + } + + /** + * Keep reference to the model controller + */ + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ICheReloadHrefAttributes) { + if ($attrs.href) { + $element.bind('click', () => { + $scope.$apply(() => { + if (this.$location.path() === $attrs.href || ('#' + this.$location.path()) === $attrs.href) { + console.log('reloading the route...'); + this.$route.reload(); + } + }); + }); } + } } diff --git a/dashboard/src/components/attribute/scroll/che-automatic-scroll.directive.ts b/dashboard/src/components/attribute/scroll/che-automatic-scroll.directive.ts index 3552debe2e..e525af77a4 100644 --- a/dashboard/src/components/attribute/scroll/che-automatic-scroll.directive.ts +++ b/dashboard/src/components/attribute/scroll/che-automatic-scroll.directive.ts @@ -10,6 +10,10 @@ */ 'use strict'; +interface ICheAutoScrollAttributes extends ng.IAttributes { + ngModel: any; +} + /** * @ngdoc directive * @name components.directive:cheAutoScroll @@ -26,25 +30,27 @@ * @author Florent Benoit */ export class CheAutoScroll { + restrict = 'A'; - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor($timeout) { - this.$timeout = $timeout; - this.restrict = 'A'; - } + $timeout: ng.ITimeoutService; - /** - * Keep reference to the model controller - */ - link($scope, element, attr) { - $scope.$watch(attr.ngModel, () => { - this.$timeout(() => { - element[0].scrollTop = element[0].scrollHeight; - }); - }, true); - } + /** + * Default constructor that is using resource + * @ngInject for Dependency injection + */ + constructor($timeout: ng.ITimeoutService) { + this.$timeout = $timeout; + } + + /** + * Keep reference to the model controller + */ + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ICheAutoScrollAttributes) { + $scope.$watch($attrs.ngModel, () => { + this.$timeout(() => { + $element[0].scrollTop = $element[0].scrollHeight; + }); + }, true); + } } diff --git a/dashboard/src/components/attribute/scroll/che-list-on-scroll-bottom.directive.ts b/dashboard/src/components/attribute/scroll/che-list-on-scroll-bottom.directive.ts index 8e9d35601b..81dde0435b 100644 --- a/dashboard/src/components/attribute/scroll/che-list-on-scroll-bottom.directive.ts +++ b/dashboard/src/components/attribute/scroll/che-list-on-scroll-bottom.directive.ts @@ -10,27 +10,25 @@ */ 'use strict'; +interface ICheListOnScrollBottomAttributes extends ng.IAttributes { + cheListOnScrollBottom: any; +} + /** * Defines a directive for a scrolled to bottom list event. * @author Michail Kuznyetsov */ export class CheListOnScrollBottom { - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor () { - this.restrict='A'; - } + restrict = 'A'; /** * Check if scroll has reached the bottom */ - link(scope, element, attrs) { - var raw = element[0]; - element.bind('scroll', function () { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ICheListOnScrollBottomAttributes) { + const raw = $element[0]; + $element.bind('scroll', function () { if (raw.scrollTop + raw.offsetHeight - raw.scrollHeight >= 0) { - scope.$apply(attrs.cheListOnScrollBottom); + $scope.$apply($attrs.cheListOnScrollBottom); } }); } diff --git a/dashboard/src/components/attribute/touch/che-on-long-touch.directive.ts b/dashboard/src/components/attribute/touch/che-on-long-touch.directive.ts index 811a318651..93a9e0a498 100644 --- a/dashboard/src/components/attribute/touch/che-on-long-touch.directive.ts +++ b/dashboard/src/components/attribute/touch/che-on-long-touch.directive.ts @@ -10,6 +10,14 @@ */ 'use strict'; +interface ICheLongTouchScope extends ng.IScope { + longTouch: boolean; +} + +interface ICheOnLongTouchAttributes extends ng.IAttributes { + cheOnLongTouch: any; +} + /** * @ngdoc directive * @name components.directive:cheOnLongTouch @@ -26,37 +34,38 @@ * @author Oleksii Kurinnyi */ export class CheOnLongTouch { + restrict = 'A'; + + $timeout: ng.ITimeoutService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($timeout) { + constructor($timeout: ng.ITimeoutService) { this.$timeout = $timeout; - - this.restrict = 'A'; } /** * Keep reference to the model controller */ - link($scope, element, attrs) { + link($scope: ICheLongTouchScope, $element: ng.IAugmentedJQuery, $attrs: ICheOnLongTouchAttributes) { $scope.longTouch = false; - element.on('touchstart mousedown', (event) => { + $element.on('touchstart mousedown', (event: JQueryEventObject) => { $scope.longTouch = true; this.$timeout(() => { if ($scope.longTouch && event.which !== 3) { - element.mouseup(); + $element.mouseup(); $scope.$apply(() => { - $scope.$eval(attrs.cheOnLongTouch); + $scope.$eval($attrs.cheOnLongTouch); $scope.longTouch = false; }); } }, 500); }); - element.on('touchend mouseup', () => { + $element.on('touchend mouseup', () => { $scope.longTouch = false; }); } diff --git a/dashboard/src/components/branding/che-branding-config.ts b/dashboard/src/components/branding/che-branding-config.ts index f0853b5766..89817ae9d2 100644 --- a/dashboard/src/components/branding/che-branding-config.ts +++ b/dashboard/src/components/branding/che-branding-config.ts @@ -14,8 +14,8 @@ import {CheBranding} from './che-branding.factory'; export class CheBrandingConfig { - constructor(register) { - // Register this factory + constructor(register: che.IRegisterService) { + // register this factory register.factory('cheBranding', CheBranding); } diff --git a/dashboard/src/components/codemirror/codemirror.ts b/dashboard/src/components/codemirror/codemirror.ts index e4440e4586..9c2e57e83c 100644 --- a/dashboard/src/components/codemirror/codemirror.ts +++ b/dashboard/src/components/codemirror/codemirror.ts @@ -10,6 +10,8 @@ */ 'use strict'; +declare const uiCodemirrorDirective: any; + export class CodeMirrorConstant { constructor(register: che.IRegisterService) { diff --git a/dashboard/src/components/components-config.ts b/dashboard/src/components/components-config.ts index 76f1ad9459..31b75615b0 100644 --- a/dashboard/src/components/components-config.ts +++ b/dashboard/src/components/components-config.ts @@ -32,6 +32,7 @@ import {InterceptorConfig} from './interceptor/interceptor-config'; export class ComponentsConfig { constructor(register: che.IRegisterService) { + /* tslint:disable */ new ApiConfig(register); new AttributeConfig(register); new FilterConfig(register); @@ -45,8 +46,8 @@ export class ComponentsConfig { new WidgetConfig(register); new CheErrorMessagesConfig(register); new ServiceConfig(register); - new InterceptorConfig(register); + /* tslint:enable */ register.directive('cheStepsContainer', CheStepsContainer); diff --git a/dashboard/src/components/filter/change-memory-unit/change-memory-unit.filter.ts b/dashboard/src/components/filter/change-memory-unit/change-memory-unit.filter.ts index b390c47924..6c2eb620d0 100644 --- a/dashboard/src/components/filter/change-memory-unit/change-memory-unit.filter.ts +++ b/dashboard/src/components/filter/change-memory-unit/change-memory-unit.filter.ts @@ -10,7 +10,6 @@ */ 'use strict'; - export enum MemoryUnit {'B', 'KB', 'MB', 'GB', 'TB'} export namespace MemoryUnit { export function keys(): string[] { @@ -34,70 +33,68 @@ export namespace MemoryUnit { */ export class ChangeMemoryUnitFilter { - constructor(register: che.IRegisterService) { - /** - * Default constructor that is using resource injection - * @ngInject for Dependency injection - */ - register.filter('changeMemoryUnit', ($log: ng.ILogService) => { - return (num: number|string, units: [string, string]) => { - const unitFrom = units[0].toUpperCase(), - unitTo = units[1].toUpperCase(); + /** + * Default constructor that is using resource injection + * @ngInject for Dependency injection + */ + static filter($log: ng.ILogService) { + return (num: number|string, units: [string, string]) => { + const unitFrom = units[0].toUpperCase(), + unitTo = units[1].toUpperCase(); - // check if number is valid - const number = parseFloat(num as string); - if (isNaN(number)) { - // do nothing if this isn't a number - $log.error(`ChangeMemoryUnitFilter: got "${num}", but can process only number greater than zero.` ); - return num; - } - if (number < 0) { - // do nothing if number is less than 0 - $log.error(`ChangeMemoryUnitFilter: got "${num}", but can process only number greater than zero.`); - return num; - } + // check if number is valid + const number = parseFloat(num as string); + if (isNaN(number)) { + // do nothing if this isn't a number + $log.error(`ChangeMemoryUnitFilter: got "${num}", but can process only number greater than zero.` ); + return num; + } + if (number < 0) { + // do nothing if number is less than 0 + $log.error(`ChangeMemoryUnitFilter: got "${num}", but can process only number greater than zero.`); + return num; + } - const availableUnits = MemoryUnit.keys(); - // check if unit types are valid - if (availableUnits.indexOf(unitFrom) === -1) { - // do nothing if unit type is unknown - $log.error(`ChangeMemoryUnitFilter: unitFrom="${unitFrom}" doesn't match any of [${availableUnits.toString()}]`); - return num; - } - if (availableUnits.indexOf(unitTo) === -1) { - // do nothing if unit type is unknown - $log.error(`ChangeMemoryUnitFilter: unitTo="${unitFrom}" doesn't match any of [${availableUnits.toString()}]`); - return num; - } + const availableUnits = MemoryUnit.keys(); + // check if unit types are valid + if (availableUnits.indexOf(unitFrom) === -1) { + // do nothing if unit type is unknown + $log.error(`ChangeMemoryUnitFilter: unitFrom="${unitFrom}" doesn't match any of [${availableUnits.toString()}]`); + return num; + } + if (availableUnits.indexOf(unitTo) === -1) { + // do nothing if unit type is unknown + $log.error(`ChangeMemoryUnitFilter: unitTo="${unitFrom}" doesn't match any of [${availableUnits.toString()}]`); + return num; + } - // process numbers - const numberBytes = this.castToBytes(number, unitFrom), - resultValue = this.castBytesTo(numberBytes, unitTo); - return resultValue + ' ' + unitTo; - }; - }); + // process numbers + const numberBytes = ChangeMemoryUnitFilter.castToBytes(number, unitFrom), + resultValue = ChangeMemoryUnitFilter.castBytesTo(numberBytes, unitTo); + return resultValue + ' ' + unitTo; + }; } - castUp(number: number, power: number): number { + static castUp(number: number, power: number): number { const temp = number / Math.pow(1024, power); return Math.round(temp * 10) / 10; } - castDown(number: number, power: number): number { + static castDown(number: number, power: number): number { return number * Math.pow(1024, power); } - getPower(unit: string) { + static getPower(unit: string) { return MemoryUnit[unit]; } - castToBytes(number: number, unitFrom: string): number { + static castToBytes(number: number, unitFrom: string): number { const power = this.getPower(unitFrom); number = Math.round(this.castDown(number, power)); return number; } - castBytesTo(number: number, unitTo: string): number { + static castBytesTo(number: number, unitTo: string): number { const power = this.getPower(unitTo); number = this.castUp(number, power); return number; diff --git a/dashboard/src/components/filter/filter-config.ts b/dashboard/src/components/filter/filter-config.ts index 08a1b42e52..aadd4d3470 100644 --- a/dashboard/src/components/filter/filter-config.ts +++ b/dashboard/src/components/filter/filter-config.ts @@ -15,10 +15,8 @@ import {ChangeMemoryUnitFilter} from './change-memory-unit/change-memory-unit.fi export class FilterConfig { constructor(register: che.IRegisterService) { - - new CheNumberRoundFilter(register); - new ChangeMemoryUnitFilter(register); - + register.filter('numberRound', CheNumberRoundFilter.filter); + register.filter('changeMemoryUnit', ChangeMemoryUnitFilter.filter); } } diff --git a/dashboard/src/components/filter/number-round/number-round.filter.ts b/dashboard/src/components/filter/number-round/number-round.filter.ts index 33a7bb1d1b..2217470728 100644 --- a/dashboard/src/components/filter/number-round/number-round.filter.ts +++ b/dashboard/src/components/filter/number-round/number-round.filter.ts @@ -12,25 +12,23 @@ export class CheNumberRoundFilter { - constructor(register: che.IRegisterService) { - register.filter('numberRound', () => { - return (number: number, precision: number) => { - number = parseFloat(number); - precision = parseInt(precision, 10); + static filter(): Function { + return (numberStr: string, precisionStr: string) => { + const number = parseFloat(numberStr); + let precision = parseInt(precisionStr, 10); - if (isNaN(number)) { - return 'NaN'; - } - if (isNaN(precision)) { - precision = 0; - } + if (isNaN(number)) { + return 'NaN'; + } + if (isNaN(precision)) { + precision = 0; + } - const factor = Math.pow(10, precision); - const tempNumber = number * factor; - const roundedTempNumber = Math.round(tempNumber); - return (roundedTempNumber / factor).toString(); - }; - }); + const factor = Math.pow(10, precision); + const tempNumber = number * factor; + const roundedTempNumber = Math.round(tempNumber); + return (roundedTempNumber / factor).toString(); + }; } } diff --git a/dashboard/src/components/github/github-service.ts b/dashboard/src/components/github/github-service.ts index 30681d44c0..1d622c9d15 100644 --- a/dashboard/src/components/github/github-service.ts +++ b/dashboard/src/components/github/github-service.ts @@ -20,13 +20,13 @@ export class GitHubService { - constructor(register) { + constructor(register: che.IRegisterService) { register.app.constant('gitHubApiUrlRoot', 'https://api.github.com') .constant('gitHubApiVersionHeader', 'application/vnd.github.moondragon+json') .constant('localGitHubToken', 'gitHubToken') .constant('gitHubCallbackPage', 'gitHubCallback.html') .service('githubOrganizationNameResolver', function () { - this.resolve = function (organization) { + this.resolve = function (organization: any) { if (!organization) { return ''; } @@ -38,16 +38,16 @@ export class GitHubService { '$interval', '$window', '$location', - function ($q, $interval, $window) { - var popupWindow = null; - var polling = null; + function ($q: ng.IQService, $interval: ng.IIntervalService, $window: ng.IWindowService, $log: ng.ILogService) { + let popupWindow = null; + let polling = null; - var popup = {}; + let popup = {} as any; popup.popupWindow = popupWindow; - popup.open = function (url, options, config) { - var optionsString = popup.stringifyOptions(popup.prepareOptions(options || {})); + popup.open = function (url: string, options: any, config: any) { + const optionsString = popup.stringifyOptions(popup.prepareOptions(options || {})); popupWindow = window.open(url, '_blank', optionsString); // jshint ignore:line if (popupWindow && popupWindow.focus) { @@ -58,28 +58,17 @@ export class GitHubService { }; popup.pollPopup = function () { - var deferred = $q.defer(); + const deferred = $q.defer(); polling = $interval(function () { try { if (popupWindow.document.title === 'callbackSuccess') { - //var queryParams = popupWindow.location.search.substring(1).replace(/\/$/, ''); - //var hashParams = popupWindow.location.hash.substring(1).replace(/\/$/, ''); - //var hash = utils.parseQueryString(hashParams); - //var qs = utils.parseQueryString(queryParams); - - //angular.extend(qs, hash); - - //if (qs.error) { - // deferred.reject({ error: qs.error }); - //} else { - // deferred.resolve(qs); - //} deferred.resolve(true); popupWindow.close(); $interval.cancel(polling); } } catch (error) { + $log.error(error); } if (popupWindow && popupWindow.closed) { @@ -90,9 +79,9 @@ export class GitHubService { return deferred.promise; }; - popup.prepareOptions = function (options) { - var width = options.width || 500; - var height = options.height || 500; + popup.prepareOptions = function (options: any) { + const width = options.width || 500; + const height = options.height || 500; return angular.extend({ width: width, height: height, @@ -101,9 +90,9 @@ export class GitHubService { }, options); }; - popup.stringifyOptions = function (options) { - var parts = []; - angular.forEach(options, function (value, key) { + popup.stringifyOptions = function (options: any) { + const parts = []; + angular.forEach(options, function (value: string, key: string) { parts.push(key + '=' + value); }); return parts.join(','); @@ -113,15 +102,15 @@ export class GitHubService { } ]) .service('camelutils', function () { - this.camelCase = function (name) { - return name.replace(/([\:\-\_]+(.))/g, function (_, separator, letter, offset) { + this.camelCase = function (name: string) { + return name.replace(/([\:\-\_]+(.))/g, function (_: any, separator: string, letter: string, offset: string) { return offset ? letter.toUpperCase() : letter; }); }; - this.parseQueryString = function (keyValue) { - var obj = {}, key, value; - angular.forEach((keyValue || '').split('&'), function (keyValue) { + this.parseQueryString = function (keyValue: any) { + let obj = {}, key, value; + angular.forEach((keyValue || '').split('&'), function (keyValue: any) { if (keyValue) { value = keyValue.split('='); key = decodeURIComponent(value[0]); @@ -133,14 +122,14 @@ export class GitHubService { }) .factory('gitHubTokenStore', function () { return { - setToken: function (token) { + setToken: function (token: string) { localStorage.setItem('gitHubToken', token); // jshint ignore:line }, getToken: function () { return localStorage.getItem('gitHubToken'); // jshint ignore:line } }; - }).factory('gitHubApiUtils', ['gitHubApiUrlRoot', function (gitHubApiUrlRoot) { + }).factory('gitHubApiUtils', ['gitHubApiUrlRoot', function (gitHubApiUrlRoot: string) { /** * Util function to parse a concatenated GitHub Link header value and return a object with rel value as properties and associated URL * as values. @@ -148,20 +137,17 @@ export class GitHubService { * For instance, passing "; rel="next" \ * , ; rel="last"" gives back: * { - * next: 'https://api.github.com/user/repos?per_page=5&sort=full_name&page=2', - * last: 'https://api.github.com/user/repos?per_page=5&sort=full_name&page=10' - * } + * next: 'https://api.github.com/user/repos?per_page=5&sort=full_name&page=2', + * last: 'https://api.github.com/user/repos?per_page=5&sort=full_name&page=10' + * } * * @param linkHeaderValue the value of the HTTP Link header to parse. {} is returned for null, empty, undefined or unparsable value * @returns a map kind object rel_value: URL */ - function parseLinkHeader(linkHeaderValue) { - var extractor = new RegExp('(<([^;]+)>;\\s?rel="(\\w+)")', 'g'); - // Sample Link Header content - // "; rel="next" \ - // , ; rel="last"" - var links = {}; - var extraction; + function parseLinkHeader(linkHeaderValue: string) { + const extractor = new RegExp('(<([^;]+)>;\\s?rel="(\\w+)")', 'g'); + const links = {}; + let extraction; while ((extraction = extractor.exec(linkHeaderValue)) !== null) { links[extraction[3]] = extraction[2]; } @@ -174,8 +160,8 @@ export class GitHubService { * @param url the URL to check * @returns true if targeted to GitHub API, false either */ - function isGitHubApiUrl(url) { - var checked = url && url.indexOf(gitHubApiUrlRoot) === 0; + function isGitHubApiUrl(url: string) { + const checked = url && url.indexOf(gitHubApiUrlRoot) === 0; return checked; } @@ -185,13 +171,13 @@ export class GitHubService { }; }]) .filter('githubFilterRepositories', function () { - return function (repositories, organizationFilter, repositoryNameFilter) { + return function (repositories: any[], organizationFilter: any, repositoryNameFilter: string) { if (!repositories) { return []; } - var filtered = []; - for (var i = 0; i < repositories.length; i++) { - var repository = repositories[i]; + const filtered = []; + for (let i = 0; i < repositories.length; i++) { + const repository = repositories[i]; if ((!organizationFilter || repository.owner.login === organizationFilter.login) && (!repositoryNameFilter || repository.name.toLocaleLowerCase().indexOf(repositoryNameFilter.toLocaleLowerCase()) >= 0)) { filtered.push(repository); @@ -199,18 +185,18 @@ export class GitHubService { } return filtered; }; - }).factory('GitHubHeadersInjectorInterceptor', ['$q', 'gitHubTokenStore', 'gitHubApiUtils', function ($q, gitHubTokenStore, gitHubApiUtils) { + }).factory('GitHubHeadersInjectorInterceptor', ['$q', 'gitHubTokenStore', 'gitHubApiUtils', function ($q: ng.IQService, gitHubTokenStore: any, gitHubApiUtils: any) { /** * Inject the token inside config as HTTP request header if the request is targeted to http://api.github.com. * * @param config the classic request config object * @returns the config passed a input param with token injected inside if needed */ - function injectToken(config) { + function injectToken(config: any) { if (gitHubApiUtils.isGitHubApiUrl(config.url)) { - var token = gitHubTokenStore.getToken(); + const token = gitHubTokenStore.getToken(); if (token) { - config.headers['Authorization'] = 'token ' + token; + config.headers.Authorization = 'token ' + token; } } return config; @@ -219,7 +205,7 @@ export class GitHubService { return { request: injectToken }; - }]).factory('GitHubUnpaginateInterceptor', ['$q', '$injector', 'gitHubApiUtils', function ($q, $injector, gitHubApiUtils) { + }]).factory('GitHubUnpaginateInterceptor', ['$q', '$injector', 'gitHubApiUtils', function ($q: ng.IQService, $injector: ng.auto.IInjectorService, gitHubApiUtils: any) { /** * Unpaginate GitHub API request when it can. It means: * - detect if the url is targeted to http://api.github.com, unless return direct response, @@ -233,21 +219,21 @@ export class GitHubService { * @param response the classic response object * @returns a response with unpaginated results in possible */ - function unpaginate(response) { + function unpaginate(response: any) { if (!gitHubApiUtils.isGitHubApiUrl(response.config.url)) { return response; } - var nextUrl = gitHubApiUtils.parseLinkHeader(response.headers('link'))['next']; + const nextUrl = gitHubApiUtils.parseLinkHeader(response.headers('link')).next; if (!nextUrl) { return response; } - var $http = $injector.get('$http'); + const $http = $injector.get('$http') as ng.IHttpService; return $http({ url: nextUrl, method: 'GET', - transformResponse: $http.defaults.transformResponse.concat([function (data) { + transformResponse: $http.defaults.transformResponse.concat([function (data: any) { return response.data.concat(data); }]) }); @@ -256,15 +242,15 @@ export class GitHubService { return { response: unpaginate }; - }]).factory('GitHubAPIVersionSetterInterceptor', ['$q', 'gitHubApiUtils', 'gitHubApiVersionHeader', function ($q, gitHubApiUtils, gitHubApiVersionHeader) { + }]).factory('GitHubAPIVersionSetterInterceptor', ['$q', 'gitHubApiUtils', 'gitHubApiVersionHeader', function ($q: ng.IQService, gitHubApiUtils: any, gitHubApiVersionHeader: any) { /** * Set the right header to indicate to GitHub API the targeted version. * * @param config the classic request config object */ - function setGitHubApiVersionHeader(config) { + function setGitHubApiVersionHeader(config: any) { if (gitHubApiUtils.isGitHubApiUrl(config.url)) { - config.headers['Accept'] = gitHubApiVersionHeader; + config.headers.Accept = gitHubApiVersionHeader; } return config; } @@ -272,13 +258,13 @@ export class GitHubService { return { request: setGitHubApiVersionHeader }; - }]).config(['$httpProvider', function ($httpProvider) { + }]).config(['$httpProvider', function ($httpProvider: ng.IHttpProvider) { $httpProvider.interceptors.push('GitHubHeadersInjectorInterceptor'); $httpProvider.interceptors.push('GitHubUnpaginateInterceptor'); $httpProvider.interceptors.push('GitHubAPIVersionSetterInterceptor'); - }]).factory('GitHub', ['$resource', function ($resource) { - var sort = 'full_name'; - var per_page = 50; + }]).factory('GitHub', ['$resource', function ($resource: ng.resource.IResourceService) { + const sort = 'full_name'; + const per_page = 50; return { user: function () { return $resource('https://api.github.com/user'); @@ -289,7 +275,7 @@ export class GitHubService { userRepositories: function () { return $resource('https://api.github.com/user/repos', {sort: sort, per_page: per_page}); }, - organizationRepositories: function (organizationLogin) { + organizationRepositories: function (organizationLogin: any) { return $resource('https://api.github.com/orgs/:organizationLogin/repos', { organizationLogin: organizationLogin, sort: sort, diff --git a/dashboard/src/components/ide-fetcher/che-ide-fetcher-config.ts b/dashboard/src/components/ide-fetcher/che-ide-fetcher-config.ts index 6c6b01eef3..a74b6e216d 100644 --- a/dashboard/src/components/ide-fetcher/che-ide-fetcher-config.ts +++ b/dashboard/src/components/ide-fetcher/che-ide-fetcher-config.ts @@ -14,10 +14,9 @@ import {CheIdeFetcher} from './che-ide-fetcher.service'; export class CheIdeFetcherConfig { - constructor(register) { - - register.factory('cheIdeFetcher', CheIdeFetcher); + constructor(register: che.IRegisterService) { + register.factory('cheIdeFetcher', CheIdeFetcher); } } diff --git a/dashboard/src/components/injector/che-ui-elements-injector-config.ts b/dashboard/src/components/injector/che-ui-elements-injector-config.ts index 19612088a4..be8a849a3e 100644 --- a/dashboard/src/components/injector/che-ui-elements-injector-config.ts +++ b/dashboard/src/components/injector/che-ui-elements-injector-config.ts @@ -9,12 +9,11 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; - -import {CheUIElementsInjectorService} from './che-ui-elements-injector.service'; +import {CheUIElementsInjectorService} from '../service/injector/che-ui-elements-injector.service'; export class CheUIElementsInjectorConfig { - constructor(register) { + constructor(register: che.IRegisterService) { register.service('cheUIElementsInjectorService', CheUIElementsInjectorService); } } diff --git a/dashboard/src/components/interceptor/interceptor-base.ts b/dashboard/src/components/interceptor/interceptor-base.ts index 17d5471bd8..c2cf035882 100644 --- a/dashboard/src/components/interceptor/interceptor-base.ts +++ b/dashboard/src/components/interceptor/interceptor-base.ts @@ -17,8 +17,8 @@ export abstract class HttpInterceptorBase { constructor() { - ['request', 'requestError', 'response', 'responseError'].forEach((method) => { - if(this[method]) { + ['request', 'requestError', 'response', 'responseError'].forEach((method: string) => { + if (this[method]) { this[method] = this[method].bind(this); } }); diff --git a/dashboard/src/components/notification/application-notifications.factory.ts b/dashboard/src/components/notification/application-notifications.factory.ts index 72f21ff961..1a0c1f1364 100644 --- a/dashboard/src/components/notification/application-notifications.factory.ts +++ b/dashboard/src/components/notification/application-notifications.factory.ts @@ -54,7 +54,7 @@ export class ApplicationNotifications { * @param removeOnRead if true - should be removed after has been shown to user * @returns {{notification}} notification */ - addErrorNotification(title: string, content: string, removeOnRead = true): any { + addErrorNotification(title: string, content: string, removeOnRead: boolean = true): any { return this._addNotification('error', title, content, removeOnRead); } @@ -66,7 +66,7 @@ export class ApplicationNotifications { * @param removeOnRead if true - should be removed after has been shown to user * @returns {{notification}} notification */ - addWarningNotification(title: string, content: string, removeOnRead = true): any { + addWarningNotification(title: string, content: string, removeOnRead: boolean = true): any { return this._addNotification('warning', title, content, removeOnRead); } @@ -78,7 +78,7 @@ export class ApplicationNotifications { * @param removeOnRead if true - should be removed after has been shown to user * @returns {{notification}} notification */ - addInfoNotification(title: string, content: string, removeOnRead = true): any { + addInfoNotification(title: string, content: string, removeOnRead: boolean = true): any { return this._addNotification('info', title, content, removeOnRead); } diff --git a/dashboard/src/components/notification/che-notification-config.ts b/dashboard/src/components/notification/che-notification-config.ts index a6219f1e0e..3a1b0b47e9 100644 --- a/dashboard/src/components/notification/che-notification-config.ts +++ b/dashboard/src/components/notification/che-notification-config.ts @@ -15,7 +15,7 @@ import {ApplicationNotifications} from './application-notifications.factory'; export class CheNotificationConfig { - constructor(register) { + constructor(register: che.IRegisterService) { register.factory('cheNotification', CheNotification); register.factory('applicationNotifications', ApplicationNotifications); } diff --git a/dashboard/src/components/routing/route-history.service.ts b/dashboard/src/components/routing/route-history.service.ts index 64f63e2953..80a526ff24 100644 --- a/dashboard/src/components/routing/route-history.service.ts +++ b/dashboard/src/components/routing/route-history.service.ts @@ -16,11 +16,14 @@ */ export class RouteHistory { + history: string[]; + /** * Default constructor that is using resource injection * @ngInject for Dependency injection */ - constructor($rootScope, $location) { + constructor($rootScope: ng.IRootScopeService, + $location: ng.ILocationService) { this.history = []; $rootScope.$on('$routeChangeSuccess', () => { this.history.push($location.path()); @@ -29,9 +32,9 @@ export class RouteHistory { /** * Add a new path on top of all existing paths - * @param path the path on which we will we redirecting when we pop current path + * @param {string} path the path on which we will we redirecting when we pop current path */ - pushPath(path) { + pushPath(path: string): void { this.history.push(path); } diff --git a/dashboard/src/components/routing/routing-config.ts b/dashboard/src/components/routing/routing-config.ts index 6cdbe7a2ff..3c0c5aa4e5 100644 --- a/dashboard/src/components/routing/routing-config.ts +++ b/dashboard/src/components/routing/routing-config.ts @@ -15,7 +15,7 @@ import {RouteHistory} from './route-history.service'; export class RoutingConfig { - constructor(register) { + constructor(register: che.IRegisterService) { register.factory('routingRedirect', RoutingRedirect); diff --git a/dashboard/src/components/routing/routing-redirect.factory.ts b/dashboard/src/components/routing/routing-redirect.factory.ts index fbaa19430a..c35566f226 100644 --- a/dashboard/src/components/routing/routing-redirect.factory.ts +++ b/dashboard/src/components/routing/routing-redirect.factory.ts @@ -17,30 +17,32 @@ */ export class RoutingRedirect { + $location: ng.ILocationService; + routeCallbacks: Array; + /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($location) { + constructor($location: ng.ILocationService) { this.$location = $location; this.routeCallbacks = []; } /** * Add a givan callback to this routing disabler - * @param routeCallback + * @param {any} routeCallback */ - addRouteCallback(routeCallback) { + addRouteCallback(routeCallback: any): void { this.routeCallbacks.push(routeCallback); } - /** * Check the given event with the given next object * @param event the routing event that can be cancelled * @param next the expected route */ - check(event, next) { + check(event: any, next: any) { // loop routes and check if pages are authorized let i = 0; @@ -54,7 +56,6 @@ export class RoutingRedirect { i++; } - // ok now page may not be accessible and need to be redirected i = 0; let foundSkip = false; @@ -74,6 +75,6 @@ export class RoutingRedirect { i++; } - } + } diff --git a/dashboard/src/components/steps-container/steps-container.directive.ts b/dashboard/src/components/steps-container/steps-container.directive.ts index ed2726d94b..774305c1f7 100644 --- a/dashboard/src/components/steps-container/steps-container.directive.ts +++ b/dashboard/src/components/steps-container/steps-container.directive.ts @@ -14,20 +14,14 @@ * Defines a directive for displaying steps of creating project or loading workspace * @author Oleksii Kurinnyi */ -export class CheStepsContainer { +export class CheStepsContainer implements ng.IDirective { - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor () { - this.restrict='E'; - this.templateUrl = 'components/steps-container/steps-container.html'; + restrict = 'E'; + templateUrl = 'components/steps-container/steps-container.html'; - this.scope = { - allSteps: '=cheAllSteps', - currentStep: '=cheCurrentStep' - } - } + scope = { + allSteps: '=cheAllSteps', + currentStep: '=cheCurrentStep' + }; } diff --git a/dashboard/src/components/typings/che.d.ts b/dashboard/src/components/typings/che.d.ts index 5bea4c275a..bc11467781 100755 --- a/dashboard/src/components/typings/che.d.ts +++ b/dashboard/src/components/typings/che.d.ts @@ -20,6 +20,8 @@ declare namespace che { wantTokeepLoader: boolean; waitingLoaded: boolean; currentPage: string; + productVersion: string; + branding: any; } export namespace api { @@ -303,7 +305,7 @@ declare namespace che { [machineName: string]: IEnvironmentMachine }; recipe: IRecipe; - warnings: IWorkspaceWarning[]; + warnings?: IWorkspaceWarning[]; } export interface IRecipe { @@ -327,7 +329,8 @@ declare namespace che { export interface IEnvironmentMachineServer { port: string|number; protocol: string; - path: string; + path?: string; + properties?: any; } export interface IWorkspaceRuntime { @@ -352,7 +355,11 @@ declare namespace che { export interface IWorkspaceRuntimeMachineServer { status: string; + port: string; url: string; + ref: string; + protocol: string; + path: string; } export interface IAgent { @@ -381,9 +388,9 @@ declare namespace che { source: IProjectSource; path?: string; commands?: Array; - mixins: Array; - modules: Array; - problems: Array; + mixins?: Array; + modules?: Array; + problems?: Array; projectType?: string; type?: string; tags?: Array; @@ -430,12 +437,11 @@ declare namespace che { [propName: string]: string | number; } - export interface IProfile extends ng.resource.IResourceClass { + export interface IProfile extends ng.resource.IResource { attributes?: IProfileAttributes; email: string; links?: Array; userId: string; - $promise?: any; } export interface INamespace { @@ -462,11 +468,10 @@ declare namespace che { v: string; workspace: IWorkspaceConfig; creator: any; - links?: any; ide?: any; button?: any; policies?: any; - links: string[]; + links?: string[]; } export interface IRegistry { diff --git a/dashboard/src/components/validator/city-name-validator.directive.ts b/dashboard/src/components/validator/city-name-validator.directive.ts index c050148d39..0f12a8b1d6 100644 --- a/dashboard/src/components/validator/city-name-validator.directive.ts +++ b/dashboard/src/components/validator/city-name-validator.directive.ts @@ -15,16 +15,16 @@ * * @author Oleksii Kurinnyi */ -export class CityNameValidator { +export class CityNameValidator implements ng.IDirective { restrict: string = 'A'; require: string = 'ngModel'; - cityNameRE: RegExp = new RegExp(/^(?:[a-zA-Z\u00A0-\u024F]+(?:\. |-| |'))*[a-zA-Z\u00A0-\u024F]+$/); + cityNameRE: RegExp = new RegExp(`^(?:[a-zA-Z\u00A0-\u024F]+(?:\. |-| |'))*[a-zA-Z\u00A0-\u024F]+$`); - link($scope, element, attrs, ctrl) { + link($scope: ng.IRootScopeService, $element: ng.IAugmentedJQuery, $attrs: ng.IAttributes, $ctrl: ng.INgModelController) { // validate only input element - if ('input' === element[0].localName) { - ctrl.$validators.cityNameValidator = (modelValue: string) => { + if ('input' === $element[0].localName) { + ($ctrl.$validators as any).cityNameValidator = (modelValue: string) => { return this.cityNameRE.test(modelValue); }; } diff --git a/dashboard/src/components/validator/git-url-validator.directive.ts b/dashboard/src/components/validator/git-url-validator.directive.ts index f32bad2799..ed3723aede 100644 --- a/dashboard/src/components/validator/git-url-validator.directive.ts +++ b/dashboard/src/components/validator/git-url-validator.directive.ts @@ -10,28 +10,20 @@ */ 'use strict'; - /** * Defines a directive for checking git URL * @author Florent Benoit */ -export class GitUrlValidator { +export class GitUrlValidator implements ng.IDirective { - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor () { - this.restrict='A'; - this.require = 'ngModel'; - - } + restrict = 'A'; + require = 'ngModel'; /** * Check that the GIT URL is compliant */ - link(scope, element, attributes, ngModel) { - ngModel.$validators.gitUrl = function(modelValue) { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attributes: ng.IAttributes, $ngModel: ng.INgModelController): void { + ($ngModel.$validators as any).gitUrl = function(modelValue: string) { var res = /((git|ssh|http(s)?)|(git@[\w\.]+))(:(\/\/))?([\w\.@\:/\-~]+)(\.git)?(\/)?/.test(modelValue); return res; }; diff --git a/dashboard/src/components/validator/unique-project-name-validator.directive.ts b/dashboard/src/components/validator/unique-project-name-validator.directive.ts index 9e7a5d4e2d..64675b7660 100644 --- a/dashboard/src/components/validator/unique-project-name-validator.directive.ts +++ b/dashboard/src/components/validator/unique-project-name-validator.directive.ts @@ -9,44 +9,52 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheAPI} from '../api/che-api.factory'; + +interface IUniqueProjectNameValidatorAttributes extends ng.IAttributes { + uniqueProjectName: Array; +} /** * Defines a directive for checking if the project name is not already taken * @author Florent Benoit */ -export class UniqueProjectNameValidator { +export class UniqueProjectNameValidator implements ng.IDirective { + restrict = 'A'; + require = 'ngModel'; + + cheAPI: CheAPI; + $q: ng.IQService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor (cheAPI, $q) { + constructor (cheAPI: CheAPI, $q: ng.IQService) { this.cheAPI = cheAPI; this.$q = $q; - this.restrict='A'; - this.require = 'ngModel'; } /** * Check that the GIT URL is compliant */ - link($scope, element, attributes, ngModel) { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attributes: ng.IAttributes, $ngModelCtrl: ng.INgModelController) { // validate only input element - if ('input' === element[0].localName) { + if ('input' === $element[0].localName) { - ngModel.$asyncValidators.uniqueProjectName = (modelValue) => { + ($ngModelCtrl.$asyncValidators as any).uniqueProjectName = (modelValue: string) => { // create promise - var deferred = this.$q.defer(); + const deferred = this.$q.defer(); // parent scope ? - var scopingTest = $scope.$parent; + let scopingTest = $scope.$parent; if (!scopingTest) { scopingTest = $scope; } - var workspaceProjects = scopingTest.$eval(attributes.uniqueProjectName); + const workspaceProjects = scopingTest.$eval(($attributes as any).uniqueProjectName); // found a selected workspace ? if (workspaceProjects) { diff --git a/dashboard/src/components/validator/unique-project-name-validator.spec.ts b/dashboard/src/components/validator/unique-project-name-validator.spec.ts index da2a7a7e85..98f0c4be77 100644 --- a/dashboard/src/components/validator/unique-project-name-validator.spec.ts +++ b/dashboard/src/components/validator/unique-project-name-validator.spec.ts @@ -9,6 +9,9 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheWorkspace} from '../api/workspace/che-workspace.factory'; +import {CheAPIBuilder} from '../api/builder/che-api-builder.factory'; +import {CheHttpBackend} from '../api/test/che-http-backend'; /** * Test the git URL @@ -16,33 +19,37 @@ */ describe('unique-project-name-validator', function() { - var $scope, form, $compiler; + let $scope, form, $compiler; /** * Project API */ - var workspace; + let workspace; /** * API builder. */ - var apiBuilder; + let apiBuilder; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * Che backend */ - var cheBackend; + let cheBackend; beforeEach(angular.mock.module('userDashboard')); - beforeEach(inject(function($compile, $rootScope, cheWorkspace, cheAPIBuilder, cheHttpBackend) { + beforeEach(inject(function($compile: ng.ICompileService, + $rootScope: ng.IRootScopeService, + cheWorkspace: CheWorkspace, + cheAPIBuilder: CheAPIBuilder, + cheHttpBackend: CheHttpBackend) { $scope = $rootScope; $compiler = $compile; workspace = cheWorkspace; @@ -57,9 +64,9 @@ describe('unique-project-name-validator', function() { it('projectAlready exists', function() { // setup tests objects - var idWorkspace1 = 'idOfMyWorkspace1'; - var workspace1 = apiBuilder.getWorkspaceBuilder().withName('testWorkspace1').withId(idWorkspace1).build(); - var wksp1Project1 = apiBuilder.getProjectReferenceBuilder().withName('project-wk1-1').build(); + let idWorkspace1 = 'idOfMyWorkspace1'; + let workspace1 = apiBuilder.getWorkspaceBuilder().withName('testWorkspace1').withId(idWorkspace1).build(); + let wksp1Project1 = apiBuilder.getProjectReferenceBuilder().withName('project-wk1-1').build(); // add into backend @@ -80,7 +87,7 @@ describe('unique-project-name-validator', function() { } }; - var element = angular.element( + let element = angular.element( '
' + '' + '
' @@ -100,9 +107,9 @@ describe('unique-project-name-validator', function() { it('project not yet defined', function() { // setup tests objects - var idWorkspace1 = 'idOfMyWorkspace1'; - var workspace1 = apiBuilder.getWorkspaceBuilder().withName('testWorkspace1').withId(idWorkspace1).build(); - var wksp1Project1 = apiBuilder.getProjectReferenceBuilder().withName('project-wk1-1').build(); + let idWorkspace1 = 'idOfMyWorkspace1'; + let workspace1 = apiBuilder.getWorkspaceBuilder().withName('testWorkspace1').withId(idWorkspace1).build(); + let wksp1Project1 = apiBuilder.getProjectReferenceBuilder().withName('project-wk1-1').build(); // add into backend @@ -124,7 +131,7 @@ describe('unique-project-name-validator', function() { } }; - var element = angular.element( + let element = angular.element( '
' + '' + '
' diff --git a/dashboard/src/components/validator/unique-stack-name-validator.directive.ts b/dashboard/src/components/validator/unique-stack-name-validator.directive.ts index 8009810097..0287e38ab8 100644 --- a/dashboard/src/components/validator/unique-stack-name-validator.directive.ts +++ b/dashboard/src/components/validator/unique-stack-name-validator.directive.ts @@ -9,45 +9,53 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheAPI} from '../api/che-api.factory'; + +interface IUniqueStackNameValidatorAttributes extends ng.IAttributes { + uniqueStackName: string; +} /** * Defines a directive for checking whether stack name already exists. * * @author Ann Shumilova */ -export class UniqueStackNameValidator { +export class UniqueStackNameValidator implements ng.IDirective { + restrict = 'A'; + require = 'ngModel'; + + cheAPI: CheAPI; + $q: ng.IQService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor (cheAPI, $q) { + constructor (cheAPI: CheAPI, $q: ng.IQService) { this.cheAPI = cheAPI; this.$q = $q; - this.restrict='A'; - this.require = 'ngModel'; } /** * Check that the name of stack is unique */ - link($scope, element, attributes, ngModel) { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attributes: ng.IAttributes, $ngModelCtrl: ng.INgModelController) { // validate only input element - if ('input' === element[0].localName) { + if ('input' === $element[0].localName) { - ngModel.$asyncValidators.uniqueStackName = (modelValue) => { + ($ngModelCtrl.$asyncValidators as any).uniqueStackName = (modelValue: string) => { // create promise - var deferred = this.$q.defer(); + const deferred = this.$q.defer(); // parent scope ? - var scopingTest = $scope.$parent; + let scopingTest = $scope.$parent; if (!scopingTest) { scopingTest = $scope; } - let currentStackName = scopingTest.$eval(attributes.uniqueStackName), + let currentStackName = scopingTest.$eval(($attributes as any).uniqueStackName), stacks = this.cheAPI.getStack().getStacks(); if (stacks.length) { for (let i = 0; i < stacks.length; i++) { diff --git a/dashboard/src/components/validator/unique-stack-name-validator.spec.ts b/dashboard/src/components/validator/unique-stack-name-validator.spec.ts index 15e51d3e98..b51ea16550 100644 --- a/dashboard/src/components/validator/unique-stack-name-validator.spec.ts +++ b/dashboard/src/components/validator/unique-stack-name-validator.spec.ts @@ -9,6 +9,9 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheStack} from '../api/che-stack.factory'; +import {CheAPIBuilder} from '../api/builder/che-api-builder.factory'; +import {CheHttpBackend} from '../api/test/che-http-backend'; /** * Test the stack name uniqueness directive @@ -16,33 +19,38 @@ */ describe('unique-stack-name-validator', function() { - var $scope, form, $compiler; + let $scope, form, $compiler; /** * Stack API */ - var factoryStack; + let factoryStack; /** * API builder. */ - var apiBuilder; + let apiBuilder; /** * Backend for handling http operations */ - var httpBackend; + let httpBackend; /** * Che backend */ - var cheBackend; + let cheBackend; beforeEach(angular.mock.module('userDashboard')); - beforeEach(inject(function($compile, $rootScope, cheStack, cheAPIBuilder, cheHttpBackend, $document) { + beforeEach(inject(function($compile: ng.ICompileService, + $rootScope: ng.IRootScopeService, + cheStack: CheStack, + cheAPIBuilder: CheAPIBuilder, + cheHttpBackend: CheHttpBackend, + $document: ng.IDocumentService) { $scope = $rootScope; $compiler = $compile; factoryStack = cheStack; @@ -56,15 +64,15 @@ describe('unique-stack-name-validator', function() { describe('Validate Stack Name', function() { it('stack already exists', function() { - let stacks = []; + const stacks = []; // setup tests objects - var idStack1 = 'idStack1'; - var nameStack1 = 'stack1'; - var stack1 = apiBuilder.getStackBuilder().withName(nameStack1).withId(idStack1).build(); + const idStack1 = 'idStack1'; + const nameStack1 = 'stack1'; + const stack1 = apiBuilder.getStackBuilder().withName(nameStack1).withId(idStack1).build(); stacks.push(stack1); - var idStack2 = 'idStack2'; - var stack2 = apiBuilder.getStackBuilder().withId(idStack2).build(); + const idStack2 = 'idStack2'; + const stack2 = apiBuilder.getStackBuilder().withId(idStack2).build(); stacks.push(stack2); // add into backend @@ -78,7 +86,7 @@ describe('unique-stack-name-validator', function() { $scope.model = {stackName: null}; - var element = angular.element( + let element = angular.element( '
' + '' + '
' @@ -96,13 +104,13 @@ describe('unique-stack-name-validator', function() { it('stack not yet defined', function() { // setup tests objects - var idStack1 = 'idStack1'; - var nameStack1 = 'stack1'; - var stack1 = apiBuilder.getStackBuilder().withName(nameStack1).withId(idStack1).build(); + const idStack1 = 'idStack1'; + const nameStack1 = 'stack1'; + const stack1 = apiBuilder.getStackBuilder().withName(nameStack1).withId(idStack1).build(); - var idStack2 = 'idStack2'; - var nameStack2 = 'stack2'; - var stack2 = apiBuilder.getStackBuilder().withName('').withId(idStack2).build(); + const idStack2 = 'idStack2'; + const nameStack2 = 'stack2'; + const stack2 = apiBuilder.getStackBuilder().withName('').withId(idStack2).build(); factoryStack.fetchStacks(); @@ -117,7 +125,7 @@ describe('unique-stack-name-validator', function() { $scope.model = { stackName: null }; - var element = angular.element( + const element = angular.element( '
' + '' + '
' diff --git a/dashboard/src/components/validator/unique-workspace-name-validator.directive.ts b/dashboard/src/components/validator/unique-workspace-name-validator.directive.ts index 22974ba4b4..52481a225f 100644 --- a/dashboard/src/components/validator/unique-workspace-name-validator.directive.ts +++ b/dashboard/src/components/validator/unique-workspace-name-validator.directive.ts @@ -9,48 +9,56 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheAPI} from '../api/che-api.factory'; + +interface IUniqueWorkspaceNameValidatorAttributes extends ng.IAttributes { + uniqueWorkspaceName: string; +} /** * Defines a directive for checking if the workspace name is not already taken * @author Oleksii Kurinnyi */ -export class UniqueWorkspaceNameValidator { +export class UniqueWorkspaceNameValidator implements ng.IDirective { + restrict = 'A'; + require = 'ngModel'; + + cheAPI: CheAPI; + $q: ng.IQService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor (cheAPI, $q) { + constructor (cheAPI: CheAPI, $q: ng.IQService) { this.cheAPI = cheAPI; this.$q = $q; - this.restrict='A'; - this.require = 'ngModel'; } /** * Check that the name of workspace is unique */ - link($scope, element, attributes, ngModel) { + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attributes: IUniqueWorkspaceNameValidatorAttributes, $ngModelCtrl: ng.INgModelController) { // validate only input element - if ('input' === element[0].localName) { + if ('input' === $element[0].localName) { - ngModel.$asyncValidators.uniqueWorkspaceName = (modelValue) => { + ($ngModelCtrl.$asyncValidators as any).uniqueWorkspaceName = (modelValue: string) => { // create promise - var deferred = this.$q.defer(); + const deferred = this.$q.defer(); // parent scope ? - var scopingTest = $scope.$parent; + let scopingTest = $scope.$parent; if (!scopingTest) { scopingTest = $scope; } - let currentWorkspaceName = scopingTest.$eval(attributes.uniqueWorkspaceName), + let currentWorkspaceName = scopingTest.$eval($attributes.uniqueWorkspaceName), workspaces = this.cheAPI.getWorkspace().getWorkspaces(); if (workspaces.length) { - for (let i=0; i' + '' + '' @@ -94,13 +99,13 @@ describe('unique-workspace-name-validator', function() { it('workspace not yet defined', function() { // setup tests objects - var idWorkspace1 = 'idOfMyWorkspace1'; - var nameWorkspace1 = 'testWorkspace1'; - var workspace1 = apiBuilder.getWorkspaceBuilder().withName(nameWorkspace1).withId(idWorkspace1).build(); + const idWorkspace1 = 'idOfMyWorkspace1'; + const nameWorkspace1 = 'testWorkspace1'; + const workspace1 = apiBuilder.getWorkspaceBuilder().withName(nameWorkspace1).withId(idWorkspace1).build(); - var idWorkspace2 = 'idOfMyWorkspace2'; - var nameWorkspace2 = 'testWorkspace2'; - var workspace2 = apiBuilder.getWorkspaceBuilder().withName().withId(idWorkspace2).build(); + const idWorkspace2 = 'idOfMyWorkspace2'; + const nameWorkspace2 = 'testWorkspace2'; + const workspace2 = apiBuilder.getWorkspaceBuilder().withName().withId(idWorkspace2).build(); factoryWorkspace.fetchWorkspaces(); @@ -115,7 +120,7 @@ describe('unique-workspace-name-validator', function() { $scope.model = { workspaceName: null }; - var element = angular.element( + const element = angular.element( '
' + '' + '
' diff --git a/dashboard/src/components/widget/accordion/che-accordion.directive.ts b/dashboard/src/components/widget/accordion/che-accordion.directive.ts index f8bd477410..f8be0c658c 100644 --- a/dashboard/src/components/widget/accordion/che-accordion.directive.ts +++ b/dashboard/src/components/widget/accordion/che-accordion.directive.ts @@ -10,52 +10,59 @@ */ 'use strict'; +interface ICheAccordionScope extends ng.IScope { + openCondition: boolean; +} + /** * Defines a directive for Accordion component * @author Oleksii Kurinnyi */ -export class CheAccordion { +export class CheAccordion implements ng.IDirective { + + restrict = 'E'; + transclude = true; + replace = true; + template = '
'; + + // scope values + scope = { + openCondition: '=cheOpenCondition' + }; + + $timeout: ng.ITimeoutService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($timeout) { + constructor($timeout: ng.ITimeoutService) { this.$timeout = $timeout; - this.restrict = 'E'; - this.transclude = true; - this.replace = true; - this.template = '
'; - - // scope values - this.scope = { - openCondition: '=cheOpenCondition' - }; } - link($scope, element, attr, ctrl) { - let currentBodyElement = element.find('.che-accordion-body'); + link($scope: ICheAccordionScope, $element: ng.IAugmentedJQuery): void { + let currentBodyElement = $element.find('.che-accordion-body'); // automatic switching panes $scope.$watch(() => { return $scope.openCondition; - }, (doOpenPane) => { - if (!element.siblings().hasClass('che-accordion-dirty')) { + }, (doOpenPane: boolean) => { + if (!$element.siblings().hasClass('che-accordion-dirty')) { openPane(doOpenPane); } }); // manual switching panes - element.bind('click', (event) => { + $element.bind('click', (event: JQueryEventObject) => { if (angular.element(event.target).parent().hasClass('che-accordion-title')) { - element.addClass('che-accordion-dirty'); + $element.addClass('che-accordion-dirty'); openPane(true); } }); - let openPane = (doOpenPane) => { - if (element.hasClass('che-accordion-closed')) { - let siblingElements = element.siblings(), + function openPane (doOpenPane: boolean) { + if ($element.hasClass('che-accordion-closed')) { + let siblingElements = $element.siblings(), panesToClose = []; // find opened pane and close it @@ -73,7 +80,7 @@ export class CheAccordion { this.$timeout(() => { // close other panes - panesToClose.forEach((pane) => { + panesToClose.forEach((pane: ng.IAugmentedJQuery) => { pane.addClass('che-accordion-closed'); }); @@ -84,10 +91,10 @@ export class CheAccordion { } // open current pane - element.removeClass('che-accordion-closed'); + $element.removeClass('che-accordion-closed'); } - },10).then(() => { - for (let i=0; i { + for (let i = 0; i < siblingElements.length; i++) { angular.element(siblingElements[i]).find('.che-accordion-body').removeAttr('style'); } }); diff --git a/dashboard/src/components/widget/button-dropdown/che-button-dropdown.controller.ts b/dashboard/src/components/widget/button-dropdown/che-button-dropdown.controller.ts index 45df225b28..914c13ab1e 100644 --- a/dashboard/src/components/widget/button-dropdown/che-button-dropdown.controller.ts +++ b/dashboard/src/components/widget/button-dropdown/che-button-dropdown.controller.ts @@ -16,18 +16,23 @@ * @author Florent Benoit */ export class CheButtonDropdownCtrl { + $timeout: ng.ITimeoutService; + $window: ng.IWindowService; + + showDropdown: boolean; + isDisabled: boolean; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($timeout, $window) { + constructor($timeout: ng.ITimeoutService, $window: ng.IWindowService) { this.$timeout = $timeout; this.showDropdown = false; this.$window = $window; } - toggleDropDown() { + toggleDropDown(): void { if (this.isDisabled) { this.showDropdown = false; return; @@ -36,13 +41,13 @@ export class CheButtonDropdownCtrl { this.showDropdown = !this.showDropdown; } - disableDropDown() { + disableDropDown(): void { this.$timeout(() => { this.showDropdown = false; }, 300); } - redirect(newPath) { + redirect(newPath: string): void { if (!newPath || this.isDisabled) { return; } diff --git a/dashboard/src/components/widget/button-dropdown/che-button-dropdown.directive.ts b/dashboard/src/components/widget/button-dropdown/che-button-dropdown.directive.ts index fa51e08a5a..c075bed52c 100644 --- a/dashboard/src/components/widget/button-dropdown/che-button-dropdown.directive.ts +++ b/dashboard/src/components/widget/button-dropdown/che-button-dropdown.directive.ts @@ -14,26 +14,20 @@ * Defines the super class for for all buttons * @author Florent Benoit */ -export class CheButtonDropdown { +export class CheButtonDropdown implements ng.IDirective { - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor() { - this.restrict = 'E'; - this.bindToController = true; - this.templateUrl = 'components/widget/button-dropdown/che-button-dropdown.html'; - this.controller = 'CheButtonDropdownCtrl'; - this.controllerAs = 'cheButtonDropdownCtrl'; + restrict = 'E'; + bindToController = true; + templateUrl = 'components/widget/button-dropdown/che-button-dropdown.html'; + controller = 'CheButtonDropdownCtrl'; + controllerAs = 'cheButtonDropdownCtrl'; - // scope values - this.scope = { - labelText: '@cheButtonDropdownLabel', - href: '@cheButtonDropdownHref', - ctrl: '=cheButtonDropdownController', - isDisabled: '=cheDisabled' - }; - } + // scope values + scope = { + labelText: '@cheButtonDropdownLabel', + href: '@cheButtonDropdownHref', + ctrl: '=cheButtonDropdownController', + isDisabled: '=cheDisabled' + }; } diff --git a/dashboard/src/components/widget/button/che-button.directive.ts b/dashboard/src/components/widget/button/che-button.directive.ts index e0788f6006..2122c2d4df 100644 --- a/dashboard/src/components/widget/button/che-button.directive.ts +++ b/dashboard/src/components/widget/button/che-button.directive.ts @@ -19,12 +19,6 @@ export abstract class CheButton { restrict: string = 'E'; bindToController: boolean = true; - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor () {} - /** * Template for the current toolbar * @param element diff --git a/dashboard/src/components/widget/chips-list/chips-list.directive.ts b/dashboard/src/components/widget/chips-list/chips-list.directive.ts index e5bc750c5d..f83ce54ccb 100644 --- a/dashboard/src/components/widget/chips-list/chips-list.directive.ts +++ b/dashboard/src/components/widget/chips-list/chips-list.directive.ts @@ -19,13 +19,7 @@ export class CheChipsList { transclude: boolean = true; require: string = 'ngModel'; - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor() { } - - template() { + template(): string { return `
{{$chip}}
@@ -36,11 +30,11 @@ export class CheChipsList {
`; } - compile(element, attrs) { - let keys = Object.keys(attrs); + compile($element: ng.IAugmentedJQuery, $attrs: ng.IAttributes) { + let keys = Object.keys($attrs); // search the md-chips element - let mdChipsElement = element.find('md-chips'); + let mdChipsElement = $element.find('md-chips'); keys.forEach((key: string) => { @@ -52,7 +46,7 @@ export class CheChipsList { if (key.indexOf('che') === 0) { return; } - let value = attrs[key]; + let value = $attrs[key]; // handle empty values as boolean if (value === '') { @@ -60,7 +54,7 @@ export class CheChipsList { } // set the value of the attribute - mdChipsElement.attr(attrs.$attr[key], value); + mdChipsElement.attr($attrs.$attr[key], value); // it needs to use DOM element method to set custom value of boolean attribute // because jQuery's 'attr' method substitutes this value with name of attribute @@ -68,7 +62,7 @@ export class CheChipsList { mdChipsElement[0].setAttribute(key, value); } - element.removeAttr(attrs.$attr[key]); + $element.removeAttr($attrs.$attr[key]); }); } diff --git a/dashboard/src/components/widget/compile/che-compile.directive.ts b/dashboard/src/components/widget/compile/che-compile.directive.ts index 579f279953..3ee466e236 100644 --- a/dashboard/src/components/widget/compile/che-compile.directive.ts +++ b/dashboard/src/components/widget/compile/che-compile.directive.ts @@ -15,21 +15,24 @@ * * @author Ann Shumilova */ -export class CheCompile { +export class CheCompile implements ng.IDirective { + + restrict = 'A'; + + $compile: ng.ICompileService; + /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor ($compile) { - this.restrict='A'; - + constructor ($compile: ng.ICompileService) { this.$compile = $compile; } - link($scope, element, attrs) { - $scope.$watch(attrs.cheCompile, (value) => { - element.html(value); - this.$compile(element.contents())($scope); + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ng.IAttributes) { + $scope.$watch(($attrs as any).cheCompile, (value: string) => { + $element.html(value); + this.$compile($element.contents())($scope); }); } diff --git a/dashboard/src/components/widget/description/che-description.directive.ts b/dashboard/src/components/widget/description/che-description.directive.ts index 62cce0d8fd..ae9ebd66fc 100644 --- a/dashboard/src/components/widget/description/che-description.directive.ts +++ b/dashboard/src/components/widget/description/che-description.directive.ts @@ -15,24 +15,18 @@ * * @author Ann Shumilova */ -export class CheDescription { +export class CheDescription implements ng.IDirective { - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor() { - this.restrict = 'E'; + restrict = 'E'; - this.replace = true; - this.transclude = true; - this.templateUrl = 'components/widget/description/che-description.html'; + replace = true; + transclude = true; + templateUrl = 'components/widget/description/che-description.html'; - // scope values - this.scope = { - linkTitle: '@?cheLinkTitle', - link: '@?cheLink' - }; - } + // scope values + scope = { + linkTitle: '@?cheLinkTitle', + link: '@?cheLink' + }; } diff --git a/dashboard/src/components/widget/dropzone/che-dropzone.controller.ts b/dashboard/src/components/widget/dropzone/che-dropzone.controller.ts index 332532fceb..01fc427513 100644 --- a/dashboard/src/components/widget/dropzone/che-dropzone.controller.ts +++ b/dashboard/src/components/widget/dropzone/che-dropzone.controller.ts @@ -9,8 +9,7 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; - -/*global FormData, XMLHttpRequest */ +import {ICheDropZoneEventObject} from './che-dropzone.directive'; /** * @ngdoc controller @@ -19,51 +18,56 @@ * @author Florent Benoit */ export class CheDropZoneCtrl { + $scope: ng.IScope; + lodash: any; + HOVER_KO_CLASS = 'che-dropzone-hover-ko'; + HOVER_OK_CLASS = 'che-dropzone-hover-ok'; + errorMessage: string = null; + dropClass: string; + waitingDrop: boolean; + progressUploadPercent: number; /** * Default constructor that is using resource * @ngInject for Dependency injection */ - constructor($scope, lodash) { + constructor($scope: ng.IScope, lodash: any) { this.$scope = $scope; this.lodash = lodash; - this.HOVER_KO_CLASS = 'che-dropzone-hover-ko'; - this.HOVER_OK_CLASS = 'che-dropzone-hover-ok'; - this.errorMessage = null; } - dropCallback(evt) { + dropCallback(evt: ICheDropZoneEventObject): void { evt.stopPropagation(); evt.preventDefault(); // handle files - var files = evt.dataTransfer.files; + const files = evt.dataTransfer.files; if (files.length > 0) { // needs to upload the file let formData = new FormData(); - for (var i = 0; i < files.length; i++) { + for (let i = 0; i < files.length; i++) { formData.append('uploadedFile', files[i]); } - var xhr = new XMLHttpRequest(); - xhr.upload.addEventListener('progress', (evt) => { - this.uploadProgress(evt, files); + const xhr = new XMLHttpRequest(); + xhr.upload.addEventListener('progress', (evt: ICheDropZoneEventObject) => { + this.uploadProgress(evt); }); - xhr.upload.addEventListener('load', (evt) => { + xhr.upload.addEventListener('load', (evt: ICheDropZoneEventObject) => { this.uploadLoad(evt, files); }); - xhr.upload.addEventListener('error', (evt) => { - this.uploadError(evt, files); + xhr.upload.addEventListener('error', (evt: ICheDropZoneEventObject) => { + this.uploadError(); }); - xhr.upload.addEventListener('abort', (evt) => { - this.uploadAbort(evt, files); + xhr.upload.addEventListener('abort', (evt: ICheDropZoneEventObject) => { + this.uploadAbort(); }); xhr.open('POST', '/admin/upload'); xhr.send(formData); return; } - var url = evt.dataTransfer.getData('URL'); + const url = evt.dataTransfer.getData('URL'); if (url == null) { this.$scope.$apply(() => { this.dropClass = this.HOVER_KO_CLASS; @@ -72,17 +76,15 @@ export class CheDropZoneCtrl { } this.handleUrl(url); - } - /** * Handle the url during the drop * @param url */ - handleUrl(url) { + handleUrl(url: string): void { - let delegateController = this.$scope.cheDropZoneCtrl.callbackController; + let delegateController = (this.$scope as any).cheDropZoneCtrl.callbackController; // promise let acceptPromise = delegateController.dropzoneAcceptURL(url); @@ -95,7 +97,7 @@ export class CheDropZoneCtrl { acceptPromise.then(() => { this.waitingDrop = false; this.dropClass = ''; - }, (error) => { + }, (error: any) => { this.waitingDrop = false; this.dropClass = this.HOVER_KO_CLASS; if (error.data && error.data.message) { @@ -111,7 +113,7 @@ export class CheDropZoneCtrl { /** * Callback when we have the progress status */ - uploadProgress(evt) { + uploadProgress(evt: ICheDropZoneEventObject): void { this.$scope.$apply(() => { if (evt.lengthComputable) { this.progressUploadPercent = Math.round(evt.loaded * 100 / evt.total); @@ -122,9 +124,9 @@ export class CheDropZoneCtrl { /** * Callback when upload to the remote servlet has been done */ - uploadLoad(evt, files) { + uploadLoad(evt: ICheDropZoneEventObject, files: any[]): void { // upload is OK then we need to upload every files - for (var i = 0; i < files.length; i++) { + for (let i = 0; i < files.length; i++) { this.handleUrl('upload:' + files[i].name); } } @@ -132,7 +134,7 @@ export class CheDropZoneCtrl { /** * Callback when we have the error */ - uploadError() { + uploadError(): void { this.$scope.$apply(() => { this.waitingDrop = false; this.dropClass = this.HOVER_KO_CLASS; @@ -143,7 +145,7 @@ export class CheDropZoneCtrl { /** * Callback when we have aborting of the upload */ - uploadAbort() { + uploadAbort(): void { this.$scope.$apply(() => { this.waitingDrop = false; this.dropClass = this.HOVER_KO_CLASS; @@ -151,15 +153,13 @@ export class CheDropZoneCtrl { }); } - - dragoverCallback(evt) { - + dragoverCallback(evt: ICheDropZoneEventObject): void { evt.stopPropagation(); evt.preventDefault(); - var okFiles = evt.dataTransfer && evt.dataTransfer && evt.dataTransfer.types && this.lodash.indexOf(evt.dataTransfer.types, 'Files') >= 0; - var okURI = evt.dataTransfer && evt.dataTransfer && evt.dataTransfer.types && this.lodash.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0; + const okFiles = evt.dataTransfer && evt.dataTransfer && evt.dataTransfer.types && this.lodash.indexOf(evt.dataTransfer.types, 'Files') >= 0; + const okURI = evt.dataTransfer && evt.dataTransfer && evt.dataTransfer.types && this.lodash.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0; - var ok = okFiles || okURI; + const ok = okFiles || okURI; this.$scope.$apply(() => { if (ok) { @@ -170,17 +170,15 @@ export class CheDropZoneCtrl { }); } - - dragEnterCallback(evt) { + dragEnterCallback(evt: ICheDropZoneEventObject): void { this.cleanup(evt); } - dragLeaveCallback(evt) { + dragLeaveCallback(evt: ICheDropZoneEventObject): void { this.cleanup(evt); } - - cleanup(evt) { + cleanup(evt: ICheDropZoneEventObject): void { evt.stopPropagation(); evt.preventDefault(); this.$scope.$apply(() => { @@ -190,6 +188,5 @@ export class CheDropZoneCtrl { }); } - } diff --git a/dashboard/src/components/widget/dropzone/che-dropzone.directive.ts b/dashboard/src/components/widget/dropzone/che-dropzone.directive.ts index 94f694834b..00438eabca 100644 --- a/dashboard/src/components/widget/dropzone/che-dropzone.directive.ts +++ b/dashboard/src/components/widget/dropzone/che-dropzone.directive.ts @@ -9,6 +9,18 @@ * Red Hat, Inc. - initial API and implementation */ 'use strict'; +import {CheDropZoneCtrl} from './che-dropzone.controller'; + +export interface ICheDropZoneEventObject extends JQueryEventObject { + dataTransfer: { + files: any[]; + getData: (key: string) => string; + types: string[]; + }; + lengthComputable: boolean; + loaded: number; + total: number; +} /** * @ngdoc directive @@ -26,42 +38,32 @@ * * * @example - - - This is a drag and drop zone - - + * + * + * This is a drag and drop zone + * + * * @author Florent Benoit */ -export class CheDropZone { +export class CheDropZone implements ng.IDirective { + restrict = 'E'; + transclude = true; + bindToController = true; + replace = true; - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor () { - this.restrict = 'E'; - this.transclude = true; - this.bindToController = true; - this.replace = true; - - this.controller = 'CheDropZoneCtrl'; - this.controllerAs = 'cheDropZoneCtrl'; - - - this.scope = { - callbackController: '=cheCallbackController' - }; - - } + controller = 'CheDropZoneCtrl'; + controllerAs = 'cheDropZoneCtrl'; + scope = { + callbackController: '=cheCallbackController' + }; /** * Template for the current drop zone * @returns {string} the template */ - template(){ - var template = '
' + template (): string { + const template = '
' + '
Drag and drop a plug-in
' + '
{{cheDropZoneCtrl.errorMessage}}
' + '' @@ -69,30 +71,26 @@ export class CheDropZone { return template; } - - /** * Keep reference to the model controller */ - link($scope, element, attributes, controller) { - let innerElement = element[0]; + link($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attributes: ng.IAttributes, $controller: CheDropZoneCtrl) { + let innerElement = $element[0]; - innerElement.addEventListener('dragenter', (evt) => { - controller.dragEnterCallback(evt); + innerElement.addEventListener('dragenter', (evt: ICheDropZoneEventObject) => { + $controller.dragEnterCallback(evt); }); - innerElement.addEventListener('dragleave', (evt) => { - controller.dragLeaveCallback(evt); + innerElement.addEventListener('dragleave', (evt: ICheDropZoneEventObject) => { + $controller.dragLeaveCallback(evt); }); - innerElement.addEventListener('dragover', (evt) => { - controller.dragoverCallback(evt); + innerElement.addEventListener('dragover', (evt: ICheDropZoneEventObject) => { + $controller.dragoverCallback(evt); }); - innerElement.addEventListener('drop', (evt) => { - controller.dropCallback(evt); + innerElement.addEventListener('drop', (evt: ICheDropZoneEventObject) => { + $controller.dropCallback(evt); }); - - } } diff --git a/dashboard/src/components/widget/editor/che-editor.html b/dashboard/src/components/widget/editor/che-editor.html index 65e71a28fc..7c20c774b4 100644 --- a/dashboard/src/components/widget/editor/che-editor.html +++ b/dashboard/src/components/widget/editor/che-editor.html @@ -1,11 +1,11 @@
- +
Editor's content is required.
{{error}}
diff --git a/dashboard/src/components/widget/empty-state/che-empty-state.directive.ts b/dashboard/src/components/widget/empty-state/che-empty-state.directive.ts index 4aba17d77a..4124058243 100644 --- a/dashboard/src/components/widget/empty-state/che-empty-state.directive.ts +++ b/dashboard/src/components/widget/empty-state/che-empty-state.directive.ts @@ -15,26 +15,19 @@ * It will change upon width of the screen * @author Oleksii Orel */ -export class CheEmptyState { +export class CheEmptyState implements ng.IDirective { - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor() { - this.restrict = 'E'; + restrict = 'E'; - this.replace = true; - this.transclude = false; - this.templateUrl = 'components/widget/empty-state/che-empty-state.html'; + replace = true; + transclude = false; + templateUrl = 'components/widget/empty-state/che-empty-state.html'; - // scope values - this.scope = { - value: '@cheValue', - prompt: '@?chePrompt', - iconClass: '@cheIconClass' - }; - - } + // scope values + scope = { + value: '@cheValue', + prompt: '@?chePrompt', + iconClass: '@cheIconClass' + }; } diff --git a/dashboard/src/components/widget/footer/che-footer.controller.ts b/dashboard/src/components/widget/footer/che-footer.controller.ts index f6816070d0..667922e38a 100644 --- a/dashboard/src/components/widget/footer/che-footer.controller.ts +++ b/dashboard/src/components/widget/footer/che-footer.controller.ts @@ -17,12 +17,6 @@ * @author Ann Shumilova */ export class CheFooterController { - /** - * Default constructor that is using resource - * @ngInject for Dependency injection - */ - constructor() { - } /** * Returns 'Make a wish' email subject. diff --git a/dashboard/src/components/widget/frame/che-frame.directive.ts b/dashboard/src/components/widget/frame/che-frame.directive.ts index fc0007f9ea..9714436962 100644 --- a/dashboard/src/components/widget/frame/che-frame.directive.ts +++ b/dashboard/src/components/widget/frame/che-frame.directive.ts @@ -12,21 +12,16 @@ export class CheFrame { - /** - * Default constructor. - */ - constructor () { - this.restrict = 'E'; - this.transclude = true; + restrict = 'E'; + transclude = true; - // scope values - this.scope = { - frameText : '@cheFrameText', - frameClass:'@cheFrameClass' - }; - } + // scope values + scope = { + frameText: '@cheFrameText', + frameClass: '@cheFrameClass' + }; - template() { + template (): string { return `
 
diff --git a/dashboard/src/components/widget/html-source/demo-source-render.directive.ts b/dashboard/src/components/widget/html-source/demo-source-render.directive.ts index f5c9b20848..2e6d07af9a 100644 --- a/dashboard/src/components/widget/html-source/demo-source-render.directive.ts +++ b/dashboard/src/components/widget/html-source/demo-source-render.directive.ts @@ -47,7 +47,7 @@ export class DemoSourceRender { this.$compile = $compile; } - template(element: ng.IAugmentedJQuery) { + template(element: ng.IAugmentedJQuery): string { let source, demoElement; if (element.prop('tagName') === 'TEXTAREA') { source = element.html(); diff --git a/dashboard/src/components/widget/input/che-textarea.directive.ts b/dashboard/src/components/widget/input/che-textarea.directive.ts index e30b9d9bd5..372f93a64f 100644 --- a/dashboard/src/components/widget/input/che-textarea.directive.ts +++ b/dashboard/src/components/widget/input/che-textarea.directive.ts @@ -12,6 +12,13 @@ import { CheInput } from './che-input.directive'; +interface ICheTextareaAttributes extends ng.IAttributes { + cheName: string; + cheLabelName: string; + chePlaceHolder: string; + chePattern: string; +} + /** * Defines a directive for creating textarea that are working either on desktop or on mobile devices. * It will change upon width of the screen @@ -29,22 +36,22 @@ export class CheTextarea extends CheInput { /** * Template for the current toolbar - * @param element - * @param attrs + * @param $element + * @param $attrs * @returns {string} the template */ - template(element, attrs) { + template($element: ng.IAugmentedJQuery, $attrs: ICheTextareaAttributes) { - var textareaName = attrs.cheName; - var labelName = attrs.cheLabelName || ''; - var placeHolder = attrs.chePlaceHolder; - var pattern = attrs.chePattern; + const textareaName = $attrs.cheName; + const labelName = $attrs.cheLabelName || ''; + const placeHolder = $attrs.chePlaceHolder; + const pattern = $attrs.chePattern; - var template = '
' + let template = '
' + '' + '' + '